diff --git a/.github/workflows/build-toolchain.yml b/.github/workflows/build-toolchain.yml index 5c9d7b710a..8413ff6804 100644 --- a/.github/workflows/build-toolchain.yml +++ b/.github/workflows/build-toolchain.yml @@ -30,7 +30,7 @@ jobs: build: name: Preset ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} runs-on: windows-latest - timeout-minutes: 20 + timeout-minutes: 40 steps: - name: Checkout Code uses: actions/checkout@v4 @@ -102,6 +102,9 @@ jobs: with: arch: x86 + - name: Setup vcpkg + uses: lukka/run-vcpkg@v11 + - name: Configure ${{ inputs.game }} with CMake Using ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} Preset shell: pwsh run: | @@ -111,10 +114,12 @@ jobs: ) $gamePrefix = "${{ inputs.game == 'Generals' && 'GENERALS' || 'ZEROHOUR' }}" + $buildFlags += "-DRTS_BUILD_CORE_TOOLS=${{ inputs.tools && 'ON' || 'OFF' }}" $buildFlags += "-DRTS_BUILD_${gamePrefix}_TOOLS=${{ inputs.tools && 'ON' || 'OFF' }}" + $buildFlags += "-DRTS_BUILD_CORE_EXTRAS=${{ inputs.extras && 'ON' || 'OFF' }}" $buildFlags += "-DRTS_BUILD_${gamePrefix}_EXTRAS=${{ inputs.extras && 'ON' || 'OFF' }}" - Write-Host "Build flags: $buildFlags" + Write-Host "Build flags: $($buildFlags -join ' | ')" cmake --preset ${{ inputs.preset }} $buildFlags @@ -131,12 +136,12 @@ jobs: if ("${{ inputs.preset }}" -like "win32*") { # For win32 preset, look in config-specific subdirectories - $configToUse = if ("${{ inputs.preset }}" -eq "win32dbg") { "Debug" } else { "Release" } - $files = Get-ChildItem -Path "$buildDir\${{ inputs.game }}\$configToUse" -File | Where-Object { $_.Extension -in @(".exe", ".dll", ".pdb") } -Verbose + $configToUse = if ("${{ inputs.preset }}" -match "debug") { "Debug" } else { "Release" } + $files = Get-ChildItem -Path "$buildDir\Core\$configToUse","$buildDir\${{ inputs.game }}\$configToUse" -File | Where-Object { $_.Extension -in @(".exe", ".dll", ".pdb") } -Verbose } else { - $files = Get-ChildItem -Path "$buildDir\${{ inputs.game }}" -File | Where-Object { $_.Extension -in @(".exe", ".dll", ".pdb") } -Verbose + $files = Get-ChildItem -Path "$buildDir\Core","$buildDir\${{ inputs.game }}" -File | Where-Object { $_.Extension -in @(".exe", ".dll", ".pdb") } -Verbose } - $files | Move-Item -Destination $artifactsDir -Verbose + $files | Move-Item -Destination $artifactsDir -Verbose -Force - name: Upload ${{ inputs.game }} ${{ inputs.preset }}${{ inputs.tools && '+t' || '' }}${{ inputs.extras && '+e' || '' }} Artifact uses: actions/upload-artifact@v4 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0f58d9478e..cd16f177f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,25 +66,25 @@ jobs: - preset: "vc6" tools: true extras: true - - preset: "vc6prof" + - preset: "vc6-profile" tools: true extras: true - - preset: "vc6int" + - preset: "vc6-internal" tools: true extras: true - - preset: "vc6dbg" + - preset: "vc6-debug" tools: true extras: true - - preset: "win32" + - preset: "win32-vcpkg" tools: true extras: true - - preset: "win32prof" + - preset: "win32-vcpkg-profile" tools: true extras: true - - preset: "win32int" + - preset: "win32-vcpkg-internal" tools: true extras: true - - preset: "win32dbg" + - preset: "win32-vcpkg-debug" tools: true extras: true fail-fast: false @@ -106,25 +106,25 @@ jobs: - preset: "vc6" tools: true extras: true - - preset: "vc6prof" + - preset: "vc6-profile" tools: true extras: true - - preset: "vc6int" + - preset: "vc6-internal" tools: true extras: true - - preset: "vc6dbg" + - preset: "vc6-debug" tools: true extras: true - preset: "win32" tools: true extras: true - - preset: "win32prof" + - preset: "win32-profile" tools: true extras: true - - preset: "win32int" + - preset: "win32-internal" tools: true extras: true - - preset: "win32dbg" + - preset: "win32-debug" tools: true extras: true fail-fast: false diff --git a/.github/workflows/valid-tags.txt b/.github/workflows/valid-tags.txt index 253a3b9f53..10ee587003 100644 --- a/.github/workflows/valid-tags.txt +++ b/.github/workflows/valid-tags.txt @@ -1,5 +1,6 @@ [GEN] [ZH] +[BFME] [CMAKE] [GITHUB] [CORE] diff --git a/CMakeLists.txt b/CMakeLists.txt index af7f2ca5db..1901338d9c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,7 +56,6 @@ endif() include(cmake/config.cmake) include(cmake/gamespy.cmake) include(cmake/lzhl.cmake) -include(cmake/zlib.cmake) add_subdirectory(Dependencies/Benchmark) if (IS_VS6_BUILD) diff --git a/CMakePresets.json b/CMakePresets.json index 1d455f0388..25963040b3 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -8,7 +8,7 @@ "configurePresets": [ { "name": "vc6", - "displayName": "Build Binaries with NMake", + "displayName": "Windows 32bit VC6 Release", "generator": "NMake Makefiles", "hidden": false, "binaryDir": "${sourceDir}/build/${presetName}", @@ -26,8 +26,8 @@ } }, { - "name": "vc6prof", - "displayName": "Build Profiling Binaries with NMake", + "name": "vc6-profile", + "displayName": "Windows 32bit VC6 Profile", "hidden": false, "inherits": "vc6", "cacheVariables": { @@ -35,21 +35,25 @@ } }, { - "name": "vc6int", - "displayName": "Build Internal Binaries with NMake", + "name": "vc6-internal", + "displayName": "Windows 32bit VC6 Internal", "inherits": "vc6", "cacheVariables": { "RTS_BUILD_OPTION_INTERNAL": "ON" } }, { - "name": "vc6dbg", - "displayName": "Build Debug Binaries with NMake", + "name": "vc6-debug", + "displayName": "Windows 32bit VC6 Debug", "hidden": false, "inherits": "vc6", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", - "RTS_BUILD_OPTION_DEBUG": "ON" + "RTS_BUILD_OPTION_DEBUG": "ON", + "CMAKE_MSVC_RUNTIME_LIBRARY": "MultiThreadedDebugDLL", + "CMAKE_CXX_FLAGS_DEBUG": "/Ob0 /Od /GZ /Zi", + "CMAKE_C_FLAGS_DEBUG": "/Ob0 /Od /GZ /Zi", + "CMAKE_EXE_LINKER_FLAGS_DEBUG": "/DEBUG" } }, { @@ -64,11 +68,24 @@ "CMAKE_MSVC_RUNTIME_LIBRARY": "MultiThreaded$<$:Debug>DLL" } }, + { + "name": "default-vcpkg", + "displayName": "Default Config for vcpkg (don't use directly!)", + "generator": "Ninja Multi-Config", + "hidden": true, + "binaryDir": "${sourceDir}/build/${presetName}", + "cacheVariables": { + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT": "$<$:Embedded>", + "CMAKE_MSVC_RUNTIME_LIBRARY": "MultiThreaded$<$:Debug>DLL", + "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" + } + }, { "name": "win32", "inherits": "default", "hidden": false, - "displayName": "Windows 32bit build", + "displayName": "Windows 32bit Release", "architecture": { "value": "Win32", "strategy": "external" @@ -83,94 +100,164 @@ } }, { - "name": "win32prof", + "name": "win32-profile", "inherits": "win32", - "displayName": "Windows 32bit Profile build", + "displayName": "Windows 32bit Profile", "cacheVariables": { "RTS_BUILD_OPTION_PROFILE": "ON" } }, { - "name": "win32int", + "name": "win32-internal", "inherits": "win32", - "displayName": "Windows 32bit Internal build", + "displayName": "Windows 32bit Internal", "cacheVariables": { "RTS_BUILD_OPTION_INTERNAL": "ON" } }, { - "name": "win32dbg", + "name": "win32-debug", "inherits": "win32", - "displayName": "Windows 32bit Debug build", + "displayName": "Windows 32bit Debug", + "cacheVariables": { + "RTS_BUILD_OPTION_DEBUG": "ON" + } + }, + { + "name": "win32-vcpkg", + "inherits": "default-vcpkg", + "hidden": false, + "displayName": "Windows 32bit VCPKG Release", + "architecture": { + "value": "Win32", + "strategy": "external" + }, + "cacheVariables": { + "RTS_FLAGS": "/W3" + }, + "vendor": { + "jetbrains.com/clion": { + "toolchain": "Visual Studio" + } + } + }, + { + "name": "win32-vcpkg-profile", + "inherits": "win32-vcpkg", + "displayName": "Windows 32bit VCPKG Profile", + "cacheVariables": { + "RTS_BUILD_OPTION_PROFILE": "ON" + } + }, + { + "name": "win32-vcpkg-internal", + "inherits": "win32-vcpkg", + "displayName": "Windows 32bit VCPKG Internal", + "cacheVariables": { + "RTS_BUILD_OPTION_INTERNAL": "ON" + } + }, + { + "name": "win32-vcpkg-debug", + "inherits": "win32-vcpkg", + "displayName": "Windows 32bit VCPKG Debug", "cacheVariables": { "RTS_BUILD_OPTION_DEBUG": "ON" } }, { "name": "unix", - "inherits": "default", + "inherits": "default-vcpkg", "hidden": false, - "displayName": "Non-Windows build" + "displayName": "Unix 32bit VCPKG Release" } ], "buildPresets": [ { "name": "vc6", "configurePreset": "vc6", - "displayName": "Build VC6 Windows build", - "description": "Build VC6 Windows build" + "displayName": "Build Windows 32bit VC6 Release", + "description": "Build Windows 32bit VC6 Release" }, { - "name": "vc6int", - "configurePreset": "vc6int", - "displayName": "Build VC6 Windows Internal build", - "description": "Build VC6 Windows Internal build" + "name": "vc6-internal", + "configurePreset": "vc6-internal", + "displayName": "Build Windows 32bit VC6 Internal", + "description": "Build Windows 32bit VC6 Internal" }, { - "name": "vc6prof", - "configurePreset": "vc6prof", - "displayName": "Build VC6 Windows Profile build", - "description": "Build VC6 Windows Profile build" + "name": "vc6-profile", + "configurePreset": "vc6-profile", + "displayName": "Build Windows 32bit VC6 Profile", + "description": "Build Windows 32bit VC6 Profile" }, { - "name": "vc6dbg", - "configurePreset": "vc6dbg", - "displayName": "Build VC6 Windows Debug build", - "description": "Build VC6 Windows Debug build" + "name": "vc6-debug", + "configurePreset": "vc6-debug", + "displayName": "Build Windows 32bit VC6 Debug", + "description": "Build Windows 32bit VC6 Debug" }, { "name": "win32", "configurePreset": "win32", - "displayName": "Build Windows build", - "description": "Build Windows build", + "displayName": "Build Windows 32bit Release", + "description": "Build Windows 32bit Release", + "configuration": "Release" + }, + { + "name": "win32-internal", + "configurePreset": "win32-internal", + "displayName": "Build Windows 32bit Internal", + "description": "Build Windows 32bit Internal", + "configuration": "Release" + }, + { + "name": "win32-profile", + "configurePreset": "win32-profile", + "displayName": "Build Windows 32bit Profile", + "description": "Build Windows 32bit Profile", + "configuration": "Release" + }, + { + "name": "win32-debug", + "configurePreset": "win32-debug", + "displayName": "Build Windows 32bit Debug", + "description": "Build Windows 32bit Debug", + "configuration": "Debug" + }, + { + "name": "win32-vcpkg", + "configurePreset": "win32-vcpkg", + "displayName": "Build Windows 32bit VCPKG Release", + "description": "Build Windows 32bit VCPKG Release", "configuration": "Release" }, { - "name": "win32int", - "configurePreset": "win32int", - "displayName": "Build Windows Internal build", - "description": "Build Windows Internal build", + "name": "win32-vcpkg-internal", + "configurePreset": "win32-vcpkg-internal", + "displayName": "Build Windows 32bit VCPKG Internal", + "description": "Build Windows 32bit VCPKG Internal", "configuration": "Release" }, { - "name": "win32prof", - "configurePreset": "win32prof", - "displayName": "Build Windows Profiling build", - "description": "Build Windows Profiling build", + "name": "win32-vcpkg-profile", + "configurePreset": "win32-vcpkg-profile", + "displayName": "Build Windows 32bit VCPKG Profile", + "description": "Build Windows 32bit VCPKG Profile", "configuration": "Release" }, { - "name": "win32dbg", - "configurePreset": "win32dbg", - "displayName": "Build Windows Debug build", - "description": "Build Windows Debug build", + "name": "win32-vcpkg-debug", + "configurePreset": "win32-vcpkg-debug", + "displayName": "Build Windows 32bit VCPKG Debug", + "description": "Build Windows 32bit VCPKG Debug", "configuration": "Debug" }, { "name": "unix", "configurePreset": "unix", - "displayName": "Build non-Windows build", - "description": "Build non-Windows build", + "displayName": "Build Unix 32bit VCPKG Release", + "description": "Build Unix 32bit VCPKG Release", "configuration": "Release" } ], @@ -189,41 +276,41 @@ ] }, { - "name": "vc6dbg", + "name": "vc6-debug", "steps": [ { "type": "configure", - "name": "vc6dbg" + "name": "vc6-debug" }, { "type": "build", - "name": "vc6dbg" + "name": "vc6-debug" } ] }, { - "name": "vc6int", + "name": "vc6-internal", "steps": [ { "type": "configure", - "name": "vc6int" + "name": "vc6-internal" }, { "type": "build", - "name": "vc6int" + "name": "vc6-internal" } ] }, { - "name": "vc6prof", + "name": "vc6-profile", "steps": [ { "type": "configure", - "name": "vc6prof" + "name": "vc6-profile" }, { "type": "build", - "name": "vc6prof" + "name": "vc6-profile" } ] }, @@ -241,41 +328,93 @@ ] }, { - "name": "win32int", + "name": "win32-internal", + "steps": [ + { + "type": "configure", + "name": "win32-internal" + }, + { + "type": "build", + "name": "win32-internal" + } + ] + }, + { + "name": "win32-profile", + "steps": [ + { + "type": "configure", + "name": "win32-profile" + }, + { + "type": "build", + "name": "win32-profile" + } + ] + }, + { + "name": "win32-debug", + "steps": [ + { + "type": "configure", + "name": "win32-debug" + }, + { + "type": "build", + "name": "win32-debug" + } + ] + }, + { + "name": "win32-vcpkg", + "steps": [ + { + "type": "configure", + "name": "win32-vcpkg" + }, + { + "type": "build", + "name": "win32-vcpkg" + } + ] + }, + { + "name": "win32-vcpkg-internal", "steps": [ { "type": "configure", - "name": "win32int" + "name": "win32-vcpkg-internal" }, { "type": "build", - "name": "win32int" + "name": "win32-vcpkg-internal" } ] }, { - "name": "win32prof", + "name": "win32-vcpkg-profile", "steps": [ { "type": "configure", - "name": "win32prof" + "name": "win32-vcpkg-profile" }, { "type": "build", - "name": "win32prof" + "name": "win32-vcpkg-profile" } ] }, { - "name": "win32dbg", + "name": "win32-vcpkg-debug", "steps": [ { "type": "configure", - "name": "win32dbg" + "name": "win32-vcpkg-debug" }, { "type": "build", - "name": "win32dbg" + "name": "win32-vcpkg-debug" } ] }, @@ -293,4 +432,4 @@ ] } ] -} +} \ No newline at end of file diff --git a/Core/CMakeLists.txt b/Core/CMakeLists.txt index efde2b1b82..30b785f330 100644 --- a/Core/CMakeLists.txt +++ b/Core/CMakeLists.txt @@ -14,12 +14,6 @@ target_link_libraries(corei_always INTERFACE corei_libraries_include ) -# Do we want to build extra SDK stuff or just the game binary? -option(RTS_BUILD_CORE_TOOLS "Build core tools" ON) -add_feature_info(CoreTools GENZH_BUILD_ZEROHOUR_TOOLS "Build Core Mod Tools") -option(RTS_BUILD_CORE_EXTRAS "Build core extra tools/tests" OFF) -add_feature_info(CoreExtras GENZH_BUILD_ZEROHOUR_EXTRAS "Build Core Extra Tools/Tests") - # Set where the build results will end up set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) @@ -27,11 +21,9 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) add_subdirectory(Libraries) # Base GameEngine library -# add_subdirectory(GameEngine) +add_subdirectory(GameEngine) # Platform specific GameEngine code # add_subdirectory(GameEngineDevice) -if (RTS_BUILD_CORE_TOOLS OR RTS_BUILD_CORE_EXTRAS) - add_subdirectory(Tools) -endif() \ No newline at end of file +add_subdirectory(Tools) diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt new file mode 100644 index 0000000000..543f71abe4 --- /dev/null +++ b/Core/GameEngine/CMakeLists.txt @@ -0,0 +1,1184 @@ +set(GAMEENGINE_SRC +# Include/Common/AcademyStats.h +# Include/Common/ActionManager.h +# Include/Common/ArchiveFile.h +# Include/Common/ArchiveFileSystem.h +# Include/Common/AsciiString.h +# Include/Common/AudioAffect.h +# Include/Common/AudioEventInfo.h +# Include/Common/AudioEventRTS.h +# Include/Common/AudioHandleSpecialValues.h +# Include/Common/AudioRandomValue.h +# Include/Common/AudioRequest.h +# Include/Common/AudioSettings.h +# Include/Common/BattleHonors.h +# Include/Common/BezFwdIterator.h +# Include/Common/BezierSegment.h +# Include/Common/BitFlags.h +# Include/Common/BitFlagsIO.h +# Include/Common/BorderColors.h +# Include/Common/BuildAssistant.h +# Include/Common/CDManager.h +# Include/Common/ClientUpdateModule.h +# Include/Common/CommandLine.h +# Include/Common/CopyProtection.h +# Include/Common/crc.h +# Include/Common/CRCDebug.h +# Include/Common/CriticalSection.h +# Include/Common/CustomMatchPreferences.h +# Include/Common/DamageFX.h +# Include/Common/DataChunk.h +# Include/Common/Debug.h +# Include/Common/Dict.h +# Include/Common/Directory.h +# Include/Common/DisabledTypes.h +# Include/Common/DiscreteCircle.h +# Include/Common/DrawModule.h +# Include/Common/DynamicAudioEventInfo.h +# Include/Common/encrypt.h +# Include/Common/Energy.h +# Include/Common/Errors.h +# Include/Common/file.h +# Include/Common/FileSystem.h +# Include/Common/FunctionLexicon.h +# Include/Common/GameAudio.h +# Include/Common/GameCommon.h +# Include/Common/GameEngine.h +# Include/Common/GameLOD.h +# Include/Common/GameMemory.h +# Include/Common/GameMusic.h +# Include/Common/GameSounds.h +# Include/Common/GameSpyMiscPreferences.h +# Include/Common/GameState.h +# Include/Common/GameStateMap.h +# Include/Common/GameType.h +# Include/Common/Geometry.h +# Include/Common/GlobalData.h +# Include/Common/Handicap.h +# Include/Common/IgnorePreferences.h +# Include/Common/INI.h +# Include/Common/INIException.h +# Include/Common/KindOf.h +# Include/Common/LadderPreferences.h +# Include/Common/Language.h +# Include/Common/LatchRestore.h +# Include/Common/List.h +# Include/Common/LocalFile.h +# Include/Common/LocalFileSystem.h +# Include/Common/MapObject.h +# Include/Common/MapReaderWriterInfo.h +# Include/Common/MessageStream.h +# Include/Common/MiniLog.h +# Include/Common/MiscAudio.h +# Include/Common/MissionStats.h +# Include/Common/ModelState.h +# Include/Common/Module.h +# Include/Common/ModuleFactory.h +# Include/Common/Money.h +# Include/Common/MultiplayerSettings.h +# Include/Common/NameKeyGenerator.h +# Include/Common/ObjectStatusTypes.h +# Include/Common/OSDisplay.h +# Include/Common/Overridable.h +# Include/Common/Override.h +# Include/Common/PartitionSolver.h +# Include/Common/PerfMetrics.h +# Include/Common/PerfTimer.h +# Include/Common/Player.h +# Include/Common/PlayerList.h +# Include/Common/PlayerTemplate.h +# Include/Common/ProductionPrerequisite.h +# Include/Common/QuickmatchPreferences.h +# Include/Common/QuotedPrintable.h +# Include/Common/Radar.h +# Include/Common/RAMFile.h +# Include/Common/RandomValue.h +# Include/Common/Recorder.h +# Include/Common/Registry.h +# Include/Common/ResourceGatheringManager.h +# Include/Common/Science.h +# Include/Common/ScopedMutex.h +# Include/Common/ScoreKeeper.h +# Include/Common/simpleplayer.h +# Include/Common/SkirmishBattleHonors.h +# Include/Common/SkirmishPreferences.h +# Include/Common/Snapshot.h +# Include/Common/SparseMatchFinder.h +# Include/Common/SpecialPower.h +# Include/Common/SpecialPowerMaskType.h +# Include/Common/SpecialPowerType.h +# Include/Common/StackDump.h +# Include/Common/StateMachine.h +# Include/Common/StatsCollector.h +# Include/Common/STLTypedefs.h +# Include/Common/StreamingArchiveFile.h +# Include/Common/SubsystemInterface.h +# Include/Common/SystemInfo.h +# Include/Common/Team.h +# Include/Common/Terrain.h +# Include/Common/TerrainTypes.h +# Include/Common/Thing.h +# Include/Common/ThingFactory.h +# Include/Common/ThingSort.h +# Include/Common/ThingTemplate.h +# Include/Common/TunnelTracker.h +# Include/Common/UnicodeString.h +# Include/Common/UnitTimings.h +# Include/Common/Upgrade.h +# Include/Common/urllaunch.h +# Include/Common/UserPreferences.h +# Include/Common/version.h +# Include/Common/WellKnownKeys.h + Include/Common/Xfer.h + Include/Common/XferCRC.h + Include/Common/XferDeepCRC.h + Include/Common/XferLoad.h + Include/Common/XferSave.h +# Include/GameClient/Anim2D.h +# Include/GameClient/AnimateWindowManager.h +# Include/GameClient/CampaignManager.h +# Include/GameClient/CDCheck.h +# Include/GameClient/ChallengeGenerals.h +# Include/GameClient/ClientInstance.h +# Include/GameClient/ClientRandomValue.h +# Include/GameClient/Color.h +# Include/GameClient/CommandXlat.h +# Include/GameClient/ControlBar.h +# Include/GameClient/ControlBarResizer.h +# Include/GameClient/ControlBarScheme.h +# Include/GameClient/Credits.h +# Include/GameClient/DebugDisplay.h +# Include/GameClient/Diplomacy.h +# Include/GameClient/DisconnectMenu.h +# Include/GameClient/Display.h +# Include/GameClient/DisplayString.h +# Include/GameClient/DisplayStringManager.h +# Include/GameClient/Drawable.h +# Include/GameClient/DrawableInfo.h +# Include/GameClient/DrawGroupInfo.h +# Include/GameClient/EstablishConnectionsMenu.h +# Include/GameClient/Eva.h +# Include/GameClient/ExtendedMessageBox.h +# Include/GameClient/FontDesc.h +# Include/GameClient/FXList.h +# Include/GameClient/Gadget.h +# Include/GameClient/GadgetCheckBox.h +# Include/GameClient/GadgetComboBox.h +# Include/GameClient/GadgetListBox.h +# Include/GameClient/GadgetProgressBar.h +# Include/GameClient/GadgetPushButton.h +# Include/GameClient/GadgetRadioButton.h +# Include/GameClient/GadgetSlider.h +# Include/GameClient/GadgetStaticText.h +# Include/GameClient/GadgetTabControl.h +# Include/GameClient/GadgetTextEntry.h +# Include/GameClient/GameClient.h +# Include/GameClient/GameFont.h +# Include/GameClient/GameInfoWindow.h +# Include/GameClient/GameText.h +# Include/GameClient/GameWindow.h +# Include/GameClient/GameWindowGlobal.h +# Include/GameClient/GameWindowID.h +# Include/GameClient/GameWindowManager.h +# Include/GameClient/GameWindowTransitions.h +# Include/GameClient/GlobalLanguage.h +# Include/GameClient/GraphDraw.h +# Include/GameClient/GUICallbacks.h +# Include/GameClient/GUICommandTranslator.h +# Include/GameClient/HeaderTemplate.h +# Include/GameClient/HintSpy.h +# Include/GameClient/HotKey.h +# Include/GameClient/Image.h +# Include/GameClient/IMEManager.h +# Include/GameClient/InGameUI.h +# Include/GameClient/Keyboard.h +# Include/GameClient/KeyDefs.h +# Include/GameClient/LanguageFilter.h +# Include/GameClient/Line2D.h +# Include/GameClient/LoadScreen.h +# Include/GameClient/LookAtXlat.h +# Include/GameClient/MapUtil.h +# Include/GameClient/MessageBox.h +# Include/GameClient/MetaEvent.h +# Include/GameClient/Module/AnimatedParticleSysBoneClientUpdate.h +# Include/GameClient/Module/BeaconClientUpdate.h +# Include/GameClient/Module/SwayClientUpdate.h +# Include/GameClient/Mouse.h +# Include/GameClient/ParabolicEase.h +# Include/GameClient/ParticleSys.h +# Include/GameClient/PlaceEventTranslator.h +# Include/GameClient/ProcessAnimateWindow.h +# Include/GameClient/RadiusDecal.h +# Include/GameClient/RayEffect.h +# Include/GameClient/SelectionInfo.h +# Include/GameClient/SelectionXlat.h +# Include/GameClient/Shadow.h +# Include/GameClient/Shell.h +# Include/GameClient/ShellHooks.h +# Include/GameClient/ShellMenuScheme.h +# Include/GameClient/Smudge.h +# Include/GameClient/Snow.h +# Include/GameClient/Statistics.h +# Include/GameClient/TerrainRoads.h +# Include/GameClient/TerrainVisual.h +# Include/GameClient/VideoPlayer.h +# Include/GameClient/View.h +# Include/GameClient/Water.h +# Include/GameClient/WindowLayout.h +# Include/GameClient/WindowVideoManager.h +# Include/GameClient/WindowXlat.h +# Include/GameClient/WinInstanceData.h +# Include/GameLogic/AI.h +# Include/GameLogic/AIDock.h +# Include/GameLogic/AIGuard.h +# Include/GameLogic/AIGuardRetaliate.h +# Include/GameLogic/AIPathfind.h +# Include/GameLogic/AIPlayer.h +# Include/GameLogic/AISkirmishPlayer.h +# Include/GameLogic/AIStateMachine.h +# Include/GameLogic/AITNGuard.h +# Include/GameLogic/Armor.h +# Include/GameLogic/ArmorSet.h +# Include/GameLogic/CaveSystem.h +# Include/GameLogic/CrateSystem.h +# Include/GameLogic/Damage.h +# Include/GameLogic/ExperienceTracker.h +# Include/GameLogic/FiringTracker.h +# Include/GameLogic/FPUControl.h +# Include/GameLogic/GameLogic.h +# Include/GameLogic/GhostObject.h +# Include/GameLogic/Locomotor.h +# Include/GameLogic/LocomotorSet.h +# Include/GameLogic/LogicRandomValue.h +# Include/GameLogic/Module/ActiveBody.h +# Include/GameLogic/Module/ActiveShroudUpgrade.h +# Include/GameLogic/Module/AIUpdate.h +# Include/GameLogic/Module/AnimationSteeringUpdate.h +# Include/GameLogic/Module/ArmorUpgrade.h +# Include/GameLogic/Module/AssaultTransportAIUpdate.h +# Include/GameLogic/Module/AssistedTargetingUpdate.h +# Include/GameLogic/Module/AutoDepositUpdate.h +# Include/GameLogic/Module/AutoFindHealingUpdate.h +# Include/GameLogic/Module/AutoHealBehavior.h +# Include/GameLogic/Module/BaikonurLaunchPower.h +# Include/GameLogic/Module/BaseRegenerateUpdate.h +# Include/GameLogic/Module/BattleBusSlowDeathBehavior.h +# Include/GameLogic/Module/BattlePlanUpdate.h +# Include/GameLogic/Module/BehaviorModule.h +# Include/GameLogic/Module/BodyModule.h +# Include/GameLogic/Module/BoneFXDamage.h +# Include/GameLogic/Module/BoneFXUpdate.h +# Include/GameLogic/Module/BridgeBehavior.h +# Include/GameLogic/Module/BridgeScaffoldBehavior.h +# Include/GameLogic/Module/BridgeTowerBehavior.h +# Include/GameLogic/Module/BunkerBusterBehavior.h +# Include/GameLogic/Module/CashBountyPower.h +# Include/GameLogic/Module/CashHackSpecialPower.h +# Include/GameLogic/Module/CaveContain.h +# Include/GameLogic/Module/CheckpointUpdate.h +# Include/GameLogic/Module/ChinookAIUpdate.h +# Include/GameLogic/Module/CleanupAreaPower.h +# Include/GameLogic/Module/CleanupHazardUpdate.h +# Include/GameLogic/Module/CollideModule.h +# Include/GameLogic/Module/CommandButtonHuntUpdate.h +# Include/GameLogic/Module/CommandSetUpgrade.h +# Include/GameLogic/Module/ContainModule.h +# Include/GameLogic/Module/ConvertToCarBombCrateCollide.h +# Include/GameLogic/Module/ConvertToHijackedVehicleCrateCollide.h +# Include/GameLogic/Module/CostModifierUpgrade.h +# Include/GameLogic/Module/CountermeasuresBehavior.h +# Include/GameLogic/Module/CrateCollide.h +# Include/GameLogic/Module/CreateCrateDie.h +# Include/GameLogic/Module/CreateModule.h +# Include/GameLogic/Module/CreateObjectDie.h +# Include/GameLogic/Module/CrushDie.h +# Include/GameLogic/Module/DamageModule.h +# Include/GameLogic/Module/DamDie.h +# Include/GameLogic/Module/DefaultProductionExitUpdate.h +# Include/GameLogic/Module/DefectorSpecialPower.h +# Include/GameLogic/Module/DeletionUpdate.h +# Include/GameLogic/Module/DeliverPayloadAIUpdate.h +# Include/GameLogic/Module/DemoralizeSpecialPower.h +# Include/GameLogic/Module/DemoTrapUpdate.h +# Include/GameLogic/Module/DeployStyleAIUpdate.h +# Include/GameLogic/Module/DestroyDie.h +# Include/GameLogic/Module/DestroyModule.h +# Include/GameLogic/Module/DieModule.h +# Include/GameLogic/Module/DockUpdate.h +# Include/GameLogic/Module/DozerAIUpdate.h +# Include/GameLogic/Module/DumbProjectileBehavior.h +# Include/GameLogic/Module/DynamicGeometryInfoUpdate.h +# Include/GameLogic/Module/DynamicShroudClearingRangeUpdate.h +# Include/GameLogic/Module/EjectPilotDie.h +# Include/GameLogic/Module/EMPUpdate.h +# Include/GameLogic/Module/EnemyNearUpdate.h +# Include/GameLogic/Module/ExperienceScalarUpgrade.h +# Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h +# Include/GameLogic/Module/FireSpreadUpdate.h +# Include/GameLogic/Module/FirestormDynamicGeometryInfoUpdate.h +# Include/GameLogic/Module/FireWeaponCollide.h +# Include/GameLogic/Module/FireWeaponPower.h +# Include/GameLogic/Module/FireWeaponUpdate.h +# Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h +# Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h +# Include/GameLogic/Module/FlammableUpdate.h +# Include/GameLogic/Module/FlightDeckBehavior.h +# Include/GameLogic/Module/FloatUpdate.h +# Include/GameLogic/Module/FXListDie.h +# Include/GameLogic/Module/GarrisonContain.h +# Include/GameLogic/Module/GenerateMinefieldBehavior.h +# Include/GameLogic/Module/GrantScienceUpgrade.h +# Include/GameLogic/Module/GrantStealthBehavior.h +# Include/GameLogic/Module/GrantUpgradeCreate.h +# Include/GameLogic/Module/HackInternetAIUpdate.h +# Include/GameLogic/Module/HealContain.h +# Include/GameLogic/Module/HealCrateCollide.h +# Include/GameLogic/Module/HeightDieUpdate.h +# Include/GameLogic/Module/HelicopterSlowDeathUpdate.h +# Include/GameLogic/Module/HelixContain.h +# Include/GameLogic/Module/HighlanderBody.h +# Include/GameLogic/Module/HijackerUpdate.h +# Include/GameLogic/Module/HiveStructureBody.h +# Include/GameLogic/Module/HordeUpdate.h +# Include/GameLogic/Module/ImmortalBody.h +# Include/GameLogic/Module/InactiveBody.h +# Include/GameLogic/Module/InstantDeathBehavior.h +# Include/GameLogic/Module/InternetHackContain.h +# Include/GameLogic/Module/JetAIUpdate.h +# Include/GameLogic/Module/JetSlowDeathBehavior.h +# Include/GameLogic/Module/KeepObjectDie.h +# Include/GameLogic/Module/LaserUpdate.h +# Include/GameLogic/Module/LifetimeUpdate.h +# Include/GameLogic/Module/LockWeaponCreate.h +# Include/GameLogic/Module/LocomotorSetUpgrade.h +# Include/GameLogic/Module/MaxHealthUpgrade.h +# Include/GameLogic/Module/MinefieldBehavior.h +# Include/GameLogic/Module/MissileAIUpdate.h +# Include/GameLogic/Module/MissileLauncherBuildingUpdate.h +# Include/GameLogic/Module/MobMemberSlavedUpdate.h +# Include/GameLogic/Module/MobNexusContain.h +# Include/GameLogic/Module/ModelConditionUpgrade.h +# Include/GameLogic/Module/MoneyCrateCollide.h +# Include/GameLogic/Module/NeutronBlastBehavior.h +# Include/GameLogic/Module/NeutronMissileSlowDeathUpdate.h +# Include/GameLogic/Module/NeutronMissileUpdate.h +# Include/GameLogic/Module/ObjectCreationUpgrade.h +# Include/GameLogic/Module/ObjectDefectionHelper.h +# Include/GameLogic/Module/ObjectHelper.h +# Include/GameLogic/Module/ObjectRepulsorHelper.h +# Include/GameLogic/Module/ObjectSMCHelper.h +# Include/GameLogic/Module/ObjectWeaponStatusHelper.h +# Include/GameLogic/Module/OCLSpecialPower.h +# Include/GameLogic/Module/OCLUpdate.h +# Include/GameLogic/Module/OpenContain.h +# Include/GameLogic/Module/OverchargeBehavior.h +# Include/GameLogic/Module/OverlordContain.h +# Include/GameLogic/Module/ParachuteContain.h +# Include/GameLogic/Module/ParkingPlaceBehavior.h +# Include/GameLogic/Module/ParticleUplinkCannonUpdate.h +# Include/GameLogic/Module/PassengersFireUpgrade.h +# Include/GameLogic/Module/PhysicsUpdate.h +# Include/GameLogic/Module/PilotFindVehicleUpdate.h +# Include/GameLogic/Module/PointDefenseLaserUpdate.h +# Include/GameLogic/Module/PoisonedBehavior.h +# Include/GameLogic/Module/PowerPlantUpdate.h +# Include/GameLogic/Module/PowerPlantUpgrade.h +# Include/GameLogic/Module/POWTruckAIUpdate.h +# Include/GameLogic/Module/POWTruckBehavior.h +# Include/GameLogic/Module/PreorderCreate.h +# Include/GameLogic/Module/PrisonBehavior.h +# Include/GameLogic/Module/PrisonDockUpdate.h +# Include/GameLogic/Module/ProductionUpdate.h +# Include/GameLogic/Module/ProjectileStreamUpdate.h +# Include/GameLogic/Module/ProneUpdate.h +# Include/GameLogic/Module/PropagandaCenterBehavior.h +# Include/GameLogic/Module/PropagandaTowerBehavior.h +# Include/GameLogic/Module/QueueProductionExitUpdate.h +# Include/GameLogic/Module/RadarUpdate.h +# Include/GameLogic/Module/RadarUpgrade.h +# Include/GameLogic/Module/RadiusDecalUpdate.h +# Include/GameLogic/Module/RailedTransportAIUpdate.h +# Include/GameLogic/Module/RailedTransportContain.h +# Include/GameLogic/Module/RailedTransportDockUpdate.h +# Include/GameLogic/Module/RailroadGuideAIUpdate.h +# Include/GameLogic/Module/RebuildHoleBehavior.h +# Include/GameLogic/Module/RebuildHoleExposeDie.h +# Include/GameLogic/Module/RepairDockUpdate.h +# Include/GameLogic/Module/ReplaceObjectUpgrade.h +# Include/GameLogic/Module/RiderChangeContain.h +# Include/GameLogic/Module/SabotageCommandCenterCrateCollide.h +# Include/GameLogic/Module/SabotageFakeBuildingCrateCollide.h +# Include/GameLogic/Module/SabotageInternetCenterCrateCollide.h +# Include/GameLogic/Module/SabotageMilitaryFactoryCrateCollide.h +# Include/GameLogic/Module/SabotagePowerPlantCrateCollide.h +# Include/GameLogic/Module/SabotageSuperweaponCrateCollide.h +# Include/GameLogic/Module/SabotageSupplyCenterCrateCollide.h +# Include/GameLogic/Module/SabotageSupplyDropzoneCrateCollide.h +# Include/GameLogic/Module/SalvageCrateCollide.h +# Include/GameLogic/Module/ShroudCrateCollide.h +# Include/GameLogic/Module/SlavedUpdate.h +# Include/GameLogic/Module/SlowDeathBehavior.h +# Include/GameLogic/Module/SmartBombTargetHomingUpdate.h +# Include/GameLogic/Module/SpawnBehavior.h +# Include/GameLogic/Module/SpawnPointProductionExitUpdate.h +# Include/GameLogic/Module/SpecialAbility.h +# Include/GameLogic/Module/SpecialAbilityUpdate.h +# Include/GameLogic/Module/SpecialPowerCompletionDie.h +# Include/GameLogic/Module/SpecialPowerCreate.h +# Include/GameLogic/Module/SpecialPowerModule.h +# Include/GameLogic/Module/SpecialPowerUpdateModule.h +# Include/GameLogic/Module/SpectreGunshipDeploymentUpdate.h +# Include/GameLogic/Module/SpectreGunshipUpdate.h +# Include/GameLogic/Module/SpyVisionSpecialPower.h +# Include/GameLogic/Module/SpyVisionUpdate.h +# Include/GameLogic/Module/SquishCollide.h +# Include/GameLogic/Module/StatusBitsUpgrade.h +# Include/GameLogic/Module/StatusDamageHelper.h +# Include/GameLogic/Module/StealthDetectorUpdate.h +# Include/GameLogic/Module/StealthUpdate.h +# Include/GameLogic/Module/StealthUpgrade.h +# Include/GameLogic/Module/StickyBombUpdate.h +# Include/GameLogic/Module/StructureBody.h +# Include/GameLogic/Module/StructureCollapseUpdate.h +# Include/GameLogic/Module/StructureToppleUpdate.h +# Include/GameLogic/Module/SubdualDamageHelper.h +# Include/GameLogic/Module/SubObjectsUpgrade.h +# Include/GameLogic/Module/SupplyCenterCreate.h +# Include/GameLogic/Module/SupplyCenterDockUpdate.h +# Include/GameLogic/Module/SupplyCenterProductionExitUpdate.h +# Include/GameLogic/Module/SupplyTruckAIUpdate.h +# Include/GameLogic/Module/SupplyWarehouseCreate.h +# Include/GameLogic/Module/SupplyWarehouseCripplingBehavior.h +# Include/GameLogic/Module/SupplyWarehouseDockUpdate.h +# Include/GameLogic/Module/TechBuildingBehavior.h +# Include/GameLogic/Module/TempWeaponBonusHelper.h +# Include/GameLogic/Module/TensileFormationUpdate.h +# Include/GameLogic/Module/ToppleUpdate.h +# Include/GameLogic/Module/TransitionDamageFX.h +# Include/GameLogic/Module/TransportAIUpdate.h +# Include/GameLogic/Module/TransportContain.h +# Include/GameLogic/Module/TunnelContain.h +# Include/GameLogic/Module/UndeadBody.h +# Include/GameLogic/Module/UnitCrateCollide.h +# Include/GameLogic/Module/UnpauseSpecialPowerUpgrade.h +# Include/GameLogic/Module/UpdateModule.h +# Include/GameLogic/Module/UpgradeDie.h +# Include/GameLogic/Module/UpgradeModule.h +# Include/GameLogic/Module/VeterancyCrateCollide.h +# Include/GameLogic/Module/VeterancyGainCreate.h +# Include/GameLogic/Module/WanderAIUpdate.h +# Include/GameLogic/Module/WaveGuideUpdate.h +# Include/GameLogic/Module/WeaponBonusUpdate.h +# Include/GameLogic/Module/WeaponBonusUpgrade.h +# Include/GameLogic/Module/WeaponSetUpgrade.h +# Include/GameLogic/Module/WorkerAIUpdate.h +# Include/GameLogic/Object.h +# Include/GameLogic/ObjectCreationList.h +# Include/GameLogic/ObjectIter.h +# Include/GameLogic/ObjectScriptStatusBits.h +# Include/GameLogic/ObjectTypes.h +# Include/GameLogic/PartitionManager.h +# Include/GameLogic/PolygonTrigger.h +# Include/GameLogic/Powers.h +# Include/GameLogic/RankInfo.h +# Include/GameLogic/ScriptActions.h +# Include/GameLogic/ScriptConditions.h +# Include/GameLogic/ScriptEngine.h +# Include/GameLogic/Scripts.h +# Include/GameLogic/SidesList.h +# Include/GameLogic/Squad.h +# Include/GameLogic/TerrainLogic.h +# Include/GameLogic/TurretAI.h +# Include/GameLogic/VictoryConditions.h +# Include/GameLogic/Weapon.h +# Include/GameLogic/WeaponBonusConditionFlags.h +# Include/GameLogic/WeaponSet.h +# Include/GameLogic/WeaponSetFlags.h +# Include/GameLogic/WeaponSetType.h +# Include/GameLogic/WeaponStatus.h +# Include/GameNetwork/Connection.h +# Include/GameNetwork/ConnectionManager.h +# Include/GameNetwork/DisconnectManager.h +# Include/GameNetwork/DownloadManager.h +# Include/GameNetwork/FileTransfer.h +# Include/GameNetwork/FirewallHelper.h +# Include/GameNetwork/FrameData.h +# Include/GameNetwork/FrameDataManager.h +# Include/GameNetwork/FrameMetrics.h +# Include/GameNetwork/GameInfo.h +# Include/GameNetwork/GameMessageParser.h +# Include/GameNetwork/GameSpy/BuddyDefs.h +# Include/GameNetwork/GameSpy/BuddyThread.h +# Include/GameNetwork/GameSpy/GameResultsThread.h +# Include/GameNetwork/GameSpy/GSConfig.h +# Include/GameNetwork/GameSpy/LadderDefs.h +# Include/GameNetwork/GameSpy/LobbyUtils.h +# Include/GameNetwork/GameSpy/MainMenuUtils.h +# Include/GameNetwork/GameSpy/PeerDefs.h +# Include/GameNetwork/GameSpy/PeerDefsImplementation.h +# Include/GameNetwork/GameSpy/PeerThread.h +# Include/GameNetwork/GameSpy/PersistentStorageDefs.h +# Include/GameNetwork/GameSpy/PersistentStorageThread.h +# Include/GameNetwork/GameSpy/PingThread.h +# Include/GameNetwork/GameSpy/StagingRoomGameInfo.h +# Include/GameNetwork/GameSpy/ThreadUtils.h +# Include/GameNetwork/GameSpyChat.h +# Include/GameNetwork/GameSpyGameInfo.h +# Include/GameNetwork/GameSpyGP.h +# Include/GameNetwork/GameSpyOverlay.h +# Include/GameNetwork/GameSpyThread.h +# Include/GameNetwork/GUIUtil.h +# Include/GameNetwork/IPEnumeration.h +# Include/GameNetwork/LANAPI.h +# Include/GameNetwork/LANAPICallbacks.h +# Include/GameNetwork/LANGameInfo.h +# Include/GameNetwork/LANPlayer.h +# Include/GameNetwork/NAT.h +# Include/GameNetwork/NetCommandList.h +# Include/GameNetwork/NetCommandMsg.h +# Include/GameNetwork/NetCommandRef.h +# Include/GameNetwork/NetCommandWrapperList.h +# Include/GameNetwork/NetPacket.h +# Include/GameNetwork/NetworkDefs.h +# Include/GameNetwork/NetworkInterface.h +# Include/GameNetwork/networkutil.h +# Include/GameNetwork/RankPointValue.h +# Include/GameNetwork/Transport.h +# Include/GameNetwork/udp.h +# Include/GameNetwork/User.h +# Include/GameNetwork/WOLBrowser/FEBDispatch.h +# Include/GameNetwork/WOLBrowser/WebBrowser.h +# Include/Precompiled/PreRTS.h +# Source/Common/Audio/AudioEventRTS.cpp +# Source/Common/Audio/AudioRequest.cpp +# Source/Common/Audio/DynamicAudioEventInfo.cpp +# Source/Common/Audio/GameAudio.cpp +# Source/Common/Audio/GameMusic.cpp +# Source/Common/Audio/GameSounds.cpp + #Source/Common/Audio/simpleplayer.cpp # unused + #Source/Common/Audio/urllaunch.cpp # unused +# Source/Common/Bezier/BezFwdIterator.cpp +# Source/Common/Bezier/BezierSegment.cpp +# Source/Common/BitFlags.cpp +# Source/Common/CommandLine.cpp +# Source/Common/crc.cpp +# Source/Common/CRCDebug.cpp +# Source/Common/DamageFX.cpp +# Source/Common/Dict.cpp +# Source/Common/DiscreteCircle.cpp +# Source/Common/GameEngine.cpp +# Source/Common/GameLOD.cpp +# Source/Common/GameMain.cpp +# Source/Common/GlobalData.cpp +# Source/Common/INI/INI.cpp +# Source/Common/INI/INIAiData.cpp +# Source/Common/INI/INIAnimation.cpp +# Source/Common/INI/INIAudioEventInfo.cpp +# Source/Common/INI/INICommandButton.cpp +# Source/Common/INI/INICommandSet.cpp +# Source/Common/INI/INIControlBarScheme.cpp +# Source/Common/INI/INICrate.cpp +# Source/Common/INI/INIDamageFX.cpp +# Source/Common/INI/INIDrawGroupInfo.cpp +# Source/Common/INI/INIGameData.cpp +# Source/Common/INI/INIMapCache.cpp +# Source/Common/INI/INIMapData.cpp +# Source/Common/INI/INIMappedImage.cpp +# Source/Common/INI/INIMiscAudio.cpp +# Source/Common/INI/INIModel.cpp +# Source/Common/INI/INIMultiplayer.cpp +# Source/Common/INI/INIObject.cpp +# Source/Common/INI/INIParticleSys.cpp +# Source/Common/INI/INISpecialPower.cpp +# Source/Common/INI/INITerrain.cpp +# Source/Common/INI/INITerrainBridge.cpp +# Source/Common/INI/INITerrainRoad.cpp +# Source/Common/INI/INIUpgrade.cpp +# Source/Common/INI/INIVideo.cpp +# Source/Common/INI/INIWater.cpp +# Source/Common/INI/INIWeapon.cpp +# Source/Common/INI/INIWebpageURL.cpp +# Source/Common/Language.cpp +# Source/Common/MessageStream.cpp +# Source/Common/MiniLog.cpp +# Source/Common/MultiplayerSettings.cpp +# Source/Common/NameKeyGenerator.cpp +# Source/Common/PartitionSolver.cpp +# Source/Common/PerfTimer.cpp +# Source/Common/RandomValue.cpp +# Source/Common/Recorder.cpp +# Source/Common/RTS/AcademyStats.cpp +# Source/Common/RTS/ActionManager.cpp +# Source/Common/RTS/Energy.cpp +# Source/Common/RTS/Handicap.cpp +# Source/Common/RTS/MissionStats.cpp +# Source/Common/RTS/Money.cpp +# Source/Common/RTS/Player.cpp +# Source/Common/RTS/PlayerList.cpp +# Source/Common/RTS/PlayerTemplate.cpp +# Source/Common/RTS/ProductionPrerequisite.cpp +# Source/Common/RTS/ResourceGatheringManager.cpp +# Source/Common/RTS/Science.cpp +# Source/Common/RTS/ScoreKeeper.cpp +# Source/Common/RTS/SpecialPower.cpp +# Source/Common/RTS/Team.cpp +# Source/Common/RTS/TunnelTracker.cpp +# Source/Common/SkirmishBattleHonors.cpp +# Source/Common/StateMachine.cpp +# Source/Common/StatsCollector.cpp +# Source/Common/System/ArchiveFile.cpp +# Source/Common/System/ArchiveFileSystem.cpp +# Source/Common/System/AsciiString.cpp +# Source/Common/System/BuildAssistant.cpp +# Source/Common/System/CDManager.cpp +# Source/Common/System/CopyProtection.cpp +# Source/Common/System/CriticalSection.cpp +# Source/Common/System/DataChunk.cpp +# Source/Common/System/Debug.cpp +# Source/Common/System/Directory.cpp +# Source/Common/System/DisabledTypes.cpp +# Source/Common/System/encrypt.cpp +# Source/Common/System/File.cpp +# Source/Common/System/FileSystem.cpp +# Source/Common/System/FunctionLexicon.cpp +# Source/Common/System/GameCommon.cpp + #Source/Common/System/GameMemory.cpp # is conditionally appended +# Source/Common/System/GameType.cpp +# Source/Common/System/Geometry.cpp +# Source/Common/System/KindOf.cpp +# Source/Common/System/List.cpp +# Source/Common/System/LocalFile.cpp +# Source/Common/System/LocalFileSystem.cpp + #Source/Common/System/MemoryInit.cpp # is conditionally appended +# Source/Common/System/ObjectStatusTypes.cpp +# Source/Common/System/QuotedPrintable.cpp +# Source/Common/System/Radar.cpp +# Source/Common/System/RAMFile.cpp +# Source/Common/System/registry.cpp +# Source/Common/System/SaveGame/GameState.cpp +# Source/Common/System/SaveGame/GameStateMap.cpp +# Source/Common/System/Snapshot.cpp +# Source/Common/System/StackDump.cpp +# Source/Common/System/StreamingArchiveFile.cpp +# Source/Common/System/SubsystemInterface.cpp +# Source/Common/System/Trig.cpp +# Source/Common/System/UnicodeString.cpp +# Source/Common/System/Upgrade.cpp + Source/Common/System/Xfer.cpp + Source/Common/System/XferCRC.cpp + Source/Common/System/XferLoad.cpp + Source/Common/System/XferSave.cpp +# Source/Common/TerrainTypes.cpp +# Source/Common/Thing/DrawModule.cpp +# Source/Common/Thing/Module.cpp +# Source/Common/Thing/ModuleFactory.cpp +# Source/Common/Thing/Thing.cpp +# Source/Common/Thing/ThingFactory.cpp +# Source/Common/Thing/ThingTemplate.cpp +# Source/Common/UserPreferences.cpp +# Source/Common/version.cpp +# Source/GameClient/ClientInstance.cpp +# Source/GameClient/Color.cpp +# Source/GameClient/Credits.cpp +# Source/GameClient/Display.cpp +# Source/GameClient/DisplayString.cpp +# Source/GameClient/DisplayStringManager.cpp +# Source/GameClient/Drawable.cpp +# Source/GameClient/Drawable/Update/AnimatedParticleSysBoneClientUpdate.cpp +# Source/GameClient/Drawable/Update/BeaconClientUpdate.cpp +# Source/GameClient/Drawable/Update/SwayClientUpdate.cpp +# Source/GameClient/DrawGroupInfo.cpp +# Source/GameClient/Eva.cpp +# Source/GameClient/FXList.cpp +# Source/GameClient/GameClient.cpp +# Source/GameClient/GameClientDispatch.cpp +# Source/GameClient/GameText.cpp +# Source/GameClient/GlobalLanguage.cpp +# Source/GameClient/GraphDraw.cpp +# Source/GameClient/GUI/AnimateWindowManager.cpp +# Source/GameClient/GUI/ChallengeGenerals.cpp +# Source/GameClient/GUI/ControlBar/ControlBar.cpp +# Source/GameClient/GUI/ControlBar/ControlBarBeacon.cpp +# Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +# Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp +# Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp +# Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp +# Source/GameClient/GUI/ControlBar/ControlBarOCLTimer.cpp +# Source/GameClient/GUI/ControlBar/ControlBarPrintPositions.cpp +# Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp +# Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +# Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp +# Source/GameClient/GUI/ControlBar/ControlBarUnderConstruction.cpp +# Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp +# Source/GameClient/GUI/EstablishConnectionsMenu/EstablishConnectionsMenu.cpp +# Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp +# Source/GameClient/GUI/Gadget/GadgetComboBox.cpp +# Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp +# Source/GameClient/GUI/Gadget/GadgetListBox.cpp +# Source/GameClient/GUI/Gadget/GadgetProgressBar.cpp +# Source/GameClient/GUI/Gadget/GadgetPushButton.cpp +# Source/GameClient/GUI/Gadget/GadgetRadioButton.cpp +# Source/GameClient/GUI/Gadget/GadgetStaticText.cpp +# Source/GameClient/GUI/Gadget/GadgetTabControl.cpp +# Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp +# Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp +# Source/GameClient/GUI/GameFont.cpp +# Source/GameClient/GUI/GameWindow.cpp +# Source/GameClient/GUI/GameWindowGlobal.cpp +# Source/GameClient/GUI/GameWindowManager.cpp +# Source/GameClient/GUI/GameWindowManagerScript.cpp +# Source/GameClient/GUI/GameWindowTransitions.cpp +# Source/GameClient/GUI/GameWindowTransitionsStyles.cpp +# Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp +# Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +# Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp +# Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp +# Source/GameClient/GUI/GUICallbacks/GeneralsExpPoints.cpp +# Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp +# Source/GameClient/GUI/GUICallbacks/InGameChat.cpp +# Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp +# Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +# Source/GameClient/GUI/GUICallbacks/MessageBox.cpp +# Source/GameClient/GUI/GUICallbacks/ReplayControls.cpp +# Source/GameClient/GUI/HeaderTemplate.cpp +# Source/GameClient/GUI/IMEManager.cpp +# Source/GameClient/GUI/LoadScreen.cpp +# Source/GameClient/GUI/ProcessAnimateWindow.cpp +# Source/GameClient/GUI/Shell/Shell.cpp +# Source/GameClient/GUI/Shell/ShellMenuScheme.cpp +# Source/GameClient/GUI/WindowLayout.cpp +# Source/GameClient/GUI/WindowVideoManager.cpp +# Source/GameClient/GUI/WinInstanceData.cpp +# Source/GameClient/InGameUI.cpp +# Source/GameClient/Input/Keyboard.cpp +# Source/GameClient/Input/Mouse.cpp +# Source/GameClient/LanguageFilter.cpp +# Source/GameClient/Line2D.cpp +# Source/GameClient/MapUtil.cpp +# Source/GameClient/MessageStream/CommandXlat.cpp +# Source/GameClient/MessageStream/GUICommandTranslator.cpp +# Source/GameClient/MessageStream/HintSpy.cpp +# Source/GameClient/MessageStream/HotKey.cpp +# Source/GameClient/MessageStream/LookAtXlat.cpp +# Source/GameClient/MessageStream/MetaEvent.cpp +# Source/GameClient/MessageStream/PlaceEventTranslator.cpp +# Source/GameClient/MessageStream/SelectionXlat.cpp +# Source/GameClient/MessageStream/WindowXlat.cpp +# Source/GameClient/ParabolicEase.cpp +# Source/GameClient/RadiusDecal.cpp +# Source/GameClient/SelectionInfo.cpp +# Source/GameClient/Snow.cpp +# Source/GameClient/Statistics.cpp +# Source/GameClient/System/Anim2D.cpp +# Source/GameClient/System/CampaignManager.cpp +# "Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp" +# Source/GameClient/System/DebugDisplay.cpp +# Source/GameClient/System/Image.cpp +# Source/GameClient/System/ParticleSys.cpp +# Source/GameClient/System/RayEffect.cpp +# Source/GameClient/System/Smudge.cpp +# Source/GameClient/Terrain/TerrainRoads.cpp +# Source/GameClient/Terrain/TerrainVisual.cpp +# Source/GameClient/VideoPlayer.cpp +# Source/GameClient/VideoStream.cpp +# Source/GameClient/View.cpp +# Source/GameClient/Water.cpp +# Source/GameLogic/AI/AI.cpp +# Source/GameLogic/AI/AIDock.cpp +# Source/GameLogic/AI/AIGroup.cpp +# Source/GameLogic/AI/AIGuard.cpp +# Source/GameLogic/AI/AIGuardRetaliate.cpp +# Source/GameLogic/AI/AIPathfind.cpp +# Source/GameLogic/AI/AIPlayer.cpp +# Source/GameLogic/AI/AISkirmishPlayer.cpp +# Source/GameLogic/AI/AIStates.cpp +# Source/GameLogic/AI/AITNGuard.cpp +# Source/GameLogic/AI/Squad.cpp +# Source/GameLogic/AI/TurretAI.cpp +# Source/GameLogic/Map/PolygonTrigger.cpp +# Source/GameLogic/Map/SidesList.cpp +# Source/GameLogic/Map/TerrainLogic.cpp +# Source/GameLogic/Object/Armor.cpp +# Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp +# Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp +# Source/GameLogic/Object/Behavior/BehaviorModule.cpp +# Source/GameLogic/Object/Behavior/BridgeBehavior.cpp +# Source/GameLogic/Object/Behavior/BridgeScaffoldBehavior.cpp +# Source/GameLogic/Object/Behavior/BridgeTowerBehavior.cpp +# Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp +# Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp +# Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp +# Source/GameLogic/Object/Behavior/FireWeaponWhenDamagedBehavior.cpp +# Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp +# Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp +# Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp +# Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp +# Source/GameLogic/Object/Behavior/InstantDeathBehavior.cpp +# Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp +# Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp +# Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp +# Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp +# Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp +# Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp +# Source/GameLogic/Object/Behavior/POWTruckBehavior.cpp +# Source/GameLogic/Object/Behavior/PrisonBehavior.cpp +# Source/GameLogic/Object/Behavior/PropagandaCenterBehavior.cpp +# Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp +# Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp +# Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp +# Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +# Source/GameLogic/Object/Behavior/SupplyWarehouseCripplingBehavior.cpp +# Source/GameLogic/Object/Behavior/TechBuildingBehavior.cpp +# Source/GameLogic/Object/Body/ActiveBody.cpp +# Source/GameLogic/Object/Body/BodyModule.cpp +# Source/GameLogic/Object/Body/HighlanderBody.cpp +# Source/GameLogic/Object/Body/HiveStructureBody.cpp +# Source/GameLogic/Object/Body/ImmortalBody.cpp +# Source/GameLogic/Object/Body/InactiveBody.cpp +# Source/GameLogic/Object/Body/StructureBody.cpp +# Source/GameLogic/Object/Body/UndeadBody.cpp +# Source/GameLogic/Object/Collide/CollideModule.cpp +# Source/GameLogic/Object/Collide/CrateCollide/ConvertToCarBombCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/HealCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/MoneyCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/ShroudCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/UnitCrateCollide.cpp +# Source/GameLogic/Object/Collide/CrateCollide/VeterancyCrateCollide.cpp +# Source/GameLogic/Object/Collide/FireWeaponCollide.cpp +# Source/GameLogic/Object/Collide/SquishCollide.cpp +# Source/GameLogic/Object/Contain/CaveContain.cpp +# Source/GameLogic/Object/Contain/GarrisonContain.cpp +# Source/GameLogic/Object/Contain/HealContain.cpp +# Source/GameLogic/Object/Contain/HelixContain.cpp +# Source/GameLogic/Object/Contain/InternetHackContain.cpp +# Source/GameLogic/Object/Contain/MobNexusContain.cpp +# Source/GameLogic/Object/Contain/OpenContain.cpp +# Source/GameLogic/Object/Contain/OverlordContain.cpp +# Source/GameLogic/Object/Contain/ParachuteContain.cpp +# Source/GameLogic/Object/Contain/RailedTransportContain.cpp +# Source/GameLogic/Object/Contain/RiderChangeContain.cpp +# Source/GameLogic/Object/Contain/TransportContain.cpp +# Source/GameLogic/Object/Contain/TunnelContain.cpp +# Source/GameLogic/Object/Create/CreateModule.cpp +# Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp +# Source/GameLogic/Object/Create/LockWeaponCreate.cpp +# Source/GameLogic/Object/Create/PreorderCreate.cpp +# Source/GameLogic/Object/Create/SpecialPowerCreate.cpp +# Source/GameLogic/Object/Create/SupplyCenterCreate.cpp +# Source/GameLogic/Object/Create/SupplyWarehouseCreate.cpp +# Source/GameLogic/Object/Create/VeterancyGainCreate.cpp +# Source/GameLogic/Object/Damage/BoneFXDamage.cpp +# Source/GameLogic/Object/Damage/DamageModule.cpp +# Source/GameLogic/Object/Damage/TransitionDamageFX.cpp +# Source/GameLogic/Object/Destroy/DestroyModule.cpp +# Source/GameLogic/Object/Die/CreateCrateDie.cpp +# Source/GameLogic/Object/Die/CreateObjectDie.cpp +# Source/GameLogic/Object/Die/CrushDie.cpp +# Source/GameLogic/Object/Die/DamDie.cpp +# Source/GameLogic/Object/Die/DestroyDie.cpp +# Source/GameLogic/Object/Die/DieModule.cpp +# Source/GameLogic/Object/Die/EjectPilotDie.cpp +# Source/GameLogic/Object/Die/FXListDie.cpp +# Source/GameLogic/Object/Die/KeepObjectDie.cpp +# Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp +# Source/GameLogic/Object/Die/SpecialPowerCompletionDie.cpp +# Source/GameLogic/Object/Die/UpgradeDie.cpp +# Source/GameLogic/Object/ExperienceTracker.cpp +# Source/GameLogic/Object/FiringTracker.cpp +# Source/GameLogic/Object/GhostObject.cpp +# Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp +# Source/GameLogic/Object/Helper/ObjectHelper.cpp +# Source/GameLogic/Object/Helper/ObjectRepulsorHelper.cpp +# Source/GameLogic/Object/Helper/ObjectSMCHelper.cpp +# Source/GameLogic/Object/Helper/ObjectWeaponStatusHelper.cpp +# Source/GameLogic/Object/Helper/StatusDamageHelper.cpp +# Source/GameLogic/Object/Helper/SubdualDamageHelper.cpp +# Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp +# Source/GameLogic/Object/Locomotor.cpp +# Source/GameLogic/Object/Object.cpp +# Source/GameLogic/Object/ObjectCreationList.cpp +# Source/GameLogic/Object/ObjectTypes.cpp +# Source/GameLogic/Object/PartitionManager.cpp +# Source/GameLogic/Object/SimpleObjectIterator.cpp +# Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp +# Source/GameLogic/Object/SpecialPower/CashBountyPower.cpp +# Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp +# Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp +# Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp +# Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp +# Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp +# Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp +# Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp +# Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp +# Source/GameLogic/Object/SpecialPower/SpyVisionSpecialPower.cpp +# Source/GameLogic/Object/Update/AIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/POWTruckAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/RailedTransportAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cpp +# Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +# Source/GameLogic/Object/Update/AnimationSteeringUpdate.cpp +# Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp +# Source/GameLogic/Object/Update/AutoDepositUpdate.cpp +# Source/GameLogic/Object/Update/AutoFindHealingUpdate.cpp +# Source/GameLogic/Object/Update/BaseRenerateUpdate.cpp +# Source/GameLogic/Object/Update/BattlePlanUpdate.cpp +# Source/GameLogic/Object/Update/BoneFXUpdate.cpp +# Source/GameLogic/Object/Update/CheckpointUpdate.cpp +# Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp +# Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp +# Source/GameLogic/Object/Update/DeletionUpdate.cpp +# Source/GameLogic/Object/Update/DemoTrapUpdate.cpp +# Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp +# Source/GameLogic/Object/Update/DockUpdate/PrisonDockUpdate.cpp +# Source/GameLogic/Object/Update/DockUpdate/RailedTransportDockUpdate.cpp +# Source/GameLogic/Object/Update/DockUpdate/RepairDockUpdate.cpp +# Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp +# Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp +# Source/GameLogic/Object/Update/DynamicGeometryInfoUpdate.cpp +# Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp +# Source/GameLogic/Object/Update/EMPUpdate.cpp +# Source/GameLogic/Object/Update/EnemyNearUpdate.cpp +# Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp +# Source/GameLogic/Object/Update/FireSpreadUpdate.cpp +# Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cpp +# Source/GameLogic/Object/Update/FireWeaponUpdate.cpp +# Source/GameLogic/Object/Update/FlammableUpdate.cpp +# Source/GameLogic/Object/Update/FloatUpdate.cpp +# Source/GameLogic/Object/Update/HeightDieUpdate.cpp +# Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp +# Source/GameLogic/Object/Update/HijackerUpdate.cpp +# Source/GameLogic/Object/Update/HordeUpdate.cpp +# Source/GameLogic/Object/Update/LaserUpdate.cpp +# Source/GameLogic/Object/Update/LifetimeUpdate.cpp +# Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp +# Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp +# Source/GameLogic/Object/Update/NeutronMissileSlowDeathUpdate.cpp +# Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp +# Source/GameLogic/Object/Update/OCLUpdate.cpp +# Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp +# Source/GameLogic/Object/Update/PhysicsUpdate.cpp +# Source/GameLogic/Object/Update/PilotFindVehicleUpdate.cpp +# Source/GameLogic/Object/Update/PointDefenseLaserUpdate.cpp +# Source/GameLogic/Object/Update/PowerPlantUpdate.cpp +# Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp +# Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp +# Source/GameLogic/Object/Update/ProductionExitUpdate/SpawnPointProductionExitUpdate.cpp +# Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp +# Source/GameLogic/Object/Update/ProductionUpdate.cpp +# Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp +# Source/GameLogic/Object/Update/ProneUpdate.cpp +# Source/GameLogic/Object/Update/RadarUpdate.cpp +# Source/GameLogic/Object/Update/RadiusDecalUpdate.cpp +# Source/GameLogic/Object/Update/SlavedUpdate.cpp +# Source/GameLogic/Object/Update/SmartBombTargetHomingUpdate.cpp +# Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp +# Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp +# Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp +# Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp +# Source/GameLogic/Object/Update/SpyVisionUpdate.cpp +# Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp +# Source/GameLogic/Object/Update/StealthUpdate.cpp +# Source/GameLogic/Object/Update/StickyBombUpdate.cpp +# Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp +# Source/GameLogic/Object/Update/StructureToppleUpdate.cpp +# Source/GameLogic/Object/Update/TensileFormationUpdate.cpp +# Source/GameLogic/Object/Update/ToppleUpdate.cpp +# Source/GameLogic/Object/Update/UpdateModule.cpp +# Source/GameLogic/Object/Update/WaveGuideUpdate.cpp +# Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp +# Source/GameLogic/Object/Upgrade/ActiveShroudUpgrade.cpp +# Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp +# Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp +# Source/GameLogic/Object/Upgrade/CostModifierUpgrade.cpp +# Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp +# Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp +# Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp +# Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp +# Source/GameLogic/Object/Upgrade/ModelConditionUpgrade.cpp +# Source/GameLogic/Object/Upgrade/ObjectCreationUpgrade.cpp +# Source/GameLogic/Object/Upgrade/PassengersFireUpgrade.cpp +# Source/GameLogic/Object/Upgrade/PowerPlantUpgrade.cpp +# Source/GameLogic/Object/Upgrade/RadarUpgrade.cpp +# Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cpp +# Source/GameLogic/Object/Upgrade/StatusBitsUpgrade.cpp +# Source/GameLogic/Object/Upgrade/StealthUpgrade.cpp +# Source/GameLogic/Object/Upgrade/SubObjectsUpgrade.cpp +# Source/GameLogic/Object/Upgrade/UnpauseSpecialPowerUpgrade.cpp +# Source/GameLogic/Object/Upgrade/UpgradeModule.cpp +# Source/GameLogic/Object/Upgrade/WeaponBonusUpgrade.cpp +# Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp +# Source/GameLogic/Object/Weapon.cpp +# Source/GameLogic/Object/WeaponSet.cpp +# Source/GameLogic/ScriptEngine/ScriptActions.cpp +# Source/GameLogic/ScriptEngine/ScriptConditions.cpp +# Source/GameLogic/ScriptEngine/ScriptEngine.cpp +# Source/GameLogic/ScriptEngine/Scripts.cpp +# Source/GameLogic/ScriptEngine/VictoryConditions.cpp +# Source/GameLogic/System/CaveSystem.cpp +# Source/GameLogic/System/CrateSystem.cpp +# Source/GameLogic/System/Damage.cpp +# Source/GameLogic/System/GameLogic.cpp +# Source/GameLogic/System/GameLogicDispatch.cpp +# Source/GameLogic/System/RankInfo.cpp +# Source/GameNetwork/Connection.cpp +# Source/GameNetwork/ConnectionManager.cpp +# Source/GameNetwork/DisconnectManager.cpp +# Source/GameNetwork/DownloadManager.cpp +# Source/GameNetwork/FileTransfer.cpp +# Source/GameNetwork/FirewallHelper.cpp +# Source/GameNetwork/FrameData.cpp +# Source/GameNetwork/FrameDataManager.cpp +# Source/GameNetwork/FrameMetrics.cpp +# Source/GameNetwork/GameInfo.cpp +# Source/GameNetwork/GameMessageParser.cpp + #Source/GameNetwork/GameSpyChat.cpp # unused + #Source/GameNetwork/GameSpyGameInfo.cpp # unused + #Source/GameNetwork/GameSpyGP.cpp # unused +# Source/GameNetwork/GameSpy/Chat.cpp +# Source/GameNetwork/GameSpy/GSConfig.cpp +# Source/GameNetwork/GameSpy/LadderDefs.cpp +# Source/GameNetwork/GameSpy/LobbyUtils.cpp +# Source/GameNetwork/GameSpy/MainMenuUtils.cpp +# Source/GameNetwork/GameSpy/PeerDefs.cpp +# Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp +# Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp +# Source/GameNetwork/GameSpy/Thread/GameResultsThread.cpp +# Source/GameNetwork/GameSpy/Thread/PeerThread.cpp +# Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp +# Source/GameNetwork/GameSpy/Thread/PingThread.cpp +# Source/GameNetwork/GameSpy/Thread/ThreadUtils.cpp +# Source/GameNetwork/GameSpyOverlay.cpp +# Source/GameNetwork/GUIUtil.cpp +# Source/GameNetwork/IPEnumeration.cpp +# Source/GameNetwork/LANAPI.cpp +# Source/GameNetwork/LANAPICallbacks.cpp +# Source/GameNetwork/LANAPIhandlers.cpp +# Source/GameNetwork/LANGameInfo.cpp +# Source/GameNetwork/NAT.cpp +# Source/GameNetwork/NetCommandList.cpp +# Source/GameNetwork/NetCommandMsg.cpp +# Source/GameNetwork/NetCommandRef.cpp +# Source/GameNetwork/NetCommandWrapperList.cpp +# Source/GameNetwork/NetMessageStream.cpp +# Source/GameNetwork/NetPacket.cpp +# Source/GameNetwork/Network.cpp +# Source/GameNetwork/NetworkUtil.cpp +# Source/GameNetwork/Transport.cpp +# Source/GameNetwork/udp.cpp +# Source/GameNetwork/User.cpp +# Source/GameNetwork/WOLBrowser/WebBrowser.cpp +# Source/Precompiled/PreRTS.cpp +) + +if(RTS_GAMEMEMORY_ENABLE) + # Uses the original Game Memory implementation. + list(APPEND GAMEENGINE_SRC +# Source/Common/System/GameMemory.cpp +# Source/Common/System/MemoryInit.cpp + ) +else() + # Uses the null implementation when disabled. + list(APPEND GAMEENGINE_SRC +# Source/Common/System/GameMemoryNull.cpp +# Include/Common/GameMemoryNull.h + ) +endif() + + +add_library(corei_gameengine_private INTERFACE) +add_library(corei_gameengine_public INTERFACE) + +target_sources(corei_gameengine_private INTERFACE ${GAMEENGINE_SRC}) + +target_include_directories(corei_gameengine_private INTERFACE +# Include/Precompiled +) + +target_link_libraries(corei_gameengine_private INTERFACE + corei_always +) + +target_compile_definitions(corei_gameengine_private INTERFACE + IG_DEBUG_STACKTRACE +) + +target_precompile_headers(corei_gameengine_private INTERFACE +# Include/Precompiled/PreRTS.h +) + +target_include_directories(corei_gameengine_public INTERFACE + Include +) + +target_link_libraries(corei_gameengine_public INTERFACE + core_compression + core_config + core_browserdispatch + core_utility + #core_wwvegas + d3d8lib + gamespy::gamespy + stlport +) diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Xfer.h b/Core/GameEngine/Include/Common/Xfer.h similarity index 95% rename from GeneralsMD/Code/GameEngine/Include/Common/Xfer.h rename to Core/GameEngine/Include/Common/Xfer.h index 449e46710b..f8f64d95ea 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Xfer.h +++ b/Core/GameEngine/Include/Common/Xfer.h @@ -27,6 +27,14 @@ // Desc: The Xfer system is capable of setting up operations to work with blocks of data // from other subsystems. It can work things such as file reading, file writing, // CRC computations etc +// +// TheSuperHackers @info helmutbuhler 04/09/2025 +// The baseclass Xfer has 3 implementations: +// - XferLoad: Load gamestate +// - XferSave: Save gamestate +// - XferCRC: Calculate gamestate CRC +// - XferDeepCRC: This derives from XferCRC and also writes the gamestate data relevant +// to crc calculation to a file (only used in developer builds) /////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferCRC.h b/Core/GameEngine/Include/Common/XferCRC.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/XferCRC.h rename to Core/GameEngine/Include/Common/XferCRC.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferDeepCRC.h b/Core/GameEngine/Include/Common/XferDeepCRC.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/XferDeepCRC.h rename to Core/GameEngine/Include/Common/XferDeepCRC.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferLoad.h b/Core/GameEngine/Include/Common/XferLoad.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/XferLoad.h rename to Core/GameEngine/Include/Common/XferLoad.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/XferSave.h b/Core/GameEngine/Include/Common/XferSave.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/XferSave.h rename to Core/GameEngine/Include/Common/XferSave.h diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Xfer.cpp b/Core/GameEngine/Source/Common/System/Xfer.cpp similarity index 99% rename from GeneralsMD/Code/GameEngine/Source/Common/System/Xfer.cpp rename to Core/GameEngine/Source/Common/System/Xfer.cpp index e389399ad2..b66d57195a 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Xfer.cpp +++ b/Core/GameEngine/Source/Common/System/Xfer.cpp @@ -36,7 +36,7 @@ #include "Common/Xfer.h" #include "Common/BitFlagsIO.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferCRC.cpp b/Core/GameEngine/Source/Common/System/XferCRC.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/System/XferCRC.cpp rename to Core/GameEngine/Source/Common/System/XferCRC.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferLoad.cpp b/Core/GameEngine/Source/Common/System/XferLoad.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/System/XferLoad.cpp rename to Core/GameEngine/Source/Common/System/XferLoad.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp b/Core/GameEngine/Source/Common/System/XferSave.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/System/XferSave.cpp rename to Core/GameEngine/Source/Common/System/XferSave.cpp diff --git a/Core/Libraries/CMakeLists.txt b/Core/Libraries/CMakeLists.txt index 415d8f8a81..1658bfbb9e 100644 --- a/Core/Libraries/CMakeLists.txt +++ b/Core/Libraries/CMakeLists.txt @@ -2,10 +2,10 @@ add_subdirectory(Source/WWVegas) # profiling library -#add_subdirectory(Source/profile) +add_subdirectory(Source/profile) # debugging library -#add_subdirectory(Source/debug) +add_subdirectory(Source/debug) add_subdirectory(Source/EABrowserDispatch) add_subdirectory(Source/EABrowserEngine) diff --git a/Core/Libraries/Include/Lib/BaseTypeCore.h b/Core/Libraries/Include/Lib/BaseTypeCore.h index b88babac74..0b542dcb51 100644 --- a/Core/Libraries/Include/Lib/BaseTypeCore.h +++ b/Core/Libraries/Include/Lib/BaseTypeCore.h @@ -37,6 +37,7 @@ // TheSuperHackers @compile feliwir 07/04/2025 Adds utility macros for cross-platform compatibility #include #include +#include /* ** Turn off some unneeded warnings. @@ -124,22 +125,17 @@ //-------------------------------------------------------------------- // Fundamental type definitions //-------------------------------------------------------------------- -typedef float Real; // 4 bytes -typedef int Int; // 4 bytes -typedef unsigned int UnsignedInt; // 4 bytes -typedef unsigned short UnsignedShort; // 2 bytes -typedef short Short; // 2 bytes -typedef unsigned char UnsignedByte; // 1 byte USED TO BE "Byte" -typedef char Byte; // 1 byte USED TO BE "SignedByte" -typedef char Char; // 1 byte of text -typedef bool Bool; // +typedef float Real; // 4 bytes +typedef int32_t Int; // 4 bytes +typedef uint32_t UnsignedInt; // 4 bytes +typedef uint16_t UnsignedShort; // 2 bytes +typedef int16_t Short; // 2 bytes +typedef unsigned char UnsignedByte; // 1 byte USED TO BE "Byte" +typedef char Byte; // 1 byte USED TO BE "SignedByte" +typedef char Char; // 1 byte of text +typedef bool Bool; // // note, the types below should use "long long", but MSVC doesn't support it yet -#ifdef _MSC_VER -typedef __int64 Int64; // 8 bytes -typedef unsigned __int64 UnsignedInt64; // 8 bytes -#else -typedef long long Int64; // 8 bytes -typedef unsigned long long UnsignedInt64; // 8 bytes -#endif +typedef int64_t Int64; // 8 bytes +typedef uint64_t UnsignedInt64; // 8 bytes #endif // _BASE_TYPE_CORE_H_ \ No newline at end of file diff --git a/GeneralsMD/Code/Libraries/Include/rts/debug.h b/Core/Libraries/Include/rts/debug.h similarity index 100% rename from GeneralsMD/Code/Libraries/Include/rts/debug.h rename to Core/Libraries/Include/rts/debug.h diff --git a/GeneralsMD/Code/Libraries/Include/rts/profile.h b/Core/Libraries/Include/rts/profile.h similarity index 100% rename from GeneralsMD/Code/Libraries/Include/rts/profile.h rename to Core/Libraries/Include/rts/profile.h diff --git a/Core/Libraries/Source/Compression/CMakeLists.txt b/Core/Libraries/Source/Compression/CMakeLists.txt index 48c69a5269..0f16820169 100644 --- a/Core/Libraries/Source/Compression/CMakeLists.txt +++ b/Core/Libraries/Source/Compression/CMakeLists.txt @@ -25,7 +25,7 @@ set_target_properties(core_compression PROPERTIES OUTPUT_NAME compression) target_sources(core_compression PRIVATE ${COMPRESSION_SRC}) target_include_directories(core_compression INTERFACE - . + ${CMAKE_CURRENT_SOURCE_DIR} ) target_link_libraries(core_compression PRIVATE @@ -34,7 +34,17 @@ target_link_libraries(core_compression PRIVATE corei_libraries_include ) + target_link_libraries(core_compression PUBLIC liblzhl - libzlib ) + +find_package(ZLIB) +if (ZLIB_FOUND) + # Adds zlib from vcpkg + target_link_libraries(core_compression PUBLIC ZLIB::ZLIB) +else() + # Adds zlib from github repository + include(${CMAKE_SOURCE_DIR}/cmake/zlib.cmake) + target_link_libraries(core_compression PUBLIC libzlib) +endif() diff --git a/Core/Libraries/Source/Compression/Compression.h b/Core/Libraries/Source/Compression/Compression.h index f74b2d6301..bea68a6b40 100644 --- a/Core/Libraries/Source/Compression/Compression.h +++ b/Core/Libraries/Source/Compression/Compression.h @@ -32,7 +32,6 @@ enum CompressionType COMPRESSION_MIN = 0, COMPRESSION_NONE = COMPRESSION_MIN, COMPRESSION_REFPACK, - COMPRESSION_MAX = COMPRESSION_REFPACK, COMPRESSION_NOXLZH, COMPRESSION_ZLIB1, COMPRESSION_ZLIB2, @@ -45,6 +44,7 @@ enum CompressionType COMPRESSION_ZLIB9, COMPRESSION_BTREE, COMPRESSION_HUFF, + COMPRESSION_MAX = COMPRESSION_HUFF, }; class CompressionManager diff --git a/Core/Libraries/Source/Compression/CompressionManager.cpp b/Core/Libraries/Source/Compression/CompressionManager.cpp index 9cd152ad98..a4e7325832 100644 --- a/Core/Libraries/Source/Compression/CompressionManager.cpp +++ b/Core/Libraries/Source/Compression/CompressionManager.cpp @@ -23,15 +23,16 @@ #include "Compression.h" #include "LZHCompress/NoxCompress.h" -extern "C" { -#include "ZLib/zlib.h" -} + +#define __MACTYPES__ +#include + #include "EAC/codex.h" #include "EAC/btreecodex.h" #include "EAC/huffcodex.h" #include "EAC/refcodex.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") @@ -45,7 +46,6 @@ const char *CompressionManager::getCompressionNameByType( CompressionType compTy static const char *s_compressionNames[COMPRESSION_MAX+1] = { "No compression", "RefPack", - /* "LZHL", "ZLib 1 (fast)", "ZLib 2", @@ -58,7 +58,6 @@ const char *CompressionManager::getCompressionNameByType( CompressionType compTy "ZLib 9 (slow)", "BTree", "Huff", - */ }; return s_compressionNames[compType]; } @@ -69,7 +68,6 @@ const char *CompressionManager::getDecompressionNameByType( CompressionType comp static const char *s_decompressionNames[COMPRESSION_MAX+1] = { "d_None", "d_RefPack", - /* "d_NoxLZW", "d_ZLib1", "d_ZLib2", @@ -82,7 +80,6 @@ const char *CompressionManager::getDecompressionNameByType( CompressionType comp "d_ZLib9", "d_BTree", "d_Huff", - */ }; return s_decompressionNames[compType]; } @@ -108,7 +105,6 @@ CompressionType CompressionManager::getCompressionType( const void *mem, Int len if ( memcmp( mem, "NOX\0", 4 ) == 0 ) return COMPRESSION_NOXLZH; - if ( memcmp( mem, "ZL1\0", 4 ) == 0 ) return COMPRESSION_ZLIB1; if ( memcmp( mem, "ZL2\0", 4 ) == 0 ) @@ -148,7 +144,6 @@ Int CompressionManager::getMaxCompressedSize( Int uncompressedLen, CompressionTy case COMPRESSION_HUFF: // guessing here case COMPRESSION_REFPACK: // guessing here return uncompressedLen + 8; - case COMPRESSION_ZLIB1: case COMPRESSION_ZLIB2: case COMPRESSION_ZLIB3: @@ -263,7 +258,7 @@ Int CompressionManager::compressData( CompressionType compType, void *srcVoid, I *(Int *)(dest+4) = 0; unsigned long outLen = destLen; - Int err = z_compress2( dest+8, &outLen, src, srcLen, level ); + Int err = compress2( (Bytef*)dest+8, &outLen, (const Bytef*)src, srcLen, level ); if (err == Z_OK || err == Z_STREAM_END) { @@ -330,7 +325,7 @@ Int CompressionManager::decompressData( void *srcVoid, Int srcLen, void *destVoi if (compType >= COMPRESSION_ZLIB1 && compType <= COMPRESSION_ZLIB9) { unsigned long outLen = destLen; - Int err = z_uncompress(dest, &outLen, src+8, srcLen-8); + Int err = uncompress((Bytef*)dest, &outLen, (const Bytef*)src+8, srcLen-8); if (err == Z_OK || err == Z_STREAM_END) { return outLen; diff --git a/Core/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp b/Core/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp index 36360865a6..b79db73c46 100644 --- a/Core/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp +++ b/Core/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp @@ -26,7 +26,7 @@ #include "NoxCompress.h" #include "CompLibHeader/lzhl.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Core/Libraries/Source/WWVegas/CMakeLists.txt b/Core/Libraries/Source/WWVegas/CMakeLists.txt index d86387528c..6c1a97bc6d 100644 --- a/Core/Libraries/Source/WWVegas/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/CMakeLists.txt @@ -7,51 +7,53 @@ target_compile_definitions(core_wwcommon INTERFACE ) target_link_libraries(core_wwcommon INTERFACE - d3d8lib core_config core_utility + d3d8lib milesstub stlport ) target_include_directories(core_wwcommon INTERFACE - . + ${CMAKE_CURRENT_SOURCE_DIR} + WW3D2 + WWAudio WWDebug + # WWDownload # is not added because headers are included as "WWDownload/file.h" WWLib + WWMath + WWSaveLoad ) -# add_subdirectory(WWAudio) +add_subdirectory(WW3D2) +add_subdirectory(WWAudio) add_subdirectory(WWDebug) +add_subdirectory(WWDownload) add_subdirectory(WWLib) -# add_subdirectory(WWMath) -# add_subdirectory(Wwutil) -# add_subdirectory(WWSaveLoad) -# add_subdirectory(WW3D2) -# add_subdirectory(WWDownload) -# add_subdirectory(wwshade) +add_subdirectory(WWMath) +add_subdirectory(WWSaveLoad) +add_subdirectory(WWStub) # Helpful interface to bundle the ww modules together. add_library(core_wwvegas INTERFACE) target_include_directories(core_wwvegas INTERFACE - . - #WW3D2 + ${CMAKE_CURRENT_SOURCE_DIR} + WW3D2 + WWAudio WWDebug - #WWDownload + # WWDownload # is not added because headers are included as "WWDownload/file.h" WWLib - #WWMath - #WWSaveLoad - #Wwutil - #wwshade + WWMath + WWSaveLoad ) target_link_libraries(core_wwvegas INTERFACE # core_ww3d2 + # core_wwaudio core_wwdebug # core_wwdownload core_wwlib - # core_wwmath - # core_wwsaveload - # core_wwshade - # core_wwutil + core_wwmath + core_wwsaveload ) diff --git a/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt new file mode 100644 index 0000000000..628746e29f --- /dev/null +++ b/Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt @@ -0,0 +1,248 @@ +set(WW3D2_SRC + aabtree.cpp + aabtree.h + #aabtreebuilder.cpp + #aabtreebuilder.h + agg_def.cpp + agg_def.h + animatedsoundmgr.cpp + animatedsoundmgr.h + #animobj.cpp + #animobj.h + #assetmgr.cpp + #assetmgr.h + assetstatus.cpp + assetstatus.h + bitmaphandler.cpp + bitmaphandler.h + #bmp2d.cpp + #bmp2d.h + #boxrobj.cpp + #boxrobj.h + bwrender.cpp + bwrender.h + #camera.cpp + #camera.h + #classid.h # unused + collect.cpp + collect.h + colorspace.h + coltest.cpp + coltest.h + coltype.h + composite.cpp + composite.h + #dazzle.cpp + #dazzle.h + #ddsfile.cpp + #ddsfile.h + #decalmsh.cpp + #decalmsh.h + decalsys.cpp + decalsys.h + distlod.cpp + distlod.h + dllist.h + #dx8caps.cpp + #dx8caps.h + #dx8fvf.cpp + #dx8fvf.h + #dx8indexbuffer.cpp + #dx8indexbuffer.h + dx8list.h + dx8polygonrenderer.cpp + dx8polygonrenderer.h + #dx8renderer.cpp + #dx8renderer.h + #dx8rendererdebugger.cpp + #dx8rendererdebugger.h + #dx8texman.cpp + #dx8texman.h + #dx8vertexbuffer.cpp + #dx8vertexbuffer.h + dx8webbrowser.cpp + dx8webbrowser.h + #dx8wrapper.cpp + #dx8wrapper.h + dynamesh.cpp + dynamesh.h + font3d.cpp + font3d.h + formconv.cpp + formconv.h + FramGrab.cpp + framgrab.h + hanim.cpp + hanim.h + #hanimmgr.cpp + #hanimmgr.h + hcanim.cpp + hcanim.h + #hlod.cpp + #hlod.h + hmdldef.cpp + hmdldef.H + #hmorphanim.cpp + #hmorphanim.h + #hrawanim.cpp + #hrawanim.h + htree.cpp + htree.h + #htreemgr.cpp + #htreemgr.h + intersec.cpp + intersec.h + intersec.inl + inttest.h + layer.cpp + layer.h + #light.cpp + #light.h + #lightenvironment.cpp + #lightenvironment.h + line3d.cpp + line3d.h + #linegrp.cpp + #linegrp.h + #mapper.cpp + #mapper.h + matinfo.cpp + matinfo.h + #matpass.cpp + #matpass.h + #matrixmapper.cpp + #matrixmapper.h + #mesh.cpp + #mesh.h + #meshbuild.cpp + #meshbuild.h + meshdam.cpp + meshdam.h + #meshgeometry.cpp + #meshgeometry.h + #meshmatdesc.cpp + #meshmatdesc.h + #meshmdl.cpp + #meshmdl.h + #meshmdlio.cpp + metalmap.cpp + metalmap.h + missingtexture.cpp + missingtexture.h + #motchan.cpp + #motchan.h + #nullrobj.cpp + #nullrobj.h + #part_buf.cpp + #part_buf.h + #part_emt.cpp + #part_emt.h + #part_ldr.cpp + #part_ldr.h + pivot.cpp + pivot.h + pointgr.cpp + pointgr.h + polyinfo.cpp + polyinfo.h + predlod.cpp + predlod.h + prim_anim.cpp + prim_anim.h + projector.cpp + projector.h + proto.cpp + proto.h + proxy.h + rddesc.h + #render2d.cpp + #render2d.h + render2dsentence.cpp + render2dsentence.h + renderobjectrecycler.cpp + renderobjectrecycler.h + rendobj.cpp + rendobj.h + #rinfo.cpp + #rinfo.h + ringobj.cpp + ringobj.h + robjlist.h + #scene.cpp + #scene.h + segline.cpp + segline.h + seglinerenderer.cpp + seglinerenderer.h + #shader.cpp + #shader.h + shattersystem.cpp + shattersystem.h + #shdlib.h + snappts.cpp + snapPts.h + #sortingrenderer.cpp + #sortingrenderer.h + soundlibrarybridge.h + soundrobj.cpp + soundrobj.h + sphereobj.cpp + sphereobj.h + static_sort_list.cpp + static_sort_list.h + statistics.cpp + statistics.h + streak.cpp + streak.h + streakRender.cpp + streakRender.h + stripoptimizer.cpp + stripoptimizer.h + surfaceclass.cpp + surfaceclass.h + #texproject.cpp + #texproject.h + #textdraw.cpp # unused + textdraw.h + #texture.cpp + #texture.h + #texturefilter.cpp + #texturefilter.h + #textureloader.cpp + #textureloader.h + #texturethumbnail.cpp + #texturethumbnail.h + #vertmaterial.cpp + #vertmaterial.h + visrasterizer.cpp + visrasterizer.h + w3d_dep.cpp + w3d_dep.h + #w3d_file.h + w3d_obsolete.h + w3d_util.cpp + w3d_util.h + w3derr.h + w3dexclusionlist.cpp + w3dexclusionlist.h + #ww3d.cpp + #ww3d.h + ww3dformat.cpp + ww3dformat.h + ww3dids.h + ww3dtrig.h +) + +add_library(corei_ww3d2 INTERFACE) + +target_sources(corei_ww3d2 INTERFACE ${WW3D2_SRC}) + +if (NOT IS_VS6_BUILD) + target_link_libraries(corei_ww3d2 INTERFACE + comsuppw + ) +endif() + +target_link_libraries(corei_ww3d2 INTERFACE + core_browserengine +) diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt b/Core/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt rename to Core/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt b/Core/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt rename to Core/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt b/Core/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt rename to Core/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp b/Core/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT b/Core/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT rename to Core/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt b/Core/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt rename to Core/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga b/Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga rename to Core/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/State Management.txt b/Core/Libraries/Source/WWVegas/WW3D2/State Management.txt similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/State Management.txt rename to Core/Libraries/Source/WWVegas/WW3D2/State Management.txt diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/aabtree.cpp b/Core/Libraries/Source/WWVegas/WW3D2/aabtree.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/aabtree.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/aabtree.cpp index 2a573fa253..ed2c28c919 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/aabtree.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/aabtree.cpp @@ -728,7 +728,7 @@ bool AABTreeClass::Intersect_OBBox_Recursive(AABTreeClass::CullNodeStruct * node return res; } -#ifdef _DEBUG +#ifdef RTS_DEBUG #pragma optimize("", off) // We get an odd error when using optimized in the debug. // All optimized seems to work. jba. #endif @@ -791,7 +791,7 @@ bool AABTreeClass::Cast_Ray_To_Polys(CullNodeStruct * node,RayCollisionTestClass } return false; } -#ifdef _DEBUG +#ifdef RTS_DEBUG #pragma optimize("", on) #endif diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/aabtree.h b/Core/Libraries/Source/WWVegas/WW3D2/aabtree.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/aabtree.h rename to Core/Libraries/Source/WWVegas/WW3D2/aabtree.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp b/Core/Libraries/Source/WWVegas/WW3D2/agg_def.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/agg_def.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h b/Core/Libraries/Source/WWVegas/WW3D2/agg_def.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h rename to Core/Libraries/Source/WWVegas/WW3D2/agg_def.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp b/Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.h b/Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.h rename to Core/Libraries/Source/WWVegas/WW3D2/animatedsoundmgr.h diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp b/Core/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.h b/Core/Libraries/Source/WWVegas/WW3D2/assetstatus.h similarity index 100% rename from Generals/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.h rename to Core/Libraries/Source/WWVegas/WW3D2/assetstatus.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp b/Core/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.h b/Core/Libraries/Source/WWVegas/WW3D2/bitmaphandler.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.h rename to Core/Libraries/Source/WWVegas/WW3D2/bitmaphandler.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bwrender.cpp b/Core/Libraries/Source/WWVegas/WW3D2/bwrender.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bwrender.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/bwrender.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bwrender.h b/Core/Libraries/Source/WWVegas/WW3D2/bwrender.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/bwrender.h rename to Core/Libraries/Source/WWVegas/WW3D2/bwrender.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/classid.h b/Core/Libraries/Source/WWVegas/WW3D2/classid.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/classid.h rename to Core/Libraries/Source/WWVegas/WW3D2/classid.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/collect.cpp b/Core/Libraries/Source/WWVegas/WW3D2/collect.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/collect.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/collect.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/collect.h b/Core/Libraries/Source/WWVegas/WW3D2/collect.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/collect.h rename to Core/Libraries/Source/WWVegas/WW3D2/collect.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/colorspace.h b/Core/Libraries/Source/WWVegas/WW3D2/colorspace.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/colorspace.h rename to Core/Libraries/Source/WWVegas/WW3D2/colorspace.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/coltest.cpp b/Core/Libraries/Source/WWVegas/WW3D2/coltest.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/coltest.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/coltest.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/coltest.h b/Core/Libraries/Source/WWVegas/WW3D2/coltest.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/coltest.h rename to Core/Libraries/Source/WWVegas/WW3D2/coltest.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/coltype.h b/Core/Libraries/Source/WWVegas/WW3D2/coltype.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/coltype.h rename to Core/Libraries/Source/WWVegas/WW3D2/coltype.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/composite.cpp b/Core/Libraries/Source/WWVegas/WW3D2/composite.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/composite.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/composite.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/composite.h b/Core/Libraries/Source/WWVegas/WW3D2/composite.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/composite.h rename to Core/Libraries/Source/WWVegas/WW3D2/composite.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/decalsys.cpp b/Core/Libraries/Source/WWVegas/WW3D2/decalsys.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/decalsys.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/decalsys.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/decalsys.h b/Core/Libraries/Source/WWVegas/WW3D2/decalsys.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/decalsys.h rename to Core/Libraries/Source/WWVegas/WW3D2/decalsys.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/distlod.cpp b/Core/Libraries/Source/WWVegas/WW3D2/distlod.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/distlod.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/distlod.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/distlod.h b/Core/Libraries/Source/WWVegas/WW3D2/distlod.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/distlod.h rename to Core/Libraries/Source/WWVegas/WW3D2/distlod.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dllist.h b/Core/Libraries/Source/WWVegas/WW3D2/dllist.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dllist.h rename to Core/Libraries/Source/WWVegas/WW3D2/dllist.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8list.h b/Core/Libraries/Source/WWVegas/WW3D2/dx8list.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8list.h rename to Core/Libraries/Source/WWVegas/WW3D2/dx8list.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp b/Core/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h b/Core/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h rename to Core/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp b/Core/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h b/Core/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h rename to Core/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.cpp b/Core/Libraries/Source/WWVegas/WW3D2/dynamesh.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/dynamesh.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.h b/Core/Libraries/Source/WWVegas/WW3D2/dynamesh.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.h rename to Core/Libraries/Source/WWVegas/WW3D2/dynamesh.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/font3d.cpp b/Core/Libraries/Source/WWVegas/WW3D2/font3d.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/font3d.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/font3d.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/font3d.h b/Core/Libraries/Source/WWVegas/WW3D2/font3d.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/font3d.h rename to Core/Libraries/Source/WWVegas/WW3D2/font3d.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/formconv.cpp b/Core/Libraries/Source/WWVegas/WW3D2/formconv.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/formconv.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/formconv.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/formconv.h b/Core/Libraries/Source/WWVegas/WW3D2/formconv.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/formconv.h rename to Core/Libraries/Source/WWVegas/WW3D2/formconv.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/framgrab.h b/Core/Libraries/Source/WWVegas/WW3D2/framgrab.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/framgrab.h rename to Core/Libraries/Source/WWVegas/WW3D2/framgrab.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.cpp b/Core/Libraries/Source/WWVegas/WW3D2/hanim.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/hanim.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.h b/Core/Libraries/Source/WWVegas/WW3D2/hanim.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hanim.h rename to Core/Libraries/Source/WWVegas/WW3D2/hanim.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp b/Core/Libraries/Source/WWVegas/WW3D2/hcanim.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/hcanim.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.h b/Core/Libraries/Source/WWVegas/WW3D2/hcanim.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hcanim.h rename to Core/Libraries/Source/WWVegas/WW3D2/hcanim.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.H b/Core/Libraries/Source/WWVegas/WW3D2/hmdldef.H similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.H rename to Core/Libraries/Source/WWVegas/WW3D2/hmdldef.H diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp b/Core/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp b/Core/Libraries/Source/WWVegas/WW3D2/htree.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/htree.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.h b/Core/Libraries/Source/WWVegas/WW3D2/htree.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.h rename to Core/Libraries/Source/WWVegas/WW3D2/htree.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.cpp b/Core/Libraries/Source/WWVegas/WW3D2/intersec.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/intersec.cpp index d4179d61e7..2ad2ba3de8 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/intersec.cpp @@ -40,6 +40,7 @@ #include "camera.h" #include "scene.h" #include "intersec.inl" +#include "Utility/CppMacros.h" ////////////////////////////////////////////////////////////////////// @@ -190,7 +191,7 @@ bool IntersectionClass::Intersect_Box(Vector3 &Box_Min, Vector3 &Box_Max, Inters float distance[PLANE_COUNT]; float candidate_plane[PLANE_COUNT]; - register Vector3 *intersection = &FinalResult->Intersection; + REGISTER Vector3 *intersection = &FinalResult->Intersection; // Find candidate planes and determine if the ray is outside the box for (counter = 0; counter < PLANE_COUNT; counter++) { diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.h b/Core/Libraries/Source/WWVegas/WW3D2/intersec.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.h rename to Core/Libraries/Source/WWVegas/WW3D2/intersec.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.inl b/Core/Libraries/Source/WWVegas/WW3D2/intersec.inl similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/intersec.inl rename to Core/Libraries/Source/WWVegas/WW3D2/intersec.inl diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/inttest.h b/Core/Libraries/Source/WWVegas/WW3D2/inttest.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/inttest.h rename to Core/Libraries/Source/WWVegas/WW3D2/inttest.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/layer.cpp b/Core/Libraries/Source/WWVegas/WW3D2/layer.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/layer.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/layer.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/layer.h b/Core/Libraries/Source/WWVegas/WW3D2/layer.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/layer.h rename to Core/Libraries/Source/WWVegas/WW3D2/layer.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/line3d.cpp b/Core/Libraries/Source/WWVegas/WW3D2/line3d.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/line3d.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/line3d.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/line3d.h b/Core/Libraries/Source/WWVegas/WW3D2/line3d.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/line3d.h rename to Core/Libraries/Source/WWVegas/WW3D2/line3d.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matinfo.cpp b/Core/Libraries/Source/WWVegas/WW3D2/matinfo.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matinfo.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/matinfo.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matinfo.h b/Core/Libraries/Source/WWVegas/WW3D2/matinfo.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/matinfo.h rename to Core/Libraries/Source/WWVegas/WW3D2/matinfo.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshdam.cpp b/Core/Libraries/Source/WWVegas/WW3D2/meshdam.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshdam.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/meshdam.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshdam.h b/Core/Libraries/Source/WWVegas/WW3D2/meshdam.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshdam.h rename to Core/Libraries/Source/WWVegas/WW3D2/meshdam.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/metalmap.cpp b/Core/Libraries/Source/WWVegas/WW3D2/metalmap.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/metalmap.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/metalmap.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/metalmap.h b/Core/Libraries/Source/WWVegas/WW3D2/metalmap.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/metalmap.h rename to Core/Libraries/Source/WWVegas/WW3D2/metalmap.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp b/Core/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.h b/Core/Libraries/Source/WWVegas/WW3D2/missingtexture.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.h rename to Core/Libraries/Source/WWVegas/WW3D2/missingtexture.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pivot.cpp b/Core/Libraries/Source/WWVegas/WW3D2/pivot.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pivot.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/pivot.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pivot.h b/Core/Libraries/Source/WWVegas/WW3D2/pivot.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pivot.h rename to Core/Libraries/Source/WWVegas/WW3D2/pivot.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp b/Core/Libraries/Source/WWVegas/WW3D2/pointgr.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/pointgr.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h b/Core/Libraries/Source/WWVegas/WW3D2/pointgr.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h rename to Core/Libraries/Source/WWVegas/WW3D2/pointgr.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp b/Core/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.h b/Core/Libraries/Source/WWVegas/WW3D2/polyinfo.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.h rename to Core/Libraries/Source/WWVegas/WW3D2/polyinfo.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/predlod.cpp b/Core/Libraries/Source/WWVegas/WW3D2/predlod.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/predlod.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/predlod.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/predlod.h b/Core/Libraries/Source/WWVegas/WW3D2/predlod.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/predlod.h rename to Core/Libraries/Source/WWVegas/WW3D2/predlod.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp b/Core/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.h b/Core/Libraries/Source/WWVegas/WW3D2/prim_anim.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.h rename to Core/Libraries/Source/WWVegas/WW3D2/prim_anim.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/projector.cpp b/Core/Libraries/Source/WWVegas/WW3D2/projector.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/projector.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/projector.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/projector.h b/Core/Libraries/Source/WWVegas/WW3D2/projector.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/projector.h rename to Core/Libraries/Source/WWVegas/WW3D2/projector.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.cpp b/Core/Libraries/Source/WWVegas/WW3D2/proto.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/proto.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.h b/Core/Libraries/Source/WWVegas/WW3D2/proto.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proto.h rename to Core/Libraries/Source/WWVegas/WW3D2/proto.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proxy.h b/Core/Libraries/Source/WWVegas/WW3D2/proxy.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/proxy.h rename to Core/Libraries/Source/WWVegas/WW3D2/proxy.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rddesc.h b/Core/Libraries/Source/WWVegas/WW3D2/rddesc.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rddesc.h rename to Core/Libraries/Source/WWVegas/WW3D2/rddesc.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp b/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp index ffd1d1bf4f..97b6ac508a 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp @@ -41,7 +41,7 @@ #include "wwmemlog.h" #include "dx8wrapper.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h b/Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h rename to Core/Libraries/Source/WWVegas/WW3D2/render2dsentence.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp b/Core/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h b/Core/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h rename to Core/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rendobj.cpp b/Core/Libraries/Source/WWVegas/WW3D2/rendobj.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rendobj.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/rendobj.cpp index df22689ef6..8e42e9f998 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rendobj.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/rendobj.cpp @@ -93,7 +93,7 @@ #include "intersec.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rendobj.h b/Core/Libraries/Source/WWVegas/WW3D2/rendobj.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/rendobj.h rename to Core/Libraries/Source/WWVegas/WW3D2/rendobj.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ringobj.cpp b/Core/Libraries/Source/WWVegas/WW3D2/ringobj.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ringobj.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/ringobj.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ringobj.h b/Core/Libraries/Source/WWVegas/WW3D2/ringobj.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ringobj.h rename to Core/Libraries/Source/WWVegas/WW3D2/ringobj.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/robjlist.h b/Core/Libraries/Source/WWVegas/WW3D2/robjlist.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/robjlist.h rename to Core/Libraries/Source/WWVegas/WW3D2/robjlist.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/segline.cpp b/Core/Libraries/Source/WWVegas/WW3D2/segline.cpp similarity index 98% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/segline.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/segline.cpp index 2701d7a88d..86db431585 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/segline.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/segline.cpp @@ -202,6 +202,11 @@ Vector2 SegmentedLineClass::Get_UV_Offset_Rate(void) return LineRenderer.Get_UV_Offset_Rate(); } +Vector2 SegmentedLineClass::Get_Current_UV_Offset(void) +{ + return LineRenderer.Get_Current_UV_Offset(); +} + int SegmentedLineClass::Is_Merge_Intersections(void) { return LineRenderer.Is_Merge_Intersections(); @@ -290,6 +295,16 @@ void SegmentedLineClass::Set_UV_Offset_Rate(const Vector2 &rate) LineRenderer.Set_UV_Offset_Rate(rate); } +void SegmentedLineClass::Set_U_Scale(float scale) +{ + LineRenderer.Set_U_Scale(scale); +} + +void SegmentedLineClass::Set_Current_UV_Offset(const Vector2& offset) +{ + LineRenderer.Set_Current_UV_Offset(offset); +} + void SegmentedLineClass::Set_Merge_Intersections(int onoff) { LineRenderer.Set_Merge_Intersections(onoff); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/segline.h b/Core/Libraries/Source/WWVegas/WW3D2/segline.h similarity index 98% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/segline.h rename to Core/Libraries/Source/WWVegas/WW3D2/segline.h index 7ca6be2e8d..bca471d192 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/segline.h +++ b/Core/Libraries/Source/WWVegas/WW3D2/segline.h @@ -96,6 +96,7 @@ class SegmentedLineClass : public RenderObjClass SegLineRendererClass::TextureMapMode Get_Texture_Mapping_Mode(void); float Get_Texture_Tile_Factor(void); Vector2 Get_UV_Offset_Rate(void); + Vector2 Get_Current_UV_Offset(void); int Is_Merge_Intersections(void); int Is_Freeze_Random(void); int Is_Sorting_Disabled(void); @@ -114,6 +115,8 @@ class SegmentedLineClass : public RenderObjClass //performance impact will result! void Set_Texture_Tile_Factor(float factor); void Set_UV_Offset_Rate(const Vector2 &rate); + void Set_U_Scale(float scale); + void Set_Current_UV_Offset(const Vector2& offset); void Set_Merge_Intersections(int onoff); void Set_Freeze_Random(int onoff); void Set_Disable_Sorting(int onoff); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp b/Core/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp similarity index 98% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp index 4c37e4d6ba..fe0e2410d4 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp @@ -60,7 +60,7 @@ #define SEGLINE_CHUNK_SIZE (128) #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -85,6 +85,7 @@ SegLineRendererClass::SegLineRendererClass(void) : TextureTileFactor(1.0f), LastUsedSyncTime(WW3D::Get_Sync_Time()), CurrentUVOffset(0.0f,0.0f), + UScale(1.0f), UVOffsetDeltaPerMS(0.0f, 0.0f), Bits(DEFAULT_BITS), m_vertexBufferSize(0), @@ -105,6 +106,7 @@ SegLineRendererClass::SegLineRendererClass(const SegLineRendererClass & that) : TextureTileFactor(1.0f), LastUsedSyncTime(that.LastUsedSyncTime), CurrentUVOffset(0.0f,0.0f), + UScale(1.0f), UVOffsetDeltaPerMS(0.0f, 0.0f), Bits(DEFAULT_BITS), m_vertexBufferSize(0), @@ -127,6 +129,7 @@ SegLineRendererClass & SegLineRendererClass::operator = (const SegLineRendererCl TextureTileFactor = that.TextureTileFactor; LastUsedSyncTime = that.LastUsedSyncTime; CurrentUVOffset = that.CurrentUVOffset; + UScale = that.UScale; UVOffsetDeltaPerMS = that.UVOffsetDeltaPerMS; Bits = that.Bits; // Don't modify m_vertexBufferSize and m_vertexBuffer @@ -189,6 +192,11 @@ void SegLineRendererClass::Set_Current_UV_Offset(const Vector2 & offset) CurrentUVOffset = offset; } +void SegLineRendererClass::Set_U_Scale(float scale) +{ + UScale = scale; +} + void SegLineRendererClass::Set_Texture_Tile_Factor(float factor) { // Care should be taken to avoid tiling a texture too many times over a single polygon; @@ -196,7 +204,7 @@ void SegLineRendererClass::Set_Texture_Tile_Factor(float factor) ///@todo: I raised this number and didn't see much difference on our min-spec. -MW const static float MAX_LINE_TILING_FACTOR = 50.0f; if (factor > MAX_LINE_TILING_FACTOR) { - WWDEBUG_SAY(("Texture (%s) Tile Factor (%.2f) too large in SegLineRendererClass!\r\n", Get_Texture()->Get_Texture_Name(), TextureTileFactor)); + // WWDEBUG_SAY(("Texture (%s) Tile Factor (%.2f) too large in SegLineRendererClass!\r\n", Get_Texture()->Get_Texture_Name(), TextureTileFactor)); factor = MAX_LINE_TILING_FACTOR; } else { factor = MAX(factor, 0.0f); @@ -327,6 +335,15 @@ void SegLineRendererClass::Render u_values[0] = 0.0f; u_values[1] = 1.0f; break; + //For animated laser texture + case GRID_TILED_TEXTURE_MAP: + for (pidx = 0; pidx < point_cnt; pidx++) { + // Increasing V + base_tex_v[pidx] = (float)(pidx + chidx) * TextureTileFactor; + } + u_values[0] = 0.0f; + u_values[1] = UScale; + break; } diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h b/Core/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h similarity index 96% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h rename to Core/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h index 2967a74e24..75f92551d4 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h +++ b/Core/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h @@ -74,7 +74,8 @@ class SegLineRendererClass enum TextureMapMode { UNIFORM_WIDTH_TEXTURE_MAP = 0x00000000, // Entire line uses one row of texture (constant V) UNIFORM_LENGTH_TEXTURE_MAP = 0x00000001, // Entire line uses one row of texture stretched length-wise - TILED_TEXTURE_MAP = 0x00000002 // Tiled continuously over line + TILED_TEXTURE_MAP = 0x00000002, // Tiled continuously over line + GRID_TILED_TEXTURE_MAP = 0x00000004 // Like TILED, but with dynamic U coordinates }; void Init(const W3dEmitterLinePropertiesStruct & props); @@ -92,6 +93,7 @@ class SegLineRendererClass TextureMapMode Get_Texture_Mapping_Mode(void) const; float Get_Texture_Tile_Factor(void) const { return TextureTileFactor; } Vector2 Get_UV_Offset_Rate(void) const; + Vector2 Get_Current_UV_Offset(void) const { return CurrentUVOffset; } int Is_Merge_Intersections(void) const { return Bits & MERGE_INTERSECTIONS; } int Is_Freeze_Random(void) const { return Bits & FREEZE_RANDOM; } int Is_Sorting_Disabled(void) const { return Bits & DISABLE_SORTING; } @@ -109,6 +111,7 @@ class SegLineRendererClass void Set_Texture_Mapping_Mode(TextureMapMode mode); void Set_Texture_Tile_Factor(float factor); // Might be clamped if too high void Set_Current_UV_Offset(const Vector2 & offset); + void Set_U_Scale(float scale); void Set_UV_Offset_Rate(const Vector2 &rate); void Set_Merge_Intersections(int onoff) { if (onoff) { Bits |= MERGE_INTERSECTIONS; } else { Bits &= ~MERGE_INTERSECTIONS; }; } void Set_Freeze_Random(int onoff) { if (onoff) { Bits |= FREEZE_RANDOM; } else { Bits &= ~FREEZE_RANDOM; }; } @@ -159,6 +162,7 @@ class SegLineRendererClass unsigned int LastUsedSyncTime; // Last sync time used Vector2 CurrentUVOffset; // Current UV offset Vector2 UVOffsetDeltaPerMS; // Amount to increase offset each millisec + float UScale; //U coordinate scale for grid animation // Various flags enum BitShiftOffsets { diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp b/Core/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.h b/Core/Libraries/Source/WWVegas/WW3D2/shattersystem.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.h rename to Core/Libraries/Source/WWVegas/WW3D2/shattersystem.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/snapPts.h b/Core/Libraries/Source/WWVegas/WW3D2/snapPts.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/snapPts.h rename to Core/Libraries/Source/WWVegas/WW3D2/snapPts.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/snappts.cpp b/Core/Libraries/Source/WWVegas/WW3D2/snappts.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/snappts.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/snappts.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/soundlibrarybridge.h b/Core/Libraries/Source/WWVegas/WW3D2/soundlibrarybridge.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/soundlibrarybridge.h rename to Core/Libraries/Source/WWVegas/WW3D2/soundlibrarybridge.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp b/Core/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.h b/Core/Libraries/Source/WWVegas/WW3D2/soundrobj.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.h rename to Core/Libraries/Source/WWVegas/WW3D2/soundrobj.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp b/Core/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.h b/Core/Libraries/Source/WWVegas/WW3D2/sphereobj.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.h rename to Core/Libraries/Source/WWVegas/WW3D2/sphereobj.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp b/Core/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.h b/Core/Libraries/Source/WWVegas/WW3D2/static_sort_list.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.h rename to Core/Libraries/Source/WWVegas/WW3D2/static_sort_list.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/statistics.cpp b/Core/Libraries/Source/WWVegas/WW3D2/statistics.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/statistics.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/statistics.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/statistics.h b/Core/Libraries/Source/WWVegas/WW3D2/statistics.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/statistics.h rename to Core/Libraries/Source/WWVegas/WW3D2/statistics.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streak.cpp b/Core/Libraries/Source/WWVegas/WW3D2/streak.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streak.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/streak.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streak.h b/Core/Libraries/Source/WWVegas/WW3D2/streak.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streak.h rename to Core/Libraries/Source/WWVegas/WW3D2/streak.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streakRender.cpp b/Core/Libraries/Source/WWVegas/WW3D2/streakRender.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streakRender.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/streakRender.cpp index 888e1cd08a..6ae932191d 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streakRender.cpp +++ b/Core/Libraries/Source/WWVegas/WW3D2/streakRender.cpp @@ -35,7 +35,7 @@ #include "RANDOM.H" #include "v3_rnd.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... // #pragma optimize("", off) // #pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1414,7 +1414,7 @@ VertexFormatXYZUV1 *StreakRendererClass::getVertexBuffer(unsigned int number) m_vertexBufferSize = numberToAlloc; } -#ifdef _INTERNAL +#ifdef RTS_INTERNAL for (unsigned i = 0; i < number; ++i) { m_vertexBuffer[i].x = m_vertexBuffer[i].y = m_vertexBuffer[i].z = m_vertexBuffer[i].u1 = m_vertexBuffer[i].v1 = (float)0xdeadbeef; diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streakRender.h b/Core/Libraries/Source/WWVegas/WW3D2/streakRender.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/streakRender.h rename to Core/Libraries/Source/WWVegas/WW3D2/streakRender.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp b/Core/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h b/Core/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h rename to Core/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp b/Core/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.h b/Core/Libraries/Source/WWVegas/WW3D2/surfaceclass.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.h rename to Core/Libraries/Source/WWVegas/WW3D2/surfaceclass.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textdraw.cpp b/Core/Libraries/Source/WWVegas/WW3D2/textdraw.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textdraw.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/textdraw.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textdraw.h b/Core/Libraries/Source/WWVegas/WW3D2/textdraw.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/textdraw.h rename to Core/Libraries/Source/WWVegas/WW3D2/textdraw.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp b/Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.h b/Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.h rename to Core/Libraries/Source/WWVegas/WW3D2/visrasterizer.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp b/Core/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.h b/Core/Libraries/Source/WWVegas/WW3D2/w3d_dep.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.h rename to Core/Libraries/Source/WWVegas/WW3D2/w3d_dep.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h b/Core/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h rename to Core/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp b/Core/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.h b/Core/Libraries/Source/WWVegas/WW3D2/w3d_util.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.h rename to Core/Libraries/Source/WWVegas/WW3D2/w3d_util.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3derr.h b/Core/Libraries/Source/WWVegas/WW3D2/w3derr.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3derr.h rename to Core/Libraries/Source/WWVegas/WW3D2/w3derr.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp b/Core/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h b/Core/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h rename to Core/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp b/Core/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp rename to Core/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.h b/Core/Libraries/Source/WWVegas/WW3D2/ww3dformat.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.h rename to Core/Libraries/Source/WWVegas/WW3D2/ww3dformat.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dids.h b/Core/Libraries/Source/WWVegas/WW3D2/ww3dids.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dids.h rename to Core/Libraries/Source/WWVegas/WW3D2/ww3dids.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h b/Core/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h rename to Core/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h b/Core/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h rename to Core/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp b/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp index 2427481c12..4230983f66 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp @@ -37,7 +37,6 @@ #include "AudibleSound.h" #include "WWAudio.h" -#include "ww3d.h" #include "wwdebug.h" #include "SoundBuffer.h" #include "Utils.h" diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.h b/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.h rename to Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.h index 10eeca4360..3ccad11658 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/AudibleSound.h @@ -153,7 +153,7 @@ class AudibleSoundClass : public SoundSceneObjClass ////////////////////////////////////////////////////////////////////// // Update methods ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); + virtual bool On_Frame_Update (unsigned int milliseconds); ////////////////////////////////////////////////////////////////////// // State control methods diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudioEvents.h b/Core/Libraries/Source/WWVegas/WWAudio/AudioEvents.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudioEvents.h rename to Core/Libraries/Source/WWVegas/WWAudio/AudioEvents.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp b/Core/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h b/Core/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h rename to Core/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h diff --git a/Core/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt new file mode 100644 index 0000000000..aed359390f --- /dev/null +++ b/Core/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt @@ -0,0 +1,57 @@ +set(WWAUDIO_SRC + AABTreeSoundCullClass.h + AudibleSound.cpp + AudibleSound.h + AudioEvents.h + AudioSaveLoad.cpp + AudioSaveLoad.h + FilteredSound.cpp + FilteredSound.h + Listener.cpp + Listener.h + listenerhandle.cpp + listenerhandle.h + LogicalListener.cpp + LogicalListener.h + LogicalSound.cpp + LogicalSound.h + PriorityVector.h + sound2dhandle.cpp + sound2dhandle.h + Sound3D.cpp + Sound3D.h + sound3dhandle.cpp + sound3dhandle.h + SoundBuffer.cpp + SoundBuffer.h + SoundChunkIDs.h + SoundCullObj.h + soundhandle.cpp + soundhandle.h + SoundPseudo3D.cpp + SoundPseudo3D.h + SoundScene.cpp + SoundScene.h + SoundSceneObj.cpp + SoundSceneObj.h + soundstreamhandle.cpp + soundstreamhandle.h + Threads.cpp + Threads.h + Utils.cpp + Utils.h + WWAudio.cpp + WWAudio.h +) + +# @todo Promote this to STATIC library when WW3D2 is a STATIC library as well + +add_library(corei_wwaudio INTERFACE) + +target_sources(corei_wwaudio INTERFACE ${WWAUDIO_SRC}) + +target_include_directories(corei_wwaudio INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) + +target_link_libraries(corei_wwaudio INTERFACE + core_wwcommon +) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp b/Core/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.h b/Core/Libraries/Source/WWVegas/WWAudio/FilteredSound.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.h rename to Core/Libraries/Source/WWVegas/WWAudio/FilteredSound.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Listener.cpp b/Core/Libraries/Source/WWVegas/WWAudio/Listener.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Listener.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/Listener.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Listener.h b/Core/Libraries/Source/WWVegas/WWAudio/Listener.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Listener.h rename to Core/Libraries/Source/WWVegas/WWAudio/Listener.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp b/Core/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.h b/Core/Libraries/Source/WWVegas/WWAudio/LogicalListener.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.h rename to Core/Libraries/Source/WWVegas/WWAudio/LogicalListener.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp b/Core/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.h b/Core/Libraries/Source/WWVegas/WWAudio/LogicalSound.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.h rename to Core/Libraries/Source/WWVegas/WWAudio/LogicalSound.h index 697dd727f9..6341cff5f8 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/LogicalSound.h @@ -87,7 +87,7 @@ class LogicalSoundClass : public SoundSceneObjClass ////////////////////////////////////////////////////////////////////// // Update methods ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); + virtual bool On_Frame_Update (unsigned int milliseconds); ////////////////////////////////////////////////////////////////////// // Position/direction methods diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/PriorityVector.h b/Core/Libraries/Source/WWVegas/WWAudio/PriorityVector.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/PriorityVector.h rename to Core/Libraries/Source/WWVegas/WWAudio/PriorityVector.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp b/Core/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp index 38d895f503..cc5a9aeeb1 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp @@ -220,7 +220,7 @@ Sound3DClass::On_Frame_Update (unsigned int milliseconds) m_PrevTransform = m_Transform; // Allow the base class to process this call - return AudibleSoundClass::On_Frame_Update (); + return AudibleSoundClass::On_Frame_Update (milliseconds); } diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.h b/Core/Libraries/Source/WWVegas/WWAudio/Sound3D.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.h rename to Core/Libraries/Source/WWVegas/WWAudio/Sound3D.h index 1e112d209a..492de6ad9a 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/Sound3D.h @@ -172,7 +172,7 @@ class Sound3DClass : public AudibleSoundClass ////////////////////////////////////////////////////////////////////// // Update methods ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); + virtual bool On_Frame_Update (unsigned int milliseconds); ////////////////////////////////////////////////////////////////////// // Handle information diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp b/Core/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h b/Core/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h rename to Core/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h b/Core/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h rename to Core/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h b/Core/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h rename to Core/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp b/Core/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp index 708b9e0802..780cb36b4c 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp @@ -278,7 +278,7 @@ SoundPseudo3DClass::On_Frame_Update (unsigned int milliseconds) } // Allow the base Sound3DClass to process this call - return Sound3DClass::On_Frame_Update (); + return Sound3DClass::On_Frame_Update (milliseconds); } diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h b/Core/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h rename to Core/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h index eb860e1373..35734a0418 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h @@ -140,7 +140,7 @@ class SoundPseudo3DClass : public Sound3DClass ////////////////////////////////////////////////////////////////////// // Update methods ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); + virtual bool On_Frame_Update (unsigned int milliseconds); ////////////////////////////////////////////////////////////////////// // Handle information diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp b/Core/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp index 32f602078f..53fcffa836 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp @@ -136,7 +136,7 @@ SoundSceneClass::Re_Partition // //////////////////////////////////////////////////////////////////////////////////////////////// void -SoundSceneClass::Collect_Logical_Sounds (int listener_count) +SoundSceneClass::Collect_Logical_Sounds (unsigned int milliseconds, int listener_count) { WWPROFILE ("Collect_Logical_Sounds"); @@ -164,7 +164,7 @@ SoundSceneClass::Collect_Logical_Sounds (int listener_count) { LogicalListenerClass::Set_Oldest_Timestamp (listener->Get_Timestamp ()); listener->Set_Timestamp (LogicalListenerClass::Get_New_Timestamp ()); - listener->On_Frame_Update (); + listener->On_Frame_Update (milliseconds); // // Collect a list of the sounds this listener can hear. diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.h b/Core/Libraries/Source/WWVegas/WWAudio/SoundScene.h similarity index 98% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.h rename to Core/Libraries/Source/WWVegas/WWAudio/SoundScene.h index 03a7bb9612..35d14ee256 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/SoundScene.h @@ -101,7 +101,7 @@ class SoundSceneClass ////////////////////////////////////////////////////////////////////// // Logical sound methods ////////////////////////////////////////////////////////////////////// - virtual void Collect_Logical_Sounds (int listener_count = -1); + virtual void Collect_Logical_Sounds (unsigned int milliseconds, int listener_count = -1); ////////////////////////////////////////////////////////////////////// // Listener methods @@ -166,7 +166,7 @@ class SoundSceneClass ////////////////////////////////////////////////////////////////////// // Protected methods ////////////////////////////////////////////////////////////////////// - virtual void On_Frame_Update (unsigned int milliseconds = 0); + virtual void On_Frame_Update (unsigned int milliseconds); virtual void Initialize (void); virtual bool Is_Logical_Sound_In_Scene (LogicalSoundClass *sound_obj, bool single_shot = false); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp b/Core/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h b/Core/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h rename to Core/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h index c3eefa77e8..3086d0b047 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h @@ -123,7 +123,7 @@ class SoundSceneObjClass : public MultiListObjectClass, public PersistClass, pub ////////////////////////////////////////////////////////////////////// // Update methods ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); + virtual bool On_Frame_Update (unsigned int milliseconds); ////////////////////////////////////////////////////////////////////// // Event handling diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Threads.cpp b/Core/Libraries/Source/WWVegas/WWAudio/Threads.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Threads.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/Threads.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Threads.h b/Core/Libraries/Source/WWVegas/WWAudio/Threads.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Threads.h rename to Core/Libraries/Source/WWVegas/WWAudio/Threads.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Utils.cpp b/Core/Libraries/Source/WWVegas/WWAudio/Utils.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Utils.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/Utils.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Utils.h b/Core/Libraries/Source/WWVegas/WWAudio/Utils.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/Utils.h rename to Core/Libraries/Source/WWVegas/WWAudio/Utils.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp b/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp index 117441acff..2a523ef0f4 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp +++ b/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp @@ -45,7 +45,6 @@ #include "AudibleSound.h" #include "Sound3D.h" #include "RAWFILE.H" -#include "ww3d.h" #include "SoundScene.h" #include "SoundPseudo3D.h" #include "ffactory.h" @@ -1323,17 +1322,9 @@ WWAudioClass::On_Frame_Update (unsigned int milliseconds) // Free_Completed_Sounds (); - // - // Calculate the time in ms since the last frame - // - unsigned int time_delta = milliseconds; - if (time_delta == 0) { - time_delta = WW3D::Get_Frame_Time (); - } - if (m_SoundScene != NULL) { m_SoundScene->On_Frame_Update (milliseconds); - m_SoundScene->Collect_Logical_Sounds (); + m_SoundScene->Collect_Logical_Sounds (milliseconds); } // @@ -1345,7 +1336,7 @@ WWAudioClass::On_Frame_Update (unsigned int milliseconds) // Update this sound object // AudibleSoundClass *sound_obj = m_Playlist[index]; - sound_obj->On_Frame_Update (time_delta); + sound_obj->On_Frame_Update (milliseconds); } return; diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.h b/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.h rename to Core/Libraries/Source/WWVegas/WWAudio/WWAudio.h index 5fafbcbbd3..0c631b8e6e 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.h +++ b/Core/Libraries/Source/WWVegas/WWAudio/WWAudio.h @@ -280,7 +280,7 @@ class WWAudioClass ////////////////////////////////////////////////////////////////////// // Update methods ////////////////////////////////////////////////////////////////////// - void On_Frame_Update (unsigned int milliseconds = 0); + void On_Frame_Update (unsigned int milliseconds); ////////////////////////////////////////////////////////////////////// // Callback methods diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp b/Core/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.h b/Core/Libraries/Source/WWVegas/WWAudio/listenerhandle.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.h rename to Core/Libraries/Source/WWVegas/WWAudio/listenerhandle.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp b/Core/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h b/Core/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h rename to Core/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp b/Core/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h b/Core/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h rename to Core/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp b/Core/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.h b/Core/Libraries/Source/WWVegas/WWAudio/soundhandle.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.h rename to Core/Libraries/Source/WWVegas/WWAudio/soundhandle.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp b/Core/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp rename to Core/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h b/Core/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h rename to Core/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h diff --git a/Core/Libraries/Source/WWVegas/WWDebug/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWDebug/CMakeLists.txt index 45f40a32c9..9d9a8cef43 100644 --- a/Core/Libraries/Source/WWVegas/WWDebug/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/WWDebug/CMakeLists.txt @@ -1,4 +1,3 @@ -# Set source files set(WWDEBUG_SRC wwdebug.cpp wwdebug.h @@ -9,7 +8,6 @@ set(WWDEBUG_SRC wwprofile.h ) -# Targets to build. add_library(core_wwdebug STATIC) set_target_properties(core_wwdebug PROPERTIES OUTPUT_NAME wwdebug) diff --git a/Core/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp b/Core/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp index e034378863..8991b8fc75 100644 --- a/Core/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp +++ b/Core/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp @@ -43,7 +43,6 @@ #include "wwdebug.h" -#include //#include "win.h" can use this if allowed to see wwlib #include #include @@ -53,6 +52,11 @@ #include #include "Except.h" +#ifdef _WIN32 +#include +#else +#include +#endif static PrintFunc _CurMessageHandler = NULL; static AssertPrintFunc _CurAssertHandler = NULL; @@ -79,7 +83,11 @@ void Convert_System_Error_To_String(int id, char* buffer, int buf_len) int Get_Last_System_Error() { +#ifdef _WIN32 return GetLastError(); +#else + return errno; +#endif } /*********************************************************************************************** diff --git a/Core/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp b/Core/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp index 7a77319e2a..e946a8188b 100644 --- a/Core/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp +++ b/Core/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp @@ -43,7 +43,6 @@ #include "wwdebug.h" #include "Vector.H" #include "FastAllocator.h" -#include #define USE_FAST_ALLOCATOR @@ -70,7 +69,8 @@ ** Enable one of the following #defines to specify which thread-sychronization ** method to use. */ -#ifndef _UNIX +#ifdef _WIN32 +#include #define MEMLOG_USE_MUTEX 0 #define MEMLOG_USE_CRITICALSECTION 1 #define MEMLOG_USE_FASTCRITICALSECTION 0 @@ -289,6 +289,10 @@ WWINLINE void * Get_Mem_Log_Mutex(void) return _MemLogCriticalSectionHandle; #endif + +#if DISABLE_MEMLOG + return NULL; +#endif } WWINLINE void Lock_Mem_Log_Mutex(void) diff --git a/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp b/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp index 1eb6f39f3d..d41742e0ca 100644 --- a/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp +++ b/Core/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp @@ -53,7 +53,6 @@ #include "wwprofile.h" #include "FastAllocator.h" #include "wwdebug.h" -#include //#include "systimer.h" #include "systimer.h" #include "RAWFILE.H" diff --git a/Core/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt new file mode 100644 index 0000000000..467d1febf5 --- /dev/null +++ b/Core/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt @@ -0,0 +1,21 @@ +set(WWDOWNLOAD_SRC + Download.cpp + Download.h + DownloadDebug.h + downloaddefs.h + FTP.CPP + ftp.h + ftpdefs.h + registry.cpp + Registry.h + urlBuilder.cpp + urlBuilder.h +) + +add_library(corei_wwdownload INTERFACE) + +target_sources(corei_wwdownload INTERFACE ${WWDOWNLOAD_SRC}) + +target_link_libraries(corei_wwdownload INTERFACE + core_wwcommon +) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/Download.cpp b/Core/Libraries/Source/WWVegas/WWDownload/Download.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/Download.cpp rename to Core/Libraries/Source/WWVegas/WWDownload/Download.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/Download.h b/Core/Libraries/Source/WWVegas/WWDownload/Download.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/Download.h rename to Core/Libraries/Source/WWVegas/WWDownload/Download.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h b/Core/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h rename to Core/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/FTP.CPP b/Core/Libraries/Source/WWVegas/WWDownload/FTP.CPP similarity index 99% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/FTP.CPP rename to Core/Libraries/Source/WWVegas/WWDownload/FTP.CPP index 0d0381d36f..1a55571639 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/FTP.CPP +++ b/Core/Libraries/Source/WWVegas/WWDownload/FTP.CPP @@ -40,9 +40,10 @@ #include "DownloadDebug.h" -#ifndef _DEBUG -#define _DEBUG -#endif +// umm... what?? BGC 3/27/03 +//#ifndef RTS_DEBUG +//#define RTS_DEBUG +//#endif /*************************************************************************/ /*_$ External References */ @@ -873,7 +874,7 @@ HRESULT Cftp::SendCommand( LPCSTR pCommand, int iSize ) if( i > 0 ) { -#ifdef _DEBUG +#ifdef RTS_DEBUG OutputDebugString( "-->" ); OutputDebugString( pCommand ); #endif @@ -953,7 +954,7 @@ HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode ) // OK, we've got a line, pull it from the socket... recv(m_iCommandSocket, pc, end-pc+strlen("\r\n"), 0); -#ifdef _DEBUG +#ifdef RTS_DEBUG OutputDebugString( "<--" ); OutputDebugString( pc ); #endif diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/Registry.h b/Core/Libraries/Source/WWVegas/WWDownload/Registry.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/Registry.h rename to Core/Libraries/Source/WWVegas/WWDownload/Registry.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/downloaddefs.h b/Core/Libraries/Source/WWVegas/WWDownload/downloaddefs.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/downloaddefs.h rename to Core/Libraries/Source/WWVegas/WWDownload/downloaddefs.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/ftp.h b/Core/Libraries/Source/WWVegas/WWDownload/ftp.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/ftp.h rename to Core/Libraries/Source/WWVegas/WWDownload/ftp.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/ftpdefs.h b/Core/Libraries/Source/WWVegas/WWDownload/ftpdefs.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/ftpdefs.h rename to Core/Libraries/Source/WWVegas/WWDownload/ftpdefs.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/registry.cpp b/Core/Libraries/Source/WWVegas/WWDownload/registry.cpp similarity index 90% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/registry.cpp rename to Core/Libraries/Source/WWVegas/WWDownload/registry.cpp index d3f7bc9e89..494e09ecb2 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/registry.cpp +++ b/Core/Libraries/Source/WWVegas/WWDownload/registry.cpp @@ -113,7 +113,11 @@ bool setUnsignedIntInRegistry( HKEY root, std::string path, std::string key, uns bool GetStringFromRegistry(std::string path, std::string key, std::string& val) { +#if RTS_GENERALS + std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; +#elif RTS_ZEROHOUR std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour"; +#endif fullPath.append(path); if (getStringFromRegistry(HKEY_LOCAL_MACHINE, fullPath.c_str(), key.c_str(), val)) @@ -126,7 +130,11 @@ bool GetStringFromRegistry(std::string path, std::string key, std::string& val) bool GetUnsignedIntFromRegistry(std::string path, std::string key, unsigned int& val) { +#if RTS_GENERALS + std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; +#elif RTS_ZEROHOUR std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour"; +#endif fullPath.append(path); if (getUnsignedIntFromRegistry(HKEY_LOCAL_MACHINE, fullPath.c_str(), key.c_str(), val)) @@ -139,7 +147,11 @@ bool GetUnsignedIntFromRegistry(std::string path, std::string key, unsigned int& bool SetStringInRegistry( std::string path, std::string key, std::string val) { +#if RTS_GENERALS + std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; +#elif RTS_ZEROHOUR std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour"; +#endif fullPath.append(path); if (setStringInRegistry( HKEY_LOCAL_MACHINE, fullPath, key, val)) @@ -150,7 +162,11 @@ bool SetStringInRegistry( std::string path, std::string key, std::string val) bool SetUnsignedIntInRegistry( std::string path, std::string key, unsigned int val) { +#if RTS_GENERALS + std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; +#elif RTS_ZEROHOUR std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour"; +#endif fullPath.append(path); if (setUnsignedIntInRegistry( HKEY_LOCAL_MACHINE, fullPath, key, val)) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp b/Core/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp similarity index 96% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp rename to Core/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp index eff44ab411..34fbd794e3 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp +++ b/Core/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp @@ -23,7 +23,11 @@ void FormatURLFromRegistry( std::string& gamePatchURL, std::string& mapPatchURL, std::string& configURL, std::string& motdURL ) { +#if RTS_GENERALS + std::string sku = "generals"; +#elif RTS_ZEROHOUR std::string sku = "GeneralsZH"; +#endif std::string language = "english"; unsigned int version = 0; // invalid version - can't get on with a corrupt reg. unsigned int mapVersion = 0; // invalid version - can't get on with a corrupt reg. diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.h b/Core/Libraries/Source/WWVegas/WWDownload/urlBuilder.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.h rename to Core/Libraries/Source/WWVegas/WWDownload/urlBuilder.h diff --git a/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt index 65bb3fcc65..88a0c0b3ab 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/WWLib/CMakeLists.txt @@ -1,4 +1,3 @@ -# Set source files set(WWLIB_SRC always.h argv.cpp @@ -71,8 +70,6 @@ set(WWLIB_SRC #md5.h mempool.h mmsys.h - mpu.cpp - MPU.H multilist.cpp multilist.h mutex.cpp @@ -91,8 +88,6 @@ set(WWLIB_SRC RANDOM.H rawfile.cpp RAWFILE.H - rcfile.cpp - rcfile.h readline.cpp readline.h realcrc.cpp @@ -102,8 +97,6 @@ set(WWLIB_SRC refcount.h #regexpr.cpp #regexpr.h - registry.cpp - registry.h #search.h sharebuf.h Signaler.h @@ -134,14 +127,10 @@ set(WWLIB_SRC uarray.h vector.cpp Vector.H - verchk.cpp - verchk.h visualc.h widestring.cpp widestring.h win.h - WWCOMUtil.cpp - WWCOMUtil.h wwfile.cpp WWFILE.H wwstring.cpp @@ -152,14 +141,28 @@ set(WWLIB_SRC XSTRAW.H ) -# Targets to build. +if(WIN32) + list(APPEND WWLIB_SRC + mpu.cpp + MPU.H + rcfile.cpp + rcfile.h + registry.cpp + registry.h + verchk.cpp + verchk.h + WWCOMUtil.cpp + WWCOMUtil.h + ) +endif() + add_library(core_wwlib STATIC) set_target_properties(core_wwlib PROPERTIES OUTPUT_NAME wwlib) target_sources(core_wwlib PRIVATE ${WWLIB_SRC}) target_include_directories(core_wwlib PUBLIC - . + ${CMAKE_CURRENT_SOURCE_DIR} ) target_link_libraries(core_wwlib PRIVATE diff --git a/Core/Libraries/Source/WWVegas/WWLib/CRC.H b/Core/Libraries/Source/WWVegas/WWLib/CRC.H index 6a8f8292ae..dcc5790680 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/CRC.H +++ b/Core/Libraries/Source/WWVegas/WWLib/CRC.H @@ -41,9 +41,9 @@ #define CRC_H #include -#ifdef _UNIX - #include "osdep.h" -#endif + +// TheSuperHackers @compile feliwir 17/04/2025 include _ltrotl macros +#include /* ** This is a CRC engine class. It will process submitted data and generate a CRC from it. diff --git a/Core/Libraries/Source/WWVegas/WWLib/Except.cpp b/Core/Libraries/Source/WWVegas/WWLib/Except.cpp index 7ed280bd3c..be4e7ca3bb 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/Except.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/Except.cpp @@ -676,17 +676,17 @@ void Dump_Exception_Info(EXCEPTION_POINTERS *e_info) /* ** The stack contents cannot be read so just print up question marks. */ - sprintf(scrap, "%08X: ", stackptr); + sprintf(scrap, "%p: ", static_cast(stackptr)); strcat(scrap, "????????\r\n"); } else { /* ** If this stack address is in our memory space then try to match it with a code symbol. */ if (IsBadCodePtr((FARPROC)*stackptr)) { - sprintf(scrap, "%08X: %08X ", stackptr, *stackptr); + sprintf(scrap, "%p: %08lX ", static_cast(stackptr), *stackptr); strcat(scrap, "DATA_PTR\r\n"); } else { - sprintf(scrap, "%08X: %08X", stackptr, *stackptr); + sprintf(scrap, "%p: %08lX", static_cast(stackptr), *stackptr); if (symbols_available) { symptr->SizeOfStruct = sizeof(symbol); @@ -783,17 +783,17 @@ int Exception_Handler(int exception_code, EXCEPTION_POINTERS *e_info) } /* - ** If there was a breakpoint then chances are it was set by a debugger. In _DEBUG mode + ** If there was a breakpoint then chances are it was set by a debugger. In RTS_DEBUG mode ** we probably should ignore breakpoints. Breakpoints become more significant in release ** mode since there probably isn't a debugger present. */ -#ifdef _DEBUG +#ifdef RTS_DEBUG if (exception_code == EXCEPTION_BREAKPOINT) { return (EXCEPTION_CONTINUE_SEARCH); } #else exception_code = exception_code; -#endif //_DEBUG +#endif //RTS_DEBUG #ifdef WWDEBUG //CONTEXT *context; @@ -818,7 +818,7 @@ int Exception_Handler(int exception_code, EXCEPTION_POINTERS *e_info) #if (0) #ifdef _DEBUG_PRINT -#ifndef _DEBUG +#ifndef RTS_DEBUG /* ** Copy the exception debug file to the network. No point in doing this for the debug version ** since symbols are not normally available. @@ -833,7 +833,7 @@ int Exception_Handler(int exception_code, EXCEPTION_POINTERS *e_info) } } DebugString ("Debug file copied\n"); -#endif //_DEBUG +#endif //RTS_DEBUG #endif //_DEBUG_PRINT #endif //(0) @@ -852,9 +852,9 @@ int Exception_Handler(int exception_code, EXCEPTION_POINTERS *e_info) ** EXCEPTION_EXECUTE_HANDLER to let us fall out of winmain. */ if (ExitOnException) { -#ifdef _DEBUG +#ifdef RTS_DEBUG _CrtSetDbgFlag(0); -#endif //_DEBUG +#endif //RTS_DEBUG TryingToExit = true; unsigned long id = Get_Main_Thread_ID(); diff --git a/Core/Libraries/Source/WWVegas/WWLib/FastAllocator.cpp b/Core/Libraries/Source/WWVegas/WWLib/FastAllocator.cpp index a53c83f6df..f3bf1b6f3f 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/FastAllocator.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/FastAllocator.cpp @@ -17,7 +17,7 @@ */ #include "FastAllocator.h" -#include +#include static FastAllocatorGeneral* generalAllocator; //This general allocator will do all allocations for us. diff --git a/Core/Libraries/Source/WWVegas/WWLib/INDEX.H b/Core/Libraries/Source/WWVegas/WWLib/INDEX.H index a5e818ee46..fc9e4923e5 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/INDEX.H +++ b/Core/Libraries/Source/WWVegas/WWLib/INDEX.H @@ -547,7 +547,7 @@ void IndexClass::Set_Archive(NodeElement const * node) const template bool IndexClass::Add_Index(INDEX const & id, T const & data) { -#ifdef _DEBUG +#ifdef RTS_DEBUG /* ** Ensure that two elements with the same index are not added to the ** array. diff --git a/Core/Libraries/Source/WWVegas/WWLib/Vector.H b/Core/Libraries/Source/WWVegas/WWLib/Vector.H index 4e331d2a18..f5eb7066f8 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/Vector.H +++ b/Core/Libraries/Source/WWVegas/WWLib/Vector.H @@ -61,7 +61,7 @@ #include #include #include -#include +#include #ifdef _MSC_VER #pragma warning (disable : 4702) // unreachable code, happens with some uses of these templates @@ -317,7 +317,7 @@ template inline int VectorClass::ID(T const * ptr) { if (!IsValid) return(0); - return(((unsigned long)ptr - (unsigned long)&(*this)[0]) / sizeof(T)); + return(((uintptr_t)ptr - (uintptr_t)&(*this)[0]) / sizeof(T)); } diff --git a/Core/Libraries/Source/WWVegas/WWLib/WWFILE.H b/Core/Libraries/Source/WWVegas/WWLib/WWFILE.H index b8a7066b30..3d4fd1ccee 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/WWFILE.H +++ b/Core/Libraries/Source/WWVegas/WWLib/WWFILE.H @@ -40,10 +40,6 @@ #ifndef WWFILE_Hx #define WWFILE_Hx -#ifdef _UNIX -#include "osdep.h" -#endif - #define YEAR(dt) (((dt & 0xFE000000) >> (9 + 16)) + 1980) #define MONTH(dt) ((dt & 0x01E00000) >> (5 + 16)) #define DAY(dt) ((dt & 0x001F0000) >> (0 + 16)) diff --git a/Core/Libraries/Source/WWVegas/WWLib/always.h b/Core/Libraries/Source/WWVegas/WWLib/always.h index 2df70428da..8b50cad0a8 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/always.h +++ b/Core/Libraries/Source/WWVegas/WWLib/always.h @@ -43,6 +43,10 @@ #include #include +// TheSuperHackers @compile feliwir 17/04/2025 include utility macros for cross-platform compatibility +#include +#include + // Disable warning about exception handling not being enabled. It's used as part of STL - in a part of STL we don't use. #pragma warning(disable : 4530) @@ -51,7 +55,7 @@ ** This helps find leaks. */ //#define STEVES_NEW_CATCHER -#ifdef _DEBUG +#ifdef RTS_DEBUG #ifdef _MSC_VER #ifdef STEVES_NEW_CATCHER @@ -70,7 +74,7 @@ #endif //STEVES_NEW_CATCHER #endif //_MSC_VER -#endif //_DEBUG +#endif //RTS_DEBUG #if !defined(DISABLE_GAMEMEMORY) // (gth) killing the Generals Memory Manager! @@ -101,7 +105,7 @@ #endif -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) #define MSGW3DNEW(MSG) new( MSG, 0 ) #define MSGW3DNEWARRAY(MSG) new( MSG, 0 ) #define W3DNEW new("W3D_" __FILE__, 0) diff --git a/Core/Libraries/Source/WWVegas/WWLib/argv.h b/Core/Libraries/Source/WWVegas/WWLib/argv.h index 8fe1ce4bac..8e8ccb7776 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/argv.h +++ b/Core/Libraries/Source/WWVegas/WWLib/argv.h @@ -47,10 +47,6 @@ #include "always.h" #endif -#ifdef _UNIX -#include "osdep.h" -#endif - // Used to parse command line that is passed into WinMain. // It also has the ability to load a file with values to append to the command line. // Normally in WinMain() there would be a call Argv::Init(lpCmdLine, fileprefix). diff --git a/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp b/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp index 3dde46736b..857ff0d812 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/cpudetect.cpp @@ -21,10 +21,13 @@ #include "wwdebug.h" #include "thread.h" #pragma warning (disable : 4201) // Nonstandard extension - nameless struct -#include #include "systimer.h" #include +#ifdef _WIN32 +#include +#endif + #ifdef _UNIX # include // for time(), localtime() and timezone variable. #endif @@ -57,7 +60,7 @@ int CPUDetectClass::ProcessorFamily; int CPUDetectClass::ProcessorModel; int CPUDetectClass::ProcessorRevision; int CPUDetectClass::ProcessorSpeed; -__int64 CPUDetectClass::ProcessorTicksPerSecond; // Ticks per second +sint64 CPUDetectClass::ProcessorTicksPerSecond; // Ticks per second double CPUDetectClass::InvProcessorTicksPerSecond; // 1.0 / Ticks per second unsigned CPUDetectClass::FeatureBits; @@ -125,10 +128,10 @@ const char* CPUDetectClass::Get_Processor_Manufacturer_Name() #define ASM_RDTSC _asm _emit 0x0f _asm _emit 0x31 -static unsigned Calculate_Processor_Speed(__int64& ticks_per_second) +static unsigned Calculate_Processor_Speed(sint64& ticks_per_second) { - unsigned __int64 timer0=0; - unsigned __int64 timer1=0; + sint64 timer0=0; + sint64 timer1=0; timer0=_rdtsc(); @@ -138,8 +141,8 @@ static unsigned Calculate_Processor_Speed(__int64& ticks_per_second) timer1=_rdtsc(); } - __int64 t=timer1-timer0; - ticks_per_second=(__int64)((1000.0/(double)elapsed)*(double)t); // Ticks per second + sint64 t=timer1-timer0; + ticks_per_second=(sint64)((1000.0/(double)elapsed)*(double)t); // Ticks per second return unsigned((double)t/(double)(elapsed*1000)); } @@ -898,8 +901,8 @@ void CPUDetectClass::Init_Memory() void CPUDetectClass::Init_OS() { - OSVERSIONINFO os; #ifdef WIN32 + OSVERSIONINFO os; os.dwOSVersionInfoSize = sizeof(os); GetVersionEx(&os); @@ -940,9 +943,11 @@ void CPUDetectClass::Init_Processor_Log() SYSLOG(("Operating System: ")); switch (OSVersionPlatformId) { +#ifdef _WIN32 case VER_PLATFORM_WIN32s: SYSLOG(("Windows 3.1")); break; case VER_PLATFORM_WIN32_WINDOWS: SYSLOG(("Windows 9x")); break; case VER_PLATFORM_WIN32_NT: SYSLOG(("Windows NT")); break; +#endif } SYSLOG(("\r\n")); @@ -1223,6 +1228,7 @@ void Get_OS_Info( switch (OSVersionPlatformId) { default: break; +#ifdef _WIN32 case VER_PLATFORM_WIN32_WINDOWS: { for(int i=0;i diff --git a/Core/Libraries/Source/WWVegas/WWLib/ini.cpp b/Core/Libraries/Source/WWVegas/WWLib/ini.cpp index 4f3f5ccb76..479cf90a8a 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/ini.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/ini.cpp @@ -1560,7 +1560,7 @@ double INIClass::Get_Double(char const * section, char const * entry, double def INIEntry * entryptr = Find_Entry(section, entry); if (entryptr != NULL && entryptr->Value != NULL) { - float val = defvalue; + double val = defvalue; sscanf(entryptr->Value, "%lf", &val); defvalue = val; if (strchr(entryptr->Value, '%') != NULL) { diff --git a/Core/Libraries/Source/WWVegas/WWLib/mempool.h b/Core/Libraries/Source/WWVegas/WWLib/mempool.h index 9b1c4e5902..e1712b813f 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/mempool.h +++ b/Core/Libraries/Source/WWVegas/WWLib/mempool.h @@ -53,7 +53,7 @@ #include "bittype.h" #include "wwdebug.h" #include "mutex.h" -#include +#include #include #include @@ -157,8 +157,14 @@ class AutoPoolClass ** Macro to declare the allocator for your class. Put this in the cpp file for ** the class. */ +#if defined(_MSC_VER) && _MSC_VER < 1300 #define DEFINE_AUTO_POOL(T,BLOCKSIZE) \ ObjectPoolClass AutoPoolClass::Allocator; +#else +#define DEFINE_AUTO_POOL(T,BLOCKSIZE) \ +template<>\ +ObjectPoolClass AutoPoolClass::Allocator = {} +#endif /*********************************************************************************************** diff --git a/Core/Libraries/Source/WWVegas/WWLib/mutex.cpp b/Core/Libraries/Source/WWVegas/WWLib/mutex.cpp index f63cc81e3b..946090a282 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/mutex.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/mutex.cpp @@ -18,8 +18,9 @@ #include "mutex.h" #include "wwdebug.h" +#ifdef _WIN32 #include - +#endif // ---------------------------------------------------------------------------- diff --git a/Core/Libraries/Source/WWVegas/WWLib/refcount.cpp b/Core/Libraries/Source/WWVegas/WWLib/refcount.cpp index 39dd095ef0..8b0fdecba3 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/refcount.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/refcount.cpp @@ -40,8 +40,9 @@ #include "refcount.h" -#include +// TheSuperHackers @compile feliwir 17/04/2025 include __debugbreak macros +#include #ifndef NDEBUG @@ -174,7 +175,7 @@ void RefCountClass::Add_Ref(void) const // See if programmer set break on for a specific address. if (this == BreakOnReference) { - DebugBreak(); // trigger the debugger + __debugbreak(); // trigger the debugger } Inc_Total_Refs(this); } @@ -201,7 +202,7 @@ void RefCountClass::Dec_Total_Refs(const RefCountClass * obj) // See if programmer set break on for a specific address. if (obj == BreakOnReference) { - DebugBreak(); // trigger the debugger + __debugbreak(); // trigger the debugger } } diff --git a/Core/Libraries/Source/WWVegas/WWLib/sharebuf.h b/Core/Libraries/Source/WWVegas/WWLib/sharebuf.h index 82b9da276f..8a6fddf751 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/sharebuf.h +++ b/Core/Libraries/Source/WWVegas/WWLib/sharebuf.h @@ -77,7 +77,7 @@ class ShareBufferClass : public W3DMPO, public RefCountClass protected: -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) const char* Msg; #endif T * Array; @@ -90,7 +90,7 @@ class ShareBufferClass : public W3DMPO, public RefCountClass template ShareBufferClass::ShareBufferClass(int count, const char* msg) : Count(count) -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) , Msg(msg) #endif { @@ -103,7 +103,7 @@ ShareBufferClass::ShareBufferClass(const ShareBufferClass & that) : Count(that.Count) { assert(Count > 0); -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) Msg = that.Msg; #endif Array = MSGW3DNEWARRAY(Msg) T[Count]; diff --git a/Core/Libraries/Source/WWVegas/WWLib/systimer.h b/Core/Libraries/Source/WWVegas/WWLib/systimer.h index 44d03a8ba1..4c8ea01624 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/systimer.h +++ b/Core/Libraries/Source/WWVegas/WWLib/systimer.h @@ -38,11 +38,25 @@ #ifndef _SYSTIMER_H #include "always.h" +#ifdef _WIN32 #include #include "mmsys.h" #define TIMEGETTIME SystemTime.Get #define MS_TIMER_SECOND 1000 +#else +#include + +inline unsigned long systimerGetMS(void) +{ + struct timeval tv; + gettimeofday(&tv, NULL); + return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); +} + +#define TIMEGETTIME systimerGetMS +#define MS_TIMER_SECOND 1000 +#endif /* ** Class that just wraps around timeGetTime() diff --git a/Core/Libraries/Source/WWVegas/WWLib/thread.cpp b/Core/Libraries/Source/WWVegas/WWLib/thread.cpp index c6c1f20561..4c8b2f27ed 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/thread.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/thread.cpp @@ -21,13 +21,15 @@ #include "thread.h" #include "Except.h" #include "wwdebug.h" -#include -#include #pragma warning ( push ) #pragma warning ( disable : 4201 ) #include "systimer.h" #pragma warning ( pop ) +#ifdef _WIN32 +#include +#include +#endif ThreadClass::ThreadClass(const char *thread_name, ExceptionHandlerType exception_handler) : handle(0), running(false), thread_priority(0) { diff --git a/Core/Libraries/Source/WWVegas/WWLib/thread.h b/Core/Libraries/Source/WWVegas/WWLib/thread.h index 62259d0b35..4e57301646 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/thread.h +++ b/Core/Libraries/Source/WWVegas/WWLib/thread.h @@ -22,9 +22,6 @@ #if defined(_MSC_VER) #pragma once #endif -#ifdef _UNIX -#include "osdep.h" -#endif #include "always.h" #include "Vector.H" diff --git a/Core/Libraries/Source/WWVegas/WWLib/widestring.h b/Core/Libraries/Source/WWVegas/WWLib/widestring.h index 5d31aa0d16..ed3728483e 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/widestring.h +++ b/Core/Libraries/Source/WWVegas/WWLib/widestring.h @@ -49,9 +49,6 @@ #include "wwstring.h" #include "trim.h" #include -#ifdef _UNIX -#include "osdep.h" -#endif ////////////////////////////////////////////////////////////////////// // diff --git a/Core/Libraries/Source/WWVegas/WWLib/win.h b/Core/Libraries/Source/WWVegas/WWLib/win.h index cf9e4e05d8..dbd62fb73f 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/win.h +++ b/Core/Libraries/Source/WWVegas/WWLib/win.h @@ -49,6 +49,8 @@ ** 4069, 4200, 4237, 4103, 4001, 4035, 4164. Makes you wonder, eh? */ +#ifdef _WIN32 + // When including windows, lets just bump the warning level back to 3... #if (_MSC_VER >= 1200) #pragma warning(push, 3) @@ -69,23 +71,22 @@ #pragma warning(pop) #endif -#ifdef _WINDOWS extern HINSTANCE ProgramInstance; extern HWND MainWindow; extern bool GameInFocus; -#ifdef _DEBUG +#ifdef RTS_DEBUG void __cdecl Print_Win32Error(unsigned long win32Error); -#else // _DEBUG +#else // RTS_DEBUG #define Print_Win32Error -#endif // _DEBUG +#endif // RTS_DEBUG -#else // _WINDOWS +#else // _WIN32 //#include // file does not exist -#endif // _WINDOWS +#endif // _WIN32 #endif // WIN_H diff --git a/Core/Libraries/Source/WWVegas/WWLib/wwfile.cpp b/Core/Libraries/Source/WWVegas/WWLib/wwfile.cpp index 8d724d7f97..0d3c47e535 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/wwfile.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/wwfile.cpp @@ -39,6 +39,9 @@ #include #include "WWFILE.H" +// TheSuperHackers @compile feliwir 17/04/2025 include _vsnprintf macros +#include + #pragma warning(disable : 4514) int FileClass::Printf(char *str, ...) diff --git a/Core/Libraries/Source/WWVegas/WWLib/wwstring.cpp b/Core/Libraries/Source/WWVegas/WWLib/wwstring.cpp index 3a8aaa6728..df7ea6566b 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/wwstring.cpp +++ b/Core/Libraries/Source/WWVegas/WWLib/wwstring.cpp @@ -35,7 +35,6 @@ * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #include "wwstring.h" -#include "win.h" #include "wwmemlog.h" #include "mutex.h" #include @@ -102,7 +101,7 @@ StringClass::Get_String (int length, bool is_temp) // // Grab this unused buffer for our string // - unsigned temp_string=reinterpret_cast(m_TempStrings); + uintptr_t temp_string=reinterpret_cast(m_TempStrings); temp_string+=MAX_TEMP_BYTES*MAX_TEMP_STRING; temp_string&=~(MAX_TEMP_BYTES*MAX_TEMP_STRING-1); temp_string+=index*MAX_TEMP_BYTES; @@ -197,8 +196,8 @@ StringClass::Free_String (void) { if (m_Buffer != m_EmptyString) { - unsigned buffer_base=reinterpret_cast(m_Buffer-sizeof (StringClass::_HEADER)); - unsigned temp_base=reinterpret_cast(m_TempStrings+MAX_TEMP_BYTES*MAX_TEMP_STRING); + uintptr_t buffer_base=reinterpret_cast(m_Buffer-sizeof (StringClass::_HEADER)); + uintptr_t temp_base=reinterpret_cast(m_TempStrings+MAX_TEMP_BYTES*MAX_TEMP_STRING); if ((buffer_base>>11)==(temp_base>>11)) { m_Buffer[0] = 0; @@ -321,7 +320,7 @@ bool StringClass::Copy_Wide (const WCHAR *source) if (source != NULL) { int length; - BOOL unmapped; + int unmapped; length = WideCharToMultiByte (CP_ACP, 0 , source, -1, NULL, 0, NULL, &unmapped); if (length > 0) { diff --git a/Core/Libraries/Source/WWVegas/WWLib/wwstring.h b/Core/Libraries/Source/WWVegas/WWLib/wwstring.h index 6d8f9d76cc..be8e25e560 100644 --- a/Core/Libraries/Source/WWVegas/WWLib/wwstring.h +++ b/Core/Libraries/Source/WWVegas/WWLib/wwstring.h @@ -46,11 +46,10 @@ #include "win.h" #include #include -#include #include "trim.h" #include "wwdebug.h" -#ifdef _UNIX -#include "osdep.h" +#ifdef _WIN32 +#include #endif diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWMath/CMakeLists.txt similarity index 81% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/CMakeLists.txt rename to Core/Libraries/Source/WWVegas/WWMath/CMakeLists.txt index e86bb8f58c..d88eb09edb 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/WWMath/CMakeLists.txt @@ -80,15 +80,14 @@ set(WWMATH_SRC wwmathids.h ) -# Targets to build. -add_library(z_wwmath STATIC) -set_target_properties(z_wwmath PROPERTIES OUTPUT_NAME wwmath) +add_library(core_wwmath STATIC) +set_target_properties(core_wwmath PROPERTIES OUTPUT_NAME wwmath) -target_sources(z_wwmath PRIVATE ${WWMATH_SRC}) +target_sources(core_wwmath PRIVATE ${WWMATH_SRC}) -target_link_libraries(z_wwmath PRIVATE - z_wwcommon +target_link_libraries(core_wwmath PRIVATE + core_wwcommon ) # @todo Test its impact and see what to do with the legacy functions. -#add_compile_definitions(z_wwmath PUBLIC ALLOW_TEMPORARIES) # Enables legacy math with "temporaries" +#add_compile_definitions(core_wwmath PUBLIC ALLOW_TEMPORARIES) # Enables legacy math with "temporaries" diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/Vector3i.h b/Core/Libraries/Source/WWVegas/WWMath/Vector3i.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/Vector3i.h rename to Core/Libraries/Source/WWVegas/WWMath/Vector3i.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabox.cpp b/Core/Libraries/Source/WWVegas/WWMath/aabox.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabox.cpp rename to Core/Libraries/Source/WWVegas/WWMath/aabox.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabox.h b/Core/Libraries/Source/WWVegas/WWMath/aabox.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabox.h rename to Core/Libraries/Source/WWVegas/WWMath/aabox.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp b/Core/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp rename to Core/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.h b/Core/Libraries/Source/WWVegas/WWMath/aabtreecull.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.h rename to Core/Libraries/Source/WWVegas/WWMath/aabtreecull.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aaplane.h b/Core/Libraries/Source/WWVegas/WWMath/aaplane.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/aaplane.h rename to Core/Libraries/Source/WWVegas/WWMath/aaplane.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp b/Core/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp rename to Core/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.h b/Core/Libraries/Source/WWVegas/WWMath/cardinalspline.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.h rename to Core/Libraries/Source/WWVegas/WWMath/cardinalspline.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/castres.h b/Core/Libraries/Source/WWVegas/WWMath/castres.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/castres.h rename to Core/Libraries/Source/WWVegas/WWMath/castres.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp b/Core/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp rename to Core/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.h b/Core/Libraries/Source/WWVegas/WWMath/catmullromspline.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.h rename to Core/Libraries/Source/WWVegas/WWMath/catmullromspline.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmath.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmath.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmath.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmath.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmath.h b/Core/Libraries/Source/WWVegas/WWMath/colmath.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmath.h rename to Core/Libraries/Source/WWVegas/WWMath/colmath.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.h b/Core/Libraries/Source/WWVegas/WWMath/colmathaabox.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.h rename to Core/Libraries/Source/WWVegas/WWMath/colmathaabox.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.h b/Core/Libraries/Source/WWVegas/WWMath/colmathfrustum.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.h rename to Core/Libraries/Source/WWVegas/WWMath/colmathfrustum.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathinlines.h b/Core/Libraries/Source/WWVegas/WWMath/colmathinlines.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathinlines.h rename to Core/Libraries/Source/WWVegas/WWMath/colmathinlines.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathline.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathline.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathline.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathline.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathline.h b/Core/Libraries/Source/WWVegas/WWMath/colmathline.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathline.h rename to Core/Libraries/Source/WWVegas/WWMath/colmathline.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathplane.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathplane.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathplane.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathplane.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathplane.h b/Core/Libraries/Source/WWVegas/WWMath/colmathplane.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathplane.h rename to Core/Libraries/Source/WWVegas/WWMath/colmathplane.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp b/Core/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp rename to Core/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cullsys.cpp b/Core/Libraries/Source/WWVegas/WWMath/cullsys.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cullsys.cpp rename to Core/Libraries/Source/WWVegas/WWMath/cullsys.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cullsys.h b/Core/Libraries/Source/WWVegas/WWMath/cullsys.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/cullsys.h rename to Core/Libraries/Source/WWVegas/WWMath/cullsys.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/culltype.h b/Core/Libraries/Source/WWVegas/WWMath/culltype.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/culltype.h rename to Core/Libraries/Source/WWVegas/WWMath/culltype.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/curve.cpp b/Core/Libraries/Source/WWVegas/WWMath/curve.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/curve.cpp rename to Core/Libraries/Source/WWVegas/WWMath/curve.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/curve.h b/Core/Libraries/Source/WWVegas/WWMath/curve.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/curve.h rename to Core/Libraries/Source/WWVegas/WWMath/curve.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/euler.cpp b/Core/Libraries/Source/WWVegas/WWMath/euler.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/euler.cpp rename to Core/Libraries/Source/WWVegas/WWMath/euler.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/euler.h b/Core/Libraries/Source/WWVegas/WWMath/euler.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/euler.h rename to Core/Libraries/Source/WWVegas/WWMath/euler.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/frustum.cpp b/Core/Libraries/Source/WWVegas/WWMath/frustum.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/frustum.cpp rename to Core/Libraries/Source/WWVegas/WWMath/frustum.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/frustum.h b/Core/Libraries/Source/WWVegas/WWMath/frustum.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/frustum.h rename to Core/Libraries/Source/WWVegas/WWMath/frustum.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/gridcull.cpp b/Core/Libraries/Source/WWVegas/WWMath/gridcull.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/gridcull.cpp rename to Core/Libraries/Source/WWVegas/WWMath/gridcull.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/gridcull.h b/Core/Libraries/Source/WWVegas/WWMath/gridcull.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/gridcull.h rename to Core/Libraries/Source/WWVegas/WWMath/gridcull.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/hermitespline.cpp b/Core/Libraries/Source/WWVegas/WWMath/hermitespline.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/hermitespline.cpp rename to Core/Libraries/Source/WWVegas/WWMath/hermitespline.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/hermitespline.h b/Core/Libraries/Source/WWVegas/WWMath/hermitespline.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/hermitespline.h rename to Core/Libraries/Source/WWVegas/WWMath/hermitespline.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lineseg.cpp b/Core/Libraries/Source/WWVegas/WWMath/lineseg.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lineseg.cpp rename to Core/Libraries/Source/WWVegas/WWMath/lineseg.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lineseg.h b/Core/Libraries/Source/WWVegas/WWMath/lineseg.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lineseg.h rename to Core/Libraries/Source/WWVegas/WWMath/lineseg.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lookuptable.cpp b/Core/Libraries/Source/WWVegas/WWMath/lookuptable.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lookuptable.cpp rename to Core/Libraries/Source/WWVegas/WWMath/lookuptable.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lookuptable.h b/Core/Libraries/Source/WWVegas/WWMath/lookuptable.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/lookuptable.h rename to Core/Libraries/Source/WWVegas/WWMath/lookuptable.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3.cpp b/Core/Libraries/Source/WWVegas/WWMath/matrix3.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3.cpp rename to Core/Libraries/Source/WWVegas/WWMath/matrix3.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3.h b/Core/Libraries/Source/WWVegas/WWMath/matrix3.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3.h rename to Core/Libraries/Source/WWVegas/WWMath/matrix3.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3d.cpp b/Core/Libraries/Source/WWVegas/WWMath/matrix3d.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3d.cpp rename to Core/Libraries/Source/WWVegas/WWMath/matrix3d.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3d.h b/Core/Libraries/Source/WWVegas/WWMath/matrix3d.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix3d.h rename to Core/Libraries/Source/WWVegas/WWMath/matrix3d.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix4.cpp b/Core/Libraries/Source/WWVegas/WWMath/matrix4.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix4.cpp rename to Core/Libraries/Source/WWVegas/WWMath/matrix4.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix4.h b/Core/Libraries/Source/WWVegas/WWMath/matrix4.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/matrix4.h rename to Core/Libraries/Source/WWVegas/WWMath/matrix4.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/normalcone.h b/Core/Libraries/Source/WWVegas/WWMath/normalcone.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/normalcone.h rename to Core/Libraries/Source/WWVegas/WWMath/normalcone.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/obbox.cpp b/Core/Libraries/Source/WWVegas/WWMath/obbox.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/obbox.cpp rename to Core/Libraries/Source/WWVegas/WWMath/obbox.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/obbox.h b/Core/Libraries/Source/WWVegas/WWMath/obbox.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/obbox.h rename to Core/Libraries/Source/WWVegas/WWMath/obbox.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/ode.cpp b/Core/Libraries/Source/WWVegas/WWMath/ode.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/ode.cpp rename to Core/Libraries/Source/WWVegas/WWMath/ode.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/ode.h b/Core/Libraries/Source/WWVegas/WWMath/ode.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/ode.h rename to Core/Libraries/Source/WWVegas/WWMath/ode.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/plane.h b/Core/Libraries/Source/WWVegas/WWMath/plane.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/plane.h rename to Core/Libraries/Source/WWVegas/WWMath/plane.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/pot.cpp b/Core/Libraries/Source/WWVegas/WWMath/pot.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/pot.cpp rename to Core/Libraries/Source/WWVegas/WWMath/pot.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/pot.h b/Core/Libraries/Source/WWVegas/WWMath/pot.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/pot.h rename to Core/Libraries/Source/WWVegas/WWMath/pot.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/quat.cpp b/Core/Libraries/Source/WWVegas/WWMath/quat.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/quat.cpp rename to Core/Libraries/Source/WWVegas/WWMath/quat.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/quat.h b/Core/Libraries/Source/WWVegas/WWMath/quat.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/quat.h rename to Core/Libraries/Source/WWVegas/WWMath/quat.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/rect.h b/Core/Libraries/Source/WWVegas/WWMath/rect.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/rect.h rename to Core/Libraries/Source/WWVegas/WWMath/rect.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/sphere.h b/Core/Libraries/Source/WWVegas/WWMath/sphere.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/sphere.h rename to Core/Libraries/Source/WWVegas/WWMath/sphere.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tcbspline.cpp b/Core/Libraries/Source/WWVegas/WWMath/tcbspline.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tcbspline.cpp rename to Core/Libraries/Source/WWVegas/WWMath/tcbspline.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tcbspline.h b/Core/Libraries/Source/WWVegas/WWMath/tcbspline.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tcbspline.h rename to Core/Libraries/Source/WWVegas/WWMath/tcbspline.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tri.cpp b/Core/Libraries/Source/WWVegas/WWMath/tri.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tri.cpp rename to Core/Libraries/Source/WWVegas/WWMath/tri.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tri.h b/Core/Libraries/Source/WWVegas/WWMath/tri.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/tri.h rename to Core/Libraries/Source/WWVegas/WWMath/tri.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp b/Core/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp rename to Core/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.h b/Core/Libraries/Source/WWVegas/WWMath/v3_rnd.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.h rename to Core/Libraries/Source/WWVegas/WWMath/v3_rnd.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector2.h b/Core/Libraries/Source/WWVegas/WWMath/vector2.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector2.h rename to Core/Libraries/Source/WWVegas/WWMath/vector2.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector2i.h b/Core/Libraries/Source/WWVegas/WWMath/vector2i.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector2i.h rename to Core/Libraries/Source/WWVegas/WWMath/vector2i.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector3.h b/Core/Libraries/Source/WWVegas/WWMath/vector3.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector3.h rename to Core/Libraries/Source/WWVegas/WWMath/vector3.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector4.h b/Core/Libraries/Source/WWVegas/WWMath/vector4.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vector4.h rename to Core/Libraries/Source/WWVegas/WWMath/vector4.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp b/Core/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp rename to Core/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.h b/Core/Libraries/Source/WWVegas/WWMath/vehiclecurve.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.h rename to Core/Libraries/Source/WWVegas/WWMath/vehiclecurve.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vp.cpp b/Core/Libraries/Source/WWVegas/WWMath/vp.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vp.cpp rename to Core/Libraries/Source/WWVegas/WWMath/vp.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vp.h b/Core/Libraries/Source/WWVegas/WWMath/vp.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/vp.h rename to Core/Libraries/Source/WWVegas/WWMath/vp.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.cpp b/Core/Libraries/Source/WWVegas/WWMath/wwmath.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.cpp rename to Core/Libraries/Source/WWVegas/WWMath/wwmath.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.h b/Core/Libraries/Source/WWVegas/WWMath/wwmath.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.h rename to Core/Libraries/Source/WWVegas/WWMath/wwmath.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmathids.h b/Core/Libraries/Source/WWVegas/WWMath/wwmathids.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmathids.h rename to Core/Libraries/Source/WWVegas/WWMath/wwmathids.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt similarity index 74% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt rename to Core/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt index bdc2b6bba0..bcb5af6819 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt +++ b/Core/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt @@ -1,4 +1,3 @@ -# Set source files set(WWSAVELOAD_SRC definition.cpp definition.h @@ -36,12 +35,11 @@ set(WWSAVELOAD_SRC wwsaveload.h ) -# Targets to build. -add_library(z_wwsaveload STATIC) -set_target_properties(z_wwsaveload PROPERTIES OUTPUT_NAME wwsaveload) +add_library(core_wwsaveload STATIC) +set_target_properties(core_wwsaveload PROPERTIES OUTPUT_NAME wwsaveload) -target_sources(z_wwsaveload PRIVATE ${WWSAVELOAD_SRC}) +target_sources(core_wwsaveload PRIVATE ${WWSAVELOAD_SRC}) -target_link_libraries(z_wwsaveload PRIVATE - z_wwcommon +target_link_libraries(core_wwsaveload PRIVATE + core_wwcommon ) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/definition.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definition.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/editable.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/editable.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/editable.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/editable.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/parameter.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/parameter.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/persist.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/persist.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/persist.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/persist.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveload.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveload.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp b/Core/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp rename to Core/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h b/Core/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h rename to Core/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h diff --git a/Core/Libraries/Source/WWVegas/WWStub/CMakeLists.txt b/Core/Libraries/Source/WWVegas/WWStub/CMakeLists.txt new file mode 100644 index 0000000000..1b5edd79cd --- /dev/null +++ b/Core/Libraries/Source/WWVegas/WWStub/CMakeLists.txt @@ -0,0 +1,14 @@ +set(WWSTUB_SRC + wwallocstub.cpp + wwdebugstub.cpp +) + +add_library(core_wwstub STATIC) +set_target_properties(core_wwstub PROPERTIES OUTPUT_NAME wwstub) + +target_sources(core_wwstub PRIVATE ${WWSTUB_SRC}) + +target_link_libraries(core_wwstub PRIVATE + core_wwcommon + corei_always +) diff --git a/Core/Libraries/Source/WWVegas/WWStub/wwallocstub.cpp b/Core/Libraries/Source/WWVegas/WWStub/wwallocstub.cpp new file mode 100644 index 0000000000..55fc3f28b5 --- /dev/null +++ b/Core/Libraries/Source/WWVegas/WWStub/wwallocstub.cpp @@ -0,0 +1,85 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +// TheSuperHackers @compile feliwir 15/04/2025 Simple allocator implementation useful for tools +#include "always.h" +#include + +#ifdef _OPERATOR_NEW_DEFINED_ + +void *operator new(size_t size) +{ + return malloc(size); +} + +void *operator new[](size_t size) +{ + return malloc(size); +} + +void operator delete(void *p) +{ + free(p); +} + +void operator delete[](void *p) +{ + free(p); +} + +void* operator new(size_t size, const char * fname, int) +{ + return malloc(size); +} + +void operator delete(void * p, const char *, int) +{ + free(p); +} + +void* operator new[](size_t size, const char * fname, int) +{ + return malloc(size); +} + +void operator delete[](void * p, const char *, int) +{ + free(p); +} + +#endif + +void* createW3DMemPool(const char *poolName, int allocationSize) +{ + return NULL; +} + +void* allocateFromW3DMemPool(void* pool, int allocationSize) +{ + return malloc(allocationSize); +} + +void* allocateFromW3DMemPool(void* pool, int allocationSize, const char* msg, int unused) +{ + return malloc(allocationSize); +} + +void freeFromW3DMemPool(void* pool, void* p) +{ + free(p); +} diff --git a/Generals/Code/Tools/mangler/wlib/syslogd.h b/Core/Libraries/Source/WWVegas/WWStub/wwdebugstub.cpp similarity index 53% rename from Generals/Code/Tools/mangler/wlib/syslogd.h rename to Core/Libraries/Source/WWVegas/WWStub/wwdebugstub.cpp index 569f2b1d5b..a86eb93156 100644 --- a/Generals/Code/Tools/mangler/wlib/syslogd.h +++ b/Core/Libraries/Source/WWVegas/WWStub/wwdebugstub.cpp @@ -1,6 +1,6 @@ /* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by @@ -16,33 +16,41 @@ ** along with this program. If not, see . */ -#ifndef SYSLOGD_HEADER -#define SYSLOGD_HEADER - +// TheSuperHackers @compile feliwir 15/04/2025 Simple debug implementation useful for tools +#include "wwdebug.h" +#include #include #include -#ifndef _WINDOWS -#include -#endif -#include -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN +char* TheCurrentIgnoreCrashPtr = NULL; + + +#ifdef DEBUG_LOGGING + +void DebugLog(const char *format, ...) +{ + // Print it to the console + + va_list arg; + va_start(arg, format); + vprintf(format, arg); + va_end(arg); +} + #endif -#define IN const -#include "odevice.h" +#ifdef DEBUG_CRASHING -// Windows doesn't have a syslog equivalent (does it?), so this class does little there -class SyslogD : public OutputDevice +void DebugCrash(const char *format, ...) { - public: - SyslogD(char *ident,int logopt,int facility,int priority); - virtual int print(const char *str,int len); + // Print it to the console + + va_list arg; + va_start(arg, format); + vprintf(format, arg); + va_end(arg); - private: - int priority; -}; + // No exit in this stub +} #endif diff --git a/GeneralsMD/Code/Libraries/Source/debug/CMakeLists.txt b/Core/Libraries/Source/debug/CMakeLists.txt similarity index 70% rename from GeneralsMD/Code/Libraries/Source/debug/CMakeLists.txt rename to Core/Libraries/Source/debug/CMakeLists.txt index e5af00fae0..f81690ac1c 100644 --- a/GeneralsMD/Code/Libraries/Source/debug/CMakeLists.txt +++ b/Core/Libraries/Source/debug/CMakeLists.txt @@ -24,15 +24,15 @@ set(DEBUG_SRC "internal.h" ) -add_library(z_debug STATIC) +add_library(core_debug STATIC) -target_sources(z_debug PRIVATE ${DEBUG_SRC}) +target_sources(core_debug PRIVATE ${DEBUG_SRC}) -target_include_directories(z_debug INTERFACE - . +target_include_directories(core_debug INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR} ) -target_link_libraries(z_debug PRIVATE +target_link_libraries(core_debug PRIVATE core_config - zi_always + corei_always ) diff --git a/GeneralsMD/Code/Libraries/Source/debug/_pch.cpp b/Core/Libraries/Source/debug/_pch.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/_pch.cpp rename to Core/Libraries/Source/debug/_pch.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/_pch.h b/Core/Libraries/Source/debug/_pch.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/_pch.h rename to Core/Libraries/Source/debug/_pch.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/compile_doxygen.bat b/Core/Libraries/Source/debug/compile_doxygen.bat similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/compile_doxygen.bat rename to Core/Libraries/Source/debug/compile_doxygen.bat diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug.cpp b/Core/Libraries/Source/debug/debug.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug.cpp rename to Core/Libraries/Source/debug/debug.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug.dox b/Core/Libraries/Source/debug/debug.dox similarity index 99% rename from GeneralsMD/Code/Libraries/Source/debug/debug.dox rename to Core/Libraries/Source/debug/debug.dox index d0e3fc934c..7c94d69c98 100644 --- a/GeneralsMD/Code/Libraries/Source/debug/debug.dox +++ b/Core/Libraries/Source/debug/debug.dox @@ -164,7 +164,7 @@ EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES INCLUDE_PATH = INCLUDE_FILE_PATTERNS = -PREDEFINED = _DEBUG \ +PREDEFINED = RTS_DEBUG \ DOXYGEN EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug.h b/Core/Libraries/Source/debug/debug.h similarity index 86% rename from GeneralsMD/Code/Libraries/Source/debug/debug.h rename to Core/Libraries/Source/debug/debug.h index 75d94495c8..f353fe3e3b 100644 --- a/GeneralsMD/Code/Libraries/Source/debug/debug.h +++ b/Core/Libraries/Source/debug/debug.h @@ -36,9 +36,9 @@ \page lib_var Library variants Generally speaking there are four different library variants: - - Internal: all asserts/checks/logs, full optimizations (_INTERNAL macro defined) - - %Debug: all asserts/checks/logs, no optimizations (_DEBUG macro defined) - - Profile: all asserts/checks/logs, full optimizations, profiling active (_PROFILE macro defined) + - Internal: all asserts/checks/logs, full optimizations (RTS_INTERNAL macro defined) + - %Debug: all asserts/checks/logs, no optimizations (RTS_DEBUG macro defined) + - Profile: all asserts/checks/logs, full optimizations, profiling active (RTS_PROFILE macro defined) - Release: no asserts/checks/logs, full optimizations These variants will be broken down into separate features which @@ -84,21 +84,21 @@ - Release: XXX.lib */ -#if defined(_DEBUG) && defined(_INTERNAL) - #error "Only either _DEBUG or _INTERNAL should ever be defined" +#if defined(RTS_DEBUG) && defined(RTS_INTERNAL) + #error "Only either RTS_DEBUG or RTS_INTERNAL should ever be defined" #endif // Define which libraries to use. -#if defined(_INTERNAL) || defined(_DEBUG) || defined(_PROFILE) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) || defined(RTS_PROFILE) # define HAS_ASSERTS # define HAS_LOGS #endif -#if !defined(_DEBUG) +#if !defined(RTS_DEBUG) # define HAS_OPT #endif -#if defined(_PROFILE) +#if defined(RTS_PROFILE) # define HAS_PROFILE #endif diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_cmd.cpp b/Core/Libraries/Source/debug/debug_cmd.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_cmd.cpp rename to Core/Libraries/Source/debug/debug_cmd.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_cmd.h b/Core/Libraries/Source/debug/debug_cmd.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_cmd.h rename to Core/Libraries/Source/debug/debug_cmd.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp b/Core/Libraries/Source/debug/debug_debug.cpp similarity index 99% rename from GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp rename to Core/Libraries/Source/debug/debug_debug.cpp index f0f1edd608..3bf0b5ab83 100644 --- a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp +++ b/Core/Libraries/Source/debug/debug_debug.cpp @@ -1437,11 +1437,11 @@ void Debug::WriteBuildInfo(void) (*this) << " " << m_version; if (*m_intVersion) (*this) << " internal " << m_intVersion; - #if defined(_INTERNAL) + #if defined(RTS_INTERNAL) operator<<(" internal"); - #elif defined(_DEBUG) + #elif defined(RTS_DEBUG) operator<<(" debug"); - #elif defined(_PROFILE) + #elif defined(RTS_PROFILE) operator<<(" profile"); #else operator<<(" release"); diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.h b/Core/Libraries/Source/debug/debug_debug.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_debug.h rename to Core/Libraries/Source/debug/debug_debug.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_dlg/debug_dlg.cpp b/Core/Libraries/Source/debug/debug_dlg/debug_dlg.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_dlg/debug_dlg.cpp rename to Core/Libraries/Source/debug/debug_dlg/debug_dlg.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_dlg/debug_dlg.rc b/Core/Libraries/Source/debug/debug_dlg/debug_dlg.rc similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_dlg/debug_dlg.rc rename to Core/Libraries/Source/debug/debug_dlg/debug_dlg.rc diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_dlg/resource.h b/Core/Libraries/Source/debug/debug_dlg/resource.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_dlg/resource.h rename to Core/Libraries/Source/debug/debug_dlg/resource.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_doc.h b/Core/Libraries/Source/debug/debug_doc.h similarity index 99% rename from GeneralsMD/Code/Libraries/Source/debug/debug_doc.h rename to Core/Libraries/Source/debug/debug_doc.h index f3d5c2e544..229dfe06ee 100644 --- a/GeneralsMD/Code/Libraries/Source/debug/debug_doc.h +++ b/Core/Libraries/Source/debug/debug_doc.h @@ -332,7 +332,7 @@ void test(const Point2D &val) DASSERT_MSG( val.x>=0 && val.y>=0, val << " is invalid"); } \endcode - Please note that all these operators should not be cluttered with any #ifdef _DEBUG + Please note that all these operators should not be cluttered with any #ifdef RTS_DEBUG or similar conditional compile statements. It is not necessary to remove these operators from the code in release builds (just don't forget to add 'inline' before the operator though). diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_except.cpp b/Core/Libraries/Source/debug/debug_except.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_except.cpp rename to Core/Libraries/Source/debug/debug_except.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_getdefaultcommands.cpp b/Core/Libraries/Source/debug/debug_getdefaultcommands.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_getdefaultcommands.cpp rename to Core/Libraries/Source/debug/debug_getdefaultcommands.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_internal.cpp b/Core/Libraries/Source/debug/debug_internal.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_internal.cpp rename to Core/Libraries/Source/debug/debug_internal.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_io.h b/Core/Libraries/Source/debug/debug_io.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_io.h rename to Core/Libraries/Source/debug/debug_io.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_io_con.cpp b/Core/Libraries/Source/debug/debug_io_con.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_io_con.cpp rename to Core/Libraries/Source/debug/debug_io_con.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_io_flat.cpp b/Core/Libraries/Source/debug/debug_io_flat.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_io_flat.cpp rename to Core/Libraries/Source/debug/debug_io_flat.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_io_net.cpp b/Core/Libraries/Source/debug/debug_io_net.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_io_net.cpp rename to Core/Libraries/Source/debug/debug_io_net.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_io_ods.cpp b/Core/Libraries/Source/debug/debug_io_ods.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_io_ods.cpp rename to Core/Libraries/Source/debug/debug_io_ods.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_macro.h b/Core/Libraries/Source/debug/debug_macro.h similarity index 97% rename from GeneralsMD/Code/Libraries/Source/debug/debug_macro.h rename to Core/Libraries/Source/debug/debug_macro.h index 89f863daa3..aca31f80c8 100644 --- a/GeneralsMD/Code/Libraries/Source/debug/debug_macro.h +++ b/Core/Libraries/Source/debug/debug_macro.h @@ -45,7 +45,7 @@ This module defines a number of macros. Usually only these macros should be used to access any debug functionality. - All these macros are defined if either _DEBUG or _INTERNAL is defined. Otherwise + All these macros are defined if either RTS_DEBUG or RTS_INTERNAL is defined. Otherwise all of them (with the exception of DCHECK and DCHECK_MSG) will be removed. */ ///@{ @@ -57,7 +57,7 @@ returns false. The user will then have the choice of aborting the program, continuing once or continuing with completely ignoring that specific assertion. - Assertions are completely removed if neither _DEBUG nor _INTERNAL are defined. + Assertions are completely removed if neither RTS_DEBUG nor RTS_INTERNAL are defined. \param expr expression, trigger assert window if false */ @@ -73,7 +73,7 @@ \endcode For more information see the \ref debug_stream page. - Assertions are completely removed if neither _DEBUG nor _INTERNAL are defined. + Assertions are completely removed if neither RTS_DEBUG nor RTS_INTERNAL are defined. \param expr expression, trigger assert window if false \param msg custom message stream, see \ref debug_stream @@ -282,7 +282,7 @@ DFAIL_IF_MSG(!ptrval,"pointer must not be NULL") return; ///@} -#elif defined(_DEBUG) || defined(_INTERNAL) +#elif defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define DASSERT(expr) \ ((void)( Debug::SkipNext() || \ diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_purecall.cpp b/Core/Libraries/Source/debug/debug_purecall.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_purecall.cpp rename to Core/Libraries/Source/debug/debug_purecall.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.cpp b/Core/Libraries/Source/debug/debug_stack.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_stack.cpp rename to Core/Libraries/Source/debug/debug_stack.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.h b/Core/Libraries/Source/debug/debug_stack.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_stack.h rename to Core/Libraries/Source/debug/debug_stack.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.inl b/Core/Libraries/Source/debug/debug_stack.inl similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/debug_stack.inl rename to Core/Libraries/Source/debug/debug_stack.inl diff --git a/GeneralsMD/Code/Libraries/Source/debug/internal.h b/Core/Libraries/Source/debug/internal.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/internal.h rename to Core/Libraries/Source/debug/internal.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/internal_except.h b/Core/Libraries/Source/debug/internal_except.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/internal_except.h rename to Core/Libraries/Source/debug/internal_except.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/internal_io.h b/Core/Libraries/Source/debug/internal_io.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/internal_io.h rename to Core/Libraries/Source/debug/internal_io.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/netserv/netserv.cpp b/Core/Libraries/Source/debug/netserv/netserv.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/netserv/netserv.cpp rename to Core/Libraries/Source/debug/netserv/netserv.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/rc_exception.inl b/Core/Libraries/Source/debug/rc_exception.inl similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/rc_exception.inl rename to Core/Libraries/Source/debug/rc_exception.inl diff --git a/GeneralsMD/Code/Libraries/Source/debug/test1/test1.cpp b/Core/Libraries/Source/debug/test1/test1.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test1/test1.cpp rename to Core/Libraries/Source/debug/test1/test1.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/test2/StdAfx.cpp b/Core/Libraries/Source/debug/test2/StdAfx.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test2/StdAfx.cpp rename to Core/Libraries/Source/debug/test2/StdAfx.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/test2/StdAfx.h b/Core/Libraries/Source/debug/test2/StdAfx.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test2/StdAfx.h rename to Core/Libraries/Source/debug/test2/StdAfx.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/test2/default.dbgcmd b/Core/Libraries/Source/debug/test2/default.dbgcmd similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test2/default.dbgcmd rename to Core/Libraries/Source/debug/test2/default.dbgcmd diff --git a/GeneralsMD/Code/Libraries/Source/debug/test2/resource.h b/Core/Libraries/Source/debug/test2/resource.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test2/resource.h rename to Core/Libraries/Source/debug/test2/resource.h diff --git a/GeneralsMD/Code/Libraries/Source/debug/test2/test2.cpp b/Core/Libraries/Source/debug/test2/test2.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test2/test2.cpp rename to Core/Libraries/Source/debug/test2/test2.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/test2/test2.rc b/Core/Libraries/Source/debug/test2/test2.rc similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test2/test2.rc rename to Core/Libraries/Source/debug/test2/test2.rc diff --git a/GeneralsMD/Code/Libraries/Source/debug/test3/test3.cpp b/Core/Libraries/Source/debug/test3/test3.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test3/test3.cpp rename to Core/Libraries/Source/debug/test3/test3.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/test4/test4.cpp b/Core/Libraries/Source/debug/test4/test4.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test4/test4.cpp rename to Core/Libraries/Source/debug/test4/test4.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/test5/test5.cpp b/Core/Libraries/Source/debug/test5/test5.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test5/test5.cpp rename to Core/Libraries/Source/debug/test5/test5.cpp diff --git a/GeneralsMD/Code/Libraries/Source/debug/test6/test6.cpp b/Core/Libraries/Source/debug/test6/test6.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/debug/test6/test6.cpp rename to Core/Libraries/Source/debug/test6/test6.cpp diff --git a/GeneralsMD/Code/Libraries/Source/profile/CMakeLists.txt b/Core/Libraries/Source/profile/CMakeLists.txt similarity index 64% rename from GeneralsMD/Code/Libraries/Source/profile/CMakeLists.txt rename to Core/Libraries/Source/profile/CMakeLists.txt index 4bea240d26..bad4e7f94c 100644 --- a/GeneralsMD/Code/Libraries/Source/profile/CMakeLists.txt +++ b/Core/Libraries/Source/profile/CMakeLists.txt @@ -18,15 +18,15 @@ set(PROFILE_SRC "profile.h" ) -add_library(z_profile STATIC) +add_library(core_profile STATIC) -target_sources(z_profile PRIVATE ${PROFILE_SRC}) +target_sources(core_profile PRIVATE ${PROFILE_SRC}) -target_include_directories(z_profile INTERFACE - . +target_include_directories(core_profile INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR} ) -target_link_libraries(z_profile PRIVATE +target_link_libraries(core_profile PRIVATE core_config - zi_always + corei_always ) diff --git a/GeneralsMD/Code/Libraries/Source/profile/_pch.cpp b/Core/Libraries/Source/profile/_pch.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/_pch.cpp rename to Core/Libraries/Source/profile/_pch.cpp diff --git a/GeneralsMD/Code/Libraries/Source/profile/_pch.h b/Core/Libraries/Source/profile/_pch.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/_pch.h rename to Core/Libraries/Source/profile/_pch.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/compile_doxygen.bat b/Core/Libraries/Source/profile/compile_doxygen.bat similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/compile_doxygen.bat rename to Core/Libraries/Source/profile/compile_doxygen.bat diff --git a/GeneralsMD/Code/Libraries/Source/profile/internal.h b/Core/Libraries/Source/profile/internal.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/internal.h rename to Core/Libraries/Source/profile/internal.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/internal_cmd.h b/Core/Libraries/Source/profile/internal_cmd.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/internal_cmd.h rename to Core/Libraries/Source/profile/internal_cmd.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/internal_funclevel.h b/Core/Libraries/Source/profile/internal_funclevel.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/internal_funclevel.h rename to Core/Libraries/Source/profile/internal_funclevel.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/internal_highlevel.h b/Core/Libraries/Source/profile/internal_highlevel.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/internal_highlevel.h rename to Core/Libraries/Source/profile/internal_highlevel.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/internal_result.h b/Core/Libraries/Source/profile/internal_result.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/internal_result.h rename to Core/Libraries/Source/profile/internal_result.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile.cpp b/Core/Libraries/Source/profile/profile.cpp similarity index 98% rename from GeneralsMD/Code/Libraries/Source/profile/profile.cpp rename to Core/Libraries/Source/profile/profile.cpp index c1114ad591..1e65d6b926 100644 --- a/GeneralsMD/Code/Libraries/Source/profile/profile.cpp +++ b/Core/Libraries/Source/profile/profile.cpp @@ -197,7 +197,7 @@ void Profile::StartRange(const char *range) if (active) { -#ifdef _PROFILE +#ifdef RTS_PROFILE m_frameNames[k].funcIndex=ProfileFuncLevelTracer::FrameStart(); DASSERT(m_frameNames[k].funcIndex>=0); #endif @@ -248,7 +248,7 @@ void Profile::AppendRange(const char *range) if (active) { -#ifdef _PROFILE +#ifdef RTS_PROFILE m_frameNames[k].funcIndex=ProfileFuncLevelTracer::FrameStart(); DASSERT(m_frameNames[k].funcIndex>=0); #endif @@ -279,7 +279,7 @@ void Profile::StopRange(const char *range) // stop recording m_frameNames[k].isRecording=false; if ( -#ifdef _PROFILE +#ifdef RTS_PROFILE m_frameNames[k].funcIndex>=0 || #endif m_frameNames[k].highIndex>=0 @@ -298,7 +298,7 @@ void Profile::StopRange(const char *range) } else atIndex=m_frameNames[k].lastGlobalIndex; -#ifdef _PROFILE +#ifdef RTS_PROFILE if (m_frameNames[k].funcIndex>=0) ProfileFuncLevelTracer::FrameEnd(m_frameNames[k].funcIndex,atIndex); if (m_frameNames[k].highIndex>=0) @@ -327,7 +327,7 @@ const char *Profile::GetFrameName(unsigned frame) void Profile::ClearTotals(void) { -#ifdef _PROFILE +#ifdef RTS_PROFILE ProfileFuncLevelTracer::ClearTotals(); #endif ProfileId::ClearTotals(); @@ -370,7 +370,7 @@ bool Profile::SimpleMatch(const char *str, const char *pattern) static void ProfileShutdown(void) { -#ifdef _PROFILE +#ifdef RTS_PROFILE ProfileFuncLevelTracer::Shutdown(); #endif ProfileId::Shutdown(); diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile.dox b/Core/Libraries/Source/profile/profile.dox similarity index 99% rename from GeneralsMD/Code/Libraries/Source/profile/profile.dox rename to Core/Libraries/Source/profile/profile.dox index 0e24e6b828..8f004994c8 100644 --- a/GeneralsMD/Code/Libraries/Source/profile/profile.dox +++ b/Core/Libraries/Source/profile/profile.dox @@ -164,7 +164,7 @@ EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES INCLUDE_PATH = INCLUDE_FILE_PATTERNS = -PREDEFINED = _DEBUG \ +PREDEFINED = RTS_DEBUG \ DOXYGEN EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile.h b/Core/Libraries/Source/profile/profile.h similarity index 97% rename from GeneralsMD/Code/Libraries/Source/profile/profile.h rename to Core/Libraries/Source/profile/profile.h index f31b654b40..d1c6fccb17 100644 --- a/GeneralsMD/Code/Libraries/Source/profile/profile.h +++ b/Core/Libraries/Source/profile/profile.h @@ -32,8 +32,8 @@ #ifndef PROFILE_H // Include guard #define PROFILE_H -#if defined(_DEBUG) && defined(_INTERNAL) - #error "Only either _DEBUG or _INTERNAL should ever be defined" +#if defined(RTS_DEBUG) && defined(RTS_INTERNAL) + #error "Only either RTS_DEBUG or RTS_INTERNAL should ever be defined" #endif // include all our public header files (use double quotes here) diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_cmd.cpp b/Core/Libraries/Source/profile/profile_cmd.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_cmd.cpp rename to Core/Libraries/Source/profile/profile_cmd.cpp diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_doc.h b/Core/Libraries/Source/profile/profile_doc.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_doc.h rename to Core/Libraries/Source/profile/profile_doc.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_funclevel.cpp b/Core/Libraries/Source/profile/profile_funclevel.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_funclevel.cpp rename to Core/Libraries/Source/profile/profile_funclevel.cpp diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_funclevel.h b/Core/Libraries/Source/profile/profile_funclevel.h similarity index 98% rename from GeneralsMD/Code/Libraries/Source/profile/profile_funclevel.h rename to Core/Libraries/Source/profile/profile_funclevel.h index 252f65a80a..8736cf8037 100644 --- a/GeneralsMD/Code/Libraries/Source/profile/profile_funclevel.h +++ b/Core/Libraries/Source/profile/profile_funclevel.h @@ -36,7 +36,7 @@ \brief The function level profiler. Note that this class exists even if the current build configuration - is not _PROFILE. In these cases all calls will simply return + is not RTS_PROFILE. In these cases all calls will simply return empty data. */ class ProfileFuncLevel diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_highlevel.cpp b/Core/Libraries/Source/profile/profile_highlevel.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_highlevel.cpp rename to Core/Libraries/Source/profile/profile_highlevel.cpp diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_highlevel.h b/Core/Libraries/Source/profile/profile_highlevel.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_highlevel.h rename to Core/Libraries/Source/profile/profile_highlevel.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_priv.dox b/Core/Libraries/Source/profile/profile_priv.dox similarity index 99% rename from GeneralsMD/Code/Libraries/Source/profile/profile_priv.dox rename to Core/Libraries/Source/profile/profile_priv.dox index 81f4b8e73a..ab3f256207 100644 --- a/GeneralsMD/Code/Libraries/Source/profile/profile_priv.dox +++ b/Core/Libraries/Source/profile/profile_priv.dox @@ -164,7 +164,7 @@ EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES INCLUDE_PATH = INCLUDE_FILE_PATTERNS = -PREDEFINED = _DEBUG \ +PREDEFINED = RTS_DEBUG \ DOXYGEN EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_result.cpp b/Core/Libraries/Source/profile/profile_result.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_result.cpp rename to Core/Libraries/Source/profile/profile_result.cpp diff --git a/GeneralsMD/Code/Libraries/Source/profile/profile_result.h b/Core/Libraries/Source/profile/profile_result.h similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/profile_result.h rename to Core/Libraries/Source/profile/profile_result.h diff --git a/GeneralsMD/Code/Libraries/Source/profile/test1/test1.cpp b/Core/Libraries/Source/profile/test1/test1.cpp similarity index 100% rename from GeneralsMD/Code/Libraries/Source/profile/test1/test1.cpp rename to Core/Libraries/Source/profile/test1/test1.cpp diff --git a/Generals/Code/Tools/Autorun/ARButton_Reg.bmp b/Core/Tools/Autorun/ARButton_Reg.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/ARButton_Reg.bmp rename to Core/Tools/Autorun/ARButton_Reg.bmp diff --git a/Generals/Code/Tools/Autorun/ARButton_Sel.bmp b/Core/Tools/Autorun/ARButton_Sel.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/ARButton_Sel.bmp rename to Core/Tools/Autorun/ARButton_Sel.bmp diff --git a/GeneralsMD/Code/Tools/Autorun/ARGS.CPP b/Core/Tools/Autorun/ARGS.CPP similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/ARGS.CPP rename to Core/Tools/Autorun/ARGS.CPP diff --git a/GeneralsMD/Code/Tools/Autorun/ARGS.H b/Core/Tools/Autorun/ARGS.H similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/ARGS.H rename to Core/Tools/Autorun/ARGS.H diff --git a/GeneralsMD/Code/Tools/Autorun/AUTORUN.RC b/Core/Tools/Autorun/AUTORUN.RC similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/AUTORUN.RC rename to Core/Tools/Autorun/AUTORUN.RC index d86646e654..1d68dc9e0c 100644 --- a/GeneralsMD/Code/Tools/Autorun/AUTORUN.RC +++ b/Core/Tools/Autorun/AUTORUN.RC @@ -8,6 +8,7 @@ // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" + ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS @@ -216,7 +217,7 @@ VERSIONINFO_1 VERSIONINFO FILEVERSION 1,0,0,0 PRODUCTVERSION 1,0,0,0 FILEFLAGSMASK 0x0L -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/Generals/Code/Tools/Autorun/AutoRun_Frn.bmp b/Core/Tools/Autorun/AutoRun_Frn.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/AutoRun_Frn.bmp rename to Core/Tools/Autorun/AutoRun_Frn.bmp diff --git a/Generals/Code/Tools/Autorun/AutoRun_Ger.bmp b/Core/Tools/Autorun/AutoRun_Ger.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/AutoRun_Ger.bmp rename to Core/Tools/Autorun/AutoRun_Ger.bmp diff --git a/Generals/Code/Tools/Autorun/Autorun.ICO b/Core/Tools/Autorun/Autorun.ICO similarity index 100% rename from Generals/Code/Tools/Autorun/Autorun.ICO rename to Core/Tools/Autorun/Autorun.ICO diff --git a/Generals/Code/Tools/Autorun/Autorun_BG.bmp b/Core/Tools/Autorun/Autorun_BG.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/Autorun_BG.bmp rename to Core/Tools/Autorun/Autorun_BG.bmp diff --git a/Generals/Code/Tools/Autorun/Bullet.bmp b/Core/Tools/Autorun/Bullet.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/Bullet.bmp rename to Core/Tools/Autorun/Bullet.bmp diff --git a/Generals/Code/Tools/Autorun/CDCNTRL.CPP b/Core/Tools/Autorun/CDCNTRL.CPP similarity index 99% rename from Generals/Code/Tools/Autorun/CDCNTRL.CPP rename to Core/Tools/Autorun/CDCNTRL.CPP index a8185a0495..3124c2ffce 100644 --- a/Generals/Code/Tools/Autorun/CDCNTRL.CPP +++ b/Core/Tools/Autorun/CDCNTRL.CPP @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals(tm) +** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify diff --git a/GeneralsMD/Code/Tools/Autorun/CDCNTRL.H b/Core/Tools/Autorun/CDCNTRL.H similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/CDCNTRL.H rename to Core/Tools/Autorun/CDCNTRL.H diff --git a/Core/Tools/Autorun/CMakeLists.txt b/Core/Tools/Autorun/CMakeLists.txt new file mode 100644 index 0000000000..73f0f8965e --- /dev/null +++ b/Core/Tools/Autorun/CMakeLists.txt @@ -0,0 +1,62 @@ +set(AUTORUN_SRC + "ARGS.CPP" + "ARGS.H" + "autorun.cpp" + "autorun.h" + "CallbackHook.h" + "CDCNTRL.CPP" + "CDCNTRL.H" + "DrawButton.cpp" + "DrawButton.h" + "EZGIMEX.cpp" + "GameText.cpp" + "GameText.h" + "GETCD.CPP" + "GetCD.h" + "gimex.h" + "IGR.cpp" + "IGR.h" + "Jsupport.cpp" + "JSUPPORT.H" + "leanAndMeanAutorun.h" + "Locale_API.cpp" + "Locale_API.h" + "locale.cpp" + "locale.h" + "POINT.h" + "RECT.h" + "resource.h" + "TTFont.cpp" + "TTFont.h" + "Utils.cpp" + "Utils.h" + "ViewHTML.cpp" + "ViewHTML.h" + "WinFix.CPP" + "WinFix.H" + "Wnd_file.cpp" + "Wnd_File.h" + "WSYS_File.cpp" + "WSYS_file.h" + "WSYS_FileSystem.cpp" + "WSYS_FileSystem.h" + "WSYS_RAMFile.cpp" + "WSYS_RAMFile.h" + "WSYS_StdFile.cpp" + "WSYS_StdFile.h" + "WSYS_StdFileSystem.cpp" + "WSYS_StdFileSystem.h" +) + +add_library(corei_autorun INTERFACE) + +target_sources(corei_autorun INTERFACE ${AUTORUN_SRC}) + +target_link_libraries(corei_autorun INTERFACE + core_config + winmm +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(corei_autorun INTERFACE AUTORUN.RC) +endif() diff --git a/GeneralsMD/Code/Tools/Autorun/CallbackHook.h b/Core/Tools/Autorun/CallbackHook.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/CallbackHook.h rename to Core/Tools/Autorun/CallbackHook.h diff --git a/GeneralsMD/Code/Tools/Autorun/DrawButton.cpp b/Core/Tools/Autorun/DrawButton.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/DrawButton.cpp rename to Core/Tools/Autorun/DrawButton.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/DrawButton.h b/Core/Tools/Autorun/DrawButton.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/DrawButton.h rename to Core/Tools/Autorun/DrawButton.h diff --git a/GeneralsMD/Code/Tools/Autorun/EZGIMEX.cpp b/Core/Tools/Autorun/EZGIMEX.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/EZGIMEX.cpp rename to Core/Tools/Autorun/EZGIMEX.cpp diff --git a/Generals/Code/Tools/Autorun/mouse.wav b/Core/Tools/Autorun/English/Present.wav similarity index 100% rename from Generals/Code/Tools/Autorun/mouse.wav rename to Core/Tools/Autorun/English/Present.wav diff --git a/GeneralsMD/Code/Tools/Autorun/mouse.wav b/Core/Tools/Autorun/English/Rock-n-Roll.wav similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/mouse.wav rename to Core/Tools/Autorun/English/Rock-n-Roll.wav diff --git a/GeneralsMD/Code/Tools/Autorun/GETCD.CPP b/Core/Tools/Autorun/GETCD.CPP similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/GETCD.CPP rename to Core/Tools/Autorun/GETCD.CPP index 9263186d06..71792aa3c9 100644 --- a/GeneralsMD/Code/Tools/Autorun/GETCD.CPP +++ b/Core/Tools/Autorun/GETCD.CPP @@ -206,7 +206,7 @@ int GetCDClass::Get_CD_Drive_For_This_Volume ( const char *volume_label ) } else { -#if _DEBUG +#if RTS_DEBUG LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | diff --git a/GeneralsMD/Code/Tools/Autorun/GameText.cpp b/Core/Tools/Autorun/GameText.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/GameText.cpp rename to Core/Tools/Autorun/GameText.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/GameText.h b/Core/Tools/Autorun/GameText.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/GameText.h rename to Core/Tools/Autorun/GameText.h diff --git a/GeneralsMD/Code/Tools/Autorun/GetCD.h b/Core/Tools/Autorun/GetCD.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/GetCD.h rename to Core/Tools/Autorun/GetCD.h diff --git a/GeneralsMD/Code/Tools/Autorun/IGR.cpp b/Core/Tools/Autorun/IGR.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/IGR.cpp rename to Core/Tools/Autorun/IGR.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/IGR.h b/Core/Tools/Autorun/IGR.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/IGR.h rename to Core/Tools/Autorun/IGR.h diff --git a/GeneralsMD/Code/Tools/Autorun/JSUPPORT.H b/Core/Tools/Autorun/JSUPPORT.H similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/JSUPPORT.H rename to Core/Tools/Autorun/JSUPPORT.H diff --git a/GeneralsMD/Code/Tools/Autorun/Jsupport.cpp b/Core/Tools/Autorun/Jsupport.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/Jsupport.cpp rename to Core/Tools/Autorun/Jsupport.cpp diff --git a/Generals/Code/Tools/Autorun/License French.bmp b/Core/Tools/Autorun/License French.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/License French.bmp rename to Core/Tools/Autorun/License French.bmp diff --git a/Generals/Code/Tools/Autorun/License French2.bmp b/Core/Tools/Autorun/License French2.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/License French2.bmp rename to Core/Tools/Autorun/License French2.bmp diff --git a/Generals/Code/Tools/Autorun/License German.bmp b/Core/Tools/Autorun/License German.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/License German.bmp rename to Core/Tools/Autorun/License German.bmp diff --git a/Generals/Code/Tools/Autorun/License German2.bmp b/Core/Tools/Autorun/License German2.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/License German2.bmp rename to Core/Tools/Autorun/License German2.bmp diff --git a/Generals/Code/Tools/Autorun/License USA.bmp b/Core/Tools/Autorun/License USA.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/License USA.bmp rename to Core/Tools/Autorun/License USA.bmp diff --git a/Generals/Code/Tools/Autorun/License USA2.bmp b/Core/Tools/Autorun/License USA2.bmp similarity index 100% rename from Generals/Code/Tools/Autorun/License USA2.bmp rename to Core/Tools/Autorun/License USA2.bmp diff --git a/GeneralsMD/Code/Tools/Autorun/Locale_API.cpp b/Core/Tools/Autorun/Locale_API.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/Locale_API.cpp rename to Core/Tools/Autorun/Locale_API.cpp index de1a27a120..873674f4c6 100644 --- a/GeneralsMD/Code/Tools/Autorun/Locale_API.cpp +++ b/Core/Tools/Autorun/Locale_API.cpp @@ -265,7 +265,7 @@ int Locale_Init ( int language, char *file ) LanguageID = 0; -#if(_DEBUG) +#if(RTS_DEBUG) switch( LanguageID ) { case 6: CodePage = 932; diff --git a/GeneralsMD/Code/Tools/Autorun/Locale_API.h b/Core/Tools/Autorun/Locale_API.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/Locale_API.h rename to Core/Tools/Autorun/Locale_API.h diff --git a/GeneralsMD/Code/Tools/Autorun/POINT.h b/Core/Tools/Autorun/POINT.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/POINT.h rename to Core/Tools/Autorun/POINT.h diff --git a/GeneralsMD/Code/Tools/Autorun/RECT.h b/Core/Tools/Autorun/RECT.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/RECT.h rename to Core/Tools/Autorun/RECT.h diff --git a/GeneralsMD/Code/Tools/Autorun/TTFont.cpp b/Core/Tools/Autorun/TTFont.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/TTFont.cpp rename to Core/Tools/Autorun/TTFont.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/TTFont.h b/Core/Tools/Autorun/TTFont.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/TTFont.h rename to Core/Tools/Autorun/TTFont.h diff --git a/GeneralsMD/Code/Tools/Autorun/Utils.cpp b/Core/Tools/Autorun/Utils.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/Utils.cpp rename to Core/Tools/Autorun/Utils.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/Utils.h b/Core/Tools/Autorun/Utils.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/Utils.h rename to Core/Tools/Autorun/Utils.h diff --git a/GeneralsMD/Code/Tools/Autorun/ViewHTML.cpp b/Core/Tools/Autorun/ViewHTML.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/ViewHTML.cpp rename to Core/Tools/Autorun/ViewHTML.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/ViewHTML.h b/Core/Tools/Autorun/ViewHTML.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/ViewHTML.h rename to Core/Tools/Autorun/ViewHTML.h diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_File.cpp b/Core/Tools/Autorun/WSYS_File.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_File.cpp rename to Core/Tools/Autorun/WSYS_File.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_FileSystem.cpp b/Core/Tools/Autorun/WSYS_FileSystem.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_FileSystem.cpp rename to Core/Tools/Autorun/WSYS_FileSystem.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_FileSystem.h b/Core/Tools/Autorun/WSYS_FileSystem.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_FileSystem.h rename to Core/Tools/Autorun/WSYS_FileSystem.h diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_RAMFile.cpp b/Core/Tools/Autorun/WSYS_RAMFile.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_RAMFile.cpp rename to Core/Tools/Autorun/WSYS_RAMFile.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_RAMFile.h b/Core/Tools/Autorun/WSYS_RAMFile.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_RAMFile.h rename to Core/Tools/Autorun/WSYS_RAMFile.h diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_StdFile.cpp b/Core/Tools/Autorun/WSYS_StdFile.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_StdFile.cpp rename to Core/Tools/Autorun/WSYS_StdFile.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_StdFile.h b/Core/Tools/Autorun/WSYS_StdFile.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_StdFile.h rename to Core/Tools/Autorun/WSYS_StdFile.h diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_StdFileSystem.cpp b/Core/Tools/Autorun/WSYS_StdFileSystem.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_StdFileSystem.cpp rename to Core/Tools/Autorun/WSYS_StdFileSystem.cpp diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_StdFileSystem.h b/Core/Tools/Autorun/WSYS_StdFileSystem.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_StdFileSystem.h rename to Core/Tools/Autorun/WSYS_StdFileSystem.h diff --git a/GeneralsMD/Code/Tools/Autorun/WSYS_file.h b/Core/Tools/Autorun/WSYS_file.h similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WSYS_file.h rename to Core/Tools/Autorun/WSYS_file.h diff --git a/GeneralsMD/Code/Tools/Autorun/WinFix.CPP b/Core/Tools/Autorun/WinFix.CPP similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/WinFix.CPP rename to Core/Tools/Autorun/WinFix.CPP index 3ddc01d047..c5a9d89b45 100644 --- a/GeneralsMD/Code/Tools/Autorun/WinFix.CPP +++ b/Core/Tools/Autorun/WinFix.CPP @@ -185,7 +185,7 @@ WindowsVersionInfo::WindowsVersionInfo(void) : // } else { - #if( _DEBUG ) + #if( RTS_DEBUG ) HKEY hKey; char szProductType[80]; DWORD dwBufLen; @@ -239,7 +239,7 @@ WindowsVersionInfo::WindowsVersionInfo(void) : //-------------------------------------------------------------------------- // Send all info found to the debug output file. //-------------------------------------------------------------------------- -#if ( _DEBUG ) +#if ( RTS_DEBUG ) Msg( __LINE__, __FILE__, "MajorVersionNumber = %d", MajorVersionNumber ); Msg( __LINE__, __FILE__, "MinorVersionNumber = %d", MinorVersionNumber ); Msg( __LINE__, __FILE__, "WindowsVersion = %d", WindowsVersion ); diff --git a/GeneralsMD/Code/Tools/Autorun/WinFix.H b/Core/Tools/Autorun/WinFix.H similarity index 100% rename from GeneralsMD/Code/Tools/Autorun/WinFix.H rename to Core/Tools/Autorun/WinFix.H diff --git a/GeneralsMD/Code/Tools/Autorun/Wnd_File.h b/Core/Tools/Autorun/Wnd_File.h similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/Wnd_File.h rename to Core/Tools/Autorun/Wnd_File.h index af127ce85c..90b5db308b 100644 --- a/GeneralsMD/Code/Tools/Autorun/Wnd_File.h +++ b/Core/Tools/Autorun/Wnd_File.h @@ -94,7 +94,7 @@ -#ifdef _DEBUG +#ifdef RTS_DEBUG void __cdecl Msg( int line, const char *file, const char *fmt, ... ); void __cdecl Msg( int line, const char *filename, const wchar_t *fmt, unsigned int codepage=1252, ... ); void Delete_Msg_File( void ); diff --git a/GeneralsMD/Code/Tools/Autorun/Wnd_file.cpp b/Core/Tools/Autorun/Wnd_file.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/Wnd_file.cpp rename to Core/Tools/Autorun/Wnd_file.cpp index b24d6f0207..a0b28974aa 100644 --- a/GeneralsMD/Code/Tools/Autorun/Wnd_file.cpp +++ b/Core/Tools/Autorun/Wnd_file.cpp @@ -83,14 +83,14 @@ char DebugFile [ MAX_PATH ] = { '\0' }; // public file class functions... //----------------------------------------------------------------------------- #if(0) -#ifndef _DEBUG +#ifndef RTS_DEBUG void __cdecl Msg( int, char *, char *, ... ) { }; // line, file, fmt void Delete_Msg_File ( void ) { }; #endif #endif -#ifdef _DEBUG +#ifdef RTS_DEBUG /**************************************************************************** * MSG -- Write Message to Debug file with line and filename. * @@ -1097,7 +1097,7 @@ HANDLE Open_File( char const *file_name, int mode ) // error! // if ( windows_file_handle == INVALID_HANDLE_VALUE ) { - // #if( _DEBUG ) + // #if( RTS_DEBUG ) // Debug_Printf( "%s: Create file error is %d\r\n", file_name, GetLastError()); // #endif return( INVALID_FILE_HANDLE ); diff --git a/Generals/Code/Tools/Autorun/arrow.cur b/Core/Tools/Autorun/arrow.cur similarity index 100% rename from Generals/Code/Tools/Autorun/arrow.cur rename to Core/Tools/Autorun/arrow.cur diff --git a/GeneralsMD/Code/Tools/Autorun/autorun.cpp b/Core/Tools/Autorun/autorun.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Autorun/autorun.cpp rename to Core/Tools/Autorun/autorun.cpp index ac8f18b8c9..100f5b515a 100644 --- a/GeneralsMD/Code/Tools/Autorun/autorun.cpp +++ b/Core/Tools/Autorun/autorun.cpp @@ -122,8 +122,6 @@ #include "Win32Device/Common/Win32BIGFileSystem.h" #endif - - //----------------------------------------------------------------------------- // DEFINES //----------------------------------------------------------------------------- @@ -316,7 +314,7 @@ const char *gAppPrefix = "ar_"; // prefix to the debug log. int FlickerPositions[ NUM_FLICKER_POSITIONS ][2]; -#if( _DEBUG ) +#if( RTS_DEBUG ) char szCDDrive[ MAX_PATH ]; #endif @@ -1010,7 +1008,7 @@ void MainWindow::Register( void ) if ( !RegisterClassEx((const WNDCLASSEX *) &wndclass ) ) { - #if(_DEBUG) + #if(RTS_DEBUG) LPVOID szMessage; FormatMessage( @@ -2474,7 +2472,7 @@ void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) ButtonList[0]->Set_State( DrawButton::FOCUS_STATE ); } -#if( _DEBUG ) +#if( RTS_DEBUG ) Msg( __LINE__, TEXT(__FILE__), TEXT("----------------------------------------------------------------------------------")); for( i=0; i #include -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/Babylon.h b/Core/Tools/Babylon/Babylon.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/Babylon.h rename to Core/Tools/Babylon/Babylon.h diff --git a/GeneralsMD/Code/Tools/Babylon/Babylon.odl b/Core/Tools/Babylon/Babylon.odl similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/Babylon.odl rename to Core/Tools/Babylon/Babylon.odl diff --git a/GeneralsMD/Code/Tools/Babylon/Babylon.rc b/Core/Tools/Babylon/Babylon.rc similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/Babylon.rc rename to Core/Tools/Babylon/Babylon.rc index bf02b942ab..8375eeb681 100644 --- a/GeneralsMD/Code/Tools/Babylon/Babylon.rc +++ b/Core/Tools/Babylon/Babylon.rc @@ -363,7 +363,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/Babylon/Babylon.reg b/Core/Tools/Babylon/Babylon.reg similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/Babylon.reg rename to Core/Tools/Babylon/Babylon.reg diff --git a/GeneralsMD/Code/Tools/Babylon/BabylonDlg.cpp b/Core/Tools/Babylon/BabylonDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/BabylonDlg.cpp rename to Core/Tools/Babylon/BabylonDlg.cpp index 99bca34e21..c89335b3e9 100644 --- a/GeneralsMD/Code/Tools/Babylon/BabylonDlg.cpp +++ b/Core/Tools/Babylon/BabylonDlg.cpp @@ -40,7 +40,7 @@ #include "ProceedDlg.h" #include "transcs.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/BabylonDlg.h b/Core/Tools/Babylon/BabylonDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/BabylonDlg.h rename to Core/Tools/Babylon/BabylonDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/CMakeLists.txt b/Core/Tools/Babylon/CMakeLists.txt similarity index 76% rename from GeneralsMD/Code/Tools/Babylon/CMakeLists.txt rename to Core/Tools/Babylon/CMakeLists.txt index 99d4b2be4b..a85ee41a72 100644 --- a/GeneralsMD/Code/Tools/Babylon/CMakeLists.txt +++ b/Core/Tools/Babylon/CMakeLists.txt @@ -51,16 +51,16 @@ set(BABYLON_SRC "XLStuff.h" ) -add_executable(z_babylon WIN32) -set_target_properties(z_babylon PROPERTIES OUTPUT_NAME babylon) +add_executable(core_babylon WIN32) +set_target_properties(core_babylon PROPERTIES OUTPUT_NAME babylon) -target_sources(z_babylon PRIVATE ${BABYLON_SRC}) +target_sources(core_babylon PRIVATE ${BABYLON_SRC}) -target_link_libraries(z_babylon PRIVATE +target_link_libraries(core_babylon PRIVATE core_config ) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_compile_definitions(z_babylon PRIVATE _AFXDLL) - target_sources(z_babylon PRIVATE Babylon.rc) + target_compile_definitions(core_babylon PRIVATE _AFXDLL) + target_sources(core_babylon PRIVATE Babylon.rc) endif() diff --git a/GeneralsMD/Code/Tools/Babylon/DlgProxy.cpp b/Core/Tools/Babylon/DlgProxy.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/DlgProxy.cpp rename to Core/Tools/Babylon/DlgProxy.cpp index 6a93458cc0..8237a7e9bb 100644 --- a/GeneralsMD/Code/Tools/Babylon/DlgProxy.cpp +++ b/Core/Tools/Babylon/DlgProxy.cpp @@ -24,7 +24,7 @@ #include "DlgProxy.h" #include "BabylonDlg.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/DlgProxy.h b/Core/Tools/Babylon/DlgProxy.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/DlgProxy.h rename to Core/Tools/Babylon/DlgProxy.h diff --git a/GeneralsMD/Code/Tools/Babylon/ExportDlg.cpp b/Core/Tools/Babylon/ExportDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/ExportDlg.cpp rename to Core/Tools/Babylon/ExportDlg.cpp index 8cb8a7b8c4..0715c7f86d 100644 --- a/GeneralsMD/Code/Tools/Babylon/ExportDlg.cpp +++ b/Core/Tools/Babylon/ExportDlg.cpp @@ -24,7 +24,7 @@ #include "ExportDlg.h" #include "direct.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/ExportDlg.h b/Core/Tools/Babylon/ExportDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/ExportDlg.h rename to Core/Tools/Babylon/ExportDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/GenerateDlg.cpp b/Core/Tools/Babylon/GenerateDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/GenerateDlg.cpp rename to Core/Tools/Babylon/GenerateDlg.cpp index 96349ce4fe..ef8382f0a9 100644 --- a/GeneralsMD/Code/Tools/Babylon/GenerateDlg.cpp +++ b/Core/Tools/Babylon/GenerateDlg.cpp @@ -24,7 +24,7 @@ #include "GenerateDlg.h" #include "direct.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/GenerateDlg.h b/Core/Tools/Babylon/GenerateDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/GenerateDlg.h rename to Core/Tools/Babylon/GenerateDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/MatchDlg.cpp b/Core/Tools/Babylon/MatchDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/MatchDlg.cpp rename to Core/Tools/Babylon/MatchDlg.cpp index 53016e4764..e0ca969937 100644 --- a/GeneralsMD/Code/Tools/Babylon/MatchDlg.cpp +++ b/Core/Tools/Babylon/MatchDlg.cpp @@ -23,7 +23,7 @@ #include "Babylon.h" #include "MatchDlg.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/MatchDlg.h b/Core/Tools/Babylon/MatchDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/MatchDlg.h rename to Core/Tools/Babylon/MatchDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/ProceedDlg.cpp b/Core/Tools/Babylon/ProceedDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/ProceedDlg.cpp rename to Core/Tools/Babylon/ProceedDlg.cpp index 047be17d55..52001f1452 100644 --- a/GeneralsMD/Code/Tools/Babylon/ProceedDlg.cpp +++ b/Core/Tools/Babylon/ProceedDlg.cpp @@ -23,7 +23,7 @@ #include "Babylon.h" #include "ProceedDlg.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/ProceedDlg.h b/Core/Tools/Babylon/ProceedDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/ProceedDlg.h rename to Core/Tools/Babylon/ProceedDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/Report.cpp b/Core/Tools/Babylon/Report.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/Report.cpp rename to Core/Tools/Babylon/Report.cpp index 9fbd81fd17..1a14acd285 100644 --- a/GeneralsMD/Code/Tools/Babylon/Report.cpp +++ b/Core/Tools/Babylon/Report.cpp @@ -24,7 +24,7 @@ #include "Report.h" #include -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/Report.h b/Core/Tools/Babylon/Report.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/Report.h rename to Core/Tools/Babylon/Report.h diff --git a/GeneralsMD/Code/Tools/Babylon/RetranslateDlg.cpp b/Core/Tools/Babylon/RetranslateDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/RetranslateDlg.cpp rename to Core/Tools/Babylon/RetranslateDlg.cpp index af9e013189..32c7945c06 100644 --- a/GeneralsMD/Code/Tools/Babylon/RetranslateDlg.cpp +++ b/Core/Tools/Babylon/RetranslateDlg.cpp @@ -23,7 +23,7 @@ #include "Babylon.h" #include "RetranslateDlg.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/RetranslateDlg.h b/Core/Tools/Babylon/RetranslateDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/RetranslateDlg.h rename to Core/Tools/Babylon/RetranslateDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/STRCHECK.PL b/Core/Tools/Babylon/STRCHECK.PL similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/STRCHECK.PL rename to Core/Tools/Babylon/STRCHECK.PL diff --git a/GeneralsMD/Code/Tools/Babylon/StdAfx.cpp b/Core/Tools/Babylon/StdAfx.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/StdAfx.cpp rename to Core/Tools/Babylon/StdAfx.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/StdAfx.h b/Core/Tools/Babylon/StdAfx.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/StdAfx.h rename to Core/Tools/Babylon/StdAfx.h diff --git a/GeneralsMD/Code/Tools/Babylon/TransDB.cpp b/Core/Tools/Babylon/TransDB.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/TransDB.cpp rename to Core/Tools/Babylon/TransDB.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/TransDB.h b/Core/Tools/Babylon/TransDB.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/TransDB.h rename to Core/Tools/Babylon/TransDB.h diff --git a/GeneralsMD/Code/Tools/Babylon/VIEWDBSII.cpp b/Core/Tools/Babylon/VIEWDBSII.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/VIEWDBSII.cpp rename to Core/Tools/Babylon/VIEWDBSII.cpp index 43dba81a90..98c051408d 100644 --- a/GeneralsMD/Code/Tools/Babylon/VIEWDBSII.cpp +++ b/Core/Tools/Babylon/VIEWDBSII.cpp @@ -23,7 +23,7 @@ #include "Babylon.h" #include "VIEWDBSII.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/VIEWDBSII.h b/Core/Tools/Babylon/VIEWDBSII.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/VIEWDBSII.h rename to Core/Tools/Babylon/VIEWDBSII.h diff --git a/GeneralsMD/Code/Tools/Babylon/VerifyDlg.cpp b/Core/Tools/Babylon/VerifyDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/VerifyDlg.cpp rename to Core/Tools/Babylon/VerifyDlg.cpp index 76a9adc3af..d1d96c1cc5 100644 --- a/GeneralsMD/Code/Tools/Babylon/VerifyDlg.cpp +++ b/Core/Tools/Babylon/VerifyDlg.cpp @@ -23,7 +23,7 @@ #include "Babylon.h" #include "VerifyDlg.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/VerifyDlg.h b/Core/Tools/Babylon/VerifyDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/VerifyDlg.h rename to Core/Tools/Babylon/VerifyDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/VerifyTextDlg.cpp b/Core/Tools/Babylon/VerifyTextDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/VerifyTextDlg.cpp rename to Core/Tools/Babylon/VerifyTextDlg.cpp index f1f710960a..3e7cae765c 100644 --- a/GeneralsMD/Code/Tools/Babylon/VerifyTextDlg.cpp +++ b/Core/Tools/Babylon/VerifyTextDlg.cpp @@ -23,7 +23,7 @@ #include "Babylon.h" #include "VerifyTextDlg.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/VerifyTextDlg.h b/Core/Tools/Babylon/VerifyTextDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/VerifyTextDlg.h rename to Core/Tools/Babylon/VerifyTextDlg.h diff --git a/GeneralsMD/Code/Tools/Babylon/ViewDBsDlg.cpp b/Core/Tools/Babylon/ViewDBsDlg.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/ViewDBsDlg.cpp rename to Core/Tools/Babylon/ViewDBsDlg.cpp index a6764ccd50..9eb3f3af5f 100644 --- a/GeneralsMD/Code/Tools/Babylon/ViewDBsDlg.cpp +++ b/Core/Tools/Babylon/ViewDBsDlg.cpp @@ -25,7 +25,7 @@ #include "VIEWDBSII.h" #include "TransDB.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/XLStuff.cpp b/Core/Tools/Babylon/XLStuff.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/XLStuff.cpp rename to Core/Tools/Babylon/XLStuff.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/XLStuff.h b/Core/Tools/Babylon/XLStuff.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/XLStuff.h rename to Core/Tools/Babylon/XLStuff.h diff --git a/GeneralsMD/Code/Tools/Babylon/bin.cpp b/Core/Tools/Babylon/bin.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/bin.cpp rename to Core/Tools/Babylon/bin.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/bin.h b/Core/Tools/Babylon/bin.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/bin.h rename to Core/Tools/Babylon/bin.h diff --git a/GeneralsMD/Code/Tools/Babylon/excel8.cpp b/Core/Tools/Babylon/excel8.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Babylon/excel8.cpp rename to Core/Tools/Babylon/excel8.cpp index 88aa3005cb..4078199d0a 100644 --- a/GeneralsMD/Code/Tools/Babylon/excel8.cpp +++ b/Core/Tools/Babylon/excel8.cpp @@ -20,7 +20,7 @@ #include "StdAfx.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/Babylon/excel8.h b/Core/Tools/Babylon/excel8.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/excel8.h rename to Core/Tools/Babylon/excel8.h diff --git a/GeneralsMD/Code/Tools/Babylon/expimp.cpp b/Core/Tools/Babylon/expimp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/expimp.cpp rename to Core/Tools/Babylon/expimp.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/expimp.h b/Core/Tools/Babylon/expimp.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/expimp.h rename to Core/Tools/Babylon/expimp.h diff --git a/GeneralsMD/Code/Tools/Babylon/fileops.cpp b/Core/Tools/Babylon/fileops.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/fileops.cpp rename to Core/Tools/Babylon/fileops.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/fileops.h b/Core/Tools/Babylon/fileops.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/fileops.h rename to Core/Tools/Babylon/fileops.h diff --git a/GeneralsMD/Code/Tools/Babylon/iff.cpp b/Core/Tools/Babylon/iff.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/iff.cpp rename to Core/Tools/Babylon/iff.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/iff.h b/Core/Tools/Babylon/iff.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/iff.h rename to Core/Tools/Babylon/iff.h diff --git a/GeneralsMD/Code/Tools/Babylon/list.cpp b/Core/Tools/Babylon/list.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/list.cpp rename to Core/Tools/Babylon/list.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/list.h b/Core/Tools/Babylon/list.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/list.h rename to Core/Tools/Babylon/list.h diff --git a/GeneralsMD/Code/Tools/Babylon/loadsave.cpp b/Core/Tools/Babylon/loadsave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/loadsave.cpp rename to Core/Tools/Babylon/loadsave.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/loadsave.h b/Core/Tools/Babylon/loadsave.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/loadsave.h rename to Core/Tools/Babylon/loadsave.h diff --git a/GeneralsMD/Code/Tools/Babylon/olestring.cpp b/Core/Tools/Babylon/olestring.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/olestring.cpp rename to Core/Tools/Babylon/olestring.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/olestring.h b/Core/Tools/Babylon/olestring.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/olestring.h rename to Core/Tools/Babylon/olestring.h diff --git a/GeneralsMD/Code/Tools/Babylon/res/Babylon.ico b/Core/Tools/Babylon/res/Babylon.ico similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/res/Babylon.ico rename to Core/Tools/Babylon/res/Babylon.ico diff --git a/GeneralsMD/Code/Tools/Babylon/res/Babylon.rc2 b/Core/Tools/Babylon/res/Babylon.rc2 similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/res/Babylon.rc2 rename to Core/Tools/Babylon/res/Babylon.rc2 diff --git a/Generals/Code/Tools/Babylon/res/bitmap1.bmp b/Core/Tools/Babylon/res/bitmap1.bmp similarity index 100% rename from Generals/Code/Tools/Babylon/res/bitmap1.bmp rename to Core/Tools/Babylon/res/bitmap1.bmp diff --git a/Generals/Code/Tools/Babylon/res/noxstring.ico b/Core/Tools/Babylon/res/noxstring.ico similarity index 100% rename from Generals/Code/Tools/Babylon/res/noxstring.ico rename to Core/Tools/Babylon/res/noxstring.ico diff --git a/Generals/Code/Tools/Babylon/res/noxstring.rc2 b/Core/Tools/Babylon/res/noxstring.rc2 similarity index 100% rename from Generals/Code/Tools/Babylon/res/noxstring.rc2 rename to Core/Tools/Babylon/res/noxstring.rc2 diff --git a/Generals/Code/Tools/Babylon/res/pause.bmp b/Core/Tools/Babylon/res/pause.bmp similarity index 100% rename from Generals/Code/Tools/Babylon/res/pause.bmp rename to Core/Tools/Babylon/res/pause.bmp diff --git a/Generals/Code/Tools/Babylon/res/paused.bmp b/Core/Tools/Babylon/res/paused.bmp similarity index 100% rename from Generals/Code/Tools/Babylon/res/paused.bmp rename to Core/Tools/Babylon/res/paused.bmp diff --git a/Generals/Code/Tools/Babylon/res/playd.bmp b/Core/Tools/Babylon/res/playd.bmp similarity index 100% rename from Generals/Code/Tools/Babylon/res/playd.bmp rename to Core/Tools/Babylon/res/playd.bmp diff --git a/Generals/Code/Tools/Babylon/res/playu.bmp b/Core/Tools/Babylon/res/playu.bmp similarity index 100% rename from Generals/Code/Tools/Babylon/res/playu.bmp rename to Core/Tools/Babylon/res/playu.bmp diff --git a/Generals/Code/Tools/Babylon/res/stop.bmp b/Core/Tools/Babylon/res/stop.bmp similarity index 100% rename from Generals/Code/Tools/Babylon/res/stop.bmp rename to Core/Tools/Babylon/res/stop.bmp diff --git a/GeneralsMD/Code/Tools/Babylon/resource.h b/Core/Tools/Babylon/resource.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/resource.h rename to Core/Tools/Babylon/resource.h diff --git a/Generals/Code/Tools/Babylon/resource.hm b/Core/Tools/Babylon/resource.hm similarity index 100% rename from Generals/Code/Tools/Babylon/resource.hm rename to Core/Tools/Babylon/resource.hm diff --git a/GeneralsMD/Code/Tools/Babylon/transcs.cpp b/Core/Tools/Babylon/transcs.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/transcs.cpp rename to Core/Tools/Babylon/transcs.cpp diff --git a/GeneralsMD/Code/Tools/Babylon/transcs.h b/Core/Tools/Babylon/transcs.h similarity index 100% rename from GeneralsMD/Code/Tools/Babylon/transcs.h rename to Core/Tools/Babylon/transcs.h diff --git a/Core/Tools/CMakeLists.txt b/Core/Tools/CMakeLists.txt index cb47b91e40..f2e820ad74 100644 --- a/Core/Tools/CMakeLists.txt +++ b/Core/Tools/CMakeLists.txt @@ -2,10 +2,35 @@ # Build useful tool binaries. if(RTS_BUILD_CORE_TOOLS) - # TODO: add subdirectory... + add_subdirectory(DebugWindow) endif() # Build less useful tool/test binaries. if(RTS_BUILD_CORE_EXTRAS) + add_subdirectory(assetcull) + add_subdirectory(Babylon) + add_subdirectory(buildVersionUpdate) add_subdirectory(Compress) + add_subdirectory(CRCDiff) + add_subdirectory(mangler) + add_subdirectory(matchbot) + add_subdirectory(textureCompress) + add_subdirectory(timingTest) + add_subdirectory(versionUpdate) + add_subdirectory(wolSetup) + add_subdirectory(WW3D) +endif() + +# Add library interfaces here +if(RTS_BUILD_GENERALS_TOOLS OR RTS_BUILD_ZEROHOUR_TOOLS) + add_subdirectory(ImagePacker) + add_subdirectory(MapCacheBuilder) + add_subdirectory(W3DView) +endif() + +# Add library interfaces here +if(RTS_BUILD_GENERALS_EXTRAS OR RTS_BUILD_ZEROHOUR_EXTRAS) + add_subdirectory(Autorun) + add_subdirectory(Launcher) + add_subdirectory(PATCHGET) endif() diff --git a/Core/Tools/CRCDiff/CMakeLists.txt b/Core/Tools/CRCDiff/CMakeLists.txt new file mode 100644 index 0000000000..4a01798a8e --- /dev/null +++ b/Core/Tools/CRCDiff/CMakeLists.txt @@ -0,0 +1,25 @@ +set(CRCDIFF_SRC + "CRCDiff.cpp" + "debug.cpp" + "debug.h" + "expander.cpp" + "expander.h" + "KVPair.cpp" + "KVPair.h" + "misc.h" +) + +add_executable(core_crcdiff WIN32) +set_target_properties(core_crcdiff PROPERTIES OUTPUT_NAME crcdiff) + +target_sources(core_crcdiff PRIVATE ${CRCDIFF_SRC}) + +target_link_libraries(core_crcdiff PRIVATE + core_config + core_utility + stlport +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_link_options(core_crcdiff PRIVATE /subsystem:console) +endif() diff --git a/GeneralsMD/Code/Tools/CRCDiff/CRCDiff.cpp b/Core/Tools/CRCDiff/CRCDiff.cpp similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/CRCDiff.cpp rename to Core/Tools/CRCDiff/CRCDiff.cpp diff --git a/GeneralsMD/Code/Tools/CRCDiff/KVPair.cpp b/Core/Tools/CRCDiff/KVPair.cpp similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/KVPair.cpp rename to Core/Tools/CRCDiff/KVPair.cpp diff --git a/GeneralsMD/Code/Tools/CRCDiff/KVPair.h b/Core/Tools/CRCDiff/KVPair.h similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/KVPair.h rename to Core/Tools/CRCDiff/KVPair.h diff --git a/Generals/Code/Tools/CRCDiff/bottom.html b/Core/Tools/CRCDiff/bottom.html similarity index 100% rename from Generals/Code/Tools/CRCDiff/bottom.html rename to Core/Tools/CRCDiff/bottom.html diff --git a/GeneralsMD/Code/Tools/CRCDiff/debug.cpp b/Core/Tools/CRCDiff/debug.cpp similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/debug.cpp rename to Core/Tools/CRCDiff/debug.cpp diff --git a/GeneralsMD/Code/Tools/CRCDiff/debug.h b/Core/Tools/CRCDiff/debug.h similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/debug.h rename to Core/Tools/CRCDiff/debug.h diff --git a/GeneralsMD/Code/Tools/CRCDiff/expander.cpp b/Core/Tools/CRCDiff/expander.cpp similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/expander.cpp rename to Core/Tools/CRCDiff/expander.cpp diff --git a/GeneralsMD/Code/Tools/CRCDiff/expander.h b/Core/Tools/CRCDiff/expander.h similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/expander.h rename to Core/Tools/CRCDiff/expander.h diff --git a/GeneralsMD/Code/Tools/CRCDiff/misc.h b/Core/Tools/CRCDiff/misc.h similarity index 100% rename from GeneralsMD/Code/Tools/CRCDiff/misc.h rename to Core/Tools/CRCDiff/misc.h diff --git a/Generals/Code/Tools/CRCDiff/row.html b/Core/Tools/CRCDiff/row.html similarity index 100% rename from Generals/Code/Tools/CRCDiff/row.html rename to Core/Tools/CRCDiff/row.html diff --git a/Generals/Code/Tools/CRCDiff/style.css b/Core/Tools/CRCDiff/style.css similarity index 100% rename from Generals/Code/Tools/CRCDiff/style.css rename to Core/Tools/CRCDiff/style.css diff --git a/Generals/Code/Tools/CRCDiff/top.html b/Core/Tools/CRCDiff/top.html similarity index 100% rename from Generals/Code/Tools/CRCDiff/top.html rename to Core/Tools/CRCDiff/top.html diff --git a/Core/Tools/Compress/Compress.cpp b/Core/Tools/Compress/Compress.cpp index 7fcf1ccdd3..84d626c70d 100644 --- a/Core/Tools/Compress/Compress.cpp +++ b/Core/Tools/Compress/Compress.cpp @@ -95,21 +95,22 @@ int main(int argc, char **argv) DEBUG_LOG(("IN:'%s' OUT:'%s' Compression:'%s'\n", inFile.c_str(), outFile.c_str(), CompressionManager::getCompressionNameByType(compressType))); + // just check compression on the input file if we have no output specified if (outFile.empty()) { - // just check compression - FILE *fp = fopen(inFile.c_str(), "rb"); - if (!fp) + FILE *fpIn = fopen(inFile.c_str(), "rb"); + if (!fpIn) { DEBUG_LOG(("Cannot open '%s'\n", inFile.c_str())); return EXIT_FAILURE; } - fseek(fp, 0, SEEK_END); - int size = ftell(fp); - fseek(fp, 0, SEEK_SET); + fseek(fpIn, 0, SEEK_END); + int size = ftell(fpIn); + fseek(fpIn, 0, SEEK_SET); char data[8]; - int numRead = fread(data, 1, 8, fp); + int numRead = fread(data, 1, 8, fpIn); + fclose(fpIn); if (numRead != 8) { @@ -121,7 +122,7 @@ int main(int argc, char **argv) if (usedType == COMPRESSION_NONE) { DEBUG_LOG(("No compression on '%s'\n", inFile.c_str())); - return EXIT_FAILURE; + return EXIT_SUCCESS; } int uncompressedSize = CompressionManager::getUncompressedSize(data, 8); @@ -133,6 +134,66 @@ int main(int argc, char **argv) return EXIT_SUCCESS; } - // compress file - return EXIT_FAILURE; + // Open the input file + FILE *fpIn = fopen(inFile.c_str(), "rb"); + if (!fpIn) + { + DEBUG_LOG(("Cannot open input '%s'\n", inFile.c_str())); + return EXIT_FAILURE; + } + + // Read the input file + fseek(fpIn, 0, SEEK_END); + int inputSize = ftell(fpIn); + fseek(fpIn, 0, SEEK_SET); + + char *inputData = new char[inputSize]; + int numRead = fread(inputData, 1, inputSize, fpIn); + fclose(fpIn); + if (numRead != inputSize) + { + DEBUG_LOG(("Cannot read input '%s'\n", inFile.c_str())); + delete[] inputData; + return EXIT_FAILURE; + } + + DEBUG_LOG(("Read %d bytes from '%s'\n", numRead, inFile.c_str())); + + // Open the output file + FILE *fpOut = fopen(outFile.c_str(), "wb"); + if (!fpOut) + { + DEBUG_LOG(("Cannot open output '%s'\n", outFile.c_str())); + delete[] inputData; + return EXIT_FAILURE; + } + + + if (compressType == COMPRESSION_NONE) + { + DEBUG_LOG(("No compression requested, writing uncompressed data\n")); + int outSize = CompressionManager::getUncompressedSize(inputData, inputSize); + char *outData = new char[outSize]; + CompressionManager::decompressData(inputData, inputSize, outData, outSize); + + // Write the output file + fwrite(outData, 1, outSize, fpOut); + } + else + { + DEBUG_LOG(("Compressing data using %s\n", CompressionManager::getCompressionNameByType(compressType))); + // Allocate the output buffer + int outSize = CompressionManager::getMaxCompressedSize(inputSize, compressType); + char *outData = new char[outSize]; + int compressedSize = CompressionManager::compressData(compressType, inputData, inputSize, outData, outSize); + + // Write the output file + fwrite(outData, 1, compressedSize, fpOut); + delete[] outData; + } + + fclose(fpOut); + delete[] inputData; + + return EXIT_SUCCESS; } diff --git a/Core/Tools/DebugWindow/CMakeLists.txt b/Core/Tools/DebugWindow/CMakeLists.txt new file mode 100644 index 0000000000..d6514ca8ad --- /dev/null +++ b/Core/Tools/DebugWindow/CMakeLists.txt @@ -0,0 +1,28 @@ +set(DEBUGWINDOW_SRC + "DebugWindow.cpp" + "DebugWindow.h" + "DebugWindowDialog.cpp" + "DebugWindowDialog.h" + "DebugWindowExport.h" + "StdAfx.cpp" + "StdAfx.h" +) + +add_library(core_debugwindow SHARED) + +target_sources(core_debugwindow PRIVATE ${DEBUGWINDOW_SRC}) + +target_link_libraries(core_debugwindow PRIVATE + core_config +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_compile_definitions(core_debugwindow PRIVATE _AFXDLL) + target_sources(core_debugwindow PRIVATE + DebugWindow.rc + DebugWindow.def + ) + set_target_properties(core_debugwindow PROPERTIES OUTPUT_NAME DebugWindow) +else() + set_target_properties(core_debugwindow PROPERTIES OUTPUT_NAME debugwindow) +endif() diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.cpp b/Core/Tools/DebugWindow/DebugWindow.cpp similarity index 99% rename from GeneralsMD/Code/Tools/DebugWindow/DebugWindow.cpp rename to Core/Tools/DebugWindow/DebugWindow.cpp index 18ee6e2100..c0db3c69c3 100644 --- a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.cpp +++ b/Core/Tools/DebugWindow/DebugWindow.cpp @@ -23,7 +23,7 @@ #include "DebugWindow.h" #include "DebugWindowDialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/Generals/Code/Tools/DebugWindow/DebugWindow.def b/Core/Tools/DebugWindow/DebugWindow.def similarity index 100% rename from Generals/Code/Tools/DebugWindow/DebugWindow.def rename to Core/Tools/DebugWindow/DebugWindow.def diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.h b/Core/Tools/DebugWindow/DebugWindow.h similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/DebugWindow.h rename to Core/Tools/DebugWindow/DebugWindow.h diff --git a/Generals/Code/Tools/DebugWindow/DebugWindow.rc b/Core/Tools/DebugWindow/DebugWindow.rc similarity index 99% rename from Generals/Code/Tools/DebugWindow/DebugWindow.rc rename to Core/Tools/DebugWindow/DebugWindow.rc index 7722908f21..bda7fb255a 100644 --- a/Generals/Code/Tools/DebugWindow/DebugWindow.rc +++ b/Core/Tools/DebugWindow/DebugWindow.rc @@ -69,7 +69,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindowDialog.cpp b/Core/Tools/DebugWindow/DebugWindowDialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/DebugWindowDialog.cpp rename to Core/Tools/DebugWindow/DebugWindowDialog.cpp diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindowDialog.h b/Core/Tools/DebugWindow/DebugWindowDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/DebugWindowDialog.h rename to Core/Tools/DebugWindow/DebugWindowDialog.h diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindowExport.h b/Core/Tools/DebugWindow/DebugWindowExport.h similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/DebugWindowExport.h rename to Core/Tools/DebugWindow/DebugWindowExport.h diff --git a/GeneralsMD/Code/Tools/DebugWindow/Resource.h b/Core/Tools/DebugWindow/Resource.h similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/Resource.h rename to Core/Tools/DebugWindow/Resource.h diff --git a/GeneralsMD/Code/Tools/DebugWindow/StdAfx.cpp b/Core/Tools/DebugWindow/StdAfx.cpp similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/StdAfx.cpp rename to Core/Tools/DebugWindow/StdAfx.cpp diff --git a/GeneralsMD/Code/Tools/DebugWindow/StdAfx.h b/Core/Tools/DebugWindow/StdAfx.h similarity index 100% rename from GeneralsMD/Code/Tools/DebugWindow/StdAfx.h rename to Core/Tools/DebugWindow/StdAfx.h diff --git a/Generals/Code/Tools/DebugWindow/post-build.bat b/Core/Tools/DebugWindow/post-build.bat similarity index 100% rename from Generals/Code/Tools/DebugWindow/post-build.bat rename to Core/Tools/DebugWindow/post-build.bat diff --git a/Generals/Code/Tools/DebugWindow/res/DebugWindow.rc2 b/Core/Tools/DebugWindow/res/DebugWindow.rc2 similarity index 100% rename from Generals/Code/Tools/DebugWindow/res/DebugWindow.rc2 rename to Core/Tools/DebugWindow/res/DebugWindow.rc2 diff --git a/Core/Tools/ImagePacker/CMakeLists.txt b/Core/Tools/ImagePacker/CMakeLists.txt new file mode 100644 index 0000000000..3b30d71bb9 --- /dev/null +++ b/Core/Tools/ImagePacker/CMakeLists.txt @@ -0,0 +1,41 @@ +set(IMAGEPACKER_SRC + "Include/ImageDirectory.h" + "Include/ImageInfo.h" + "Include/ImagePacker.h" + "Include/TexturePage.h" + "Include/WindowProc.h" + "Include/WinMain.h" + "Source/ImageInfo.cpp" + "Source/ImagePacker.cpp" + "Source/TexturePage.cpp" + "Source/WinMain.cpp" + "Source/WindowProcedures/DirectorySelect.cpp" + "Source/WindowProcedures/ImageErrorProc.cpp" + "Source/WindowProcedures/ImagePackerProc.cpp" + "Source/WindowProcedures/PageErrorProc.cpp" + "Source/WindowProcedures/PreviewProc.cpp" +) + +add_library(corei_imagepacker INTERFACE) + +target_sources(corei_imagepacker INTERFACE ${IMAGEPACKER_SRC}) + +target_include_directories(corei_imagepacker INTERFACE + Include + Resource +) + +target_link_libraries(corei_imagepacker INTERFACE + benchmark + comctl32 + core_debug + core_profile + dbghelplib + imm32 + vfw32 + winmm +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(corei_imagepacker INTERFACE Resource/ImagePacker.rc) +endif() diff --git a/GeneralsMD/Code/Tools/ImagePacker/Include/ImageDirectory.h b/Core/Tools/ImagePacker/Include/ImageDirectory.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Include/ImageDirectory.h rename to Core/Tools/ImagePacker/Include/ImageDirectory.h diff --git a/GeneralsMD/Code/Tools/ImagePacker/Include/ImageInfo.h b/Core/Tools/ImagePacker/Include/ImageInfo.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Include/ImageInfo.h rename to Core/Tools/ImagePacker/Include/ImageInfo.h diff --git a/GeneralsMD/Code/Tools/ImagePacker/Include/ImagePacker.h b/Core/Tools/ImagePacker/Include/ImagePacker.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Include/ImagePacker.h rename to Core/Tools/ImagePacker/Include/ImagePacker.h diff --git a/GeneralsMD/Code/Tools/ImagePacker/Include/TexturePage.h b/Core/Tools/ImagePacker/Include/TexturePage.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Include/TexturePage.h rename to Core/Tools/ImagePacker/Include/TexturePage.h diff --git a/GeneralsMD/Code/Tools/ImagePacker/Include/WinMain.h b/Core/Tools/ImagePacker/Include/WinMain.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Include/WinMain.h rename to Core/Tools/ImagePacker/Include/WinMain.h diff --git a/GeneralsMD/Code/Tools/ImagePacker/Include/WindowProc.h b/Core/Tools/ImagePacker/Include/WindowProc.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Include/WindowProc.h rename to Core/Tools/ImagePacker/Include/WindowProc.h diff --git a/Generals/Code/Tools/ImagePacker/Resource/ImagePacker.rc b/Core/Tools/ImagePacker/Resource/ImagePacker.rc similarity index 100% rename from Generals/Code/Tools/ImagePacker/Resource/ImagePacker.rc rename to Core/Tools/ImagePacker/Resource/ImagePacker.rc diff --git a/GeneralsMD/Code/Tools/ImagePacker/Resource/Resource.h b/Core/Tools/ImagePacker/Resource/Resource.h similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Resource/Resource.h rename to Core/Tools/ImagePacker/Resource/Resource.h diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/ImageInfo.cpp b/Core/Tools/ImagePacker/Source/ImageInfo.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/ImageInfo.cpp rename to Core/Tools/ImagePacker/Source/ImageInfo.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/ImagePacker.cpp b/Core/Tools/ImagePacker/Source/ImagePacker.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/ImagePacker.cpp rename to Core/Tools/ImagePacker/Source/ImagePacker.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/TexturePage.cpp b/Core/Tools/ImagePacker/Source/TexturePage.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/TexturePage.cpp rename to Core/Tools/ImagePacker/Source/TexturePage.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/WinMain.cpp b/Core/Tools/ImagePacker/Source/WinMain.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/WinMain.cpp rename to Core/Tools/ImagePacker/Source/WinMain.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/DirectorySelect.cpp b/Core/Tools/ImagePacker/Source/WindowProcedures/DirectorySelect.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/DirectorySelect.cpp rename to Core/Tools/ImagePacker/Source/WindowProcedures/DirectorySelect.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/ImageErrorProc.cpp b/Core/Tools/ImagePacker/Source/WindowProcedures/ImageErrorProc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/ImageErrorProc.cpp rename to Core/Tools/ImagePacker/Source/WindowProcedures/ImageErrorProc.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/ImagePackerProc.cpp b/Core/Tools/ImagePacker/Source/WindowProcedures/ImagePackerProc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/ImagePackerProc.cpp rename to Core/Tools/ImagePacker/Source/WindowProcedures/ImagePackerProc.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/PageErrorProc.cpp b/Core/Tools/ImagePacker/Source/WindowProcedures/PageErrorProc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/PageErrorProc.cpp rename to Core/Tools/ImagePacker/Source/WindowProcedures/PageErrorProc.cpp diff --git a/GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/PreviewProc.cpp b/Core/Tools/ImagePacker/Source/WindowProcedures/PreviewProc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/ImagePacker/Source/Window Procedures/PreviewProc.cpp rename to Core/Tools/ImagePacker/Source/WindowProcedures/PreviewProc.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/BFISH.CPP b/Core/Tools/Launcher/BFISH.CPP similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/BFISH.CPP rename to Core/Tools/Launcher/BFISH.CPP diff --git a/GeneralsMD/Code/Tools/Launcher/BFISH.H b/Core/Tools/Launcher/BFISH.H similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/BFISH.H rename to Core/Tools/Launcher/BFISH.H diff --git a/Core/Tools/Launcher/CMakeLists.txt b/Core/Tools/Launcher/CMakeLists.txt new file mode 100644 index 0000000000..453f05b15d --- /dev/null +++ b/Core/Tools/Launcher/CMakeLists.txt @@ -0,0 +1,74 @@ +add_subdirectory(DatGen) + +set(LAUNCHER_SRC + "BFISH.CPP" + "BFISH.H" + "configfile.cpp" + "configfile.h" + "dialog.cpp" + "dialog.h" + "dictionary.h" + "filed.h" + "findpatch.cpp" + "findpatch.h" + "loadbmp.cpp" + "loadbmp.h" + "main.cpp" + "monod.cpp" + "monod.h" + "odevice.h" + "patch.cpp" + "patch.h" + "process.cpp" + "process.h" + "Protect.cpp" + "Protect.h" + "resource.h" + "streamer.cpp" + "streamer.h" + "wdebug.cpp" + "wdebug.h" + "winblows.cpp" + "winblows.h" + "wstring.cpp" + "wstring.h" + "wstypes.h" + "Toolkit/Debug/DebugPrint.cpp" + "Toolkit/Debug/DebugPrint.h" + "Toolkit/Storage/File.cpp" + "Toolkit/Storage/File.h" + "Toolkit/Storage/Rights.h" + "Toolkit/Storage/Stream.h" + "Toolkit/Support/RefCounted.h" + "Toolkit/Support/RefPtr.h" + "Toolkit/Support/StringConvert.cpp" + "Toolkit/Support/StringConvert.h" + "Toolkit/Support/UString.cpp" + "Toolkit/Support/UString.h" + "Toolkit/Support/UTypes.h" + "Toolkit/Support/Visualc.h" +) + +add_library(corei_launcher INTERFACE) + +target_sources(corei_launcher INTERFACE ${LAUNCHER_SRC}) + +target_include_directories(corei_launcher INTERFACE + Toolkit +) + +target_compile_definitions(corei_launcher INTERFACE + USE_NOTEPAD + $<$:USE_GAMEDIR_FROM_LCF> +) + +target_link_libraries(corei_launcher INTERFACE + comctl32 + core_config + core_utility + safedisc +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(corei_launcher INTERFACE launcher1.rc) +endif() diff --git a/Core/Tools/Launcher/DatGen/CMakeLists.txt b/Core/Tools/Launcher/DatGen/CMakeLists.txt new file mode 100644 index 0000000000..b70263f49e --- /dev/null +++ b/Core/Tools/Launcher/DatGen/CMakeLists.txt @@ -0,0 +1,21 @@ +set(DATGEN_SRC + "DatGen.cpp" + "../BFISH.CPP" + "../BFISH.H" + "../Toolkit/Debug/DebugPrint.cpp" + "../Toolkit/Debug/DebugPrint.h" +) + +add_library(corei_datgen INTERFACE) + +target_include_directories(corei_datgen INTERFACE + ../ + ../Toolkit +) + +target_link_libraries(corei_datgen INTERFACE + core_config + safedisc +) + +target_sources(corei_datgen INTERFACE ${DATGEN_SRC}) diff --git a/GeneralsMD/Code/Tools/Launcher/DatGen/DatGen.cpp b/Core/Tools/Launcher/DatGen/DatGen.cpp similarity index 87% rename from GeneralsMD/Code/Tools/Launcher/DatGen/DatGen.cpp rename to Core/Tools/Launcher/DatGen/DatGen.cpp index 2fc90933df..5835a3c639 100644 --- a/GeneralsMD/Code/Tools/Launcher/DatGen/DatGen.cpp +++ b/Core/Tools/Launcher/DatGen/DatGen.cpp @@ -41,10 +41,17 @@ static void doIt(void) // Get game information HKEY hKey; bool usesHKeycurrentUser = false; - LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour", 0, KEY_READ, &hKey); + +#if RTS_GENERALS + const char* gameRegistryKey = "Software\\Electronic Arts\\EA Games\\Generals"; +#elif RTS_ZEROHOUR + const char* gameRegistryKey = "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour"; +#endif + + LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, gameRegistryKey, 0, KEY_READ, &hKey); if (result != ERROR_SUCCESS) { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour", 0, KEY_READ, &hKey); + result = RegOpenKeyEx(HKEY_CURRENT_USER, gameRegistryKey, 0, KEY_READ, &hKey); usesHKeycurrentUser = true; } assert((result == ERROR_SUCCESS) && "Failed to open game registry key"); @@ -90,13 +97,20 @@ static void doIt(void) unsigned char gameSerialNumber[64]; gameSerialNumber[0] = '\0'; sizeOfBuffer = sizeof(gameSerialNumber); + +#if RTS_GENERALS + const char* serialRegistryKey = "Software\\Electronic Arts\\EA Games\\Generals\\ergc"; +#elif RTS_ZEROHOUR + const char* serialRegistryKey = "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour\\ergc"; +#endif + if (usesHKeycurrentUser) { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour\\ergc", 0, KEY_READ, &hKey); + result = RegOpenKeyEx(HKEY_CURRENT_USER, serialRegistryKey, 0, KEY_READ, &hKey); } else { - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour\\ergc", 0, KEY_READ, &hKey); + result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, serialRegistryKey, 0, KEY_READ, &hKey); } assert((result == ERROR_SUCCESS) && "Failed to open game serial registry key"); diff --git a/Generals/Code/Tools/Launcher/Generals.ico b/Core/Tools/Launcher/GeneralsV.ico similarity index 100% rename from Generals/Code/Tools/Launcher/Generals.ico rename to Core/Tools/Launcher/GeneralsV.ico diff --git a/GeneralsMD/Code/Tools/Launcher/Generals.ico b/Core/Tools/Launcher/GeneralsZH.ico similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Generals.ico rename to Core/Tools/Launcher/GeneralsZH.ico diff --git a/GeneralsMD/Code/Tools/Launcher/Protect.cpp b/Core/Tools/Launcher/Protect.cpp similarity index 91% rename from GeneralsMD/Code/Tools/Launcher/Protect.cpp rename to Core/Tools/Launcher/Protect.cpp index 885fd57411..543ab76ef3 100644 --- a/GeneralsMD/Code/Tools/Launcher/Protect.cpp +++ b/Core/Tools/Launcher/Protect.cpp @@ -149,10 +149,17 @@ void SendProtectMessage(HANDLE process, DWORD threadID) // Get game information HKEY hKey; bool usesHKeycurrentUser = false; - LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour", 0, KEY_READ, &hKey); + +#if RTS_GENERALS + const char* gameRegistryKey = "Software\\Electronic Arts\\EA Games\\Generals"; +#elif RTS_ZEROHOUR + const char* gameRegistryKey = "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour"; +#endif + + LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, gameRegistryKey, 0, KEY_READ, &hKey); if (result != ERROR_SUCCESS) { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour", 0, KEY_READ, &hKey); + result = RegOpenKeyEx(HKEY_CURRENT_USER, gameRegistryKey, 0, KEY_READ, &hKey); usesHKeycurrentUser = true; } assert((result == ERROR_SUCCESS) && "Failed to open game registry key"); @@ -196,13 +203,20 @@ void SendProtectMessage(HANDLE process, DWORD threadID) unsigned char gameSerialNumber[64]; gameSerialNumber[0] = '\0'; sizeOfBuffer = sizeof(gameSerialNumber); + +#if RTS_GENERALS + const char* serialRegistryKey = "Software\\Electronic Arts\\EA Games\\Generals\\ergc"; +#elif RTS_ZEROHOUR + const char* serialRegistryKey = "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour\\ergc"; +#endif + if (usesHKeycurrentUser) { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour\\ergc", 0, KEY_READ, &hKey); + result = RegOpenKeyEx(HKEY_CURRENT_USER, serialRegistryKey, 0, KEY_READ, &hKey); } else { - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Command and Conquer Generals Zero Hour\\ergc", 0, KEY_READ, &hKey); + result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, serialRegistryKey, 0, KEY_READ, &hKey); } assert((result == ERROR_SUCCESS) && "Failed to open game serial registry key"); @@ -280,7 +294,7 @@ void SendProtectMessage(HANDLE process, DWORD threadID) DebugPrint("Waiting for game (timeout in %.02f seconds)...\n", ((float)((5 * 60) * 1000) * 0.001)); -#ifdef _DEBUG +#ifdef RTS_DEBUG unsigned long start = timeGetTime(); #endif @@ -289,7 +303,7 @@ void SendProtectMessage(HANDLE process, DWORD threadID) handles[1] = process; DWORD waitResult = WaitForMultipleObjects(2, &handles[0], FALSE, ((5 * 60) * 1000)); -#ifdef _DEBUG +#ifdef RTS_DEBUG unsigned long stop = timeGetTime(); #endif @@ -309,7 +323,7 @@ void SendProtectMessage(HANDLE process, DWORD threadID) DebugPrint("***** Timeout!\n"); } -#ifdef _DEBUG +#ifdef RTS_DEBUG DebugPrint("Waited %.02f seconds\n", ((float)(stop - start) * 0.001)); #endif diff --git a/GeneralsMD/Code/Tools/Launcher/Protect.h b/Core/Tools/Launcher/Protect.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Protect.h rename to Core/Tools/Launcher/Protect.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp b/Core/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp rename to Core/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp index 1777f94780..bb1289c10a 100644 --- a/GeneralsMD/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp +++ b/Core/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp @@ -34,7 +34,7 @@ * ******************************************************************************/ -#ifdef _DEBUG +#ifdef RTS_DEBUG #include "DebugPrint.h" #include @@ -182,4 +182,4 @@ void __cdecl PrintWin32Error(const char* string, ...) } } -#endif // _DEBUG +#endif // RTS_DEBUG diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.h b/Core/Tools/Launcher/Toolkit/Debug/DebugPrint.h similarity index 96% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.h rename to Core/Tools/Launcher/Toolkit/Debug/DebugPrint.h index 58099e19fc..dd1f4723bf 100644 --- a/GeneralsMD/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.h +++ b/Core/Tools/Launcher/Toolkit/Debug/DebugPrint.h @@ -37,7 +37,7 @@ #ifndef _DEBUGPRINT_H_ #define _DEBUGPRINT_H_ -#ifdef _DEBUG +#ifdef RTS_DEBUG #ifdef __cplusplus extern "C" @@ -55,11 +55,11 @@ extern char debugLogName[]; } #endif -#else // _DEBUG +#else // RTS_DEBUG #define DebugPrint #define PrintWin32Error -#endif // _DEBUG +#endif // RTS_DEBUG #endif // _DEBUGPRINT_H_ diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/File.cpp b/Core/Tools/Launcher/Toolkit/Storage/File.cpp similarity index 99% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/File.cpp rename to Core/Tools/Launcher/Toolkit/Storage/File.cpp index 23ce0d83c4..0b187952cf 100644 --- a/GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/File.cpp +++ b/Core/Tools/Launcher/Toolkit/Storage/File.cpp @@ -728,7 +728,7 @@ File::EFileError File::Save(const void* buffer, UInt32 size) bool File::OnFileError(EFileError error, bool) { - #ifdef _DEBUG + #ifdef RTS_DEBUG const char* _errorNames[] = { "FileError_None", diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/File.h b/Core/Tools/Launcher/Toolkit/Storage/File.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/File.h rename to Core/Tools/Launcher/Toolkit/Storage/File.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/Rights.h b/Core/Tools/Launcher/Toolkit/Storage/Rights.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/Rights.h rename to Core/Tools/Launcher/Toolkit/Storage/Rights.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/Stream.h b/Core/Tools/Launcher/Toolkit/Storage/Stream.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Storage/Stream.h rename to Core/Tools/Launcher/Toolkit/Storage/Stream.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/RefCounted.h b/Core/Tools/Launcher/Toolkit/Support/RefCounted.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/RefCounted.h rename to Core/Tools/Launcher/Toolkit/Support/RefCounted.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/RefPtr.h b/Core/Tools/Launcher/Toolkit/Support/RefPtr.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/RefPtr.h rename to Core/Tools/Launcher/Toolkit/Support/RefPtr.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/StringConvert.cpp b/Core/Tools/Launcher/Toolkit/Support/StringConvert.cpp similarity index 98% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/StringConvert.cpp rename to Core/Tools/Launcher/Toolkit/Support/StringConvert.cpp index 30e5931664..009f44f023 100644 --- a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/StringConvert.cpp +++ b/Core/Tools/Launcher/Toolkit/Support/StringConvert.cpp @@ -89,13 +89,13 @@ Char* UnicodeToANSI(const WChar* string, Char* buffer, UInt bufferLength) return NULL; } - #ifdef _DEBUG + #ifdef RTS_DEBUG int result = #endif WideCharToMultiByte(CP_ACP, 0, string, -1, buffer, bufferLength, NULL, NULL); - #ifdef _DEBUG + #ifdef RTS_DEBUG if (result == 0) { PrintWin32Error("ConvertToANSI() Failed"); diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/StringConvert.h b/Core/Tools/Launcher/Toolkit/Support/StringConvert.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/StringConvert.h rename to Core/Tools/Launcher/Toolkit/Support/StringConvert.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/UString.cpp b/Core/Tools/Launcher/Toolkit/Support/UString.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/UString.cpp rename to Core/Tools/Launcher/Toolkit/Support/UString.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/UString.h b/Core/Tools/Launcher/Toolkit/Support/UString.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/UString.h rename to Core/Tools/Launcher/Toolkit/Support/UString.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/UTypes.h b/Core/Tools/Launcher/Toolkit/Support/UTypes.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/UTypes.h rename to Core/Tools/Launcher/Toolkit/Support/UTypes.h diff --git a/GeneralsMD/Code/Tools/Launcher/Toolkit/Support/Visualc.h b/Core/Tools/Launcher/Toolkit/Support/Visualc.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/Toolkit/Support/Visualc.h rename to Core/Tools/Launcher/Toolkit/Support/Visualc.h diff --git a/GeneralsMD/Code/Tools/Launcher/configfile.cpp b/Core/Tools/Launcher/configfile.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/configfile.cpp rename to Core/Tools/Launcher/configfile.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/configfile.h b/Core/Tools/Launcher/configfile.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/configfile.h rename to Core/Tools/Launcher/configfile.h diff --git a/GeneralsMD/Code/Tools/Launcher/dialog.cpp b/Core/Tools/Launcher/dialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/dialog.cpp rename to Core/Tools/Launcher/dialog.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/dialog.h b/Core/Tools/Launcher/dialog.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/dialog.h rename to Core/Tools/Launcher/dialog.h diff --git a/GeneralsMD/Code/Tools/Launcher/dictionary.h b/Core/Tools/Launcher/dictionary.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/dictionary.h rename to Core/Tools/Launcher/dictionary.h diff --git a/GeneralsMD/Code/Tools/Launcher/filed.h b/Core/Tools/Launcher/filed.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/filed.h rename to Core/Tools/Launcher/filed.h diff --git a/GeneralsMD/Code/Tools/Launcher/findpatch.cpp b/Core/Tools/Launcher/findpatch.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/findpatch.cpp rename to Core/Tools/Launcher/findpatch.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/findpatch.h b/Core/Tools/Launcher/findpatch.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/findpatch.h rename to Core/Tools/Launcher/findpatch.h diff --git a/Generals/Code/Tools/Launcher/launcher1.rc b/Core/Tools/Launcher/launcher1.rc similarity index 95% rename from Generals/Code/Tools/Launcher/launcher1.rc rename to Core/Tools/Launcher/launcher1.rc index 0cb9126c88..901299979b 100644 --- a/Generals/Code/Tools/Launcher/launcher1.rc +++ b/Core/Tools/Launcher/launcher1.rc @@ -112,7 +112,11 @@ END // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. -IDI_GENERALS ICON DISCARDABLE "Generals.ico" +#if RTS_GENERALS +IDI_GENERALS ICON DISCARDABLE "GeneralsV.ico" +#elif RTS_ZEROHOUR +IDI_GENERALS ICON DISCARDABLE "GeneralsZH.ico" +#endif ///////////////////////////////////////////////////////////////////////////// // diff --git a/GeneralsMD/Code/Tools/Launcher/loadbmp.cpp b/Core/Tools/Launcher/loadbmp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/loadbmp.cpp rename to Core/Tools/Launcher/loadbmp.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/loadbmp.h b/Core/Tools/Launcher/loadbmp.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/loadbmp.h rename to Core/Tools/Launcher/loadbmp.h diff --git a/GeneralsMD/Code/Tools/Launcher/main.cpp b/Core/Tools/Launcher/main.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/main.cpp rename to Core/Tools/Launcher/main.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/monod.cpp b/Core/Tools/Launcher/monod.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/monod.cpp rename to Core/Tools/Launcher/monod.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/monod.h b/Core/Tools/Launcher/monod.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/monod.h rename to Core/Tools/Launcher/monod.h diff --git a/GeneralsMD/Code/Tools/Launcher/odevice.h b/Core/Tools/Launcher/odevice.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/odevice.h rename to Core/Tools/Launcher/odevice.h diff --git a/GeneralsMD/Code/Tools/Launcher/patch.cpp b/Core/Tools/Launcher/patch.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/patch.cpp rename to Core/Tools/Launcher/patch.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/patch.h b/Core/Tools/Launcher/patch.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/patch.h rename to Core/Tools/Launcher/patch.h diff --git a/GeneralsMD/Code/Tools/Launcher/process.cpp b/Core/Tools/Launcher/process.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/process.cpp rename to Core/Tools/Launcher/process.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/process.h b/Core/Tools/Launcher/process.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/process.h rename to Core/Tools/Launcher/process.h diff --git a/GeneralsMD/Code/Tools/Launcher/resource.h b/Core/Tools/Launcher/resource.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/resource.h rename to Core/Tools/Launcher/resource.h diff --git a/GeneralsMD/Code/Tools/Launcher/streamer.cpp b/Core/Tools/Launcher/streamer.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/streamer.cpp rename to Core/Tools/Launcher/streamer.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/streamer.h b/Core/Tools/Launcher/streamer.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/streamer.h rename to Core/Tools/Launcher/streamer.h diff --git a/GeneralsMD/Code/Tools/Launcher/wdebug.cpp b/Core/Tools/Launcher/wdebug.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/wdebug.cpp rename to Core/Tools/Launcher/wdebug.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/wdebug.h b/Core/Tools/Launcher/wdebug.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/wdebug.h rename to Core/Tools/Launcher/wdebug.h diff --git a/GeneralsMD/Code/Tools/Launcher/winblows.cpp b/Core/Tools/Launcher/winblows.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/winblows.cpp rename to Core/Tools/Launcher/winblows.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/winblows.h b/Core/Tools/Launcher/winblows.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/winblows.h rename to Core/Tools/Launcher/winblows.h diff --git a/GeneralsMD/Code/Tools/Launcher/wstring.cpp b/Core/Tools/Launcher/wstring.cpp similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/wstring.cpp rename to Core/Tools/Launcher/wstring.cpp diff --git a/GeneralsMD/Code/Tools/Launcher/wstring.h b/Core/Tools/Launcher/wstring.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/wstring.h rename to Core/Tools/Launcher/wstring.h diff --git a/GeneralsMD/Code/Tools/Launcher/wstypes.h b/Core/Tools/Launcher/wstypes.h similarity index 100% rename from GeneralsMD/Code/Tools/Launcher/wstypes.h rename to Core/Tools/Launcher/wstypes.h diff --git a/Core/Tools/MapCacheBuilder/CMakeLists.txt b/Core/Tools/MapCacheBuilder/CMakeLists.txt new file mode 100644 index 0000000000..5d390853a8 --- /dev/null +++ b/Core/Tools/MapCacheBuilder/CMakeLists.txt @@ -0,0 +1,28 @@ +set(MAPCACHEBUILDER_SRC + "Include/WinMain.h" + "Resource/Resource.h" + "Source/WinMain.cpp" +) + +add_library(corei_mapcachebuilder INTERFACE) + +target_sources(corei_mapcachebuilder INTERFACE ${MAPCACHEBUILDER_SRC}) + +target_include_directories(corei_mapcachebuilder INTERFACE + Include + Resource +) +# +target_link_libraries(corei_mapcachebuilder INTERFACE + comctl32 + core_debug + core_profile + dbghelplib + imm32 + vfw32 + winmm +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(corei_mapcachebuilder INTERFACE Resource/MapCacheBuilder.rc) +endif() diff --git a/GeneralsMD/Code/Tools/MapCacheBuilder/Include/WinMain.h b/Core/Tools/MapCacheBuilder/Include/WinMain.h similarity index 100% rename from GeneralsMD/Code/Tools/MapCacheBuilder/Include/WinMain.h rename to Core/Tools/MapCacheBuilder/Include/WinMain.h diff --git a/Generals/Code/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc b/Core/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc similarity index 100% rename from Generals/Code/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc rename to Core/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc diff --git a/GeneralsMD/Code/Tools/MapCacheBuilder/Resource/Resource.h b/Core/Tools/MapCacheBuilder/Resource/Resource.h similarity index 100% rename from GeneralsMD/Code/Tools/MapCacheBuilder/Resource/Resource.h rename to Core/Tools/MapCacheBuilder/Resource/Resource.h diff --git a/GeneralsMD/Code/Tools/MapCacheBuilder/Source/WinMain.cpp b/Core/Tools/MapCacheBuilder/Source/WinMain.cpp similarity index 99% rename from GeneralsMD/Code/Tools/MapCacheBuilder/Source/WinMain.cpp rename to Core/Tools/MapCacheBuilder/Source/WinMain.cpp index 492b2fb40e..3abf1f9e8a 100644 --- a/GeneralsMD/Code/Tools/MapCacheBuilder/Source/WinMain.cpp +++ b/Core/Tools/MapCacheBuilder/Source/WinMain.cpp @@ -110,7 +110,7 @@ // PRIVATE TYPES ////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/PATCHGET/CHATAPI.CPP b/Core/Tools/PATCHGET/CHATAPI.CPP similarity index 99% rename from GeneralsMD/Code/Tools/PATCHGET/CHATAPI.CPP rename to Core/Tools/PATCHGET/CHATAPI.CPP index 46045047d2..e89fdc781f 100644 --- a/GeneralsMD/Code/Tools/PATCHGET/CHATAPI.CPP +++ b/Core/Tools/PATCHGET/CHATAPI.CPP @@ -52,7 +52,11 @@ enum EVENT_TYPES NUM_EVENTS // keep last }; +#if RTS_GENERALS +#define GAME_NAME "Command and Conquer Generals" +#elif RTS_ZEROHOUR #define GAME_NAME "Command & Conquer" +#endif HANDLE Events[NUM_EVENTS]; @@ -882,7 +886,7 @@ char const * Fetch_String(int id) void LogMsg(const char *msg) { -#ifdef _DEBUG +#ifdef RTS_DEBUG FILE *out=fopen("register.log","a"); fprintf(out,"%s\n",msg); fflush(out); diff --git a/GeneralsMD/Code/Tools/PATCHGET/CHATAPI.H b/Core/Tools/PATCHGET/CHATAPI.H similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/CHATAPI.H rename to Core/Tools/PATCHGET/CHATAPI.H diff --git a/Core/Tools/PATCHGET/CMakeLists.txt b/Core/Tools/PATCHGET/CMakeLists.txt new file mode 100644 index 0000000000..265a74c785 --- /dev/null +++ b/Core/Tools/PATCHGET/CMakeLists.txt @@ -0,0 +1,41 @@ +set(PATCHGET_SRC + "CHATAPI.CPP" + "CHATAPI.H" + "COMINIT.CPP" + "COMINIT.H" + "debug.cpp" + "debug.h" + "DownloadManager.cpp" + "DownloadManager.h" + "PROCESS.CPP" + "PROCESS.H" + "registry.cpp" + "Registry.h" + "RESOURCE.H" + "WINBLOWS.CPP" + "WINBLOWS.H" + "WSTYPES.H" +) + +add_library(corei_patchgrabber INTERFACE) + +target_sources(corei_patchgrabber INTERFACE ${PATCHGET_SRC}) + +target_link_libraries(corei_patchgrabber INTERFACE + comctl32 + core_debug + core_profile + dbghelplib + gamespy::gamespy + imm32 + vfw32 + winmm +) + +target_compile_definitions(corei_patchgrabber INTERFACE + $<$:DEBUG_CRASHING> +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(corei_patchgrabber INTERFACE SCRIPT1.RC) +endif() diff --git a/GeneralsMD/Code/Tools/PATCHGET/COMINIT.CPP b/Core/Tools/PATCHGET/COMINIT.CPP similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/COMINIT.CPP rename to Core/Tools/PATCHGET/COMINIT.CPP diff --git a/GeneralsMD/Code/Tools/PATCHGET/COMINIT.H b/Core/Tools/PATCHGET/COMINIT.H similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/COMINIT.H rename to Core/Tools/PATCHGET/COMINIT.H diff --git a/GeneralsMD/Code/Tools/PATCHGET/DownloadManager.cpp b/Core/Tools/PATCHGET/DownloadManager.cpp similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/DownloadManager.cpp rename to Core/Tools/PATCHGET/DownloadManager.cpp diff --git a/GeneralsMD/Code/Tools/PATCHGET/DownloadManager.h b/Core/Tools/PATCHGET/DownloadManager.h similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/DownloadManager.h rename to Core/Tools/PATCHGET/DownloadManager.h diff --git a/Generals/Code/Tools/PATCHGET/Generals.ico b/Core/Tools/PATCHGET/Generals.ico similarity index 100% rename from Generals/Code/Tools/PATCHGET/Generals.ico rename to Core/Tools/PATCHGET/Generals.ico diff --git a/Generals/Code/Tools/PATCHGET/GeneralsEnglish.bmp b/Core/Tools/PATCHGET/GeneralsEnglish.bmp similarity index 100% rename from Generals/Code/Tools/PATCHGET/GeneralsEnglish.bmp rename to Core/Tools/PATCHGET/GeneralsEnglish.bmp diff --git a/Generals/Code/Tools/PATCHGET/GeneralsFrench.bmp b/Core/Tools/PATCHGET/GeneralsFrench.bmp similarity index 100% rename from Generals/Code/Tools/PATCHGET/GeneralsFrench.bmp rename to Core/Tools/PATCHGET/GeneralsFrench.bmp diff --git a/Generals/Code/Tools/PATCHGET/GeneralsGerman.bmp b/Core/Tools/PATCHGET/GeneralsGerman.bmp similarity index 100% rename from Generals/Code/Tools/PATCHGET/GeneralsGerman.bmp rename to Core/Tools/PATCHGET/GeneralsGerman.bmp diff --git a/GeneralsMD/Code/Tools/PATCHGET/PROCESS.CPP b/Core/Tools/PATCHGET/PROCESS.CPP similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/PROCESS.CPP rename to Core/Tools/PATCHGET/PROCESS.CPP diff --git a/GeneralsMD/Code/Tools/PATCHGET/PROCESS.H b/Core/Tools/PATCHGET/PROCESS.H similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/PROCESS.H rename to Core/Tools/PATCHGET/PROCESS.H diff --git a/GeneralsMD/Code/Tools/PATCHGET/RESOURCE.H b/Core/Tools/PATCHGET/RESOURCE.H similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/RESOURCE.H rename to Core/Tools/PATCHGET/RESOURCE.H diff --git a/GeneralsMD/Code/Tools/PATCHGET/Registry.h b/Core/Tools/PATCHGET/Registry.h similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/Registry.h rename to Core/Tools/PATCHGET/Registry.h diff --git a/Generals/Code/Tools/PATCHGET/SCRIPT1.RC b/Core/Tools/PATCHGET/SCRIPT1.RC similarity index 99% rename from Generals/Code/Tools/PATCHGET/SCRIPT1.RC rename to Core/Tools/PATCHGET/SCRIPT1.RC index 70f78550b1..5e1ef24474 100644 --- a/Generals/Code/Tools/PATCHGET/SCRIPT1.RC +++ b/Core/Tools/PATCHGET/SCRIPT1.RC @@ -85,7 +85,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L @@ -246,7 +246,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L @@ -454,7 +454,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/PATCHGET/WINBLOWS.CPP b/Core/Tools/PATCHGET/WINBLOWS.CPP similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/WINBLOWS.CPP rename to Core/Tools/PATCHGET/WINBLOWS.CPP diff --git a/GeneralsMD/Code/Tools/PATCHGET/WINBLOWS.H b/Core/Tools/PATCHGET/WINBLOWS.H similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/WINBLOWS.H rename to Core/Tools/PATCHGET/WINBLOWS.H diff --git a/GeneralsMD/Code/Tools/PATCHGET/WSTYPES.H b/Core/Tools/PATCHGET/WSTYPES.H similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/WSTYPES.H rename to Core/Tools/PATCHGET/WSTYPES.H diff --git a/Generals/Code/Tools/PATCHGET/debug.cpp b/Core/Tools/PATCHGET/debug.cpp similarity index 98% rename from Generals/Code/Tools/PATCHGET/debug.cpp rename to Core/Tools/PATCHGET/debug.cpp index 00714e8db7..64a24880ff 100644 --- a/Generals/Code/Tools/PATCHGET/debug.cpp +++ b/Core/Tools/PATCHGET/debug.cpp @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals(tm) +** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify diff --git a/GeneralsMD/Code/Tools/PATCHGET/debug.h b/Core/Tools/PATCHGET/debug.h similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/debug.h rename to Core/Tools/PATCHGET/debug.h diff --git a/GeneralsMD/Code/Tools/PATCHGET/registry.cpp b/Core/Tools/PATCHGET/registry.cpp similarity index 100% rename from GeneralsMD/Code/Tools/PATCHGET/registry.cpp rename to Core/Tools/PATCHGET/registry.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/AddToLineupDialog.cpp b/Core/Tools/W3DView/AddToLineupDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AddToLineupDialog.cpp rename to Core/Tools/W3DView/AddToLineupDialog.cpp index 3ddd9e0915..c9c24e3c83 100644 --- a/GeneralsMD/Code/Tools/W3DView/AddToLineupDialog.cpp +++ b/Core/Tools/W3DView/AddToLineupDialog.cpp @@ -28,7 +28,7 @@ #include -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AddToLineupDialog.h b/Core/Tools/W3DView/AddToLineupDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AddToLineupDialog.h rename to Core/Tools/W3DView/AddToLineupDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/AdvancedAnimSheet.cpp b/Core/Tools/W3DView/AdvancedAnimSheet.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AdvancedAnimSheet.cpp rename to Core/Tools/W3DView/AdvancedAnimSheet.cpp index ba1a4d4697..f09526a2a4 100644 --- a/GeneralsMD/Code/Tools/W3DView/AdvancedAnimSheet.cpp +++ b/Core/Tools/W3DView/AdvancedAnimSheet.cpp @@ -30,7 +30,7 @@ #include "Utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AdvancedAnimSheet.h b/Core/Tools/W3DView/AdvancedAnimSheet.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AdvancedAnimSheet.h rename to Core/Tools/W3DView/AdvancedAnimSheet.h diff --git a/GeneralsMD/Code/Tools/W3DView/AggregateNameDialog.cpp b/Core/Tools/W3DView/AggregateNameDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AggregateNameDialog.cpp rename to Core/Tools/W3DView/AggregateNameDialog.cpp index ec42ded48a..faacfe9af9 100644 --- a/GeneralsMD/Code/Tools/W3DView/AggregateNameDialog.cpp +++ b/Core/Tools/W3DView/AggregateNameDialog.cpp @@ -37,7 +37,7 @@ #include "W3D_File.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AggregateNameDialog.h b/Core/Tools/W3DView/AggregateNameDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AggregateNameDialog.h rename to Core/Tools/W3DView/AggregateNameDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/AmbientLightDialog.cpp b/Core/Tools/W3DView/AmbientLightDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AmbientLightDialog.cpp rename to Core/Tools/W3DView/AmbientLightDialog.cpp index 84480a5209..f03ea32c09 100644 --- a/GeneralsMD/Code/Tools/W3DView/AmbientLightDialog.cpp +++ b/Core/Tools/W3DView/AmbientLightDialog.cpp @@ -28,7 +28,7 @@ #include "ViewerScene.H" #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AmbientLightDialog.h b/Core/Tools/W3DView/AmbientLightDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AmbientLightDialog.h rename to Core/Tools/W3DView/AmbientLightDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/AnimMixingPage.cpp b/Core/Tools/W3DView/AnimMixingPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AnimMixingPage.cpp rename to Core/Tools/W3DView/AnimMixingPage.cpp index 363ce33413..357584764a 100644 --- a/GeneralsMD/Code/Tools/W3DView/AnimMixingPage.cpp +++ b/Core/Tools/W3DView/AnimMixingPage.cpp @@ -31,7 +31,7 @@ #include "Utils.h" #include "AssetMgr.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AnimMixingPage.h b/Core/Tools/W3DView/AnimMixingPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AnimMixingPage.h rename to Core/Tools/W3DView/AnimMixingPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/AnimReportPage.cpp b/Core/Tools/W3DView/AnimReportPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AnimReportPage.cpp rename to Core/Tools/W3DView/AnimReportPage.cpp index 61a5c5aad0..dab0089716 100644 --- a/GeneralsMD/Code/Tools/W3DView/AnimReportPage.cpp +++ b/Core/Tools/W3DView/AnimReportPage.cpp @@ -31,7 +31,7 @@ #include "Utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AnimReportPage.h b/Core/Tools/W3DView/AnimReportPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AnimReportPage.h rename to Core/Tools/W3DView/AnimReportPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/AnimatedSoundOptionsDialog.cpp b/Core/Tools/W3DView/AnimatedSoundOptionsDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AnimatedSoundOptionsDialog.cpp rename to Core/Tools/W3DView/AnimatedSoundOptionsDialog.cpp index e5576969c1..c03bde2e7b 100644 --- a/GeneralsMD/Code/Tools/W3DView/AnimatedSoundOptionsDialog.cpp +++ b/Core/Tools/W3DView/AnimatedSoundOptionsDialog.cpp @@ -34,7 +34,7 @@ #include "utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AnimatedSoundOptionsDialog.h b/Core/Tools/W3DView/AnimatedSoundOptionsDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AnimatedSoundOptionsDialog.h rename to Core/Tools/W3DView/AnimatedSoundOptionsDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/AnimationPropPage.cpp b/Core/Tools/W3DView/AnimationPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AnimationPropPage.cpp rename to Core/Tools/W3DView/AnimationPropPage.cpp index 273a06d029..303f652005 100644 --- a/GeneralsMD/Code/Tools/W3DView/AnimationPropPage.cpp +++ b/Core/Tools/W3DView/AnimationPropPage.cpp @@ -29,7 +29,7 @@ #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AnimationPropPage.h b/Core/Tools/W3DView/AnimationPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AnimationPropPage.h rename to Core/Tools/W3DView/AnimationPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/AnimationSpeed.cpp b/Core/Tools/W3DView/AnimationSpeed.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AnimationSpeed.cpp rename to Core/Tools/W3DView/AnimationSpeed.cpp index 307a721010..b0a86361c9 100644 --- a/GeneralsMD/Code/Tools/W3DView/AnimationSpeed.cpp +++ b/Core/Tools/W3DView/AnimationSpeed.cpp @@ -27,7 +27,7 @@ #include "Utils.H" #include "W3DViewDoc.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AnimationSpeed.h b/Core/Tools/W3DView/AnimationSpeed.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AnimationSpeed.h rename to Core/Tools/W3DView/AnimationSpeed.h diff --git a/GeneralsMD/Code/Tools/W3DView/AssetInfo.cpp b/Core/Tools/W3DView/AssetInfo.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AssetInfo.cpp rename to Core/Tools/W3DView/AssetInfo.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/AssetInfo.h b/Core/Tools/W3DView/AssetInfo.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AssetInfo.h rename to Core/Tools/W3DView/AssetInfo.h diff --git a/GeneralsMD/Code/Tools/W3DView/AssetPropertySheet.cpp b/Core/Tools/W3DView/AssetPropertySheet.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/AssetPropertySheet.cpp rename to Core/Tools/W3DView/AssetPropertySheet.cpp index 1bd96e84c9..9c8d83b987 100644 --- a/GeneralsMD/Code/Tools/W3DView/AssetPropertySheet.cpp +++ b/Core/Tools/W3DView/AssetPropertySheet.cpp @@ -23,7 +23,7 @@ #include "W3DView.h" #include "AssetPropertySheet.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/AssetPropertySheet.h b/Core/Tools/W3DView/AssetPropertySheet.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AssetPropertySheet.h rename to Core/Tools/W3DView/AssetPropertySheet.h diff --git a/GeneralsMD/Code/Tools/W3DView/AssetTypes.h b/Core/Tools/W3DView/AssetTypes.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/AssetTypes.h rename to Core/Tools/W3DView/AssetTypes.h diff --git a/GeneralsMD/Code/Tools/W3DView/BackgroundBMPDialog.cpp b/Core/Tools/W3DView/BackgroundBMPDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/BackgroundBMPDialog.cpp rename to Core/Tools/W3DView/BackgroundBMPDialog.cpp index 95623c4059..8bf69d3546 100644 --- a/GeneralsMD/Code/Tools/W3DView/BackgroundBMPDialog.cpp +++ b/Core/Tools/W3DView/BackgroundBMPDialog.cpp @@ -26,7 +26,7 @@ #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/BackgroundBMPDialog.h b/Core/Tools/W3DView/BackgroundBMPDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/BackgroundBMPDialog.h rename to Core/Tools/W3DView/BackgroundBMPDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/BackgroundColorDialog.cpp b/Core/Tools/W3DView/BackgroundColorDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/BackgroundColorDialog.cpp rename to Core/Tools/W3DView/BackgroundColorDialog.cpp index 2b83733cf0..b626786b4b 100644 --- a/GeneralsMD/Code/Tools/W3DView/BackgroundColorDialog.cpp +++ b/Core/Tools/W3DView/BackgroundColorDialog.cpp @@ -27,7 +27,7 @@ #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/BackgroundColorDialog.h b/Core/Tools/W3DView/BackgroundColorDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/BackgroundColorDialog.h rename to Core/Tools/W3DView/BackgroundColorDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/BackgroundObjectDialog.cpp b/Core/Tools/W3DView/BackgroundObjectDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/BackgroundObjectDialog.cpp rename to Core/Tools/W3DView/BackgroundObjectDialog.cpp index 955dd305c0..a860ee0b7f 100644 --- a/GeneralsMD/Code/Tools/W3DView/BackgroundObjectDialog.cpp +++ b/Core/Tools/W3DView/BackgroundObjectDialog.cpp @@ -27,7 +27,7 @@ #include "W3DViewDoc.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/BackgroundObjectDialog.h b/Core/Tools/W3DView/BackgroundObjectDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/BackgroundObjectDialog.h rename to Core/Tools/W3DView/BackgroundObjectDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/BoneMgrDialog.cpp b/Core/Tools/W3DView/BoneMgrDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/BoneMgrDialog.cpp rename to Core/Tools/W3DView/BoneMgrDialog.cpp index 145241fe1f..7e5a5a4da7 100644 --- a/GeneralsMD/Code/Tools/W3DView/BoneMgrDialog.cpp +++ b/Core/Tools/W3DView/BoneMgrDialog.cpp @@ -30,7 +30,7 @@ #include "DataTreeView.H" //#include "HModel.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/BoneMgrDialog.h b/Core/Tools/W3DView/BoneMgrDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/BoneMgrDialog.h rename to Core/Tools/W3DView/BoneMgrDialog.h diff --git a/Core/Tools/W3DView/CMakeLists.txt b/Core/Tools/W3DView/CMakeLists.txt new file mode 100644 index 0000000000..a39051ac73 --- /dev/null +++ b/Core/Tools/W3DView/CMakeLists.txt @@ -0,0 +1,175 @@ +set(W3DVIEW_SRC + "AddToLineupDialog.cpp" + "AddToLineupDialog.h" + "AdvancedAnimSheet.cpp" + "AdvancedAnimSheet.h" + "AggregateNameDialog.cpp" + "AggregateNameDialog.h" + "AmbientLightDialog.cpp" + "AmbientLightDialog.h" + "AnimatedSoundOptionsDialog.cpp" + "AnimatedSoundOptionsDialog.h" + "AnimationPropPage.cpp" + "AnimationPropPage.h" + "AnimationSpeed.cpp" + "AnimationSpeed.h" + "AnimMixingPage.cpp" + "AnimMixingPage.h" + "AnimReportPage.cpp" + "AnimReportPage.h" + "AssetInfo.cpp" + "AssetInfo.h" + "AssetPropertySheet.cpp" + "AssetPropertySheet.h" + "AssetTypes.h" + "BackgroundBMPDialog.cpp" + "BackgroundBMPDialog.h" + "BackgroundColorDialog.cpp" + "BackgroundColorDialog.h" + "BackgroundObjectDialog.cpp" + "BackgroundObjectDialog.h" + "BoneMgrDialog.cpp" + "BoneMgrDialog.h" + "CameraDistanceDialog.cpp" + "CameraDistanceDialog.h" + "CameraSettingsDialog.cpp" + "CameraSettingsDialog.h" + "ColorBar.cpp" + "ColorBar.h" + "ColorPicker.cpp" + "ColorPicker.h" + "ColorPickerDialogClass.cpp" + "ColorPickerDialogClass.h" + "ColorSelectionDialog.cpp" + "ColorSelectionDialog.h" + "ColorUtils.cpp" + "ColorUtils.h" + "DataTreeView.cpp" + "DataTreeView.h" + "DeviceSelectionDialog.cpp" + "DeviceSelectionDialog.h" + "DialogToolbar.cpp" + "DialogToolbar.h" + "DirectoryDialog.cpp" + "DirectoryDialog.h" + "EditLODDialog.cpp" + "EditLODDialog.h" + "EmitterColorPropPage.cpp" + "EmitterColorPropPage.h" + "EmitterFramePropPage.cpp" + "EmitterFramePropPage.h" + "EmitterGeneralPropPage.cpp" + "EmitterGeneralPropPage.h" + "EmitterInstanceList.cpp" + "EmitterInstanceList.h" + "EmitterLineGroupPropPage.cpp" + "EmitterLineGroupPropPage.h" + "EmitterLinePropPage.cpp" + "EmitterLinePropPage.h" + "EmitterParticlePropPage.cpp" + "EmitterParticlePropPage.h" + "EmitterPhysicsPropPage.cpp" + "EmitterPhysicsPropPage.h" + "EmitterPropertySheet.cpp" + "EmitterPropertySheet.h" + "EmitterRotationPropPage.cpp" + "EmitterRotationPropPage.h" + "EmitterSizePropPage.cpp" + "EmitterSizePropPage.h" + "EmitterUserPropPage.cpp" + "EmitterUserPropPage.h" + "GammaDialog.cpp" + "GammaDialog.h" + "Globals.cpp" + "Globals.h" + "GraphicView.cpp" + "GraphicView.h" + "HierarchyPropPage.cpp" + "HierarchyPropPage.h" + "LODDefs.h" + "MainFrm.cpp" + "MainFrm.h" + "MeshPropPage.cpp" + "MeshPropPage.h" + "OpacitySettingsDialog.cpp" + "OpacitySettingsDialog.h" + "OpacityVectorDialog.cpp" + "OpacityVectorDialog.h" + "ParticleBlurTimeKeyDialog.cpp" + "ParticleBlurTimeKeyDialog.h" + "ParticleFrameKeyDialog.cpp" + "ParticleFrameKeyDialog.h" + "ParticleRotationKeyDialog.cpp" + "ParticleRotationKeyDialog.h" + "ParticleSizeDialog.cpp" + "ParticleSizeDialog.h" + "PlaySoundDialog.cpp" + "PlaySoundDialog.h" + "ResolutionDialog.cpp" + "ResolutionDialog.h" + "resource.h" + "RestrictedFileDialog.cpp" + "RestrictedFileDialog.h" + "RingColorPropPage.cpp" + "RingColorPropPage.h" + "RingGeneralPropPage.cpp" + "RingGeneralPropPage.h" + "RingPropertySheet.cpp" + "RingPropertySheet.h" + "RingSizePropPage.cpp" + "RingSizePropPage.h" + "SaveSettingsDialog.cpp" + "SaveSettingsDialog.h" + "ScaleDialog.cpp" + "ScaleDialog.h" + "SceneLightDialog.cpp" + "SceneLightDialog.h" + "ScreenCursor.cpp" + "ScreenCursor.h" + "SoundEditDialog.cpp" + "SoundEditDialog.h" + "SphereColorPropPage.cpp" + "SphereColorPropPage.h" + "SphereGeneralPropPage.cpp" + "SphereGeneralPropPage.h" + "SpherePropertySheet.cpp" + "SpherePropertySheet.h" + "SphereSizePropPage.cpp" + "SphereSizePropPage.h" + #"SphereUtils.cpp" # Unused and does not compile + #"SphereUtils.h" # Unused and does not compile + "StdAfx.cpp" + "StdAfx.h" + #"TextureMgrDialog.cpp" # Unused + #"TextureMgrDialog.h" # Unused + "TexturePathDialog.cpp" + "TexturePathDialog.h" + #"TextureSettingsDialog.cpp" # Unused + #"TextureSettingsDialog.h" # Unused + "Toolbar.cpp" + "Toolbar.h" + "Utils.cpp" + "Utils.h" + "Vector3RndCombo.cpp" + "Vector3RndCombo.H" + "ViewerAssetMgr.cpp" + "ViewerAssetMgr.h" + "ViewerScene.cpp" + "ViewerScene.h" + "VolumeRandomDialog.cpp" + "VolumeRandomDialog.h" + "W3DView.cpp" + "W3DView.h" + "W3DViewDoc.cpp" + "W3DViewDoc.h" + "W3DViewView.cpp" + "W3DViewView.h" +) + +add_library(corei_w3dview INTERFACE) + +target_sources(corei_w3dview INTERFACE ${W3DVIEW_SRC}) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(corei_w3dview INTERFACE W3DView.rc) +endif() diff --git a/GeneralsMD/Code/Tools/W3DView/CameraDistanceDialog.cpp b/Core/Tools/W3DView/CameraDistanceDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/CameraDistanceDialog.cpp rename to Core/Tools/W3DView/CameraDistanceDialog.cpp index 617600fd9a..1ceeefb9b9 100644 --- a/GeneralsMD/Code/Tools/W3DView/CameraDistanceDialog.cpp +++ b/Core/Tools/W3DView/CameraDistanceDialog.cpp @@ -26,7 +26,7 @@ #include "graphicview.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/CameraDistanceDialog.h b/Core/Tools/W3DView/CameraDistanceDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/CameraDistanceDialog.h rename to Core/Tools/W3DView/CameraDistanceDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/CameraSettingsDialog.cpp b/Core/Tools/W3DView/CameraSettingsDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/CameraSettingsDialog.cpp rename to Core/Tools/W3DView/CameraSettingsDialog.cpp index e48e2cc818..44f58a6cc4 100644 --- a/GeneralsMD/Code/Tools/W3DView/CameraSettingsDialog.cpp +++ b/Core/Tools/W3DView/CameraSettingsDialog.cpp @@ -29,7 +29,7 @@ #include "viewerscene.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/CameraSettingsDialog.h b/Core/Tools/W3DView/CameraSettingsDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/CameraSettingsDialog.h rename to Core/Tools/W3DView/CameraSettingsDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ColorBar.cpp b/Core/Tools/W3DView/ColorBar.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ColorBar.cpp rename to Core/Tools/W3DView/ColorBar.cpp index 65d4949f56..5dbc76d3dc 100644 --- a/GeneralsMD/Code/Tools/W3DView/ColorBar.cpp +++ b/Core/Tools/W3DView/ColorBar.cpp @@ -29,7 +29,7 @@ #include -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ColorBar.h b/Core/Tools/W3DView/ColorBar.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ColorBar.h rename to Core/Tools/W3DView/ColorBar.h diff --git a/GeneralsMD/Code/Tools/W3DView/ColorPicker.cpp b/Core/Tools/W3DView/ColorPicker.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ColorPicker.cpp rename to Core/Tools/W3DView/ColorPicker.cpp index d3b6da263f..40ca884c26 100644 --- a/GeneralsMD/Code/Tools/W3DView/ColorPicker.cpp +++ b/Core/Tools/W3DView/ColorPicker.cpp @@ -29,7 +29,7 @@ #include "utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ColorPicker.h b/Core/Tools/W3DView/ColorPicker.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ColorPicker.h rename to Core/Tools/W3DView/ColorPicker.h diff --git a/GeneralsMD/Code/Tools/W3DView/ColorPickerDialogClass.cpp b/Core/Tools/W3DView/ColorPickerDialogClass.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ColorPickerDialogClass.cpp rename to Core/Tools/W3DView/ColorPickerDialogClass.cpp index e5774e9547..dc12331399 100644 --- a/GeneralsMD/Code/Tools/W3DView/ColorPickerDialogClass.cpp +++ b/Core/Tools/W3DView/ColorPickerDialogClass.cpp @@ -25,7 +25,7 @@ #include "colorpicker.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ColorPickerDialogClass.h b/Core/Tools/W3DView/ColorPickerDialogClass.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ColorPickerDialogClass.h rename to Core/Tools/W3DView/ColorPickerDialogClass.h diff --git a/GeneralsMD/Code/Tools/W3DView/ColorSelectionDialog.cpp b/Core/Tools/W3DView/ColorSelectionDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ColorSelectionDialog.cpp rename to Core/Tools/W3DView/ColorSelectionDialog.cpp index 5d155b11d2..8690e8ce46 100644 --- a/GeneralsMD/Code/Tools/W3DView/ColorSelectionDialog.cpp +++ b/Core/Tools/W3DView/ColorSelectionDialog.cpp @@ -25,7 +25,7 @@ #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ColorSelectionDialog.h b/Core/Tools/W3DView/ColorSelectionDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ColorSelectionDialog.h rename to Core/Tools/W3DView/ColorSelectionDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ColorUtils.cpp b/Core/Tools/W3DView/ColorUtils.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ColorUtils.cpp rename to Core/Tools/W3DView/ColorUtils.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/ColorUtils.h b/Core/Tools/W3DView/ColorUtils.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ColorUtils.h rename to Core/Tools/W3DView/ColorUtils.h diff --git a/GeneralsMD/Code/Tools/W3DView/DataTreeView.cpp b/Core/Tools/W3DView/DataTreeView.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/DataTreeView.cpp rename to Core/Tools/W3DView/DataTreeView.cpp index 8831f7518e..9c4be29433 100644 --- a/GeneralsMD/Code/Tools/W3DView/DataTreeView.cpp +++ b/Core/Tools/W3DView/DataTreeView.cpp @@ -56,7 +56,7 @@ #include "ViewerScene.h" #include "texture.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -139,7 +139,7 @@ CDataTreeView::OnDraw (CDC *pDC) ///////////////////////////////////////////////////////////////////////////// // CDataTreeView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CDataTreeView::AssertValid() const { CTreeView::AssertValid(); @@ -149,7 +149,7 @@ void CDataTreeView::Dump(CDumpContext& dc) const { CTreeView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CDataTreeView message handlers diff --git a/GeneralsMD/Code/Tools/W3DView/DataTreeView.h b/Core/Tools/W3DView/DataTreeView.h similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/DataTreeView.h rename to Core/Tools/W3DView/DataTreeView.h index 44f0073774..d8f8e72e1b 100644 --- a/GeneralsMD/Code/Tools/W3DView/DataTreeView.h +++ b/Core/Tools/W3DView/DataTreeView.h @@ -63,7 +63,7 @@ class CDataTreeView : public CTreeView // Implementation protected: virtual ~CDataTreeView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/W3DView/DeviceSelectionDialog.cpp b/Core/Tools/W3DView/DeviceSelectionDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/DeviceSelectionDialog.cpp rename to Core/Tools/W3DView/DeviceSelectionDialog.cpp index 959efd6697..60237c7441 100644 --- a/GeneralsMD/Code/Tools/W3DView/DeviceSelectionDialog.cpp +++ b/Core/Tools/W3DView/DeviceSelectionDialog.cpp @@ -30,7 +30,7 @@ #include "Utils.H" #include "rddesc.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/DeviceSelectionDialog.h b/Core/Tools/W3DView/DeviceSelectionDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/DeviceSelectionDialog.h rename to Core/Tools/W3DView/DeviceSelectionDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/DialogToolbar.cpp b/Core/Tools/W3DView/DialogToolbar.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/DialogToolbar.cpp rename to Core/Tools/W3DView/DialogToolbar.cpp index cd42749846..2f85a9e2d4 100644 --- a/GeneralsMD/Code/Tools/W3DView/DialogToolbar.cpp +++ b/Core/Tools/W3DView/DialogToolbar.cpp @@ -58,7 +58,7 @@ DialogToolbarClass::DialogToolbarClass (void) return ; } -#ifdef _DEBUG +#ifdef RTS_DEBUG void DialogToolbarClass::AssertValid() const { CToolBar::AssertValid(); @@ -68,7 +68,7 @@ void DialogToolbarClass::Dump(CDumpContext& dc) const { CToolBar::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG /////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/Tools/W3DView/DialogToolbar.h b/Core/Tools/W3DView/DialogToolbar.h similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/DialogToolbar.h rename to Core/Tools/W3DView/DialogToolbar.h index d1c1777241..98b7efc275 100644 --- a/GeneralsMD/Code/Tools/W3DView/DialogToolbar.h +++ b/Core/Tools/W3DView/DialogToolbar.h @@ -74,7 +74,7 @@ class DialogToolbarClass : public CToolBar // Implementation protected: -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/W3DView/DirectoryDialog.cpp b/Core/Tools/W3DView/DirectoryDialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/DirectoryDialog.cpp rename to Core/Tools/W3DView/DirectoryDialog.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/DirectoryDialog.h b/Core/Tools/W3DView/DirectoryDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/DirectoryDialog.h rename to Core/Tools/W3DView/DirectoryDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/EditLODDialog.cpp b/Core/Tools/W3DView/EditLODDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EditLODDialog.cpp rename to Core/Tools/W3DView/EditLODDialog.cpp index 2ee165fbac..cece7851bd 100644 --- a/GeneralsMD/Code/Tools/W3DView/EditLODDialog.cpp +++ b/Core/Tools/W3DView/EditLODDialog.cpp @@ -28,7 +28,7 @@ #include "W3DViewDoc.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EditLODDialog.h b/Core/Tools/W3DView/EditLODDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EditLODDialog.h rename to Core/Tools/W3DView/EditLODDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterColorPropPage.cpp b/Core/Tools/W3DView/EmitterColorPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterColorPropPage.cpp rename to Core/Tools/W3DView/EmitterColorPropPage.cpp index 15af6f9eff..68f8ebd88b 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterColorPropPage.cpp +++ b/Core/Tools/W3DView/EmitterColorPropPage.cpp @@ -28,7 +28,7 @@ #include "colorutils.h" #include "emitterinstancelist.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterColorPropPage.h b/Core/Tools/W3DView/EmitterColorPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterColorPropPage.h rename to Core/Tools/W3DView/EmitterColorPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterFramePropPage.cpp b/Core/Tools/W3DView/EmitterFramePropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterFramePropPage.cpp rename to Core/Tools/W3DView/EmitterFramePropPage.cpp index 77951da09f..13e5291f93 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterFramePropPage.cpp +++ b/Core/Tools/W3DView/EmitterFramePropPage.cpp @@ -26,7 +26,7 @@ #include "ParticleFrameKeyDialog.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterFramePropPage.h b/Core/Tools/W3DView/EmitterFramePropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterFramePropPage.h rename to Core/Tools/W3DView/EmitterFramePropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterGeneralPropPage.cpp b/Core/Tools/W3DView/EmitterGeneralPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterGeneralPropPage.cpp rename to Core/Tools/W3DView/EmitterGeneralPropPage.cpp index 9d5564d956..c9189b741d 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterGeneralPropPage.cpp +++ b/Core/Tools/W3DView/EmitterGeneralPropPage.cpp @@ -29,7 +29,7 @@ #include "Shader.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterGeneralPropPage.h b/Core/Tools/W3DView/EmitterGeneralPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterGeneralPropPage.h rename to Core/Tools/W3DView/EmitterGeneralPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterInstanceList.cpp b/Core/Tools/W3DView/EmitterInstanceList.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterInstanceList.cpp rename to Core/Tools/W3DView/EmitterInstanceList.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterInstanceList.h b/Core/Tools/W3DView/EmitterInstanceList.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterInstanceList.h rename to Core/Tools/W3DView/EmitterInstanceList.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterLineGroupPropPage.cpp b/Core/Tools/W3DView/EmitterLineGroupPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterLineGroupPropPage.cpp rename to Core/Tools/W3DView/EmitterLineGroupPropPage.cpp index d46168885a..2b8b60c2a3 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterLineGroupPropPage.cpp +++ b/Core/Tools/W3DView/EmitterLineGroupPropPage.cpp @@ -28,7 +28,7 @@ #include "ColorBar.H" #include "ParticleBlurTimeKeyDialog.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterLineGroupPropPage.h b/Core/Tools/W3DView/EmitterLineGroupPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterLineGroupPropPage.h rename to Core/Tools/W3DView/EmitterLineGroupPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterLinePropPage.cpp b/Core/Tools/W3DView/EmitterLinePropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterLinePropPage.cpp rename to Core/Tools/W3DView/EmitterLinePropPage.cpp index e4df4be17b..9247fbae94 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterLinePropPage.cpp +++ b/Core/Tools/W3DView/EmitterLinePropPage.cpp @@ -26,7 +26,7 @@ #include "EmitterInstanceList.h" #include "Utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterLinePropPage.h b/Core/Tools/W3DView/EmitterLinePropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterLinePropPage.h rename to Core/Tools/W3DView/EmitterLinePropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterParticlePropPage.cpp b/Core/Tools/W3DView/EmitterParticlePropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterParticlePropPage.cpp rename to Core/Tools/W3DView/EmitterParticlePropPage.cpp index f17f6f5499..d3a26efcac 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterParticlePropPage.cpp +++ b/Core/Tools/W3DView/EmitterParticlePropPage.cpp @@ -28,7 +28,7 @@ #include "VolumeRandomDialog.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterParticlePropPage.h b/Core/Tools/W3DView/EmitterParticlePropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterParticlePropPage.h rename to Core/Tools/W3DView/EmitterParticlePropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterPhysicsPropPage.cpp b/Core/Tools/W3DView/EmitterPhysicsPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterPhysicsPropPage.cpp rename to Core/Tools/W3DView/EmitterPhysicsPropPage.cpp index 042e5bd91b..8b89c19c9e 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterPhysicsPropPage.cpp +++ b/Core/Tools/W3DView/EmitterPhysicsPropPage.cpp @@ -27,7 +27,7 @@ #include "VolumeRandomDialog.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterPhysicsPropPage.h b/Core/Tools/W3DView/EmitterPhysicsPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterPhysicsPropPage.h rename to Core/Tools/W3DView/EmitterPhysicsPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterPropertySheet.cpp b/Core/Tools/W3DView/EmitterPropertySheet.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterPropertySheet.cpp rename to Core/Tools/W3DView/EmitterPropertySheet.cpp index f5da44ae1b..c6997ae9fb 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterPropertySheet.cpp +++ b/Core/Tools/W3DView/EmitterPropertySheet.cpp @@ -43,7 +43,7 @@ #include "texture.h" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterPropertySheet.h b/Core/Tools/W3DView/EmitterPropertySheet.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterPropertySheet.h rename to Core/Tools/W3DView/EmitterPropertySheet.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterRotationPropPage.cpp b/Core/Tools/W3DView/EmitterRotationPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterRotationPropPage.cpp rename to Core/Tools/W3DView/EmitterRotationPropPage.cpp index 02a009bd6d..994870c85e 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterRotationPropPage.cpp +++ b/Core/Tools/W3DView/EmitterRotationPropPage.cpp @@ -26,7 +26,7 @@ #include "ParticleRotationKeyDialog.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterRotationPropPage.h b/Core/Tools/W3DView/EmitterRotationPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterRotationPropPage.h rename to Core/Tools/W3DView/EmitterRotationPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterSizePropPage.cpp b/Core/Tools/W3DView/EmitterSizePropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterSizePropPage.cpp rename to Core/Tools/W3DView/EmitterSizePropPage.cpp index 2189a0eb16..19eeb24115 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterSizePropPage.cpp +++ b/Core/Tools/W3DView/EmitterSizePropPage.cpp @@ -26,7 +26,7 @@ #include "ParticleSizeDialog.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterSizePropPage.h b/Core/Tools/W3DView/EmitterSizePropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterSizePropPage.h rename to Core/Tools/W3DView/EmitterSizePropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterUserPropPage.cpp b/Core/Tools/W3DView/EmitterUserPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/EmitterUserPropPage.cpp rename to Core/Tools/W3DView/EmitterUserPropPage.cpp index f4e4753c96..a6f0a7cac4 100644 --- a/GeneralsMD/Code/Tools/W3DView/EmitterUserPropPage.cpp +++ b/Core/Tools/W3DView/EmitterUserPropPage.cpp @@ -26,7 +26,7 @@ #include "Part_Emt.H" #include "EmitterInstanceList.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/EmitterUserPropPage.h b/Core/Tools/W3DView/EmitterUserPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/EmitterUserPropPage.h rename to Core/Tools/W3DView/EmitterUserPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/GammaDialog.cpp b/Core/Tools/W3DView/GammaDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/GammaDialog.cpp rename to Core/Tools/W3DView/GammaDialog.cpp index 851f4790e0..622a4affa4 100644 --- a/GeneralsMD/Code/Tools/W3DView/GammaDialog.cpp +++ b/Core/Tools/W3DView/GammaDialog.cpp @@ -24,7 +24,7 @@ #include "GammaDialog.h" #include "dx8wrapper.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/GammaDialog.h b/Core/Tools/W3DView/GammaDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/GammaDialog.h rename to Core/Tools/W3DView/GammaDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/Globals.cpp b/Core/Tools/W3DView/Globals.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Globals.cpp rename to Core/Tools/W3DView/Globals.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/Globals.h b/Core/Tools/W3DView/Globals.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Globals.h rename to Core/Tools/W3DView/Globals.h diff --git a/GeneralsMD/Code/Tools/W3DView/GraphicView.cpp b/Core/Tools/W3DView/GraphicView.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/GraphicView.cpp rename to Core/Tools/W3DView/GraphicView.cpp index 0375873b03..c2c9c7284a 100644 --- a/GeneralsMD/Code/Tools/W3DView/GraphicView.cpp +++ b/Core/Tools/W3DView/GraphicView.cpp @@ -48,7 +48,7 @@ #include "dx8wrapper.h" #include "matrix3.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -144,7 +144,7 @@ CGraphicView::OnDraw (CDC* pDC) } -#ifdef _DEBUG +#ifdef RTS_DEBUG void CGraphicView::AssertValid() const { CView::AssertValid(); @@ -154,7 +154,7 @@ void CGraphicView::Dump(CDumpContext& dc) const { CView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG @@ -546,7 +546,7 @@ CGraphicView::RepaintView // // Let the audio class think // - WWAudioClass::Get_Instance ()->On_Frame_Update (); + WWAudioClass::Get_Instance ()->On_Frame_Update (WW3D::Get_Frame_Time()); // // Update the count of particles and polys in the status bar diff --git a/GeneralsMD/Code/Tools/W3DView/GraphicView.h b/Core/Tools/W3DView/GraphicView.h similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/GraphicView.h rename to Core/Tools/W3DView/GraphicView.h index 7337b986f1..60798740b2 100644 --- a/GeneralsMD/Code/Tools/W3DView/GraphicView.h +++ b/Core/Tools/W3DView/GraphicView.h @@ -71,7 +71,7 @@ class CGraphicView : public CView // Implementation protected: virtual ~CGraphicView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/W3DView/HierarchyPropPage.cpp b/Core/Tools/W3DView/HierarchyPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/HierarchyPropPage.cpp rename to Core/Tools/W3DView/HierarchyPropPage.cpp index 74c920567f..9b7119eeed 100644 --- a/GeneralsMD/Code/Tools/W3DView/HierarchyPropPage.cpp +++ b/Core/Tools/W3DView/HierarchyPropPage.cpp @@ -28,7 +28,7 @@ #include "MeshPropPage.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/HierarchyPropPage.h b/Core/Tools/W3DView/HierarchyPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/HierarchyPropPage.h rename to Core/Tools/W3DView/HierarchyPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/LODDefs.h b/Core/Tools/W3DView/LODDefs.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/LODDefs.h rename to Core/Tools/W3DView/LODDefs.h diff --git a/GeneralsMD/Code/Tools/W3DView/MainFrm.cpp b/Core/Tools/W3DView/MainFrm.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/MainFrm.cpp rename to Core/Tools/W3DView/MainFrm.cpp index f7aa346cbe..2629edc938 100644 --- a/GeneralsMD/Code/Tools/W3DView/MainFrm.cpp +++ b/Core/Tools/W3DView/MainFrm.cpp @@ -81,7 +81,7 @@ #include "ww3d.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -623,7 +623,7 @@ CMainFrame::PreCreateWindow (CREATESTRUCT& cs) ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); @@ -634,7 +634,7 @@ void CMainFrame::Dump(CDumpContext& dc) const CFrameWnd::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG //////////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/Tools/W3DView/MainFrm.h b/Core/Tools/W3DView/MainFrm.h similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/MainFrm.h rename to Core/Tools/W3DView/MainFrm.h index ac364967c2..9549096bfb 100644 --- a/GeneralsMD/Code/Tools/W3DView/MainFrm.h +++ b/Core/Tools/W3DView/MainFrm.h @@ -67,7 +67,7 @@ class CMainFrame : public CFrameWnd // Implementation public: virtual ~CMainFrame(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/W3DView/MeshPropPage.cpp b/Core/Tools/W3DView/MeshPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/MeshPropPage.cpp rename to Core/Tools/W3DView/MeshPropPage.cpp index e314717f95..a34741d966 100644 --- a/GeneralsMD/Code/Tools/W3DView/MeshPropPage.cpp +++ b/Core/Tools/W3DView/MeshPropPage.cpp @@ -28,7 +28,7 @@ #include "MeshMdl.H" #include "w3d_file.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/MeshPropPage.h b/Core/Tools/W3DView/MeshPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/MeshPropPage.h rename to Core/Tools/W3DView/MeshPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/OpacitySettingsDialog.cpp b/Core/Tools/W3DView/OpacitySettingsDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/OpacitySettingsDialog.cpp rename to Core/Tools/W3DView/OpacitySettingsDialog.cpp index 9993cd89b8..2f5716af5d 100644 --- a/GeneralsMD/Code/Tools/W3DView/OpacitySettingsDialog.cpp +++ b/Core/Tools/W3DView/OpacitySettingsDialog.cpp @@ -36,7 +36,7 @@ #include "OpacitySettingsDialog.h" #include "ColorBar.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/OpacitySettingsDialog.h b/Core/Tools/W3DView/OpacitySettingsDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/OpacitySettingsDialog.h rename to Core/Tools/W3DView/OpacitySettingsDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/OpacityVectorDialog.cpp b/Core/Tools/W3DView/OpacityVectorDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/OpacityVectorDialog.cpp rename to Core/Tools/W3DView/OpacityVectorDialog.cpp index baa7fa5af9..6773d4f4b0 100644 --- a/GeneralsMD/Code/Tools/W3DView/OpacityVectorDialog.cpp +++ b/Core/Tools/W3DView/OpacityVectorDialog.cpp @@ -30,7 +30,7 @@ #include "euler.h" #include "matrix3.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/OpacityVectorDialog.h b/Core/Tools/W3DView/OpacityVectorDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/OpacityVectorDialog.h rename to Core/Tools/W3DView/OpacityVectorDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleBlurTimeKeyDialog.cpp b/Core/Tools/W3DView/ParticleBlurTimeKeyDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ParticleBlurTimeKeyDialog.cpp rename to Core/Tools/W3DView/ParticleBlurTimeKeyDialog.cpp index 6d4aeeba21..f57e8d29db 100644 --- a/GeneralsMD/Code/Tools/W3DView/ParticleBlurTimeKeyDialog.cpp +++ b/Core/Tools/W3DView/ParticleBlurTimeKeyDialog.cpp @@ -24,7 +24,7 @@ #include "ParticleBlurTimeKeyDialog.h" #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleBlurTimeKeyDialog.h b/Core/Tools/W3DView/ParticleBlurTimeKeyDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ParticleBlurTimeKeyDialog.h rename to Core/Tools/W3DView/ParticleBlurTimeKeyDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleFrameKeyDialog.cpp b/Core/Tools/W3DView/ParticleFrameKeyDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ParticleFrameKeyDialog.cpp rename to Core/Tools/W3DView/ParticleFrameKeyDialog.cpp index fe0078af0a..cc52540d87 100644 --- a/GeneralsMD/Code/Tools/W3DView/ParticleFrameKeyDialog.cpp +++ b/Core/Tools/W3DView/ParticleFrameKeyDialog.cpp @@ -24,7 +24,7 @@ #include "ParticleFrameKeyDialog.h" #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleFrameKeyDialog.h b/Core/Tools/W3DView/ParticleFrameKeyDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ParticleFrameKeyDialog.h rename to Core/Tools/W3DView/ParticleFrameKeyDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleRotationKeyDialog.cpp b/Core/Tools/W3DView/ParticleRotationKeyDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ParticleRotationKeyDialog.cpp rename to Core/Tools/W3DView/ParticleRotationKeyDialog.cpp index 82551d42c8..99caef21a4 100644 --- a/GeneralsMD/Code/Tools/W3DView/ParticleRotationKeyDialog.cpp +++ b/Core/Tools/W3DView/ParticleRotationKeyDialog.cpp @@ -24,7 +24,7 @@ #include "ParticleRotationKeyDialog.h" #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleRotationKeyDialog.h b/Core/Tools/W3DView/ParticleRotationKeyDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ParticleRotationKeyDialog.h rename to Core/Tools/W3DView/ParticleRotationKeyDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleSizeDialog.cpp b/Core/Tools/W3DView/ParticleSizeDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ParticleSizeDialog.cpp rename to Core/Tools/W3DView/ParticleSizeDialog.cpp index 3ac1579e6c..0cc186dd33 100644 --- a/GeneralsMD/Code/Tools/W3DView/ParticleSizeDialog.cpp +++ b/Core/Tools/W3DView/ParticleSizeDialog.cpp @@ -24,7 +24,7 @@ #include "ParticleSizeDialog.h" #include "Utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ParticleSizeDialog.h b/Core/Tools/W3DView/ParticleSizeDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ParticleSizeDialog.h rename to Core/Tools/W3DView/ParticleSizeDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/PlaySoundDialog.cpp b/Core/Tools/W3DView/PlaySoundDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/PlaySoundDialog.cpp rename to Core/Tools/W3DView/PlaySoundDialog.cpp index 60063cd95a..49ae62af18 100644 --- a/GeneralsMD/Code/Tools/W3DView/PlaySoundDialog.cpp +++ b/Core/Tools/W3DView/PlaySoundDialog.cpp @@ -25,7 +25,7 @@ #include "audiblesound.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/PlaySoundDialog.h b/Core/Tools/W3DView/PlaySoundDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/PlaySoundDialog.h rename to Core/Tools/W3DView/PlaySoundDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/Res/GAMMA.BMP b/Core/Tools/W3DView/Res/GAMMA.BMP similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/GAMMA.BMP rename to Core/Tools/W3DView/Res/GAMMA.BMP diff --git a/GeneralsMD/Code/Tools/W3DView/Res/Light.w3d b/Core/Tools/W3DView/Res/Light.w3d similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/Light.w3d rename to Core/Tools/W3DView/Res/Light.w3d diff --git a/GeneralsMD/Code/Tools/W3DView/Res/Toolbar.bmp b/Core/Tools/W3DView/Res/Toolbar.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/Toolbar.bmp rename to Core/Tools/W3DView/Res/Toolbar.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/W3DView.ico b/Core/Tools/W3DView/Res/W3DView.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/W3DView.ico rename to Core/Tools/W3DView/Res/W3DView.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/W3DView.rc2 b/Core/Tools/W3DView/Res/W3DView.rc2 similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/W3DView.rc2 rename to Core/Tools/W3DView/Res/W3DView.rc2 diff --git a/GeneralsMD/Code/Tools/W3DView/Res/W3DViewDoc.ico b/Core/Tools/W3DView/Res/W3DViewDoc.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/W3DViewDoc.ico rename to Core/Tools/W3DView/Res/W3DViewDoc.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/aggregat.ico b/Core/Tools/W3DView/Res/aggregat.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/aggregat.ico rename to Core/Tools/W3DView/Res/aggregat.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/animatio.ico b/Core/Tools/W3DView/Res/animatio.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/animatio.ico rename to Core/Tools/W3DView/Res/animatio.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/bmp00002.bmp b/Core/Tools/W3DView/Res/bmp00002.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/bmp00002.bmp rename to Core/Tools/W3DView/Res/bmp00002.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/cur00001.cur b/Core/Tools/W3DView/Res/cur00001.cur similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/cur00001.cur rename to Core/Tools/W3DView/Res/cur00001.cur diff --git a/GeneralsMD/Code/Tools/W3DView/Res/cursor.tga b/Core/Tools/W3DView/Res/cursor.tga similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/cursor.tga rename to Core/Tools/W3DView/Res/cursor.tga diff --git a/GeneralsMD/Code/Tools/W3DView/Res/cursor1.cur b/Core/Tools/W3DView/Res/cursor1.cur similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/cursor1.cur rename to Core/Tools/W3DView/Res/cursor1.cur diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ffwd.bmp b/Core/Tools/W3DView/Res/ffwd.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ffwd.bmp rename to Core/Tools/W3DView/Res/ffwd.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ffwdsel.bmp b/Core/Tools/W3DView/Res/ffwdsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ffwdsel.bmp rename to Core/Tools/W3DView/Res/ffwdsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/frame.ico b/Core/Tools/W3DView/Res/frame.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/frame.ico rename to Core/Tools/W3DView/Res/frame.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/grab.tga b/Core/Tools/W3DView/Res/grab.tga similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/grab.tga rename to Core/Tools/W3DView/Res/grab.tga diff --git a/GeneralsMD/Code/Tools/W3DView/Res/hierarch.ico b/Core/Tools/W3DView/Res/hierarch.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/hierarch.ico rename to Core/Tools/W3DView/Res/hierarch.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00001.ico b/Core/Tools/W3DView/Res/ico00001.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00001.ico rename to Core/Tools/W3DView/Res/ico00001.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00002.ico b/Core/Tools/W3DView/Res/ico00002.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00002.ico rename to Core/Tools/W3DView/Res/ico00002.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00003.ico b/Core/Tools/W3DView/Res/ico00003.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00003.ico rename to Core/Tools/W3DView/Res/ico00003.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00004.ico b/Core/Tools/W3DView/Res/ico00004.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00004.ico rename to Core/Tools/W3DView/Res/ico00004.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00005.ico b/Core/Tools/W3DView/Res/ico00005.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00005.ico rename to Core/Tools/W3DView/Res/ico00005.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00006.ico b/Core/Tools/W3DView/Res/ico00006.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00006.ico rename to Core/Tools/W3DView/Res/ico00006.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00007.ico b/Core/Tools/W3DView/Res/ico00007.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00007.ico rename to Core/Tools/W3DView/Res/ico00007.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00008.ico b/Core/Tools/W3DView/Res/ico00008.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00008.ico rename to Core/Tools/W3DView/Res/ico00008.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00009.ico b/Core/Tools/W3DView/Res/ico00009.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00009.ico rename to Core/Tools/W3DView/Res/ico00009.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00010.ico b/Core/Tools/W3DView/Res/ico00010.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00010.ico rename to Core/Tools/W3DView/Res/ico00010.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00011.ico b/Core/Tools/W3DView/Res/ico00011.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00011.ico rename to Core/Tools/W3DView/Res/ico00011.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00012.ico b/Core/Tools/W3DView/Res/ico00012.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00012.ico rename to Core/Tools/W3DView/Res/ico00012.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00013.ico b/Core/Tools/W3DView/Res/ico00013.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00013.ico rename to Core/Tools/W3DView/Res/ico00013.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00014.ico b/Core/Tools/W3DView/Res/ico00014.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00014.ico rename to Core/Tools/W3DView/Res/ico00014.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00015.ico b/Core/Tools/W3DView/Res/ico00015.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00015.ico rename to Core/Tools/W3DView/Res/ico00015.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00016.ico b/Core/Tools/W3DView/Res/ico00016.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00016.ico rename to Core/Tools/W3DView/Res/ico00016.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00017.ico b/Core/Tools/W3DView/Res/ico00017.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00017.ico rename to Core/Tools/W3DView/Res/ico00017.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ico00018.ico b/Core/Tools/W3DView/Res/ico00018.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ico00018.ico rename to Core/Tools/W3DView/Res/ico00018.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/icon1.ico b/Core/Tools/W3DView/Res/icon1.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/icon1.ico rename to Core/Tools/W3DView/Res/icon1.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/icon2.ico b/Core/Tools/W3DView/Res/icon2.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/icon2.ico rename to Core/Tools/W3DView/Res/icon2.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/line.ico b/Core/Tools/W3DView/Res/line.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/line.ico rename to Core/Tools/W3DView/Res/line.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/lineup.ico b/Core/Tools/W3DView/Res/lineup.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/lineup.ico rename to Core/Tools/W3DView/Res/lineup.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/material.ico b/Core/Tools/W3DView/Res/material.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/material.ico rename to Core/Tools/W3DView/Res/material.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/openfold.ico b/Core/Tools/W3DView/Res/openfold.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/openfold.ico rename to Core/Tools/W3DView/Res/openfold.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/orbit.tga b/Core/Tools/W3DView/Res/orbit.tga similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/orbit.tga rename to Core/Tools/W3DView/Res/orbit.tga diff --git a/GeneralsMD/Code/Tools/W3DView/Res/particle.ico b/Core/Tools/W3DView/Res/particle.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/particle.ico rename to Core/Tools/W3DView/Res/particle.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/pause.bmp b/Core/Tools/W3DView/Res/pause.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/pause.bmp rename to Core/Tools/W3DView/Res/pause.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/pausesel.bmp b/Core/Tools/W3DView/Res/pausesel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/pausesel.bmp rename to Core/Tools/W3DView/Res/pausesel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/play.bmp b/Core/Tools/W3DView/Res/play.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/play.bmp rename to Core/Tools/W3DView/Res/play.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/playsel.bmp b/Core/Tools/W3DView/Res/playsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/playsel.bmp rename to Core/Tools/W3DView/Res/playsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/reverse.bmp b/Core/Tools/W3DView/Res/reverse.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/reverse.bmp rename to Core/Tools/W3DView/Res/reverse.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/reversesel.bmp b/Core/Tools/W3DView/Res/reversesel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/reversesel.bmp rename to Core/Tools/W3DView/Res/reversesel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/rotatez.bmp b/Core/Tools/W3DView/Res/rotatez.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/rotatez.bmp rename to Core/Tools/W3DView/Res/rotatez.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/rotatezsel.bmp b/Core/Tools/W3DView/Res/rotatezsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/rotatezsel.bmp rename to Core/Tools/W3DView/Res/rotatezsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/rotation.ico b/Core/Tools/W3DView/Res/rotation.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/rotation.ico rename to Core/Tools/W3DView/Res/rotation.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/sound.ico b/Core/Tools/W3DView/Res/sound.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/sound.ico rename to Core/Tools/W3DView/Res/sound.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/stop.bmp b/Core/Tools/W3DView/Res/stop.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/stop.bmp rename to Core/Tools/W3DView/Res/stop.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/stopsel.bmp b/Core/Tools/W3DView/Res/stopsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/stopsel.bmp rename to Core/Tools/W3DView/Res/stopsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/user1.ico b/Core/Tools/W3DView/Res/user1.ico similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/user1.ico rename to Core/Tools/W3DView/Res/user1.ico diff --git a/GeneralsMD/Code/Tools/W3DView/Res/xdir.bmp b/Core/Tools/W3DView/Res/xdir.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/xdir.bmp rename to Core/Tools/W3DView/Res/xdir.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/xdirsel.bmp b/Core/Tools/W3DView/Res/xdirsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/xdirsel.bmp rename to Core/Tools/W3DView/Res/xdirsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ydir.bmp b/Core/Tools/W3DView/Res/ydir.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ydir.bmp rename to Core/Tools/W3DView/Res/ydir.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/ydirsel.bmp b/Core/Tools/W3DView/Res/ydirsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/ydirsel.bmp rename to Core/Tools/W3DView/Res/ydirsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/zdir.bmp b/Core/Tools/W3DView/Res/zdir.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/zdir.bmp rename to Core/Tools/W3DView/Res/zdir.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/zdirsel.bmp b/Core/Tools/W3DView/Res/zdirsel.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/zdirsel.bmp rename to Core/Tools/W3DView/Res/zdirsel.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/Res/zoom.tga b/Core/Tools/W3DView/Res/zoom.tga similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Res/zoom.tga rename to Core/Tools/W3DView/Res/zoom.tga diff --git a/GeneralsMD/Code/Tools/W3DView/ResolutionDialog.cpp b/Core/Tools/W3DView/ResolutionDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ResolutionDialog.cpp rename to Core/Tools/W3DView/ResolutionDialog.cpp index 05b57376c7..63a2992c2d 100644 --- a/GeneralsMD/Code/Tools/W3DView/ResolutionDialog.cpp +++ b/Core/Tools/W3DView/ResolutionDialog.cpp @@ -30,7 +30,7 @@ -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ResolutionDialog.h b/Core/Tools/W3DView/ResolutionDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ResolutionDialog.h rename to Core/Tools/W3DView/ResolutionDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/RestrictedFileDialog.cpp b/Core/Tools/W3DView/RestrictedFileDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/RestrictedFileDialog.cpp rename to Core/Tools/W3DView/RestrictedFileDialog.cpp index f951ee79a0..4b694f3e48 100644 --- a/GeneralsMD/Code/Tools/W3DView/RestrictedFileDialog.cpp +++ b/Core/Tools/W3DView/RestrictedFileDialog.cpp @@ -25,7 +25,7 @@ #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/RestrictedFileDialog.h b/Core/Tools/W3DView/RestrictedFileDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/RestrictedFileDialog.h rename to Core/Tools/W3DView/RestrictedFileDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/RingColorPropPage.cpp b/Core/Tools/W3DView/RingColorPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/RingColorPropPage.cpp rename to Core/Tools/W3DView/RingColorPropPage.cpp index 2218b6ee79..bf56754090 100644 --- a/GeneralsMD/Code/Tools/W3DView/RingColorPropPage.cpp +++ b/Core/Tools/W3DView/RingColorPropPage.cpp @@ -26,7 +26,7 @@ #include "colorutils.h" #include "utils.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/RingColorPropPage.h b/Core/Tools/W3DView/RingColorPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/RingColorPropPage.h rename to Core/Tools/W3DView/RingColorPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/RingGeneralPropPage.cpp b/Core/Tools/W3DView/RingGeneralPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/RingGeneralPropPage.cpp rename to Core/Tools/W3DView/RingGeneralPropPage.cpp index 58626c3e25..225c83ed45 100644 --- a/GeneralsMD/Code/Tools/W3DView/RingGeneralPropPage.cpp +++ b/Core/Tools/W3DView/RingGeneralPropPage.cpp @@ -26,7 +26,7 @@ #include "assetmgr.h" #include "texture.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/RingGeneralPropPage.h b/Core/Tools/W3DView/RingGeneralPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/RingGeneralPropPage.h rename to Core/Tools/W3DView/RingGeneralPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/RingPropertySheet.cpp b/Core/Tools/W3DView/RingPropertySheet.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/RingPropertySheet.cpp rename to Core/Tools/W3DView/RingPropertySheet.cpp index 624d27650a..09c718d67e 100644 --- a/GeneralsMD/Code/Tools/W3DView/RingPropertySheet.cpp +++ b/Core/Tools/W3DView/RingPropertySheet.cpp @@ -27,7 +27,7 @@ #include "assetmgr.h" #include "datatreeview.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/RingPropertySheet.h b/Core/Tools/W3DView/RingPropertySheet.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/RingPropertySheet.h rename to Core/Tools/W3DView/RingPropertySheet.h diff --git a/GeneralsMD/Code/Tools/W3DView/RingSizePropPage.cpp b/Core/Tools/W3DView/RingSizePropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/RingSizePropPage.cpp rename to Core/Tools/W3DView/RingSizePropPage.cpp index ef5f84821d..daaf3476db 100644 --- a/GeneralsMD/Code/Tools/W3DView/RingSizePropPage.cpp +++ b/Core/Tools/W3DView/RingSizePropPage.cpp @@ -26,7 +26,7 @@ #include "utils.h" #include "scaledialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/RingSizePropPage.h b/Core/Tools/W3DView/RingSizePropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/RingSizePropPage.h rename to Core/Tools/W3DView/RingSizePropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/SaveSettingsDialog.cpp b/Core/Tools/W3DView/SaveSettingsDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SaveSettingsDialog.cpp rename to Core/Tools/W3DView/SaveSettingsDialog.cpp index a0ce5b1069..e2b0cac9db 100644 --- a/GeneralsMD/Code/Tools/W3DView/SaveSettingsDialog.cpp +++ b/Core/Tools/W3DView/SaveSettingsDialog.cpp @@ -26,7 +26,7 @@ #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/SaveSettingsDialog.h b/Core/Tools/W3DView/SaveSettingsDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SaveSettingsDialog.h rename to Core/Tools/W3DView/SaveSettingsDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ScaleDialog.cpp b/Core/Tools/W3DView/ScaleDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/ScaleDialog.cpp rename to Core/Tools/W3DView/ScaleDialog.cpp index 09edef807c..18b98f597b 100644 --- a/GeneralsMD/Code/Tools/W3DView/ScaleDialog.cpp +++ b/Core/Tools/W3DView/ScaleDialog.cpp @@ -23,7 +23,7 @@ #include "w3dview.h" #include "ScaleDialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/ScaleDialog.h b/Core/Tools/W3DView/ScaleDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ScaleDialog.h rename to Core/Tools/W3DView/ScaleDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/SceneLightDialog.cpp b/Core/Tools/W3DView/SceneLightDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SceneLightDialog.cpp rename to Core/Tools/W3DView/SceneLightDialog.cpp index 77e3904670..b5905b70a6 100644 --- a/GeneralsMD/Code/Tools/W3DView/SceneLightDialog.cpp +++ b/Core/Tools/W3DView/SceneLightDialog.cpp @@ -29,7 +29,7 @@ #include "Light.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/SceneLightDialog.h b/Core/Tools/W3DView/SceneLightDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SceneLightDialog.h rename to Core/Tools/W3DView/SceneLightDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/ScreenCursor.cpp b/Core/Tools/W3DView/ScreenCursor.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ScreenCursor.cpp rename to Core/Tools/W3DView/ScreenCursor.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/ScreenCursor.h b/Core/Tools/W3DView/ScreenCursor.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ScreenCursor.h rename to Core/Tools/W3DView/ScreenCursor.h diff --git a/GeneralsMD/Code/Tools/W3DView/SoundEditDialog.cpp b/Core/Tools/W3DView/SoundEditDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SoundEditDialog.cpp rename to Core/Tools/W3DView/SoundEditDialog.cpp index 0555cc4974..67ec22e582 100644 --- a/GeneralsMD/Code/Tools/W3DView/SoundEditDialog.cpp +++ b/Core/Tools/W3DView/SoundEditDialog.cpp @@ -46,7 +46,7 @@ #include "assetmgr.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -112,7 +112,7 @@ END_MESSAGE_MAP() // SoundEditDialogClass // ///////////////////////////////////////////////////////////////////////////// -#ifdef _DEBUG +#ifdef RTS_DEBUG void SoundEditDialogClass::AssertValid() const { CDialog::AssertValid(); @@ -122,7 +122,7 @@ void SoundEditDialogClass::Dump(CDumpContext& dc) const { CDialog::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG diff --git a/GeneralsMD/Code/Tools/W3DView/SoundEditDialog.h b/Core/Tools/W3DView/SoundEditDialog.h similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SoundEditDialog.h rename to Core/Tools/W3DView/SoundEditDialog.h index 996187f0e6..8d4e63f28f 100644 --- a/GeneralsMD/Code/Tools/W3DView/SoundEditDialog.h +++ b/Core/Tools/W3DView/SoundEditDialog.h @@ -68,7 +68,7 @@ class SoundEditDialogClass : public CDialog // Implementation protected: -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/W3DView/SphereColorPropPage.cpp b/Core/Tools/W3DView/SphereColorPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SphereColorPropPage.cpp rename to Core/Tools/W3DView/SphereColorPropPage.cpp index 6c9d2fc767..a4ecdff020 100644 --- a/GeneralsMD/Code/Tools/W3DView/SphereColorPropPage.cpp +++ b/Core/Tools/W3DView/SphereColorPropPage.cpp @@ -27,7 +27,7 @@ #include "utils.h" #include "opacityvectordialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/SphereColorPropPage.h b/Core/Tools/W3DView/SphereColorPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SphereColorPropPage.h rename to Core/Tools/W3DView/SphereColorPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/SphereGeneralPropPage.cpp b/Core/Tools/W3DView/SphereGeneralPropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SphereGeneralPropPage.cpp rename to Core/Tools/W3DView/SphereGeneralPropPage.cpp index c430cc4e5c..310d15ea12 100644 --- a/GeneralsMD/Code/Tools/W3DView/SphereGeneralPropPage.cpp +++ b/Core/Tools/W3DView/SphereGeneralPropPage.cpp @@ -26,7 +26,7 @@ #include "assetmgr.h" #include "texture.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/SphereGeneralPropPage.h b/Core/Tools/W3DView/SphereGeneralPropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SphereGeneralPropPage.h rename to Core/Tools/W3DView/SphereGeneralPropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/SpherePropertySheet.cpp b/Core/Tools/W3DView/SpherePropertySheet.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SpherePropertySheet.cpp rename to Core/Tools/W3DView/SpherePropertySheet.cpp index c5d3a1007c..5e87fab5f8 100644 --- a/GeneralsMD/Code/Tools/W3DView/SpherePropertySheet.cpp +++ b/Core/Tools/W3DView/SpherePropertySheet.cpp @@ -27,7 +27,7 @@ #include "assetmgr.h" #include "datatreeview.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/SpherePropertySheet.h b/Core/Tools/W3DView/SpherePropertySheet.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SpherePropertySheet.h rename to Core/Tools/W3DView/SpherePropertySheet.h diff --git a/GeneralsMD/Code/Tools/W3DView/SphereSizePropPage.cpp b/Core/Tools/W3DView/SphereSizePropPage.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/SphereSizePropPage.cpp rename to Core/Tools/W3DView/SphereSizePropPage.cpp index cbd03885b8..b9c30a31ad 100644 --- a/GeneralsMD/Code/Tools/W3DView/SphereSizePropPage.cpp +++ b/Core/Tools/W3DView/SphereSizePropPage.cpp @@ -26,7 +26,7 @@ #include "utils.h" #include "scaledialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/SphereSizePropPage.h b/Core/Tools/W3DView/SphereSizePropPage.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SphereSizePropPage.h rename to Core/Tools/W3DView/SphereSizePropPage.h diff --git a/GeneralsMD/Code/Tools/W3DView/SphereUtils.cpp b/Core/Tools/W3DView/SphereUtils.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SphereUtils.cpp rename to Core/Tools/W3DView/SphereUtils.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/SphereUtils.h b/Core/Tools/W3DView/SphereUtils.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/SphereUtils.h rename to Core/Tools/W3DView/SphereUtils.h diff --git a/GeneralsMD/Code/Tools/W3DView/StdAfx.cpp b/Core/Tools/W3DView/StdAfx.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/StdAfx.cpp rename to Core/Tools/W3DView/StdAfx.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/StdAfx.h b/Core/Tools/W3DView/StdAfx.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/StdAfx.h rename to Core/Tools/W3DView/StdAfx.h diff --git a/GeneralsMD/Code/Tools/W3DView/TextureMgrDialog.cpp b/Core/Tools/W3DView/TextureMgrDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/TextureMgrDialog.cpp rename to Core/Tools/W3DView/TextureMgrDialog.cpp index effa0c3646..b694c012b8 100644 --- a/GeneralsMD/Code/Tools/W3DView/TextureMgrDialog.cpp +++ b/Core/Tools/W3DView/TextureMgrDialog.cpp @@ -45,7 +45,7 @@ #include "texture.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/TextureMgrDialog.h b/Core/Tools/W3DView/TextureMgrDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/TextureMgrDialog.h rename to Core/Tools/W3DView/TextureMgrDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/TexturePathDialog.cpp b/Core/Tools/W3DView/TexturePathDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/TexturePathDialog.cpp rename to Core/Tools/W3DView/TexturePathDialog.cpp index e669060332..aac4ae0d32 100644 --- a/GeneralsMD/Code/Tools/W3DView/TexturePathDialog.cpp +++ b/Core/Tools/W3DView/TexturePathDialog.cpp @@ -26,7 +26,7 @@ #include "utils.h" #include "directorydialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/TexturePathDialog.h b/Core/Tools/W3DView/TexturePathDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/TexturePathDialog.h rename to Core/Tools/W3DView/TexturePathDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/TextureSettingsDialog.cpp b/Core/Tools/W3DView/TextureSettingsDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/TextureSettingsDialog.cpp rename to Core/Tools/W3DView/TextureSettingsDialog.cpp index 0f1c887f41..e1a0bd852d 100644 --- a/GeneralsMD/Code/Tools/W3DView/TextureSettingsDialog.cpp +++ b/Core/Tools/W3DView/TextureSettingsDialog.cpp @@ -38,7 +38,7 @@ #include "Utils.H" #include "AssetMgr.H" -/*#ifdef _DEBUG +/*#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/TextureSettingsDialog.h b/Core/Tools/W3DView/TextureSettingsDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/TextureSettingsDialog.h rename to Core/Tools/W3DView/TextureSettingsDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/Toolbar.cpp b/Core/Tools/W3DView/Toolbar.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Toolbar.cpp rename to Core/Tools/W3DView/Toolbar.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/Toolbar.h b/Core/Tools/W3DView/Toolbar.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Toolbar.h rename to Core/Tools/W3DView/Toolbar.h diff --git a/GeneralsMD/Code/Tools/W3DView/Utils.cpp b/Core/Tools/W3DView/Utils.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Utils.cpp rename to Core/Tools/W3DView/Utils.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/Utils.h b/Core/Tools/W3DView/Utils.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Utils.h rename to Core/Tools/W3DView/Utils.h diff --git a/GeneralsMD/Code/Tools/W3DView/Vector3RndCombo.H b/Core/Tools/W3DView/Vector3RndCombo.H similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Vector3RndCombo.H rename to Core/Tools/W3DView/Vector3RndCombo.H diff --git a/GeneralsMD/Code/Tools/W3DView/Vector3RndCombo.cpp b/Core/Tools/W3DView/Vector3RndCombo.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/Vector3RndCombo.cpp rename to Core/Tools/W3DView/Vector3RndCombo.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/ViewerAssetMgr.cpp b/Core/Tools/W3DView/ViewerAssetMgr.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ViewerAssetMgr.cpp rename to Core/Tools/W3DView/ViewerAssetMgr.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/ViewerAssetMgr.h b/Core/Tools/W3DView/ViewerAssetMgr.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ViewerAssetMgr.h rename to Core/Tools/W3DView/ViewerAssetMgr.h diff --git a/GeneralsMD/Code/Tools/W3DView/ViewerScene.cpp b/Core/Tools/W3DView/ViewerScene.cpp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ViewerScene.cpp rename to Core/Tools/W3DView/ViewerScene.cpp diff --git a/GeneralsMD/Code/Tools/W3DView/ViewerScene.h b/Core/Tools/W3DView/ViewerScene.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/ViewerScene.h rename to Core/Tools/W3DView/ViewerScene.h diff --git a/GeneralsMD/Code/Tools/W3DView/VolumeRandomDialog.cpp b/Core/Tools/W3DView/VolumeRandomDialog.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/VolumeRandomDialog.cpp rename to Core/Tools/W3DView/VolumeRandomDialog.cpp index 52427c3341..45b5f2ffd6 100644 --- a/GeneralsMD/Code/Tools/W3DView/VolumeRandomDialog.cpp +++ b/Core/Tools/W3DView/VolumeRandomDialog.cpp @@ -37,7 +37,7 @@ #include "V3_Rnd.H" #include "Utils.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/W3DView/VolumeRandomDialog.h b/Core/Tools/W3DView/VolumeRandomDialog.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/VolumeRandomDialog.h rename to Core/Tools/W3DView/VolumeRandomDialog.h diff --git a/GeneralsMD/Code/Tools/W3DView/W3DView.cpp b/Core/Tools/W3DView/W3DView.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/W3DView.cpp rename to Core/Tools/W3DView/W3DView.cpp index c54b4008f0..3547ad4ff5 100644 --- a/GeneralsMD/Code/Tools/W3DView/W3DView.cpp +++ b/Core/Tools/W3DView/W3DView.cpp @@ -40,7 +40,7 @@ #include "ww3d.h" #include "AssetMgr.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -110,10 +110,10 @@ WinMain { int retcode = 0; -#ifndef _DEBUG +#ifndef RTS_DEBUG try { -#endif //_DEBUG +#endif //RTS_DEBUG //::AfxWinInit (hInstance, hPrevInstance, lpCmdLine, nCmdShow); //::AfxInitialize (FALSE, _MFC_VER); @@ -127,14 +127,14 @@ WinMain retcode = ::AfxWinMain (hInstance, hPrevInstance, lpCmdLine, nCmdShow); -#ifndef _DEBUG +#ifndef RTS_DEBUG } catch (...) { ::MessageBox (NULL, "Internal Application Error", "Unrecoverable Error", MB_ICONERROR | MB_OK); } -#endif //_DEBUG +#endif //RTS_DEBUG return retcode; } diff --git a/GeneralsMD/Code/Tools/W3DView/W3DView.h b/Core/Tools/W3DView/W3DView.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/W3DView.h rename to Core/Tools/W3DView/W3DView.h diff --git a/GeneralsMD/Code/Tools/W3DView/W3DView.rc b/Core/Tools/W3DView/W3DView.rc similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/W3DView.rc rename to Core/Tools/W3DView/W3DView.rc index 738fc80a95..3c640bc25b 100644 --- a/GeneralsMD/Code/Tools/W3DView/W3DView.rc +++ b/Core/Tools/W3DView/W3DView.rc @@ -2075,7 +2075,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 5,3,2,0 PRODUCTVERSION 5,3,2,0 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/W3DView/W3DView.reg b/Core/Tools/W3DView/W3DView.reg similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/W3DView.reg rename to Core/Tools/W3DView/W3DView.reg diff --git a/GeneralsMD/Code/Tools/W3DView/W3DViewDoc.cpp b/Core/Tools/W3DView/W3DViewDoc.cpp similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/W3DViewDoc.cpp rename to Core/Tools/W3DView/W3DViewDoc.cpp index baa0782345..aa84f7e569 100644 --- a/GeneralsMD/Code/Tools/W3DView/W3DViewDoc.cpp +++ b/Core/Tools/W3DView/W3DViewDoc.cpp @@ -62,7 +62,7 @@ #include "dazzle.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -333,7 +333,7 @@ CW3DViewDoc::Serialize(CArchive& ar) ///////////////////////////////////////////////////////////////////////////// // CW3DViewDoc diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CW3DViewDoc::AssertValid() const { CDocument::AssertValid(); @@ -343,7 +343,7 @@ void CW3DViewDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG /////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/Tools/W3DView/W3DViewDoc.h b/Core/Tools/W3DView/W3DViewDoc.h similarity index 99% rename from GeneralsMD/Code/Tools/W3DView/W3DViewDoc.h rename to Core/Tools/W3DView/W3DViewDoc.h index c751bcbdf2..fbdcbac949 100644 --- a/GeneralsMD/Code/Tools/W3DView/W3DViewDoc.h +++ b/Core/Tools/W3DView/W3DViewDoc.h @@ -94,7 +94,7 @@ class CW3DViewDoc : public CDocument // Implementation public: virtual ~CW3DViewDoc(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/W3DView/W3DViewView.cpp b/Core/Tools/W3DView/W3DViewView.cpp similarity index 97% rename from GeneralsMD/Code/Tools/W3DView/W3DViewView.cpp rename to Core/Tools/W3DView/W3DViewView.cpp index bd6dd56793..6a0f4f6337 100644 --- a/GeneralsMD/Code/Tools/W3DView/W3DViewView.cpp +++ b/Core/Tools/W3DView/W3DViewView.cpp @@ -25,7 +25,7 @@ #include "W3DViewDoc.h" #include "W3DViewView.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -76,7 +76,7 @@ void CW3DViewView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // CW3DViewView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CW3DViewView::AssertValid() const { CView::AssertValid(); @@ -92,7 +92,7 @@ CW3DViewDoc* CW3DViewView::GetDocument() // non-debug version is inline ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CW3DViewDoc))); return (CW3DViewDoc*)m_pDocument; } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CW3DViewView message handlers diff --git a/GeneralsMD/Code/Tools/W3DView/W3DViewView.h b/Core/Tools/W3DView/W3DViewView.h similarity index 96% rename from GeneralsMD/Code/Tools/W3DView/W3DViewView.h rename to Core/Tools/W3DView/W3DViewView.h index b46932239e..4f8ab9210d 100644 --- a/GeneralsMD/Code/Tools/W3DView/W3DViewView.h +++ b/Core/Tools/W3DView/W3DViewView.h @@ -52,7 +52,7 @@ class CW3DViewView : public CView // Implementation public: virtual ~CW3DViewView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif @@ -66,7 +66,7 @@ class CW3DViewView : public CView DECLARE_MESSAGE_MAP() }; -#ifndef _DEBUG // debug version in W3DViewView.cpp +#ifndef RTS_DEBUG // debug version in W3DViewView.cpp inline CW3DViewDoc* CW3DViewView::GetDocument() { return (CW3DViewDoc*)m_pDocument; } #endif diff --git a/GeneralsMD/Code/Tools/W3DView/bitmap1.bmp b/Core/Tools/W3DView/bitmap1.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/bitmap1.bmp rename to Core/Tools/W3DView/bitmap1.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/keyframe.bmp b/Core/Tools/W3DView/keyframe.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/keyframe.bmp rename to Core/Tools/W3DView/keyframe.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/marker.bmp b/Core/Tools/W3DView/marker.bmp similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/marker.bmp rename to Core/Tools/W3DView/marker.bmp diff --git a/GeneralsMD/Code/Tools/W3DView/resource.h b/Core/Tools/W3DView/resource.h similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/resource.h rename to Core/Tools/W3DView/resource.h diff --git a/GeneralsMD/Code/Tools/W3DView/resource.hm b/Core/Tools/W3DView/resource.hm similarity index 100% rename from GeneralsMD/Code/Tools/W3DView/resource.hm rename to Core/Tools/W3DView/resource.hm diff --git a/Generals/Code/Tools/WW3D/CMakeLists.txt b/Core/Tools/WW3D/CMakeLists.txt similarity index 100% rename from Generals/Code/Tools/WW3D/CMakeLists.txt rename to Core/Tools/WW3D/CMakeLists.txt diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/AlphaModifier.cpp b/Core/Tools/WW3D/max2w3d/AlphaModifier.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/AlphaModifier.cpp rename to Core/Tools/WW3D/max2w3d/AlphaModifier.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/AlphaModifier.h b/Core/Tools/WW3D/max2w3d/AlphaModifier.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/AlphaModifier.h rename to Core/Tools/WW3D/max2w3d/AlphaModifier.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/AppData.cpp b/Core/Tools/WW3D/max2w3d/AppData.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/AppData.cpp rename to Core/Tools/WW3D/max2w3d/AppData.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/CMakeLists.txt b/Core/Tools/WW3D/max2w3d/CMakeLists.txt similarity index 88% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/CMakeLists.txt rename to Core/Tools/WW3D/max2w3d/CMakeLists.txt index 65242ec2fe..433365eb59 100644 --- a/GeneralsMD/Code/Tools/WW3D/max2w3d/CMakeLists.txt +++ b/Core/Tools/WW3D/max2w3d/CMakeLists.txt @@ -146,19 +146,19 @@ set(MAX2W3D_SRC "w3dutil.h" ) -add_library(z_max2w3d SHARED) -set_target_properties(z_max2w3d PROPERTIES OUTPUT_NAME max2w3d SUFFIX ".dle") +add_library(core_max2w3d SHARED) +set_target_properties(core_max2w3d PROPERTIES OUTPUT_NAME max2w3d SUFFIX ".dle") -target_include_directories(z_max2w3d PRIVATE +target_include_directories(core_max2w3d PRIVATE "../pluglib" ) -target_sources(z_max2w3d PRIVATE ${MAX2W3D_SRC}) +target_sources(core_max2w3d PRIVATE ${MAX2W3D_SRC}) # TODO: What does W3D_MAX4 do? Needs cmake option? -target_compile_definitions(z_max2w3d PRIVATE W3D_MAX4) +target_compile_definitions(core_max2w3d PRIVATE W3D_MAX4) -target_link_libraries(z_max2w3d PRIVATE +target_link_libraries(core_max2w3d PRIVATE Comctl32 # This is only linked to have its basetsd.h used instead of the vs6's basetsd.h # The headers typedef INT_PTR to different types, but maxsdk expects it @@ -166,11 +166,11 @@ target_link_libraries(z_max2w3d PRIVATE d3d8lib maxsdk winmm - z_pluglib + core_pluglib ) -set_target_properties(z_max2w3d PROPERTIES LINK_FLAGS "/DEF:max2w3d.def") +set_target_properties(core_max2w3d PROPERTIES LINK_FLAGS "/DEF:max2w3d.def") if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(z_max2w3d PRIVATE max2w3d.rc) + target_sources(core_max2w3d PRIVATE max2w3d.rc) endif() diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/ExportAll.cpp b/Core/Tools/WW3D/max2w3d/ExportAll.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/ExportAll.cpp rename to Core/Tools/WW3D/max2w3d/ExportAll.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/ExportAllDlg.cpp b/Core/Tools/WW3D/max2w3d/ExportAllDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/ExportAllDlg.cpp rename to Core/Tools/WW3D/max2w3d/ExportAllDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/ExportAllDlg.h b/Core/Tools/WW3D/max2w3d/ExportAllDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/ExportAllDlg.h rename to Core/Tools/WW3D/max2w3d/ExportAllDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/FormClass.cpp b/Core/Tools/WW3D/max2w3d/FormClass.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/FormClass.cpp rename to Core/Tools/WW3D/max2w3d/FormClass.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/FormClass.h b/Core/Tools/WW3D/max2w3d/FormClass.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/FormClass.h rename to Core/Tools/WW3D/max2w3d/FormClass.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtl.cpp b/Core/Tools/WW3D/max2w3d/GameMtl.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtl.cpp rename to Core/Tools/WW3D/max2w3d/GameMtl.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlDlg.cpp b/Core/Tools/WW3D/max2w3d/GameMtlDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlDlg.cpp rename to Core/Tools/WW3D/max2w3d/GameMtlDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlDlg.h b/Core/Tools/WW3D/max2w3d/GameMtlDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlDlg.h rename to Core/Tools/WW3D/max2w3d/GameMtlDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlForm.cpp b/Core/Tools/WW3D/max2w3d/GameMtlForm.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlForm.cpp rename to Core/Tools/WW3D/max2w3d/GameMtlForm.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlForm.h b/Core/Tools/WW3D/max2w3d/GameMtlForm.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlForm.h rename to Core/Tools/WW3D/max2w3d/GameMtlForm.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp b/Core/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp rename to Core/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.h b/Core/Tools/WW3D/max2w3d/GameMtlPassDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.h rename to Core/Tools/WW3D/max2w3d/GameMtlPassDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp b/Core/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp rename to Core/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.h b/Core/Tools/WW3D/max2w3d/GameMtlShaderDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.h rename to Core/Tools/WW3D/max2w3d/GameMtlShaderDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp b/Core/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp rename to Core/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.h b/Core/Tools/WW3D/max2w3d/GameMtlTextureDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.h rename to Core/Tools/WW3D/max2w3d/GameMtlTextureDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp b/Core/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp rename to Core/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h b/Core/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h rename to Core/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/InputDlg.cpp b/Core/Tools/WW3D/max2w3d/InputDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/InputDlg.cpp rename to Core/Tools/WW3D/max2w3d/InputDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/InputDlg.h b/Core/Tools/WW3D/max2w3d/InputDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/InputDlg.h rename to Core/Tools/WW3D/max2w3d/InputDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/LightGlareSave.cpp b/Core/Tools/WW3D/max2w3d/LightGlareSave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/LightGlareSave.cpp rename to Core/Tools/WW3D/max2w3d/LightGlareSave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/LightGlareSave.h b/Core/Tools/WW3D/max2w3d/LightGlareSave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/LightGlareSave.h rename to Core/Tools/WW3D/max2w3d/LightGlareSave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeform.cpp b/Core/Tools/WW3D/max2w3d/MeshDeform.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeform.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeform.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeform.h b/Core/Tools/WW3D/max2w3d/MeshDeform.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeform.h rename to Core/Tools/WW3D/max2w3d/MeshDeform.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformData.cpp b/Core/Tools/WW3D/max2w3d/MeshDeformData.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformData.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeformData.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformData.h b/Core/Tools/WW3D/max2w3d/MeshDeformData.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformData.h rename to Core/Tools/WW3D/max2w3d/MeshDeformData.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformDefs.h b/Core/Tools/WW3D/max2w3d/MeshDeformDefs.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformDefs.h rename to Core/Tools/WW3D/max2w3d/MeshDeformDefs.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformPanel.cpp b/Core/Tools/WW3D/max2w3d/MeshDeformPanel.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformPanel.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeformPanel.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformPanel.h b/Core/Tools/WW3D/max2w3d/MeshDeformPanel.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformPanel.h rename to Core/Tools/WW3D/max2w3d/MeshDeformPanel.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSave.cpp b/Core/Tools/WW3D/max2w3d/MeshDeformSave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSave.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeformSave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSave.h b/Core/Tools/WW3D/max2w3d/MeshDeformSave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSave.h rename to Core/Tools/WW3D/max2w3d/MeshDeformSave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h b/Core/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h rename to Core/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp b/Core/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.h b/Core/Tools/WW3D/max2w3d/MeshDeformSaveSet.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.h rename to Core/Tools/WW3D/max2w3d/MeshDeformSaveSet.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSet.cpp b/Core/Tools/WW3D/max2w3d/MeshDeformSet.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSet.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeformSet.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSet.h b/Core/Tools/WW3D/max2w3d/MeshDeformSet.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformSet.h rename to Core/Tools/WW3D/max2w3d/MeshDeformSet.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformUndo.cpp b/Core/Tools/WW3D/max2w3d/MeshDeformUndo.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformUndo.cpp rename to Core/Tools/WW3D/max2w3d/MeshDeformUndo.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformUndo.h b/Core/Tools/WW3D/max2w3d/MeshDeformUndo.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/MeshDeformUndo.h rename to Core/Tools/WW3D/max2w3d/MeshDeformUndo.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/PCToPS2Material.cpp b/Core/Tools/WW3D/max2w3d/PCToPS2Material.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/PCToPS2Material.cpp rename to Core/Tools/WW3D/max2w3d/PCToPS2Material.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/PS2GameMtl.cpp b/Core/Tools/WW3D/max2w3d/PS2GameMtl.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/PS2GameMtl.cpp rename to Core/Tools/WW3D/max2w3d/PS2GameMtl.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp b/Core/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp rename to Core/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h b/Core/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h rename to Core/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h diff --git a/Generals/Code/Tools/WW3D/max2w3d/Res/DISK12.ICO b/Core/Tools/WW3D/max2w3d/Res/DISK12.ICO similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/Res/DISK12.ICO rename to Core/Tools/WW3D/max2w3d/Res/DISK12.ICO diff --git a/Generals/Code/Tools/WW3D/max2w3d/Res/one.bmp b/Core/Tools/WW3D/max2w3d/Res/one.bmp similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/Res/one.bmp rename to Core/Tools/WW3D/max2w3d/Res/one.bmp diff --git a/Generals/Code/Tools/WW3D/max2w3d/Res/orig.ico b/Core/Tools/WW3D/max2w3d/Res/orig.ico similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/Res/orig.ico rename to Core/Tools/WW3D/max2w3d/Res/orig.ico diff --git a/Generals/Code/Tools/WW3D/max2w3d/Res/orig1.ico b/Core/Tools/WW3D/max2w3d/Res/orig1.ico similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/Res/orig1.ico rename to Core/Tools/WW3D/max2w3d/Res/orig1.ico diff --git a/Generals/Code/Tools/WW3D/max2w3d/Res/two.bmp b/Core/Tools/WW3D/max2w3d/Res/two.bmp similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/Res/two.bmp rename to Core/Tools/WW3D/max2w3d/Res/two.bmp diff --git a/Generals/Code/Tools/WW3D/max2w3d/Res/ww3d.bmp b/Core/Tools/WW3D/max2w3d/Res/ww3d.bmp similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/Res/ww3d.bmp rename to Core/Tools/WW3D/max2w3d/Res/ww3d.bmp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/SceneSetup.cpp b/Core/Tools/WW3D/max2w3d/SceneSetup.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/SceneSetup.cpp rename to Core/Tools/WW3D/max2w3d/SceneSetup.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/SceneSetupDlg.cpp b/Core/Tools/WW3D/max2w3d/SceneSetupDlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/SceneSetupDlg.cpp rename to Core/Tools/WW3D/max2w3d/SceneSetupDlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/SceneSetupDlg.h b/Core/Tools/WW3D/max2w3d/SceneSetupDlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/SceneSetupDlg.h rename to Core/Tools/WW3D/max2w3d/SceneSetupDlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/SkinCopy.cpp b/Core/Tools/WW3D/max2w3d/SkinCopy.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/SkinCopy.cpp rename to Core/Tools/WW3D/max2w3d/SkinCopy.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/SnapPoints.cpp b/Core/Tools/WW3D/max2w3d/SnapPoints.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/SnapPoints.cpp rename to Core/Tools/WW3D/max2w3d/SnapPoints.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/SnapPoints.h b/Core/Tools/WW3D/max2w3d/SnapPoints.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/SnapPoints.h rename to Core/Tools/WW3D/max2w3d/SnapPoints.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/TARGA.CPP b/Core/Tools/WW3D/max2w3d/TARGA.CPP similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/TARGA.CPP rename to Core/Tools/WW3D/max2w3d/TARGA.CPP diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/TARGA.H b/Core/Tools/WW3D/max2w3d/TARGA.H similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/TARGA.H rename to Core/Tools/WW3D/max2w3d/TARGA.H diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Utility.cpp b/Core/Tools/WW3D/max2w3d/Utility.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/Utility.cpp rename to Core/Tools/WW3D/max2w3d/Utility.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/aabtreebuilder.cpp b/Core/Tools/WW3D/max2w3d/aabtreebuilder.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/aabtreebuilder.cpp rename to Core/Tools/WW3D/max2w3d/aabtreebuilder.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/aabtreebuilder.h b/Core/Tools/WW3D/max2w3d/aabtreebuilder.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/aabtreebuilder.h rename to Core/Tools/WW3D/max2w3d/aabtreebuilder.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/animationcompressionsettings.cpp b/Core/Tools/WW3D/max2w3d/animationcompressionsettings.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/animationcompressionsettings.cpp rename to Core/Tools/WW3D/max2w3d/animationcompressionsettings.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/animationcompressionsettings.h b/Core/Tools/WW3D/max2w3d/animationcompressionsettings.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/animationcompressionsettings.h rename to Core/Tools/WW3D/max2w3d/animationcompressionsettings.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/bchannel.cpp b/Core/Tools/WW3D/max2w3d/bchannel.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/bchannel.cpp rename to Core/Tools/WW3D/max2w3d/bchannel.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/bchannel.h b/Core/Tools/WW3D/max2w3d/bchannel.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/bchannel.h rename to Core/Tools/WW3D/max2w3d/bchannel.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/boneicon.cpp b/Core/Tools/WW3D/max2w3d/boneicon.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/boneicon.cpp rename to Core/Tools/WW3D/max2w3d/boneicon.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/boneicon.h b/Core/Tools/WW3D/max2w3d/boneicon.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/boneicon.h rename to Core/Tools/WW3D/max2w3d/boneicon.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/bpick.cpp b/Core/Tools/WW3D/max2w3d/bpick.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/bpick.cpp rename to Core/Tools/WW3D/max2w3d/bpick.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/bpick.h b/Core/Tools/WW3D/max2w3d/bpick.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/bpick.h rename to Core/Tools/WW3D/max2w3d/bpick.h diff --git a/Generals/Code/Tools/WW3D/max2w3d/changes.txt b/Core/Tools/WW3D/max2w3d/changes.txt similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/changes.txt rename to Core/Tools/WW3D/max2w3d/changes.txt diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/colboxsave.cpp b/Core/Tools/WW3D/max2w3d/colboxsave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/colboxsave.cpp rename to Core/Tools/WW3D/max2w3d/colboxsave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/colboxsave.h b/Core/Tools/WW3D/max2w3d/colboxsave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/colboxsave.h rename to Core/Tools/WW3D/max2w3d/colboxsave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/dazzlesave.cpp b/Core/Tools/WW3D/max2w3d/dazzlesave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/dazzlesave.cpp rename to Core/Tools/WW3D/max2w3d/dazzlesave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/dazzlesave.h b/Core/Tools/WW3D/max2w3d/dazzlesave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/dazzlesave.h rename to Core/Tools/WW3D/max2w3d/dazzlesave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/dllmain.cpp b/Core/Tools/WW3D/max2w3d/dllmain.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/dllmain.cpp rename to Core/Tools/WW3D/max2w3d/dllmain.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/dllmain.h b/Core/Tools/WW3D/max2w3d/dllmain.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/dllmain.h rename to Core/Tools/WW3D/max2w3d/dllmain.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/exportlog.cpp b/Core/Tools/WW3D/max2w3d/exportlog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/exportlog.cpp rename to Core/Tools/WW3D/max2w3d/exportlog.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/exportlog.h b/Core/Tools/WW3D/max2w3d/exportlog.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/exportlog.h rename to Core/Tools/WW3D/max2w3d/exportlog.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/floaterdialog.cpp b/Core/Tools/WW3D/max2w3d/floaterdialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/floaterdialog.cpp rename to Core/Tools/WW3D/max2w3d/floaterdialog.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/floaterdialog.h b/Core/Tools/WW3D/max2w3d/floaterdialog.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/floaterdialog.h rename to Core/Tools/WW3D/max2w3d/floaterdialog.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gamemaps.cpp b/Core/Tools/WW3D/max2w3d/gamemaps.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gamemaps.cpp rename to Core/Tools/WW3D/max2w3d/gamemaps.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gamemaps.h b/Core/Tools/WW3D/max2w3d/gamemaps.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gamemaps.h rename to Core/Tools/WW3D/max2w3d/gamemaps.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gamemtl.h b/Core/Tools/WW3D/max2w3d/gamemtl.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gamemtl.h rename to Core/Tools/WW3D/max2w3d/gamemtl.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/genlodextensiondialog.cpp b/Core/Tools/WW3D/max2w3d/genlodextensiondialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/genlodextensiondialog.cpp rename to Core/Tools/WW3D/max2w3d/genlodextensiondialog.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/genlodextensiondialog.h b/Core/Tools/WW3D/max2w3d/genlodextensiondialog.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/genlodextensiondialog.h rename to Core/Tools/WW3D/max2w3d/genlodextensiondialog.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp b/Core/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp rename to Core/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.h b/Core/Tools/WW3D/max2w3d/genmtlnamesdialog.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.h rename to Core/Tools/WW3D/max2w3d/genmtlnamesdialog.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gennamesdialog.cpp b/Core/Tools/WW3D/max2w3d/gennamesdialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gennamesdialog.cpp rename to Core/Tools/WW3D/max2w3d/gennamesdialog.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gennamesdialog.h b/Core/Tools/WW3D/max2w3d/gennamesdialog.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gennamesdialog.h rename to Core/Tools/WW3D/max2w3d/gennamesdialog.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/geometryexportcontext.h b/Core/Tools/WW3D/max2w3d/geometryexportcontext.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/geometryexportcontext.h rename to Core/Tools/WW3D/max2w3d/geometryexportcontext.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/geometryexporttask.cpp b/Core/Tools/WW3D/max2w3d/geometryexporttask.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/geometryexporttask.cpp rename to Core/Tools/WW3D/max2w3d/geometryexporttask.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/geometryexporttask.h b/Core/Tools/WW3D/max2w3d/geometryexporttask.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/geometryexporttask.h rename to Core/Tools/WW3D/max2w3d/geometryexporttask.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gmtldlg.cpp b/Core/Tools/WW3D/max2w3d/gmtldlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gmtldlg.cpp rename to Core/Tools/WW3D/max2w3d/gmtldlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gridsnapmodifier.cpp b/Core/Tools/WW3D/max2w3d/gridsnapmodifier.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gridsnapmodifier.cpp rename to Core/Tools/WW3D/max2w3d/gridsnapmodifier.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/gridsnapmodifier.h b/Core/Tools/WW3D/max2w3d/gridsnapmodifier.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/gridsnapmodifier.h rename to Core/Tools/WW3D/max2w3d/gridsnapmodifier.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/hiersave.cpp b/Core/Tools/WW3D/max2w3d/hiersave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/hiersave.cpp rename to Core/Tools/WW3D/max2w3d/hiersave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/hiersave.h b/Core/Tools/WW3D/max2w3d/hiersave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/hiersave.h rename to Core/Tools/WW3D/max2w3d/hiersave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/hlodsave.cpp b/Core/Tools/WW3D/max2w3d/hlodsave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/hlodsave.cpp rename to Core/Tools/WW3D/max2w3d/hlodsave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/hlodsave.h b/Core/Tools/WW3D/max2w3d/hlodsave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/hlodsave.h rename to Core/Tools/WW3D/max2w3d/hlodsave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/logdlg.cpp b/Core/Tools/WW3D/max2w3d/logdlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/logdlg.cpp rename to Core/Tools/WW3D/max2w3d/logdlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/logdlg.h b/Core/Tools/WW3D/max2w3d/logdlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/logdlg.h rename to Core/Tools/WW3D/max2w3d/logdlg.h diff --git a/Generals/Code/Tools/WW3D/max2w3d/max2w3d.def b/Core/Tools/WW3D/max2w3d/max2w3d.def similarity index 100% rename from Generals/Code/Tools/WW3D/max2w3d/max2w3d.def rename to Core/Tools/WW3D/max2w3d/max2w3d.def diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/max2w3d.rc b/Core/Tools/WW3D/max2w3d/max2w3d.rc similarity index 99% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/max2w3d.rc rename to Core/Tools/WW3D/max2w3d/max2w3d.rc index ed224c713b..5cd43dff9f 100644 --- a/GeneralsMD/Code/Tools/WW3D/max2w3d/max2w3d.rc +++ b/Core/Tools/WW3D/max2w3d/max2w3d.rc @@ -1806,7 +1806,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,5,0 PRODUCTVERSION 1,0,5,0 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/maxworldinfo.cpp b/Core/Tools/WW3D/max2w3d/maxworldinfo.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/maxworldinfo.cpp rename to Core/Tools/WW3D/max2w3d/maxworldinfo.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/maxworldinfo.h b/Core/Tools/WW3D/max2w3d/maxworldinfo.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/maxworldinfo.h rename to Core/Tools/WW3D/max2w3d/maxworldinfo.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/meshbuild.cpp b/Core/Tools/WW3D/max2w3d/meshbuild.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/meshbuild.cpp rename to Core/Tools/WW3D/max2w3d/meshbuild.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/meshbuild.h b/Core/Tools/WW3D/max2w3d/meshbuild.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/meshbuild.h rename to Core/Tools/WW3D/max2w3d/meshbuild.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/meshcon.cpp b/Core/Tools/WW3D/max2w3d/meshcon.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/meshcon.cpp rename to Core/Tools/WW3D/max2w3d/meshcon.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/meshcon.h b/Core/Tools/WW3D/max2w3d/meshcon.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/meshcon.h rename to Core/Tools/WW3D/max2w3d/meshcon.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/meshsave.cpp b/Core/Tools/WW3D/max2w3d/meshsave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/meshsave.cpp rename to Core/Tools/WW3D/max2w3d/meshsave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/meshsave.h b/Core/Tools/WW3D/max2w3d/meshsave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/meshsave.h rename to Core/Tools/WW3D/max2w3d/meshsave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/motion.cpp b/Core/Tools/WW3D/max2w3d/motion.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/motion.cpp rename to Core/Tools/WW3D/max2w3d/motion.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/motion.h b/Core/Tools/WW3D/max2w3d/motion.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/motion.h rename to Core/Tools/WW3D/max2w3d/motion.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/namedsel.cpp b/Core/Tools/WW3D/max2w3d/namedsel.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/namedsel.cpp rename to Core/Tools/WW3D/max2w3d/namedsel.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/namedsel.h b/Core/Tools/WW3D/max2w3d/namedsel.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/namedsel.h rename to Core/Tools/WW3D/max2w3d/namedsel.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/nullsave.cpp b/Core/Tools/WW3D/max2w3d/nullsave.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/nullsave.cpp rename to Core/Tools/WW3D/max2w3d/nullsave.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/nullsave.h b/Core/Tools/WW3D/max2w3d/nullsave.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/nullsave.h rename to Core/Tools/WW3D/max2w3d/nullsave.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp b/Core/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp rename to Core/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.h b/Core/Tools/WW3D/max2w3d/presetexportoptionsdialog.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.h rename to Core/Tools/WW3D/max2w3d/presetexportoptionsdialog.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/rcmenu.cpp b/Core/Tools/WW3D/max2w3d/rcmenu.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/rcmenu.cpp rename to Core/Tools/WW3D/max2w3d/rcmenu.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/rcmenu.h b/Core/Tools/WW3D/max2w3d/rcmenu.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/rcmenu.h rename to Core/Tools/WW3D/max2w3d/rcmenu.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/resource.h b/Core/Tools/WW3D/max2w3d/resource.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/resource.h rename to Core/Tools/WW3D/max2w3d/resource.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/simpdib.cpp b/Core/Tools/WW3D/max2w3d/simpdib.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/simpdib.cpp rename to Core/Tools/WW3D/max2w3d/simpdib.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/simpdib.h b/Core/Tools/WW3D/max2w3d/simpdib.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/simpdib.h rename to Core/Tools/WW3D/max2w3d/simpdib.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/skin.cpp b/Core/Tools/WW3D/max2w3d/skin.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/skin.cpp rename to Core/Tools/WW3D/max2w3d/skin.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/skin.h b/Core/Tools/WW3D/max2w3d/skin.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/skin.h rename to Core/Tools/WW3D/max2w3d/skin.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/skindata.cpp b/Core/Tools/WW3D/max2w3d/skindata.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/skindata.cpp rename to Core/Tools/WW3D/max2w3d/skindata.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/skindata.h b/Core/Tools/WW3D/max2w3d/skindata.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/skindata.h rename to Core/Tools/WW3D/max2w3d/skindata.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/util.cpp b/Core/Tools/WW3D/max2w3d/util.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/util.cpp rename to Core/Tools/WW3D/max2w3d/util.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/util.h b/Core/Tools/WW3D/max2w3d/util.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/util.h rename to Core/Tools/WW3D/max2w3d/util.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vchannel.cpp b/Core/Tools/WW3D/max2w3d/vchannel.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vchannel.cpp rename to Core/Tools/WW3D/max2w3d/vchannel.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vchannel.h b/Core/Tools/WW3D/max2w3d/vchannel.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vchannel.h rename to Core/Tools/WW3D/max2w3d/vchannel.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vxl.cpp b/Core/Tools/WW3D/max2w3d/vxl.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vxl.cpp rename to Core/Tools/WW3D/max2w3d/vxl.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vxl.h b/Core/Tools/WW3D/max2w3d/vxl.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vxl.h rename to Core/Tools/WW3D/max2w3d/vxl.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vxldbg.cpp b/Core/Tools/WW3D/max2w3d/vxldbg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vxldbg.cpp rename to Core/Tools/WW3D/max2w3d/vxldbg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vxldbg.h b/Core/Tools/WW3D/max2w3d/vxldbg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vxldbg.h rename to Core/Tools/WW3D/max2w3d/vxldbg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vxllayer.cpp b/Core/Tools/WW3D/max2w3d/vxllayer.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vxllayer.cpp rename to Core/Tools/WW3D/max2w3d/vxllayer.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/vxllayer.h b/Core/Tools/WW3D/max2w3d/vxllayer.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/vxllayer.h rename to Core/Tools/WW3D/max2w3d/vxllayer.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3d_file.h b/Core/Tools/WW3D/max2w3d/w3d_file.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3d_file.h rename to Core/Tools/WW3D/max2w3d/w3d_file.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3d_obsolete.h b/Core/Tools/WW3D/max2w3d/w3d_obsolete.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3d_obsolete.h rename to Core/Tools/WW3D/max2w3d/w3d_obsolete.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dappdata.cpp b/Core/Tools/WW3D/max2w3d/w3dappdata.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dappdata.cpp rename to Core/Tools/WW3D/max2w3d/w3dappdata.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dappdata.h b/Core/Tools/WW3D/max2w3d/w3dappdata.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dappdata.h rename to Core/Tools/WW3D/max2w3d/w3dappdata.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddesc.cpp b/Core/Tools/WW3D/max2w3d/w3ddesc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddesc.cpp rename to Core/Tools/WW3D/max2w3d/w3ddesc.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddesc.h b/Core/Tools/WW3D/max2w3d/w3ddesc.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddesc.h rename to Core/Tools/WW3D/max2w3d/w3ddesc.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddlg.cpp b/Core/Tools/WW3D/max2w3d/w3ddlg.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddlg.cpp rename to Core/Tools/WW3D/max2w3d/w3ddlg.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddlg.h b/Core/Tools/WW3D/max2w3d/w3ddlg.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3ddlg.h rename to Core/Tools/WW3D/max2w3d/w3ddlg.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dexp.cpp b/Core/Tools/WW3D/max2w3d/w3dexp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dexp.cpp rename to Core/Tools/WW3D/max2w3d/w3dexp.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dexp.h b/Core/Tools/WW3D/max2w3d/w3dexp.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dexp.h rename to Core/Tools/WW3D/max2w3d/w3dexp.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dmtl.cpp b/Core/Tools/WW3D/max2w3d/w3dmtl.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dmtl.cpp rename to Core/Tools/WW3D/max2w3d/w3dmtl.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dmtl.h b/Core/Tools/WW3D/max2w3d/w3dmtl.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dmtl.h rename to Core/Tools/WW3D/max2w3d/w3dmtl.h diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dutil.cpp b/Core/Tools/WW3D/max2w3d/w3dutil.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dutil.cpp rename to Core/Tools/WW3D/max2w3d/w3dutil.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/w3dutil.h b/Core/Tools/WW3D/max2w3d/w3dutil.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/max2w3d/w3dutil.h rename to Core/Tools/WW3D/max2w3d/w3dutil.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/BITTYPE.H b/Core/Tools/WW3D/pluglib/BITTYPE.H similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/BITTYPE.H rename to Core/Tools/WW3D/pluglib/BITTYPE.H diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/CMakeLists.txt b/Core/Tools/WW3D/pluglib/CMakeLists.txt similarity index 80% rename from GeneralsMD/Code/Tools/WW3D/pluglib/CMakeLists.txt rename to Core/Tools/WW3D/pluglib/CMakeLists.txt index 6c2f8192a4..9b286ad659 100644 --- a/GeneralsMD/Code/Tools/WW3D/pluglib/CMakeLists.txt +++ b/Core/Tools/WW3D/pluglib/CMakeLists.txt @@ -53,9 +53,9 @@ set(PLUGLIB_SRC "WWmatrix3.h" ) -add_library(z_pluglib STATIC) -set_target_properties(z_pluglib PROPERTIES OUTPUT_NAME pluglib) +add_library(core_pluglib STATIC) +set_target_properties(core_pluglib PROPERTIES OUTPUT_NAME pluglib) -target_sources(z_pluglib PRIVATE ${PLUGLIB_SRC}) +target_sources(core_pluglib PRIVATE ${PLUGLIB_SRC}) -target_link_libraries(z_pluglib PRIVATE maxsdk) +target_link_libraries(core_pluglib PRIVATE maxsdk) diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/EULER.CPP b/Core/Tools/WW3D/pluglib/EULER.CPP similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/EULER.CPP rename to Core/Tools/WW3D/pluglib/EULER.CPP diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/EULER.H b/Core/Tools/WW3D/pluglib/EULER.H similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/EULER.H rename to Core/Tools/WW3D/pluglib/EULER.H diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/PROGRESS.H b/Core/Tools/WW3D/pluglib/PROGRESS.H similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/PROGRESS.H rename to Core/Tools/WW3D/pluglib/PROGRESS.H diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/Vector.CPP b/Core/Tools/WW3D/pluglib/Vector.CPP similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/Vector.CPP rename to Core/Tools/WW3D/pluglib/Vector.CPP diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/Vector.H b/Core/Tools/WW3D/pluglib/Vector.H similarity index 99% rename from GeneralsMD/Code/Tools/WW3D/pluglib/Vector.H rename to Core/Tools/WW3D/pluglib/Vector.H index fe08a4be65..645cef71b7 100644 --- a/GeneralsMD/Code/Tools/WW3D/pluglib/Vector.H +++ b/Core/Tools/WW3D/pluglib/Vector.H @@ -303,7 +303,7 @@ template inline int VectorClass::ID(T const * ptr) { if (!IsValid) return(0); - return(((unsigned long)ptr - (unsigned long)&(*this)[0]) / sizeof(T)); + return(((uintptr_t)ptr - (uintptr_t)&(*this)[0]) / sizeof(T)); } diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/WWmatrix3.cpp b/Core/Tools/WW3D/pluglib/WWmatrix3.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/WWmatrix3.cpp rename to Core/Tools/WW3D/pluglib/WWmatrix3.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/WWmatrix3.h b/Core/Tools/WW3D/pluglib/WWmatrix3.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/WWmatrix3.h rename to Core/Tools/WW3D/pluglib/WWmatrix3.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/aaplane.h b/Core/Tools/WW3D/pluglib/aaplane.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/aaplane.h rename to Core/Tools/WW3D/pluglib/aaplane.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/always.h b/Core/Tools/WW3D/pluglib/always.h similarity index 99% rename from GeneralsMD/Code/Tools/WW3D/pluglib/always.h rename to Core/Tools/WW3D/pluglib/always.h index 428804165c..81d557d2da 100644 --- a/GeneralsMD/Code/Tools/WW3D/pluglib/always.h +++ b/Core/Tools/WW3D/pluglib/always.h @@ -48,7 +48,7 @@ ** This helps find leaks. */ //#define STEVES_NEW_CATCHER -#ifdef _DEBUG +#ifdef RTS_DEBUG #ifdef _MSC_VER #ifdef STEVES_NEW_CATCHER @@ -67,7 +67,7 @@ void* __cdecl operator new(unsigned int s); #endif //STEVES_NEW_CATCHER #endif //_MSC_VER -#endif //_DEBUG +#endif //RTS_DEBUG // Jani: Intel's C++ compiler issues too many warnings in WW libraries when using warning level 4 diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/bool.h b/Core/Tools/WW3D/pluglib/bool.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/bool.h rename to Core/Tools/WW3D/pluglib/bool.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/borlandc.h b/Core/Tools/WW3D/pluglib/borlandc.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/borlandc.h rename to Core/Tools/WW3D/pluglib/borlandc.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/chunkio.cpp b/Core/Tools/WW3D/pluglib/chunkio.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/chunkio.cpp rename to Core/Tools/WW3D/pluglib/chunkio.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/chunkio.h b/Core/Tools/WW3D/pluglib/chunkio.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/chunkio.h rename to Core/Tools/WW3D/pluglib/chunkio.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/errclass.h b/Core/Tools/WW3D/pluglib/errclass.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/errclass.h rename to Core/Tools/WW3D/pluglib/errclass.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/hashcalc.h b/Core/Tools/WW3D/pluglib/hashcalc.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/hashcalc.h rename to Core/Tools/WW3D/pluglib/hashcalc.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/hsv.cpp b/Core/Tools/WW3D/pluglib/hsv.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/hsv.cpp rename to Core/Tools/WW3D/pluglib/hsv.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/hsv.h b/Core/Tools/WW3D/pluglib/hsv.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/hsv.h rename to Core/Tools/WW3D/pluglib/hsv.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/iostruct.h b/Core/Tools/WW3D/pluglib/iostruct.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/iostruct.h rename to Core/Tools/WW3D/pluglib/iostruct.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/jshell.cpp b/Core/Tools/WW3D/pluglib/jshell.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/jshell.cpp rename to Core/Tools/WW3D/pluglib/jshell.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/matrix3d.cpp b/Core/Tools/WW3D/pluglib/matrix3d.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/matrix3d.cpp rename to Core/Tools/WW3D/pluglib/matrix3d.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/matrix3d.h b/Core/Tools/WW3D/pluglib/matrix3d.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/matrix3d.h rename to Core/Tools/WW3D/pluglib/matrix3d.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/matrix4.cpp b/Core/Tools/WW3D/pluglib/matrix4.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/matrix4.cpp rename to Core/Tools/WW3D/pluglib/matrix4.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/matrix4.h b/Core/Tools/WW3D/pluglib/matrix4.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/matrix4.h rename to Core/Tools/WW3D/pluglib/matrix4.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/nodefilt.cpp b/Core/Tools/WW3D/pluglib/nodefilt.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/nodefilt.cpp rename to Core/Tools/WW3D/pluglib/nodefilt.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/nodefilt.h b/Core/Tools/WW3D/pluglib/nodefilt.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/nodefilt.h rename to Core/Tools/WW3D/pluglib/nodefilt.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/nodelist.cpp b/Core/Tools/WW3D/pluglib/nodelist.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/nodelist.cpp rename to Core/Tools/WW3D/pluglib/nodelist.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/nodelist.h b/Core/Tools/WW3D/pluglib/nodelist.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/nodelist.h rename to Core/Tools/WW3D/pluglib/nodelist.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/noinit.h b/Core/Tools/WW3D/pluglib/noinit.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/noinit.h rename to Core/Tools/WW3D/pluglib/noinit.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/palette.cpp b/Core/Tools/WW3D/pluglib/palette.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/palette.cpp rename to Core/Tools/WW3D/pluglib/palette.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/palette.h b/Core/Tools/WW3D/pluglib/palette.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/palette.h rename to Core/Tools/WW3D/pluglib/palette.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/plane.h b/Core/Tools/WW3D/pluglib/plane.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/plane.h rename to Core/Tools/WW3D/pluglib/plane.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/rawfile.cpp b/Core/Tools/WW3D/pluglib/rawfile.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/rawfile.cpp rename to Core/Tools/WW3D/pluglib/rawfile.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/rawfile.h b/Core/Tools/WW3D/pluglib/rawfile.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/rawfile.h rename to Core/Tools/WW3D/pluglib/rawfile.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/realcrc.cpp b/Core/Tools/WW3D/pluglib/realcrc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/realcrc.cpp rename to Core/Tools/WW3D/pluglib/realcrc.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/realcrc.h b/Core/Tools/WW3D/pluglib/realcrc.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/realcrc.h rename to Core/Tools/WW3D/pluglib/realcrc.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/rgb.cpp b/Core/Tools/WW3D/pluglib/rgb.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/rgb.cpp rename to Core/Tools/WW3D/pluglib/rgb.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/rgb.h b/Core/Tools/WW3D/pluglib/rgb.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/rgb.h rename to Core/Tools/WW3D/pluglib/rgb.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/uarray.h b/Core/Tools/WW3D/pluglib/uarray.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/uarray.h rename to Core/Tools/WW3D/pluglib/uarray.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/vector2.h b/Core/Tools/WW3D/pluglib/vector2.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/vector2.h rename to Core/Tools/WW3D/pluglib/vector2.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/vector3.h b/Core/Tools/WW3D/pluglib/vector3.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/vector3.h rename to Core/Tools/WW3D/pluglib/vector3.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/vector3i.h b/Core/Tools/WW3D/pluglib/vector3i.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/vector3i.h rename to Core/Tools/WW3D/pluglib/vector3i.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/vector4.h b/Core/Tools/WW3D/pluglib/vector4.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/vector4.h rename to Core/Tools/WW3D/pluglib/vector4.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/visualc.h b/Core/Tools/WW3D/pluglib/visualc.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/visualc.h rename to Core/Tools/WW3D/pluglib/visualc.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/w3d_file.h b/Core/Tools/WW3D/pluglib/w3d_file.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/w3d_file.h rename to Core/Tools/WW3D/pluglib/w3d_file.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/w3dquat.cpp b/Core/Tools/WW3D/pluglib/w3dquat.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/w3dquat.cpp rename to Core/Tools/WW3D/pluglib/w3dquat.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/w3dquat.h b/Core/Tools/WW3D/pluglib/w3dquat.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/w3dquat.h rename to Core/Tools/WW3D/pluglib/w3dquat.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/watcom.h b/Core/Tools/WW3D/pluglib/watcom.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/watcom.h rename to Core/Tools/WW3D/pluglib/watcom.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/win.h b/Core/Tools/WW3D/pluglib/win.h similarity index 98% rename from GeneralsMD/Code/Tools/WW3D/pluglib/win.h rename to Core/Tools/WW3D/pluglib/win.h index 784bebefe1..0614e0b41c 100644 --- a/GeneralsMD/Code/Tools/WW3D/pluglib/win.h +++ b/Core/Tools/WW3D/pluglib/win.h @@ -74,15 +74,15 @@ extern HINSTANCE ProgramInstance; extern HWND MainWindow; extern bool GameInFocus; -#ifdef _DEBUG +#ifdef RTS_DEBUG void __cdecl Print_Win32Error(unsigned long win32Error); -#else // _DEBUG +#else // RTS_DEBUG #define Print_Win32Error -#endif // _DEBUG +#endif // RTS_DEBUG #else // _WINDOWS #include diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/wwfile.h b/Core/Tools/WW3D/pluglib/wwfile.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/wwfile.h rename to Core/Tools/WW3D/pluglib/wwfile.h diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/wwmath.cpp b/Core/Tools/WW3D/pluglib/wwmath.cpp similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/wwmath.cpp rename to Core/Tools/WW3D/pluglib/wwmath.cpp diff --git a/GeneralsMD/Code/Tools/WW3D/pluglib/wwmath.h b/Core/Tools/WW3D/pluglib/wwmath.h similarity index 100% rename from GeneralsMD/Code/Tools/WW3D/pluglib/wwmath.h rename to Core/Tools/WW3D/pluglib/wwmath.h diff --git a/Core/Tools/assetcull/CMakeLists.txt b/Core/Tools/assetcull/CMakeLists.txt new file mode 100644 index 0000000000..ce70dc9ab7 --- /dev/null +++ b/Core/Tools/assetcull/CMakeLists.txt @@ -0,0 +1,16 @@ +set(ASSETCULL_SRC + "assetcull.cpp" +) + +add_executable(core_assetcull WIN32) +set_target_properties(core_assetcull PROPERTIES OUTPUT_NAME assetcull) + +target_sources(core_assetcull PRIVATE ${ASSETCULL_SRC}) + +target_link_libraries(core_assetcull PRIVATE + core_config +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_link_options(core_assetcull PRIVATE /subsystem:console) +endif() diff --git a/GeneralsMD/Code/Tools/assetcull/assetcull.cpp b/Core/Tools/assetcull/assetcull.cpp similarity index 100% rename from GeneralsMD/Code/Tools/assetcull/assetcull.cpp rename to Core/Tools/assetcull/assetcull.cpp diff --git a/Core/Tools/buildVersionUpdate/CMakeLists.txt b/Core/Tools/buildVersionUpdate/CMakeLists.txt new file mode 100644 index 0000000000..cad2418d55 --- /dev/null +++ b/Core/Tools/buildVersionUpdate/CMakeLists.txt @@ -0,0 +1,13 @@ +set(BUILDVERSIONUPDATE_SRC + "buildVersionUpdate.cpp" +) + +add_executable(core_buildversionupdate WIN32) +set_target_properties(core_buildversionupdate PROPERTIES OUTPUT_NAME buildversionupdate) + +target_sources(core_buildversionupdate PRIVATE ${BUILDVERSIONUPDATE_SRC}) + +target_link_libraries(core_buildversionupdate PRIVATE + core_config + core_wwlib +) diff --git a/GeneralsMD/Code/Tools/buildVersionUpdate/buildVersionUpdate.cpp b/Core/Tools/buildVersionUpdate/buildVersionUpdate.cpp similarity index 100% rename from GeneralsMD/Code/Tools/buildVersionUpdate/buildVersionUpdate.cpp rename to Core/Tools/buildVersionUpdate/buildVersionUpdate.cpp diff --git a/GeneralsMD/Code/Tools/mangler/CMakeLists.txt b/Core/Tools/mangler/CMakeLists.txt similarity index 52% rename from GeneralsMD/Code/Tools/mangler/CMakeLists.txt rename to Core/Tools/mangler/CMakeLists.txt index ca6811c079..ae7e3ded64 100644 --- a/GeneralsMD/Code/Tools/mangler/CMakeLists.txt +++ b/Core/Tools/mangler/CMakeLists.txt @@ -56,40 +56,52 @@ set(MANGLERTEST_SRC "manglertest.cpp" ) -add_library(z_manglerlib STATIC) -set_target_properties(z_manglerlib PROPERTIES OUTPUT_NAME manglerlib) +add_library(core_manglerlib STATIC) +set_target_properties(core_manglerlib PROPERTIES OUTPUT_NAME manglerlib) -target_sources(z_manglerlib PUBLIC ${MANGLERLIB_SRC}) -target_include_directories(z_manglerlib PRIVATE . wlib wnet) -target_link_libraries(z_manglerlib PRIVATE wsock32) -target_link_libraries(z_manglerlib PUBLIC +target_sources(core_manglerlib PUBLIC ${MANGLERLIB_SRC}) +target_include_directories(core_manglerlib PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + wlib + wnet +) +target_link_libraries(core_manglerlib PRIVATE wsock32) +target_link_libraries(core_manglerlib PUBLIC core_config core_utility ) # mangler app -add_executable(z_mangler WIN32) -set_target_properties(z_mangler PROPERTIES OUTPUT_NAME mangler) +add_executable(core_mangler WIN32) +set_target_properties(core_mangler PROPERTIES OUTPUT_NAME mangler) -target_sources(z_mangler PRIVATE ${MANGLER_SRC}) -target_include_directories(z_mangler PRIVATE . wlib wnet) -target_link_libraries(z_mangler PRIVATE z_manglerlib) +target_sources(core_mangler PRIVATE ${MANGLER_SRC}) +target_include_directories(core_mangler PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + wlib + wnet +) +target_link_libraries(core_mangler PRIVATE core_manglerlib) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(z_mangler PRIVATE /subsystem:console) + target_link_options(core_mangler PRIVATE /subsystem:console) endif() # manglertest app -add_executable(z_manglertest WIN32) -set_target_properties(z_manglertest PROPERTIES OUTPUT_NAME manglertest) +add_executable(core_manglertest WIN32) +set_target_properties(core_manglertest PROPERTIES OUTPUT_NAME manglertest) -target_sources(z_manglertest PRIVATE ${MANGLERTEST_SRC}) -target_include_directories(z_manglertest PRIVATE . wlib wnet) -target_link_libraries(z_manglertest PRIVATE z_manglerlib) +target_sources(core_manglertest PRIVATE ${MANGLERTEST_SRC}) +target_include_directories(core_manglertest PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + wlib + wnet +) +target_link_libraries(core_manglertest PRIVATE core_manglerlib) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(z_manglertest PRIVATE /subsystem:console) + target_link_options(core_manglertest PRIVATE /subsystem:console) endif() diff --git a/GeneralsMD/Code/Tools/mangler/crc.cpp b/Core/Tools/mangler/crc.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/crc.cpp rename to Core/Tools/mangler/crc.cpp diff --git a/GeneralsMD/Code/Tools/mangler/crc.h b/Core/Tools/mangler/crc.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/crc.h rename to Core/Tools/mangler/crc.h diff --git a/GeneralsMD/Code/Tools/mangler/endian.h b/Core/Tools/mangler/endian.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/endian.h rename to Core/Tools/mangler/endian.h diff --git a/GeneralsMD/Code/Tools/mangler/mangler.cpp b/Core/Tools/mangler/mangler.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/mangler.cpp rename to Core/Tools/mangler/mangler.cpp diff --git a/GeneralsMD/Code/Tools/mangler/mangler.h b/Core/Tools/mangler/mangler.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/mangler.h rename to Core/Tools/mangler/mangler.h diff --git a/GeneralsMD/Code/Tools/mangler/manglertest.cpp b/Core/Tools/mangler/manglertest.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/manglertest.cpp rename to Core/Tools/mangler/manglertest.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/arraylist.h b/Core/Tools/mangler/wlib/arraylist.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/arraylist.h rename to Core/Tools/mangler/wlib/arraylist.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/configfile.cpp b/Core/Tools/mangler/wlib/configfile.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/configfile.cpp rename to Core/Tools/mangler/wlib/configfile.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/configfile.h b/Core/Tools/mangler/wlib/configfile.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/configfile.h rename to Core/Tools/mangler/wlib/configfile.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/critsec.cpp b/Core/Tools/mangler/wlib/critsec.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/critsec.cpp rename to Core/Tools/mangler/wlib/critsec.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/critsec.h b/Core/Tools/mangler/wlib/critsec.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/critsec.h rename to Core/Tools/mangler/wlib/critsec.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/dictionary.h b/Core/Tools/mangler/wlib/dictionary.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/dictionary.h rename to Core/Tools/mangler/wlib/dictionary.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/filed.h b/Core/Tools/mangler/wlib/filed.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/filed.h rename to Core/Tools/mangler/wlib/filed.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/linkedlist.h b/Core/Tools/mangler/wlib/linkedlist.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/linkedlist.h rename to Core/Tools/mangler/wlib/linkedlist.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/mboxd.h b/Core/Tools/mangler/wlib/mboxd.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/mboxd.h rename to Core/Tools/mangler/wlib/mboxd.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/monod.cpp b/Core/Tools/mangler/wlib/monod.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/monod.cpp rename to Core/Tools/mangler/wlib/monod.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/monod.h b/Core/Tools/mangler/wlib/monod.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/monod.h rename to Core/Tools/mangler/wlib/monod.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/odevice.h b/Core/Tools/mangler/wlib/odevice.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/odevice.h rename to Core/Tools/mangler/wlib/odevice.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/sem4.cpp b/Core/Tools/mangler/wlib/sem4.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/sem4.cpp rename to Core/Tools/mangler/wlib/sem4.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/sem4.h b/Core/Tools/mangler/wlib/sem4.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/sem4.h rename to Core/Tools/mangler/wlib/sem4.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/stderrd.h b/Core/Tools/mangler/wlib/stderrd.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/stderrd.h rename to Core/Tools/mangler/wlib/stderrd.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/stdoutd.h b/Core/Tools/mangler/wlib/stdoutd.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/stdoutd.h rename to Core/Tools/mangler/wlib/stdoutd.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/streamer.cpp b/Core/Tools/mangler/wlib/streamer.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/streamer.cpp rename to Core/Tools/mangler/wlib/streamer.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/streamer.h b/Core/Tools/mangler/wlib/streamer.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/streamer.h rename to Core/Tools/mangler/wlib/streamer.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/syslogd.cpp b/Core/Tools/mangler/wlib/syslogd.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/syslogd.cpp rename to Core/Tools/mangler/wlib/syslogd.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/syslogd.h b/Core/Tools/mangler/wlib/syslogd.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/syslogd.h rename to Core/Tools/mangler/wlib/syslogd.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/threadfac.cpp b/Core/Tools/mangler/wlib/threadfac.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/threadfac.cpp rename to Core/Tools/mangler/wlib/threadfac.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/threadfac.h b/Core/Tools/mangler/wlib/threadfac.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/threadfac.h rename to Core/Tools/mangler/wlib/threadfac.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/threadsafe.h b/Core/Tools/mangler/wlib/threadsafe.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/threadsafe.h rename to Core/Tools/mangler/wlib/threadsafe.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/timezone.cpp b/Core/Tools/mangler/wlib/timezone.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/timezone.cpp rename to Core/Tools/mangler/wlib/timezone.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/timezone.h b/Core/Tools/mangler/wlib/timezone.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/timezone.h rename to Core/Tools/mangler/wlib/timezone.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/ustring.h b/Core/Tools/mangler/wlib/ustring.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/ustring.h rename to Core/Tools/mangler/wlib/ustring.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wdebug.cpp b/Core/Tools/mangler/wlib/wdebug.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wdebug.cpp rename to Core/Tools/mangler/wlib/wdebug.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wdebug.h b/Core/Tools/mangler/wlib/wdebug.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wdebug.h rename to Core/Tools/mangler/wlib/wdebug.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wstring.cpp b/Core/Tools/mangler/wlib/wstring.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wstring.cpp rename to Core/Tools/mangler/wlib/wstring.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wstring.h b/Core/Tools/mangler/wlib/wstring.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wstring.h rename to Core/Tools/mangler/wlib/wstring.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wstypes.h b/Core/Tools/mangler/wlib/wstypes.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wstypes.h rename to Core/Tools/mangler/wlib/wstypes.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wtime.cpp b/Core/Tools/mangler/wlib/wtime.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wtime.cpp rename to Core/Tools/mangler/wlib/wtime.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/wtime.h b/Core/Tools/mangler/wlib/wtime.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/wtime.h rename to Core/Tools/mangler/wlib/wtime.h diff --git a/GeneralsMD/Code/Tools/mangler/wlib/xtime.cpp b/Core/Tools/mangler/wlib/xtime.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/xtime.cpp rename to Core/Tools/mangler/wlib/xtime.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wlib/xtime.h b/Core/Tools/mangler/wlib/xtime.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wlib/xtime.h rename to Core/Tools/mangler/wlib/xtime.h diff --git a/GeneralsMD/Code/Tools/mangler/wnet/field.cpp b/Core/Tools/mangler/wnet/field.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/field.cpp rename to Core/Tools/mangler/wnet/field.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wnet/field.h b/Core/Tools/mangler/wnet/field.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/field.h rename to Core/Tools/mangler/wnet/field.h diff --git a/GeneralsMD/Code/Tools/mangler/wnet/packet.cpp b/Core/Tools/mangler/wnet/packet.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/packet.cpp rename to Core/Tools/mangler/wnet/packet.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wnet/packet.h b/Core/Tools/mangler/wnet/packet.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/packet.h rename to Core/Tools/mangler/wnet/packet.h diff --git a/GeneralsMD/Code/Tools/mangler/wnet/tcp.cpp b/Core/Tools/mangler/wnet/tcp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/tcp.cpp rename to Core/Tools/mangler/wnet/tcp.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wnet/tcp.h b/Core/Tools/mangler/wnet/tcp.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/tcp.h rename to Core/Tools/mangler/wnet/tcp.h diff --git a/GeneralsMD/Code/Tools/mangler/wnet/udp.cpp b/Core/Tools/mangler/wnet/udp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/udp.cpp rename to Core/Tools/mangler/wnet/udp.cpp diff --git a/GeneralsMD/Code/Tools/mangler/wnet/udp.h b/Core/Tools/mangler/wnet/udp.h similarity index 100% rename from GeneralsMD/Code/Tools/mangler/wnet/udp.h rename to Core/Tools/mangler/wnet/udp.h diff --git a/Generals/Code/Tools/matchbot/CMakeLists.txt b/Core/Tools/matchbot/CMakeLists.txt similarity index 78% rename from Generals/Code/Tools/matchbot/CMakeLists.txt rename to Core/Tools/matchbot/CMakeLists.txt index 316701119f..b37c128ccc 100644 --- a/Generals/Code/Tools/matchbot/CMakeLists.txt +++ b/Core/Tools/matchbot/CMakeLists.txt @@ -59,14 +59,18 @@ set(MATCHBOT_SRC "wnet/udp.h" ) -add_executable(g_matchbot WIN32) -set_target_properties(g_matchbot PROPERTIES OUTPUT_NAME matchbot) +add_executable(core_matchbot WIN32) +set_target_properties(core_matchbot PROPERTIES OUTPUT_NAME matchbot) -target_sources(g_matchbot PRIVATE ${MATCHBOT_SRC}) +target_sources(core_matchbot PRIVATE ${MATCHBOT_SRC}) -target_include_directories(g_matchbot PRIVATE . wlib wnet) +target_include_directories(core_matchbot PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + wlib + wnet +) -target_link_libraries(g_matchbot PRIVATE +target_link_libraries(core_matchbot PRIVATE gamespy::gamespy core_config core_utility @@ -74,5 +78,5 @@ target_link_libraries(g_matchbot PRIVATE ) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(g_matchbot PRIVATE /subsystem:console) + target_link_options(core_matchbot PRIVATE /subsystem:console) endif() diff --git a/GeneralsMD/Code/Tools/matchbot/debug.cpp b/Core/Tools/matchbot/debug.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/debug.cpp rename to Core/Tools/matchbot/debug.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/debug.h b/Core/Tools/matchbot/debug.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/debug.h rename to Core/Tools/matchbot/debug.h diff --git a/GeneralsMD/Code/Tools/matchbot/encrypt.cpp b/Core/Tools/matchbot/encrypt.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/encrypt.cpp rename to Core/Tools/matchbot/encrypt.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/encrypt.h b/Core/Tools/matchbot/encrypt.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/encrypt.h rename to Core/Tools/matchbot/encrypt.h diff --git a/GeneralsMD/Code/Tools/matchbot/generals.cpp b/Core/Tools/matchbot/generals.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/generals.cpp rename to Core/Tools/matchbot/generals.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/generals.h b/Core/Tools/matchbot/generals.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/generals.h rename to Core/Tools/matchbot/generals.h diff --git a/GeneralsMD/Code/Tools/matchbot/global.cpp b/Core/Tools/matchbot/global.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/global.cpp rename to Core/Tools/matchbot/global.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/global.h b/Core/Tools/matchbot/global.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/global.h rename to Core/Tools/matchbot/global.h diff --git a/GeneralsMD/Code/Tools/matchbot/main.cpp b/Core/Tools/matchbot/main.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/main.cpp rename to Core/Tools/matchbot/main.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/matcher.cpp b/Core/Tools/matchbot/matcher.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/matcher.cpp rename to Core/Tools/matchbot/matcher.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/matcher.h b/Core/Tools/matchbot/matcher.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/matcher.h rename to Core/Tools/matchbot/matcher.h diff --git a/GeneralsMD/Code/Tools/matchbot/mydebug.cpp b/Core/Tools/matchbot/mydebug.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/mydebug.cpp rename to Core/Tools/matchbot/mydebug.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/mydebug.h b/Core/Tools/matchbot/mydebug.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/mydebug.h rename to Core/Tools/matchbot/mydebug.h diff --git a/GeneralsMD/Code/Tools/matchbot/rand.cpp b/Core/Tools/matchbot/rand.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/rand.cpp rename to Core/Tools/matchbot/rand.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/rand.h b/Core/Tools/matchbot/rand.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/rand.h rename to Core/Tools/matchbot/rand.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/arraylist.h b/Core/Tools/matchbot/wlib/arraylist.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/arraylist.h rename to Core/Tools/matchbot/wlib/arraylist.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/configfile.cpp b/Core/Tools/matchbot/wlib/configfile.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/configfile.cpp rename to Core/Tools/matchbot/wlib/configfile.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/configfile.h b/Core/Tools/matchbot/wlib/configfile.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/configfile.h rename to Core/Tools/matchbot/wlib/configfile.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/critsec.cpp b/Core/Tools/matchbot/wlib/critsec.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/critsec.cpp rename to Core/Tools/matchbot/wlib/critsec.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/critsec.h b/Core/Tools/matchbot/wlib/critsec.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/critsec.h rename to Core/Tools/matchbot/wlib/critsec.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/dictionary.h b/Core/Tools/matchbot/wlib/dictionary.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/dictionary.h rename to Core/Tools/matchbot/wlib/dictionary.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/filed.h b/Core/Tools/matchbot/wlib/filed.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/filed.h rename to Core/Tools/matchbot/wlib/filed.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/linkedlist.h b/Core/Tools/matchbot/wlib/linkedlist.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/linkedlist.h rename to Core/Tools/matchbot/wlib/linkedlist.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/mboxd.h b/Core/Tools/matchbot/wlib/mboxd.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/mboxd.h rename to Core/Tools/matchbot/wlib/mboxd.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/monod.cpp b/Core/Tools/matchbot/wlib/monod.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/monod.cpp rename to Core/Tools/matchbot/wlib/monod.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/monod.h b/Core/Tools/matchbot/wlib/monod.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/monod.h rename to Core/Tools/matchbot/wlib/monod.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/odevice.h b/Core/Tools/matchbot/wlib/odevice.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/odevice.h rename to Core/Tools/matchbot/wlib/odevice.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/sem4.cpp b/Core/Tools/matchbot/wlib/sem4.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/sem4.cpp rename to Core/Tools/matchbot/wlib/sem4.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/sem4.h b/Core/Tools/matchbot/wlib/sem4.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/sem4.h rename to Core/Tools/matchbot/wlib/sem4.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/stderrd.h b/Core/Tools/matchbot/wlib/stderrd.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/stderrd.h rename to Core/Tools/matchbot/wlib/stderrd.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/stdoutd.h b/Core/Tools/matchbot/wlib/stdoutd.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/stdoutd.h rename to Core/Tools/matchbot/wlib/stdoutd.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/streamer.cpp b/Core/Tools/matchbot/wlib/streamer.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/streamer.cpp rename to Core/Tools/matchbot/wlib/streamer.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/streamer.h b/Core/Tools/matchbot/wlib/streamer.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/streamer.h rename to Core/Tools/matchbot/wlib/streamer.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/syslogd.cpp b/Core/Tools/matchbot/wlib/syslogd.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/syslogd.cpp rename to Core/Tools/matchbot/wlib/syslogd.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/syslogd.h b/Core/Tools/matchbot/wlib/syslogd.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/syslogd.h rename to Core/Tools/matchbot/wlib/syslogd.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/threadfac.cpp b/Core/Tools/matchbot/wlib/threadfac.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/threadfac.cpp rename to Core/Tools/matchbot/wlib/threadfac.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/threadfac.h b/Core/Tools/matchbot/wlib/threadfac.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/threadfac.h rename to Core/Tools/matchbot/wlib/threadfac.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/threadsafe.h b/Core/Tools/matchbot/wlib/threadsafe.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/threadsafe.h rename to Core/Tools/matchbot/wlib/threadsafe.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/timezone.cpp b/Core/Tools/matchbot/wlib/timezone.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/timezone.cpp rename to Core/Tools/matchbot/wlib/timezone.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/timezone.h b/Core/Tools/matchbot/wlib/timezone.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/timezone.h rename to Core/Tools/matchbot/wlib/timezone.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/ustring.h b/Core/Tools/matchbot/wlib/ustring.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/ustring.h rename to Core/Tools/matchbot/wlib/ustring.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wdebug.cpp b/Core/Tools/matchbot/wlib/wdebug.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wdebug.cpp rename to Core/Tools/matchbot/wlib/wdebug.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wdebug.h b/Core/Tools/matchbot/wlib/wdebug.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wdebug.h rename to Core/Tools/matchbot/wlib/wdebug.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wstring.cpp b/Core/Tools/matchbot/wlib/wstring.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wstring.cpp rename to Core/Tools/matchbot/wlib/wstring.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wstring.h b/Core/Tools/matchbot/wlib/wstring.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wstring.h rename to Core/Tools/matchbot/wlib/wstring.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wstypes.h b/Core/Tools/matchbot/wlib/wstypes.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wstypes.h rename to Core/Tools/matchbot/wlib/wstypes.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wtime.cpp b/Core/Tools/matchbot/wlib/wtime.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wtime.cpp rename to Core/Tools/matchbot/wlib/wtime.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/wtime.h b/Core/Tools/matchbot/wlib/wtime.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/wtime.h rename to Core/Tools/matchbot/wlib/wtime.h diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/xtime.cpp b/Core/Tools/matchbot/wlib/xtime.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/xtime.cpp rename to Core/Tools/matchbot/wlib/xtime.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wlib/xtime.h b/Core/Tools/matchbot/wlib/xtime.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wlib/xtime.h rename to Core/Tools/matchbot/wlib/xtime.h diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/field.cpp b/Core/Tools/matchbot/wnet/field.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/field.cpp rename to Core/Tools/matchbot/wnet/field.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/field.h b/Core/Tools/matchbot/wnet/field.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/field.h rename to Core/Tools/matchbot/wnet/field.h diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/packet.cpp b/Core/Tools/matchbot/wnet/packet.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/packet.cpp rename to Core/Tools/matchbot/wnet/packet.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/packet.h b/Core/Tools/matchbot/wnet/packet.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/packet.h rename to Core/Tools/matchbot/wnet/packet.h diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/tcp.cpp b/Core/Tools/matchbot/wnet/tcp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/tcp.cpp rename to Core/Tools/matchbot/wnet/tcp.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/tcp.h b/Core/Tools/matchbot/wnet/tcp.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/tcp.h rename to Core/Tools/matchbot/wnet/tcp.h diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/udp.cpp b/Core/Tools/matchbot/wnet/udp.cpp similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/udp.cpp rename to Core/Tools/matchbot/wnet/udp.cpp diff --git a/GeneralsMD/Code/Tools/matchbot/wnet/udp.h b/Core/Tools/matchbot/wnet/udp.h similarity index 100% rename from GeneralsMD/Code/Tools/matchbot/wnet/udp.h rename to Core/Tools/matchbot/wnet/udp.h diff --git a/Core/Tools/textureCompress/CMakeLists.txt b/Core/Tools/textureCompress/CMakeLists.txt new file mode 100644 index 0000000000..951147a899 --- /dev/null +++ b/Core/Tools/textureCompress/CMakeLists.txt @@ -0,0 +1,18 @@ +set(TEXTURECOMPRESS_SRC + "resource.h" + "textureCompress.cpp" +) + +add_executable(core_texturecompress WIN32) +set_target_properties(core_texturecompress PROPERTIES OUTPUT_NAME texturecompress) + +target_sources(core_texturecompress PRIVATE ${TEXTURECOMPRESS_SRC}) + +target_link_libraries(core_texturecompress PRIVATE + core_config + core_wwlib +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_sources(core_texturecompress PRIVATE textureCompress.rc) +endif() diff --git a/GeneralsMD/Code/Tools/textureCompress/resource.h b/Core/Tools/textureCompress/resource.h similarity index 100% rename from GeneralsMD/Code/Tools/textureCompress/resource.h rename to Core/Tools/textureCompress/resource.h diff --git a/GeneralsMD/Code/Tools/textureCompress/textureCompress.cpp b/Core/Tools/textureCompress/textureCompress.cpp similarity index 100% rename from GeneralsMD/Code/Tools/textureCompress/textureCompress.cpp rename to Core/Tools/textureCompress/textureCompress.cpp diff --git a/Generals/Code/Tools/textureCompress/textureCompress.rc b/Core/Tools/textureCompress/textureCompress.rc similarity index 100% rename from Generals/Code/Tools/textureCompress/textureCompress.rc rename to Core/Tools/textureCompress/textureCompress.rc diff --git a/Core/Tools/timingTest/CMakeLists.txt b/Core/Tools/timingTest/CMakeLists.txt new file mode 100644 index 0000000000..ac7207e089 --- /dev/null +++ b/Core/Tools/timingTest/CMakeLists.txt @@ -0,0 +1,20 @@ +set(TIMINGTEST_SRC + "StdAfx.cpp" + "StdAfx.h" + "timingTest.cpp" +) + +add_executable(core_timingtest WIN32) +set_target_properties(core_timingtest PROPERTIES OUTPUT_NAME timingtest) + +target_sources(core_timingtest PRIVATE ${TIMINGTEST_SRC}) + +target_link_libraries(core_timingtest PRIVATE + core_config + core_utility + winmm +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_link_options(core_timingtest PRIVATE /subsystem:console) +endif() diff --git a/GeneralsMD/Code/Tools/timingTest/StdAfx.cpp b/Core/Tools/timingTest/StdAfx.cpp similarity index 100% rename from GeneralsMD/Code/Tools/timingTest/StdAfx.cpp rename to Core/Tools/timingTest/StdAfx.cpp diff --git a/GeneralsMD/Code/Tools/timingTest/StdAfx.h b/Core/Tools/timingTest/StdAfx.h similarity index 100% rename from GeneralsMD/Code/Tools/timingTest/StdAfx.h rename to Core/Tools/timingTest/StdAfx.h diff --git a/GeneralsMD/Code/Tools/timingTest/timingTest.cpp b/Core/Tools/timingTest/timingTest.cpp similarity index 100% rename from GeneralsMD/Code/Tools/timingTest/timingTest.cpp rename to Core/Tools/timingTest/timingTest.cpp diff --git a/Core/Tools/versionUpdate/CMakeLists.txt b/Core/Tools/versionUpdate/CMakeLists.txt new file mode 100644 index 0000000000..e9d1f21dec --- /dev/null +++ b/Core/Tools/versionUpdate/CMakeLists.txt @@ -0,0 +1,13 @@ +set(VERSIONUPDATE_SRC + "versionUpdate.cpp" +) + +add_executable(core_versionupdate WIN32) +set_target_properties(core_versionupdate PROPERTIES OUTPUT_NAME versionupdate) + +target_sources(core_versionupdate PRIVATE ${VERSIONUPDATE_SRC}) + +target_link_libraries(core_versionupdate PRIVATE + core_config + core_wwlib +) diff --git a/GeneralsMD/Code/Tools/versionUpdate/versionUpdate.cpp b/Core/Tools/versionUpdate/versionUpdate.cpp similarity index 100% rename from GeneralsMD/Code/Tools/versionUpdate/versionUpdate.cpp rename to Core/Tools/versionUpdate/versionUpdate.cpp diff --git a/Generals/Code/Tools/wolSetup/CMakeLists.txt b/Core/Tools/wolSetup/CMakeLists.txt similarity index 63% rename from Generals/Code/Tools/wolSetup/CMakeLists.txt rename to Core/Tools/wolSetup/CMakeLists.txt index f3f9d8cdf8..01e253838f 100644 --- a/Generals/Code/Tools/wolSetup/CMakeLists.txt +++ b/Core/Tools/wolSetup/CMakeLists.txt @@ -11,22 +11,22 @@ set(WOLSETUP_SRC "WOLAPI/downloaddefs.h" "WOLAPI/ftpdefs.h" "WOLAPI/netutildefs.h" - "WOLAPI/wolapi.h" "WOLAPI/wolapi_i.c" + "WOLAPI/wolapi.h" ) -add_executable(g_wolsetup WIN32) -set_target_properties(g_wolsetup PROPERTIES OUTPUT_NAME wolsetup) +add_executable(core_wolsetup WIN32) +set_target_properties(core_wolsetup PROPERTIES OUTPUT_NAME wolsetup) -target_sources(g_wolsetup PRIVATE ${WOLSETUP_SRC}) +target_sources(core_wolsetup PRIVATE ${WOLSETUP_SRC}) -target_link_libraries(g_wolsetup PRIVATE +target_link_libraries(core_wolsetup PRIVATE core_config Version ) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(g_wolsetup PRIVATE wolSetup.rc) + target_sources(core_wolsetup PRIVATE wolSetup.rc) endif() # TODO: Copy the dll's that reside in the WOLAPI folder. diff --git a/GeneralsMD/Code/Tools/wolSetup/StdAfx.cpp b/Core/Tools/wolSetup/StdAfx.cpp similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/StdAfx.cpp rename to Core/Tools/wolSetup/StdAfx.cpp diff --git a/GeneralsMD/Code/Tools/wolSetup/StdAfx.h b/Core/Tools/wolSetup/StdAfx.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/StdAfx.h rename to Core/Tools/wolSetup/StdAfx.h diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/chatdefs.h b/Core/Tools/wolSetup/WOLAPI/chatdefs.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/WOLAPI/chatdefs.h rename to Core/Tools/wolSetup/WOLAPI/chatdefs.h diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/downloaddefs.h b/Core/Tools/wolSetup/WOLAPI/downloaddefs.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/WOLAPI/downloaddefs.h rename to Core/Tools/wolSetup/WOLAPI/downloaddefs.h diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/ftpdefs.h b/Core/Tools/wolSetup/WOLAPI/ftpdefs.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/WOLAPI/ftpdefs.h rename to Core/Tools/wolSetup/WOLAPI/ftpdefs.h diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/netutildefs.h b/Core/Tools/wolSetup/WOLAPI/netutildefs.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/WOLAPI/netutildefs.h rename to Core/Tools/wolSetup/WOLAPI/netutildefs.h diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/wolapi.dll b/Core/Tools/wolSetup/WOLAPI/wolapi.dll similarity index 100% rename from Generals/Code/Tools/wolSetup/WOLAPI/wolapi.dll rename to Core/Tools/wolSetup/WOLAPI/wolapi.dll diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi.h b/Core/Tools/wolSetup/WOLAPI/wolapi.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi.h rename to Core/Tools/wolSetup/WOLAPI/wolapi.h diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi_i.c b/Core/Tools/wolSetup/WOLAPI/wolapi_i.c similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi_i.c rename to Core/Tools/wolSetup/WOLAPI/wolapi_i.c diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/woldbg.dll b/Core/Tools/wolSetup/WOLAPI/woldbg.dll similarity index 100% rename from Generals/Code/Tools/wolSetup/WOLAPI/woldbg.dll rename to Core/Tools/wolSetup/WOLAPI/woldbg.dll diff --git a/Generals/Code/Tools/wolSetup/makedist.bat b/Core/Tools/wolSetup/makedist.bat similarity index 100% rename from Generals/Code/Tools/wolSetup/makedist.bat rename to Core/Tools/wolSetup/makedist.bat diff --git a/GeneralsMD/Code/Tools/wolSetup/resource.h b/Core/Tools/wolSetup/resource.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/resource.h rename to Core/Tools/wolSetup/resource.h diff --git a/Generals/Code/Tools/wolSetup/small.ico b/Core/Tools/wolSetup/small.ico similarity index 100% rename from Generals/Code/Tools/wolSetup/small.ico rename to Core/Tools/wolSetup/small.ico diff --git a/GeneralsMD/Code/Tools/wolSetup/verchk.cpp b/Core/Tools/wolSetup/verchk.cpp similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/verchk.cpp rename to Core/Tools/wolSetup/verchk.cpp diff --git a/GeneralsMD/Code/Tools/wolSetup/verchk.h b/Core/Tools/wolSetup/verchk.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/verchk.h rename to Core/Tools/wolSetup/verchk.h diff --git a/GeneralsMD/Code/Tools/wolSetup/wolInit.cpp b/Core/Tools/wolSetup/wolInit.cpp similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/wolInit.cpp rename to Core/Tools/wolSetup/wolInit.cpp diff --git a/GeneralsMD/Code/Tools/wolSetup/wolSetup.cpp b/Core/Tools/wolSetup/wolSetup.cpp similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/wolSetup.cpp rename to Core/Tools/wolSetup/wolSetup.cpp diff --git a/GeneralsMD/Code/Tools/wolSetup/wolSetup.h b/Core/Tools/wolSetup/wolSetup.h similarity index 100% rename from GeneralsMD/Code/Tools/wolSetup/wolSetup.h rename to Core/Tools/wolSetup/wolSetup.h diff --git a/Generals/Code/Tools/wolSetup/wolSetup.ico b/Core/Tools/wolSetup/wolSetup.ico similarity index 100% rename from Generals/Code/Tools/wolSetup/wolSetup.ico rename to Core/Tools/wolSetup/wolSetup.ico diff --git a/Generals/Code/Tools/wolSetup/wolSetup.rc b/Core/Tools/wolSetup/wolSetup.rc similarity index 100% rename from Generals/Code/Tools/wolSetup/wolSetup.rc rename to Core/Tools/wolSetup/wolSetup.rc diff --git a/Dependencies/SafeDisc/CMakeLists.txt b/Dependencies/SafeDisc/CMakeLists.txt index 4091508e9b..52b043e299 100644 --- a/Dependencies/SafeDisc/CMakeLists.txt +++ b/Dependencies/SafeDisc/CMakeLists.txt @@ -1,2 +1,4 @@ add_library(safedisc INTERFACE) -target_include_directories(safedisc INTERFACE .) \ No newline at end of file +target_include_directories(safedisc INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR} +) diff --git a/Dependencies/Utility/Utility/CppMacros.h b/Dependencies/Utility/Utility/CppMacros.h index 3d83dda8c5..57aaa75abc 100644 --- a/Dependencies/Utility/Utility/CppMacros.h +++ b/Dependencies/Utility/Utility/CppMacros.h @@ -37,3 +37,13 @@ #else #define CPP_11(code) #endif + +#if __cplusplus >= 201703L +#define REGISTER +#else +#define REGISTER register +#endif + +#if __cplusplus < 201103L +#define static_assert(expr, msg) +#endif diff --git a/Dependencies/Utility/Utility/endian_compat.h b/Dependencies/Utility/Utility/endian_compat.h new file mode 100644 index 0000000000..56b35c33be --- /dev/null +++ b/Dependencies/Utility/Utility/endian_compat.h @@ -0,0 +1,246 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +// This file contains macros to help with endian conversions between different endian systems. +#pragma once + +// VC6 does not support pragma once +#ifndef ENDIAN_COMPAT_H +#define ENDIAN_COMPAT_H + +#include +#include + + +#if defined(__linux__) || defined(__CYGWIN__) +#include + +#elif defined(__APPLE__) +#include + +#define htobe16(x) OSSwapHostToBigInt16(x) +#define htole16(x) OSSwapHostToLittleInt16(x) +#define be16toh(x) OSSwapBigToHostInt16(x) +#define le16toh(x) OSSwapLittleToHostInt16(x) + +#define htobe32(x) OSSwapHostToBigInt32(x) +#define htole32(x) OSSwapHostToLittleInt32(x) +#define be32toh(x) OSSwapBigToHostInt32(x) +#define le32toh(x) OSSwapLittleToHostInt32(x) + +#define htobe64(x) OSSwapHostToBigInt64(x) +#define htole64(x) OSSwapHostToLittleInt64(x) +#define be64toh(x) OSSwapBigToHostInt64(x) +#define le64toh(x) OSSwapLittleToHostInt64(x) + +#elif defined(__OpenBSD__) +#include + +#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) +#include + +#define be16toh(x) betoh16(x) +#define le16toh(x) letoh16(x) + +#define be32toh(x) betoh32(x) +#define le32toh(x) letoh32(x) + +#define be64toh(x) betoh64(x) +#define le64toh(x) letoh64(x) + +#elif defined(_WIN32) || defined(_WIN64) +#if !(defined(_MSC_VER) && _MSC_VER < 1300) +#include +#define htobe16(x) _byteswap_ushort(x) +#define htole16(x) (x) +#define be16toh(x) _byteswap_ushort(x) +#define le16toh(x) (x) + +#define htobe32(x) _byteswap_ulong(x) +#define htole32(x) (x) +#define be32toh(x) _byteswap_ulong(x) +#define le32toh(x) (x) + +#define htobe64(x) _byteswap_uint64(x) +#define htole64(x) (x) +#define be64toh(x) _byteswap_uint64(x) +#define le64toh(x) (x) +#else +#define bswap16(x) ( (uint16_t)( ((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8) ) ) +#define bswap32(x) ( ((x & 0xFF000000) >> 24) | \ + ((x & 0x00FF0000) >> 8) | \ + ((x & 0x0000FF00) << 8) | \ + ((x & 0x000000FF) << 24) ) +#define bswap64(x) ( (((uint64_t)(x) & 0xFF00000000000000) >> 56) | \ + (((uint64_t)(x) & 0x00FF000000000000) >> 40) | \ + (((uint64_t)(x) & 0x0000FF0000000000) >> 24) | \ + (((uint64_t)(x) & 0x000000FF00000000) >> 8) | \ + (((uint64_t)(x) & 0x00000000FF000000) << 8) | \ + (((uint64_t)(x) & 0x0000000000FF0000) << 24) | \ + (((uint64_t)(x) & 0x000000000000FF00) << 40) | \ + (((uint64_t)(x) & 0x00000000000000FF) << 56) ) + +#define htobe16(x) bswap16(x) +#define htole16(x) (x) +#define be16toh(x) bswap16(x) +#define le16toh(x) (x) + +#define htobe32(x) bswap32(x) +#define htole32(x) (x) +#define be32toh(x) bswap32(x) +#define le32toh(x) (x) + +#define htobe64(x) bswap64(x) +#define htole64(x) (x) +#define be64toh(x) bswap64(x) +#define le64toh(x) (x) + +#endif // _MSC_VER + +#else +#error platform not supported +#endif + + +// Endian helper function data types +#if defined(__linux__) || defined(__CYGWIN__) +typedef uint16_t SwapType16; +typedef uint32_t SwapType32; +typedef uint64_t SwapType64; + +#elif defined(__APPLE__) +typedef UInt16 SwapType16; +typedef UInt32 SwapType32; +typedef UInt64 SwapType64; + +#elif defined(__OpenBSD__) +typedef uint16_t SwapType16; +typedef uint32_t SwapType32; +typedef uint64_t SwapType64; + +#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) +typedef uint16_t SwapType16; +typedef uint32_t SwapType32; +typedef uint64_t SwapType64; + +#elif defined(_WIN32) || defined(_WIN64) +typedef uint16_t SwapType16; +typedef uint32_t SwapType32; +typedef uint64_t SwapType64; + +#else +#error platform not supported +#endif + + +// Endian helper functions +static_assert(sizeof(SwapType16) == 2, "expected size does not match"); +static_assert(sizeof(SwapType32) == 4, "expected size does not match"); +static_assert(sizeof(SwapType64) == 8, "expected size does not match"); + +// VC6 compatible overloaded endian functions +#if defined(_MSC_VER) && _MSC_VER < 1300 + +// Big endian to host +inline int16_t betoh(int16_t value) { return be16toh(value); } +inline uint16_t betoh(uint16_t value) { return be16toh(value); } +inline int32_t betoh(int32_t value) { return be32toh(value); } +inline uint32_t betoh(uint32_t value) { return be32toh(value); } +inline int64_t betoh(int64_t value) { return be64toh(value); } +inline uint64_t betoh(uint64_t value) { return be64toh(value); } +// Host to big endian +inline int16_t htobe(int16_t value) { return htobe16(value); } +inline uint16_t htobe(uint16_t value) { return htobe16(value); } +inline int32_t htobe(int32_t value) { return htobe32(value); } +inline uint32_t htobe(uint32_t value) { return htobe32(value); } +inline int64_t htobe(int64_t value) { return htobe64(value); } +inline uint64_t htobe(uint64_t value) { return htobe64(value); } +// Little endian to host +inline int16_t letoh(int16_t value) { return le16toh(value); } +inline uint16_t letoh(uint16_t value) { return le16toh(value); } +inline int32_t letoh(int32_t value) { return le32toh(value); } +inline uint32_t letoh(uint32_t value) { return le32toh(value); } +inline int64_t letoh(int64_t value) { return le64toh(value); } +inline uint64_t letoh(uint64_t value) { return le64toh(value); } +// Host to little endian +inline int16_t htole(int16_t value) { return htole16(value); } +inline uint16_t htole(uint16_t value) { return htole16(value); } +inline int32_t htole(int32_t value) { return htole32(value); } +inline uint32_t htole(uint32_t value) { return htole32(value); } +inline int64_t htole(int64_t value) { return htole64(value); } +inline uint64_t htole(uint64_t value) { return htole64(value); } + +#else + +namespace Endian +{ +template struct htobeHelper; +template struct htoleHelper; +template struct betohHelper; +template struct letohHelper; + +// 2 byte integer, enum +template struct htobeHelper { static inline Type swap(Type value) { return static_cast(htobe16(static_cast(value))); } }; +template struct htoleHelper { static inline Type swap(Type value) { return static_cast(htole16(static_cast(value))); } }; +template struct betohHelper { static inline Type swap(Type value) { return static_cast(be16toh(static_cast(value))); } }; +template struct letohHelper { static inline Type swap(Type value) { return static_cast(le16toh(static_cast(value))); } }; +// 4 byte integer, enum +template struct htobeHelper { static inline Type swap(Type value) { return static_cast(htobe32(static_cast(value))); } }; +template struct htoleHelper { static inline Type swap(Type value) { return static_cast(htole32(static_cast(value))); } }; +template struct betohHelper { static inline Type swap(Type value) { return static_cast(be32toh(static_cast(value))); } }; +template struct letohHelper { static inline Type swap(Type value) { return static_cast(le16toh(static_cast(value))); } }; +// 8 byte integer, enum +template struct htobeHelper { static inline Type swap(Type value) { return static_cast(htobe64(static_cast(value))); } }; +template struct htoleHelper { static inline Type swap(Type value) { return static_cast(htole64(static_cast(value))); } }; +template struct betohHelper { static inline Type swap(Type value) { return static_cast(be64toh(static_cast(value))); } }; +template struct letohHelper { static inline Type swap(Type value) { return static_cast(le16toh(static_cast(value))); } }; +// float +template <> struct htobeHelper { static inline float swap(float value) { SwapType32 v = htobe32(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct htoleHelper { static inline float swap(float value) { SwapType32 v = htole32(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct betohHelper { static inline float swap(float value) { SwapType32 v = be32toh(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct letohHelper { static inline float swap(float value) { SwapType32 v = le16toh(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +// double +template <> struct htobeHelper { static inline double swap(double value) { SwapType64 v = htobe64(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct htoleHelper { static inline double swap(double value) { SwapType64 v = htole64(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct betohHelper { static inline double swap(double value) { SwapType64 v = be64toh(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +template <> struct letohHelper { static inline double swap(double value) { SwapType64 v = le16toh(*reinterpret_cast(&value)); return *reinterpret_cast(&v); } }; +} // namespace Endian + +// c++ template functions, takes any 2, 4, 8 bytes, including float, double, enum + +// Host to big endian +template inline Type htobe(Type value) { return Endian::htobeHelper::swap(value); } +// Host to little endian +template inline Type htole(Type value) { return Endian::htoleHelper::swap(value); } +// Big endian to host +template inline Type betoh(Type value) { return Endian::betohHelper::swap(value); } +// Little endian to host +template inline Type letoh(Type value) { return Endian::letohHelper::swap(value); } + +// Host to big endian +template inline void htobe_ref(Type &value) { value = Endian::htobeHelper::swap(value); } +// Host to little endian +template inline void htole_ref(Type &value) { value = Endian::htoleHelper::swap(value); } +// Big endian to host +template inline void betoh_ref(Type &value) { value = Endian::betohHelper::swap(value); } +// Little endian to host +template inline void letoh_ref(Type &value) { value = Endian::letohHelper::swap(value); } + +#endif // _MSC_VER < 1300 + +#endif // ENDIAN_COMPAT_H \ No newline at end of file diff --git a/Dependencies/Utility/Utility/stdint_adapter.h b/Dependencies/Utility/Utility/stdint_adapter.h new file mode 100644 index 0000000000..b73de83603 --- /dev/null +++ b/Dependencies/Utility/Utility/stdint_adapter.h @@ -0,0 +1,175 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +#pragma once + +#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) +/* 7.18.1.4 Integer types capable of holding object pointers */ +#ifdef _WIN64 + typedef __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else + typedef int intptr_t; + typedef unsigned int uintptr_t; +#endif + +/* 7.18.1.1 Exact-width integer types */ +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef int int32_t; +typedef unsigned int uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +/* 7.18.1.2 Minimum-width integer types */ +typedef signed char int_least8_t; +typedef unsigned char uint_least8_t; +typedef short int_least16_t; +typedef unsigned short uint_least16_t; +typedef int int_least32_t; +typedef unsigned uint_least32_t; +typedef __int64 int_least64_t; +typedef unsigned __int64 uint_least64_t; +/* 7.18.1.3 Fastest minimum-width integer types + * Not actually guaranteed to be fastest for all purposes + * Here we use the exact-width types for 8 and 16-bit ints. + */ +typedef signed char int_fast8_t; +typedef unsigned char uint_fast8_t; +typedef short int_fast16_t; +typedef unsigned short uint_fast16_t; +typedef int int_fast32_t; +typedef unsigned int uint_fast32_t; +typedef __int64 int_fast64_t; +typedef unsigned __int64 uint_fast64_t; +/* 7.18.1.5 Greatest-width integer types */ +typedef __int64 intmax_t; +typedef unsigned __int64 uintmax_t; +/* 7.18.2 Limits of specified-width integer types */ +/* 7.18.2.1 Limits of exact-width integer types */ +#define INT8_MIN (-128) +#define INT16_MIN (-32768) +#define INT32_MIN (-2147483647 - 1) +#define INT64_MIN (-9223372036854775807i64 - 1) +#define INT8_MAX 127 +#define INT16_MAX 32767 +#define INT32_MAX 2147483647 +#define INT64_MAX 9223372036854775807i64 +#define UINT8_MAX 255 +#define UINT16_MAX 65535 +#define UINT32_MAX 0xffffffffU /* 4294967295U */ +#define UINT64_MAX 0xffffffffffffffffUi64 /* 18446744073709551615ULL */ +/* 7.18.2.2 Limits of minimum-width integer types */ +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX +/* 7.18.2.3 Limits of fastest minimum-width integer types */ +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX +/* 7.18.2.4 Limits of integer types capable of holding + object pointers */ +#ifdef _WIN64 +#define INTPTR_MIN INT64_MIN +#define INTPTR_MAX INT64_MAX +#define UINTPTR_MAX UINT64_MAX +#else +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX +#endif +/* 7.18.2.5 Limits of greatest-width integer types */ +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX +/* 7.18.3 Limits of other integer types */ +#ifdef _WIN64 +#define PTRDIFF_MIN INT64_MIN +#define PTRDIFF_MAX INT64_MAX +#else +#define PTRDIFF_MIN INT32_MIN +#define PTRDIFF_MAX INT32_MAX +#endif +#define SIG_ATOMIC_MIN INT32_MIN +#define SIG_ATOMIC_MAX INT32_MAX +#ifndef SIZE_MAX +#ifdef _WIN64 +#define SIZE_MAX UINT64_MAX +#else +#define SIZE_MAX UINT32_MAX +#endif +#endif + +#define WCHAR_MIN 0 +#define WCHAR_MAX ((wchar_t)-1) +/* + * wint_t is unsigned short for compatibility with MS runtime + */ +#define WINT_MIN 0U +#define WINT_MAX 0xffffU +/* 7.18.4 Macros for integer constants */ +/* 7.18.4.1 Macros for minimum-width integer constants + Accoding to Douglas Gwyn : + "This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC + 9899:1999 as initially published, the expansion was required + to be an integer constant of precisely matching type, which + is impossible to accomplish for the shorter types on most + platforms, because C99 provides no standard way to designate + an integer constant with width less than that of type int. + TC1 changed this to require just an integer constant + *expression* with *promoted* type." + The trick used here is from Clive D W Feather. +*/ +#define INT8_C(val) (INT_LEAST8_MAX-INT_LEAST8_MAX+(val)) +#define INT16_C(val) (INT_LEAST16_MAX-INT_LEAST16_MAX+(val)) +#define INT32_C(val) (INT_LEAST32_MAX-INT_LEAST32_MAX+(val)) +/* The 'trick' doesn't work in C89 for long long because, without + suffix, (val) will be evaluated as int, not intmax_t */ +#define INT64_C(val) val##i64 +#define UINT8_C(val) (val) +#define UINT16_C(val) (val) +#define UINT32_C(val) (val##i32) +#define UINT64_C(val) val##ui64 +/* 7.18.4.2 Macros for greatest-width integer constants */ +#define INTMAX_C(val) val##i64 +#define UINTMAX_C(val) val##ui64 + +#else + +#include + +#endif diff --git a/Generals/CMakeLists.txt b/Generals/CMakeLists.txt index 2cbcf0a0e5..7953714f5a 100644 --- a/Generals/CMakeLists.txt +++ b/Generals/CMakeLists.txt @@ -2,15 +2,6 @@ cmake_minimum_required(VERSION 3.25) project(g_generals LANGUAGES C CXX) -# Do we want to build extra SDK stuff or just the game binary? -option(RTS_BUILD_GENERALS_TOOLS "Build tools for Generals" ON) -add_feature_info(GeneralsTools RTS_BUILD_GENERALS_TOOLS "Build Generals Mod Tools") -option(RTS_BUILD_GENERALS_EXTRAS "Build extra tools/tests for Generals" OFF) -add_feature_info(GeneralsExtras RTS_BUILD_GENERALS_EXTRAS "Build Generals Extra Tools/Tests") - -# Do we want to build documentation? -option(RTS_BUILD_GENERALS_DOCS "Build documentation for Generals" OFF) -add_feature_info(GeneralsDocs RTS_BUILD_GENERALS_DOCS "Build Generals Documentation") if (RTS_BUILD_GENERALS_DOCS) find_package(Doxygen REQUIRED) doxygen_add_docs(g_docs Code) @@ -73,4 +64,9 @@ if(RTS_INSTALL_PREFIX_GENERALS AND NOT "${RTS_INSTALL_PREFIX_GENERALS}" STREQUAL install(TARGETS g_mapcachebuilder RUNTIME DESTINATION "${RTS_INSTALL_PREFIX_GENERALS}") install(FILES $ DESTINATION "${RTS_INSTALL_PREFIX_GENERALS}" OPTIONAL) endif() + + if(TARGET g_w3dview) + install(TARGETS g_w3dview RUNTIME DESTINATION "${RTS_INSTALL_PREFIX_GENERALS}") + install(FILES $ DESTINATION "${RTS_INSTALL_PREFIX_GENERALS}" OPTIONAL) + endif() endif() diff --git a/Generals/Code/CMakeLists.txt b/Generals/Code/CMakeLists.txt index df16145112..838818eff2 100644 --- a/Generals/Code/CMakeLists.txt +++ b/Generals/Code/CMakeLists.txt @@ -19,6 +19,10 @@ target_include_directories(gi_libraries_source_wwvegas_ww3d2 INTERFACE "Librarie target_include_directories(gi_libraries_source_wwvegas_wwmath INTERFACE "Libraries/Source/WWVegas/WWMath") target_include_directories(gi_libraries_source_wwvegas_wwsaveload INTERFACE "Libraries/Source/WWVegas/WWSaveLoad") target_include_directories(gi_main INTERFACE "Main") + +target_compile_definitions(gi_always INTERFACE + RTS_GENERALS=1 +) target_link_libraries(gi_always INTERFACE core_utility gi_libraries_include diff --git a/Generals/Code/GameEngine/CMakeLists.txt b/Generals/Code/GameEngine/CMakeLists.txt index 1882ac95ac..f999f68eb2 100644 --- a/Generals/Code/GameEngine/CMakeLists.txt +++ b/Generals/Code/GameEngine/CMakeLists.txt @@ -123,15 +123,16 @@ set(GAMEENGINE_SRC Include/Common/UserPreferences.h Include/Common/version.h Include/Common/WellKnownKeys.h - Include/Common/Xfer.h - Include/Common/XferCRC.h - Include/Common/XferDeepCRC.h - Include/Common/XferLoad.h - Include/Common/XferSave.h +# Include/Common/Xfer.h +# Include/Common/XferCRC.h +# Include/Common/XferDeepCRC.h +# Include/Common/XferLoad.h +# Include/Common/XferSave.h Include/GameClient/Anim2D.h Include/GameClient/AnimateWindowManager.h Include/GameClient/CampaignManager.h Include/GameClient/CDCheck.h + Include/GameClient/ClientInstance.h Include/GameClient/ClientRandomValue.h Include/GameClient/Color.h Include/GameClient/CommandXlat.h @@ -391,6 +392,7 @@ set(GAMEENGINE_SRC Include/GameLogic/Module/SpecialPowerCompletionDie.h Include/GameLogic/Module/SpecialPowerCreate.h Include/GameLogic/Module/SpecialPowerModule.h + Include/GameLogic/Module/SpecialPowerUpdateModule.h Include/GameLogic/Module/SpyVisionSpecialPower.h Include/GameLogic/Module/SpyVisionUpdate.h Include/GameLogic/Module/SquishCollide.h @@ -619,10 +621,10 @@ set(GAMEENGINE_SRC Source/Common/System/Trig.cpp Source/Common/System/UnicodeString.cpp Source/Common/System/Upgrade.cpp - Source/Common/System/Xfer.cpp - Source/Common/System/XferCRC.cpp - Source/Common/System/XferLoad.cpp - Source/Common/System/XferSave.cpp +# Source/Common/System/Xfer.cpp +# Source/Common/System/XferCRC.cpp +# Source/Common/System/XferLoad.cpp +# Source/Common/System/XferSave.cpp Source/Common/TerrainTypes.cpp Source/Common/Thing/DrawModule.cpp Source/Common/Thing/Module.cpp @@ -632,6 +634,7 @@ set(GAMEENGINE_SRC Source/Common/Thing/ThingTemplate.cpp Source/Common/UserPreferences.cpp Source/Common/version.cpp + Source/GameClient/ClientInstance.cpp Source/GameClient/Color.cpp Source/GameClient/Credits.cpp Source/GameClient/Display.cpp @@ -1072,27 +1075,19 @@ target_sources(g_gameengine PRIVATE ${GAMEENGINE_SRC}) target_include_directories(g_gameengine PUBLIC Include ) + target_include_directories(g_gameengine PRIVATE Include/Precompiled ) target_link_libraries(g_gameengine PRIVATE + corei_gameengine_private gi_always ) target_link_libraries(g_gameengine PUBLIC - d3d8lib - core_browserdispatch - core_compression + corei_gameengine_public g_wwvegas - core_config - core_utility - gamespy::gamespy - stlport -) - -target_compile_definitions(g_gameengine PRIVATE - IG_DEBUG_STACKTRACE ) target_precompile_headers(g_gameengine PRIVATE Include/Precompiled/PreRTS.h) diff --git a/Generals/Code/GameEngine/Include/Common/ArchiveFileSystem.h b/Generals/Code/GameEngine/Include/Common/ArchiveFileSystem.h index e9695e0c17..b1f75e7411 100644 --- a/Generals/Code/GameEngine/Include/Common/ArchiveFileSystem.h +++ b/Generals/Code/GameEngine/Include/Common/ArchiveFileSystem.h @@ -172,11 +172,10 @@ class ArchiveFileSystem : public SubsystemInterface // Unprotected this for copy-protection routines AsciiString getArchiveFilenameForFile(const AsciiString& filename) const; - void loadMods( void ); protected: - virtual void loadIntoDirectoryTree(const ArchiveFile *archiveFile, const AsciiString& archiveFilename, Bool overwrite = FALSE); ///< load the archive file's header information and apply it to the global archive directory tree. + virtual void loadIntoDirectoryTree(const ArchiveFile *archiveFile, const AsciiString& archiveFilename, Bool overwrite = FALSE ); ///< load the archive file's header information and apply it to the global archive directory tree. ArchiveFileMap m_archiveFileMap; ArchivedDirectoryInfo m_rootDirectory; diff --git a/Generals/Code/GameEngine/Include/Common/AsciiString.h b/Generals/Code/GameEngine/Include/Common/AsciiString.h index f3719d3eec..fcfb049f52 100644 --- a/Generals/Code/GameEngine/Include/Common/AsciiString.h +++ b/Generals/Code/GameEngine/Include/Common/AsciiString.h @@ -89,7 +89,7 @@ class AsciiString // add a ctor/dtor, 'cuz they won't ever be called. struct AsciiStringData { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) const char* m_debugptr; // just makes it easier to read in the debugger #endif unsigned short m_refCount; // reference count @@ -99,7 +99,7 @@ class AsciiString inline char* peek() { return (char*)(this+1); } }; - #ifdef _DEBUG + #ifdef RTS_DEBUG void validate() const; #else inline void validate() const { } diff --git a/Generals/Code/GameEngine/Include/Common/AudioEventInfo.h b/Generals/Code/GameEngine/Include/Common/AudioEventInfo.h index fcc0804ba8..a9924df317 100644 --- a/Generals/Code/GameEngine/Include/Common/AudioEventInfo.h +++ b/Generals/Code/GameEngine/Include/Common/AudioEventInfo.h @@ -82,6 +82,8 @@ enum AudioControl CPP_11(: Int) AC_INTERRUPT = 0x0010, }; +class DynamicAudioEventInfo; + struct AudioEventInfo : public MemoryPoolObject { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( AudioEventInfo, "AudioEventInfo" ) @@ -118,6 +120,16 @@ struct AudioEventInfo : public MemoryPoolObject AudioType m_soundType; // This should be either Music, Streaming or SoundEffect + + // DynamicAudioEventInfo interfacing functions + virtual Bool isLevelSpecific() const { return false; } ///< If true, this sound is only defined on the current level and can be deleted when that level ends + virtual DynamicAudioEventInfo * getDynamicAudioEventInfo() { return NULL; } ///< If this object is REALLY a DynamicAudioEventInfo, return a pointer to the derived class + virtual const DynamicAudioEventInfo * getDynamicAudioEventInfo() const { return NULL; } ///< If this object is REALLY a DynamicAudioEventInfo, return a pointer to the derived class + + /// Is this a permenant sound? That is, if I start this sound up, will it ever end + /// "on its own" or only if I explicitly kill it? + Bool isPermanentSound() const { return BitIsSet( m_control, AC_LOOP ) && (m_loopCount == 0 ); } + static const FieldParse m_audioEventInfo[]; ///< the parse table for INI definition const FieldParse *getFieldParse( void ) const { return m_audioEventInfo; } }; diff --git a/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h b/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h index da4a1e3cb1..5911362b0a 100644 --- a/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h +++ b/Generals/Code/GameEngine/Include/Common/BitFlagsIO.h @@ -138,6 +138,18 @@ template ((BitFlags*)store)->parse(ini, NULL); } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +template +/*static*/ void BitFlags::parseSingleBitFromINI(INI* ini, void* /*instance*/, void *store, const void* /*userData*/) +{ + const char *token = ini->getNextToken(); + Int bitIndex = INI::scanIndexList(token, s_bitNameList); // this throws if the token is not found + + Int *storeAsInt = (Int*)store; + *storeAsInt = bitIndex; +} + //------------------------------------------------------------------------------------------------- /** Xfer method * Version Info: diff --git a/Generals/Code/GameEngine/Include/Common/CRCDebug.h b/Generals/Code/GameEngine/Include/Common/CRCDebug.h index 3452b9fe01..6a0d7e2f26 100644 --- a/Generals/Code/GameEngine/Include/Common/CRCDebug.h +++ b/Generals/Code/GameEngine/Include/Common/CRCDebug.h @@ -68,9 +68,11 @@ void dumpReal(Real r, AsciiString name, AsciiString fname, Int line); void outputCRCDebugLines( void ); + void CRCDebugStartNewGame( void ); void outputCRCDumpLines( void ); void addCRCDebugLine(const char *fmt, ...); + void addCRCDebugLineNoCounter(const char *fmt, ...); void addCRCDumpLine(const char *fmt, ...); void addCRCGenLine(const char *fmt, ...); #define CRCDEBUG_LOG(x) addCRCDebugLine x @@ -97,7 +99,9 @@ extern Bool g_crcModuleDataFromLogic; extern Bool g_keepCRCSaves; - + extern Bool g_saveDebugCRCPerFrame; + extern AsciiString g_saveDebugCRCPerFrameDir; + extern Bool g_logObjectCRCs; #else // DEBUG_CRC diff --git a/Generals/Code/GameEngine/Include/Common/CommandLine.h b/Generals/Code/GameEngine/Include/Common/CommandLine.h index f60d2288dd..6e8997c7da 100644 --- a/Generals/Code/GameEngine/Include/Common/CommandLine.h +++ b/Generals/Code/GameEngine/Include/Common/CommandLine.h @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals(tm) +** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify diff --git a/Generals/Code/GameEngine/Include/Common/DataChunk.h b/Generals/Code/GameEngine/Include/Common/DataChunk.h index 3fe923efda..a1130f184c 100644 --- a/Generals/Code/GameEngine/Include/Common/DataChunk.h +++ b/Generals/Code/GameEngine/Include/Common/DataChunk.h @@ -136,6 +136,7 @@ class DataChunkOutput void writeUnicodeString(UnicodeString string); void writeArrayOfBytes(char *ptr, Int len); void writeDict(const Dict& d); + void writeNameKey(const NameKeyType key); }; //---------------------------------------------------------------------- @@ -228,6 +229,8 @@ class DataChunkInput UnicodeString readUnicodeString(void); Dict readDict(void); void readArrayOfBytes(char *ptr, Int len); + + NameKeyType readNameKey(void); }; diff --git a/Generals/Code/GameEngine/Include/Common/Debug.h b/Generals/Code/GameEngine/Include/Common/Debug.h index 860ea96698..829946295e 100644 --- a/Generals/Code/GameEngine/Include/Common/Debug.h +++ b/Generals/Code/GameEngine/Include/Common/Debug.h @@ -50,7 +50,7 @@ class AsciiString; -#if defined(_DEBUG) && defined(_INTERNAL) +#if defined(RTS_DEBUG) && defined(RTS_INTERNAL) #error "Only one at a time of these should ever be defined" #endif @@ -63,15 +63,15 @@ class AsciiString; // have any debugging of any kind. //#define DISABLE_DEBUG_LOGGING -// by default, turn on ALLOW_DEBUG_UTILS if _DEBUG is turned on. -#if (defined(_DEBUG) || defined(_INTERNAL)) && !defined(ALLOW_DEBUG_UTILS) && !defined(DISABLE_ALLOW_DEBUG_UTILS) +// by default, turn on ALLOW_DEBUG_UTILS if RTS_DEBUG is turned on. +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) && !defined(ALLOW_DEBUG_UTILS) && !defined(DISABLE_ALLOW_DEBUG_UTILS) #define ALLOW_DEBUG_UTILS 1 #elif defined(DEBUG_LOGGING) || defined(DEBUG_CRASHING) || defined(DEBUG_STACKTRACE) || defined(DEBUG_PROFILE) // TheSuperHackers @tweak also turn on when any of the above options is already set. #define ALLOW_DEBUG_UTILS 1 #endif -// these are predicated on ALLOW_DEBUG_UTILS, not _DEBUG, and allow you to selectively disable +// these are predicated on ALLOW_DEBUG_UTILS, not RTS_DEBUG, and allow you to selectively disable // bits of the debug stuff for special builds. #if defined(ALLOW_DEBUG_UTILS) && !defined(DEBUG_LOGGING) && !defined(DISABLE_DEBUG_LOGGING) #define DEBUG_LOGGING 1 @@ -120,8 +120,8 @@ class AsciiString; DEBUG_FLAG_LOG_TO_FILE = 0x01, DEBUG_FLAG_LOG_TO_CONSOLE = 0x02, DEBUG_FLAG_PREPEND_TIME = 0x04, -#ifdef _INTERNAL - // by default, _INTERNAL builds log to file, but not to console, in the interest +#ifdef RTS_INTERNAL + // by default, RTS_INTERNAL builds log to file, but not to console, in the interest // of speed. want console output? just change this line: DEBUG_FLAGS_DEFAULT = (DEBUG_FLAG_LOG_TO_FILE) #else @@ -148,6 +148,8 @@ class AsciiString; #ifdef DEBUG_LOGGING DEBUG_EXTERN_C void DebugLog(const char *format, ...); + DEBUG_EXTERN_C const char* DebugGetLogFileName(); + DEBUG_EXTERN_C const char* DebugGetLogFileNamePrev(); // This defines a bitmask of log types that we care about, to allow some flexability // in what gets logged. This should be extended to asserts, too, but the assert box diff --git a/Generals/Code/GameEngine/Include/Common/Dict.h b/Generals/Code/GameEngine/Include/Common/Dict.h index d0969480fb..7ac311a0ac 100644 --- a/Generals/Code/GameEngine/Include/Common/Dict.h +++ b/Generals/Code/GameEngine/Include/Common/Dict.h @@ -320,7 +320,7 @@ class Dict inline DictPair* peek() { return (DictPair*)(this+1); } }; - #ifdef _DEBUG + #ifdef RTS_DEBUG void validate() const; #else inline void validate() const { } diff --git a/Generals/Code/GameEngine/Include/Common/DrawModule.h b/Generals/Code/GameEngine/Include/Common/DrawModule.h index a9cb5f02bc..152b137d63 100644 --- a/Generals/Code/GameEngine/Include/Common/DrawModule.h +++ b/Generals/Code/GameEngine/Include/Common/DrawModule.h @@ -77,7 +77,7 @@ class DrawModule : public DrawableModule virtual void releaseShadows(void) = 0; ///< frees all shadow resources used by this module - used by Options screen. virtual void allocateShadows(void) = 0; ///< create shadow resources if not already present. Used by Options screen. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void getRenderCost(RenderCost & rc) const { }; ///< estimates the render cost of this draw module #endif diff --git a/Generals/Code/GameEngine/Include/Common/Energy.h b/Generals/Code/GameEngine/Include/Common/Energy.h index a6faacd27c..aea2740367 100644 --- a/Generals/Code/GameEngine/Include/Common/Energy.h +++ b/Generals/Code/GameEngine/Include/Common/Energy.h @@ -66,7 +66,7 @@ class Energy : public Snapshot public: - inline Energy() : m_energyProduction(0), m_energyConsumption(0), m_owner(NULL) { } + Energy(); // reset energy information to base values. void init( Player *owner) @@ -77,7 +77,7 @@ class Energy : public Snapshot } /// return current energy production in kilowatts - Int getProduction() const { return m_energyProduction; } + Int getProduction() const; /// return current energy consumption in kilowatts Int getConsumption() const { return m_energyConsumption; } diff --git a/Generals/Code/GameEngine/Include/Common/GameAudio.h b/Generals/Code/GameEngine/Include/Common/GameAudio.h index a9254cdca6..200efefb4c 100644 --- a/Generals/Code/GameEngine/Include/Common/GameAudio.h +++ b/Generals/Code/GameEngine/Include/Common/GameAudio.h @@ -136,7 +136,7 @@ class AudioManager : public SubsystemInterface public: AudioManager(); virtual ~AudioManager(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void audioDebugDisplay(DebugDisplayInterface *dd, void *userData, FILE *fp = NULL ) = 0; #endif @@ -152,10 +152,6 @@ class AudioManager : public SubsystemInterface virtual void resumeAudio( AudioAffect which ) = 0; virtual void pauseAmbient( Bool shouldPause ) = 0; - // device dependent stops. - virtual void stopAllAmbientsBy( Object* obj ) = 0; - virtual void stopAllAmbientsBy( Drawable* draw ) = 0; - // for focus issues virtual void loseFocus( void ); virtual void regainFocus( void ); @@ -240,6 +236,8 @@ class AudioManager : public SubsystemInterface // on zoom. virtual void set3DVolumeAdjustment( Real volumeAdjustment ); + virtual Bool has3DSensitiveStreamsPlaying( void ) const = 0; + virtual void *getHandleForBink( void ) = 0; virtual void releaseHandleForBink( void ) = 0; @@ -257,6 +255,7 @@ class AudioManager : public SubsystemInterface virtual void processRequestList( void ); virtual AudioEventInfo *newAudioEventInfo( AsciiString newEventName ); + virtual void addAudioEventInfo( AudioEventInfo * newEventInfo ); virtual AudioEventInfo *findAudioEventInfo( AsciiString eventName ) const; const AudioSettings *getAudioSettings( void ) const; @@ -298,6 +297,7 @@ class AudioManager : public SubsystemInterface // For Worldbuilder, to build lists from which to select virtual void findAllAudioEventsOfType( AudioType audioType, std::vector& allEvents ); + virtual const AudioEventInfoHash & getAllAudioEvents() const { return m_allAudioEventInfo; } Real getZoomVolume() const { return m_zoomVolume; } protected: @@ -316,7 +316,11 @@ class AudioManager : public SubsystemInterface // For tracking purposes virtual AudioHandle allocateNewHandle( void ); - + // Remove all AudioEventInfo's with the m_isLevelSpecific flag + virtual void removeLevelSpecificAudioEventInfos( void ); + + void removeAllAudioRequests( void ); + protected: AudioSettings *m_audioSettings; MiscAudio *m_miscAudio; diff --git a/Generals/Code/GameEngine/Include/Common/GameCommon.h b/Generals/Code/GameEngine/Include/Common/GameCommon.h index 90c23ecc61..54c6145432 100644 --- a/Generals/Code/GameEngine/Include/Common/GameCommon.h +++ b/Generals/Code/GameEngine/Include/Common/GameCommon.h @@ -54,7 +54,7 @@ #include "Lib/BaseType.h" // ---------------------------------------------------------------------------------------------- -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) #define NO_DUMP_PERF_STATS #else #define NO_DUMP_PERF_STATS diff --git a/Generals/Code/GameEngine/Include/Common/GameMemory.h b/Generals/Code/GameEngine/Include/Common/GameMemory.h index 2c222407e9..03dd4d109a 100644 --- a/Generals/Code/GameEngine/Include/Common/GameMemory.h +++ b/Generals/Code/GameEngine/Include/Common/GameMemory.h @@ -53,12 +53,12 @@ #define DISABLE_MEMORYPOOL_CHECKPOINTING 1 #endif -#if (defined(_DEBUG) || defined(_INTERNAL)) && !defined(MEMORYPOOL_DEBUG_CUSTOM_NEW) && !defined(DISABLE_MEMORYPOOL_DEBUG_CUSTOM_NEW) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) && !defined(MEMORYPOOL_DEBUG_CUSTOM_NEW) && !defined(DISABLE_MEMORYPOOL_DEBUG_CUSTOM_NEW) #define MEMORYPOOL_DEBUG_CUSTOM_NEW #endif -//#if (defined(_DEBUG) || defined(_INTERNAL)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) -#if (defined(_DEBUG)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) +//#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) +#if (defined(RTS_DEBUG)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) #define MEMORYPOOL_DEBUG #endif diff --git a/Generals/Code/GameEngine/Include/Common/GameType.h b/Generals/Code/GameEngine/Include/Common/GameType.h index 566f560f7c..b793738073 100644 --- a/Generals/Code/GameEngine/Include/Common/GameType.h +++ b/Generals/Code/GameEngine/Include/Common/GameType.h @@ -58,6 +58,8 @@ enum FormationID CPP_11(: Int) FORCE_FORMATIONID_TO_LONG_SIZE = 0x7ffffff }; +#define INVALID_ANGLE -100.0f + class INI; //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Include/Common/Geometry.h b/Generals/Code/GameEngine/Include/Common/Geometry.h index ec3e436fdb..3d6874a321 100644 --- a/Generals/Code/GameEngine/Include/Common/Geometry.h +++ b/Generals/Code/GameEngine/Include/Common/Geometry.h @@ -67,7 +67,7 @@ static const char *GeometryNames[] = #endif // end DEFINE_GEOMETRY_NAMES //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) enum ExtentModType CPP_11(: Int) { EXTENTMOD_INVALID = 0, @@ -179,6 +179,7 @@ class GeometryInfo : public Snapshot /// note that the pt is generated using game logic random, not game client random! void makeRandomOffsetWithinFootprint(Coord3D& pt) const; + void makeRandomOffsetOnPerimeter(Coord3D& pt) const; //Chooses a random point on the extent border. void clipPointToFootprint(const Coord3D& geomCenter, Coord3D& ptToClip) const; @@ -187,7 +188,7 @@ class GeometryInfo : public Snapshot // given an object with this geom, SET how far above the object's canonical position its max z should extend. void setMaxHeightAbovePosition(Real z); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void tweakExtents(ExtentModType extentModType, Real extentModAmount); AsciiString getDescriptiveString() const; #endif diff --git a/Generals/Code/GameEngine/Include/Common/GlobalData.h b/Generals/Code/GameEngine/Include/Common/GlobalData.h index 7840845813..f53073f33c 100644 --- a/Generals/Code/GameEngine/Include/Common/GlobalData.h +++ b/Generals/Code/GameEngine/Include/Common/GlobalData.h @@ -243,6 +243,7 @@ class GlobalData : public SubsystemInterface UnsignedInt m_noDraw; ///< Used to disable drawing, to profile game logic code. AIDebugOptions m_debugAI; ///< Used to display AI debug information + Bool m_debugSupplyCenterPlacement; ///< Dumps to log everywhere it thinks about placing a supply center Bool m_debugAIObstacles; ///< Used to display AI obstacle debug information Bool m_showObjectHealth; ///< debug display object health Bool m_scriptDebug; ///< Should we attempt to load the script debugger window (.DLL) @@ -326,6 +327,7 @@ class GlobalData : public SubsystemInterface AsciiString m_shellMapName; ///< Holds the shell map name Bool m_shellMapOn; ///< User can set the shell map not to load Bool m_playIntro; ///< Flag to say if we're to play the intro or not + Bool m_playSizzle; ///< Flag to say whether we play the sizzle movie after the logo movie. Bool m_afterIntro; ///< we need to tell the game our intro is done Bool m_allowExitOutOfMovies; ///< flag to allow exit out of movies only after the Intro has played @@ -435,7 +437,11 @@ class GlobalData : public SubsystemInterface Real m_keyboardCameraRotateSpeed; ///< How fast the camera rotates when rotated via keyboard controls. Int m_playStats; ///< Int whether we want to log play stats or not, if <= 0 then we don't log -#if defined(_DEBUG) || defined(_INTERNAL) + Bool m_TiVOFastMode; ///< When true, the client speeds up the framerate... set by HOTKEY! + + + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_wireframe; Bool m_stateMachineDebug; Bool m_useCameraConstraints; @@ -470,6 +476,7 @@ class GlobalData : public SubsystemInterface Int m_debugProjectileTileDuration; ///< How long should these tiles stay around, in frames? RGBColor m_debugProjectileTileColor; ///< What color should these tiles be? Bool m_showCollisionExtents; ///< Used to display collision extents + Bool m_showAudioLocations; ///< Used to display audio markers and ambient sound radii Bool m_saveStats; Bool m_saveAllStats; Bool m_useLocalMOTD; @@ -480,6 +487,7 @@ class GlobalData : public SubsystemInterface Int m_latencyPeriod; ///< Period of sinusoidal modulation of latency Int m_latencyNoise; ///< Max amplitude of jitter to throw in Int m_packetLoss; ///< Percent of packets to drop + Bool m_extraLogging; ///< More expensive debug logging to catch crashes. #endif #ifdef DEBUG_CRASHING diff --git a/Generals/Code/GameEngine/Include/Common/MessageStream.h b/Generals/Code/GameEngine/Include/Common/MessageStream.h index 1edb0c70c2..6592d771f1 100644 --- a/Generals/Code/GameEngine/Include/Common/MessageStream.h +++ b/Generals/Code/GameEngine/Include/Common/MessageStream.h @@ -235,7 +235,7 @@ class GameMessage : public MemoryPoolObject MSG_META_CHAT_EVERYONE, ///< send chat msg to everyone (incl. observers) MSG_META_DIPLOMACY, ///< bring up diplomacy screen MSG_META_OPTIONS, ///< bring up options screen -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) MSG_META_HELP, ///< bring up help screen #endif @@ -266,10 +266,12 @@ class GameMessage : public MemoryPoolObject MSG_META_BEGIN_CAMERA_ZOOM_OUT, MSG_META_END_CAMERA_ZOOM_OUT, MSG_META_CAMERA_RESET, + MSG_META_TOGGLE_FAST_FORWARD_REPLAY, ///< Toggle the fast forward feature + // META items that are really for debug/demo/development use only... // They do not get built into RELEASE builds. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) MSG_META_DEMO_TOGGLE_BEHIND_BUILDINGS, ///< Toggles showing units behind buildings or not MSG_META_DEMO_TOGGLE_LETTERBOX, ///< enable/disable letterbox mode MSG_META_DEMO_TOGGLE_MESSAGE_TEXT, ///< toggle the text from the UI messages @@ -383,11 +385,11 @@ class GameMessage : public MemoryPoolObject MSG_META_DEBUG_WIN, ///< Instant Win MSG_META_DEMO_TOGGLE_DEBUG_STATS, ///< show/hide the debug stats /// @todo END section to REMOVE (not disable) for release -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) MSG_META_DEMO_TOGGLE_AUDIODEBUG, ///< show/hide the audio debug info -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS MSG_META_DEMO_PERFORM_STATISTICAL_DUMP, ///< dump performance stats for this frame to StatisticsDump.txt #endif//DUMP_PERF_STATS @@ -560,7 +562,7 @@ class GameMessage : public MemoryPoolObject MSG_BEGIN_DEBUG_NETWORK_MESSAGES = 1900, ///< network messages that exist only in debug/internal builds. all grouped separately. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // all debug/internal-only messages must go here. MSG_DEBUG_KILL_SELECTION, MSG_DEBUG_HURT_OBJECT, diff --git a/Generals/Code/GameEngine/Include/Common/Money.h b/Generals/Code/GameEngine/Include/Common/Money.h index 2af2524424..c8b13e9d0c 100644 --- a/Generals/Code/GameEngine/Include/Common/Money.h +++ b/Generals/Code/GameEngine/Include/Common/Money.h @@ -82,8 +82,15 @@ class Money : public Snapshot void setPlayerIndex(Int ndx) { m_playerIndex = ndx; } -protected: + static void parseMoneyAmount( INI *ini, void *instance, void *store, const void* userData ); + + // Does the amount of this == the amount of that (compare everything except m_playerIndex) + Bool amountEqual( const Money & that ) const + { + return m_money == that.m_money; + } +protected: // snapshot methods virtual void crc( Xfer *xfer ); virtual void xfer( Xfer *xfer ); diff --git a/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h b/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h index 1d93377754..8cc00ebb40 100644 --- a/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h +++ b/Generals/Code/GameEngine/Include/Common/MultiplayerSettings.h @@ -79,9 +79,9 @@ class MultiplayerSettings : public SubsystemInterface MultiplayerSettings( void ); - void init() { } - void update() { } - void reset() { } + virtual void init() { } + virtual void update() { } + virtual void reset() { } //----------------------------------------------------------------------------------------------- static const FieldParse m_multiplayerSettingsFieldParseTable[]; ///< the parse table for INI definition diff --git a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h index 1363a4b5b6..583f42d658 100644 --- a/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h +++ b/Generals/Code/GameEngine/Include/Common/NameKeyGenerator.h @@ -96,9 +96,11 @@ class NameKeyGenerator : public SubsystemInterface /// Given a string, convert into a unique integer key. NameKeyType nameToKey(const AsciiString& name) { return nameToKey(name.str()); } + NameKeyType nameToLowercaseKey(const AsciiString& name) { return nameToLowercaseKey(name.str()); } /// Given a string, convert into a unique integer key. NameKeyType nameToKey(const char* name); + NameKeyType nameToLowercaseKey(const char *name); /** given a key, return the name. this is almost never needed, @@ -108,6 +110,9 @@ class NameKeyGenerator : public SubsystemInterface */ AsciiString keyToName(NameKeyType key); + // Get a string out of the INI. Store it into a NameKeyType + static void parseStringAsNameKeyType( INI *ini, void *instance, void *store, const void* userData ); + private: enum diff --git a/Generals/Code/GameEngine/Include/Common/PerfTimer.h b/Generals/Code/GameEngine/Include/Common/PerfTimer.h index 30d77aa749..fee64c7509 100644 --- a/Generals/Code/GameEngine/Include/Common/PerfTimer.h +++ b/Generals/Code/GameEngine/Include/Common/PerfTimer.h @@ -33,7 +33,7 @@ #include "Utility/intrin_compat.h" -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /* NOTE NOTE NOTE: never check this in with this enabled, since there is a nonzero time penalty for running in this mode. Only enable it for local builds for testing purposes! (srj) @@ -153,7 +153,7 @@ void PerfGather::stopTimer() ++m_callCount; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(*m_activeHead != NULL, ("m_activeHead is null, uh oh")); DEBUG_ASSERTCRASH(*m_activeHead == this, ("I am not the active timer, uh oh")); DEBUG_ASSERTCRASH(m_activeHead >= &m_active[0] && m_activeHead <= &m_active[MAX_ACTIVE_STACK-1], ("active under/over flow")); diff --git a/Generals/Code/GameEngine/Include/Common/Player.h b/Generals/Code/GameEngine/Include/Common/Player.h index e074b926b4..be96a90299 100644 --- a/Generals/Code/GameEngine/Include/Common/Player.h +++ b/Generals/Code/GameEngine/Include/Common/Player.h @@ -307,7 +307,7 @@ class Player : public Snapshot void onUpgradeCompleted( const UpgradeTemplate *upgradeTemplate ); ///< An upgrade just finished, do things like tell all objects to recheck UpgradeModules void onUpgradeRemoved(){} ///< An upgrade just got removed, this doesn't do anything now. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /// Prereq disabling cheat key void toggleIgnorePrereqs(){ m_DEMO_ignorePrereqs = !m_DEMO_ignorePrereqs; } Bool ignoresPrereqs() const { return m_DEMO_ignorePrereqs; } @@ -767,7 +767,7 @@ class Player : public Snapshot Real m_cashBountyPercent; /// @todo REMOVE (not disable) these cheat keys -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_DEMO_ignorePrereqs; ///< Can I ignore prereq checks? Bool m_DEMO_freeBuild; ///< Can I build everything for no money? Bool m_DEMO_instantBuild; ///< Can I build anything in one frame? diff --git a/Generals/Code/GameEngine/Include/Common/Radar.h b/Generals/Code/GameEngine/Include/Common/Radar.h index 33d61a0069..fb1b65547a 100644 --- a/Generals/Code/GameEngine/Include/Common/Radar.h +++ b/Generals/Code/GameEngine/Include/Common/Radar.h @@ -169,6 +169,7 @@ class Radar : public Snapshot, Bool isRadarWindow( GameWindow *window ) { return (m_radarWindow == window) && (m_radarWindow != NULL); } Bool radarToWorld( const ICoord2D *radar, Coord3D *world ); ///< radar point to world point on terrain + Bool radarToWorld2D( const ICoord2D *radar, Coord3D *world ); ///< radar point to world point (x,y only!) Bool worldToRadar( const Coord3D *world, ICoord2D *radar ); ///< translate world point to radar (x,y) Bool localPixelToRadar( const ICoord2D *pixel, ICoord2D *radar ); ///< translate pixel (with UL of radar being (0,0)) to logical radar coords Bool screenPixelToWorld( const ICoord2D *pixel, Coord3D *world ); ///< translate pixel (with UL of the screen being (0,0)) to world position in the world diff --git a/Generals/Code/GameEngine/Include/Common/Recorder.h b/Generals/Code/GameEngine/Include/Common/Recorder.h index 7dd61c617b..581c5dfe72 100644 --- a/Generals/Code/GameEngine/Include/Common/Recorder.h +++ b/Generals/Code/GameEngine/Include/Common/Recorder.h @@ -71,7 +71,7 @@ class RecorderClass : public SubsystemInterface { Bool testVersionPlayback(AsciiString filename); ///< Returns if the playback is a valid playback file for this version or not. AsciiString getCurrentReplayFilename( void ); ///< valid during playback only void stopPlayback(); ///< Stops playback. Its fine to call this even if not playing back a file. -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool analyzeReplay( AsciiString filename ); Bool isAnalysisInProgress( void ); #endif diff --git a/Generals/Code/GameEngine/Include/Common/Science.h b/Generals/Code/GameEngine/Include/Common/Science.h index e124fafa26..192da64f1b 100644 --- a/Generals/Code/GameEngine/Include/Common/Science.h +++ b/Generals/Code/GameEngine/Include/Common/Science.h @@ -81,6 +81,8 @@ class ScienceStore : public SubsystemInterface friend class ScienceInfo; public: + virtual ~ScienceStore(); + void init(); void reset(); void update() { } diff --git a/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h b/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h index 067ff78421..e3a933b502 100644 --- a/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h +++ b/Generals/Code/GameEngine/Include/Common/SparseMatchFinder.h @@ -36,7 +36,7 @@ #include "Common/BitFlags.h" #include "Common/STLTypedefs.h" -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define SPARSEMATCH_DEBUG #else #undef SPARSEMATCH_DEBUG @@ -72,6 +72,26 @@ class SparseMatchFinder } }; + struct MapHelper + { + bool operator()(const BITSET& a, const BITSET& b) const + { + int i; + if (a.size() < b.size()) { + return true; + } + for (i = 0; i < a.size(); ++i) { + bool aVal = a.test(i); + bool bVal = b.test(i); + if (aVal && bVal) continue; + if (!aVal && !bVal) continue; + if (!aVal) return true; + return false; + } + return false; // all bits match. + } + }; + //------------------------------------------------------------------------------------------------- typedef std::hash_map< BITSET, const MATCHABLE*, HashMapHelper, HashMapHelper > MatchMap; @@ -176,16 +196,22 @@ class SparseMatchFinder const MATCHABLE* findBestInfo(const std::vector& v, const BITSET& bits) const { typename MatchMap::const_iterator it = m_bestMatches.find(bits); + + const MATCHABLE *first = NULL; if (it != m_bestMatches.end()) { - return (*it).second; + first = (*it).second; } - + if (first != NULL) { + return first; + } + const MATCHABLE* info = findBestInfoSlow(v, bits); DEBUG_ASSERTCRASH(info != NULL, ("no suitable match for criteria was found!\n")); - if (info != NULL) + if (info != NULL) { m_bestMatches[bits] = info; + } return info; } diff --git a/Generals/Code/GameEngine/Include/Common/SpecialPower.h b/Generals/Code/GameEngine/Include/Common/SpecialPower.h index 6e2dc52cca..d50e9242e3 100644 --- a/Generals/Code/GameEngine/Include/Common/SpecialPower.h +++ b/Generals/Code/GameEngine/Include/Common/SpecialPower.h @@ -123,6 +123,7 @@ class SpecialPowerTemplate : public Overridable UnsignedInt getViewObjectDuration( void ) const { return getFO()->m_viewObjectDuration; } Real getViewObjectRange( void ) const { return getFO()->m_viewObjectRange; } Real getRadiusCursorRadius() const { return getFO()->m_radiusCursorRadius; } + Bool isShortcutPower() const { return getFO()->m_shortcutPower; } private: @@ -142,6 +143,7 @@ class SpecialPowerTemplate : public Overridable Real m_radiusCursorRadius; ///< size of radius cursor, if any Bool m_publicTimer; ///< display a countdown timer for this special power for all to see Bool m_sharedNSync; ///< If true, this is a special that is shared between all of a player's command centers + Bool m_shortcutPower; ///< Is this shortcut power capable of being fired by the side panel? static const FieldParse m_specialPowerFieldParse[]; ///< the parse table diff --git a/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h b/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h index f350a2ea45..ffabd68f9c 100644 --- a/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h +++ b/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h @@ -31,6 +31,7 @@ #define __SPECIALPOWERMASKTYPE_H__ #include "Common/BitFlags.h" +#include "Common/BitFlagsIO.h" #include "Common/SpecialPowerType.h" typedef BitFlags SpecialPowerMaskType; diff --git a/Generals/Code/GameEngine/Include/Common/StackDump.h b/Generals/Code/GameEngine/Include/Common/StackDump.h index d0f7a1ff4f..2a6b040ab6 100644 --- a/Generals/Code/GameEngine/Include/Common/StackDump.h +++ b/Generals/Code/GameEngine/Include/Common/StackDump.h @@ -31,7 +31,7 @@ #define IG_DEBUG_STACKTRACE 1 #endif -#if defined(_DEBUG) || defined(_INTERNAL) || defined(IG_DEBUG_STACKTRACE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(IG_DEBUG_STACKTRACE) // Writes a stackdump (provide a callback : gets called per line) // If callback is NULL then will write using OuputDebugString diff --git a/Generals/Code/GameEngine/Include/Common/StateMachine.h b/Generals/Code/GameEngine/Include/Common/StateMachine.h index 25cb7eb145..49b561c65c 100644 --- a/Generals/Code/GameEngine/Include/Common/StateMachine.h +++ b/Generals/Code/GameEngine/Include/Common/StateMachine.h @@ -45,11 +45,11 @@ class State; class StateMachine; class Object; -#undef STATE_MACHINE_DEBUG -#if defined(_DEBUG) +//#undef STATE_MACHINE_DEBUG +#if defined(RTS_DEBUG) #define STATE_MACHINE_DEBUG #endif -#if defined(_INTERNAL) +#if defined(RTS_INTERNAL) #define STATE_MACHINE_DEBUG //uncomment to debug state machines in internal. jba. #endif @@ -169,6 +169,7 @@ class State : public MemoryPoolObject, public Snapshot #ifdef STATE_MACHINE_DEBUG virtual AsciiString getName() const {return m_name;} + std::vector *getTransitions(void); #endif // for internal use by the StateMachine class --------------------------------------------------------- @@ -318,7 +319,7 @@ class StateMachine : public MemoryPoolObject, public Snapshot // StateReturnType internalSetState( StateID newStateID ); ///< for internal use only - change the current state of the machine -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) UnsignedInt peekSleepTill() const { return m_sleepTill; } #endif diff --git a/Generals/Code/GameEngine/Include/Common/Thing.h b/Generals/Code/GameEngine/Include/Common/Thing.h index f766515fff..995b3e1e1c 100644 --- a/Generals/Code/GameEngine/Include/Common/Thing.h +++ b/Generals/Code/GameEngine/Include/Common/Thing.h @@ -161,7 +161,7 @@ class Thing : public MemoryPoolObject // since ThingTemplates are shared between many, many Things, the Thing // should never be able to change it. OVERRIDE m_template; ///< reference back to template database -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) AsciiString m_templateName; #endif /* diff --git a/Generals/Code/GameEngine/Include/Common/ThingTemplate.h b/Generals/Code/GameEngine/Include/Common/ThingTemplate.h index d6ef1ee3f5..30a2793119 100644 --- a/Generals/Code/GameEngine/Include/Common/ThingTemplate.h +++ b/Generals/Code/GameEngine/Include/Common/ThingTemplate.h @@ -286,7 +286,7 @@ class ModuleInfo return m_info.size(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool containsPartialName(const char* n) const { for (size_t i = 0; i < m_info.size(); i++) diff --git a/Generals/Code/GameEngine/Include/Common/UnicodeString.h b/Generals/Code/GameEngine/Include/Common/UnicodeString.h index 13688973d9..5f15a0e046 100644 --- a/Generals/Code/GameEngine/Include/Common/UnicodeString.h +++ b/Generals/Code/GameEngine/Include/Common/UnicodeString.h @@ -89,7 +89,7 @@ class UnicodeString // add a ctor/dtor, 'cuz they won't ever be called. struct UnicodeStringData { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) const WideChar* m_debugptr; // just makes it easier to read in the debugger #endif unsigned short m_refCount; // reference count @@ -99,7 +99,7 @@ class UnicodeString inline WideChar* peek() { return (WideChar*)(this+1); } }; - #ifdef _DEBUG + #ifdef RTS_DEBUG void validate() const; #else inline void validate() const { } diff --git a/Generals/Code/GameEngine/Include/Common/Xfer.h b/Generals/Code/GameEngine/Include/Common/Xfer.h deleted file mode 100644 index 9975e9ae5e..0000000000 --- a/Generals/Code/GameEngine/Include/Common/Xfer.h +++ /dev/null @@ -1,188 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Xfer.h /////////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: The Xfer system is capable of setting up operations to work with blocks of data -// from other subsystems. It can work things such as file reading, file writing, -// CRC computations etc -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __XFER_H_ -#define __XFER_H_ - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Common/ModelState.h" -#include "Common/Science.h" -#include "Common/Upgrade.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class Snapshot; -typedef Int Color; -enum ObjectID CPP_11(: Int); -enum DrawableID CPP_11(: Int); -enum KindOfType CPP_11(: Int); -enum ScienceType CPP_11(: Int); -class Matrix3D; - -// ------------------------------------------------------------------------------------------------ -typedef UnsignedByte XferVersion; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -enum XferMode CPP_11(: Int) -{ - XFER_INVALID = 0, - - XFER_SAVE, - XFER_LOAD, - XFER_CRC, - - NUM_XFER_TYPES // please keep this last -}; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -enum XferStatus CPP_11(: Int) -{ - XFER_STATUS_INVALID = 0, - - XFER_OK, ///< all is green and good - XFER_EOF, ///< end of file encountered - XFER_FILE_NOT_FOUND, ///< requested file does not exist - XFER_FILE_NOT_OPEN, ///< file was not open - XFER_FILE_ALREADY_OPEN, ///< this xfer is already open - XFER_READ_ERROR, ///< error reading from file - XFER_WRITE_ERROR, ///< error writing to file - XFER_MODE_UNKNOWN, ///< unknown xfer mode - XFER_SKIP_ERROR, ///< error skipping file - XFER_BEGIN_END_MISMATCH, ///< mismatched pair calls of begin/end block - XFER_OUT_OF_MEMORY, ///< out of memory - XFER_STRING_ERROR, ///< error with strings - XFER_INVALID_VERSION, ///< invalid version encountered - XFER_INVALID_PARAMETERS, ///< invalid parameters - XFER_LIST_NOT_EMPTY, ///< trying to xfer into a list that should be empty, but isn't - XFER_UNKNOWN_STRING, ///< unrecognized string value - - XFER_ERROR_UNKNOWN, ///< unknown error (isn't that useful!) - - NUM_XFER_STATUS // please keep this last -}; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -enum XferOptions CPP_11(: UnsignedInt) -{ - XO_NONE = 0x00000000, - XO_NO_POST_PROCESSING = 0x00000001, - - XO_ALL = 0xFFFFFFFF // keep this last please -}; - -/////////////////////////////////////////////////////////////////////////////////////////////////// -typedef Int XferBlockSize; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class Xfer -{ - -public: - - Xfer( void ); - virtual ~Xfer( void ); - - virtual XferMode getXferMode( void ) { return m_xferMode; } - AsciiString getIdentifier( void ) { return m_identifier; } - - // xfer management - virtual void setOptions( UnsignedInt options ) { BitSet( m_options, options ); } - virtual void clearOptions( UnsignedInt options ) { BitClear( m_options, options ); } - virtual UnsignedInt getOptions( void ) { return m_options; } - virtual void open( AsciiString identifier ) = 0; ///< xfer open event - virtual void close( void ) = 0; ///< xfer close event - virtual Int beginBlock( void ) = 0; ///< xfer begin block event - virtual void endBlock( void ) = 0; ///< xfer end block event - virtual void skip( Int dataSize ) = 0; ///< xfer skip data - - virtual void xferSnapshot( Snapshot *snapshot ) = 0; ///< entry point for xfering a snapshot - - // - // default transfer methods, these call the implementation method with the data - // parameters. You may use the default, or derive and create new ways to xfer each - // of these types of data - // - virtual void xferVersion( XferVersion *versionData, XferVersion currentVersion ); - virtual void xferByte( Byte *byteData ); - virtual void xferUnsignedByte( UnsignedByte *unsignedByteData ); - virtual void xferBool( Bool *boolData ); - virtual void xferInt( Int *intData ); - virtual void xferInt64( Int64 *int64Data ); - virtual void xferUnsignedInt( UnsignedInt *unsignedIntData ); - virtual void xferShort( Short *shortData ); - virtual void xferUnsignedShort( UnsignedShort *unsignedShortData ); - virtual void xferReal( Real *realData ); - virtual void xferMarkerLabel( AsciiString asciiStringData ); // This is purely for readability purposes - it is explicitly discarded on load. - virtual void xferAsciiString( AsciiString *asciiStringData ); - virtual void xferUnicodeString( UnicodeString *unicodeStringData ); - virtual void xferCoord3D( Coord3D *coord3D ); - virtual void xferICoord3D( ICoord3D *iCoord3D ); - virtual void xferRegion3D( Region3D *region3D ); - virtual void xferIRegion3D( IRegion3D *iRegion3D ); - virtual void xferCoord2D( Coord2D *coord2D ); - virtual void xferICoord2D( ICoord2D *iCoord2D ); - virtual void xferRegion2D( Region2D *region2D ); - virtual void xferIRegion2D( IRegion2D *iRegion2D ); - virtual void xferRealRange( RealRange *realRange ); - virtual void xferColor( Color *color ); - virtual void xferRGBColor( RGBColor *rgbColor ); - virtual void xferRGBAColorReal( RGBAColorReal *rgbaColorReal ); - virtual void xferRGBAColorInt( RGBAColorInt *rgbaColorInt ); - virtual void xferObjectID( ObjectID *objectID ); - virtual void xferDrawableID( DrawableID *drawableID ); - virtual void xferSTLObjectIDList( std::list< ObjectID > *objectIDListData ); - virtual void xferSTLIntList( std::list< Int > *intListData ); - virtual void xferScienceType( ScienceType *science ); - virtual void xferScienceVec( ScienceVec *scienceVec ); - virtual void xferKindOf( KindOfType *kindOfData ); - virtual void xferUpgradeMask( UpgradeMaskType *upgradeMaskData ); - virtual void xferUser( void *data, Int dataSize ); - virtual void xferMatrix3D( Matrix3D* mtx ); - virtual void xferMapName( AsciiString *mapNameData ); - -protected: - - // this is the actual xfer impelmentation that each derived class should implement - virtual void xferImplementation( void *data, Int dataSize ) = 0; - - UnsignedInt m_options; ///< xfer options - XferMode m_xferMode; ///< the current xfer mode - AsciiString m_identifier; ///< the string identifier - -}; - -#endif // __XFER_H_ - diff --git a/Generals/Code/GameEngine/Include/Common/XferCRC.h b/Generals/Code/GameEngine/Include/Common/XferCRC.h deleted file mode 100644 index e26671402b..0000000000 --- a/Generals/Code/GameEngine/Include/Common/XferCRC.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferCRC.h //////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: Xfer hard disk read implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __XFERCRC_H_ -#define __XFERCRC_H_ - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "Common/Xfer.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class Snapshot; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class XferCRC : public Xfer -{ - -public: - - XferCRC( void ); - virtual ~XferCRC( void ); - - // Xfer methods - virtual void open( AsciiString identifier ); ///< start a CRC session with this xfer instance - virtual void close( void ); ///< stop CRC session - virtual Int beginBlock( void ); ///< start block event - virtual void endBlock( void ); ///< end block event - virtual void skip( Int dataSize ); ///< skip xfer event - - virtual void xferSnapshot( Snapshot *snapshot ); ///< entry point for xfering a snapshot - - // Xfer CRC methods - virtual UnsignedInt getCRC( void ); ///< get computed CRC in network byte order - -protected: - - virtual void xferImplementation( void *data, Int dataSize ); - - void addCRC( UnsignedInt val ); ///< CRC a 4-byte block - - UnsignedInt m_crc; - -}; - -#endif // __XFERDISKWRITE_H_ - diff --git a/Generals/Code/GameEngine/Include/Common/XferDeepCRC.h b/Generals/Code/GameEngine/Include/Common/XferDeepCRC.h deleted file mode 100644 index 94e0eba37c..0000000000 --- a/Generals/Code/GameEngine/Include/Common/XferDeepCRC.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferDeepCRC.h //////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: Xfer hard disk read implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __XFERDEEPCRC_H_ -#define __XFERDEEPCRC_H_ - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "Common/Xfer.h" -#include "Common/XferCRC.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class Snapshot; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class XferDeepCRC : public XferCRC -{ - -public: - - XferDeepCRC( void ); - virtual ~XferDeepCRC( void ); - - // Xfer methods - virtual void open( AsciiString identifier ); ///< start a CRC session with this xfer instance - virtual void close( void ); ///< stop CRC session - - // xfer methods - virtual void xferMarkerLabel( AsciiString asciiStringData ); ///< xfer ascii string (need our own) - virtual void xferAsciiString( AsciiString *asciiStringData ); ///< xfer ascii string (need our own) - virtual void xferUnicodeString( UnicodeString *unicodeStringData ); ///< xfer unicode string (need our own); - -protected: - - virtual void xferImplementation( void *data, Int dataSize ); - - FILE * m_fileFP; ///< pointer to file -}; - -#endif // __XFERDEEPCRC_H_ - diff --git a/Generals/Code/GameEngine/Include/Common/XferLoad.h b/Generals/Code/GameEngine/Include/Common/XferLoad.h deleted file mode 100644 index 45515f3f60..0000000000 --- a/Generals/Code/GameEngine/Include/Common/XferLoad.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferLoad.h /////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: Xfer hard disk read implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __XFER_LOAD_H_ -#define __XFER_LOAD_H_ - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include -#include "Common/Xfer.h" - -// FOWARD REFERNCES /////////////////////////////////////////////////////////////////////////////// -class Snapshot; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class XferLoad : public Xfer -{ - -public: - - XferLoad( void ); - virtual ~XferLoad( void ); - - virtual void open( AsciiString identifier ); ///< open file for writing - virtual void close( void ); ///< close file - virtual Int beginBlock( void ); ///< read placeholder block size - virtual void endBlock( void ); ///< reading an end block is a no-op - virtual void skip( Int dataSize ); ///< skip forward dataSize bytes in file - - virtual void xferSnapshot( Snapshot *snapshot ); ///< entry point for xfering a snapshot - - // xfer methods - virtual void xferAsciiString( AsciiString *asciiStringData ); ///< xfer ascii string (need our own) - virtual void xferUnicodeString( UnicodeString *unicodeStringData ); ///< xfer unicode string (need our own); - -protected: - - virtual void xferImplementation( void *data, Int dataSize ); ///< the xfer implementation - - FILE * m_fileFP; ///< pointer to file - -}; - -#endif // __XFER_LOAD_H_ - diff --git a/Generals/Code/GameEngine/Include/Common/XferSave.h b/Generals/Code/GameEngine/Include/Common/XferSave.h deleted file mode 100644 index 112fdb5d45..0000000000 --- a/Generals/Code/GameEngine/Include/Common/XferSave.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferSave.h /////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: Xfer hard disk write implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __XFER_SAVE_H_ -#define __XFER_SAVE_H_ - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "Common/Xfer.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class XferBlockData; -class Snapshot; - -/////////////////////////////////////////////////////////////////////////////////////////////////// -typedef long XferFilePos; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class XferSave : public Xfer -{ - -public: - - XferSave( void ); - virtual ~XferSave( void ); - - // Xfer methods - virtual void open( AsciiString identifier ); ///< open file for writing - virtual void close( void ); ///< close file - virtual Int beginBlock( void ); ///< write placeholder block size - virtual void endBlock( void ); ///< backup to last begin block and write size - virtual void skip( Int dataSize ); ///< skipping during a write is a no-op - - virtual void xferSnapshot( Snapshot *snapshot ); ///< entry point for xfering a snapshot - - // xfer methods - virtual void xferAsciiString( AsciiString *asciiStringData ); ///< xfer ascii string (need our own) - virtual void xferUnicodeString( UnicodeString *unicodeStringData ); ///< xfer unicode string (need our own); - -protected: - - virtual void xferImplementation( void *data, Int dataSize ); ///< the xfer implementation - - FILE * m_fileFP; ///< pointer to file - XferBlockData *m_blockStack; ///< stack of block data - -}; - -#endif // __XFER_SAVE_H_ - diff --git a/Generals/Code/GameEngine/Include/Common/crc.h b/Generals/Code/GameEngine/Include/Common/crc.h index 8547351f09..2bc5ef495e 100644 --- a/Generals/Code/GameEngine/Include/Common/crc.h +++ b/Generals/Code/GameEngine/Include/Common/crc.h @@ -32,6 +32,9 @@ #define _CRC_H_ #include "Lib/BaseType.h" + +#ifdef RTS_DEBUG + //#include "winsock2.h" // for htonl class CRC @@ -50,4 +53,77 @@ class CRC UnsignedInt crc; }; +#else + +// optimized inline only version +class CRC +{ +public: + CRC(void) { crc=0; } + + /// Compute the CRC for a buffer, added into current CRC + __forceinline void computeCRC( const void *buf, Int len ) + { + if (!buf||len<1) + return; + +#if !(defined(_MSC_VER) && _MSC_VER < 1300) + // C++ version left in for reference purposes + for (UnsignedByte *uintPtr=(UnsignedByte *)buf;len>0;len--,uintPtr++) + { + int hibit; + if (crc & 0x80000000) + { + hibit = 1; + } + else + { + hibit = 0; + } + + crc <<= 1; + crc += *uintPtr; + crc += hibit; + } +#else + // ASM version, verified by comparing resulting data with C++ version data + unsigned *crcPtr=&crc; + _asm + { + mov esi,[buf] + mov ecx,[len] + dec ecx + mov edi,[crcPtr] + mov ebx,dword ptr [edi] + xor eax,eax + lp: + mov al,byte ptr [esi] + shl ebx,1 + inc esi + adc ebx,eax + dec ecx + jns lp + mov dword ptr [edi],ebx + }; +#endif + } + + /// Clears the CRC to 0 + void clear( void ) + { + crc = 0; + } + + ///< Get the combined CRC + UnsignedInt get( void ) const + { + return crc; + } + +private: + UnsignedInt crc; +}; + +#endif + #endif // _CRC_H_ diff --git a/Generals/Code/GameEngine/Include/GameClient/ClientInstance.h b/Generals/Code/GameEngine/Include/GameClient/ClientInstance.h new file mode 100644 index 0000000000..74e7add404 --- /dev/null +++ b/Generals/Code/GameEngine/Include/GameClient/ClientInstance.h @@ -0,0 +1,47 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ +#include "Lib/BaseType.h" + +namespace rts +{ + +// TheSuperHackers @feature Adds support for launching multiple game clients and keeping track of their instance id. + +class ClientInstance +{ +public: + // Can be called N times, but is initialized just once. + static bool initialize(); + + static bool isInitialized(); + + // Returns the instance index of this game client. Starts at 0. + static UnsignedInt getInstanceIndex(); + + // Returns the instance id of this game client. Starts at 1. + static UnsignedInt getInstanceId(); + + // Returns the instance name of the first game client. + static const char* getFirstInstanceName(); + +private: + static HANDLE s_mutexHandle; + static UnsignedInt s_instanceIndex; +}; + +} // namespace rts diff --git a/Generals/Code/GameEngine/Include/GameClient/Color.h b/Generals/Code/GameEngine/Include/GameClient/Color.h index 2c512e7986..94d952790c 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Color.h +++ b/Generals/Code/GameEngine/Include/GameClient/Color.h @@ -76,6 +76,15 @@ extern void GameGetColorComponents( Color color, UnsignedByte *green, UnsignedByte *blue, UnsignedByte *alpha ); + +// Put on ice until later - M Lorenzen +//extern void GameGetColorComponentsWithCheatSpy( Color color, +// UnsignedByte *red, +// UnsignedByte *green, +// UnsignedByte *blue, +// UnsignedByte *alpha ); + + extern void GameGetColorComponentsReal( Color color, Real *red, Real *green, Real *blue, Real *alpha ); extern Color GameDarkenColor( Color color, Int percent = 10 ); diff --git a/Generals/Code/GameEngine/Include/GameClient/ControlBar.h b/Generals/Code/GameEngine/Include/GameClient/ControlBar.h index c25dd7fccf..47e96c62fc 100644 --- a/Generals/Code/GameEngine/Include/GameClient/ControlBar.h +++ b/Generals/Code/GameEngine/Include/GameClient/ControlBar.h @@ -341,6 +341,10 @@ class CommandButton : public Overridable // bleah. shouldn't be const, but is. sue me. (srj) void copyImagesFrom( const CommandButton *button, Bool markUIDirtyIfChanged ) const; + + // bleah. shouldn't be const, but is. sue me. (Kris) -snork! + void copyButtonTextFrom( const CommandButton *button, Bool shortcutButton, Bool markUIDirtyIfChanged ) const; + // bleah. shouldn't be const, but is. sue me. (srj) void setFlashCount(Int c) const { m_flashCount = c; } @@ -359,8 +363,11 @@ class CommandButton : public Overridable RadiusCursorType m_radiusCursor; ///< radius cursor, if any AsciiString m_cursorName; ///< cursor name for placement (NEED_TARGET_POS) or valid version (CONTEXTMODE_COMMAND) AsciiString m_invalidCursorName; ///< cursor name for invalid version - AsciiString m_textLabel; ///< string manager text label - AsciiString m_descriptionLabel; ///< The description of the current command, read in from the ini + + // bleah. shouldn't be mutable, but is. sue me. (Kris) -snork! + mutable AsciiString m_textLabel; ///< string manager text label + mutable AsciiString m_descriptionLabel; ///< The description of the current command, read in from the ini + AsciiString m_purchasedLabel; ///< Description for the current command if it has already been purchased. AsciiString m_conflictingLabel; ///< Description for the current command if it can't be selected due to multually-exclusive choice. WeaponSlotType m_weaponSlot; ///< for commands that refer to a weapon slot @@ -640,7 +647,7 @@ class ControlBar : public SubsystemInterface virtual void update( void ); ///< from subsystem interface /// mark the UI as dirty so the context of everything is re-evaluated - void markUIDirty( void ) { m_UIDirty = TRUE; } + void markUIDirty( void ); /// a drawable has just become selected void onDrawableSelected( Drawable *draw ); @@ -999,6 +1006,11 @@ class ControlBar : public SubsystemInterface Bool m_radarAttackGlowOn; Int m_remainingRadarAttackGlowFrames; GameWindow *m_radarAttackGlowWindow; + +#if defined( RTS_INTERNAL ) || defined( RTS_DEBUG ) + UnsignedInt m_lastFrameMarkedDirty; + UnsignedInt m_consecutiveDirtyFrames; +#endif // ControlBarResizer *m_controlBarResizer; }; diff --git a/Generals/Code/GameEngine/Include/GameClient/DebugDisplay.h b/Generals/Code/GameEngine/Include/GameClient/DebugDisplay.h index b1d42a3f70..c156b900b9 100644 --- a/Generals/Code/GameEngine/Include/GameClient/DebugDisplay.h +++ b/Generals/Code/GameEngine/Include/GameClient/DebugDisplay.h @@ -142,7 +142,7 @@ class DebugDisplay : public DebugDisplayInterface // displayers -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern void AudioDebugDisplay( DebugDisplayInterface *debugDisplay, void *userData, FILE *fp ); #endif diff --git a/Generals/Code/GameEngine/Include/GameClient/Display.h b/Generals/Code/GameEngine/Include/GameClient/Display.h index 966f724795..1a873ce8e6 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Display.h +++ b/Generals/Code/GameEngine/Include/GameClient/Display.h @@ -92,7 +92,7 @@ class Display : public SubsystemInterface virtual void setGamma(Real gamma, Real bright, Real contrast, Bool calibrate) {}; virtual Bool testMinSpecRequirements(Bool *videoPassed, Bool *cpuPassed, Bool *memPassed,StaticGameLODLevel *idealVideoLevel=NULL, Real *cpuTime=NULL) {*videoPassed=*cpuPassed=*memPassed=true; return true;} virtual void doSmartAssetPurgeAndPreload(const char* usageFileName) = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void dumpAssetUsage(const char* mapname) = 0; #endif @@ -163,7 +163,7 @@ class Display : public SubsystemInterface virtual void clearShroud() = 0; ///< empty the entire shroud virtual void setBorderShroudLevel(UnsignedByte level) = 0; ///killIcon(t); } Bool hasIconInfo() const { return m_iconInfo != NULL; } + const AudioEventRTS * getAmbientSound() const { return m_ambientSound == NULL ? NULL : &m_ambientSound->m_event; } protected: // snapshot methods @@ -590,7 +591,7 @@ class Drawable : public Thing, const AudioEventRTS& getAmbientSoundByDamage(BodyDamageType dt); -#ifdef _DEBUG +#ifdef RTS_DEBUG void validatePos() const; #endif diff --git a/Generals/Code/GameEngine/Include/GameClient/GadgetCheckBox.h b/Generals/Code/GameEngine/Include/GameClient/GadgetCheckBox.h index 0545f14e47..f801752f62 100644 --- a/Generals/Code/GameEngine/Include/GameClient/GadgetCheckBox.h +++ b/Generals/Code/GameEngine/Include/GameClient/GadgetCheckBox.h @@ -80,6 +80,7 @@ extern void GadgetCheckBoxSetText( GameWindow *g, UnicodeString text ); extern Bool GadgetCheckBoxIsChecked( GameWindow *g ); extern void GadgetCheckBoxSetChecked( GameWindow *g, Bool isChecked); +extern void GadgetCheckBoxToggle( GameWindow *g); inline void GadgetCheckBoxSetEnabledImage( GameWindow *g, const Image *image ) { g->winSetEnabledImage( 0, image ); } inline void GadgetCheckBoxSetEnabledColor( GameWindow *g, Color color ) { g->winSetEnabledColor( 0, color ); } diff --git a/Generals/Code/GameEngine/Include/GameClient/GameWindow.h b/Generals/Code/GameEngine/Include/GameClient/GameWindow.h index e5c427436b..c1204631d5 100644 --- a/Generals/Code/GameEngine/Include/GameClient/GameWindow.h +++ b/Generals/Code/GameEngine/Include/GameClient/GameWindow.h @@ -248,6 +248,7 @@ friend class GameWindowManager; Int winBringToTop( void ); ///< bring this window to the top of the win list Int winEnable( Bool enable ); /**< enable/disable a window, a disbled window can be seen but accepts no input */ + Bool winGetEnabled( void ); ///< Is window enabled? Int winHide( Bool hide ); ///< hide/unhide a window Bool winIsHidden( void ); ///< is this window hidden/ UnsignedInt winSetStatus( UnsignedInt status ); ///< set status bits diff --git a/Generals/Code/GameEngine/Include/GameClient/InGameUI.h b/Generals/Code/GameEngine/Include/GameClient/InGameUI.h index 80c4a11a16..a087d962e4 100644 --- a/Generals/Code/GameEngine/Include/GameClient/InGameUI.h +++ b/Generals/Code/GameEngine/Include/GameClient/InGameUI.h @@ -564,7 +564,7 @@ friend class Drawable; // for selection/deselection transactions Real durationInSeconds, Real zRisePerSecond ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void DEBUG_addFloatingText(const AsciiString& text,const Coord3D * pos, Color color); #endif @@ -584,7 +584,7 @@ friend class Drawable; // for selection/deselection transactions { MOVE_HINT = 0, ATTACK_HINT, -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_HINT, #endif NUM_HINT_TYPES // keep this one last diff --git a/Generals/Code/GameEngine/Include/GameClient/Mouse.h b/Generals/Code/GameEngine/Include/GameClient/Mouse.h index a055538b23..6010c529af 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Mouse.h +++ b/Generals/Code/GameEngine/Include/GameClient/Mouse.h @@ -281,7 +281,7 @@ class Mouse : public SubsystemInterface void mouseNotifyResolutionChange(void); Bool isClick(const ICoord2D *anchor, const ICoord2D *dest, UnsignedInt previousMouseClick, UnsignedInt currentMouseClick); - + AsciiString m_tooltipFontName; ///< tooltip font Int m_tooltipFontSize; ///< tooltip font Bool m_tooltipFontIsBold; ///< tooltip font diff --git a/Generals/Code/GameEngine/Include/GameClient/Shadow.h b/Generals/Code/GameEngine/Include/GameClient/Shadow.h index 16761ff27a..f536de90db 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Shadow.h +++ b/Generals/Code/GameEngine/Include/GameClient/Shadow.h @@ -116,7 +116,7 @@ class Shadow }; - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void getRenderCost(RenderCost & rc) const = 0; #endif diff --git a/Generals/Code/GameEngine/Include/GameClient/View.h b/Generals/Code/GameEngine/Include/GameClient/View.h index 474bd879af..dbe6d9270a 100644 --- a/Generals/Code/GameEngine/Include/GameClient/View.h +++ b/Generals/Code/GameEngine/Include/GameClient/View.h @@ -83,6 +83,16 @@ class View : public Snapshot SHAKE_COUNT }; + // Return values for worldToScreenTriReturn + enum WorldToScreenReturn CPP_11(: Int) + { + WTS_INSIDE_FRUSTUM = 0, // On the screen (inside frustum of camera) + WTS_OUTSIDE_FRUSTUM, // Return is valid but off the screen (outside frustum of camera) + WTS_INVALID, // No transform possible + + WTS_COUNT + }; + public: View( void ); @@ -183,7 +193,8 @@ class View : public Snapshot virtual void setFieldOfView( Real angle ) { m_FOV = angle; } ///< Set the horizontal field of view angle virtual Real getFieldOfView( void ) { return m_FOV; } ///< Get the horizontal field of view angle - virtual Bool worldToScreen( const Coord3D *w, ICoord2D *s ) = 0; ///< Transform world coordinate "w" into screen coordinate "s" + Bool worldToScreen( const Coord3D *w, ICoord2D *s ) { return worldToScreenTriReturn( w, s ) == WTS_INSIDE_FRUSTUM; } ///< Transform world coordinate "w" into screen coordinate "s" + virtual WorldToScreenReturn worldToScreenTriReturn(const Coord3D *w, ICoord2D *s ) = 0; ///< Like worldToScreen(), but with a more informative return value virtual void screenToWorld( const ICoord2D *s, Coord3D *w ) = 0; ///< Transform screen coordinate "s" into world coordinate "w" virtual void screenToTerrain( const ICoord2D *screen, Coord3D *world ) = 0; ///< transform screen coord to a point on the 3D terrain virtual void screenToWorldAtZ( const ICoord2D *s, Coord3D *w, Real z ) = 0; ///< transform screen point to world point at the specified world Z value diff --git a/Generals/Code/GameEngine/Include/GameClient/Water.h b/Generals/Code/GameEngine/Include/GameClient/Water.h index f3428b8eaf..e9d0876674 100644 --- a/Generals/Code/GameEngine/Include/GameClient/Water.h +++ b/Generals/Code/GameEngine/Include/GameClient/Water.h @@ -81,6 +81,10 @@ class WaterTransparencySetting : public Overridable public: Real m_transparentWaterDepth; Real m_minWaterOpacity; + RGBColor m_standingWaterColor; + RGBColor m_radarColor; + Bool m_additiveBlend; + AsciiString m_standingWaterTexture; AsciiString m_skyboxTextureN; AsciiString m_skyboxTextureE; @@ -93,6 +97,15 @@ class WaterTransparencySetting : public Overridable { m_transparentWaterDepth = 3.0f; m_minWaterOpacity = 1.0f; + m_standingWaterColor.red = 1.0f; + m_standingWaterColor.green = 1.0f; + m_standingWaterColor.blue = 1.0f; + m_radarColor.red = 0.55f; + m_radarColor.green = 0.55f; + m_radarColor.blue = 1.0f; + m_standingWaterTexture = "TWWater01.tga"; + m_additiveBlend = FALSE; + m_skyboxTextureN = "TSMorningN.tga"; m_skyboxTextureE = "TSMorningE.tga"; m_skyboxTextureS = "TSMorningS.tga"; diff --git a/Generals/Code/GameEngine/Include/GameLogic/AI.h b/Generals/Code/GameEngine/Include/GameLogic/AI.h index 894f22b144..5814cad7a6 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AI.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AI.h @@ -892,7 +892,7 @@ class AIGroup : public MemoryPoolObject, public Snapshot void groupHackInternet( CommandSourceType cmdSource ); ///< Begin hacking the internet for free cash from the heavens. void groupDoSpecialPower( UnsignedInt specialPowerID, UnsignedInt commandOptions ); void groupDoSpecialPowerAtObject( UnsignedInt specialPowerID, Object *object, UnsignedInt commandOptions ); - void groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const Coord3D *location, const Object *object, UnsignedInt commandOptions ); + void groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const Coord3D *location, Real angle, const Object *object, UnsignedInt commandOptions ); #ifdef ALLOW_SURRENDER void groupSurrender( const Object *objWeSurrenderedTo, Bool surrender, CommandSourceType cmdSource ); #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/AIPathfind.h b/Generals/Code/GameEngine/Include/GameLogic/AIPathfind.h index b4e06b7360..4818f1aeec 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AIPathfind.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AIPathfind.h @@ -409,7 +409,7 @@ class PathfindLayer Bool connectsZones(PathfindZoneManager *zm, const LocomotorSet& locomotorSet,Int zone1, Int zone2); Bool isPointOnWall(ObjectID *wallPieces, Int numPieces, const Coord3D *pt); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void doDebugIcons(void) ; #endif protected: @@ -819,7 +819,7 @@ class Pathfinder : PathfindServicesInterface, public Snapshot void checkChangeLayers(PathfindCell *parentCell); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void doDebugIcons(void) ; #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h b/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h index 17fb5921d0..fe0bd377da 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h +++ b/Generals/Code/GameEngine/Include/GameLogic/ArmorSet.h @@ -84,7 +84,7 @@ class ArmorTemplateSet inline Int getConditionsYesCount() const { return 1; } inline const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h index 5c779f4f94..b01357434c 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h @@ -412,6 +412,8 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface Real getLocomotorDistanceToGoal(); const Locomotor *getCurLocomotor() const {return m_curLocomotor;} Locomotor *getCurLocomotor() { return m_curLocomotor; } + LocomotorSetType getCurLocomotorSetType() const { return m_curLocomotorSet; } + Bool hasLocomotorForSurface(LocomotorSurfaceType surfaceType); // turret stuff. WhichTurretType getWhichTurretForWeaponSlot(WeaponSlotType wslot, Real* turretAngle, Real* turretPitch = NULL) const; @@ -476,6 +478,7 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface void friend_endingMove(void); void friend_setPath(Path *newPath); + Path* friend_getPath() { return m_path; } void friend_setGoalObject(Object *obj); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/AutoDepositUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/AutoDepositUpdate.h index 976d891cac..f5c77dfe91 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/AutoDepositUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/AutoDepositUpdate.h @@ -61,6 +61,13 @@ //----------------------------------------------------------------------------- class Player; class Thing; +void parseUpgradePair( INI *ini, void *instance, void *store, const void *userData ); +struct upgradePair +{ + std::string type; + Int amount; +}; + //----------------------------------------------------------------------------- // TYPE DEFINES /////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/BaikonurLaunchPower.h b/Generals/Code/GameEngine/Include/GameLogic/Module/BaikonurLaunchPower.h index 180c8501c9..b6abc03f78 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/BaikonurLaunchPower.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/BaikonurLaunchPower.h @@ -80,7 +80,7 @@ class BaikonurLaunchPower : public SpecialPowerModule BaikonurLaunchPower( Thing *thing, const ModuleData *moduleData ); virtual void doSpecialPower( UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h index d84ca943a9..aeb4c63ff6 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/BattlePlanUpdate.h @@ -34,7 +34,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "Common/KindOf.h" -#include "GameLogic/Module/UpdateModule.h" +#include "GameLogic/Module/SpecialPowerUpdateModule.h" // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class SpecialPowerModule; @@ -137,12 +137,13 @@ class BattlePlanUpdate : public UpdateModule, public SpecialPowerUpdateInterface // virtual destructor prototype provided by memory pool declaration // SpecialPowerUpdateInterface - virtual void initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ); + virtual Bool initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ); virtual Bool isSpecialAbility() const { return false; } virtual Bool isSpecialPower() const { return true; } virtual Bool isActive() const {return m_status != TRANSITIONSTATUS_IDLE;} virtual SpecialPowerUpdateInterface* getSpecialPowerUpdateInterface() { return this; } - virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const { return false; } + virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const { return false; } //Is it active now? + virtual Bool doesSpecialPowerHaveOverridableDestination() const { return false; } //Does it have it, even if it's not active? virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) {} virtual Bool isPowerCurrentlyInUse( const CommandButton *command = NULL ) const; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h index 431786efe7..d75394f372 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/BehaviorModule.h @@ -79,6 +79,7 @@ class SpecialPowerTemplate; class WeaponTemplate; class DamageInfo; class ParticleSystemTemplate; +class StealthUpdate; //------------------------------------------------------------------------------------------------- @@ -163,6 +164,7 @@ class BehaviorModule : public ObjectModule, public BehaviorModuleInterface virtual SpecialPowerModuleInterface* getSpecialPower() { return NULL; } virtual UpdateModuleInterface* getUpdate() { return NULL; } virtual UpgradeModuleInterface* getUpgrade() { return NULL; } + virtual StealthUpdate* getStealth() { return NULL; } virtual ParkingPlaceBehaviorInterface* getParkingPlaceBehaviorInterface() { return NULL; } virtual RebuildHoleBehaviorInterface* getRebuildHoleBehaviorInterface() { return NULL; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/CashHackSpecialPower.h b/Generals/Code/GameEngine/Include/GameLogic/Module/CashHackSpecialPower.h index 4644c62b5e..b26b9b5820 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/CashHackSpecialPower.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/CashHackSpecialPower.h @@ -78,7 +78,7 @@ class CashHackSpecialPower : public SpecialPowerModule // virtual destructor provided by memory pool object virtual void doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/CleanupAreaPower.h b/Generals/Code/GameEngine/Include/GameLogic/Module/CleanupAreaPower.h index aa13b71753..ee6998a079 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/CleanupAreaPower.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/CleanupAreaPower.h @@ -73,7 +73,7 @@ class CleanupAreaPower : public SpecialPowerModule CleanupAreaPower( Thing *thing, const ModuleData* moduleData ); // virtual destructor prototype defined by MemoryPoolObject - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); }; #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/DefectorSpecialPower.h b/Generals/Code/GameEngine/Include/GameLogic/Module/DefectorSpecialPower.h index b0a855620d..71135babcb 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/DefectorSpecialPower.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/DefectorSpecialPower.h @@ -76,7 +76,7 @@ class DefectorSpecialPower : public SpecialPowerModule // virtual destructor prototype provided by memory pool object virtual void doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/DemoralizeSpecialPower.h b/Generals/Code/GameEngine/Include/GameLogic/Module/DemoralizeSpecialPower.h index 18f1b64fb8..eaec166a87 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/DemoralizeSpecialPower.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/DemoralizeSpecialPower.h @@ -75,7 +75,7 @@ class DemoralizeSpecialPower : public SpecialPowerModule // virtual destructor prototype provided by memory pool object virtual void doSpecialPowerAtObject( const Object *obj, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h b/Generals/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h index 86fe5737f1..ca876b9bed 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h @@ -116,7 +116,7 @@ class DumbProjectileBehavior : public UpdateModule, public ProjectileUpdateInter WeaponBonusConditionFlags m_extraBonusFlags; Bool calcFlightPath(Bool recalcNumSegments); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void displayFlightPath(); ///< Uses little debug icons in worldspace to show the path chosen when it is decided upon #endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponUpdate.h index 8839ffe235..dff6cc6a0a 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/FireWeaponUpdate.h @@ -65,6 +65,8 @@ class FireWeaponUpdate : public UpdateModule virtual UpdateSleepTime update(); protected: + + Bool isOkayToFire(); Weapon* m_weapon; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h index 6259f6b938..6fc04c6096 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/HackInternetAIUpdate.h @@ -197,10 +197,10 @@ class HackInternetAIUpdate : public AIUpdateInterface, public HackInternetAIInte virtual void aiDoCommand(const AICommandParms* parms); - UnsignedInt getUnpackTime() const { return getHackInternetAIUpdateModuleData()->m_unpackTime; } - UnsignedInt getPackTime() const { return getHackInternetAIUpdateModuleData()->m_packTime; } Real getPackUnpackVariationFactor() const { return getHackInternetAIUpdateModuleData()->m_packUnpackVariationFactor; } - UnsignedInt getCashUpdateDelay() const { return getHackInternetAIUpdateModuleData()->m_cashUpdateDelay; } + UnsignedInt getUnpackTime() const; + UnsignedInt getPackTime() const; + UnsignedInt getCashUpdateDelay() const; UnsignedInt getRegularCashAmount() const { return getHackInternetAIUpdateModuleData()->m_regularCashAmount; } UnsignedInt getVeteranCashAmount() const { return getHackInternetAIUpdateModuleData()->m_veteranCashAmount; } UnsignedInt getEliteCashAmount() const { return getHackInternetAIUpdateModuleData()->m_eliteCashAmount; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h index ee61d39eb4..05dd189442 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h @@ -35,7 +35,7 @@ #include "GameLogic/AIStateMachine.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/MissileLauncherBuildingUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/MissileLauncherBuildingUpdate.h index df91d66d1d..e78eb1b2a7 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/MissileLauncherBuildingUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/MissileLauncherBuildingUpdate.h @@ -35,7 +35,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "Common/AudioEventRTS.h" #include "Common/INI.h" -#include "GameLogic/Module/UpdateModule.h" +#include "GameLogic/Module/SpecialPowerUpdateModule.h" class DamageInfo; class SpecialPowerTemplate; class SpecialPowerModule; @@ -102,12 +102,13 @@ class MissileLauncherBuildingUpdate : public UpdateModule, public SpecialPowerUp // virtual destructor prototype provided by memory pool declaration //SpecialPowerUpdateInterface pure virtual implementations - virtual void initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ); + virtual Bool initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ); virtual Bool isSpecialAbility() const { return false; } virtual Bool isSpecialPower() const { return true; } virtual Bool isActive() const { return m_doorState != m_timeoutState; } SpecialPowerTemplate* getTemplate() const; - virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const { return false; } + virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const { return false; } //Is it active now? + virtual Bool doesSpecialPowerHaveOverridableDestination() const { return false; } //Does it have it, even if it's not active? virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) {} virtual SpecialPowerUpdateInterface* getSpecialPowerUpdateInterface() { return this; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/OCLSpecialPower.h b/Generals/Code/GameEngine/Include/GameLogic/Module/OCLSpecialPower.h index 16e3395935..ba2cc52b12 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/OCLSpecialPower.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/OCLSpecialPower.h @@ -90,7 +90,7 @@ class OCLSpecialPower : public SpecialPowerModule virtual void doSpecialPower( UnsignedInt commandOptions ); virtual void doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/ParticleUplinkCannonUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/ParticleUplinkCannonUpdate.h index b528e51c61..33a7200c25 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/ParticleUplinkCannonUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/ParticleUplinkCannonUpdate.h @@ -34,7 +34,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "Common/KindOf.h" -#include "GameLogic/Module/UpdateModule.h" +#include "GameLogic/Module/SpecialPowerUpdateModule.h" // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class SpecialPowerModule; @@ -156,7 +156,7 @@ class ParticleUplinkCannonUpdate : public UpdateModule, public SpecialPowerUpdat // virtual destructor prototype provided by memory pool declaration // SpecialPowerUpdateInterface - virtual void initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ); + virtual Bool initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ); virtual Bool isSpecialAbility() const { return false; } virtual Bool isSpecialPower() const { return true; } virtual Bool isActive() const {return m_status != STATUS_IDLE;} @@ -180,7 +180,8 @@ class ParticleUplinkCannonUpdate : public UpdateModule, public SpecialPowerUpdat Bool calculateDefaultInformation(); Bool calculateUpBonePositions(); - virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const; + virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const; //Is it active now? + virtual Bool doesSpecialPowerHaveOverridableDestination() const { return true; } //Does it have it, even if it's not active? virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ); // Disabled conditions to process (termination conditions!) diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbility.h b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbility.h index b4fb02cb6c..03eaff3d46 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbility.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbility.h @@ -59,7 +59,7 @@ class SpecialAbility : public SpecialPowerModule SpecialAbility( Thing *thing, const ModuleData *moduleData ); virtual void doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); virtual void doSpecialPower( UnsignedInt commandOptions ); protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h index 8e4eed83ac..f4a06f28b8 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialAbilityUpdate.h @@ -35,7 +35,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "Common/AudioEventRTS.h" #include "Common/INI.h" -#include "GameLogic/Module/UpdateModule.h" +#include "GameLogic/Module/SpecialPowerUpdateModule.h" #include "GameClient/ParticleSys.h" class DamageInfo; @@ -173,11 +173,12 @@ class SpecialAbilityUpdate : public UpdateModule, public SpecialPowerUpdateInter // virtual destructor prototype provided by memory pool declaration // SpecialPowerUpdateInterface - virtual void initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ); + virtual Bool initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ); virtual Bool isSpecialAbility() const { return true; } virtual Bool isSpecialPower() const { return false; } virtual Bool isActive() const { return m_active; } - virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const { return false; } + virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const { return false; } //Is it active now? + virtual Bool doesSpecialPowerHaveOverridableDestination() const { return false; } //Does it have it, even if it's not active? virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) {} virtual Bool isPowerCurrentlyInUse( const CommandButton *command = NULL ) const; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h index 52a1f34047..ce437dcb65 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h @@ -64,8 +64,8 @@ class SpecialPowerModuleInterface virtual void pauseCountdown( Bool pause ) = 0; virtual void doSpecialPower( UnsignedInt commandOptions ) = 0; virtual void doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions ) = 0; - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) = 0; - virtual void doSpecialPowerAtMultipleLocations( const Coord3D *locations, Int locCount, UnsignedInt commandOptions ) = 0; + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) = 0; + virtual void doSpecialPowerUsingWaypoints( const Waypoint *way, UnsignedInt commandOptions ) = 0; virtual void markSpecialPowerTriggered( const Coord3D *location ) = 0; virtual void startPowerRecharge() = 0; virtual const AudioEventRTS& getInitiateSound() const = 0; @@ -134,8 +134,8 @@ class SpecialPowerModule : public BehaviorModule, // virtual void doSpecialPower( UnsignedInt commandOptions ); virtual void doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ); - virtual void doSpecialPowerAtMultipleLocations( const Coord3D *locations, Int locCount, UnsignedInt commandOptions ); + virtual void doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ); + virtual void doSpecialPowerUsingWaypoints( const Waypoint *way, UnsignedInt commandOptions ); /** Now, there are special powers that require some preliminary processing before the actual @@ -157,10 +157,7 @@ class SpecialPowerModule : public BehaviorModule, protected: - void initiateIntentToDoSpecialPower( const Object *targetObj, - const Coord3D *targetPos, - UnsignedInt commandOptions, - Int locationCount = 0 ); + Bool initiateIntentToDoSpecialPower( const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ); void triggerSpecialPower( const Coord3D *location ); void createViewObject( const Coord3D *location ); void resolveSpecialPower( void ); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h new file mode 100644 index 0000000000..adc89c1f8a --- /dev/null +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerUpdateModule.h @@ -0,0 +1,53 @@ +/* +** Command & Conquer Generals(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: SpecialPowerUpdateModule.h ///////////////////////////////////////////////////////////////////////////////// +// Author: Kris Morness, July 2003 +// Desc: Originally lived in UpdateModule.h +/////////////////////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __SPECIAL_POWER_UPDATE_MODULE_H +#define __SPECIAL_POWER_UPDATE_MODULE_H + +#include "Common/Module.h" +#include "Common/GameType.h" + +//------------------------------------------------------------------------------------------------- +class SpecialPowerUpdateInterface +{ +public: + virtual Bool initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ) = 0; + virtual Bool isSpecialAbility() const = 0; + virtual Bool isSpecialPower() const = 0; + virtual Bool isActive() const = 0; + virtual CommandOption getCommandOption() const = 0; + virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const = 0; //Is it active now? + virtual Bool doesSpecialPowerHaveOverridableDestination() const = 0; //Does it have it, even if it's not active? + virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) = 0; + virtual Bool isPowerCurrentlyInUse( const CommandButton *command = NULL ) const = 0; +}; + +#endif diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h index 405f2fdab1..1ebc399137 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h @@ -123,6 +123,8 @@ class StealthUpdate : public UpdateModule StealthUpdate( Thing *thing, const ModuleData* moduleData ); // virtual destructor prototype provided by memory pool declaration + virtual StealthUpdate* getStealth() { return this; } + virtual UpdateSleepTime update(); //Still gets called, even if held -ML diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h index c95defbac4..05fbc91da5 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h @@ -63,6 +63,7 @@ class WeaponTemplate; class DamageInfo; class ParticleSystemTemplate; class CommandButton; +class Waypoint; enum CommandOption CPP_11(: Int); //------------------------------------------------------------------------------------------------- @@ -259,20 +260,6 @@ class SlavedUpdateInterface }; -//------------------------------------------------------------------------------------------------- -class SpecialPowerUpdateInterface -{ -public: - virtual void initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount = 0 ) = 0; - virtual Bool isSpecialAbility() const = 0; - virtual Bool isSpecialPower() const = 0; - virtual Bool isActive() const = 0; - virtual CommandOption getCommandOption() const = 0; - virtual Bool doesSpecialPowerHaveOverridableDestinationActive() const = 0; - virtual void setSpecialPowerOverridableDestination( const Coord3D *loc ) = 0; - virtual Bool isPowerCurrentlyInUse( const CommandButton *command = NULL ) const = 0; -}; - //------------------------------------------------------------------------------------------------- class ProjectileUpdateInterface { diff --git a/Generals/Code/GameEngine/Include/GameLogic/Object.h b/Generals/Code/GameEngine/Include/GameLogic/Object.h index 75bfa92a8a..062f927afc 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Object.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Object.h @@ -45,6 +45,7 @@ #include "GameLogic/WeaponBonusConditionFlags.h" #include "GameLogic/WeaponSet.h" #include "GameLogic/WeaponSetFlags.h" +#include "GameLogic/Module/StealthUpdate.h" //----------------------------------------------------------------------------- // Forward References @@ -271,6 +272,7 @@ class Object : public Thing, public Snapshot BodyModuleInterface* getBodyModule() const { return m_body; } ContainModuleInterface* getContain() const { return m_contain; } + StealthUpdate* getStealth() const { return m_stealth; } SpawnBehaviorInterface* getSpawnBehaviorInterface() const; @@ -304,9 +306,11 @@ class Object : public Thing, public Snapshot // Ditto for special powers -- Kris SpecialPowerModuleInterface* findSpecialPowerModuleInterface( SpecialPowerType type ) const; + SpecialPowerModuleInterface* findAnyShortcutSpecialPowerModuleInterface() const; SpecialAbilityUpdate* findSpecialAbilityUpdate( SpecialPowerType type ) const; SpecialPowerCompletionDie* findSpecialPowerCompletionDie() const; SpecialPowerUpdateInterface* findSpecialPowerWithOverridableDestinationActive( SpecialPowerType type = SPECIAL_INVALID ) const; + SpecialPowerUpdateInterface* findSpecialPowerWithOverridableDestination( SpecialPowerType type = SPECIAL_INVALID ) const; inline ObjectStatusMaskType getStatusBits() const { return m_status; } inline Bool testStatus( ObjectStatusTypes bit ) const { return m_status.test( bit ); } @@ -423,9 +427,9 @@ class Object : public Thing, public Snapshot SpecialPowerModuleInterface *getSpecialPowerModule( const SpecialPowerTemplate *specialPowerTemplate ) const; void doSpecialPower( const SpecialPowerTemplate *specialPowerTemplate, UnsignedInt commandOptions, Bool forced = false ); ///< execute power void doSpecialPowerAtObject( const SpecialPowerTemplate *specialPowerTemplate, Object *obj, UnsignedInt commandOptions, Bool forced = false ); ///< execute power - void doSpecialPowerAtLocation( const SpecialPowerTemplate *specialPowerTemplate, const Coord3D *loc, UnsignedInt commandOptions, Bool forced = false ); ///< execute power - void doSpecialPowerAtMultipleLocations( const SpecialPowerTemplate *specialPowerTemplate, - const Coord3D *locations, Int locCount, UnsignedInt commandOptions, Bool forced = false ); ///< execute power + void doSpecialPowerAtLocation( const SpecialPowerTemplate *specialPowerTemplate, const Coord3D *loc, Real angle, UnsignedInt commandOptions, Bool forced = false ); ///< execute power + void doSpecialPowerUsingWaypoints( const SpecialPowerTemplate *specialPowerTemplate, const Waypoint *way, UnsignedInt commandOptions, Bool forced = false ); ///< execute power + void doCommandButton( const CommandButton *commandButton, CommandSourceType cmdSource ); void doCommandButtonAtObject( const CommandButton *commandButton, Object *obj, CommandSourceType cmdSource ); void doCommandButtonAtPosition( const CommandButton *commandButton, const Coord3D *pos, CommandSourceType cmdSource ); @@ -691,6 +695,7 @@ class Object : public Thing, public Snapshot // cache these, for convenience ContainModuleInterface* m_contain; BodyModuleInterface* m_body; + StealthUpdate* m_stealth; AIUpdateInterface* m_ai; ///< ai interface (if any), cached for handy access. (duplicate of entry in the module array!) PhysicsBehavior* m_physics; ///< physics interface (if any), cached for handy access. (duplicate of entry in the module array!) @@ -749,7 +754,7 @@ class Object : public Thing, public Snapshot // --------- BYTE-SIZED THINGS GO HERE Bool m_isSelectable; Bool m_modulesReady; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_hasDiedAlready; #endif UnsignedByte m_scriptStatus; ///< status as set by scripting, corresponds to ORed ObjectScriptStatusBits @@ -760,12 +765,10 @@ class Object : public Thing, public Snapshot }; // end class Object -#ifdef DEBUG_LOGGING // describe an object as an AsciiString: e.g. "Object 102 (KillerBuggy) [GLARocketBuggy, owned by player 2 (GLAIntroPlayer)]" -AsciiString DescribeObject(const Object *obj); -#endif // DEBUG_LOGGING +AsciiString DebugDescribeObject(const Object *obj); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define DEBUG_OBJECT_ID_EXISTS #else #undef DEBUG_OBJECT_ID_EXISTS diff --git a/Generals/Code/GameEngine/Include/GameLogic/ObjectCreationList.h b/Generals/Code/GameEngine/Include/GameLogic/ObjectCreationList.h index 40abaa9b8b..a64c6c5226 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/ObjectCreationList.h +++ b/Generals/Code/GameEngine/Include/GameLogic/ObjectCreationList.h @@ -27,6 +27,9 @@ // Desc: General Effects Descriptions /////////////////////////////////////////////////////////////////////////////////////////////////// +// Kris: August 23, 2003 +// All OCLs return the first object that is created (or NULL if not applicable). + #pragma once #ifndef _ObjectCreationList_H_ @@ -81,19 +84,19 @@ class ObjectCreationNugget : public MemoryPoolObject needed. Note that primary can be null, so you must check for this. Bool useOwner determines whether we are creating the the master object or not (for deliverpayload) */ - virtual void create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const = 0; + virtual Object* create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const = 0; /** the object-based version... by default, just call the location-based implementation. Note that primary can be null, so you must check for this. */ - virtual void create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const; + virtual Object* create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const; /** A variation used by DeliverPayload -- the createOwner Bool specifies whether we are creating the transport object, or using the existing one. */ - virtual void create( const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) const; + virtual Object* create( const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) const; }; EMPTY_DTOR(ObjectCreationNugget) @@ -132,30 +135,44 @@ class ObjectCreationList void addObjectCreationNugget(ObjectCreationNugget* nugget); - inline static void create( const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) + // Kris: August 23, 2003 + // All OCLs return the first object that is created (or NULL if not applicable). + inline static Object* create( const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) { - if (ocl) ocl->create( primaryObj, primary, secondary, createOwner, lifetimeFrames ); + if( ocl ) + return ocl->createInternal( primaryObj, primary, secondary, createOwner, lifetimeFrames ); + return NULL; } + // Kris: August 23, 2003 + // All OCLs return the first object that is created (or NULL if not applicable). /// inline convenience method to avoid having to check for null. - inline static void create(const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) + inline static Object* create(const ObjectCreationList* ocl, const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) { - if (ocl) ocl->create( primaryObj, primary, secondary, lifetimeFrames ); + if (ocl) + return ocl->createInternal( primaryObj, primary, secondary, lifetimeFrames ); + return NULL; } + // Kris: August 23, 2003 + // All OCLs return the first object that is created (or NULL if not applicable). /// inline convenience method to avoid having to check for null. - inline static void create( const ObjectCreationList* ocl, const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) + inline static Object* create( const ObjectCreationList* ocl, const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) { - if (ocl) ocl->create( primary, secondary, lifetimeFrames ); + if (ocl) + return ocl->createInternal( primary, secondary, lifetimeFrames ); + return NULL; } protected: private: - void create(const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) const; - void create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const; - void create(const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const; + // Kris: August 23, 2003 + // All OCLs return the first object that is created (or NULL if not applicable). + Object* createInternal(const Object* primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) const; + Object* createInternal(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const; + Object* createInternal(const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const; // note, this list doesn't own the nuggets; all nuggets are owned by the Store. typedef std::vector ObjectCreationNuggetVector; diff --git a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h index 8296ddb069..9591422810 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/Generals/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -353,7 +353,7 @@ class PartitionCell : public Snapshot // not MPO: allocated in an array inline CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; } - #ifdef _DEBUG + #ifdef RTS_DEBUG void validateCoiList(); #endif @@ -595,7 +595,7 @@ class PartitionFilter { public: virtual Bool allow(Object *objOther) = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() = 0; #endif }; @@ -609,7 +609,7 @@ class PartitionFilterIsFlying : public PartitionFilter public: PartitionFilterIsFlying() { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterIsFlying"; } #endif }; @@ -625,7 +625,7 @@ class PartitionFilterWouldCollide : public PartitionFilter public: PartitionFilterWouldCollide(const Coord3D& pos, const GeometryInfo& geom, Real angle, Bool desired); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterWouldCollide"; } #endif }; @@ -641,7 +641,7 @@ class PartitionFilterSamePlayer : public PartitionFilter public: PartitionFilterSamePlayer(const Player *player) : m_player(player) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterSamePlayer"; } #endif }; @@ -667,7 +667,7 @@ class PartitionFilterRelationship : public PartitionFilter }; PartitionFilterRelationship(const Object *obj, Int flags) : m_obj(obj), m_flags(flags) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRelationship"; } #endif }; @@ -684,7 +684,7 @@ class PartitionFilterAcceptOnTeam : public PartitionFilter public: PartitionFilterAcceptOnTeam(const Team *team); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptOnTeam"; } #endif }; @@ -701,7 +701,7 @@ class PartitionFilterAcceptOnSquad : public PartitionFilter public: PartitionFilterAcceptOnSquad(const Squad *squad); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptOnSquad"; } #endif }; @@ -724,7 +724,7 @@ class PartitionFilterLineOfSight : public PartitionFilter public: PartitionFilterLineOfSight(const Object *obj); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLineOfSight"; } #endif }; @@ -742,7 +742,7 @@ class PartitionFilterPossibleToAttack : public PartitionFilter public: PartitionFilterPossibleToAttack(AbleToAttackType t, const Object *obj, CommandSourceType commandSource); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPossibleToAttack"; } #endif }; @@ -758,7 +758,7 @@ class PartitionFilterLastAttackedBy : public PartitionFilter public: PartitionFilterLastAttackedBy(Object *obj); virtual Bool allow(Object *other); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLastAttackedBy"; } #endif }; @@ -774,7 +774,7 @@ class PartitionFilterAcceptByObjectStatus : public PartitionFilter public: PartitionFilterAcceptByObjectStatus(ObjectStatusMaskType mustBeSet, ObjectStatusMaskType mustBeClear) : m_mustBeSet(mustBeSet), m_mustBeClear(mustBeClear) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptByObjectStatus"; } #endif }; @@ -794,7 +794,7 @@ class PartitionFilterRejectByObjectStatus : public PartitionFilter { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectByObjectStatus"; } #endif }; @@ -811,7 +811,7 @@ class PartitionFilterStealthedAndUndetected : public PartitionFilter public: PartitionFilterStealthedAndUndetected( const Object *obj, Bool allow ) { m_obj = obj; m_allow = allow; } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterStealthedAndUndetected"; } #endif }; @@ -827,7 +827,7 @@ class PartitionFilterAcceptByKindOf : public PartitionFilter public: PartitionFilterAcceptByKindOf(const KindOfMaskType& mustBeSet, const KindOfMaskType& mustBeClear) : m_mustBeSet(mustBeSet), m_mustBeClear(mustBeClear) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptByKindOf"; } #endif }; @@ -847,7 +847,7 @@ class PartitionFilterRejectByKindOf : public PartitionFilter { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectByKindOf"; } #endif }; @@ -864,7 +864,7 @@ class PartitionFilterRejectBehind: public PartitionFilter public: PartitionFilterRejectBehind( Object *obj ); virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectBehind"; } #endif }; @@ -879,7 +879,7 @@ class PartitionFilterAlive : public PartitionFilter PartitionFilterAlive(void) { } protected: virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAlive"; } #endif }; @@ -897,7 +897,7 @@ class PartitionFilterSameMapStatus : public PartitionFilter PartitionFilterSameMapStatus(const Object *obj) : m_obj(obj) { } protected: virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterSameMapStatus"; } #endif }; @@ -912,7 +912,7 @@ class PartitionFilterOnMap : public PartitionFilter PartitionFilterOnMap() { } protected: virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterOnMap"; } #endif }; @@ -932,7 +932,7 @@ class PartitionFilterRejectBuildings : public PartitionFilter PartitionFilterRejectBuildings(const Object *o); protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectBuildings"; } #endif }; @@ -952,7 +952,7 @@ class PartitionFilterInsignificantBuildings : public PartitionFilter m_allowNonBuildings(allowNonBuildings), m_allowInsignificant(allowInsignificant) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterInsignificantBuildings"; } #endif }; @@ -970,7 +970,7 @@ class PartitionFilterFreeOfFog : public PartitionFilter m_comparisonIndex(toWhom){} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterFreeOfFog"; } #endif }; @@ -987,7 +987,7 @@ class PartitionFilterRepulsor : public PartitionFilter PartitionFilterRepulsor(const Object *o) : m_self(o) { } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRepulsor"; } #endif }; @@ -1008,7 +1008,7 @@ class PartitionFilterIrregularArea : public PartitionFilter PartitionFilterIrregularArea(Coord3D* area, Int numPointsInArea) : m_area(area), m_numPointsInArea(numPointsInArea) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterIrregularArea"; } #endif }; @@ -1028,7 +1028,7 @@ class PartitionFilterPolygonTrigger : public PartitionFilter PartitionFilterPolygonTrigger(const PolygonTrigger *trigger) : m_trigger(trigger) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPolygonTrigger"; } #endif }; @@ -1048,7 +1048,7 @@ class PartitionFilterPlayer : public PartitionFilter PartitionFilterPlayer(const Player *player, Bool match) : m_player(player), m_match(match) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPlayer"; } #endif }; @@ -1073,7 +1073,7 @@ class PartitionFilterPlayerAffiliation : public PartitionFilter } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPlayerAffiliation"; } #endif }; @@ -1093,7 +1093,7 @@ class PartitionFilterThing : public PartitionFilter PartitionFilterThing(const ThingTemplate *thing, Bool match) : m_tThing(thing), m_match(match) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterThing"; } #endif }; @@ -1118,7 +1118,7 @@ class PartitionFilterGarrisonable : public PartitionFilter } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterGarrisonable"; } #endif }; @@ -1141,7 +1141,7 @@ class PartitionFilterGarrisonableByPlayer : public PartitionFilter } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterGarrisonableByPlayer"; } #endif }; @@ -1159,7 +1159,7 @@ class PartitionFilterUnmannedObject : public PartitionFilter PartitionFilterUnmannedObject( Bool match ) : m_match(match) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterUnmannedObject"; } #endif }; @@ -1181,7 +1181,7 @@ class PartitionFilterValidCommandButtonTarget : public PartitionFilter m_source(source), m_commandButton(commandButton), m_match(match), m_commandSource(commandSource) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterValidCommandButtonTarget"; } #endif }; diff --git a/Generals/Code/GameEngine/Include/GameLogic/RankInfo.h b/Generals/Code/GameEngine/Include/GameLogic/RankInfo.h index 5dc67b87d2..44aaf8d8e9 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/RankInfo.h +++ b/Generals/Code/GameEngine/Include/GameLogic/RankInfo.h @@ -49,11 +49,13 @@ class RankInfo : public Overridable Int m_sciencePurchasePointsGranted; ScienceVec m_sciencesGranted; }; -EMPTY_DTOR(RankInfo) +//EMPTY_DTOR(RankInfo) //------------------------------------------------------------------------------------------------- class RankInfoStore : public SubsystemInterface { +public: + virtual ~RankInfoStore(); public: void init(); diff --git a/Generals/Code/GameEngine/Include/GameLogic/ScriptEngine.h b/Generals/Code/GameEngine/Include/GameLogic/ScriptEngine.h index 15339841fc..af7ed44b27 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/ScriptEngine.h +++ b/Generals/Code/GameEngine/Include/GameLogic/ScriptEngine.h @@ -50,7 +50,7 @@ class Player; class PolygonTrigger; class ObjectTypes; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL #define SPECIAL_SCRIPT_PROFILING #endif @@ -136,7 +136,7 @@ class AttackPriorityInfo : public Snapshot void setPriority(const ThingTemplate *tThing, Int priority); Int getPriority(const ThingTemplate *tThing) const; AsciiString getName(void) const {return m_name;} -#ifdef _DEBUG +#ifdef RTS_DEBUG void dumpPriorityInfo(void); #endif @@ -352,7 +352,7 @@ class ScriptEngine : public SubsystemInterface, void setEnableVTune(Bool value); Bool getEnableVTune() const; ///End VTUNE -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void debugVictory( void ); //#endif protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h index f00eab68a4..8ab67fb6cb 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h +++ b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h @@ -138,7 +138,7 @@ class WeaponTemplateSet inline Int getConditionsYesCount() const { return 1; } inline const WeaponSetFlags& getNthConditionsYes(Int i) const { return m_types; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } #endif }; diff --git a/Generals/Code/GameEngine/Include/GameNetwork/Connection.h b/Generals/Code/GameEngine/Include/GameNetwork/Connection.h index be1348ecf3..3a0178510f 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/Connection.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/Connection.h @@ -79,7 +79,7 @@ class Connection : public MemoryPoolObject void setQuitting( void ); Bool isQuitting( void ) { return m_isQuitting; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void debugPrintCommands(); #endif diff --git a/Generals/Code/GameEngine/Include/GameNetwork/ConnectionManager.h b/Generals/Code/GameEngine/Include/GameNetwork/ConnectionManager.h index a376e926c7..81b99037a9 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/ConnectionManager.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/ConnectionManager.h @@ -140,7 +140,7 @@ class ConnectionManager Int getAverageFPS( void ); Int getSlotAverageFPS(Int slot); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void debugPrintConnectionCommands(); #endif diff --git a/Generals/Code/GameEngine/Include/GameNetwork/NetCommandRef.h b/Generals/Code/GameEngine/Include/GameNetwork/NetCommandRef.h index 18ce11519f..79d1ad12fb 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/NetCommandRef.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/NetCommandRef.h @@ -31,7 +31,7 @@ #include "GameNetwork/NetCommandMsg.h" #include "Common/GameMemory.h" -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) // #define DEBUG_NETCOMMANDREF #endif diff --git a/Generals/Code/GameEngine/Include/GameNetwork/NetworkDefs.h b/Generals/Code/GameEngine/Include/GameNetwork/NetworkDefs.h index df8707bc60..9ad0803cc3 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/NetworkDefs.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/NetworkDefs.h @@ -99,7 +99,7 @@ struct TransportMessage }; #pragma pack(pop) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #pragma pack(push, 1) struct DelayedTransportMessage { diff --git a/Generals/Code/GameEngine/Include/GameNetwork/NetworkInterface.h b/Generals/Code/GameEngine/Include/GameNetwork/NetworkInterface.h index a728d18823..2dc06db8d1 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/NetworkInterface.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/NetworkInterface.h @@ -120,7 +120,7 @@ class NetworkInterface : public SubsystemInterface virtual Int getExecutionFrame() = 0; ///< Returns the next valid frame for simultaneous command execution. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void toggleNetworkOn( void ) = 0; ///< toggle whether or not to send network traffic. #endif diff --git a/Generals/Code/GameEngine/Include/GameNetwork/Transport.h b/Generals/Code/GameEngine/Include/GameNetwork/Transport.h index 8737f9a01d..0408129adf 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/Transport.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/Transport.h @@ -76,7 +76,7 @@ class Transport //: public MemoryPoolObject TransportMessage m_outBuffer[MAX_MESSAGES]; TransportMessage m_inBuffer[MAX_MESSAGES]; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DelayedTransportMessage m_delayedInBuffer[MAX_MESSAGES]; #endif diff --git a/Generals/Code/GameEngine/Include/GameNetwork/networkutil.h b/Generals/Code/GameEngine/Include/GameNetwork/networkutil.h index 760a6f640a..9272705623 100644 --- a/Generals/Code/GameEngine/Include/GameNetwork/networkutil.h +++ b/Generals/Code/GameEngine/Include/GameNetwork/networkutil.h @@ -39,7 +39,9 @@ Bool IsCommandSynchronized(NetCommandType type); AsciiString GetAsciiNetCommandType(NetCommandType type); #ifdef DEBUG_LOGGING +extern "C" { void dumpBufferToLog(const void *vBuf, Int len, const char *fname, Int line); +}; #define LOGBUFFER(buf, len) dumpBufferToLog(buf, len, __FILE__, __LINE__) #else #define LOGBUFFER(buf, len) {} diff --git a/Generals/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp b/Generals/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp index d6043a43a5..a5f5f9b6ab 100644 --- a/Generals/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp +++ b/Generals/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp @@ -57,7 +57,7 @@ #include "GameClient/Drawable.h" // For getPosition #include "GameClient/GameClient.h" // For getDrawableByID -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/Generals/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/Generals/Code/GameEngine/Source/Common/Audio/GameAudio.cpp index e6102e5753..9a196bcee5 100644 --- a/Generals/Code/GameEngine/Source/Common/Audio/GameAudio.cpp +++ b/Generals/Code/GameEngine/Source/Common/Audio/GameAudio.cpp @@ -71,7 +71,7 @@ #include "WWMath/matrix3d.h" /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif @@ -248,7 +248,7 @@ void AudioManager::init() break; } // We loop infinitely on the splash screen if we don't allow breaking out of this loop. -//#if !defined( _DEBUG ) && !defined( _INTERNAL ) +//#if !defined( RTS_DEBUG ) && !defined( RTS_INTERNAL ) else { // Display the warning. @@ -390,6 +390,7 @@ void AudioManager::update() m_zoomVolume = 1.0f - scalar * maxBoostScalar; } } + set3DVolumeAdjustment( m_zoomVolume ); } @@ -780,8 +781,8 @@ void AudioManager::set3DVolumeAdjustment( Real volumeAdjustment ) if (m_sound3DVolume > 1.0f) m_sound3DVolume = 1.0f; - - m_volumeHasChanged = TRUE; + if ( ! has3DSensitiveStreamsPlaying() ) + m_volumeHasChanged = TRUE; } //------------------------------------------------------------------------------------------------- @@ -820,6 +821,18 @@ void AudioManager::appendAudioRequest( AudioRequest *m_request ) m_audioRequests.push_back(m_request); } +//------------------------------------------------------------------------------------------------- +// Remove all pending audio requests +void AudioManager::removeAllAudioRequests( void ) +{ + std::list::iterator it; + for ( it = m_audioRequests.begin(); it != m_audioRequests.end(); it++ ) { + releaseAudioRequest( *it ); + } + + m_audioRequests.clear(); +} + //------------------------------------------------------------------------------------------------- void AudioManager::processRequestList( void ) { @@ -839,6 +852,23 @@ AudioEventInfo *AudioManager::newAudioEventInfo( AsciiString audioName ) return m_allAudioEventInfo[audioName]; } +//------------------------------------------------------------------------------------------------- +// Add an AudioEventInfo structure allocated elsewhere to the audio event list +void AudioManager::addAudioEventInfo( AudioEventInfo * newEvent ) +{ + // Warning: Don't try to copy the structure. It may be a derived class + AudioEventInfo *eventInfo = findAudioEventInfo( newEvent->m_audioName ); + if (eventInfo) + { + DEBUG_CRASH(("Requested add of '%s' multiple times. Is this intentional? - jkmcd\n", newEvent->m_audioName.str())); + *eventInfo = *newEvent; + } + else + { + m_allAudioEventInfo[newEvent->m_audioName] = newEvent; + } +} + //------------------------------------------------------------------------------------------------- AudioEventInfo *AudioManager::findAudioEventInfo( AsciiString eventName ) const { @@ -851,6 +881,28 @@ AudioEventInfo *AudioManager::findAudioEventInfo( AsciiString eventName ) const return (*it).second; } +//------------------------------------------------------------------------------------------------- +// Remove all AudioEventInfo's with the m_isLevelSpecific flag +void AudioManager::removeLevelSpecificAudioEventInfos(void) +{ + AudioEventInfoHash::iterator it = m_allAudioEventInfo.begin(); + + while ( it != m_allAudioEventInfo.end() ) + { + AudioEventInfoHash::iterator next = it; // Make sure erase doesn't cause problems + next++; + + if ( it->second->isLevelSpecific() ) + { + it->second->deleteInstance(); + m_allAudioEventInfo.erase( it ); + } + + it = next; + } + +} + //------------------------------------------------------------------------------------------------- const AudioSettings *AudioManager::getAudioSettings( void ) const { diff --git a/Generals/Code/GameEngine/Source/Common/Audio/GameMusic.cpp b/Generals/Code/GameEngine/Source/Common/Audio/GameMusic.cpp index 28159bff6d..d9adae2520 100644 --- a/Generals/Code/GameEngine/Source/Common/Audio/GameMusic.cpp +++ b/Generals/Code/GameEngine/Source/Common/Audio/GameMusic.cpp @@ -52,6 +52,11 @@ #include "Common/GameAudio.h" #include "Common/INI.h" +#ifdef RTS_INTERNAL +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + //---------------------------------------------------------------------------- // Externals //---------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/Common/Audio/GameSounds.cpp b/Generals/Code/GameEngine/Source/Common/Audio/GameSounds.cpp index ed36f7fdde..6a0f0b93f5 100644 --- a/Generals/Code/GameEngine/Source/Common/Audio/GameSounds.cpp +++ b/Generals/Code/GameEngine/Source/Common/Audio/GameSounds.cpp @@ -56,7 +56,7 @@ #include "GameLogic/PartitionManager.h" /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/Generals/Code/GameEngine/Source/Common/CRCDebug.cpp b/Generals/Code/GameEngine/Source/Common/CRCDebug.cpp index 2907bf16a8..97d87f5044 100644 --- a/Generals/Code/GameEngine/Source/Common/CRCDebug.cpp +++ b/Generals/Code/GameEngine/Source/Common/CRCDebug.cpp @@ -28,11 +28,12 @@ #include "Common/CRCDebug.h" #include "Common/Debug.h" #include "Common/PerfTimer.h" +#include "Common/LocalFileSystem.h" #include "GameClient/InGameUI.h" #include "GameNetwork/IPEnumeration.h" #include -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -41,11 +42,12 @@ #ifdef DEBUG_CRC static const Int MaxStrings = 64000; +static const Int MaxStringLen = 1024; -static char DebugStrings[MaxStrings][1024]; +static char DebugStrings[MaxStrings][MaxStringLen]; static Int nextDebugString = 0; static Int numDebugStrings = 0; -//static char DumpStrings[MaxStrings][1024]; +//static char DumpStrings[MaxStrings][MaxStringLen]; //static Int nextDumpString = 0; //static Int numDumpStrings = 0; @@ -91,12 +93,8 @@ CRCVerification::~CRCVerification() #endif } -static Bool dumped = FALSE; void outputCRCDebugLines( void ) { - if (dumped) - return; - dumped = TRUE; IPEnumeration ips; AsciiString fname; fname.format("crcDebug%s.txt", ips.getMachineName().str()); @@ -116,6 +114,62 @@ void outputCRCDebugLines( void ) if (fp) fclose(fp); } +Int lastCRCDebugFrame = 0; +Int lastCRCDebugIndex = 0; +extern Bool inCRCGen; + +void CRCDebugStartNewGame() +{ + if (TheGameLogic->isInShellGame()) + return; + if (g_saveDebugCRCPerFrame) + { + // Create folder for frame data, if it doesn't exist yet. + CreateDirectory(g_saveDebugCRCPerFrameDir.str(), NULL); + + // Delete existing files + FilenameList files; + AsciiString dir = g_saveDebugCRCPerFrameDir; + dir.concat("/"); + TheLocalFileSystem->getFileListInDirectory(dir.str(), "", "DebugFrame_*.txt", files, FALSE); + FilenameList::iterator it; + for (it = files.begin(); it != files.end(); ++it) + { + DeleteFile(it->str()); + } + } + nextDebugString = 0; + numDebugStrings = 0; + lastCRCDebugFrame = 0; + lastCRCDebugIndex = 0; +} + +static void outputCRCDebugLinesPerFrame() +{ + if (!g_saveDebugCRCPerFrame || numDebugStrings == 0) + return; + AsciiString fname; + fname.format("%s/DebugFrame_%06d.txt", g_saveDebugCRCPerFrameDir.str(), lastCRCDebugFrame); + FILE *fp = fopen(fname.str(), "wt"); + int start = 0; + int end = nextDebugString; + if (numDebugStrings >= MaxStrings) + start = nextDebugString - MaxStrings; + nextDebugString = 0; + numDebugStrings = 0; + if (!fp) + return; + + for (Int i=start; iisInGameLogicUpdate()*/) + if (TheGameLogic == NULL || !(IS_FRAME_OK_TO_LOG)) return; - if (IS_FRAME_OK_TO_LOG) + if (lastCRCDebugFrame != TheGameLogic->getFrame()) { + outputCRCDebugLinesPerFrame(); + lastCRCDebugFrame = TheGameLogic->getFrame(); + lastCRCDebugIndex = 0; + } - if (lastCRCDebugFrame != TheGameLogic->getFrame()) - { - lastCRCDebugFrame = TheGameLogic->getFrame(); - lastCRCDebugIndex = 0; - } - - sprintf(DebugStrings[nextDebugString], "%d:%d ", TheGameLogic->getFrame(), lastCRCDebugIndex++); - //DebugStrings[nextDebugString][0] = 0; - Int len = strlen(DebugStrings[nextDebugString]); + if (count) + sprintf(DebugStrings[nextDebugString], "%d:%05d ", TheGameLogic->getFrame(), lastCRCDebugIndex++); + else + DebugStrings[nextDebugString][0] = 0; + Int len = strlen(DebugStrings[nextDebugString]); - va_list va; - va_start( va, fmt ); - _vsnprintf(DebugStrings[nextDebugString]+len, 1024-len, fmt, va ); - DebugStrings[nextDebugString][1023] = 0; - va_end( va ); + _vsnprintf(DebugStrings[nextDebugString]+len, MaxStringLen-len, fmt, args); + DebugStrings[nextDebugString][MaxStringLen-1] = 0; - char *tmp = DebugStrings[nextDebugString]; - while (tmp && *tmp) + char *tmp = DebugStrings[nextDebugString]; + while (tmp && *tmp) + { + if (*tmp == '\r' || *tmp == '\n') { - if (*tmp == '\r' || *tmp == '\n') - { - *tmp = ' '; - } - ++tmp; + *tmp = ' '; } + ++tmp; + } + + //DEBUG_LOG(("%s\n", DebugStrings[nextDebugString])); - //DEBUG_LOG(("%s\n", DebugStrings[nextDebugString])); + ++nextDebugString; + ++numDebugStrings; + if (nextDebugString == MaxStrings) + nextDebugString = 0; +} - ++nextDebugString; - ++numDebugStrings; - if (nextDebugString == MaxStrings) - nextDebugString = 0; +void addCRCDebugLine(const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + addCRCDebugLineInternal(true, fmt, args); + va_end(args); +} - } +void addCRCDebugLineNoCounter(const char *fmt, ...) +{ + // TheSuperHackers @feature helmutbuhler 04/09/2025 + // This version doesn't increase the lastCRCDebugIndex counter + // and can be used for logging lines that don't necessarily match up on all peers. + // (Otherwise the numbers would no longer match up and the diff would be very difficult to read) + va_list args; + va_start(args, fmt); + addCRCDebugLineInternal(false, fmt, args); + va_end(args); } void addCRCGenLine(const char *fmt, ...) { - if (dumped || !(IS_FRAME_OK_TO_LOG)) + if (!(IS_FRAME_OK_TO_LOG)) return; - static char buf[1024]; + static char buf[MaxStringLen]; va_list va; va_start( va, fmt ); - _vsnprintf(buf, 1024, fmt, va ); + _vsnprintf(buf, MaxStringLen, fmt, va ); va_end( va ); - buf[1023] = 0; + buf[MaxStringLen-1] = 0; addCRCDebugLine("%s", buf); //DEBUG_LOG(("%s", buf)); @@ -205,8 +271,8 @@ void addCRCDumpLine(const char *fmt, ...) /* va_list va; va_start( va, fmt ); - _vsnprintf(DumpStrings[nextDumpString], 1024, fmt, va ); - DumpStrings[nextDumpString][1023] = 0; + _vsnprintf(DumpStrings[nextDumpString], MaxStringLen, fmt, va ); + DumpStrings[nextDumpString][MaxStringLen-1] = 0; va_end( va ); ++nextDumpString; @@ -218,9 +284,6 @@ void addCRCDumpLine(const char *fmt, ...) void dumpVector3(const Vector3 *v, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); @@ -231,9 +294,6 @@ void dumpVector3(const Vector3 *v, AsciiString name, AsciiString fname, Int line void dumpCoord3D(const Coord3D *c, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); @@ -244,9 +304,6 @@ void dumpCoord3D(const Coord3D *c, AsciiString name, AsciiString fname, Int line void dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); @@ -260,9 +317,6 @@ void dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int li void dumpReal(Real r, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); diff --git a/Generals/Code/GameEngine/Source/Common/CommandLine.cpp b/Generals/Code/GameEngine/Source/Common/CommandLine.cpp index 791bf9a9e1..e687854dcd 100644 --- a/Generals/Code/GameEngine/Source/Common/CommandLine.cpp +++ b/Generals/Code/GameEngine/Source/Common/CommandLine.cpp @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals(tm) +** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify @@ -34,6 +34,14 @@ #include "GameClient/GameText.h" #include "GameNetwork/NetworkDefs.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + + Bool TheDebugIgnoreSyncErrors = FALSE; extern Int DX8Wrapper_PreserveFPU; @@ -41,6 +49,8 @@ extern Int DX8Wrapper_PreserveFPU; Int TheCRCFirstFrameToLog = -1; UnsignedInt TheCRCLastFrameToLog = 0xffffffff; Bool g_keepCRCSaves = FALSE; +Bool g_saveDebugCRCPerFrame = FALSE; +AsciiString g_saveDebugCRCPerFrameDir; Bool g_crcModuleDataFromLogic = FALSE; Bool g_crcModuleDataFromClient = FALSE; Bool g_verifyClientCRC = FALSE; // verify that GameLogic CRC doesn't change from client @@ -48,7 +58,7 @@ Bool g_clientDeepCRC = FALSE; Bool g_logObjectCRCs = FALSE; #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern Bool g_useStringFile; #endif @@ -153,7 +163,8 @@ Int parseFPUPreserve(char *args[], int argc) return 2; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + //============================================================================= //============================================================================= Int parseUseCSF(char *args[], int) @@ -194,6 +205,7 @@ Int parseNoMilCap(char *args[], int) } return 1; } +#endif // RTS_DEBUG || RTS_INTERNAL //============================================================================= //============================================================================= @@ -231,6 +243,22 @@ Int parseKeepCRCSave(char *args[], int argc) return 1; } +//============================================================================= +//============================================================================= +Int parseSaveDebugCRCPerFrame(char* args[], int argc) +{ +#ifdef DEBUG_CRC + if (argc > 1) + { + g_saveDebugCRCPerFrame = TRUE; + g_saveDebugCRCPerFrameDir = args[1]; + if (TheCRCFirstFrameToLog == -1) + TheCRCFirstFrameToLog = 0; + } +#endif + return 2; +} + //============================================================================= //============================================================================= Int parseCRCLogicModuleData(char *args[], int argc) @@ -320,6 +348,8 @@ Int parseNoDraw(char *args[], int argc) return 1; } +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + //============================================================================= //============================================================================= Int parseLogToConsole(char *args[], int) @@ -330,7 +360,7 @@ Int parseLogToConsole(char *args[], int) return 1; } -#endif // _DEBUG || _INTERNAL +#endif // RTS_DEBUG || RTS_INTERNAL //============================================================================= //============================================================================= @@ -406,7 +436,7 @@ Int parseYRes(char *args[], int num) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= //============================================================================= Int parseLatencyAverage(char *args[], int num) @@ -589,7 +619,7 @@ Int parseMunkee(char *args[], int) } return 1; } -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseScriptDebug(char *args[], int) { @@ -622,7 +652,18 @@ Int parseBuildMapCache(char *args[], int) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +Int parsePreload( char *args[], int num ) +{ + if( TheWritableGlobalData ) + TheWritableGlobalData->m_preloadAssets = TRUE; + return 1; +} +#endif + + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseDisplayDebug(char *args[], int) { if (TheWritableGlobalData) @@ -642,12 +683,6 @@ Int parseFile(char *args[], int num) return 2; } -Int parsePreload( char *args[], int num ) -{ - if( TheWritableGlobalData ) - TheWritableGlobalData->m_preloadAssets = TRUE; - return 1; -} Int parsePreloadEverything( char *args[], int num ) { @@ -680,7 +715,7 @@ Int parseVTune ( char *args[], int num ) } /// end stuff for VTUNE -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= //============================================================================= @@ -694,7 +729,7 @@ Int parseNoFX(char *args[], int) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseNoShroud(char *args[], int) { if (TheWritableGlobalData) @@ -723,7 +758,7 @@ Int parseNoMoveCamera(char *args[], int) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseNoCinematic(char *args[], int) { if (TheWritableGlobalData) @@ -755,18 +790,37 @@ Int parseNoShellMap(char *args[], int) return 1; } -#if (defined(_DEBUG) || defined(_INTERNAL)) +Int parseNoShaders(char *args[], int) +{ + if (TheWritableGlobalData) + { + TheWritableGlobalData->m_chipSetType = 1; //force to a voodoo card which uses least amount of features. + } + return 1; +} + +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) Int parseNoLogo(char *args[], int) { if (TheWritableGlobalData) { TheWritableGlobalData->m_playIntro = FALSE; TheWritableGlobalData->m_afterIntro = TRUE; + TheWritableGlobalData->m_playSizzle = FALSE; } return 1; } #endif +Int parseNoSizzle( char *args[], int ) +{ + if (TheWritableGlobalData) + { + TheWritableGlobalData->m_playSizzle = FALSE; + } + return 1; +} + Int parseShellMap(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -796,8 +850,12 @@ Int parseWinCursors(char *args[], int num) Int parseQuickStart( char *args[], int num ) { -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) parseNoLogo( args, num ); +#else + //Kris: Patch 1.01 -- Allow release builds to skip the sizzle video, but still force the EA logo to show up. + //This is for legal reasons. + parseNoSizzle( args, num ); #endif parseNoShellMap( args, num ); parseNoWindowAnimation( args, num ); @@ -813,6 +871,29 @@ Int parseConstantDebug( char *args[], int num ) return 1; } +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) +Int parseExtraLogging( char *args[], int num ) +{ + if (TheWritableGlobalData) + { + TheWritableGlobalData->m_extraLogging = TRUE; + } + return 1; +} +#endif + +//-allAdvice feature +/* +Int parseAllAdvice( char *args[], int num ) +{ + if( TheWritableGlobalData ) + { + TheWritableGlobalData->m_allAdvice = TRUE; + } + return 1; +} +*/ + Int parseShowTeamDot( char *args[], int num ) { if( TheWritableGlobalData ) @@ -823,7 +904,7 @@ Int parseShowTeamDot( char *args[], int num ) } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseSelectAll( char *args[], int num ) { if( TheWritableGlobalData ) @@ -891,7 +972,7 @@ Int parseDemoLoadScreen(char *args[], int num) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseSaveStats(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -903,7 +984,7 @@ Int parseSaveStats(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseSaveAllStats(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -916,7 +997,7 @@ Int parseSaveAllStats(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseLocalMOTD(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -928,7 +1009,7 @@ Int parseLocalMOTD(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseCameraDebug(char *args[], int num) { if (TheWritableGlobalData) @@ -939,7 +1020,7 @@ Int parseCameraDebug(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseBenchmark(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -951,6 +1032,20 @@ Int parseBenchmark(char *args[], int num) } #endif +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) +#ifdef DUMP_PERF_STATS +Int parseStats(char *args[], int num) +{ + if (TheWritableGlobalData && num > 1) + { + TheWritableGlobalData->m_dumpStatsAtInterval = TRUE; + TheWritableGlobalData->m_statsInterval = atoi(args[1]); + } + return 2; +} +#endif +#endif + #ifdef DEBUG_CRASHING Int parseIgnoreAsserts(char *args[], int num) { @@ -1034,14 +1129,14 @@ Int parseMod(char *args[], Int num) } // now check for dir-ness - struct stat statBuf; - if (stat(modPath.str(), &statBuf) != 0) + struct _stat statBuf; + if (_stat(modPath.str(), &statBuf) != 0) { DEBUG_LOG(("Could not _stat() mod.\n")); return 2; // could not stat the file/dir. } - if (statBuf.st_mode & S_IFDIR) + if (statBuf.st_mode & _S_IFDIR) { if (!modPath.endsWith("\\") && !modPath.endsWith("/")) modPath.concat('\\'); @@ -1107,7 +1202,10 @@ static CommandLineParam params[] = { "-scriptDebug", parseScriptDebug }, { "-playStats", parsePlayStats }, { "-mod", parseMod }, -#if (defined(_DEBUG) || defined(_INTERNAL)) + { "-noshaders", parseNoShaders }, + { "-quickstart", parseQuickStart }, + +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) { "-noaudio", parseNoAudio }, { "-map", parseMapName }, { "-nomusic", parseNoMusic }, @@ -1115,21 +1213,65 @@ static CommandLineParam params[] = { "-noLogOrCrash", parseNoLogOrCrash }, { "-FPUPreserve", parseFPUPreserve }, { "-benchmark", parseBenchmark }, - { "-saveStats", parseSaveStats }, +#ifdef DUMP_PERF_STATS + { "-stats", parseStats }, +#endif + { "-saveStats", parseSaveStats }, { "-localMOTD", parseLocalMOTD }, { "-UseCSF", parseUseCSF }, { "-NoInputDisable", parseNoInputDisable }, +#endif +#ifdef DEBUG_CRC + // TheSuperHackers @info helmutbuhler 04/09/2025 + // The following arguments are useful for CRC debugging. + // Note that you need to have a debug or internal configuration build in order to use this. + // Release configuration also works if RELEASE_DEBUG_LOGGING is defined in Debug.h + // Also note that all players need to play in the same configuration, otherwise mismatch will + // occur almost immediately. + // Try this if you want to play the game and have useful debug information in case mismatch occurs: + // -ignoreAsserts -DebugCRCFromFrame 0 -VerifyClientCRC -LogObjectCRCs -NetCRCInterval 1 + // After mismatch occurs, you can examine the logfile and also reproduce the crc from the replay with this (and diff that with the log): + // -ignoreAsserts -DebugCRCFromFrame xxx -LogObjectCRCs -SaveDebugCRCPerFrame crc + + // After which frame to log crc logging. Call with 0 to log all frames and with -1 to log none (default). { "-DebugCRCFromFrame", parseDebugCRCFromFrame }, + + // Last frame to log { "-DebugCRCUntilFrame", parseDebugCRCUntilFrame }, + + // Save data involving CRC calculation to a binary file. (This isn't that useful.) { "-KeepCRCSaves", parseKeepCRCSave }, + + // TheSuperHackers @feature helmutbuhler 04/09/2025 + // Store CRC Debug Logging into a separate file for each frame. + // Pass the foldername after this where those files are to be stored. + // This is useful for replay analysis. + // Note that the passed folder is deleted if it already exists for every started game. + { "-SaveDebugCRCPerFrame", parseSaveDebugCRCPerFrame }, + { "-CRCLogicModuleData", parseCRCLogicModuleData }, { "-CRCClientModuleData", parseCRCClientModuleData }, - { "-ClientDeepCRC", parseClientDeepCRC }, + + // Verify that Game Logic CRC doesn't change during client update. + // Client update is only for visuals and not supposed to change the crc. + // (This is implemented using CRCVerification class in GameEngine::update) { "-VerifyClientCRC", parseVerifyClientCRC }, + + // Write out binary crc data pre and post client update to "clientPre.crc" and "clientPost.crc" + { "-ClientDeepCRC", parseClientDeepCRC }, + + // Log CRC of Objects and Weapons (See Object::crc and Weapon::crc) { "-LogObjectCRCs", parseLogObjectCRCs }, - { "-saveAllStats", parseSaveAllStats }, + + // Number of frames between each CRC check between all players in multiplayer games + // (if not all crcs are equal, mismatch occurs). { "-NetCRCInterval", parseNetCRCInterval }, + + // Number of frames between each CRC that is written to replay files in singleplayer games. { "-ReplayCRCInterval", parseReplayCRCInterval }, +#endif +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + { "-saveAllStats", parseSaveAllStats }, { "-noDraw", parseNoDraw }, { "-nomilcap", parseNoMilCap }, { "-nofade", parseNoFade }, @@ -1155,8 +1297,10 @@ static CommandLineParam params[] = { "-munkee", parseMunkee }, { "-displayDebug", parseDisplayDebug }, { "-file", parseFile }, - { "-preload", parsePreload }, - { "-preloadEverything", parsePreloadEverything }, + +// { "-preload", parsePreload }, + + { "-preloadEverything", parsePreloadEverything }, { "-logAssets", parseLogAssets }, { "-netMinPlayers", parseNetMinPlayers }, { "-DemoLoadScreen", parseDemoLoadScreen }, @@ -1176,7 +1320,6 @@ static CommandLineParam params[] = { "-noShellAnim", parseNoWindowAnimation }, { "-winCursors", parseWinCursors }, { "-constantDebug", parseConstantDebug }, - { "-quickstart", parseQuickStart }, { "-seed", parseSeed }, { "-noagpfix", parseIncrAGPBuf }, { "-noFPSLimit", parseNoFPSLimit }, @@ -1184,6 +1327,8 @@ static CommandLineParam params[] = { "-jumpToFrame", parseJumpToFrame }, { "-updateImages", parseUpdateImages }, { "-showTeamDot", parseShowTeamDot }, + { "-extraLogging", parseExtraLogging }, + #endif #ifdef DEBUG_LOGGING @@ -1198,6 +1343,15 @@ static CommandLineParam params[] = #ifdef DEBUG_STACKTRACE { "-ignoreStackTrace", parseIgnoreStackTrace }, #endif + + //-allAdvice feature + //{ "-allAdvice", parseAllAdvice }, + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) + { "-preload", parsePreload }, +#endif + + }; // parseCommandLine =========================================================== diff --git a/Generals/Code/GameEngine/Source/Common/Dict.cpp b/Generals/Code/GameEngine/Source/Common/Dict.cpp index 471bad1da7..ae8993bd78 100644 --- a/Generals/Code/GameEngine/Source/Common/Dict.cpp +++ b/Generals/Code/GameEngine/Source/Common/Dict.cpp @@ -107,7 +107,7 @@ void Dict::DictPair::setNameAndType(NameKeyType key, Dict::DataType type) } // ----------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void Dict::validate() const { if (!m_data) return; diff --git a/Generals/Code/GameEngine/Source/Common/GameEngine.cpp b/Generals/Code/GameEngine/Source/Common/GameEngine.cpp index ceb2fe255c..bca49f07cc 100644 --- a/Generals/Code/GameEngine/Source/Common/GameEngine.cpp +++ b/Generals/Code/GameEngine/Source/Common/GameEngine.cpp @@ -110,7 +110,7 @@ #include "Common/version.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -257,9 +257,9 @@ void GameEngine::init( int argc, char *argv[] ) { DEBUG_LOG(("================================================================================\n")); #ifdef DEBUG_LOGGING - #if defined _DEBUG + #if defined RTS_DEBUG const char *buildType = "Debug"; - #elif defined _INTERNAL + #elif defined RTS_INTERNAL const char *buildType = "Internal"; #else const char *buildType = "Release"; @@ -299,7 +299,7 @@ void GameEngine::init( int argc, char *argv[] ) initSubsystem(TheArchiveFileSystem, "TheArchiveFileSystem", createArchiveFileSystem(), NULL); // this MUST come after TheLocalFileSystem creation initSubsystem(TheWritableGlobalData, "TheWritableGlobalData", MSGNEW("GameEngineSubsystem") GlobalData(), &xferCRC, "Data\\INI\\Default\\GameData.ini", "Data\\INI\\GameData.ini"); - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // If we're in Debug or Internal, load the Debug info as well. ini.load( AsciiString( "Data\\INI\\GameDataDebug.ini" ), INI_LOAD_OVERWRITE, NULL ); #endif @@ -374,7 +374,7 @@ void GameEngine::init( int argc, char *argv[] ) fname.format("Data\\%s\\CommandMap.ini", GetRegistryLanguage().str()); initSubsystem(TheMetaMap,"TheMetaMap", MSGNEW("GameEngineSubsystem") MetaMap(), NULL, fname.str(), "Data\\INI\\CommandMap.ini"); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ini.load("Data\\INI\\CommandMapDebug.ini", INI_LOAD_MULTIFILE, NULL); #endif @@ -411,27 +411,6 @@ void GameEngine::init( int argc, char *argv[] ) // load music dialog will still cause the game to quit. // m_quitting = FALSE; - // for fingerprinting, we need to ensure the presence of these files - AsciiString dirName; - dirName = TheArchiveFileSystem->getArchiveFilenameForFile("generalsb.sec"); - if (dirName.compareNoCase("gensec.big") != 0) - { - DEBUG_LOG(("generalsb.sec was not found in gensec.big - it was in '%s'\n", dirName.str())); - m_quitting = TRUE; - } - - dirName = TheArchiveFileSystem->getArchiveFilenameForFile("generalsa.sec"); - const char *noPath = dirName.reverseFind('\\'); - if (noPath) { - dirName = noPath + 1; - } - - if (dirName.compareNoCase("music.big") != 0) - { - DEBUG_LOG(("generalsa.sec was not found in music.big - it was in '%s'\n", dirName.str())); - m_quitting = TRUE; - } - // initialize the MapCache TheMapCache = MSGNEW("GameEngineSubsystem") MapCache; TheMapCache->updateCache(); @@ -609,7 +588,7 @@ void GameEngine::execute( void ) { DWORD prevTime = timeGetTime(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DWORD startTime = timeGetTime() / 1000; #endif @@ -626,7 +605,7 @@ void GameEngine::execute( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) { // enter only if in benchmark mode if (TheGlobalData->m_benchmarkTimer > 0) @@ -684,23 +663,33 @@ void GameEngine::execute( void ) // I'm disabling this in internal because many people need alt-tab capability. If you happen to be // doing performance tuning, please just change this on your local system. -MDC - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ::Sleep(1); // give everyone else a tiny time slice. #endif - // limit the framerate - DWORD now = timeGetTime(); - DWORD limit = (1000.0f/m_maxFPS)-1; - while (TheGlobalData->m_useFpsLimit && (now - prevTime) < limit) - { - ::Sleep(0); - now = timeGetTime(); - } - //Int slept = now - prevTime; - //DEBUG_LOG(("delayed %d\n",slept)); - prevTime = now; - } + #if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) + if ( ! TheGlobalData->m_TiVOFastMode ) + #else //always allow this cheatkey if we're in a replaygame. + if ( ! (TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame())) + #endif + { + // limit the framerate + DWORD now = timeGetTime(); + DWORD limit = (1000.0f/m_maxFPS)-1; + while (TheGlobalData->m_useFpsLimit && (now - prevTime) < limit) + { + ::Sleep(0); + now = timeGetTime(); + } + //Int slept = now - prevTime; + //DEBUG_LOG(("delayed %d\n",slept)); + + prevTime = now; + + } + + } } } // perfgather for execute_loop diff --git a/Generals/Code/GameEngine/Source/Common/GameLOD.cpp b/Generals/Code/GameEngine/Source/Common/GameLOD.cpp index d431a9d38e..08600c85ce 100644 --- a/Generals/Code/GameEngine/Source/Common/GameLOD.cpp +++ b/Generals/Code/GameEngine/Source/Common/GameLOD.cpp @@ -41,7 +41,7 @@ #define DEFINE_PARTICLE_SYSTEM_NAMES #include "GameClient/ParticleSys.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp index fd339e79b2..ccaa5b5f7d 100644 --- a/Generals/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/Generals/Code/GameEngine/Source/Common/GlobalData.cpp @@ -488,7 +488,7 @@ GlobalData* GlobalData::m_theOriginal = NULL; { "KeyboardCameraRotateSpeed", INI::parseReal, NULL, offsetof( GlobalData, m_keyboardCameraRotateSpeed ) }, { "PlayStats", INI::parseInt, NULL, offsetof( GlobalData, m_playStats ) }, -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) { "DisableCameraFade", INI::parseBool, NULL, offsetof( GlobalData, m_disableCameraFade ) }, { "DisableScriptedInputDisabling", INI::parseBool, NULL, offsetof( GlobalData, m_disableScriptedInputDisabling ) }, { "DisableMilitaryCaption", INI::parseBool, NULL, offsetof( GlobalData, m_disableMilitaryCaption ) }, @@ -500,6 +500,7 @@ GlobalData* GlobalData::m_theOriginal = NULL; { "ShroudOn", INI::parseBool, NULL, offsetof( GlobalData, m_shroudOn ) }, { "FogOfWarOn", INI::parseBool, NULL, offsetof( GlobalData, m_fogOfWarOn ) }, { "ShowCollisionExtents", INI::parseBool, NULL, offsetof( GlobalData, m_showCollisionExtents ) }, + { "ShowAudioLocations", INI::parseBool, NULL, offsetof( GlobalData, m_showAudioLocations ) }, { "DebugProjectileTileWidth", INI::parseReal, NULL, offsetof( GlobalData, m_debugProjectileTileWidth) }, { "DebugProjectileTileDuration",INI::parseInt, NULL, offsetof( GlobalData, m_debugProjectileTileDuration) }, { "DebugProjectileTileColor", INI::parseRGBColor, NULL, offsetof( GlobalData, m_debugProjectileTileColor) }, @@ -518,6 +519,7 @@ GlobalData* GlobalData::m_theOriginal = NULL; { "UseLocalMOTD", INI::parseBool, NULL, offsetof( GlobalData, m_useLocalMOTD ) }, { "BaseStatsDir", INI::parseAsciiString,NULL, offsetof( GlobalData, m_baseStatsDir ) }, { "LocalMOTDPath", INI::parseAsciiString,NULL, offsetof( GlobalData, m_MOTDPath ) }, + { "ExtraLogging", INI::parseBool, NULL, offsetof( GlobalData, m_extraLogging ) }, #endif { NULL, NULL, NULL, 0 } // keep this last @@ -541,7 +543,9 @@ GlobalData::GlobalData() m_theOriginal = this; m_next = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) + m_TiVOFastMode = FALSE; + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_wireframe = 0; m_stateMachineDebug = FALSE; m_useCameraConstraints = TRUE; @@ -550,6 +554,7 @@ GlobalData::GlobalData() m_jabberOn = FALSE; m_munkeeOn = FALSE; m_showCollisionExtents = FALSE; + m_showAudioLocations = FALSE; m_debugCamera = FALSE; m_specialPowerUsesDelay = TRUE; m_debugVisibility = FALSE; @@ -581,6 +586,7 @@ GlobalData::GlobalData() m_useLocalMOTD = FALSE; m_baseStatsDir = ".\\"; m_MOTDPath = "MOTD.txt"; + m_extraLogging = FALSE; #endif #ifdef DEBUG_CRASHING @@ -806,6 +812,7 @@ GlobalData::GlobalData() // End Add m_debugAI = AI_DEBUG_NONE; + m_debugSupplyCenterPlacement = FALSE; m_debugAIObstacles = FALSE; m_showClientPhysics = TRUE; m_showTerrainNormals = FALSE; @@ -957,6 +964,7 @@ GlobalData::GlobalData() m_shellMapName.set("Maps\\ShellMap1\\ShellMap1.map"); m_shellMapOn =TRUE; m_playIntro = TRUE; + m_playSizzle = TRUE; m_afterIntro = FALSE; m_allowExitOutOfMovies = FALSE; m_loadScreenRender = FALSE; @@ -1055,8 +1063,10 @@ GlobalData::~GlobalData( void ) if (m_weaponBonusSet) m_weaponBonusSet->deleteInstance(); - if( m_theOriginal == this ) + if( m_theOriginal == this ) { m_theOriginal = NULL; + TheWritableGlobalData = NULL; + } } // end ~GlobalData diff --git a/Generals/Code/GameEngine/Source/Common/INI/INI.cpp b/Generals/Code/GameEngine/Source/Common/INI/INI.cpp index dcaa165fb1..81d8374b9e 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INI.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INI.cpp @@ -59,7 +59,7 @@ #include "GameLogic/ObjectCreationList.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/INI/INICommandButton.cpp b/Generals/Code/GameEngine/Source/Common/INI/INICommandButton.cpp index 836294a36f..178463c103 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INICommandButton.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INICommandButton.cpp @@ -32,6 +32,7 @@ #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine #include "Common/INI.h" +#include "Common/SpecialPower.h" #include "GameClient/ControlBar.h" //------------------------------------------------------------------------------------------------- @@ -72,6 +73,21 @@ void ControlBar::parseCommandButtonDefinition( INI *ini ) // parse the ini definition ini->initFromINI( button, button->getFieldParse() ); + + + //Make sure buttons with special power templates also have the appropriate option set. + const SpecialPowerTemplate *spTemplate = button->getSpecialPowerTemplate(); + Bool needsTemplate = BitIsSet( button->getOptions(), NEED_SPECIAL_POWER_SCIENCE ); + if( spTemplate && !needsTemplate ) + { + DEBUG_CRASH( ("[LINE: %d in '%s'] CommandButton %s has SpecialPower = %s but the button also requires Options = NEED_SPECIAL_POWER_SCIENCE. Failure to do so will cause bugs such as invisible side shortcut buttons", + ini->getLineNum(), ini->getFilename().str(), name.str(), spTemplate->getName().str() ) ); + } + else if( !spTemplate && needsTemplate ) + { + DEBUG_CRASH( ("[LINE: %d in '%s'] CommandButton %s has Options = NEED_SPECIAL_POWER_SCIENCE but doesn't specify a SpecialPower = xxxx. Please evaluate INI.", + ini->getLineNum(), ini->getFilename().str(), name.str() ) ); + } } // end parseCommandButtonDefinition diff --git a/Generals/Code/GameEngine/Source/Common/INI/INIMapCache.cpp b/Generals/Code/GameEngine/Source/Common/INI/INIMapCache.cpp index f294a5b0bc..abc56997d5 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INIMapCache.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INIMapCache.cpp @@ -38,6 +38,12 @@ #include "Common/WellKnownKeys.h" #include "Common/QuotedPrintable.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + class MapMetaDataReader { public: diff --git a/Generals/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp b/Generals/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp index 9615b7eac1..324913d218 100644 --- a/Generals/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp +++ b/Generals/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp @@ -34,7 +34,7 @@ #include "Common/Registry.h" #include "GameNetwork/WOLBrowser/WebBrowser.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/MessageStream.cpp b/Generals/Code/GameEngine/Source/Common/MessageStream.cpp index f1dcfecb07..71ccc2fa3e 100644 --- a/Generals/Code/GameEngine/Source/Common/MessageStream.cpp +++ b/Generals/Code/GameEngine/Source/Common/MessageStream.cpp @@ -41,6 +41,15 @@ MessageStream *TheMessageStream = NULL; CommandList *TheCommandList = NULL; + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + + //------------------------------------------------------------------------------------------------ // GameMessage // @@ -337,7 +346,7 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_META_CHAT_EVERYONE) CHECK_IF(MSG_META_DIPLOMACY) CHECK_IF(MSG_META_OPTIONS) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CHECK_IF(MSG_META_HELP) #endif CHECK_IF(MSG_META_TOGGLE_LOWER_DETAILS) @@ -364,7 +373,12 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_META_BEGIN_CAMERA_ZOOM_OUT) CHECK_IF(MSG_META_END_CAMERA_ZOOM_OUT) CHECK_IF(MSG_META_CAMERA_RESET) -#if defined(_DEBUG) || defined(_INTERNAL) + + + CHECK_IF(MSG_META_TOGGLE_FAST_FORWARD_REPLAY) + + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CHECK_IF(MSG_META_DEMO_TOGGLE_BEHIND_BUILDINGS) CHECK_IF(MSG_META_DEMO_TOGGLE_LETTERBOX) CHECK_IF(MSG_META_DEMO_TOGGLE_MESSAGE_TEXT) @@ -473,12 +487,12 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_META_DEBUG_DUMP_ALL_PLAYER_OBJECTS) CHECK_IF(MSG_META_DEBUG_WIN) CHECK_IF(MSG_META_DEMO_TOGGLE_DEBUG_STATS) -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) CHECK_IF(MSG_META_DEMO_TOGGLE_AUDIODEBUG) -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS CHECK_IF(MSG_META_DEMO_PERFORM_STATISTICAL_DUMP) #endif//DUMP_PERF_STATS @@ -620,7 +634,7 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_SELF_DESTRUCT) CHECK_IF(MSG_CREATE_FORMATION) CHECK_IF(MSG_LOGIC_CRC) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CHECK_IF(MSG_DEBUG_KILL_SELECTION) CHECK_IF(MSG_DEBUG_HURT_OBJECT) CHECK_IF(MSG_DEBUG_KILL_OBJECT) @@ -951,7 +965,7 @@ void MessageStream::removeTranslator( TranslatorID id ) // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool isInvalidDebugCommand( GameMessage::Type t ) { @@ -1040,7 +1054,7 @@ void MessageStream::propagateMessages( void ) for( msg=m_firstMessage; msg; msg=next ) { if (ss->m_translator -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) && !isInvalidDebugCommand(msg->getType()) #endif ) diff --git a/Generals/Code/GameEngine/Source/Common/MiniLog.cpp b/Generals/Code/GameEngine/Source/Common/MiniLog.cpp index e65967f34f..c1a27a3697 100644 --- a/Generals/Code/GameEngine/Source/Common/MiniLog.cpp +++ b/Generals/Code/GameEngine/Source/Common/MiniLog.cpp @@ -61,6 +61,8 @@ LogClass::~LogClass() void LogClass::log(const char *fmt, ...) { + if (!m_fp) + return; static char buf[1024]; static Int lastFrame = 0; static Int lastIndex = 0; diff --git a/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp index dca57a0e6f..9e84fb0a2c 100644 --- a/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp +++ b/Generals/Code/GameEngine/Source/Common/NameKeyGenerator.cpp @@ -98,6 +98,16 @@ inline UnsignedInt calcHashForString(const char* p) return result; } +/* ------------------------------------------------------------------------ */ +inline UnsignedInt calcHashForLowercaseString(const char* p) +{ + UnsignedInt result = 0; + Byte *pp = (Byte*)p; + while (*pp) + result = (result << 5) + result + tolower(*pp++); + return result; +} + //------------------------------------------------------------------------------------------------- AsciiString NameKeyGenerator::keyToName(NameKeyType key) { @@ -135,7 +145,7 @@ NameKeyType NameKeyGenerator::nameToKey(const char* nameString) NameKeyType result = b->m_key; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // reality-check to be sure our hasher isn't going bad. const Int maxThresh = 3; Int numOverThresh = 0; @@ -160,6 +170,63 @@ NameKeyType NameKeyGenerator::nameToKey(const char* nameString) } // end nameToKey +//------------------------------------------------------------------------------------------------- +NameKeyType NameKeyGenerator::nameToLowercaseKey(const char* nameString) +{ + Bucket *b; + + UnsignedInt hash = calcHashForLowercaseString(nameString) % SOCKET_COUNT; + + // hmm, do we have it already? + for (b = m_sockets[hash]; b; b = b->m_nextInSocket) + { + if (_stricmp(nameString, b->m_nameString.str()) == 0) + return b->m_key; + } + + // nope, guess not. let's allocate it. + b = newInstance(Bucket); + b->m_key = (NameKeyType)m_nextID++; + b->m_nameString = nameString; + b->m_nextInSocket = m_sockets[hash]; + m_sockets[hash] = b; + + NameKeyType result = b->m_key; + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + // reality-check to be sure our hasher isn't going bad. + const Int maxThresh = 3; + Int numOverThresh = 0; + for (Int i = 0; i < SOCKET_COUNT; ++i) + { + Int numInThisSocket = 0; + for (b = m_sockets[i]; b; b = b->m_nextInSocket) + ++numInThisSocket; + + if (numInThisSocket > maxThresh) + ++numOverThresh; + } + + // if more than a small percent of the sockets are getting deep, probably want to increase the socket count. + if (numOverThresh > SOCKET_COUNT/20) + { + DEBUG_CRASH(("hmm, might need to increase the number of bucket-sockets for NameKeyGenerator (numOverThresh %d = %f%%)\n",numOverThresh,(Real)numOverThresh/(Real)(SOCKET_COUNT/20))); + } +#endif + + return result; + +} // end nameToLowercaseKey + +//------------------------------------------------------------------------------------------------- +// Get a string out of the INI. Store it into a NameKeyType +//------------------------------------------------------------------------------------------------- +void NameKeyGenerator::parseStringAsNameKeyType( INI *ini, void *instance, void *store, const void* userData ) +{ + *(NameKeyType *)store = TheNameKeyGenerator->nameToKey( ini->getNextToken() ); +} + + //------------------------------------------------------------------------------------------------- NameKeyType StaticNameKey::key() const { diff --git a/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp b/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp index 5f45c36ee5..91e9fb8774 100644 --- a/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp +++ b/Generals/Code/GameEngine/Source/Common/PerfTimer.cpp @@ -36,7 +36,7 @@ #include "GameClient/GraphDraw.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -517,7 +517,7 @@ void PerfTimer::outputInfo( void ) return; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) double totalTimeInMS = 1000.0 * m_runningTime / s_ticksPerSec; double avgTimePerFrame = totalTimeInMS / (m_lastFrame - m_startFrame + 1); double avgTimePerCall = totalTimeInMS / m_callCount; @@ -555,7 +555,7 @@ void PerfTimer::outputInfo( void ) //------------------------------------------------------------------------------------------------- void PerfTimer::showMetrics( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) double totalTimeInMS = 1000.0 * m_runningTime / s_ticksPerSec; double avgTimePerFrame = totalTimeInMS / (m_lastFrame - m_startFrame + 1); double avgTimePerCall = totalTimeInMS / m_callCount; diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp index 14225d2caa..7eb26c8cb8 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp @@ -64,7 +64,7 @@ #include "GameLogic/ExperienceTracker.h"//LORENZEN -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp index bacf681997..711568b020 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp @@ -51,6 +51,26 @@ #include "Common/Xfer.h" #include "GameLogic/Object.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + +//----------------------------------------------------------------------------- +Energy::Energy() +{ + m_energyProduction = 0; + m_energyConsumption = 0; + m_owner = NULL; +} + +//----------------------------------------------------------------------------- +Int Energy::getProduction() const +{ + return m_energyProduction; +} + //----------------------------------------------------------------------------- Real Energy::getEnergySupplyRatio() const { diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp index d311cea959..13d219f064 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp @@ -123,3 +123,13 @@ void Money::loadPostProcess( void ) } // end loadPostProcess + +// ------------------------------------------------------------------------------------------------ +/** Parse a money amount for the ini file. E.g. DefaultStartingMoney = 10000 */ +// ------------------------------------------------------------------------------------------------ +void Money::parseMoneyAmount( INI *ini, void *instance, void *store, const void* userData ) +{ + // Someday, maybe, have mulitple fields like Gold:10000 Wood:1000 Tiberian:10 + Money * money = (Money *)store; + INI::parseUnsignedInt( ini, instance, &money->m_money, userData ); +} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp index 79b022cd18..b29be797b9 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -99,7 +99,7 @@ #include "GameLogic/VictoryConditions.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -430,7 +430,7 @@ void Player::init(const PlayerTemplate* pt) m_unitsShouldHunt = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_DEMO_ignorePrereqs = FALSE; m_DEMO_freeBuild = FALSE; m_DEMO_instantBuild = FALSE; @@ -1093,8 +1093,7 @@ void Player::becomingLocalPlayer(Bool yes) Drawable *draw = object->getDrawable(); if( draw ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate *update = (StealthUpdate*)object->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = object->getStealth(); if( update && update->isDisguised() ) { Player *disguisedPlayer = ThePlayerList->getNthPlayer( update->getDisguisedPlayerIndex() ); @@ -1302,6 +1301,10 @@ void Player::preTeamDestroy( const Team *team ) // ai notification callback if( m_ai ) m_ai->aiPreTeamDestroy( team ); + + // TheSuperHackers @bugfix Mauller/Xezon 03/05/2025 Clear the default team to prevent dangling pointer usage + if( m_defaultTeam == team ) + m_defaultTeam = NULL; } // preTeamDestroy //------------------------------------------------------------------------------------------------- @@ -2455,7 +2458,7 @@ Bool Player::canBuild(const ThingTemplate *tmplate) const prereqsOK = false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (ignoresPrereqs()) prereqsOK = true; #endif diff --git a/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp b/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp index 714a68eaca..7d1d043aaa 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp @@ -54,13 +54,13 @@ #include "Common/Team.h" #include "Common/WellKnownKeys.h" #include "Common/Xfer.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #include "GameLogic/Object.h" #endif #include "GameLogic/SidesList.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp b/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp index 82959a51d7..3c542e9d1c 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp @@ -53,7 +53,7 @@ #include "Common/Science.h" #include "GameClient/Image.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -304,12 +304,12 @@ const PlayerTemplate* PlayerTemplateStore::findPlayerTemplate(NameKeyType nameke namekey = g0; // end ugly, hokey code to quietly load old maps... - #ifdef _DEBUG + #ifdef RTS_DEBUG AsciiString nn = KEYNAME(namekey); #endif for (PlayerTemplateVector::const_iterator it = m_playerTemplates.begin(); it != m_playerTemplates.end(); ++it) { - #ifdef _DEBUG + #ifdef RTS_DEBUG AsciiString n = KEYNAME((*it).getNameKey()); #endif if ((*it).getNameKey() == namekey) diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index ba54998549..88e33e4b22 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -52,7 +52,7 @@ #include "GameClient/Drawable.h" #include "GameClient/GameText.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp index 0314912789..83a2124e2b 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp @@ -35,7 +35,7 @@ ScienceStore* TheScienceStore = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -48,6 +48,23 @@ void ScienceStore::init() m_sciences.clear(); } +//----------------------------------------------------------------------------- +ScienceStore::~ScienceStore() +{ + // nope. + //m_sciences.clear(); + + // go through all sciences and delete any overrides + for (ScienceInfoVec::iterator it = m_sciences.begin(); it != m_sciences.end(); /*++it*/) + { + ScienceInfo* si = *it; + ++it; + if (si) { + si->deleteInstance(); + } + } +} + //----------------------------------------------------------------------------- void ScienceStore::reset() { diff --git a/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp index 224056f4d4..f5f39175d7 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp @@ -37,7 +37,7 @@ #include "GameLogic/Object.h" #include "Common/BitFlagsIO.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -176,6 +176,7 @@ void SpecialPowerStore::parseSpecialPowerDefinition( INI *ini ) { "ViewObjectDuration", INI::parseDurationUnsignedInt, NULL, offsetof( SpecialPowerTemplate, m_viewObjectDuration ) }, { "ViewObjectRange", INI::parseReal, NULL, offsetof( SpecialPowerTemplate, m_viewObjectRange ) }, { "RadiusCursorRadius", INI::parseReal, NULL, offsetof( SpecialPowerTemplate, m_radiusCursorRadius ) }, + { "ShortcutPower", INI::parseBool, NULL, offsetof( SpecialPowerTemplate, m_shortcutPower ) }, { NULL, NULL, NULL, 0 } // keep this last }; @@ -194,6 +195,7 @@ SpecialPowerTemplate::SpecialPowerTemplate() m_viewObjectDuration = 0; m_viewObjectRange = 0; m_radiusCursorRadius = 0; + m_shortcutPower = FALSE; } // end SpecialPowerTemplate diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp index d0ffe86afa..d88d87e2bd 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp @@ -51,7 +51,7 @@ #include "GameLogic/ScriptActions.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/RandomValue.cpp b/Generals/Code/GameEngine/Source/Common/RandomValue.cpp index 369e78f364..a65d27b371 100644 --- a/Generals/Code/GameEngine/Source/Common/RandomValue.cpp +++ b/Generals/Code/GameEngine/Source/Common/RandomValue.cpp @@ -37,7 +37,7 @@ //#define DETERMINISTIC // to allow repetition for debugging -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/Recorder.cpp b/Generals/Code/GameEngine/Source/Common/Recorder.cpp index e7e2c12f0c..a4293d1860 100644 --- a/Generals/Code/GameEngine/Source/Common/Recorder.cpp +++ b/Generals/Code/GameEngine/Source/Common/Recorder.cpp @@ -30,6 +30,7 @@ #include "Common/Player.h" #include "Common/GlobalData.h" #include "Common/GameEngine.h" +#include "GameClient/ClientInstance.h" #include "GameClient/GameWindow.h" #include "GameClient/GameWindowManager.h" #include "GameClient/InGameUI.h" @@ -45,7 +46,7 @@ #include "Common/CRCDebug.h" #include "Common/version.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -56,10 +57,17 @@ Int REPLAY_CRC_INTERVAL = 100; const char *replayExtention = ".rep"; const char *lastReplayFileName = "00000000"; // a name the user is unlikely to ever type, but won't cause panic & confusion +// TheSuperHackers @tweak helmutbuhler 25/04/2025 +// The replay header contains two time fields; startTime and endTime of type time_t. +// time_t is 32 bit wide on VC6, but on newer compilers it is 64 bit wide. +// In order to remain compatible we need to load and save time values with 32 bits. +// Note that this will overflow on January 18, 2038. @todo Upgrade to 64 bits when we break compatibility. +typedef int32_t replay_time_t; + static time_t startTime; static const UnsignedInt startTimeOffset = 6; -static const UnsignedInt endTimeOffset = startTimeOffset + sizeof(time_t); -static const UnsignedInt framesOffset = endTimeOffset + sizeof(time_t); +static const UnsignedInt endTimeOffset = startTimeOffset + sizeof(replay_time_t); +static const UnsignedInt framesOffset = endTimeOffset + sizeof(replay_time_t); static const UnsignedInt desyncOffset = framesOffset + sizeof(UnsignedInt); static const UnsignedInt quitEarlyOffset = desyncOffset + sizeof(Bool); static const UnsignedInt disconOffset = quitEarlyOffset + sizeof(Bool); @@ -75,7 +83,8 @@ void RecorderClass::logGameStart(AsciiString options) if (!fseek(m_file, startTimeOffset, SEEK_SET)) { // save off start time - fwrite(&startTime, sizeof(time_t), 1, m_file); + replay_time_t tmp = (replay_time_t)startTime; + fwrite(&tmp, sizeof(replay_time_t), 1, m_file); } // move back to end of stream #ifdef DEBUG_CRASHING @@ -84,7 +93,7 @@ void RecorderClass::logGameStart(AsciiString options) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheNetwork && TheGlobalData->m_saveStats) { //if (TheLAN) @@ -145,7 +154,7 @@ void RecorderClass::logPlayerDisconnect(UnicodeString player, Int slot) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { unsigned long bufSize = MAX_COMPUTERNAME_LENGTH + 1; @@ -190,7 +199,7 @@ void RecorderClass::logCRCMismatch( void ) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { m_wasDesync = TRUE; @@ -229,7 +238,8 @@ void RecorderClass::logGameEnd( void ) if (!fseek(m_file, endTimeOffset, SEEK_SET)) { // save off end time - fwrite(&t, sizeof(time_t), 1, m_file); + replay_time_t tmp = (replay_time_t)t; + fwrite(&tmp, sizeof(replay_time_t), 1, m_file); } // move to appropriate offset if (!fseek(m_file, framesOffset, SEEK_SET)) @@ -244,7 +254,7 @@ void RecorderClass::logGameEnd( void ) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheNetwork && TheGlobalData->m_saveStats) { //if (TheLAN) @@ -273,22 +283,9 @@ void RecorderClass::logGameEnd( void ) #endif } -#ifdef DEBUG_LOGGING - #if defined(_INTERNAL) - #define DEBUG_FILE_NAME "DebugLogFileI.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevI.txt" - #elif defined(_DEBUG) - #define DEBUG_FILE_NAME "DebugLogFileD.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevD.txt" - #else - #define DEBUG_FILE_NAME "DebugLogFile.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrev.txt" - #endif -#endif - void RecorderClass::cleanUpReplayFile( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { char fname[_MAX_PATH+1]; @@ -298,14 +295,19 @@ void RecorderClass::cleanUpReplayFile( void ) AsciiString oldFname; oldFname.format("%s%s", getReplayDir().str(), m_fileName.str()); CopyFile(oldFname.str(), fname, TRUE); -#ifdef DEBUG_FILE_NAME + +#ifdef DEBUG_LOGGING + const char* logFileName = DebugGetLogFileName(); + if (logFileName[0] == '\0') + return; + AsciiString debugFname = fname; debugFname.removeLastChar(); debugFname.removeLastChar(); debugFname.removeLastChar(); debugFname.concat("txt"); UnsignedInt fileSize = 0; - FILE *fp = fopen(DEBUG_FILE_NAME, "rb"); + FILE *fp = fopen(logFileName, "rb"); if (fp) { fseek(fp, 0, SEEK_END); @@ -318,13 +320,13 @@ void RecorderClass::cleanUpReplayFile( void ) const int MAX_DEBUG_SIZE = 65536; if (fileSize <= MAX_DEBUG_SIZE || TheGlobalData->m_saveAllStats) { - DEBUG_LOG(("Using CopyFile to copy %s\n", DEBUG_FILE_NAME)); - CopyFile(DEBUG_FILE_NAME, debugFname.str(), TRUE); + DEBUG_LOG(("Using CopyFile to copy %s\n", logFileName)); + CopyFile(logFileName, debugFname.str(), TRUE); } else { - DEBUG_LOG(("manual copy of %s\n", DEBUG_FILE_NAME)); - FILE *ifp = fopen(DEBUG_FILE_NAME, "rb"); + DEBUG_LOG(("manual copy of %s\n", logFileName)); + FILE *ifp = fopen(logFileName, "rb"); FILE *ofp = fopen(debugFname.str(), "wb"); if (ifp && ofp) { @@ -348,7 +350,7 @@ void RecorderClass::cleanUpReplayFile( void ) ofp = NULL; } } -#endif // DEBUG_FILE_NAME +#endif // DEBUG_LOGGING } #endif } @@ -555,9 +557,9 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, In // // **** if this changes, change the LAN Playtest code above **** // - time_t t = 0; - fwrite(&t, sizeof(time_t), 1, m_file); // reserve space for start time - fwrite(&t, sizeof(time_t), 1, m_file); // reserve space for end time + replay_time_t t = 0; + fwrite(&t, sizeof(replay_time_t), 1, m_file); // reserve space for start time + fwrite(&t, sizeof(replay_time_t), 1, m_file); // reserve space for end time UnsignedInt frames = 0; fwrite(&frames, sizeof(UnsignedInt), 1, m_file); // reserve space for duration in frames @@ -834,8 +836,11 @@ Bool RecorderClass::readReplayHeader(ReplayHeader& header) } // read in some stats - fread(&header.startTime, sizeof(time_t), 1, m_file); - fread(&header.endTime, sizeof(time_t), 1, m_file); + replay_time_t tmp; + fread(&tmp, sizeof(replay_time_t), 1, m_file); + header.startTime = tmp; + fread(&tmp, sizeof(replay_time_t), 1, m_file); + header.endTime = tmp; fread(&header.frameDuration, sizeof(UnsignedInt), 1, m_file); @@ -900,7 +905,7 @@ Bool RecorderClass::readReplayHeader(ReplayHeader& header) return TRUE; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool RecorderClass::analyzeReplay( AsciiString filename ) { m_doingAnalysis = TRUE; @@ -1096,8 +1101,8 @@ Bool RecorderClass::playbackFile(AsciiString filename) { return FALSE; } -#ifdef DEBUG_LOGGING +#ifdef DEBUG_CRASHING Bool versionStringDiff = header.versionString != TheVersion->getUnicodeVersion(); Bool versionTimeStringDiff = header.versionTimeString != TheVersion->getUnicodeBuildTime(); Bool versionNumberDiff = header.versionNumber != TheVersion->getVersionNumber(); @@ -1109,15 +1114,20 @@ Bool RecorderClass::playbackFile(AsciiString filename) AsciiString tempStr; if (exeDifferent) { + // TheSuperHackers @fix helmutbuhler 05/05/2025 No longer attempts to print unicode as ascii + // via a call to AsciiString::format with %ls format. It does not work with non-ascii characters. + UnicodeString tempStrWide; debugString = "EXE is different:\n"; if (versionStringDiff) { - tempStr.format(" Version [%ls] vs [%ls]\n", TheVersion->getUnicodeVersion().str(), header.versionString.str()); + tempStrWide.format(L" Version [%s] vs [%s]\n", TheVersion->getUnicodeVersion().str(), header.versionString.str()); + tempStr.translate(tempStrWide); debugString.concat(tempStr); } if (versionTimeStringDiff) { - tempStr.format(" Build Time [%ls] vs [%ls]\n", TheVersion->getUnicodeBuildTime().str(), header.versionTimeString.str()); + tempStrWide.format(L" Build Time [%s] vs [%s]\n", TheVersion->getUnicodeBuildTime().str(), header.versionTimeString.str()); + tempStr.translate(tempStrWide); debugString.concat(tempStr); } if (versionNumberDiff) @@ -1532,7 +1542,7 @@ AsciiString RecorderClass::getReplayExtention() { */ AsciiString RecorderClass::getLastReplayFileName() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheNetwork && TheGlobalData->m_saveStats) { GameInfo *game = NULL; @@ -1593,7 +1603,17 @@ AsciiString RecorderClass::getLastReplayFileName() } } #endif - return AsciiString(lastReplayFileName); + + AsciiString filename; + if (rts::ClientInstance::getInstanceId() > 1u) + { + filename.format("%s_Instance%.2u", lastReplayFileName, rts::ClientInstance::getInstanceId()); + } + else + { + filename = lastReplayFileName; + } + return filename; } /** diff --git a/Generals/Code/GameEngine/Source/Common/StateMachine.cpp b/Generals/Code/GameEngine/Source/Common/StateMachine.cpp index f8df862b8c..7189447f34 100644 --- a/Generals/Code/GameEngine/Source/Common/StateMachine.cpp +++ b/Generals/Code/GameEngine/Source/Common/StateMachine.cpp @@ -37,8 +37,9 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... + //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif @@ -89,6 +90,24 @@ class StIncrementer --num; } }; +#ifdef STATE_MACHINE_DEBUG +//----------------------------------------------------------------------------- +std::vector * State::getTransitions( void ) +{ + std::vector *ids = new std::vector; + ids->push_back(m_successStateID); + ids->push_back(m_failureStateID); + // check transition condition list + if (!m_transitions.empty()) + { + for(std::vector::const_iterator it = m_transitions.begin(); it != m_transitions.end(); ++it) + { + ids->push_back(it->toStateID); + } + } + return ids; +} +#endif //----------------------------------------------------------------------------- /** @@ -637,6 +656,61 @@ StateReturnType StateMachine::internalSetState( StateID newStateID ) */ StateReturnType StateMachine::initDefaultState() { +#ifdef DEBUG_LOGGING +#ifdef STATE_MACHINE_DEBUG +#define REALLY_VERBOSE_LOG(x) /* */ + // Run through all the transitions and make sure there aren't any transitions to undefined states. jba. [8/18/2003] + std::map::iterator i; + REALLY_VERBOSE_LOG(("SM_BEGIN\n")); + for( i = m_stateMap.begin(); i != m_stateMap.end(); ++i ) { + State *state = (*i).second; + StateID id = state->getID(); + // Check transitions. [8/18/2003] + std::vector *ids = state->getTransitions(); + // check transitions + REALLY_VERBOSE_LOG(("State %s(%d) : ", state->getName().str(), id)); + if (!ids->empty()) + { + for(std::vector::const_iterator it = ids->begin(); it != ids->end(); ++it) + { + StateID curID = *it; + REALLY_VERBOSE_LOG(("%d('", curID)); + if (curID == INVALID_STATE_ID) { + REALLY_VERBOSE_LOG(("INVALID_STATE_ID', ")); + continue; + } + if (curID == EXIT_MACHINE_WITH_SUCCESS) { + REALLY_VERBOSE_LOG(("EXIT_MACHINE_WITH_SUCCESS', ")); + continue; + } + if (curID == EXIT_MACHINE_WITH_FAILURE) { + REALLY_VERBOSE_LOG(("EXIT_MACHINE_WITH_FAILURE', ")); + continue; + } + // locate the actual state associated with the given ID + std::map::iterator i; + i = m_stateMap.find( curID ); + + if (i == m_stateMap.end()) { + DEBUG_LOG(("\nState %s(%d) : ", state->getName().str(), id)); + DEBUG_LOG(("Transition %d not found\n", curID)); + DEBUG_LOG(("This MUST BE FIXED!!!jba\n")); + DEBUG_CRASH(("Invalid transition.")); + } else { + State *st = (*i).second; + if (st->getName().isNotEmpty()) { + REALLY_VERBOSE_LOG(("%s') ", st->getName().str())); + } + } + } + } + REALLY_VERBOSE_LOG(("\n")); + delete ids; + ids = NULL; + } + REALLY_VERBOSE_LOG(("SM_END\n\n")); +#endif +#endif DEBUG_ASSERTCRASH(!m_locked, ("Machine is locked here, but probably should not be")); if (m_defaultStateInited) { @@ -757,7 +831,7 @@ void StateMachine::xfer( Xfer *xfer ) } Bool snapshotAllStates = false; -#ifdef _DEBUG +#ifdef RTS_DEBUG //snapshotAllStates = true; #endif xfer->xferBool(&snapshotAllStates); diff --git a/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp b/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp index 6cf1197959..ed8acf1492 100644 --- a/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp +++ b/Generals/Code/GameEngine/Source/Common/StatsCollector.cpp @@ -108,7 +108,7 @@ void StatsCollector::reset( void ) { // make sure we have a stats Dir. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { AsciiString playtestDir = TheGlobalData->m_baseStatsDir; @@ -254,7 +254,7 @@ void StatsCollector::writeFileEnd( void ) fprintf(f, "===================================================\n"); fprintf(f, "* Times are in Game Seconds which are based off of frames. Current fps is set to %d\n", LOGICFRAMES_PER_SECOND); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_benchmarkTimer > 0) { fprintf(f, "\n*** BENCHMARK MODE STATS ***\n"); @@ -322,7 +322,7 @@ void StatsCollector::createFileName( void ) name.removeLastChar(); // m name.removeLastChar(); // . m_statsFileName.clear(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { m_statsFileName.set(TheGlobalData->m_baseStatsDir); diff --git a/Generals/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp b/Generals/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp index 7ac3a236b2..2b94283ef6 100644 --- a/Generals/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp @@ -51,7 +51,7 @@ #include "Common/AsciiString.h" #include "Common/PerfTimer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/AsciiString.cpp b/Generals/Code/GameEngine/Source/Common/System/AsciiString.cpp index 7b56859716..255f8c6282 100644 --- a/Generals/Code/GameEngine/Source/Common/System/AsciiString.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/AsciiString.cpp @@ -93,7 +93,7 @@ AsciiString::AsciiString(const AsciiString& stringSrc) : m_data(stringSrc.m_data } // ----------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void AsciiString::validate() const { if (!m_data) return; @@ -146,7 +146,7 @@ void AsciiString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveData AsciiStringData* newData = (AsciiStringData*)TheDynamicMemoryAllocator->allocateBytesDoNotZero(actualBytes, "STR_AsciiString::ensureUniqueBufferOfSize"); newData->m_refCount = 1; newData->m_numCharsAllocated = (actualBytes - sizeof(AsciiStringData))/sizeof(char); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) newData->m_debugptr = newData->peek(); // just makes it easier to read in the debugger #endif @@ -371,12 +371,7 @@ void AsciiString::format(const char* format, ...) // ----------------------------------------------------- void AsciiString::format_va(const AsciiString& format, va_list args) { - validate(); - char buf[MAX_FORMAT_BUF_LEN]; - if (_vsnprintf(buf, sizeof(buf)/sizeof(char)-1, format.str(), args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + format_va(format.str(), args); } // ----------------------------------------------------- @@ -384,10 +379,16 @@ void AsciiString::format_va(const char* format, va_list args) { validate(); char buf[MAX_FORMAT_BUF_LEN]; - if (_vsnprintf(buf, sizeof(buf)/sizeof(char)-1, format, args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + const int result = _vsnprintf(buf, sizeof(buf)/sizeof(char)-1, format, args); + if (result >= 0) + { + set(buf); + validate(); + } + else + { + DEBUG_ASSERTCRASH(false, ("AsciiString::format_va failed with code:%d format:\"%s\"", result, format)); + } } // ----------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/Common/System/BuildAssistant.cpp b/Generals/Code/GameEngine/Source/Common/System/BuildAssistant.cpp index 9024ae88d5..e0adfad4dc 100644 --- a/Generals/Code/GameEngine/Source/Common/System/BuildAssistant.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/BuildAssistant.cpp @@ -59,7 +59,7 @@ // PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// BuildAssistant *TheBuildAssistant = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/CopyProtection.cpp b/Generals/Code/GameEngine/Source/Common/System/CopyProtection.cpp index b4777877d5..0af60e1e78 100644 --- a/Generals/Code/GameEngine/Source/Common/System/CopyProtection.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/CopyProtection.cpp @@ -50,7 +50,7 @@ static const char* const protectGUID = "7BEB9006-CC19-4aca-913A-C870A88DE01A"; // Generals Protect GUID */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool skipProtection(void) { //return FALSE; @@ -79,7 +79,7 @@ Bool CopyProtect::isLauncherRunning(void) } DEBUG_LOG(("result was %d\n", (int)isRunning)); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (skipProtection()) { DEBUG_LOG(("DevStudio is running - forcing to TRUE\n")); @@ -95,7 +95,7 @@ Bool CopyProtect::notifyLauncher(void) { DEBUG_LOG(("COPYPROTECTION - Notify launcher\n")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (skipProtection()) { DEBUG_LOG(("DevStudio is running - skipping notifyLauncher()\n")); @@ -207,7 +207,7 @@ Bool CopyProtect::validate(void) "Play the \"Command & Conquer: Generals\" Multiplayer Test.") == 0); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (skipProtection()) { DEBUG_LOG(("DevStudio is running - forcing to TRUE\n")); diff --git a/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp b/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp index 8dd1fb5b16..3db41183b2 100644 --- a/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/DataChunk.cpp @@ -368,6 +368,16 @@ void DataChunkOutput::writeUnicodeString( UnicodeString theString ) ::fwrite( theString.str(), len*sizeof(WideChar) , 1, m_tmp_file ); } +void DataChunkOutput::writeNameKey( const NameKeyType key ) +{ + AsciiString kname = TheNameKeyGenerator->keyToName(key); + Int keyAndType = m_contents.allocateID(kname); + keyAndType <<= 8; + Dict::DataType t = Dict::DICT_ASCIISTRING; + keyAndType |= (t & 0xff); + writeInt(keyAndType); +} + void DataChunkOutput::writeDict( const Dict& d ) { UnsignedShort len = d.getPairCount(); @@ -880,6 +890,20 @@ void DataChunkInput::readArrayOfBytes(char *ptr, Int len) decrementDataLeft( len ); } +NameKeyType DataChunkInput::readNameKey(void) +{ + Int keyAndType = readInt(); +#ifdef DEBUG_CRASHING + Dict::DataType t = (Dict::DataType)(keyAndType & 0xff); + DEBUG_ASSERTCRASH(t==Dict::DICT_ASCIISTRING,("Invalid key data.")); +#endif + keyAndType >>= 8; + + AsciiString kname = m_contents.getName(keyAndType); + NameKeyType k = TheNameKeyGenerator->nameToKey(kname); + return k; +} + Dict DataChunkInput::readDict() { UnsignedShort len; diff --git a/Generals/Code/GameEngine/Source/Common/System/Debug.cpp b/Generals/Code/GameEngine/Source/Common/System/Debug.cpp index caa3ce37cb..96054018cf 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Debug.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Debug.cpp @@ -46,15 +46,24 @@ #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -// USER INCLUDES +// USER INCLUDES + +// TheSuperHackers @feature helmutbuhler 04/10/2025 +// Uncomment this to show normal logging stuff in the crc logging. +// This can be helpful for context, but can also clutter diffs because normal logs aren't necessarily +// deterministic or the same on all peers in multiplayer games. +//#define INCLUDE_DEBUG_LOG_IN_CRC_LOG + #define DEBUG_THREADSAFE #ifdef DEBUG_THREADSAFE #include "Common/CriticalSection.h" #endif #include "Common/Debug.h" +#include "Common/CRCDebug.h" #include "Common/Registry.h" #include "Common/SystemInfo.h" #include "Common/UnicodeString.h" +#include "GameClient/ClientInstance.h" #include "GameClient/GameText.h" #include "GameClient/Keyboard.h" #include "GameClient/Mouse.h" @@ -66,7 +75,7 @@ extern HWND ApplicationHWnd; extern const char *gAppPrefix; /// So WB can have a different log file name. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // this should ALWAYS be present #pragma optimize("", off) #endif @@ -77,15 +86,15 @@ extern const char *gAppPrefix; /// So WB can have a different log file name. #ifdef DEBUG_LOGGING -#if defined(_INTERNAL) - #define DEBUG_FILE_NAME "DebugLogFileI.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevI.txt" -#elif defined(_DEBUG) - #define DEBUG_FILE_NAME "DebugLogFileD.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevD.txt" +#if defined(RTS_INTERNAL) + #define DEBUG_FILE_NAME "DebugLogFileI" + #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevI" +#elif defined(RTS_DEBUG) + #define DEBUG_FILE_NAME "DebugLogFileD" + #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevD" #else - #define DEBUG_FILE_NAME "DebugLogFile.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrev.txt" + #define DEBUG_FILE_NAME "DebugLogFile" + #define DEBUG_FILE_NAME_PREV "DebugLogFilePrev" #endif #endif @@ -97,8 +106,12 @@ extern const char *gAppPrefix; /// So WB can have a different log file name. // ---------------------------------------------------------------------------- // PRIVATE DATA // ---------------------------------------------------------------------------- +// TheSuperHackers @info Must not use static RAII types when set in DebugInit, +// because DebugInit can be called during static module initialization before the main function is called. #ifdef DEBUG_LOGGING static FILE *theLogFile = NULL; +static char theLogFileName[ _MAX_PATH ]; +static char theLogFileNamePrev[ _MAX_PATH ]; #endif #define LARGE_BUFFER 8192 static char theBuffer[ LARGE_BUFFER ]; // make it big to avoid weird overflow bugs in debug mode @@ -141,7 +154,7 @@ static void doStackDump(); inline Bool ignoringAsserts() { #ifdef DEBUG_CRASHING - return !DX8Wrapper_IsWindowed || TheGlobalData->m_debugIgnoreAsserts; + return !DX8Wrapper_IsWindowed || (TheGlobalData&&TheGlobalData->m_debugIgnoreAsserts); #else return !DX8Wrapper_IsWindowed; #endif @@ -236,6 +249,10 @@ static void doLogOutput(const char *buffer) { ::OutputDebugString(buffer); } + +#ifdef INCLUDE_DEBUG_LOG_IN_CRC_LOG + addCRCDebugLineNoCounter("%s", buffer); +#endif } #endif @@ -347,6 +364,11 @@ void DebugInit(int flags) #ifdef DEBUG_LOGGING + // TheSuperHackers @info Debug initialization can happen very early. + // Therefore, initialize the client instance now. + if (!rts::ClientInstance::initialize()) + return; + char dirbuf[ _MAX_PATH ]; ::GetModuleFileName( NULL, dirbuf, sizeof( dirbuf ) ); char *pEnd = dirbuf + strlen( dirbuf ); @@ -360,22 +382,26 @@ void DebugInit(int flags) pEnd--; } - char prevbuf[ _MAX_PATH ]; - char curbuf[ _MAX_PATH ]; - - strcpy(prevbuf, dirbuf); - strcat(prevbuf, gAppPrefix); - strcat(prevbuf, DEBUG_FILE_NAME_PREV); - strcpy(curbuf, dirbuf); - strcat(curbuf, gAppPrefix); - strcat(curbuf, DEBUG_FILE_NAME); - - remove(prevbuf); - rename(curbuf, prevbuf); - theLogFile = fopen(curbuf, "w"); + strcpy(theLogFileNamePrev, dirbuf); + strcat(theLogFileNamePrev, gAppPrefix); + strcat(theLogFileNamePrev, DEBUG_FILE_NAME_PREV); + if (rts::ClientInstance::getInstanceId() > 1u) + sprintf(theLogFileNamePrev + strlen(theLogFileNamePrev), "_Instance%.2u", rts::ClientInstance::getInstanceId()); + strcat(theLogFileNamePrev, ".txt"); + + strcpy(theLogFileName, dirbuf); + strcat(theLogFileName, gAppPrefix); + strcat(theLogFileName, DEBUG_FILE_NAME); + if (rts::ClientInstance::getInstanceId() > 1u) + sprintf(theLogFileName + strlen(theLogFileName), "_Instance%.2u", rts::ClientInstance::getInstanceId()); + strcat(theLogFileName, ".txt"); + + remove(theLogFileNamePrev); + rename(theLogFileName, theLogFileNamePrev); + theLogFile = fopen(theLogFileName, "w"); if (theLogFile != NULL) { - DebugLog("Log %s opened: %s\n", curbuf, getCurrentTimeString()); + DebugLog("Log %s opened: %s\n", theLogFileName, getCurrentTimeString()); } #endif } @@ -412,6 +438,17 @@ void DebugLog(const char *format, ...) whackFunnyCharacters(theBuffer); doLogOutput(theBuffer); } + +const char* DebugGetLogFileName() +{ + return theLogFileName; +} + +const char* DebugGetLogFileNamePrev() +{ + return theLogFileNamePrev; +} + #endif // ---------------------------------------------------------------------------- @@ -468,7 +505,7 @@ void DebugCrash(const char *format, ...) doLogOutput(theCrashBuffer); #endif #ifdef DEBUG_STACKTRACE - if (!TheGlobalData->m_debugIgnoreStackTrace) + if (!(TheGlobalData && TheGlobalData->m_debugIgnoreStackTrace)) { doStackDump(); } @@ -663,6 +700,10 @@ void ReleaseCrash(const char *reason) char prevbuf[ _MAX_PATH ]; char curbuf[ _MAX_PATH ]; + if (TheGlobalData==NULL) { + return; // We are shutting down, and TheGlobalData has been freed. jba. [4/15/2003] + } + strcpy(prevbuf, TheGlobalData->getPath_UserData().str()); strcat(prevbuf, RELEASECRASH_FILE_NAME_PREV); strcpy(curbuf, TheGlobalData->getPath_UserData().str()); @@ -693,7 +734,7 @@ void ReleaseCrash(const char *reason) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /* static */ char buff[8192]; // not so static so we can be threadsafe _snprintf(buff, 8192, "Sorry, a serious error occurred. (%s)", reason); buff[8191] = 0; diff --git a/Generals/Code/GameEngine/Source/Common/System/GameCommon.cpp b/Generals/Code/GameEngine/Source/Common/System/GameCommon.cpp index c60f22e80b..e85783ad91 100644 --- a/Generals/Code/GameEngine/Source/Common/System/GameCommon.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/GameCommon.cpp @@ -51,7 +51,7 @@ const char *TheRelationshipNames[] = Real normalizeAngle(Real angle) { DEBUG_ASSERTCRASH(!_isnan(angle), ("Angle is NAN in normalizeAngle!\n")); - + if( _isnan(angle) ) return 0;// ARGH!!!! Don't assert and then not handle it! Error bad! Fix error! diff --git a/Generals/Code/GameEngine/Source/Common/System/GameMemory.cpp b/Generals/Code/GameEngine/Source/Common/System/GameMemory.cpp index 6ac1cb3624..6c41901e8c 100644 --- a/Generals/Code/GameEngine/Source/Common/System/GameMemory.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/GameMemory.cpp @@ -64,7 +64,7 @@ DECLARE_PERF_TIMER(MemoryPoolDebugging) DECLARE_PERF_TIMER(MemoryPoolInitFilling) #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -113,7 +113,7 @@ DECLARE_PERF_TIMER(MemoryPoolInitFilling) }; // in debug mode (but not internal), save stacktraces too - #if !defined(MEMORYPOOL_CHECKPOINTING) && defined(MEMORYPOOL_STACKTRACE) && defined(_DEBUG) + #if !defined(MEMORYPOOL_CHECKPOINTING) && defined(MEMORYPOOL_STACKTRACE) && defined(RTS_DEBUG) #define MEMORYPOOL_SINGLEBLOCK_GETS_STACKTRACE #endif diff --git a/Generals/Code/GameEngine/Source/Common/System/Geometry.cpp b/Generals/Code/GameEngine/Source/Common/System/Geometry.cpp index ecff9259c9..7e16c3b378 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Geometry.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Geometry.cpp @@ -36,7 +36,7 @@ #include "Common/RandomValue.h" #include "Common/Xfer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -420,6 +420,53 @@ void GeometryInfo::makeRandomOffsetWithinFootprint(Coord3D& pt) const }; } +//============================================================================= +void GeometryInfo::makeRandomOffsetOnPerimeter(Coord3D& pt) const +{ + switch(m_type) + { + case GEOMETRY_SPHERE: + case GEOMETRY_CYLINDER: + { + DEBUG_CRASH( ("GeometryInfo::makeRandomOffsetOnPerimeter() not implemented for SPHERE or CYLINDER extents. Using position.") ); + + //Kris: Did not have time nor need to support non-box extents. I added this feature for script placement + // of boobytraps. + pt.x = 0.0f; + pt.y = 0.0f; + break; + } + + case GEOMETRY_BOX: + { + if( GameLogicRandomValueReal( 0.0f, 1.0f ) < 0.5f ) + { + //Pick random point on x axis. + pt.x = GameLogicRandomValueReal(-m_majorRadius, m_majorRadius); + + //Min or max the y axis value + if( GameLogicRandomValueReal( 0.0f, 1.0f ) < 0.5f ) + pt.y = -m_minorRadius; + else + pt.y = m_minorRadius; + } + else + { + //Pick random point on y axis. + pt.y = GameLogicRandomValueReal(-m_minorRadius, m_minorRadius); + + //Min or max the x axis value + if( GameLogicRandomValueReal( 0.0f, 1.0f ) < 0.5f ) + pt.x = -m_majorRadius; + else + pt.x = m_majorRadius; + } + pt.z = 0.0f; + break; + } + }; +} + //============================================================================= Real GeometryInfo::getFootprintArea() const { @@ -471,7 +518,7 @@ void GeometryInfo::calcBoundingStuff() }; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= void GeometryInfo::tweakExtents(ExtentModType extentModType, Real extentModAmount) { @@ -495,7 +542,7 @@ void GeometryInfo::tweakExtents(ExtentModType extentModType, Real extentModAmoun } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= AsciiString GeometryInfo::getDescriptiveString() const { diff --git a/Generals/Code/GameEngine/Source/Common/System/LocalFile.cpp b/Generals/Code/GameEngine/Source/Common/System/LocalFile.cpp index ab53a29211..f379ba32a7 100644 --- a/Generals/Code/GameEngine/Source/Common/System/LocalFile.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/LocalFile.cpp @@ -61,7 +61,7 @@ #include "Common/PerfTimer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/MemoryInit.cpp b/Generals/Code/GameEngine/Source/Common/System/MemoryInit.cpp index 6798a26f36..79077b33f3 100644 --- a/Generals/Code/GameEngine/Source/Common/System/MemoryInit.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/MemoryInit.cpp @@ -49,7 +49,7 @@ #include "Lib/BaseType.h" #include "Common/GameMemory.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/Radar.cpp b/Generals/Code/GameEngine/Source/Common/System/Radar.cpp index c7865df79c..8fb9c069a3 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Radar.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Radar.cpp @@ -53,7 +53,7 @@ #include "GameLogic/Module/ContainModule.h" #include "GameLogic/Module/StealthUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -426,8 +426,7 @@ void Radar::addObject( Object *obj ) //Because we have support for disguised units pretending to be units from another //team, we need to intercept it here and make sure it's rendered appropriately //based on which client is rendering it. - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate *update = (StealthUpdate*)obj->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = obj->getStealth(); if( update ) { if( update->isDisguised() ) @@ -615,11 +614,11 @@ void Radar::removeObject( Object *obj ) //------------------------------------------------------------------------------------------------- /** Translate a 2D spot on the radar (from (0,0) to (RADAR_CELL_WIDTH,RADAR_CELL_HEIGHT) - * to a 3D spot in the world on the terrain + * to a 3D spot in the world. Does not determine Z value! * Return TRUE if the radar points translates to a valid world position * Return FALSE if the radar point is not a valid world position */ //------------------------------------------------------------------------------------------------- -Bool Radar::radarToWorld( const ICoord2D *radar, Coord3D *world ) +Bool Radar::radarToWorld2D( const ICoord2D *radar, Coord3D *world ) { Int x, y; @@ -644,6 +643,19 @@ Bool Radar::radarToWorld( const ICoord2D *radar, Coord3D *world ) // translate to world world->x = x * m_xSample; world->y = y * m_ySample; + return TRUE; +} + +//------------------------------------------------------------------------------------------------- +/** Translate a 2D spot on the radar (from (0,0) to (RADAR_CELL_WIDTH,RADAR_CELL_HEIGHT) + * to a 3D spot in the world on the terrain + * Return TRUE if the radar points translates to a valid world position + * Return FALSE if the radar point is not a valid world position */ +//------------------------------------------------------------------------------------------------- +Bool Radar::radarToWorld( const ICoord2D *radar, Coord3D *world ) +{ + if (!radarToWorld2D(radar,world)) + return FALSE; // find the terrain height here world->z = TheTerrainLogic->getGroundHeight( world->x, world->y ); @@ -1242,8 +1254,15 @@ void Radar::tryUnderAttackEvent( const Object *obj ) // ------------------------------------------------------------------------------------------------ void Radar::tryInfiltrationEvent( const Object *obj ) { + + //Sanity! + if( !obj ) + { + return; + } + // We should only be warned against infiltrations that are taking place against us. - if (obj->getControllingPlayer() != ThePlayerList->getLocalPlayer()) + if( obj->getControllingPlayer() != ThePlayerList->getLocalPlayer() ) return; // create the radar event diff --git a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp index f321a01bb0..7e68d12f0c 100644 --- a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp @@ -59,7 +59,7 @@ #include "GameLogic/SidesList.h" #include "GameLogic/TerrainLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp index 0625d7e74b..2ca950c46c 100644 --- a/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp @@ -43,7 +43,7 @@ // GLOBALS //////////////////////////////////////////////////////////////////////////////////////// GameStateMap *TheGameStateMap = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/StackDump.cpp b/Generals/Code/GameEngine/Source/Common/System/StackDump.cpp index 1450537656..1c0a319e14 100644 --- a/Generals/Code/GameEngine/Source/Common/System/StackDump.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/StackDump.cpp @@ -24,7 +24,7 @@ #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#if defined(_DEBUG) || defined(_INTERNAL) || defined(IG_DEBUG_STACKTRACE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(IG_DEBUG_STACKTRACE) #pragma pack(push, 8) diff --git a/Generals/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp b/Generals/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp index 60d0777a15..93b247f846 100644 --- a/Generals/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp @@ -29,7 +29,7 @@ #include "Common/SubsystemInterface.h" #include "Common/Xfer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/System/UnicodeString.cpp b/Generals/Code/GameEngine/Source/Common/System/UnicodeString.cpp index 4ae1104266..1f8aa59a14 100644 --- a/Generals/Code/GameEngine/Source/Common/System/UnicodeString.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/UnicodeString.cpp @@ -46,7 +46,7 @@ #include "Common/CriticalSection.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -57,7 +57,7 @@ /*static*/ UnicodeString UnicodeString::TheEmptyString; // ----------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void UnicodeString::validate() const { if (!m_data) return; @@ -102,7 +102,7 @@ void UnicodeString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveDa UnicodeStringData* newData = (UnicodeStringData*)TheDynamicMemoryAllocator->allocateBytesDoNotZero(actualBytes, "STR_UnicodeString::ensureUniqueBufferOfSize"); newData->m_refCount = 1; newData->m_numCharsAllocated = (actualBytes - sizeof(UnicodeStringData))/sizeof(WideChar); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) newData->m_debugptr = newData->peek(); // just makes it easier to read in the debugger #endif @@ -308,12 +308,7 @@ void UnicodeString::format(const WideChar* format, ...) // ----------------------------------------------------- void UnicodeString::format_va(const UnicodeString& format, va_list args) { - validate(); - WideChar buf[MAX_FORMAT_BUF_LEN]; - if (_vsnwprintf(buf, sizeof(buf)/sizeof(WideChar)-1, format.str(), args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + format_va(format.str(), args); } // ----------------------------------------------------- @@ -321,10 +316,16 @@ void UnicodeString::format_va(const WideChar* format, va_list args) { validate(); WideChar buf[MAX_FORMAT_BUF_LEN]; - if (_vsnwprintf(buf, sizeof(buf)/sizeof(WideChar)-1, format, args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + const int result = _vsnwprintf(buf, sizeof(buf)/sizeof(WideChar)-1, format, args); + if (result >= 0) + { + set(buf); + validate(); + } + else + { + DEBUG_ASSERTCRASH(false, ("UnicodeString::format_va failed with code:%d", result)); + } } //----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp index 9a93b83749..e8a6c8141c 100644 --- a/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -155,7 +155,7 @@ UpgradeTemplate::~UpgradeTemplate( void ) //------------------------------------------------------------------------------------------------- Int UpgradeTemplate::calcTimeToBuild( Player *player ) const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( player->buildsInstantly() ) { return 1; diff --git a/Generals/Code/GameEngine/Source/Common/System/Xfer.cpp b/Generals/Code/GameEngine/Source/Common/System/Xfer.cpp deleted file mode 100644 index f90994b4e3..0000000000 --- a/Generals/Code/GameEngine/Source/Common/System/Xfer.cpp +++ /dev/null @@ -1,802 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Xfer.cpp ///////////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: The Xfer system is capable of setting up operations to work with blocks of data -// from other subsystems. It can work things such as file reading, file writing, -// CRC computations etc -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#include "Common/Upgrade.h" -#include "Common/GameState.h" -#include "Common/Xfer.h" -#include "Common/BitFlagsIO.h" - -#ifdef _INTERNAL -// for occasional debugging... -//#pragma optimize("", off) -//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") -#endif - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -Xfer::Xfer( void ) -{ - - m_options = XO_NONE; - m_xferMode = XFER_INVALID; - -} // end Xfer - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -Xfer::~Xfer( void ) -{ - -} // end ~Xfer - -// ------------------------------------------------------------------------------------------------ -/** Open */ -// ------------------------------------------------------------------------------------------------ -void Xfer::open( AsciiString identifier ) -{ - - // save identifier - m_identifier = identifier; - -} // end open - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferByte( Byte *byteData ) -{ - - xferImplementation( byteData, sizeof( Byte ) ); - -} // end xferByte - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferVersion( XferVersion *versionData, XferVersion currentVersion ) -{ - - xferImplementation( versionData, sizeof( XferVersion ) ); - - // sanity, after the xfer, version data is never allowed to be higher than the current version - if( *versionData > currentVersion ) - { - - DEBUG_CRASH(( "XferVersion - Unknown version '%d' should be no higher than '%d'\n", - *versionData, currentVersion )); - throw XFER_INVALID_VERSION; - - } // end if - -} // end xferVersion - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferUnsignedByte( UnsignedByte *unsignedByteData ) -{ - - xferImplementation( unsignedByteData, sizeof( UnsignedByte ) ); - -} // end xferUnsignedByte - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferBool( Bool *boolData ) -{ - - xferImplementation( boolData, sizeof( Bool ) ); - -} // end xferBool - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferInt( Int *intData ) -{ - - xferImplementation( intData, sizeof( Int ) ); - -} // end xferInt - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferInt64( Int64 *int64Data ) -{ - - xferImplementation( int64Data, sizeof( Int64 ) ); - -} // end xferInt64 - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferUnsignedInt( UnsignedInt *unsignedIntData ) -{ - - xferImplementation( unsignedIntData, sizeof( UnsignedInt ) ); - -} // end xferUnsignedInt - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferShort( Short *shortData ) -{ - - xferImplementation( shortData, sizeof( Short ) ); - -} // end xferShort - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferUnsignedShort( UnsignedShort *unsignedShortData ) -{ - - xferImplementation( unsignedShortData, sizeof( UnsignedShort ) ); - -} // end xferUnsignedShort - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferReal( Real *realData ) -{ - - xferImplementation( realData, sizeof( Real ) ); - -} // end xferReal - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferMapName( AsciiString *mapNameData ) -{ - if (getXferMode() == XFER_SAVE) - { - AsciiString tmp = TheGameState->realMapPathToPortableMapPath(*mapNameData); - xferAsciiString(&tmp); - } - else if (getXferMode() == XFER_LOAD) - { - xferAsciiString(mapNameData); - *mapNameData = TheGameState->portableMapPathToRealMapPath(*mapNameData); - } -} // end xferAsciiString - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferAsciiString( AsciiString *asciiStringData ) -{ - - xferImplementation( (void *)asciiStringData->str(), sizeof( Byte ) * asciiStringData->getLength() ); - -} // end xferAsciiString - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferMarkerLabel( AsciiString asciiStringData ) -{ -} // end xferMarkerLabel - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferUnicodeString( UnicodeString *unicodeStringData ) -{ - - xferImplementation( (void *)unicodeStringData->str(), sizeof( WideChar ) * unicodeStringData->getLength() ); - -} // end xferUnicodeString - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferCoord3D( Coord3D *coord3D ) -{ - - xferReal( &coord3D->x ); - xferReal( &coord3D->y ); - xferReal( &coord3D->z ); - -} // end xferCoord3D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferICoord3D( ICoord3D *iCoord3D ) -{ - - xferInt( &iCoord3D->x ); - xferInt( &iCoord3D->y ); - xferInt( &iCoord3D->z ); - -} // end xferICoor3D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferRegion3D( Region3D *region3D ) -{ - - xferCoord3D( ®ion3D->lo ); - xferCoord3D( ®ion3D->hi ); - -} // end xferRegion3D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferIRegion3D( IRegion3D *iRegion3D ) -{ - - xferICoord3D( &iRegion3D->lo ); - xferICoord3D( &iRegion3D->hi ); - -} // end xferIRegion3D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferCoord2D( Coord2D *coord2D ) -{ - - xferReal( &coord2D->x ); - xferReal( &coord2D->y ); - -} // end xferCoord2D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferICoord2D( ICoord2D *iCoord2D ) -{ - - xferInt( &iCoord2D->x ); - xferInt( &iCoord2D->y ); - -} // end xferICoord2D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferRegion2D( Region2D *region2D ) -{ - - xferCoord2D( ®ion2D->lo ); - xferCoord2D( ®ion2D->hi ); - -} // end xferRegion2D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferIRegion2D( IRegion2D *iRegion2D ) -{ - - xferICoord2D( &iRegion2D->lo ); - xferICoord2D( &iRegion2D->hi ); - -} // end xferIRegion2D - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferRealRange( RealRange *realRange ) -{ - - xferReal( &realRange->lo ); - xferReal( &realRange->hi ); - -} // end xferRealRange - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferColor( Color *color ) -{ - - xferImplementation( color, sizeof( Color ) ); - -} // end xferColor - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferRGBColor( RGBColor *rgbColor ) -{ - - xferReal( &rgbColor->red ); - xferReal( &rgbColor->green ); - xferReal( &rgbColor->blue ); - -} // end xferRGBColor - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferRGBAColorReal( RGBAColorReal *rgbaColorReal ) -{ - - xferReal( &rgbaColorReal->red ); - xferReal( &rgbaColorReal->green ); - xferReal( &rgbaColorReal->blue ); - xferReal( &rgbaColorReal->alpha ); - -} // end xferRGBAColorReal - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferRGBAColorInt( RGBAColorInt *rgbaColorInt ) -{ - - xferUnsignedInt( &rgbaColorInt->red ); - xferUnsignedInt( &rgbaColorInt->green ); - xferUnsignedInt( &rgbaColorInt->blue ); - xferUnsignedInt( &rgbaColorInt->alpha ); - -} // end xferRGBAColorInt - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferObjectID( ObjectID *objectID ) -{ - - xferImplementation( objectID, sizeof( ObjectID ) ); - -} // end xferObjeftID - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferDrawableID( DrawableID *drawableID ) -{ - - xferImplementation( drawableID, sizeof( DrawableID ) ); - -} // end xferDrawableID - -// ------------------------------------------------------------------------------------------------ -/** STL Object ID list (cause it's a common data structure we use a lot) - * Version Info; - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferSTLObjectIDList( std::list< ObjectID > *objectIDListData ) -{ - - // - // the fact that this is a list and a little higher level than a simple data type - // is reason enough to have every one of these versioned - // - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xferVersion( &version, currentVersion ); - - // xfer the count of the list - UnsignedShort listCount = objectIDListData->size(); - xferUnsignedShort( &listCount ); - - // xfer list data - ObjectID objectID; - if( getXferMode() == XFER_SAVE || getXferMode() == XFER_CRC ) - { - - // save all ids - std::list< ObjectID >::const_iterator it; - for( it = objectIDListData->begin(); it != objectIDListData->end(); ++it ) - { - - objectID = *it; - xferObjectID( &objectID ); - - } // end for - - } // end if, save - else if( getXferMode() == XFER_LOAD ) - { - - // sanity, the list should be empty before we transfer more data into it - if( objectIDListData->size() != 0 ) - { - - DEBUG_CRASH(( "Xfer::xferSTLObjectIDList - object list should be empty before loading\n" )); - throw XFER_LIST_NOT_EMPTY; - - } // end if - - // read all ids - for( UnsignedShort i = 0; i < listCount; ++i ) - { - - xferObjectID( &objectID ); - objectIDListData->push_back( objectID ); - - } // end for, i - - } // end else if - else - { - - DEBUG_CRASH(( "xferSTLObjectIDList - Unknown xfer mode '%d'\n", getXferMode() )); - throw XFER_MODE_UNKNOWN; - - } // end else - -} // end xferSTLObjectIDList - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferSTLIntList( std::list< Int > *intListData ) -{ - - // sanity - if( intListData == NULL ) - return; - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xferVersion( &version, currentVersion ); - - // xfer the count of the list - UnsignedShort listCount = intListData->size(); - xferUnsignedShort( &listCount ); - - // xfer list data - Int intData; - if( getXferMode() == XFER_SAVE || getXferMode() == XFER_CRC ) - { - - // save all ids - std::list< Int >::const_iterator it; - for( it = intListData->begin(); it != intListData->end(); ++it ) - { - - intData = *it; - xferInt( &intData ); - - } // end for - - } // end if, save - else if( getXferMode() == XFER_LOAD ) - { - - // sanity, the list should be empty before we transfer more data into it - if( intListData->size() != 0 ) - { - - DEBUG_CRASH(( "Xfer::xferSTLIntList - int list should be empty before loading\n" )); - throw XFER_LIST_NOT_EMPTY; - - } // end if - - // read all ids - for( UnsignedShort i = 0; i < listCount; ++i ) - { - - xferInt( &intData ); - intListData->push_back( intData ); - - } // end for, i - - } // end else if - else - { - - DEBUG_CRASH(( "xferSTLIntList - Unknown xfer mode '%d'\n", getXferMode() )); - throw XFER_MODE_UNKNOWN; - - } // end else - -} // end xferSTLIntList - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferScienceType( ScienceType *science ) -{ - - // sanity - DEBUG_ASSERTCRASH( science != NULL, ("xferScienceType - Invalid parameters\n") ); - - AsciiString scienceName; - - if( getXferMode() == XFER_SAVE ) - { - // translate to string - scienceName = TheScienceStore->getInternalNameForScience( *science ); - - // write the string - xferAsciiString( &scienceName ); - - } // end if, save - else if( getXferMode() == XFER_LOAD ) - { - xferAsciiString( &scienceName ); - - // translate to science - *science = TheScienceStore->getScienceFromInternalName( scienceName ); - if( *science == SCIENCE_INVALID ) - { - - DEBUG_CRASH(( "xferScienceType - Unknown science '%s'\n", scienceName.str() )); - throw XFER_UNKNOWN_STRING; - - } // end if - - } // end else if, load - else if( getXferMode() == XFER_CRC ) - { - xferImplementation( science, sizeof( *science ) ); - - } // end else if, crc - else - { - - DEBUG_CRASH(( "xferScienceVec - Unknown xfer mode '%d'\n", getXferMode() )); - throw XFER_MODE_UNKNOWN; - - } // end else - -} // end xferScienceType - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferScienceVec( ScienceVec *scienceVec ) -{ - - // sanity - DEBUG_ASSERTCRASH( scienceVec != NULL, ("xferScienceVec - Invalid parameters\n") ); - - // this deserves a version number - const XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xferVersion( &version, currentVersion ); - - // count of vector - UnsignedShort count = scienceVec->size(); - xferUnsignedShort( &count ); - - if( getXferMode() == XFER_SAVE ) - { - for( ScienceVec::const_iterator it = scienceVec->begin(); it != scienceVec->end(); ++it ) - { - ScienceType science = *it; - xferScienceType(&science); - } - } - else if( getXferMode() == XFER_LOAD ) - { - // vector should be empty at this point - if( scienceVec->empty() == FALSE ) - { - DEBUG_CRASH(( "xferScienceVec - vector is not empty, but should be\n" )); - throw XFER_LIST_NOT_EMPTY; - } - - for( UnsignedShort i = 0; i < count; ++i ) - { - ScienceType science; - xferScienceType(&science); - scienceVec->push_back( science ); - } - - } - else if( getXferMode() == XFER_CRC ) - { - for( ScienceVec::const_iterator it = scienceVec->begin(); it != scienceVec->end(); ++it ) - { - ScienceType science = *it; - xferImplementation( &science, sizeof( ScienceType ) ); - } // end for, it - } // end else if, crc - else - { - - DEBUG_CRASH(( "xferScienceVec - Unknown xfer mode '%d'\n", getXferMode() )); - throw XFER_MODE_UNKNOWN; - - } // end else - -} // end xferScienceVec - -// ------------------------------------------------------------------------------------------------ -/** kind of type, for load/save it is xfered as a string so we can reorder the - * kindofs if we like - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferKindOf( KindOfType *kindOfData ) -{ - - // this deserves a version number - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xferVersion( &version, currentVersion ); - - // check which type of xfer we're doing - if( getXferMode() == XFER_SAVE ) - { - - // save as an ascii string - AsciiString kindOfName = KindOfMaskType::getNameFromSingleBit(*kindOfData); - xferAsciiString( &kindOfName ); - - } // end if, save - else if( getXferMode() == XFER_LOAD ) - { - - // read ascii string from file - AsciiString kindOfName; - xferAsciiString( &kindOfName ); - - // turn kind of name into an enum value - Int bit = KindOfMaskType::getSingleBitFromName(kindOfName.str()); - if (bit != -1) - *kindOfData = (KindOfType)bit; - - } // end else if, load - else if( getXferMode() == XFER_CRC ) - { - - // just call the xfer implementation on the data values - xferImplementation( kindOfData, sizeof( KindOfType ) ); - - } // end else if, crc - else - { - - DEBUG_CRASH(( "xferKindOf - Unknown xfer mode '%d'\n", getXferMode() )); - throw XFER_MODE_UNKNOWN; - - } // end else - -} // end xferKindOf - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferUpgradeMask( UpgradeMaskType *upgradeMaskData ) -{ - - // this deserves a version number - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xferVersion( &version, currentVersion ); - - //Kris: The Upgrade system has been converted from Int64 to BitFlags. However because the - //names of upgrades are saved to preserve order reassignments (inserting a new upgrade in - //the INI file will skew the bit values), we must continue saving the names of the upgrades - //in order to recalculate the actual bit value of said upgrade. - //--------------------------------------------------------------------------------------------- - //NOTE: The xfer code didn't have to change with the bitset upgrades, because either way, we're - //converting data <-> Ascii, so the minor syntax works with the before and after code! - - // check which type of xfer we're doing - if( getXferMode() == XFER_SAVE ) - { - AsciiString upgradeName; - - // count how many bits are set in the mask - UnsignedShort count = 0; - UpgradeTemplate *upgradeTemplate; - for( upgradeTemplate = TheUpgradeCenter->firstUpgradeTemplate(); upgradeTemplate; upgradeTemplate = upgradeTemplate->friend_getNext() ) - { - // if the mask of this upgrade is set, it counts - if( upgradeMaskData->testForAll( upgradeTemplate->getUpgradeMask() ) ) - { - count++; - } - } // end for, upgradeTemplate - - // write the count - xferUnsignedShort( &count ); - - // write out the upgrades as strings - for( upgradeTemplate = TheUpgradeCenter->firstUpgradeTemplate(); upgradeTemplate; upgradeTemplate = upgradeTemplate->friend_getNext() ) - { - // if the mask of this upgrade is set, it counts - if( upgradeMaskData->testForAll( upgradeTemplate->getUpgradeMask() ) ) - { - upgradeName = upgradeTemplate->getUpgradeName(); - xferAsciiString( &upgradeName ); - } // end if - } // end for, upgradeTemplate - } // end if, save - else if( getXferMode() == XFER_LOAD ) - { - AsciiString upgradeName; - const UpgradeTemplate *upgradeTemplate; - - // how many strings are we going to read from the file - UnsignedShort count; - xferUnsignedShort( &count ); - - // zero the mask data - upgradeMaskData->clear(); - - // read all the strings and set the mask vaules - for( UnsignedShort i = 0; i < count; ++i ) - { - - // read the string - xferAsciiString( &upgradeName ); - - // find this upgrade template - upgradeTemplate = TheUpgradeCenter->findUpgrade( upgradeName ); - if( upgradeTemplate == NULL ) - { - - DEBUG_CRASH(( "Xfer::xferUpgradeMask - Unknown upgrade '%s'\n", upgradeName.str() )); - throw XFER_UNKNOWN_STRING; - - } // end if - - // set the mask data - upgradeMaskData->set( upgradeTemplate->getUpgradeMask() ); - - } // end for i - - } // end else if, load - else if( getXferMode() == XFER_CRC ) - { - - // just xfer implementation the data itself - xferImplementation( upgradeMaskData, sizeof( UpgradeMaskType ) ); - - } // end else if, crc - else - { - - DEBUG_CRASH(( "xferUpgradeMask - Unknown xfer mode '%d'\n", getXferMode() )); - throw XFER_MODE_UNKNOWN; - - } // end else - -} // end xferUpgradeMask - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferUser( void *data, Int dataSize ) -{ - - xferImplementation( data, dataSize ); - -} // end xferUser - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -void Xfer::xferMatrix3D( Matrix3D* mtx ) -{ - // this deserves a version number - const XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xferVersion( &version, currentVersion ); - - Vector4& tmp0 = (*mtx)[0]; - Vector4& tmp1 = (*mtx)[1]; - Vector4& tmp2 = (*mtx)[2]; - - xferReal(&tmp0.X); - xferReal(&tmp0.Y); - xferReal(&tmp0.Z); - xferReal(&tmp0.W); - - xferReal(&tmp1.X); - xferReal(&tmp1.Y); - xferReal(&tmp1.Z); - xferReal(&tmp1.W); - - xferReal(&tmp2.X); - xferReal(&tmp2.Y); - xferReal(&tmp2.Z); - xferReal(&tmp2.W); -} - - diff --git a/Generals/Code/GameEngine/Source/Common/System/XferCRC.cpp b/Generals/Code/GameEngine/Source/Common/System/XferCRC.cpp deleted file mode 100644 index d5a391e200..0000000000 --- a/Generals/Code/GameEngine/Source/Common/System/XferCRC.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferCRC.cpp ////////////////////////////////////////////////////////////////////////////// -// Author: Matt Campbell, February 2002 -// Desc: Xfer CRC implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine - -#include "Common/XferCRC.h" -#include "Common/XferDeepCRC.h" -#include "Common/crc.h" -#include "Common/Snapshot.h" -#include "winsock2.h" // for htonl - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -XferCRC::XferCRC( void ) -{ - - m_xferMode = XFER_CRC; - //Added By Sadullah Nader - //Initialization(s) inserted - m_crc = 0; - // -} // end XferCRC - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -XferCRC::~XferCRC( void ) -{ - -} // end ~XferCRC - -//------------------------------------------------------------------------------------------------- -/** Open file 'identifier' for writing */ -//------------------------------------------------------------------------------------------------- -void XferCRC::open( AsciiString identifier ) -{ - - // call base class - Xfer::open( identifier ); - - // initialize CRC to brand new one at zero - m_crc = 0; - -} // end open - -//------------------------------------------------------------------------------------------------- -/** Close our current file */ -//------------------------------------------------------------------------------------------------- -void XferCRC::close( void ) -{ - -} // end close - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -Int XferCRC::beginBlock( void ) -{ - - return 0; - -} // end beginBlock - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void XferCRC::endBlock( void ) -{ - -} // end endBlock - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void XferCRC::addCRC( UnsignedInt val ) -{ - int hibit; - - val = htonl(val); - - if (m_crc & 0x80000000) - { - hibit = 1; - } - else - { - hibit = 0; - } - - m_crc <<= 1; - m_crc += val; - m_crc += hibit; - -} // end addCRC - -// ------------------------------------------------------------------------------------------------ -/** Entry point for xfering a snapshot */ -// ------------------------------------------------------------------------------------------------ -void XferCRC::xferSnapshot( Snapshot *snapshot ) -{ - - if( snapshot == NULL ) - { - - return; - - } // end if - - // run the crc function of the snapshot - snapshot->crc( this ); - -} // end xferSnapshot - -//------------------------------------------------------------------------------------------------- -/** Perform a single CRC operation on the data passed in */ -//------------------------------------------------------------------------------------------------- -void XferCRC::xferImplementation( void *data, Int dataSize ) -{ - - if (!data || dataSize < 1) - { - return; - } - - const UnsignedInt *uintPtr = (const UnsignedInt *) (data); - - for (Int i=0 ; igetLength() > 16385 ) - { - - DEBUG_CRASH(( "XferSave cannot save this ascii string because it's too long. Change the size of the length header (but be sure to preserve save file compatability\n" )); - throw XFER_STRING_ERROR; - - } // end if - - // save length of string to follow - UnsignedShort len = asciiStringData->getLength(); - xferUnsignedShort( &len ); - - // save string data - if( len > 0 ) - xferUser( (void *)asciiStringData->str(), sizeof( Byte ) * len ); - -} // end xferAsciiString - -// ------------------------------------------------------------------------------------------------ -/** Save unicodee string */ -// ------------------------------------------------------------------------------------------------ -void XferDeepCRC::xferUnicodeString( UnicodeString *unicodeStringData ) -{ - - // sanity - if( unicodeStringData->getLength() > 255 ) - { - - DEBUG_CRASH(( "XferSave cannot save this unicode string because it's too long. Change the size of the length header (but be sure to preserve save file compatability\n" )); - throw XFER_STRING_ERROR; - - } // end if - - // save length of string to follow - Byte len = unicodeStringData->getLength(); - xferByte( &len ); - - // save string data - if( len > 0 ) - xferUser( (void *)unicodeStringData->str(), sizeof( WideChar ) * len ); - -} // end xferUnicodeString diff --git a/Generals/Code/GameEngine/Source/Common/System/XferLoad.cpp b/Generals/Code/GameEngine/Source/Common/System/XferLoad.cpp deleted file mode 100644 index fed6616a63..0000000000 --- a/Generals/Code/GameEngine/Source/Common/System/XferLoad.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferLoad.cpp ///////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: Xfer implemenation for loading from disk -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine -#include "Common/Debug.h" -#include "Common/GameState.h" -#include "Common/Snapshot.h" -#include "Common/XferLoad.h" - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -XferLoad::XferLoad( void ) -{ - - m_xferMode = XFER_LOAD; - m_fileFP = NULL; - -} // end XferLoad - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -XferLoad::~XferLoad( void ) -{ - - // warn the user if a file was left open - if( m_fileFP != NULL ) - { - - DEBUG_CRASH(( "Warning: Xfer file '%s' was left open\n", m_identifier.str() )); - close(); - - } // end if - -} // end ~XferLoad - -//------------------------------------------------------------------------------------------------- -/** Open file 'identifier' for reading */ -//------------------------------------------------------------------------------------------------- -void XferLoad::open( AsciiString identifier ) -{ - - // sanity, check to see if we're already open - if( m_fileFP != NULL ) - { - - DEBUG_CRASH(( "Cannot open file '%s' cause we've already got '%s' open\n", - identifier.str(), m_identifier.str() )); - throw XFER_FILE_ALREADY_OPEN; - - } // end if - - // call base class - Xfer::open( identifier ); - - // open the file - m_fileFP = fopen( identifier.str(), "rb" ); - if( m_fileFP == NULL ) - { - - DEBUG_CRASH(( "File '%s' not found\n", identifier.str() )); - throw XFER_FILE_NOT_FOUND; - - } // end if - -} // end open - -//------------------------------------------------------------------------------------------------- -/** Close our current file */ -//------------------------------------------------------------------------------------------------- -void XferLoad::close( void ) -{ - - // sanity, if we don't have an open file we can do nothing - if( m_fileFP == NULL ) - { - - DEBUG_CRASH(( "Xfer close called, but no file was open\n" )); - throw XFER_FILE_NOT_OPEN; - - } // end if - - // close the file - fclose( m_fileFP ); - m_fileFP = NULL; - - // erase the filename - m_identifier.clear(); - -} // end close - -//------------------------------------------------------------------------------------------------- -/** Read a block size descriptor from the file at the current position */ -//------------------------------------------------------------------------------------------------- -Int XferLoad::beginBlock( void ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("Xfer begin block - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - // read block size - XferBlockSize blockSize; - if( fread( &blockSize, sizeof( XferBlockSize ), 1, m_fileFP ) != 1 ) - { - - DEBUG_CRASH(( "Xfer - Error reading block size for '%s'\n", m_identifier.str() )); - return 0; - - } // end if - - // return the block size - return blockSize; - -} // end beginBlock - -// ------------------------------------------------------------------------------------------------ -/** End block ... this does nothing when reading */ -// ------------------------------------------------------------------------------------------------ -void XferLoad::endBlock( void ) -{ - -} // end endBlock - -//------------------------------------------------------------------------------------------------- -/** Skip forward 'dataSize' bytes in the file */ -//------------------------------------------------------------------------------------------------- -void XferLoad::skip( Int dataSize ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("XferLoad::skip - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - // sanity - DEBUG_ASSERTCRASH( dataSize >=0, ("XferLoad::skip - dataSize '%d' must be greater than 0\n", - dataSize) ); - - // skip datasize in the file from the current position - if( fseek( m_fileFP, dataSize, SEEK_CUR ) != 0 ) - throw XFER_SKIP_ERROR; - -} // end skip - -// ------------------------------------------------------------------------------------------------ -/** Entry point for xfering a snapshot */ -// ------------------------------------------------------------------------------------------------ -void XferLoad::xferSnapshot( Snapshot *snapshot ) -{ - - if( snapshot == NULL ) - { - - DEBUG_CRASH(( "XferLoad::xferSnapshot - Invalid parameters\n" )); - throw XFER_INVALID_PARAMETERS; - - } // end if - - // run the xfer function of the snapshot - snapshot->xfer( this ); - - // add this snapshot to the game state for later post processing if not restricted - if( BitIsSet( getOptions(), XO_NO_POST_PROCESSING ) == FALSE ) - TheGameState->addPostProcessSnapshot( snapshot ); - -} // end xferSnapshot - -// ------------------------------------------------------------------------------------------------ -/** Read string from file and store in ascii string */ -// ------------------------------------------------------------------------------------------------ -void XferLoad::xferAsciiString( AsciiString *asciiStringData ) -{ - - // read bytes of string length to follow - UnsignedByte len; - xferUnsignedByte( &len ); - - // read all the string data - const Int MAX_XFER_LOAD_STRING_BUFFER = 1024; - static Char buffer[ MAX_XFER_LOAD_STRING_BUFFER ]; - - if( len > 0 ) - xferUser( buffer, sizeof( Byte ) * len ); - buffer[ len ] = 0; // terminate - - // save into ascii string - asciiStringData->set( buffer ); - -} // end xferAsciiString - -// ------------------------------------------------------------------------------------------------ -/** Read string from file and store in unicode string */ -// ------------------------------------------------------------------------------------------------ -void XferLoad::xferUnicodeString( UnicodeString *unicodeStringData ) -{ - - // read bytes of string length to follow - UnsignedByte len; - xferUnsignedByte( &len ); - - // read all the string data - const Int MAX_XFER_LOAD_STRING_BUFFER = 1024; - static WideChar buffer[ MAX_XFER_LOAD_STRING_BUFFER ]; - - if( len > 0 ) - xferUser( buffer, sizeof( WideChar ) * len ); - buffer[ len ] = 0; // terminate - - // save into unicode string - unicodeStringData->set( buffer ); - -} // end xferUnicodeString - -//------------------------------------------------------------------------------------------------- -/** Perform the read operation */ -//------------------------------------------------------------------------------------------------- -void XferLoad::xferImplementation( void *data, Int dataSize ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("XferLoad - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - // read data from file - if( fread( data, dataSize, 1, m_fileFP ) != 1 ) - { - - DEBUG_CRASH(( "XferLoad - Error reading from file '%s'\n", m_identifier.str() )); - throw XFER_READ_ERROR; - - } // end if - -} // end xferImplementation - diff --git a/Generals/Code/GameEngine/Source/Common/System/XferSave.cpp b/Generals/Code/GameEngine/Source/Common/System/XferSave.cpp deleted file mode 100644 index 16b911b0cb..0000000000 --- a/Generals/Code/GameEngine/Source/Common/System/XferSave.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: XferSave.cpp ///////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, February 2002 -// Desc: Xfer disk write implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#include "Common/XferSave.h" -#include "Common/Snapshot.h" -#include "Common/GameMemory.h" - -// PRIVATE TYPES ////////////////////////////////////////////////////////////////////////////////// -class XferBlockData : public MemoryPoolObject -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(XferBlockData, "XferBlockData") - -public: - - XferFilePos filePos; ///< the file position of this block - XferBlockData *next; ///< next block on the stack - -}; -EMPTY_DTOR(XferBlockData) - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// PUBLIC METHDOS ///////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -XferSave::XferSave( void ) -{ - - m_xferMode = XFER_SAVE; - m_fileFP = NULL; - m_blockStack = NULL; - -} // end XferSave - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -XferSave::~XferSave( void ) -{ - - // warn the user if a file was left open - if( m_fileFP != NULL ) - { - - DEBUG_CRASH(( "Warning: Xfer file '%s' was left open\n", m_identifier.str() )); - close(); - - } // end if - - // - // the block stack should be empty, if it's not that means we started blocks but never - // called enough matching end blocks - // - if( m_blockStack != NULL ) - { - - // tell the user there is an error - DEBUG_CRASH(( "Warning: XferSave::~XferSave - m_blockStack was not NULL!\n" )); - - // delete the block stack - XferBlockData *next; - while( m_blockStack ) - { - - next = m_blockStack->next; - m_blockStack->deleteInstance(); - m_blockStack = next; - - } // end while - - } // end if - -} // end ~XferSave - -//------------------------------------------------------------------------------------------------- -/** Open file 'identifier' for writing */ -//------------------------------------------------------------------------------------------------- -void XferSave::open( AsciiString identifier ) -{ - - // sanity, check to see if we're already open - if( m_fileFP != NULL ) - { - - DEBUG_CRASH(( "Cannot open file '%s' cause we've already got '%s' open\n", - identifier.str(), m_identifier.str() )); - throw XFER_FILE_ALREADY_OPEN; - - } // end if - - // call base class - Xfer::open( identifier ); - - // open the file - m_fileFP = fopen( identifier.str(), "w+b" ); - if( m_fileFP == NULL ) - { - - DEBUG_CRASH(( "File '%s' not found\n", identifier.str() )); - throw XFER_FILE_NOT_FOUND; - - } // end if - -} // end open - -//------------------------------------------------------------------------------------------------- -/** Close our current file */ -//------------------------------------------------------------------------------------------------- -void XferSave::close( void ) -{ - - // sanity, if we don't have an open file we can do nothing - if( m_fileFP == NULL ) - { - - DEBUG_CRASH(( "Xfer close called, but no file was open\n" )); - throw XFER_FILE_NOT_OPEN; - - } // end if - - // close the file - fclose( m_fileFP ); - m_fileFP = NULL; - - // erase the filename - m_identifier.clear(); - -} // end close - -//------------------------------------------------------------------------------------------------- -/** Write a placeholder at the current location in the file and store this location - * internally. The next endBlock that is called will back up to the most recently stored - * beginBlock and write the difference in file bytes from the endBlock call to the - * location of this beginBlock. The current file position will then return to the location - * at which endBlock was called */ -//------------------------------------------------------------------------------------------------- -Int XferSave::beginBlock( void ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("Xfer begin block - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - // get the current file position so we can back up here for the next end block call - XferFilePos filePos = ftell( m_fileFP ); - - // write a placeholder - XferBlockSize blockSize = 0; - if( fwrite( &blockSize, sizeof( XferBlockSize ), 1, m_fileFP ) != 1 ) - { - - DEBUG_CRASH(( "XferSave::beginBlock - Error writing block size in '%s'\n", - m_identifier.str() )); - return XFER_WRITE_ERROR; - - } // end if - - // save this block position on the top of the "stack" - XferBlockData *top = newInstance(XferBlockData); -// impossible -- exception will be thrown (srj) -// if( top == NULL ) -// { -// -// DEBUG_CRASH(( "XferSave - Begin block, out of memory - can't save block stack data\n" )); -// return XFER_OUT_OF_MEMORY; -// -// } // end if - - top->filePos = filePos; - top->next = m_blockStack; - m_blockStack = top; - - return XFER_OK; - -} // end beginBlock - -//------------------------------------------------------------------------------------------------- -/** Do the tail end as described in beginBlock above. Back up to the last begin block, - * write the file difference from current position to the last begin position, and put - * current file position back to where it was */ -//------------------------------------------------------------------------------------------------- -void XferSave::endBlock( void ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("Xfer end block - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - // sanity, make sure we have a block started - if( m_blockStack == NULL ) - { - - DEBUG_CRASH(( "Xfer end block called, but no matching begin block was found\n" )); - throw XFER_BEGIN_END_MISMATCH; - - } // end if - - // save our current file position - XferFilePos currentFilePos = ftell( m_fileFP ); - - // pop the block descriptor off the top of the block stack - XferBlockData *top = m_blockStack; - m_blockStack = m_blockStack->next; - - // rewind the file to the block position - fseek( m_fileFP, top->filePos, SEEK_SET ); - - // write the size in bytes between the block position and what is our current file position - XferBlockSize blockSize = currentFilePos - top->filePos - sizeof( XferBlockSize ); - if( fwrite( &blockSize, sizeof( XferBlockSize ), 1, m_fileFP ) != 1 ) - { - - DEBUG_CRASH(( "Error writing block size to file '%s'\n", m_identifier.str() )); - throw XFER_WRITE_ERROR; - - } // end if - - // place the file pointer back to the current position - fseek( m_fileFP, currentFilePos, SEEK_SET ); - - // delete the block data as it's all used up now - top->deleteInstance(); - -} // end endBlock - -//------------------------------------------------------------------------------------------------- -/** Skip forward 'dataSize' bytes in the file */ -//------------------------------------------------------------------------------------------------- -void XferSave::skip( Int dataSize ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("XferSave - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - - // skip forward dataSize bytes - fseek( m_fileFP, dataSize, SEEK_CUR ); - -} // end skip - -// ------------------------------------------------------------------------------------------------ -/** Entry point for xfering a snapshot */ -// ------------------------------------------------------------------------------------------------ -void XferSave::xferSnapshot( Snapshot *snapshot ) -{ - - if( snapshot == NULL ) - { - - DEBUG_CRASH(( "XferSave::xferSnapshot - Invalid parameters\n" )); - throw XFER_INVALID_PARAMETERS; - - } // end if - - // run the xfer function of the snapshot - snapshot->xfer( this ); - -} // end xferSnapshot - -// ------------------------------------------------------------------------------------------------ -/** Save ascii string */ -// ------------------------------------------------------------------------------------------------ -void XferSave::xferAsciiString( AsciiString *asciiStringData ) -{ - - // sanity - if( asciiStringData->getLength() > 255 ) - { - - DEBUG_CRASH(( "XferSave cannot save this unicode string because it's too long. Change the size of the length header (but be sure to preserve save file compatability\n" )); - throw XFER_STRING_ERROR; - - } // end if - - // save length of string to follow - UnsignedByte len = asciiStringData->getLength(); - xferUnsignedByte( &len ); - - // save string data - if( len > 0 ) - xferUser( (void *)asciiStringData->str(), sizeof( Byte ) * len ); - -} // end xferAsciiString - -// ------------------------------------------------------------------------------------------------ -/** Save unicodee string */ -// ------------------------------------------------------------------------------------------------ -void XferSave::xferUnicodeString( UnicodeString *unicodeStringData ) -{ - - // sanity - if( unicodeStringData->getLength() > 255 ) - { - - DEBUG_CRASH(( "XferSave cannot save this unicode string because it's too long. Change the size of the length header (but be sure to preserve save file compatability\n" )); - throw XFER_STRING_ERROR; - - } // end if - - // save length of string to follow - UnsignedByte len = unicodeStringData->getLength(); - xferUnsignedByte( &len ); - - // save string data - if( len > 0 ) - xferUser( (void *)unicodeStringData->str(), sizeof( WideChar ) * len ); - -} // end xferUnicodeString - -//------------------------------------------------------------------------------------------------- -/** Perform the write operation */ -//------------------------------------------------------------------------------------------------- -void XferSave::xferImplementation( void *data, Int dataSize ) -{ - - // sanity - DEBUG_ASSERTCRASH( m_fileFP != NULL, ("XferSave - file pointer for '%s' is NULL\n", - m_identifier.str()) ); - - // write data to file - if( fwrite( data, dataSize, 1, m_fileFP ) != 1 ) - { - - DEBUG_CRASH(( "XferSave - Error writing to file '%s'\n", m_identifier.str() )); - throw XFER_WRITE_ERROR; - - } // end if - -} // end xferImplementation diff --git a/Generals/Code/GameEngine/Source/Common/System/registry.cpp b/Generals/Code/GameEngine/Source/Common/System/registry.cpp index 8e016558c4..c475d9ddfa 100644 --- a/Generals/Code/GameEngine/Source/Common/System/registry.cpp +++ b/Generals/Code/GameEngine/Source/Common/System/registry.cpp @@ -30,7 +30,7 @@ #include "Common/Registry.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/Thing/Module.cpp b/Generals/Code/GameEngine/Source/Common/Thing/Module.cpp index d77464a884..34ef9d96f6 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/Module.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/Module.cpp @@ -47,6 +47,12 @@ #include "GameLogic/Module/UpdateModule.h" #include "GameLogic/Module/UpgradeModule.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma message("************************************** WARNING, optimization disabled for debugging purposes") +#endif + /////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Generals/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp b/Generals/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp index 5804c7fe41..5402d019f6 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp @@ -259,7 +259,7 @@ ModuleFactory *TheModuleFactory = NULL; ///< the module factory singleton // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/Thing/Thing.cpp b/Generals/Code/GameEngine/Source/Common/Thing/Thing.cpp index 4940d4ca62..2ea011e384 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/Thing.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/Thing.cpp @@ -46,7 +46,7 @@ #include "Lib/trig.h" #include "GameLogic/TerrainLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -68,7 +68,7 @@ Thing::Thing( const ThingTemplate *thingTemplate ) } // end if m_template = thingTemplate; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_templateName = thingTemplate->getName(); #endif m_transform.Make_Identity(); diff --git a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index 64572047cf..16ca6f6b31 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -48,7 +48,7 @@ #include "GameClient/Drawable.h" #include "Common/INI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... ///#pragma optimize("", off) ///#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -363,7 +363,7 @@ Drawable *ThingFactory::newDrawable(const ThingTemplate *tmplate, DrawableStatus } // end newDrawableByType -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString TheThingTemplateBeingParsedName; #endif @@ -372,7 +372,7 @@ AsciiString TheThingTemplateBeingParsedName; //------------------------------------------------------------------------------------------------- /*static*/ void ThingFactory::parseObjectDefinition( INI* ini, const AsciiString& name, const AsciiString& reskinFrom ) { -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) TheThingTemplateBeingParsedName = name; #endif @@ -426,7 +426,7 @@ AsciiString TheThingTemplateBeingParsedName; thingTemplate->validate(); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) TheThingTemplateBeingParsedName.clear(); #endif } diff --git a/Generals/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp b/Generals/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp index 37cb205bad..cedcb61716 100644 --- a/Generals/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp +++ b/Generals/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp @@ -70,7 +70,7 @@ #include "GameLogic/Powers.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -299,7 +299,7 @@ void ModuleInfo::addModuleInfo(ThingTemplate *thingTemplate, // there must be a module tag present, and it must be unique across all module infos // for this thing template // -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // get module info const Nugget *nugget; @@ -688,7 +688,7 @@ void ThingTemplate::parseRemoveModule(INI *ini, void *instance, void *store, con Bool removed = self->removeModuleInfo(modToRemove, removedModuleName); if (!removed) { - DEBUG_ASSERTCRASH(removed, ("RemoveModule %s was not found for %s.\n",modToRemove, self->getName().str())); + DEBUG_ASSERTCRASH(removed, ("RemoveModule %s was not found for %s. The game will crash now!\n",modToRemove, self->getName().str())); throw INI_INVALID_DATA; } @@ -802,7 +802,7 @@ void ThingTemplate::parseArmorTemplateSet( INI* ini, void *instance, void * /*st ArmorTemplateSet ws; ws.parseArmorTemplateSet(ini); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES) { for (ArmorTemplateSetVector::const_iterator it = self->m_armorTemplateSets.begin(); it != self->m_armorTemplateSets.end(); ++it) @@ -830,7 +830,7 @@ void ThingTemplate::parseWeaponTemplateSet( INI* ini, void *instance, void * /*s WeaponTemplateSet ws; ws.parseWeaponTemplateSet(ini, self); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES) { for (WeaponTemplateSetVector::const_iterator it = self->m_weaponTemplateSets.begin(); it != self->m_weaponTemplateSets.end(); ++it) @@ -925,7 +925,7 @@ AIUpdateModuleData *ThingTemplate::friend_getAIModuleInfo(void) //------------------------------------------------------------------------------------------------- void ThingTemplate::validateAudio() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define AUDIO_TEST(y) \ if (!get##y()->getEventName().isEmpty() && get##y()->getEventName().compareNoCase("NoSound") != 0) { \ @@ -1019,7 +1019,7 @@ void ThingTemplate::validate() validateAudio(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (getName() == "DefaultThingTemplate") return; @@ -1115,6 +1115,20 @@ ThingTemplate::~ThingTemplate() void ThingTemplate::resolveNames() { Int i, j; + + //Kris: July 31, 2003 + //NOTE: Make sure that all code in this function supports caching properly. For example, + // templates can be partially overridden by map.ini files. When this happens, strings + // that have been parsed are looked up, cached, then cleared. The problem is if a string + // gets cached, but not overridden, it will be clear the next time we call this function. + // so we will want to make sure we don't NULL out cached data if the string is empty. A + // concrete example is overriding an object with prerequisites. We just override the portrait. + // So the 1st time we call this function, we get the standard template data. During this first + // call, the strings are looked up, cached, and cleared. Then we override the portrait in the + // map.ini. The next time we call this function, we look up all the strings again. The prereq + // names didn't used to check for empty strings so they would NULL out all the previous prereqs + // the object had. So be sure to make sure all string lookups don't blindly lookup things -- check + // if the string isNotEmpty first! for (i = 0; i < m_prereqInfo.size(); i++) { @@ -1385,7 +1399,7 @@ Int ThingTemplate::calcTimeToBuild( const Player* player) const Real factionModifier = 1 + player->getProductionTimeChangePercent( getName() ); buildTime *= factionModifier; -#if defined (_DEBUG) || defined (_INTERNAL) +#if defined (RTS_DEBUG) || defined (RTS_INTERNAL) if( player->buildsInstantly() ) { buildTime = 1; diff --git a/Generals/Code/GameEngine/Source/Common/UserPreferences.cpp b/Generals/Code/GameEngine/Source/Common/UserPreferences.cpp index 3c3f23cc82..a8efb383cd 100644 --- a/Generals/Code/GameEngine/Source/Common/UserPreferences.cpp +++ b/Generals/Code/GameEngine/Source/Common/UserPreferences.cpp @@ -50,7 +50,7 @@ #include "GameClient/MapUtil.h" #include "GameNetwork/GameSpy/PeerDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/Common/crc.cpp b/Generals/Code/GameEngine/Source/Common/crc.cpp index 913ddd975e..f3cbc369e2 100644 --- a/Generals/Code/GameEngine/Source/Common/crc.cpp +++ b/Generals/Code/GameEngine/Source/Common/crc.cpp @@ -28,6 +28,7 @@ #include "Common/crc.h" #include "Common/Debug.h" +#ifdef RTS_DEBUG void CRC::addCRC( UnsignedByte val ) { @@ -79,3 +80,4 @@ UnsignedInt CRC::get( void ) } // end skip +#endif diff --git a/Generals/Code/GameEngine/Source/Common/version.cpp b/Generals/Code/GameEngine/Source/Common/version.cpp index a5009c3628..fb77214457 100644 --- a/Generals/Code/GameEngine/Source/Common/version.cpp +++ b/Generals/Code/GameEngine/Source/Common/version.cpp @@ -41,7 +41,7 @@ Version::Version() m_localBuildNum = 0; m_buildUser = AsciiString("somebody"); m_buildLocation = AsciiString("somewhere"); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL m_showFullVersion = TRUE; #else m_showFullVersion = FALSE; @@ -70,15 +70,15 @@ UnsignedInt Version::getVersionNumber( void ) AsciiString Version::getAsciiVersion( void ) { AsciiString version; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (m_localBuildNum) version.format("%d.%d.%d.%d%c%c", m_major, m_minor, m_buildNum, m_localBuildNum, m_buildUser.getCharAt(0), m_buildUser.getCharAt(1)); else version.format("%d.%d.%d", m_major, m_minor, m_buildNum); -#else // defined _DEBUG || defined _INTERNAL +#else // defined RTS_DEBUG || defined RTS_INTERNAL version.format("%d.%d", m_major, m_minor); -#endif // defined _DEBUG || defined _INTERNAL +#endif // defined RTS_DEBUG || defined RTS_INTERNAL return version; } @@ -87,21 +87,21 @@ UnicodeString Version::getUnicodeVersion( void ) { UnicodeString version; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (!m_localBuildNum) version.format(TheGameText->fetch("Version:Format3").str(), m_major, m_minor, m_buildNum); else version.format(TheGameText->fetch("Version:Format4").str(), m_major, m_minor, m_buildNum, m_localBuildNum, m_buildUser.getCharAt(0), m_buildUser.getCharAt(1)); -#else // defined _DEBUG || defined _INTERNAL +#else // defined RTS_DEBUG || defined RTS_INTERNAL version.format(TheGameText->fetch("Version:Format2").str(), m_major, m_minor); -#endif // defined _DEBUG || defined _INTERNAL +#endif // defined RTS_DEBUG || defined RTS_INTERNAL -#ifdef _DEBUG +#ifdef RTS_DEBUG version.concat(UnicodeString(L" Debug")); #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL version.concat(UnicodeString(L" Internal")); #endif @@ -118,11 +118,11 @@ UnicodeString Version::getFullUnicodeVersion( void ) version.format(TheGameText->fetch("Version:Format4").str(), m_major, m_minor, m_buildNum, m_localBuildNum, m_buildUser.getCharAt(0), m_buildUser.getCharAt(1)); -#ifdef _DEBUG +#ifdef RTS_DEBUG version.concat(UnicodeString(L" Debug")); #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL version.concat(UnicodeString(L" Internal")); #endif diff --git a/Generals/Code/GameEngine/Source/GameClient/ClientInstance.cpp b/Generals/Code/GameEngine/Source/GameClient/ClientInstance.cpp new file mode 100644 index 0000000000..5b142a256c --- /dev/null +++ b/Generals/Code/GameEngine/Source/GameClient/ClientInstance.cpp @@ -0,0 +1,99 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ +#include "PreRTS.h" +#include "GameClient/ClientInstance.h" + +#define GENERALS_GUID "685EAFF2-3216-4265-B047-251C5F4B82F3" + +namespace rts +{ +HANDLE ClientInstance::s_mutexHandle = NULL; +UnsignedInt ClientInstance::s_instanceIndex = 0; + +bool ClientInstance::initialize() +{ + if (isInitialized()) + { + return true; + } + + // Create a mutex with a unique name to Generals in order to determine if our app is already running. + // WARNING: DO NOT use this number for any other application except Generals. + while (true) + { +#ifdef RTS_MULTI_INSTANCE + std::string guidStr = getFirstInstanceName(); + if (s_instanceIndex > 0u) + { + char idStr[33]; + itoa(s_instanceIndex, idStr, 10); + guidStr.push_back('-'); + guidStr.append(idStr); + } + s_mutexHandle = CreateMutex(NULL, FALSE, guidStr.c_str()); + if (GetLastError() == ERROR_ALREADY_EXISTS) + { + if (s_mutexHandle != NULL) + { + CloseHandle(s_mutexHandle); + s_mutexHandle = NULL; + } + // Try again with a new instance. + ++s_instanceIndex; + continue; + } +#else + s_mutexHandle = CreateMutex(NULL, FALSE, getFirstInstanceName()); + if (GetLastError() == ERROR_ALREADY_EXISTS) + { + if (s_mutexHandle != NULL) + { + CloseHandle(s_mutexHandle); + s_mutexHandle = NULL; + } + return false; + } +#endif + break; + } + + return true; +} + +bool ClientInstance::isInitialized() +{ + return s_mutexHandle != NULL; +} + +UnsignedInt ClientInstance::getInstanceIndex() +{ + DEBUG_ASSERTLOG(!isInitialized(), ("ClientInstance::isInitialized() failed")); + return s_instanceIndex; +} + +UnsignedInt ClientInstance::getInstanceId() +{ + return getInstanceIndex() + 1; +} + +const char* ClientInstance::getFirstInstanceName() +{ + return GENERALS_GUID; +} + +} // namespace rts diff --git a/Generals/Code/GameEngine/Source/GameClient/Color.cpp b/Generals/Code/GameEngine/Source/GameClient/Color.cpp index 4f33cdfe84..36943ff01e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Color.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Color.cpp @@ -78,6 +78,17 @@ // GameGetColorComponents ===================================================== /** Get the RGB color comonents of a color */ //============================================================================= + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + +//Put on ice until later M Lorenzen +//static UnsignedByte s_cheaterHasBeenSpied = 0; + void GameGetColorComponents( Color color, UnsignedByte *red, UnsignedByte *green, @@ -92,6 +103,25 @@ void GameGetColorComponents( Color color, } // end GameGetColorComponents +//Put on ice until later M Lorenzen +//void GameGetColorComponentsWithCheatSpy( Color color, +// UnsignedByte *red, +// UnsignedByte *green, +// UnsignedByte *blue, +// UnsignedByte *alpha ) +//{ +// +// *alpha |= (color & 0xFE000000) >> 24; // this waives the low order bit in alpha +// s_cheaterHasBeenSpied |= *alpha & (1<<0); // this records it and gets angry +// *red |= (color & 0x00FE0000) >> 16; // decoy +// s_cheaterHasBeenSpied |= *red & (1<<8); // decoy +// *green |= (color & 0x0000FE00) >> 8; // decoy +// s_cheaterHasBeenSpied |= *green & (1<<17); // decoy +// *blue |= (color & 0x000000FE) >> 0; // decoy +// s_cheaterHasBeenSpied |= *blue & (1<<25); // decoy +// +//} // end GameGetColorComponents + void GameGetColorComponentsReal( Color color, Real *red, Real *green, Real *blue, Real *alpha ) { *alpha = ((color & 0xFF000000) >> 24) / 255.0f; @@ -113,5 +143,15 @@ Color GameDarkenColor( Color color, Int percent ) g -= (g * percent / 100); b -= (b * percent / 100); +// Put on ice until later M Lorenzen +// TheWritableGlobalData->m_cheaterHasBeenSpiedIfMyLowestBitIsTrue = (r<<24) | (g<<16) | (b<<8) | s_cheaterHasBeenSpied; +// DEBUG_ASSERTCRASH( TheWritableGlobalData->m_cheaterHasBeenSpiedIfMyLowestBitIsTrue == FALSE, ("DIRTY ROTTEN CHEATER")); +// //my, but this looks like we just stored an alpha value along with rgb into the global data + + + + return GameMakeColor(r,g,b,a); -}// end GameDarkenColor \ No newline at end of file + +}// end GameDarkenColor + diff --git a/Generals/Code/GameEngine/Source/GameClient/Credits.cpp b/Generals/Code/GameEngine/Source/GameClient/Credits.cpp index 88b64cf122..c64ba754e8 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Credits.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Credits.cpp @@ -56,7 +56,7 @@ #include "GameClient/Display.h" #include "GameClient/GameText.h" #include "GameClient/GlobalLanguage.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp index 1550cae3bf..92530cee43 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -76,7 +76,7 @@ #include "GameClient/Shadow.h" #include "GameClient/GameText.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2083,7 +2083,7 @@ const AudioEventRTS& Drawable::getAmbientSoundByDamage(BodyDamageType dt) //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void Drawable::validatePos() const { const Coord3D* ourPos = getPosition(); @@ -2126,8 +2126,7 @@ void Drawable::setStealthLook(StealthLookType look) if( obj ) { //Try to get the stealthupdate module and see if the opacity value is overriden. - static NameKeyType key_StealthUpdate = NAMEKEY("StealthUpdate"); - StealthUpdate* stealth = (StealthUpdate *)obj->findUpdateModule(key_StealthUpdate); + StealthUpdate* stealth = obj->getStealth(); if( stealth ) { if( stealth->isDisguised() ) @@ -2210,7 +2209,7 @@ void Drawable::draw( View *view ) -#ifdef _DEBUG +#ifdef RTS_DEBUG validatePos(); #endif diff --git a/Generals/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp b/Generals/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp index 00930e31e2..b0ad847dc0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp @@ -43,7 +43,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/Eva.cpp b/Generals/Code/GameEngine/Source/GameClient/Eva.cpp index be519189b6..39d9c5c916 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Eva.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Eva.cpp @@ -31,7 +31,7 @@ #include "Common/PlayerList.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/FXList.cpp b/Generals/Code/GameEngine/Source/GameClient/FXList.cpp index f9cae22db4..fe09f37394 100644 --- a/Generals/Code/GameEngine/Source/GameClient/FXList.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/FXList.cpp @@ -54,7 +54,7 @@ // PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index 9209202477..5e1d32956e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -82,7 +82,7 @@ #include "GameNetwork/GameInfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -133,6 +133,36 @@ static void commandButtonTooltip(GameWindow *window, TheControlBar->showBuildTooltipLayout(window); } +/// mark the UI as dirty so the context of everything is re-evaluated +void ControlBar::markUIDirty( void ) +{ + m_UIDirty = TRUE; + +#if defined( RTS_INTERNAL ) || defined( RTS_DEBUG ) + UnsignedInt now = TheGameLogic->getFrame(); + if( now == m_lastFrameMarkedDirty ) + { + //Do nothing. + } + else if( now == m_lastFrameMarkedDirty + 1 ) + { + m_consecutiveDirtyFrames++; + } + else + { + m_consecutiveDirtyFrames = 1; + } + m_lastFrameMarkedDirty = now; + + if( m_consecutiveDirtyFrames > 20 ) + { + DEBUG_CRASH( ("Serious flaw in interface system! Either new code or INI has caused the interface to be marked dirty every frame. This problem actually causes the interface to completely lockup not allowing you to click normal game buttons.") ); + } + +#endif +} + + void ControlBar::populatePurchaseScience( Player* player ) { // TheInGameUI->deselectAllDrawables(); @@ -252,7 +282,11 @@ void ControlBar::populatePurchaseScience( Player* player ) setControlCommand( m_sciencePurchaseWindowsRank3[ i ], commandButton ); ScienceType st = SCIENCE_INVALID; - st = commandButton->getScienceVec()[ 0 ]; + ScienceVec sv = commandButton->getScienceVec(); + if (! sv.empty()) + { + st = sv[ 0 ]; + } if( player->isScienceDisabled( st ) ) { @@ -695,6 +729,41 @@ void CommandButton::copyImagesFrom( const CommandButton *button, Bool markUIDirt } } +//------------------------------------------------------------------------------------------------- +// bleah. shouldn't be const, but is. sue me. (Kris) -snork! +void CommandButton::copyButtonTextFrom( const CommandButton *button, Bool shortcutButton, Bool markUIDirtyIfChanged ) const +{ + //This function was added to change the strings when you upgrade from a DaisyCutter to a MOAB. All other special + //powers are the same. + Bool change = FALSE; + if( shortcutButton ) + { + //Not the best code, but conflicting label means shortcut label (most won't have any string specified). + if( button->getConflictingLabel().isNotEmpty() && m_textLabel.compare( button->getConflictingLabel() ) ) + { + m_textLabel = button->getConflictingLabel(); + change = TRUE; + } + } + else + { + //Copy the text from the purchase science button if it exists (most won't). + if( button->getTextLabel().isNotEmpty() && m_textLabel.compare( button->getTextLabel() ) ) + { + m_textLabel = button->getTextLabel(); + change = TRUE; + } + } + if( button->getDescriptionLabel().isNotEmpty() && m_descriptionLabel.compare( button->getDescriptionLabel() ) ) + { + m_descriptionLabel = button->getDescriptionLabel(); + change = TRUE; + } + if( markUIDirtyIfChanged && change ) + { + TheControlBar->markUIDirty(); + } +} //------------------------------------------------------------------------------------------------- /** Parse a single command button definition */ @@ -869,6 +938,11 @@ ControlBar::ControlBar( void ) m_remainingRadarAttackGlowFrames = 0; m_radarAttackGlowWindow = NULL; +#if defined( RTS_INTERNAL ) || defined( RTS_DEBUG ) + m_lastFrameMarkedDirty = 0; + m_consecutiveDirtyFrames = 0; +#endif + } // end ControlBar //------------------------------------------------------------------------------------------------- @@ -940,6 +1014,10 @@ ControlBar::~ControlBar( void ) } m_radarAttackGlowWindow = NULL; + + if (m_rightHUDCameoWindow && m_rightHUDCameoWindow->winGetUserData()) + delete m_rightHUDCameoWindow->winGetUserData(); + } // end ~ControlBar void ControlBarPopupDescriptionUpdateFunc( WindowLayout *layout, void *param ); @@ -1017,9 +1095,12 @@ void ControlBar::init( void ) id = TheNameKeyGenerator->nameToKey( windowName.str() ); m_commandWindows[ i ] = TheWindowManager->winGetWindowFromId( m_contextParent[ CP_COMMAND ], id ); - m_commandWindows[ i ]->winGetPosition(&commandPos.x, &commandPos.y); - m_commandWindows[ i ]->winGetSize(&commandSize.x, &commandSize.y); - m_commandWindows[ i ]->winSetStatus( WIN_STATUS_USE_OVERLAY_STATES ); + if (m_commandWindows[ i ]) + { + m_commandWindows[ i ]->winGetPosition(&commandPos.x, &commandPos.y); + m_commandWindows[ i ]->winGetSize(&commandSize.x, &commandSize.y); + m_commandWindows[ i ]->winSetStatus( WIN_STATUS_USE_OVERLAY_STATES ); + } // removed from multiplayer branch // windowName.format( "ControlBar.wnd:CommandMarker%02d", i + 1 ); @@ -1052,7 +1133,7 @@ void ControlBar::init( void ) m_sciencePurchaseWindowsRank3[ i ]->winSetStatus( WIN_STATUS_USE_OVERLAY_STATES ); } // end for i - for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_8; i++ ) + for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_8; i++ ) { windowName.format( "GeneralsExpPoints.wnd:ButtonRank8Number%d", i ); id = TheNameKeyGenerator->nameToKey( windowName.str() ); @@ -1933,7 +2014,10 @@ CommandSet* ControlBar::findNonConstCommandSet( const AsciiString& name ) const CommandButton *ControlBar::findCommandButton( const AsciiString& name ) { CommandButton *btn = findNonConstCommandButton(name); - btn = (CommandButton *)btn->friend_getFinalOverride(); + if( btn ) + { + btn = (CommandButton *)btn->friend_getFinalOverride(); + } return btn; } @@ -2059,7 +2143,11 @@ void ControlBar::switchToContext( ControlBarContext context, Drawable *draw ) //Clear any potentially flashing buttons! for( int i = 0; i < MAX_COMMANDS_PER_SET; i++ ) { - m_commandWindows[ i ]->winClearStatus( WIN_STATUS_FLASHING ); + // the implementation won't necessarily use the max number of windows possible + if (m_commandWindows[ i ]) + { + m_commandWindows[ i ]->winClearStatus( WIN_STATUS_FLASHING ); + } } // if there is a current selected drawable then we wil display a selection portrait if present if( draw ) @@ -2506,8 +2594,7 @@ void ControlBar::setPortraitByObject( Object *obj ) setPortraitByObject( NULL ); return; } - static NameKeyType key_StealthUpdate = NAMEKEY("StealthUpdate"); - StealthUpdate* stealth = (StealthUpdate *)obj->findUpdateModule(key_StealthUpdate); + StealthUpdate* stealth = obj->getStealth(); if( stealth && stealth->isDisguised() ) { //Fake player upgrades too! diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp index bf410c8204..1c45d02a68 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp @@ -59,7 +59,7 @@ #include "GameClient/GameWindowManager.h" #include "GameClient/GadgetPushButton.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -179,6 +179,8 @@ void ControlBar::doTransportInventoryUI( Object *transport, const CommandSet *co const CommandButton *commandButton; for( Int i = 0; i < MAX_COMMANDS_PER_SET; i++ ) { + // our implementation doesn't necessarily make use of the max possible command buttons + if (! m_commandWindows[ i ]) continue; // get command button commandButton = commandSet->getCommandButton(i); @@ -213,6 +215,9 @@ void ControlBar::doTransportInventoryUI( Object *transport, const CommandSet *co m_commandWindows[ i ]->winHide( TRUE ); } + + // is this where we set the cameos disabled when container is subdued? + // if we've counted more UI spots than the transport can hold, hide this command window if( inventoryCommandCount > transportMax ) m_commandWindows[ i ]->winHide( TRUE ); @@ -279,7 +284,10 @@ void ControlBar::populateCommand( Object *obj ) // hide all the buttons for( i = 0; i < MAX_COMMANDS_PER_SET; i++ ) - m_commandWindows[ i ]->winHide( TRUE ); + if (m_commandWindows[ i ]) + { + m_commandWindows[ i ]->winHide( TRUE ); + } // nothing left to do return; @@ -294,6 +302,8 @@ void ControlBar::populateCommand( Object *obj ) const CommandButton *commandButton; for( i = 0; i < MAX_COMMANDS_PER_SET; i++ ) { + // our implementation doesn't necessarily make use of the max possible command buttons + if (! m_commandWindows[ i ]) continue; // get command button commandButton = commandSet->getCommandButton(i); @@ -377,7 +387,7 @@ void ControlBar::populateCommand( Object *obj ) //Now we have to search through the command buttons to find a matching purchase science button. for( const CommandButton *command = m_commandButtons; command; command = command->getNext() ) { - if( command->getCommandType() == GUI_COMMAND_PURCHASE_SCIENCE ) + if( command && command->getCommandType() == GUI_COMMAND_PURCHASE_SCIENCE ) { //All purchase sciences specify a single science. if( command->getScienceVec().empty() ) @@ -732,6 +742,9 @@ void ControlBar::updateContextCommand( void ) GameWindow *win; const CommandButton *command; + // our implementation doesn't necessarily make use of the max possible command buttons + if (! m_commandWindows[ i ]) continue; + // get the window win = m_commandWindows[ i ]; @@ -1277,7 +1290,7 @@ CommandAvailability ControlBar::getCommandAvailability( const CommandButton *com } else if( SpecialAbilityUpdate *spUpdate = obj->findSpecialAbilityUpdate( command->getSpecialPowerTemplate()->getSpecialPowerType() ) ) { - if( spUpdate->isPowerCurrentlyInUse( command ) ) + if( spUpdate && spUpdate->isPowerCurrentlyInUse( command ) ) { return COMMAND_RESTRICTED; } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp index 5f585e7ddf..2347c5b799 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp @@ -56,7 +56,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ProductionUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -95,6 +95,11 @@ CBCommandStatus ControlBar::processCommandUI( GameWindow *control, { // get the command pointer from the control user data we put in the button const CommandButton *commandButton = (const CommandButton *)GadgetButtonGetData(control); + if( !commandButton ) + { + DEBUG_CRASH( ("ControlBar::processCommandUI() -- Button activated has no data. Ignoring...") ); + return CBC_COMMAND_NOT_USED; + } // sanity, we won't process messages if we have no source object, // unless we're CB_CONTEXT_PURCHASE_SCIENCE or GUI_COMMAND_SPECIAL_POWER_FROM_COMMAND_CENTER diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp index e7baa5b7f8..85eb3c63f3 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp @@ -40,7 +40,7 @@ #include "GameClient/InGameUI.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -96,7 +96,10 @@ void ControlBar::addCommonCommands( Drawable *draw, Bool firstDrawable ) { m_commonCommands[ i ] = NULL; - m_commandWindows[ i ]->winHide( TRUE ); + if (m_commandWindows[ i ]) + { + m_commandWindows[ i ]->winHide( TRUE ); + } // After Every change to the m_commandWIndows, we need to show fill in the missing blanks with the images // removed from multiplayer branch //showCommandMarkers(); @@ -118,6 +121,8 @@ void ControlBar::addCommonCommands( Drawable *draw, Bool firstDrawable ) // just add each command that is classified as a common command for( i = 0; i < MAX_COMMANDS_PER_SET; i++ ) { + // our implementation doesn't necessarily make use of the max possible command buttons + if (! m_commandWindows[ i ]) continue; // get command command = commandSet->getCommandButton(i); @@ -148,6 +153,9 @@ void ControlBar::addCommonCommands( Drawable *draw, Bool firstDrawable ) for( i = 0; i < MAX_COMMANDS_PER_SET; i++ ) { + // our implementation doesn't necessarily make use of the max possible command buttons + if (! m_commandWindows[ i ]) continue; + // get the command command = commandSet->getCommandButton(i); @@ -213,7 +221,12 @@ void ControlBar::populateMultiSelect( void ) // by default, hide all the controls in the command section for( Int i = 0; i < MAX_COMMANDS_PER_SET; i++ ) - m_commandWindows[ i ]->winHide( TRUE ); + { + if (m_commandWindows[ i ]) + { + m_commandWindows[ i ]->winHide( TRUE ); + } + } // sanity DEBUG_ASSERTCRASH( TheInGameUI->getSelectCount() > 1, @@ -333,6 +346,9 @@ void ControlBar::updateContextMultiSelect( void ) // get the control window win = m_commandWindows[ i ]; + // our implementation doesn't necessarily make use of the max possible command buttons + if (!win) continue; + // don't consider hidden windows if( win->winIsHidden() == TRUE ) continue; @@ -389,6 +405,8 @@ void ControlBar::updateContextMultiSelect( void ) // for( i = 0; i < MAX_COMMANDS_PER_SET; i++ ) { + // our implementation doesn't necessarily make use of the max possible command buttons + if (! m_commandWindows[ i ]) continue; // don't consider hidden commands if( m_commandWindows[ i ]->winIsHidden() == TRUE ) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index 06bea9b829..423ea8559a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -62,7 +62,7 @@ #include "GameClient/Image.h" #include "GameClient/GameWindowManager.h" #include "GameClient/GadgetPushButton.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp index c30f0e620c..35ecaadc07 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp @@ -44,7 +44,7 @@ #include "GameClient/GadgetPushButton.h" #include "GameClient/HotKey.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp index 9429a7f9fe..6be336feff 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp @@ -93,7 +93,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp index 6f5cf79f75..c69607616a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp @@ -57,7 +57,7 @@ #include "GameNetwork/GameSpy/BuddyDefs.h" #include "GameNetwork/GameSpy/PeerDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp index 326b6c1eeb..ba0595257f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp @@ -47,7 +47,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp index 334a822b26..d2a06b3d81 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp @@ -44,7 +44,7 @@ #include "GameNetwork/GameInfo.h" #include "GameNetwork/LANAPI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp index e73f6db297..5ae7770207 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -57,7 +57,7 @@ #include "GameClient/GameText.h" #include "GameNetwork/GUIUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp index 800248f48f..0b7b9ed501 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp @@ -44,7 +44,7 @@ #include "GameClient/MapUtil.h" #include "GameNetwork/GUIUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp index c2b854f032..83c0d27559 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -75,7 +75,7 @@ //for accessing the InGameUI #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -98,7 +98,7 @@ enum static Bool raiseMessageBoxes = TRUE; static Bool campaignSelected = FALSE; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL static NameKeyType campaignID = NAMEKEY_INVALID; static GameWindow *buttonCampaign = NULL; #ifdef TEST_COMPRESSION @@ -517,7 +517,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) showSelectiveButtons(SHOW_NONE); // Set up the version number -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL WinInstanceData instData; #ifdef TEST_COMPRESSION instData.init(); @@ -1247,7 +1247,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, if(buttonPushed) break; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if( control == buttonCampaign ) { buttonPushed = TRUE; @@ -1425,10 +1425,10 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, } // end else if else if( controlID == worldBuilderID ) { -#if defined _DEBUG +#if defined RTS_DEBUG if(_spawnl(_P_NOWAIT,"WorldBuilderD.exe","WorldBuilderD.exe", NULL) < 0) MessageBoxOk(TheGameText->fetch("GUI:WorldBuilder"), TheGameText->fetch("GUI:WorldBuilderLoadFailed"),NULL); -#elif defined _INTERNAL +#elif defined RTS_INTERNAL if(_spawnl(_P_NOWAIT,"WorldBuilderI.exe","WorldBuilderI.exe", NULL) < 0) MessageBoxOk(TheGameText->fetch("GUI:WorldBuilder"), TheGameText->fetch("GUI:WorldBuilderLoadFailed"),NULL); #else @@ -1443,7 +1443,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, else if( controlID == exitID ) { // If we ever want to add a dialog before we exit out of the game, uncomment this line and kill the quitCallback() line below. -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //Added By Sadullah Nader //Changed the preprocessing code to normal code diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp index c175a8ca75..8ab1f2782d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -50,7 +50,7 @@ #include "GameNetwork/LANAPI.h" #include "GameNetwork/LANAPICallbacks.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp index 81acfd09bf..8281677db6 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -75,7 +75,7 @@ // This is for non-RC builds only!!! #define VERBOSE_VERSION L"Release" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp index 64b22551e0..dbfbf1e43d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp @@ -96,7 +96,7 @@ static GameWindow *comboBoxLadderName = NULL; static GameWindow *textEntryLadderPassword = NULL; static GameWindow *textEntryGamePassword = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp index 66b2e287e6..ff6780eaca 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp @@ -68,7 +68,7 @@ //#include "GameNetwork/GameSpy/PeerThread.h" #include "GameNetwork/GameSpyOverlay.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp index 13cde82e42..6465db36a8 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp @@ -60,7 +60,7 @@ #include "WWDownload/Registry.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp index e73b1b658e..41bf4ea81e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp @@ -59,7 +59,7 @@ #include "GameClient/Shell.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp index b4af248d41..61bb2d9818 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp @@ -53,7 +53,7 @@ #include "GameClient/DisconnectMenu.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp index 3f1fa52740..cc494c7755 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp @@ -48,7 +48,7 @@ #include "GameClient/GameText.h" #include "GameClient/GameWindowTransitions.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -75,7 +75,7 @@ static Int initialGadgetDelay = 2; static Bool justEntered = FALSE; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL static GameWindow *buttonAnalyzeReplay = NULL; #endif @@ -181,7 +181,10 @@ void PopulateReplayFileListbox(GameWindow *listbox) const MapMetaData *md = TheMapCache->findMap(info.getMap()); if (!md) { - mapStr.translate(info.getMap()); + // TheSuperHackers @bugfix helmutbuhler 08/03/2025 Just use the filename. + // Displaying a long map path string would break the map list gui. + const char* filename = info.getMap().reverseFind('\\'); + mapStr.translate(filename ? filename + 1 : info.getMap()); } else { @@ -291,7 +294,7 @@ void ReplayMenuInit( WindowLayout *layout, void *userData ) GadgetListBoxReset(listboxReplayFiles); PopulateReplayFileListbox(listboxReplayFiles); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL WinInstanceData instData; instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); @@ -512,7 +515,7 @@ WindowMsgHandledType ReplayMenuSystem( GameWindow *window, UnsignedInt msg, GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if( controlID == buttonAnalyzeReplay->winGetWindowId() ) { if(listboxReplayFiles) diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp index 8c0cbd5607..fadfd684e7 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -99,7 +99,7 @@ //Added By Saad #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp index 7677da1ae2..ee3236fde7 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp @@ -67,7 +67,7 @@ #include "GameNetwork/IPEnumeration.h" #include "WWDownload/Registry.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -411,7 +411,7 @@ static MessageBoxReturnType cancelStartBecauseOfNoCD( void *userData ) Bool IsFirstCDPresent(void) { -#if !defined(_INTERNAL) && !defined(_DEBUG) +#if !defined(RTS_INTERNAL) && !defined(RTS_DEBUG) return TheFileSystem->areMusicFilesOnCD(); #else return TRUE; @@ -778,7 +778,12 @@ void updateMapStartSpots( GameInfo *myGame, GameWindow *buttonMapStartPositions[ if (it == TheMapCache->end()) { for (Int i = 0; i < MAX_SLOTS; ++i) - buttonMapStartPositions[i]->winHide(TRUE); + { + if ( buttonMapStartPositions[i] != NULL ) + { + buttonMapStartPositions[i]->winHide(TRUE); + } + } return; } MapMetaData mmd = it->second; @@ -786,14 +791,20 @@ void updateMapStartSpots( GameInfo *myGame, GameWindow *buttonMapStartPositions[ Int i = 0; for(; i < MAX_SLOTS; ++i) { - GadgetButtonSetText(buttonMapStartPositions[i], UnicodeString::TheEmptyString); - if (!onLoadScreen) - { - buttonMapStartPositions[i]->winSetTooltip(TheGameText->fetch("TOOLTIP:StartPosition")); - } + if ( buttonMapStartPositions[i] != NULL ) + { + GadgetButtonSetText(buttonMapStartPositions[i], UnicodeString::TheEmptyString); + if (!onLoadScreen) + { + buttonMapStartPositions[i]->winSetTooltip(TheGameText->fetch("TOOLTIP:StartPosition")); + } + } } for( i = 0; i < MAX_SLOTS; ++i) { + if ( buttonMapStartPositions[i] == NULL ) + continue; + GameSlot *gs =myGame->getSlot(i); if(onLoadScreen) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp index a5ad03678c..806f96701c 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp @@ -57,7 +57,7 @@ // PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1302,8 +1302,6 @@ WindowMsgHandledType WOLBuddyOverlayRCMenuSystem( GameWindow *window, UnsignedIn BuddyInfoMap *m = TheGameSpyInfo->getBuddyRequestMap(); m->erase( profileID ); - - // DONT CHECK IN UNTIL MATT HAS REVIEWED // if the profile ID is not from a buddy and we're okaying his request, then // request to add him to our list automatically CLH 2-18-03 if(!TheGameSpyInfo->isBuddy(profileID)) @@ -1311,7 +1309,6 @@ WindowMsgHandledType WOLBuddyOverlayRCMenuSystem( GameWindow *window, UnsignedIn RequestBuddyAdd(profileID, nick); } updateBuddyInfo(); - } else if (!isBuddy) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp index b38ca41ac0..d8eeaec7b2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -65,7 +65,7 @@ void WOLDisplaySlotList( void ); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -75,7 +75,7 @@ extern std::list TheLobbyQueuedUTMs; extern void MapSelectorTooltip(GameWindow *window, WinInstanceData *instData, UnsignedInt mouse); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern Bool g_debugSlots; void slotListDebugLog(const char *fmt, ...) { @@ -1782,7 +1782,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) case PeerResponse::PEERRESPONSE_ROOMUTM: { sawImportantMessage = TRUE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (g_debugSlots) { DEBUG_LOG(("About to process a room UTM. Command is '%s', command options is '%s'\n", @@ -2336,7 +2336,7 @@ Bool handleGameSetupSlashCommands(UnicodeString uText) TheGameSpyInfo->sendChat(UnicodeString(uText.str()+4), TRUE, NULL); return TRUE; // was a slash command } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) else if (token == "slots") { g_debugSlots = !g_debugSlots; @@ -2350,7 +2350,7 @@ Bool handleGameSetupSlashCommands(UnicodeString uText) TheGameSpyPeerMessageQueue->addRequest( req ); return TRUE; } -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) return FALSE; // not a slash command } diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp index ebdc81d8ab..2a4c2f83dd 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -70,7 +70,7 @@ #include "GameNetwork/GameSpy/LobbyUtils.h" #include "GameNetwork/RankPointValue.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -133,7 +133,7 @@ static Int groupRoomToJoin = 0; static Int initialGadgetDelay = 2; static Bool justEntered = FALSE; -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) Bool g_fakeCRC = FALSE; Bool g_debugSlots = FALSE; #endif @@ -202,7 +202,7 @@ Bool handleLobbySlashCommands(UnicodeString uText) return TRUE; // was a slash command } */ -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) else if (token == "fakecrc") { g_fakeCRC = !g_fakeCRC; @@ -1552,7 +1552,7 @@ WindowMsgHandledType WOLLobbyMenuSystem( GameWindow *window, UnsignedInt msg, { // bad crc. don't go. DEBUG_LOG(("WOLLobbyMenuSystem - CRC mismatch with the game I'm trying to join. My CRC's - EXE:0x%08X INI:0x%08X Their CRC's - EXE:0x%08x INI:0x%08x\n", TheGlobalData->m_exeCRC, TheGlobalData->m_iniCRC, roomToJoin->getExeCRC(), roomToJoin->getIniCRC())); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_netMinPlayers) { GSMessageBoxOk(TheGameText->fetch("GUI:JoinFailedDefault"), TheGameText->fetch("GUI:JoinFailedCRCMismatch")); diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp index 6d088b5c00..20f24e1f5d 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp @@ -48,7 +48,7 @@ #include "GameNetwork/GameSpy/PersistentStorageDefs.h" #include "GameNetwork/GameSpy/PersistentStorageThread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp index ddf502aa13..79a9052618 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp @@ -68,7 +68,7 @@ #include "GameNetwork/WOLBrowser/WebBrowser.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp index 994b36d68c..4217ff2df5 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp @@ -44,7 +44,7 @@ #include "GameClient/MapUtil.h" #include "GameNetwork/GUIUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp index cec8b3873f..b90c6cec80 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -65,7 +65,7 @@ #include "GameNetwork/GameSpy/PersistentStorageThread.h" #include "GameNetwork/RankPointValue.h" #include "GameNetwork/GameSpy/LadderDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp index df96b71b67..981b154bcc 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp @@ -67,7 +67,7 @@ #include "GameNetwork/GameSpy/MainMenuUtils.h" #include "GameNetwork/WOLBrowser/WebBrowser.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp index 70d89bdc04..e3d4803941 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp @@ -343,6 +343,29 @@ void GadgetCheckBoxSetChecked( GameWindow *g, Bool isChecked) (WindowMsgData)g, 0 ); } + +// GadgetCheckBoxToggle ============================================ +//============================================================================= +/** Toggle the check state for the check box */ +//============================================================================= +void GadgetCheckBoxToggle( GameWindow *g) +{ + WinInstanceData *instData = g->winGetInstanceData(); + Bool isChecked = BitIsSet(instData->m_state, WIN_STATE_SELECTED); + if (isChecked) + { + BitClear(instData->m_state, WIN_STATE_SELECTED); + } + else + { + BitSet(instData->m_state, WIN_STATE_SELECTED); + } + + TheWindowManager->winSendSystemMsg( g->winGetOwner(), GBM_SELECTED, + (WindowMsgData)g, 0 ); + +} + // GadgetCheckBoxIsChecked ====================================================== /** Check the check state */ //============================================================================= diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp index 39cca219f7..5061e193b2 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp @@ -67,7 +67,7 @@ /////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp index 57aeb3c7eb..d78bc6c7de 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp @@ -63,7 +63,7 @@ #include "GameClient/GameWindowGlobal.h" #include "GameClient/Keyboard.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp index 6e5fad5b60..f447a22ae4 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp @@ -57,7 +57,7 @@ // DEFINES //////////////////////////////////////////////////////////////////// // PRIVATE TYPES ////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp index f8d51d79fa..26cc5db554 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp @@ -66,7 +66,7 @@ /////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp index ad874a96b0..1ae3901b53 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp @@ -61,7 +61,7 @@ #include "GameClient/GadgetStaticText.h" #include "GameClient/Mouse.h" #include "GameClient/SelectionXlat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -658,6 +658,16 @@ Int GameWindow::winEnable( Bool enable ) } // end WinEnable +// GameWindow::winGetEnabled ====================================================== +/** Enable or disable a window based on the enable parameter. + * A disabled window can be seen but accepts no input. */ +//============================================================================= +Bool GameWindow::winGetEnabled( void ) +{ + return BitIsSet( m_status, WIN_STATUS_ENABLED ); + +} // end winGetEnabled + // GameWindow::winHide ======================================================== /** Hide or show a window based on the hide parameter. * A hidden window can't be seen and accepts no input. */ diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index 986ccce0d3..64842165f4 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -61,7 +61,7 @@ UnsignedInt WindowLayoutCurrentVersion = 2; /////////////////////////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp index bd27d407cd..84fef3f297 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp @@ -72,6 +72,13 @@ #include "GameClient/GameText.h" #include "GameClient/HeaderTemplate.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + // DEFINES //////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp index 166ec82202..467d9e539e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp @@ -47,7 +47,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp index aaf8551855..c23c810aa0 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp @@ -47,7 +47,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp index 464a96c832..c221a14acb 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp @@ -60,7 +60,7 @@ #include "GameClient/HeaderTemplate.h" #include "GameClient/GameFont.h" #include "GameClient/GlobalLanguage.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index 6ea534b16c..7b2ec52176 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -61,7 +61,7 @@ #include "GameClient/Color.h" #include "Common/NameKeyGenerator.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 1794cce95d..11e2107c8c 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -48,7 +48,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") @@ -94,7 +94,7 @@ // DEFINES //////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp index 14ae3bd374..b37b6f84ec 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp @@ -45,7 +45,7 @@ // PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// Shell *TheShell = NULL; ///< the shell singleton definition -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp b/Generals/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp index 2677952060..01613ca995 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp @@ -33,7 +33,7 @@ #include "GameClient/WindowLayout.h" #include "GameClient/Shell.h" #include "GameClient/GameWindowManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) diff --git a/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp b/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp index d5d380c7e4..d66eb41296 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GameClient.cpp @@ -81,7 +81,7 @@ #include "GameLogic/GhostObject.h" #include "GameLogic/Object.h" #include "GameLogic/ScriptEngine.h" // For TheScriptEngine - jkmcd -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -457,6 +457,9 @@ void GameClient::reset( void ) // clear any drawable TOC we might have m_drawableTOC.clear(); + // TheSuperHackers @fix Mauller 13/04/2025 Reset the drawable id so it does not keep growing over the lifetime of the game. + m_nextDrawableID = (DrawableID)1; + } // end reset /** ----------------------------------------------------------------------------------------------- @@ -511,7 +514,7 @@ void GameClient::update( void ) //Initial Game Codition. We must show the movie first and then we can display the shell if(TheGlobalData->m_afterIntro && !TheDisplay->isMoviePlaying()) { - if( playSizzle) + if( playSizzle && TheGlobalData->m_playSizzle) { TheWritableGlobalData->m_allowExitOutOfMovies = TRUE; if(TheGameLODManager && TheGameLODManager->didMemPass()) @@ -617,7 +620,7 @@ void GameClient::update( void ) if (!freezeTime) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) #else if (true) @@ -648,7 +651,7 @@ void GameClient::update( void ) while (draw) { // update() could free the Drawable, so go ahead and grab 'next' Drawable* next = draw->getNextDrawable(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) #else if (true) @@ -685,7 +688,7 @@ void GameClient::update( void ) } } -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) // need to draw the first frame, then don't draw again until TheGlobalData->m_noDraw if (TheGlobalData->m_noDraw > TheGameLogic->getFrame() && TheGameLogic->getFrame() > 0) { diff --git a/Generals/Code/GameEngine/Source/GameClient/GameText.cpp b/Generals/Code/GameEngine/Source/GameClient/GameText.cpp index fea292a06a..b6ab31acd6 100644 --- a/Generals/Code/GameEngine/Source/GameClient/GameText.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/GameText.cpp @@ -48,6 +48,7 @@ #include "GameClient/GameText.h" #include "Common/Language.h" #include "Common/Registry.h" +#include "GameClient/ClientInstance.h" #include "GameClient/LanguageFilter.h" #include "Common/Debug.h" #include "Common/UnicodeString.h" @@ -57,7 +58,7 @@ #include "Common/FileSystem.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -68,7 +69,7 @@ // Externals //---------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool g_useStringFile = TRUE; #endif @@ -167,7 +168,7 @@ class GameTextManager : public GameTextInterface StringInfo *m_stringInfo; StringLookUp *m_stringLUT; Bool m_initialized; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_jabberWockie; Bool m_munkee; #endif @@ -248,7 +249,7 @@ GameTextManager::GameTextManager() m_stringLUT(NULL), m_initialized(FALSE), m_noStringList(NULL), -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_jabberWockie(FALSE), m_munkee(FALSE), m_useStringFile(g_useStringFile), @@ -301,7 +302,7 @@ void GameTextManager::init( void ) m_initialized = TRUE; m_maxLabelLen = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if(TheGlobalData) { m_jabberWockie = TheGlobalData->m_jabberOn; @@ -370,8 +371,21 @@ void GameTextManager::init( void ) qsort( m_stringLUT, m_textCount, sizeof(StringLookUp), compareLUT ); UnicodeString ourName = fetch("GUI:Command&ConquerGenerals"); + + if (rts::ClientInstance::getInstanceId() > 1u) + { + UnicodeString s; + s.format(L"Instance:%.2u - %s", rts::ClientInstance::getInstanceId(), ourName.str()); + ourName = s; + } + + AsciiString ourNameA; + ourNameA.translate(ourName); //get ASCII version for Win 9x + extern HWND ApplicationHWnd; ///< our application window handle if (ApplicationHWnd) { + //Set it twice because Win 9x does not support SetWindowTextW. + ::SetWindowText(ApplicationHWnd, ourNameA.str()); ::SetWindowTextW(ApplicationHWnd, ourName.str()); } @@ -690,7 +704,7 @@ void GameTextManager::translateCopy( WideChar *outbuf, Char *inbuf ) { Int slash = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if ( m_jabberWockie ) { static Char buffer[MAX_UITEXT_LENGTH*2]; diff --git a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp index b348ab5233..61fa15b205 100644 --- a/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -86,7 +86,7 @@ #include "GameLogic/Module/SupplyWarehouseDockUpdate.h" #include "GameLogic/Module/MobMemberSlavedUpdate.h"//ML -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2115,7 +2115,7 @@ void InGameUI::createGarrisonHint( const GameMessage *msg ) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define AI_DEBUG_TOOLTIPS 1 #ifdef AI_DEBUG_TOOLTIPS @@ -2124,7 +2124,7 @@ void InGameUI::createGarrisonHint( const GameMessage *msg ) #include "GameLogic/AIPathfind.h" #endif // AI_DEBUG_TOOLTIPS -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------------------------------- /** Details of what is mouse hovered over right now are in this message. Terrain might result @@ -2196,7 +2196,7 @@ void InGameUI::createMouseoverHint( const GameMessage *msg ) else m_mousedOverDrawableID = draw->getID(); -#if defined(_DEBUG) || defined(_INTERNAL) //Extra hacky, sorry, but I need to use this in constantdebug report +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //Extra hacky, sorry, but I need to use this in constantdebug report if ( TheGlobalData->m_constantDebugUpdate == TRUE ) m_mousedOverDrawableID = draw->getID(); #endif @@ -2218,8 +2218,7 @@ void InGameUI::createMouseoverHint( const GameMessage *msg ) //Because we have support for disguised units pretending to be units from another //team, we need to intercept it here and make sure it's rendered appropriately //based on which client is rendering it. - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate *update = (StealthUpdate*)obj->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = obj->getStealth(); if( update ) { if( update->isDisguised() ) @@ -2423,7 +2422,7 @@ void InGameUI::createCommandHint( const GameMessage *msg ) { const Object* obj = draw->getObject(); Int localPlayerIndex = ThePlayerList ? ThePlayerList->getLocalPlayer()->getPlayerIndex() : 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ObjectShroudStatus ss = (!obj || !TheGlobalData->m_shroudOn) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); #else ObjectShroudStatus ss = (!obj) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); @@ -4778,7 +4777,7 @@ void InGameUI::addFloatingText(const UnicodeString& text,const Coord3D *pos, Col //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline Bool isClose(Real a, Real b) { return fabs(a-b) <= 1.0f; } inline Bool isClose(const Coord3D& a, const Coord3D& b) { diff --git a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index e5036556e8..4df5571b8e 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -47,7 +47,7 @@ #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -389,6 +389,7 @@ void Mouse::checkForDrag( void ) } // end checkForDrag + //------------------------------------------------------------------------------------------------- /** Check for mouse click, using allowed drag forgiveness */ //------------------------------------------------------------------------------------------------- @@ -411,6 +412,7 @@ Bool Mouse::isClick(const ICoord2D *anchor, const ICoord2D *dest, UnsignedInt pr } + /////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -636,7 +638,8 @@ void Mouse::reset( void ) ///@ todo Write Mouse::reset() if there needs to be anything here // reset the text of the cursor text - m_cursorTextDisplayString->reset(); + if ( m_cursorTextDisplayString ) + m_cursorTextDisplayString->reset(); } // end reset @@ -678,6 +681,11 @@ void Mouse::createStreamMessages( void ) Int delay = m_tooltipDelayTime; if(m_tooltipDelay >= 0 ) delay = m_tooltipDelay; + if( TheGlobalData->m_scriptDebug ) + { + //No delay while scriptdebugging! + delay = 0; + } if( now - m_stillTime >= delay ) { diff --git a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index 9790c0b40e..d591f623ee 100644 --- a/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -29,7 +29,7 @@ #include "Common/FileSystem.h" #include "Common/file.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -58,7 +58,7 @@ void LanguageFilter::init() { return; } - WideChar word[128]; + wchar_t word[128]; while (readWord(file1, word)) { Int wordLen = wcslen(word); if (wordLen == 0) { diff --git a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp index 04cfe1b4ea..144483b000 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MapUtil.cpp @@ -61,7 +61,7 @@ #include "GameNetwork/GameInfo.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -465,7 +465,7 @@ void MapCache::updateCache( void ) writeCacheINI( TRUE ); } loadStandardMaps(); // we shall overwrite info from matching user maps to prevent munkees from getting rowdy :) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheLocalFileSystem->doesFileExist(getMapDir().str())) { // only create the map cache file if "Maps" exist @@ -504,7 +504,7 @@ void MapCache::loadStandardMaps(void) INI ini; AsciiString fname; fname.format("%s\\%s", getMapDir().str(), m_mapCacheName); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) File *fp = TheFileSystem->openFile(fname.str(), File::READ); if (fp != NULL) { @@ -512,7 +512,7 @@ void MapCache::loadStandardMaps(void) fp = NULL; #endif ini.load( fname, INI_LOAD_OVERWRITE, NULL ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } #endif } diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp index 3858c74c00..a6faef0355 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp @@ -86,14 +86,14 @@ #include "GameNetwork/GameSpyOverlay.h" #include "GameNetwork/GameSpy/BuddyThread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /*non-static*/ Real TheSkateDistOverride = 0.0f; void countObjects(Object *obj, void *userData) @@ -2202,7 +2202,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage return DESTROY_MESSAGE; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ExtentModType extentModType = EXTENTMOD_INVALID; Real extentModAmount = 0.0f; #endif @@ -2828,7 +2828,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEPLOY: - #ifdef _DEBUG + #ifdef RTS_DEBUG DEBUG_ASSERTCRASH(FALSE, ("unimplemented meta command MSG_META_DEPLOY !")); #endif /// @todo srj implement me @@ -2837,7 +2837,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_FOLLOW: - #ifdef _DEBUG + #ifdef RTS_DEBUG DEBUG_ASSERTCRASH(FALSE, ("unimplemented meta command MSG_META_FOLLOW !")); #endif /// @todo srj implement me @@ -3050,7 +3050,24 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage case GameMessage::MSG_META_CAMERA_RESET: TheInGameUI->resetCamera(); break; - + case GameMessage::MSG_META_TOGGLE_FAST_FORWARD_REPLAY: + { + if( TheGlobalData ) + { + #if !defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)//may be defined in GameCommon.h + if (TheGameLogic->isInReplayGame()) + #endif + { + TheWritableGlobalData->m_TiVOFastMode = 1 - TheGlobalData->m_TiVOFastMode; + TheInGameUI->message( UnicodeString( L"m_TiVOFastMode: %s" ), + TheGlobalData->m_TiVOFastMode ? L"ON" : L"OFF" ); + } + } // end if + + disp = DESTROY_MESSAGE; + break; + + } // end toggle special power delays //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_BEGIN_FORCEMOVE: DEBUG_ASSERTCRASH(!TheInGameUI->isInForceMoveToMode(), ("forceMoveToMode mismatch")); @@ -3354,7 +3371,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage } // end case GameMessage::MSG_MOUSE_LEFT_CLICK -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------- BEGIN DEMO MESSAGES //------------------------------------------------------------------------- BEGIN DEMO MESSAGES //------------------------------------------------------------------------- BEGIN DEMO MESSAGES @@ -4545,11 +4562,11 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //--------------------------------------------------------------------------- END DEMO MESSAGES //--------------------------------------------------------------------------- END DEMO MESSAGES //--------------------------------------------------------------------------- END DEMO MESSAGES -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------DEMO MESSAGES //----------------------------------------------------------------------------------------- -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) case GameMessage::MSG_META_DEMO_TOGGLE_AUDIODEBUG: { if (TheDisplay->getDebugDisplayCallback() == AudioDebugDisplay) @@ -4560,7 +4577,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage break; } -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS //------------------------------------------------------------------------DEMO MESSAGES diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp index ebd05c4a7a..18b3651e76 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp @@ -47,7 +47,7 @@ #include "GameClient/GUICommandTranslator.h" #include "GameClient/CommandXlat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp index 9c642e6169..2beae42eff 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp @@ -337,7 +337,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage m_anchor = msg->getArgument( 0 )->pixel; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // adjust the field of view if (m_isChangingFOV) { @@ -495,7 +495,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage } // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_BEGIN_ADJUST_PITCH: { DEBUG_ASSERTCRASH(!m_isPitching, ("hmm, mismatched m_isPitching")); @@ -503,10 +503,10 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage disp = DESTROY_MESSAGE; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_END_ADJUST_PITCH: { DEBUG_ASSERTCRASH(m_isPitching, ("hmm, mismatched m_isPitching")); @@ -514,19 +514,19 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage disp = DESTROY_MESSAGE; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_DESHROUD: { ThePartitionManager->revealMapForPlayerPermanently( ThePlayerList->getLocalPlayer()->getPlayerIndex() ); break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_ENSHROUD: { // Need to first undo the permanent Look laid down by DEMO_DESHROUD, then blast a shroud dollop. @@ -534,10 +534,10 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage ThePartitionManager->shroudMapForPlayer( ThePlayerList->getLocalPlayer()->getPlayerIndex() ); break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_BEGIN_ADJUST_FOV: { DEBUG_ASSERTCRASH(!m_isChangingFOV, ("hmm, mismatched m_isChangingFOV")); @@ -545,17 +545,17 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage m_anchor = m_currentPos; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_END_ADJUST_FOV: { DEBUG_ASSERTCRASH(m_isChangingFOV, ("hmm, mismatched m_isChangingFOV")); m_isChangingFOV = false; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_SAVE_VIEW1: @@ -599,7 +599,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage } //----------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_LOCK_CAMERA_TO_PLANES: { Drawable *first = NULL; @@ -660,7 +660,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage disp = DESTROY_MESSAGE; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } // end switch diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp index d653093226..fbb450c4bd 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp @@ -47,14 +47,14 @@ #include "GameClient/WindowLayout.h" #include "GameClient/GUICallbacks.h" #include "GameClient/DebugDisplay.h" // for AudioDebugDisplay - +#include "GameClient/GameText.h" #include "GameClient/MetaEvent.h" #include "GameLogic/GameLogic.h" // for TheGameLogic->getFrame() MetaMap *TheMetaMap = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... ///#pragma optimize("", off) ///#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -171,8 +171,9 @@ static const LookupListRec GameMessageMetaTypeNames[] = { "BEGIN_CAMERA_ZOOM_OUT", GameMessage::MSG_META_BEGIN_CAMERA_ZOOM_OUT }, { "END_CAMERA_ZOOM_OUT", GameMessage::MSG_META_END_CAMERA_ZOOM_OUT }, { "CAMERA_RESET", GameMessage::MSG_META_CAMERA_RESET }, + { "TOGGLE_FAST_FORWARD_REPLAY", GameMessage::MSG_META_TOGGLE_FAST_FORWARD_REPLAY }, -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) { "HELP", GameMessage::MSG_META_HELP }, { "DEMO_INSTANT_QUIT", GameMessage::MSG_META_DEMO_INSTANT_QUIT }, @@ -293,12 +294,12 @@ static const LookupListRec GameMessageMetaTypeNames[] = { "DEBUG_DUMP_ALL_PLAYER_OBJECTS", GameMessage::MSG_META_DEBUG_DUMP_ALL_PLAYER_OBJECTS }, { "DEMO_WIN", GameMessage::MSG_META_DEBUG_WIN }, { "DEMO_TOGGLE_DEBUG_STATS", GameMessage::MSG_META_DEMO_TOGGLE_DEBUG_STATS }, -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) { "DEMO_TOGGLE_AUDIODEBUG", GameMessage::MSG_META_DEMO_TOGGLE_AUDIODEBUG }, -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS { "DEMO_PERFORM_STATISTICAL_DUMP", GameMessage::MSG_META_DEMO_PERFORM_STATISTICAL_DUMP }, #endif//DUMP_PERF_STATS @@ -448,6 +449,27 @@ GameMessageDisposition MetaEventTranslator::translateGameMessage(const GameMessa } else { + + // THIS IS A GREASY HACK... MESSAGE SHOULD BE HANDLED IN A TRANSLATOR, BUT DURING CINEMATICS THE TRANSLATOR IS DISABLED + if( map->m_meta == GameMessage::MSG_META_TOGGLE_FAST_FORWARD_REPLAY) + { + #if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)//may be defined in GameCommon.h + if( TheGlobalData ) + #else + if( TheGlobalData && TheGameLogic->isInReplayGame()) + #endif + { + if ( TheWritableGlobalData ) + TheWritableGlobalData->m_TiVOFastMode = 1 - TheGlobalData->m_TiVOFastMode; + + if ( TheInGameUI ) + TheInGameUI->message( TheGlobalData->m_TiVOFastMode ? TheGameText->fetch("GUI:FF_ON") : TheGameText->fetch("GUI:FF_OFF") ); + } + disp = KEEP_MESSAGE; // cause for goodness sake, this key gets used a lot by non-replay hotkeys + break; + } + + /*GameMessage *metaMsg =*/ TheMessageStream->appendMessage(map->m_meta); //DEBUG_LOG(("Frame %d: MetaEventTranslator::translateGameMessage() normal: %s\n", TheGameLogic->getFrame(), findGameMessageNameByType(map->m_meta))); } diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp index a877c62b2e..e3c2c9a81a 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp @@ -56,7 +56,7 @@ #include "GameClient/SelectionXlat.h" #include "GameClient/TerrainVisual.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -65,7 +65,7 @@ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) static Bool TheHurtSelectionMode = false; static Bool TheHandOfGodSelectionMode = false; static Bool TheDebugSelectionMode = false; @@ -783,7 +783,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa if (newDrawablesSelected == 1 && draw) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheHandOfGodSelectionMode && draw) { Object* obj = draw->getObject(); @@ -1175,7 +1175,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEMO_TOGGLE_HAND_OF_GOD_MODE: { @@ -1186,7 +1186,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEMO_TOGGLE_HURT_ME_MODE: { @@ -1197,7 +1197,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEMO_DEBUG_SELECTION: { diff --git a/Generals/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp b/Generals/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp index d581163c89..0241f4fa5b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp @@ -55,7 +55,7 @@ #include "GameClient/Shell.h" #include "GameClient/Display.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -75,7 +75,7 @@ // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats extern ICoord2D TheMousePos; #endif @@ -218,7 +218,7 @@ GameMessageDisposition WindowTranslator::translateGameMessage(const GameMessage { // all window events have the position of the mouse as arg 0 ICoord2D mousePos = msg->getArgument( 0 )->pixel; -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats TheMousePos.x = mousePos.x; TheMousePos.y = mousePos.y; #endif diff --git a/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp b/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp index d9ad6bd472..d009983a60 100644 --- a/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/RadiusDecal.cpp @@ -36,7 +36,7 @@ #include "GameClient/Shadow.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp b/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp index 7aa24453eb..4f873f7426 100644 --- a/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/SelectionInfo.cpp @@ -37,7 +37,7 @@ #include "GameClient/GameClient.h" #include "GameClient/KeyDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -342,7 +342,7 @@ void translatePickTypesToKindof(UnsignedInt pickTypes, KindOfMaskType& outMask) Bool addDrawableToList( Drawable *draw, void *userData ) { PickDrawableStruct *pds = (PickDrawableStruct *) userData; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_allowUnselectableSelection) { pds->drawableListToFill->push_back(draw); return TRUE; diff --git a/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp b/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp index 687fa16a80..e9b2069915 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/Anim2D.cpp @@ -38,7 +38,7 @@ #include "GameClient/Image.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp b/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp index f58f462e71..3fb63c252b 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp @@ -61,6 +61,14 @@ //----------------------------------------------------------------------------- CampaignManager *TheCampaignManager = NULL; + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + const FieldParse CampaignManager::m_campaignFieldParseTable[] = { diff --git a/Generals/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp b/Generals/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp index 24da603408..af2862ec9f 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp @@ -105,7 +105,7 @@ static void printFunc( char *text ) // AudioDebugDisplay //============================================================================ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void AudioDebugDisplay ( DebugDisplayInterface *dd, void *, FILE *fp = NULL ) { TheAudio->audioDebugDisplay( dd, NULL, fp ); diff --git a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index fd2c0b6cfb..3cec8c15f8 100644 --- a/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -49,7 +49,7 @@ #include "GameLogic/Object.h" #include "GameLogic/TerrainLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp index 4193be2905..f6bec5e353 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp @@ -31,6 +31,15 @@ #include "Common/Xfer.h" #include "GameClient/TerrainVisual.h" + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + + // GLOBALS //////////////////////////////////////////////////////////////////////////////////////// TerrainVisual *TheTerrainVisual = NULL; diff --git a/Generals/Code/GameEngine/Source/GameClient/Water.cpp b/Generals/Code/GameEngine/Source/GameClient/Water.cpp index 21b15c06db..d0ae1910fb 100644 --- a/Generals/Code/GameEngine/Source/GameClient/Water.cpp +++ b/Generals/Code/GameEngine/Source/GameClient/Water.cpp @@ -64,7 +64,10 @@ const FieldParse WaterTransparencySetting::m_waterTransparencySettingFieldParseT { "TransparentWaterDepth", INI::parseReal, NULL, offsetof( WaterTransparencySetting, m_transparentWaterDepth ) }, { "TransparentWaterMinOpacity", INI::parseReal, NULL, offsetof( WaterTransparencySetting, m_minWaterOpacity ) }, - + { "StandingWaterColor", INI::parseRGBColor, NULL, offsetof( WaterTransparencySetting, m_standingWaterColor ) }, + { "StandingWaterTexture",INI::parseAsciiString, NULL, offsetof( WaterTransparencySetting, m_standingWaterTexture ) }, + { "AdditiveBlending", INI::parseBool, NULL, offsetof( WaterTransparencySetting, m_additiveBlend) }, + { "RadarWaterColor", INI::parseRGBColor, NULL, offsetof( WaterTransparencySetting, m_radarColor) }, { "SkyboxTextureN", INI::parseAsciiString,NULL, offsetof( WaterTransparencySetting, m_skyboxTextureN ) }, { "SkyboxTextureE", INI::parseAsciiString,NULL, offsetof( WaterTransparencySetting, m_skyboxTextureE ) }, { "SkyboxTextureS", INI::parseAsciiString,NULL, offsetof( WaterTransparencySetting, m_skyboxTextureS ) }, diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp index ab17dd5f98..26eff78bda 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -47,7 +47,7 @@ extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -524,7 +524,7 @@ class PartitionFilterLiveMapEnemies : public PartitionFilter return true; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLiveMapEnemies"; } #endif }; @@ -554,7 +554,7 @@ class PartitionFilterWithinAttackRange : public PartitionFilter return false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterWithinAttackRange"; } #endif }; @@ -860,7 +860,7 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { // ICK. This really nasty statement is used so that we only initialize this color once. diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp index 58ecf31396..b540b3ab73 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp @@ -53,9 +53,10 @@ #include "GameLogic/Module/SpawnBehavior.h" #include "GameLogic/Module/SpecialPowerModule.h" #include "GameLogic/Module/StealthUpdate.h" +#include "GameLogic/Module/SpecialPowerUpdateModule.h" #include "GameLogic/ObjectIter.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -639,6 +640,39 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cm } +static void clampToMap(Coord3D *dest, PlayerType pt) +// Clamps to the player's current visible map area. jba. [8/28/2003] +{ + Region3D extent; + if (pt==PLAYER_COMPUTER) { + // AI gets to operate inside the pathable shrouded area. [8/28/2003] + TheTerrainLogic->getMaximumPathfindExtent(&extent); + } else { + // Human player has to stay within the visible map. + TheTerrainLogic->getExtent(&extent); + } + + extent.hi.x -= PATHFIND_CELL_SIZE_F; + extent.hi.y -= PATHFIND_CELL_SIZE_F; + extent.lo.x += PATHFIND_CELL_SIZE_F; + extent.lo.y += PATHFIND_CELL_SIZE_F; + if (!extent.isInRegionNoZ(dest)) { + // clamp to in region. [8/28/2003] + if (dest->x < extent.lo.x) { + dest->x = extent.lo.x; + } + if (dest->y < extent.lo.y) { + dest->y = extent.lo.y; + } + if (dest->x > extent.hi.x) { + dest->x = extent.hi.x; + } + if (dest->y > extent.hi.y) { + dest->y = extent.hi.y; + } + } +} + //------------------------------------------------------------------------------------------------- // Internal function for moving a group of infantry as a column. // @@ -1471,6 +1505,36 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd //------------------------------------------------------------------------------------------------- // AI Command Interface implementation for AIGroup // +const Int STD_WAYPOINT_CLAMP_MARGIN = ( PATHFIND_CELL_SIZE_F * 4.0f ); +const Int STD_AIRCRAFT_EXTRA_MARGIN = ( PATHFIND_CELL_SIZE_F * 10.0f ); + +void clampWaypointPosition( Coord3D &position, Int margin ) +{ + Region3D mapExtent; + TheTerrainLogic->getExtent(&mapExtent); + + // trim some fat off of all sides, + mapExtent.hi.x -= margin; + mapExtent.hi.y -= margin; + mapExtent.lo.x += margin; + mapExtent.lo.y += margin; + + if ( mapExtent.isInRegionNoZ( &position ) == FALSE ) + { + if ( position.x > mapExtent.hi.x ) + position.x = mapExtent.hi.x; + else if ( position.x < mapExtent.lo.x ) + position.x = mapExtent.lo.x; + + if ( position.y > mapExtent.hi.y ) + position.y = mapExtent.hi.y; + else if ( position.y < mapExtent.lo.y ) + position.y = mapExtent.lo.y; + + position.z = TheTerrainLogic->getGroundHeight( position.x, position.y ); + } +} + /** * Move to given position(s) @@ -1620,8 +1684,7 @@ void AIGroup::groupMoveToPosition( const Coord3D *pos, Bool addWaypoint, Command //Not stealthed, not detected -- so do auto-acquire while stealthed? if( !ai->canAutoAcquireWhileStealthed() ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)theUnit->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = theUnit->getStealth(); if( stealth ) { //Delay the mood check time (for autoacquire) until after the unit can stealth again. @@ -1710,6 +1773,39 @@ void AIGroup::groupScatter( CommandSourceType cmdSource ) } } + +const Real CIRCLE = ( 2.0f * PI ); + +void getHelicopterOffset( Coord3D& posOut, Int idx ) +{ + if (idx == 0) + return; + + Real assumedHeliDiameter = 70.0f; + Real radius = assumedHeliDiameter; + Real circumference = radius * CIRCLE; + Real angle = 0; + Real angleBetweenEachChopper = assumedHeliDiameter / circumference * CIRCLE; + for (Int h = 1; h < idx; ++h ) + { + angle += angleBetweenEachChopper; + + if ( angle > CIRCLE ) + { + radius += assumedHeliDiameter; + circumference = radius * CIRCLE; + angleBetweenEachChopper = assumedHeliDiameter / circumference * CIRCLE; + angle -= CIRCLE; + } + } + + Coord3D tempCtr = posOut; + posOut.x = tempCtr.x + (sin(angle) * radius); + posOut.y = tempCtr.y + (cos(angle) * radius); + +} + + /** * Move to given position(s), tightening the formation */ @@ -1915,8 +2011,7 @@ void AIGroup::groupIdle(CommandSourceType cmdSource) //Not stealthed, not detected -- so do auto-acquire while stealthed? if( !ai->canAutoAcquireWhileStealthed() ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)obj->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = obj->getStealth(); if( stealth ) { //Delay the mood check time (for autoacquire) until after the unit can stealth again. @@ -2515,7 +2610,7 @@ void AIGroup::groupDoSpecialPower( UnsignedInt specialPowerID, UnsignedInt comma * don't use AIUpdateInterfaces!!! No special power uses an AIUpdateInterface immediately, but special * abilities, which are derived from special powers do... and are unit triggered. Those do have AI. */ -void AIGroup::groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const Coord3D *location, const Object *objectInWay, UnsignedInt commandOptions ) +void AIGroup::groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const Coord3D *location, Real angle, const Object *objectInWay, UnsignedInt commandOptions ) { //This one requires a position std::list::iterator i; @@ -2540,7 +2635,7 @@ void AIGroup::groupDoSpecialPowerAtLocation( UnsignedInt specialPowerID, const C { if( TheActionManager->canDoSpecialPowerAtLocation( object, location, CMD_FROM_PLAYER, spTemplate, objectInWay, commandOptions ) ) { - mod->doSpecialPowerAtLocation( location, commandOptions ); + mod->doSpecialPowerAtLocation( location, angle, commandOptions ); object->friend_setUndetectedDefector( FALSE );// My secret is out } diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp index ac132af682..9046b339ed 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp @@ -54,7 +54,7 @@ const Real CLOSE_ENOUGH = (25.0f); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp index e18c3c420c..0ed0639287 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp @@ -71,7 +71,7 @@ //------------------------------------------------------------------------------------------------- -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -340,7 +340,7 @@ void Path::xfer( Xfer *xfer ) xfer->xferBool(&m_blockedByAlly); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI == AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -743,7 +743,7 @@ void Path::computePointOnPath( ClosestPointOnPathInfo& out ) { - CRCDEBUG_LOG(("Path::computePointOnPath() fzor %s\n", DescribeObject(obj).str())); + CRCDEBUG_LOG(("Path::computePointOnPath() for %s\n", DebugDescribeObject(obj).str())); out.layer = LAYER_GROUND; out.posOnPath.zero(); @@ -2521,7 +2521,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye DEBUG_LOG(("Time to calculate zones %f, cells %d\n", timeToUpdate, (globalBounds.hi.x-globalBounds.lo.x)*(globalBounds.hi.y-globalBounds.lo.y))); #endif #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI && false) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -2835,7 +2835,7 @@ Bool PathfindLayer::isUnused(void) /** * Draws debug cell info. */ -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void PathfindLayer::doDebugIcons(void) { if (isUnused()) return; extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -4209,7 +4209,7 @@ void Pathfinder::debugShowSearch( Bool pathFound ) if (!TheGlobalData->m_debugAI) { return; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); // show all explored cells for debugging @@ -4333,7 +4333,7 @@ void Pathfinder::cleanOpenAndClosedLists(void) { m_closedList = NULL; } m_cumulativeCellsAllocated += count; -//#ifdef _DEBUG +//#ifdef RTS_DEBUG #if 0 // Check for dangling cells. for( int j=0; j<=m_extent.hi.y; j++ ) @@ -5194,7 +5194,7 @@ Bool Pathfinder::queueForPath(ObjectID id) return true; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void Pathfinder::doDebugIcons(void) { const Int FRAMES_TO_SHOW_OBSTACLES = 100; extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -5445,7 +5445,7 @@ void Pathfinder::processPathfindQueue(void) #endif #endif } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL doDebugIcons(); #endif @@ -6142,7 +6142,7 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe } // failure - goal cannot be reached -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL #ifdef INTENSE_DEBUG DEBUG_LOG(("internal find path FAILURE...\n")); #endif @@ -6290,7 +6290,7 @@ Path *Pathfinder::buildGroundPath(Bool isCrusher, const Coord3D *fromPos, Pathfi path->optimizeGroundPath( isCrusher, pathDiameter ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -6335,7 +6335,7 @@ Path *Pathfinder::buildHierachicalPath( const Coord3D *fromPos, PathfindCell *go prependCells(path, fromPos, goalCell, true); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -6604,7 +6604,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from, DEBUG_LOG((" time %d msec %d cells", (::GetTickCount()-startTimeMS), cellCount)); DEBUG_LOG((" SUCCESS\n")); #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool show = TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS; if (show) debugShowSearch(true); @@ -6649,7 +6649,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from, const Int adjacent[5] = {0, 1, 2, 3, 0}; Bool neighborFlags[8] = {false, false, false, false, false, false, false}; - UnsignedInt newCostSoFar; + UnsignedInt newCostSoFar = 0; for( int i=0; im_debugAI) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -7140,7 +7140,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu m_isTunneling = false; // construct and return path Path *path = buildHierachicalPath( from, goalCell ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool show = TheGlobalData->m_debugAI==AI_DEBUG_PATHS; show |= (TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS); if (show) { @@ -7175,7 +7175,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu return path; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL #if 0 Bool show = TheGlobalData->m_debugAI==AI_DEBUG_PATHS; show |= (TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS); @@ -7342,7 +7342,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu m_isTunneling = false; // construct and return path Path *path = buildHierachicalPath( from, closestCell ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL #if 0 if (TheGlobalData->m_debugAI) { @@ -7376,7 +7376,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu } // failure - goal cannot be reached -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -7783,7 +7783,7 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet } } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (closestCell) { debugShowSearch(true); *dest = closestPos; @@ -8335,7 +8335,7 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSet DEBUG_LOG(("Pathfind(findClosestPath) failed from (%f,%f) to (%f,%f), original valid %d --", from->x, from->y, to->x, to->y, valid)); DEBUG_LOG(("Unit '%s', time %f\n", obj->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) debugShowSearch(false); #endif @@ -8383,7 +8383,7 @@ Path *Pathfinder::buildActualPath( const Object *obj, LocomotorSurfaceTypeMask a // cleanup the path by checking line of sight path->optimize(obj, acceptableSurfaces, blocked); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -9721,7 +9721,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj, } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL debugShowSearch(true); #endif @@ -9797,7 +9797,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet // until goal is found. // -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); if (TheGlobalData->m_debugAI) { @@ -9820,7 +9820,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet info.radius = radius; info.considerTransient = blocked; info.acceptableSurfaces = locomotorSet.getValidSurfaces(); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) { RGBColor color; color.setFromInt(0); @@ -9908,7 +9908,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet DEBUG_LOG(("patchPath Pathfind failed -- ")); DEBUG_LOG(("Unit '%s', time %f\n", obj->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) { debugShowSearch(true); } @@ -9958,7 +9958,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot } */ if (m_isMapReady == false) return NULL; // Should always be ok. -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Int startTimeMS = ::GetTickCount(); #endif @@ -10148,7 +10148,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot #endif if (show) debugShowSearch(true); - #if defined _DEBUG || defined _INTERNAL + #if defined RTS_DEBUG || defined RTS_INTERNAL //DEBUG_LOG(("Attack path took %d cells, %f sec\n", cellCount, (::GetTickCount()-startTimeMS)/1000.0f)); #endif // construct and return path @@ -10204,7 +10204,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot cleanOpenAndClosedLists(); return path; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL DEBUG_LOG(("%d (%d cells)", TheGameLogic->getFrame(), cellCount)); DEBUG_LOG(("Attack Pathfind failed from (%f,%f) to (%f,%f) -- \n", from->x, from->y, victim->getPosition()->x, victim->getPosition()->y)); DEBUG_LOG(("Unit '%s', attacking '%s' time %f\n", obj->getTemplate()->getName().str(), victim->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); @@ -10227,7 +10227,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor { //CRCDEBUG_LOG(("Pathfinder::findSafePath()\n")); if (m_isMapReady == false) return NULL; // Should always be ok. -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Int startTimeMS = ::GetTickCount(); #endif @@ -10334,7 +10334,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor #endif if (show) debugShowSearch(true); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL //DEBUG_LOG(("Attack path took %d cells, %f sec\n", cellCount, (::GetTickCount()-startTimeMS)/1000.0f)); #endif // construct and return path @@ -10365,7 +10365,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor TheScriptEngine->AppendDebugMessage("Overflowed Safe path", false); #endif #if 0 -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL DEBUG_LOG(("%d (%d cells)", TheGameLogic->getFrame(), cellCount)); DEBUG_LOG(("Attack Pathfind failed from (%f,%f) to (%f,%f) -- \n", from->x, from->y, victim->getPosition()->x, victim->getPosition()->y)); DEBUG_LOG(("Unit '%s', attacking '%s' time %f\n", obj->getTemplate()->getName().str(), victim->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp index c7cc019ad7..6e2a185d92 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/SupplyWarehouseDockUpdate.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -626,7 +626,7 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI == AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -1041,7 +1041,13 @@ Bool AIPlayer::isLocationSafe(const Coord3D *pos, const ThingTemplate *tthing ) void AIPlayer::onUnitProduced( Object *factory, Object *unit ) { Bool found = false; + // TheSuperHackers @fix Mauller 26/04/2025 Fixes uninitialized variable. + // To keep retail compatibility this needs to remain uninitialized in VS6 builds. +#if defined(_MSC_VER) && _MSC_VER < 1300 Bool supplyTruck; +#else + Bool supplyTruck = false; +#endif // factory could be NULL at the start of the game. if (factory == NULL) { @@ -1770,9 +1776,16 @@ void AIPlayer::buildBySupplies(Int minimumCash, const AsciiString& thingName) BuildAssistant::NO_OBJECT_OVERLAP, NULL, m_player ) != LBC_OK ) { // Warn. - AsciiString bldgName = tTemplate->getName(); - bldgName.concat(" - buildAISupplyCenter unable to place. Attempting to adjust position."); - TheScriptEngine->AppendDebugMessage(bldgName, false); + const Coord3D *warehouseLocation = bestSupplyWarehouse->getPosition(); + AsciiString debugMessage; + debugMessage.format(" %s - buildBySupplies unable to place near dock at (%.2f,%.2f). Attempting to adjust position.", + tTemplate->getName().str(), + warehouseLocation->x, + warehouseLocation->y + ); + TheScriptEngine->AppendDebugMessage(debugMessage, false); + if( TheGlobalData->m_debugSupplyCenterPlacement ) + DEBUG_LOG(("%s", debugMessage.str())); // try to fix. Real posOffset; // Wiggle it a little :) @@ -1789,12 +1802,16 @@ void AIPlayer::buildBySupplies(Int minimumCash, const AsciiString& thingName) BuildAssistant::NO_OBJECT_OVERLAP, NULL, m_player ) == LBC_OK; if (valid) break; + if( TheGlobalData->m_debugSupplyCenterPlacement ) + DEBUG_LOG(("buildBySupplies -- Fail at (%.2f,%.2f)\n", newPos.x, newPos.y)); newPos.y = yPos+posOffset; valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, tTemplate, angle, BuildAssistant::CLEAR_PATH | BuildAssistant::TERRAIN_RESTRICTIONS | BuildAssistant::NO_OBJECT_OVERLAP, NULL, m_player ) == LBC_OK; + if( !valid && TheGlobalData->m_debugSupplyCenterPlacement ) + DEBUG_LOG(("buildBySupplies -- Fail at (%.2f,%.2f)\n", newPos.x, newPos.y)); } if (valid) break; xPos = location.x-offset; @@ -1807,17 +1824,26 @@ void AIPlayer::buildBySupplies(Int minimumCash, const AsciiString& thingName) BuildAssistant::NO_OBJECT_OVERLAP, NULL, m_player ) == LBC_OK; if (valid) break; + if( TheGlobalData->m_debugSupplyCenterPlacement ) + DEBUG_LOG(("buildBySupplies -- Fail at (%.2f,%.2f)\n", newPos.x, newPos.y)); newPos.x = xPos+posOffset; valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, tTemplate, angle, BuildAssistant::CLEAR_PATH | BuildAssistant::TERRAIN_RESTRICTIONS | BuildAssistant::NO_OBJECT_OVERLAP, NULL, m_player ) == LBC_OK; + if( !valid && TheGlobalData->m_debugSupplyCenterPlacement ) + DEBUG_LOG(("buildBySupplies -- Fail at (%.2f,%.2f)\n", newPos.x, newPos.y)); } if (valid) break; } } - if (valid) location = newPos; + if (valid) + { + if( TheGlobalData->m_debugSupplyCenterPlacement ) + DEBUG_LOG(("buildAISupplyCenter -- SUCCESS at (%.2f,%.2f)\n", newPos.x, newPos.y)); + location = newPos; + } TheTerrainVisual->removeAllBibs(); // isLocationLegalToBuild adds bib feedback, turn it off. jba. location.z = 0; // All build list locations are ground relative. m_player->addToPriorityBuildList(thingName, &location, angle); diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp index df556f9bfa..7249508975 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp @@ -56,7 +56,7 @@ #include "GameLogic/Module/ProductionUpdate.h" #include "GameClient/TerrainVisual.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 3d81a08c52..92b830bfcc 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -66,7 +66,7 @@ #include "GameLogic/Module/ContainModule.h" #include "GameLogic/Module/PhysicsUpdate.h" #include "GameLogic/Module/StealthUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -852,6 +852,14 @@ AsciiString AIStateMachine::getCurrentStateName(void) const */ StateReturnType AIStateMachine::updateStateMachine() { + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + Bool idle = getOwner()->getAI()->isIdle(); + if( !idle && TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("%d - %s::update() start - %s", TheGameLogic->getFrame(), getCurrentStateName().str(), getOwner()->getTemplate()->getName().str() ) ); + #endif + //end -extraLogging + if (m_temporaryState) { // execute this state @@ -862,13 +870,49 @@ StateReturnType AIStateMachine::updateStateMachine() status = STATE_SUCCESS; } } - if (status==STATE_CONTINUE) { + if (status==STATE_CONTINUE) + { + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( !idle && TheGlobalData->m_extraLogging ) + DEBUG_LOG( (" - RETURN EARLY STATE_CONTINUE\n") ); + #endif + //end -extraLogging + return status; } m_temporaryState->onExit(EXIT_NORMAL); m_temporaryState = NULL; } - return StateMachine::updateStateMachine(); + StateReturnType retType = StateMachine::updateStateMachine(); + + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + AsciiString result; + if( TheGlobalData->m_extraLogging ) + { + switch( retType ) + { + case STATE_CONTINUE: + result.format( "CONTINUE" ); + break; + case STATE_SUCCESS: + result.format( "SUCCESS" ); + break; + case STATE_FAILURE: + result.format( "FAILURE" ); + break; + default: + result.format( "UNKNOWN %d", retType ); + break; + } + if( !idle ) + DEBUG_LOG( (" - RETURNING %s\n", result.str() ) ); + } + #endif + //end -extraLogging + + return retType; } //---------------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp index 93beadb0fe..eb1ba16ad1 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp @@ -55,7 +55,7 @@ const Real CLOSE_ENOUGH = (25.0f); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp index b8cbe84e2b..8f529bdbe6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/Squad.cpp @@ -48,7 +48,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp index 433e9c443a..ffef7d4b09 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp @@ -47,7 +47,7 @@ const UnsignedInt WAIT_INDEFINITELY = 0xffffffff; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -308,7 +308,7 @@ TurretAI::TurretAI(Object* owner, const TurretAIData* data, WhichTurretType tur) m_angle = getNaturalTurretAngle(); m_pitch = getNaturalTurretPitch(); -#ifdef _DEBUG +#ifdef RTS_DEBUG char smbuf[256]; sprintf(smbuf, "TurretStateMachine for tur %08lx slot %d",this,tur); const char* smname = smbuf; @@ -672,7 +672,7 @@ UpdateSleepTime TurretAI::updateTurretAI() { USE_PERF_TIMER(TurretAI) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(!m_enabled || m_turretStateMachine->peekSleepTill() == 0 || m_turretStateMachine->peekSleepTill() >= m_sleepUntil, ("Turret Machine is less sleepy than turret")); @@ -731,7 +731,7 @@ UpdateSleepTime TurretAI::updateTurretAI() m_sleepUntil = now + subMachineSleep; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(!m_enabled || m_turretStateMachine->peekSleepTill() == 0 || m_turretStateMachine->peekSleepTill() >= m_sleepUntil, ("Turret Machine is less sleepy than turret")); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp index 8c1f0cfff3..9a190bea8f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp @@ -189,7 +189,7 @@ Bool PolygonTrigger::ParsePolygonTriggersDataChunk(DataChunkInput &file, DataChu // before water areas existed, so create a default one. PolygonTrigger *pTrig = newInstance(PolygonTrigger)(4); pTrig->setWaterArea(true); -#ifdef _DEBUG +#ifdef RTS_DEBUG pTrig->setTriggerName("AutoAddedWaterAreaTrigger"); #endif pTrig->m_triggerID = maxTriggerId++; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index c9ea9c3068..2bbd6e6843 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -59,7 +59,7 @@ #include "WWMath/plane.h" #include "WWMath/tri.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -136,7 +136,7 @@ Object *Bridge::createTower( Coord3D *worldPos, if( towerTemplate == NULL || bridge == NULL ) { - DEBUG_CRASH(( "createTower: Invalid params\n" )); + DEBUG_CRASH(( "Bridge::createTower(): Invalid params\n" )); return NULL; } // end if @@ -430,9 +430,11 @@ Bridge::Bridge(Object *bridgeObj) } // end switch tower = createTower( &pos, type, towerTemplate, bridgeObj ); - - // store the tower object ID - m_bridgeInfo.towerObjectID[ i ] = tower->getID(); + if( tower ) + { + // store the tower object ID + m_bridgeInfo.towerObjectID[ i ] = tower->getID(); + } } // end for, i diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp index fb13604213..7e2ea1e227 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp @@ -44,6 +44,12 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- struct AutoHealPlayerScanHelper diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp index 34ac4ddab6..cf090cc716 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp @@ -45,7 +45,7 @@ #include "GameLogic/Module/PhysicsUpdate.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -451,7 +451,7 @@ Bool DumbProjectileBehavior::calcFlightPath(Bool recalcNumSegments) flightCurve.getSegmentPoints( m_flightPathSegments, &m_flightPath ); DEBUG_ASSERTCRASH(m_flightPathSegments == m_flightPath.size(), ("m_flightPathSegments mismatch")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_debugProjectilePath ) displayFlightPath(); #endif @@ -487,7 +487,7 @@ Bool DumbProjectileBehavior::projectileHandleCollision( Object *other ) const ContainedItemsList* items = contain->getContainedItemsList(); if (items) { - for (ContainedItemsList::const_iterator it = items->begin(); *it != NULL && numKilled < d->m_garrisonHitKillCount; ) + for (ContainedItemsList::const_iterator it = items->begin(); it != items->end() && numKilled < d->m_garrisonHitKillCount; ) { Object* thingToKill = *it++; if (!thingToKill->isEffectivelyDead() && thingToKill->isKindOfMulti(d->m_garrisonHitKillKindof, d->m_garrisonHitKillKindofNot)) @@ -674,7 +674,7 @@ UpdateSleepTime DumbProjectileBehavior::update() // ------------------------------------------------------------------------------------------------ /** displayFlightPath for debugging */ // ------------------------------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void DumbProjectileBehavior::displayFlightPath() { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp index e0d1b7e164..7fde1f16f3 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp @@ -49,7 +49,7 @@ #include "GameLogic/Weapon.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp index 05e0dd448e..c2b8af0357 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp @@ -54,7 +54,7 @@ #include "GameLogic/Weapon.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp index e21968f434..5cf8018b9c 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp @@ -43,7 +43,7 @@ #include "GameLogic/Object.h" #include "GameLogic/ObjectCreationList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp index 4bfb7cf08a..1083e304d4 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp @@ -45,7 +45,7 @@ #include "GameLogic/Module/AutoHealBehavior.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp index f6b0335db9..83ea354a02 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp @@ -43,7 +43,7 @@ #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp index 0f96ead6dd..2548dbb573 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp @@ -44,7 +44,7 @@ #include "GameLogic/TerrainLogic.h" #include "Common/Team.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp index d4f346fa5b..a0d37ad48b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp @@ -37,7 +37,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp index dd1cb7c56c..149eeb7366 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp @@ -44,7 +44,7 @@ #include "GameLogic/Module/BodyModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp index b77d341a3c..14aed92100 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Module/RebuildHoleBehavior.h" #include "GameLogic/Module/StickyBombUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp index 0b8b069d47..3eb9059ccc 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp @@ -51,7 +51,7 @@ #include "GameLogic/Weapon.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp index c3bcd56f84..72a1eddabf 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp @@ -48,7 +48,7 @@ #define NONE_SPAWNED_YET (0xffffffff) -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp index f02e3de162..bedfb191dc 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp @@ -57,7 +57,7 @@ #include "GameLogic/Module/DieModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp index a4111fb8a1..2bcccf16d4 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp @@ -56,7 +56,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/Module/DozerAIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp index d44ab0f2dc..49945919ba 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp @@ -39,6 +39,12 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/CrateCollide.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- CrateCollideModuleData::CrateCollideModuleData() diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp index 1122dc66e8..ae7c08f504 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp @@ -41,7 +41,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp index 626230a42f..eb9eb21d58 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp @@ -54,7 +54,7 @@ #include "GameClient/InGameUI.h" #include "GameClient/View.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/MobNexusContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/MobNexusContain.cpp index d0edff32fc..cd498acb93 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/MobNexusContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/MobNexusContain.cpp @@ -442,8 +442,7 @@ Bool MobNexusContain::tryToEvacuate( Bool exposeStealthedUnits ) if( obj->isKindOf( KINDOF_STEALTH_GARRISON ) && exposeStealthedUnits ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)obj->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = obj->getStealth(); if( stealth ) { stealth->markAsDetected(); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 9d1cc97e73..589c50c052 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -57,7 +57,7 @@ #include "GameLogic/PartitionManager.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -284,7 +284,7 @@ void OpenContain::addToContain( Object *rider ) if( rider == NULL ) return; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( !isValidContainerFor( rider, false ) ) { Object *reportObject = rider; @@ -515,7 +515,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, { /* - #ifdef _DEBUG + #ifdef RTS_DEBUG TheInGameUI->message( UnicodeString( L"'%S(%d)' no longer contains '%S(%d)'" ), getObject()->getTemplate()->getName().str(), getObject()->getID(), @@ -533,8 +533,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, m_stealthUnitsContained--; if( exposeStealthUnits ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)rider->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = rider->getStealth(); if( stealth ) { stealth->markAsDetected(); @@ -700,8 +699,7 @@ void OpenContain::onCollide( Object *other, const Coord3D *loc, const Coord3D *n if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) ) { // aiExit is needed to walk away from the building well, but it doesn't take the Unstealth flag - static const NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)rider->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = rider->getStealth(); if( stealth ) { stealth->markAsDetected(); @@ -1239,8 +1237,7 @@ void OpenContain::markAllPassengersDetected( ) // call it if( rider->isKindOf( KINDOF_STEALTH_GARRISON ) ) { - static const NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)rider->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = rider->getStealth(); if( stealth ) { stealth->markAsDetected(); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp index f093146131..e84213ce62 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp @@ -43,6 +43,14 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ OverlordContainModuleData::OverlordContainModuleData() diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp index 004f8f4971..37d6878d98 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp @@ -49,7 +49,7 @@ const Real NO_START_Z = 1e10; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp index 071ac662f2..cbf62d9d7f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp @@ -45,7 +45,7 @@ #include "GameLogic/Module/TransportContain.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp index f6314ba07e..c9ec85f6ec 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp @@ -43,7 +43,7 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp index 78109cf7a2..c3c7e2ddb7 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp @@ -35,7 +35,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/PreorderCreate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp index 6444b3010c..583b0dea93 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp @@ -37,6 +37,12 @@ #include "GameLogic/Object.h" #include "GameLogic/ObjectCreationList.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ CreateObjectDieModuleData::CreateObjectDieModuleData() diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp index 9124420c6e..9cd6452976 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp @@ -35,6 +35,12 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Module/DestroyDie.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- DestroyDie::DestroyDie( Thing *thing, const ModuleData* moduleData ) : DieModule( thing, moduleData ) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp index be8b4095e6..f4af098b8d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp @@ -38,7 +38,7 @@ #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/FXListDie.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/FXListDie.cpp index 2e97bc0208..19ef817627 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/FXListDie.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/FXListDie.cpp @@ -65,8 +65,6 @@ void FXListDie::onDie( const DamageInfo *damageInfo ) const FXListDieModuleData* d = getFXListDieModuleData(); if (d->m_defaultDeathFX) { - // if the object has any ambient sound(s), kill 'em now. - TheAudio->stopAllAmbientsBy(getObject()); if (d->m_orientToObject) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp index f5ed0dd68d..5bbd58f543 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp @@ -45,7 +45,7 @@ #include "GameLogic/Object.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp index bb3d186739..8b8435a823 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp index 040dfbbe94..5810e9c2c2 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp index 559554ec9d..67f2aed1e6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp @@ -42,7 +42,10 @@ GhostObject::GhostObject(void): //Added By Sadullah Nader //Initializations missing and needed m_parentAngle(0.0f), -m_parentGeometryIsSmall(0.0f), +// TheSuperHackers @bugfix tomsons26 26/04/2025 Change initialization of m_parentGeometryIsSmall from 0.0f. +// Assigning a float to a bool results in the compiler using a random 1 byte value to assign to the bool. +// @todo Change initialization to 'false' when applicable. +m_parentGeometryIsSmall(true), m_parentGeometryMajorRadius(0.0f), m_parentGeometryminorRadius(0.0f), m_parentObject(NULL), diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp index 4ad81a88b3..32921202b3 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ObjectDefectionHelper.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp index 2692c3229c..f50df5163b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp @@ -34,7 +34,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ObjectHelper.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp index 04e1f54f1e..d4af84d787 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp @@ -46,7 +46,7 @@ #include "GameLogic/Module/BodyModule.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 93bfeb712c..4e9aa4dcc6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -101,7 +101,7 @@ #include "Common/CRCDebug.h" #include "Common/MiscAudio.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -142,8 +142,7 @@ extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBCo //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#ifdef DEBUG_LOGGING -AsciiString DescribeObject(const Object *obj) +AsciiString DebugDescribeObject(const Object *obj) { if (!obj) return ""; @@ -167,7 +166,6 @@ AsciiString DescribeObject(const Object *obj) return ret; } -#endif // DEBUG_LOGGING //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- @@ -183,6 +181,7 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu m_behaviors(NULL), m_body(NULL), m_contain(NULL), + m_stealth(NULL), m_partitionData(NULL), m_radarData(NULL), m_drawable(NULL), @@ -204,7 +203,7 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu m_formationID(NO_FORMATION_ID), m_isReceivingDifficultyBonus(FALSE) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_hasDiedAlready = false; #endif //Modules have not been created yet! @@ -366,6 +365,13 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu m_contain = contain; } + StealthUpdate* stealth = newMod->getStealth(); + if ( stealth ) + { + DEBUG_ASSERTCRASH( m_stealth == NULL, ("DuplicateStealthUpdates!") ); + m_stealth = stealth; + } + AIUpdateInterface* ai = newMod->getAIUpdateInterface(); if (ai) { @@ -491,7 +497,7 @@ void Object::initObject() // Kris -- All missiles must be projectiles! This is the perfect place to assert them! // srj: yes, but only in debug... -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( !isKindOf( KINDOF_PROJECTILE ) ) { if( isKindOf( KINDOF_SMALL_MISSILE ) || isKindOf( KINDOF_BALLISTIC_MISSILE ) ) @@ -2327,7 +2333,7 @@ void Object::setTriggerAreaFlagsForChangeInPosition() if (m_team) m_team->setEnteredExited(); TheGameLogic->updateObjectsChangedTriggerAreas(); -#ifdef _DEBUG +#ifdef RTS_DEBUG //TheScriptEngine->AppendDebugMessage("Object exited.", false); #endif } @@ -2362,7 +2368,7 @@ void Object::setTriggerAreaFlagsForChangeInPosition() m_team->setEnteredExited(); TheGameLogic->updateObjectsChangedTriggerAreas(); ++m_numTriggerAreasActive; -#ifdef _DEBUG +#ifdef RTS_DEBUG //TheScriptEngine->AppendDebugMessage("Object entered.", false); #endif } @@ -3356,10 +3362,6 @@ void Object::onDisabledEdge(Bool becomingDisabled) //------------------------------------------------------------------------------------------------- void Object::crc( Xfer *xfer ) { - // This is evil - we cast the const Matrix3D * to a Matrix3D * because the XferCRC class must use - // the same interface as the XferLoad class for save game restore. This only works because - // XferCRC does not modify its data. - #ifdef DEBUG_CRC // g_logObjectCRCs = TRUE; // Bool g_logAllObjects = TRUE; @@ -3368,7 +3370,7 @@ void Object::crc( Xfer *xfer ) Bool doLogging = g_logObjectCRCs /* && getControllingPlayer()->getPlayerType() == PLAYER_HUMAN */; if (doLogging) { - tmp.format("CRC of Object %d (%s), owned by player %d, ", m_id, getTemplate()->getName().str(), getControllingPlayer()->getPlayerIndex()); + tmp.format("CRC of Object %d (%s), owned by player %d, team: %d, ", m_id, getTemplate()->getName().str(), getControllingPlayer()->getPlayerIndex(), this->getTeam() ? this->getTeam()->getID() : TEAM_ID_INVALID); logString.concat(tmp); } #endif // DEBUG_CRC @@ -3382,6 +3384,9 @@ void Object::crc( Xfer *xfer ) } #endif // DEBUG_CRC + // This is evil - we cast the const Matrix3D * to a Matrix3D * because the XferCRC class must use + // the same interface as the XferLoad class for save game restore. This only works because + // XferCRC does not modify its data. xfer->xferUser((Matrix3D *)getTransformMatrix(), sizeof(Matrix3D)); #ifdef DEBUG_CRC if (doLogging) @@ -3396,16 +3401,6 @@ void Object::crc( Xfer *xfer ) #endif // DEBUG_CRC -#ifdef DEBUG_CRC - if (doLogging) - { - const Matrix3D *mtx = getTransformMatrix(); - CRCDEBUG_LOG(("CRC of Object %d (%s), owned by player %d, ", m_id, getTemplate()->getName().str(), getControllingPlayer()->getPlayerIndex())); - DUMPMATRIX3D(mtx); - } -#endif //DEBUG_CRC - - xfer->xferUser(&m_id, sizeof(m_id)); #ifdef DEBUG_CRC if (doLogging) @@ -3861,7 +3856,7 @@ void Object::xfer( Xfer *xfer ) //m_body; //m_ai; //m_physics; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //m_hasDiedAlready; #endif @@ -4025,7 +4020,7 @@ void Object::onCapture( Player *oldOwner, Player *newOwner ) void Object::onDie( DamageInfo *damageInfo ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(m_hasDiedAlready == false, ("Object::onDie has been called multiple times. This is invalid. jkmcd")); m_hasDiedAlready = true; #endif @@ -4487,7 +4482,7 @@ void Object::unshroud() //------------------------------------------------------------------------------------------------- Real Object::getVisionRange() const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { Vector3 pos(m_visionRange, 0, 0); @@ -4523,7 +4518,7 @@ Real Object::getShroudClearingRange() const shroudClearingRange = getGeometryInfo().getBoundingCircleRadius(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { Vector3 pos(shroudClearingRange, 0, 0); @@ -4580,7 +4575,7 @@ void Object::setShroudClearingRange( Real newShroudClearingRange ) //------------------------------------------------------------------------------------------------- Real Object::getShroudRange() const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { Vector3 pos(m_shroudRange, 0, 0); @@ -4674,7 +4669,7 @@ void Object::doSpecialPowerAtObject( const SpecialPowerTemplate *specialPowerTem /** Execute special power */ //------------------------------------------------------------------------------------------------- void Object::doSpecialPowerAtLocation( const SpecialPowerTemplate *specialPowerTemplate, - const Coord3D *loc, UnsignedInt commandOptions, Bool forced ) + const Coord3D *loc, Real angle, UnsignedInt commandOptions, Bool forced ) { if (isDisabled()) @@ -4687,15 +4682,14 @@ void Object::doSpecialPowerAtLocation( const SpecialPowerTemplate *specialPowerT // get the module and execute SpecialPowerModuleInterface *mod = getSpecialPowerModule( specialPowerTemplate ); if( mod ) - mod->doSpecialPowerAtLocation( loc, commandOptions ); + mod->doSpecialPowerAtLocation( loc, angle, commandOptions ); } //------------------------------------------------------------------------------------------------- /** Execute special power */ //------------------------------------------------------------------------------------------------- -void Object::doSpecialPowerAtMultipleLocations( const SpecialPowerTemplate *specialPowerTemplate, - const Coord3D *locations, Int locCount, UnsignedInt commandOptions, Bool forced ) +void Object::doSpecialPowerUsingWaypoints( const SpecialPowerTemplate *specialPowerTemplate, const Waypoint *way, UnsignedInt commandOptions, Bool forced ) { if (isDisabled()) @@ -4708,7 +4702,7 @@ void Object::doSpecialPowerAtMultipleLocations( const SpecialPowerTemplate *spec // get the module and execute SpecialPowerModuleInterface *mod = getSpecialPowerModule( specialPowerTemplate ); if( mod ) - mod->doSpecialPowerAtMultipleLocations( locations, locCount, commandOptions ); + mod->doSpecialPowerUsingWaypoints( way, commandOptions ); } @@ -4921,7 +4915,7 @@ void Object::doCommandButtonAtPosition( const CommandButton *commandButton, cons if( commandButton->getSpecialPowerTemplate() ) { CommandOption commandOptions = (CommandOption)(commandButton->getOptions() | COMMAND_FIRED_BY_SCRIPT); - doSpecialPowerAtLocation( commandButton->getSpecialPowerTemplate(), pos, commandOptions, cmdSource == CMD_FROM_SCRIPT ); + doSpecialPowerAtLocation( commandButton->getSpecialPowerTemplate(), pos, INVALID_ANGLE, commandOptions, cmdSource == CMD_FROM_SCRIPT ); } break; } @@ -5042,6 +5036,26 @@ SpecialPowerModuleInterface* Object::findSpecialPowerModuleInterface( SpecialPow return NULL; } +// ------------------------------------------------------------------------------------------------ +// Search our special power modules for the first occurrence of a shortcut special. +// ------------------------------------------------------------------------------------------------ +SpecialPowerModuleInterface* Object::findAnyShortcutSpecialPowerModuleInterface() const +{ + for( BehaviorModule** m = m_behaviors; *m; ++m ) + { + SpecialPowerModuleInterface* sp = (*m)->getSpecialPower(); + if (!sp) + continue; + + const SpecialPowerTemplate *spTemplate = sp->getSpecialPowerTemplate(); + if( spTemplate && spTemplate->isShortcutPower() ) + { + return sp; + } + } + return NULL; +} + // ------------------------------------------------------------------------------------------------ /** Get spawn behavior interface from object */ // ------------------------------------------------------------------------------------------------ @@ -5077,6 +5091,26 @@ SpecialPowerUpdateInterface* Object::findSpecialPowerWithOverridableDestinationA return NULL; } +// ------------------------------------------------------------------------------------------------ +// Simply find the special power module that is potentially allowed to plot positions to target. +// ------------------------------------------------------------------------------------------------ +SpecialPowerUpdateInterface* Object::findSpecialPowerWithOverridableDestination( SpecialPowerType type ) const +{ + for( BehaviorModule** u = m_behaviors; *u; ++u ) + { + SpecialPowerUpdateInterface *spInterface = (*u)->getSpecialPowerUpdateInterface(); + if( spInterface ) + { + if( spInterface->doesSpecialPowerHaveOverridableDestination() ) + { + return spInterface; + } + } + } // end for + return NULL; +} + + // ------------------------------------------------------------------------------------------------ // Search our special ability updates for a specific one. // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp index 16bc57d848..151bd8dab9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp @@ -70,7 +70,7 @@ #include "Common/CRCDebug.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -103,16 +103,16 @@ static void adjustVector(Coord3D *vec, const Matrix3D* mtx) /////////////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------------- -void ObjectCreationNugget::create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames ) const +Object* ObjectCreationNugget::create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames ) const { - create( primary, primary ? primary->getPosition() : NULL, secondary ? secondary->getPosition() : NULL, lifetimeFrames ); + return create( primary, primary ? primary->getPosition() : NULL, secondary ? secondary->getPosition() : NULL, lifetimeFrames ); } //------------------------------------------------------------------------------------------------- //This one is called only when we have a nugget that doesn't care about createOwner. -void ObjectCreationNugget::create( const Object *primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames ) const +Object* ObjectCreationNugget::create( const Object *primaryObj, const Coord3D *primary, const Coord3D *secondary, Bool createOwner, UnsignedInt lifetimeFrames ) const { - create( primaryObj, primary, secondary, lifetimeFrames ); + return create( primaryObj, primary, secondary, lifetimeFrames ); } //------------------------------------------------------------------------------------------------- @@ -128,18 +128,19 @@ class FireWeaponNugget : public ObjectCreationNugget { } - virtual void create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const { if (!primaryObj || !primary || !secondary) { DEBUG_CRASH(("You must have a primary and secondary source for this effect")); - return; + return NULL; } if (m_weapon) { TheWeaponStore->createAndFireTempWeapon( m_weapon, primaryObj, secondary ); } + return NULL; } static void parse(INI *ini, void *instance, void* /*store*/, const void* /*userData*/) @@ -174,12 +175,12 @@ class AttackNugget : public ObjectCreationNugget { } - virtual void create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const { if (!primaryObj || !primary || !secondary) { DEBUG_CRASH(("You must have a primary and secondary source for this effect")); - return; + return NULL; } // Star trekkin, across the universe. @@ -207,6 +208,7 @@ class AttackNugget : public ObjectCreationNugget rd->createRadiusDecal(m_deliveryDecalTemplate, m_deliveryDecalRadius, *secondary); rd->killWhenNoLongerAttacking(true); } + return NULL; } static void parse(INI *ini, void *instance, void* /*store*/, const void* /*userData*/) @@ -261,17 +263,17 @@ class DeliverPayloadNugget : public ObjectCreationNugget // End Add } - virtual void create(const Object *primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create(const Object *primaryObj, const Coord3D *primary, const Coord3D *secondary, UnsignedInt lifetimeFrames = 0 ) const { - create( primaryObj, primary, secondary, true, lifetimeFrames ); + return create( primaryObj, primary, secondary, true, lifetimeFrames ); } - virtual void create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, Bool createOwner, UnsignedInt lifetimeFrames = 0 ) const { if (!primaryObj || !primary || !secondary) { DEBUG_CRASH(("You must have a primary and secondary source for this effect")); - return; + return NULL; } Team* owner = primaryObj ? primaryObj->getControllingPlayer()->getDefaultTeam() : NULL; @@ -310,6 +312,7 @@ class DeliverPayloadNugget : public ObjectCreationNugget CWy = dx * s + dy * c + dy; } + Object *firstTransport = NULL; for( Int formationIndex = 0; formationIndex < m_formationSize; formationIndex++ ) { Coord3D offset; @@ -372,7 +375,11 @@ class DeliverPayloadNugget : public ObjectCreationNugget transport = TheThingFactory->newObject( ttn, owner ); if( !transport ) { - return; + return NULL; + } + if( !firstTransport ) + { + firstTransport = transport; } transport->setPosition(&startPos); transport->setOrientation(orient); @@ -434,6 +441,12 @@ class DeliverPayloadNugget : public ObjectCreationNugget for (std::vector::const_iterator it = m_payload.begin(); it != m_payload.end(); ++it) { const ThingTemplate* payloadTmpl = TheThingFactory->findTemplate(it->m_payloadName); + if( !payloadTmpl ) + { + DEBUG_CRASH( ("DeliverPayloadNugget::create() -- %s couldn't create %s (template not found).", + transport->getTemplate()->getName().str(), it->m_payloadName.str() ) ); + return NULL; + } for (int i = 0; i < it->m_payloadCount; ++i) { Object* payload = TheThingFactory->newObject( payloadTmpl, owner ); @@ -493,6 +506,7 @@ class DeliverPayloadNugget : public ObjectCreationNugget DEBUG_CRASH(("You should really have a DeliverPayloadAIUpdate here")); } } + return firstTransport; } static void parsePayload( INI* ini, void *instance, void *store, const void* /*userData*/ ) @@ -607,7 +621,7 @@ class ApplyRandomForceNugget : public ObjectCreationNugget { } - virtual void create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const { if (primary) { @@ -635,11 +649,13 @@ class ApplyRandomForceNugget : public ObjectCreationNugget { DEBUG_CRASH(("You must have a primary source for this effect")); } + return NULL; } - virtual void create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const { DEBUG_CRASH(("You must call this effect with an object, not a location")); + return NULL; } static void parse(INI *ini, void *instance, void* /*store*/, const void* /*userData*/) @@ -761,33 +777,35 @@ class GenericObjectCreationNugget : public ObjectCreationNugget m_offset.zero(); } - virtual void create(const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create(const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames = 0 ) const { if (primary) { if (m_skipIfSignificantlyAirborne && primary->isSignificantlyAboveTerrain()) - return; + return NULL; - reallyCreate( primary->getPosition(), primary->getTransformMatrix(), primary->getOrientation(), primary, lifetimeFrames ); + return reallyCreate( primary->getPosition(), primary->getTransformMatrix(), primary->getOrientation(), primary, lifetimeFrames ); } else { DEBUG_CRASH(("You must have a primary source for this effect")); } + return NULL; } - virtual void create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const + virtual Object* create(const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames = 0 ) const { if (primary) { const Matrix3D *xfrm = NULL; - const Real orientation = 0.0; - reallyCreate( primary, xfrm, orientation, primaryObj, lifetimeFrames ); + const Real angle = 0.0; + return reallyCreate( primary, xfrm, angle, primaryObj, lifetimeFrames ); } else { DEBUG_CRASH(("You must have a primary source for this effect")); } + return NULL; } static const FieldParse* getCommonFieldParse() @@ -1207,15 +1225,15 @@ class GenericObjectCreationNugget : public ObjectCreationNugget } } - void reallyCreate(const Coord3D *pos, const Matrix3D *mtx, Real orientation, const Object *sourceObj, UnsignedInt lifetimeFrames ) const + Object* reallyCreate(const Coord3D *pos, const Matrix3D *mtx, Real orientation, const Object *sourceObj, UnsignedInt lifetimeFrames ) const { static const ThingTemplate* debrisTemplate = TheThingFactory->findTemplate("GenericDebris"); if (m_names.size() <= 0) - return; + return NULL; if (m_requiresLivePlayer && (!sourceObj || !sourceObj->getControllingPlayer()->isPlayerActive())) - return; // don't spawn useful objects for dead players. Avoid the zombie units from Yuri's. + return NULL; // don't spawn useful objects for dead players. Avoid the zombie units from Yuri's. // Object type debris might need this information to process visual UpgradeModules. Team *debrisOwner = NULL; @@ -1223,16 +1241,24 @@ class GenericObjectCreationNugget : public ObjectCreationNugget debrisOwner = sourceObj->getControllingPlayer()->getDefaultTeam(); Object* container = NULL; + Object *firstObject = NULL; if (!m_putInContainer.isEmpty()) { const ThingTemplate* containerTmpl = TheThingFactory->findTemplate(m_putInContainer); if (containerTmpl) { container = TheThingFactory->newObject( containerTmpl, debrisOwner ); + if( !container ) + { + DEBUG_CRASH( ("OCL::reallyCreate() failed to create container %s.", m_putInContainer.str() ) ); + return firstObject; + } + firstObject = container; container->setProducer(sourceObj); } } + for (Int nn = 0; nn < m_debrisToGenerate; nn++) { Int pick = GameLogicRandomValue(0, m_names.size() - 1); @@ -1253,6 +1279,15 @@ class GenericObjectCreationNugget : public ObjectCreationNugget continue; Object *debris = TheThingFactory->newObject( tmpl, debrisOwner ); + if( !debris ) + { + DEBUG_CRASH( ("OCL::reallyCreate() failed to create debris %s.", tmpl->getName().str() ) ); + return firstObject; + } + if( !firstObject ) + { + firstObject = debris; + } debris->setProducer(sourceObj); if (m_preserveLayer && sourceObj != NULL && container == NULL) { @@ -1304,6 +1339,8 @@ class GenericObjectCreationNugget : public ObjectCreationNugget if (container) doStuffToObj( container, AsciiString::TheEmptyString, pos, mtx, orientation, sourceObj, lifetimeFrames ); + + return firstObject; } static void parseDebrisObjectNames( INI* ini, void *instance, void *store, const void* /*userData*/ ) @@ -1404,33 +1441,48 @@ void ObjectCreationList::addObjectCreationNugget(ObjectCreationNugget* nugget) } //------------------------------------------------------------------------------------------------- -void ObjectCreationList::create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, Bool createOwner, UnsignedInt lifetimeFrames ) const +Object* ObjectCreationList::createInternal( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, Bool createOwner, UnsignedInt lifetimeFrames ) const { DEBUG_ASSERTCRASH(primaryObj != NULL, ("You should always call OCLs with a non-null primary Obj, even for positional calls, to get team ownership right")); + Object *theFirstObject = NULL; for (ObjectCreationNuggetVector::const_iterator i = m_nuggets.begin(); i != m_nuggets.end(); ++i) { - (*i)->create( primaryObj, primary, secondary, createOwner, lifetimeFrames ); + Object *curObj = (*i)->create( primaryObj, primary, secondary, createOwner, lifetimeFrames ); + if (theFirstObject==NULL) { + theFirstObject = curObj; + } } + return theFirstObject; } //------------------------------------------------------------------------------------------------- -void ObjectCreationList::create( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames ) const +Object* ObjectCreationList::createInternal( const Object* primaryObj, const Coord3D *primary, const Coord3D* secondary, UnsignedInt lifetimeFrames ) const { DEBUG_ASSERTCRASH(primaryObj != NULL, ("You should always call OCLs with a non-null primary Obj, even for positional calls, to get team ownership right")); + Object *theFirstObject = NULL; for (ObjectCreationNuggetVector::const_iterator i = m_nuggets.begin(); i != m_nuggets.end(); ++i) { - (*i)->create( primaryObj, primary, secondary, lifetimeFrames ); + Object *curObj = (*i)->create( primaryObj, primary, secondary, lifetimeFrames ); + if (theFirstObject==NULL) { + theFirstObject = curObj; + } } + return theFirstObject; } //------------------------------------------------------------------------------------------------- -void ObjectCreationList::create( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames ) const +Object* ObjectCreationList::createInternal( const Object* primary, const Object* secondary, UnsignedInt lifetimeFrames ) const { DEBUG_ASSERTCRASH(primary != NULL, ("You should always call OCLs with a non-null primary Obj, even for positional calls, to get team ownership right")); + Object *theFirstObject = NULL; for (ObjectCreationNuggetVector::const_iterator i = m_nuggets.begin(); i != m_nuggets.end(); ++i) { - (*i)->create( primary, secondary, lifetimeFrames ); + Object *curObj = (*i)->create( primary, secondary, lifetimeFrames ); + if (theFirstObject==NULL) { + theFirstObject = curObj; + } } + return theFirstObject; } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index 05e7676dce..d8345fbb8a 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -79,7 +79,7 @@ #include "GameClient/Line2D.h" #include "GameClient/ControlBar.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG //#include "GameClient/InGameUI.h" // for debugHints #include "Common/PlayerList.h" #endif @@ -92,7 +92,7 @@ UnsignedInt s_gcoPerfFrame = 0xffffffff; #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1488,7 +1488,7 @@ void PartitionCell::getCellCenterPos(Real& x, Real& y) } //----------------------------------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void PartitionCell::validateCoiList() { CellAndObjectIntersection *nextCoi = 0, *prevCoi = 0; @@ -2134,7 +2134,7 @@ void PartitionData::invalidateShroudedStatusForAllPlayers() } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) static AsciiString theObjName; #endif @@ -2144,7 +2144,7 @@ Int PartitionData::calcMaxCoiForShape(GeometryType geom, Real majorRadius, Real Int result; if (isSmall) { - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int chk = calcMaxCoiForShape(geom, majorRadius, minorRadius, false); (void)chk; DEBUG_ASSERTCRASH(chk <= 4, ("Small objects should be <= 4 cells, but I calced %s as %d\n",theObjName.str(),chk)); @@ -2186,7 +2186,7 @@ Int PartitionData::calcMaxCoiForObject() Real majorRadius = obj->getGeometryInfo().getMajorRadius(); Real minorRadius = obj->getGeometryInfo().getMinorRadius(); Bool isSmall = obj->getGeometryInfo().getIsSmall(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) theObjName = obj->getTemplate()->getName(); #endif return calcMaxCoiForShape(geom, majorRadius, minorRadius, isSmall); @@ -2688,7 +2688,7 @@ void PartitionManager::shutdown() m_updatedSinceLastReset = false; ThePartitionManager->removeAllDirtyModules(); -#ifdef _DEBUG +#ifdef RTS_DEBUG // the above *should* remove all the touched cells (via unRegisterObject), but let's check: DEBUG_ASSERTCRASH( m_moduleList == NULL, ("hmm, modules left over")); PartitionData *mod, *nextMod; @@ -2772,7 +2772,7 @@ void PartitionManager::update() processPendingUndoShroudRevealQueue(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugThreatMap) { if (TheGameLogic->getFrame() % TheGlobalData->m_debugThreatMapTileDuration) @@ -2832,7 +2832,7 @@ void PartitionManager::update() } } } -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) } // end update //------------------------------------------------------------------------------ @@ -3161,7 +3161,7 @@ void PartitionManager::calcRadiusVec() } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int total = 0; for (Int i = 0; i <= m_maxGcoRadius; ++i) { @@ -3203,7 +3203,7 @@ Object *PartitionManager::getClosestObjects( GetPrecisionTimer(&startTime64); #endif -#ifdef _DEBUG +#ifdef RTS_DEBUG static Int theEntrancyCount = 0; DEBUG_ASSERTCRASH(theEntrancyCount == 0, ("sorry, this routine is not reentrant")); ++theEntrancyCount; @@ -3406,7 +3406,7 @@ Object *PartitionManager::getClosestObjects( *closestDistArg = (Real)sqrtf(closestDistSqr); } -#ifdef _DEBUG +#ifdef RTS_DEBUG --theEntrancyCount; #endif #ifdef DUMP_PERF_STATS @@ -5351,7 +5351,7 @@ Bool PartitionFilterPossibleToAttack::allow(Object *objOther) // return false; // we should have already filtered out isAbleToAttack! -#ifdef _DEBUG +#ifdef RTS_DEBUG // disable this assert for INTERNAL builds (srj) DEBUG_ASSERTCRASH(m_obj && m_obj->isAbleToAttack(), ("if the object is unable to attack at all, you should filter that out ahead of time!")); #endif @@ -5458,8 +5458,7 @@ Bool PartitionFilterStealthedAndUndetected::allow( Object *objOther ) else { //Exception case -- bomb trucks can't be considered stealthed units when they are disguised as the enemy. - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate *update = (StealthUpdate*)objOther->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = objOther->getStealth(); if( update && update->isDisguised() ) { Player *ourPlayer = m_obj->getControllingPlayer(); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp index 59f23bd3a7..2cea6d5d2e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp @@ -98,7 +98,7 @@ void BaikonurLaunchPower::doSpecialPower( UnsignedInt commandOptions ) } // ------------------------------------------------------------------------------------------------ -void BaikonurLaunchPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void BaikonurLaunchPower::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; @@ -106,7 +106,7 @@ void BaikonurLaunchPower::doSpecialPowerAtLocation( const Coord3D *loc, Unsigned const BaikonurLaunchPowerModuleData *data = getBaikonurLaunchPowerModuleData(); // call the base class action cause we are *EXTENDING* functionality - SpecialPowerModule::doSpecialPowerAtLocation( loc, commandOptions ); + SpecialPowerModule::doSpecialPowerAtLocation( loc, angle, commandOptions ); //Create the detonation const ThingTemplate *thing = TheThingFactory->findTemplate( data->m_detonationObject ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp index 1cdb794a59..b1bd94370f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp @@ -97,7 +97,7 @@ CashHackSpecialPower::~CashHackSpecialPower( void ) // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -void CashHackSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void CashHackSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp index f4ef27cc7f..cb9851027e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp @@ -84,7 +84,7 @@ CleanupAreaPower::~CleanupAreaPower() } //------------------------------------------------------------------------------------------------- -void CleanupAreaPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void CleanupAreaPower::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp index 9e40e9ffbf..2edbcf596f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp @@ -90,7 +90,7 @@ DefectorSpecialPower::~DefectorSpecialPower( void ) // ------------------------------------------------------------------------------------------------ -void DefectorSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void DefectorSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp index 08d1a90e54..8665ec5212 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp @@ -98,7 +98,7 @@ DemoralizeSpecialPower::~DemoralizeSpecialPower( void ) // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -void DemoralizeSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void DemoralizeSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; @@ -108,7 +108,7 @@ void DemoralizeSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, Unsig return; // call the base class action cause we are *EXTENDING* functionality - SpecialPowerModule::doSpecialPowerAtLocation( loc, commandOptions ); + SpecialPowerModule::doSpecialPowerAtLocation( loc, angle, commandOptions ); // the source of my fiendish power Object *source = getObject(); @@ -179,13 +179,13 @@ void DemoralizeSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, Unsig // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -void DemoralizeSpecialPower::doSpecialPowerAtObject( const Object *obj, UnsignedInt commandOptions ) +void DemoralizeSpecialPower::doSpecialPowerAtObject( const Object *obj, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; if( obj ) - doSpecialPowerAtLocation( obj->getPosition(), commandOptions ); + doSpecialPowerAtLocation( obj->getPosition(), angle, commandOptions ); } // end doSpecialPowerAtObject diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp index 4e86a03c44..ed5006c196 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp @@ -43,7 +43,7 @@ // MODULE DATA //////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -145,7 +145,7 @@ OCLSpecialPower::~OCLSpecialPower( void ) //------------------------------------------------------------------------------------------------- /** Execute the power */ //------------------------------------------------------------------------------------------------- -void OCLSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void OCLSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; @@ -155,7 +155,7 @@ void OCLSpecialPower::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt return; // call the base class action cause we are *EXTENDING* functionality - SpecialPowerModule::doSpecialPowerAtLocation( loc, commandOptions ); + SpecialPowerModule::doSpecialPowerAtLocation( loc, angle, commandOptions ); const ObjectCreationList* ocl = findOCL(); @@ -207,7 +207,7 @@ void OCLSpecialPower::doSpecialPowerAtObject( Object *obj, UnsignedInt commandOp // convert to a location if( !obj ) return; - doSpecialPowerAtLocation( obj->getPosition(), commandOptions ); + doSpecialPowerAtLocation( obj->getPosition(), INVALID_ANGLE, commandOptions ); } // ------------------------------------------------------------------------------------------------ @@ -220,7 +220,7 @@ void OCLSpecialPower::doSpecialPower( UnsignedInt commandOptions ) creationCoord.set( getObject()->getPosition() ); // call the base class action cause we are *EXTENDING* functionality - SpecialPowerModule::doSpecialPowerAtLocation( &creationCoord, commandOptions ); + SpecialPowerModule::doSpecialPowerAtLocation( &creationCoord, INVALID_ANGLE, commandOptions ); const ObjectCreationList* ocl = findOCL(); ObjectCreationList::create( ocl, getObject(), &creationCoord, &creationCoord, false ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp index 861ac413c3..e985809aa6 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp @@ -39,6 +39,11 @@ /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ @@ -57,7 +62,7 @@ SpecialAbility::~SpecialAbility( void ) // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -void SpecialAbility::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void SpecialAbility::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (getObject()->isDisabled()) return; @@ -67,7 +72,7 @@ void SpecialAbility::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt c return; // call the base class action cause we are *EXTENDING* functionality - SpecialPowerModule::doSpecialPowerAtLocation( loc, commandOptions ); + SpecialPowerModule::doSpecialPowerAtLocation( loc, angle, commandOptions ); } // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp index 32b81cd5f2..62399560e5 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp @@ -46,6 +46,7 @@ #include "GameLogic/Module/DeletionUpdate.h" #include "GameLogic/Module/UpdateModule.h" #include "GameLogic/Module/SpecialPowerModule.h" +#include "GameLogic/Module/SpecialPowerUpdateModule.h" #include "GameLogic/ScriptEngine.h" #include "GameClient/Eva.h" @@ -53,7 +54,7 @@ #include "GameClient/ControlBar.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -269,7 +270,7 @@ Bool SpecialPowerModule::isModuleForPower( const SpecialPowerTemplate *specialPo //------------------------------------------------------------------------------------------------- Bool SpecialPowerModule::isReady() const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // this is a cheat ... remove this for release! if( TheGlobalData->m_specialPowerUsesDelay == FALSE ) return TRUE; @@ -301,7 +302,7 @@ Bool SpecialPowerModule::isReady() const //------------------------------------------------------------------------------------------------- Real SpecialPowerModule::getPercentReady() const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_specialPowerUsesDelay == FALSE ) return 1.0f; #endif @@ -349,7 +350,7 @@ Real SpecialPowerModule::getPercentReady() const //------------------------------------------------------------------------------------------------- void SpecialPowerModule::startPowerRecharge() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // this is a cheat ... remove this for release! if( TheGlobalData->m_specialPowerUsesDelay == FALSE ) return; @@ -388,7 +389,7 @@ void SpecialPowerModule::startPowerRecharge() //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -void SpecialPowerModule::initiateIntentToDoSpecialPower( const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ) +Bool SpecialPowerModule::initiateIntentToDoSpecialPower( const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ) { Bool valid = false; // tell our update modules that we intend to do this special power. @@ -400,7 +401,7 @@ void SpecialPowerModule::initiateIntentToDoSpecialPower( const Object *targetObj //Validate that we are calling the correct module! if( isModuleForPower( getSpecialPowerModuleData()->m_specialPowerTemplate ) ) { - spu->initiateIntentToDoSpecialPower( getSpecialPowerModuleData()->m_specialPowerTemplate, targetObj, targetPos, commandOptions, locationCount ); + spu->initiateIntentToDoSpecialPower( getSpecialPowerModuleData()->m_specialPowerTemplate, targetObj, targetPos, way, commandOptions ); valid = true; } } @@ -414,6 +415,8 @@ void SpecialPowerModule::initiateIntentToDoSpecialPower( const Object *targetObj //DEBUG_CRASH(( "Object does not contain special power module (%s) to execute. Did you forget to add it to the object INI?\n", // command->m_specialPower->getName().str() )); } + + return valid; } //------------------------------------------------------------------------------------------------- @@ -537,7 +540,7 @@ void SpecialPowerModule::doSpecialPower( UnsignedInt commandOptions ) //This tells the update module that we want to do our special power. The update modules //will then start processing each frame. - initiateIntentToDoSpecialPower( NULL, NULL, commandOptions ); + initiateIntentToDoSpecialPower( NULL, NULL, NULL, commandOptions ); //Only trigger the special power immediately if the updatemodule doesn't start the attack. //An example of a case that wouldn't trigger immediately is for a unit that needs to @@ -559,7 +562,7 @@ void SpecialPowerModule::doSpecialPowerAtObject( Object *obj, UnsignedInt comman //This tells the update module that we want to do our special power. The update modules //will then start processing each frame. - initiateIntentToDoSpecialPower( obj, NULL, commandOptions ); + initiateIntentToDoSpecialPower( obj, NULL, NULL, commandOptions ); //Only trigger the special power immediately if the updatemodule doesn't start the attack. //An example of a case that wouldn't trigger immediately is for a unit that needs to @@ -573,7 +576,7 @@ void SpecialPowerModule::doSpecialPowerAtObject( Object *obj, UnsignedInt comman //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -void SpecialPowerModule::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedInt commandOptions ) +void SpecialPowerModule::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions ) { if (m_pausedCount > 0 || getObject()->isDisabled()) { return; @@ -581,7 +584,7 @@ void SpecialPowerModule::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedI //This tells the update module that we want to do our special power. The update modules //will then start processing each frame. - initiateIntentToDoSpecialPower( NULL, loc, commandOptions ); + initiateIntentToDoSpecialPower( NULL, loc, NULL, commandOptions ); //Only trigger the special power immediately if the updatemodule doesn't start the attack. //An example of a case that wouldn't trigger immediately is for a unit that needs to @@ -595,7 +598,7 @@ void SpecialPowerModule::doSpecialPowerAtLocation( const Coord3D *loc, UnsignedI //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -void SpecialPowerModule::doSpecialPowerAtMultipleLocations( const Coord3D *locations, Int locCount, UnsignedInt commandOptions ) +void SpecialPowerModule::doSpecialPowerUsingWaypoints( const Waypoint *way, UnsignedInt commandOptions ) { if (m_pausedCount > 0 || getObject()->isDisabled()) { return; @@ -603,7 +606,7 @@ void SpecialPowerModule::doSpecialPowerAtMultipleLocations( const Coord3D *locat //This tells the update module that we want to do our special power. The update modules //will then start processing each frame. - initiateIntentToDoSpecialPower( NULL, locations, commandOptions, locCount ); + initiateIntentToDoSpecialPower( NULL, NULL, way, commandOptions ); //Only trigger the special power immediately if the updatemodule doesn't start the attack. //An example of a case that wouldn't trigger immediately is for a unit that needs to diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 8634003c69..b5718276fa 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -73,7 +73,7 @@ #define SLEEPY_AI -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2163,7 +2163,7 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void ) // obstacles, and follow the intermediate path points. ClosestPointOnPathInfo info; CRCDEBUG_LOG(("AIUpdateInterface::doLocomotor() - calling computePointOnPath() for %s\n", - DescribeObject(getObject()).str())); + DebugDescribeObject(getObject()).str())); getPath()->computePointOnPath(getObject(), m_locomotorSet, *getObject()->getPosition(), info); onPathDistToGoal = info.distAlongPath; goalPos = info.posOnPath; @@ -2290,7 +2290,7 @@ void AIUpdateInterface::setLocomotorGoalPositionExplicit(const Coord3D& newPos) { m_locomotorGoalType = POSITION_EXPLICIT; m_locomotorGoalData = newPos; -#ifdef _DEBUG +#ifdef RTS_DEBUG if (_isnan(m_locomotorGoalData.x) || _isnan(m_locomotorGoalData.y) || _isnan(m_locomotorGoalData.z)) { DEBUG_CRASH(("NAN in setLocomotorGoalPositionExplicit")); @@ -2303,7 +2303,7 @@ void AIUpdateInterface::setLocomotorGoalOrientation(Real angle) { m_locomotorGoalType = ANGLE; m_locomotorGoalData.x = angle; -#ifdef _DEBUG +#ifdef RTS_DEBUG if (_isnan(m_locomotorGoalData.x) || _isnan(m_locomotorGoalData.y) || _isnan(m_locomotorGoalData.z)) { DEBUG_CRASH(("NAN in setLocomotorGoalOrientation")); @@ -5010,3 +5010,15 @@ Int AIUpdateInterface::friend_getWaypointGoalPathSize() const return getStateMachine()->getGoalPathSize(); } + +// ------------------------------------------------------------------------------------------------ +Bool AIUpdateInterface::hasLocomotorForSurface(LocomotorSurfaceType surfaceType) +{ + LocomotorSurfaceTypeMask surfaceMask = (LocomotorSurfaceTypeMask)surfaceType; + if (m_locomotorSet.findLocomotor(surfaceMask)) + return TRUE; + else + return FALSE; +} + +// ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp index 99dc57b347..da0c9b3c2a 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp @@ -43,7 +43,7 @@ #include "GameLogic/PartitionManager.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp index 4419431935..de824bfba5 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -48,7 +48,7 @@ const Real BIGNUM = 99999.0f; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp index 65a5933674..5eae915004 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp @@ -49,7 +49,7 @@ #include "GameLogic/Weapon.h" #include "GameLogic/WeaponSet.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -304,7 +304,7 @@ void DeliverPayloadAIUpdate::deliverPayload( // must make the state machine AFTER initing the other stuff, since it may inquire of its values... m_deliverPayloadStateMachine = newInstance(DeliverPayloadStateMachine)( getObject() ); m_deliverPayloadStateMachine->initDefaultState(); -#ifdef _DEBUG +#ifdef RTS_DEBUG m_deliverPayloadStateMachine->setName("DeliverPayloadSpecificAI"); #endif } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp index bad1c5fcce..48062d7aa4 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp @@ -46,7 +46,7 @@ #include "GameLogic/Module/DeployStyleAIUpdate.h" #include "GameLogic/Module/PhysicsUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp index 3f272c82a5..18c0d93145 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp @@ -55,7 +55,7 @@ #include "GameLogic/Module/DozerAIUpdate.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2114,6 +2114,9 @@ void DozerAIUpdate::internalCancelTask( DozerTask task ) // sanity DEBUG_ASSERTCRASH( task >= 0 && task < DOZER_NUM_TASKS, ("Illegal dozer task '%d'\n", task) ); + + if(task < 0 || task >= DOZER_NUM_TASKS) + return; //DAMNIT! You CANNOT assert and then not handle the damn error! The. Code. Must. Not. Crash. // call the single method that gets called for completing and canceling tasks internalTaskCompleteOrCancelled( task ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp index cf2d4c677b..e87acdf362 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Object.h" //#include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -164,12 +164,31 @@ void HackInternetAIUpdate::hackInternet() // must make the state machine AFTER initing the other stuff, since it may inquire of its values... //m_hackInternetStateMachine = newInstance(HackInternetStateMachine)( getObject() ); //m_hackInternetStateMachine->initDefaultState(); -#ifdef _DEBUG +#ifdef RTS_DEBUG //m_hackInternetStateMachine->setName("HackInternetSpecificAI"); #endif getStateMachine()->setState(UNPACKING); } +// ------------------------------------------------------------------------------------------------ +UnsignedInt HackInternetAIUpdate::getUnpackTime() const +{ + // Not yet contained at the time this is queried + return getHackInternetAIUpdateModuleData()->m_unpackTime; +} + +// ------------------------------------------------------------------------------------------------ +UnsignedInt HackInternetAIUpdate::getPackTime() const +{ + return getHackInternetAIUpdateModuleData()->m_packTime; +} + +// ------------------------------------------------------------------------------------------------ +UnsignedInt HackInternetAIUpdate::getCashUpdateDelay() const +{ + return getHackInternetAIUpdateModuleData()->m_cashUpdateDelay; +} + // ------------------------------------------------------------------------------------------------ /** CRC */ // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp index 4fec10cdb7..12d0b138d1 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp @@ -48,7 +48,7 @@ const Real BIGNUM = 99999.0f; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -136,7 +136,7 @@ class PartitionFilterHasParkingPlace : public PartitionFilter public: PartitionFilterHasParkingPlace(ObjectID id) : m_id(id) { } protected: -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterHasParkingPlace"; } #endif virtual Bool allow(Object *objOther) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp index 749d288212..725840f56d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp @@ -52,7 +52,7 @@ const Real BIGNUM = 99999.0f; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -338,7 +338,7 @@ Bool MissileAIUpdate::projectileHandleCollision( Object *other ) const ContainedItemsList* items = contain->getContainedItemsList(); if (items) { - for (ContainedItemsList::const_iterator it = items->begin(); *it != NULL && numKilled < d->m_garrisonHitKillCount; ) + for (ContainedItemsList::const_iterator it = items->begin(); it != items->end() && numKilled < d->m_garrisonHitKillCount; ) { Object* thingToKill = *it++; if (!thingToKill->isEffectivelyDead() && thingToKill->isKindOfMulti(d->m_garrisonHitKillKindof, d->m_garrisonHitKillKindofNot)) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp index 2838c0a558..8ca6f8849d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp @@ -58,7 +58,7 @@ static const Int INVALID_PATH = -1; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -871,7 +871,7 @@ class PartitionFilterIsValidCarriage : public PartitionFilter PartitionFilterIsValidCarriage(Object* obj, const RailroadBehaviorModuleData* data) : m_obj(obj), m_data(data) { } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterIsValidCarriage"; } #endif diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp index 6755ef023f..b1884d6df0 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp @@ -41,7 +41,7 @@ #include "GameClient/Drawable.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp index 78b51aed7d..652a3f7ea2 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp @@ -36,7 +36,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp index 2b27ebe9ca..7cc2be21d9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp @@ -43,6 +43,7 @@ #include "Common/RandomValue.h" #include "Common/GlobalData.h" #include "Common/ResourceGatheringManager.h" +#include "Common/Upgrade.h" #include "GameClient/Drawable.h" #include "GameClient/GameText.h" @@ -61,7 +62,7 @@ #include "GameLogic/Module/WorkerAIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -205,7 +206,7 @@ void WorkerAIUpdate::createMachines( void ) m_workerMachine->initDefaultState();// this has to wait until all three are in place since // an immediate transition check will ask questions of the machines. -//#ifdef _DEBUG +//#ifdef RTS_DEBUG // m_workerMachine->setDebugOutput(TRUE); // m_dozerMachine->setDebugOutput(TRUE); // m_supplyTruckStateMachine->setDebugOutput(TRUE); @@ -775,6 +776,9 @@ void WorkerAIUpdate::internalCancelTask( DozerTask task ) // sanity DEBUG_ASSERTCRASH( task >= 0 && task < DOZER_NUM_TASKS, ("Illegal dozer task '%d'\n", task) ); + + if(task < 0 || task >= DOZER_NUM_TASKS) + return; //DAMNIT! You CANNOT assert and then not handle the damn error! The. Code. Must. Not. Crash. // call the single method that gets called for completing and canceling tasks internalTaskCompleteOrCancelled( task ); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp index f63b490d33..2526e17f4c 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp @@ -41,6 +41,15 @@ #include "GameLogic/Module/AssistedTargetingUpdate.h" #include "GameLogic/Module/LaserUpdate.h" + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- void AssistedTargetingUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp index 5ce3820628..37cb378d64 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/AutoDepositUpdate.cpp @@ -68,7 +68,36 @@ #include "GameClient/GameText.h" //----------------------------------------------------------------------------- // DEFINES //////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- +void parseUpgradePair( INI *ini, void *instance, void *store, const void *userData ) +{ + upgradePair info; + info.type = ""; + info.amount = 0; + + const char *token = ini->getNextToken( ini->getSepsColon() ); + + if ( stricmp(token, "UpgradeType") == 0 ) + { + token = ini->getNextTokenOrNull( ini->getSepsColon() ); + if (!token) throw INI_INVALID_DATA; + + info.type = token; + } + else + throw INI_INVALID_DATA; + + + token = ini->getNextTokenOrNull( ini->getSepsColon() ); + if ( stricmp(token, "Boost") == 0 ) + info.amount = INI::scanInt(ini->getNextToken( ini->getSepsColon() )); + else + throw INI_INVALID_DATA; + + // Insert the info into the upgrade list + std::list * theList = (std::list*)store; + theList->push_back(info); + +} // end parseFactionObjectCreationList //----------------------------------------------------------------------------- // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp index 5db7bb2257..8c3eb42b98 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/Module/StealthDetectorUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -264,12 +264,12 @@ void BattlePlanUpdate::onObjectCreated() } //------------------------------------------------------------------------------------------------- -void BattlePlanUpdate::initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ) +Bool BattlePlanUpdate::initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ) { if( m_specialPowerModule->getSpecialPowerTemplate() != specialPowerTemplate ) { //Check to make sure our modules are connected. - return; + return FALSE; } //Set the desired status based on the command button option! @@ -285,6 +285,13 @@ void BattlePlanUpdate::initiateIntentToDoSpecialPower(const SpecialPowerTemplate { m_desiredPlan = PLANSTATUS_SEARCHANDDESTROY; } + else + { + DEBUG_CRASH( ("Selected an unsupported strategy for strategy center.") ); + return FALSE; + } + + return TRUE; } Bool BattlePlanUpdate::isPowerCurrentlyInUse( const CommandButton *command ) const diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp index 6486e2c323..80979372ab 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp @@ -46,7 +46,7 @@ #include "GameLogic/WeaponSet.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp index 67db6b2ac1..6321cc43a4 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp @@ -52,7 +52,7 @@ #include "GameLogic/Module/SpecialPowerModule.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp index 315760aa89..6e7a12218b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp @@ -59,7 +59,7 @@ DeletionUpdate::~DeletionUpdate( void ) void DeletionUpdate::setLifetimeRange( UnsignedInt minFrames, UnsignedInt maxFrames ) { -#if defined _DEBUG && defined CRISS_CROSS_GEOMETRY +#if defined RTS_DEBUG && defined CRISS_CROSS_GEOMETRY setWakeFrame(getObject(), UPDATE_SLEEP(2)); #else UnsignedInt delay = calcSleepDelay(minFrames, maxFrames); @@ -82,7 +82,7 @@ UnsignedInt DeletionUpdate::calcSleepDelay(UnsignedInt minFrames, UnsignedInt ma UpdateSleepTime DeletionUpdate::update( void ) { // Destroy (NOT kill) if time is up -#if defined _DEBUG && defined CRISS_CROSS_GEOMETRY +#if defined RTS_DEBUG && defined CRISS_CROSS_GEOMETRY Object *obj = getObject(); if (obj) { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp index eb8fab038d..1e9131b938 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp @@ -501,7 +501,9 @@ void DockUpdate::loadDockPositions() if( m_numberApproachPositions != DYNAMIC_APPROACH_VECTOR_FLAG ) { // Dynamic means no bones - Coord3D approachBones[DEFAULT_APPROACH_VECTOR_SIZE]; + // TheSuperHackers @fix helmutbuhler 19/04/2025 Zero initialize array to prevent uninitialized memory reads. + // Important: the entire target vector is used for serialization and crc and must not contain random data. + Coord3D approachBones[DEFAULT_APPROACH_VECTOR_SIZE] = {0}; m_numberApproachPositionBones = myDrawable->getPristineBonePositions( "DockWaiting", 1, approachBones, NULL, m_numberApproachPositions); if( m_numberApproachPositions == m_approachPositions.size() )//safeguard: will always be true { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp index 6d53258aa0..12b9b40e5c 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp @@ -38,7 +38,7 @@ #include "GameLogic/PartitionManager.h" #include "GameLogic/AIPathfind.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp index 9558f6e05a..b24f982587 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp @@ -37,7 +37,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp index 8878bee1ea..fd15889b50 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp @@ -48,7 +48,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp index e0bbaa0780..df413ad986 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp @@ -51,6 +51,12 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/Module/BodyModule.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + //------------------------------------------------------------------------------------------------- FireOCLAfterWeaponCooldownUpdateModuleData::FireOCLAfterWeaponCooldownUpdateModuleData() { diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp index 15e884008b..c004860d70 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp @@ -51,7 +51,7 @@ class PartitionFilterFlammable : public PartitionFilter PartitionFilterFlammable(){ } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterFlammable"; } #endif }; diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp index 956224c556..4e95b74946 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp @@ -35,7 +35,7 @@ #include "GameLogic/Module/FireWeaponUpdate.h" #include "GameLogic/WeaponStatus.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -87,13 +87,27 @@ FireWeaponUpdate::~FireWeaponUpdate( void ) UpdateSleepTime FireWeaponUpdate::update( void ) { // If my weapon is ready, shoot it. - if( m_weapon && m_weapon->getStatus() == READY_TO_FIRE ) + if( isOkayToFire() ) { m_weapon->forceFireWeapon( getObject(), getObject()->getPosition() ); } return UPDATE_SLEEP_NONE; } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +Bool FireWeaponUpdate::isOkayToFire() +{ + if( m_weapon == NULL ) + return FALSE; + + // Weapon is reloading + if( m_weapon->getStatus() != READY_TO_FIRE ) + return FALSE; + + return TRUE; +} + // ------------------------------------------------------------------------------------------------ /** CRC */ // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp index e2cd8d4c3a..670271cb3e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp @@ -40,7 +40,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp index 544aff90a0..5cbf6cc7e9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Module/HeightDieUpdate.h" #include "GameLogic/Module/PhysicsUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp index d072d2d337..98ecd1ce6d 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp @@ -55,7 +55,7 @@ /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp index 5043c8d598..57b71869ba 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp @@ -47,7 +47,7 @@ //------------------------------------------------------------------------------------------------- -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -79,7 +79,7 @@ class PartitionFilterHordeMember : public PartitionFilter PartitionFilterHordeMember(Object* obj, const HordeUpdateModuleData* data) : m_obj(obj), m_data(data) { } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterHordeMember"; } #endif diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp index 036e728c3a..998e52fd81 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Module/LifetimeUpdate.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp index beaa99eb13..f19fe7ada9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp @@ -41,7 +41,7 @@ #include "GameClient/Drawable.h" #include "GameClient/FXList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -185,7 +185,7 @@ void MissileLauncherBuildingUpdate::switchToState(DoorStateType dst) TheAudio->removeAudioEvent(m_openIdleAudio.getPlayingHandle()); } break; -#ifdef _DEBUG +#ifdef RTS_DEBUG default: DEBUG_CRASH(("unknown state")); break; @@ -203,13 +203,14 @@ void MissileLauncherBuildingUpdate::switchToState(DoorStateType dst) } //------------------------------------------------------------------------------------------------- -void MissileLauncherBuildingUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ) +Bool MissileLauncherBuildingUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(!TheGlobalData->m_specialPowerUsesDelay || m_doorState == DOOR_OPEN, ("door is not fully open when specialpower is fired!")); #endif switchToState(DOOR_WAITING_TO_CLOSE); + return TRUE; } //------------------------------------------------------------------------------------------------- @@ -250,7 +251,7 @@ UpdateSleepTime MissileLauncherBuildingUpdate::update( void ) switchToState(m_timeoutState); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(!TheGlobalData->m_specialPowerUsesDelay || !(m_specialPowerModule->isReady() && m_doorState != DOOR_OPEN), ("door is not fully open when specialpower is ready!")); #endif diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp index 86b3bd9b39..48a3a4971f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp @@ -55,7 +55,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp index b1ae089b6a..f4422f9ae7 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp @@ -59,7 +59,7 @@ #include "GameLogic/Module/LaserUpdate.h" #include "GameLogic/Module/ActiveBody.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -268,14 +268,14 @@ void ParticleUplinkCannonUpdate::onObjectCreated() } //------------------------------------------------------------------------------------------------- -void ParticleUplinkCannonUpdate::initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, UnsignedInt commandOptions, Int locationCount ) +Bool ParticleUplinkCannonUpdate::initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ) { const ParticleUplinkCannonUpdateModuleData *data = getParticleUplinkCannonUpdateModuleData(); if( m_specialPowerModule->getSpecialPowerTemplate() != specialPowerTemplate ) { //Check to make sure our modules are connected. - return; + return FALSE; } if( !BitIsSet( commandOptions, COMMAND_FIRED_BY_SCRIPT ) ) @@ -306,6 +306,7 @@ void ParticleUplinkCannonUpdate::initiateIntentToDoSpecialPower(const SpecialPow SpecialPowerModule *spModule = (SpecialPowerModule*)spmInterface; spModule->markSpecialPowerTriggered( &m_initialTargetPosition ); } + return TRUE; } //------------------------------------------------------------------------------------------------- @@ -870,7 +871,8 @@ void ParticleUplinkCannonUpdate::createGroundToOrbitLaser( UnsignedInt growthFra if( beam ) { TheGameClient->destroyDrawable( beam ); - m_orbitToTargetBeamID = INVALID_DRAWABLE_ID; + // TheSuperHackers @fix helmutbuhler 19/04/2025 Invalidate the relevant drawable ID. + m_groundToOrbitBeamID = INVALID_DRAWABLE_ID; } if( data->m_particleBeamLaserName.isNotEmpty() ) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp index 7b59b43f0e..b79daea4c5 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp @@ -63,7 +63,7 @@ const Int MOTIVE_FRAMES = LOGICFRAMES_PER_SECOND / 3; #define SLEEPY_PHYSICS -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp index 908dddc4c5..cdace6f8c7 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp @@ -38,7 +38,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/PowerPlantUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp index 7d953dce32..56fc57d9aa 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp @@ -55,7 +55,7 @@ #include "GameLogic/Object.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -217,6 +217,8 @@ ProductionUpdate::~ProductionUpdate( void ) production = m_productionQueue; removeFromProductionQueue( production ); + // TheSuperHackers @fix Mauller 13/04/2025 Delete instance of production item + production->deleteInstance(); } // end while diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp index 94a5a9d2ba..9f706cb5cf 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Module/ProjectileStreamUpdate.h" #include "WWMath/vector3.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp index d015fa46eb..d4b5ea35ce 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp @@ -50,7 +50,7 @@ #include "GameLogic/Module/SlavedUpdate.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp index f15bb6c1f6..3962be8f6b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp @@ -63,7 +63,7 @@ #include "GameLogic/Module/StealthUpdate.h" #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -380,11 +380,11 @@ UpdateSleepTime SpecialAbilityUpdate::update( void ) } //------------------------------------------------------------------------------------------------- -void SpecialAbilityUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTemplate *specialPowerTemplate, +Bool SpecialAbilityUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, - UnsignedInt commandOptions, - Int locationCount ) + const Waypoint *way, + UnsignedInt commandOptions ) { const SpecialAbilityUpdateModuleData* data = getSpecialAbilityUpdateModuleData(); const SpecialPowerTemplate *spTemplate = data->m_specialPowerTemplate; @@ -392,7 +392,7 @@ void SpecialAbilityUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTem if( spTemplate != specialPowerTemplate ) { //Check to make sure our modules are connected. - return; + return FALSE; } //Clear target values @@ -418,13 +418,12 @@ void SpecialAbilityUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTem { //Get the position! m_targetPos = *targetPos; - m_locationCount = locationCount; } //Clear any old AI before starting this special ability. if( !getObject()->getAIUpdateInterface() ) { - return; + return FALSE; } getObject()->getAIUpdateInterface()->aiIdle( CMD_FROM_AI ); @@ -459,6 +458,8 @@ void SpecialAbilityUpdate::initiateIntentToDoSpecialPower( const SpecialPowerTem setWakeFrame(getObject(), UPDATE_SLEEP_NONE); + + return TRUE; } //------------------------------------------------------------------------------------------------- @@ -580,8 +581,7 @@ Bool SpecialAbilityUpdate::handlePackingProcessing() if( getSpecialAbilityUpdateModuleData()->m_loseStealthOnTrigger && m_animFrames < getSpecialAbilityUpdateModuleData()->m_preTriggerUnstealthFrames) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)getObject()->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = getObject()->getStealth(); if( stealth ) { stealth->markAsDetected(); @@ -1440,10 +1440,9 @@ void SpecialAbilityUpdate::triggerAbilityEffect() case SPECIAL_DISGUISE_AS_VEHICLE: { Object *target = TheGameLogic->findObjectByID( m_targetID ); - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); if( target ) { - StealthUpdate *update = (StealthUpdate*)object->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = object->getStealth(); if( update ) { update->disguiseAsObject( target ); @@ -1456,8 +1455,7 @@ void SpecialAbilityUpdate::triggerAbilityEffect() if( data->m_loseStealthOnTrigger && okToLoseStealth) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)object->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = object->getStealth(); if( stealth ) { stealth->markAsDetected(); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp index 70c4d631c7..106fe566cc 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp @@ -50,7 +50,7 @@ #include "Common/PlayerList.h" #include "Common/Player.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -120,7 +120,7 @@ class PartitionFilterStealthedOrStealthGarrisoned : public PartitionFilter virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterStealthedOrStealthGarrisoned"; } #endif }; @@ -207,8 +207,7 @@ UpdateSleepTime StealthDetectorUpdate::update( void ) if ( them->isEffectivelyDead() ) continue; - static NameKeyType key_StealthUpdate = NAMEKEY("StealthUpdate"); - StealthUpdate* stealth = (StealthUpdate *)them->findUpdateModule(key_StealthUpdate); + StealthUpdate* stealth = them->getStealth(); if ( stealth ) { @@ -324,8 +323,7 @@ UpdateSleepTime StealthDetectorUpdate::update( void ) { rider = *it; - static NameKeyType key_StealthUpdate = NAMEKEY("StealthUpdate"); - StealthUpdate* stealth = (StealthUpdate *)rider->findUpdateModule(key_StealthUpdate); + StealthUpdate* stealth = rider->getStealth(); if ( stealth ) { // we have found someone diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp index 907a1579c6..74f7b3f460 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp @@ -58,7 +58,7 @@ #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -411,6 +411,10 @@ UpdateSleepTime StealthUpdate::update( void ) { //Switch models at the halfway point changeVisualDisguise(); + + // TheSuperHackers @fix Skyaero 06/05/2025 obtain the new drawable + draw = getObject()->getDrawable(); + m_disguiseHalfpointReached = true; } //Opacity ranges from full to none at midpoint and full again at the end @@ -647,8 +651,7 @@ void StealthUpdate::disguiseAsObject( const Object *target ) const StealthUpdateModuleData *data = getStealthUpdateModuleData(); if( target && target->getControllingPlayer() ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)target->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = target->getStealth(); if( stealth && stealth->getDisguisedTemplate() ) { m_disguiseAsTemplate = stealth->getDisguisedTemplate(); @@ -756,7 +759,9 @@ void StealthUpdate::changeVisualDisguise() const ThingTemplate *tTemplate = self->getTemplate(); - TheThingFactory->newDrawable( tTemplate ); + // TheSuperHackers @fix helmutbuhler 13/04/2025 Fixes missing pointer assignment for the new drawable. + // This originally caused no runtime crash because the new drawable is allocated at the same address as the previously deleted drawable via the MemoryPoolBlob. + draw = TheThingFactory->newDrawable( tTemplate ); if( draw ) { TheGameLogic->bindObjectAndDrawable(self, draw); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp index dfd74a376c..6439347f66 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp @@ -48,7 +48,7 @@ #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp index 64fa09084b..1075711f56 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp @@ -47,7 +47,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -76,7 +76,7 @@ class PartitionFilterTensileFormationMember : public PartitionFilter public: PartitionFilterTensileFormationMember( Object* obj ) : m_obj( obj ) { } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterTensileFormationMember"; } #endif virtual Bool allow( Object *objOther ) diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp index 02627d0045..f4148d27f9 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp @@ -33,7 +33,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Module/UpdateModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -116,7 +116,7 @@ void UpdateModule::xfer( Xfer *xfer ) // extend base class BehaviorModule::xfer( xfer ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /* this is a fix for the following scenario: diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp index 00d5359b90..c059dde8a0 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp @@ -32,7 +32,7 @@ #include "Common/Xfer.h" #include "GameLogic/Module/UpgradeModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 1b750f0854..5be602c13b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -86,7 +86,7 @@ const DistanceCalculationType ATTACK_RANGE_CALC_TYPE = FROM_BOUNDINGSPHERE_3D; #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -743,11 +743,37 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate ObjectID* projectileID ) const { + + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + AsciiString targetStr; + if( TheGlobalData->m_extraLogging ) + { + if( victimObj ) + targetStr.format( "%s", victimObj->getTemplate()->getName().str() ); + else if( victimPos ) + targetStr.format( "%d,%d,%d", victimPos->x, victimPos->y, victimPos->z ); + else + targetStr.format( "SELF." ); + + DEBUG_LOG( ("%d - WeaponTemplate::fireWeaponTemplate() begin - %s attacking %s - ", + TheGameLogic->getFrame(), sourceObj->getTemplate()->getName().str(), targetStr.str() ) ); + } + #endif + //end -extraLogging + //CRCDEBUG_LOG(("WeaponTemplate::fireWeaponTemplate() from %s\n", DescribeObject(sourceObj).str())); DEBUG_ASSERTCRASH(specificBarrelToUse >= 0, ("specificBarrelToUse should no longer be -1\n")); if (sourceObj == NULL || (victimObj == NULL && victimPos == NULL)) { + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("FAIL 1 (sourceObj %d == NULL || (victimObj %d == NULL && victimPos %d == NULL)\n", sourceObj != 0, victimObj != 0, victimPos != 0) ); + #endif + //end -extraLogging + return 0; } @@ -819,6 +845,14 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate if (distSqr > attackRangeSqr) { //DEBUG_ASSERTCRASH(distSqr < 5*5 || distSqr < attackRangeSqr*1.2f, ("*** victim is out of range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(attackRangeSqr))); + + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("FAIL 2 (distSqr %.2f > attackRangeSqr %.2f)\n", distSqr, attackRangeSqr ) ); + #endif + //end -extraLogging + return 0; } } @@ -833,6 +867,14 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate #endif { DEBUG_ASSERTCRASH(distSqr > minAttackRangeSqr*0.8f, ("*** victim is closer than min attack range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(minAttackRangeSqr))); + + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("FAIL 3 (distSqr %.2f< minAttackRangeSqr %.2f - 0.5f && !isProjectileDetonation %d)\n", distSqr, minAttackRangeSqr, isProjectileDetonation ) ); + #endif + //end -extraLogging + return 0; } } @@ -921,6 +963,15 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate // go ahead and do it now //DEBUG_LOG(("WeaponTemplate::fireWeaponTemplate: firing weapon immediately!\n")); dealDamageInternal(sourceID, damageID, damagePos, bonus, isProjectileDetonation); + + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("EARLY 4 (delayed damage applied now)\n") ); + #endif + //end -extraLogging + + return TheGameLogic->getFrame(); } else @@ -933,6 +984,15 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate //DEBUG_LOG(("WeaponTemplate::fireWeaponTemplate: firing weapon in %d frames (= %d)!\n", delayInWholeFrames,when)); TheWeaponStore->setDelayedDamage(this, damagePos, when, sourceID, damageID, bonus); } + + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("EARLY 5 (delaying damage applied until frame %d)\n", when ) ); + #endif + //end -extraLogging + + return when; } } @@ -1040,6 +1100,13 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate // actually, this is ok, for things like Firestorm.... (srj) projectile->setPosition(&projectileDestination); } + //-extraLogging + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + if( TheGlobalData->m_extraLogging ) + DEBUG_LOG( ("DONE\n") ); + #endif + //end -extraLogging + return 0; } } @@ -1518,7 +1585,7 @@ void WeaponStore::postProcessLoad() if (weapon->m_projectileName.isNone()) weapon->m_projectileName.clear(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!weapon->getFireSound().getEventName().isEmpty() && weapon->getFireSound().getEventName().compareNoCase("NoSound") != 0) { DEBUG_ASSERTCRASH(TheAudio->isValidAudioEvent(&weapon->getFireSound()), ("Invalid FireSound %s in Weapon '%s'.", weapon->getFireSound().getEventName().str(), weapon->getName().str())); diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp index 55fe5b9ed1..a53d702f91 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp @@ -53,7 +53,7 @@ #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -425,7 +425,6 @@ Bool WeaponSet::isAnyWithinTargetPitch(const Object* obj, const Object* victim) //------------------------------------------------------------------------------------------------- CanAttackResult WeaponSet::getAbleToAttackSpecificObject( AbleToAttackType attackType, const Object* source, const Object* victim, CommandSourceType commandSource ) const { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); // basic sanity checks. if (!source || @@ -467,7 +466,7 @@ CanAttackResult WeaponSet::getAbleToAttackSpecificObject( AbleToAttackType attac // force-attack allows you to attack disguised things, which also happen to be stealthed. // since we normally disallow attacking stealthed things (even via force-fire), we check // for disguised and explicitly ignore stealth in that case - StealthUpdate *update = (StealthUpdate*)victim->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = victim->getStealth(); if (update && update->isDisguised()) allowStealthToPreventAttacks = FALSE; } @@ -485,7 +484,7 @@ CanAttackResult WeaponSet::getAbleToAttackSpecificObject( AbleToAttackType attac else { //Exception case -- don't return false if we are a bomb truck disguised as an enemy vehicle. - StealthUpdate *update = (StealthUpdate*)victim->findUpdateModule( key_StealthUpdate ); + StealthUpdate *update = victim->getStealth(); if( update && update->isDisguised() ) { Player *ourPlayer = source->getControllingPlayer(); diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp index 479049651c..6cf5f7c2c8 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp @@ -81,7 +81,7 @@ #include "GameLogic/Weapon.h" #include "GameLogic/VictoryConditions.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -3104,7 +3104,7 @@ void ScriptActions::doMergeTeamIntoTeam(const AsciiString& teamSrcName, const As //------------------------------------------------------------------------------------------------- void ScriptActions::doDisableInput() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_disableScriptedInputDisabling) #endif { @@ -3589,7 +3589,7 @@ void ScriptActions::doUnfreezeTime(void) //------------------------------------------------------------------------------------------------- void ScriptActions::doMilitaryCaption(const AsciiString& briefing, Int duration) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_disableMilitaryCaption) duration = 1; #endif @@ -3893,7 +3893,7 @@ void ScriptActions::doNamedFireSpecialPowerAtWaypoint( const AsciiString& unit, if (!way) { return; } - mod->doSpecialPowerAtLocation(way->getLocation(), COMMAND_FIRED_BY_SCRIPT ); + mod->doSpecialPowerAtLocation(way->getLocation(), INVALID_ANGLE, COMMAND_FIRED_BY_SCRIPT ); } } } @@ -3936,10 +3936,9 @@ void ScriptActions::doSkirmishFireSpecialPowerAtMostCost( const AsciiString &pla SpecialPowerModuleInterface *mod = pObj->getSpecialPowerModule(power); if (mod) { - mod->doSpecialPowerAtLocation( &location, COMMAND_FIRED_BY_SCRIPT ); + mod->doSpecialPowerAtLocation( &location, INVALID_ANGLE, COMMAND_FIRED_BY_SCRIPT ); break; } - } } } diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp index 74f761df89..c6a4868690 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Scripts.h" #include "GameLogic/VictoryConditions.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 03ff9b0ec5..3e56599931 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -56,7 +56,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/SidesList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -104,7 +104,7 @@ Bool st_particleSystemNeedsStopping = FALSE; ///< Set along with st_particleSyst #define FORMAT_STRING_LEADING_STRING "%s%.2f" // That's it for particle editor -#if defined(_INTERNAL) +#if defined(RTS_INTERNAL) #define DO_VTUNE_STUFF #endif @@ -193,7 +193,7 @@ Int AttackPriorityInfo::getPriority(const ThingTemplate *tThing) const return priority; } -#ifdef _DEBUG +#ifdef RTS_DEBUG /** Dump the info. */ //------------------------------------------------------------------------------------------------- void AttackPriorityInfo::dumpPriorityInfo(void) @@ -4880,7 +4880,7 @@ void ScriptEngine::update( void ) _adjustVariable(m_flags[k].name.str(), m_flags[k].value); } } -#ifdef _DEBUG +#ifdef RTS_DEBUG if (TheGameLogic->getFrame()==0) { for (i=0; im_disableCameraFade) { m_fade = FADE_NONE; @@ -8609,7 +8609,7 @@ void ScriptEngine::loadPostProcess( void ) } // end loadPostProcess -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void ScriptEngine::debugVictory( void ) { ScriptAction *action = newInstance(ScriptAction)(ScriptAction::VICTORY); diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp index 800721b112..5415b24e2f 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp @@ -66,7 +66,7 @@ #include "GameLogic/SidesList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2372,7 +2372,7 @@ Bool ScriptAction::ParseActionDataChunk(DataChunkInput &file, DataChunkInfo *inf pScriptAction->m_actionType = (enum ScriptActionType)file.readInt(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) const ActionTemplate* at = TheScriptEngine->getActionTemplate(pScriptAction->m_actionType); if (at && (at->getName().isEmpty() || (at->getName().compareNoCase("(placeholder)") == 0))) { DEBUG_CRASH(("Invalid Script Action found in script '%s'\n", pScript->getName().str())); diff --git a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp index 9b598efc71..c75633340b 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp @@ -51,7 +51,7 @@ #include "GameNetwork/GameInfo.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index e0086435cd..3879f0674e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -122,7 +122,7 @@ FILE *g_UT_commaLog=NULL; #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -421,10 +421,6 @@ void GameLogic::reset( void ) m_thingTemplateBuildableOverrides.clear(); m_controlBarOverrides.clear(); - // destroy all objects - // TheSuperHackers @info xezon 10/04/2025 Objects need to be destroyed before clearing the object hash. - destroyAllObjectsImmediate(); - // set the hash to be rather large. We need to optimize this value later. m_objHash.clear(); #if USING_STLPORT @@ -437,6 +433,9 @@ void GameLogic::reset( void ) m_mouseVisibleMemory = TRUE; setFPMode(); + // destroy all objects + destroyAllObjectsImmediate(); + m_nextObjID = (ObjectID)1; m_frameObjectsChangedTriggerAreas = 0; @@ -978,6 +977,15 @@ void GameLogic::startNewGame( Bool saveGame ) GetPrecisionTimer(&startTime64); #endif + // reset the frame counter + m_frame = 0; + +#ifdef DEBUG_CRC + // TheSuperHackers @info helmutbuhler 04/09/2025 + // Let CRC Logger know that a new game was started. + CRCDebugStartNewGame(); +#endif + if( saveGame == FALSE ) { @@ -1028,6 +1036,7 @@ void GameLogic::startNewGame( Bool saveGame ) m_rankLevelLimit = 1000; // this is reset every game. setDefaults( saveGame ); TheWritableGlobalData->m_loadScreenRender = TRUE; ///< mark it so only a few select things are rendered during load + TheWritableGlobalData->m_TiVOFastMode = FALSE; //always disable the TIVO fast-forward mode at the start of a new game. m_showBehindBuildingMarkers = TRUE; m_drawIconUI = TRUE; @@ -1124,8 +1133,7 @@ void GameLogic::startNewGame( Bool saveGame ) if(m_loadScreen) updateLoadProgress(LOAD_PROGRESS_POST_PARTICLE_INI_LOAD); - // reset the frame counter - m_frame = 0; + DEBUG_ASSERTCRASH(m_frame == 0, ("framecounter expected to be 0 here\n")); // before loading the map, load the map.ini file in the same directory. loadMapINI( TheGlobalData->m_mapName ); @@ -2228,7 +2236,7 @@ void GameLogic::processCommandList( CommandList *list ) for( msg = list->getFirstMessage(); msg; msg = msg->next() ) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(msg != NULL && msg != (GameMessage*)0xdeadbeef, ("bad msg")); #endif logicMessageDispatcher( msg, NULL ); @@ -3122,7 +3130,7 @@ void GameLogic::update( void ) Bool generateForMP = (isMPGameOrReplay && (m_frame % TheGameInfo->getCRCInterval()) == 0); #ifdef DEBUG_CRC Bool generateForSolo = isSoloGameOrReplay && ((m_frame && (m_frame%100 == 0)) || - (getFrame() > TheCRCFirstFrameToLog && getFrame() < TheCRCLastFrameToLog && ((m_frame % REPLAY_CRC_INTERVAL) == 0))); + (getFrame() >= TheCRCFirstFrameToLog && getFrame() < TheCRCLastFrameToLog && ((m_frame % REPLAY_CRC_INTERVAL) == 0))); #else Bool generateForSolo = isSoloGameOrReplay && ((m_frame % REPLAY_CRC_INTERVAL) == 0); #endif // DEBUG_CRC @@ -3135,14 +3143,14 @@ void GameLogic::update( void ) GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_LOGIC_CRC ); msg->appendIntegerArgument( m_CRC ); msg->appendBooleanArgument( (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK) ); // playback CRC - //DEBUG_LOG(("Appended CRC of %8.8X on frame %d\n", m_CRC, m_frame)); + DEBUG_LOG(("Appended CRC on frame %d: %8.8X\n", m_frame, m_CRC)); } else { GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_LOGIC_CRC ); msg->appendIntegerArgument( m_CRC ); msg->appendBooleanArgument( (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK) ); // playback CRC - //DEBUG_LOG(("Appended Playback CRC of %8.8X on frame %d\n", m_CRC, m_frame)); + DEBUG_LOG(("Appended Playback CRC on frame %d: %8.8X\n", m_frame, m_CRC)); } } @@ -3478,6 +3486,12 @@ UnsignedInt GameLogic::getCRC( Int mode, AsciiString deepCRCFileName ) { AsciiString crcName; #ifdef DEBUG_CRC + // TheSuperHackers @info helmutbuhler 04/09/2025 + // This allows you to save the binary data that is involved in the crc calculation + // to a binary file per frame. + // This was apparently used early in development and isn't that useful, because diffing + // that binary data is very difficult. The CRC logging is much easier to diff and also more + // granular than this because it can capture changes between two frames. if (isInGameLogicUpdate() && g_keepCRCSaves && m_frame < 5) { xferCRC = NEW XferDeepCRC; @@ -3693,7 +3707,6 @@ void GameLogic::setGamePaused( Bool paused, Bool pauseMusic ) while( drawable ) { drawable->startAmbientSound(); - TheAudio->stopAllAmbientsBy( drawable ); drawable = drawable->getNextDrawable(); } } diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 31c36e00a1..042c55643e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -85,7 +85,7 @@ #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -342,7 +342,7 @@ void GameLogic::prepareNewGame( Int gameMode, GameDifficulty diff, Int rankPoint //------------------------------------------------------------------------------------------------- void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(msg != NULL && msg != (GameMessage*)0xdeadbeef, ("bad msg")); #endif @@ -443,7 +443,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) case GameMessage::MSG_CLEAR_GAME_DATA: { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheDisplay && TheGlobalData->m_dumpAssetUsage) TheDisplay->dumpAssetUsage(TheGlobalData->m_mapName.str()); #endif @@ -691,7 +691,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) { AIGroup* theGroup = TheAI->createGroup(); theGroup->add(source); - theGroup->groupDoSpecialPowerAtLocation( specialPowerID, &targetCoord, objectInWay, options ); + theGroup->groupDoSpecialPowerAtLocation( specialPowerID, &targetCoord, INVALID_ANGLE, objectInWay, options ); TheAI->destroyGroup(theGroup); } else @@ -699,7 +699,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) //Use the selected group! if( currentlySelectedGroup ) { - currentlySelectedGroup->groupDoSpecialPowerAtLocation( specialPowerID, &targetCoord, objectInWay, options ); + currentlySelectedGroup->groupDoSpecialPowerAtLocation( specialPowerID, &targetCoord, INVALID_ANGLE, objectInWay, options ); } } break; @@ -888,7 +888,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) break; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DEBUG_KILL_SELECTION: { @@ -1917,13 +1917,13 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) if (thisPlayer->isLocalPlayer()) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // don't even put this in release, cause someone might hack it. if (!TheDebugIgnoreSyncErrors) { #endif m_shouldValidateCRCs = TRUE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } #endif } diff --git a/Generals/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp b/Generals/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp index a234bc8db4..39eaea660e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp @@ -35,12 +35,34 @@ RankInfoStore* TheRankInfoStore = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif +//----------------------------------------------------------------------------- +RankInfo::~RankInfo() +{ +} + + +//----------------------------------------------------------------------------- +RankInfoStore::~RankInfoStore() +{ + Int level; + for (level =0; level < getRankLevelCount(); level++) + { + RankInfo* ri = m_rankInfos[level]; + if (ri) + { + ri->deleteInstance(); + } + } + m_rankInfos.clear(); +} + + //----------------------------------------------------------------------------- void RankInfoStore::init() { diff --git a/Generals/Code/GameEngine/Source/GameNetwork/Connection.cpp b/Generals/Code/GameEngine/Source/GameNetwork/Connection.cpp index 4a91ac1cff..6b87fb074a 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/Connection.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/Connection.cpp @@ -206,14 +206,14 @@ void Connection::sendNetCommandMsg(NetCommandMsg *msg, UnsignedByte relay) { if (ref != NULL) { /* -#if ((defined(_DEBUG)) || (defined(_INTERNAL))) +#if ((defined(RTS_DEBUG)) || (defined(RTS_INTERNAL))) if (msg->getNetCommandType() == NETCOMMANDTYPE_GAMECOMMAND) { DEBUG_LOG(("Connection::sendNetCommandMsg - added game command %d to net command list for frame %d.\n", msg->getID(), msg->getExecutionFrame())); } else if (msg->getNetCommandType() == NETCOMMANDTYPE_FRAMEINFO) { DEBUG_LOG(("Connection::sendNetCommandMsg - added frame info for frame %d\n", msg->getExecutionFrame())); } -#endif // _DEBUG || _INTERNAL +#endif // RTS_DEBUG || RTS_INTERNAL */ ref->setRelay(relay); @@ -371,7 +371,7 @@ NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte ori return NULL; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool doDebug = FALSE; if (temp->getCommand()->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) { doDebug = TRUE; @@ -384,7 +384,7 @@ NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte ori m_averageLatency += lat / CONNECTION_LATENCY_HISTORY_LENGTH; m_latencies[index] = lat; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug == TRUE) { DEBUG_LOG(("Connection::processAck - disconnect frame command %d found, removing from command list.\n", commandID)); } @@ -411,7 +411,7 @@ void Connection::doRetryMetrics() { } } -#if defined(_DEBUG) || (_INTERNAL) +#if defined(RTS_DEBUG) || (RTS_INTERNAL) void Connection::debugPrintCommands() { NetCommandRef *ref = m_netCommandList->getFirstMessage(); while (ref != NULL) { diff --git a/Generals/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/Generals/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp index a4183201f7..10214452d1 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp @@ -53,7 +53,7 @@ #include "GameClient/DisconnectMenu.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -682,7 +682,7 @@ void ConnectionManager::processChat(NetChatCommandMsg *msg) void ConnectionManager::processFile(NetFileCommandMsg *msg) { -#ifdef _INTERNAL +#ifdef RTS_INTERNAL UnicodeString log; log.format(L"Saw file transfer: '%hs' of %d bytes from %d", msg->getPortableFilename().str(), msg->getFileLength(), msg->getPlayerID()); DEBUG_LOG(("%ls\n", log.str())); @@ -827,14 +827,14 @@ void ConnectionManager::processFrameInfo(NetFrameCommandMsg *msg) { * it doesn't keep resending it. */ void ConnectionManager::processAckStage1(NetCommandMsg *msg) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool doDebug = (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) ? TRUE : FALSE; #endif UnsignedByte playerID = msg->getPlayerID(); NetCommandRef *ref = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug == TRUE) { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::processAck - processing ack for command %d from player %d\n", ((NetAckStage1CommandMsg *)msg)->getCommandID(), playerID)); } @@ -1035,7 +1035,7 @@ void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) { } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool doDebug = (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) ? TRUE : FALSE; #endif @@ -1045,7 +1045,7 @@ void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) { ackmsg = bothmsg; commandID = bothmsg->getCommandID(); originalPlayerID = bothmsg->getOriginalPlayerID(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug) { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::ackCommand - doing ack both for command %d from player %d\n", bothmsg->getCommandID(), bothmsg->getOriginalPlayerID())); } @@ -1055,7 +1055,7 @@ void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) { ackmsg = stage1msg; commandID = stage1msg->getCommandID(); originalPlayerID = stage1msg->getOriginalPlayerID(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug) { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::ackCommand - doing ack stage 1 for command %d from player %d\n", stage1msg->getCommandID(), stage1msg->getOriginalPlayerID())); } @@ -1554,7 +1554,7 @@ Int commandsReadyDebugSpewage = 0; */ Bool ConnectionManager::allCommandsReady(UnsignedInt frame, Bool justTesting /* = FALSE */) { Bool retval = TRUE; - FrameDataReturnType frameRetVal; + FrameDataReturnType frameRetVal = FRAMEDATA_NOTREADY; // retval = FALSE; // ****for testing purposes only!!!!!!**** Int i = 0; for (; (i < MAX_SLOTS) && retval; ++i) { @@ -2329,7 +2329,7 @@ Int ConnectionManager::getSlotAverageFPS(Int slot) { return m_fpsAverages[slot]; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void ConnectionManager::debugPrintConnectionCommands() { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::debugPrintConnectionCommands - begin commands\n")); for (Int i = 0; i < MAX_SLOTS; ++i) { @@ -2361,7 +2361,7 @@ void ConnectionManager::notifyOthersOfCurrentFrame(Int frame) { msg->detach(); DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::notifyOthersOfCurrentFrame - start screen on debug stuff\n")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) debugPrintConnectionCommands(); #endif } diff --git a/Generals/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp b/Generals/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp index bc25662af1..968d681054 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp @@ -35,7 +35,7 @@ #include "GameNetwork/GameSpy/PingThread.h" #include "GameNetwork/GameSpy/GSConfig.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp b/Generals/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp index b34d115042..cb5975f885 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp @@ -56,7 +56,7 @@ #include "GameNetwork/NetworkDefs.h" #include "GameNetwork/GameSpy/GSConfig.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp index aa0a44db6f..f7eb013b31 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp @@ -44,7 +44,7 @@ #include "Common/PlayerTemplate.h" #include "GameNetwork/LANAPICallbacks.h" // for acceptTrueColor, etc -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameInfo.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameInfo.cpp index d1a7ecc847..f854efa7ed 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameInfo.cpp @@ -45,7 +45,7 @@ #include "GameNetwork/LANAPICallbacks.h" // for testing packet size #include "strtok_r.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp index 69e7b65979..2bd368d922 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp @@ -37,7 +37,7 @@ #include "GameNetwork/GameSpy/PeerDefsImplementation.h" #include "GameNetwork/GameSpy/PeerThread.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp index 60be316d5e..f8f6e98cbe 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp @@ -36,7 +36,7 @@ #include "GameNetwork/GameSpy/GSConfig.h" #include "GameNetwork/RankPointValue.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp index 31f213fd26..cf8336b358 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp @@ -39,7 +39,7 @@ #include "GameClient/GameText.h" #include "GameClient/MapUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp index 72071c2a90..6961a9d16a 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp @@ -62,7 +62,7 @@ #include "Common/STLTypedefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp index 7bec02e582..0d8cb1a8ea 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp @@ -54,7 +54,7 @@ #include "WWDownload/Registry.h" #include "WWDownload/urlBuilder.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp index 9f930de290..aebd617cc5 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp @@ -46,7 +46,7 @@ #include "GameNetwork/RankPointValue.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp index be20575ee4..490c41545e 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp @@ -48,7 +48,7 @@ #include "GameNetwork/NAT.h" #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -584,7 +584,7 @@ void GameSpyStagingRoom::startGame(Int gameID) } } -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (numHumans < 2) { launchGame(); @@ -592,7 +592,7 @@ void GameSpyStagingRoom::startGame(Int gameID) TheGameSpyInfo->leaveStagingRoom(); } else -//#endif // defined(_DEBUG) || defined(_INTERNAL) +//#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) { TheNAT = NEW NAT(); TheNAT->attachSlotList(m_slot, getLocalSlotNum(), m_localIP); @@ -669,7 +669,7 @@ AsciiString GameSpyStagingRoom::generateGameSpyGameResultsPacket( void ) Int gsPlayerID = slot->getProfileID(); Bool disconnected = slot->disconnected(); - AsciiString result = "loss", side = "USA"; + AsciiString result = "loss"; if (disconnected) result = "discon"; else if (TheNetwork->sawCRCMismatch()) @@ -677,9 +677,9 @@ AsciiString GameSpyStagingRoom::generateGameSpyGameResultsPacket( void ) else if (TheVictoryConditions->hasAchievedVictory(p)) result = "win"; - side = p->getPlayerTemplate()->getSide(); + AsciiString side = p->getPlayerTemplate()->getSide(); if (side == "America") - side = "USA"; + side = "USA"; //conform to GameSpy AsciiString playerStr; playerStr.format("\\player_%d\\%s\\pid_%d\\%d\\team_%d\\%d\\result_%d\\%s\\side_%d\\%s", diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp index 410dbeed1d..b970e4c4f0 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp @@ -41,7 +41,7 @@ #include "mutex.h" #include "thread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp index b9642a9f0d..653c1ba238 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp @@ -48,7 +48,7 @@ #include "Common/MiniLog.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -84,7 +84,7 @@ static LogClass s_stateChangedLog("StateChanged.txt"); // -MDC 2/14/2003 #define USE_BROADCAST_KEYS -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp index 1802928f37..c23cbfbec8 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp @@ -41,7 +41,7 @@ #include "Common/StackDump.h" #include "Common/SubsystemInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp b/Generals/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp index 2d17ff3db4..2a6fb008ec 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp @@ -135,7 +135,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo case L'r': case L'R': remainder.nextToken(&token); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (token.compareNoCase(L"raw") == 0) { // Send raw IRC commands (Ascii only) @@ -149,7 +149,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo } #endif break; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL case L'k': case L'K': remainder.nextToken(&token); @@ -194,7 +194,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo } return true; // show it anyway } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL else if (token.compareNoCase(L"oper") == 0) { // Send raw IRC oper command @@ -245,7 +245,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo return true; // show it anyway } break; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL case L'c': case L'C': remainder.nextToken(&token); @@ -262,7 +262,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo return true; // show it anyway } break; -#endif // _DEBUG || defined _INTERNAL +#endif // RTS_DEBUG || defined RTS_INTERNAL } } */ diff --git a/Generals/Code/GameEngine/Source/GameNetwork/LANAPI.cpp b/Generals/Code/GameEngine/Source/GameNetwork/LANAPI.cpp index 2764d7c61f..948fd0e3af 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/LANAPI.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/LANAPI.cpp @@ -38,7 +38,7 @@ #include "Common/UserPreferences.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -263,7 +263,7 @@ AsciiString GetMessageTypeString(UnsignedInt type) void LANAPI::checkMOTD( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_useLocalMOTD) { // for a playtest, let's log some play statistics, eh? diff --git a/Generals/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/Generals/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp index 2e8628cc95..006c270e9b 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp @@ -50,7 +50,7 @@ LANAPI *TheLAN = NULL; extern Bool LANbuttonPushed; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/Generals/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp index c0d1a3ed38..cd410527f0 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp @@ -232,7 +232,7 @@ void LANAPI::handleRequestJoin( LANMessage *msg, UnsignedInt senderIP ) Bool canJoin = true; // see if the CRCs match -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_netMinPlayers > 0) { #endif if (msg->GameToJoin.iniCRC != TheGlobalData->m_iniCRC || @@ -247,10 +247,12 @@ void LANAPI::handleRequestJoin( LANMessage *msg, UnsignedInt senderIP ) reply.GameNotJoined.playerIP = senderIP; canJoin = false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } #endif +// TheSuperHackers @tweak Disables the duplicate serial check +#if 0 // check for a duplicate serial AsciiString s; for (player = 0; canJoin && player m_playersToDisconnect; GameWindow *m_messageWindow; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_networkOn; #endif }; @@ -279,7 +279,7 @@ Network::Network() m_conMgr = NULL; m_messageWindow = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_networkOn = TRUE; #endif } @@ -362,7 +362,7 @@ void Network::init() DEBUG_LOG(("FRAMES_TO_KEEP = %d\n", FRAMES_TO_KEEP)); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_networkOn = TRUE; #endif @@ -380,7 +380,8 @@ void Network::setSawCRCMismatch( void ) TheRecorder->logCRCMismatch(); // dump GameLogic random seed - DEBUG_LOG(("GameLogic frame = %d\n", TheGameLogic->getFrame())); + DEBUG_LOG(("Latest frame for mismatch = %d GameLogic frame = %d\n", + TheGameLogic->getFrame()-m_runAhead-1, TheGameLogic->getFrame())); DEBUG_LOG(("GetGameLogicRandomSeedCRC() = %d\n", GetGameLogicRandomSeedCRC())); // dump CRCs @@ -691,7 +692,7 @@ void Network::update( void ) // m_frameDataReady = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (m_networkOn == FALSE) { return; } @@ -725,7 +726,7 @@ void Network::update( void ) void Network::liteupdate() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (m_networkOn == FALSE) { return; } @@ -749,7 +750,7 @@ void Network::endOfGameCheck() { DEBUG_LOG(("Network::endOfGameCheck - about to show the shell\n")); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) else { m_conMgr->debugPrintConnectionCommands(); } @@ -1011,7 +1012,7 @@ Int Network::getSlotAverageFPS(Int slot) { return -1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void Network::toggleNetworkOn() { if (m_networkOn == TRUE) { m_networkOn = FALSE; diff --git a/Generals/Code/GameEngine/Source/GameNetwork/Transport.cpp b/Generals/Code/GameEngine/Source/GameNetwork/Transport.cpp index 20103dac33..f46da8cb8e 100644 --- a/Generals/Code/GameEngine/Source/GameNetwork/Transport.cpp +++ b/Generals/Code/GameEngine/Source/GameNetwork/Transport.cpp @@ -29,7 +29,7 @@ #include "GameNetwork/Transport.h" #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -136,7 +136,7 @@ Bool Transport::init( UnsignedInt ip, UnsignedShort port ) { m_outBuffer[i].length = 0; m_inBuffer[i].length = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_delayedInBuffer[i].message.length = 0; #endif } @@ -154,7 +154,7 @@ Bool Transport::init( UnsignedInt ip, UnsignedShort port ) m_port = port; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_latencyAverage > 0 || TheGlobalData->m_latencyNoise) m_useLatency = true; @@ -249,7 +249,7 @@ Bool Transport::doSend() { } } // for (i=0; iRead(buf, MAX_MESSAGE_LEN, &from)) > 0 ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // Packet loss simulation if (m_usePacketLoss) { @@ -332,7 +332,7 @@ Bool Transport::doRecv() for (int i=0; i SetAsciiString; typedef SetAsciiString::iterator SetAsciiStringIt; SetAsciiString m_allEventsLoaded; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/Common/W3DRadar.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/Common/W3DRadar.h index 0f7745bd81..b60b0967e1 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/Common/W3DRadar.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/Common/W3DRadar.h @@ -76,12 +76,12 @@ class W3DRadar : public Radar void initializeTextureFormats( void ); ///< find format to use for the radar texture void deleteResources( void ); ///< delete resources used void drawEvents( Int pixelX, Int pixelY, Int width, Int height); ///< draw all of the radar events - void drawHeroIcon( Int pixelX, Int pixelY, Int width, Int height, const Coord3D *pos ); //< draw a hero icon + void drawHeroIcon( Int pixelX, Int pixelY, Int width, Int height, const Coord3D *pos ); //< draw a hero icon void drawViewBox( Int pixelX, Int pixelY, Int width, Int height ); ///< draw view box void buildTerrainTexture( TerrainLogic *terrain ); ///< create the terrain texture of the radar void drawIcons( Int pixelX, Int pixelY, Int width, Int height ); ///< draw all of the radar icons void renderObjectList( const RadarObject *listHead, TextureClass *texture, Bool calcHero = FALSE ); ///< render an object list to the texture - void interpolateColorForHeight( RGBColor *color, + void interpolateColorForHeight( RGBColor *color, Real height, Real hiZ, Real midZ, @@ -118,7 +118,7 @@ class W3DRadar : public Radar Real m_viewZoom; ///< camera zoom used for the view box we have ICoord2D m_viewBox[ 4 ]; ///< radar cell points for the 4 corners of view box - std::list m_cachedHeroPosList; //< cache of hero positions for drawing icons in radar overlay + std::list m_cachedHeroPosList; //< cache of hero positions for drawing icons in radar overlay }; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 46509f32cc..7305c4e073 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -175,7 +175,7 @@ struct ModelConditionInfo Int m_fxBone; ///< the FX bone for this barrel (zero == no bone) Int m_muzzleFlashBone; ///< the muzzle-flash subobj bone for this barrel (zero == none) Matrix3D m_projectileOffsetMtx; ///< where the projectile fires from -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString m_muzzleFlashBoneName; #endif @@ -190,7 +190,7 @@ struct ModelConditionInfo m_fxBone = 0; m_muzzleFlashBone = 0; m_projectileOffsetMtx.Make_Identity(); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) m_muzzleFlashBoneName.clear(); #endif } @@ -199,7 +199,7 @@ struct ModelConditionInfo }; typedef std::vector WeaponBarrelInfoVec; -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString m_description; #endif std::vector m_conditionsYesVec; @@ -248,7 +248,7 @@ struct ModelConditionInfo inline Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(m_conditionsYesVec.size() > 0, ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } inline const ModelConditionFlags& getNthConditionsYes(Int i) const { return m_conditionsYesVec[i]; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline AsciiString getDescription() const { return m_description; } #endif @@ -350,7 +350,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual void releaseShadows(void); ///< frees all shadow resources used by this module - used by Options screen. virtual void allocateShadows(void); ///< create shadow resources if not already present. Used by Options screen. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void getRenderCost(RenderCost & rc) const; ///< estimates the render cost of this draw module void getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) const; #endif @@ -508,7 +508,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface void adjustAnimSpeedToMovementSpeed(); static void hideAllMuzzleFlashes(const ModelConditionInfo* state, RenderObjClass* renderObject); void hideAllHeadlights(Bool hide); -#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test. +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //art wants to see buildings without flags as a test. void hideGarrisonFlags(Bool hide); #endif }; diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h index 88c863ea4e..3403e1d4be 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h @@ -54,7 +54,6 @@ class Vector3; class VertexMaterialClass; -class GrannyAnimManagerClass; class W3DAssetManager: public WW3DAssetManager { @@ -103,8 +102,6 @@ class W3DAssetManager: public WW3DAssetManager int replaceHLODTexture(RenderObjClass *robj, TextureClass *oldTex, TextureClass *newTex); int replaceMeshTexture(RenderObjClass *robj, TextureClass *oldTex, TextureClass *newTex); - GrannyAnimManagerClass *m_GrannyAnimManager; - //'E&B' customizations /* virtual RenderObjClass * Create_Render_Obj(const char * name, float scale, const Vector3 &hsv_shift); TextureClass * Get_Texture_With_HSV_Shift(const char * filename, const Vector3 &hsv_shift, MipCountType mip_level_count = MIP_LEVELS_ALL); diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h index 2d211d249e..de0823f65e 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h @@ -33,7 +33,7 @@ #include "vertmaterial.h" #include "Lib/BaseType.h" -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL struct DebugIcon; // /// W3DDebugIcons: Draws huge numbers of debug icons for pathfinding quickly. @@ -76,6 +76,6 @@ class W3DDebugIcons : public RenderObjClass public: static void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); }; -#endif // _DEBUG or _INTERNAL +#endif // RTS_DEBUG or RTS_INTERNAL #endif // end __W3D_DEBUG_ICONS_H_ diff --git a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h index 16c89505d4..b88aa035fd 100644 --- a/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h +++ b/Generals/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h @@ -71,7 +71,7 @@ class W3DDisplay : public Display virtual void getDisplayModeDescription(Int modeIndex, Int *xres, Int *yres, Int *bitDepth); ///removeShadow(this);} ///removeShadow(this);} ///m_preloadReport) { @@ -127,7 +127,7 @@ AudioHandle MilesAudioManager::addAudioEvent( const AudioEventRTS *eventToAdd ) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------------------------------- void MilesAudioManager::audioDebugDisplay(DebugDisplayInterface *dd, void *, FILE *fp ) { @@ -446,7 +446,7 @@ void MilesAudioManager::init() AudioManager::init(); #ifdef INTENSE_DEBUG DEBUG_LOG(("Sound has temporarily been disabled in debug builds only. jkmcd\n")); - // for now, _DEBUG builds only should have no sound. ask jkmcd or srj about this. + // for now, RTS_DEBUG builds only should have no sound. ask jkmcd or srj about this. return; #endif @@ -467,13 +467,17 @@ void MilesAudioManager::postProcessLoad() //------------------------------------------------------------------------------------------------- void MilesAudioManager::reset() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) dumpAllAssetsUsed(); m_allEventsLoaded.clear(); #endif AudioManager::reset(); stopAllAudioImmediately(); + removeAllAudioRequests(); + // This must come after stopAllAudioImmediately() and removeAllAudioRequests(), to ensure that + // sounds pointing to the temporary AudioEventInfo handles are deleted before their info is deleted + removeLevelSpecificAudioEventInfos(); } //------------------------------------------------------------------------------------------------- @@ -603,6 +607,7 @@ void MilesAudioManager::pauseAudio( AudioAffect which ) } } + //------------------------------------------------------------------------------------------------- void MilesAudioManager::resumeAudio( AudioAffect which ) { @@ -652,19 +657,6 @@ void MilesAudioManager::pauseAmbient( Bool shouldPause ) } -//------------------------------------------------------------------------------------------------- -void MilesAudioManager::stopAllAmbientsBy( Object *obj ) -{ - -} - -//------------------------------------------------------------------------------------------------- -void MilesAudioManager::stopAllAmbientsBy( Drawable *draw ) -{ - -} - - //------------------------------------------------------------------------------------------------- void MilesAudioManager::playAudioEvent( AudioEventRTS *event ) { @@ -1174,6 +1166,16 @@ void MilesAudioManager::stopAllAudioImmediately( void ) it = m_playingStreams.erase(it); } + for (it = m_fadingAudio.begin(); it != m_fadingAudio.end(); ) { + playing = (*it); + if (!playing) { + continue; + } + + releasePlayingAudio(playing); + it = m_fadingAudio.erase(it); + } + std::list::iterator hit; for (hit = m_audioForcePlayed.begin(); hit != m_audioForcePlayed.end(); ++hit) { if (*hit) { @@ -2390,6 +2392,44 @@ void MilesAudioManager::processPlayingList( void ) } } +//Patch for a rare bug (only on about 5% of in-studio machines suffer, and not all the time) . +//The actual mechanics of this problem are still elusive as of the date of this comment. 8/21/03 +//but the cause is clear. Some cinematics do a radical change in the microphone position, which +//calls for a radical 3DSoundVolume adjustment. If this happens while a stereo stream is *ENDING*, +//low-level code gets caught in a tight loop. (Hangs) on some machines. +//To prevent this condition, we just suppress the updating of 3DSoundVolume while one of these +//is on the list. Since the music tracks play continuously, they never *END* during these cinematics. +//so we filter them out as, *NOT SENSITIVE*... we do want to update 3DSoundVolume during music, +//which is almost all of the time. + +Bool MilesAudioManager::has3DSensitiveStreamsPlaying( void ) const +{ + if ( m_playingStreams.empty() ) + return FALSE; + + for ( std::list< PlayingAudio* >::const_iterator it = m_playingStreams.begin(); it != m_playingStreams.end(); ++it ) + { + const PlayingAudio *playing = (*it); + + if ( ! playing ) + continue; + + if ( playing->m_audioEventRTS->getAudioEventInfo()->m_soundType != AT_Music ) + { + return TRUE; + } + + if ( playing->m_audioEventRTS->getEventName().startsWith("Game_") == FALSE ) + { + return TRUE; + } + } + + return FALSE; + +} + + //------------------------------------------------------------------------------------------------- void MilesAudioManager::processFadingList( void ) { @@ -2489,7 +2529,14 @@ Bool MilesAudioManager::checkForSample( AudioRequest *req ) return true; } - if (req->m_pendingEvent->getAudioEventInfo()->m_type != AT_SoundEffect) { + if ( req->m_pendingEvent->getAudioEventInfo() == NULL ) + { + // Fill in event info + getInfoForAudioEvent( req->m_pendingEvent ); + } + + if (req->m_pendingEvent->getAudioEventInfo()->m_type != AT_SoundEffect) + { return true; } @@ -3017,7 +3064,7 @@ void AILCALLBACK setStreamCompleted( HSTREAM streamCompleted ) //------------------------------------------------------------------------------------------------- U32 AILCALLBACK streamingFileOpen(char const *fileName, U32 *file_handle) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (sizeof(U32) != sizeof(File*)) { RELEASE_CRASH(("streamingFileOpen - This function requires work in order to compile on non 32-bit platforms.\n")); } @@ -3277,7 +3324,7 @@ Bool AudioFileCache::freeEnoughSpaceForSample(const OpenAudioFile& sampleThatNee } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------------------------------- void MilesAudioManager::dumpAllAssetsUsed() { diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp index 284379cd1b..5b4b7d9754 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp @@ -48,18 +48,20 @@ #include "GameClient/Image.h" #include "GameClient/Line2D.h" #include "GameClient/TerrainVisual.h" +#include "GameClient/Water.h" #include "W3DDevice/Common/W3DRadar.h" #include "W3DDevice/GameClient/HeightMap.h" #include "W3DDevice/GameClient/W3DShroud.h" #include "WW3D2/texture.h" #include "WW3D2/dx8caps.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif + // PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// enum { OVERLAY_REFRESH_RATE = 6 }; ///< over updates once this many frames @@ -277,8 +279,6 @@ void W3DRadar::drawHeroIcon( Int pixelX, Int pixelY, Int width, Int height, cons } } - - //------------------------------------------------------------------------------------------------- /** Draw a "box" into the texture passed in that represents the viewable area for * the tactical display into the game world */ @@ -616,7 +616,6 @@ void W3DRadar::drawIcons( Int pixelX, Int pixelY, Int width, Int height ) } } - //------------------------------------------------------------------------------------------------- /** Render an object list into the texture passed in */ //------------------------------------------------------------------------------------------------- @@ -698,8 +697,7 @@ void W3DRadar::renderObjectList( const RadarObject *listHead, TextureClass *text // Now it twinkles for any stealthed object, whether locally controlled or neutral-observier-viewed if( obj->testStatus( OBJECT_STATUS_STEALTHED ) ) { - static NameKeyType key_StealthUpdate = NAMEKEY( "StealthUpdate" ); - StealthUpdate* stealth = (StealthUpdate*)obj->findUpdateModule( key_StealthUpdate ); + StealthUpdate* stealth = obj->getStealth(); if( !stealth ) continue; @@ -1035,9 +1033,9 @@ void W3DRadar::buildTerrainTexture( TerrainLogic *terrain ) m_reconstructViewBox = TRUE; // setup our water color - waterColor.red = 0.55f; - waterColor.green = 0.55f; - waterColor.blue = 1.0f; + waterColor.red = TheWaterTransparency->m_radarColor.red; + waterColor.green = TheWaterTransparency->m_radarColor.green; + waterColor.blue = TheWaterTransparency->m_radarColor.blue; // get the terrain surface to draw in surface = m_terrainTexture->Get_Surface_Level(); @@ -1269,7 +1267,7 @@ void W3DRadar::buildTerrainTexture( TerrainLogic *terrain ) //------------------------------------------------------------------------------------------------- void W3DRadar::clearShroud() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_shroudOn) return; #endif @@ -1289,7 +1287,7 @@ void W3DRadar::clearShroud() //------------------------------------------------------------------------------------------------- void W3DRadar::setShroudLevel(Int shroudX, Int shroudY, CellShroudStatus setting) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_shroudOn) return; #endif @@ -1426,7 +1424,7 @@ void W3DRadar::draw( Int pixelX, Int pixelY, Int width, Int height ) TheDisplay->drawImage( m_overlayImage, ul.x, ul.y, lr.x, lr.y ); // draw the shroud image -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_shroudOn ) #else if (true) @@ -1467,3 +1465,154 @@ void W3DRadar::refreshTerrain( TerrainLogic *terrain ) buildTerrainTexture( terrain ); } // end refreshTerrain + + + + + +///The following is an "archive" of an attempt to foil the mapshroud hack... saved for later, since it is too close to release to try it + + +/* + * + void W3DRadar::renderObjectList( const RadarObject *listHead, TextureClass *texture, Bool calcHero ) +{ + + // sanity + if( listHead == NULL || texture == NULL ) + return; + + // get surface for texture to render into + SurfaceClass *surface = texture->Get_Surface_Level(); + + // loop through all objects and draw + ICoord2D radarPoint; + + Player *player = ThePlayerList->getLocalPlayer(); + Int playerIndex=0; + if (player) + playerIndex=player->getPlayerIndex(); + + UnsignedByte minAlpha = 8; + + if( calcHero ) + { + // clear all entries from the cached hero object list + m_cachedHeroPosList.clear(); + } + + for( const RadarObject *rObj = listHead; rObj; rObj = rObj->friend_getNext() ) + { + UnsignedByte h = (UnsignedByte)(rObj->isTemporarilyHidden()); + if ( h ) + continue; + + UnsignedByte a = 0; + + // get object + const Object *obj = rObj->friend_getObject(); + UnsignedByte r = 1; // all decoys + + // cache hero object positions for drawing in icon layer + if( calcHero && obj->isHero() ) + { + m_cachedHeroPosList.push_back(obj->getPosition()); + } + + // get the color we're going to draw in + UnsignedInt c = 0xfe000000;// this is a decoy + c |= (UnsignedInt)( obj->testStatus( OBJECT_STATUS_STEALTHED ) );//so is this + + // check for shrouded status + UnsignedByte k = (UnsignedByte)(obj->getShroudedStatus(playerIndex) > OBJECTSHROUD_PARTIAL_CLEAR); + if ( k || a) + continue; //object is fogged or shrouded, don't render it. + + // + // objects with a local only unit priority will only appear on the radar if they + // are controlled by the local player, or if the local player is an observer (cause + // they are godlike and can see everything) + // + if( obj->getRadarPriority() == RADAR_PRIORITY_LOCAL_UNIT_ONLY && + obj->getControllingPlayer() != ThePlayerList->getLocalPlayer() && + ThePlayerList->getLocalPlayer()->isPlayerActive() ) + continue; + + UnsignedByte g = c|a; + UnsignedByte b = h|a; + // get object position + const Coord3D *pos = obj->getPosition(); + + // compute object position as a radar blip + radarPoint.x = pos->x / (m_mapExtent.width() / RADAR_CELL_WIDTH); + radarPoint.y = pos->y / (m_mapExtent.height() / RADAR_CELL_HEIGHT); + + + const UnsignedInt framesForTransition = LOGICFRAMES_PER_SECOND; + + + + // adjust the alpha for stealth units so they "fade/blink" on the radar for the controller + // if( obj->getRadarPriority() == RADAR_PRIORITY_LOCAL_UNIT_ONLY ) + // ML-- What the heck is this? local-only and neutral-observier-viewed units are stealthy?? Since when? + // Now it twinkles for any stealthed object, whether locally controlled or neutral-observier-viewed + c = rObj->getColor(); + + if( g & r ) + { + Real alphaScale = INT_TO_REAL(TheGameLogic->getFrame() % framesForTransition) / (framesForTransition * 0.5f); + minAlpha <<= 2; // decoy + + if ( ( obj->isLocallyControlled() == (Bool)a ) // another decoy, comparing the return of this non-inline with a local + && !obj->testStatus( OBJECT_STATUS_DISGUISED ) + && !obj->testStatus( OBJECT_STATUS_DETECTED ) + && ++a != 0 // The trick is that this increment does not occur unless all three above conditions are true + && minAlpha == 32 // tricksy hobbit decoy + && c != 0 ) // ditto + { + g = (UnsignedByte)(rObj->getColor()); + continue; + } + + a |= k | b; + GameGetColorComponentsWithCheatSpy( c, &r, &g, &b, &a );//this function does not touch the low order bit in 'a' + + + if( alphaScale > 0.0f ) + a = REAL_TO_UNSIGNEDBYTE( ((alphaScale - 1.0f) * (255.0f - minAlpha)) + minAlpha ); + else + a = REAL_TO_UNSIGNEDBYTE( (alphaScale * (255.0f - minAlpha)) + minAlpha ); + c = GameMakeColor( r, g, b, a ); + + } // end if + + + + + // draw the blip, but make sure the points are legal + if( legalRadarPoint( radarPoint.x, radarPoint.y ) ) + surface->DrawPixel( radarPoint.x, radarPoint.y, c ); + + radarPoint.x++; + if( legalRadarPoint( radarPoint.x, radarPoint.y ) ) + surface->DrawPixel( radarPoint.x, radarPoint.y, c ); + + radarPoint.y++; + if( legalRadarPoint( radarPoint.x, radarPoint.y ) ) + surface->DrawPixel( radarPoint.x, radarPoint.y, c ); + + radarPoint.x--; + if( legalRadarPoint( radarPoint.x, radarPoint.y ) ) + surface->DrawPixel( radarPoint.x, radarPoint.y, c ); + + + + + } // end for + REF_PTR_RELEASE(surface); + +} // end renderObjectList + + + * + */ diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp index 4f7382b206..d77d71ee55 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp @@ -38,6 +38,15 @@ #include "GameLogic/Module/ContainModule.h" #include "W3DDevice/GameClient/Module/W3DDependencyModelDraw.h" + + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + + //------------------------------------------------------------------------------------------------- W3DDependencyModelDrawModuleData::W3DDependencyModelDrawModuleData() { diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp index 049db8ea6e..03c2c710ad 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp @@ -52,7 +52,7 @@ #include "WW3D2/assetmgr.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -234,6 +234,8 @@ W3DLaserDraw::~W3DLaserDraw( void ) } // end for i delete [] m_line3D; + // TheSuperHackers @fix Mauller 11/03/2025 Free reference counted material + REF_PTR_RELEASE(m_texture); } //------------------------------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp index 83df059960..aabe4c25ab 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp @@ -68,7 +68,7 @@ #include "WW3D2/meshmdl.h" #include "Common/BitFlagsIO.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -85,7 +85,7 @@ static inline Bool isValidTimeToCalcLogicStuff() //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(DEBUG_CRC) && (defined(_DEBUG) || defined(_INTERNAL)) +#if defined(DEBUG_CRC) && (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) #include class LogClass { @@ -205,11 +205,11 @@ LogClass BonePosLog("bonePositions.txt"); //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) extern AsciiString TheThingTemplateBeingParsedName; #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern Real TheSkateDistOverride; #endif @@ -472,7 +472,7 @@ static Bool findSingleSubObj(RenderObjClass* robj, const AsciiString& boneName, if (test == childObject) { boneIndex = robj->Get_Sub_Object_Bone_Index(0, subObj); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) test->Release_Ref(); test = robj->Get_Sub_Object_On_Bone(0, boneIndex); DEBUG_ASSERTCRASH(test != NULL && test == childObject, ("*** ASSET ERROR: Hmm, bone problem")); @@ -752,7 +752,7 @@ void ModelConditionInfo::validateWeaponBarrelInfo() const { sprintf(buffer, "%s%02d", mfName.str(), i); findPristineBone(NAMEKEY(buffer), &info.m_muzzleFlashBone); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) if (info.m_muzzleFlashBone) info.m_muzzleFlashBoneName = buffer; #endif @@ -800,7 +800,7 @@ void ModelConditionInfo::validateWeaponBarrelInfo() const if (!mfName.isEmpty()) findPristineBone(NAMEKEY(mfName), &info.m_muzzleFlashBone); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) if (info.m_muzzleFlashBone) info.m_muzzleFlashBoneName = mfName; #endif @@ -965,7 +965,7 @@ void ModelConditionInfo::loadAnimations() const void ModelConditionInfo::clear() { int i; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_description.clear(); #endif m_conditionsYesVec.clear(); @@ -1454,7 +1454,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void info.m_conditionsYesVec.clear(); info.m_conditionsYesVec.push_back(blankConditions); - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) info.m_description.clear(); info.m_description.concat(TheThingTemplateBeingParsedName); info.m_description.concat(" DEFAULT"); @@ -1485,7 +1485,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void } info.m_transitionSig = buildTransitionSig(firstKey, secondKey); - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) info.m_description.clear(); info.m_description.concat(TheThingTemplateBeingParsedName); info.m_description.concat(" TRANSITION: "); @@ -1509,7 +1509,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void ModelConditionFlags conditionsYes; - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) AsciiString description; conditionsYes.parse(ini, &description); @@ -1561,7 +1561,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void // } ModelConditionFlags conditionsYes; - #if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString description; conditionsYes.parse(ini, &description); @@ -1850,18 +1850,18 @@ void W3DModelDraw::setShadowsEnabled(Bool enable) } /**collect some stats about the rendering cost of this draw module */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DModelDraw::getRenderCost(RenderCost & rc) const { getRenderCostRecursive(rc,m_renderObject); if (m_shadow) m_shadow->getRenderCost(rc); } -#endif //_DEBUG || _INTERNAL +#endif //RTS_DEBUG || RTS_INTERNAL /**recurse through sub-objs to collect stats about the rendering cost of this draw module */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DModelDraw::getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) const { if (robj == NULL) return; @@ -1898,7 +1898,7 @@ void W3DModelDraw::getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) } } } -#endif //_DEBUG || _INTERNAL +#endif //RTS_DEBUG || RTS_INTERNAL //------------------------------------------------------------------------------------------------- void W3DModelDraw::setFullyObscuredByShroud(Bool fullyObscured) @@ -2217,7 +2217,7 @@ Real W3DModelDraw::getCurAnimDistanceCovered() const if (m_curState != NULL && m_whichAnimInCurState >= 0) { const W3DAnimationInfo& animInfo = m_curState->m_animations[m_whichAnimInCurState]; - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheSkateDistOverride != 0.0f) return TheSkateDistOverride; #endif @@ -2763,7 +2763,7 @@ void W3DModelDraw::nukeCurrentRender(Matrix3D* xform) } //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test. +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //art wants to see buildings without flags as a test. void W3DModelDraw::hideGarrisonFlags(Bool hide) { if (!m_renderObject) @@ -2989,7 +2989,7 @@ void W3DModelDraw::setModelState(const ModelConditionInfo* newState) rebuildWeaponRecoilInfo(newState); doHideShowSubObjs(&newState->m_hideShowVec); -#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test. +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //art wants to see buildings without flags as a test. if (TheGlobalData->m_hideGarrisonFlags && draw->isKindOf(KINDOF_STRUCTURE)) hideGarrisonFlags(TRUE); #endif @@ -3218,7 +3218,7 @@ Bool W3DModelDraw::getProjectileLaunchOffset( //BONEPOS_LOG(("can't find best info\n")); return false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CRCDEBUG_LOG(("W3DModelDraw::getProjectileLaunchOffset() for %s\n", stateToUse->getDescription().str())); #endif @@ -4185,7 +4185,7 @@ void W3DModelDrawModuleData::xfer( Xfer *x ) { ModelConditionInfo *info = &(*it); x->xferByte(&(info->m_validStuff)); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) x->xferAsciiString(&(info->m_description)); #endif if (info->m_validStuff) diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp index 25532106f8..0c241f714e 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp @@ -44,7 +44,7 @@ #include "W3DDevice/GameClient/W3DScene.h" #include "Common/GameState.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp index d7fbe0c03d..c409c8610d 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp @@ -47,7 +47,7 @@ #include "W3DDevice/GameClient/Module/W3DTankDraw.h" #include "WW3D2/matinfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -163,6 +163,9 @@ void W3DTankDraw::createEmitters( void ) //------------------------------------------------------------------------------------------------- W3DTankDraw::~W3DTankDraw() { + // TheSuperHackers @fix Mauller 16/04/2025 Delete particle systems + tossEmitters(); + for (Int i=0; iGet_Bone_Index(getW3DTruckDrawModuleData()->m_frontLeftTireBoneName.str()); DEBUG_ASSERTCRASH(m_frontLeftTireBone, ("Missing front-left tire bone %s in model %s\n", getW3DTruckDrawModuleData()->m_frontLeftTireBoneName.str(), getRenderObject()->Get_Name())); - + } + + if( !getW3DTruckDrawModuleData()->m_frontRightTireBoneName.isEmpty() ) + { m_frontRightTireBone = getRenderObject()->Get_Bone_Index(getW3DTruckDrawModuleData()->m_frontRightTireBoneName.str()); DEBUG_ASSERTCRASH(m_frontRightTireBone, ("Missing front-right tire bone %s in model %s\n", getW3DTruckDrawModuleData()->m_frontRightTireBoneName.str(), getRenderObject()->Get_Name())); - - if (!m_frontRightTireBone ) - { - m_frontLeftTireBone = 0; - } } + //Rear tires if( !getW3DTruckDrawModuleData()->m_rearLeftTireBoneName.isEmpty() ) { m_rearLeftTireBone = getRenderObject()->Get_Bone_Index(getW3DTruckDrawModuleData()->m_rearLeftTireBoneName.str()); DEBUG_ASSERTCRASH(m_rearLeftTireBone, ("Missing rear-left tire bone %s in model %s\n", getW3DTruckDrawModuleData()->m_rearLeftTireBoneName.str(), getRenderObject()->Get_Name())); + } + if( !getW3DTruckDrawModuleData()->m_rearRightTireBoneName.isEmpty() ) + { m_rearRightTireBone = getRenderObject()->Get_Bone_Index(getW3DTruckDrawModuleData()->m_rearRightTireBoneName.str()); DEBUG_ASSERTCRASH(m_rearRightTireBone, ("Missing rear-left tire bone %s in model %s\n", getW3DTruckDrawModuleData()->m_rearRightTireBoneName.str(), getRenderObject()->Get_Name())); - - if (!m_rearRightTireBone) - { - m_rearLeftTireBone = 0; - } } //midFront tires diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp index 5aabffda89..071cb170cf 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp @@ -39,7 +39,7 @@ #include "GameClient/ControlBarScheme.h" #include "GameClient/MapUtil.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -497,8 +497,14 @@ void W3DCommandBarGenExpDraw( GameWindow *window, WinInstanceData *instData ) static const Image *endBar = TheMappedImageCollection->findImageByName("GenExpBarTop1"); static const Image *beginBar = TheMappedImageCollection->findImageByName("GenExpBarBottom1"); static const Image *centerBar = TheMappedImageCollection->findImageByName("GenExpBar1"); - Int progress; - progress = ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) /(player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown()); + Int progress = 0; + Int skillPointsRequired = player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown(); + + // TheSuperHackers @bugfix Mauller 04/05/2025 Prevent possible division by zero + if ( skillPointsRequired > 0) + { + progress = ( ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) / skillPointsRequired ); + } if(progress <= 0) return; diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp index a1fb462d41..48314c84c6 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp @@ -68,7 +68,7 @@ /////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp index b98e277089..23ae42355b 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp @@ -58,7 +58,7 @@ #include "W3DDevice/GameClient/W3DGadget.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp index 1e33c7efca..407ac1242b 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp @@ -70,7 +70,7 @@ /////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp index b6b3565651..527ebcc5e2 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp @@ -53,7 +53,7 @@ #include "W3DDevice/GameClient/W3DGadget.h" #include "W3DDevice/GameClient/W3DDisplay.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp index 688ba83480..760db4efae 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp @@ -91,7 +91,7 @@ #include "Common/PerfTimer.h" #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -314,7 +314,7 @@ UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX #else Real shadeR, shadeG, shadeB; Int diffuse = vbMirror->diffuse; -#ifdef _DEBUG +#ifdef RTS_DEBUG //vbMirror->diffuse += 30; // Shows which vertexes are geting touched by dynamic light. debug only. #endif @@ -407,7 +407,7 @@ Int HeightMapRenderObjClass::getXWithOrigin(Int x) x -= m_originX; if (x<0) x+= m_x-1; if (x>= m_x-1) x-=m_x-1; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH (x>=0, ("X out of range.")); DEBUG_ASSERTCRASH (x= m_y-1) y-=m_y-1; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH (y>=0, ("Y out of range.")); DEBUG_ASSERTCRASH (y= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH); #endif @@ -718,7 +718,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *d if (m_vertexBufferTiles && m_map) { -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(x0 >= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH); #endif @@ -865,7 +865,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB if (m_vertexBufferTiles && m_map) { -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(x0 >= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH); #endif @@ -1152,7 +1152,7 @@ The vertex coordinates and texture coordinates, as well as static lighting are u */ Int HeightMapRenderObjClass::updateBlock(Int x0, Int y0, Int x1, Int y1, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(x0>=0&&y0>=0 && x1m_shroudOn) m_shroud = NEW W3DShroud; else @@ -2807,7 +2807,7 @@ void HeightMapRenderObjClass::allocateScorchBuffers(void) m_scorchesInBuffer = 0; // If we just allocated the buffers, we got no scorches in the buffer. m_curNumScorchVertices=0; m_curNumScorchIndices=0; -#ifdef _DEBUG +#ifdef RTS_DEBUG Vector3 loc(4*MAP_XY_FACTOR,4*MAP_XY_FACTOR,0); addScorch(loc, 1*MAP_XY_FACTOR, SCORCH_1); loc.Y += 10*MAP_XY_FACTOR; @@ -3157,7 +3157,7 @@ Int HeightMapRenderObjClass::getStaticDiffuse(Int x, Int y) if ( vbMirror[2].x==X && vbMirror[2].y==Y) { return(vbMirror[2].diffuse); } -#ifdef _DEBUG +#ifdef RTS_DEBUG char buf[256]; sprintf(buf, "(%f,%f) -> mirror (%f, %f)\n", X, Y, vbMirror->x, vbMirror->y); ::OutputDebugString(buf); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp index 9dfb98b61c..bbd0b18ae2 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp @@ -58,7 +58,7 @@ #include "W3DDevice/GameClient/W3DShadow.h" #include "W3DDevice/GameClient/HeightMap.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -124,39 +124,6 @@ int SHADOW_DECAL_INDEX_SIZE=65536; class W3DShadowTexture; //forward reference class W3DShadowTextureManager; //forward reference -/** Object for maintaining and updating an object's shadow texture. -*/ -class W3DProjectedShadow : public Shadow -{ - friend class W3DProjectedShadowManager; - - public: - W3DProjectedShadow(void); - ~W3DProjectedShadow(void); - void setRenderObject( RenderObjClass *robj) {m_robj=robj;} - void setObjPosHistory(const Vector3 &pos) {m_lastObjPosition=pos;} ///removeShadow(this);} ///m_ShadowName); + if (nameLen <= 1) //no texture name given, use same as object + { strcpy(texture_name,defaultDecalName); + } + else + { strncpy(texture_name,shadowInfo->m_ShadowName,nameLen); + strcpy(texture_name+nameLen,".tga"); //append texture extension + } + + st=m_W3DShadowTextureManager->getTexture(texture_name); + if (st == NULL) + { + //need to add this texture without creating it from a real renderobject + TextureClass *w3dTexture=WW3DAssetManager::Get_Instance()->Get_Texture(texture_name); + w3dTexture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); + w3dTexture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); + w3dTexture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); + + DEBUG_ASSERTCRASH(w3dTexture != NULL, ("Could not load decal texture")); + + if (!w3dTexture) + return NULL; + + st = NEW W3DShadowTexture; // poolify + SET_REF_OWNER( st ); + st->Set_Name(texture_name); + m_W3DShadowTextureManager->addTexture( st ); + st->setTexture(w3dTexture); + } + shadowType=SHADOW_DECAL; + decalSizeX=shadowInfo->m_sizeX; + decalSizeY=shadowInfo->m_sizeY; + decalOffsetX=shadowInfo->m_offsetX; + decalOffsetY=shadowInfo->m_offsetY; + + W3DProjectedShadow *shadow = NEW W3DProjectedShadow; + + // sanity + if( shadow == NULL ) + return NULL; + + shadow->setTexture(0,st); + shadow->m_type = shadowType; /// type of projection + shadow->m_allowWorldAlign=allowWorldAlign; /// wrap shadow around world geometry - else align perpendicular to local z-axis. + + + //Check if app is overriding any of the default texture stretch factors. + if (decalSizeX) + decalSizeX=1.0f/decalSizeX; //world space distance to stretch full texture scale + else + decalSizeX=1.0f/(defaultWidth*2.0f);//use bounding box to determine size + + if (decalSizeY) + decalSizeY=-1.0f/decalSizeY; + else + decalSizeY=-1.0f/(defaultWidth*2.0f);//world space distance to stretch full texture + + if (decalOffsetX) + decalOffsetX=-decalOffsetX*decalSizeX; + else + decalOffsetX=0.0f;//-box.Center.X*decalSizeX; + + if (decalOffsetY) + decalOffsetY=-decalOffsetY*decalSizeY; + else + decalOffsetY=0.0f;//-box.Center.Y*decalSizeY; + + //Prestore some values used during projection to optimize out division. + shadow->m_oowDecalSizeX = decalSizeX; //one over width + shadow->m_oowDecalSizeY = decalSizeY; //one over height + shadow->m_decalSizeX = 1.0f/decalSizeX; //width + shadow->m_decalSizeY = 1.0f/decalSizeY; //height + + shadow->m_decalOffsetU= decalOffsetX; + shadow->m_decalOffsetV= decalOffsetY; + + shadow->m_flags = 0; + + shadow->init(); + + return shadow; +} + void W3DProjectedShadowManager::removeShadow (W3DProjectedShadow *shadow) { W3DProjectedShadow *prev_shadow=NULL; @@ -2031,7 +2099,7 @@ void W3DProjectedShadowManager::removeAllShadows(void) } // end for } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DProjectedShadow::getRenderCost(RenderCost & rc) const { if (TheGlobalData->m_useShadowDecals && m_isEnabled && !m_isInvisibleEnabled) diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp index 3b5cedcfb3..1d4ca52407 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp @@ -58,7 +58,7 @@ #include "WW3D2/dx8caps.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -748,43 +748,6 @@ Int W3DShadowGeometry::initFromMesh(RenderObjClass *robj) Int W3DShadowGeometry::init(RenderObjClass *robj) { return TRUE; -// m_robj=robj; -/* //code to deal with granny - don't think we'll use shadow volumes on these!? - granny_file *fileInfo=robj->getPrototype().m_file; - - for (Int modelIndex=0; modelIndexModelCount; modelIndex++) - { - granny_model *sourceModel = fileInfo->Models[modelIndex]; - if (stricmp(sourceModel->Name,"AABOX") == 0) - { //found a collision box, copy out data - int MeshCount = sourceModel->MeshBindingCount; - if (MeshCount==1) - { - granny_mesh *sourceMesh = sourceModel->MeshBindings[0].Mesh; - granny_pn33_vertex *Vertices = (granny_pn33_vertex *)sourceMesh->PrimaryVertexData->Vertices; - Vector3 points[24]; - - assert (sourceMesh->PrimaryVertexData->VertexCount <= 24); - - for (Int boxVertex=0; boxVertexPrimaryVertexData->VertexCount; boxVertex++) - { points[boxVertex].Set(Vertices[boxVertex].Position[0], - Vertices[boxVertex].Position[1], - Vertices[boxVertex].Position[2]); - } - box.Init(points,sourceMesh->PrimaryVertexData->VertexCount); - } - } - else - { //mesh is part of model - int meshCount = sourceModel->MeshBindingCount; - for (Int meshIndex=0; meshIndexMeshBindings[meshIndex].Mesh; - if (sourceMesh->PrimaryVertexData) - vertexCount+=sourceMesh->PrimaryVertexData->VertexCount; - } - } - }*/ } /////////////////////////////////////////////////////////////////////////////// @@ -1208,7 +1171,7 @@ void W3DVolumetricShadow::updateOptimalExtrusionPadding(void) // getRenderCost ============================================================ // Returns number of draw calls for this shadow. // ============================================================================ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DVolumetricShadow::getRenderCost(RenderCost & rc) const { Int drawCount = 0; @@ -3944,7 +3907,7 @@ int W3DShadowGeometryManager::Load_Geom(RenderObjClass *robj, const char *name) } /* -** Iterator converter from HashableClass to GrannyAnimClass +** Iterator converter from HashableClass to W3DShadowGeometry */ W3DShadowGeometry * W3DShadowGeometryManagerIterator::Get_Current_Geom( void ) { diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp index f59098d150..77e61f902c 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp @@ -88,7 +88,7 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) IDirect3DSurface8 *surface_level; D3DSURFACE_DESC surface_desc; D3DLOCKED_RECT locked_rect; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(0, &surface_level)); + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); if (surface_desc.Width < TEXTURE_WIDTH) { surface_level->Release(); @@ -104,7 +104,7 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) Int tilesPerRow = surface_desc.Width/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); tilesPerRow *= 2; // Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#ifdef _DEBUG +#ifdef RTS_DEBUG //DEBUG_ASSERTCRASH(tilesPerRow*numRows >= htMap->m_numBitmapTiles, ("Too many tiles.")); DEBUG_ASSERTCRASH((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow, ("Bitmap too small.")); #endif @@ -186,9 +186,9 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) } surface_level->UnlockRect(); surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(D3DTexture, NULL, 0, D3DX_FILTER_BOX)); + DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, 0, D3DX_FILTER_BOX)); if (TheWritableGlobalData->m_textureReductionFactor) { - D3DTexture->SetLOD(TheWritableGlobalData->m_textureReductionFactor); + Peek_D3D_Texture()->SetLOD(TheWritableGlobalData->m_textureReductionFactor); } return(surface_desc.Height); } @@ -224,7 +224,7 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) Int tilesPerRow = surface_desc.Width/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); tilesPerRow *= 2; Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(tilesPerRow*numRows >= htMap->m_numBitmapTiles); assert((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow); #endif @@ -362,7 +362,7 @@ int TerrainTextureClass::update256(WorldHeightMap *htMap) IDirect3DSurface8 *surface_level; D3DSURFACE_DESC surface_desc; D3DLOCKED_RECT locked_rect; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(0, &surface_level)); + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); if (surface_desc.Width != 256) { surface_level->Release(); @@ -377,7 +377,7 @@ int TerrainTextureClass::update256(WorldHeightMap *htMap) tilesPerRow *= 2; Int numRows = surface_desc.Height/(tilePixelExtent+tileOffset); -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(tilesPerRow*numRows >= htMap->m_numBitmapTiles); assert((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow); #endif @@ -499,7 +499,7 @@ int TerrainTextureClass::update256(WorldHeightMap *htMap) } surface_level->UnlockRect(); surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(D3DTexture, NULL, 0, D3DX_FILTER_BOX)); + DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, 0, D3DX_FILTER_BOX)); // Note - normal width for the terrain texture is 1024. We are at 256 // probably running on a voodoo. The height we return is scaled up // to match the expected width of 1024. jba. @@ -565,14 +565,9 @@ AlphaTerrainTextureClass::AlphaTerrainTextureClass( TextureClass *pBaseTex ): TextureClass(8, 8, WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_1 ) { - if (D3DTexture) { - // Release the 8x8 texture. - D3DTexture->Release(); - D3DTexture = NULL; - } // Attach the base texture's d3d texture. - D3DTexture = pBaseTex->Peek_D3D_Texture(); - D3DTexture->AddRef(); + IDirect3DTexture8 * d3d_tex = pBaseTex->Peek_D3D_Texture(); + Set_D3D_Base_Texture(d3d_tex); } @@ -849,7 +844,7 @@ int AlphaEdgeTextureClass::update(WorldHeightMap *htMap) IDirect3DSurface8 *surface_level; D3DSURFACE_DESC surface_desc; D3DLOCKED_RECT locked_rect; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(0, &surface_level)); + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0, &surface_level)); DX8_ErrorCode(surface_level->LockRect(&locked_rect, NULL, 0)); DX8_ErrorCode(surface_level->GetDesc(&surface_desc)); @@ -912,7 +907,7 @@ int AlphaEdgeTextureClass::update(WorldHeightMap *htMap) } surface_level->UnlockRect(); surface_level->Release(); - DX8_ErrorCode(D3DXFilterTexture(D3DTexture, NULL, 0, D3DX_FILTER_BOX)); + DX8_ErrorCode(D3DXFilterTexture(Peek_D3D_Texture(), NULL, 0, D3DX_FILTER_BOX)); return(surface_desc.Height); } diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp index 531cf18e23..36c381b283 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp @@ -69,7 +69,7 @@ #include "Common/PerfTimer.h" #include "Common/GlobalData.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -150,17 +150,11 @@ RenderObjClass * W3DPrototypeClass::Create(void) //--------------------------------------------------------------------- W3DAssetManager::W3DAssetManager(void) { -#ifdef INCLUDE_GRANNY_IN_BUILD - m_GrannyAnimManager = NEW GrannyAnimManagerClass; -#endif } //--------------------------------------------------------------------- W3DAssetManager::~W3DAssetManager(void) { -#ifdef INCLUDE_GRANNY_IN_BUILD - delete m_GrannyAnimManager; -#endif } #ifdef DUMP_PERF_STATS @@ -217,7 +211,7 @@ TextureClass *W3DAssetManager::Get_Texture( // extern std::vector preloadTextureNamesGlobalHack; // preloadTextureNamesGlobalHack.push_back(tex->Get_Texture_Name()); // } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_preloadReport) { //loading a new asset and app is requesting a log of all loaded assets. @@ -700,12 +694,6 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( GetPrecisionTimer(&startTime64); #endif -#ifdef INCLUDE_GRANNY_IN_BUILD - Bool isGranny = false; - char *pext=strrchr(name,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); -#endif Bool reallyscale = (WWMath::Fabs(scale - ident_scale) > scale_epsilon); Bool reallycolor = (color & 0xFFFFFF) != 0; //black is not a valid color and assumes no custom coloring. Bool reallytexture = (oldTexture != NULL && newTexture != NULL); @@ -727,12 +715,6 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( // see if we got a cached version RenderObjClass *rendobj = NULL; -#ifdef INCLUDE_GRANNY_IN_BUILD - if (isGranny) - { //Granny objects share the same prototype since they allow instance scaling. - strcpy(newname,name); //use same name for all granny objects at any scale. - } -#endif Set_WW3D_Load_On_Demand(false); // munged name will never be found in a file. rendobj = WW3DAssetManager::Create_Render_Obj(newname); if (rendobj) @@ -740,11 +722,6 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( //when we need to save this render object to a file. Used during saving //of fog of war ghost objects. rendobj->Set_ObjectColor(color); -#ifdef INCLUDE_GRANNY_IN_BUILD - if (isGranny) - ///@todo Granny objects are realtime scaled - fix to scale like W3D. - rendobj->Set_ObjectScale(scale); -#endif Set_WW3D_Load_On_Demand(true); // Auto Load. #ifdef DUMP_PERF_STATS @@ -767,16 +744,11 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( { // If we didn't find one, try to load on demand char filename [MAX_PATH]; - const char *mesh_name = ::strchr (name, '.'); + const char *mesh_name = strchr (name, '.'); if (mesh_name != NULL) { - ::lstrcpyn(filename, name, ((int)mesh_name) - ((int)name) + 1); -#ifdef INCLUDE_GRANNY_IN_BUILD - if (isGranny) - ::lstrcat(filename, ".gr2"); - else -#endif - ::lstrcat(filename, ".w3d"); + lstrcpyn(filename, name, ((int)mesh_name) - ((int)name) + 1); + lstrcat(filename, ".w3d"); } else { sprintf( filename, "%s.w3d", name); } @@ -785,15 +757,7 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( if ( Load_3D_Assets( filename ) == false ) { StringClass new_filename = StringClass("..\\") + filename; - if (Load_3D_Assets( new_filename ) == false) - { -#ifdef INCLUDE_GRANNY_IN_BUILD - char *mesh_name = ::strchr (filename, '.'); - ::lstrcpyn (mesh_name, ".gr2",5); - Load_3D_Assets( filename ); - isGranny=true; -#endif - } + Load_3D_Assets( new_filename ); } proto = Find_Prototype(name); // try again @@ -823,33 +787,21 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( #endif return NULL; } -#ifdef INCLUDE_GRANNY_IN_BUILD - if (!isGranny) -#endif - { - Make_Unique(rendobj,reallyscale,reallycolor); - if (reallytexture) - { - TextureClass *oldTex = Get_Texture(oldTexture); - TextureClass *newTex = Get_Texture(newTexture); - replaceAssetTexture(rendobj,oldTex,newTex); - REF_PTR_RELEASE(newTex); - REF_PTR_RELEASE(oldTex); - } - if (reallyscale) - rendobj->Scale(scale); - if (reallycolor) - Recolor_Asset(rendobj,color); - } -#ifdef INCLUDE_GRANNY_IN_BUILD - else + Make_Unique(rendobj,reallyscale,reallycolor); + if (reallytexture) { - ///@todo Granny objects are realtime scaled - fix to scale like W3D. - rendobj->Set_ObjectScale(scale); - return rendobj; + TextureClass *oldTex = Get_Texture(oldTexture); + TextureClass *newTex = Get_Texture(newTexture); + replaceAssetTexture(rendobj,oldTex,newTex); + REF_PTR_RELEASE(newTex); + REF_PTR_RELEASE(oldTex); } -#endif + if (reallyscale) + rendobj->Scale(scale); + + if (reallycolor) + Recolor_Asset(rendobj,color); W3DPrototypeClass *w3dproto = newInstance(W3DPrototypeClass)(rendobj, newname); rendobj->Release_Ref(); @@ -986,14 +938,6 @@ bool W3DAssetManager::Load_3D_Assets( const char * filename ) GetPrecisionTimer(&startTime64); #endif -#ifdef INCLUDE_GRANNY_IN_BUILD - Bool isGranny = false; - char *pext=strrchr(filename,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); - if (!isGranny) -#endif - // Try to find an existing prototype char basename[512]; strcpy(basename, filename); @@ -1015,7 +959,7 @@ bool W3DAssetManager::Load_3D_Assets( const char * filename ) bool result = WW3DAssetManager::Load_3D_Assets(filename); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (result && TheGlobalData->m_preloadReport) { //loading a new asset and app is requesting a log of all loaded assets. @@ -1038,40 +982,6 @@ bool W3DAssetManager::Load_3D_Assets( const char * filename ) #endif return result; -#ifdef INCLUDE_GRANNY_IN_BUILD - //Loading assets for Granny File - PrototypeClass * newproto = NULL; - newproto = _GrannyLoader.Load_W3D(filename); - /* - ** Now, see if the prototype that we loaded has a duplicate - ** name with any of our currently loaded prototypes (can't have that!) - */ - if (newproto != NULL) { - if (!Render_Obj_Exists(newproto->Get_Name())) { - /* - ** Add the new, unique prototype to our list - */ - Add_Prototype(newproto); - } else { - /* - ** Warn the user about a name collision with this prototype - ** and dump it - */ - WWDEBUG_SAY(("Render Object Name Collision: %s\r\n",newproto->Get_Name())); - delete newproto; - newproto = NULL; - return false; - } - } else { - /* - ** Warn user that a prototype was not generated from this - ** chunk type - */ - WWDEBUG_SAY(("Could not generate Granny prototype! File = %d\r\n",filename)); - return false; - } - return true; -#endif } #ifdef DUMP_PERF_STATS @@ -1089,47 +999,17 @@ HAnimClass * W3DAssetManager::Get_HAnim(const char * name) #endif WWPROFILE( "WW3DAssetManager::Get_HAnim" ); -#ifdef INCLUDE_GRANNY_IN_BUILD - Bool isGranny = false; - char *pext=strrchr(name,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); - if (!isGranny) -#endif - { - HAnimClass *anim=WW3DAssetManager::Get_HAnim(name); //we only do custom granny processing. + HAnimClass *anim=WW3DAssetManager::Get_HAnim(name); #ifdef DUMP_PERF_STATS - if (HAnim_Recursions == 1) - { - GetPrecisionTimer(&endTime64); - Total_Get_HAnim_Time += endTime64-startTime64; - } - HAnim_Recursions--; -#endif - return anim; - } - -#ifdef INCLUDE_GRANNY_IN_BUILD - // Try to find the hanim - HAnimClass * anim = m_GrannyAnimManager->Get_Anim(name); - if (WW3D_Load_On_Demand && anim == NULL) { // If we didn't find it, try to load on demand - if ( !m_GrannyAnimManager->Is_Missing( name ) ) { // if this is NOT a known missing anim - - // If we can't find it, try the parent directory - if ( m_GrannyAnimManager->Load_Anim(name) == 1 ) { - StringClass new_filename = StringClass("..\\") + name; - m_GrannyAnimManager->Load_Anim( new_filename ); - } - - anim = m_GrannyAnimManager->Get_Anim(name); // Try again - if (anim == NULL) { -// WWDEBUG_SAY(("WARNING: Animation %s not found!\n", name)); - m_GrannyAnimManager->Register_Missing( name ); // This is now a KNOWN missing anim - } - } + if (HAnim_Recursions == 1) + { + GetPrecisionTimer(&endTime64); + Total_Get_HAnim_Time += endTime64-startTime64; } - return anim; + HAnim_Recursions--; #endif + return anim; + } //--------------------------------------------------------------------- @@ -1420,11 +1300,6 @@ static inline void Munge_Texture_Name(char *newname, const char *oldname, const RenderObjClass * W3DAssetManager::Create_Render_Obj(const char * name,float scale, const Vector3 &hsv_shift) { Bool isGranny = false; -#ifdef INCLUDE_GRANNY_IN_BUILD - char *pext=strrchr(name,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); -#endif Bool reallyscale = (WWMath::Fabs(scale - ident_scale) > scale_epsilon); Bool reallyhsv_shift = (WWMath::Fabs(hsv_shift.X - ident_HSV.X) > H_epsilon || WWMath::Fabs(hsv_shift.Y - ident_HSV.Y) > S_epsilon || WWMath::Fabs(hsv_shift.Z - ident_HSV.Z) > V_epsilon); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBibBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBibBuffer.cpp index c8090660f7..92c6a6bb66 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBibBuffer.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBibBuffer.cpp @@ -92,10 +92,16 @@ void W3DBibBuffer::loadBibsInVertexAndIndexBuffers(void) if (!m_anythingChanged) { return; } + m_curNumBibVertices = 0; m_curNumBibIndices = 0; m_curNumNormalBibIndices = 0; m_curNumNormalBibVertex = 0; + + if (m_numBibs==0) { + return; + } + VertexFormatXYZDUV1 *vb; UnsignedShort *ib; // Lock the buffers. diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp index 000667db31..012a4344c1 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp @@ -72,6 +72,12 @@ #include "WW3D2/meshmdl.h" #include "WW3D2/scene.h" +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + //----------------------------------------------------------------------------- // Private Data //----------------------------------------------------------------------------- @@ -130,7 +136,7 @@ are already set. */ //============================================================================= void W3DBridge::renderBridge(Bool wireframe) { - if (m_visible) { + if (m_visible && m_numPolygons && m_numVertex) { if (!wireframe) DX8Wrapper::Set_Texture(0,m_bridgeTexture); // Draw all the bridges. DX8Wrapper::Draw_Triangles( m_firstIndex, m_numPolygons, m_firstVertex, m_numVertex); @@ -514,7 +520,17 @@ void W3DBridge::getIndicesNVertices(UnsignedShort *destination_ib, VertexFormatX m_numPolygons = 0; if (m_sectionMesh == NULL) { numV = getModelVerticesFixed(destination_vb, *curVertexP, m_leftMtx, m_leftMesh, pLightsIterator); + if (!numV) + { //not enough room for vertices + DEBUG_ASSERTCRASH( numV, ("W3DBridge::GetIndicesNVertices(). Vertex overflow.\n") ); + return; + } numI = getModelIndices( destination_ib, *curIndexP, *curVertexP, m_leftMesh); + if (!numI) + { //not enough room for indices + DEBUG_ASSERTCRASH( numI, ("W3DBridge::GetIndicesNVertices(). Index overflow.\n") ); + return; + } *curIndexP += numI; *curVertexP += numV; m_numVertex += numV; @@ -554,7 +570,17 @@ void W3DBridge::getIndicesNVertices(UnsignedShort *destination_ib, VertexFormatX vec /= bridgeLength; numV = getModelVertices(destination_vb, *curVertexP, xOffset, vec, vecNormal, vecZ, m_start, m_leftMtx, m_leftMesh, pLightsIterator); + if (!numV) + { //not enough room for vertices + DEBUG_ASSERTCRASH( numV, ("W3DBridge::GetIndicesNVertices(). Vertex overflow.\n") ); + return; + } numI = getModelIndices( destination_ib, *curIndexP, *curVertexP, m_leftMesh); + if (!numI) + { //not enough room for indices + DEBUG_ASSERTCRASH( numI, ("W3DBridge::GetIndicesNVertices(). Index overflow.\n") ); + return; + } *curIndexP += numI; *curVertexP += numV; m_numVertex += numV; @@ -565,7 +591,17 @@ void W3DBridge::getIndicesNVertices(UnsignedShort *destination_ib, VertexFormatX for (i=0; iaudioDebugDisplay( NULL, NULL, m_fp ); fprintf( m_fp, "\n" ); #endif @@ -351,7 +351,7 @@ W3DDisplay::W3DDisplay() m_2DScene = NULL; m_3DInterfaceScene = NULL; m_averageFPS = TheGlobalData->m_framesPerSecondLimit; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_timerAtCumuFPSStart = 0; #endif for (i=0; ifreeDisplayString(m_displayStrings[i]); + // TheSuperHackers @fix Mauller/Tomsons26 28/04/2025 Free benchmark display string + if( m_benchmarkDisplayString ) { + TheDisplayStringManager->freeDisplayString(m_benchmarkDisplayString); + } + // delete 2D renderer if( m_2DRender ) { @@ -619,7 +626,7 @@ void W3DDisplay::init( void ) // create our 3D scene m_3DScene =NEW_REF( RTS3DScene, () ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_wireframe ) m_3DScene->Set_Polygon_Mode( SceneClass::LINE ); #endif @@ -670,7 +677,6 @@ void W3DDisplay::init( void ) WW3D::Set_Prelit_Mode( WW3D::PRELIT_MODE_LIGHTMAP_MULTI_PASS ); WW3D::Set_Collision_Box_Display_Mask(0x00); ///getFrame() == START_CUMU_FRAME) { m_timerAtCumuFPSStart = time64; @@ -860,7 +866,7 @@ void W3DDisplay::updateAverageFPS(void) lastUpdateTime64 = time64; } -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats ICoord2D TheMousePos; #endif @@ -954,7 +960,7 @@ void W3DDisplay::gatherDebugStats( void ) double ms = 1000.0f/fps; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) double cumuTime = ((double)(time64 - m_timerAtCumuFPSStart) / (double)(freq64)); if (cumuTime < 0.0) cumuTime = 0.0; Int numFrames = (Int)TheGameLogic->getFrame() - (Int)START_CUMU_FRAME; @@ -1125,7 +1131,7 @@ void W3DDisplay::gatherDebugStats( void ) if (debugD3D) { unibuffer.concat(L", DEBUG D3D"); } -#ifdef _DEBUG +#ifdef RTS_DEBUG unibuffer.concat(L", DEBUG app"); #endif @@ -1250,7 +1256,7 @@ void W3DDisplay::gatherDebugStats( void ) } Object *object = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats Drawable *draw = TheTacticalView->pickDrawable(&TheMousePos, FALSE, (PickType)0xffffffff ); #else Drawable *draw = TheGameClient->findDrawableByID( TheInGameUI->getMousedOverDrawableID() ); @@ -1359,7 +1365,7 @@ void W3DDisplay::gatherDebugStats( void ) draw->getPosition()->z ); // (gth) compute some stats about the rendering cost of this drawable -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) RenderCost rcost; for (DrawModule** dm = draw->getDrawModules(); *dm; ++dm) { @@ -1491,7 +1497,7 @@ void W3DDisplay::calculateTerrainLOD( void ) TerrainLOD goodLOD = TERRAIN_LOD_MIN; TerrainLOD curLOD = TERRAIN_LOD_AUTOMATIC; Int count = 0; -#ifdef _DEBUG +#ifdef RTS_DEBUG // just go to TERRAIN_LOD_NO_WATER, mirror off. TheWritableGlobalData->m_terrainLOD = TERRAIN_LOD_NO_WATER; m_3DScene->drawTerrainOnly(false); @@ -1551,7 +1557,7 @@ void W3DDisplay::calculateTerrainLOD( void ) TheWritableGlobalData->m_terrainLOD = goodLOD; m_3DScene->drawTerrainOnly(false); TheTerrainRenderObject->adjustTerrainLOD(0); -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(count<10, ("calculateTerrainLOD") ); #endif @@ -1614,7 +1620,7 @@ void W3DDisplay::draw( void ) // compute debug statistics for display later if ( m_debugDisplayCallback == StatDebugDisplay -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || TheGlobalData->m_benchmarkTimer > 0 #endif ) @@ -1762,6 +1768,11 @@ void W3DDisplay::draw( void ) Int numRenderTargetVertices=Debug_Statistics::Get_DX8_Vertices(); // start render block + #if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) + if ( (TheGameLogic->getFrame() % 30 == 1) || ( ! ( !TheGameLogic->isGamePaused() && TheGlobalData->m_TiVOFastMode) ) ) + #else + if ( (TheGameLogic->getFrame() % 30 == 1) || ( ! (!TheGameLogic->isGamePaused() && TheGlobalData->m_TiVOFastMode && TheGameLogic->isInReplayGame())) ) + #endif { //USE_PERF_TIMER(BigAssRenderLoop) static Bool couldRender = true; @@ -1843,7 +1854,7 @@ void W3DDisplay::draw( void ) drawCurrentDebugDisplay(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_benchmarkTimer > 0) { drawFPSStats(); @@ -1851,7 +1862,7 @@ void W3DDisplay::draw( void ) #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugShowGraphicalFramerate) { drawFramerateBar(); @@ -2982,7 +2993,7 @@ void W3DDisplay::toggleMovieCapture(void) } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) static FILE *AssetDumpFile=NULL; @@ -3135,7 +3146,7 @@ void W3DDisplay::doSmartAssetPurgeAndPreload(const char* usageFileName) //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DDisplay::dumpAssetUsage(const char* mapname) { if (!m_assetManager || !mapname || !*mapname) diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp index a084645579..80b67ceeb8 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp @@ -56,7 +56,7 @@ #include "GameClient/GlobalLanguage.h" // DEFINES //////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp index cd56ba06f0..6728c86599 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayStringManager.cpp @@ -44,7 +44,7 @@ //------------------------------------------------------------------------------------------------- W3DDisplayStringManager::W3DDisplayStringManager( void ) { - for (Int i = 0; i < 10; ++i) + for (Int i = 0; i < MAX_GROUPS; ++i) { m_groupNumeralStrings[i] = NULL; } @@ -56,7 +56,7 @@ W3DDisplayStringManager::W3DDisplayStringManager( void ) //------------------------------------------------------------------------------------------------- W3DDisplayStringManager::~W3DDisplayStringManager( void ) { - for (Int i = 0; i < 10; ++i) + for (Int i = 0; i < MAX_GROUPS; ++i) { if (m_groupNumeralStrings[i]) freeDisplayString(m_groupNumeralStrings[i]); @@ -79,14 +79,20 @@ void W3DDisplayStringManager::postProcessLoad( void ) TheDrawGroupInfo->m_fontSize, TheDrawGroupInfo->m_fontIsBold ); - for (Int i = 0; i < 10; ++i) + for (Int i = 0; i < MAX_GROUPS; ++i) { m_groupNumeralStrings[i] = newDisplayString(); m_groupNumeralStrings[i]->setFont(font); - AsciiString displayNumber; - displayNumber.format("NUMBER:%d", i); - m_groupNumeralStrings[i]->setText(TheGameText->fetch(displayNumber)); +#ifdef KRIS_BRUTAL_HACK_FOR_AIRCRAFT_CARRIER_DEBUGGING + UnicodeString displayNumber; + displayNumber.format( L"%d", i); + m_groupNumeralStrings[i]->setText( displayNumber ); +#else + AsciiString displayNumber; + displayNumber.format("NUMBER:%d", i); + m_groupNumeralStrings[i]->setText(TheGameText->fetch(displayNumber)); +#endif } m_formationLetterDisplayString = newDisplayString(); @@ -225,7 +231,8 @@ void W3DDisplayStringManager::update( void ) //------------------------------------------------------------------------------------------------- DisplayString *W3DDisplayStringManager::getGroupNumeralString( Int numeral ) { - if (numeral < 0 || numeral > 9) { + if (numeral < 0 || numeral > MAX_GROUPS - 1 ) + { DEBUG_CRASH(("Numeral '%d' out of range.\n", numeral)); return m_groupNumeralStrings[0]; } diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp index 9dc3467645..1050a3e7c9 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp @@ -395,7 +395,7 @@ int GameFileClass::Size(void) //------------------------------------------------------------------------------------------------- int GameFileClass::Write(void const *buffer, Int len) { -#ifdef _DEBUG +#ifdef RTS_DEBUG #endif return(0); } diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp index 4f83c3ece6..99090e4b40 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp @@ -52,14 +52,14 @@ #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif -#ifdef _DEBUG +#ifdef RTS_DEBUG #include "W3DDevice/GameClient/HeightMap.h" #include "WW3D2/dx8indexbuffer.h" #include "WW3D2/dx8vertexbuffer.h" @@ -259,7 +259,7 @@ void DebugHintObject::Render(RenderInfoClass & rinfo) DX8Wrapper::Draw_Triangles( 0, 1, 0, 3); } } -#endif // _DEBUG +#endif // RTS_DEBUG /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp index 1c30255555..e6cf34f8ae 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp @@ -47,7 +47,7 @@ #include "mutex.h" #include "thread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp index a0c2b9187b..86e61d7253 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp @@ -70,7 +70,7 @@ static const Real TEE_WIDTH_ADJUSTMENT = 1.03f; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -698,7 +698,7 @@ void W3DRoadBuffer::loadFloat4PtSection(RoadSegment *pRoad, Vector2 loc, V = Vector2::Dot_Product(roadNormal, curVector); U = Vector2::Dot_Product(roadVector, curVector); Int diffuse = 0; - #ifdef _DEBUG + #ifdef RTS_DEBUG //diffuse &= 0xFFFF00FF; // strip out green. #endif vb[numRoadVertices].u1 = uOffset+U/(uScale*4); @@ -996,7 +996,7 @@ void W3DRoadBuffer::loadLit4PtSection(RoadSegment *pRoad, UnsignedShort *ib, Ver shadeB*=255; diffuse=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((int)255 << 24); - #ifdef _DEBUG + #ifdef RTS_DEBUG //diffuse &= 0xFFFF00FF; // strip out green. #endif vb[m_curNumRoadVertices].u1 = info.uOffset+U/(info.scale*4); @@ -1346,7 +1346,7 @@ void W3DRoadBuffer::loadRoadSegment(UnsignedShort *ib, VertexFormatXYZDUV1 *vb, void W3DRoadBuffer::moveRoadSegTo(Int fromNdx, Int toNdx) { if (fromNdx<0 || fromNdx>=m_numRoads || toNdx<0 || toNdx>=m_numRoads) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_LOG(("bad moveRoadSegTo\n")); #endif return; @@ -1379,7 +1379,7 @@ void W3DRoadBuffer::checkLinkBefore(Int ndx) } Vector2 loc2 = m_roads[ndx].m_pt2.loc; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[ndx].m_pt1.loc == m_roads[ndx+1].m_pt2.loc, ("Bad link\n")); if (ndx>0) { DEBUG_ASSERTLOG(m_roads[ndx].m_pt2.loc != m_roads[ndx-1].m_pt1.loc, ("Bad Link\n")); @@ -1396,7 +1396,7 @@ void W3DRoadBuffer::checkLinkBefore(Int ndx) Int checkNdx = endOfCurSeg+1; while (checkNdx < m_numRoads) { if (m_roads[checkNdx].m_pt1.loc == loc2) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[checkNdx].m_pt1.count==1, ("Bad count\n")); #endif moveRoadSegTo(checkNdx, ndx); @@ -1404,7 +1404,7 @@ void W3DRoadBuffer::checkLinkBefore(Int ndx) if (m_roads[ndx].m_pt2.count != 1) return; endOfCurSeg++; } else if (m_roads[checkNdx].m_pt2.loc == loc2) { -#ifdef _DEBUG +#ifdef RTS_DEBUG if (m_roads[checkNdx].m_pt2.count!=1) { ::OutputDebugString("fooey.\n"); } @@ -1441,14 +1441,14 @@ void W3DRoadBuffer::checkLinkAfter(Int ndx) } Vector2 loc1 = m_roads[ndx].m_pt1.loc; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[ndx].m_pt2.loc == m_roads[ndx-1].m_pt1.loc, ("Bad link\n")); #endif Int checkNdx = ndx+1; while (checkNdx < m_numRoads && ndx < m_numRoads-1) { if (m_roads[checkNdx].m_pt2.loc == loc1) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[checkNdx].m_pt2.count==1, ("Bad count\n")); #endif ndx++; @@ -1456,7 +1456,7 @@ void W3DRoadBuffer::checkLinkAfter(Int ndx) loc1 = m_roads[ndx].m_pt1.loc; if (m_roads[ndx].m_pt1.count != 1) return; } else if (m_roads[checkNdx].m_pt1.loc == loc1) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[checkNdx].m_pt1.count==1, ("Wrong m_pt1.count.\n")); if ( m_roads[checkNdx].m_pt1.count!=1) { ::OutputDebugString("Wrong m_pt1.count.\n"); @@ -1579,7 +1579,7 @@ void W3DRoadBuffer::addMapObjects() } if (pMapObj->getFlag(FLAG_ROAD_POINT1)) { pMapObj2 = pMapObj->getNext(); -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(pMapObj2 && pMapObj2->getFlag(FLAG_ROAD_POINT2), ("Bad Flag\n")); #endif if (pMapObj2==NULL) break; @@ -3259,7 +3259,7 @@ void W3DRoadBuffer::drawRoads(CameraClass * camera, TextureClass *cloudTexture, } else { m_roadTypes[i].applyTexture(); } - #ifdef _DEBUG + #ifdef RTS_DEBUG //DX8Wrapper::Set_Shader(detailShader); // shows clipping. #endif for (Int pass=0; pass < devicePasses; pass++) diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp index ce47b3c99a..2f8633aa94 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp @@ -63,7 +63,7 @@ #include "WW3D2/dx8caps.h" #include "WW3D2/colorspace.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -104,7 +104,7 @@ RTS3DScene::RTS3DScene() m_scratchLight = NEW_REF( LightClass, (LightClass::DIRECTIONAL) ); // REF_PTR_SET(m_globalLight[lightIndex], pLight); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) m_shroudMaterialPass = NEW_REF(W3DShroudMaterialPassClass,()); else @@ -751,7 +751,7 @@ void RTS3DScene::renderOneObject(RenderInfoClass &rinfo, RenderObjClass *robj, I if (drawInfo) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_shroudOn) ss = OBJECTSHROUD_CLEAR; #endif @@ -1124,16 +1124,6 @@ void RTS3DScene::Customized_Render( RenderInfoClass &rinfo ) renderOneObject(rinfo, robj, localPlayerIndex); } } - -#ifdef INCLUDE_GRANNY_IN_BUILD - if (TheGrannyRenderObjSystem) - { //we only want to update granny animations once per frame, so only queue - //them up if this is not a mirror pass. - if (!ShaderClass::Is_Backface_Culling_Inverted()) - TheGrannyRenderObjSystem->queueUpdate(); - TheGrannyRenderObjSystem->Flush(); - } -#endif //Tell shadow manager to render shadows at the end of this frame //Don't draw shadows if there is no terrain present. @@ -1781,3 +1771,160 @@ void RTS3DInterfaceScene::Customized_Render( RenderInfoClass &rinfo ) } // end Customized_Render + + +/// The following is an :archive" of a partial attempt at detecting the mapshroud hack +/* + * + +void RTS3DScene::Visibility_Check(CameraClass * camera) +{ +#ifdef DIRTY_CONDITION_FLAGS + StDrawableDirtyStuffLocker lockDirtyStuff; +#endif + + RefRenderObjListIterator it(&RenderList); + DrawableInfo *drawInfo = NULL; + Drawable *draw = NULL; + RenderObjClass * robj; + + m_numPotentialOccluders=0; + m_numPotentialOccludees=0; + m_translucentObjectsCount=0; + m_numNonOccluderOrOccludee=0; + + Int currentFrame=0; + if (TheGameLogic) currentFrame = TheGameLogic->getFrame(); + if (currentFrame <= TheGlobalData->m_defaultOcclusionDelay) + currentFrame = TheGlobalData->m_defaultOcclusionDelay+1; //make sure occlusion is enabled when game starts (frame 0). + + + if (ShaderClass::Is_Backface_Culling_Inverted()) + { //we are rendering reflections + ///@todo: Have better flag to detect reflection pass + + // Loop over all top-level RenderObjects in this scene. If the bounding sphere is not in front + // of all the frustum planes, it is invisible. + for (it.First(); !it.Is_Done(); it.Next()) { + + robj = it.Peek_Obj(); + + draw=NULL; + drawInfo = (DrawableInfo *)robj->Get_User_Data(); + if (drawInfo) + draw=drawInfo->m_drawable; + + if( draw ) + { + if (robj->Is_Force_Visible()) { + robj->Set_Visible(true); + } else { + robj->Set_Visible(draw->getDrawsInMirror() && !camera->Cull_Sphere(robj->Get_Bounding_Sphere())); + } + } + else + { //perform normal culling on non-drawables + if (robj->Is_Force_Visible()) { + robj->Set_Visible(true); + } else { + robj->Set_Visible(!camera->Cull_Sphere(robj->Get_Bounding_Sphere())); + } + } + } + } + else + { + + // Loop over all top-level RenderObjects in this scene. If the bounding sphere is not in front + // of all the frustum planes, it is invisible. + for (it.First(); !it.Is_Done(); it.Next()) { + + robj = it.Peek_Obj(); + + if (robj->Is_Force_Visible()) { + robj->Set_Visible(true); + } else if (robj->Is_Hidden()) { + robj->Set_Visible(false); + } else { + + UnsignedByte isVisible = 0; + + + //Cheater Foil + isVisible |= (UnsignedByte)(camera->Cull_Sphere(robj->Get_Bounding_Sphere()) == FALSE); + isVisible |= (UnsignedByte)(draw->isDrawableEffectivelyHidden()); + isVisible |= (draw->getFullyObscuredByShroudWithCheatSpy()); + robj->Set_VisibleWithCheatSpy(isVisible); + if (robj->Is_VisibleWithCheatSpy())//this will clear for the bit set above + + { //need to keep track of occluders and ocludees for subsequent code. + drawInfo = (DrawableInfo *)robj->Get_User_Data(); + if (drawInfo && (draw=drawInfo->m_drawable) != NULL) + { + +// now handled above in the cheater foil <<<<<<<<<<<< +// if (draw->isDrawableEffectivelyHidden() || draw->getFullyObscuredByShroud()) +// { robj->Set_Visible(false); +// continue; +// } + //assume normal rendering. + drawInfo->m_flags = DrawableInfo::ERF_IS_NORMAL; //clear any rendering flags that may be in effect. + + + if (draw->getEffectiveOpacity() != 1.0f && m_translucentObjectsCount < TheGlobalData->m_maxVisibleTranslucentObjects) + { drawInfo->m_flags |= DrawableInfo::ERF_IS_TRANSLUCENT; //object is translucent + m_translucentObjectsBuffer[m_translucentObjectsCount++] = robj; + } + if (TheGlobalData->m_enableBehindBuildingMarkers && TheGameLogic->getShowBehindBuildingMarkers()) + { + //visible drawable. Check if it's either an occluder or occludee + if (draw->isKindOf(KINDOF_STRUCTURE) && m_numPotentialOccluders < TheGlobalData->m_maxVisibleOccluderObjects) + { //object which could occlude other objects that need to be visible. + //Make sure this object is not translucent so it's not rendered twice (from m_potentialOccluders and m_translucentObjectsBuffer) + if (drawInfo->m_flags ^ DrawableInfo::ERF_IS_TRANSLUCENT) + m_potentialOccluders[m_numPotentialOccluders++]=robj; + drawInfo->m_flags |= DrawableInfo::ERF_POTENTIAL_OCCLUDER; + } + else + if (draw->getObject() && + (draw->isKindOf(KINDOF_SCORE) || draw->isKindOf(KINDOF_SCORE_CREATE) || draw->isKindOf(KINDOF_SCORE_DESTROY) || draw->isKindOf(KINDOF_MP_COUNT_FOR_VICTORY)) && + (draw->getObject()->getSafeOcclusionFrame()) <= currentFrame && m_numPotentialOccludees < TheGlobalData->m_maxVisibleOccludeeObjects) + { //object which could be occluded but still needs to be visible. + //We process transucent units twice (also in m_translucentObjectsBuffer) because we need to see them when occluded. + m_potentialOccludees[m_numPotentialOccludees++]=robj; + drawInfo->m_flags |= DrawableInfo::ERF_POTENTIAL_OCCLUDEE; + } + else + if (drawInfo->m_flags == DrawableInfo::ERF_IS_NORMAL && m_numNonOccluderOrOccludee < TheGlobalData->m_maxVisibleNonOccluderOrOccludeeObjects) + { //regular object with no custom effects but still needs to be delayed to get the occlusion feature to work correctly. + //Make sure this object is not translucent so it's not rendered twice (from m_potentialOccluders and m_translucentObjectsBuffer) + if (drawInfo->m_flags ^ DrawableInfo::ERF_IS_TRANSLUCENT) //make sure not translucent + m_nonOccludersOrOccludees[m_numNonOccluderOrOccludee++]=robj; + drawInfo->m_flags |= DrawableInfo::ERF_IS_NON_OCCLUDER_OR_OCCLUDEE; + } + } + + + } + } + +// robj->Set_Visible(isVisible); //now handled above in the cheater foil + } + + ///@todo: We're not using LOD yet so I disabled this code. MW + // Also, should check how multiple passes (reflections) get along + // with the LOD manager - we're rendering double the load it thinks we are. + // Prepare visible objects for LOD: + // if (robj->Is_Really_Visible()) { + // robj->Prepare_LOD(*camera); + // } + } + } + + Visibility_Checked = true; +} + + + * + */ + diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp index a86eda95f3..31019b900c 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp @@ -74,7 +74,7 @@ #include "Common/GameLOD.h" #include "benchmark.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1077,7 +1077,7 @@ Int ShroudTextureShader::set(Int stage) if (stage == 0) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaSpriteShader); else diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp index 2926c39464..fcb943d214 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp @@ -42,7 +42,7 @@ #include "Common/GlobalData.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -154,7 +154,7 @@ void W3DShroud::init(WorldHeightMap *pMap, Real worldCellSizeX, Real worldCellSi memset(m_finalFogData,0,srcWidth*srcHeight); #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) m_pSrcTexture = DX8Wrapper::_Create_DX8_Surface(srcWidth,srcHeight, WW3D_FORMAT_A4R4G4B4); else @@ -178,7 +178,7 @@ void W3DShroud::init(WorldHeightMap *pMap, Real worldCellSizeX, Real worldCellSi //clear entire texture to black memset(m_srcTextureData,0,m_srcTexturePitch*srcHeight); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) fillShroudData(TheGlobalData->m_shroudAlpha); //initialize shroud to a known value #endif @@ -232,7 +232,7 @@ Bool W3DShroud::ReAcquireResources(void) // Create destination texture (stored in video memory). // Since we control the video memory copy, we can do partial updates more efficiently. Or do shift blits. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) m_pDstTexture = MSGNEW("TextureClass") TextureClass(m_dstTextureWidth,m_dstTextureHeight,WW3D_FORMAT_A4R4G4B4,MIP_LEVELS_1, TextureClass::POOL_DEFAULT); else @@ -264,7 +264,7 @@ W3DShroudLevel W3DShroud::getShroudLevel(Int x, Int y) { UnsignedShort pixel=*(UnsignedShort *)((Byte *)m_srcTextureData + x*2 + y*m_srcTexturePitch); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) //in this mode, alpha channel holds intensity return (W3DShroudLevel)((1.0f-((Real)(pixel >> 12)/15.0f))*255.0f); @@ -289,7 +289,7 @@ void W3DShroud::setShroudLevel(Int x, Int y, W3DShroudLevel level, Bool textureO if (level < TheGlobalData->m_shroudAlpha) level = TheGlobalData->m_shroudAlpha; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) { ///@todo: optimize this case if we end up using fog shroud. @@ -354,7 +354,7 @@ void W3DShroud::fillShroudData(W3DShroudLevel level) if (level < TheGlobalData->m_shroudAlpha) level = TheGlobalData->m_shroudAlpha; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //convert value to pixel format if (TheGlobalData && TheGlobalData->m_fogOfWarOn) { @@ -417,7 +417,7 @@ void W3DShroud::fillBorderShroudData(W3DShroudLevel level, SurfaceClass* pDestSu if (level < TheGlobalData->m_shroudAlpha) level = TheGlobalData->m_shroudAlpha; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //convert value to pixel format if (TheGlobalData && TheGlobalData->m_fogOfWarOn) { @@ -525,7 +525,7 @@ void W3DShroud::render(CameraClass *cam) if (DX8Wrapper::_Get_D3D_Device8() && (DX8Wrapper::_Get_D3D_Device8()->TestCooperativeLevel()) != D3D_OK) return; //device not ready to render anything -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn != m_drawFogOfWar) { //fog state has changed since last time shroud system was initialized @@ -585,7 +585,7 @@ void W3DShroud::render(CameraClass *cam) { for (Int x=0; xm_fogOfWarOn) { dataDest[x]=((TheGlobalData->m_shroudColor.getAsInt()>>4)&0xf) | (((TheGlobalData->m_shroudColor.getAsInt()>>12)&0xf)<<4) | (((TheGlobalData->m_shroudColor.getAsInt()>>20)&0xf)<<8) | ((((255-(dataSrc[x] & 0xff))>>4)&0xf)<<12); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp index 1754aca760..38ce674c73 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp @@ -60,7 +60,7 @@ #include "GameLogic/Object.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp index a122987507..fd8ddb0b56 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp @@ -84,14 +84,6 @@ W3DTerrainVisual::~W3DTerrainVisual() TheTerrainTracksRenderObjClassSystem=NULL; } -#ifdef INCLUDE_GRANNY_IN_BUILD - if (TheGrannyRenderObjSystem) - { - delete TheGrannyRenderObjSystem; - TheGrannyRenderObjSystem=NULL; - } -#endif - if (TheW3DShadowManager) { delete TheW3DShadowManager; @@ -121,11 +113,6 @@ void W3DTerrainVisual::init( void ) TheTerrainTracksRenderObjClassSystem = NEW TerrainTracksRenderObjClassSystem; TheTerrainTracksRenderObjClassSystem->init(W3DDisplay::m_3DScene); -#ifdef INCLUDE_GRANNY_IN_BUILD - // initialize Granny model drawing system - TheGrannyRenderObjSystem = NEW GrannyRenderObjSystem; -#endif - // initialize object shadow drawing system TheW3DShadowManager = NEW W3DShadowManager; TheW3DShadowManager->init(); @@ -319,7 +306,7 @@ Bool W3DTerrainVisual::load( AsciiString filename ) // add our terrain render object to the scene W3DDisplay::m_3DScene->Add_Render_Object( m_terrainRenderObject ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Icon drawing utility object for pathfinding. W3DDebugIcons *icons = NEW W3DDebugIcons; W3DDisplay::m_3DScene->Add_Render_Object( icons ); diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp index 03887a9b30..fb6831ff07 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp @@ -42,6 +42,7 @@ #include "Common/Module.h" #include "Common/RandomValue.h" #include "Common/ThingTemplate.h" +#include "Common/ThingSort.h" #include "Common/PerfTimer.h" #include "Common/PlayerList.h" #include "Common/Player.h" @@ -70,6 +71,7 @@ #include "GameLogic/Object.h" #include "GameLogic/ScriptEngine.h" #include "GameLogic/TerrainLogic.h" ///< @todo This should be TerrainVisual (client side) +#include "Common/AudioEventInfo.h" #include "W3DDevice/Common/W3DConvert.h" #include "W3DDevice/GameClient/HeightMap.h" @@ -92,7 +94,7 @@ #include "WinMain.h" /** @todo Remove this, it's only here because we are using timeGetTime, but we can remove that when we have our own timer */ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -439,7 +441,7 @@ void W3DView::setCameraTransform( void ) } m_3DCamera->Set_Clip_Planes(nearZ, farZ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_useCameraConstraints) #endif { @@ -462,7 +464,7 @@ void W3DView::setCameraTransform( void ) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_3DCamera->Set_View_Plane( m_FOV, -1 ); #endif @@ -580,7 +582,39 @@ static void drawTerrainNormal( Drawable *draw, void *userData ) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) +// ------------------------------------------------------------------------------------------------ +// Draw a crude circle. Appears on top of any world geometry +// ------------------------------------------------------------------------------------------------ +void drawDebugCircle( const Coord3D & center, Real radius, Real width, Color color ) +{ + const Real inc = PI/4.0f; + Real angle = 0.0f; + Coord3D pnt, lastPnt; + ICoord2D start, end; + Bool endValid, startValid; + + lastPnt.x = center.x + radius * (Real)cos(angle); + lastPnt.y = center.y + radius * (Real)sin(angle); + lastPnt.z = center.z; + endValid = ( TheTacticalView->worldToScreenTriReturn( &lastPnt, &end ) != View::WTS_INVALID ); + + for( angle = inc; angle <= 2.0f * PI; angle += inc ) + { + pnt.x = center.x + radius * (Real)cos(angle); + pnt.y = center.y + radius * (Real)sin(angle); + pnt.z = center.z; + startValid = ( TheTacticalView->worldToScreenTriReturn( &pnt, &start ) != View::WTS_INVALID ); + + if ( startValid && endValid ) + TheDisplay->drawLine( start.x, start.y, end.x, end.y, width, color ); + + lastPnt = pnt; + end = start; + endValid = startValid; + } +} + void drawDrawableExtents( Drawable *draw, void *userData ); // FORWARD DECLARATION // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ @@ -651,47 +685,24 @@ static void drawDrawableExtents( Drawable *draw, void *userData ) case GEOMETRY_SPHERE: // not quite right, but close enough case GEOMETRY_CYLINDER: { - Real angle, inc = PI/4.0f; - Real radius = draw->getDrawableGeometryInfo().getMajorRadius(); - Coord3D pnt, lastPnt; - ICoord2D start, end; - Real z = draw->getPosition()->z; + Coord3D center = *draw->getPosition(); + const Real radius = draw->getDrawableGeometryInfo().getMajorRadius(); // draw cylinder for( int i=0; i<2; i++ ) { + drawDebugCircle( center, radius, 1.0f, color ); - angle = 0.0f; - lastPnt.x = draw->getPosition()->x + radius * (Real)cos(angle); - lastPnt.y = draw->getPosition()->y + radius * (Real)sin(angle); - lastPnt.z = z; - TheTacticalView->worldToScreen( &lastPnt, &end ); - - for( angle = inc; angle <= 2.0f * PI; angle += inc ) - { - pnt.x = draw->getPosition()->x + radius * (Real)cos(angle); - pnt.y = draw->getPosition()->y + radius * (Real)sin(angle); - pnt.z = z; - TheTacticalView->worldToScreen( &pnt, &start ); - - TheDisplay->drawLine( start.x, start.y, end.x, end.y, 1.0f, color ); - - lastPnt = pnt; - end = start; - } - - // next time 'round, draw the top of the cylinder - z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition(); - + // next time 'round, draw the top of the cylinder + center.z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition(); } // end for i // draw centerline - pnt.x = draw->getPosition()->x; - pnt.y = draw->getPosition()->y; - pnt.z = draw->getPosition()->z; - TheTacticalView->worldToScreen( &pnt, &start ); - pnt.z = draw->getPosition()->z + draw->getDrawableGeometryInfo().getMaxHeightAbovePosition(); - TheTacticalView->worldToScreen( &pnt, &end ); + ICoord2D start, end; + center = *draw->getPosition(); + TheTacticalView->worldToScreen( ¢er, &start ); + center.z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition(); + TheTacticalView->worldToScreen( ¢er, &end ); TheDisplay->drawLine( start.x, start.y, end.x, end.y, 1.0f, color ); break; @@ -712,6 +723,118 @@ static void drawDrawableExtents( Drawable *draw, void *userData ) } // end if } // end drawDrawableExtents + + +void drawAudioLocations( Drawable *draw, void *userData ); +// ------------------------------------------------------------------------------------------------ +// Helper for drawAudioLocations +// ------------------------------------------------------------------------------------------------ +static void drawContainedAudioLocations( Object *obj, void *userData ) +{ + Drawable *draw = obj->getDrawable(); + + if( draw ) + drawAudioLocations( draw, userData ); + +} // end drawContainedAudio + + +//------------------------------------------------------------------------------------------------- +// Draw the location of audio objects in the world +//------------------------------------------------------------------------------------------------- +static void drawAudioLocations( Drawable *draw, void *userData ) +{ + // draw audio for things that are contained by this + Object *obj = draw->getObject(); + if( obj ) + { + ContainModuleInterface *contain = obj->getContain(); + + if( contain ) + contain->iterateContained( drawContainedAudioLocations, userData, FALSE ); + + } // end if + + const ThingTemplate * thingTemplate = draw->getTemplate(); + + if ( thingTemplate == NULL || thingTemplate->getEditorSorting() != ES_AUDIO ) + { + return; // All done + } + + // Copied in hideously inappropriate code copying ways from DrawObject.cpp + // Should definately be a global, probably read in from an INI file + static const Int poleHeight = 20; + static const Int flagHeight = 10; + static const Int flagWidth = 10; + const Color color = GameMakeColor(0x25, 0x25, 0xEF, 0xFF); + + // Draw flag for audio-only objects: + // * + // * * + // * * + // * * + // * * + // * * + // * + // * + // * + // * + // * + + Coord3D worldPoint; + ICoord2D start, end; + + worldPoint = *draw->getPosition(); + TheTacticalView->worldToScreen( &worldPoint, &start ); + worldPoint.z += poleHeight; + TheTacticalView->worldToScreen( &worldPoint, &end ); + TheDisplay->drawLine( start.x, start.y, end.x, end.y, 1.0f, color ); + + worldPoint.z -= flagHeight / 2; + worldPoint.x += flagWidth; + TheTacticalView->worldToScreen( &worldPoint, &start ); + TheDisplay->drawLine( start.x, start.y, end.x, end.y, 1.0f, color ); + + worldPoint.z -= flagHeight / 2; + worldPoint.x -= flagWidth; + TheTacticalView->worldToScreen( &worldPoint, &end ); + TheDisplay->drawLine( start.x, start.y, end.x, end.y, 1.0f, color ); +} + +//------------------------------------------------------------------------------------------------- +// Draw the radii of sounds attached to any type of object. +//------------------------------------------------------------------------------------------------- +static void drawAudioRadii( const Drawable * drawable ) +{ + + // Draw radii, if sound is playing + const AudioEventRTS * ambientSound = drawable->getAmbientSound(); + + if ( ambientSound && ambientSound->isCurrentlyPlaying() ) + { + const AudioEventInfo * ambientInfo = ambientSound->getAudioEventInfo(); + + if ( ambientInfo == NULL ) + { + // I don't think that's right... + OutputDebugString( ("Playing sound has NULL AudioEventInfo?\n" ) ); + + if ( TheAudio != NULL ) + { + ambientInfo = TheAudio->findAudioEventInfo( ambientSound->getEventName() ); + } + } + + if ( ambientInfo != NULL ) + { + // Colors match those used in WorldBuilder + drawDebugCircle( *drawable->getPosition(), ambientInfo->m_minDistance, 1.0f, GameMakeColor(0x00, 0x00, 0xFF, 0xFF) ); + drawDebugCircle( *drawable->getPosition(), ambientInfo->m_maxDistance, 1.0f, GameMakeColor(0xFF, 0x00, 0xFF, 0xFF) ); + } + } +} + #endif //------------------------------------------------------------------------------------------------- @@ -725,7 +848,7 @@ static void drawablePostDraw( Drawable *draw, void *userData ) Object* obj = draw->getObject(); Int localPlayerIndex = ThePlayerList ? ThePlayerList->getLocalPlayer()->getPlayerIndex() : 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ObjectShroudStatus ss = (!obj || !TheGlobalData->m_shroudOn) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); #else ObjectShroudStatus ss = (!obj) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); @@ -743,10 +866,13 @@ static void drawablePostDraw( Drawable *draw, void *userData ) draw->drawIconUI(); //} -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // debug collision extents if( TheGlobalData->m_showCollisionExtents ) drawDrawableExtents( draw, userData ); + + if ( TheGlobalData->m_showAudioLocations ) + drawAudioLocations( draw, userData ); #endif // debug terrain normals at object positions @@ -1398,7 +1524,7 @@ void W3DView::draw( void ) } // end if, show debug AI -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_debugCamera ) { UnsignedInt c = 0xaaffffff; @@ -1456,7 +1582,19 @@ void W3DView::draw( void ) TheDisplay->drawLine(s1.x, s1.y, s2.x, s2.y, 1.0f, c); } -#endif + + if ( TheGlobalData->m_showAudioLocations ) + { + // Draw audio radii for ALL drawables, not just those on screen + const Drawable * drawable = TheGameClient->getDrawableList(); + + while ( drawable != NULL ) + { + drawAudioRadii( drawable ); + drawable = drawable->getNextDrawable(); + } + } +#endif // DEBUG or INTERNAL Region3D axisAlignedRegion; getAxisAlignedViewRegion(axisAlignedRegion); @@ -1701,7 +1839,7 @@ void W3DView::setFieldOfView( Real angle ) { View::setFieldOfView( angle ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // this is only for testing, and recalculating the // camera every frame is wasteful setCameraTransform(); @@ -1710,14 +1848,14 @@ void W3DView::setFieldOfView( Real angle ) //------------------------------------------------------------------------------------------------- /** Using the W3D camera translate the world coordinate to a screen coord. - Screen coordinates returned in absolute values relative to full display resolution. */ + Screen coordinates returned in absolute values relative to full display resolution. + Returns if the point is on screen, off screen, or not transformable */ //------------------------------------------------------------------------------------------------- -Bool W3DView::worldToScreen( const Coord3D *w, ICoord2D *s ) +View::WorldToScreenReturn W3DView::worldToScreenTriReturn( const Coord3D *w, ICoord2D *s ) { - // sanity if( w == NULL || s == NULL ) - return FALSE; + return WTS_INVALID; if( m_3DCamera ) { @@ -1731,7 +1869,7 @@ Bool W3DView::worldToScreen( const Coord3D *w, ICoord2D *s ) // Can't get a valid number if it's beyond the clip planes. jba s->x = 0; s->y = 0; - return FALSE; + return WTS_INVALID; } // @@ -1750,15 +1888,15 @@ Bool W3DView::worldToScreen( const Coord3D *w, ICoord2D *s ) // s->y = (getHeight() * (-screen.Y + 1.0f)) / 2.0f; if (projection != CameraClass::INSIDE_FRUSTUM) { - return FALSE; + return WTS_OUTSIDE_FRUSTUM; } - return TRUE; + return WTS_INSIDE_FRUSTUM; } // end if - return FALSE; -} // end worldToScreen + return WTS_INVALID; +} // end worldToScreenTriReturn //------------------------------------------------------------------------------------------------- /** Using the W3D camera translate the screen coord to world coord */ diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp index c9e781fd43..150712c48a 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp @@ -86,7 +86,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -105,16 +105,9 @@ W3DWaypointBuffer::W3DWaypointBuffer(void) m_line = new SegmentedLineClass; m_texture = WW3DAssetManager::Get_Instance()->Get_Texture( "EXLaser.tga" ); - if( m_texture ) - { - m_line->Set_Texture( m_texture ); - } - ShaderClass lineShader=ShaderClass::_PresetAdditiveShader; - lineShader.Set_Depth_Compare(ShaderClass::PASS_ALWAYS); - m_line->Set_Shader( lineShader ); //pick the alpha blending mode you want - see shader.h for others. - m_line->Set_Width( 1.5f ); - m_line->Set_Color( Vector3( 0.25f, 0.5f, 1.0f ) ); - m_line->Set_Texture_Mapping_Mode( SegLineRendererClass::TILED_TEXTURE_MAP ); //this tiles the texture across the line + + + setDefaultLineStyle(); } //============================================================================= @@ -125,6 +118,8 @@ W3DWaypointBuffer::W3DWaypointBuffer(void) W3DWaypointBuffer::~W3DWaypointBuffer(void) { REF_PTR_RELEASE( m_waypointNodeRobj ); + REF_PTR_RELEASE( m_texture ); + REF_PTR_RELEASE( m_line ); } //============================================================================= @@ -137,6 +132,21 @@ void W3DWaypointBuffer::freeWaypointBuffers() } +void W3DWaypointBuffer::setDefaultLineStyle( void ) +{ + if( m_texture ) + { + m_line->Set_Texture( m_texture ); + } + ShaderClass lineShader=ShaderClass::_PresetAdditiveShader; + lineShader.Set_Depth_Compare(ShaderClass::PASS_ALWAYS); + m_line->Set_Shader( lineShader ); //pick the alpha blending mode you want - see shader.h for others. + m_line->Set_Width( 1.5f ); + m_line->Set_Color( Vector3( 0.25f, 0.5f, 1.0f ) ); + m_line->Set_Texture_Mapping_Mode( SegLineRendererClass::TILED_TEXTURE_MAP ); //this tiles the texture across the line +} + + //============================================================================= // W3DWaypointBuffer::drawWaypoints //============================================================================= @@ -418,7 +428,6 @@ void W3DWaypointBuffer::drawWaypoints(RenderInfoClass &rinfo) m_line->Render( localRinfo ); } - } } diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp index 1374e383a6..6f083fe844 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp @@ -66,7 +66,7 @@ #include "W3DDevice/GameClient/W3DCustomScene.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -196,8 +196,11 @@ static Bool wireframeForDebug = 0; void WaterRenderObjClass::setupJbaWaterShader(void) { + if (!TheWaterTransparency->m_additiveBlend) + DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaShader); + else + DX8Wrapper::Set_Shader(ShaderClass::_PresetAdditiveShader); - DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaShader); VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); DX8Wrapper::Set_Material(vmat); REF_PTR_RELEASE(vmat); @@ -304,7 +307,8 @@ WaterRenderObjClass::~WaterRenderObjClass(void) { WaterSettings[i].m_skyTextureFile.clear(); WaterSettings[i].m_waterTextureFile.clear(); } - + ((WaterTransparencySetting*)TheWaterTransparency.getNonOverloadedPointer())->deleteInstance(); + TheWaterTransparency = NULL; ReleaseResources(); if (m_waterTrackSystem) @@ -365,9 +369,6 @@ WaterRenderObjClass::WaterRenderObjClass(void) m_waterSparklesTexture=0; m_riverXOffset=0; m_riverYOffset=0; - - - } //------------------------------------------------------------------------------------------------- @@ -430,7 +431,6 @@ HRESULT WaterRenderObjClass::initBumpMap(LPDIRECT3DTEXTURE8 *pTex, TextureClass #ifdef MIPMAP_BUMP_TEXTURE - numLevels=pBumpSource->Get_Mip_Level_Count(); pBumpSource->Get_Level_Description(d3dsd); if (Get_Bytes_Per_Pixel(d3dsd.Format) != 4) @@ -440,6 +440,13 @@ HRESULT WaterRenderObjClass::initBumpMap(LPDIRECT3DTEXTURE8 *pTex, TextureClass return S_OK; } + if (pBumpSource->Peek_D3D_Texture()) + { + numLevels=pBumpSource->Peek_D3D_Texture()->GetLevelCount(); + } + else + return S_OK; + pTex[0]=DX8Wrapper::_Create_DX8_Texture(d3dsd.Width,d3dsd.Height,WW3D_FORMAT_U8V8,MIP_LEVELS_ALL,D3DPOOL_MANAGED,false); for (Int level=0; level < numLevels; level++) @@ -929,9 +936,9 @@ void WaterRenderObjClass::ReAcquireResources(void) } shader = "ps.1.1\n \ - tex t0 \n\ - tex t1 \n\ - tex t2 \n\ + tex t0 ;get water texture\n\ + tex t1 ;get white highlights on black background\n\ + tex t2 ;get white highlights with more tiling\n\ tex t3 ; get black shroud \n\ mul r0,v0,t0 ; blend vertex color and alpha into base texture. \n\ mad r0.rgb, t1, t2, r0 ; blend sparkles and noise \n\ @@ -1078,10 +1085,12 @@ Int WaterRenderObjClass::init(Real waterLevel, Real dx, Real dy, SceneClass *par material->Peek_Texture(i)->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); } } + + REF_PTR_RELEASE(material); } - m_riverTexture=WW3DAssetManager::Get_Instance()->Get_Texture("TWWater01.tga"); - + m_riverTexture=WW3DAssetManager::Get_Instance()->Get_Texture(TheWaterTransparency->m_standingWaterTexture.str()); + //For some reason setting a NULL texture does not result in 0xffffffff for pixel shaders so using explicit "white" texture. m_whiteTexture=MSGNEW("TextureClass") TextureClass(1,1,WW3D_FORMAT_A4R4G4B4,MIP_LEVELS_1); SurfaceClass *surface=m_whiteTexture->Get_Surface_Level(); @@ -1099,6 +1108,15 @@ Int WaterRenderObjClass::init(Real waterLevel, Real dx, Real dy, SceneClass *par return 0; } +void WaterRenderObjClass::updateMapOverrides(void) +{ + if (m_riverTexture && TheWaterTransparency->m_standingWaterTexture.compareNoCase(m_riverTexture->Get_Texture_Name()) != 0) + { + REF_PTR_RELEASE(m_riverTexture); + m_riverTexture = WW3DAssetManager::Get_Instance()->Get_Texture(TheWaterTransparency->m_standingWaterTexture.str()); + } +} + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ void WaterRenderObjClass::reset( void ) @@ -2705,29 +2723,49 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig) } - Real shadeR, shadeG, shadeB; - shadeR = TheGlobalData->m_terrainAmbient[0].red; - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; + Real shadeR=TheWaterTransparency->m_standingWaterColor.red; + Real shadeG=TheWaterTransparency->m_standingWaterColor.green; + Real shadeB=TheWaterTransparency->m_standingWaterColor.blue; - //Add in diffuse lighting from each terrain light - for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) + //If the water color is not overridden, use legacy lighting code. + if ( shadeR==1.0f && shadeG==1.0f && shadeB==1.0f) { - if (-TheGlobalData->m_terrainLightPos[lightIndex].z > 0) - { shadeR += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].red; - shadeG += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].green; - shadeB += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].blue; + shadeR = TheGlobalData->m_terrainAmbient[0].red; + shadeG = TheGlobalData->m_terrainAmbient[0].green; + shadeB = TheGlobalData->m_terrainAmbient[0].blue; + + //Add in diffuse lighting from each terrain light + for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) + { + if (-TheGlobalData->m_terrainLightPos[lightIndex].z > 0) + { shadeR += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].red; + shadeG += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].green; + shadeB += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].blue; + } } - } - //Get water material colors - Real waterShadeR = (m_settings[m_tod].waterDiffuse & 0xff) / 255.0f; - Real waterShadeG = ((m_settings[m_tod].waterDiffuse >> 8) & 0xff) / 255.0f; - Real waterShadeB = ((m_settings[m_tod].waterDiffuse >> 16) & 0xff) / 255.0f; + //Get water material colors + Real waterShadeR = (m_settings[m_tod].waterDiffuse & 0xff) / 255.0f; + Real waterShadeG = ((m_settings[m_tod].waterDiffuse >> 8) & 0xff) / 255.0f; + Real waterShadeB = ((m_settings[m_tod].waterDiffuse >> 16) & 0xff) / 255.0f; - shadeR=shadeR*waterShadeR*255.0f; - shadeG=shadeG*waterShadeG*255.0f; - shadeB=shadeB*waterShadeB*255.0f; + shadeR=shadeR*waterShadeR*255.0f; + shadeG=shadeG*waterShadeG*255.0f; + shadeB=shadeB*waterShadeB*255.0f; + } + else + { + shadeR=shadeR*255.0f; + shadeG=shadeG*255.0f; + shadeB=shadeB*255.0f; + + if (shadeR == 0 && shadeG == 0 && shadeB == 0) + { //special case where we disable lighting + shadeR=255; + shadeG=255; + shadeB=255; + } + } Int diffuse=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16); @@ -2832,9 +2870,15 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig) DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); //position the water surface DX8Wrapper::Set_Index_Buffer(ib_access,0); DX8Wrapper::Set_Vertex_Buffer(vb_access); - DX8Wrapper::Set_Texture(0,m_riverTexture); //set to white + DX8Wrapper::Set_Texture(0,m_riverTexture); //set to blue setupJbaWaterShader(); + + //In additive blending we need to use the alpha at the edges of river to darken + //rgb instead. + if (TheWaterTransparency->m_additiveBlend) + DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); + if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(m_riverWaterPixelShader); DWORD cull; DX8Wrapper::_Get_D3D_Device8()->GetRenderState(D3DRS_CULLMODE, &cull); @@ -2852,6 +2896,9 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig) if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(NULL); + //restore blend mode to what W3D expects. + if (TheWaterTransparency->m_additiveBlend) + DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_ONE ); //do second pass to apply the shroud on water plane if (TheTerrainRenderObject->getShroud()) @@ -2896,7 +2943,11 @@ void WaterRenderObjClass::setupFlatWaterShader(void) } DX8Wrapper::Set_Texture(0,m_riverTexture); - DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaShader); + if (!TheWaterTransparency->m_additiveBlend) + DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaShader); + else + DX8Wrapper::Set_Shader(ShaderClass::_PresetAdditiveShader); + VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); DX8Wrapper::Set_Material(vmat); REF_PTR_RELEASE(vmat); @@ -2987,7 +3038,7 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4]) DynamicIBAccessClass::WriteLockClass lockib(&ib_access); UnsignedShort *curIb = lockib.Get_Index_Array(); for (j=0; jm_terrainAmbient[0].red; - shadeG = TheGlobalData->m_terrainAmbient[0].green; - shadeB = TheGlobalData->m_terrainAmbient[0].blue; + Real shadeR=TheWaterTransparency->m_standingWaterColor.red; + Real shadeG=TheWaterTransparency->m_standingWaterColor.green; + Real shadeB=TheWaterTransparency->m_standingWaterColor.blue; - //Add in diffuse lighting from each terrain light - for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) + //If the water color is not overridden, use legacy lighting code. + if ( shadeR==1.0f && shadeG==1.0f && shadeB==1.0f) { - if (-TheGlobalData->m_terrainLightPos[lightIndex].z > 0) - { shadeR += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].red; - shadeG += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].green; - shadeB += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].blue; + shadeR = TheGlobalData->m_terrainAmbient[0].red; + shadeG = TheGlobalData->m_terrainAmbient[0].green; + shadeB = TheGlobalData->m_terrainAmbient[0].blue; + + //Add in diffuse lighting from each terrain light + for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++) + { + if (-TheGlobalData->m_terrainLightPos[lightIndex].z > 0) + { shadeR += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].red; + shadeG += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].green; + shadeB += -TheGlobalData->m_terrainLightPos[lightIndex].z * TheGlobalData->m_terrainDiffuse[lightIndex].blue; + } } - } - //Get water material colors - Real waterShadeR = (m_settings[m_tod].waterDiffuse & 0xff) / 255.0f; - Real waterShadeG = ((m_settings[m_tod].waterDiffuse >> 8) & 0xff) / 255.0f; - Real waterShadeB = ((m_settings[m_tod].waterDiffuse >> 16) & 0xff) / 255.0f; + //Get water material colors + Real waterShadeR = (m_settings[m_tod].waterDiffuse & 0xff) / 255.0f; + Real waterShadeG = ((m_settings[m_tod].waterDiffuse >> 8) & 0xff) / 255.0f; + Real waterShadeB = ((m_settings[m_tod].waterDiffuse >> 16) & 0xff) / 255.0f; - shadeR=shadeR*waterShadeR*255.0f; - shadeG=shadeG*waterShadeG*255.0f; - shadeB=shadeB*waterShadeB*255.0f; + shadeR=shadeR*waterShadeR*255.0f; + shadeG=shadeG*waterShadeG*255.0f; + shadeB=shadeB*waterShadeB*255.0f; + } + else + { + shadeR=shadeR*255.0f; + shadeG=shadeG*255.0f; + shadeB=shadeB*255.0f; + + if (shadeR == 0 && shadeG == 0 && shadeB == 0) + { //special case where we disable lighting + shadeR=255; + shadeG=255; + shadeB=255; + } + } Int diffuse=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16); @@ -3165,7 +3237,8 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4]) //If video card supports it and it's enabled, feather the water edge using destination alpha if (DX8Wrapper::getBackBufferFormat() == WW3D_FORMAT_A8R8G8B8 && TheGlobalData->m_showSoftWaterEdge && TheWaterTransparency->m_transparentWaterDepth !=0) { DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_DESTALPHA ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVDESTALPHA ); + if (!TheWaterTransparency->m_additiveBlend) + DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVDESTALPHA ); } @@ -3209,8 +3282,15 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4]) if (m_riverWaterPixelShader) DX8Wrapper::_Get_D3D_Device8()->SetPixelShader(NULL); //Restore alpha blend to default values since we may have changed them to feather edges. - DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); - DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); + if (!TheWaterTransparency->m_additiveBlend) + { DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); + DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); + } + else + { + DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_ONE ); + DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_ONE ); + } if (TheTerrainRenderObject->getShroud()) { diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp index 9af3f0ec67..bc414441c4 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp @@ -50,7 +50,7 @@ #include "WW3D2/matinfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp index 5bb26b9c7b..b95040ead1 100644 --- a/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp +++ b/Generals/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp @@ -41,7 +41,7 @@ #include "GameLogic/AI.h" #include "GameLogic/AIPathfind.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp index 2f52d96c98..94730ba482 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp @@ -26,7 +26,6 @@ // Bryan Cleveland, August 2002 ///////////////////////////////////////////////////////////// -#include #include "Common/AudioAffect.h" #include "Common/ArchiveFile.h" #include "Common/ArchiveFileSystem.h" @@ -36,8 +35,9 @@ #include "Common/LocalFileSystem.h" #include "Win32Device/Common/Win32BIGFile.h" #include "Win32Device/Common/Win32BIGFileSystem.h" +#include "Utility/endian_compat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -77,8 +77,6 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { Int archiveFileSize = 0; Int numLittleFiles = 0; - ArchiveFile *archiveFile = NEW Win32BIGFile; - DEBUG_LOG(("Win32BIGFileSystem::openArchiveFile - opening BIG file %s\n", filename)); if (fp == NULL) { @@ -107,7 +105,7 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { // read in the number of files contained in this BIG file. // change the order of the bytes cause the file size is in reverse byte order for some reason. fp->read(&numLittleFiles, 4); - numLittleFiles = ntohl(numLittleFiles); + numLittleFiles = betoh(numLittleFiles); DEBUG_LOG(("Win32BIGFileSystem::openArchiveFile - %d are contained in archive\n", numLittleFiles)); // for (Int i = 0; i < 2; ++i) { @@ -120,6 +118,8 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { fp->seek(0x10, File::START); // read in each directory listing. ArchivedFileInfo *fileInfo = NEW ArchivedFileInfo; + // TheSuperHackers @fix Mauller 23/04/2025 Create new file handle when necessary to prevent memory leak + ArchiveFile *archiveFile = NEW Win32BIGFile; for (Int i = 0; i < numLittleFiles; ++i) { Int filesize = 0; @@ -127,8 +127,8 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { fp->read(&fileOffset, 4); fp->read(&filesize, 4); - filesize = ntohl(filesize); - fileOffset = ntohl(fileOffset); + filesize = betoh(filesize); + fileOffset = betoh(fileOffset); fileInfo->m_archiveFilename = archiveFileName; fileInfo->m_offset = fileOffset; diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp index 80cfd4611d..08a5eaaaee 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp @@ -45,7 +45,6 @@ Win32LocalFileSystem::~Win32LocalFileSystem() { File * Win32LocalFileSystem::openFile(const Char *filename, Int access /* = 0 */) { //USE_PERF_TIMER(Win32LocalFileSystem_openFile) - Win32LocalFile *file = newInstance( Win32LocalFile ); // sanity check if (strlen(filename) <= 0) { @@ -69,6 +68,9 @@ File * Win32LocalFileSystem::openFile(const Char *filename, Int access /* = 0 */ } } + // TheSuperHackers @fix Mauller 21/04/2025 Create new file handle when necessary to prevent memory leak + Win32LocalFile *file = newInstance( Win32LocalFile ); + if (file->open(filename, access) == FALSE) { file->close(); file->deleteInstance(); diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp index 572acee254..761a98b785 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp @@ -37,7 +37,7 @@ #include "Common/UnicodeString.h" #include "GameClient/GameText.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp index 58fdb04f8c..be810e08d6 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp @@ -49,37 +49,37 @@ struct ErrorLookup }; static ErrorLookup errorLookup[] = { -{ DIERR_ACQUIRED, "DIERR_ACQUIRED" }, -{ DIERR_ALREADYINITIALIZED, "DIERR_ALREADYINITIALIZED" }, -{ DIERR_BADDRIVERVER, "DIERR_BADDRIVERVER" }, -{ DIERR_BETADIRECTINPUTVERSION, "DIERR_BETADIRECTINPUTVERSION" }, -{ DIERR_DEVICEFULL, "DIERR_DEVICEFULL" }, -{ DIERR_DEVICENOTREG, "DIERR_DEVICENOTREG" }, -{ DIERR_EFFECTPLAYING, "DIERR_EFFECTPLAYING" }, -{ DIERR_GENERIC, "DIERR_GENERIC" }, -{ DIERR_HANDLEEXISTS, "DIERR_HANDLEEXISTS" }, -{ DIERR_HASEFFECTS, "DIERR_HASEFFECTS" }, -{ DIERR_INCOMPLETEEFFECT, "DIERR_INCOMPLETEEFFECT" }, -{ DIERR_INPUTLOST, "DIERR_INPUTLOST" }, -{ DIERR_INVALIDPARAM, "DIERR_INVALIDPARAM" }, -{ DIERR_MAPFILEFAIL, "DIERR_MAPFILEFAIL" }, -{ DIERR_MOREDATA, "DIERR_MOREDATA" }, -{ DIERR_NOAGGREGATION, "DIERR_NOAGGREGATION" }, -{ DIERR_NOINTERFACE, "DIERR_NOINTERFACE" }, -{ DIERR_NOTACQUIRED, "DIERR_NOTACQUIRED" }, -{ DIERR_NOTBUFFERED, "DIERR_NOTBUFFERED" }, -{ DIERR_NOTDOWNLOADED, "DIERR_NOTDOWNLOADED" }, -{ DIERR_NOTEXCLUSIVEACQUIRED, "DIERR_NOTEXCLUSIVEACQUIRED" }, -{ DIERR_NOTFOUND, "DIERR_NOTFOUND" }, -{ DIERR_NOTINITIALIZED, "DIERR_NOTINITIALIZED" }, -{ DIERR_OBJECTNOTFOUND, "DIERR_OBJECTNOTFOUND" }, -{ DIERR_OLDDIRECTINPUTVERSION, "DIERR_OLDDIRECTINPUTVERSION" }, -{ DIERR_OTHERAPPHASPRIO, "DIERR_OTHERAPPHASPRIO" }, -{ DIERR_OUTOFMEMORY, "DIERR_OUTOFMEMORY" }, -{ DIERR_READONLY, "DIERR_READONLY" }, -{ DIERR_REPORTFULL, "DIERR_REPORTFULL" }, -{ DIERR_UNPLUGGED, "DIERR_UNPLUGGED" }, -{ DIERR_UNSUPPORTED, "DIERR_UNSUPPORTED" }, +{ (HRESULT)DIERR_ACQUIRED, "DIERR_ACQUIRED" }, +{ (HRESULT)DIERR_ALREADYINITIALIZED, "DIERR_ALREADYINITIALIZED" }, +{ (HRESULT)DIERR_BADDRIVERVER, "DIERR_BADDRIVERVER" }, +{ (HRESULT)DIERR_BETADIRECTINPUTVERSION, "DIERR_BETADIRECTINPUTVERSION" }, +{ (HRESULT)DIERR_DEVICEFULL, "DIERR_DEVICEFULL" }, +{ (HRESULT)DIERR_DEVICENOTREG, "DIERR_DEVICENOTREG" }, +{ (HRESULT)DIERR_EFFECTPLAYING, "DIERR_EFFECTPLAYING" }, +{ (HRESULT)DIERR_GENERIC, "DIERR_GENERIC" }, +{ (HRESULT)DIERR_HANDLEEXISTS, "DIERR_HANDLEEXISTS" }, +{ (HRESULT)DIERR_HASEFFECTS, "DIERR_HASEFFECTS" }, +{ (HRESULT)DIERR_INCOMPLETEEFFECT, "DIERR_INCOMPLETEEFFECT" }, +{ (HRESULT)DIERR_INPUTLOST, "DIERR_INPUTLOST" }, +{ (HRESULT)DIERR_INVALIDPARAM, "DIERR_INVALIDPARAM" }, +{ (HRESULT)DIERR_MAPFILEFAIL, "DIERR_MAPFILEFAIL" }, +{ (HRESULT)DIERR_MOREDATA, "DIERR_MOREDATA" }, +{ (HRESULT)DIERR_NOAGGREGATION, "DIERR_NOAGGREGATION" }, +{ (HRESULT)DIERR_NOINTERFACE, "DIERR_NOINTERFACE" }, +{ (HRESULT)DIERR_NOTACQUIRED, "DIERR_NOTACQUIRED" }, +{ (HRESULT)DIERR_NOTBUFFERED, "DIERR_NOTBUFFERED" }, +{ (HRESULT)DIERR_NOTDOWNLOADED, "DIERR_NOTDOWNLOADED" }, +{ (HRESULT)DIERR_NOTEXCLUSIVEACQUIRED, "DIERR_NOTEXCLUSIVEACQUIRED" }, +{ (HRESULT)DIERR_NOTFOUND, "DIERR_NOTFOUND" }, +{ (HRESULT)DIERR_NOTINITIALIZED, "DIERR_NOTINITIALIZED" }, +{ (HRESULT)DIERR_OBJECTNOTFOUND, "DIERR_OBJECTNOTFOUND" }, +{ (HRESULT)DIERR_OLDDIRECTINPUTVERSION, "DIERR_OLDDIRECTINPUTVERSION" }, +{ (HRESULT)DIERR_OTHERAPPHASPRIO, "DIERR_OTHERAPPHASPRIO" }, +{ (HRESULT)DIERR_OUTOFMEMORY, "DIERR_OUTOFMEMORY" }, +{ (HRESULT)DIERR_READONLY, "DIERR_READONLY" }, +{ (HRESULT)DIERR_REPORTFULL, "DIERR_REPORTFULL" }, +{ (HRESULT)DIERR_UNPLUGGED, "DIERR_UNPLUGGED" }, +{ (HRESULT)DIERR_UNSUPPORTED, "DIERR_UNSUPPORTED" }, { 0, NULL } }; diff --git a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp index d5c0eb9616..d6a80e85fd 100644 --- a/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp +++ b/Generals/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp @@ -37,7 +37,7 @@ #include "Win32Device/GameClient/Win32Mouse.h" #include "WinMain.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/Libraries/Source/WWVegas/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/CMakeLists.txt index 38082f3ffd..e26a5809cd 100644 --- a/Generals/Code/Libraries/Source/WWVegas/CMakeLists.txt +++ b/Generals/Code/Libraries/Source/WWVegas/CMakeLists.txt @@ -2,26 +2,20 @@ add_library(g_wwcommon INTERFACE) target_link_libraries(g_wwcommon INTERFACE - d3d8lib core_config core_utility core_wwcommon + d3d8lib milesstub stlport ) target_include_directories(g_wwcommon INTERFACE - . + ${CMAKE_CURRENT_SOURCE_DIR} WW3D2 - WWAudio - WWMath - WWSaveLoad - Wwutil ) -add_subdirectory(WWMath) -add_subdirectory(Wwutil) -add_subdirectory(WWSaveLoad) +add_subdirectory(WWAudio) add_subdirectory(WW3D2) add_subdirectory(WWDownload) @@ -29,19 +23,12 @@ add_subdirectory(WWDownload) add_library(g_wwvegas INTERFACE) target_include_directories(g_wwvegas INTERFACE - . + ${CMAKE_CURRENT_SOURCE_DIR} WW3D2 - WWDownload - WWMath - WWSaveLoad - Wwutil ) target_link_libraries(g_wwvegas INTERFACE - core_wwvegas + core_wwvegas g_ww3d2 g_wwdownload - g_wwmath - g_wwsaveload - g_wwutil ) diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt index 8e5e03baf9..e4e14e3d9a 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt @@ -1,108 +1,109 @@ -# Set source files set(WW3D2_SRC - aabtree.cpp - aabtree.h + #aabtree.cpp + #aabtree.h aabtreebuilder.cpp aabtreebuilder.h - agg_def.cpp - agg_def.h + #agg_def.cpp + #agg_def.h + #animatedsoundmgr.cpp + #animatedsoundmgr.h animobj.cpp animobj.h assetmgr.cpp assetmgr.h - assetstatus.cpp - assetstatus.h - bitmaphandler.cpp - bitmaphandler.h + #assetstatus.cpp + #assetstatus.h + #bitmaphandler.cpp + #bitmaphandler.h bmp2d.cpp bmp2d.h boxrobj.cpp boxrobj.h - bwrender.cpp - bwrender.h + #bwrender.cpp + #bwrender.h camera.cpp camera.h #classid.h - collect.cpp - collect.h - colorspace.h - coltest.cpp - coltest.h - coltype.h - composite.cpp - composite.h + #collect.cpp + #collect.h + #colorspace.h + #coltest.cpp + #coltest.h + #coltype.h + #composite.cpp + #composite.h dazzle.cpp dazzle.h ddsfile.cpp ddsfile.h decalmsh.cpp decalmsh.h - decalsys.cpp - decalsys.h - distlod.cpp - distlod.h - dllist.h + #decalsys.cpp + #decalsys.h + #distlod.cpp + #distlod.h + #dllist.h dx8caps.cpp dx8caps.h dx8fvf.cpp dx8fvf.h dx8indexbuffer.cpp dx8indexbuffer.h - dx8list.h - dx8polygonrenderer.cpp - dx8polygonrenderer.h + #dx8list.h + #dx8polygonrenderer.cpp + #dx8polygonrenderer.h dx8renderer.cpp dx8renderer.h dx8texman.cpp dx8texman.h dx8vertexbuffer.cpp dx8vertexbuffer.h - dx8webbrowser.cpp - dx8webbrowser.h + #dx8webbrowser.cpp + #dx8webbrowser.h dx8wrapper.cpp dx8wrapper.h - dynamesh.cpp - dynamesh.h - font3d.cpp - font3d.h - formconv.cpp - formconv.h - FramGrab.cpp - framgrab.h - hanim.cpp - hanim.h + #dynamesh.cpp + #dynamesh.h + #font3d.cpp + #font3d.h + #formconv.cpp + #formconv.h + #FramGrab.cpp + #framgrab.h + #hanim.cpp + #hanim.h hanimmgr.cpp hanimmgr.h - hcanim.cpp - hcanim.h + #hcanim.cpp + #hcanim.h hlod.cpp hlod.h - hmdldef.cpp - hmdldef.H + #hmdldef.cpp + #hmdldef.H hmorphanim.cpp hmorphanim.h hrawanim.cpp hrawanim.h - htree.cpp - htree.h + #htree.cpp + #htree.h htreemgr.cpp htreemgr.h - intersec.cpp - intersec.h - intersec.inl - inttest.h - layer.cpp - layer.h + #intersec.cpp + #intersec.h + #intersec.inl + #inttest.h + #layer.cpp + #layer.h light.cpp light.h lightenvironment.cpp lightenvironment.h - line3d.cpp - line3d.h + #line3d.cpp + #line3d.h mapper.cpp mapper.h - matinfo.cpp - matinfo.h + #matinfo.cpp + #matinfo.h matpass.cpp matpass.h matrixmapper.cpp @@ -111,8 +112,8 @@ set(WW3D2_SRC mesh.h meshbuild.cpp meshbuild.h - meshdam.cpp - meshdam.h + #meshdam.cpp + #meshdam.h meshgeometry.cpp meshgeometry.h meshmatdesc.cpp @@ -120,10 +121,10 @@ set(WW3D2_SRC meshmdl.cpp meshmdl.h meshmdlio.cpp - metalmap.cpp - metalmap.h - missingtexture.cpp - missingtexture.h + #metalmap.cpp + #metalmap.h + #missingtexture.cpp + #missingtexture.h motchan.cpp motchan.h nullrobj.cpp @@ -134,69 +135,70 @@ set(WW3D2_SRC part_emt.h part_ldr.cpp part_ldr.h - pivot.cpp - pivot.h - pointgr.cpp - pointgr.h - polyinfo.cpp - polyinfo.h - predlod.cpp - predlod.h - prim_anim.cpp - prim_anim.h - projector.cpp - projector.h - proto.cpp - proto.h - proxy.h - rddesc.h + #pivot.cpp + #pivot.h + #pointgr.cpp + #pointgr.h + #polyinfo.cpp + #polyinfo.h + #predlod.cpp + #predlod.h + #prim_anim.cpp + #prim_anim.h + #projector.cpp + #projector.h + #proto.cpp + #proto.h + #proxy.h + #rddesc.h render2d.cpp render2d.h - render2dsentence.cpp - render2dsentence.h - renderobjectrecycler.cpp - renderobjectrecycler.h - rendobj.cpp - rendobj.h + #render2dsentence.cpp + #render2dsentence.h + #renderobjectrecycler.cpp + #renderobjectrecycler.h + #rendobj.cpp + #rendobj.h rinfo.cpp rinfo.h - ringobj.cpp - ringobj.h - robjlist.h + #ringobj.cpp + #ringobj.h + #robjlist.h scene.cpp scene.h - segline.cpp - segline.h - seglinerenderer.cpp - seglinerenderer.h + #segline.cpp + #segline.h + #seglinerenderer.cpp + #seglinerenderer.h shader.cpp shader.h - shattersystem.cpp - shattersystem.h - snappts.cpp - snapPts.h + #shattersystem.cpp + #shattersystem.h + #snappts.cpp + #snapPts.h sortingrenderer.cpp sortingrenderer.h - soundrobj.cpp - soundrobj.h - sphereobj.cpp - sphereobj.h - static_sort_list.cpp - static_sort_list.h - statistics.cpp - statistics.h - streak.cpp - streak.h - streakRender.cpp - streakRender.h - stripoptimizer.cpp - stripoptimizer.h - surfaceclass.cpp - surfaceclass.h + #soundlibrarybridge.h + #soundrobj.cpp + #soundrobj.h + #sphereobj.cpp + #sphereobj.h + #static_sort_list.cpp + #static_sort_list.h + #statistics.cpp + #statistics.h + #streak.cpp + #streak.h + #streakRender.cpp + #streakRender.h + #stripoptimizer.cpp + #stripoptimizer.h + #surfaceclass.cpp + #surfaceclass.h texproject.cpp texproject.h #textdraw.cpp - textdraw.h + #textdraw.h texture.cpp texture.h texturefilter.cpp @@ -207,38 +209,31 @@ set(WW3D2_SRC texturethumbnail.h vertmaterial.cpp vertmaterial.h - visrasterizer.cpp - visrasterizer.h - w3d_dep.cpp - w3d_dep.h + #visrasterizer.cpp + #visrasterizer.h + #w3d_dep.cpp + #w3d_dep.h w3d_file.h - w3d_obsolete.h - w3d_util.cpp - w3d_util.h - w3derr.h - w3dexclusionlist.cpp - w3dexclusionlist.h + #w3d_obsolete.h + #w3d_util.cpp + #w3d_util.h + #w3derr.h + #w3dexclusionlist.cpp + #w3dexclusionlist.h ww3d.cpp ww3d.h - ww3dformat.cpp - ww3dformat.h - ww3dids.h - ww3dtrig.h + #ww3dformat.cpp + #ww3dformat.h + #ww3dids.h + #ww3dtrig.h ) -# Targets to build. add_library(g_ww3d2 STATIC) set_target_properties(g_ww3d2 PROPERTIES OUTPUT_NAME ww3d2) target_sources(g_ww3d2 PRIVATE ${WW3D2_SRC}) -if (NOT IS_VS6_BUILD) - target_link_libraries(g_ww3d2 PUBLIC - comsuppw - ) -endif() - target_link_libraries(g_ww3d2 PRIVATE - core_browserengine + corei_ww3d2 g_wwcommon ) diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp deleted file mode 100644 index 89f0aeeb2e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/FramGrab.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FramGrab.cpp: implementation of the FrameGrabClass class. -// -////////////////////////////////////////////////////////////////////// - -#include "framgrab.h" -#include -#include -//#include - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -FrameGrabClass::FrameGrabClass(const char *filename, MODE mode, int width, int height, int bitcount, float framerate) -{ - HRESULT hr; - - Mode = mode; - Filename = filename; - FrameRate = framerate; - Counter = 0; - - Stream = 0; - AVIFile = 0; - - if(Mode != AVI) return; - - AVIFileInit(); // opens AVIFile library - - // find the first free file with this prefix - int counter = 0; - int result; - char file[256]; - do { - sprintf(file, "%s%d.AVI", filename, counter++); - result = _access(file, 0); - } while(result != -1); - - // Create new AVI file using AVIFileOpen. - hr = AVIFileOpen(&AVIFile, file, OF_WRITE | OF_CREATE, NULL); - if (hr != 0) { - char buf[256]; - sprintf(buf, "Unable to open %s\n", Filename); - OutputDebugString(buf); - CleanupAVI(); - return; - } - - - // Create a stream using AVIFileCreateStream. - AVIStreamInfo.fccType = streamtypeVIDEO; - AVIStreamInfo.fccHandler = mmioFOURCC('M','S','V','C'); - AVIStreamInfo.dwFlags = 0; - AVIStreamInfo.dwCaps = 0; - AVIStreamInfo.wPriority = 0; - AVIStreamInfo.wLanguage = 0; - AVIStreamInfo.dwScale = 1; - AVIStreamInfo.dwRate = (int)FrameRate; - AVIStreamInfo.dwStart = 0; - AVIStreamInfo.dwLength = 0; - AVIStreamInfo.dwInitialFrames = 0; - AVIStreamInfo.dwSuggestedBufferSize = 0; - AVIStreamInfo.dwQuality = 0; - AVIStreamInfo.dwSampleSize = 0; - SetRect(&AVIStreamInfo.rcFrame, 0, 0, width, height); - AVIStreamInfo.dwEditCount = 0; - AVIStreamInfo.dwFormatChangeCount = 0; - sprintf(AVIStreamInfo.szName,"G"); - - hr = AVIFileCreateStream(AVIFile, &Stream, &AVIStreamInfo); - if (hr != 0) { - CleanupAVI(); - return; - } - - // Set format of new stream - BitmapInfoHeader.biWidth = width; - BitmapInfoHeader.biHeight = height; - BitmapInfoHeader.biBitCount = (unsigned short)bitcount; - BitmapInfoHeader.biSizeImage = ((((UINT)BitmapInfoHeader.biBitCount * BitmapInfoHeader.biWidth + 31) & ~31) / 8) * BitmapInfoHeader.biHeight; - BitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER); // size of structure - BitmapInfoHeader.biPlanes = 1; // must be set to 1 - BitmapInfoHeader.biCompression = BI_RGB; // uncompressed - BitmapInfoHeader.biXPelsPerMeter = 1; // not used - BitmapInfoHeader.biYPelsPerMeter = 1; // not used - BitmapInfoHeader.biClrUsed = 0; // all colors are used - BitmapInfoHeader.biClrImportant = 0; // all colors are important - - hr = AVIStreamSetFormat(Stream, 0, &BitmapInfoHeader, sizeof(BitmapInfoHeader)); - if (hr != 0) { - CleanupAVI(); - return; - } - - Bitmap = (long *) GlobalAllocPtr(GMEM_MOVEABLE, BitmapInfoHeader.biSizeImage); -} - -FrameGrabClass::~FrameGrabClass() -{ - if(Mode == AVI) { - CleanupAVI(); - } -} - -void FrameGrabClass::CleanupAVI() { - if(Bitmap != 0) { GlobalFreePtr(Bitmap); Bitmap = 0; } - if(Stream != 0) { AVIStreamRelease(Stream); Stream = 0; } - if(AVIFile != 0) { AVIFileRelease(AVIFile); AVIFile = 0; } - - AVIFileExit(); - Mode = RAW; -} - -void FrameGrabClass::GrabAVI(void *BitmapPointer) -{ - // CompressDIB(&bi, lpOld, &biNew, lpNew); - - // Save the compressed data using AVIStreamWrite. - HRESULT hr = AVIStreamWrite(Stream, Counter++, 1, BitmapPointer, BitmapInfoHeader.biSizeImage, AVIIF_KEYFRAME, NULL, NULL); - if(hr != 0) { - char buf[256]; - sprintf(buf, "avi write error %x/%d\n", hr, hr); - OutputDebugString(buf); - } -} - -void FrameGrabClass::GrabRawFrame(void * /*BitmapPointer*/) -{ - -} - - -void FrameGrabClass::ConvertGrab(void *BitmapPointer) -{ - ConvertFrame(BitmapPointer); - Grab( Bitmap ); -} - - -void FrameGrabClass::Grab(void *BitmapPointer) -{ - if(Mode == AVI) - GrabAVI(BitmapPointer); - else - GrabRawFrame(BitmapPointer); -} - - -void FrameGrabClass::ConvertFrame(void *BitmapPointer) -{ - - int width = BitmapInfoHeader.biWidth; - int height = BitmapInfoHeader.biHeight; - long *image = (long *) BitmapPointer; - - // copy the data, doing a vertical flip & byte re-ordering of the pixel longwords - int y = height; - while(y--) { - int x = width; - int yoffset = y * width; - int yoffset2 = (height - y) * width; - while(x--) { - long *source = &image[yoffset + x]; - long *dest = &Bitmap[yoffset2 + x]; - *dest = *source; - unsigned char *c = (unsigned char *) dest; - c[3] = c[0]; - c[0] = c[2]; - c[2] = c[3]; - c[3] = 0; - } - } -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/aabtree.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/aabtree.cpp deleted file mode 100644 index 23adbe4569..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/aabtree.cpp +++ /dev/null @@ -1,1236 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/aabtree.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/24/01 5:34p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * AABTreeClass::AABTreeClass -- Constructor * - * AABTreeClass::AABTreeClass -- Constructor * - * AABTreeClass::AABTreeClass -- copy constructor * - * AABTreeClass::~AABTreeClass -- Destructor * - * AABTreeClass::operator = -- assignment operator * - * AABTreeClass::Reset -- reset this tree, releases all allocated resources * - * AABTreeClass::Build_Tree_Recursive -- Initializes this tree from the given builder * - * AABTreeClass::Set_Mesh -- set the mesh pointer * - * AABTreeClass::Generate_APT -- Generate an active poly table for the mesh * - * AABTreeClass::Generate_OBBox_APT_Recursive -- recursively generate the apt * - * AABTreeClass::Cast_Ray_Recursive -- Internal implementation of Cast_Ray * - * AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive -- Internal implementation * - * AABTreeClass::Cast_AABox_Recursive -- internal implementation of Cast_AABox * - * AABTreeClass::Cast_OBBox_Recursive -- Internal implementation of Cast_OBBox * - * AABTreeClass::Intersect_OBBox_Recursive -- internal implementation of Intersect_OBBox * - * AABTreeClass::Cast_Ray_To_Polys -- cast the ray to polys in the given node * - * AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray_To_Polys -- cast ray to polys in the nod* - * AABTreeClass::Cast_AABox_To_Polys -- cast aabox to polys in the given node * - * AABTreeClass::Cast_OBBox_To_Polys -- cast obbox to polys in the given node * - * AABTreeClass::Intersect_OBBox_With_Polys -- Test polys for intersection * - * AABTreeClass::Update_Bounding_Boxes_Recursive -- recompute the bounding boxes * - * AABTreeClass::Update_Min_Max -- updates min and max given a polygon index * - * AABTreeClass::Load_W3D -- Load a W3D description of an AABTree * - * AABTreeClass::Read_Poly_Indices -- load the polygon index array * - * AABTreeClass::Read_Nodes -- Load the node array * - * AABTreeClass::Generate_APT -- generate an apt from a box and viewdir * - * AABTreeClass::Generate_OBBox_APT_Recursive -- recurse, generate the apt for a box and vie * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "aabtree.h" -#include "aabtreebuilder.h" -#include "wwdebug.h" -#include "tri.h" -#include "meshgeometry.h" -#include "coltest.h" -#include "inttest.h" -#include "colmathinlines.h" -#include "w3d_file.h" -#include "chunkio.h" - - - -/*********************************************************************************************** - * AABTreeClass::AABTreeClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -AABTreeClass::AABTreeClass(void) : - NodeCount(0), - Nodes(NULL), - PolyCount(0), - PolyIndices(NULL), - Mesh(NULL) -{ -} - -/*********************************************************************************************** - * AABTreeClass::AABTreeClass -- Constructor * - * * - * Builds an AABTree from the contents of an AABTreeBuilderClass. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - * 5/23/2000 gth : Created. * - *=============================================================================================*/ -AABTreeClass::AABTreeClass(AABTreeBuilderClass * builder) -{ - NodeCount = builder->Node_Count(); - Nodes = W3DNEWARRAY AABTreeClass::CullNodeStruct[NodeCount]; - - PolyCount = builder->Poly_Count(); - PolyIndices = W3DNEWARRAY uint32[PolyCount]; - - int curpolyindex = 0; - Build_Tree_Recursive(builder->Root,curpolyindex); -} - - -/*********************************************************************************************** - * AABTreeClass::AABTreeClass -- copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/99 GTH : Created. * - *=============================================================================================*/ -AABTreeClass::AABTreeClass(const AABTreeClass & that) : - NodeCount(0), - Nodes(NULL), - PolyCount(0), - PolyIndices(0), - Mesh(NULL) -{ - *this = that; -} - -/*********************************************************************************************** - * AABTreeClass::~AABTreeClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -AABTreeClass::~AABTreeClass(void) -{ - Reset(); -} - -/*********************************************************************************************** - * AABTreeClass::operator = -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/99 GTH : Created. * - *=============================================================================================*/ -AABTreeClass & AABTreeClass::operator = (const AABTreeClass & that) -{ - Reset(); - - NodeCount = that.NodeCount; - if (NodeCount > 0) { - Nodes = W3DNEWARRAY CullNodeStruct[NodeCount]; - memcpy(Nodes,that.Nodes,NodeCount * sizeof(CullNodeStruct)); - } - - PolyCount = that.PolyCount; - if (PolyCount > 0) { - PolyIndices = W3DNEWARRAY uint32[PolyCount]; - memcpy(PolyIndices,that.PolyIndices,PolyCount * sizeof(uint32)); - } - - Mesh = that.Mesh; - - return *this; -} - - -/*********************************************************************************************** - * AABTreeClass::Reset -- reset this tree, releases all allocated resources * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/99 GTH : Created. * - *=============================================================================================*/ -void AABTreeClass::Reset(void) -{ - NodeCount = 0; - if (Nodes) { - delete[] Nodes; - Nodes = NULL; - } - PolyCount = 0; - if (PolyIndices) { - delete[] PolyIndices; - PolyIndices = NULL; - } - if (Mesh) { - Mesh = NULL; - } -} - -/*********************************************************************************************** - * AABTreeClass::Scale - uniform scale * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/17/02 Jani : Created. * - *=============================================================================================*/ -void AABTreeClass::Scale(float f) -{ - for (int i=0;iIndex]); - - newnode->Min = node->Min; - newnode->Max = node->Max; - - /* - ** If this is a non-leaf node, set up the child indices, otherwise set up the polygon indices - */ - if (node->Front != NULL) { - - WWASSERT(node->Back != NULL); // if we have one child, we better have both! - newnode->Set_Front_Child(node->Front->Index); - newnode->Set_Back_Child(node->Back->Index); - - } else { - - newnode->Set_Poly0(curpolyindex); - newnode->Set_Poly_Count(node->PolyCount); - - } - - /* - ** Copy the polygon indices for this node into our array - */ - for (int pcounter = 0; pcounter < node->PolyCount; pcounter++) { - PolyIndices[curpolyindex++] = node->PolyIndices[pcounter]; - } - - /* - ** Install the children - */ - if (node->Front) { - Build_Tree_Recursive(node->Front,curpolyindex); - } - if (node->Back) { - Build_Tree_Recursive(node->Back,curpolyindex); - } -} - - -/*********************************************************************************************** - * AABTreeClass::Set_Mesh -- set the mesh pointer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/99 GTH : Created. * - *=============================================================================================*/ -void AABTreeClass::Set_Mesh(MeshGeometryClass * mesh) -{ - Mesh = mesh; -} - - -/*********************************************************************************************** - * AABTreeClass::Generate_APT -- Generate an active poly table for the mesh * - * * - * INPUT: * - * box - oriented box to cull the mesh against (in the mesh's coordinate system!!!) * - * apt - vector of ints to fill the apt into * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void AABTreeClass::Generate_APT(const OBBoxClass & box,SimpleDynVecClass & apt) -{ - OBBoxAPTContextStruct context(box,apt); - Generate_OBBox_APT_Recursive(&(Nodes[0]),context); -} - - - -/*********************************************************************************************** - * AABTreeClass::Generate_OBBox_APT_Recursive -- recursively generate the apt * - * * - * INPUT: * - * node - current node in the recursion * - * context - structure containing the results/current state * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/25/00 gth : Created. * - *=============================================================================================*/ -void AABTreeClass::Generate_OBBox_APT_Recursive(CullNodeStruct * node,OBBoxAPTContextStruct & context) -{ - /* - ** Test the volume against the bounding volume of this node - ** If it is outside, stop descending the tree. - */ - AABoxClass nodebox; - nodebox.Init_Min_Max(node->Min,node->Max); // NOTE: too bad we have to compute the nodebox!!! - - if (!CollisionMath::Intersection_Test(context.Box,nodebox)) { - return; - } - - /* - ** If this is a leaf, test its polygons, otherwise recurse into the children - */ - if (node->Is_Leaf()) { - - int polycount = node->Get_Poly_Count(); - int poly0 = node->Get_Poly0(); - - if (polycount > 0) { - TriClass tri; - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polys = Mesh->Get_Polygon_Array(); -#if (!OPTIMIZE_PLANEEQ_RAM) - const Vector4 * norms = Mesh->Get_Plane_Array(); -#endif - for (int poly_counter=0; poly_counterGet_Front_Child()]),context); - Generate_OBBox_APT_Recursive(&(Nodes[node->Get_Back_Child()]),context); - } -} - - -/*********************************************************************************************** - * AABTreeClass::Generate_APT -- generate an apt from a box and viewdir * - * * - * Indices of the polys which intersect the box and are not backfacing to the given viewdir * - * will be added to the passed in apt. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/10/2001 gth : Created. * - *=============================================================================================*/ -void AABTreeClass::Generate_APT -( - const OBBoxClass & box, - const Vector3 & viewdir, - SimpleDynVecClass & apt -) -{ - OBBoxRayAPTContextStruct context(box,viewdir,apt); - Generate_OBBox_APT_Recursive(&(Nodes[0]),context); -} - - -/*********************************************************************************************** - * AABTreeClass::Generate_OBBox_APT_Recursive -- recurse, generate the apt for a box and viewd * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/10/2001 gth : Created. * - *=============================================================================================*/ -void AABTreeClass::Generate_OBBox_APT_Recursive(CullNodeStruct * node, OBBoxRayAPTContextStruct & context) -{ - /* - ** Test the volume against the bounding volume of this node - ** If it is outside, stop descending the tree. - */ - AABoxClass nodebox; - nodebox.Init_Min_Max(node->Min,node->Max); // NOTE: too bad we have to compute the nodebox!!! - - if (!CollisionMath::Intersection_Test(context.Box,nodebox)) { - return; - } - - /* - ** If this is a leaf, test its polygons, otherwise recurse into the children - */ - if (node->Is_Leaf()) { - - int polycount = node->Get_Poly_Count(); - int poly0 = node->Get_Poly0(); - - if (polycount > 0) { - TriClass tri; - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polys = Mesh->Get_Polygon_Array(); -#if (!OPTIMIZE_PLANEEQ_RAM) - const Vector4 * norms = Mesh->Get_Plane_Array(); -#endif - - for (int poly_counter=0; poly_counterGet_Front_Child()]),context); - Generate_OBBox_APT_Recursive(&(Nodes[node->Get_Back_Child()]),context); - } -} - - -/*********************************************************************************************** - * AABTreeClass::Cast_Ray_Recursive -- Internal implementation of Cast_Ray * - * * - * INPUT: * - * raytest - contains all of the ray test information * - * node - current cull node being processed * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -bool AABTreeClass::Cast_Ray_Recursive(CullNodeStruct * node,RayCollisionTestClass & raytest) -{ - /* - ** Cull the collision test against the bounding volume of this node - ** If it is culled, stop descending the tree. - */ - if (raytest.Cull(node->Min,node->Max)) { - return false; - } - - bool res = false; - if (node->Is_Leaf()) { - - return Cast_Ray_To_Polys(node,raytest); - - } else { - - res = res | Cast_Ray_Recursive(&(Nodes[node->Get_Front_Child()]),raytest); - res = res | Cast_Ray_Recursive(&(Nodes[node->Get_Back_Child()]),raytest); - - } - - return res; -} - - -/*********************************************************************************************** - * AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive -- Internal implementation * - * * - * INPUT: * - * node - current cull node being processed * - * start_point - starting point * - * axis_r - the axis along which the ray is projected * - * axis_1, axis_2 - the other two axes * - * direction - 0 means the ray goes toward the negative axis, 1 means positive. * - * flags - reference bitfield for result flags (ray hit edge, start point embedded in tri, etc)* - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/30/00 NH : Created. * - *=============================================================================================*/ -int AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive(CullNodeStruct * node, - const Vector3 & start_point, int axis_r, int axis_1, int axis_2, int direction, - unsigned char & flags) -{ - /* - ** Cull the ray against the bounding volume of this node - ** If it is culled, stop descending the tree. - ** We do two main tests: a 2D test against axis1 and axis2 to see if the starting point (and - ** hence the ray) falls within the 2D projection of the bbox, and a 1D test to see if the ray - ** is completely above or below the bbox. The second test checks (start > max) or (start < min) - ** depending on the direction of the ray - we do this in a branchless fashion by turning - ** (start < min) into (-start > -min). Then we can use tables to perform the correct check. - */ - static const float sign[2] = { -1.0f, 1.0f }; - float bounds[2], start[2]; - bounds[0] = -node->Min[axis_r]; - bounds[1] = node->Max[axis_r]; - start[0] = -start_point[axis_r]; - start[1] = start_point[axis_r]; - if ( start_point[axis_1] < node->Min[axis_1] || start_point[axis_2] < node->Min[axis_2] || - start_point[axis_1] > node->Max[axis_1] || start_point[axis_2] > node->Max[axis_2] || - start[direction] > bounds[direction] ) { - return 0; - } - - int count = 0; - if (node->Is_Leaf()) { - - return Cast_Semi_Infinite_Axis_Aligned_Ray_To_Polys(node, start_point, axis_r, axis_1, - axis_2, direction, flags); - - } else { - - count += Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive(&(Nodes[node->Get_Front_Child()]), - start_point, axis_r, axis_1, axis_2, direction, flags); - count += Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive(&(Nodes[node->Get_Back_Child()]), - start_point, axis_r, axis_1, axis_2, direction, flags); - - } - - return count; -} - - -/*********************************************************************************************** - * AABTreeClass::Cast_AABox_Recursive -- internal implementation of Cast_AABox * - * * - * INPUT: * - * boxtest - contains description of the collision operation to be performed * - * node - current cull node being processed * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -bool AABTreeClass::Cast_AABox_Recursive(CullNodeStruct * node,AABoxCollisionTestClass & boxtest) -{ - /* - ** First, check the bounding box of the move against the bounding box - ** of this tree, if they don't intersect, bail out - */ - if (boxtest.Cull(node->Min,node->Max)) { - return false; - } - - bool res = false; - if (node->Is_Leaf()) { - - return Cast_AABox_To_Polys(node,boxtest); - - } else { - - res = res | Cast_AABox_Recursive(&(Nodes[node->Get_Front_Child()]),boxtest); - res = res | Cast_AABox_Recursive(&(Nodes[node->Get_Back_Child()]),boxtest); - - } - - return res; -} - - -/*********************************************************************************************** - * AABTreeClass::Cast_OBBox_Recursive -- Internal implementation of Cast_OBBox * - * * - * INPUT: * - * boxtest - contains description of the collision test to be performed * - * node - current cull node being processed * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -bool AABTreeClass::Cast_OBBox_Recursive(CullNodeStruct * node,OBBoxCollisionTestClass & boxtest) -{ - /* - ** First, check the bounding box of the move against the bounding box - ** of this tree, if they don't intersect, bail out - */ - if (boxtest.Cull(node->Min,node->Max)) { - return false; - } - - bool res = false; - if (node->Is_Leaf()) { - - return Cast_OBBox_To_Polys(node,boxtest); - - } else { - - res = res | Cast_OBBox_Recursive(&(Nodes[node->Get_Front_Child()]),boxtest); - res = res | Cast_OBBox_Recursive(&(Nodes[node->Get_Back_Child()]),boxtest); - - } - - return res; -} - - -/*********************************************************************************************** - * AABTreeClass::Intersect_OBBox_Recursive -- internal implementation of Intersect_OBBox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/20/00 gth : Created. * - *=============================================================================================*/ -bool AABTreeClass::Intersect_OBBox_Recursive(AABTreeClass::CullNodeStruct * node,OBBoxIntersectionTestClass & test) -{ - /* - ** Cull the collision test against the bounding volume of this node - ** If it is culled, stop descending the tree. - */ - if (test.Cull(node->Min,node->Max)) { - return false; - } - - bool res = false; - if (node->Is_Leaf()) { - - return Intersect_OBBox_With_Polys(node,test); - - } else { - - res = res | Intersect_OBBox_Recursive(&(Nodes[node->Get_Front_Child()]),test); - res = res | Intersect_OBBox_Recursive(&(Nodes[node->Get_Back_Child()]),test); - } - - return res; -} - -#ifdef _DEBUG -#pragma optimize("", off) // We get an odd error when using optimized in the debug. -// All optimized seems to work. jba. -#endif -/*********************************************************************************************** - * AABTreeClass::Cast_Ray_To_Polys -- cast the ray to polys in the given node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -bool AABTreeClass::Cast_Ray_To_Polys(CullNodeStruct * node,RayCollisionTestClass & raytest) -{ - if (node->Get_Poly_Count() > 0) { - /* - ** Simply loop through the polys in this node, checking each for collision - */ - TriClass tri; - - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polyverts = Mesh->Get_Polygon_Array(); -#if (!OPTIMIZE_PLANEEQ_RAM) - const Vector4 * norms = Mesh->Get_Plane_Array(); -#endif - - int polyhit = -1; - int poly0 = node->Get_Poly0(); - int polycount = node->Get_Poly_Count(); - - for (int poly_counter=0; poly_counterStartBad) { - return true; - } - } - if (polyhit != -1) { - raytest.Result->SurfaceType = Mesh->Get_Poly_Surface_Type (polyhit); - return true; - } - } - return false; -} -#ifdef _DEBUG -#pragma optimize("", on) -#endif - - -/*********************************************************************************************** - * AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray_To_Polys -- cast ray to polys in the node * - * * - * INPUT: * - * node - current cull node being processed * - * start_point - starting point * - * axis_r - the axis along which the ray is projected * - * axis_1, axis_2 - the other two axes * - * direction - 0 means the ray goes toward the negative axis, 1 means positive. * - * flags - reference bitfield for result flags (ray hit edge, start point embedded in tri, etc)* - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/30/00 NH : Created. * - *=============================================================================================*/ -int AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray_To_Polys(CullNodeStruct * node, - const Vector3 & start_point, int axis_r, int axis_1, int axis_2, int direction, - unsigned char & flags) -{ - int count = 0; - - if (node->Get_Poly_Count() > 0) { - - /* - ** Simply loop through the polys in this node, checking each for collision - */ - - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polyverts = Mesh->Get_Polygon_Array(); - const Vector4 * plane = Mesh->Get_Plane_Array(); - int poly0 = node->Get_Poly0(); - int polycount = node->Get_Poly_Count(); - - for (int poly_counter=0; poly_counter < polycount; poly_counter++) { - - int poly_index = PolyIndices[poly0 + poly_counter]; - - const Vector3 &v0 = loc[ polyverts[poly_index][0] ]; - const Vector3 &v1 = loc[ polyverts[poly_index][1] ]; - const Vector3 &v2 = loc[ polyverts[poly_index][2] ]; - const Vector4 &tri_plane = plane[poly_index]; - - // Since (int)true is defined as 1, and (int)false as 0: - count += (unsigned int)Cast_Semi_Infinite_Axis_Aligned_Ray_To_Triangle(v0, v1, v2, - tri_plane, start_point, axis_r, axis_1, axis_2, direction, flags); - } - } - - return count; -} - - -/*********************************************************************************************** - * AABTreeClass::Cast_AABox_To_Polys -- cast aabox to polys in the given node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -bool AABTreeClass::Cast_AABox_To_Polys(CullNodeStruct * node,AABoxCollisionTestClass & boxtest) -{ - if (node->Get_Poly_Count() > 0) { - /* - ** Simply loop through the polys in this node, checking each for collision - */ - TriClass tri; - - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polyverts = Mesh->Get_Polygon_Array(); -#if (!OPTIMIZE_PLANEEQ_RAM) - const Vector4 * norms = Mesh->Get_Plane_Array(); -#endif - - int polyhit = -1; - int poly0 = node->Get_Poly0(); - int polycount = node->Get_Poly_Count(); - - for (int poly_counter=0; poly_counterStartBad) { - return true; - } - } - if (polyhit != -1) { - boxtest.Result->SurfaceType = Mesh->Get_Poly_Surface_Type (polyhit); - return true; - } - } - return false; -} - - -/*********************************************************************************************** - * AABTreeClass::Cast_OBBox_To_Polys -- cast obbox to polys in the given node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -bool AABTreeClass::Cast_OBBox_To_Polys(CullNodeStruct * node,OBBoxCollisionTestClass & boxtest) -{ - int polycount = node->Get_Poly_Count(); - int poly0 = node->Get_Poly0(); - - if (polycount > 0) { - /* - ** Simply loop through the polys in this node, checking each for collision - */ - TriClass tri; - - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polyverts = Mesh->Get_Polygon_Array(); -#if (!OPTIMIZE_PLANEEQ_RAM) - const Vector4 * norms = Mesh->Get_Plane_Array(); -#endif - - int polyhit = -1; - - for (int poly_counter=0; poly_counterStartBad) { - return true; - } - } - if (polyhit != -1) { - boxtest.Result->SurfaceType = Mesh->Get_Poly_Surface_Type (polyhit); - return true; - } - } - return false; - -} - - -/*********************************************************************************************** - * AABTreeClass::Intersect_OBBox_With_Polys -- Test polys for intersection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/20/00 gth : Created. * - *=============================================================================================*/ -bool AABTreeClass::Intersect_OBBox_With_Polys -( - CullNodeStruct * node, - OBBoxIntersectionTestClass & test -) -{ - int poly0 = node->Get_Poly0(); - int polycount = node->Get_Poly_Count(); - - if (polycount > 0) { - /* - ** Simply loop through the polys in this node, checking each for collision - */ - TriClass tri; - - const Vector3 * loc = Mesh->Get_Vertex_Array(); - const TriIndex * polyverts = Mesh->Get_Polygon_Array(); -#if (!OPTIMIZE_PLANEEQ_RAM) - const Vector4 * norms = Mesh->Get_Plane_Array(); -#endif - - for (int poly_counter=0; poly_counterMin.Set(100000.0f,100000.0f,100000.0f); - node->Max.Set(-100000.0f,-100000.0f,-100000.0f); - - /* - ** Recurse to the children first - */ - if (node->Is_Leaf() == false) { - - Update_Bounding_Boxes_Recursive(&(Nodes[node->Get_Front_Child()])); - Update_Bounding_Boxes_Recursive(&(Nodes[node->Get_Back_Child()])); - - /* - ** Bound our children - */ - int front = node->Get_Front_Child(); - int back = node->Get_Back_Child(); - - if (Nodes[front].Min.X < node->Min.X) node->Min.X = Nodes[front].Min.X; - if (Nodes[front].Max.X > node->Max.X) node->Max.X = Nodes[front].Max.X; - - if (Nodes[front].Min.Y < node->Min.Y) node->Min.Y = Nodes[front].Min.Y; - if (Nodes[front].Max.Y > node->Max.Y) node->Max.Y = Nodes[front].Max.Y; - - if (Nodes[front].Min.Z < node->Min.Z) node->Min.Z = Nodes[front].Min.Z; - if (Nodes[front].Max.Z > node->Max.Z) node->Max.Z = Nodes[front].Max.Z; - - if (Nodes[back].Min.X < node->Min.X) node->Min.X = Nodes[back].Min.X; - if (Nodes[back].Max.X > node->Max.X) node->Max.X = Nodes[back].Max.X; - - if (Nodes[back].Min.Y < node->Min.Y) node->Min.Y = Nodes[back].Min.Y; - if (Nodes[back].Max.Y > node->Max.Y) node->Max.Y = Nodes[back].Max.Y; - - if (Nodes[back].Min.Z < node->Min.Z) node->Min.Z = Nodes[back].Min.Z; - if (Nodes[back].Max.Z > node->Max.Z) node->Max.Z = Nodes[back].Max.Z; - - } else { - - /* - ** Bound our polygons - */ - int poly0 = node->Get_Poly0(); - int polycount = node->Get_Poly_Count(); - - for (int poly_index = 0; poly_index < polycount; poly_index++) { - int pi = PolyIndices[poly0 + poly_index]; - Update_Min_Max(pi,node->Min,node->Max ); - } - - } - - WWASSERT(node->Min.X != 100000.0f); - WWASSERT(node->Min.Y != 100000.0f); - WWASSERT(node->Min.Z != 100000.0f); - WWASSERT(node->Max.X != -100000.0f); - WWASSERT(node->Max.Y != -100000.0f); - WWASSERT(node->Max.Z != -100000.0f); -} - - -/*********************************************************************************************** - * AABTreeClass::Update_Min_Max -- updates min and max given a polygon index * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/99 GTH : Created. * - *=============================================================================================*/ -void AABTreeClass::Update_Min_Max(int poly_index,Vector3 & min,Vector3 & max) -{ - for (int vert_index = 0; vert_index < 3; vert_index++) { - - const TriIndex * polyverts = Mesh->Get_Polygon_Array() + poly_index; - const Vector3 * point = Mesh->Get_Vertex_Array() + (*polyverts)[vert_index]; - - if (point->X < min.X) min.X = point->X; - if (point->Y < min.Y) min.Y = point->Y; - if (point->Z < min.Z) min.Z = point->Z; - - if (point->X > max.X) max.X = point->X; - if (point->Y > max.Y) max.Y = point->Y; - if (point->Z > max.Z) max.Z = point->Z; - } -} - - -/*********************************************************************************************** - * AABTreeClass::Load_W3D -- Load a W3D description of an AABTree * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/22/2000 gth : Created. * - *=============================================================================================*/ -void AABTreeClass::Load_W3D(ChunkLoadClass & cload) -{ - Reset(); - - W3dMeshAABTreeHeader header; - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == W3D_CHUNK_AABTREE_HEADER); - cload.Read(&header,sizeof(header)); - cload.Close_Chunk(); - - NodeCount = header.NodeCount; - PolyCount = header.PolyCount; - Nodes = W3DNEWARRAY CullNodeStruct[NodeCount]; - PolyIndices = W3DNEWARRAY uint32[PolyCount]; - - while (cload.Open_Chunk()) { - switch (cload.Cur_Chunk_ID()) - { - case W3D_CHUNK_AABTREE_POLYINDICES: - Read_Poly_Indices(cload); - break; - - case W3D_CHUNK_AABTREE_NODES: - Read_Nodes(cload); - break; - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * AABTreeClass::Read_Poly_Indices -- load the polygon index array * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/22/2000 gth : Created. * - *=============================================================================================*/ -void AABTreeClass::Read_Poly_Indices(ChunkLoadClass & cload) -{ - cload.Read(PolyIndices,sizeof(uint32) * PolyCount); -} - - -/*********************************************************************************************** - * AABTreeClass::Read_Nodes -- Load the node array * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/22/2000 gth : Created. * - *=============================================================================================*/ -void AABTreeClass::Read_Nodes(ChunkLoadClass & cload) -{ - W3dMeshAABTreeNode w3dnode; - - for (int i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/aabtree.h $* - * * - * Org Author:: Greg Hjelstrom * - * * - * Author:: Kenny Mitchell * - * * - * $Modtime:: 6/26/02 2:58p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * 06/26/02 KM Integrating shader system - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AABTREE_H -#define AABTREE_H - -#include "always.h" -#include "refcount.h" -#include "simplevec.h" -#include "vector3.h" -#include "Vector3i.h" -#include "aaplane.h" -#include "bittype.h" -#include "colmath.h" -#include "wwdebug.h" -#include "aabtreebuilder.h" -#include "obbox.h" -#include -#include - - -class MeshClass; -class CameraClass; -class RayCollisionTestClass; -class AABoxCollisionTestClass; -class OBBoxCollisionTestClass; -class OBBoxIntersectionTestClass; -class ChunkLoadClass; -class ChunkSaveClass; -class MeshGeometryClass; -class OBBoxClass; -class ChunkLoadClass; - -struct BoxRayAPTContextStruct; - -#define AABTREE_LEAF_FLAG 0x80000000 - - -/* -** AABTreeClass -** This class encapsulates an Axis-Aligned Bounding Box Tree for a mesh. This tree -** can be used to perform hierarchical culling for collision detection. Note that -** this class is constructed using the AABTreeBuilderClass; these two classes are -** very tightly coupled. Pretty much the only code which needs to know about the AABTreeClass -** is in MeshGeometryClass. I moved these out into a separate file just to reduce the -** size of meshmdl.cpp. -*/ -class AABTreeClass : public W3DMPO, public RefCountClass -{ - W3DMPO_GLUE(AABTreeClass) -public: - - AABTreeClass(void); - AABTreeClass(AABTreeBuilderClass * builder); - AABTreeClass(const AABTreeClass & that); - ~AABTreeClass(void); - - void Load_W3D(ChunkLoadClass & cload); - - // Uniformly scale the AABTree - void Scale(float scale); - - int Get_Node_Count(void) { return NodeCount; } - int Get_Poly_Count(void) { return PolyCount; } - int Compute_Ram_Size(void); - void Generate_APT(const OBBoxClass & box,SimpleDynVecClass & apt); - void Generate_APT(const OBBoxClass & box,const Vector3 & viewdir,SimpleDynVecClass & apt); - - bool Cast_Ray(RayCollisionTestClass & raytest); - int Cast_Semi_Infinite_Axis_Aligned_Ray(const Vector3 & start_point, - int axis_dir, unsigned char & flags); - bool Cast_AABox(AABoxCollisionTestClass & boxtest); - bool Cast_OBBox(OBBoxCollisionTestClass & boxtest); - bool Intersect_OBBox(OBBoxIntersectionTestClass & boxtest); - - void Set_Mesh(MeshGeometryClass * mesh); - -private: - - AABTreeClass & operator = (const AABTreeClass & that); - - void Read_Poly_Indices(ChunkLoadClass & cload); - void Read_Nodes(ChunkLoadClass & cload); - - void Build_Tree_Recursive(AABTreeBuilderClass::CullNodeStruct * node,int &curpolyindex); - void Reset(void); - void Update_Bounding_Boxes(void); - void Update_Min_Max(int index,Vector3 & min,Vector3 & max); - - /* - ** CullNodeStruct - the culling tree is built out of an array of these structures - ** They contain the extents of an axis-aligned box, indices to children nodes, - ** and indices into the polygon array - ** (05/22/2000 gth - changed this structure to support either child nodes -or- - ** a polygon array but not both at the same time. Also switched to 32bit indices - ** so that the code doesn't become useless as quickly ) - */ - struct CullNodeStruct - { - Vector3 Min; - Vector3 Max; - - uint32 FrontOrPoly0; - uint32 BackOrPolyCount; - - // accessors - inline bool Is_Leaf(void); - - inline int Get_Back_Child(void); // returns index of back child (only call for non-LEAFs!!!) - inline int Get_Front_Child(void); // returns index of front child (only call for non-LEAFs!!!) - inline int Get_Poly0(void); // returns index of first polygon (only call on LEAFs) - inline int Get_Poly_Count(void); // returns polygon count (only call on LEAFs) - - // initialization - inline void Set_Front_Child(uint32 index); - inline void Set_Back_Child(uint32 index); - inline void Set_Poly0(uint32 index); - inline void Set_Poly_Count(uint32 count); - }; - - /* - ** OBBoxAPTContextStruct - this is a temporary datastructure used in building - ** an APT by culling the mesh to an oriented bounding box. - */ - struct OBBoxAPTContextStruct - { - OBBoxAPTContextStruct(const OBBoxClass & box,SimpleDynVecClass & apt) : - Box(box), APT(apt) - { } - - OBBoxClass Box; - SimpleDynVecClass & APT; - }; - - /** - ** OBBoxRayAPTContextStruct - temporary datastructure used in building an APT - ** by culling the mesh to a oriented box and eliminating backfaces to a ray. - */ - struct OBBoxRayAPTContextStruct - { - OBBoxRayAPTContextStruct(const OBBoxClass & box,const Vector3 & viewdir,SimpleDynVecClass & apt) : - Box(box), - ViewVector(viewdir), - APT(apt) - { } - - OBBoxClass Box; - Vector3 ViewVector; - SimpleDynVecClass & APT; - }; - - void Generate_OBBox_APT_Recursive(CullNodeStruct * node,OBBoxAPTContextStruct & context); - void Generate_OBBox_APT_Recursive(CullNodeStruct * node, OBBoxRayAPTContextStruct & context); - - bool Cast_Ray_Recursive(CullNodeStruct * node,RayCollisionTestClass & raytest); - int Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive(CullNodeStruct * node, const Vector3 & start_point, - int axis_r, int axis_1, int axis_2, int direction, unsigned char & flags); - bool Cast_AABox_Recursive(CullNodeStruct * node,AABoxCollisionTestClass & boxtest); - bool Cast_OBBox_Recursive(CullNodeStruct * node,OBBoxCollisionTestClass & boxtest); - bool Intersect_OBBox_Recursive(CullNodeStruct * node,OBBoxIntersectionTestClass & boxtest); - - bool Cast_Ray_To_Polys(CullNodeStruct * node,RayCollisionTestClass & raytest); - int Cast_Semi_Infinite_Axis_Aligned_Ray_To_Polys(CullNodeStruct * node, const Vector3 & start_point, - int axis_r, int axis_1, int axis_2, int direction, unsigned char & flags); - bool Cast_AABox_To_Polys(CullNodeStruct * node,AABoxCollisionTestClass & boxtest); - bool Cast_OBBox_To_Polys(CullNodeStruct * node,OBBoxCollisionTestClass & boxtest); - bool Intersect_OBBox_With_Polys(CullNodeStruct * node,OBBoxIntersectionTestClass & boxtest); - - void Update_Bounding_Boxes_Recursive(CullNodeStruct * node); - - int NodeCount; // number of nodes in the tree - CullNodeStruct * Nodes; // array of nodes - int PolyCount; // number of polygons in the parent mesh (and the number of indexes in our array) - uint32 * PolyIndices; // linear array of polygon indices, nodes index into this array - MeshGeometryClass * Mesh; // pointer to the parent mesh (non-ref-counted; we are a member of this mesh) - - friend class MeshClass; - friend class MeshGeometryClass; - friend class AuxMeshDataClass; - friend class AABTreeBuilderClass; - -}; - -inline int AABTreeClass::Compute_Ram_Size(void) -{ - return NodeCount * sizeof(CullNodeStruct) + - PolyCount * sizeof(int) + - sizeof(AABTreeClass); -} - -inline bool AABTreeClass::Cast_Ray(RayCollisionTestClass & raytest) -{ - WWASSERT(Nodes != NULL); - return Cast_Ray_Recursive(&(Nodes[0]),raytest); -} - -inline int AABTreeClass::Cast_Semi_Infinite_Axis_Aligned_Ray(const Vector3 & start_point, - int axis_dir, unsigned char & flags) -{ - // These tables translate between the axis_dir representation (which is an integer in which 0 - // indicates a ray along the positive x axis, 1 along the negative x axis, 2 the positive y - // axis, 3 negative y axis, 4 positive z axis, 5 negative z axis) and a four-integer - // representation (axis_r is the axis number - 0, 1 or 2 - of the axis along which the ray is - // cast; axis_1 and axis_2 are the axis numbers of the other two axes; direction is 0 for - // negative and 1 for positive direction of the ray). - static const int axis_r[6] = { 0, 0, 1, 1, 2, 2 }; - static const int axis_1[6] = { 1, 1, 2, 2, 0, 0 }; - static const int axis_2[6] = { 2, 2, 0, 0, 1, 1 }; - static const int direction[6] = { 1, 0, 1, 0, 1, 0 }; - WWASSERT(Nodes != NULL); - WWASSERT(axis_dir >= 0); - WWASSERT(axis_dir < 6); - - // The functions called after this point will 'or' bits into this variable, so it needs to - // be initialized here to TRI_RAYCAST_FLAG_NONE. - flags = TRI_RAYCAST_FLAG_NONE; - - return Cast_Semi_Infinite_Axis_Aligned_Ray_Recursive(&(Nodes[0]), start_point, - axis_r[axis_dir], axis_1[axis_dir], axis_2[axis_dir], direction[axis_dir], flags); -} - -inline bool AABTreeClass::Cast_AABox(AABoxCollisionTestClass & boxtest) -{ - WWASSERT(Nodes != NULL); - return Cast_AABox_Recursive(&(Nodes[0]),boxtest); -} - -inline bool AABTreeClass::Cast_OBBox(OBBoxCollisionTestClass & boxtest) -{ - WWASSERT(Nodes != NULL); - return Cast_OBBox_Recursive(&(Nodes[0]),boxtest); -} - -inline bool AABTreeClass::Intersect_OBBox(OBBoxIntersectionTestClass & boxtest) -{ - WWASSERT(Nodes != NULL); - return Intersect_OBBox_Recursive(&(Nodes[0]),boxtest); -} - -inline void AABTreeClass::Update_Bounding_Boxes(void) -{ - WWASSERT(Nodes != NULL); - Update_Bounding_Boxes_Recursive(&(Nodes[0])); -} - - -/*********************************************************************************************** - - AABTreeClass::CullNodeStruct implementation - - These nodes can be either leaf nodes or non-leaf nodes. If they are leaf nodes, they - will contain an index to their first polygon index and a polygon count. If they are - non-leafs they will contain indices to their front and back children. Since I'm re-using - the same variables for the child indices and the polygon indices, you have to call - the Is_Leaf function then only call the appropriate functions. The flag indicating whether - this node is a leaf is stored in the MSB of the FrontOrPoly0 variable. It will always - be stripped off by these accessor functions - -***********************************************************************************************/ - -inline bool AABTreeClass::CullNodeStruct::Is_Leaf(void) -{ - return ((FrontOrPoly0 & AABTREE_LEAF_FLAG) != 0); -} - -inline int AABTreeClass::CullNodeStruct::Get_Front_Child(void) -{ - WWASSERT(!Is_Leaf()); - return FrontOrPoly0; // we shouldn't be calling this on a leaf and the leaf bit should be zero... -} - -inline int AABTreeClass::CullNodeStruct::Get_Back_Child(void) -{ - WWASSERT(!Is_Leaf()); - return BackOrPolyCount; -} - -inline int AABTreeClass::CullNodeStruct::Get_Poly0(void) -{ - WWASSERT(Is_Leaf()); - return (FrontOrPoly0 & ~AABTREE_LEAF_FLAG); -} - -inline int AABTreeClass::CullNodeStruct::Get_Poly_Count(void) -{ - WWASSERT(Is_Leaf()); - return BackOrPolyCount; -} - -inline void AABTreeClass::CullNodeStruct::Set_Front_Child(uint32 index) -{ - WWASSERT(index < 0x7FFFFFFF); - FrontOrPoly0 = index; -} - -inline void AABTreeClass::CullNodeStruct::Set_Back_Child(uint32 index) -{ - WWASSERT(index < 0x7FFFFFFF); - BackOrPolyCount = index; -} - -inline void AABTreeClass::CullNodeStruct::Set_Poly0(uint32 index) -{ - WWASSERT(index < 0x7FFFFFFF); - FrontOrPoly0 = (index | AABTREE_LEAF_FLAG); -} - -inline void AABTreeClass::CullNodeStruct::Set_Poly_Count(uint32 count) -{ - WWASSERT(count < 0x7FFFFFFF); - BackOrPolyCount = count; -} - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp deleted file mode 100644 index 4275e31188..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/agg_def.cpp +++ /dev/null @@ -1,894 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/agg_def.cpp $* - * * - * Author:: Patrick Smith - * * - * $Modtime:: 4/05/01 10:21a $* - * * - * $Revision:: 5 $* - * * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "agg_def.h" -#include "htree.h" -#include "w3derr.h" -#include "chunkio.h" -#include "wwdebug.h" -#include "assetmgr.h" -#include "matinfo.h" -#include "texture.h" -#include "wwstring.h" - -#include - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Local constants -// -const char * const EMPTY_STRING = ""; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Global variable initialization -// -AggregateLoaderClass _AggregateLoader; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// AggregateDefClass -// -AggregateDefClass::AggregateDefClass (void) - : m_pName (NULL) -{ - // Set our member data to default settings - ::memset (&m_Info, 0, sizeof (m_Info)); - ::memset (&m_MiscInfo, 0, sizeof (m_MiscInfo)); - m_MiscInfo.OriginalClassID = RenderObjClass::CLASSID_HLOD; - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// AggregateDefClass -// -AggregateDefClass::AggregateDefClass (const AggregateDefClass &src) - : m_pName (NULL) -{ - // Set our member data to default settings - ::memset (&m_Info, 0, sizeof (m_Info)); - ::memset (&m_MiscInfo, 0, sizeof (m_MiscInfo)); - m_MiscInfo.OriginalClassID = RenderObjClass::CLASSID_HLOD; - - // Invoke the assignment operator - (*this) = src; - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// AggregateDefClass -// -AggregateDefClass::AggregateDefClass (RenderObjClass &base_model) - : m_pName (NULL) -{ - // Set our member data to default settings - ::memset (&m_Info, 0, sizeof (m_Info)); - ::memset (&m_MiscInfo, 0, sizeof (m_MiscInfo)); - m_MiscInfo.OriginalClassID = RenderObjClass::CLASSID_HLOD; - - Initialize (base_model); - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// ~AggregateDefClass -// -AggregateDefClass::~AggregateDefClass (void) -{ - // Free the name buffer if necessary - if (m_pName != NULL) { - - // free() is used because the buffer was allocated with ::_strdup(). - ::free (m_pName); - m_pName = NULL; - } - - Free_Subobject_List (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -const AggregateDefClass & -AggregateDefClass::operator= (const AggregateDefClass &src) -{ - int index; - - // Free the name buffer if necessary - if (m_pName != NULL) { - ::free (m_pName); - m_pName = NULL; - } - - // Start with a fresh set of data - Free_Subobject_List (); - - // Copy the src object's name and info struct - Set_Name (src.Get_Name ()); - ::memcpy (&m_Info, &src.m_Info, sizeof (m_Info)); - ::memcpy (&m_MiscInfo, &src.m_MiscInfo, sizeof (m_MiscInfo)); - m_Version = src.m_Version; - - // Loop through all the entries in the src object's subobj list - for (index = 0; index < src.m_SubobjectList.Count (); index ++) { - W3dAggregateSubobjectStruct *pinfo = src.m_SubobjectList[index]; - if (pinfo != NULL) { - - // Copy the src object's info for this subobj - W3dAggregateSubobjectStruct *new_info = W3DNEW W3dAggregateSubobjectStruct; - ::memcpy (new_info, pinfo, sizeof (W3dAggregateSubobjectStruct)); - - // Add this subobj to our list - m_SubobjectList.Add (new_info); - } - } - - // Return a reference to ourselves - return *this; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Free_Subobject_List -// -void -AggregateDefClass::Free_Subobject_List (void) -{ - // Delete all the stucture pointers contained in the subobject list - for (int index = 0; index < m_SubobjectList.Count (); index ++) { - W3dAggregateSubobjectStruct *pinfo = m_SubobjectList[index]; - if (pinfo) { - delete pinfo; - } - } - - // Reset the lists contents - m_SubobjectList.Delete_All (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Create -// -RenderObjClass * -AggregateDefClass::Create (void) -{ - // Attempt to create an instance of the hierarchy - RenderObjClass *pmodel = Create_Render_Object (m_Info.BaseModelName); - if (pmodel != NULL) { - - // Perform the aggregation - Attach_Subobjects (*pmodel); - - // Let the new object know what its new name and base name are. - pmodel->Set_Name (m_pName); - pmodel->Set_Base_Model_Name (m_Info.BaseModelName); - pmodel->Set_Sub_Objects_Match_LOD ((m_MiscInfo.Flags & W3D_AGGREGATE_FORCE_SUB_OBJ_LOD) == W3D_AGGREGATE_FORCE_SUB_OBJ_LOD); - - } else { - WWDEBUG_SAY (("Unable to load aggregate %s.\r\n", m_Info.BaseModelName)); - } - - // Return a pointer to the new aggregate - return pmodel; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Find_Subobject -// -RenderObjClass * -AggregateDefClass::Find_Subobject -( - RenderObjClass &model, - const char mesh_path[MESH_PATH_ENTRIES][MESH_PATH_ENTRY_LEN], - const char bone_path[MESH_PATH_ENTRIES][MESH_PATH_ENTRY_LEN] -) -{ - RenderObjClass *parent_model = &model; - parent_model->Add_Ref (); - - // Loop through all the models in our "path" until we've either failed - // or found the exact mesh we were looking for... - for (int index = 1; - (mesh_path[index][0] != 0) && (parent_model != NULL); - index ++) { - - // Look one level deeper into the subobject chain... - RenderObjClass *sub_obj = NULL; - if (bone_path[index][0] == 0) { - sub_obj = parent_model->Get_Sub_Object_By_Name (mesh_path[index]); - } else { - - int bone_index = parent_model->Get_Bone_Index (bone_path[index]); - int subobj_count = parent_model->Get_Num_Sub_Objects_On_Bone (bone_index); - - // Loop through all the subobjects on this bone - for (int subobj_index = 0; (subobj_index < subobj_count) && (sub_obj == NULL); subobj_index ++) { - - // Is this the subobject we were looking for? - RenderObjClass *ptemp_obj = parent_model->Get_Sub_Object_On_Bone (subobj_index, bone_index); - if (::lstrcmpi (ptemp_obj->Get_Name (), mesh_path[index]) == 0) { - sub_obj = ptemp_obj; - } else { - REF_PTR_RELEASE (ptemp_obj); - } - } - } - - REF_PTR_RELEASE (parent_model); - - // The parent for the next iteration is the subobject on this one. - parent_model = sub_obj; - } - - // Return a pointer to the subobject - return parent_model; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Attach_Subobjects -// -void -AggregateDefClass::Attach_Subobjects (RenderObjClass &base_model) -{ - // Now loop through all the subobjects and attach them to the appropriate bone - for (int index = 0; index < m_SubobjectList.Count (); index ++) { - W3dAggregateSubobjectStruct *psubobj_info = m_SubobjectList[index]; - if (psubobj_info != NULL) { - - // Now create this subobject and attach it to its bone. - RenderObjClass *prender_obj = Create_Render_Object (psubobj_info->SubobjectName); - if (prender_obj != NULL) { - - // Attach this object to the requested bone - if (base_model.Add_Sub_Object_To_Bone (prender_obj, psubobj_info->BoneName) == false) { - WWDEBUG_SAY (("Unable to attach %s to %s.\r\n", psubobj_info->SubobjectName, psubobj_info->BoneName)); - } - - // Release our hold on this pointer - prender_obj->Release_Ref (); - } else { - WWDEBUG_SAY (("Unable to load aggregate subobject %s.\r\n", psubobj_info->SubobjectName)); - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Create_Render_Object -// -RenderObjClass * -AggregateDefClass::Create_Render_Object (const char *passet_name) -{ - // Assume failure - RenderObjClass *prender_obj = NULL; - - // Attempt to get an instance of the render object from the asset manager - prender_obj = WW3DAssetManager::Get_Instance()->Create_Render_Obj (passet_name); - - // If we couldn't find the render object in the asset manager, then attempt to - // load it from file - if ((prender_obj == NULL) && - Load_Assets (passet_name)) { - - // It should be in the asset manager now, so attempt to get it again. - prender_obj = WW3DAssetManager::Get_Instance()->Create_Render_Obj (passet_name); - } - - // Return a pointer to the render object - return prender_obj; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Load_Assets -// -bool -AggregateDefClass::Load_Assets (const char *passet_name) -{ - // Assume failure - bool retval = false; - - // Param OK? - if (passet_name != NULL) { - - // Determine what the current working directory is - char path[MAX_PATH]; - ::GetCurrentDirectory (sizeof (path), path); - - // Ensure the path is directory delimited - if (path[::lstrlen(path)-1] != '\\') { - ::lstrcat (path, "\\"); - } - - // Assume the filename is simply the "asset name" + the w3d extension - ::lstrcat (path, passet_name); - ::lstrcat (path, ".w3d"); - - // If the file exists, then load it into the asset manager. - if (::GetFileAttributes (path) != 0xFFFFFFFF) { - retval = WW3DAssetManager::Get_Instance()->Load_3D_Assets (path); - } - } - - // Return the true/false result code - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -void -AggregateDefClass::Initialize (RenderObjClass &base_model) -{ - // Start with fresh lists - Free_Subobject_List (); - - // Determine what the render objects original name was. - const char *orig_model_name = base_model.Get_Base_Model_Name (); - orig_model_name = (orig_model_name == NULL) ? base_model.Get_Name () : orig_model_name; - - // Record information about this base model - ::lstrcpy (m_Info.BaseModelName, orig_model_name); - m_Info.SubobjectCount = 0; - m_MiscInfo.OriginalClassID = base_model.Class_ID (); - m_MiscInfo.Flags = 0; - m_MiscInfo.Flags |= base_model.Is_Sub_Objects_Match_LOD_Enabled () ? W3D_AGGREGATE_FORCE_SUB_OBJ_LOD : 0; - - - // Pass the aggregate name along - Set_Name (base_model.Get_Name ()); - - // Create a new instance of the model which we can use - // to compare with the supplied model and determine - // which 'bones-models' and textures are new. - RenderObjClass *pvanilla_model = (RenderObjClass *)Create_Render_Object (orig_model_name); - - // Build lists of changes from the delta between the original model and the provided one - Build_Subobject_List (*pvanilla_model, base_model); - - // Release the model if necessary - REF_PTR_RELEASE (pvanilla_model); - return ; -} - - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Build_Subobject_List -// -void -AggregateDefClass::Build_Subobject_List -( - RenderObjClass &original_model, - RenderObjClass &model -) -{ - int index; - - // Loop through all the bones in this render obj - int bone_count = model.Get_Num_Bones (); - for (int bone_index = 0; bone_index < bone_count; bone_index ++) { - const char *pbone_name = model.Get_Bone_Name (bone_index); - - // Build a list of nodes that are contained in the vanilla model - DynamicVectorClass orig_node_list; - for (index = 0; - index < original_model.Get_Num_Sub_Objects_On_Bone (bone_index); - index ++) { - RenderObjClass *psubobj = original_model.Get_Sub_Object_On_Bone (index, bone_index); - if (psubobj != NULL) { - orig_node_list.Add (psubobj); - } - } - - // Build a list of nodes that are contained in this bone - DynamicVectorClass node_list; - for (index = 0; - index < model.Get_Num_Sub_Objects_On_Bone (bone_index); - index ++) { - RenderObjClass *psubobj = model.Get_Sub_Object_On_Bone (index, bone_index); - if (psubobj != NULL) { - node_list.Add (psubobj); - } - } - - int node_count = node_list.Count (); - if (node_count > 0) { - - // Loop through the subobjects and add each one to our internal list - W3dAggregateSubobjectStruct subobj_info = { 0 }; - for (int node_index = 0; node_index < node_count; node_index ++) { - RenderObjClass *psubobject = node_list[node_index]; - WWASSERT (psubobject != NULL); - - // Is this subobject new? (i.e. not in a 'vanilla' instance?) - const char *prototype_name = psubobject->Get_Name (); - if (psubobject != NULL && - (Is_Object_In_List (prototype_name, orig_node_list) == false)) { - - // Add this subobject to our list - ::lstrcpy (subobj_info.SubobjectName, prototype_name); - ::lstrcpy (subobj_info.BoneName, pbone_name); - Add_Subobject (subobj_info); - m_Info.SubobjectCount ++; - - // Attach this render object to the 'original' model (this is done - // so we can do texture compares later) - RenderObjClass *prender_obj = WW3DAssetManager::Get_Instance ()->Create_Render_Obj (prototype_name); - ((RenderObjClass &)original_model).Add_Sub_Object_To_Bone (prender_obj, pbone_name); - REF_PTR_RELEASE (prender_obj); - } - } - } - - // Free our hold on the render objs in the original node list - for (index = 0; index < orig_node_list.Count (); index ++) { - REF_PTR_RELEASE (orig_node_list[index]); - } - orig_node_list.Delete_All (); - - // Free our hold on the render objs in the node list - for (index = 0; index < node_list.Count (); index ++) { - REF_PTR_RELEASE (node_list[index]); - } - node_list.Delete_All (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Is_Object_In_List -// -bool -AggregateDefClass::Is_Object_In_List -( - const char *passet_name, - DynamicVectorClass &node_list -) -{ - // Assume failure - bool retval = false; - - // Loop through the nodes in the list until we've found the one - // were are looking for. - for (int node_index = 0; (node_index < node_list.Count ()) && (retval == false); node_index ++) { - RenderObjClass *prender_obj = node_list[node_index]; - - // Is this the render object we were looking for? - if (prender_obj != NULL && - ::lstrcmpi (prender_obj->Get_Name (), passet_name) == 0) { - retval = true; - } - } - - // Return the true/false result code - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -WW3DErrorType -AggregateDefClass::Load_W3D (ChunkLoadClass &chunk_load) -{ - W3dTextureReplacerHeaderStruct header = { 0 }; - - - while (chunk_load.Open_Chunk()) { - - WW3DErrorType error = WW3D_ERROR_OK; - - switch (chunk_load.Cur_Chunk_ID()) { - - case W3D_CHUNK_AGGREGATE_HEADER: - error = Read_Header(chunk_load); - break; - - case W3D_CHUNK_AGGREGATE_INFO: - error = Read_Info(chunk_load); - break; - - case W3D_CHUNK_TEXTURE_REPLACER_INFO: - if (chunk_load.Read (&header, sizeof (header)) == sizeof (header)) { - if (header.ReplacedTexturesCount > 0) { - WWDEBUG_SAY(("Obsolete texture replacement chunk encountered in aggregate: %s\r\n",m_pName)); - } - } - break; - - case W3D_CHUNK_AGGREGATE_CLASS_INFO: - error = Read_Class_Info(chunk_load); - break; - - default: - - // Unknown chunk. - break; - } - chunk_load.Close_Chunk(); - if (error != WW3D_ERROR_OK) return (error); - } - - return WW3D_ERROR_OK; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Read_Header -// -WW3DErrorType -AggregateDefClass::Read_Header (ChunkLoadClass &chunk_load) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_LOAD_FAILED; - - // Is this the header chunk? - W3dAggregateHeaderStruct header = { 0 }; - if (chunk_load.Read (&header, sizeof (header)) == sizeof (header)) { - - // Copy the name from the header structure - m_pName = ::_strdup (header.Name); - m_Version = header.Version; - - // Success! - ret_val = WW3D_ERROR_OK; - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Read_Info -// -WW3DErrorType -AggregateDefClass::Read_Info (ChunkLoadClass &chunk_load) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_LOAD_FAILED; - - // Read the chunk straight into our member structure - ::memset (&m_Info, 0, sizeof (m_Info)); - if (chunk_load.Read (&m_Info, sizeof (m_Info)) == sizeof (m_Info)) { - - // Success! - ret_val = WW3D_ERROR_OK; - - // Read all the subobjects from the file - for (UINT isubobject = 0; - (isubobject < m_Info.SubobjectCount) && (ret_val == WW3D_ERROR_OK); - isubobject ++) { - - // Read this subobject's definition from the file - ret_val = Read_Subobject (chunk_load); - } - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Read_Subobject -// -WW3DErrorType -AggregateDefClass::Read_Subobject (ChunkLoadClass &chunk_load) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_LOAD_FAILED; - - // Read the subobject information from the file - W3dAggregateSubobjectStruct subobj_info = { 0 }; - if (chunk_load.Read (&subobj_info, sizeof (subobj_info)) == sizeof (subobj_info)) { - - // Add this subobject to our list - Add_Subobject (subobj_info); - - // Success! - ret_val = WW3D_ERROR_OK; - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Add_Subobject -// -void -AggregateDefClass::Add_Subobject (const W3dAggregateSubobjectStruct &subobj_info) -{ - // Create a new structure and copy the contents of the src - W3dAggregateSubobjectStruct *pnew_entry = W3DNEW W3dAggregateSubobjectStruct; - ::lstrcpy (pnew_entry->SubobjectName, subobj_info.SubobjectName); - ::lstrcpy (pnew_entry->BoneName, subobj_info.BoneName); - - // Add this new entry to the list - m_SubobjectList.Add (pnew_entry); - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Read_Class_Info -// -WW3DErrorType -AggregateDefClass::Read_Class_Info (ChunkLoadClass &chunk_load) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_LOAD_FAILED; - - // Read the chunk straight into our header structure - ::memset (&m_MiscInfo, 0, sizeof (m_MiscInfo)); - if (chunk_load.Read (&m_MiscInfo, sizeof (m_MiscInfo)) == sizeof (m_MiscInfo)) { - - // Success! - ret_val = WW3D_ERROR_OK; - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -WW3DErrorType -AggregateDefClass::Save_W3D (ChunkSaveClass &chunk_save) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_SAVE_FAILED; - - // Begin a chunk that identifies an aggregate - if (chunk_save.Begin_Chunk (W3D_CHUNK_AGGREGATE) == TRUE) { - - // Attempt to save the different sections of the aggregate definition - if ((Save_Header (chunk_save) == WW3D_ERROR_OK) && - (Save_Info (chunk_save) == WW3D_ERROR_OK) && - (Save_Class_Info (chunk_save) == WW3D_ERROR_OK)) { - - // Success! - ret_val = WW3D_ERROR_OK; - } - - // Close the aggregate chunk - chunk_save.End_Chunk (); - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Save_Header -// -WW3DErrorType -AggregateDefClass::Save_Header (ChunkSaveClass &chunk_save) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_SAVE_FAILED; - - // Begin a chunk that identifies the aggregate - if (chunk_save.Begin_Chunk (W3D_CHUNK_AGGREGATE_HEADER) == TRUE) { - - // Fill the header structure - W3dAggregateHeaderStruct header = { 0 }; - header.Version = W3D_CURRENT_AGGREGATE_VERSION; - ::lstrcpyn (header.Name, m_pName, sizeof (header.Name)); - header.Name[sizeof (header.Name) - 1] = 0; - - // Write the header out to the chunk - if (chunk_save.Write (&header, sizeof (header)) == sizeof (header)) { - // Success! - ret_val = WW3D_ERROR_OK; - } - - // End the header chunk - chunk_save.End_Chunk (); - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Save_Info -// -WW3DErrorType -AggregateDefClass::Save_Info (ChunkSaveClass &chunk_save) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_SAVE_FAILED; - - // Begin a chunk that identifies the aggregate settings - if (chunk_save.Begin_Chunk (W3D_CHUNK_AGGREGATE_INFO) == TRUE) { - - // Write the settings structure out to the chunk - if (chunk_save.Write (&m_Info, sizeof (m_Info)) == sizeof (m_Info)) { - // Success! - ret_val = WW3D_ERROR_OK; - - // Write all the subobjects to the file - for (int isubobject = 0; - (isubobject < m_SubobjectList.Count ()) && (ret_val == WW3D_ERROR_OK); - isubobject ++) { - - // Write this object to the file - ret_val = Save_Subobject (chunk_save, m_SubobjectList[isubobject]); - } - } - - // End the settings chunk - chunk_save.End_Chunk (); - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Save_Subobject -// -WW3DErrorType -AggregateDefClass::Save_Subobject -( - ChunkSaveClass &chunk_save, - W3dAggregateSubobjectStruct *psubobject -) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_SAVE_FAILED; - - // Write the subobj structure out to the chunk - if (chunk_save.Write (psubobject, sizeof (W3dAggregateSubobjectStruct)) == sizeof (W3dAggregateSubobjectStruct)) { - - // Success! - ret_val = WW3D_ERROR_OK; - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Save_Class_Info -// -WW3DErrorType -AggregateDefClass::Save_Class_Info (ChunkSaveClass &chunk_save) -{ - // Assume error - WW3DErrorType ret_val = WW3D_ERROR_SAVE_FAILED; - - // Begin a chunk that identifies the texture replacer header - if (chunk_save.Begin_Chunk (W3D_CHUNK_AGGREGATE_CLASS_INFO) == TRUE) { - - // Write the class information structure out to the chunk - if (chunk_save.Write (&m_MiscInfo, sizeof (m_MiscInfo)) == sizeof (m_MiscInfo)) { - - // Success! - ret_val = WW3D_ERROR_OK; - } - - // End the class info chunk - chunk_save.End_Chunk (); - } - - // Return the WW3D_ERROR_TYPE return code - return ret_val; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -PrototypeClass * -AggregateLoaderClass::Load_W3D (ChunkLoadClass &chunk_load) -{ - // Assume failure - AggregatePrototypeClass *pprototype = NULL; - - // Create a definition object - AggregateDefClass *pdefinition = W3DNEW AggregateDefClass; - if (pdefinition != NULL) { - - // Ask the definition object to load the aggregate data - if (pdefinition->Load_W3D (chunk_load) != WW3D_ERROR_OK) { - - // Error! Free the definition - delete pdefinition; - pdefinition = NULL; - } else { - - // Success! Create a prototype from the definition - pprototype = W3DNEW AggregatePrototypeClass (pdefinition); - } - } - - // Return a pointer to the prototype - return pprototype; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h deleted file mode 100644 index 55f2bc3dd8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/agg_def.h +++ /dev/null @@ -1,259 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/agg_def.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 4/05/01 9:52a $* - * * - * $Revision:: 2 $* - * * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AGGREGATE_DEF_H -#define AGGREGATE_DEF_H - -#include "proto.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "w3derr.h" -#include "Vector.H" -#include "bittype.h" -#include - -#ifdef _UNIX -#include "osdep.h" -#endif - - -// Forward declarations -class ChunkLoadClass; -class ChunkSaveClass; -class IndirectTextureClass; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Macros -// -#ifndef SAFE_FREE -#define SAFE_FREE(pointer) \ -{ \ - if (pointer) { \ - ::free (pointer); \ - pointer = 0; \ - } \ -} - -#endif //SAFE_FREE - - -////////////////////////////////////////////////////////////////////////////////// -// -// AggregateDefClass -// -// Description of an aggregate object. Used by the asset manager -// to construct aggregates. An 'aggregate' is simply a 'shell' that -// contains references to a hierarchy model and subobjects to attach to its bones. -// -class AggregateDefClass -{ - public: - - /////////////////////////////////////////////////////////// - // - // Public constructors/destructors - // - AggregateDefClass (void); - AggregateDefClass (RenderObjClass &base_model); - AggregateDefClass (const AggregateDefClass &src); - virtual ~AggregateDefClass (void); - - - /////////////////////////////////////////////////////////// - // - // Public operators - // - const AggregateDefClass &operator= (const AggregateDefClass &src); - - /////////////////////////////////////////////////////////// - // - // Public methods - // - virtual WW3DErrorType Load_W3D (ChunkLoadClass &chunk_load); - virtual WW3DErrorType Save_W3D (ChunkSaveClass &chunk_save); - const char * Get_Name (void) const { return m_pName; } - void Set_Name (const char *pname) { SAFE_FREE (m_pName); m_pName = ::_strdup (pname); } - RenderObjClass * Create (void); - AggregateDefClass * Clone (void) const { return W3DNEW AggregateDefClass (*this); } - - // - // Public accessors - // - ULONG Class_ID (void) const { return m_MiscInfo.OriginalClassID; } - - // - // Initialization - // - void Initialize (RenderObjClass &base_model); - - protected: - - /////////////////////////////////////////////////////////// - // - // Protected data types - // - typedef struct _TEXTURE_INFO - { - W3dTextureReplacerStruct names; - IndirectTextureClass * pnew_texture; - - bool operator == (_TEXTURE_INFO &src) { return false; } - bool operator != (_TEXTURE_INFO &src) { return true; } - } TEXTURE_INFO; - - - /////////////////////////////////////////////////////////// - // - // Protected methods - // - - // - // Loading methods - // - virtual WW3DErrorType Read_Header (ChunkLoadClass &chunk_load); - virtual WW3DErrorType Read_Info (ChunkLoadClass &chunk_load); - virtual WW3DErrorType Read_Subobject (ChunkLoadClass &chunk_load); - virtual WW3DErrorType Read_Class_Info (ChunkLoadClass &chunk_load); - - // - // Saving methods - // - virtual WW3DErrorType Save_Header (ChunkSaveClass &chunk_save); - virtual WW3DErrorType Save_Info (ChunkSaveClass &chunk_save); - virtual WW3DErrorType Save_Subobject (ChunkSaveClass &chunk_save, W3dAggregateSubobjectStruct *psubobject); - virtual WW3DErrorType Save_Class_Info (ChunkSaveClass &chunk_save); - - // - // Creation methods - // - virtual void Attach_Subobjects (RenderObjClass &base_model); - - // - // Search methods - // - virtual RenderObjClass * Find_Subobject (RenderObjClass &model, const char mesh_path[MESH_PATH_ENTRIES][MESH_PATH_ENTRY_LEN], const char bone_path[MESH_PATH_ENTRIES][MESH_PATH_ENTRY_LEN]); - - // - // Misc. methods - // - virtual void Free_Subobject_List (void); - virtual void Add_Subobject (const W3dAggregateSubobjectStruct &subobj_info); - virtual bool Load_Assets (const char *asset_name); - virtual RenderObjClass *Create_Render_Object (const char *passet_name); - virtual bool Is_Object_In_List (const char *passet_name, DynamicVectorClass &node_list); - - virtual void Build_Subobject_List (RenderObjClass &original_model, RenderObjClass &model); - - - private: - - /////////////////////////////////////////////////////////// - // - // Private member data - // - DWORD m_Version; - DynamicVectorClass m_SubobjectList; - W3dAggregateInfoStruct m_Info; - W3dAggregateMiscInfo m_MiscInfo; - char * m_pName; -}; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// AggregatePrototypeClass -// -class AggregatePrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(AggregatePrototypeClass) - public: - - /////////////////////////////////////////////////////////// - // - // Public constructors/destructors - // - AggregatePrototypeClass (AggregateDefClass *pdef) { m_pDefinition = pdef; } - - /////////////////////////////////////////////////////////// - // - // Public methods - // - virtual const char * Get_Name(void) const { return m_pDefinition->Get_Name (); } - virtual int Get_Class_ID(void) const { return m_pDefinition->Class_ID (); } - virtual RenderObjClass * Create (void) { return m_pDefinition->Create (); } - virtual void DeleteSelf() { delete this; } - virtual AggregateDefClass * Get_Definition (void) const { return m_pDefinition; } - virtual void Set_Definition (AggregateDefClass *pdef) { m_pDefinition = pdef; } - - protected: - virtual ~AggregatePrototypeClass (void) { delete m_pDefinition; } - - private: - - /////////////////////////////////////////////////////////// - // - // Private member data - // - AggregateDefClass * m_pDefinition; -}; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// AggregateLoaderClass -// -class AggregateLoaderClass : public PrototypeLoaderClass -{ - public: - - virtual int Chunk_Type (void) { return W3D_CHUNK_AGGREGATE; } - virtual PrototypeClass * Load_W3D (ChunkLoadClass &chunk_load); -}; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Global variables -// -extern AggregateLoaderClass _AggregateLoader; - - -#endif //__AGGREGATE_DEF_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp index d8a4470525..fe4e4753cc 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp @@ -65,6 +65,7 @@ #include "hcanim.h" #include "ww3d.h" #include "wwmemlog.h" +#include "animatedsoundmgr.h" /*********************************************************************************************** @@ -87,12 +88,15 @@ Animatable3DObjClass::Animatable3DObjClass(const char * htree_name) : // Inline struct members can't be initialized in init list for some reason... ModeAnim.Motion=NULL; ModeAnim.Frame=0.0f; + ModeAnim.PrevFrame=0.0f; ModeAnim.LastSyncTime=WW3D::Get_Sync_Time(); ModeAnim.frameRateMultiplier=1.0; // 020607 srj -- added ModeAnim.animDirection=1.0; // 020607 srj -- added ModeInterp.Motion0=NULL; ModeInterp.Motion1=NULL; ModeInterp.Frame0=0.0f; + ModeInterp.PrevFrame0=0.0f; + ModeInterp.PrevFrame1=0.0f; ModeInterp.Frame1=0.0f; ModeInterp.Percentage=0.0f; ModeCombo.AnimCombo=NULL; @@ -140,12 +144,15 @@ Animatable3DObjClass::Animatable3DObjClass(const Animatable3DObjClass & src) : // Inline struct members can't be initialized in init list for some reason... ModeAnim.Motion=NULL; ModeAnim.Frame=0.0f; + ModeAnim.PrevFrame=0.0f; ModeAnim.LastSyncTime=WW3D::Get_Sync_Time(); ModeAnim.frameRateMultiplier=1.0; // 020607 srj -- added ModeAnim.animDirection=1.0; // 020607 srj -- added ModeInterp.Motion0=NULL; ModeInterp.Motion1=NULL; ModeInterp.Frame0=0.0f; + ModeInterp.PrevFrame0=0.0f; + ModeInterp.PrevFrame1=0.0f; ModeInterp.Frame1=0.0f; ModeInterp.Percentage=0.0f; ModeCombo.AnimCombo=NULL; @@ -202,12 +209,15 @@ Animatable3DObjClass & Animatable3DObjClass::operator = (const Animatable3DObjCl CurMotionMode = BASE_POSE; ModeAnim.Motion = NULL; ModeAnim.Frame = 0.0f; + ModeAnim.PrevFrame = 0.0f; ModeAnim.LastSyncTime = WW3D::Get_Sync_Time(); ModeAnim.frameRateMultiplier=1.0; // 020607 srj -- added ModeAnim.animDirection=1.0; // 020607 srj -- added ModeInterp.Motion0 = NULL; ModeInterp.Motion1 = NULL; ModeInterp.Frame0 = 0.0f; + ModeInterp.PrevFrame0 = 0.0f; + ModeInterp.PrevFrame1 = 0.0f; ModeInterp.Frame1 = 0.0f; ModeInterp.Percentage = 0.0f; ModeCombo.AnimCombo = NULL; @@ -468,15 +478,24 @@ void Animatable3DObjClass::Set_Animation(HAnimClass * motion, float frame, int m Release(); CurMotionMode = SINGLE_ANIM; ModeAnim.Motion = motion; + ModeAnim.PrevFrame = ModeAnim.Frame; ModeAnim.Frame = frame; ModeAnim.LastSyncTime = WW3D::Get_Sync_Time(); ModeAnim.frameRateMultiplier=1.0; // 020607 srj -- added ModeAnim.animDirection=1.0; // 020607 srj -- added + ModeAnim.AnimMode = mode; + if (mode < ANIM_MODE_LOOP_BACKWARDS) ModeAnim.animDirection = 1.0f; //assume playing forwards else ModeAnim.animDirection = -1.0f; //reverse animation playback + + const char* sound_name = AnimatedSoundMgrClass::Get_Embedded_Sound_Name(motion); + if (sound_name) { + int bone_index = Get_Bone_Index(sound_name); + motion->Set_Embedded_Sound_Bone_Index(bone_index); + } } else { CurMotionMode = BASE_POSE; Release(); @@ -512,6 +531,8 @@ void Animatable3DObjClass::Set_Animation CurMotionMode = DOUBLE_ANIM; ModeInterp.Motion0 = motion0; ModeInterp.Motion1 = motion1; + ModeInterp.PrevFrame0 = ModeInterp.Frame0; + ModeInterp.PrevFrame1 = ModeInterp.Frame1; ModeInterp.Frame0 = frame0; ModeInterp.Frame1 = frame1; ModeInterp.Percentage = percentage; @@ -519,10 +540,20 @@ void Animatable3DObjClass::Set_Animation if ( ModeInterp.Motion0 != NULL ) { ModeInterp.Motion0->Add_Ref(); + const char* sound_name = AnimatedSoundMgrClass::Get_Embedded_Sound_Name(motion0); + if (sound_name) { + int bone_index = Get_Bone_Index(sound_name); + motion0->Set_Embedded_Sound_Bone_Index(bone_index); + } } if ( ModeInterp.Motion1 != NULL ) { ModeInterp.Motion1->Add_Ref(); + const char* sound_name = AnimatedSoundMgrClass::Get_Embedded_Sound_Name(motion1); + if (sound_name) { + int bone_index = Get_Bone_Index(sound_name); + motion1->Set_Embedded_Sound_Bone_Index(bone_index); + } } } @@ -549,6 +580,19 @@ void Animatable3DObjClass::Set_Animation CurMotionMode = MULTIPLE_ANIM; ModeCombo.AnimCombo = anim_combo; Set_Hierarchy_Valid(false); + + if (anim_combo) { + int count = anim_combo->Get_Num_Anims(); + for (int index = 0; index < count; index ++) { + HAnimClass *motion = anim_combo->Peek_Motion(index); + + const char* sound_name = AnimatedSoundMgrClass::Get_Embedded_Sound_Name(motion); + if (sound_name) { + int bone_index = Get_Bone_Index(sound_name); + motion->Set_Embedded_Sound_Bone_Index(bone_index); + } + } + } } @@ -752,20 +796,57 @@ void Animatable3DObjClass::Update_Sub_Object_Transforms(void) break; case SINGLE_ANIM: + if ( ModeAnim.AnimMode != ANIM_MODE_MANUAL ) { Single_Anim_Progress(); } Anim_Update(Transform,ModeAnim.Motion,ModeAnim.Frame); + + /* + ** Play any sounds that are triggered by this frame of animation + */ + if ( ModeAnim.Motion->Has_Embedded_Sounds() ) { + ModeAnim.PrevFrame = AnimatedSoundMgrClass::Trigger_Sound(ModeAnim.Motion, ModeAnim.PrevFrame, ModeAnim.Frame, HTree->Get_Transform(ModeAnim.Motion->Get_Embedded_Sound_Bone_Index())); + } break; case DOUBLE_ANIM: Blend_Update(Transform,ModeInterp.Motion0,ModeInterp.Frame0, ModeInterp.Motion1,ModeInterp.Frame1,ModeInterp.Percentage); + + /* + ** Play any sounds that are triggered by this frame of animation + */ + if ( ModeInterp.Motion0->Has_Embedded_Sounds() ) { + ModeInterp.PrevFrame0 = AnimatedSoundMgrClass::Trigger_Sound(ModeInterp.Motion0, ModeInterp.PrevFrame0, ModeInterp.Frame0, HTree->Get_Transform(ModeInterp.Motion0->Get_Embedded_Sound_Bone_Index())); + } + + if ( ModeInterp.Motion1->Has_Embedded_Sounds() ) { + ModeInterp.PrevFrame1 = AnimatedSoundMgrClass::Trigger_Sound(ModeInterp.Motion1, ModeInterp.PrevFrame1, ModeInterp.Frame1, HTree->Get_Transform(ModeInterp.Motion1->Get_Embedded_Sound_Bone_Index())); + } + break; case MULTIPLE_ANIM: + { Combo_Update(Transform,ModeCombo.AnimCombo); + + /* + ** Play any sounds that are triggered by this frame of animation + */ + int count = ModeCombo.AnimCombo->Get_Num_Anims(); + for (int index = 0; index < count; index ++) { + HAnimClass *motion = ModeCombo.AnimCombo->Peek_Motion(index); + + if ( motion != NULL && motion->Has_Embedded_Sounds() ) { + float prev_frame = AnimatedSoundMgrClass::Trigger_Sound(motion, ModeCombo.AnimCombo->Get_Prev_Frame(index), + ModeCombo.AnimCombo->Get_Frame(index), HTree->Get_Transform(motion->Get_Embedded_Sound_Bone_Index())); + ModeCombo.AnimCombo->Set_Prev_Frame(index, prev_frame); + } + + } break; + } default: break; @@ -966,9 +1047,17 @@ void Animatable3DObjClass::Single_Anim_Progress (void) // // Update the frame number and sync time // - ModeAnim.Frame = Compute_Current_Frame(&ModeAnim.animDirection); - ModeAnim.LastSyncTime = WW3D::Get_Sync_Time(); + float oldprev = ModeAnim.PrevFrame; + ModeAnim.PrevFrame = ModeAnim.Frame; + ModeAnim.Frame = Compute_Current_Frame(&ModeAnim.animDirection); + ModeAnim.LastSyncTime = WW3D::Get_Sync_Time(); + if (ModeAnim.Frame == ModeAnim.PrevFrame) { + // This function was somehow called twice per frame. + // Since ModeAnim.Frame hasn't changed, reset the ModeAnim.PrevFrame. + // If you don't do this sounds won't be triggered properly because Frame and PrevFrame will be the same. + ModeAnim.PrevFrame = oldprev; + } // // Force the heirarchy to be recalculated // @@ -1045,4 +1134,4 @@ void Animatable3DObjClass::Set_HTree(HTreeClass * new_htree) } -// EOF - animobj.cpp \ No newline at end of file +// EOF - animobj.cpp diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.h index 7f90fd81a8..9de98c0ec7 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/animobj.h @@ -26,9 +26,9 @@ * * * Author:: Greg_h * * * - * $Modtime:: 6/26/01 7:01p $* + * $Modtime:: 12/10/01 11:18a $* * * - * $Revision:: 3 $* + * $Revision:: 4 $* * * *---------------------------------------------------------------------------------------------* * Functions: * @@ -188,7 +188,8 @@ class Animatable3DObjClass : public CompositeRenderObjClass struct { HAnimClass * Motion; float Frame; - int AnimMode; + float PrevFrame; + int AnimMode; mutable int LastSyncTime; float animDirection; float frameRateMultiplier; // 020607 srj -- added @@ -201,6 +202,8 @@ class Animatable3DObjClass : public CompositeRenderObjClass HAnimClass * Motion1; float Frame0; float Frame1; + float PrevFrame0; + float PrevFrame1; float Percentage; } ModeInterp; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp index ecb92029e6..334cd38265 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.cpp @@ -200,6 +200,7 @@ class Font3DDataIterator : public AssetIterator WW3DAssetManager::WW3DAssetManager(void) : PrototypeLoaders (PROTOLOADERS_VECTOR_SIZE), Prototypes (PROTOTYPES_VECTOR_SIZE), + WW3D_Load_On_Demand (false), Activate_Fog_On_Load (false), MetalManager(0) @@ -212,7 +213,10 @@ WW3DAssetManager::WW3DAssetManager(void) : Prototypes.Set_Growth_Step(PROTOTYPES_GROWTH_RATE); // install the default loaders +#ifndef USE_WWSHADE Register_Prototype_Loader(&_MeshLoader); +#endif + Register_Prototype_Loader(&_HModelLoader); Register_Prototype_Loader(&_CollectionLoader); Register_Prototype_Loader(&_BoxLoader); @@ -798,7 +802,8 @@ RenderObjClass * WW3DAssetManager::Create_Render_Obj(const char * name) // If we can't find it, try the parent directory if ( Load_3D_Assets( filename ) == false ) { - StringClass new_filename = StringClass("..\\") + filename; + StringClass new_filename(StringClass("..\\"),true); + new_filename+=filename; Load_3D_Assets( new_filename ); } @@ -1024,7 +1029,8 @@ HTreeClass * WW3DAssetManager::Get_HTree(const char * name) // If we can't find it, try the parent directory if ( Load_3D_Assets( filename ) == false ) { - StringClass new_filename = StringClass("..\\") + filename; + StringClass new_filename("..\\",true); + new_filename+=filename; Load_3D_Assets( new_filename ); } @@ -1095,11 +1101,21 @@ TextureClass * WW3DAssetManager::Get_Texture const char * filename, MipCountType mip_level_count, WW3DFormat texture_format, - bool allow_compression + bool allow_compression, + TextureBaseClass::TexAssetType type, + bool allow_reduction ) { WWPROFILE( "WW3DAssetManager::Get_Texture 1" ); + /* + ** We cannot currently mip-map bumpmaps + */ + if (texture_format==WW3D_FORMAT_U8V8) + { + mip_level_count=MIP_LEVELS_1; + } + /* ** Bail if the user isn't really asking for anything */ @@ -1114,11 +1130,10 @@ TextureClass * WW3DAssetManager::Get_Texture /* ** See if the texture has already been loaded. */ - TextureClass* tex = TextureHash.Get(lower_case_name); if (tex && texture_format!=WW3D_FORMAT_UNKNOWN) { - WWASSERT_PRINT(tex->Get_Texture_Format()==texture_format,("Texture %s has already been loaded witt different format",filename)); + WWASSERT_PRINT(tex->Get_Texture_Format()==texture_format,("Texture %s has already been loaded with different format",filename)); } /* @@ -1126,7 +1141,10 @@ TextureClass * WW3DAssetManager::Get_Texture */ if (!tex) { - tex = NEW_REF (TextureClass, (lower_case_name, NULL, mip_level_count, texture_format, allow_compression)); + if (type==TextureBaseClass::TEX_REGULAR) + { + tex = NEW_REF (TextureClass, (lower_case_name, NULL, mip_level_count, texture_format, allow_compression)); + } TextureHash.Insert(tex->Get_Texture_Name(),tex); } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h index 71e8673ff6..36e8446dee 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/assetmgr.h @@ -16,7 +16,7 @@ ** along with this program. If not, see . */ -/* $Header: /Commando/Code/ww3d2/assetmgr.h 15 7/24/01 6:28p Jani_p $ */ +/* $Header: /Commando/Code/ww3d2/assetmgr.h 19 12/17/01 7:55p Jani_p $ */ /*********************************************************************************************** *** Confidential - Westwood Studios *** *********************************************************************************************** @@ -27,9 +27,9 @@ * * * Author:: Greg_h * * * - * $Modtime:: 7/17/01 5:52p $* + * $Modtime:: 12/15/01 4:14p $* * * - * $Revision:: 15 $* + * $Revision:: 19 $* * * *---------------------------------------------------------------------------------------------* * Functions: * @@ -267,7 +267,9 @@ class WW3DAssetManager const char * filename, MipCountType mip_level_count=MIP_LEVELS_ALL, WW3DFormat texture_format=WW3D_FORMAT_UNKNOWN, - bool allow_compression=true + bool allow_compression=true, + TextureBaseClass::TexAssetType type=TextureBaseClass::TEX_REGULAR, + bool allow_reduction=true ); TextureClass* Get_Bumpmap_Based_On_Texture(TextureClass* texture); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp deleted file mode 100644 index f64bc8300e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bitmaphandler.cpp +++ /dev/null @@ -1,448 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "bitmaphandler.h" -#include "wwdebug.h" -#include "colorspace.h" - -void Bitmap_Assert(bool condition) -{ - WWASSERT(condition); -} - -void BitmapHandlerClass::Create_Mipmap_B8G8R8A8( - unsigned char* dest_surface, - unsigned dest_surface_pitch, - unsigned char* src_surface, - unsigned src_surface_pitch, - unsigned width, - unsigned height) -{ - unsigned src_pitch=src_surface_pitch/4; - for (unsigned y=0;y1 ) ? 63 : 127; - - switch(dest_surface_format) { - case WW3D_FORMAT_U8V8: - *dest_ptr++ = (unsigned char)iDu; - *dest_ptr++ = (unsigned char)iDv; - break; - - case WW3D_FORMAT_L6V5U5: - *(unsigned short*)dest_ptr = (unsigned short)( ( (iDu>>3) & 0x1f ) << 0 ); - *(unsigned short*)dest_ptr |= (unsigned short)( ( (iDv>>3) & 0x1f ) << 5 ); - *(unsigned short*)dest_ptr |= (unsigned short)( ( ( uL>>2) & 0x3f ) << 10 ); - dest_ptr += 2; - break; - - case WW3D_FORMAT_X8L8V8U8: - *dest_ptr++ = (unsigned char)iDu; - *dest_ptr++ = (unsigned char)iDv; - *dest_ptr++ = (unsigned char)uL; - *dest_ptr++ = (unsigned char)0L; - break; - - default: - WWASSERT(0); // Unknown bumpmap format - break; - } - - // Move one pixel to the left (src is 32-bpp) - src_ptr_mid+=src_bpp; - src_ptr_prev_line+=src_bpp; - src_ptr_next_line+=src_bpp; - } - } - return; - } - - bool has_hsv_shift = hsv_shift[0]!=0.0f || hsv_shift[1]!=0.0f || hsv_shift[2]!=0.0f; - if (src_surface_format==dest_surface_format && (src_surface_format==WW3D_FORMAT_A8R8G8B8 || src_surface_format==WW3D_FORMAT_X8R8G8B8)) { - // One-to-one copy or scaling? - dest_surface_pitch/=4; - src_surface_pitch/=4; - if (dest_surface_width==src_surface_width && dest_surface_height==src_surface_height) { - // Generate the next mip level while copying the current surface? - if (generate_mip_level) { - if (dest_surface_width==1) { - unsigned b8g8r8a8=*(unsigned*)src_surface; - if (has_hsv_shift) Recolor(b8g8r8a8,hsv_shift); - *(unsigned*)dest_surface=b8g8r8a8; - } - else { - for (unsigned y=0;y. -*/ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef BITMAPHANDLER_H -#define BITMAPHANDLER_H - -#include "always.h" -#include "ww3dformat.h" -#include "vector3.h" -#include "colorspace.h" - -void Bitmap_Assert(bool condition); - -class BitmapHandlerClass -{ -public: - // Read pixel at given address - WWINLINE static void Read_B8G8R8A8( - unsigned char* argb, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp); - - // Read pixel at given address - WWINLINE static void Read_B8G8R8A8( - unsigned& argb, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp); - - // Read pixel from surface - WWINLINE static void Read_B8G8R8A8( - unsigned& argb, - const unsigned char* src_ptr, - WW3DFormat src_format, - int x, - int y, - int width, - int height, - const unsigned char* palette, - unsigned palette_bpp); - - WWINLINE static void Write_B8G8R8A8( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned char* argb); - - WWINLINE static void Write_B8G8R8A8( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned& argb); - - WWINLINE static void Copy_Pixel( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp); - - WWINLINE static void Copy_Pixel( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp, - const Vector3& hsv_shift); - - WWINLINE static unsigned Combine_A8R8G8B8( - unsigned bgra1, - unsigned bgra2, - unsigned bgra3, - unsigned bgra4); - - static void Create_Mipmap_B8G8R8A8( - unsigned char* dest_surface, - unsigned dest_surface_pitch, - unsigned char* src_surface, - unsigned src_surface_pitch, - unsigned width, - unsigned height); - - static void Copy_Image_Generate_Mipmap( - unsigned width, - unsigned height, - unsigned char* dest_surface, - unsigned dest_pitch, - WW3DFormat dest_format, - unsigned char* src_surface, - unsigned src_pitch, - WW3DFormat src_format, - unsigned char* mip_surface, - unsigned mip_pitch, - const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f)); - - static void Copy_Image( - unsigned char* dest_surface, - unsigned dest_surface_width, - unsigned dest_surface_height, - unsigned dest_surface_pitch, - WW3DFormat dest_surface_format, - unsigned char* src_surface, - unsigned src_surface_width, - unsigned src_surface_height, - unsigned src_surface_pitch, - WW3DFormat src_surface_format, - const unsigned char* src_palette, - unsigned src_palette_bpp, - bool generate_mip_level, - const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f)); - -}; - -// ---------------------------------------------------------------------------- -// -// Read color value of given type in BGRA (D3D) byte order. Regarless -// of the source format the color value is converted to 32-bit format. -// -// ---------------------------------------------------------------------------- - -WWINLINE void BitmapHandlerClass::Read_B8G8R8A8( - unsigned char* argb, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp) -{ - switch (src_format) { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - *(unsigned*)argb=*(unsigned*)src_ptr; - break; - case WW3D_FORMAT_R8G8B8: - *argb++=src_ptr[0]; - *argb++=src_ptr[1]; - *argb++=src_ptr[2]; - *argb++=0xff; - break; - case WW3D_FORMAT_A4R4G4B4: - { - unsigned short tmp; - tmp=*(unsigned short*)src_ptr; - *argb++=((tmp&0x000f)<<4); - *argb++=((tmp&0x00f0)); - *argb++=((tmp&0x0f00)>>4); - *argb++=((tmp&0xf000)>>8); - } - break; - case WW3D_FORMAT_A1R5G5B5: - { - unsigned short tmp; - tmp=*(unsigned short*)src_ptr; - argb[3]=tmp&0x8000 ? 0xff : 0x0; - argb[2]=(tmp>>7)&0xf8; - argb[1]=(tmp>>2)&0xf8; - argb[0]=(tmp<<3)&0xf8; - } - break; - case WW3D_FORMAT_R5G6B5: - { - unsigned short tmp; - tmp=*(unsigned short*)src_ptr; - argb[3]=0xff; - argb[2]=(tmp>>8)&0xf8; - argb[1]=(tmp>>3)&0xfc; - argb[0]=(tmp<<3)&0xf8; - } - break; - case WW3D_FORMAT_R3G3B2: - { - unsigned char tmp=*src_ptr; - argb[3]=0xff; - argb[2]=tmp&0xe0; - argb[1]=(tmp<<3)&0xe0; - argb[0]=(tmp<<6)&0xc0; - } - break; - case WW3D_FORMAT_L8: - { - unsigned char tmp=*src_ptr++; - *argb++=tmp; - *argb++=tmp; - *argb++=tmp; - *argb++=0xff; - } - break; - case WW3D_FORMAT_A8: - { - *argb++=0; - *argb++=0; - *argb++=0; - *argb++=*src_ptr++; - } - break; - case WW3D_FORMAT_P8: - { - unsigned char index=*src_ptr++; - switch (palette_bpp) { - case 4: - *argb++=palette[palette_bpp*index+3]; - *argb++=palette[palette_bpp*index+2]; - *argb++=palette[palette_bpp*index+1]; - *argb++=palette[palette_bpp*index+0]; - break; - case 3: - *argb++=palette[palette_bpp*index+2]; - *argb++=palette[palette_bpp*index+1]; - *argb++=palette[palette_bpp*index+0]; - *argb++=0xff; - break; - case 2: - case 1: - default: - Bitmap_Assert(0); - break; - } - } - break; - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - default: Bitmap_Assert(0); break; - } -} - -WWINLINE void BitmapHandlerClass::Read_B8G8R8A8( - unsigned& argb, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp) -{ - Read_B8G8R8A8((unsigned char*)&argb,src_ptr,src_format,palette,palette_bpp); -} - -// Read pixel from surface -WWINLINE void BitmapHandlerClass::Read_B8G8R8A8( - unsigned& argb, - const unsigned char* src_ptr, - WW3DFormat src_format, - int x, - int y, - int width, - int height, - const unsigned char* palette, - unsigned palette_bpp) -{ - if (x<0 || y<0 || x>=width || y>=height) { - argb=0; - return; - } - - unsigned bpp=Get_Bytes_Per_Pixel(src_format); - Read_B8G8R8A8( - argb, - src_ptr+bpp*x+width*bpp*y, - src_format, - palette, - palette_bpp); -} - - -// ---------------------------------------------------------------------------- -// -// Write color value of given type in BGRA (D3D) byte order. The source value -// is always 32 bit and it is converted to defined destination format. -// -// ---------------------------------------------------------------------------- - -WWINLINE void BitmapHandlerClass::Write_B8G8R8A8( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned char* argb) -{ - switch (dest_format) { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - *(unsigned*)dest_ptr=*(unsigned*)argb; - break; - case WW3D_FORMAT_R8G8B8: - *dest_ptr++=*argb++; - *dest_ptr++=*argb++; - *dest_ptr++=*argb++; - break; - case WW3D_FORMAT_A4R4G4B4: - { - unsigned short tmp; - tmp=((argb[3])&0xf0)<<8; - tmp|=((argb[2])&0xf0)<<4; - tmp|=((argb[1])&0xf0); - tmp|=((argb[0])&0xf0)>>4; - *(unsigned short*)dest_ptr=tmp; - } - break; - case WW3D_FORMAT_A1R5G5B5: - { - unsigned short tmp; - tmp=argb[3] ? 0x8000 : 0x0; - tmp|=((argb[2])&0xf8)<<7; - tmp|=((argb[1])&0xf8)<<2; - tmp|=((argb[0])&0xf8)>>3; - *(unsigned short*)dest_ptr=tmp; - } - break; - case WW3D_FORMAT_R5G6B5: - { - unsigned short tmp; - tmp=((argb[2])&0xf8)<<8; - tmp|=((argb[1])&0xfc)<<3; - tmp|=((argb[0])&0xf8)>>3; - *(unsigned short*)dest_ptr=tmp; - } - break; - case WW3D_FORMAT_R3G3B2: - { - unsigned char tmp; - tmp=((argb[2])&0xe0); - tmp|=((argb[1])&0xe0)>>3; - tmp|=((argb[0])&0xc0)>>6; - *(unsigned short*)dest_ptr=tmp; - } - break; - case WW3D_FORMAT_L8: - { - // CIE Req. 709: Y709 = 0.2125R + 0.7154G + 0.0721B - unsigned char tmp = (unsigned char) ( ( - ((unsigned int)argb[0] * (unsigned int)0x1275) + // 0.0721B - ((unsigned int)argb[1] * (unsigned int)0xB725) + // 0.7154G (rounded up so FF, FF, FF becomes FF) - ((unsigned int)argb[2] * (unsigned int)0x3666) // 0.2125R - ) >> 16); - *dest_ptr++=tmp; - } - break; - case WW3D_FORMAT_A8: - { - *dest_ptr++=*argb++; - } - break; - case WW3D_FORMAT_DXT1: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - case WW3D_FORMAT_P8: // Paletted destination not supported - default: Bitmap_Assert(0); break; - } -} - -WWINLINE void BitmapHandlerClass::Write_B8G8R8A8( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned& argb) -{ - Write_B8G8R8A8(dest_ptr,dest_format,(unsigned char*)&argb); -} - -// ---------------------------------------------------------------------------- -// -// Copy pixel. Perform color space conversion if needed. The source and -// destination are always D3D-style BGRA. -// -// ---------------------------------------------------------------------------- - -WWINLINE void BitmapHandlerClass::Copy_Pixel( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp) -{ - // Color space conversion needed? - - if (dest_format==src_format) { - switch (dest_format) { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - *(unsigned*)dest_ptr=*(unsigned*)src_ptr; - break; - case WW3D_FORMAT_R8G8B8: - *dest_ptr++=src_ptr[0]; - *dest_ptr++=src_ptr[1]; - *dest_ptr++=src_ptr[2]; - break; - case WW3D_FORMAT_A4R4G4B4: - { - unsigned short tmp=*(unsigned short*)src_ptr; - *(unsigned short*)dest_ptr=((tmp&0x000f)<<12)|((tmp&0x00f0)<<4)|((tmp&0x0f00)>>4)|((tmp&0xf000)>>12); - } - break; - case WW3D_FORMAT_A1R5G5B5: - { - unsigned short tmp=*(unsigned short*)src_ptr; - *(unsigned short*)dest_ptr=((tmp&0x001f)<<11)|((tmp&0x03e0)<<1)|((tmp&0x7c00)>>9)|((tmp&0x8000)>>15); - } - break; - case WW3D_FORMAT_R5G6B5: - { - unsigned short tmp=*(unsigned short*)src_ptr; - *(unsigned short*)dest_ptr=((tmp&0x001f)<<11)|(tmp&0x07e0)|((tmp&0xf800)>>11); - } - break; - case WW3D_FORMAT_R3G3B2: - case WW3D_FORMAT_L8: - case WW3D_FORMAT_A8: *dest_ptr++=*src_ptr++; - break; - case WW3D_FORMAT_P8: // Paletted destinations not supported - default: Bitmap_Assert(0); break; - } - } - else { - unsigned b8g8r8a8; - Read_B8G8R8A8(b8g8r8a8,src_ptr,src_format,palette,palette_bpp); - Write_B8G8R8A8(dest_ptr,dest_format,b8g8r8a8); - } -} - -// ---------------------------------------------------------------------------- -// -// Copy pixel with HSV shift. The source and destination are always D3D-style BGRA. -// -// ---------------------------------------------------------------------------- - -WWINLINE void BitmapHandlerClass::Copy_Pixel( - unsigned char* dest_ptr, - WW3DFormat dest_format, - const unsigned char* src_ptr, - WW3DFormat src_format, - const unsigned char* palette, - unsigned palette_bpp, - const Vector3& hsv_shift) -{ - unsigned b8g8r8a8; - Read_B8G8R8A8(b8g8r8a8,src_ptr,src_format,palette,palette_bpp); - Recolor(b8g8r8a8,hsv_shift); - Write_B8G8R8A8(dest_ptr,dest_format,b8g8r8a8); -} - -WWINLINE unsigned BitmapHandlerClass::Combine_A8R8G8B8( - unsigned bgra1, - unsigned bgra2, - unsigned bgra3, - unsigned bgra4) -{ - bgra1&=0xfcfcfcfc; - bgra2&=0xfcfcfcfc; - bgra3&=0xfcfcfcfc; - bgra4&=0xfcfcfcfc; - bgra1>>=2; - bgra2>>=2; - bgra3>>=2; - bgra4>>=2; - bgra1+=bgra2; - bgra3+=bgra4; - bgra1+=bgra3; - return bgra1; -} - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp index 0b5ca708de..fa7c3850fa 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bmp2d.cpp @@ -213,12 +213,12 @@ Bitmap2DObjClass::Bitmap2DObjClass //Set_Aspect(resh/(float)resw); // Find the dimensions of the texture: - SurfaceClass::SurfaceDescription sd; - texture->Get_Level_Description(sd); +// SurfaceClass::SurfaceDescription sd; +// texture->Get_Level_Description(sd); // convert image width and image height to normalized values - float vw = (float) sd.Width / (float)resw; - float vh = (float) sd.Height / (float)resh; + float vw = (float) texture->Get_Width() / (float)resw; + float vh = (float) texture->Get_Height() / (float)resh; // if we requested the image to be centered around a point adjust the // coordinates accordingly. @@ -236,7 +236,7 @@ Bitmap2DObjClass::Bitmap2DObjClass if (additive) { shader = ShaderClass::_PresetAdditive2DShader; } else { - if (ignore_alpha == false && Has_Alpha(sd.Format)) { + if (ignore_alpha == false && Has_Alpha(texture->Get_Texture_Format())) { shader = ShaderClass::_PresetAlpha2DShader; } else { shader = ShaderClass::_PresetOpaque2DShader; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bwrender.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bwrender.cpp deleted file mode 100644 index 75fcf1ffe0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bwrender.cpp +++ /dev/null @@ -1,242 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d2 * - * * - * $Archive:: /Commando/Code/ww3d2/bwrender.cpp $* - * * - * Original Author:: Jani Penttinen * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 4/04/01 10:14a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "bwrender.h" -#include "vp.h" -#include - - -BWRenderClass::Buffer::Buffer(unsigned char* buffer_, int scale_) - : - buffer(buffer_), - scale(scale_), - minv(3), - maxv(scale_-3) -{ -} - -BWRenderClass::Buffer::~Buffer() -{ -} - -void BWRenderClass::Buffer::Set_H_Line(int start_x, int end_x, int y) -{ - if (y=maxv || end_x=maxv) return; - if (start_x=maxv) end_x=maxv-1; - unsigned char* ptr=buffer+scale*y+start_x; - int w=end_x-start_x; - if (w) { - ::memset(ptr,0x00,w); - -/* // Blurring (test) - *(ptr-1)&=0x80; - *(ptr-2)&=0xc0; - *(ptr+w)&=0x80; - *(ptr+w+1)&=0xc0; - for (int a=0;a(vertices), - half_scale, - half_scale, - count*2); -} - -// -------------------------------------------------------------------- - -static inline bool Cull( - const Vector2& c1, - const Vector2& c2, - const Vector2& c3) -{ - float x1=c2[0]-c1[0]; - float y1=c2[1]-c1[1]; - float x2=c3[0]-c1[0]; - float y2=c3[1]-c1[1]; - float r=x1*y2-x2*y1; - if (r<0) return false; - return true; -} - -void BWRenderClass::Render_Triangle_Strip(const unsigned long* indices,int index_count) -{ - index_count-=2; - bool b=false; - for (int n=0;nx_step_2) { - float t=x_step_1; - x_step_1=x_step_2; - x_step_2=t; - } - - while (ycnt>0) { - pixel_buffer.Set_H_Line(WWMath::Float_To_Long(x_left),WWMath::Float_To_Long(x_right),y); - - x_left+=x_step_1; - x_right+=x_step_2; - ycnt--; - y++; - } - } - else { - if (xcf[0]0) { - pixel_buffer.Set_H_Line(WWMath::Float_To_Long(x_left),WWMath::Float_To_Long(x_right),y); - x_left+=x_step_1; - x_right+=x_step_2; - ycnt--; - y++; - } - } - -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bwrender.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/bwrender.h deleted file mode 100644 index a281b7c7f1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/bwrender.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d2 * - * * - * $Archive:: /Commando/Code/ww3d2/bwrender.h $* - * * - * Original Author:: Jani Penttinen * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 4/04/01 10:36a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef BWRENDER_H -#define BWRENDER_H - - -#include "always.h" -#include "vector2.h" -#include "vector3.h" -#include "Vector3i.h" - -/** -** BWRenderClass -** This class implements a simple black-and-white triangle rasterizer which -** can be used to generate shadow textures. It is faster than a general purpose -** software renderer due to the fact that no z-buffering or sorting is needed and -** texturing isn't supported. -** (gth) 04/02/2001 - I'm going to add render-to-texture code to Renegade so this -** class may be obsolete. -*/ -class BWRenderClass -{ - // Internal pixel buffer used by the triangle renderer - // The buffer is not allocated or freed by this class. - class Buffer - { - unsigned char* buffer; - int scale; - int minv; - int maxv; - public: - Buffer(unsigned char* buffer, int scale); - ~Buffer(); - - void Set_H_Line(int start_x, int end_x, int y); - void Fill(unsigned char c); - inline int Scale() const { return scale; } - } pixel_buffer; - - Vector2* vertices; - - void Render_Preprocessed_Triangle(Vector3& xcf,Vector3i& yci); - -public: - BWRenderClass(unsigned char* buffer, int scale); - ~BWRenderClass(); - - void Fill(unsigned char c); - void Set_Vertex_Locations(Vector2* vertices,int count); // Warning! Contents are modified! - void Render_Triangles(const unsigned long* indices,int index_count); - void Render_Triangle_Strip(const unsigned long* indices,int index_count); -}; - - -#endif //BWRENDER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/classid.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/classid.h deleted file mode 100644 index 11e87ddcd4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/classid.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /Commando/Code/ww3d2/classid.h $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 3/29/01 1:13a $* - * * - * $Revision:: 2 $* - * * - *-------------------------------------------------------------------------*/ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CLASSID_H -#define CLASSID_H - -#include "always.h" - -/* -** enum of all the WW3D class IDs. -*/ -enum -{ - ID_INDIRECT_TEXTURE_CLASS = 0x10000, // IndirectTextureClass "texture.h" - ID_VARIABLE_TEXTURE_CLASS, // VariableTextureClass "texture.h" - ID_FILE_LIST_TEXTURE_CLASS, // FileListTextureClass "texture.h" - ID_RESIZEABLE_TEXTURE_INSTANCE_CLASS, // ResizeableTextureInstanceClass "texture.h" - ID_ANIM_TEXTURE_INSTANCE_CLASS, // AnimTextureInstanceClass "texture.h" - ID_MANUAL_ANIM_TEXTURE_INSTANCE_CLASS, // ManualAnimTextureInstanceClass "texture.h" - ID_TIME_ANIM_TEXTURE_INSTANCE_CLASS, // TimeAnimTextureInstanceClass "texture.h" - ID_POINT_GROUP_CLASS, // PointGroupClass "pointgr.h" - ID_MESH_MODEL_CLASS, // MeshModelClass "mesh.cpp" - ID_CACHED_TEXTURE_FILE_CLASS, // CachedTextureFileClass "assetmgr.cpp" - ID_STREAMING_TEXTURE_CLASS, // StreamingTextureClass "texture.h" - ID_STREAMING_TEXTURE_INSTANCE_CLASS, // StreamingTextureInstanceClass "texture.h" -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/collect.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/collect.cpp deleted file mode 100644 index 619fcb371a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/collect.cpp +++ /dev/null @@ -1,1109 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/collect.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CollectionClass::CollectionClass -- default constructor for collection render object * - * CollectionClass::CollectionClass -- constructor for collection render object * - * CollectionClass::CollectionClass -- copy constructor * - * CollectionClass::CollectionClass -- assignment operator * - * CollectionClass::~CollectionClass -- destructor * - * CollectionClass::Clone -- virtual copy constructor * - * CollectionClass::Free -- releases all assets in use by this collection * - * CollectionClass::Class_ID -- returns class id for collection render objects * - * CollectionClass::Get_Num_Polys -- returns the number of polygons in this collection * - * CollectionClass::Render -- render this collection * - * CollectionClass::Special_Render -- passes the special render call to all sub-objects * - * CollectionClass::Set_Transform -- set the transform for this collection * - * CollectionClass::Set_Position -- set the position for this collection * - * CollectionClass::Get_Num_Sub_Objects -- returns the number of sub objects * - * CollectionClass::Get_Sub_Object -- returns a pointer to the desired sub object * - * CollectionClass::Add_Sub_Object -- adds another object into this collection * - * CollectionClass::Remove_Sub_Object -- removes a sub object from this collection * - * CollectionClass::Cast_Ray -- passes the ray test to each sub object * - * CollectionClass::Cast_AABox -- passes the axis-aligned box test to each sub object * - * CollectionClass::Cast_OBBox -- passes the oriented box test to each sub object * - * CollectionClass::Intersect_AABox -- test for intersection with an AABox * - * CollectionClass::Intersect_OBBox -- test for intersection with an OBBox * - * CollectionClass::Get_Obj_Space_Bounding_Sphere -- returns the object space bounding spher * - * CollectionClass::Get_Obj_Space_Bounding_Box -- returns the object-space bounding box * - * CollectionClass::Snap_Point_Count -- returns the number of snap points in this collecion * - * CollectionClass::Get_Snap_Point -- return the desired snap point * - * CollectionClass::Scale -- scale the objects in this collection * - * CollectionClass::Scale -- scale the objects in this collection * - * CollectionClass::Update_Obj_Space_Bounding_Volumes -- recomputes the object space boundin * - * CollectionClass::Update_Sub_Object_Transforms -- recomputes all sub object transforms * - * CollectionLoaderClass::Load -- reads a collection from a w3d file * - * CollectionDefClass::CollectionDefClass -- constructor * - * CollectionDefClass::~CollectionDefClass -- destructor for collection definition * - * CollectionDefClass::Free -- releases assets in use by a collection definition * - * CollectionDefClass::Get_Name -- returns name of the collection * - * CollectionDefClass::Load -- loads a collection definition from a w3d file * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "collect.h" -#include "chunkio.h" -#include "camera.h" -#include "wwdebug.h" -#include "snapPts.h" -#include "assetmgr.h" -#include "ww3d.h" -#include "w3derr.h" -//#include "sr.hpp" - - -CollectionLoaderClass _CollectionLoader; - -/* -** CollectionDefClass. This is the "blueprint" for a collection object -** The asset manager will store these until someone actually asks it to -** create an instance of the collection object -*/ -class CollectionDefClass -{ -public: - - CollectionDefClass(void); - ~CollectionDefClass(void); - - const char * Get_Name(void) const; - WW3DErrorType Load(ChunkLoadClass & cload); - -protected: - - void Free(void); - - char Name[W3D_NAME_LEN]; - DynamicVectorClass ObjectNames; - SnapPointsClass * SnapPoints; - - DynamicVectorClass ProxyList; - - friend class CollectionClass; -}; - - -/* -** CollectionPrototypeClass this is the render object prototype for -** Collections. -*/ -class CollectionPrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(CollectionPrototypeClass) -public: - CollectionPrototypeClass(CollectionDefClass * def) { ColDef = def; WWASSERT(ColDef); } - - virtual const char * Get_Name(void) const { return ColDef->Get_Name(); } - virtual int Get_Class_ID(void) const { return RenderObjClass::CLASSID_COLLECTION; } - virtual RenderObjClass * Create(void) { return NEW_REF( CollectionClass, (*ColDef)); } - virtual void DeleteSelf() { delete this; } - - CollectionDefClass * ColDef; - -protected: - virtual ~CollectionPrototypeClass(void) { delete ColDef; } -}; - - -/*********************************************************************************************** - * CollectionClass::CollectionClass -- default constructor for collection render object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 23/8/00 GTH : Created. * - *=============================================================================================*/ -CollectionClass::CollectionClass(void) : - SnapPoints(NULL) -{ - Update_Obj_Space_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * CollectionClass::CollectionClass -- constructor for collection render object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -CollectionClass::CollectionClass(const CollectionDefClass & def) : - SubObjects(def.ObjectNames.Count()), - SnapPoints(NULL) -{ - // Set our name - Set_Name (def.Get_Name ()); - - // create the sub objects - SubObjects.Resize(def.ObjectNames.Count()); - for (int i=0; iCreate_Render_Obj(def.ObjectNames[i])); - SubObjects[i]->Set_Container(this); - } - - // Copy the list of placeholder objects from the definition - ProxyList = def.ProxyList; - - // grab ahold of the snap points. - SnapPoints = def.SnapPoints; - if (SnapPoints) SnapPoints->Add_Ref(); - - // set up our collision typeas the union of all of our sub-objects - Update_Sub_Object_Bits(); - - // update the object bounding volumes - Update_Obj_Space_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * CollectionClass::CollectionClass -- copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -CollectionClass::CollectionClass(const CollectionClass & src) : - CompositeRenderObjClass(src), - SubObjects(src.SubObjects.Count()), - SnapPoints(NULL) -{ - *this = src; -} - - -/*********************************************************************************************** - * CollectionClass::CollectionClass -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -CollectionClass & CollectionClass::operator = (const CollectionClass & that) -{ - if (this != &that) { - Free(); - CompositeRenderObjClass::operator = (that); - - SubObjects.Resize(that.SubObjects.Count()); - for (int i=0; iClone()); - SubObjects[i]->Set_Container(this); - } - - // Copy the list of placeholder objects from the definition - ProxyList = that.ProxyList; - - SnapPoints = that.SnapPoints; - if (SnapPoints) SnapPoints->Add_Ref(); - - Update_Sub_Object_Bits(); - Update_Obj_Space_Bounding_Volumes(); - } - return * this; -} - - -/*********************************************************************************************** - * CollectionClass::~CollectionClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -CollectionClass::~CollectionClass(void) -{ - Free(); -} - - -/*********************************************************************************************** - * CollectionClass::Clone -- virtual copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -RenderObjClass * CollectionClass::Clone(void) const -{ - return NEW_REF( CollectionClass, (*this)); -} - - -/*********************************************************************************************** - * CollectionClass::Free -- releases all assets in use by this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Free(void) -{ - for (int i=0; iSet_Container(NULL); - SubObjects[i]->Release_Ref(); - SubObjects[i] = NULL; - } - SubObjects.Delete_All(); - ProxyList.Delete_All (); - - REF_PTR_RELEASE(SnapPoints); -} - - -/*********************************************************************************************** - * CollectionClass::Class_ID -- returns class id for collection render objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -int CollectionClass::Class_ID(void) const -{ - return RenderObjClass::CLASSID_COLLECTION; -} - - -/*********************************************************************************************** - * CollectionClass::Get_Num_Polys -- returns the number of polygons in this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -int CollectionClass::Get_Num_Polys(void) const -{ - int pcount = 0; - for (int i=0; iGet_Num_Polys(); - } - return pcount; -} - - -/*********************************************************************************************** - * CollectionClass::Render -- render this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Render(RenderInfoClass & rinfo) -{ - if (Is_Not_Hidden_At_All() == false) { - return; - } - - if (Are_Sub_Object_Transforms_Dirty()) { - Update_Sub_Object_Transforms(); - } - - for (int i=0; iRender(rinfo); - } -} - - -/*********************************************************************************************** - * CollectionClass::Special_Render -- passes the special render call to all sub-objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/2/99 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Special_Render(SpecialRenderInfoClass & rinfo) -{ - if (Is_Not_Hidden_At_All() == false) { - return; - } - - if (Are_Sub_Object_Transforms_Dirty()) { - Update_Sub_Object_Transforms(); - } - - for (int i=0; iSpecial_Render(rinfo); - } -} - -/*********************************************************************************************** - * CollectionClass::Set_Transform -- set the transform for this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Set_Transform(const Matrix3D &m) -{ - RenderObjClass::Set_Transform(m); - Set_Sub_Object_Transforms_Dirty(true); -} - - -/*********************************************************************************************** - * CollectionClass::Set_Position -- set the position for this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Set_Position(const Vector3 &v) -{ - RenderObjClass::Set_Position(v); - Set_Sub_Object_Transforms_Dirty(true); -} - - -/*********************************************************************************************** - * CollectionClass::Get_Num_Sub_Objects -- returns the number of sub objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -int CollectionClass::Get_Num_Sub_Objects(void) const -{ - return SubObjects.Count(); -} - - -/*********************************************************************************************** - * CollectionClass::Get_Sub_Object -- returns a pointer to the desired sub object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -RenderObjClass * CollectionClass::Get_Sub_Object(int index) const -{ - if (SubObjects[index]) { - SubObjects[index]->Add_Ref(); - } - return SubObjects[index]; -} - - -/*********************************************************************************************** - * CollectionClass::Add_Sub_Object -- adds another object into this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -int CollectionClass::Add_Sub_Object(RenderObjClass * subobj) -{ - WWASSERT(subobj); - subobj->Add_Ref(); - subobj->Set_Container(this); - subobj->Set_Transform(Transform); - int res = SubObjects.Add(subobj); - Update_Sub_Object_Bits(); - Update_Obj_Space_Bounding_Volumes(); - if (Is_In_Scene()) { - subobj->Notify_Added(Scene); - } - return res; -} - - -/*********************************************************************************************** - * CollectionClass::Remove_Sub_Object -- removes a sub object from this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -int CollectionClass::Remove_Sub_Object(RenderObjClass * robj) -{ - if (robj == NULL) return 0; - - int res = 0; - - Matrix3D tm = Get_Transform(); - - for (int i=0; iNotify_Removed(Scene); - } - SubObjects[i]->Set_Container(NULL); - SubObjects[i]->Set_Transform(tm); - SubObjects[i]->Release_Ref(); - res = SubObjects.Delete(i); - break; - } - } - - if (res != 0) { - Update_Sub_Object_Bits(); - Update_Obj_Space_Bounding_Volumes(); - } - - return res; -} - - -/*********************************************************************************************** - * CollectionClass::Cast_Ray -- passes the ray test to each sub object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -bool CollectionClass::Cast_Ray(RayCollisionTestClass & raytest) -{ - bool res = false; - for (int i=0; iCast_Ray(raytest); - } - return res; -} - - -/*********************************************************************************************** - * CollectionClass::Cast_AABox -- passes the axis-aligned box test to each sub object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -bool CollectionClass::Cast_AABox(AABoxCollisionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iCast_AABox(boxtest); - } - return res; -} - - -/*********************************************************************************************** - * CollectionClass::Cast_OBBox -- passes the oriented box test to each sub object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -bool CollectionClass::Cast_OBBox(OBBoxCollisionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iCast_OBBox(boxtest); - } - return res; -} - - -/*********************************************************************************************** - * CollectionClass::Intersect_AABox -- test for intersection with an AABox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -bool CollectionClass::Intersect_AABox(AABoxIntersectionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iIntersect_AABox(boxtest); - } - return res; -} - - -/*********************************************************************************************** - * CollectionClass::Intersect_OBBox -- test for intersection with an OBBox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -bool CollectionClass::Intersect_OBBox(OBBoxIntersectionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iIntersect_OBBox(boxtest); - } - return res; -} - -/*********************************************************************************************** - * CollectionClass::Get_Obj_Space_Bounding_Sphere -- returns the object space bounding sphere. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - sphere = BoundSphere; -} - - -/*********************************************************************************************** - * CollectionClass::Get_Obj_Space_Bounding_Box -- returns the object-space bounding box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - box = BoundBox; -} - - -/*********************************************************************************************** - * CollectionClass::Snap_Point_Count -- returns the number of snap points in this collecion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -int CollectionClass::Snap_Point_Count(void) -{ - if (SnapPoints) { - return SnapPoints->Count(); - } else { - return 0; - } -} - - -/*********************************************************************************************** - * CollectionClass::Get_Snap_Point -- return the desired snap point * - * * - * This function will set the passed vector to be equal to the object space coordinates of * - * the desired snap point. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Get_Snap_Point(int index,Vector3 * set) -{ - WWASSERT(set != NULL); - if (SnapPoints) { - *set = (*SnapPoints)[index]; - } else { - set->X = set->Y = set->Z = 0; - } -} - - -/*********************************************************************************************** - * CollectionClass::Scale -- scale the objects in this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Scale(float scale) -{ - for (int i=0; iScale(scale); - } -} - - -/*********************************************************************************************** - * CollectionClass::Scale -- scale the objects in this collection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Scale(float scalex, float scaley, float scalez) -{ - for (int i=0; iScale(scalex,scaley,scalez); - } -} - - -/*********************************************************************************************** - * CollectionClass::Update_Obj_Space_Bounding_Volumes -- recomputes the object space bounding * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Update_Obj_Space_Bounding_Volumes(void) -{ - int i; - if (SubObjects.Count() <= 0) { - BoundSphere = SphereClass(Vector3(0,0,0),0); - BoundBox.Center.Set(0,0,0); - BoundBox.Extent.Set(0,0,0); - return; - } - - Matrix3D tm = Get_Transform(); - Set_Transform(Matrix3D(1)); - - // loop through all sub-objects, combining their bounding spheres. - BoundSphere = SubObjects[0]->Get_Bounding_Sphere(); - for (i=1; i < SubObjects.Count(); i++) { - BoundSphere.Add_Sphere(SubObjects[i]->Get_Bounding_Sphere()); - } - - // loop through the sub-objects, computing a box in the root coordinate - // system which bounds all of the meshes. Note that we've set the - // root coordinate system to identity for this. - MinMaxAABoxClass box(Vector3(FLT_MAX,FLT_MAX,FLT_MAX),Vector3(-FLT_MAX,-FLT_MAX,-FLT_MAX)); - - for (i=0; i < SubObjects.Count(); i++) { - box.Add_Box(SubObjects[i]->Get_Bounding_Box()); - } - - BoundBox.Init(box); - - Invalidate_Cached_Bounding_Volumes(); - - // Now update the object space bounding volumes of this object's container: - RenderObjClass *container = Get_Container(); - if (container) container->Update_Obj_Space_Bounding_Volumes(); - - Set_Transform(tm); -} - - -/*********************************************************************************************** - * CollectionClass::Update_Sub_Object_Transforms -- recomputes all sub object transforms * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionClass::Update_Sub_Object_Transforms(void) -{ - RenderObjClass::Update_Sub_Object_Transforms(); - for (int i=0; iSet_Transform(Transform); - SubObjects[i]->Update_Sub_Object_Transforms(); - } - Set_Sub_Object_Transforms_Dirty(false); -} - - -/*********************************************************************************************** - * CollectionClass::Get_Placeholder -- Returns information about a placeholder object. - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/28/99 PDS : Created. * - *=============================================================================================*/ -bool CollectionClass::Get_Proxy (int index, ProxyClass &proxy) const -{ - bool retval = false; - - if (index >= 0 && index < ProxyList.Count ()) { - - // - // Return the proxy information to the caller - // - proxy = ProxyList[index]; - retval = true; - } - - return retval; -} - - -/*********************************************************************************************** - * CollectionClass::Get_Proxy_Count -- Returns the count of proxy objects in the collection. - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/28/99 PDS : Created. * - *=============================================================================================*/ -int CollectionClass::Get_Proxy_Count (void) const -{ - return ProxyList.Count (); -} - - -/*********************************************************************************************** - * CollectionDefClass::CollectionDefClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -CollectionDefClass::CollectionDefClass(void) -{ - SnapPoints = NULL; -} - - -/*********************************************************************************************** - * CollectionDefClass::~CollectionDefClass -- destructor for collection definition * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -CollectionDefClass::~CollectionDefClass(void) -{ - Free(); -} - - -/*********************************************************************************************** - * CollectionDefClass::Free -- releases assets in use by a collection definition * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -void CollectionDefClass::Free(void) -{ - for (int i=0; i 0); - char * name = W3DNEWARRAY char [cload.Cur_Chunk_Length()]; - cload.Read(name,cload.Cur_Chunk_Length()); - ObjectNames.Add(name); - break; - } - - case W3D_CHUNK_PLACEHOLDER: - { - // Read the placeholder information from the chunk - WWASSERT(cload.Cur_Chunk_Length() > 0); - W3dPlaceholderStruct info; - cload.Read(&info, sizeof (info)); - - // Read the placeholder name from the chunk - char *name = W3DNEWARRAY char[info.name_len + 1]; - cload.Read(name, info.name_len); - name[info.name_len] = 0; - - // Create a matrix from the data in the chunk - Matrix3D transform (info.transform[0][0], info.transform[1][0], info.transform[2][0], info.transform[3][0], - info.transform[0][1], info.transform[1][1], info.transform[2][1], info.transform[3][1], - info.transform[0][2], info.transform[1][2], info.transform[2][2], info.transform[3][2]); - - // Add this placeholder to our list - ProxyList.Add (ProxyClass (name, transform)); - - // Free the name array - delete [] name; - break; - } - - case W3D_CHUNK_POINTS: - SnapPoints = NEW_REF(SnapPointsClass, ()); - SnapPoints->Load_W3D(cload); - break; - } - - cload.Close_Chunk(); - } - - return WW3D_ERROR_OK; - -Error: - - return WW3D_ERROR_LOAD_FAILED; -} - -/*********************************************************************************************** - * CollectionLoaderClass::Load -- reads a collection from a w3d file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -PrototypeClass * CollectionLoaderClass::Load_W3D(ChunkLoadClass & cload) -{ - CollectionDefClass * def = W3DNEW CollectionDefClass; - - if (def == NULL) { - return NULL; - } - - if (def->Load(cload) != WW3D_ERROR_OK) { - - // load failed, delete the model and return an error - delete def; - return NULL; - - } else { - - // ok, accept this model! - CollectionPrototypeClass * proto = W3DNEW CollectionPrototypeClass(def); - return proto; - - } -} - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/collect.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/collect.h deleted file mode 100644 index 57d3fe87f1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/collect.h +++ /dev/null @@ -1,149 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/collect.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLLECT_H -#define COLLECT_H - -#include "rendobj.h" -#include "composite.h" -#include "Vector.H" -#include "proto.h" -#include "w3d_file.h" -#include "wwstring.h" -#include "proxy.h" - -class CollectionDefClass; -class SnapPointsClass; - - -/* -** CollectionClass -** This is a render object which contains a collection of render objects. -*/ -class CollectionClass : public CompositeRenderObjClass -{ -public: - - CollectionClass(void); - CollectionClass(const CollectionDefClass & def); - CollectionClass(const CollectionClass & src); - CollectionClass & operator = (const CollectionClass &); - virtual ~CollectionClass(void); - virtual RenderObjClass * Clone(void) const; - - virtual int Class_ID(void) const; - virtual int Get_Num_Polys(void) const; - - ///////////////////////////////////////////////////////////////////////////// - // Proxy interface - ///////////////////////////////////////////////////////////////////////////// - virtual int Get_Proxy_Count (void) const; - virtual bool Get_Proxy (int index, ProxyClass &proxy) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Rendering - ///////////////////////////////////////////////////////////////////////////// - virtual void Render(RenderInfoClass & rinfo); - virtual void Special_Render(SpecialRenderInfoClass & rinfo); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - "Scene Graph" - ///////////////////////////////////////////////////////////////////////////// - virtual void Set_Transform(const Matrix3D &m); - virtual void Set_Position(const Vector3 &v); - virtual int Get_Num_Sub_Objects(void) const; - virtual RenderObjClass * Get_Sub_Object(int index) const; - virtual int Add_Sub_Object(RenderObjClass * subobj); - virtual int Remove_Sub_Object(RenderObjClass * robj); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Collision Detection, Ray Tracing - ///////////////////////////////////////////////////////////////////////////// - virtual bool Cast_Ray(RayCollisionTestClass & raytest); - virtual bool Cast_AABox(AABoxCollisionTestClass & boxtest); - virtual bool Cast_OBBox(OBBoxCollisionTestClass & boxtest); - virtual bool Intersect_AABox(AABoxIntersectionTestClass & boxtest); - virtual bool Intersect_OBBox(OBBoxIntersectionTestClass & boxtest); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Bounding Volumes - ///////////////////////////////////////////////////////////////////////////// - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Attributes, Options, Properties, etc - ///////////////////////////////////////////////////////////////////////////// - virtual int Snap_Point_Count(void); - virtual void Get_Snap_Point(int index,Vector3 * set); - virtual void Scale(float scale); - virtual void Scale(float scalex, float scaley, float scalez); - virtual void Update_Obj_Space_Bounding_Volumes(void); - -protected: - - void Free(void); - void Update_Sub_Object_Transforms(void); - - DynamicVectorClass ProxyList; - DynamicVectorClass SubObjects; - SnapPointsClass * SnapPoints; - - SphereClass BoundSphere; - AABoxClass BoundBox; -}; - - -/* -** CollectionLoaderClass -** Loader for collection objects -*/ -class CollectionLoaderClass : public PrototypeLoaderClass -{ -public: - - virtual int Chunk_Type(void) { return W3D_CHUNK_COLLECTION; } - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload); -}; - -extern CollectionLoaderClass _CollectionLoader; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/colorspace.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/colorspace.h deleted file mode 100644 index 65b960e162..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/colorspace.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Colorspace * - * * - * $Archive:: $* - * * - * Original Author:: Hector Yee * - * * - * $Author:: $* - * * - * $Modtime:: $* - * * - * $Revision:: $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLORSPACE_H -#define COLORSPACE_H - -#include "dx8wrapper.h" -#include - -void RGB_To_HSV(Vector3 &hsv,const Vector3 &rgb); -void HSV_To_RGB(Vector3 &rgb, const Vector3 &hsv); -void Recolor(Vector3 &rgb, const Vector3 &hsv_shift); - -//--------------------------------------------------------------------- -// Color Conversions -//--------------------------------------------------------------------- - -inline void RGB_To_HSV(Vector3 &hsv,const Vector3 &rgb) -// modified from Foley et al. page 592 -// converts rgb[0..1] to h [0,360), s and v in [0,1] -// negative h values are to signify undefined -{ - float max=WWMath::Max(rgb.X,rgb.Y); - max=WWMath::Max(max,rgb.Z); - float min=WWMath::Min(rgb.X,rgb.Y); - min=WWMath::Min(min,rgb.Z); - - // value - hsv.Z=max; - - // saturation - hsv.Y=(max!=0.0f)?((max-min)/max):0.0f; - if (hsv.Y==0.0f) hsv.X=-1.0f; - else - { - float delta=max-min; - if (rgb.X==max) - hsv.X=(rgb.Y-rgb.Z)/delta; - else if (rgb.Y==max) - hsv.X=2.0f+ (rgb.Z-rgb.X)/delta; - else if (rgb.Z==max) - hsv.X=4.0f+ (rgb.X-rgb.Y)/delta; - hsv.X*=60.0f; - if (hsv.X<0.0f) hsv.X+=360.0f; - } -} - -inline void HSV_To_RGB(Vector3 &rgb, const Vector3 &hsv) -{ - float h=hsv.X; - float s=hsv.Y; - float v=hsv.Z; - - if (hsv.Y==0.0f) { - rgb.Set(v,v,v); - } else { - float f,p,q,t; - - int i; - - if (h==360.0f) h=0.0f; - - h/=60.0f; - i=WWMath::Floor(h); - f=h-i; - p=v*(1.0f-s); - q=v*(1.0f-(s*f)); - t=v*(1.0f-(s*(1.0f-f))); - switch (i) { - case 0: - rgb.Set(v,t,p); - break; - case 1: - rgb.Set(q,v,p); - break; - case 2: - rgb.Set(p,v,t); - break; - case 3: - rgb.Set(p,q,v); - break; - case 4: - rgb.Set(t,p,v); - break; - case 5: - rgb.Set(v,p,q); - break; - } - } -} - -inline void Recolor(Vector3 &rgb, const Vector3 &hsv_shift) -{ - Vector3 hsv; - RGB_To_HSV(hsv,rgb); - - // If the Hue has the "undefined flag" (a negative value), this means that the color is pure - // monochrome. In this case do not shift the hue (it is undefined) or the saturation (it is 0 - // so it cannot be decreased, and increasing it would cause the undefined hue to actually - // become visible). In this case, we only modify the value. - if (hsv.X<0.0f) hsv+=Vector3(0.0f,0.0f,hsv_shift.Z); - else hsv+=hsv_shift; - - // angular mod - if (hsv.X<0.0f) hsv.X+=360.0f; - if (hsv.X>360.0f) hsv.X-=360.0f; - // clamp saturation and value - hsv.Y=WWMath::Clamp(hsv.Y,0.0f,1.0f); - hsv.Z=WWMath::Clamp(hsv.Z,0.0f,1.0f); - HSV_To_RGB(rgb,hsv); -} - -inline void Recolor(unsigned& rgba, const Vector3 &hsv_shift) -{ - Vector4 rgba_v = DX8Wrapper::Convert_Color(rgba); - Recolor((Vector3&)rgba_v, hsv_shift); - rgba = DX8Wrapper::Convert_Color(rgba_v); -} - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltest.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltest.cpp deleted file mode 100644 index 3282c89e2e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltest.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/coltest.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/07/01 10:26a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "coltest.h" - - -AABoxCollisionTestClass::AABoxCollisionTestClass(const AABoxCollisionTestClass & that) : - CollisionTestClass(that), - Box(that.Box), - Move(that.Move), - SweepMin(that.SweepMin), - SweepMax(that.SweepMax) -{ -} - -AABoxCollisionTestClass::AABoxCollisionTestClass(const AABoxClass & aabox,const Vector3 & move,CastResultStruct * res,int collision_type) : - CollisionTestClass(res,collision_type), - Box(aabox), - Move(move) -{ - SweepMin = Box.Center - Box.Extent; - SweepMax = Box.Center + Box.Extent; - - Vector3 endmin = Box.Center + move - Box.Extent; - Vector3 endmax = Box.Center + move + Box.Extent; - - if (endmax.X > SweepMax.X) SweepMax.X = endmax.X; - if (endmax.Y > SweepMax.Y) SweepMax.Y = endmax.Y; - if (endmax.Z > SweepMax.Z) SweepMax.Z = endmax.Z; - - if (endmin.X < SweepMin.X) SweepMin.X = endmin.X; - if (endmin.Y < SweepMin.Y) SweepMin.Y = endmin.Y; - if (endmin.Z < SweepMin.Z) SweepMin.Z = endmin.Z; -} - - -bool AABoxCollisionTestClass::Cull(const AABoxClass & box) -{ -// const float MOVE_THRESHOLD = 2.0f; -// if (WWMath::Fabs(Move.X) + WWMath::Fabs(Move.Y) + WWMath::Fabs(Move.Z) > MOVE_THRESHOLD) { -// CastResultStruct res; -// return !Box.Cast_To_Box(Move,box,&res); -// } else { - Vector3 min_corner; - Vector3 max_corner; - Vector3::Subtract(box.Center,box.Extent,&min_corner); - Vector3::Add(box.Center,box.Extent,&max_corner); - - if ((SweepMin.X > max_corner.X) || (SweepMax.X < min_corner.X)) { - return true; - } - - if ((SweepMin.Y > max_corner.Y) || (SweepMax.Y < min_corner.Y)) { - return true; - } - - if ((SweepMin.Z > max_corner.Z) || (SweepMax.Z < min_corner.Z)) { - return true; - } - return false; -// } -} - - -void AABoxCollisionTestClass::Rotate(ROTATION_TYPE rotation) -{ - -#ifndef NDEBUG - - int i; - Matrix3D tm(1); - switch(rotation) { - case ROTATE_NONE: - break; - case ROTATE_Z90: - tm = Matrix3D::RotateZ90; - break; - case ROTATE_Z180: - tm = Matrix3D::RotateZ180; - break; - case ROTATE_Z270: - tm = Matrix3D::RotateZ270; - break; - } - -#ifdef ALLOW_TEMPORARIES - Vector3 realcenter = tm * Box.Center; -#else - Vector3 realcenter; - tm.mulVector3(Box.Center, realcenter); -#endif - - Vector3 pts[8]; - Vector3 & min = SweepMin; - Vector3 & max = SweepMax; - - pts[0].Set(min.X,min.Y,min.Z); - pts[1].Set(min.X,max.Y,min.Z); - pts[2].Set(max.X,max.Y,min.Z); - pts[3].Set(max.X,min.Y,min.Z); - - pts[4].Set(min.X,min.Y,max.Z); - pts[5].Set(min.X,max.Y,max.Z); - pts[6].Set(max.X,max.Y,max.Z); - pts[7].Set(max.X,min.Y,max.Z); - -// for (i=0; i<8; i++) { -// pts[i] = tm * pts[i]; -// } - tm.mulVector3Array(pts, 8); - - Vector3 realmin = pts[0]; - Vector3 realmax = pts[0]; - - for (i=1; i<8; i++) { - if (realmin.X >= pts[i].X) realmin.X = pts[i].X; - if (realmin.Y >= pts[i].Y) realmin.Y = pts[i].Y; - if (realmin.Z >= pts[i].Z) realmin.Z = pts[i].Z; - - if (realmax.X <= pts[i].X) realmax.X = pts[i].X; - if (realmax.Y <= pts[i].Y) realmax.Y = pts[i].Y; - if (realmax.Z <= pts[i].Z) realmax.Z = pts[i].Z; - } - - -#endif - - - // rotate the test by the desired rotation about the Z axis, special cased for - // 90 degree rotations about Z. arbitrary rotations cause the axis aligned - // box to not be aligned any more :-) - float tmp,minx,miny,maxx,maxy; - switch(rotation) { - case ROTATE_NONE: - break; - - case ROTATE_Z90: - // rotate the center point and the move vector - tmp = Box.Center.X; Box.Center.X = -Box.Center.Y; Box.Center.Y = tmp; - tmp = Move.X; Move.X = -Move.Y; Move.Y = tmp; - - // swap x and y for the extent - tmp = Box.Extent.X; Box.Extent.X = Box.Extent.Y; Box.Extent.Y = tmp; - - // update sweep bounding box - minx = SweepMin.X; miny = SweepMin.Y; maxx = SweepMax.X; maxy = SweepMax.Y; - SweepMin.X = -maxy; - SweepMin.Y = minx; - SweepMax.X = -miny; - SweepMax.Y = maxx; - break; - - case ROTATE_Z180: - // rotate center and move vector - Box.Center.X = -Box.Center.X; - Box.Center.Y = -Box.Center.Y; - Move.X = -Move.X; - Move.Y = -Move.Y; - - // update min/max boxes - minx = SweepMin.X; miny = SweepMin.Y; maxx = SweepMax.X; maxy = SweepMax.Y; - SweepMin.X = -maxx; - SweepMin.Y = -maxy; - SweepMax.X = -minx; - SweepMax.Y = -miny; - break; - - case ROTATE_Z270: - // rotate center and move. - tmp = Box.Center.X; Box.Center.X = Box.Center.Y; Box.Center.Y = -tmp; - tmp = Move.X; Move.X = Move.Y; Move.Y = -tmp; - - // update extent (x and y axis swap) - tmp = Box.Extent.X; Box.Extent.X = Box.Extent.Y; Box.Extent.Y = tmp; - - // update min/max boxes - minx = SweepMin.X; miny = SweepMin.Y; maxx = SweepMax.X; maxy = SweepMax.Y; - SweepMin.X = miny; - SweepMin.Y = -maxx; - SweepMax.X = maxy; - SweepMax.Y = -minx; - break; - } - -#ifndef NDEBUG - - assert((Box.Center - realcenter).Length() < 0.001f); - assert((SweepMin - realmin).Length() < 0.001f); - assert((SweepMax - realmax).Length() < 0.001f); - -#endif -} - - -void AABoxCollisionTestClass::Transform(const Matrix3D & tm) -{ - // NOTE: this function will expand the box to enclose the rotated - // form of the original box. In practice, this function was only - // implemented to double-check the results of the Translate and Rotate - // functions. - int i; - Vector3 tmpcenter = Box.Center; - Vector3 tmpextent = Box.Extent; - tm.Transform_Center_Extent_AABox(tmpcenter,tmpextent,&Box.Center,&Box.Extent); - - Move = tm.Rotate_Vector(Move); - - Vector3 pts[8]; - Vector3 & min = SweepMin; - Vector3 & max = SweepMax; - - pts[0].Set(min.X,min.Y,min.Z); - pts[1].Set(min.X,max.Y,min.Z); - pts[2].Set(max.X,max.Y,min.Z); - pts[3].Set(max.X,min.Y,min.Z); - - pts[4].Set(min.X,min.Y,max.Z); - pts[5].Set(min.X,max.Y,max.Z); - pts[6].Set(max.X,max.Y,max.Z); - pts[7].Set(max.X,min.Y,max.Z); - -// for (i=0; i<8; i++) { -// pts[i] = tm * pts[i]; -// } - tm.mulVector3Array(pts, 8); - - Vector3 realmin = pts[0]; - Vector3 realmax = pts[0]; - - for (i=1; i<8; i++) { - if (realmin.X >= pts[i].X) realmin.X = pts[i].X; - if (realmin.Y >= pts[i].Y) realmin.Y = pts[i].Y; - if (realmin.Z >= pts[i].Z) realmin.Z = pts[i].Z; - - if (realmax.X <= pts[i].X) realmax.X = pts[i].X; - if (realmax.Y <= pts[i].Y) realmax.Y = pts[i].Y; - if (realmax.Z <= pts[i].Z) realmax.Z = pts[i].Z; - } - - SweepMin = realmin; - SweepMax = realmax; -} - - - -OBBoxCollisionTestClass::OBBoxCollisionTestClass -( - const OBBoxClass & obbox, - const Vector3 & move, - CastResultStruct * res, - int type -) : - CollisionTestClass(res,type), - Box(obbox), - Move(move) -{ - Vector3 max_extent; - max_extent.X = WWMath::Fabs(Box.Basis[0][0] * Box.Extent.X) + - WWMath::Fabs(Box.Basis[0][1] * Box.Extent.Y) + - WWMath::Fabs(Box.Basis[0][2] * Box.Extent.Z) + 0.01f; - - max_extent.Y = WWMath::Fabs(Box.Basis[1][0] * Box.Extent.X) + - WWMath::Fabs(Box.Basis[1][1] * Box.Extent.Y) + - WWMath::Fabs(Box.Basis[1][2] * Box.Extent.Z) + 0.01f; - - max_extent.Z = WWMath::Fabs(Box.Basis[2][0] * Box.Extent.X) + - WWMath::Fabs(Box.Basis[2][1] * Box.Extent.Y) + - WWMath::Fabs(Box.Basis[2][2] * Box.Extent.Z) + 0.01f; - - SweepMin = Box.Center - max_extent; - SweepMax = Box.Center + max_extent; - - Vector3 endmin = Box.Center + move - max_extent; - Vector3 endmax = Box.Center + move + max_extent; - - if (endmax.X > SweepMax.X) SweepMax.X = endmax.X; - if (endmax.Y > SweepMax.Y) SweepMax.Y = endmax.Y; - if (endmax.Z > SweepMax.Z) SweepMax.Z = endmax.Z; - - if (endmin.X < SweepMin.X) SweepMin.X = endmin.X; - if (endmin.Y < SweepMin.Y) SweepMin.Y = endmin.Y; - if (endmin.Z < SweepMin.Z) SweepMin.Z = endmin.Z; -} - -OBBoxCollisionTestClass::OBBoxCollisionTestClass(const OBBoxCollisionTestClass & that) : - CollisionTestClass(that), - Box(that.Box), - Move(that.Move), - SweepMin(that.SweepMin), - SweepMax(that.SweepMax) -{ -} - -OBBoxCollisionTestClass::OBBoxCollisionTestClass -( - const OBBoxCollisionTestClass & that, - const Matrix3D & tm -) : - CollisionTestClass(that) -{ - tm.Transform_Min_Max_AABox(that.SweepMin,that.SweepMax,&SweepMin,&SweepMax); - Matrix3D::Rotate_Vector(tm,that.Move,&Move); - OBBoxClass::Transform(tm,that.Box,&Box); -} - -OBBoxCollisionTestClass::OBBoxCollisionTestClass -( - const AABoxCollisionTestClass & that, - const Matrix3D & tm -) : - CollisionTestClass(that) -{ - tm.Transform_Min_Max_AABox(that.SweepMin,that.SweepMax,&SweepMin,&SweepMax); - Matrix3D::Rotate_Vector(tm,that.Move,&Move); - Matrix3D::Transform_Vector(tm,that.Box.Center,&(Box.Center)); - Box.Extent = that.Box.Extent; - Box.Basis = tm; // copies the 3x3 rotation portion of the transform -} - - -bool OBBoxCollisionTestClass::Cull(const AABoxClass & box) -{ - Vector3 min_corner; - Vector3 max_corner; - Vector3::Subtract(box.Center,box.Extent,&min_corner); - Vector3::Add(box.Center,box.Extent,&max_corner); - - if ((SweepMin.X > max_corner.X) || (SweepMax.X < min_corner.X)) { - return true; - } - - if ((SweepMin.Y > max_corner.Y) || (SweepMax.Y < min_corner.Y)) { - return true; - } - - if ((SweepMin.Z > max_corner.Z) || (SweepMax.Z < min_corner.Z)) { - return true; - } - return false; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltest.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltest.h deleted file mode 100644 index f406ecbb08..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltest.h +++ /dev/null @@ -1,317 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /VSS_Sync/ww3d2/coltest.h $* - * * - * Org Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 07/01/02 12:45p $* - * * - * $Revision:: 5 $* - * * - * 07/01/02 KM Coltype enum change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLTEST_H -#define COLTEST_H - -#include "always.h" -#include "castres.h" -#include "lineseg.h" -#include "aabox.h" -#include "obbox.h" -#include "tri.h" -#include "colmath.h" -#include "coltype.h" - -class RenderObjClass; - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// CollisionTestClass -// -// Each type of collision test will have an associated class which -// ties together all of the information necessary for the test. -// These classes also provide a perfect place to add any information -// which can be pre-calculated. -// -// The base class: CollisionTestClass simply contains a pointer to -// the user's CastResultStruct which will contain the results of -// the collision test. I store a pointer to a result structure -// because in some cases, new CollisionTestClasses are created in -// the process of checking (e.g. if the test needs to be transformed -// into another coordinate system) and I did not want to be -// constantly copying the result structure around. So, the user -// must allocate a result structure (usually on the stack) and keep it -// until the CollisionTestClass is discarded. -// -// Every CollisionTestClass should have the following functions: -// -// bool Cull(const Vector3 & min,const Vector3 & max); -// bool Cull(const AABoxClass & box); -// bool Cast_To_Triangle(const TriClass & tri); -// -// These are not virtual because I don't want to pay the price of virtual function -// calls at the point in the code where these are used. It may be possible to -// write template functions if we use these exact function prototpyes for all -// collision test classes though. -// -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class CollisionTestClass -{ -public: - CollisionTestClass(CastResultStruct * res,int collision_type); - CollisionTestClass(const CollisionTestClass & that); - -public: - CastResultStruct * Result; - int CollisionType; - RenderObjClass * CollidedRenderObj; -}; - - -inline CollisionTestClass::CollisionTestClass(CastResultStruct * res,int collision_type) : - Result(res), - CollisionType(collision_type), - CollidedRenderObj(NULL) -{ -} - -inline CollisionTestClass::CollisionTestClass(const CollisionTestClass & that) : - Result(that.Result), - CollisionType(that.CollisionType), - CollidedRenderObj(that.CollidedRenderObj) -{ -} - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// RayCollisionTestClass -// -// Contains a linesegment to be tested and of course the inherited -// pointer to a CollisionStruct for the result -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class RayCollisionTestClass : public CollisionTestClass -{ -public: - - RayCollisionTestClass(const LineSegClass & ray,CastResultStruct * res,int collision_type = COLL_TYPE_0,bool check_translucent=false, bool check_hidden=false); - RayCollisionTestClass(const RayCollisionTestClass & raytest,const Matrix3D & tm); - - bool Cull(const Vector3 & min,const Vector3 & max); - bool Cull(const AABoxClass & box); - bool Cast_To_Triangle(const TriClass & tri); - -public: - - LineSegClass Ray; - bool CheckTranslucent; - bool CheckHidden; - -private: - - // not implemented - RayCollisionTestClass(const RayCollisionTestClass &); - RayCollisionTestClass & operator = (const RayCollisionTestClass &); - -}; - - -inline RayCollisionTestClass::RayCollisionTestClass(const LineSegClass & ray,CastResultStruct * res,int collision_type,bool check_translucent, bool check_hidden) : - CollisionTestClass(res,collision_type), - Ray(ray), - CheckTranslucent(check_translucent), - CheckHidden(check_hidden) -{ -} - -inline RayCollisionTestClass::RayCollisionTestClass(const RayCollisionTestClass & raytest,const Matrix3D & tm) : - CollisionTestClass(raytest), - Ray(raytest.Ray,tm), - CheckTranslucent(raytest.CheckTranslucent), - CheckHidden(raytest.CheckHidden) -{ -} - -inline bool RayCollisionTestClass::Cull(const Vector3 & min,const Vector3 & max) -{ - return (CollisionMath::Overlap_Test(min,max,Ray) == CollisionMath::POS); -} - -inline bool RayCollisionTestClass::Cull(const AABoxClass & box) -{ - return (CollisionMath::Overlap_Test(box,Ray) == CollisionMath::POS); -} - -inline bool RayCollisionTestClass::Cast_To_Triangle(const TriClass & tri) -{ - return CollisionMath::Collide(Ray,tri,Result); -} - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// AABoxCollisionTestClass -// -// Contains an Axis Aligned Box and a movement vector to be tested -// for collision. Also adds Min and Max vectors both for the initial -// box and for the volume swept out by the box. -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class AABoxCollisionTestClass : public CollisionTestClass -{ -public: - - AABoxCollisionTestClass(const AABoxClass & aabox,const Vector3 & move,CastResultStruct * res,int collision_type = COLL_TYPE_0); - AABoxCollisionTestClass(const AABoxCollisionTestClass & that); - - enum ROTATION_TYPE - { - ROTATE_NONE = 0, - ROTATE_Z90, - ROTATE_Z180, - ROTATE_Z270 - }; - - bool Cull(const Vector3 & min,const Vector3 & max); - bool Cull(const AABoxClass & box); - bool Cast_To_Triangle(const TriClass & tri); - - void Translate(const Vector3 & translation); - void Rotate(ROTATION_TYPE rotation); - void Transform(const Matrix3D & tm); - -public: - - AABoxClass Box; - Vector3 Move; - - Vector3 SweepMin; - Vector3 SweepMax; - -private: - - // not implemented - AABoxCollisionTestClass & operator = (const AABoxCollisionTestClass &); - -}; - - -inline void AABoxCollisionTestClass::Translate(const Vector3 & translation) -{ - // translate the test by the desired translation vector - Box.Center += translation; - SweepMin += translation; - SweepMax += translation; -} - -inline bool AABoxCollisionTestClass::Cull(const Vector3 & min,const Vector3 & max) -{ - if ((SweepMin.X > max.X) || (SweepMax.X < min.X)) { - return true; - } - - if ((SweepMin.Y > max.Y) || (SweepMax.Y < min.Y)) { - return true; - } - - if ((SweepMin.Z > max.Z) || (SweepMax.Z < min.Z)) { - return true; - } - return false; -} - -inline bool AABoxCollisionTestClass::Cast_To_Triangle(const TriClass & tri) -{ - return CollisionMath::Collide(Box,Move,tri,Result); -} - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// OBBoxCollisionTestClass -// -// Contains an Oriented Bounding Box and a movement vector to be tested -// for collision. Also adds Min and Max vectors (axis aligned box) -// both for the initial box and for the volume swept out by the box. -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class OBBoxCollisionTestClass : public CollisionTestClass -{ -public: - - OBBoxCollisionTestClass(const OBBoxClass & obbox,const Vector3 & move,CastResultStruct * res,int type = COLL_TYPE_0); - OBBoxCollisionTestClass(const OBBoxCollisionTestClass & that); - OBBoxCollisionTestClass(const OBBoxCollisionTestClass & that,const Matrix3D & tm); - OBBoxCollisionTestClass(const AABoxCollisionTestClass & that,const Matrix3D & tm); - - bool Cull(const Vector3 & min,const Vector3 & max); - bool Cull(const AABoxClass & box); - bool Cast_To_Triangle(const TriClass & tri); - -public: - - OBBoxClass Box; - Vector3 Move; - Vector3 SweepMin; - Vector3 SweepMax; - -private: - // not implemented - OBBoxCollisionTestClass & operator = (const OBBoxCollisionTestClass &); -}; - - -inline bool OBBoxCollisionTestClass::Cull(const Vector3 & min,const Vector3 & max) -{ - if ((SweepMin.X > max.X) || (SweepMax.X < min.X)) { - return true; - } - - if ((SweepMin.Y > max.Y) || (SweepMax.Y < min.Y)) { - return true; - } - - if ((SweepMin.Z > max.Z) || (SweepMax.Z < min.Z)) { - return true; - } - return false; -} - -inline bool OBBoxCollisionTestClass::Cast_To_Triangle(const TriClass & tri) -{ - return CollisionMath::Collide(Box,Move,tri,Vector3(0,0,0),Result); -} - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltype.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltype.h deleted file mode 100644 index 4047f469d0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/coltype.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/coltype.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 07/01/02 12:45p $* - * * - * $Revision:: 2 $* - * * - * 07/01/02 KM Coltype enum change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef COLTYPE_H -#define COLTYPE_H - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Collision 'Types' -// -// This enum defines the collision type bit-field that is used in render object -// collision detection. -// -// The collision type field in a collision or intersection test is used as a -// low-level collision mask. It will be 'AND'ed with the collision type of -// the render object and will ignore the object unless the result is -// non-zero. In Commando, we use this to implement separate collision -// representations for "physical" collisions versus "projectile" -// collisions. I.e. we use a very simple mesh for the character's -// physical collision and a more complex set of meshes for checking whether -// a bullet hits a person. This masking system is not meant to be a general -// "collision grouping" system. You should use a higher level system for doing -// things like making bullets ignore each other, etc. -// -// One more wrinkle to the system: The collision type in the render obj -// will always have the LSB set (COLL_TYPE_ALL) so that you can always -// do queries against every piece of geometry in a render obj if desired. -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -enum -{ - COLL_TYPE_ALL = 0x01, // perform this test against *EVERYTHING* - COLL_TYPE_0 = 0x02, // perform this test against type 0 collision objects - COLL_TYPE_1 = 0x04, // perform this test against type 1 collision objects - COLL_TYPE_2 = 0x08, - COLL_TYPE_3 = 0x10, - COLL_TYPE_4 = 0x20, - COLL_TYPE_5 = 0x40, - COLL_TYPE_6 = 0x80, - - COLL_TYPE_PHYSICAL = COLL_TYPE_0, // physics collisions - COLL_TYPE_PROJECTILE = COLL_TYPE_1, // projectile collisions - COLL_TYPE_VIS = COLL_TYPE_2, // "vis node" detection - COLL_TYPE_CAMERA = COLL_TYPE_3, // camera collision (99% should match physical setting) - COLL_TYPE_VEHICLE = COLL_TYPE_4, // vehicles will collide with physical and this. -}; - - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/composite.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/composite.cpp deleted file mode 100644 index f07e78cdfa..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/composite.cpp +++ /dev/null @@ -1,561 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/composite.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/27/01 12:45a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CompositeRenderObjClass::CompositeRenderObjClass -- Constructor * - * CompositeRenderObjClass::CompositeRenderObjClass -- copy constructor * - * CompositeRenderObjClass::~CompositeRenderObjClass -- Destructor * - * CompositeRenderObjClass::operator -- assignment operator * - * CompositeRenderObjClass::Restart -- Recursively call Restart on all sub-objects * - * CompositeRenderObjClass::Get_Name -- returns the name of this render object * - * CompositeRenderObjClass::Set_Name -- sets the name of this render object * - * CompositeRenderObjClass::Set_Base_Model_Name -- sets the "base-model-name" * - * CompositeRenderObjClass::Get_Num_Polys -- returns the number of polys * - * CompositeRenderObjClass::Notify_Added -- notify all sub-objects that they were added * - * CompositeRenderObjClass::Notify_Removed -- notifies all subobjs they were removed from th * - * CompositeRenderObjClass::Cast_Ray -- cast a ray against this object * - * CompositeRenderObjClass::Cast_AABox -- cast a swept AABox against this object * - * CompositeRenderObjClass::Cast_OBBox -- cast a swept OBBox against this object * - * CompositeRenderObjClass::Intersect_AABox -- intersect this object with an AABox * - * CompositeRenderObjClass::Intersect_OBBox -- intersect this object with an OBBox * - * CompositeRenderObjClass::Create_Decal -- create a decal on this object * - * CompositeRenderObjClass::Delete_Decal -- remove a logical decal from this object * - * CompositeRenderObjClass::Update_Obj_Space_Bounding_Volumes -- updates the object-space BV * - * CompositeRenderObjClass::Set_User_Data -- set the userdata pointer * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "composite.h" -#include "wwdebug.h" -#include -#include - - -/*********************************************************************************************** - * CompositeRenderObjClass::CompositeRenderObjClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -CompositeRenderObjClass::CompositeRenderObjClass(void) -{ -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::CompositeRenderObjClass -- copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -CompositeRenderObjClass::CompositeRenderObjClass(const CompositeRenderObjClass & that) -{ - Set_Name(that.Get_Name()); - Set_Base_Model_Name(that.Get_Base_Model_Name()); -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::~CompositeRenderObjClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -CompositeRenderObjClass::~CompositeRenderObjClass(void) -{ -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::operator -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -CompositeRenderObjClass & CompositeRenderObjClass::operator = (const CompositeRenderObjClass & that) -{ - Set_Name(that.Get_Name()); - Set_Base_Model_Name(that.Get_Base_Model_Name()); - return *this; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Restart -- Recursively call Restart on all sub-objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/30/2001 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Restart(void) -{ - for (int ni = 0; ni < Get_Num_Sub_Objects(); ni++) { - RenderObjClass * robj = Get_Sub_Object(ni); - WWASSERT(robj); - robj->Restart(); - robj->Release_Ref(); - } -} - -/*********************************************************************************************** - * CompositeRenderObjClass::Get_Name -- returns the name of this render object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -const char * CompositeRenderObjClass::Get_Name(void) const -{ - return Name; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Set_Name -- sets the name of this render object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Set_Name(const char * name) -{ - Name=name; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Set_Base_Model_Name -- sets the "base-model-name" * - * * - * The base-model-name was needed by the aggregate code. Ask Patrick Smith about it :-) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Set_Base_Model_Name(const char *name) -{ - // NULL is a legal value for BaseModelName. Unfortunately, - // StringClass::operator= does not modify the string when - // assigning NULL, so we explicitly handle that case here. - if (name != 0) { - BaseModelName = name; - } else { - BaseModelName = ""; - } -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Get_Num_Polys -- returns the number of polys * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -int CompositeRenderObjClass::Get_Num_Polys(void) const -{ - int count = 0; - for (int ni = 0; ni < Get_Num_Sub_Objects(); ni++) { - RenderObjClass * robj = Get_Sub_Object(ni); - WWASSERT(robj); - count += robj->Get_Num_Polys(); - robj->Release_Ref(); - } - return count; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Notify_Added -- notify all sub-objects that they were added * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Notify_Added(SceneClass * scene) -{ - RenderObjClass::Notify_Added(scene); - for (int ni = 0; ni < Get_Num_Sub_Objects(); ni++) { - RenderObjClass * robj = Get_Sub_Object(ni); - WWASSERT(robj); - robj->Notify_Added(scene); - robj->Release_Ref(); - } -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Notify_Removed -- notifies all subobjs they were removed from the * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Notify_Removed(SceneClass * scene) -{ - for (int ni = 0; ni < Get_Num_Sub_Objects(); ni++) { - RenderObjClass * robj = Get_Sub_Object(ni); - WWASSERT(robj); - robj->Notify_Removed(scene); - robj->Release_Ref(); - } - RenderObjClass::Notify_Removed(scene); -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Cast_Ray -- cast a ray against this object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -bool CompositeRenderObjClass::Cast_Ray(RayCollisionTestClass & raytest) -{ - bool res = false; - for (int i=0; iCast_Ray(raytest); - robj->Release_Ref(); - } - return res; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Cast_AABox -- cast a swept AABox against this object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -bool CompositeRenderObjClass::Cast_AABox(AABoxCollisionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iCast_AABox(boxtest); - robj->Release_Ref(); - } - return res; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Cast_OBBox -- cast a swept OBBox against this object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -bool CompositeRenderObjClass::Cast_OBBox(OBBoxCollisionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iCast_OBBox(boxtest); - robj->Release_Ref(); - } - return res; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Intersect_AABox -- intersect this object with an AABox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -bool CompositeRenderObjClass::Intersect_AABox(AABoxIntersectionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iIntersect_AABox(boxtest); - robj->Release_Ref(); - } - return res; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Intersect_OBBox -- intersect this object with an OBBox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -bool CompositeRenderObjClass::Intersect_OBBox(OBBoxIntersectionTestClass & boxtest) -{ - bool res = false; - for (int i=0; iIntersect_OBBox(boxtest); - robj->Release_Ref(); - } - return res; -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Create_Decal -- create a decal on this object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Create_Decal(DecalGeneratorClass * generator) -{ - for (int i=0; iCreate_Decal(generator); - robj->Release_Ref(); - } -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Delete_Decal -- remove a logical decal from this object * - * * - * This internally removes all decals with the given ID. The ID comes from the generator * - * which was used to create the decals. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Delete_Decal(uint32 decal_id) -{ - for (int i=0; iDelete_Decal(decal_id); - robj->Release_Ref(); - } -} - - -/*********************************************************************************************** - * CompositeRenderObjClass::Update_Obj_Space_Bounding_Volumes -- updates the object-space BVs * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Update_Obj_Space_Bounding_Volumes(void) -{ - int i; - RenderObjClass * robj = NULL; - - // if we don't have any sub objects, just set default bounds - if (Get_Num_Sub_Objects() <= 0) { - ObjSphere.Init(Vector3(0,0,0),0); - ObjBox.Center.Set(0,0,0); - ObjBox.Extent.Set(0,0,0); - return; - } - - - AABoxClass obj_aabox; - MinMaxAABoxClass box; - SphereClass sphere; - - // loop through all sub-objects, combining their object-space bounding spheres and boxes. - robj = Get_Sub_Object(0); - WWASSERT(robj); - robj->Get_Obj_Space_Bounding_Sphere(ObjSphere); - robj->Get_Obj_Space_Bounding_Box(obj_aabox); - robj->Release_Ref(); - box.Init(obj_aabox); - - for (i=1; iGet_Obj_Space_Bounding_Sphere(sphere); - robj->Get_Obj_Space_Bounding_Box(obj_aabox); - - ObjSphere.Add_Sphere(sphere); - box.Add_Box(obj_aabox); - - robj->Release_Ref(); - } - - ObjBox.Init(box); - - Invalidate_Cached_Bounding_Volumes(); - - // Now update the object space bounding volumes of this object's container: - RenderObjClass *container = Get_Container(); - if (container) container->Update_Obj_Space_Bounding_Volumes(); -} - -/*********************************************************************************************** - * CompositeRenderObjClass::Set_User_Data -- set the userdata * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void CompositeRenderObjClass::Set_User_Data(void *value, bool recursive) -{ - RenderObjClass::Set_User_Data(value); - if (recursive) { - for (int i=0; iSet_User_Data(value,recursive); - robj->Release_Ref(); - } - } -} - -const char * CompositeRenderObjClass::Get_Base_Model_Name (void) const -{ - if (BaseModelName.Is_Empty()) { - return NULL; - } - - return BaseModelName; -} \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/composite.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/composite.h deleted file mode 100644 index 007f01706a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/composite.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/composite.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/25/01 12:25p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COMPOSITE_H -#define COMPOSITE_H - -#include "rendobj.h" -#include "wwstring.h" - -/* -** CompositeRenderObjClass -** The sole purpose of this class is to encapsulate some of the chores that all -** "composite" (contain sub objects) render objects have to do. Typically all -** of the functions are implemented through the existing sub-object interface -** so there is still no assumption on how you store/organize your sub-objects. -*/ -class CompositeRenderObjClass : public RenderObjClass -{ -public: - - CompositeRenderObjClass(void); - CompositeRenderObjClass(const CompositeRenderObjClass & that); - virtual ~CompositeRenderObjClass(void); - CompositeRenderObjClass & operator = (const CompositeRenderObjClass & that); - - virtual void Restart(void); - - virtual const char * Get_Name(void) const; - virtual void Set_Name(const char * name); - virtual const char * Get_Base_Model_Name (void) const; - virtual void Set_Base_Model_Name (const char *name); - virtual int Get_Num_Polys(void) const; - virtual void Notify_Added(SceneClass * scene); - virtual void Notify_Removed(SceneClass * scene); - - virtual bool Cast_Ray(RayCollisionTestClass & raytest); - virtual bool Cast_AABox(AABoxCollisionTestClass & boxtest); - virtual bool Cast_OBBox(OBBoxCollisionTestClass & boxtest); - virtual bool Intersect_AABox(AABoxIntersectionTestClass & boxtest); - virtual bool Intersect_OBBox(OBBoxIntersectionTestClass & boxtest); - - virtual void Create_Decal(DecalGeneratorClass * generator); - virtual void Delete_Decal(uint32 decal_id); - - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const { sphere = ObjSphere; } - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const { box = ObjBox; } - virtual void Update_Obj_Space_Bounding_Volumes(void); - - virtual void Set_User_Data(void *value, bool recursive = false); - -protected: - - StringClass Name; // name of the render object - StringClass BaseModelName; // name of the original render obj (before aggregation) - SphereClass ObjSphere; // object-space bounding sphere - AABoxClass ObjBox; // object-space bounding box -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp index df25824490..61156e1580 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp @@ -303,7 +303,7 @@ const Vector2 DazzleINIClass::Get_Vector2(char const *section, char const *entry INIEntry * entryptr = Find_Entry(section, entry); if (entryptr && entryptr->Value != NULL) { Vector2 ret; - if ( sscanf( entryptr->Value, "%f,%f", &ret[0], &ret[1], &ret[2] ) == 2 ) { + if ( sscanf( entryptr->Value, "%f,%f", &ret[0], &ret[1] ) == 2 ) { return ret; } } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.cpp index 5a8fc9830a..c027c5f6e0 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.cpp @@ -16,27 +16,38 @@ ** along with this program. If not, see . */ +// 08/06/02 KM Added cube map and volume texture support #include "ddsfile.h" #include "ffactory.h" #include "bufffile.h" #include "formconv.h" #include "dx8wrapper.h" #include "bitmaphandler.h" +#include "colorspace.h" +#include +#include // ---------------------------------------------------------------------------- DDSFileClass::DDSFileClass(const char* name,unsigned reduction_factor) : - Name(name), DDSMemory(NULL), Width(0), Height(0), + Depth(0), + FullWidth(0), + FullHeight(0), + FullDepth(0), LevelSizes(NULL), LevelOffsets(NULL), MipLevels(0), ReductionFactor(reduction_factor), - Format(WW3D_FORMAT_UNKNOWN) + Format(WW3D_FORMAT_UNKNOWN), + Type(DDS_TEXTURE), + DateTime(0), + CubeFaceSize(0) { + strncpy(Name,name,sizeof(Name)); // The name could be given in .tga or .dds format, so ensure we're opening .dds... int len=strlen(Name); Name[len-3]='d'; @@ -44,17 +55,37 @@ DDSFileClass::DDSFileClass(const char* name,unsigned reduction_factor) Name[len-1]='s'; file_auto_ptr file(_TheFileFactory,Name); - if (!file->Is_Available()) { + if (!file->Is_Available()) + { return; } - file->Open(); + int result=file->Open(); + if (!result) + { + WWASSERT("File would not open\n"); + return; + } + + DateTime=file->Get_Date_Time(); char header[4]; - file->Read(header,4); + + unsigned read_bytes=file->Read(header,4); + if (!read_bytes) + { + WWASSERT("File loading failed trying to read header\n"); + return; + } // Now, we read DDSURFACEDESC2 defining the compressed data - unsigned read_bytes=file->Read(&SurfaceDesc,sizeof(LegacyDDSURFACEDESC2)); + read_bytes=file->Read(&SurfaceDesc,sizeof(LegacyDDSURFACEDESC2)); // Verify the structure size matches the read size - WWASSERT(read_bytes==SurfaceDesc.Size); + if (read_bytes==0 || read_bytes!=SurfaceDesc.Size) + { + StringClass tmp(0,true); + tmp.Format("File %s loading failed.\nTried to read %d bytes, got %d. (SurfDesc.size=%d)\n",name,sizeof(LegacyDDSURFACEDESC2),read_bytes,SurfaceDesc.Size); + WWASSERT_PRINT(0,tmp); + return; + } Format=D3DFormat_To_WW3DFormat((D3DFORMAT)SurfaceDesc.PixelFormat.FourCC); WWASSERT( @@ -68,10 +99,10 @@ DDSFileClass::DDSFileClass(const char* name,unsigned reduction_factor) if (MipLevels==0) MipLevels=1; //Adjust the reduction factor to keep textures above some minimum dimensions - if (MipLevels <= WW3D::Get_Texture_Min_Mip_Levels()) + if (MipLevels <= WW3D::Get_Texture_Min_Dimension()) ReductionFactor=0; else - { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Mip_Levels(); + { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Dimension(); if (ReductionFactor >= mipToDrop) ReductionFactor=mipToDrop; } @@ -86,32 +117,72 @@ DDSFileClass::DDSFileClass(const char* name,unsigned reduction_factor) if (MipLevels>2) MipLevels-=2; else MipLevels=1; - Width=SurfaceDesc.Width>>ReductionFactor; - Height=SurfaceDesc.Height>>ReductionFactor; + // check texture type, normal, cube or volume + if (SurfaceDesc.Caps.Caps2&DDSCAPS2_CUBEMAP) + { + Type=DDS_CUBEMAP; + } + else if (SurfaceDesc.Caps.Caps2&DDSCAPS2_VOLUME) + { + Type=DDS_VOLUME; + } -// MipLevels=SurfaceDesc.dwMipMapCount; -// if (MipLevels==0) MipLevels=1; - unsigned level_size=Calculate_DXTC_Surface_Size(SurfaceDesc.Width,SurfaceDesc.Height,Format); + FullWidth=SurfaceDesc.Width; + FullHeight=SurfaceDesc.Height; + FullDepth=SurfaceDesc.Depth; + Width=SurfaceDesc.Width>>ReductionFactor; + Height=SurfaceDesc.Height>>ReductionFactor; + Depth=SurfaceDesc.Depth; + + unsigned level_size=Calculate_DXTC_Surface_Size + ( + SurfaceDesc.Width, + SurfaceDesc.Height, + Format + ); unsigned level_offset=0; + unsigned level_mip_dec=4; + if (Type==DDS_VOLUME) + { + // add slices to level data size + level_size*=SurfaceDesc.Depth; + level_mip_dec=8; + } + LevelSizes=W3DNEWARRAY unsigned[MipLevels]; LevelOffsets=W3DNEWARRAY unsigned[MipLevels]; unsigned level=0; - for (;level16) { // If surface is bigger than one block (8 or 16 bytes)... - level_size/=4; + for (;level16) + { // If surface is bigger than one block (8 or 16 bytes)... + level_size/=level_mip_dec; } } - for (level=0;level16) { // If surface is bigger than one block (8 or 16 bytes)... - level_size/=4; + if (level_size>16) + { // If surface is bigger than one block (8 or 16 bytes)... + level_size/=level_mip_dec; } } + + if (Type==DDS_CUBEMAP) + { + for (level=0; level2) + CubeFaceSize+=16; + } // Verify we read through the whole file (not more, not less). #if 0 // This code is commented out because it complains for all our files, but it doesn't seem to actually @@ -149,6 +220,14 @@ unsigned DDSFileClass::Get_Height(unsigned level) const return height; } +unsigned DDSFileClass::Get_Depth(unsigned level) const +{ + WWASSERT(level>level; + if (depth<4) depth=4; + return depth; +} + const unsigned char* DDSFileClass::Get_Memory_Pointer(unsigned level) const { WWASSERT(levelOpen(); // Data size is file size minus the header and info block unsigned size=file->Size()-SurfaceDesc.Size-4; + + if (!size) + { + return false; + } + // Skip mip levels if reduction factor is not zero - unsigned level_size=Calculate_DXTC_Surface_Size(SurfaceDesc.Width,SurfaceDesc.Height,Format); + unsigned level_size=Calculate_DXTC_Surface_Size + ( + SurfaceDesc.Width, + SurfaceDesc.Height, + Format + ); + unsigned skipped_offset=0; for (unsigned i=0;iSeek(SurfaceDesc.Size+4+skipped_offset); WWASSERT(seek_size==(SurfaceDesc.Size+4+skipped_offset)); - if (size) + if (size && size<0x80000000) { // Allocate memory for the data excluding the headers DDSMemory=MSGW3DNEWARRAY("DDSMemory") unsigned char[size]; @@ -232,6 +323,28 @@ bool DDSFileClass::Load() return true; } +// ---------------------------------------------------------------------------- + +WWINLINE static unsigned RGB565_To_ARGB8888(unsigned short rgb) +{ + unsigned rgba=0; + rgba|=unsigned(rgb&0x001f)<<3; + rgba|=unsigned(rgb&0x07e0)<<5; + rgba|=unsigned(rgb&0xf800)<<8; + return rgba; +} + +WWINLINE static unsigned short ARGB8888_To_RGB565(unsigned argb_) +{ + unsigned char* argb=(unsigned char*)&argb_; + unsigned short rgb; + rgb=((argb[2])&0xf8)<<8; + rgb|=((argb[1])&0xfc)<<3; + rgb|=((argb[0])&0xf8)>>3; + return rgb; +} + + // ---------------------------------------------------------------------------- // // Copy mipmap level to D3D surface. The copying is performed using another @@ -239,7 +352,7 @@ bool DDSFileClass::Load() // // ---------------------------------------------------------------------------- -void DDSFileClass::Copy_Level_To_Surface(unsigned level,IDirect3DSurface8* d3d_surface) +void DDSFileClass::Copy_Level_To_Surface(unsigned level,IDirect3DSurface8* d3d_surface,const Vector3& hsv_shift) { WWASSERT(d3d_surface); // Verify that the destination surface size matches the source surface size @@ -256,7 +369,8 @@ void DDSFileClass::Copy_Level_To_Surface(unsigned level,IDirect3DSurface8* d3d_s surface_desc.Width, surface_desc.Height, reinterpret_cast(locked_rect.pBits), - locked_rect.Pitch); + locked_rect.Pitch, + hsv_shift); // Finally, unlock the surface DX8_ErrorCode(d3d_surface->UnlockRect()); @@ -272,21 +386,80 @@ void DDSFileClass::Copy_Level_To_Surface(unsigned level,IDirect3DSurface8* d3d_s // // ---------------------------------------------------------------------------- -void DDSFileClass::Copy_Level_To_Surface( +void DDSFileClass::Copy_Level_To_Surface +( unsigned level, WW3DFormat dest_format, unsigned dest_width, unsigned dest_height, unsigned char* dest_surface, - unsigned dest_pitch) + unsigned dest_pitch, + const Vector3& hsv_shift +) { WWASSERT(DDSMemory); WWASSERT(dest_surface); + if (!DDSMemory || !Get_Memory_Pointer(level)) + { + WWASSERT_PRINT(DDSMemory,"Surface mip level pointer is missing\n"); + return; + } + // If the format and size is a match just copy the contents + bool has_hsv_shift = hsv_shift[0]!=0.0f || hsv_shift[1]!=0.0f || hsv_shift[2]!=0.0f; if (dest_format==Format && dest_width==Get_Width(level) && dest_height==Get_Height(level)) { - unsigned compressed_size=Get_Level_Size(level); - memcpy(dest_surface,Get_Memory_Pointer(level),compressed_size); + // If hue shift, we can't just copy... + if (has_hsv_shift) { + if (Format==WW3D_FORMAT_DXT1) { + const unsigned* src_ptr=reinterpret_cast(Get_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else if (Format==WW3D_FORMAT_DXT5) { + const unsigned* src_ptr=reinterpret_cast(Get_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else { + WWASSERT(0); + } + + } + else { + unsigned compressed_size=Get_Level_Size(level); + memcpy(dest_surface,Get_Memory_Pointer(level),compressed_size); + } } else { // If size matches, copy each pixel linearly with color space conversion @@ -295,14 +468,40 @@ void DDSFileClass::Copy_Level_To_Surface( // is DXT2, just copy the contents and create an empty alpha channel. // This is needed on NVidia cards that have problems with DXT1 compression. if (Format==WW3D_FORMAT_DXT1 && dest_format==WW3D_FORMAT_DXT2) { - const unsigned* src_ptr=reinterpret_cast(Get_Memory_Pointer(level)); - unsigned* dest_ptr=reinterpret_cast(dest_surface); - for (unsigned y=0;y(Get_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else { + const unsigned* src_ptr=reinterpret_cast(Get_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y(Get_CubeMap_Memory_Pointer(face,level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else if (Format==WW3D_FORMAT_DXT5) + { + const unsigned* src_ptr=reinterpret_cast(Get_CubeMap_Memory_Pointer(face,level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else + { + WWASSERT(0); + } + + } + else + { + unsigned compressed_size=Get_Level_Size(level); + memcpy(dest_surface,Get_CubeMap_Memory_Pointer(face,level),compressed_size); + } + } + else + { + // If size matches, copy each pixel linearly with color space conversion + if (dest_width==Get_Width(level) && dest_height==Get_Height(level)) + { + // An exception here - if the source format is DXT1 and the destination + // is DXT2, just copy the contents and create an empty alpha channel. + // This is needed on NVidia cards that have problems with DXT1 compression. + if (Format==WW3D_FORMAT_DXT1 && dest_format==WW3D_FORMAT_DXT2) + { + // If hue shift, we can't just copy... + if (has_hsv_shift) + { + const unsigned* src_ptr=reinterpret_cast(Get_CubeMap_Memory_Pointer(face,level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else + { + const unsigned* src_ptr=reinterpret_cast(Get_CubeMap_Memory_Pointer(face,level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y(Get_Volume_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else if (Format==WW3D_FORMAT_DXT5) + { + const unsigned* src_ptr=reinterpret_cast(Get_Volume_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else + { + WWASSERT(0); + } + + } + else + { + unsigned compressed_size=Get_Level_Size(level); + memcpy(dest_surface,Get_Volume_Memory_Pointer(level),compressed_size); + } + } + else + { + // If size matches, copy each pixel linearly with color space conversion + if (dest_width==Get_Width(level) && dest_height==Get_Height(level)) + { + // An exception here - if the source format is DXT1 and the destination + // is DXT2, just copy the contents and create an empty alpha channel. + // This is needed on NVidia cards that have problems with DXT1 compression. + if (Format==WW3D_FORMAT_DXT1 && dest_format==WW3D_FORMAT_DXT2) + { + // If hue shift, we can't just copy... + if (has_hsv_shift) + { + const unsigned* src_ptr=reinterpret_cast(Get_Volume_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;y>16)); + unsigned col1=RGB565_To_ARGB8888(unsigned short(cols&0xffff)); + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + col0=ARGB8888_To_RGB565(col0); + col1=ARGB8888_To_RGB565(col1); + cols=unsigned(col0)<<16|col1; + *dest_ptr++=cols; + + *dest_ptr++=*src_ptr++; // Bytes 5-8 of color block + } + } + } + else + { + const unsigned* src_ptr=reinterpret_cast(Get_Volume_Memory_Pointer(level)); + unsigned* dest_ptr=reinterpret_cast(dest_surface); + for (unsigned y=0;ycol1) { + if (has_hsv_shift) { + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + } + for (int y=0;y<4;++y) { unsigned char* tmp_dest_ptr=dest_ptr; dest_ptr+=dest_pitch; @@ -570,6 +1117,11 @@ bool DDSFileClass::Get_4x4_Block( return false; // No alpha found in the block } else { + if (has_hsv_shift) { + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + } + bool contains_alpha=false; for (int y=0;y<4;++y) { unsigned char* tmp_dest_ptr=dest_ptr; dest_ptr+=dest_pitch; @@ -579,7 +1131,7 @@ bool DDSFileClass::Get_4x4_Block( case 0: dest_pixel=col0|0xff000000; break; case 1: dest_pixel=col1|0xff000000; break; case 2: dest_pixel=Combine_Colors(col1,col0,128)|0xff000000; break; - case 3: dest_pixel=0x00000000; break; + case 3: dest_pixel=0x00000000; contains_alpha=true; break; } line>>=2; @@ -587,7 +1139,7 @@ bool DDSFileClass::Get_4x4_Block( tmp_dest_ptr+=dest_bpp; } } - return true; // Alpha block... + return contains_alpha; // Alpha block...? } } break; @@ -628,6 +1180,10 @@ bool DDSFileClass::Get_4x4_Block( const unsigned char* color_block=alpha_block+8; unsigned col0=RGB565_To_ARGB8888(*(unsigned short*)&color_block[0]); unsigned col1=RGB565_To_ARGB8888(*(unsigned short*)&color_block[2]); + if (has_hsv_shift) { + Recolor(col0,hsv_shift); + Recolor(col1,hsv_shift); + } unsigned dest_pixel=0; unsigned bit_idx=0; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h index 30b3a57708..d871916a09 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h @@ -16,6 +16,8 @@ ** along with this program. If not, see . */ +// 08/06/02 KM Added cube map and volume texture support + #ifndef DDSFILE_H #define DDSFILE_H @@ -178,14 +180,21 @@ class DDSFileClass { unsigned Width; unsigned Height; + unsigned Depth; + unsigned FullWidth; + unsigned FullHeight; + unsigned FullDepth; unsigned MipLevels; + unsigned long DateTime; unsigned ReductionFactor; unsigned char* DDSMemory; WW3DFormat Format; + DDSType Type; unsigned* LevelSizes; unsigned* LevelOffsets; + unsigned CubeFaceSize; LegacyDDSURFACEDESC2 SurfaceDesc; - StringClass Name; + char Name[256]; static unsigned Calculate_DXTC_Surface_Size(unsigned width, unsigned height, WW3DFormat format); @@ -197,22 +206,59 @@ class DDSFileClass unsigned Get_Width(unsigned level) const; unsigned Get_Height(unsigned level) const; + unsigned Get_Depth(unsigned level) const; + unsigned Get_Full_Width() const { return FullWidth; } // Get the width of level 0 of non-reduced texture + unsigned Get_Full_Height() const { return FullHeight; } // Get the height of level 0 of non-reduced texture + unsigned Get_Full_Depth() const { return FullDepth; } + unsigned long Get_Date_Time() const { return DateTime; } unsigned Get_Mip_Level_Count() const { return MipLevels; } const unsigned char* Get_Memory_Pointer(unsigned level) const; unsigned Get_Level_Size(unsigned level) const; WW3DFormat Get_Format() const { return Format; } + DDSType Get_Type() const { return Type; } + // Copy pixels to the destination surface. - void Copy_Level_To_Surface(unsigned level,IDirect3DSurface8* d3d_surface); + void Copy_Level_To_Surface(unsigned level,IDirect3DSurface8* d3d_surface,const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f)); void Copy_Level_To_Surface( unsigned level, WW3DFormat dest_format, unsigned dest_width, unsigned dest_height, unsigned char* dest_surface, - unsigned dest_pitch); + unsigned dest_pitch, + const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f)); + // cube map + const unsigned char* Get_CubeMap_Memory_Pointer(unsigned face, unsigned level) const; + void Copy_CubeMap_Level_To_Surface + ( + unsigned face, + unsigned level, + WW3DFormat dest_format, + unsigned width, + unsigned height, + unsigned char* surf, + unsigned pitch, + const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f) + ); + + // volume texture + const unsigned char* Get_Volume_Memory_Pointer(unsigned level) const; + void Copy_Volume_Level_To_Surface + ( + unsigned level, + unsigned depth, + WW3DFormat dest_format, + unsigned width, + unsigned height, + unsigned char* vol, + unsigned row_pitch, + unsigned slice_pitch, + const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f) + ); + // Get pixel in A8R8G8B8 format. This isn't the fastest possible way of reading data from DDS. unsigned Get_Pixel(unsigned level,unsigned x,unsigned y) const; @@ -225,7 +271,8 @@ class DDSFileClass WW3DFormat dest_format, // Destination surface format, A8R8G8B8 is fastest unsigned level, // DDS mipmap level to copy from unsigned source_x, // DDS x offset to copy from, must be aligned by 4! - unsigned source_y) const; // DDS y offset to copy from, must be aligned by 4! + unsigned source_y, // DDS y offset to copy from, must be aligned by 4! + const Vector3& hsv_shift=Vector3(0.0f,0.0f,0.0f)) const; bool Load(); bool Is_Available() const { return !!LevelSizes; } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/decalsys.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/decalsys.cpp deleted file mode 100644 index 2a729f9c18..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/decalsys.cpp +++ /dev/null @@ -1,488 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/decalsys.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 8 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * DecalSystemClass::DecalSystemClass -- Constructor * - * DecalSystemClass::~DecalSystemClass -- Destructor * - * DecalSystemClass::Lock_Decal_Generator -- returns a DecalGenerator * - * DecalSystemClass::Unlock_Decal_Generator -- Destroys the decal generator * - * DecalSystemClass::Generate_Unique_Global_Decal_Id -- Generates a unique id for a decal * - * DecalGeneratorClass::DecalGeneratorClass -- Constructor * - * DecalGeneratorClass::~DecalGeneratorClass -- Destructor * - * DecalGeneratorClass::Add_Mesh -- Meshes that generate a decal should add themselves * - * DecalGeneratorClass::Get_Mesh_List -- returns the list of meshes * - * DecalGeneratorClass::Set_Mesh_Transform -- sets the current mesh coordinate system * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "decalsys.h" -#include "rendobj.h" -#include "mesh.h" -#include "decalmsh.h" -#include "matrixmapper.h" -#include "texture.h" - - -uint32 DecalSystemClass::DecalIDGenerator = 0; - - -/* -** DecalSystemClass Implementation -*/ - -/*********************************************************************************************** - * DecalSystemClass::DecalSystemClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -DecalSystemClass::DecalSystemClass(void) -{ -} - - -/*********************************************************************************************** - * DecalSystemClass::~DecalSystemClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -DecalSystemClass::~DecalSystemClass(void) -{ -} - - -/*********************************************************************************************** - * DecalSystemClass::Lock_Decal_Generator -- returns a DecalGenerator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -DecalGeneratorClass * DecalSystemClass::Lock_Decal_Generator(void) -{ - DecalGeneratorClass * gen = W3DNEW DecalGeneratorClass(Generate_Decal_Id(), this); - return gen; -} - - -/*********************************************************************************************** - * DecalSystemClass::Unlock_Decal_Generator -- Destroys the decal generator * - * * - * Derived classes may take a record of the results of the generator here. Then they can * - * put a cap on the total number of decals in the system or whatever... * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void DecalSystemClass::Unlock_Decal_Generator(DecalGeneratorClass * generator) -{ - delete generator; -} - - -/*********************************************************************************************** - * DecalSystemClass::Generate_Unique_Global_Decal_Id -- Generates a unique id for a decal * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Hopefully you won't use more than 4 billion decals at one time... * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -uint32 DecalSystemClass::Generate_Unique_Global_Decal_Id(void) -{ - return DecalIDGenerator++; -} - - -/* -** DecalGeneratorClass Implementation -*/ - -/*********************************************************************************************** - * DecalGeneratorClass::DecalGeneratorClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -DecalGeneratorClass::DecalGeneratorClass(uint32 id,DecalSystemClass * system) : - DecalID(id), - System(system), - BackfaceVal(0.0f), - ApplyToTranslucentMeshes(false), - Material(NULL) -{ - Material = NEW_REF(MaterialPassClass,()); - - WWASSERT(System != NULL); - WWASSERT(Material != NULL); -} - - -/*********************************************************************************************** - * DecalGeneratorClass::~DecalGeneratorClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -DecalGeneratorClass::~DecalGeneratorClass(void) -{ - REF_PTR_RELEASE(Material); -} - - -/*********************************************************************************************** - * DecalGeneratorClass::Add_Mesh -- Meshes that generate a decal should add themselves * - * * - * This adds a mesh to the internal list. All meshes that actually add a decal should add * - * themselves to this list so that the DecalSystem can keep track of them. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void DecalGeneratorClass::Add_Mesh(RenderObjClass * mesh) -{ - WWASSERT(mesh->Class_ID() == RenderObjClass::CLASSID_MESH); - MeshList.Add(mesh); -} - - -/*********************************************************************************************** - * DecalGeneratorClass::Get_Mesh_List -- returns the list of meshes * - * * - * This is the list of meshes which generated decals for this "logical decal" * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -NonRefRenderObjListClass & DecalGeneratorClass::Get_Mesh_List(void) -{ - return MeshList; -} - - -/*********************************************************************************************** - * DecalGeneratorClass::Set_Mesh_Transform -- sets the current mesh coordinate system * - * * - * The coordinate system of the mesh is needed in order to compute texture coordinates for * - * the decal polygons. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/26/00 gth : Created. * - *=============================================================================================*/ -void DecalGeneratorClass::Set_Mesh_Transform(const Matrix3D & mesh_transform) -{ - /* - ** Mobj-texture = Projection * Mwrld-texture * Mobj-wrld - */ - Matrix3D world_to_texture; - Matrix3D tmp; - Matrix4x4 mesh_to_texture; - - Transform.Get_Orthogonal_Inverse(world_to_texture); - Matrix3D::Multiply(world_to_texture,mesh_transform,&tmp); - Matrix4x4::Multiply(Projection,tmp,&mesh_to_texture); - - /* - ** Plug the matrix and texture size into the mapper - */ - if (WW3D::Is_Texturing_Enabled()) { - float texsize = 64.0f; - TextureClass * tex = Material->Peek_Texture(); - WWASSERT(tex != NULL); - if (tex) { - SurfaceClass::SurfaceDescription surface_desc; - tex->Get_Level_Description(surface_desc); - texsize = surface_desc.Width; - } - - Mapper->Set_Texture_Transform(mesh_to_texture,texsize); - } -} - - -/* -** MultiFixedPoolDecalSystemClass implementation -*/ - -MultiFixedPoolDecalSystemClass::MultiFixedPoolDecalSystemClass(uint32 num_pools, const uint32 *pool_sizes) : - Pools(0), - PoolCount(num_pools), - Generator_PoolID(0), - Generator_SlotID(0) -{ - if (PoolCount) - { - WWASSERT(pool_sizes); - Pools = W3DNEWARRAY LogicalDecalPoolClass [PoolCount]; - } - for (uint32 i = 0; i < PoolCount; i++) { - assert(pool_sizes[i]); - Pools[i].Initialize(pool_sizes[i]); - } -} - -MultiFixedPoolDecalSystemClass::MultiFixedPoolDecalSystemClass(const MultiFixedPoolDecalSystemClass & that) : - Pools(0), - PoolCount(that.PoolCount), - Generator_PoolID(that.Generator_PoolID), - Generator_SlotID(that.Generator_SlotID) -{ - uint32 i; - - // Allocate arrays (we dont' copy array contents because those are mesh-specific and will be - // filled when the state is set anyway) - if (PoolCount) Pools = W3DNEWARRAY LogicalDecalPoolClass [PoolCount]; - for (i = 0; i < PoolCount; i++) { - Pools[i].Initialize(that.Pools[i].Size); - } -} - -MultiFixedPoolDecalSystemClass::~MultiFixedPoolDecalSystemClass(void) -{ - if (Pools) { - delete [] Pools; - Pools = 0; - } -} - -// This clears the slot in addition to locking the generator, thus preventing any decal id -// collisions (since any decal previously in that slot will have the same id as the new one). -DecalGeneratorClass * MultiFixedPoolDecalSystemClass::Lock_Decal_Generator(void) -{ - Clear_Decal_Slot(Generator_PoolID, Generator_SlotID); - return DecalSystemClass::Lock_Decal_Generator(); -} - -// This will register the decal in the system in the appropriate pool and slot (determined by -// the generator's pool and slot ids), removing any decal which may have been there before. -void MultiFixedPoolDecalSystemClass::Unlock_Decal_Generator(DecalGeneratorClass * generator) -{ - find_logical_decal(generator->Get_Decal_ID()).Set(generator); - DecalSystemClass::Unlock_Decal_Generator(generator); -} - -// This notifies the system that a mesh which has decals on it was destroyed - therefore we -// need to remove the mesh from our list to avoid dangling pointers. -void MultiFixedPoolDecalSystemClass::Decal_Mesh_Destroyed(uint32 decal_id,DecalMeshClass * mesh) -{ - // We must remove this mesh from all lists where it is present. The method is: for each - // decal id present in the decal mesh, find the logical decal and remove the decal mesh from - // its list. - assert(mesh); - MeshClass *parent = mesh->Peek_Parent(); - find_logical_decal(decal_id).MeshList.Remove(parent); -} - -// Not part of the DecalSystemClass interface - this function removes any decal currently in -// the given slot in the given pool. -void MultiFixedPoolDecalSystemClass::Clear_Decal_Slot(uint32 pool_id, uint32 slot_id) -{ - find_logical_decal(pool_id, slot_id).Clear(encode_decal_id(pool_id, slot_id)); -} - -// This one removes all decals in a given pool. -void MultiFixedPoolDecalSystemClass::Clear_Pool(uint32 pool_id) -{ - LogicalDecalPoolClass & pool = Pools[pool_id]; - uint32 pool_size = pool.Size; - for (uint32 slot_id = 0; slot_id < pool_size; slot_id++) { - pool.Array[slot_id].Clear(encode_decal_id(pool_id, slot_id)); - } -} - -// And this one removes all decals in the system. -void MultiFixedPoolDecalSystemClass::Clear_All_Decals(void) -{ - for (uint32 pool_id = 0; pool_id < PoolCount; pool_id++) { - LogicalDecalPoolClass & pool = Pools[pool_id]; - uint32 pool_size = pool.Size; - for (uint32 slot_id = 0; slot_id < pool_size; slot_id++) { - pool.Array[slot_id].Clear(encode_decal_id(pool_id, slot_id)); - } - } -} - -// Get a reference to the logical decal at the given pool and slot id (performs range checking) -MultiFixedPoolDecalSystemClass::LogicalDecalClass & MultiFixedPoolDecalSystemClass::find_logical_decal(uint32 pool_id, uint32 slot_id) -{ - assert(pool_id < PoolCount); - pool_id = MIN(pool_id, PoolCount); - LogicalDecalPoolClass & pool = Pools[pool_id]; - assert(slot_id < pool.Size); - slot_id = MIN(slot_id, pool.Size); - return pool.Array[slot_id]; -} - -// Get a reference to the logical decal with the given decal id -MultiFixedPoolDecalSystemClass::LogicalDecalClass & MultiFixedPoolDecalSystemClass::find_logical_decal(uint32 decal_id) -{ - uint32 pool_id, slot_id; - decode_decal_id(decal_id, pool_id, slot_id); - return find_logical_decal(pool_id, slot_id); -} - - -/* -** MultiFixedPoolDecalSystemClass::LogicalDecalClass implementation -*/ - -MultiFixedPoolDecalSystemClass::LogicalDecalClass::LogicalDecalClass(void) -{ -} - -MultiFixedPoolDecalSystemClass::LogicalDecalClass::~LogicalDecalClass(void) -{ - // We don't need to do anything here since the mesh list will get removed automatically and - // the decals themselves don't neccessarily need to be removed because the logical decal is. - // (we don't hold references to the meshes in the mesh list) -} - -// Sets the logical decal to the one specified by the given generator (clearing any existing -// decal information) -void MultiFixedPoolDecalSystemClass::LogicalDecalClass::Set(DecalGeneratorClass * generator) -{ - Clear(generator->Get_Decal_ID()); - - /* - ** Copy the generators' mesh list into our mesh list - */ - NonRefRenderObjListIterator gen_mesh_it(&(generator->Get_Mesh_List())); - for (gen_mesh_it.First(); !gen_mesh_it.Is_Done(); gen_mesh_it.Next()) { - MeshList.Add(gen_mesh_it.Get_Obj()); - } -} - -// Just clears any existing logical decal information, leaving the decal empty. -void MultiFixedPoolDecalSystemClass::LogicalDecalClass::Clear(uint32 decal_id) -{ - // Remove the decal with this ID from all meshes where it appears - NonRefRenderObjListIterator it(&MeshList); - for (it.First(); !it.Is_Done(); it.Next()) { - it.Get_Obj()->Delete_Decal(decal_id); - } - - // Delete list - while (!MeshList.Is_Empty()) { - MeshList.Remove_Head(); - } -} - - -/* -** MultiFixedPoolDecalSystemClass::LogicalDecalPoolClass implementation -*/ - -MultiFixedPoolDecalSystemClass::LogicalDecalPoolClass::LogicalDecalPoolClass(void) : - Array(0), - Size(0) -{ -} - -MultiFixedPoolDecalSystemClass::LogicalDecalPoolClass::~LogicalDecalPoolClass(void) -{ - if (Array) { - delete [] Array; - Array = 0; - } -} - -void MultiFixedPoolDecalSystemClass::LogicalDecalPoolClass::Initialize(uint32 size) -{ - if (Array) { - delete [] Array; - Array = 0; - } - - Size = size; - assert(Size); - Array = W3DNEWARRAY LogicalDecalClass[Size]; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/decalsys.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/decalsys.h deleted file mode 100644 index 80e9c4fd36..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/decalsys.h +++ /dev/null @@ -1,308 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/decalsys.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 6/29/01 11:30a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DECALSYS_H -#define DECALSYS_H - -#include "always.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "obbox.h" -#include "robjlist.h" -#include "matpass.h" -#include "projector.h" - -class DecalGeneratorClass; -class DecalMeshClass; - -/** -** DecalSystemClass -** This is a class that manages creation and destruction of decals in the system. It is -** meant to be over-ridden for game-specific behaviors. -** -** Sample Code: -** 1 - Create the generator. The system gives it a unique id and gives you a clean decal generator -** -** DecalGeneratorClass * gen = DecalSystem->Lock_Decal_Generator(); -** gen->Set_Transform(tm); -** gen->Set_Projection(proj_tm); -** gen->Set_Bounds(OBBox); -** -** 2 - Apply the generator to any objects that you want it to affect. It wont do anything if it -** does not overlap any polygons in those objects -** -** Scene->Collect_Objects(gen->Get_Bounding_Box(),objectlist); -** for (iterator.First(objectlist); !iterator.Is_Done(); iterator.Next()) { -** iterator.Peek_Object()->Create_Decal(gen); -** } -** -** 3 - Release the generator back to the system. At this point, the system may record which meshes -** actually generated extra decal polygons for future removal. All of this information will be -** tied together with the unique 'decal ID' that was assigned to the generator. -** -** DecalSystem->Unlock_Decal_Generator(gen); -** -*/ -class DecalSystemClass -{ -public: - DecalSystemClass(void); - virtual ~DecalSystemClass(void); - - /* - ** Create and release DecalGenerators. Note that this is the point at which the - ** decal system can track "logical" decals. The generator will keep an internal list - ** of all of the render objects which generated decals which you should copy if you - ** want to track them (e.g. if you want to cap the maximum number of active decals and - ** kill the old ones...) - */ - virtual DecalGeneratorClass * Lock_Decal_Generator(void); - virtual void Unlock_Decal_Generator(DecalGeneratorClass * generator); - - /* - ** When a decal-mesh is destroyed, it must inform the DecalSystem. Otherwise, systems - ** which track decals can get dangling pointers. - */ - virtual void Decal_Mesh_Destroyed(uint32 decal_id,DecalMeshClass * mesh) { } - -protected: - - /* - ** This generates the decal ID when a generator is created. This decal system reroutes this - ** to Generate_Unique_Global_Decal_Id(), but other decal systems may use a different method. - */ - virtual uint32 Generate_Decal_Id(void) { return Generate_Unique_Global_Decal_Id(); } - - /* - ** Unique ID generation for decals. Not all decal systems have to use - ** this method of generating ids. Some may wish to assign the id as the - ** array index of the logical id or use some other aritrary method. - */ - static uint32 Generate_Unique_Global_Decal_Id(void); - - static uint32 DecalIDGenerator; -}; - - -/** -** DecalGeneratorClass -** This class encapsulates the information needed to generate a decal. It also tracks -** what meshes actually used it to generate new decal polygons. -*/ -class DecalGeneratorClass : public ProjectorClass -{ -public: - - /* - ** All meshes that actually generate decal polygons should register themselves in the - ** list. Then when the decal generation is finished, this list can be copied so that - ** we can come back to those meshes and remove the decals if we want to. - */ - void Add_Mesh(RenderObjClass * mesh); - NonRefRenderObjListClass & Get_Mesh_List(void); - - /* - ** Decal generator parameters. - ** see ProjectorClass for control over the coordinate system, projection, etc - */ - uint32 Get_Decal_ID(void) { return DecalID; } - DecalSystemClass * Peek_Decal_System(void) { return System; } - - /* - ** Backface rejection thresh-hold. The dot-product between the projection vector and - ** the normal of each polygon is taken, if the result is greater than this value the polygon - ** is accepted into the decal. Set it to -1 if you want to accept all polygons. - */ - void Set_Backface_Threshhold(float val) { BackfaceVal = val; } - float Get_Backface_Threshhold(void) { return BackfaceVal; } - - /* - ** Normally, decals are not generated on translucent meshes. This is due to the "floating - ** decals" that you can get on things like trees. The user can override this behavior - ** through the following interface. - */ - void Apply_To_Translucent_Meshes(bool onoff) { ApplyToTranslucentMeshes = onoff; } - bool Is_Applied_To_Translucent_Meshes(void) { return ApplyToTranslucentMeshes; } - - /* - ** Material parameters: just grab a pointer the material pass and modify it. - ** Remember to release your ref to it when you are done. - */ - MaterialPassClass * Get_Material(void) { WWASSERT(Material != NULL); Material->Add_Ref(); return Material; } - - /* - ** Decal generation support. Call Set_Mesh_Transform for the mesh you want to add - ** a decal to. Then for each vertex, you can call 'Compute_Texture_Coordinate' - */ - void Set_Mesh_Transform(const Matrix3D & tm); - -protected: - - DecalGeneratorClass(uint32 id,DecalSystemClass * system); - ~DecalGeneratorClass(void); - - /* - ** Logical Decal ID, DecalSystem that this generator is tied to - */ - DecalSystemClass * System; - uint32 DecalID; // unique ID generated by the DecalSystem - - /* - ** Backface Threshhold, Translucent mesh decal enable - */ - float BackfaceVal; - bool ApplyToTranslucentMeshes; - - /* - ** Material settings - */ - MaterialPassClass * Material; // material settings for the decal - - /* - ** Results, list of the meshes which actually generated decal polygons for this logical decal. - */ - NonRefRenderObjListClass MeshList; - - friend class DecalSystemClass; -}; - - -/** -** MultiFixedPoolDecalSystemClass: This is for decal systems which use several fixed-size decal -** pools (If more than one pool is used, it is usually to have separate pools for several -** different classes of decals). Note that here the decal IDs are a combination of the pool and -** slot ids. (decal ids only have to be unique within a given decal system) -*/ - -class MultiFixedPoolDecalSystemClass : public DecalSystemClass -{ - -public: - - MultiFixedPoolDecalSystemClass(uint32 num_pools, const uint32 *pool_sizes); - MultiFixedPoolDecalSystemClass(const MultiFixedPoolDecalSystemClass & that); - virtual ~MultiFixedPoolDecalSystemClass(void); - - // This clears the slot in addition to locking the generator, thus preventing any decal id - // collisions (since any decal previously in that slot will have the same id as the new one). - virtual DecalGeneratorClass * Lock_Decal_Generator(void); - - // This will register the decal in the system in the appropriate pool and slot (determined by - // the generator's pool and slot ids), removing any decal which may have been there before. - virtual void Unlock_Decal_Generator(DecalGeneratorClass * generator); - - // This notifies the system that a mesh which has decals on it was destroyed - therefore we - // need to remove the mesh from our list to avoid dangling pointers. - virtual void Decal_Mesh_Destroyed(uint32 id,DecalMeshClass * mesh); - - // Not part of the DecalSystemClass interface - this function removes any decal currently in - // the given slot in the given pool. - void Clear_Decal_Slot(uint32 pool_id, uint32 slot_id); - - // This one removes all decals in a given pool. - void Clear_Pool(uint32 pool_id); - - // And this one removes all decals in the system. - void Clear_All_Decals(void); - -protected: - - /* - ** This generates the decal ID when a generator is created. This decal system generates the - ** decal ID from a pool ID and slot ID which are part of the state of the system so someone - ** can set them before calling Lock_Decal_Generator() (which is where this function is called). - ** We do it this way to avoid needing to override Lock_Decal_Generator(). - */ - virtual uint32 Generate_Decal_Id(void) { return encode_decal_id(Generator_PoolID, Generator_SlotID); } - uint32 Generator_PoolID; // These should be set before calling Lock_Decal_Generator() - uint32 Generator_SlotID; // These should be set before calling Lock_Decal_Generator() - - class LogicalDecalClass; - - // Get a reference to the logical decal at the given pool and slot id (performs range chacking) - LogicalDecalClass & find_logical_decal(uint32 pool_id, uint32 slot_id); - - // Get a reference to the logical decal with the given decal id - LogicalDecalClass & find_logical_decal(uint32 decal_id); - - // The decal ids are formed so that the upper 16 bits are equal to the pool id and the lower - // 16 bits are equal to the slot id. - static uint32 encode_decal_id(uint32 pool_id, uint32 slot_id) { return (slot_id & 0xFFFF) | (pool_id << 16); } - static void decode_decal_id(uint32 decal_id, uint32 & pool_id, uint32 & slot_id) { slot_id = decal_id & 0xFFFF; pool_id = decal_id >> 16; } - - // A class to store the meshes to which the decal has been applied (so that they can be removed when needed) - class LogicalDecalClass - { - public: - LogicalDecalClass(void); - ~LogicalDecalClass(void); - - void Set(DecalGeneratorClass * generator); - - // Just clears any existing logical decal information, leaving the decal empty. - void Clear(uint32 decal_id); - - NonRefRenderObjListClass MeshList; - }; - - class LogicalDecalPoolClass - { - public: - LogicalDecalPoolClass(void); - ~LogicalDecalPoolClass(void); - - void Initialize(uint32 size); - - LogicalDecalClass * Array; - uint32 Size; - }; - - LogicalDecalPoolClass * Pools; - uint32 PoolCount; - -}; - - - - -#endif //DECALSYS_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/distlod.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/distlod.cpp deleted file mode 100644 index 2f096ea2c6..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/distlod.cpp +++ /dev/null @@ -1,1166 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/distlod.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 2/06/01 3:21p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * DistLODDefClass -- default constructor for DistLODDefClass * - * DistLODDefClass::DistLODDefClass -- manual constructor for DistLODDefClass * - * DistLODDefClass::~DistLODDefClass -- destructor for DistLODDefClass * - * DistLODDefClass::Free -- releases all memory in use by this object * - * DistLODDefClass::Load -- initialize this object from a W3D file * - * DistLODDefClass::read_header -- read the header from a W3D file * - * DistLODDefClass::read_node -- read a model node description from a W3D file * - * DistLODClass::DistLODClass -- constructor * - * DistLODClass::DistLODClass -- copy constructor * - * DistLODClass::~DistLODClass -- destructor * - * DistLODClass::Free -- releases memory in use * - * DistLODClass::Get_Name -- returns the name of this LOD object * - * DistLODClass::Get_Num_Polys -- returns the number of polys in this model * - * DistLODClass::Render -- Render this LOD. * - * DistLODClass::Special_Render -- custom render function * - * DistLODCLass::Get_Num_Sub_Objects -- returns the number of subobjects (levels of detail) * - * DistLODClass::Get_Sub_Object -- returns pointer to the specified sub-object (LOD) * - * DistLODCLass::Set_Transform -- sets the transform for this model * - * DistLODClass::Set_Position -- set the position of this object * - * DistLODClass::Set_Animation -- set the animation state of this model * - * DistLODClass::Set_Animation -- set the animation state of this model * - * DistLODClass::Set_Animation -- set the animation state to a blend of two anims * - * DistLODClass::Set_Animation -- set the animation state to a combination of anims * - * DistLODClass::Get_Num_Bones -- returns the number of bones * - * DistLODClass::Get_Bone_Name -- returns the name of the specified bone * - * DistLODClass::Get_Bone_Index -- returns the index of the given bone (if found) * - * DistLODClass::Get_Bone_Transform -- returns the transform of the given bone * - * DistLODClass::Get_Bone_Transform -- returns the transform of the given bone * - * DistLODClass::Capture_Bone -- take control of a bone * - * DistLODClass::Release_Bone -- release control of a bone * - * DistLODClass::Is_Bone_Captured -- check whether the given bone is captured * - * DistLODClass::Control_Bone -- set the transform for a captured bone * - * DistLODClass::Cast_Ray -- cast a ray against this model * - * DistLODClass::Cast_AABox -- perform an AABox cast against this model * - * DistLODClass::Cast_OBBox -- perform an OBBox cast against this model * - * DistLODCLass::Get_Num_Snap_Points -- returns number of snap points in this model * - * DistLODClass::Get_Snap_Point -- returns the i'th snap point * - * DistLODCLass::Scale -- scale this model; passes on to each LOD * - * DistLODClass::Scale -- scale this model; passes on to each LOD * - * DistLODClass::Update_LOD -- adjusts the current LOD based on the distance * - * DistLODClass::Increment_Lod -- moves to a higher detail LOD * - * DistLODClass::Decrement_Lod -- moves to a lower detail LOD * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "distlod.h" -#include "nstrdup.h" -#include "ww3d.h" -#include "assetmgr.h" -#include "camera.h" -#include "w3derr.h" -#include "wwdebug.h" -#include "chunkio.h" -#include "hlod.h" -#include "rinfo.h" -#include "coltest.h" -#include "inttest.h" - -/* -** Loader Instance -*/ -DistLODLoaderClass _DistLODLoader; - - -RenderObjClass * DistLODPrototypeClass::Create(void) -{ - DistLODClass * dist = NEW_REF( DistLODClass , ( *Definition ) ); - - // Have to pull each LOD out of the DistLOD, create a copy of the name - // and destroy the DistLOD so that the models are "containerless". Also - // invert the order of the models in the DistLOD - char * name = nstrdup(dist->Get_Name()); - WWASSERT(name != NULL); - - int count = dist->Get_Num_Sub_Objects(); - RenderObjClass ** robj = W3DNEWARRAY RenderObjClass * [count]; - int i=0; - for (; iGet_Sub_Object(i); - WWASSERT(robj[count - 1 - i] != NULL); - } - dist->Release_Ref(); - - WWDEBUG_SAY(("OBSOLETE Dist-LOD model found! Please re-export %s!\r\n",name)); - HLodClass * hlod = NEW_REF(HLodClass , (name,robj,count)); - - // Now, release the temporary refs and memory for the name - for (i=0; iRelease_Ref(); - } - free(name); - - return hlod; -} - -/* -** The Prototype Loader -*/ -PrototypeClass *DistLODLoaderClass::Load_W3D( ChunkLoadClass &cload ) -{ - DistLODDefClass * pCDistLODClass = W3DNEW DistLODDefClass; - - if (pCDistLODClass == NULL) - { - return NULL; - } - - if (pCDistLODClass->Load_W3D(cload) != WW3D_ERROR_OK) - { - // load failed, delete the model and return an error - delete pCDistLODClass; - return NULL; - - } else { - - // ok, accept this model! - DistLODPrototypeClass *pCLODProto = W3DNEW DistLODPrototypeClass (pCDistLODClass); - return pCLODProto; - } -} - - -/*********************************************************************************************** - * DistLODDefClass -- default constructor for DistLODDefClass * - * * - * DistLODDefClass is a "blueprint" for constructing a DistLODClass * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -DistLODDefClass::DistLODDefClass(void) : - Name(NULL), - LodCount(0), - Lods(NULL) -{ -} - - -/*********************************************************************************************** - * DistLODDefClass::DistLODDefClass -- manual constructor for DistLODDefClass * - * * - * This constructor allows you to create a DistLODDef Manually (and then use it to create * - * the desired DistLODClass). The array of DistLODModelDefStructs which you pass in will * - * only be read from so you are responsible for the memory used by them. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/15/98 GTH : Created. * - *=============================================================================================*/ -DistLODDefClass::DistLODDefClass(const char * name,int lodcount,DistLODNodeDefStruct * modeldefs) : - Name(NULL), - LodCount(0), - Lods(NULL) -{ - assert(name != NULL); - Name = nstrdup(name); - - LodCount = lodcount; - Lods = W3DNEWARRAY DistLODNodeDefStruct[LodCount]; - for (int i=0; iCreate_Render_Obj(def.Lods[i].Name); - assert(Lods[i].Model != NULL); - Lods[i].Model->Set_Container(this); - - // copy the distances - Lods[i].ResUpDist = def.Lods[i].ResUpDist; - Lods[i].ResDownDist = def.Lods[i].ResDownDist; - } - - Update_Sub_Object_Bits(); - Update_Obj_Space_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * DistLODClass::DistLODClass -- copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -DistLODClass::DistLODClass(const DistLODClass & that) : - CompositeRenderObjClass( that ) -{ - LodCount = that.LodCount; - CurLod = VpPushLod = that.CurLod; - - Lods = W3DNEWARRAY LODNodeClass[LodCount]; - for (int i=0; iClone(); - assert(Lods[i].Model != NULL); - Lods[i].Model->Set_Container(this); - - // copy the distances - Lods[i].ResUpDist = that.Lods[i].ResUpDist; - Lods[i].ResDownDist = that.Lods[i].ResDownDist; - } - Update_Obj_Space_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * DistLODClass::~DistLODClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -DistLODClass::~DistLODClass(void) -{ - Free(); -} - - -/*********************************************************************************************** - * DistLODClass::Free -- releases memory in use * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Free(void) -{ - if (Lods != NULL) { - for (int i=0; iSet_Container(NULL); - Lods[i].Model->Release_Ref(); - Lods[i].Model = NULL; - } - } - delete[] Lods; - Lods = NULL; - } - CurLod = 0; - LodCount = 0; -} - - -/*********************************************************************************************** - * DistLODClass::Get_Num_Polys -- returns the number of polys in this model * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * returns the number of polys in the *current* lod. * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -int DistLODClass::Get_Num_Polys(void) const -{ - return Lods[CurLod].Model->Get_Num_Polys(); -} - - -/*********************************************************************************************** - * DistLODClass::Render -- Render this LOD. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Render(RenderInfoClass & rinfo) -{ - if (Is_Not_Hidden_At_All() == false) { - return; - } - - Update_Lod(rinfo.Camera); - Lods[CurLod].Model->Render(rinfo); -} - - -/*********************************************************************************************** - * DistLODClass::Special_Render -- custom render function * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Special_Render(SpecialRenderInfoClass & rinfo) -{ - Update_Lod(rinfo.Camera); - Lods[CurLod].Model->Special_Render(rinfo); -} - - -/*********************************************************************************************** - * DistLODCLass::Get_Num_Sub_Objects -- returns the number of subobjects (levels of detail) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -int DistLODClass::Get_Num_Sub_Objects(void) const -{ - return LodCount; -} - - -/*********************************************************************************************** - * DistLODClass::Get_Sub_Object -- returns pointer to the specified sub-object (LOD) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -RenderObjClass * DistLODClass::Get_Sub_Object(int index) const -{ - assert(index >= 0); - assert(index < LodCount); - - if (Lods[index].Model == NULL) { - return NULL; - } else { - Lods[index].Model->Add_Ref(); - return Lods[index].Model; - } -} - -int DistLODClass::Add_Sub_Object_To_Bone(RenderObjClass * subobj,int bone_index) -{ - // NOTE: this is broken code, a render object cannot have two containers... - if (subobj->Class_ID() == CLASSID_DISTLOD) { - // Add each lod of the sub object to a cooresponding model of mine - DistLODClass * sub_lod_obj = (DistLODClass *)subobj; - for (int i=0; i< LodCount; i++) { - Lods[i].Model->Add_Sub_Object_To_Bone( sub_lod_obj->Lods[ MIN( i, sub_lod_obj->LodCount-1 ) ].Model, bone_index); - } - } else { - Lods[0].Model->Add_Sub_Object_To_Bone( subobj, bone_index); - } - return 0; -} - - -/*********************************************************************************************** - * DistLODCLass::Set_Transform -- sets the transform for this model * - * * - * sets the transform in all LODs. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Set_Transform(const Matrix3D &m) -{ - RenderObjClass::Set_Transform(m); - for (int i=0; iSet_Transform(m); - } -} - - -/*********************************************************************************************** - * DistLODClass::Set_Position -- set the position of this object * - * * - * sets the position of all lods * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Set_Position(const Vector3 &v) -{ - RenderObjClass::Set_Position(v); - for (int i=0; iSet_Position(v); - } -} - - -/*********************************************************************************************** - * DistLODClass::Set_Animation -- set the animation state of this model * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Set_Animation( void ) -{ - for (int i=0; iSet_Animation(); - } -} - - -/*********************************************************************************************** - * DistLODClass::Set_Animation -- set the animation state of this model * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Set_Animation( HAnimClass * motion,float frame,int mode) -{ - for (int i=0; iSet_Animation(motion,frame,mode); - } -} - - -/*********************************************************************************************** - * DistLODClass::Set_Animation -- set the animation state to a blend of two anims * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Set_Animation( HAnimClass * motion0,float frame0,HAnimClass * motion1,float frame1,float percentage) -{ - for (int i=0; iSet_Animation(motion0,frame0,motion1,frame1,percentage); - } -} - - -/*********************************************************************************************** - * DistLODClass::Set_Animation -- set the animation state to a combination of anims * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Set_Animation( HAnimComboClass * anim_combo) -{ - for (int i=0; iSet_Animation( anim_combo); - } -} - - -/*********************************************************************************************** - * DistLODClass::Peek_Animation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - *=============================================================================================*/ -HAnimClass * DistLODClass::Peek_Animation( void ) -{ - return Lods[0].Model->Peek_Animation(); -} - - -/*********************************************************************************************** - * DistLODClass::Get_Num_Bones -- returns the number of bones * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -int DistLODClass::Get_Num_Bones(void) -{ - return Lods[0].Model->Get_Num_Bones(); -} - - -/*********************************************************************************************** - * DistLODClass::Get_Bone_Name -- returns the name of the specified bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -const char * DistLODClass::Get_Bone_Name(int bone_index) -{ - return Lods[0].Model->Get_Bone_Name(bone_index); -} - - -/*********************************************************************************************** - * DistLODClass::Get_Bone_Index -- returns the index of the given bone (if found) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -int DistLODClass::Get_Bone_Index(const char * bonename) -{ - // Highest LOD is used since lowest may be a Null3DObjClass. - return Lods[0].Model->Get_Bone_Index(bonename); -} - - -/*********************************************************************************************** - * DistLODClass::Get_Bone_Transform -- returns the transform of the given bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -const Matrix3D & DistLODClass::Get_Bone_Transform(const char * bonename) -{ - // Highest LOD is used since lowest may be a Null3DObjClass. - return Lods[0].Model->Get_Bone_Transform(bonename); -} - - -/*********************************************************************************************** - * DistLODClass::Get_Bone_Transform -- returns the transform of the given bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -const Matrix3D & DistLODClass::Get_Bone_Transform(int boneindex) -{ - // Highest LOD is used since lowest may be a Null3DObjClass. - return Lods[0].Model->Get_Bone_Transform(boneindex); -} - - -/*********************************************************************************************** - * DistLODClass::Capture_Bone -- take control of a bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Capture_Bone(int bindex) -{ - for (int i=0; iCapture_Bone(bindex); - } -} - - -/*********************************************************************************************** - * DistLODClass::Release_Bone -- release control of a bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Release_Bone(int bindex) -{ - for (int i=0; iRelease_Bone(bindex); - } -} - - -/*********************************************************************************************** - * DistLODClass::Is_Bone_Captured -- check whether the given bone is captured * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -bool DistLODClass::Is_Bone_Captured(int bindex) const -{ - // Highest LOD is used since lowest may be a Null3DObjClass. - return Lods[0].Model->Is_Bone_Captured(bindex); -} - - -/*********************************************************************************************** - * DistLODClass::Control_Bone -- set the transform for a captured bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Control_Bone(int bindex,const Matrix3D & tm,bool world_space_translation) -{ - for (int i=0; iControl_Bone(bindex,tm,world_space_translation); - } -} - -/*********************************************************************************************** - * DistLODClass::Cast_Ray -- cast a ray against this model * - * * - * casts the ray against the top-level LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -bool DistLODClass::Cast_Ray(RayCollisionTestClass & raytest) -{ - if (raytest.CollisionType & Get_Collision_Type()) { - return Lods[HIGHEST_LOD].Model->Cast_Ray(raytest); - } else { - return false; - } -} - - -/*********************************************************************************************** - * DistLODClass::Cast_AABox -- perform an AABox cast against this model * - * * - * tests against the top-level LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/3/99 GTH : Created. * - *=============================================================================================*/ -bool DistLODClass::Cast_AABox(AABoxCollisionTestClass & boxtest) -{ - if (boxtest.CollisionType & Get_Collision_Type()) { - return Lods[HIGHEST_LOD].Model->Cast_AABox(boxtest); - } else { - return false; - } -} - - -/*********************************************************************************************** - * DistLODClass::Cast_OBBox -- perform an OBBox cast against this model * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -bool DistLODClass::Cast_OBBox(OBBoxCollisionTestClass & boxtest) -{ - if (boxtest.CollisionType & Get_Collision_Type()) { - return Lods[HIGHEST_LOD].Model->Cast_OBBox(boxtest); - } else { - return false; - } -} - - -/*********************************************************************************************** - * DistLODCLass::Get_Num_Snap_Points -- returns number of snap points in this model * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -int DistLODClass::Get_Num_Snap_Points(void) -{ - return Lods[0].Model->Get_Num_Snap_Points(); -} - - -/*********************************************************************************************** - * DistLODClass::Get_Snap_Point -- returns the i'th snap point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Get_Snap_Point(int index,Vector3 * set) -{ - Lods[0].Model->Get_Snap_Point(index,set); -} - - -/*********************************************************************************************** - * DistLODCLass::Scale -- scale this model; passes on to each LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Scale(float scale) -{ - for (int i=0; iScale(scale); - } -} - - -/*********************************************************************************************** - * DistLODClass::Scale -- scale this model; passes on to each LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Scale(float scalex, float scaley, float scalez) -{ - for (int i=0; iScale(scalex,scaley,scalez); - } -} - - -/*********************************************************************************************** - * DistLODClass::Update_LOD -- adjusts the current LOD based on the distance * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Update_Lod(const CameraClass & camera) -{ - // evaluate the distance from the camera and select an LOD based on it. - float dist = ( - camera.Get_Position() - - Lods[CurLod].Model->Get_Bounding_Sphere().Center - ).Quick_Length(); - - if (dist < Lods[CurLod].ResUpDist) { - Increment_Lod(); - } else if (dist > Lods[CurLod].ResDownDist) { - Decrement_Lod(); - } -} - - -/*********************************************************************************************** - * DistLODClass::Increment_Lod -- moves to a higher detail LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Increment_Lod(void) -{ - // TODO: change the order in which models are stored - if (CurLod > 0) { - if (Is_In_Scene()) { - Lods[CurLod].Model->Notify_Removed(Scene); - } - CurLod--; - if (Is_In_Scene()) { - Lods[CurLod].Model->Notify_Added(Scene); - } - } -} - - -/*********************************************************************************************** - * DistLODClass::Decrement_Lod -- moves to a lower detail LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/99 GTH : Created. * - *=============================================================================================*/ -void DistLODClass::Decrement_Lod(void) -{ - if (CurLod < LodCount - 1) { - if (Is_In_Scene()) { - Lods[CurLod].Model->Notify_Removed(Scene); - } - CurLod++; - if (Is_In_Scene()) { - Lods[CurLod].Model->Notify_Added(Scene); - } - } -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/distlod.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/distlod.h deleted file mode 100644 index a17240aa54..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/distlod.h +++ /dev/null @@ -1,246 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/distlod.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/25/01 2:46p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DISTLOD_H -#define DISTLOD_H - -#include "proto.h" -#include "rendobj.h" -#include "composite.h" -#include "w3derr.h" - -class ChunkLoadClass; -struct DistLODNodeDefStruct; -class DistLODDefClass; - - -/* -** DistLODClass -** Distance based LOD switching. This is a simple LOD object which switches models -** based on the pre-set distances. Note that the models are stored in order of -** descending resolution; i.e. the highest res model will be in index 0. -** Most functions in this class simply pass the call on to all of the LODs. -** -** When the level of detail is changed, the LOD which was being used must be -** notified that it is being removed from the scene and the new LOD must be -** notified that it is being added. This allows us to correctly handle lights -** and particle emitters in LODs... -*/ -class DistLODClass : public CompositeRenderObjClass -{ -public: - - DistLODClass(const DistLODDefClass & desc); - DistLODClass(const DistLODClass & that); - virtual ~DistLODClass(void); - virtual RenderObjClass * Clone(void) const { return W3DNEW DistLODClass(*this); } - virtual int Class_ID(void) const { return CLASSID_DISTLOD; } - virtual int Get_Num_Polys(void) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Rendering - ///////////////////////////////////////////////////////////////////////////// - virtual void Render(RenderInfoClass & rinfo); - virtual void Special_Render(SpecialRenderInfoClass & rinfo); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - "Scene Graph" - // Access each LOD individually through Get_Sub_Object. - ///////////////////////////////////////////////////////////////////////////// - virtual void Set_Transform(const Matrix3D &m); - virtual void Set_Position(const Vector3 &v); - - virtual int Get_Num_Sub_Objects(void) const; - virtual RenderObjClass * Get_Sub_Object(int index) const; - - virtual int Add_Sub_Object_To_Bone(RenderObjClass * subobj,int bone_index); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Hierarchical Animation - // Here again, these functions are passed on to all LODs. Each LOD is - // assumed to use the same HTree (or have no HTree, this is so that LODs are - // animation-compatible) so the bone query functions simply pass to the top - // LOD. - ///////////////////////////////////////////////////////////////////////////// - virtual void Set_Animation( void ); - virtual void Set_Animation( HAnimClass * motion, float frame, int anim_mode = ANIM_MODE_MANUAL); - virtual void Set_Animation( HAnimClass * motion0,float frame0,HAnimClass * motion1,float frame1,float percentage); - virtual void Set_Animation( HAnimComboClass * anim_combo); - virtual HAnimClass * Peek_Animation( void ); - virtual int Get_Num_Bones(void); - virtual const char * Get_Bone_Name(int bone_index); - virtual int Get_Bone_Index(const char * bonename); - virtual const Matrix3D & Get_Bone_Transform(const char * bonename); - virtual const Matrix3D & Get_Bone_Transform(int boneindex); - virtual void Capture_Bone(int bindex); - virtual void Release_Bone(int bindex); - virtual bool Is_Bone_Captured(int bindex) const; - virtual void Control_Bone(int bindex,const Matrix3D & tm,bool world_space_translation = false); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Collision Detection, Ray Tracing - // Collision tests are performed on the top-level LOD. - ///////////////////////////////////////////////////////////////////////////// - virtual bool Cast_Ray(RayCollisionTestClass & raytest); - virtual bool Cast_AABox(AABoxCollisionTestClass & boxtest); - virtual bool Cast_OBBox(OBBoxCollisionTestClass & boxtest); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Attributes, Options, Properties, etc - ///////////////////////////////////////////////////////////////////////////// - virtual int Get_Num_Snap_Points(void); - virtual void Get_Snap_Point(int index,Vector3 * set); - virtual void Scale(float scale); - virtual void Scale(float scalex, float scaley, float scalez); - - ///////////////////////////////////////////////////////////////////////////// - // DistLOD Interface - ///////////////////////////////////////////////////////////////////////////// - virtual float Get_Switch_Up_Dist(int index) const { return Lods[index].ResUpDist; } - virtual float Get_Switch_Down_Dist(int index) const { return Lods[index].ResDownDist; } - virtual void Set_Switch_Up_Dist(int index, float dist) { Lods[index].ResUpDist = dist; } - virtual void Set_Switch_Down_Dist(int index, float dist) { Lods[index].ResDownDist = dist; } - -private: - - enum { HIGHEST_LOD = 0 }; - - void Free(void); - void Update_Lod(const CameraClass & camera); - void Increment_Lod(void); - void Decrement_Lod(void); - - struct LODNodeClass - { - RenderObjClass * Model; - float ResUpDist; - float ResDownDist; - }; - - int LodCount; // how many models are in this LOD object - int CurLod; // which model is currently used for rendering - int VpPushLod; // which model was used for the vp->push (in CurLod changes before the pop) - LODNodeClass * Lods; // one LODNodeClass for each level -}; - - -/* -** Loaders for DistLODClass -*/ -class DistLODLoaderClass : public PrototypeLoaderClass -{ -public: - - virtual int Chunk_Type (void) { return W3D_CHUNK_LODMODEL; } - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload); -}; - -/* -** DistLODModelDefStruct -** Describes a single model in a Distance-Based LOD Object -*/ -struct DistLODNodeDefStruct -{ - DistLODNodeDefStruct(void) : Name(NULL),ResDownDist(0.0f),ResUpDist(0.0f) {} - - char * Name; - float ResDownDist; - float ResUpDist; -}; - -/* -** DistLODDefClass -** Description of a Distance-Based LOD Object. These are similar -** to the HModelDef's that are used by the asset manager to construct -** HModels. -*/ -class DistLODDefClass -{ -public: - - DistLODDefClass(void); - DistLODDefClass(const char * name,int lodcount,DistLODNodeDefStruct * lods); - ~DistLODDefClass(void); - - WW3DErrorType Load_W3D(ChunkLoadClass & cload); - const char * Get_Name(void) const { return Name; } - -private: - - char * Name; - - int LodCount; - DistLODNodeDefStruct * Lods; - - void Free(void); - bool read_header(ChunkLoadClass & cload); - bool read_node(ChunkLoadClass & cload,DistLODNodeDefStruct * node); - - friend class DistLODClass; -}; - -/* -** Prototype for Dist-LOD objects -*/ -class DistLODPrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(DistLODPrototypeClass) -public: - DistLODPrototypeClass( DistLODDefClass *def ) { Definition = def; } - - virtual const char * Get_Name(void) const { return Definition->Get_Name(); } - virtual int Get_Class_ID(void) const { return RenderObjClass::CLASSID_DISTLOD; } - virtual RenderObjClass * Create(void); - virtual void DeleteSelf() { delete this; } - -protected: - virtual ~DistLODPrototypeClass(void) { delete Definition; } - -private: - DistLODDefClass * Definition; -}; - -/* -** Instance of the loaders which the asset manager install -*/ -extern DistLODLoaderClass _DistLODLoader; - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dllist.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dllist.h deleted file mode 100644 index 2748c17c25..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dllist.h +++ /dev/null @@ -1,211 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/dllist.h $* - * * - * Original Author:: Jani Penttinen * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 3/21/01 6:18p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DLLIST_H -#define DLLIST_H - - -template class DLNodeClass; - -template -class DLListClass -{ - friend DLNodeClass; - DLNodeClass* head; - DLNodeClass* tail; - -public: - DLListClass() : head(0), tail(0) {} - virtual ~DLListClass() { } - - void Add_Head(DLNodeClass* node); - void Remove_Head(); - void Add_Tail(DLNodeClass* node); - void Remove_Tail(); - - T* Head() { return static_cast(head); } - T* Tail() { return static_cast(tail); } - const T* Const_Head() const { return static_cast(head); } - const T* Const_Tail() const { return static_cast(tail); } -}; - -// Destroy-list will call delete for all nodes when the list is destructed. Note that the class doesn't work -// with undeclared pointer types (destructor has to be known). -template -class DLDestroyListClass : public DLListClass -{ - using DLListClass::Head; - -public: - virtual ~DLDestroyListClass() - { - while (T* t=Head()) { - delete t; - } - } -}; - -template -class DLNodeClass : public W3DMPO -{ - // nope, this is an ABC - //W3DMPO_GLUE(DLNodeClass) - - friend DLListClass; - DLNodeClass* succ; - DLNodeClass* pred; - DLListClass* list; -public: - DLNodeClass() : succ(0), pred(0), list(0) {} - ~DLNodeClass() { Remove(); } - - void Insert_Before(DLNodeClass* n) - { - list=n->list; - succ=n; - pred=n->pred; - if (n->pred) n->pred->succ=this; - n->pred=this; - - if (list->head==n) { - list->head=this; - } - } - - void Insert_After(DLNodeClass* n) - { - list=n->list; - pred=n; - succ=n->succ; - if (n->succ) n->succ->pred=this; - n->succ=this; - - if (list->tail==n) { - list->tail=this; - } - } - - void Remove() - { - if (!list) return; - if (list->Head()==this) { - DLListClass* tmp_list=list; - list=0; - tmp_list->Remove_Head(); - return; - } - if (list->Tail()==this) { - DLListClass* tmp_list=list; - list=0; - tmp_list->Remove_Tail(); - return; - } - if (succ) succ->pred=pred; - if (pred) pred->succ=succ; - list=0; - } - - - T* Succ() { return static_cast(succ); } - T* Pred() { return static_cast(pred); } - const T* Const_Succ() const { return static_cast(succ); } - const T* Const_Pred() const { return static_cast(pred); } - - DLListClass* List() { return list; } -}; - - -template -inline void DLListClass::Add_Head(DLNodeClass* n) -{ - n->list=this; - if (head) { - n->Insert_Before(head); - head=n; - } - else { - tail=n; - head=n; - n->succ=0; - n->pred=0; - } -} - -template -inline void DLListClass::Add_Tail(DLNodeClass* n) -{ - n->list=this; - if (tail) { - n->Insert_After(tail); - tail=n; - } - else { - tail=n; - head=n; - n->succ=0; - n->pred=0; - } -} - -template -inline void DLListClass::Remove_Head() -{ - if (!head) return; - DLNodeClass* n=head; - head=head->Succ(); - if (!head) tail=head; - else head->pred=0; - n->Remove(); -} - -template -inline void DLListClass::Remove_Tail() -{ - if (!tail) return; - DLNodeClass* n=tail; - tail=tail->Pred(); - if (!tail) head=tail; - else tail->succ=0; - n->Remove(); -} - -#endif //DLLIST_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp index dee9853b43..356f4c96de 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.cpp @@ -22,16 +22,17 @@ * * * Project Name : dx8 caps * * * - * $Archive:: /VSS_Sync/ww3d2/dx8caps.cpp $* + * $Archive:: /Commando/Code/ww3d2/dx8caps.cpp $* * * * Original Author:: Hector Yee * * * - * $Author:: Vss_sync $* + * Author : Kenny Mitchell * + * * + * $Modtime:: 06/27/02 1:27p $* * * - * $Modtime:: 8/29/01 8:16p $* - * * - * $Revision:: 11 $* + * $Revision:: 31 $* * * + * 06/27/02 KM Z Format support * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -40,6 +41,11 @@ #include "dx8caps.h" #include "dx8wrapper.h" #include "formconv.h" +#pragma warning (disable : 4201) // nonstandard extension - nameless struct +#include +#include + +static StringClass CapsWorkString; enum { @@ -47,11 +53,429 @@ enum { VENROD_ID_ATI=0x1002 }; + +static const char* VendorNames[]={ + "Unknown", + "NVidia", + "ATI", + "Intel", + "S3", + "PowerVR", + "Matrox", + "3Dfx", + "3DLabs", + "CirrusLogic", + "Rendition" +}; + +DX8Caps::VendorIdType DX8Caps::Define_Vendor(unsigned vendor_id) +{ + switch (vendor_id) { + case 0x3d3d: + case 0x104c: return VENDOR_3DLABS; + case 0x12D2: // STB - NVIDIA's Riva128 + case 0x14AF: // Guillemot's NVIDIA based cards + case 0x10de: return VENDOR_NVIDIA; + case 0x1002: return VENDOR_ATI; + case 0x8086: return VENDOR_INTEL; + case 0x5333: return VENDOR_S3; + case 0x104A: return VENDOR_POWERVR; + case 0x102B: return VENDOR_MATROX; + case 0x1142: // Alliance based reference cards + case 0x109D: // Macronix based reference cards + case 0x121A: return VENDOR_3DFX; + default: + return VENDOR_UNKNOWN; + } +} + +static const char* DeviceNamesNVidia[]={ + "Unknown NVidia device", + "GeForce3", + "Quadro2 PRO", + "GeForce2 Go", + "GeForce2 ULTRA", + "GeForce2 GTS", + "Quadro", + "GeForce DDR", + "GeForce 256", + "TNT2 Aladdin", + "TNT2", + "TNT2 ULTRA", + "TNT2 Vanta", + "TNT2 M64", + "TNT", + "RIVA 128", + "TNT Vanta", + "NV1", + "GeForce2 MX" + "GeForce4 Ti 4600", + "GeForce4 Ti 4400", + "GeForce4 Ti", + "GeForce4 Ti 4200", + "GeForce4 MX 460", + "GeForce4 MX 440", + "GeForce4 MX 420", + "GeForce4", + "GeForce4 Go 440", + "GeForce4 Go 420", + "GeForce4 Go 420 32M", + "GeForce4 Go 440 64M", + "GeForce4 Go", + "GeForce3 Ti 500", + "GeForce3 Ti 200", + "GeForce2 Integrated", + "GeForce2 Ti", + "Quadro2 MXR//EX//GO", + "GeFORCE2_MX 100//200", + "GeFORCE2_MX 400", + "Quadro DCC" +}; + +static const char* DeviceNamesATI[]={ + "Unknown ATI Device", + "Rage II", + "Rage II+", + "Rage IIc PCI", + "Rage IIc AGP", + "Rage 128 Mobility", + "Rage 128 Mobility M3", + "Rage 128 Mobility M4", + "Rage 128 PRO ULTRA", + "Rage 128 4X", + "Rage 128 PRO GL", + "Rage 128 PRO VR", + "Rage 128 GL", + "Rage 128 VR", + "Rage PRO", + "Rage PRO Mobility", + "Mobility Radeon", + "Mobility Radeon VE(M6)", + "Radeon VE", + "Radeon DDR", + "Radeon", + "Mobility R7500", + "R7500", + "R8500" +}; + +static const char* DeviceNames3DLabs[]={ + "Unknown 3DLabs Device", + "Permedia", + "300SX", + "500TX", + "Delta", + "MX", + "Gamma", + "Permedia2S (ST)", + "Permedia3", + "R3", + "Permedia4", + "R4", + "G2", + "Oxygen VX1", + "TI P1", + "Permedia2" +}; + +static const char* DeviceNames3Dfx[]={ + "Unknown 3Dfx Device", + "Voodoo 5500 AGP", + "Voodoo 3", + "Banshee", + "Voodoo 2", + "Voodoo Graphics", + "Voodoo Rush" +}; + +static const char* DeviceNamesMatrox[]={ + "Unknown Matrox Device", + "G550", + "G400", + "G200 AGP", + "G200 PCI", + "G100 PCI", + "G100 AGP", + "Millennium II AGP", + "Millennium II PCI", + "Mystique", + "Millennium", + "Parhelia", + "Parhelia AGP 8X" +}; + +static const char* DeviceNamesPowerVR[]={ + "Unknown PowerVR Device", + "Kyro" +}; + +static const char* DeviceNamesS3[]={ + "Unknown S3 Device", + "Savage MX", + "Savage 4", + "Savage 200" +}; + +static const char* DeviceNamesIntel[]={ + "Unknown Intel Device", + "i810", + "i810e", + "i815" +}; + +DX8Caps::DeviceTypeATI DX8Caps::Get_ATI_Device(unsigned device_id) +{ + switch (device_id) { + case 0x4754: return DEVICE_ATI_RAGE_II; + case 0x4755: return DEVICE_ATI_RAGE_II_PLUS; + case 0x5656: return DEVICE_ATI_RAGE_IIC_PCI; + case 0x4756: return DEVICE_ATI_RAGE_IIC_PCI; + case 0x475A: return DEVICE_ATI_RAGE_IIC_AGP; + case 0x4759: return DEVICE_ATI_RAGE_IIC_AGP; + case 0x4757: return DEVICE_ATI_RAGE_IIC_AGP; + case 0x4742: + case 0x4744: + case 0x4749: + case 0x4750: + case 0x474C: + case 0x474E: + case 0x474D: + case 0x474F: + case 0x4752: return DEVICE_ATI_RAGE_PRO; + + case 0x4C4D: + case 0x4C52: + case 0x4C42: + case 0x4C49: + case 0x4C50: return DEVICE_ATI_RAGE_PRO_MOBILITY; + + case 0x4C57: return DEVICE_ATI_MOBILITY_R7500; + + case 0x4C59: + case 0x4C5A: return DEVICE_ATI_MOBILITY_RADEON_VE_M6; + + case 0x4D46: + case 0x4D4C: return DEVICE_ATI_RAGE_128_MOBILITY_M4; + case 0x4C45: + case 0x4C46: return DEVICE_ATI_RAGE_128_MOBILITY_M3; + + case 0x5041: + case 0x5042: + case 0x5043: + case 0x5044: + case 0x5045: + case 0x5046: return DEVICE_ATI_RAGE_128_PRO_GL; + + case 0x5047: + case 0x5048: + case 0x5049: + case 0x504A: + case 0x504B: + case 0x504C: + case 0x504D: + case 0x504E: + case 0x504F: + case 0x5050: + case 0x5051: + case 0x5052: + case 0x5053: + case 0x5054: + case 0x5055: + case 0x5056: + case 0x5057: + case 0x5058: return DEVICE_ATI_RAGE_128_PRO_VR; + + case 0x5159: + case 0x515A: return DEVICE_ATI_RADEON_VE; + + case 0x5144: + case 0x5145: + case 0x5146: + case 0x5147: return DEVICE_ATI_RADEON_DDR; + + case 0x514c: + case 0x514e: + case 0x514f: return DEVICE_ATI_R8500; + + case 0x5157: return DEVICE_ATI_R7500; + + case 0x5245: + case 0x5246: + case 0x534B: + case 0x534C: + case 0x534D: return DEVICE_ATI_RAGE_128_GL; + + case 0x524B: + case 0x524C: + case 0x5345: + case 0x5346: + case 0x5347: return DEVICE_ATI_RAGE_128_VR; + + case 0x5446: + case 0x544C: + case 0x5452: + case 0x5453: + case 0x5454: + case 0x5455: return DEVICE_ATI_RAGE_128_PRO_ULTRA; + + case 0x534E: return DEVICE_ATI_RAGE_128_4X; + + default: return DEVICE_ATI_UNKNOWN; + } +} + +DX8Caps::DeviceType3DLabs DX8Caps::Get_3DLabs_Device(unsigned device_id) +{ + switch (device_id) { + case 0x0001: return DEVICE_3DLABS_300SX; + case 0x0002: return DEVICE_3DLABS_500TX; + case 0x0003: return DEVICE_3DLABS_DELTA; + case 0x0004: return DEVICE_3DLABS_PERMEDIA; + case 0x0006: return DEVICE_3DLABS_MX; + case 0x0007: return DEVICE_3DLABS_PERMEDIA2; + case 0x0008: return DEVICE_3DLABS_GAMMA; + case 0x0009: return DEVICE_3DLABS_PERMEDIA2S_ST; + case 0x000a: return DEVICE_3DLABS_PERMEDIA3; + case 0x000b: return DEVICE_3DLABS_R3; + case 0x000c: return DEVICE_3DLABS_PERMEDIA4; + case 0x000d: return DEVICE_3DLABS_R4; + case 0x000e: return DEVICE_3DLABS_G2; + case 0x4C59: return DEVICE_3DLABS_OXYGEN_VX1; + case 0x3D04: return DEVICE_3DLABS_TI_P1; + case 0x3D07: return DEVICE_3DLABS_PERMEDIA2; + default: return DEVICE_3DLABS_UNKNOWN; + } +} + +DX8Caps::DeviceTypeNVidia DX8Caps::Get_NVidia_Device(unsigned device_id) +{ + switch (device_id) { + case 0x0250: return DEVICE_NVIDIA_GEFORCE4_TI_4600; + case 0x0251: return DEVICE_NVIDIA_GEFORCE4_TI_4400; + case 0x0252: return DEVICE_NVIDIA_GEFORCE4_TI; + case 0x0253: return DEVICE_NVIDIA_GEFORCE4_TI_4200; + case 0x0170: return DEVICE_NVIDIA_GEFORCE4_MX_460; + case 0x0171: return DEVICE_NVIDIA_GEFORCE4_MX_440; + case 0x0172: return DEVICE_NVIDIA_GEFORCE4_MX_420; + case 0x0173: return DEVICE_NVIDIA_GEFORCE4; + case 0x0174: return DEVICE_NVIDIA_GEFORCE4_GO_440; + case 0x0175: return DEVICE_NVIDIA_GEFORCE4_GO_420; + case 0x0176: return DEVICE_NVIDIA_GEFORCE4_GO_420_32M; + case 0x0178: return DEVICE_NVIDIA_GEFORCE4_GO; + case 0x0179: return DEVICE_NVIDIA_GEFORCE4_GO_440_64M; + case 0x0203: return DEVICE_NVIDIA_QUADRO_DCC; + case 0x0202: return DEVICE_NVIDIA_GEFORCE3_TI_500; + case 0x0201: return DEVICE_NVIDIA_GEFORCE3_TI_200; + case 0x0200: return DEVICE_NVIDIA_GEFORCE3; + case 0x01A0: return DEVICE_NVIDIA_GEFORCE2_INTEGRATED; + case 0x0153: return DEVICE_NVIDIA_QUADRO2_PRO; + case 0x0152: return DEVICE_NVIDIA_GEFORCE2_ULTRA; + case 0x0151: return DEVICE_NVIDIA_GEFORCE2_TI; + case 0x0150: return DEVICE_NVIDIA_GEFORCE2_GTS; + case 0x0113: return DEVICE_NVIDIA_QUADRO2_MXR_EX_GO; + case 0x0112: return DEVICE_NVIDIA_GEFORCE2_GO; + case 0x0111: return DEVICE_NVIDIA_GEFORCE2_MX_100_200; + case 0x0110: return DEVICE_NVIDIA_GEFORCE2_MX_400; + case 0x0103: return DEVICE_NVIDIA_QUADRO; + case 0x0101: return DEVICE_NVIDIA_GEFORCE_DDR; + case 0x0100: return DEVICE_NVIDIA_GEFORCE_256; + case 0x00A0: return DEVICE_NVIDIA_TNT2_ALADDIN; + case 0x0028: return DEVICE_NVIDIA_TNT2; + case 0x0029: return DEVICE_NVIDIA_TNT2_ULTRA; + case 0x002C: return DEVICE_NVIDIA_TNT2_VANTA; + case 0x002D: return DEVICE_NVIDIA_TNT2_M64; + case 0x0020: return DEVICE_NVIDIA_TNT; + case 0x0008: return DEVICE_NVIDIA_NV1; + + // STB cards + case 0x0019: + case 0x0018: return DEVICE_NVIDIA_RIVA_128; + + // Guillemot Cards + case 0x5008: return DEVICE_NVIDIA_TNT_VANTA; // Maxi Gamer Phoenix 2 + case 0x5810: return DEVICE_NVIDIA_TNT2; // Maxi Gamer Xentor + case 0x5820: return DEVICE_NVIDIA_TNT2_ULTRA; // Maxi Gamer Xentor 32 + case 0x4d20: return DEVICE_NVIDIA_TNT2_M64; // Maxi Gamer Cougar + case 0x5620: return DEVICE_NVIDIA_TNT2_M64; // Maxi Gamer Cougar Video Edition + case 0x5020: return DEVICE_NVIDIA_GEFORCE_256; // Maxi Gamer 3D Prophet + + default: return DEVICE_NVIDIA_UNKNOWN; + } +} + + +DX8Caps::DeviceType3Dfx DX8Caps::Get_3Dfx_Device(unsigned device_id) +{ + switch (device_id) { + case 0x0009: return DEVICE_3DFX_VOODOO_5500_AGP; + case 0x0005: return DEVICE_3DFX_VOODOO_3; + case 0x0003: return DEVICE_3DFX_BANSHEE; + case 0x0002: return DEVICE_3DFX_VOODOO_2; + case 0x0001: return DEVICE_3DFX_VOODOO_GRAPHICS; + case 0x643d: // Alliance AT25/AT3D based reference board + case 0x8626: // Macronix based reference board + return DEVICE_3DFX_VOODOO_RUSH; + default: return DEVICE_3DFX_UNKNOWN; + } +} + +DX8Caps::DeviceTypeMatrox DX8Caps::Get_Matrox_Device(unsigned device_id) +{ + switch (device_id) { + case 0x2527: return DEVICE_MATROX_G550; + case 0x0525: return DEVICE_MATROX_G400; + case 0x0521: return DEVICE_MATROX_G200_AGP; + case 0x0520: return DEVICE_MATROX_G200_PCI; + case 0x1000: return DEVICE_MATROX_G100_PCI; + case 0x1001: return DEVICE_MATROX_G100_AGP; + case 0x051F: return DEVICE_MATROX_MILLENNIUM_II_AGP; + case 0x051B: return DEVICE_MATROX_MILLENNIUM_II_PCI; + case 0x051A: return DEVICE_MATROX_MYSTIQUE; + case 0x0519: return DEVICE_MATROX_MILLENNIUM; + case 0x0527: return DEVICE_MATROX_PARHELIA; + case 0x0528: return DEVICE_MATROX_PARHELIA_AGP8X; + + default: return DEVICE_MATROX_UNKNOWN; + } +} + +DX8Caps::DeviceTypePowerVR DX8Caps::Get_PowerVR_Device(unsigned device_id) +{ + switch (device_id) { + case 0x0010: return DEVICE_POWERVR_KYRO; + default: return DEVICE_POWERVR_UNKNOWN; + } +} + +DX8Caps::DeviceTypeS3 DX8Caps::Get_S3_Device(unsigned device_id) +{ + switch (device_id) { + case 0x8C10: return DEVICE_S3_SAVAGE_MX; + case 0x8A22: return DEVICE_S3_SAVAGE_4; + case 0x9102: return DEVICE_S3_SAVAGE_200; + default: return DEVICE_S3_UNKNOWN; + } +} + +DX8Caps::DeviceTypeIntel DX8Caps::Get_Intel_Device(unsigned device_id) +{ + switch (device_id) { + case 0x7123: return DEVICE_INTEL_810; + case 0x7121: return DEVICE_INTEL_810E; + case 0x1132: return DEVICE_INTEL_815; + default: return DEVICE_INTEL_UNKNOWN; + } +} + DX8Caps::DX8Caps( IDirect3D8* direct3d, IDirect3DDevice8* D3DDevice, WW3DFormat display_format, const D3DADAPTER_IDENTIFIER8& adapter_id) + : + Direct3D(direct3d), + MaxDisplayWidth(0), + MaxDisplayHeight(0) { Init_Caps(D3DDevice); Compute_Caps(display_format, adapter_id); @@ -61,6 +485,7 @@ DX8Caps::DX8Caps( //they don't show up in our memory manager as a leak. -MW 7-22-03 void DX8Caps::Shutdown(void) { + CapsWorkString.Release_Resources(); } // ---------------------------------------------------------------------------- @@ -110,12 +535,15 @@ void DX8Caps::Compute_Caps(WW3DFormat display_format, const D3DADAPTER_IDENTIFIE supportGamma=((swVPCaps.Caps2&D3DCAPS2_FULLSCREENGAMMA)==D3DCAPS2_FULLSCREENGAMMA); + MaxTexturesPerPass=MAX_TEXTURE_STAGES; + Check_Texture_Format_Support(display_format,caps); Check_Texture_Compression_Support(caps); Check_Bumpmap_Support(caps); Check_Shader_Support(caps); Check_Maximum_Texture_Support(caps); Vendor_Specific_Hacks(adapter_id); + CapsWorkString=""; } // ---------------------------------------------------------------------------- @@ -147,20 +575,96 @@ void DX8Caps::Check_Texture_Compression_Support(const D3DCAPS8& caps) void DX8Caps::Check_Texture_Format_Support(WW3DFormat display_format,const D3DCAPS8& caps) { + if (display_format==WW3D_FORMAT_UNKNOWN) { + for (unsigned i=0;iCheckDeviceFormat( + Direct3D->CheckDeviceFormat( caps.AdapterOrdinal, caps.DeviceType, d3d_display_format, 0, D3DRTYPE_TEXTURE, - WW3DFormat_To_D3DFormat((WW3DFormat)i))); + WW3DFormat_To_D3DFormat(format))); + } + } +} + +void DX8Caps::Check_Render_To_Texture_Support(WW3DFormat display_format,const D3DCAPS8& caps) +{ + if (display_format==WW3D_FORMAT_UNKNOWN) { + for (unsigned i=0;iCheckDeviceFormat( + caps.AdapterOrdinal, + caps.DeviceType, + d3d_display_format, + D3DUSAGE_RENDERTARGET, + D3DRTYPE_TEXTURE, + WW3DFormat_To_D3DFormat(format))); + } + } +} + +//********************************************************************************************** +//! Check Depth Stencil Format Support +/*! KJM +*/ +void DX8Caps::Check_Depth_Stencil_Support(WW3DFormat display_format, const D3DCAPS8& caps) +{ + if (display_format==WW3D_FORMAT_UNKNOWN) + { + for (unsigned i=0;iCheckDeviceFormat + ( + caps.AdapterOrdinal, + caps.DeviceType, + d3d_display_format, + D3DUSAGE_DEPTHSTENCIL, + D3DRTYPE_TEXTURE, + WW3DZFormat_To_D3DFormat(format) + ) + ); } } } @@ -199,3 +703,4 @@ void DX8Caps::Vendor_Specific_Hacks(const D3DADAPTER_IDENTIFIER8& adapter_id) // SupportDXTC=false; } + diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h index b5a4d5060b..28c1b983b1 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8caps.h @@ -22,16 +22,17 @@ * * * Project Name : DX8 Caps * * * - * $Archive:: /VSS_Sync/ww3d2/dx8caps.h $* + * $Archive:: /Commando/Code/ww3d2/dx8caps.h $* * * * Original Author:: Hector Yee * * * - * $Author:: Vss_sync $* + * Author : Kenny Mitchell * + * * + * $Modtime:: 06/27/02 1:27p $* * * - * $Modtime:: 8/29/01 8:16p $* - * * - * $Revision:: 8 $* + * $Revision:: 24 $* * * + * 06/27/02 KM Z Format support * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ @@ -217,6 +218,7 @@ class DX8Caps bool Support_Bump_Envmap() const { return SupportBumpEnvmap; } bool Support_Bump_Envmap_Luminance() const { return SupportBumpEnvmapLuminance; } bool Support_Dot3() const { return SupportDot3; } + int Get_Max_Textures_Per_Pass() const { return MaxTexturesPerPass; } // ------------------------------------------------------------------------- // @@ -232,6 +234,8 @@ class DX8Caps int Get_Max_Simultaneous_Textures() const { return MaxSimultaneousTextures;} bool Support_Texture_Format(WW3DFormat format) const { return SupportTextureFormat[format]; } + bool Support_Render_To_Texture_Format(WW3DFormat format) const { return SupportRenderToTextureFormat[format]; } + bool Support_Depth_Stencil_Format(WW3DZFormat format) const { return SupportDepthStencilFormat[format]; } D3DCAPS8 const & Get_DX8_Caps() const { return (SupportTnL?hwVPCaps:swVPCaps); } @@ -239,14 +243,29 @@ class DX8Caps D3DCAPS8 const & Get_SW_VP_Caps() const { return swVPCaps; }; private: + static VendorIdType Define_Vendor(unsigned vendor_id); + static DeviceTypeATI Get_ATI_Device(unsigned device_id); + static DeviceType3DLabs Get_3DLabs_Device(unsigned device_id); + static DeviceTypeNVidia Get_NVidia_Device(unsigned device_id); + static DeviceType3Dfx Get_3Dfx_Device(unsigned device_id); + static DeviceTypeMatrox Get_Matrox_Device(unsigned device_id); + static DeviceTypePowerVR Get_PowerVR_Device(unsigned device_id); + static DeviceTypeS3 Get_S3_Device(unsigned device_id); + static DeviceTypeIntel Get_Intel_Device(unsigned device_id); + void Init_Caps(IDirect3DDevice8* D3DDevice); void Check_Texture_Format_Support(WW3DFormat display_format,const D3DCAPS8& caps); + void Check_Render_To_Texture_Support(WW3DFormat display_format,const D3DCAPS8& caps); + void Check_Depth_Stencil_Support(WW3DFormat display_format, const D3DCAPS8& caps); void Check_Texture_Compression_Support(const D3DCAPS8& caps); void Check_Bumpmap_Support(const D3DCAPS8& caps); void Check_Shader_Support(const D3DCAPS8& caps); void Check_Maximum_Texture_Support(const D3DCAPS8& caps); void Vendor_Specific_Hacks(const D3DADAPTER_IDENTIFIER8& adapter_id); + int MaxDisplayWidth; + int MaxDisplayHeight; + D3DCAPS8 hwVPCaps; D3DCAPS8 swVPCaps; bool SupportTnL; @@ -256,10 +275,14 @@ class DX8Caps bool SupportBumpEnvmap; bool SupportBumpEnvmapLuminance; bool SupportTextureFormat[WW3D_FORMAT_COUNT]; + bool SupportRenderToTextureFormat[WW3D_FORMAT_COUNT]; + bool SupportDepthStencilFormat[WW3D_ZFORMAT_COUNT]; bool SupportDot3; + int MaxTexturesPerPass; int VertexShaderVersion; int PixelShaderVersion; int MaxSimultaneousTextures; + IDirect3D8* Direct3D; // warning XDK name conflict KJM }; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8list.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8list.h deleted file mode 100644 index 6873ac1c55..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8list.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/dx8list.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Hector_y $* - * * - * $Modtime:: 4/25/01 1:37p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DX8LIST_H -#define DX8LIST_H - -#include "always.h" -#include "multilist.h" - - -/* -** Here we're just typedefing some multi-lists so we don't have to write the -** long template names. -*/ -class DX8TextureCategoryClass; -typedef MultiListClass TextureCategoryList; -typedef MultiListIterator TextureCategoryListIterator; - -class DX8FVFCategoryContainer; -typedef MultiListClass FVFCategoryList; -typedef MultiListIterator FVFCategoryListIterator; - -class DX8PolygonRendererClass; -typedef MultiListClass DX8PolygonRendererList; -typedef MultiListIterator DX8PolygonRendererListIterator; - -class DX8TextureTrackerClass; -typedef MultiListClass DX8TextureTrackerList; -typedef MultiListIterator DX8TextureTrackerListIterator; - - -#endif //DX8LIST_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp deleted file mode 100644 index 7fed775016..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/dx8polygonrenderer.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 8/22/01 6:54p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#include "dx8polygonrenderer.h" -#include "dx8renderer.h" - - -// ---------------------------------------------------------------------------- - -DX8PolygonRendererClass::DX8PolygonRendererClass( - unsigned index_count_, - MeshModelClass* mmc_, - DX8TextureCategoryClass* tex_cat, - unsigned vertex_offset_, - unsigned index_offset_, - bool strip_, - unsigned pass_) - : - mmc(mmc_), - texture_category(tex_cat), - index_offset(index_offset_), - vertex_offset(vertex_offset_), - min_vertex_index(0), - vertex_index_range(0), - index_count(index_count_), - strip(strip_), - pass(pass_) -{ - WWASSERT(index_count); - mmc->PolygonRendererList.Add_Tail(this); -} - -DX8PolygonRendererClass::DX8PolygonRendererClass(const DX8PolygonRendererClass& src,MeshModelClass* mmc_) - : - mmc(mmc_), - texture_category(src.texture_category), - index_offset(src.index_offset), - vertex_offset(src.vertex_offset), - min_vertex_index(src.min_vertex_index), - vertex_index_range(src.vertex_index_range), - index_count(src.index_count), - strip(src.strip), - pass(src.pass) -{ - mmc->PolygonRendererList.Add_Tail(this); -} - -DX8PolygonRendererClass::~DX8PolygonRendererClass() -{ - if (texture_category) texture_category->Remove_Polygon_Renderer(this); -} - -// ---------------------------------------------------------------------------- - -void DX8PolygonRendererClass::Log() -{ - StringClass work(true); - - work.Format(" %8d %8d %6d %6d %6d %s\n", - index_count, - index_count/3, - index_offset, - min_vertex_index, - vertex_index_range, - mmc->Get_Name()); - -/* work.Format( - " Index count: %d (%d polys) i_offset: %d min_vi: %d vi_range: %d ident: %d (%s)\n", - index_count, - index_count/3, - index_offset, - min_vertex_index, - vertex_index_range, - mmc->ident, - mmc->Get_Name()); -*/ WWDEBUG_SAY((work)); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h deleted file mode 100644 index 10200285fc..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/dx8polygonrenderer.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 7/12/01 6:38p $* - * * - * $Revision:: 22 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DX8_POLYGON_RENDERER_H -#define DX8_POLYGON_RENDERER_H - - -#include "always.h" -#include "meshmdl.h" -#include "dx8list.h" -#include "sortingrenderer.h" -#include "mesh.h" -#include "dx8wrapper.h" - -class DX8PolygonRendererClass; -class DX8TextureCategoryClass; - - -/** -** DX8PolygonRendererClass -** This is a record of a batch/range of polygons to be rendered. These hang off of the DX8TextureCategoryClass's -** and are rendered after the system installs a vertex buffer and textures in the DX8 wrapper. -*/ -class DX8PolygonRendererClass : public MultiListObjectClass -{ - MeshModelClass * mmc; - DX8TextureCategoryClass * texture_category; - unsigned index_offset; // absolute index of index 0 for our parent mesh - unsigned vertex_offset; // absolute index of vertex 0 for our parent mesh - unsigned index_count; // number of indices - unsigned min_vertex_index; // relative index of the first vertex our polys reference - unsigned vertex_index_range; // range to the last vertex our polys reference - bool strip; // is this a strip? - unsigned pass; // rendering pass - -public: - DX8PolygonRendererClass( - unsigned index_count, - MeshModelClass* mmc_, - DX8TextureCategoryClass* tex_cat, - unsigned vertex_offset, - unsigned index_offset, - bool strip, - unsigned pass); - DX8PolygonRendererClass(const DX8PolygonRendererClass& src,MeshModelClass* mmc_); - ~DX8PolygonRendererClass(); - - void Render(/*const Matrix3D & tm,*/int base_vertex_offset); - void Render_Sorted(/*const Matrix3D & tm,*/int base_vertex_offset,const SphereClass & bounding_sphere); - void Set_Vertex_Index_Range(unsigned min_vertex_index_,unsigned vertex_index_range_); - - unsigned Get_Vertex_Offset(void) { return vertex_offset; } - unsigned Get_Index_Offset(void) { return index_offset; } - inline unsigned Get_Pass(void) { return pass; } - - MeshModelClass* Get_Mesh_Model_Class() { return mmc; } - DX8TextureCategoryClass* Get_Texture_Category() { return texture_category; } - void Set_Texture_Category(DX8TextureCategoryClass* tc) { texture_category=tc; } - - void Log(); -}; - -// ---------------------------------------------------------------------------- - -inline void DX8PolygonRendererClass::Set_Vertex_Index_Range(unsigned min_vertex_index_,unsigned vertex_index_range_) -{ -// WWDEBUG_SAY(("Set_Vertex_Index_Range - min: %d, range: %d\n",min_vertex_index_,vertex_index_range_)); -// if (vertex_index_range_>30000) { -// int a=0; -// a++; -// } - min_vertex_index=min_vertex_index_; - vertex_index_range=vertex_index_range_; -} - -// ---------------------------------------------------------------------------- - -inline void DX8PolygonRendererClass::Render(/*const Matrix3D & tm,*/int base_vertex_offset) -{ -// DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); -// SNAPSHOT_SAY(("Set_Transform\n")); - SNAPSHOT_SAY(("Set_Index_Buffer_Index_Offset(%d)\n",base_vertex_offset)); - - DX8Wrapper::Set_Index_Buffer_Index_Offset(base_vertex_offset); - if (strip) { - SNAPSHOT_SAY(("Draw_Strip(%d,%d,%d,%d)\n",index_offset,index_count-2,min_vertex_index,vertex_index_range)); - DX8Wrapper::Draw_Strip( - index_offset, - index_count-2, - min_vertex_index, - vertex_index_range); - } - else { - SNAPSHOT_SAY(("Draw_Triangles(%d,%d,%d,%d)\n",index_offset,index_count-2,min_vertex_index,vertex_index_range)); - DX8Wrapper::Draw_Triangles( - index_offset, - index_count/3, - min_vertex_index, - vertex_index_range); - } -} - -inline void DX8PolygonRendererClass::Render_Sorted(/*const Matrix3D & tm,*/int base_vertex_offset,const SphereClass & bounding_sphere) -{ - WWASSERT(!strip); // Strips can't be sorted for now -// DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); -// SNAPSHOT_SAY(("Set_Transform\n")); - SNAPSHOT_SAY(("Set_Index_Buffer_Index_Offset(%d)\n",base_vertex_offset)); - SNAPSHOT_SAY(("Insert_Sorting_Triangles(%d,%d,%d,%d)\n",index_offset,index_count-2,min_vertex_index,vertex_index_range)); - - DX8Wrapper::Set_Index_Buffer_Index_Offset(base_vertex_offset); - SortingRendererClass::Insert_Triangles( - bounding_sphere, - index_offset, - index_count/3, - min_vertex_index, - vertex_index_range); - -} - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp index 211bdcf6f7..4c82f5cbe3 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.cpp @@ -26,12 +26,13 @@ * * * Original Author:: Hector Yee * * * - * $Author:: Hector_y $* + * Author : Kenny Mitchell * + * * + * $Modtime:: 06/27/02 1:27p $* * * - * $Modtime:: 4/26/01 1:41p $* - * * - * $Revision:: 3 $* + * $Revision:: 4 $* * * + * 06/27/02 KM Texture class abstraction * *---------------------------------------------------------------------------------------------* * Functions: * * DX8TextureManagerClass::Shutdown -- Shuts down the texture manager * @@ -51,7 +52,7 @@ #include "dx8texman.h" -DX8TextureTrackerList DX8TextureManagerClass::Managed_Textures; +TextureTrackerList DX8TextureManagerClass::Managed_Textures; /*********************************************************************************************** @@ -68,12 +69,13 @@ DX8TextureTrackerList DX8TextureManagerClass::Managed_Textures; * * * HISTORY: * * 4/25/2001 hy : Created. * + * 5/16/2002 km : Added depth stencil texture tracking and abstraction * *=============================================================================================*/ void DX8TextureManagerClass::Shutdown() { while (!Managed_Textures.Is_Empty()) { - DX8TextureTrackerClass *track=Managed_Textures.Remove_Head(); + TextureTrackerClass *track=Managed_Textures.Remove_Head(); delete track; track=NULL; } @@ -93,8 +95,9 @@ void DX8TextureManagerClass::Shutdown() * * * HISTORY: * * 4/25/2001 hy : Created. * + * 5/16/2002 km : Added depth stencil texture tracking and abstraction * *=============================================================================================*/ -void DX8TextureManagerClass::Add(DX8TextureTrackerClass *track) +void DX8TextureManagerClass::Add(TextureTrackerClass *track) { // this function should only be called by the texture constructor Managed_Textures.Add(track); @@ -115,16 +118,17 @@ void DX8TextureManagerClass::Add(DX8TextureTrackerClass *track) * * * HISTORY: * * 4/25/2001 hy : Created. * + * 5/16/2002 km : Added depth stencil texture tracking and abstraction * *=============================================================================================*/ -void DX8TextureManagerClass::Remove(TextureClass *tex) +void DX8TextureManagerClass::Remove(TextureBaseClass *tex) { // this function should only be called by the texture destructor - DX8TextureTrackerListIterator it(&Managed_Textures); + TextureTrackerListIterator it(&Managed_Textures); while (!it.Is_Done()) { - DX8TextureTrackerClass *track=it.Peek_Obj(); - if (track->Texture==tex) + TextureTrackerClass *track=it.Peek_Obj(); + if (track->Get_Texture()==tex) { it.Remove_Current_Object(); delete track; @@ -149,17 +153,16 @@ void DX8TextureManagerClass::Remove(TextureClass *tex) * * * HISTORY: * * 4/25/2001 hy : Created. * + * 5/16/2002 km : Added depth stencil texture tracking and abstraction * *=============================================================================================*/ void DX8TextureManagerClass::Release_Textures() { - DX8TextureTrackerListIterator it(&Managed_Textures); + TextureTrackerListIterator it(&Managed_Textures); while (!it.Is_Done()) { - DX8TextureTrackerClass *track=it.Peek_Obj(); - WWASSERT(track->Texture->D3DTexture); - track->Texture->D3DTexture->Release(); - track->Texture->D3DTexture=NULL; + TextureTrackerClass *track=it.Peek_Obj(); + track->Release(); it.Next(); } } @@ -179,18 +182,18 @@ void DX8TextureManagerClass::Release_Textures() * * * HISTORY: * * 4/25/2001 hy : Created. * + * 5/16/2002 km : Added depth stencil texture tracking and abstraction * *=============================================================================================*/ void DX8TextureManagerClass::Recreate_Textures() { - DX8TextureTrackerListIterator it(&Managed_Textures); + TextureTrackerListIterator it(&Managed_Textures); while (!it.Is_Done()) { - DX8TextureTrackerClass *track=it.Peek_Obj(); - WWASSERT(track->Texture->D3DTexture==NULL); - track->Texture->D3DTexture=DX8Wrapper::_Create_DX8_Texture(track->Width,track->Height, - track->Format,track->Mip_level_count,D3DPOOL_DEFAULT,track->RenderTarget); - track->Texture->Dirty=true; + TextureTrackerClass *track=it.Peek_Obj(); + track->Recreate(); + track->Get_Texture()->Set_Dirty(); it.Next(); } } + diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h index c5696f2ddd..cef92a6f61 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8texman.h @@ -53,40 +53,89 @@ class DX8TextureManagerClass; -class DX8TextureTrackerClass : public MultiListObjectClass +class TextureTrackerClass : public MultiListObjectClass { -friend DX8TextureManagerClass; public: - DX8TextureTrackerClass(unsigned int w, unsigned int h, WW3DFormat format, - MipCountType count,bool rt, - TextureClass *tex): - Width(w), - Height(h), - Format(format), - Mip_level_count(count), - RenderTarget(rt), - Texture(tex) + TextureTrackerClass + ( + unsigned int w, + unsigned int h, + MipCountType count, + TextureBaseClass *tex + ) + : Width(w), + Height(h), + Mip_level_count(count), + Texture(tex) { } -private: + + virtual void Recreate() const =0; + + void Release() + { + Texture->Set_D3D_Base_Texture(NULL); + } + + TextureBaseClass* Get_Texture() const { return Texture; } + + +protected: + unsigned int Width; unsigned int Height; - WW3DFormat Format; MipCountType Mip_level_count; + TextureBaseClass *Texture; +}; + +class DX8TextureTrackerClass : public TextureTrackerClass +{ +public: + DX8TextureTrackerClass + ( + unsigned int w, + unsigned int h, + WW3DFormat format, + MipCountType count, + TextureBaseClass *tex, + bool rt + ) + : TextureTrackerClass(w,h,count,tex), Format(format), RenderTarget(rt) + { + } + + virtual void Recreate() const + { + WWASSERT(Texture->Peek_D3D_Base_Texture()==NULL); + Texture->Poke_Texture + ( + DX8Wrapper::_Create_DX8_Texture + ( + Width, + Height, + Format, + Mip_level_count, + D3DPOOL_DEFAULT, + RenderTarget + ) + ); + } + +private: + WW3DFormat Format; bool RenderTarget; - TextureClass *Texture; }; class DX8TextureManagerClass { public: static void Shutdown(); - static void Add(DX8TextureTrackerClass *track); - static void Remove(TextureClass *tex); + static void Add(TextureTrackerClass *track); + static void Remove(TextureBaseClass *tex); static void Release_Textures(); static void Recreate_Textures(); private: - static DX8TextureTrackerList Managed_Textures; + static TextureTrackerList Managed_Textures; }; #endif // ifdef TEXTUREMANAGER \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp deleted file mode 100644 index f806904303..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//****************************************************************************************** -// -// Earth And Beyond -// Copyright (c) 2002 Electronic Arts , Inc. - Westwood Studios -// -// File Name : dx8webbrowser.cpp -// Description : Implementation of D3D Embedded Browser wrapper. -// Author : Darren Schueller -// Date of Creation : 6/4/2002 -// -//****************************************************************************************** -// $Header: $ -//****************************************************************************************** - -#include "dx8webbrowser.h" -#include "ww3d.h" -#include "dx8wrapper.h" - -#if ENABLE_EMBEDDED_BROWSER - -#if defined(_MSC_VER) && _MSC_VER < 1300 - -// Import the Browser Type Library -// BGC, the path for the dll file is pretty odd, no? -// I'll leave it like this till I can figure out a -// better way. -#import "../../../../../Run/BrowserEngine.dll" no_namespace - -#else - -#include -#include - -#include "EABrowserEngine/BrowserEngine.h" - -typedef _com_ptr_t<_com_IIID> IFEBrowserEngine2Ptr; - -#endif - -static IFEBrowserEngine2Ptr pBrowser = 0; - -HWND DX8WebBrowser::hWnd = 0; - -bool DX8WebBrowser::Initialize( const char* badpageurl, - const char* loadingpageurl, - const char* mousefilename, - const char* mousebusyfilename) -{ - if(pBrowser == 0) - { - // Initialize COM - CoInitialize(0); - - // Create an instance of the browser control - HRESULT hr = pBrowser.CreateInstance(__uuidof(FEBrowserEngine2)); - - if(hr == REGDB_E_CLASSNOTREG) - { - HMODULE lib = ::LoadLibrary("BrowserEngine.DLL"); - if(lib) - { - FARPROC proc = ::GetProcAddress(lib,"DllRegisterServer"); - if(proc) - { - proc(); - // Create an instance of the browser control - hr = pBrowser.CreateInstance(__uuidof(FEBrowserEngine2)); - } - FreeLibrary(lib); - } - } - - // Initialize the browser. - if(hr == S_OK) - { - hWnd = (HWND)WW3D::Get_Window(); - pBrowser->Initialize(reinterpret_cast(DX8Wrapper::_Get_D3D_Device8())); - - if(badpageurl) - pBrowser->put_BadPageURL(_bstr_t(badpageurl)); - - if(loadingpageurl) - pBrowser->put_LoadingPageURL(_bstr_t(loadingpageurl)); - - if(mousefilename) - pBrowser->put_MouseFileName(_bstr_t(mousefilename)); - - if(mousebusyfilename) - pBrowser->put_MouseBusyFileName(_bstr_t(mousebusyfilename)); - } - else - { - pBrowser = 0; - return false; - } - } - - return true; -} - -void DX8WebBrowser::Shutdown() -{ - if(pBrowser) - { - // Shutdown the browser - pBrowser->Shutdown(); - - // Release the smart pointer. - pBrowser = 0; - - hWnd = 0; - - // Shut down COM - CoUninitialize(); - } -} - - -// ****************************************************************************************** -// * Function Name: DX8WebBrowser::Update -// ****************************************************************************************** -// * Description: Updates the browser image surfaces by copying the bits from the browser -// * DCs to the D3D Image surfaces. -// * -// * Return Type: -// * -// * Argument: void -// * -// ****************************************************************************************** -void DX8WebBrowser::Update(void) -{ - if(pBrowser) pBrowser->D3DUpdate(); -}; - - -// ****************************************************************************************** -// * Function Name: DX8WebBrowser::Render -// ****************************************************************************************** -// * Description: Draws all browsers to the back buffer. -// * -// * Return Type: -// * -// * Argument: int backbufferindex -// * -// ****************************************************************************************** -void DX8WebBrowser::Render(int backbufferindex) -{ - if(pBrowser) pBrowser->D3DRender(backbufferindex); -}; - -// ****************************************************************************************** -// * Function Name: DX8WebBrowser::CreateBrowser -// ****************************************************************************************** -// * Description: Creates a browser window. -// * -// * Return Type: -// * -// * Argument: const char* browsername - This is a "name" used to identify the -// * browser instance. Multiple browsers can -// * be created, and are referenced using this name. -// * Argument: const char* url - The url to display. -// * Argument: int x - The position and size of the browser (in pixels) -// * Argument: int y -// * Argument: int w -// * Argument: int h -// * Argument: int updateticks - When non-zero, this forces the browser image to get updated -// * at the specified rate (number of milliseconds) regardless -// * of paint messages. When this is zero (the default) the browser -// * image is only updated whenever a paint message is received. -// * -// ****************************************************************************************** -void DX8WebBrowser::CreateBrowser(const char* browsername, const char* url, int x, int y, int w, int h, int updateticks, LONG options, LPDISPATCH gamedispatch) -{ - WWDEBUG_SAY(("DX8WebBrowser::CreateBrowser - Creating browser with the name %s, url = %s, (x, y, w, h) = (%d, %d, %d, %d), update ticks = %d\n", browsername, url, x, y, h, w, updateticks)); - if(pBrowser) - { - _bstr_t brsname(browsername); - pBrowser->CreateBrowser(brsname, _bstr_t(url), reinterpret_cast(hWnd), x, y, w, h, options, gamedispatch); - pBrowser->SetUpdateRate(brsname, updateticks); - } -} - - -// ****************************************************************************************** -// * Function Name: DX8WebBrowser::DestroyBrowser -// ****************************************************************************************** -// * Description: Destroys the specified browser. This closes the window and releases -// * the browser instance. -// * -// * Return Type: -// * -// * Argument: const char* browsername - The name of the browser to destroy. -// * -// ****************************************************************************************** -void DX8WebBrowser::DestroyBrowser(const char* browsername) -{ - WWDEBUG_SAY(("DX8WebBrowser::DestroyBrowser - destroying browser %s\n", browsername)); - if(pBrowser) - pBrowser->DestroyBrowser(_bstr_t(browsername)); -} - - -// ****************************************************************************************** -// * Function Name: DX8WebBrowser::Is_Browser_Open -// ****************************************************************************************** -// * Description: This function checks to see if a browser of the specified name exists and -// * is currently open. -// * -// * Return Type: -// * -// * Argument: const char* browsername - The name of the browser to test. -// * -// ****************************************************************************************** -bool DX8WebBrowser::Is_Browser_Open(const char* browsername) -{ - if(pBrowser == 0) return false; -#if defined(_MSC_VER) && _MSC_VER < 1300 - return (pBrowser->IsOpen(_bstr_t(browsername)) != 0); -#else - long isOpen; - return (pBrowser->IsOpen(_bstr_t(browsername), &isOpen) != 0); -#endif -} - -// ****************************************************************************************** -// * Function Name: DX8WebBrowser::Navigate -// ****************************************************************************************** -// * Description: This function causes the browser to navigate to the specified page. -// * -// * Return Type: -// * -// * Argument: const char* browsername - The name of the browser to test. -// * const char* url - The url to navigate to. -// * -// ****************************************************************************************** -void DX8WebBrowser::Navigate(const char* browsername, const char* url) -{ - if(pBrowser == 0) return; - pBrowser->Navigate(_bstr_t(browsername),_bstr_t(url)); -} - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h deleted file mode 100644 index 82d68c35d7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8webbrowser.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//****************************************************************************************** -// -// Earth And Beyond -// Copyright (c) 2002 Electronic Arts , Inc. - Westwood Studios -// -// File Name : dx8webbrowser.h -// Description : Implementation of D3D Embedded Browser Wrapper -// Author : Darren Schueller -// Date of Creation : 6/4/2002 -// -//****************************************************************************************** -// $Header: $ -//****************************************************************************************** - -#ifndef DX8_WEBBROWSER_H -#define DX8_WEBBROWSER_H - -#include -#include "d3d8.h" - -// *********************************** -// Set this to 0 to remove all embedded browser code. -// -#define ENABLE_EMBEDDED_BROWSER 1 -// -// *********************************** - -#if ENABLE_EMBEDDED_BROWSER - -// These options must match the browser option bits defined in the BrowserEngine code. -// Look in febrowserengine.h -#define BROWSEROPTION_SCROLLBARS 0x0001 -#define BROWSEROPTION_3DBORDER 0x0002 - -struct IDirect3DDevice8; - -/** -** DX8WebBrowser -** -** DX8 interface wrapper class. This encapsulates the BrowserEngine interface. -*/ -class DX8WebBrowser -{ -public: - - static bool Initialize( const char* badpageurl = 0, - const char* loadingpageurl = 0, - const char* mousefilename = 0, - const char* mousebusyfilename = 0); //Initialize the Embedded Browser - - static void Shutdown(void); // Shutdown the embedded browser. Will close any open browsers. - - static void Update(void); // Copies all browser contexts to D3D Image surfaces. - static void Render(int backbufferindex); //Draws all browsers to the backbuffer. - - // Creates a browser with the specified name - static void CreateBrowser(const char* browsername, const char* url, int x, int y, int w, int h, int updateticks = 0, LONG options = BROWSEROPTION_SCROLLBARS | BROWSEROPTION_3DBORDER, LPDISPATCH gamedispatch = 0); - - // Destroys the browser with the specified name - static void DestroyBrowser(const char* browsername); - - // Returns true if a browser with the specified name is open. - static bool Is_Browser_Open(const char* browsername); - - // Navigates the specified browser to the specified page. - static void Navigate(const char* browsername, const char* url); - -private: - // The window handle of the application. This is initialized by Initialize(). - static HWND hWnd; -}; - -#endif - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp index caf71e2e47..6c327fa4f4 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp @@ -42,6 +42,7 @@ #define WW3D_DEVTYPE D3DDEVTYPE_HAL #include "dx8wrapper.h" +#include "dx8webbrowser.h" #include "dx8fvf.h" #include "dx8vertexbuffer.h" #include "dx8indexbuffer.h" @@ -109,6 +110,19 @@ D3DMATRIX DX8Wrapper::old_world; D3DMATRIX DX8Wrapper::old_view; D3DMATRIX DX8Wrapper::old_prj; +// shader system additions KJM v +DWORD DX8Wrapper::Vertex_Shader = 0; +DWORD DX8Wrapper::Pixel_Shader = 0; + +Vector4 DX8Wrapper::Vertex_Shader_Constants[MAX_VERTEX_SHADER_CONSTANTS]; +Vector4 DX8Wrapper::Pixel_Shader_Constants[MAX_PIXEL_SHADER_CONSTANTS]; + +LightEnvironmentClass* DX8Wrapper::Light_Environment = NULL; +RenderInfoClass* DX8Wrapper::Render_Info = NULL; + +DWORD DX8Wrapper::Vertex_Processing_Behavior = 0; +Vector3 DX8Wrapper::Ambient_Color; +// shader system additions KJM ^ bool DX8Wrapper::world_identity; unsigned DX8Wrapper::RenderStates[256]; unsigned DX8Wrapper::TextureStageStates[MAX_TEXTURE_STAGES][32]; @@ -123,6 +137,7 @@ IDirect3D8 * DX8Wrapper::D3DInterface = NULL; IDirect3DDevice8 * DX8Wrapper::D3DDevice = NULL; IDirect3DSurface8 * DX8Wrapper::CurrentRenderTarget = NULL; IDirect3DSurface8 * DX8Wrapper::DefaultRenderTarget = NULL; +bool DX8Wrapper::IsRenderToTexture = false; unsigned DX8Wrapper::matrix_changes = 0; unsigned DX8Wrapper::material_changes = 0; @@ -132,11 +147,21 @@ unsigned DX8Wrapper::light_changes = 0; unsigned DX8Wrapper::texture_changes = 0; unsigned DX8Wrapper::render_state_changes = 0; unsigned DX8Wrapper::texture_stage_state_changes = 0; +unsigned DX8Wrapper::draw_calls = 0; unsigned DX8Wrapper::_MainThreadID = 0; bool DX8Wrapper::CurrentDX8LightEnables[4]; +bool DX8Wrapper::IsDeviceLost; +int DX8Wrapper::ZBias; +float DX8Wrapper::ZNear; +float DX8Wrapper::ZFar; +Matrix4x4 DX8Wrapper::ProjectionMatrix; +Matrix4x4 DX8Wrapper::DX8Transforms[D3DTS_WORLD+1]; DX8Caps* DX8Wrapper::CurrentCaps = 0; +// Hack test... this disables rendering of batches of too few polygons. +unsigned DX8Wrapper::DrawPolygonLowBoundLimit=0; + D3DADAPTER_IDENTIFIER8 DX8Wrapper::CurrentAdapterIdentifier; unsigned long DX8Wrapper::FrameCount = 0; @@ -153,21 +178,17 @@ static unsigned last_frame_texture_changes = 0; static unsigned last_frame_render_state_changes = 0; static unsigned last_frame_texture_stage_state_changes = 0; static unsigned last_frame_number_of_DX8_calls = 0; +static unsigned last_frame_draw_calls = 0; static D3DPRESENT_PARAMETERS _PresentParameters; static DynamicVectorClass _RenderDeviceNameTable; static DynamicVectorClass _RenderDeviceShortNameTable; static DynamicVectorClass _RenderDeviceDescriptionTable; -/* -** Registry value names -*/ -#define VALUE_NAME_RENDER_DEVICE_NAME "RenderDeviceName" -#define VALUE_NAME_RENDER_DEVICE_WIDTH "RenderDeviceWidth" -#define VALUE_NAME_RENDER_DEVICE_HEIGHT "RenderDeviceHeight" -#define VALUE_NAME_RENDER_DEVICE_DEPTH "RenderDeviceDepth" -#define VALUE_NAME_RENDER_DEVICE_WINDOWED "RenderDeviceWindowed" -#define VALUE_NAME_RENDER_DEVICE_TEXTURE_DEPTH "RenderDeviceTextureDepth" + +typedef IDirect3D8* (WINAPI *Direct3DCreate8Type) (UINT SDKVersion); +Direct3DCreate8Type Direct3DCreate8Ptr = NULL; +HINSTANCE D3D8Lib = NULL; DX8_CleanupHook *DX8Wrapper::m_pCleanupHook=NULL; #ifdef EXTENDED_STATS @@ -210,10 +231,13 @@ void Non_Fatal_Log_DX8_ErrorCode(unsigned res,const char * file,int line) } -bool DX8Wrapper::Init(void * hwnd) + +bool DX8Wrapper::Init(void * hwnd, bool lite) { WWASSERT(!IsInitted); + memset(Vertex_Shader_Constants,0,sizeof(Vector4)*MAX_VERTEX_SHADER_CONSTANTS); + memset(Pixel_Shader_Constants,0,sizeof(Vector4)*MAX_PIXEL_SHADER_CONSTANTS); /* ** Initialize all variables! */ @@ -250,19 +274,32 @@ bool DX8Wrapper::Init(void * hwnd) Invalidate_Cached_Render_States(); - /* - ** Create the D3D interface object - */ - D3DInterface = Direct3DCreate8(D3D_SDK_VERSION); // TODO: handle failure cases... - if (D3DInterface == NULL) { - return(false); + if (!lite) { + D3D8Lib = LoadLibrary("D3D8.DLL"); + + if (D3D8Lib == NULL) return false; // Return false at this point if init failed + + Direct3DCreate8Ptr = (Direct3DCreate8Type) GetProcAddress(D3D8Lib, "Direct3DCreate8"); + if (Direct3DCreate8Ptr == NULL) return false; + + /* + ** Create the D3D interface object + */ + WWDEBUG_SAY(("Create Direct3D8\n")); + D3DInterface = Direct3DCreate8Ptr(D3D_SDK_VERSION); // TODO: handle failure cases... + if (D3DInterface == NULL) { + return(false); + } + IsInitted = true; + + /* + ** Enumerate the available devices + */ + WWDEBUG_SAY(("Enumerate devices\n")); + Enumerate_Devices(); + WWDEBUG_SAY(("DX8Wrapper Init completed\n")); } - IsInitted = true; - /* - ** Enumerate the available devices - */ - Enumerate_Devices(); return(true); } @@ -274,10 +311,22 @@ void DX8Wrapper::Shutdown(void) Release_Device(); } - for (int i = 0; i < MAX_TEXTURE_STAGES; i++) { - if (Textures[i]) { - Textures[i]->Release(); - Textures[i] = NULL; + if (D3DInterface) { + D3DInterface->Release(); + D3DInterface=NULL; + + } + + if (CurrentCaps) + { + int max=CurrentCaps->Get_Max_Textures_Per_Pass(); + for (int i = 0; i < max; i++) + { + if (Textures[i]) + { + Textures[i]->Release(); + Textures[i] = NULL; + } } } @@ -286,6 +335,11 @@ void DX8Wrapper::Shutdown(void) D3DInterface=NULL; } + if (D3D8Lib) { + FreeLibrary(D3D8Lib); + D3D8Lib = NULL; + } + _RenderDeviceNameTable.Clear(); // note - Delete_All() resizes the vector, causing a reallocation. Clear is better. jba. _RenderDeviceShortNameTable.Clear(); _RenderDeviceDescriptionTable.Clear(); @@ -313,21 +367,6 @@ void DX8Wrapper::Do_Onetime_Device_Dependent_Inits(void) ShatterSystem::Init(); TextureLoader::Init(); -#ifdef WW3D_DX8 - -// WW3DAssetManager::Get_Instance()->Open_Texture_File_Cache("cache_"); - - /* - ** Initialize the dazzle system - */ - FileClass * dazzle_ini_file = _TheFileFactory->Get_File(DAZZLE_INI_FILENAME); - if (dazzle_ini_file) { - INIClass dazzle_ini(*dazzle_ini_file); - DazzleRenderObjClass::Init_From_INI(&dazzle_ini); - _TheFileFactory->Return_File(dazzle_ini_file); - } -#endif //WW3D_DX8 - Set_Default_Global_Render_States(); } @@ -387,9 +426,20 @@ void DX8Wrapper::Invalidate_Cached_Render_States(void) } Textures[a]=NULL; } + ShaderClass::Invalidate(); + //Need to explicitly set render_state texture pointers to NULL. MW Release_Render_State(); + + // (gth) clear the matrix shadows too + for (int i=0; iRelease_Engine_Ref(); REF_PTR_RELEASE(render_state.vertex_buffer); if (render_state.index_buffer) render_state.index_buffer->Release_Engine_Ref(); REF_PTR_RELEASE(render_state.index_buffer); REF_PTR_RELEASE(render_state.material); - for (unsigned i=0;iGet_Max_Textures_Per_Pass();++i) REF_PTR_RELEASE(render_state.Textures[i]); -#ifdef WW3D_DX8 - DazzleRenderObjClass::Deinit(); -#endif //WW3D_DX8 TextureLoader::Deinit(); SortingRendererClass::Deinit(); @@ -419,6 +467,11 @@ void DX8Wrapper::Do_Onetime_Device_Dependent_Shutdowns(void) TheDX8MeshRenderer.Shutdown(); MissingTexture::_Deinit(); + if (CurrentCaps) { + delete CurrentCaps; + CurrentCaps=NULL; + } + } @@ -461,28 +514,32 @@ bool DX8Wrapper::Create_Device(void) return false; } - unsigned vertex_processing_type=D3DCREATE_SOFTWARE_VERTEXPROCESSING; + Vertex_Processing_Behavior=D3DCREATE_SOFTWARE_VERTEXPROCESSING; if (caps.DevCaps&D3DDEVCAPS_HWTRANSFORMANDLIGHT) { - vertex_processing_type=D3DCREATE_MIXED_VERTEXPROCESSING; + Vertex_Processing_Behavior=D3DCREATE_MIXED_VERTEXPROCESSING; } #ifdef CREATE_DX8_MULTI_THREADED - vertex_processing_type|=D3DCREATE_MULTITHREADED; + Vertex_Processing_Behavior|=D3DCREATE_MULTITHREADED; _DX8SingleThreaded=false; #else _DX8SingleThreaded=true; #endif if (DX8Wrapper_PreserveFPU) - vertex_processing_type |= D3DCREATE_FPU_PRESERVE; + Vertex_Processing_Behavior |= D3DCREATE_FPU_PRESERVE; + +#ifdef CREATE_DX8_FPU_PRESERVE + Vertex_Processing_Behavior|=D3DCREATE_FPU_PRESERVE; +#endif HRESULT hr=D3DInterface->CreateDevice ( CurRenderDevice, WW3D_DEVTYPE, _Hwnd, - vertex_processing_type, + Vertex_Processing_Behavior, &_PresentParameters, &D3DDevice ); @@ -501,6 +558,7 @@ bool DX8Wrapper::Create_Device(void) bool DX8Wrapper::Reset_Device(bool reload_assets) { + WWDEBUG_SAY(("Resetting device.\n")); DX8_THREAD_ASSERT(); if ((IsInitted) && (D3DDevice != NULL)) { // Release all non-MANAGED stuff @@ -513,6 +571,9 @@ bool DX8Wrapper::Reset_Device(bool reload_assets) DynamicIBAccessClass::_Deinit(); DX8TextureManagerClass::Release_Textures(); + memset(Vertex_Shader_Constants,0,sizeof(Vector4)*MAX_VERTEX_SHADER_CONSTANTS); + memset(Pixel_Shader_Constants,0,sizeof(Vector4)*MAX_PIXEL_SHADER_CONSTANTS); + HRESULT hr=_Get_D3D_Device8()->TestCooperativeLevel(); if (hr != D3DERR_DEVICELOST ) { DX8CALL_HRES(Reset(&_PresentParameters),hr) @@ -531,8 +592,10 @@ bool DX8Wrapper::Reset_Device(bool reload_assets) } Invalidate_Cached_Render_States(); Set_Default_Global_Render_States(); + WWDEBUG_SAY(("Device reset completed\n")); return true; } + WWDEBUG_SAY(("Device reset failed\n")); return false; } @@ -1375,8 +1438,9 @@ bool DX8Wrapper::Find_Z_Mode(D3DFORMAT colorbuffer,D3DFORMAT backbuffer, D3DFORM WWDEBUG_SAY(("Found zbuffer mode D3DFMT_D15S1\n")); return true; } - + // can't find a match + WWDEBUG_SAY(("Failed to find a valid zbuffer mode\r\n")); return false; } @@ -1411,6 +1475,7 @@ void DX8Wrapper::Reset_Statistics() texture_changes = 0; render_state_changes =0; texture_stage_state_changes =0; + draw_calls =0; number_of_DX8_calls = 0; last_frame_matrix_changes = 0; @@ -1422,6 +1487,7 @@ void DX8Wrapper::Reset_Statistics() last_frame_render_state_changes = 0; last_frame_texture_stage_state_changes = 0; last_frame_number_of_DX8_calls = 0; + last_frame_draw_calls =0; } void DX8Wrapper::Begin_Statistics() @@ -1435,6 +1501,7 @@ void DX8Wrapper::Begin_Statistics() render_state_changes =0; texture_stage_state_changes =0; number_of_DX8_calls=0; + draw_calls=0; } void DX8Wrapper::End_Statistics() @@ -1448,6 +1515,7 @@ void DX8Wrapper::End_Statistics() last_frame_render_state_changes = render_state_changes; last_frame_texture_stage_state_changes = texture_stage_state_changes; last_frame_number_of_DX8_calls=number_of_DX8_calls; + last_frame_draw_calls=draw_calls; } unsigned DX8Wrapper::Get_Last_Frame_Matrix_Changes() { return last_frame_matrix_changes; } @@ -1459,6 +1527,7 @@ unsigned DX8Wrapper::Get_Last_Frame_Texture_Changes() { return last_frame_text unsigned DX8Wrapper::Get_Last_Frame_Render_State_Changes() { return last_frame_render_state_changes; } unsigned DX8Wrapper::Get_Last_Frame_Texture_Stage_State_Changes() { return last_frame_texture_stage_state_changes; } unsigned DX8Wrapper::Get_Last_Frame_DX8_Calls() { return last_frame_number_of_DX8_calls; } +unsigned DX8Wrapper::Get_Last_Frame_Draw_Calls() { return last_frame_draw_calls; } unsigned long DX8Wrapper::Get_FrameCount(void) {return FrameCount;} void DX8_Assert() @@ -1470,6 +1539,11 @@ void DX8_Assert() void DX8Wrapper::Begin_Scene(void) { DX8_THREAD_ASSERT(); + +#if ENABLE_EMBEDDED_BROWSER + DX8WebBrowser::Update(); +#endif + DX8CALL(BeginScene()); DX8WebBrowser::Update(); @@ -1484,7 +1558,12 @@ void DX8Wrapper::End_Scene(bool flip_frames) if (flip_frames) { DX8_Assert(); - HRESULT hr=_Get_D3D_Device8()->Present(NULL, NULL, NULL, NULL); + HRESULT hr; + { + WWPROFILE("DX8Device::Present()"); + hr=_Get_D3D_Device8()->Present(NULL, NULL, NULL, NULL); + } + number_of_DX8_calls++; if (SUCCEEDED(hr)) { @@ -1493,8 +1572,12 @@ void DX8Wrapper::End_Scene(bool flip_frames) ::Sleep(stats.m_sleepTime); } #endif + IsDeviceLost=false; FrameCount++; } + else { + IsDeviceLost=true; + } // If the device was lost we need to check for cooperative level and possibly reset the device if (hr==D3DERR_DEVICELOST) { @@ -1502,6 +1585,10 @@ void DX8Wrapper::End_Scene(bool flip_frames) if (hr==D3DERR_DEVICENOTRESET) { Reset_Device(); } + else { + // Sleep it not active + ThreadClass::Sleep_Ms(200); + } } else { DX8_ErrorCode(hr); @@ -1511,7 +1598,7 @@ void DX8Wrapper::End_Scene(bool flip_frames) // Each frame, release all of the buffers and textures. Set_Vertex_Buffer(NULL); Set_Index_Buffer(NULL,0); - for (unsigned i=0;iGet_Max_Textures_Per_Pass();++i) Set_Texture(i,NULL); Set_Material(NULL); } @@ -1536,12 +1623,14 @@ void DX8Wrapper::Flip_To_Primary(void) WWDEBUG_SAY(("TestCooperativeLevel Failed!\n")); if (D3DERR_DEVICELOST == hr) { + IsDeviceLost=true; WWDEBUG_SAY(("DEVICELOST: Cannot flip to primary.\n")); return; } + IsDeviceLost=false; if (D3DERR_DEVICENOTRESET == hr) { - WWDEBUG_SAY(("DEVICENOTRESET: Resetting device.\n")); + WWDEBUG_SAY(("DEVICENOTRESET\n")); Reset_Device(); resetAttempts++; } @@ -1550,9 +1639,13 @@ void DX8Wrapper::Flip_To_Primary(void) hr = _Get_D3D_Device8()->Present(NULL, NULL, NULL, NULL); if (SUCCEEDED(hr)) { + IsDeviceLost=false; FrameCount++; WWDEBUG_SAY(("Flip to primary succeeded %ld\n", FrameCount)); } + else { + IsDeviceLost=true; + } } --flipCount; @@ -1588,7 +1681,7 @@ void DX8Wrapper::Set_Viewport(CONST D3DVIEWPORT8* pViewport) // ---------------------------------------------------------------------------- // // Set vertex buffer. A reference to previous vertex buffer is released and -// this one is assigned the current vertex buffer. The DX8 vertex buffer will +// this one is assigned the current vertex buffer. The DX8 vertex buffer will // actually be set in Apply() which is called by Draw_Indexed_Triangles(). // // ---------------------------------------------------------------------------- @@ -1614,7 +1707,7 @@ void DX8Wrapper::Set_Vertex_Buffer(const VertexBufferClass* vb) // ---------------------------------------------------------------------------- // // Set index buffer. A reference to previous index buffer is released and -// this one is assigned the current index buffer. The DX8 index buffer will +// this one is assigned the current index buffer. The DX8 index buffer will // actually be set in Apply() which is called by Draw_Indexed_Triangles(). // // ---------------------------------------------------------------------------- @@ -1685,7 +1778,7 @@ void DX8Wrapper::Set_Index_Buffer(const DynamicIBAccessClass& iba_,unsigned shor void DX8Wrapper::Draw_Sorting_IB_VB( unsigned primitive_type, - unsigned short start_index, + unsigned short start_index, unsigned short polygon_count, unsigned short min_vertex_index, unsigned short vertex_count) @@ -1703,7 +1796,7 @@ void DX8Wrapper::Draw_Sorting_IB_VB( unsigned size = dyn_vb_access.FVF_Info().Get_FVF_Size()*vertex_count/sizeof(unsigned); unsigned *dest_u =(unsigned*) dest; unsigned *src_u = (unsigned*) src; - + for (unsigned i=0;i=polygon_count) return; + DX8_THREAD_ASSERT(); SNAPSHOT_SAY(("DX8 - draw\n")); @@ -1777,7 +1873,58 @@ void DX8Wrapper::Draw( // Debug feature to disable triangle drawing... if (!_Is_Triangle_Draw_Enabled()) return; - SNAPSHOT_SAY(("DX8 - draw %s polygons (%d vertices)\n",polygon_count,vertex_count)); +#ifdef MESH_RENDER_SNAPSHOT_ENABLED + if (WW3D::Is_Snapshot_Activated()) { + unsigned long passes=0; + SNAPSHOT_SAY(("ValidateDevice: ")); + HRESULT res=D3DDevice->ValidateDevice(&passes); + switch (res) { + case D3D_OK: + SNAPSHOT_SAY(("OK\n")); + break; + + case D3DERR_CONFLICTINGTEXTUREFILTER: + SNAPSHOT_SAY(("D3DERR_CONFLICTINGTEXTUREFILTER\n")); + break; + case D3DERR_CONFLICTINGTEXTUREPALETTE: + SNAPSHOT_SAY(("D3DERR_CONFLICTINGTEXTUREPALETTE\n")); + break; + case D3DERR_DEVICELOST: + SNAPSHOT_SAY(("D3DERR_DEVICELOST\n")); + break; + case D3DERR_TOOMANYOPERATIONS: + SNAPSHOT_SAY(("D3DERR_TOOMANYOPERATIONS\n")); + break; + case D3DERR_UNSUPPORTEDALPHAARG: + SNAPSHOT_SAY(("D3DERR_UNSUPPORTEDALPHAARG\n")); + break; + case D3DERR_UNSUPPORTEDALPHAOPERATION: + SNAPSHOT_SAY(("D3DERR_UNSUPPORTEDALPHAOPERATION\n")); + break; + case D3DERR_UNSUPPORTEDCOLORARG: + SNAPSHOT_SAY(("D3DERR_UNSUPPORTEDCOLORARG\n")); + break; + case D3DERR_UNSUPPORTEDCOLOROPERATION: + SNAPSHOT_SAY(("D3DERR_UNSUPPORTEDCOLOROPERATION\n")); + break; + case D3DERR_UNSUPPORTEDFACTORVALUE: + SNAPSHOT_SAY(("D3DERR_UNSUPPORTEDFACTORVALUE\n")); + break; + case D3DERR_UNSUPPORTEDTEXTUREFILTER: + SNAPSHOT_SAY(("D3DERR_UNSUPPORTEDTEXTUREFILTER\n")); + break; + case D3DERR_WRONGTEXTUREFORMAT: + SNAPSHOT_SAY(("D3DERR_WRONGTEXTUREFORMAT\n")); + break; + default: + SNAPSHOT_SAY(("UNKNOWN Error\n")); + break; + } + } +#endif // MESH_RENDER_SHAPSHOT_ENABLED + + + SNAPSHOT_SAY(("DX8 - draw %d polygons (%d vertices)\n",polygon_count,vertex_count)); if (vertex_count<3) { min_vertex_index=0; @@ -1806,6 +1953,7 @@ void DX8Wrapper::Draw( break; }*/ DX8_RECORD_RENDER(polygon_count,vertex_count,render_state.shader); + DX8_RECORD_DRAW_CALLS(); DX8CALL(DrawIndexedPrimitive( (D3DPRIMITIVETYPE)primitive_type, min_vertex_index, @@ -1853,7 +2001,7 @@ void DX8Wrapper::Draw( void DX8Wrapper::Draw_Triangles( unsigned buffer_type, - unsigned short start_index, + unsigned short start_index, unsigned short polygon_count, unsigned short min_vertex_index, unsigned short vertex_count) @@ -1873,7 +2021,7 @@ void DX8Wrapper::Draw_Triangles( // ---------------------------------------------------------------------------- void DX8Wrapper::Draw_Triangles( - unsigned short start_index, + unsigned short start_index, unsigned short polygon_count, unsigned short min_vertex_index, unsigned short vertex_count) @@ -1888,7 +2036,7 @@ void DX8Wrapper::Draw_Triangles( // ---------------------------------------------------------------------------- void DX8Wrapper::Draw_Strip( - unsigned short start_index, + unsigned short start_index, unsigned short polygon_count, unsigned short min_vertex_index, unsigned short vertex_count) @@ -1904,6 +2052,8 @@ void DX8Wrapper::Draw_Strip( void DX8Wrapper::Apply_Render_State_Changes() { + SNAPSHOT_SAY(("DX8Wrapper::Apply_Render_State_Changes()\n")); + if (!render_state_changed) return; if (render_state_changed&SHADER_CHANGED) { SNAPSHOT_SAY(("DX8 - apply shader\n")); @@ -1911,11 +2061,21 @@ void DX8Wrapper::Apply_Render_State_Changes() } unsigned mask=TEXTURE0_CHANGED; - for (unsigned i=0;iGet_Max_Textures_Per_Pass();++i,mask<<=1) + { + if (render_state_changed&mask) + { SNAPSHOT_SAY(("DX8 - apply texture %d\n",i)); - if (render_state.Textures[i]) render_state.Textures[i]->Apply(i); - else TextureBaseClass::Apply_Null(i); + + if (render_state.Textures[i]) + { + render_state.Textures[i]->Apply(i); + } + else + { + TextureBaseClass::Apply_Null(i); + } } } @@ -1937,11 +2097,28 @@ void DX8Wrapper::Apply_Render_State_Changes() if (render_state_changed&mask) { SNAPSHOT_SAY(("DX8 - apply light %d\n",index)); if (render_state.LightEnable[index]) { +#ifdef MESH_RENDER_SNAPSHOT_ENABLED + if ( WW3D::Is_Snapshot_Activated() ) { + D3DLIGHT8 * light = &(render_state.Lights[index]); + static const char * _light_types[] = { "Unknown", "Point","Spot", "Directional" }; + WWASSERT((light->Type >= 0) && (light->Type <= 3)); + + SNAPSHOT_SAY((" type = %s amb = %4.2f,%4.2f,%4.2f diff = %4.2f,%4.2f,%4.2f spec = %4.2f, %4.2f, %4.2f\n", + _light_types[light->Type], + light->Ambient.r,light->Ambient.g,light->Ambient.b, + light->Diffuse.r,light->Diffuse.g,light->Diffuse.b, + light->Specular.r,light->Specular.g,light->Specular.b )); + SNAPSHOT_SAY((" pos = %f, %f, %f dir = %f, %f, %f\n", + light->Position.x, light->Position.y, light->Position.z, + light->Direction.x, light->Direction.y, light->Direction.z )); + } +#endif + Set_DX8_Light(index,&render_state.Lights[index]); } else { Set_DX8_Light(index,NULL); - + SNAPSHOT_SAY((" clearing light to NULL\n")); } } } @@ -2006,6 +2183,8 @@ void DX8Wrapper::Apply_Render_State_Changes() } render_state_changed&=((unsigned)WORLD_IDENTITY|(unsigned)VIEW_IDENTITY); + + SNAPSHOT_SAY(("DX8Wrapper::Apply_Render_State_Changes() - finished\n")); } IDirect3DTexture8 * DX8Wrapper::_Create_DX8_Texture @@ -2097,7 +2276,7 @@ IDirect3DTexture8 * DX8Wrapper::_Create_DX8_Texture filename, D3DX_DEFAULT, D3DX_DEFAULT, - mip_level_count,//create_mipmaps ? 0 : 1, + mip_level_count,//create_mipmaps ? 0 : 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, @@ -2119,13 +2298,6 @@ IDirect3DTexture8 * DX8Wrapper::_Create_DX8_Texture texture->Release(); return MissingTexture::_Get_Missing_Texture(); } - else { -// unsigned reduction=WW3D::Get_Texture_Reduction(); -// unsigned level_count=texture->GetLevelCount(); -// if (reduction>=level_count) reduction=level_count-1; -// texture->SetLOD(reduction); - } - return texture; } @@ -2201,12 +2373,28 @@ IDirect3DSurface8 * DX8Wrapper::_Create_DX8_Surface(const char *filename_) // If file not found, create a surface with missing texture in it if (!myfile->Is_Available()) { - return MissingTexture::_Create_Missing_Surface(); + // If file not found, try the dds format + // else create a surface with missing texture in it + char compressed_name[200]; + strncpy(compressed_name,filename_, 200); + char *ext = strstr(compressed_name, "."); + if ( (strlen(ext)==4) && + ( (ext[1] == 't') || (ext[1] == 'T') ) && + ( (ext[2] == 'g') || (ext[2] == 'G') ) && + ( (ext[3] == 'a') || (ext[3] == 'A') ) ) { + ext[1]='d'; + ext[2]='d'; + ext[3]='s'; + } + file_auto_ptr myfile2(_TheFileFactory,compressed_name); + if (!myfile2->Is_Available()) + return MissingTexture::_Create_Missing_Surface(); } } + StringClass filename_string(filename_,true); surface=TextureLoader::Load_Surface_Immediate( - filename_, + filename_string, WW3D_FORMAT_UNKNOWN, true); return surface; @@ -2232,9 +2420,9 @@ void DX8Wrapper::_Update_Texture(TextureClass *system, TextureClass *video) { WWASSERT(system); WWASSERT(video); - WWASSERT(system->Pool==TextureClass::POOL_SYSTEMMEM); - WWASSERT(video->Pool==TextureClass::POOL_DEFAULT); - DX8CALL(UpdateTexture(system->D3DTexture,video->D3DTexture)); + WWASSERT(system->Get_Pool()==TextureClass::POOL_SYSTEMMEM); + WWASSERT(video->Get_Pool()==TextureClass::POOL_DEFAULT); + DX8CALL(UpdateTexture(system->Peek_D3D_Base_Texture(),video->Peek_D3D_Base_Texture())); } void DX8Wrapper::Compute_Caps(WW3DFormat display_format) @@ -2245,6 +2433,19 @@ void DX8Wrapper::Compute_Caps(WW3DFormat display_format) CurrentCaps=new DX8Caps(_Get_D3D8(),D3DDevice,display_format,Get_Current_Adapter_Identifier()); } + +void DX8Wrapper::Set_Light(unsigned index, const D3DLIGHT8* light) +{ + if (light) { + render_state.Lights[index]=*light; + render_state.LightEnable[index]=true; + } + else { + render_state.LightEnable[index]=false; + } + render_state_changed|=(LIGHT0_CHANGED<Peek_D3D_Texture() == NULL) + if (tex->Peek_D3D_Base_Texture() == NULL) { WWDEBUG_SAY(("DX8Wrapper - Render target creation failed!\r\n")); REF_PTR_RELEASE(tex); @@ -2534,6 +2735,8 @@ DX8Wrapper::Set_Render_Target(IDirect3DSwapChain8 *swap_chain) render_target = NULL; } + IsRenderToTexture = false; + return ; } @@ -2619,6 +2822,7 @@ DX8Wrapper::Set_Render_Target(IDirect3DSurface8 *render_target) depth_buffer = NULL; } + IsRenderToTexture = false; return ; } @@ -2705,7 +2909,7 @@ void DX8Wrapper::Set_Gamma(float gamma,float bright,float contrast,bool calibrat ramp.blue[i]=(WORD) (out*65535); } - if (DX8Wrapper::Get_Current_Caps()->Support_Gamma()) { + if (Get_Current_Caps()->Support_Gamma()) { DX8Wrapper::_Get_D3D_Device8()->SetGammaRamp(flag,&ramp); } else { HWND hwnd = GetDesktopWindow(); @@ -2718,6 +2922,739 @@ void DX8Wrapper::Set_Gamma(float gamma,float bright,float contrast,bool calibrat } } +//********************************************************************************************** +//! Resets render device to default state +/*! +*/ +void DX8Wrapper::Apply_Default_State() +{ + SNAPSHOT_SAY(("DX8Wrapper::Apply_Default_State()\n")); + + // only set states used in game + Set_DX8_Render_State(D3DRS_ZENABLE, TRUE); +// Set_DX8_Render_State(D3DRS_FILLMODE, D3DFILL_SOLID); + Set_DX8_Render_State(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); + //Set_DX8_Render_State(D3DRS_LINEPATTERN, 0); + Set_DX8_Render_State(D3DRS_ZWRITEENABLE, TRUE); + Set_DX8_Render_State(D3DRS_ALPHATESTENABLE, FALSE); + //Set_DX8_Render_State(D3DRS_LASTPIXEL, FALSE); + Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_ONE); + Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_ZERO); + Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_CW); + Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); + Set_DX8_Render_State(D3DRS_ALPHAREF, 0); + Set_DX8_Render_State(D3DRS_ALPHAFUNC, D3DCMP_LESSEQUAL); + Set_DX8_Render_State(D3DRS_DITHERENABLE, FALSE); + Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE, FALSE); + Set_DX8_Render_State(D3DRS_FOGENABLE, FALSE); + Set_DX8_Render_State(D3DRS_SPECULARENABLE, FALSE); +// Set_DX8_Render_State(D3DRS_ZVISIBLE, FALSE); +// Set_DX8_Render_State(D3DRS_FOGCOLOR, 0); +// Set_DX8_Render_State(D3DRS_FOGTABLEMODE, D3DFOG_NONE); +// Set_DX8_Render_State(D3DRS_FOGSTART, 0); + +// Set_DX8_Render_State(D3DRS_FOGEND, WWMath::Float_As_Int(1.0f)); +// Set_DX8_Render_State(D3DRS_FOGDENSITY, WWMath::Float_As_Int(1.0f)); + + //Set_DX8_Render_State(D3DRS_EDGEANTIALIAS, FALSE); + Set_DX8_Render_State(D3DRS_ZBIAS, 0); +// Set_DX8_Render_State(D3DRS_RANGEFOGENABLE, FALSE); + Set_DX8_Render_State(D3DRS_STENCILENABLE, FALSE); + Set_DX8_Render_State(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP); + Set_DX8_Render_State(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP); + Set_DX8_Render_State(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP); + Set_DX8_Render_State(D3DRS_STENCILFUNC, D3DCMP_ALWAYS); + Set_DX8_Render_State(D3DRS_STENCILREF, 0); + Set_DX8_Render_State(D3DRS_STENCILMASK, 0xffffffff); + Set_DX8_Render_State(D3DRS_STENCILWRITEMASK, 0xffffffff); + Set_DX8_Render_State(D3DRS_TEXTUREFACTOR, 0); +/* Set_DX8_Render_State(D3DRS_WRAP0, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP1, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP2, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP3, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP4, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP5, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP6, D3DWRAP_U| D3DWRAP_V); + Set_DX8_Render_State(D3DRS_WRAP7, D3DWRAP_U| D3DWRAP_V);*/ + Set_DX8_Render_State(D3DRS_CLIPPING, TRUE); + Set_DX8_Render_State(D3DRS_LIGHTING, FALSE); + //Set_DX8_Render_State(D3DRS_AMBIENT, 0); +// Set_DX8_Render_State(D3DRS_FOGVERTEXMODE, D3DFOG_NONE); + Set_DX8_Render_State(D3DRS_COLORVERTEX, TRUE); +/* Set_DX8_Render_State(D3DRS_LOCALVIEWER, TRUE); + Set_DX8_Render_State(D3DRS_NORMALIZENORMALS, FALSE); + Set_DX8_Render_State(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1); + Set_DX8_Render_State(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2); + Set_DX8_Render_State(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL); + Set_DX8_Render_State(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL); + Set_DX8_Render_State(D3DRS_VERTEXBLEND, D3DVBF_DISABLE);*/ + //Set_DX8_Render_State(D3DRS_CLIPPLANEENABLE, 0); + Set_DX8_Render_State(D3DRS_SOFTWAREVERTEXPROCESSING, FALSE); + //Set_DX8_Render_State(D3DRS_POINTSIZE, 0x3f800000); + //Set_DX8_Render_State(D3DRS_POINTSIZE_MIN, 0); + //Set_DX8_Render_State(D3DRS_POINTSPRITEENABLE, FALSE); + //Set_DX8_Render_State(D3DRS_POINTSCALEENABLE, FALSE); + //Set_DX8_Render_State(D3DRS_POINTSCALE_A, 0); + //Set_DX8_Render_State(D3DRS_POINTSCALE_B, 0); + //Set_DX8_Render_State(D3DRS_POINTSCALE_C, 0); + //Set_DX8_Render_State(D3DRS_MULTISAMPLEANTIALIAS, TRUE); + //Set_DX8_Render_State(D3DRS_MULTISAMPLEMASK, 0xffffffff); + //Set_DX8_Render_State(D3DRS_PATCHEDGESTYLE, D3DPATCHEDGE_DISCRETE); + //Set_DX8_Render_State(D3DRS_PATCHSEGMENTS, 0x3f800000); + //Set_DX8_Render_State(D3DRS_DEBUGMONITORTOKEN, D3DDMT_ENABLE); + //Set_DX8_Render_State(D3DRS_POINTSIZE_MAX, Float_At_Int(64.0f)); + //Set_DX8_Render_State(D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE); + Set_DX8_Render_State(D3DRS_COLORWRITEENABLE, 0x0000000f); + //Set_DX8_Render_State(D3DRS_TWEENFACTOR, 0); + Set_DX8_Render_State(D3DRS_BLENDOP, D3DBLENDOP_ADD); + //Set_DX8_Render_State(D3DRS_POSITIONORDER, D3DORDER_CUBIC); + //Set_DX8_Render_State(D3DRS_NORMALORDER, D3DORDER_LINEAR); + + // disable TSS stages + int i; + for (i=0; iGet_Max_Textures_Per_Pass(); i++) + { + Set_DX8_Texture_Stage_State(i, D3DTSS_COLOROP, D3DTOP_DISABLE); + Set_DX8_Texture_Stage_State(i, D3DTSS_COLORARG1, D3DTA_TEXTURE); + Set_DX8_Texture_Stage_State(i, D3DTSS_COLORARG2, D3DTA_DIFFUSE); + + Set_DX8_Texture_Stage_State(i, D3DTSS_ALPHAOP, D3DTOP_DISABLE); + Set_DX8_Texture_Stage_State(i, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); + Set_DX8_Texture_Stage_State(i, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); + + /*Set_DX8_Texture_Stage_State(i, D3DTSS_BUMPENVMAT00, 0); + Set_DX8_Texture_Stage_State(i, D3DTSS_BUMPENVMAT01, 0); + Set_DX8_Texture_Stage_State(i, D3DTSS_BUMPENVMAT10, 0); + Set_DX8_Texture_Stage_State(i, D3DTSS_BUMPENVMAT11, 0); + Set_DX8_Texture_Stage_State(i, D3DTSS_BUMPENVLSCALE, 0); + Set_DX8_Texture_Stage_State(i, D3DTSS_BUMPENVLOFFSET, 0);*/ + + Set_DX8_Texture_Stage_State(i, D3DTSS_TEXCOORDINDEX, i); + + + Set_DX8_Texture_Stage_State(i, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); + Set_DX8_Texture_Stage_State(i, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); + Set_DX8_Texture_Stage_State(i, D3DTSS_BORDERCOLOR, 0); +// Set_DX8_Texture_Stage_State(i, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); +// Set_DX8_Texture_Stage_State(i, D3DTSS_MINFILTER, D3DTEXF_LINEAR); +// Set_DX8_Texture_Stage_State(i, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); +// Set_DX8_Texture_Stage_State(i, D3DTSS_MIPMAPLODBIAS, 0); +// Set_DX8_Texture_Stage_State(i, D3DTSS_MAXMIPLEVEL, 0); +// Set_DX8_Texture_Stage_State(i, D3DTSS_MAXANISOTROPY, 1); + //Set_DX8_Texture_Stage_State(i, D3DTSS_ADDRESSW, D3DTADDRESS_WRAP); + //Set_DX8_Texture_Stage_State(i, D3DTSS_COLORARG0, D3DTA_CURRENT); + //Set_DX8_Texture_Stage_State(i, D3DTSS_ALPHAARG0, D3DTA_CURRENT); + //Set_DX8_Texture_Stage_State(i, D3DTSS_RESULTARG, D3DTA_CURRENT); + + Set_DX8_Texture_Stage_State(i, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); + Set_Texture(i,NULL); + } + +// DX8Wrapper::Set_Material(NULL); + VertexMaterialClass::Apply_Null(); + + for (unsigned index=0;index<4;++index) { + SNAPSHOT_SAY(("Clearing light %d to NULL\n",index)); + Set_DX8_Light(index,NULL); + } + + // set up simple default TSS + Vector4 vconst[MAX_VERTEX_SHADER_CONSTANTS]; + memset(vconst,0,sizeof(Vector4)*MAX_VERTEX_SHADER_CONSTANTS); + Set_Vertex_Shader_Constant(0, vconst, MAX_VERTEX_SHADER_CONSTANTS); + + Vector4 pconst[MAX_PIXEL_SHADER_CONSTANTS]; + memset(pconst,0,sizeof(Vector4)*MAX_PIXEL_SHADER_CONSTANTS); + Set_Pixel_Shader_Constant(0, pconst, MAX_PIXEL_SHADER_CONSTANTS); + + Set_Vertex_Shader(DX8_FVF_XYZNDUV2); + Set_Pixel_Shader(0); + + ShaderClass::Invalidate(); +} + +const char* DX8Wrapper::Get_DX8_Render_State_Name(D3DRENDERSTATETYPE state) +{ + switch (state) { + case D3DRS_ZENABLE : return "D3DRS_ZENABLE"; + case D3DRS_FILLMODE : return "D3DRS_FILLMODE"; + case D3DRS_SHADEMODE : return "D3DRS_SHADEMODE"; + case D3DRS_LINEPATTERN : return "D3DRS_LINEPATTERN"; + case D3DRS_ZWRITEENABLE : return "D3DRS_ZWRITEENABLE"; + case D3DRS_ALPHATESTENABLE : return "D3DRS_ALPHATESTENABLE"; + case D3DRS_LASTPIXEL : return "D3DRS_LASTPIXEL"; + case D3DRS_SRCBLEND : return "D3DRS_SRCBLEND"; + case D3DRS_DESTBLEND : return "D3DRS_DESTBLEND"; + case D3DRS_CULLMODE : return "D3DRS_CULLMODE"; + case D3DRS_ZFUNC : return "D3DRS_ZFUNC"; + case D3DRS_ALPHAREF : return "D3DRS_ALPHAREF"; + case D3DRS_ALPHAFUNC : return "D3DRS_ALPHAFUNC"; + case D3DRS_DITHERENABLE : return "D3DRS_DITHERENABLE"; + case D3DRS_ALPHABLENDENABLE : return "D3DRS_ALPHABLENDENABLE"; + case D3DRS_FOGENABLE : return "D3DRS_FOGENABLE"; + case D3DRS_SPECULARENABLE : return "D3DRS_SPECULARENABLE"; + case D3DRS_ZVISIBLE : return "D3DRS_ZVISIBLE"; + case D3DRS_FOGCOLOR : return "D3DRS_FOGCOLOR"; + case D3DRS_FOGTABLEMODE : return "D3DRS_FOGTABLEMODE"; + case D3DRS_FOGSTART : return "D3DRS_FOGSTART"; + case D3DRS_FOGEND : return "D3DRS_FOGEND"; + case D3DRS_FOGDENSITY : return "D3DRS_FOGDENSITY"; + case D3DRS_EDGEANTIALIAS : return "D3DRS_EDGEANTIALIAS"; + case D3DRS_ZBIAS : return "D3DRS_ZBIAS"; + case D3DRS_RANGEFOGENABLE : return "D3DRS_RANGEFOGENABLE"; + case D3DRS_STENCILENABLE : return "D3DRS_STENCILENABLE"; + case D3DRS_STENCILFAIL : return "D3DRS_STENCILFAIL"; + case D3DRS_STENCILZFAIL : return "D3DRS_STENCILZFAIL"; + case D3DRS_STENCILPASS : return "D3DRS_STENCILPASS"; + case D3DRS_STENCILFUNC : return "D3DRS_STENCILFUNC"; + case D3DRS_STENCILREF : return "D3DRS_STENCILREF"; + case D3DRS_STENCILMASK : return "D3DRS_STENCILMASK"; + case D3DRS_STENCILWRITEMASK : return "D3DRS_STENCILWRITEMASK"; + case D3DRS_TEXTUREFACTOR : return "D3DRS_TEXTUREFACTOR"; + case D3DRS_WRAP0 : return "D3DRS_WRAP0"; + case D3DRS_WRAP1 : return "D3DRS_WRAP1"; + case D3DRS_WRAP2 : return "D3DRS_WRAP2"; + case D3DRS_WRAP3 : return "D3DRS_WRAP3"; + case D3DRS_WRAP4 : return "D3DRS_WRAP4"; + case D3DRS_WRAP5 : return "D3DRS_WRAP5"; + case D3DRS_WRAP6 : return "D3DRS_WRAP6"; + case D3DRS_WRAP7 : return "D3DRS_WRAP7"; + case D3DRS_CLIPPING : return "D3DRS_CLIPPING"; + case D3DRS_LIGHTING : return "D3DRS_LIGHTING"; + case D3DRS_AMBIENT : return "D3DRS_AMBIENT"; + case D3DRS_FOGVERTEXMODE : return "D3DRS_FOGVERTEXMODE"; + case D3DRS_COLORVERTEX : return "D3DRS_COLORVERTEX"; + case D3DRS_LOCALVIEWER : return "D3DRS_LOCALVIEWER"; + case D3DRS_NORMALIZENORMALS : return "D3DRS_NORMALIZENORMALS"; + case D3DRS_DIFFUSEMATERIALSOURCE : return "D3DRS_DIFFUSEMATERIALSOURCE"; + case D3DRS_SPECULARMATERIALSOURCE : return "D3DRS_SPECULARMATERIALSOURCE"; + case D3DRS_AMBIENTMATERIALSOURCE : return "D3DRS_AMBIENTMATERIALSOURCE"; + case D3DRS_EMISSIVEMATERIALSOURCE : return "D3DRS_EMISSIVEMATERIALSOURCE"; + case D3DRS_VERTEXBLEND : return "D3DRS_VERTEXBLEND"; + case D3DRS_CLIPPLANEENABLE : return "D3DRS_CLIPPLANEENABLE"; + case D3DRS_SOFTWAREVERTEXPROCESSING : return "D3DRS_SOFTWAREVERTEXPROCESSING"; + case D3DRS_POINTSIZE : return "D3DRS_POINTSIZE"; + case D3DRS_POINTSIZE_MIN : return "D3DRS_POINTSIZE_MIN"; + case D3DRS_POINTSPRITEENABLE : return "D3DRS_POINTSPRITEENABLE"; + case D3DRS_POINTSCALEENABLE : return "D3DRS_POINTSCALEENABLE"; + case D3DRS_POINTSCALE_A : return "D3DRS_POINTSCALE_A"; + case D3DRS_POINTSCALE_B : return "D3DRS_POINTSCALE_B"; + case D3DRS_POINTSCALE_C : return "D3DRS_POINTSCALE_C"; + case D3DRS_MULTISAMPLEANTIALIAS : return "D3DRS_MULTISAMPLEANTIALIAS"; + case D3DRS_MULTISAMPLEMASK : return "D3DRS_MULTISAMPLEMASK"; + case D3DRS_PATCHEDGESTYLE : return "D3DRS_PATCHEDGESTYLE"; + case D3DRS_PATCHSEGMENTS : return "D3DRS_PATCHSEGMENTS"; + case D3DRS_DEBUGMONITORTOKEN : return "D3DRS_DEBUGMONITORTOKEN"; + case D3DRS_POINTSIZE_MAX : return "D3DRS_POINTSIZE_MAX"; + case D3DRS_INDEXEDVERTEXBLENDENABLE : return "D3DRS_INDEXEDVERTEXBLENDENABLE"; + case D3DRS_COLORWRITEENABLE : return "D3DRS_COLORWRITEENABLE"; + case D3DRS_TWEENFACTOR : return "D3DRS_TWEENFACTOR"; + case D3DRS_BLENDOP : return "D3DRS_BLENDOP"; +// case D3DRS_POSITIONORDER : return "D3DRS_POSITIONORDER"; +// case D3DRS_NORMALORDER : return "D3DRS_NORMALORDER"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Texture_Stage_State_Name(D3DTEXTURESTAGESTATETYPE state) +{ + switch (state) { + case D3DTSS_COLOROP : return "D3DTSS_COLOROP"; + case D3DTSS_COLORARG1 : return "D3DTSS_COLORARG1"; + case D3DTSS_COLORARG2 : return "D3DTSS_COLORARG2"; + case D3DTSS_ALPHAOP : return "D3DTSS_ALPHAOP"; + case D3DTSS_ALPHAARG1 : return "D3DTSS_ALPHAARG1"; + case D3DTSS_ALPHAARG2 : return "D3DTSS_ALPHAARG2"; + case D3DTSS_BUMPENVMAT00 : return "D3DTSS_BUMPENVMAT00"; + case D3DTSS_BUMPENVMAT01 : return "D3DTSS_BUMPENVMAT01"; + case D3DTSS_BUMPENVMAT10 : return "D3DTSS_BUMPENVMAT10"; + case D3DTSS_BUMPENVMAT11 : return "D3DTSS_BUMPENVMAT11"; + case D3DTSS_TEXCOORDINDEX : return "D3DTSS_TEXCOORDINDEX"; + case D3DTSS_ADDRESSU : return "D3DTSS_ADDRESSU"; + case D3DTSS_ADDRESSV : return "D3DTSS_ADDRESSV"; + case D3DTSS_BORDERCOLOR : return "D3DTSS_BORDERCOLOR"; + case D3DTSS_MAGFILTER : return "D3DTSS_MAGFILTER"; + case D3DTSS_MINFILTER : return "D3DTSS_MINFILTER"; + case D3DTSS_MIPFILTER : return "D3DTSS_MIPFILTER"; + case D3DTSS_MIPMAPLODBIAS : return "D3DTSS_MIPMAPLODBIAS"; + case D3DTSS_MAXMIPLEVEL : return "D3DTSS_MAXMIPLEVEL"; + case D3DTSS_MAXANISOTROPY : return "D3DTSS_MAXANISOTROPY"; + case D3DTSS_BUMPENVLSCALE : return "D3DTSS_BUMPENVLSCALE"; + case D3DTSS_BUMPENVLOFFSET : return "D3DTSS_BUMPENVLOFFSET"; + case D3DTSS_TEXTURETRANSFORMFLAGS : return "D3DTSS_TEXTURETRANSFORMFLAGS"; + case D3DTSS_ADDRESSW : return "D3DTSS_ADDRESSW"; + case D3DTSS_COLORARG0 : return "D3DTSS_COLORARG0"; + case D3DTSS_ALPHAARG0 : return "D3DTSS_ALPHAARG0"; + case D3DTSS_RESULTARG : return "D3DTSS_RESULTARG"; + default : return "UNKNOWN"; + } +} + +void DX8Wrapper::Get_DX8_Render_State_Value_Name(StringClass& name, D3DRENDERSTATETYPE state, unsigned value) +{ + switch (state) { + case D3DRS_ZENABLE: + name=Get_DX8_ZBuffer_Type_Name(value); + break; + + case D3DRS_FILLMODE: + name=Get_DX8_Fill_Mode_Name(value); + break; + + case D3DRS_SHADEMODE: + name=Get_DX8_Shade_Mode_Name(value); + break; + + case D3DRS_LINEPATTERN: + case D3DRS_FOGCOLOR: + case D3DRS_ALPHAREF: + case D3DRS_STENCILMASK: + case D3DRS_STENCILWRITEMASK: + case D3DRS_TEXTUREFACTOR: + case D3DRS_AMBIENT: + case D3DRS_CLIPPLANEENABLE: + case D3DRS_MULTISAMPLEMASK: + name.Format("0x%x",value); + break; + + case D3DRS_ZWRITEENABLE: + case D3DRS_ALPHATESTENABLE: + case D3DRS_LASTPIXEL: + case D3DRS_DITHERENABLE: + case D3DRS_ALPHABLENDENABLE: + case D3DRS_FOGENABLE: + case D3DRS_SPECULARENABLE: + case D3DRS_STENCILENABLE: + case D3DRS_RANGEFOGENABLE: + case D3DRS_EDGEANTIALIAS: + case D3DRS_CLIPPING: + case D3DRS_LIGHTING: + case D3DRS_COLORVERTEX: + case D3DRS_LOCALVIEWER: + case D3DRS_NORMALIZENORMALS: + case D3DRS_SOFTWAREVERTEXPROCESSING: + case D3DRS_POINTSPRITEENABLE: + case D3DRS_POINTSCALEENABLE: + case D3DRS_MULTISAMPLEANTIALIAS: + case D3DRS_INDEXEDVERTEXBLENDENABLE: + name=value ? "TRUE" : "FALSE"; + break; + + case D3DRS_SRCBLEND: + case D3DRS_DESTBLEND: + name=Get_DX8_Blend_Name(value); + break; + + case D3DRS_CULLMODE: + name=Get_DX8_Cull_Mode_Name(value); + break; + + case D3DRS_ZFUNC: + case D3DRS_ALPHAFUNC: + case D3DRS_STENCILFUNC: + name=Get_DX8_Cmp_Func_Name(value); + break; + + case D3DRS_ZVISIBLE: + name="NOTSUPPORTED"; + break; + + case D3DRS_FOGTABLEMODE: + case D3DRS_FOGVERTEXMODE: + name=Get_DX8_Fog_Mode_Name(value); + break; + + case D3DRS_FOGSTART: + case D3DRS_FOGEND: + case D3DRS_FOGDENSITY: + case D3DRS_POINTSIZE: + case D3DRS_POINTSIZE_MIN: + case D3DRS_POINTSCALE_A: + case D3DRS_POINTSCALE_B: + case D3DRS_POINTSCALE_C: + case D3DRS_PATCHSEGMENTS: + case D3DRS_POINTSIZE_MAX: + case D3DRS_TWEENFACTOR: + name.Format("%f",*(float*)&value); + break; + + case D3DRS_ZBIAS: + case D3DRS_STENCILREF: + name.Format("%d",value); + break; + + case D3DRS_STENCILFAIL: + case D3DRS_STENCILZFAIL: + case D3DRS_STENCILPASS: + name=Get_DX8_Stencil_Op_Name(value); + break; + + case D3DRS_WRAP0: + case D3DRS_WRAP1: + case D3DRS_WRAP2: + case D3DRS_WRAP3: + case D3DRS_WRAP4: + case D3DRS_WRAP5: + case D3DRS_WRAP6: + case D3DRS_WRAP7: + name="0"; + if (value&D3DWRAP_U) name+="|D3DWRAP_U"; + if (value&D3DWRAP_V) name+="|D3DWRAP_V"; + if (value&D3DWRAP_W) name+="|D3DWRAP_W"; + break; + + case D3DRS_DIFFUSEMATERIALSOURCE: + case D3DRS_SPECULARMATERIALSOURCE: + case D3DRS_AMBIENTMATERIALSOURCE: + case D3DRS_EMISSIVEMATERIALSOURCE: + name=Get_DX8_Material_Source_Name(value); + break; + + case D3DRS_VERTEXBLEND: + name=Get_DX8_Vertex_Blend_Flag_Name(value); + break; + + case D3DRS_PATCHEDGESTYLE: + name=Get_DX8_Patch_Edge_Style_Name(value); + break; + + case D3DRS_DEBUGMONITORTOKEN: + name=Get_DX8_Debug_Monitor_Token_Name(value); + break; + + case D3DRS_COLORWRITEENABLE: + name="0"; + if (value&D3DCOLORWRITEENABLE_RED) name+="|D3DCOLORWRITEENABLE_RED"; + if (value&D3DCOLORWRITEENABLE_GREEN) name+="|D3DCOLORWRITEENABLE_GREEN"; + if (value&D3DCOLORWRITEENABLE_BLUE) name+="|D3DCOLORWRITEENABLE_BLUE"; + if (value&D3DCOLORWRITEENABLE_ALPHA) name+="|D3DCOLORWRITEENABLE_ALPHA"; + break; + case D3DRS_BLENDOP: + name=Get_DX8_Blend_Op_Name(value); + break; + default: + name.Format("UNKNOWN (%d)",value); + break; + } +} + +void DX8Wrapper::Get_DX8_Texture_Stage_State_Value_Name(StringClass& name, D3DTEXTURESTAGESTATETYPE state, unsigned value) +{ + switch (state) { + case D3DTSS_COLOROP: + case D3DTSS_ALPHAOP: + name=Get_DX8_Texture_Op_Name(value); + break; + + case D3DTSS_COLORARG0: + case D3DTSS_COLORARG1: + case D3DTSS_COLORARG2: + case D3DTSS_ALPHAARG0: + case D3DTSS_ALPHAARG1: + case D3DTSS_ALPHAARG2: + case D3DTSS_RESULTARG: + name=Get_DX8_Texture_Arg_Name(value); + break; + + case D3DTSS_ADDRESSU: + case D3DTSS_ADDRESSV: + case D3DTSS_ADDRESSW: + name=Get_DX8_Texture_Address_Name(value); + break; + + case D3DTSS_MAGFILTER: + case D3DTSS_MINFILTER: + case D3DTSS_MIPFILTER: + name=Get_DX8_Texture_Filter_Name(value); + break; + + case D3DTSS_TEXTURETRANSFORMFLAGS: + name=Get_DX8_Texture_Transform_Flag_Name(value); + + // Floating point values + case D3DTSS_MIPMAPLODBIAS: + case D3DTSS_BUMPENVMAT00: + case D3DTSS_BUMPENVMAT01: + case D3DTSS_BUMPENVMAT10: + case D3DTSS_BUMPENVMAT11: + case D3DTSS_BUMPENVLSCALE: + case D3DTSS_BUMPENVLOFFSET: + name.Format("%f",*(float*)&value); + break; + + case D3DTSS_TEXCOORDINDEX: + if ((value&0xffff0000)==D3DTSS_TCI_CAMERASPACENORMAL) { + name.Format("D3DTSS_TCI_CAMERASPACENORMAL|%d",value&0xffff); + } + else if ((value&0xffff0000)==D3DTSS_TCI_CAMERASPACEPOSITION) { + name.Format("D3DTSS_TCI_CAMERASPACEPOSITION|%d",value&0xffff); + } + else if ((value&0xffff0000)==D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR) { + name.Format("D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR|%d",value&0xffff); + } + else { + name.Format("%d",value); + } + break; + + // Integer value + case D3DTSS_MAXMIPLEVEL: + case D3DTSS_MAXANISOTROPY: + name.Format("%d",value); + break; + // Hex values + case D3DTSS_BORDERCOLOR: + name.Format("0x%x",value); + break; + + default: + name.Format("UNKNOWN (%d)",value); + break; + } +} + +const char* DX8Wrapper::Get_DX8_Texture_Op_Name(unsigned value) +{ + switch (value) { + case D3DTOP_DISABLE : return "D3DTOP_DISABLE"; + case D3DTOP_SELECTARG1 : return "D3DTOP_SELECTARG1"; + case D3DTOP_SELECTARG2 : return "D3DTOP_SELECTARG2"; + case D3DTOP_MODULATE : return "D3DTOP_MODULATE"; + case D3DTOP_MODULATE2X : return "D3DTOP_MODULATE2X"; + case D3DTOP_MODULATE4X : return "D3DTOP_MODULATE4X"; + case D3DTOP_ADD : return "D3DTOP_ADD"; + case D3DTOP_ADDSIGNED : return "D3DTOP_ADDSIGNED"; + case D3DTOP_ADDSIGNED2X : return "D3DTOP_ADDSIGNED2X"; + case D3DTOP_SUBTRACT : return "D3DTOP_SUBTRACT"; + case D3DTOP_ADDSMOOTH : return "D3DTOP_ADDSMOOTH"; + case D3DTOP_BLENDDIFFUSEALPHA : return "D3DTOP_BLENDDIFFUSEALPHA"; + case D3DTOP_BLENDTEXTUREALPHA : return "D3DTOP_BLENDTEXTUREALPHA"; + case D3DTOP_BLENDFACTORALPHA : return "D3DTOP_BLENDFACTORALPHA"; + case D3DTOP_BLENDTEXTUREALPHAPM : return "D3DTOP_BLENDTEXTUREALPHAPM"; + case D3DTOP_BLENDCURRENTALPHA : return "D3DTOP_BLENDCURRENTALPHA"; + case D3DTOP_PREMODULATE : return "D3DTOP_PREMODULATE"; + case D3DTOP_MODULATEALPHA_ADDCOLOR : return "D3DTOP_MODULATEALPHA_ADDCOLOR"; + case D3DTOP_MODULATECOLOR_ADDALPHA : return "D3DTOP_MODULATECOLOR_ADDALPHA"; + case D3DTOP_MODULATEINVALPHA_ADDCOLOR : return "D3DTOP_MODULATEINVALPHA_ADDCOLOR"; + case D3DTOP_MODULATEINVCOLOR_ADDALPHA : return "D3DTOP_MODULATEINVCOLOR_ADDALPHA"; + case D3DTOP_BUMPENVMAP : return "D3DTOP_BUMPENVMAP"; + case D3DTOP_BUMPENVMAPLUMINANCE : return "D3DTOP_BUMPENVMAPLUMINANCE"; + case D3DTOP_DOTPRODUCT3 : return "D3DTOP_DOTPRODUCT3"; + case D3DTOP_MULTIPLYADD : return "D3DTOP_MULTIPLYADD"; + case D3DTOP_LERP : return "D3DTOP_LERP"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Texture_Arg_Name(unsigned value) +{ + switch (value) { + case D3DTA_CURRENT : return "D3DTA_CURRENT"; + case D3DTA_DIFFUSE : return "D3DTA_DIFFUSE"; + case D3DTA_SELECTMASK : return "D3DTA_SELECTMASK"; + case D3DTA_SPECULAR : return "D3DTA_SPECULAR"; + case D3DTA_TEMP : return "D3DTA_TEMP"; + case D3DTA_TEXTURE : return "D3DTA_TEXTURE"; + case D3DTA_TFACTOR : return "D3DTA_TFACTOR"; + case D3DTA_ALPHAREPLICATE : return "D3DTA_ALPHAREPLICATE"; + case D3DTA_COMPLEMENT : return "D3DTA_COMPLEMENT"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Texture_Filter_Name(unsigned value) +{ + switch (value) { + case D3DTEXF_NONE : return "D3DTEXF_NONE"; + case D3DTEXF_POINT : return "D3DTEXF_POINT"; + case D3DTEXF_LINEAR : return "D3DTEXF_LINEAR"; + case D3DTEXF_ANISOTROPIC : return "D3DTEXF_ANISOTROPIC"; + case D3DTEXF_FLATCUBIC : return "D3DTEXF_FLATCUBIC"; + case D3DTEXF_GAUSSIANCUBIC : return "D3DTEXF_GAUSSIANCUBIC"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Texture_Address_Name(unsigned value) +{ + switch (value) { + case D3DTADDRESS_WRAP : return "D3DTADDRESS_WRAP"; + case D3DTADDRESS_MIRROR : return "D3DTADDRESS_MIRROR"; + case D3DTADDRESS_CLAMP : return "D3DTADDRESS_CLAMP"; + case D3DTADDRESS_BORDER : return "D3DTADDRESS_BORDER"; + case D3DTADDRESS_MIRRORONCE: return "D3DTADDRESS_MIRRORONCE"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Texture_Transform_Flag_Name(unsigned value) +{ + switch (value) { + case D3DTTFF_DISABLE : return "D3DTTFF_DISABLE"; + case D3DTTFF_COUNT1 : return "D3DTTFF_COUNT1"; + case D3DTTFF_COUNT2 : return "D3DTTFF_COUNT2"; + case D3DTTFF_COUNT3 : return "D3DTTFF_COUNT3"; + case D3DTTFF_COUNT4 : return "D3DTTFF_COUNT4"; + case D3DTTFF_PROJECTED : return "D3DTTFF_PROJECTED"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_ZBuffer_Type_Name(unsigned value) +{ + switch (value) { + case D3DZB_FALSE : return "D3DZB_FALSE"; + case D3DZB_TRUE : return "D3DZB_TRUE"; + case D3DZB_USEW : return "D3DZB_USEW"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Fill_Mode_Name(unsigned value) +{ + switch (value) { + case D3DFILL_POINT : return "D3DFILL_POINT"; + case D3DFILL_WIREFRAME : return "D3DFILL_WIREFRAME"; + case D3DFILL_SOLID : return "D3DFILL_SOLID"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Shade_Mode_Name(unsigned value) +{ + switch (value) { + case D3DSHADE_FLAT : return "D3DSHADE_FLAT"; + case D3DSHADE_GOURAUD : return "D3DSHADE_GOURAUD"; + case D3DSHADE_PHONG : return "D3DSHADE_PHONG"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Blend_Name(unsigned value) +{ + switch (value) { + case D3DBLEND_ZERO : return "D3DBLEND_ZERO"; + case D3DBLEND_ONE : return "D3DBLEND_ONE"; + case D3DBLEND_SRCCOLOR : return "D3DBLEND_SRCCOLOR"; + case D3DBLEND_INVSRCCOLOR : return "D3DBLEND_INVSRCCOLOR"; + case D3DBLEND_SRCALPHA : return "D3DBLEND_SRCALPHA"; + case D3DBLEND_INVSRCALPHA : return "D3DBLEND_INVSRCALPHA"; + case D3DBLEND_DESTALPHA : return "D3DBLEND_DESTALPHA"; + case D3DBLEND_INVDESTALPHA : return "D3DBLEND_INVDESTALPHA"; + case D3DBLEND_DESTCOLOR : return "D3DBLEND_DESTCOLOR"; + case D3DBLEND_INVDESTCOLOR : return "D3DBLEND_INVDESTCOLOR"; + case D3DBLEND_SRCALPHASAT : return "D3DBLEND_SRCALPHASAT"; + case D3DBLEND_BOTHSRCALPHA : return "D3DBLEND_BOTHSRCALPHA"; + case D3DBLEND_BOTHINVSRCALPHA : return "D3DBLEND_BOTHINVSRCALPHA"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Cull_Mode_Name(unsigned value) +{ + switch (value) { + case D3DCULL_NONE : return "D3DCULL_NONE"; + case D3DCULL_CW : return "D3DCULL_CW"; + case D3DCULL_CCW : return "D3DCULL_CCW"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Cmp_Func_Name(unsigned value) +{ + switch (value) { + case D3DCMP_NEVER : return "D3DCMP_NEVER"; + case D3DCMP_LESS : return "D3DCMP_LESS"; + case D3DCMP_EQUAL : return "D3DCMP_EQUAL"; + case D3DCMP_LESSEQUAL : return "D3DCMP_LESSEQUAL"; + case D3DCMP_GREATER : return "D3DCMP_GREATER"; + case D3DCMP_NOTEQUAL : return "D3DCMP_NOTEQUAL"; + case D3DCMP_GREATEREQUAL : return "D3DCMP_GREATEREQUAL"; + case D3DCMP_ALWAYS : return "D3DCMP_ALWAYS"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Fog_Mode_Name(unsigned value) +{ + switch (value) { + case D3DFOG_NONE : return "D3DFOG_NONE"; + case D3DFOG_EXP : return "D3DFOG_EXP"; + case D3DFOG_EXP2 : return "D3DFOG_EXP2"; + case D3DFOG_LINEAR : return "D3DFOG_LINEAR"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Stencil_Op_Name(unsigned value) +{ + switch (value) { + case D3DSTENCILOP_KEEP : return "D3DSTENCILOP_KEEP"; + case D3DSTENCILOP_ZERO : return "D3DSTENCILOP_ZERO"; + case D3DSTENCILOP_REPLACE : return "D3DSTENCILOP_REPLACE"; + case D3DSTENCILOP_INCRSAT : return "D3DSTENCILOP_INCRSAT"; + case D3DSTENCILOP_DECRSAT : return "D3DSTENCILOP_DECRSAT"; + case D3DSTENCILOP_INVERT : return "D3DSTENCILOP_INVERT"; + case D3DSTENCILOP_INCR : return "D3DSTENCILOP_INCR"; + case D3DSTENCILOP_DECR : return "D3DSTENCILOP_DECR"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Material_Source_Name(unsigned value) +{ + switch (value) { + case D3DMCS_MATERIAL : return "D3DMCS_MATERIAL"; + case D3DMCS_COLOR1 : return "D3DMCS_COLOR1"; + case D3DMCS_COLOR2 : return "D3DMCS_COLOR2"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Vertex_Blend_Flag_Name(unsigned value) +{ + switch (value) { + case D3DVBF_DISABLE : return "D3DVBF_DISABLE"; + case D3DVBF_1WEIGHTS : return "D3DVBF_1WEIGHTS"; + case D3DVBF_2WEIGHTS : return "D3DVBF_2WEIGHTS"; + case D3DVBF_3WEIGHTS : return "D3DVBF_3WEIGHTS"; + case D3DVBF_TWEENING : return "D3DVBF_TWEENING"; + case D3DVBF_0WEIGHTS : return "D3DVBF_0WEIGHTS"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Patch_Edge_Style_Name(unsigned value) +{ + switch (value) { + case D3DPATCHEDGE_DISCRETE : return "D3DPATCHEDGE_DISCRETE"; + case D3DPATCHEDGE_CONTINUOUS:return "D3DPATCHEDGE_CONTINUOUS"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Debug_Monitor_Token_Name(unsigned value) +{ + switch (value) { + case D3DDMT_ENABLE : return "D3DDMT_ENABLE"; + case D3DDMT_DISABLE : return "D3DDMT_DISABLE"; + default : return "UNKNOWN"; + } +} + +const char* DX8Wrapper::Get_DX8_Blend_Op_Name(unsigned value) +{ + switch (value) { + case D3DBLENDOP_ADD : return "D3DBLENDOP_ADD"; + case D3DBLENDOP_SUBTRACT : return "D3DBLENDOP_SUBTRACT"; + case D3DBLENDOP_REVSUBTRACT: return "D3DBLENDOP_REVSUBTRACT"; + case D3DBLENDOP_MIN : return "D3DBLENDOP_MIN"; + case D3DBLENDOP_MAX : return "D3DBLENDOP_MAX"; + default : return "UNKNOWN"; + } +} + + //============================================================================ // DX8Wrapper::getBackBufferFormat //============================================================================ diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h index 85237c1a18..b8bd2ddeac 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h @@ -60,7 +60,25 @@ #include "dx8indexbuffer.h" #include "vertmaterial.h" +/* +** Registry value names +*/ +#define VALUE_NAME_RENDER_DEVICE_NAME "RenderDeviceName" +#define VALUE_NAME_RENDER_DEVICE_WIDTH "RenderDeviceWidth" +#define VALUE_NAME_RENDER_DEVICE_HEIGHT "RenderDeviceHeight" +#define VALUE_NAME_RENDER_DEVICE_DEPTH "RenderDeviceDepth" +#define VALUE_NAME_RENDER_DEVICE_WINDOWED "RenderDeviceWindowed" +#define VALUE_NAME_RENDER_DEVICE_TEXTURE_DEPTH "RenderDeviceTextureDepth" + const unsigned MAX_TEXTURE_STAGES=2; +const unsigned MAX_VERTEX_STREAMS=2; +const unsigned MAX_VERTEX_SHADER_CONSTANTS=96; +const unsigned MAX_PIXEL_SHADER_CONSTANTS=8; +const unsigned MAX_SHADOW_MAPS=1; + +#define prevVer +#define nextVer + enum { BUFFER_TYPE_DX8, @@ -90,6 +108,7 @@ class SurfaceClass; #define DX8_RECORD_TEXTURE_CHANGE() texture_changes++ #define DX8_RECORD_RENDER_STATE_CHANGE() render_state_changes++ #define DX8_RECORD_TEXTURE_STAGE_STATE_CHANGE() texture_stage_state_changes++ +#define DX8_RECORD_DRAW_CALLS() draw_calls++ extern unsigned number_of_DX8_calls; extern bool _DX8SingleThreaded; @@ -229,7 +248,7 @@ class DX8Wrapper static DX8_Stats stats; #endif - static bool Init(void * hwnd); + static bool Init(void * hwnd, bool lite = false); static void Shutdown(void); static void SetCleanupHook(DX8_CleanupHook *pCleanupHook) {m_pCleanupHook = pCleanupHook;}; @@ -239,6 +258,10 @@ class DX8Wrapper */ static void Do_Onetime_Device_Dependent_Inits(void); static void Do_Onetime_Device_Dependent_Shutdowns(void); + + static bool Is_Device_Lost() { return IsDeviceLost; } + static bool Is_Initted(void) { return IsInitted; } + static bool Has_Stencil (void); static void Get_Format_Name(unsigned int format, StringClass *tex_format); @@ -291,6 +314,7 @@ class DX8Wrapper static void Set_DX8_Texture_Stage_State(unsigned stage, D3DTEXTURESTAGESTATETYPE state, unsigned value); static void Set_DX8_Texture(unsigned int stage, IDirect3DBaseTexture8* texture); static void Set_Light_Environment(LightEnvironmentClass* light_env); + static LightEnvironmentClass* Get_Light_Environment() { return Light_Environment; } static void Set_Fog(bool enable, const Vector3 &color, float start, float end); static WWINLINE const D3DLIGHT8& Peek_Light(unsigned index); @@ -329,6 +353,7 @@ class DX8Wrapper /* ** Resources */ + static IDirect3DTexture8 * _Create_DX8_Texture ( unsigned int width, @@ -423,6 +448,26 @@ class DX8Wrapper static void Set_Render_Target (TextureBaseClass * texture); static void Set_Render_Target (IDirect3DSurface8 *render_target); static void Set_Render_Target (IDirect3DSwapChain8 *swap_chain); + static bool Is_Render_To_Texture(void) { return IsRenderToTexture; } + + // shader system udpates KJM v + static void Apply_Default_State(); + + static void Set_Vertex_Shader(DWORD vertex_shader); + static void Set_Pixel_Shader(DWORD pixel_shader); + + static void Set_Vertex_Shader_Constant(int reg, const void* data, int count); + static void Set_Pixel_Shader_Constant(int reg, const void* data, int count); + + static DWORD Get_Vertex_Processing_Behavior() { return Vertex_Processing_Behavior; } + + // Needed by scene lighting class + static void Set_Ambient(const Vector3& color); + static const Vector3& Get_Ambient() { return Ambient_Color; } + // shader system updates KJM ^ + + + static IDirect3DDevice8* _Get_D3D_Device8() { return D3DDevice; } static IDirect3D8* _Get_D3D8() { return D3DInterface; } @@ -435,8 +480,37 @@ class DX8Wrapper static bool Registry_Save_Render_Device( const char * sub_key ); static bool Registry_Load_Render_Device( const char * sub_key, bool resize_window ); + static const char* Get_DX8_Render_State_Name(D3DRENDERSTATETYPE state); + static const char* Get_DX8_Texture_Stage_State_Name(D3DTEXTURESTAGESTATETYPE state); + static unsigned Get_DX8_Render_State(D3DRENDERSTATETYPE state) { return RenderStates[state]; } + + // Names of the specific values of render states and texture stage states + static void Get_DX8_Texture_Stage_State_Value_Name(StringClass& name, D3DTEXTURESTAGESTATETYPE state, unsigned value); + static void Get_DX8_Render_State_Value_Name(StringClass& name, D3DRENDERSTATETYPE state, unsigned value); + + static const char* Get_DX8_Texture_Address_Name(unsigned value); + static const char* Get_DX8_Texture_Filter_Name(unsigned value); + static const char* Get_DX8_Texture_Arg_Name(unsigned value); + static const char* Get_DX8_Texture_Op_Name(unsigned value); + static const char* Get_DX8_Texture_Transform_Flag_Name(unsigned value); + static const char* Get_DX8_ZBuffer_Type_Name(unsigned value); + static const char* Get_DX8_Fill_Mode_Name(unsigned value); + static const char* Get_DX8_Shade_Mode_Name(unsigned value); + static const char* Get_DX8_Blend_Name(unsigned value); + static const char* Get_DX8_Cull_Mode_Name(unsigned value); + static const char* Get_DX8_Cmp_Func_Name(unsigned value); + static const char* Get_DX8_Fog_Mode_Name(unsigned value); + static const char* Get_DX8_Stencil_Op_Name(unsigned value); + static const char* Get_DX8_Material_Source_Name(unsigned value); + static const char* Get_DX8_Vertex_Blend_Flag_Name(unsigned value); + static const char* Get_DX8_Patch_Edge_Style_Name(unsigned value); + static const char* Get_DX8_Debug_Monitor_Token_Name(unsigned value); + static const char* Get_DX8_Blend_Op_Name(unsigned value); + static void Invalidate_Cached_Render_States(void); + static void Set_Draw_Polygon_Low_Bound_Limit(unsigned n) { DrawPolygonLowBoundLimit=n; } + protected: static bool Create_Device(void); @@ -495,8 +569,10 @@ class DX8Wrapper static RenderStateStruct render_state; static unsigned render_state_changed; + static Matrix4x4 DX8Transforms[D3DTS_WORLD+1]; static bool IsInitted; + static bool IsDeviceLost; static void * Hwnd; static unsigned _MainThreadID; @@ -514,6 +590,20 @@ class DX8Wrapper static D3DMATRIX old_view; static D3DMATRIX old_prj; + // shader system updates KJM v + static DWORD Vertex_Shader; + static DWORD Pixel_Shader; + + static Vector4 Vertex_Shader_Constants[MAX_VERTEX_SHADER_CONSTANTS]; + static Vector4 Pixel_Shader_Constants[MAX_PIXEL_SHADER_CONSTANTS]; + + static LightEnvironmentClass* Light_Environment; + static RenderInfoClass* Render_Info; + + static DWORD Vertex_Processing_Behavior; + static Vector3 Ambient_Color; + // shader system updates KJM ^ + static bool world_identity; static unsigned RenderStates[256]; static unsigned TextureStageStates[MAX_TEXTURE_STAGES][32]; @@ -542,10 +632,18 @@ class DX8Wrapper static D3DADAPTER_IDENTIFIER8 CurrentAdapterIdentifier; static IDirect3D8 * D3DInterface; //d3d8; - static IDirect3DDevice8 * D3DDevice; //d3ddevice8; + static IDirect3DDevice8 * D3DDevice; //d3ddevice8; static IDirect3DSurface8 * CurrentRenderTarget; static IDirect3DSurface8 * DefaultRenderTarget; + static unsigned DrawPolygonLowBoundLimit; + + static bool IsRenderToTexture; + + static int ZBias; + static float ZNear; + static float ZFar; + static Matrix4x4 ProjectionMatrix; friend void DX8_Assert(); friend class WW3D; @@ -553,20 +651,79 @@ class DX8Wrapper friend class DX8VertexBufferClass; }; +// shader system updates KJM v +WWINLINE void DX8Wrapper::Set_Vertex_Shader(DWORD vertex_shader) +{ +#if 0 //(gth) some code is bypassing this acessor function so we can't count on this variable... + // may be incorrect if shaders are created and destroyed dynamically + if (Vertex_Shader==vertex_shader) return; +#endif + + Vertex_Shader=vertex_shader; + DX8CALL(SetVertexShader(Vertex_Shader)); +} + +WWINLINE void DX8Wrapper::Set_Pixel_Shader(DWORD pixel_shader) +{ + // may be incorrect if shaders are created and destroyed dynamically + if (Pixel_Shader==pixel_shader) return; + + Pixel_Shader=pixel_shader; + DX8CALL(SetPixelShader(Pixel_Shader)); +} + +WWINLINE void DX8Wrapper::Set_Vertex_Shader_Constant(int reg, const void* data, int count) +{ + int memsize=sizeof(Vector4)*count; + + // may be incorrect if shaders are created and destroyed dynamically + if (memcmp(data, &Vertex_Shader_Constants[reg],memsize)==0) return; + + memcpy(&Vertex_Shader_Constants[reg],data,memsize); + DX8CALL(SetVertexShaderConstant(reg,data,count)); +} + +WWINLINE void DX8Wrapper::Set_Pixel_Shader_Constant(int reg, const void* data, int count) +{ + int memsize=sizeof(Vector4)*count; + + // may be incorrect if shaders are created and destroyed dynamically + if (memcmp(data, &Pixel_Shader_Constants[reg],memsize)==0) return; + + memcpy(&Pixel_Shader_Constants[reg],data,memsize); + DX8CALL(SetPixelShaderConstant(reg,data,count)); +} +// shader system updates KJM ^ + WWINLINE void DX8Wrapper::_Set_DX8_Transform(D3DTRANSFORMSTATETYPE transform,const Matrix4x4& m) { - SNAPSHOT_SAY(("DX8 - SetTransform\n")); - DX8_RECORD_MATRIX_CHANGE(); - DX8CALL(SetTransform(transform,(D3DMATRIX*)&m)); + WWASSERT(transform<=D3DTS_WORLD); +#if 0 // (gth) this optimization is breaking generals because they set the transform behind our backs. + if (m!=DX8Transforms[transform]) +#endif + { + DX8Transforms[transform]=m; + SNAPSHOT_SAY(("DX8 - SetTransform %d [%f,%f,%f,%f][%f,%f,%f,%f][%f,%f,%f,%f][%f,%f,%f,%f]\n",transform,m[0][0],m[0][1],m[0][2],m[0][3],m[1][0],m[1][1],m[1][2],m[1][3],m[2][0],m[2][1],m[2][2],m[2][3],m[3][0],m[3][1],m[3][2],m[3][3])); + DX8_RECORD_MATRIX_CHANGE(); + DX8CALL(SetTransform(transform,(D3DMATRIX*)&m)); + } } WWINLINE void DX8Wrapper::_Set_DX8_Transform(D3DTRANSFORMSTATETYPE transform,const Matrix3D& m) { - SNAPSHOT_SAY(("DX8 - SetTransform\n")); - DX8_RECORD_MATRIX_CHANGE(); - DX8CALL(SetTransform(transform,(D3DMATRIX*)&m)); + WWASSERT(transform<=D3DTS_WORLD); + Matrix4x4 mtx(m); +#if 0 // (gth) this optimization is breaking generals because they set the transform behind our backs. + if (mtx!=DX8Transforms[transform]) +#endif + { + DX8Transforms[transform]=mtx; + SNAPSHOT_SAY(("DX8 - SetTransform %d [%f,%f,%f,%f][%f,%f,%f,%f][%f,%f,%f,%f]\n",transform,m[0][0],m[0][1],m[0][2],m[0][3],m[1][0],m[1][1],m[1][2],m[1][3],m[2][0],m[2][1],m[2][2],m[2][3])); + DX8_RECORD_MATRIX_CHANGE(); + DX8CALL(SetTransform(transform,(D3DMATRIX*)&m)); + } } WWINLINE void DX8Wrapper::_Get_DX8_Transform(D3DTRANSFORMSTATETYPE transform, Matrix4x4& m) @@ -610,6 +767,13 @@ WWINLINE void DX8Wrapper::Set_Fog(bool enable, const Vector3 &color, float start Set_DX8_Render_State(D3DRS_FOGEND, *(DWORD *)(&end)); } + +WWINLINE void DX8Wrapper::Set_Ambient(const Vector3& color) +{ + Ambient_Color=color; + Set_DX8_Render_State(D3DRS_AMBIENT, DX8Wrapper::Convert_Color(color,0.0f)); +} + // ---------------------------------------------------------------------------- // // Set vertex buffer to be used in the subsequent render calls. If there was @@ -648,7 +812,15 @@ WWINLINE void DX8Wrapper::Set_DX8_Render_State(D3DRENDERSTATETYPE state, unsigne // Can't monitor state changes because setShader call to GERD may change the states! if (RenderStates[state]==value) return; - SNAPSHOT_SAY(("DX8 - SetRenderState(%d,%d)\n",state,value)); +#ifdef MESH_RENDER_SNAPSHOT_ENABLED + if (WW3D::Is_Snapshot_Activated()) { + StringClass value_name(0,true); + Get_DX8_Render_State_Value_Name(value_name,state,value); + SNAPSHOT_SAY(("DX8 - SetRenderState(state: %s, value: %s)\n", + Get_DX8_Render_State_Name(state), + value_name)); + } +#endif RenderStates[state]=value; DX8CALL(SetRenderState( state, value )); @@ -669,8 +841,16 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture_Stage_State(unsigned stage, D3DTEXTURE // Can't monitor state changes because setShader call to GERD may change the states! if (TextureStageStates[stage][(unsigned int)state]==value) return; - - SNAPSHOT_SAY(("DX8 - SetTextureStageState(%d,%d,%d)\n",stage,state,value)); +#ifdef MESH_RENDER_SNAPSHOT_ENABLED + if (WW3D::Is_Snapshot_Activated()) { + StringClass value_name(0,true); + Get_DX8_Texture_Stage_State_Value_Name(value_name,state,value); + SNAPSHOT_SAY(("DX8 - SetTextureStageState(stage: %d, state: %s, value: %s)\n", + stage, + Get_DX8_Texture_Stage_State_Name(state), + value_name)); + } +#endif TextureStageStates[stage][(unsigned int)state]=value; DX8CALL(SetTextureStageState( stage, state, value )); @@ -934,7 +1114,7 @@ WWINLINE void DX8Wrapper::Get_Shader(ShaderClass& shader) WWINLINE void DX8Wrapper::Set_Texture(unsigned stage,TextureBaseClass* texture) { - WWASSERT(stageGet_Max_Textures_Per_Pass()); if (texture==render_state.Textures[stage]) return; REF_PTR_SET(render_state.Textures[stage],texture); render_state_changed|=(TEXTURE0_CHANGED<. -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /Commando/Code/ww3d2/dynamesh.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 12/03/01 4:50p $* - * * - * $Revision:: 25 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "dynamesh.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "dx8wrapper.h" -#include "sortingrenderer.h" -#include "rinfo.h" -#include "camera.h" -#include "dx8fvf.h" - - - -/* -** DynamicMeshModel implementation -*/ - -DynamicMeshModel::DynamicMeshModel(unsigned int max_polys, unsigned int max_verts) : - MeshGeometryClass(), - DynamicMeshPNum(0), - DynamicMeshVNum(0), - MatDesc(NULL), - MatInfo(NULL) -{ - MatInfo = NEW_REF(MaterialInfoClass, ()); - - MatDesc = W3DNEW MeshMatDescClass; - MatDesc->Set_Polygon_Count(max_polys); - MatDesc->Set_Vertex_Count(max_verts); - - Reset_Geometry(max_polys, max_verts); -} - -DynamicMeshModel::DynamicMeshModel(unsigned int max_polys, unsigned int max_verts, MaterialInfoClass *mat_info) : - MeshGeometryClass(), - DynamicMeshPNum(0), - DynamicMeshVNum(0), - MatDesc(NULL), - MatInfo(NULL) -{ - MatInfo = mat_info; - MatInfo->Add_Ref(); - - MatDesc = W3DNEW MeshMatDescClass; - MatDesc->Set_Polygon_Count(max_polys); - MatDesc->Set_Vertex_Count(max_verts); - - Reset_Geometry(max_polys, max_verts); -} - -DynamicMeshModel::DynamicMeshModel(const DynamicMeshModel &src) : - MeshGeometryClass(src), - DynamicMeshPNum(src.DynamicMeshPNum), - DynamicMeshVNum(src.DynamicMeshVNum), - MatDesc(NULL), - MatInfo(NULL) -{ - // Copy the material info structure. - MatInfo = NEW_REF(MaterialInfoClass, (*(src.MatInfo))); - - - // [SKB: Feb 21 2002 @ 11:47pm] : - // Moved before the remapping cause I don't like referencing null. - MatDesc = W3DNEW MeshMatDescClass; - - // remap! - MaterialRemapperClass remapper(src.MatInfo, MatInfo); - remapper.Remap_Mesh(src.MatDesc, MatDesc); -} - -DynamicMeshModel::~DynamicMeshModel(void) -{ - if (MatDesc) { - delete MatDesc; - MatDesc = NULL; - } - REF_PTR_RELEASE(MatInfo); -} - -void DynamicMeshModel::Compute_Plane_Equations(void) -{ - // Make sure the arrays are allocated before we do this - get_vert_normals(); - Vector4 * planes = get_planes(true); - - // Set the poly and vertex counts to the dynamic counts, call the base class function, then - // set them back. - int old_poly_count = PolyCount; - int old_vert_count = VertexCount; - PolyCount = DynamicMeshPNum; - VertexCount = DynamicMeshVNum; - - MeshGeometryClass::Compute_Plane_Equations(planes); - - PolyCount = old_poly_count; - VertexCount = old_vert_count; -} - -void DynamicMeshModel::Compute_Vertex_Normals(void) -{ - // Make sure the arrays are allocated before we do this - Vector3 * vnorms = get_vert_normals(); - get_planes(true); - - // Set the poly and vertex counts to the dynamic counts, call the base class function, then - // set them back. - int old_poly_count = PolyCount; - int old_vert_count = VertexCount; - PolyCount = DynamicMeshPNum; - VertexCount = DynamicMeshVNum; - - MeshGeometryClass::Compute_Vertex_Normals(vnorms); - - PolyCount = old_poly_count; - VertexCount = old_vert_count; -} - -void DynamicMeshModel::Compute_Bounds(Vector3 * verts) -{ - // Set the poly and vertex counts to the dynamic counts, call the base class function, then - // set them back. - int old_poly_count = PolyCount; - int old_vert_count = VertexCount; - PolyCount = DynamicMeshPNum; - VertexCount = DynamicMeshVNum; - - MeshGeometryClass::Compute_Bounds(verts); - - PolyCount = old_poly_count; - VertexCount = old_vert_count; -} - -void DynamicMeshModel::Reset(void) -{ - Set_Counts(0, 0); - int polycount = Get_Polygon_Count(); - int vertcount = Get_Vertex_Count(); - Reset_Geometry(polycount, vertcount); - MatDesc->Reset(polycount, vertcount, 1); - REF_PTR_RELEASE(MatInfo); - MatInfo = NEW_REF(MaterialInfoClass, ()); -} - -void DynamicMeshModel::Render(RenderInfoClass & rinfo) -{ - // Process texture reductions: -// MatInfo->Process_Texture_Reduction(); - - unsigned buffer_type=(Get_Flag(MeshGeometryClass::SORT)&& WW3D::Is_Sorting_Enabled()) ? BUFFER_TYPE_DYNAMIC_SORTING : BUFFER_TYPE_DYNAMIC_DX8; - - /* - ** Write the vertex data to the vertex buffer. We assume the FVF contains positions, normals, - ** one texture channel, and the diffuse color channel (color0). If it does not contain all - ** these components, the code will fail. - */ - DynamicVBAccessClass dynamic_vb(buffer_type,dynamic_fvf_type,DynamicMeshVNum); - const FVFInfoClass &fvf_info = dynamic_vb.FVF_Info(); - - { // scope for lock - - DynamicVBAccessClass::WriteLockClass lock(&dynamic_vb); - unsigned char *vertices = (unsigned char*)lock.Get_Formatted_Vertex_Array(); - const Vector3 *locs = Get_Vertex_Array(); - const Vector3 *normals = Get_Vertex_Normal_Array(); - const Vector2 *uvs = MatDesc->Get_UV_Array_By_Index(0, false); - const unsigned *colors = MatDesc->Get_Color_Array(0, false); - const static Vector3 default_normal(0.0f, 0.0f, 0.0f); - const static Vector2 default_uv(0.0f, 0.0f); - const unsigned int default_color = 0xFFFFFFFF; - for (int i=0; i < DynamicMeshVNum; i++) - { - *(Vector3 *)(vertices + fvf_info.Get_Location_Offset()) = locs[i]; - *(Vector3 *)(vertices + fvf_info.Get_Normal_Offset()) = normals[i]; - if (uvs) { - *(Vector2 *)(vertices + fvf_info.Get_Tex_Offset(0)) = uvs[i]; - } else { - *(Vector2 *)(vertices + fvf_info.Get_Tex_Offset(0)) = default_uv; - } - if (colors) { - *(unsigned int *)(vertices + fvf_info.Get_Diffuse_Offset()) = colors[i]; - } else { - *(unsigned int *)(vertices + fvf_info.Get_Diffuse_Offset()) = default_color; - } - vertices += fvf_info.Get_FVF_Size(); - } - - } // end scope for lock - - /* - ** Write index data to index buffers - */ - DynamicIBAccessClass dynamic_ib(buffer_type,DynamicMeshPNum * 3); - const TriIndex *tris = Get_Polygon_Array(); - - { // scope for lock - - DynamicIBAccessClass::WriteLockClass lock(&dynamic_ib); - unsigned short * indices = lock.Get_Index_Array(); - for (int i=0; i < DynamicMeshPNum; i++) - { - indices[i*3 + 0] = (unsigned short)tris[i][0]; - indices[i*3 + 1] = (unsigned short)tris[i][1]; - indices[i*3 + 2] = (unsigned short)tris[i][2]; - } - - } // end scope for lock - - /* - ** Set vertex and index buffers - */ - DX8Wrapper::Set_Vertex_Buffer(dynamic_vb); - DX8Wrapper::Set_Index_Buffer(dynamic_ib,0); - - /* - ** Draw dynamesh, one pass at a time - */ - unsigned int pass_count = Get_Pass_Count(); - for (unsigned int pass = 0; pass < pass_count; pass++) { - - /* - ** Set current render states (texture, vertex material, shader). Scan triangles until one - ** of these changes, and then draw. - */ - - // The vertex index range used - unsigned short min_vert_idx = DynamicMeshVNum - 1; - unsigned short max_vert_idx = 0; - unsigned short start_tri_idx = 0; - unsigned short cur_tri_idx = 0; - - bool done = false; - bool texture_changed = false; - bool material_changed = false; - bool shader_changed = false; - - TextureClass **texture_array0 = NULL; - TexBufferClass * tex_buf = MatDesc->Get_Texture_Array(pass, 0, false); - if (tex_buf) { - texture_array0 = tex_buf->Get_Array(); - } else { - texture_array0 = NULL; - } - VertexMaterialClass **material_array = NULL; - MatBufferClass * mat_buf = MatDesc->Get_Material_Array(pass, false); - if (mat_buf) { - material_array = mat_buf->Get_Array(); - } else { - material_array = NULL; - } - ShaderClass *shader_array = MatDesc->Get_Shader_Array(pass, false); - - // Set the DX8 state to the first triangle's state - if (texture_array0) { - DX8Wrapper::Set_Texture(0,texture_array0[0]); - } else { - DX8Wrapper::Set_Texture(0,MatDesc->Peek_Single_Texture(pass, 0)); - } - if (material_array) { - DX8Wrapper::Set_Material(material_array[tris[0].I]); - } else { - DX8Wrapper::Set_Material(MatDesc->Peek_Single_Material(pass)); - } - if (shader_array) { - DX8Wrapper::Set_Shader(shader_array[0]); - } else { - DX8Wrapper::Set_Shader(MatDesc->Get_Single_Shader(pass)); - } - - SphereClass sphere(Vector3(0.0f,0.0f,0.0f),0.0f); - Get_Bounding_Sphere(&sphere); - - // If no texture, shader or material arrays for this pass just draw and go to next pass - if (!texture_array0 && !material_array && !shader_array) { - if (buffer_type==BUFFER_TYPE_DYNAMIC_SORTING) { - SortingRendererClass::Insert_Triangles(sphere,0, DynamicMeshPNum, 0, DynamicMeshVNum); - } - else { - DX8Wrapper::Draw_Triangles(0, DynamicMeshPNum, 0, DynamicMeshVNum); - } - continue; - } - - while (!done) { - - // Add vertex indices of tri[cur_tri_idx] to min_vert_idx, max_vert_idx - const TriIndex &tri = tris[cur_tri_idx]; - unsigned short min_idx = (short)MIN(MIN(tri.I, tri.J), tri.K); - unsigned short max_idx = (short)MAX(MAX(tri.I, tri.J), tri.K); - min_vert_idx = MIN(min_vert_idx, min_idx); - max_vert_idx = MAX(max_vert_idx, max_idx); - - // Check the next triangle to see if the current run has ended. - unsigned short next_tri_idx = cur_tri_idx + 1; - done = next_tri_idx >= DynamicMeshPNum; - if (done) { - texture_changed = false; - material_changed = false; - shader_changed = false; - } else { - texture_changed = texture_array0 && texture_array0[cur_tri_idx] != texture_array0[next_tri_idx]; - material_changed = material_array && material_array[tris[cur_tri_idx].I] != material_array[tris[next_tri_idx].I]; - shader_changed = shader_array && shader_array[cur_tri_idx] != shader_array[next_tri_idx]; - } - - // If run ends (mesh ends or state changes) draw, reset indices, set state for next run. - if (done || texture_changed || material_changed || shader_changed) { - if (buffer_type==BUFFER_TYPE_DYNAMIC_SORTING) { - SortingRendererClass::Insert_Triangles( - sphere, - (start_tri_idx * 3), - (1 + cur_tri_idx - start_tri_idx), - min_vert_idx, - 1 + max_vert_idx - min_vert_idx); - } - else { - DX8Wrapper::Draw_Triangles( - (start_tri_idx * 3), - (1 + cur_tri_idx - start_tri_idx), - min_vert_idx, - 1 + max_vert_idx - min_vert_idx); - } - start_tri_idx = next_tri_idx; - min_vert_idx = DynamicMeshVNum - 1; - max_vert_idx = 0; - if (texture_changed) DX8Wrapper::Set_Texture(0,texture_array0[next_tri_idx]); - if (material_changed) DX8Wrapper::Set_Material(material_array[tris[next_tri_idx].I]); - if (shader_changed) DX8Wrapper::Set_Shader(shader_array[next_tri_idx]); - } - - cur_tri_idx = next_tri_idx; - - } // while (!done) - - } // for (pass) - -} - -void DynamicMeshModel::Initialize_Texture_Array(int pass, int stage, TextureClass *texture) -{ - TexBufferClass * texlist = MatDesc->Get_Texture_Array(pass, 0, true); - for (int lp = 0; lp < PolyCount; lp++) { - texlist->Set_Element(lp, texture); - } -} - -void DynamicMeshModel::Initialize_Material_Array(int pass, VertexMaterialClass *vmat) -{ - MatBufferClass * vertmatlist = MatDesc->Get_Material_Array(pass, true); - for (int lp = 0; lp < VertexCount; lp++) { - vertmatlist->Set_Element(lp, vmat); - } -} - -void DynamicMeshClass::Render(RenderInfoClass & rinfo) -{ - if (Is_Not_Hidden_At_All() == false) return; - - // test for an empty mesh.. - if (PolyCount == 0 ) return; - - // If static sort lists are enabled and this mesh has a sort level, put it on the list instead - // of rendering it. - - if (WW3D::Are_Static_Sort_Lists_Enabled() && SortLevel != SORT_LEVEL_NONE) { - - WW3D::Add_To_Static_Sort_List(this, SortLevel); - - } else { - - const FrustumClass & frustum = rinfo.Camera.Get_Frustum(); - - if (CollisionMath::Overlap_Test(frustum, Get_Bounding_Box()) != CollisionMath::OUTSIDE) { - DX8Wrapper::Set_Transform(D3DTS_WORLD, Transform); - Model->Render(rinfo); - } - } -} - -bool DynamicMeshClass::End_Vertex() -{ - // check that we have room for a new vertex - WWASSERT(VertCount < Model->Get_Vertex_Count()); - - // if we are a multi-material object record the material - int pass = Get_Pass_Count(); - while (pass--) { - if (MultiVertexMaterial[pass]) { - VertexMaterialClass *mat = Peek_Material_Info()->Get_Vertex_Material(VertexMaterialIdx[pass]); - Model->Set_Material(VertCount, mat, pass); - REF_PTR_RELEASE(mat); - } - - } - - // if we are multi colored, record the color - for (int color_array_index = 0; color_array_index < MAX_COLOR_ARRAYS; color_array_index++) { - if (MultiVertexColor[color_array_index]) { -// Vector4 * color = &((Model->Get_Color_Array(color_array_index))[VertCount]); -// color->X = CurVertexColor[color_array_index].X; -// color->Y = CurVertexColor[color_array_index].Y; -// color->Z = CurVertexColor[color_array_index].Z; -// color->W = CurVertexColor[color_array_index].W; - unsigned * color = &((Model->Get_Color_Array(color_array_index))[VertCount]); - *color=DX8Wrapper::Convert_Color_Clamp(CurVertexColor[color_array_index]); - } - } - - // mark this vertex as being complete - VertCount++; - TriVertexCount++; - - // if we have 3 or more vertices, add a new poly - if (TriVertexCount >= 3) { - - // check that we have room for a new poly - WWASSERT(PolyCount < Model->Get_Polygon_Count()); - - // set vertex indices - TriIndex *poly = &(Model->Get_Non_Const_Polygon_Array())[PolyCount]; - if (TriMode == TRI_MODE_STRIPS) { - (*poly)[0] = VertCount-3; - (*poly)[1] = VertCount-2; - (*poly)[2] = VertCount-1; - - // for every other tri, reverse vertex order - if (Flip_Face()) { - (*poly)[1] = VertCount-1; - (*poly)[2] = VertCount-2; - } - } else { - (*poly)[0] = FanVertex; - (*poly)[1] = VertCount-2; - (*poly)[2] = VertCount-1; - } - - // check each pass - int pass = Get_Pass_Count(); - while (pass--) { - - // If we are multi texture - if (MultiTexture[pass]) { - TextureClass *tex = Peek_Material_Info()->Get_Texture(TextureIdx[pass]); - Model->Set_Texture(PolyCount, tex, pass); - REF_PTR_RELEASE(tex); - } - } - - // increase the count and record that we have a new material - PolyCount++; - Model->Set_Counts(PolyCount, VertCount); - } - return true; -} - -/****************************************************************** -** -** DynamicMeshClass -** -*******************************************************************/ -DynamicMeshClass::DynamicMeshClass(int max_poly, int max_vert) : - Model(NULL), - PolyCount(0), - VertCount(0), - TriVertexCount(0), - FanVertex(0), - TriMode(TRI_MODE_STRIPS), - SortLevel(SORT_LEVEL_NONE) -{ - int pass = MAX_PASSES; - while (pass--) { - MultiTexture[pass] = false; - TextureIdx[pass] = -1; - - MultiVertexMaterial[pass] = false; - VertexMaterialIdx[pass] = -1; - } - - for (int color_array_index = 0; color_array_index < MAX_COLOR_ARRAYS; color_array_index++) { - MultiVertexColor[color_array_index] = false; - CurVertexColor[color_array_index].Set(1.0f, 1.0f, 1.0f, 1.0f); - } - - Model = NEW_REF(DynamicMeshModel, (max_poly, max_vert)); -} - -DynamicMeshClass::DynamicMeshClass(int max_poly, int max_vert, MaterialInfoClass *mat_info) : - Model(NULL), - PolyCount(0), - VertCount(0), - TriVertexCount(0), - FanVertex(0), - TriMode(TRI_MODE_STRIPS), - SortLevel(SORT_LEVEL_NONE) -{ - int pass = MAX_PASSES; - while (pass--) { - MultiTexture[pass] = false; - TextureIdx[pass] = -1; - - MultiVertexMaterial[pass] = false; - VertexMaterialIdx[pass] = -1; - } - - for (int color_array_index = 0; color_array_index < MAX_COLOR_ARRAYS; color_array_index++) { - MultiVertexColor[color_array_index] = false; - CurVertexColor[color_array_index].Set(1.0f, 1.0f, 1.0f, 1.0f); - } - - Model = NEW_REF(DynamicMeshModel, (max_poly, max_vert, mat_info)); -} - -DynamicMeshClass::DynamicMeshClass(const DynamicMeshClass & src) : - RenderObjClass(src), - Model(NULL), - PolyCount(src.PolyCount), - VertCount(src.VertCount), - TriVertexCount(src.TriVertexCount), - FanVertex(src.FanVertex), - TriMode(src.TriMode), - SortLevel(src.SortLevel) -{ - int pass = MAX_PASSES; - while (pass--) { - MultiTexture[pass] = src.MultiTexture[pass]; - TextureIdx[pass] = src.TextureIdx[pass]; - - MultiVertexMaterial[pass] = src.MultiVertexMaterial[pass]; - VertexMaterialIdx[pass] = src.VertexMaterialIdx[pass]; - - MultiVertexColor[pass] = src.MultiVertexColor[pass]; - CurVertexColor[pass] = src.CurVertexColor[pass]; - } - - for (int color_array_index = 0; color_array_index < MAX_COLOR_ARRAYS; color_array_index++) { - MultiVertexColor[color_array_index] = src.MultiVertexColor[color_array_index]; - CurVertexColor[color_array_index] = src.CurVertexColor[color_array_index]; - } - - Model = NEW_REF(DynamicMeshModel, (*(src.Model))); -} - -void DynamicMeshClass::Resize(int max_polys, int max_verts) -{ - Reset(); - - REF_PTR_RELEASE(Model); - Model = NEW_REF(DynamicMeshModel, (max_polys, max_verts)); - - // reset all the texture & vertex material indices - int pass = MAX_PASSES; - while (pass--) { - TextureIdx[pass] = -1; - VertexMaterialIdx[pass] = -1; - MultiVertexMaterial[pass] = false; - } -} - -DynamicMeshClass::~DynamicMeshClass() -{ - REF_PTR_RELEASE(Model); -} - -RenderObjClass * DynamicMeshClass::Clone(void) const -{ - return NEW_REF(DynamicMeshClass, (*this)); -} - -void DynamicMeshClass::Location(float x, float y, float z) -{ - Vector3 * loc = Model->Get_Vertex_Array(); - assert(loc); - - loc[VertCount].X = x; - loc[VertCount].Y = y; - loc[VertCount].Z = z; -} - -/* -** For moving a vertex after the DynaMesh has already been created. -*/ -void DynamicMeshClass::Move_Vertex(int index, float x, float y, float z) -{ - Vector3 * loc = Model->Get_Vertex_Array(); - assert(loc); - loc[index][0] = x; - loc[index][1] = y; - loc[index][2] = z; -} - -/* -** Get a vertex value. -*/ -void DynamicMeshClass::Get_Vertex(int index, float &x, float &y, float &z) -{ - Vector3 * loc = Model->Get_Vertex_Array(); - assert(loc); - x = loc[index][0]; - y = loc[index][1]; - z = loc[index][2]; -} - - -/* -** Offset the entire mesh -*/ -void DynamicMeshClass::Translate_Vertices(const Vector3 & offset) -{ - Vector3 * loc = Model->Get_Vertex_Array(); - assert(loc); - for (int i=0; i < Get_Num_Vertices(); i++) { - loc[i].X += offset.X; - loc[i].Y += offset.Y; - loc[i].Z += offset.Z; - } - - Set_Dirty_Bounds(); - Set_Dirty_Planes(); -} - -int DynamicMeshClass::Set_Vertex_Material(int idx, int pass) -{ - assert(idx < Peek_Material_Info()->Vertex_Material_Count()); - VertexMaterialIdx[pass] = idx; - if (!MultiVertexMaterial[pass]) { - // WWASSERT( VertexMaterialIdx[pass] == 0); - VertexMaterialClass *mat = Peek_Material_Info()->Get_Vertex_Material(VertexMaterialIdx[pass]); - Model->Set_Single_Material(mat, pass); - mat->Release_Ref(); - } - return VertexMaterialIdx[pass]; -} - -int DynamicMeshClass::Set_Vertex_Material(VertexMaterialClass *material, bool dont_search, int pass) -{ - // Check if same as the last vertex material - if (Peek_Material_Info()->Vertex_Material_Count() && (VertexMaterialIdx[pass] != -1) && Peek_Material_Info()->Peek_Vertex_Material(VertexMaterialIdx[pass]) == material) { - return VertexMaterialIdx[pass]; - } - - // if there are vertex materials in the list then we may have just jumped - // to becoming a multi-vertex-material object. Take care of that here. - if ((!MultiVertexMaterial[pass]) && Peek_Material_Info()->Vertex_Material_Count() && (VertexMaterialIdx[pass] != -1) && Peek_Material_Info()->Peek_Vertex_Material(VertexMaterialIdx[pass]) != material) { - - // allocate the array of per-vertex vertex material overrides - VertexMaterialClass *mat = Peek_Material_Info()->Get_Vertex_Material(VertexMaterialIdx[pass]); - Model->Initialize_Material_Array(pass, mat); - mat->Release_Ref(); - - // flag that we need to write the per -vertex vertex material override array - MultiVertexMaterial[pass] = true; - } - - // add the material to the material info class if we cant find it in the - // list. if we are not supposed to search the list for it then just add - // it. - if (!dont_search) { - int lp = 0, found = 0; - for (; lp < Peek_Material_Info()->Vertex_Material_Count(); lp ++) { - VertexMaterialClass *mat = Peek_Material_Info()->Get_Vertex_Material(lp); - if (material == mat) { - VertexMaterialIdx[pass] = lp; - found = 1; - mat->Release_Ref(); - break; - } - mat->Release_Ref(); - } - if (!found) { - Peek_Material_Info()->Add_Vertex_Material(material); - VertexMaterialIdx[pass] = Peek_Material_Info()->Vertex_Material_Count() - 1; - } - } else { - Peek_Material_Info()->Add_Vertex_Material(material); - VertexMaterialIdx[pass] = Peek_Material_Info()->Vertex_Material_Count() - 1; - } - - if (!MultiVertexMaterial[pass]) { - Model->Set_Single_Material(Peek_Material_Info()->Peek_Vertex_Material(VertexMaterialIdx[pass]), pass); - } - return(VertexMaterialIdx[pass]); -} - -int DynamicMeshClass::Set_Texture(int idx, int pass) -{ - WWASSERT(idx < Peek_Material_Info()->Texture_Count()); - TextureIdx[pass] = idx; - if (!MultiTexture[pass]) { - TextureClass *tex = Peek_Material_Info()->Get_Texture(TextureIdx[pass]); - Model->Set_Single_Texture(tex, pass); - tex->Release_Ref(); - } - return TextureIdx[pass]; -} - -int DynamicMeshClass::Set_Texture(TextureClass *texture, bool dont_search, int pass) -{ - // Check if same as the last texture - if (Peek_Material_Info()->Texture_Count() && (TextureIdx[pass] != -1) && Peek_Material_Info()->Peek_Texture(TextureIdx[pass]) == texture) { - return TextureIdx[pass]; - } - - // if there are textures in the list then we may have just jumped - // to becoming a multi-texture object. Take care of that here. - if ((!MultiTexture[pass]) && Peek_Material_Info()->Texture_Count() && (TextureIdx[pass] != -1) && Peek_Material_Info()->Peek_Texture(TextureIdx[pass]) != texture) { - - // allocate the array of per polygon material over-rides - TextureClass *tex = Peek_Material_Info()->Get_Texture(TextureIdx[pass]); - Model->Initialize_Texture_Array(pass, 0, tex); - tex->Release_Ref(); - - // flag that we need to write the per polygon material overide array - MultiTexture[pass] = true; - } - - // add the material to the material info class if we cant find it in the - // list. if we are not supposed to search the list for it then just add - // it. - if (!dont_search) { - int lp = 0, found = 0; - for (; lp < Peek_Material_Info()->Texture_Count(); lp ++) { - TextureClass *tex = Peek_Material_Info()->Get_Texture(lp); - if (texture == tex) { - TextureIdx[pass] = lp; - found = 1; - tex->Release_Ref(); - break; - } - tex->Release_Ref(); - } - if (!found) { - Peek_Material_Info()->Add_Texture(texture); - TextureIdx[pass] = Peek_Material_Info()->Texture_Count() - 1; - } - } else { - Peek_Material_Info()->Add_Texture(texture); - TextureIdx[pass] = Peek_Material_Info()->Texture_Count() - 1; - } - - if (!MultiTexture[pass]) { - TextureClass *tex = Peek_Material_Info()->Get_Texture(TextureIdx[pass]); - Model->Set_Single_Texture(tex, pass); - tex->Release_Ref(); - } - return(TextureIdx[pass]); -} - -/* -** -*/ -// Remap locations to match a screen -void DynamicScreenMeshClass::Location( float x, float y, float z) -{ - DynamicMeshClass::Location( (x * 2) - 1, Aspect - (y * 2 * Aspect), 0); -} - -// For moving a vertex after the DynaMesh has already been created. -void DynamicScreenMeshClass::Move_Vertex(int index, float x, float y, float z) -{ - DynamicMeshClass::Move_Vertex( index, (x * 2) - 1, Aspect - (y * 2 * Aspect), 0); -} - -// Set position -void DynamicScreenMeshClass::Set_Position(const Vector3 &v) -{ - DynamicMeshClass::Set_Position(Vector3(v.X * 2, -(v.Y * 2 * Aspect), 0)); -} - -void DynamicScreenMeshClass::Reset( void ) -{ - Reset_Flags(); - Reset_Mesh_Counters(); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.h deleted file mode 100644 index cba8c937a4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/dynamesh.h +++ /dev/null @@ -1,582 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /Commando/Code/ww3d2/dynamesh.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 12/03/01 4:20p $* - * * - * $Revision:: 15 $* - * * - *-------------------------------------------------------------------------*/ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DYNAMESH_H -#define DYNAMESH_H - -#include "meshgeometry.h" -#include "meshmatdesc.h" -#include "matinfo.h" -#include "rendobj.h" -#include "polyinfo.h" -#include "dx8wrapper.h" - -class ShaderClass; -class IntersectionClass; -class IntersectionResultClass; - -/* -** DynamicMeshModel: used for low-level rendering of DynamicMeshClass. -** It is composed of the same two classes (one base, one embedded as -** MeshModelClass, so many of its features are similar (see meshmdl.h) -*/ -class DynamicMeshModel : public MeshGeometryClass -{ - W3DMPO_GLUE(DynamicMeshModel) - -public: - - DynamicMeshModel(unsigned int max_polys, unsigned int max_verts); - DynamicMeshModel(unsigned int max_polys, unsigned int max_verts, MaterialInfoClass *mat_info); - DynamicMeshModel(const DynamicMeshModel &src); - ~DynamicMeshModel(void); - - // Inherited from MeshGeometryClass - virtual void Compute_Plane_Equations(void); - virtual void Compute_Vertex_Normals(void); - virtual void Compute_Bounds(Vector3 * verts); - - // Reset mesh (with existing max polygon and max vertex counts) - void Reset(void); - - // Render mesh - void Render(RenderInfoClass & rinfo); - - // Set current polygon and vertex counts - void Set_Counts(int pnum, int vnum) { DynamicMeshPNum = pnum; DynamicMeshVNum = vnum; } - - // Access to material stuff: - unsigned * Get_Color_Array(int color_array_index) { return MatDesc->Get_Color_Array(color_array_index); } - Vector2 * Get_UV_Array(int uv_array_index) { return MatDesc->Get_UV_Array_By_Index(uv_array_index); } - - void Set_Single_Material(VertexMaterialClass * vmat, int pass=0) { MatDesc->Set_Single_Material(vmat, pass); } - void Set_Single_Texture(TextureClass * tex, int pass=0, int stage=0) { MatDesc->Set_Single_Texture(tex, pass, stage); } - void Set_Single_Shader(ShaderClass shader, int pass=0) { MatDesc->Set_Single_Shader(shader, pass); } - - void Set_Material(int vidx, VertexMaterialClass * vmat, int pass=0) { MatDesc->Set_Material(vidx, vmat, pass); } - void Set_Shader(int pidx, ShaderClass shader, int pass=0) { MatDesc->Set_Shader(pidx, shader, pass); } - void Set_Texture(int pidx, TextureClass * tex, int pass=0, int stage=0) { MatDesc->Set_Texture(pidx, tex, pass, stage); } - void Set_Pass_Count(int passes) { MatDesc->Set_Pass_Count(passes); } - int Get_Pass_Count(void) const { return MatDesc->Get_Pass_Count(); } - - // Create the array (if it doesn't exist), fill it with the supplied value. - void Initialize_Texture_Array(int pass, int stage, TextureClass *texture = NULL); - void Initialize_Material_Array(int pass, VertexMaterialClass *vmat = NULL); - - // Accessors to material info: - MaterialInfoClass *Peek_Material_Info(void) { return MatInfo; } - MaterialInfoClass *Get_Material_Info(void) { if (MatInfo) MatInfo->Add_Ref(); return MatInfo;} - void Set_Material_Info(MaterialInfoClass *mat_info) - { - if (MatInfo) - MatInfo->Release_Ref(); - WWASSERT(MatInfo != 0); - MatInfo = mat_info; - MatInfo->Add_Ref(); - } - - // New geometry accessors (non-const) - TriIndex * Get_Non_Const_Polygon_Array(void); - Vector3 * Get_Non_Const_Vertex_Normal_Array(void); - -private: - - // These are current counts, as opposed to those in the mesh geometry and - // material description which are actually maximum counts. - int DynamicMeshPNum; - int DynamicMeshVNum; - - // All non-geometry properties (uvs, colors, textures, shaders, etc) - MeshMatDescClass * MatDesc; - - // Lists of textures and vertex materials for ease of processing - MaterialInfoClass * MatInfo; - -}; - -/* -** Dynamic Meshes -*/ -class DynamicMeshClass : public RenderObjClass { - -public: - - // constructor and destructor - DynamicMeshClass( int max_poly, int max_vert); - DynamicMeshClass( int max_poly, int max_vert, MaterialInfoClass *mat_info); - DynamicMeshClass( const DynamicMeshClass & src); - virtual ~DynamicMeshClass( void); - - // Inherited from RenderObjClass: - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const { return CLASSID_DYNAMESH; } - virtual void Render(RenderInfoClass & rinfo); - - virtual MaterialInfoClass *Peek_Material_Info(void) { return Model->Peek_Material_Info(); } - virtual MaterialInfoClass *Get_Material_Info(void) { return Model->Get_Material_Info(); } - virtual void Set_Material_Info(MaterialInfoClass *mat_info) { Model->Set_Material_Info(mat_info); } - - // all render objects should be able to tell you how many polygons were - // used in the making of the render object. - virtual int Get_Num_Polys(void) const { return PolyCount; } - - // return the number of vertices used by this renderobject - virtual int Get_Num_Vertices(void) const { return VertCount; } - - // Get and set static sort level - virtual int Get_Sort_Level(void) const { return SortLevel; } - virtual void Set_Sort_Level(int level) { SortLevel = level; if(level != SORT_LEVEL_NONE) Disable_Sort();} - - // object space bounding volumes - virtual inline void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual inline void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - - // Set the vertex material for the current triangle - int Set_Vertex_Material( int idx, int pass = 0); - int Set_Vertex_Material( VertexMaterialClass *material, bool dont_search = false, int pass = 0); - - // Set the number of passes for the mesh - void Set_Pass_Count(int passes) { assert(PolyCount == 0); Model->Set_Pass_Count(passes); } - int Get_Pass_Count() { return Model->Get_Pass_Count(); } - - // Set the texture for the current triangle - int Set_Texture( int idx, int pass = 0); - int Set_Texture( TextureClass *texture, bool dont_search = false, int pass = 0); - - // Set the shader for the current triangle - int Set_Shader( const ShaderClass & shader, int pass = 0) { Model->Set_Single_Shader(shader, pass); return 0; } - - // set the shader, texture, and vertex material as found in the polygon info object - void Set_Polygon_Info(const PolygonInfoClass &polyInfo, bool dont_search_texture = false, bool dont_search_vertex_material = false, int pass = 0) - { - // there must be a shader.. - assert(polyInfo.Peek_Shader() != 0); - Set_Shader(* (polyInfo.Peek_Shader()), pass); - - assert(polyInfo.Peek_Vertex_Material() != 0); - Set_Vertex_Material(polyInfo.Peek_Vertex_Material(), dont_search_vertex_material, pass); - - if (polyInfo.Peek_Texture()) - Set_Texture(polyInfo.Peek_Texture(), dont_search_texture, pass); - } - - // Set vertex Color - inline int Set_Vertex_Color(const Vector4 & color, int color_array_index = 0); - inline int Set_Vertex_Color(const Vector3 & color, int color_array_index = 0); - - // reset the mesh flags - void Reset_Flags() { Set_Dirty(); } - - // Flush the mesh - void Reset_Native_Mesh() { Model->Reset(); } - - // reset our poly and vertex counts - void Reset_Mesh_Counters() - { - Model->Set_Counts(0, 0); - Disable_Sort(); - PolyCount = 0; - VertCount = 0; - } - - // Reset all polys and verts. Call the other reset functions directly if you do not want all - // characteristics to be reset. - virtual void Reset( void ) - { - // Note that the active poly count has changed since the last render call by setting the dirty flag - Reset_Flags(); - Reset_Native_Mesh(); - Reset_Mesh_Counters(); - - // reset all the texture & vertex material indices - int pass = MAX_PASSES; - while (pass--) { - TextureIdx[pass] = -1; - VertexMaterialIdx[pass] = -1; - MultiVertexMaterial[pass] = false; - } - } - - // Deletes mesh and recreates it with new max_polys and verts. - void Resize(int max_polys, int max_verts); - - // Triangle creation routines - void Begin_Tri_Strip( void ) { TriVertexCount = 0; TriMode = TRI_MODE_STRIPS; } - void Begin_Tri_Fan( void ) { TriVertexCount = 0; TriMode = TRI_MODE_FANS; FanVertex = VertCount; } - - // vertex creation routines - void Begin_Vertex( void) {} - - virtual void Location( float x, float y, float z); - - // version for speedier use in certain cases - void Location_Inline( float x, float y, float z ) - { - Vector3 * loc = Model->Get_Vertex_Array(); - assert(loc); - - loc[VertCount].X = x; - loc[VertCount].Y = y; - loc[VertCount].Z = z; - } - void Location_Inline(Vector3 &v) { Location_Inline(v.X,v.Y,v.Z); } - - // retrieve a reference to the vertex in the object - // WARNING: does not validate index - Vector3 & Get_Location(int index) { - return Model->Get_Vertex_Array()[index]; - } - - void Normal( float x, float y, float z) - { - Vector3 * norms = Model->Get_Non_Const_Vertex_Normal_Array(); - assert(norms); - - norms[VertCount].X = x; - norms[VertCount].Y = y; - norms[VertCount].Z = z; - } - void Normal(Vector3 &v) { Normal(v.X,v.Y,v.Z); } - - // retrieve a reference to the normal vector3 in the object - // WARNING: does not validate index - Vector3 & Get_Normal(int index) { return Model->Get_Non_Const_Vertex_Normal_Array()[index]; } - - void Color(float r, float g, float b, float a, int color_array_index = 0) - { -// Vector4 * color = Model->Get_Color_Array(color_array_index); - unsigned * color = Model->Get_Color_Array(color_array_index); - assert(color); - - color[VertCount]=DX8Wrapper::Convert_Color_Clamp(Vector4(r,g,b,a)); -// color[VertCount].X = r; -// color[VertCount].Y = g; -// color[VertCount].Z = b; -// color[VertCount].W = a; - } - void Color(const Vector4 &v, int color_array_index = 0) { Color(v.X, v.Y, v.Z, v.W, color_array_index); } - void Color(unsigned v, int color_array_index=0) - { - unsigned * color = Model->Get_Color_Array(color_array_index); - assert(color); - color[VertCount]=v; - } - - // retrieve a reference to a color entry in the object - // WARNING: does not validate index -// Vector4 & Get_Color(int index, int color_array_index = 0) { return Model->Get_Color_Array(color_array_index)[index]; } - unsigned Get_Color(int index, int color_array_index = 0) { return Model->Get_Color_Array(color_array_index)[index]; } - - void UV(float u, float v, int uv_array_index = 0) - { - Vector2 * uv = Model->Get_UV_Array(uv_array_index); - assert(uv); - - uv[VertCount].U = u; - uv[VertCount].V = v; - } - void UV( Vector2 &v, int uv_array_index = 0) { UV(v.U, v.V, uv_array_index); } - // retrieve a reference to a UV entry in the object - // WARNING: does not validate index - Vector2 & Get_UV(int index, int uv_array_index = 0 ) - { - return Model->Get_UV_Array(uv_array_index)[index]; - } - - bool End_Vertex( void); - - // vertex creation shortcut, performs a begin, projected, rotated, and end - bool Vertex(float x, float y, float z, float u, float v) - { - Begin_Vertex(); - Location(x, y, z); - UV(u, v); - return End_Vertex(); - } - - bool Vertex(Vector2 v) - { - Begin_Vertex(); - Location(v.X, v.Y, 0); - return End_Vertex(); - } - - void End_Tri_Strip( void ) - { - TriVertexCount = 0; - } - - void End_Tri_Fan( void ) - { - TriVertexCount = 0; - } - - // For moving a vertex after the DynaMesh has already been created. - virtual void Move_Vertex(int index, float x, float y, float z); - virtual void Get_Vertex(int index, float &x, float &y, float &z); - - // For moving all vertices in the mesh by a fixed amount - void Translate_Vertices(const Vector3 & offset); - - // For changing the color of a vertex after DynaMesh has been created. - virtual void Change_Vertex_Color(int index, const Vector4 &color, int color_array_index) - { - // check if switching to multivertexcolor - if (!MultiVertexColor[color_array_index]) { - Switch_To_Multi_Vertex_Color(color_array_index); - } - CurVertexColor[color_array_index].X = color.X; - CurVertexColor[color_array_index].Y = color.Y; - CurVertexColor[color_array_index].Z = color.Z; - CurVertexColor[color_array_index].W = color.W; -// Vector4 * color_list = Model->Get_Color_Array(color_array_index); - unsigned * color_list = Model->Get_Color_Array(color_array_index); - color_list[index] = DX8Wrapper::Convert_Color_Clamp(color); - } - - - /* - ** The following are a bunch of inlined functions for setting & clearing the mesh model's various flags - */ - // dirty flags - void Set_Dirty_Bounds(void) { Model->Set_Flag(MeshGeometryClass::DIRTY_BOUNDS, true); } - void Clear_Dirty_Bounds(void) { Model->Set_Flag(MeshGeometryClass::DIRTY_BOUNDS, false); } - void Set_Dirty_Planes(void) { Model->Set_Flag(MeshGeometryClass::DIRTY_PLANES, true); } - void Clear_Dirty_Planes(void) { Model->Set_Flag(MeshGeometryClass::DIRTY_PLANES, false); } - void Set_Dirty_Vertex_Normals(void) { Model->Set_Flag(MeshGeometryClass::DIRTY_VNORMALS, true); } - void Clear_Dirty_Vertex_Normals(void) { Model->Set_Flag(MeshGeometryClass::DIRTY_VNORMALS, false); } - - // control flags - void Disable_Sort(void) { Model->Set_Flag(MeshGeometryClass::SORT, false); } - void Enable_Sort(void) { Model->Set_Flag(MeshGeometryClass::SORT, true); } - bool Sort_Enabled(void) { return (Model->Get_Flag(MeshGeometryClass::SORT) != 0); } - - void Disable_Bounding_Box(void) { Model->Set_Flag(MeshGeometryClass::DISABLE_BOUNDING_BOX, true); } - void Enable_Bounding_Box(void) { Model->Set_Flag(MeshGeometryClass::DISABLE_BOUNDING_BOX, false); } - bool Test_Bounding_Box(void) { return (Model->Get_Flag(MeshGeometryClass::DISABLE_BOUNDING_BOX) == 0); } - - void Disable_Bounding_Sphere(void) { Model->Set_Flag(MeshGeometryClass::DISABLE_BOUNDING_SPHERE, true); } - void Enable_Bounding_Sphere(void) { Model->Set_Flag(MeshGeometryClass::DISABLE_BOUNDING_SPHERE, false); } - bool Test_Bounding_Sphere(void) { return (Model->Get_Flag(MeshGeometryClass::DISABLE_BOUNDING_SPHERE) == 0); } - - // this is called by the Reset function - void Set_Dirty( void) { Set_Dirty_Bounds(); Set_Dirty_Planes(); Set_Dirty_Vertex_Normals(); } - - enum { - MAX_COLOR_ARRAYS = MeshMatDescClass::MAX_COLOR_ARRAYS, - MAX_PASSES = MeshMatDescClass::MAX_PASSES - }; - - // USER BE WARNED: This hack is only here because DynamicMeshClass does not expose all of the - // features that DynamicMeshModel provides. It may be dangerous to modify the model behind the - // DynamicMeshClass's back so use at your own risk! - DynamicMeshModel * Peek_Model(void) { return Model; } - -protected: - - inline void Switch_To_Multi_Vertex_Color(int color_array_index = 0); - - // tells when the triangle needs to be back flipped - virtual bool Flip_Face( void) { return (!(TriVertexCount & 1)); } - - // Low-level mesh object - DynamicMeshModel * Model; - - int VertexMaterialIdx[MAX_PASSES]; - bool MultiVertexMaterial[MAX_PASSES]; - int TextureIdx[MAX_PASSES]; - bool MultiTexture[MAX_PASSES]; - - Vector4 CurVertexColor[MAX_COLOR_ARRAYS]; - bool MultiVertexColor[MAX_COLOR_ARRAYS]; - - // number of polygons in the mesh - int PolyCount; - - // number of vertices in the mesh - int VertCount; - - // triangle vertex number - int TriVertexCount; - - // base vertex when submitting fans - int FanVertex; - - // is user currently submitting strips or fans - enum { TRI_MODE_STRIPS = 0, TRI_MODE_FANS = 1 }; - int TriMode; - - // The static sort level - char SortLevel; -}; - -inline Vector3 * DynamicMeshModel::Get_Non_Const_Vertex_Normal_Array(void) -{ - if (Get_Flag(DIRTY_VNORMALS)) { - Compute_Vertex_Normals(); - } - return get_vert_normals(); -} - -inline TriIndex * DynamicMeshModel::Get_Non_Const_Polygon_Array(void) -{ - return get_polys(); -} - -inline void DynamicMeshClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - if (!Bounding_Volumes_Valid()) { - Model->Compute_Bounds(NULL); - } - Model->Get_Bounding_Sphere(&sphere); -} - -inline void DynamicMeshClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - if (!Bounding_Volumes_Valid()) { - Model->Compute_Bounds(NULL); - } - Model->Get_Bounding_Box(&box); -} - -/* -** -*/ -void DynamicMeshClass::Switch_To_Multi_Vertex_Color(int color_array_index) -{ -/* Vector4 * color_list = Model->Get_Color_Array(color_array_index); - // set the proper color for all the existing vertices - for (int lp = 0; lp < VertCount; lp++) { - color_list[lp].X = CurVertexColor[color_array_index].X; - color_list[lp].Y = CurVertexColor[color_array_index].Y; - color_list[lp].Z = CurVertexColor[color_array_index].Z; - color_list[lp].W = CurVertexColor[color_array_index].W; - } -*/ - unsigned * color_list = Model->Get_Color_Array(color_array_index); - // set the proper color for all the existing vertices - unsigned vertex_color=DX8Wrapper::Convert_Color_Clamp(CurVertexColor[color_array_index]); - for (int lp = 0; lp < VertCount; lp++) { - color_list[lp]=vertex_color; - } - - MultiVertexColor[color_array_index] = true; -} - -/* -** Set the color of all vertices in the mesh for one color_array_index -*/ -int DynamicMeshClass::Set_Vertex_Color(const Vector4 & color, int color_array_index) -{ - // check if switching to multivertexcolor - if (!MultiVertexColor[color_array_index]) { - Switch_To_Multi_Vertex_Color(color_array_index); - } - - CurVertexColor[color_array_index] = color; - return 0; -} - -int DynamicMeshClass::Set_Vertex_Color(const Vector3 & color, int color_array_index) -{ - Set_Vertex_Color(Vector4(color.X,color.Y,color.Z,1),color_array_index); - return 0; -} - - -/* -** Dynamic Screen Meshes -** -** Same as DynamicMesh, but mapped in Screen Coordinates -** -** Screen -> 0,0 1,0 -** +---+ -** | | -** +---+ -** 0,1 1,1 -** -** -** View -> -1,1 1,1 -** +---+ -** | | -** +---+ -** -1,-1 1,-1 -** -** Note: since y is inverted, it switches from right handed to left handed -** (from counter-clockwise to clockwise), so Flip Face accounts for this -*/ -class DynamicScreenMeshClass : public DynamicMeshClass { - -public: - // constructor and destructor - DynamicScreenMeshClass( int max_poly, int max_vert, float aspect = 1.0f ) : DynamicMeshClass( max_poly, max_vert), Aspect( aspect ) {} - DynamicScreenMeshClass( const DynamicScreenMeshClass & src) : DynamicMeshClass(src), Aspect(src.Aspect) {} - virtual ~DynamicScreenMeshClass( void) {} - - // function to clone a dynamic screen mesh class - virtual RenderObjClass * Clone(void) const { return NEW_REF( DynamicScreenMeshClass, (*this)); } - - // class id of this render object - virtual int Class_ID(void) const { return CLASSID_DYNASCREENMESH; } - - // Remap locations to match a screen - virtual void Location( float x, float y, float z = 0.0f); - - // For moving a vertex after the DynaMesh has already been created. - virtual void Move_Vertex(int index, float x, float y, float z = 0.0f); - - // Set position - virtual void Set_Position(const Vector3 &v); - - virtual void Reset( void); - - virtual void Set_Aspect(float aspect) { Aspect=aspect; }; - -protected: - - // Aspect Ratio of the virtual screen. - // 1.0 gives a -1,-1 to 1,1 display - // 3/4 givs a -1,-3/4 to 1,3/4 display - float Aspect; - - // tells when the triangle needs to be back flipped - virtual bool Flip_Face( void) { return !DynamicMeshClass::Flip_Face(); } -}; - -#endif // DYNAMESH \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/font3d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/font3d.cpp deleted file mode 100644 index 7e66b43beb..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/font3d.cpp +++ /dev/null @@ -1,429 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/font3d.cpp $* - * * - * $Org Author:: Jani_p $* - * * - * $Author:: Kenny_m $* - * * - * $Modtime:: 08/05/02 10:44a $* - * * - * $Revision:: 17 $* - * * - * 08/05/02 KM Texture class redesign - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "font3d.h" -#include "assetmgr.h" -#include "texture.h" -#include -#include -#include "surfaceclass.h" -#include "texture.h" -#include "vector2i.h" - -static SurfaceClass *_surface; - -/*********************************************************************************************** - * * - * Font3DDataClass::Font3DDataClass -- constructor * - * * - * Constructs and load a Targa font image to create a texture matetial * - * * - ***********************************************************************************************/ -Font3DDataClass::Font3DDataClass( const char *filename ) -{ - Texture = NULL; - Load_Font_Image( filename); - Name = strdup( filename); - Name = strupr( Name); -} - - -/*********************************************************************************************** - * * - * Font3DDataClass::~Font3DDataClass -- destructor * - * * - ***********************************************************************************************/ -Font3DDataClass::~Font3DDataClass(void) -{ - if (Name != NULL) { - free(Name); - Name = NULL; - } - - REF_PTR_RELEASE(Texture); -} - - -/*********************************************************************************************** - * * - * FontClass::Minimize_Font_Image * - * * - * Rebuilds the give image to better pack characters and to insure a square power of two size * - * Must be called AFTER Make_Proportional() so each chars minimal bounding box is known * - * Will only create a new texture of size 128x128 or 256x256, dependent on original width * - * * - ***********************************************************************************************/ -SurfaceClass *Font3DDataClass::Minimize_Font_Image( SurfaceClass *surface ) -{ - SurfaceClass::SurfaceDescription sd; - - surface->Get_Description(sd); - - float current_width = sd.Width; - float current_height = sd.Height; - - // determine new width make the size of the new image either 128x128 or 256x256, - // dependent on the width of the original image - int new_width; - if (current_width < 256) { - new_width = 128; - } else { - new_width = 256; - } - - int new_height = new_width; - // create a new 4 bit alpha image to build into - // We dont support non-homogeneous copies just yet - SurfaceClass *new_surface = NEW_REF(SurfaceClass,(new_width, new_height,WW3D_FORMAT_A4R4G4B4)); - //SurfaceClass *new_surface0 = NEW_REF(SurfaceClass,(new_width, new_height,sd.Format)); - - // fill with transparent black - new_surface->Clear(); - - // indices for the location of each added char - int new_x = 0; - int new_y = 0; - - // for each character, copy minimum bounding area to (new_x, new_y) in the new image - for (int char_index = 0; char_index < 256; char_index++) { - - // find the lop left coordinate and the height and width of the char's bounding box - // (must convert the normalized uv tables to pixels and round off) - int src_x = (int)(UOffsetTable[ char_index ] * current_width + 0.5); - int src_y = (int)(VOffsetTable[ char_index ] * current_height + 0.5); - int width = (int)(UWidthTable[ char_index ] * current_width + 0.5); - int height = (int)(VHeight * current_height + 0.5); - - // if the character has any visible pixels at all... - if (width != 0) { - - // if this charactger will not fit on the current line, goto the next line - if (new_x + width > new_width) { - new_x = 0; - new_y += height; - - // if we have run out of lines, we have a problem - // we assert because we have already modified tables for some of the chars - if (new_y + height > new_height) { - new_y -= height; - WWDEBUG_SAY(( "Font doesn't fit texture 2 on char %c\n", char_index )); - } - } - - // blit from original image to new image - - new_surface->Copy(new_x, new_y,src_x,src_y,width,height,surface); - - } - - // update the U and V tables to show new character location - UOffsetTable[ char_index ] = (float)(new_x) / (float)new_width; - VOffsetTable[ char_index ] = (float)(new_y) / (float)new_width; - - // update width in terms of new normal image width - UWidthTable[ char_index ] *= (float)current_width / (float)new_width; - - new_x += width; - } - - // update height in terms of new normal image height - VHeight *= (float)current_height / (float)new_height; - - // be sure the new image is SMALLER than the old image -// assert ( (new_width * new_height) <= (current_width * current_height)); - - // release the old surface and return the new one - REF_PTR_RELEASE(surface); - - _surface = new_surface; - - return _surface; -} - -/*********************************************************************************************** - * * - * FontClass::Make_Proportional * - * * - * Modifys U and Width tables to convert a monospace font into a proportional font. Hieght * - * remains the same. Performed by getting the current mono-space bounding box and bringing * - * in the left and right edges to the first non-transparent ( != 0 ) pixel. Then the U and * - * width tables are updated with the new values. The image itself is not modified unless... * - * * - * we complete by calling Minimize_Font_Image to shink the image & insure a power of 2 square * - * * - ***********************************************************************************************/ -SurfaceClass *Font3DDataClass::Make_Proportional( SurfaceClass *surface ) -{ - SurfaceClass::SurfaceDescription sd; - surface->Get_Description(sd); - float width = sd.Width; - float height = sd.Height; - - // for each character in the font... - for (int char_index = 0; char_index < 256; char_index++) { - - // find the current bounding box - // (must convert the normalized uv tables to pixels and round off) - int x0 = (int)(UOffsetTable[ char_index ] * width + 0.5); - int y0 = (int)(VOffsetTable[ char_index ] * height + 0.5); - int x1 = x0 + (int)(UWidthTable[ char_index ] * width + 0.5); - int y1 = y0 + (int)(VHeight * height + 0.5); - - // find minimum bounding box by finding the minimum and maximum non-0 x pixel location - Vector2i minb(x0,y0); - Vector2i maxb(x1,y1); - - surface->FindBB(&minb,&maxb); - - // set the new edges - x0 = minb.I; - x1 = maxb.I+1; - - // if we didn't find ANY non-transparent pixels, the char has no width. - if (x1 < x0) { - x1 = x0; - } - - // turn off all character after del - if (char_index > 0x80) { - x1 = x0; - } - - // update the U and width tables - UOffsetTable[ char_index ] = (float)x0 / width; - UWidthTable[ char_index ] = (float)( x1 - x0 ) / width; - CharWidthTable[ char_index ] = x1 - x0; - } - - // now shink the image given the minimum char sizes -// surface = Minimize_Font_Image( surface ); - Minimize_Font_Image( _surface ); - return NULL; -} - -/*********************************************************************************************** - * * - * Font3DDataClass::Load_Font_Image( SR_SCENE *scene, char *filename ) * - * * - * Loads a targa font image file, arranged as 16x16 characters, and builds u v tables to * - * find each character. Converts the mono-space font into a proportional font, then uploads * - * the image to the scene as a textur material. * - * * - ***********************************************************************************************/ -bool Font3DDataClass::Load_Font_Image( const char *filename ) -{ - // get the font surface - SurfaceClass *surface = NEW_REF(SurfaceClass,(filename)); - WWASSERT(surface); - - SurfaceClass::SurfaceDescription sd; - surface->Get_Description(sd); - - // If input is a font strike (strip) process it as such - if ( sd.Width > 8 * sd.Height ) { - - // the height of the strike is the height of the characters - VHeight = 1; - CharHeight = sd.Height; - - int column = 0; - int width = sd.Width; - - - // for each char, find the uv start location and set the - // mono-spaced width and height in normalized screen units - for (int char_index = 0; char_index < 256; char_index++) { - - if ( char_index >= 0x7F ) { - - UOffsetTable[ char_index ] = 0; - VOffsetTable[ char_index ] = 0; - UWidthTable[ char_index ] = 0; - CharWidthTable[ char_index ] = 0; - - } else { - - // find the first non-transparent column... - while (( column < width ) && ( surface->Is_Transparent_Column(column) )) column++; - int start = column; - - // find the first transparent column... - while (( column < width ) && ( !surface->Is_Transparent_Column(column) )) column++; - int end = column; - - if ( end <= start ) { - WWDEBUG_SAY(( "Error Char %d start %d end %d width %d\n", char_index, start, end, width )); - } - -// WWASSERT( end > start ); - - UOffsetTable[ char_index ] = (float)start / width; - VOffsetTable[ char_index ] = 0; - UWidthTable[ char_index ] = (float)(end - start) / width; - CharWidthTable[ char_index ] = end - start; - } - - } - - // convert the just created mon-spaced font to proportional (optional) -// surface = Make_Proportional( surface ); - _surface = surface; - surface = NULL; - Minimize_Font_Image( _surface ); - - } else { - - // Determine the width and height of each mono spaced character in pixels - // (assumes 16x16 array of chars) - float font_width = sd.Width; - float font_height = sd.Height; - float mono_pixel_width = (font_width / 16); - float mono_pixel_height = (font_height / 16); - - // for each char, find the uv start location and set the - // mono-spaced width and height in normalized screen units - for (int char_index = 0; char_index < 256; char_index++) { - UOffsetTable[ char_index ] = (float)((char_index % 16) * mono_pixel_width) / font_width; - VOffsetTable[ char_index ] = (float)((char_index / 16) * mono_pixel_height) / font_height; - UWidthTable[ char_index ] = mono_pixel_width / font_width; - CharWidthTable[ char_index ] = mono_pixel_width; - } - VHeight = mono_pixel_height / font_height; - CharHeight = mono_pixel_height; - - // convert the just created mon-spaced font to proportional (optional) - - _surface = surface; - surface = NULL; - Make_Proportional( _surface ); - } - - // create the texture - if ( _surface ) { - Texture = NEW_REF(TextureClass,(_surface,MIP_LEVELS_1)); - REF_PTR_RELEASE(_surface); - } - - // return SUCCESS! - return true; -} - - -/*********************************************************************************************** - * * - * Font3DInstanceClass::Font3DInstanceClass -- constructor * - * * - * Constructs and load a Targa font image to create a texture matetial * - * * - ***********************************************************************************************/ -Font3DInstanceClass::Font3DInstanceClass( const char *filename ) -{ - FontData = WW3DAssetManager::Get_Instance()->Get_Font3DData( filename); - MonoSpacing = 0.0f; - Scale = 1.0f; - SpaceSpacing = (int)(FontData->Char_Width('H') / 2.0f); - InterCharSpacing = 1; - Build_Cached_Tables(); -} - -/*********************************************************************************************** - * * - * Font3DInstanceClass::~Font3DInstanceClass -- destructor * - * * - ***********************************************************************************************/ -Font3DInstanceClass::~Font3DInstanceClass(void) -{ - REF_PTR_RELEASE(FontData); -} - -/* -** -*/ -void Font3DInstanceClass::Set_Mono_Spaced( void ) -{ - MonoSpacing = FontData->Char_Width('W') + 1; - Build_Cached_Tables(); -} - -void Font3DInstanceClass::Build_Cached_Tables() -{ - // Rebuild the cached tables - for (int a=0;a<256;++a) { - float width = (float)FontData->Char_Width(a); - if ( a == ' ' ) { - width = SpaceSpacing; - } - - ScaledWidthTable[a] = Scale * width; - if (MonoSpacing != 0.0f) { - ScaledSpacingTable[a] = Scale * MonoSpacing; - } else { - ScaledSpacingTable[a] = Scale * (width + InterCharSpacing); - } - } - ScaledHeight = floorf(Scale * (float)FontData->Char_Height('A')); -} - -/*********************************************************************************************** - * * - * Font3DInstanceClass::String_Screen_Width( char *test_str ) * - * * - * Finds the normalized screenspace width of a character string - useful for checking before * - * printing to avoid overflowing the screen. * * - ***********************************************************************************************/ -float Font3DInstanceClass::String_Width( const WCHAR *test_str ) -{ - float width = 0.0; - for (; *test_str; test_str++) { - width += Char_Spacing(*test_str); - } - - return width; -} - -float Font3DInstanceClass::String_Width( const char *test_str ) -{ - float width = 0.0; - for (; *test_str; test_str++) { - width += Char_Spacing(*test_str); - } - - return width; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/font3d.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/font3d.h deleted file mode 100644 index d1f584dec8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/font3d.h +++ /dev/null @@ -1,223 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/font3d.h $* - * * - * $Author:: Byon_g $* - * * - * $Modtime:: 4/05/01 2:19p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------*/ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef FONT3D_H -#define FONT3D_H - -#include "always.h" -#include "refcount.h" -#include "vector4.h" -#include "widestring.h" -#include "rect.h" - -class TextureClass; -class SurfaceClass; - -/****************************************************************** -** -** Font3DDataClass -** -** This class provides an interface to a font texture. Once -** created and loaded with a font, the object can return texture -** u v coordinate for any character in the font, as well as the -** character width for proportional fonts. Fonts are loaded as -** 16-bit Targa files, then converted to proportional fonts by -** finding the minimum bounding box for each chacter. The font -** texture is then minimized to a 256x256 or 128x128 texture -** material by re-stacking chars by thier minimum bounding box. -** -** During use, this class is really no more than a data table accessor -** Only during creation is any real code run. -** -** Since the space char nevers needs to be drawn, do not use -** the conventional method of acessing and drawing chars (which will -** still work). Instead, call Get_Space_Width to determine the user- -** settable width, and skip the drawing. -** -*******************************************************************/ -class Font3DDataClass : public RefCountClass { - -public: - - /* - ** Constructor, Constructor which loads a targa file, - ** and Destructor - */ - Font3DDataClass( const char *filename ); - ~Font3DDataClass(); - - // the name of the font data (used for name matching and the like.) - char *Name; - - /* - ** access character width and height in pixels (clamp char to 0.255) - */ - - unsigned char Char_Width( WCHAR ch = (WCHAR)'H' ) { return CharWidthTable[ch&0xFF]; }// & 0xFF]; } // No need to "& 0xff" with chars!!! - unsigned char Char_Height( WCHAR /*ch = 'H'*/ ) { return CharHeight; } - - // u and v are in normalized texture space - inline float Char_U_Offset( WCHAR ch = (WCHAR)'H') { return UOffsetTable[ch&0xFF]; }// & 0xFF]; } - inline float Char_V_Offset( WCHAR ch = (WCHAR)'H') { return VOffsetTable[ch&0xFF]; }// & 0xFF]; } - inline float Char_U_Width( WCHAR ch = (WCHAR)'H' ) { return UWidthTable[ch&0xFF]; }// & 0xFF]; } - inline float Char_V_Height( WCHAR /*ch = 'H'*/) { return VHeight; } - - // get all four UV values as one vector4 - Vector4 Char_UV_Corners( WCHAR ch = (WCHAR)'H' ) - { -// ch &= 0xFF; - return Vector4( UOffsetTable[ch], VOffsetTable[ch], - UOffsetTable[ch] + UWidthTable[ch], - VOffsetTable[ch] + VHeight ); - } - - /* - ** access texture material - */ - TextureClass * Peek_Texture( void ) { return Texture; } - -private: - /* - ** The material (texture) which holds the font - */ - TextureClass * Texture; - - /* - ** Normalized texture page offsets for each character - */ - float UOffsetTable[ 256 ]; - float VOffsetTable[ 256 ]; - float UWidthTable[ 256 ]; - float VHeight; - - unsigned char CharWidthTable[ 256 ]; - unsigned char CharHeight; - - /* - ** load a targa font image (.TGA) - */ - bool Load_Font_Image( const char *filename ); - - /* - ** routines to convert a mono-spaced font to a proportional - ** font and minimize texture image size as a result - */ - SurfaceClass *Make_Proportional( SurfaceClass *font_image ); - SurfaceClass *Minimize_Font_Image( SurfaceClass *font_image ); - -}; - -/****************************************************************** -** -** Font3DInstanceClass -** -*******************************************************************/ -class Font3DInstanceClass : public RefCountClass { - -public: - /* - ** Constructor which creates/gets a Font3DDataClass object, - ** and Destructor - */ - Font3DInstanceClass( const char *filename ); - ~Font3DInstanceClass(); - - /* - ** access texture material - */ - TextureClass *Peek_Texture( void ) { return FontData->Peek_Texture(); } - - /* - ** The non-scaled monospace char width in pixels ( set to 0 for proportional spaced font ) - */ - void Set_Mono_Spaced( void ); - void Set_Proportional( void ) { MonoSpacing = 0; Build_Cached_Tables(); } - - - /* - ** Set the font scale (default to 1) - ** This amount will be automatically applied to all Char_Screen_Width calls - */ - void Set_Scale( float scale ) { Scale = scale; Build_Cached_Tables(); } - // float Get_Scale() const { return Scale; } - - /* - ** The scaled character pixel width, height, and spacing data (clamp char to 0.255) - */ - float Char_Width( WCHAR ch ) const { return ScaledWidthTable[ch&0xFF]; } - float Char_Spacing( WCHAR ch ) const { return ScaledSpacingTable[ch&0xFF]; } - float Char_Height( void ) const { return ScaledHeight; } - - - /* - ** The scaled pixel width of a string; useful before printing to avoid screen overflows. - */ - float String_Width( const WCHAR *test_str ); - float String_Width( const char *test_str ); - - /* - ** Char UVs - */ - // u and v are in normalized texture space - // inline float Char_U_Offset( WCHAR ch = (WCHAR)'H') { return FontData->Char_U_Offset( ch & 0xFF ); } - // inline float Char_V_Offset( WCHAR ch = (WCHAR)'H') { return FontData->Char_V_Offset( ch & 0xFF ); } - // inline float Char_U_Width( WCHAR ch = (WCHAR)'H' ) { return FontData->Char_U_Width( ch & 0xFF ); } - // inline float Char_V_Height( WCHAR ch = (WCHAR)'H') { return FontData->Char_V_Height( ch & 0xFF ); } - // Vector4 Char_UV_Corners( WCHAR ch = (WCHAR)'H' ) { return FontData->Char_UV_Corners( ch & 0xFF ); } - RectClass Char_UV( WCHAR ch ) { return RectClass( FontData->Char_U_Offset(ch), - FontData->Char_V_Offset(ch), - FontData->Char_U_Offset(ch) + FontData->Char_U_Width(ch), - FontData->Char_V_Offset(ch) + FontData->Char_V_Height(ch) ); } -private: - - Font3DDataClass * FontData; // The font data - float Scale; // The current scale factor - float SpaceSpacing; // non-scaled width of space in pixels ( defaults to 1/2 'H' width ) - float InterCharSpacing; // non-scaled width between chars in pixels - float MonoSpacing; // non-scaled monospace char width in pixels (0 for proportional) - - float ScaledWidthTable[256]; // scaled cache of the chars pixel widths - float ScaledSpacingTable[256]; // scaled cache of the chars pixel spacing - float ScaledHeight; // scaled cache of the chars pixel height - - void Build_Cached_Tables(); -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/formconv.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/formconv.cpp deleted file mode 100644 index 9c20e6b3e2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/formconv.cpp +++ /dev/null @@ -1,252 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/formconv.cpp $* - * * - * Original Author:: Nathaniel Hoffman * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 3 $* - * * - * 06/27/02 KM Z Format support * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#include "formconv.h" - -D3DFORMAT WW3DFormatToD3DFormatConversionArray[WW3D_FORMAT_COUNT] = { - D3DFMT_UNKNOWN, - D3DFMT_R8G8B8, - D3DFMT_A8R8G8B8, - D3DFMT_X8R8G8B8, - D3DFMT_R5G6B5, - D3DFMT_X1R5G5B5, - D3DFMT_A1R5G5B5, - D3DFMT_A4R4G4B4, - D3DFMT_R3G3B2, - D3DFMT_A8, - D3DFMT_A8R3G3B2, - D3DFMT_X4R4G4B4, - D3DFMT_A8P8, - D3DFMT_P8, - D3DFMT_L8, - D3DFMT_A8L8, - D3DFMT_A4L4, - D3DFMT_V8U8, // Bumpmap - D3DFMT_L6V5U5, // Bumpmap - D3DFMT_X8L8V8U8, // Bumpmap - D3DFMT_DXT1, - D3DFMT_DXT2, - D3DFMT_DXT3, - D3DFMT_DXT4, - D3DFMT_DXT5 -}; - -// adding depth stencil format conversion -D3DFORMAT WW3DZFormatToD3DFormatConversionArray[WW3D_ZFORMAT_COUNT] = -{ -#ifndef _XBOX - D3DFMT_UNKNOWN, - D3DFMT_D16_LOCKABLE, // 16-bit z-buffer bit depth. This is an application-lockable surface format. - D3DFMT_D32, // 32-bit z-buffer bit depth. - 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. - D3DFMT_D24S8, // 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel. - D3DFMT_D16, // 16-bit z-buffer bit depth. - D3DFMT_D24X8, // 32-bit z-buffer bit depth using 24 bits for the depth channel. - D3DFMT_D24X4S4, // 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel. -#else - D3DFMT_UNKNOWN, - D3DFMT_D16_LOCKABLE, // 16-bit z-buffer bit depth. This is an application-lockable surface format. - D3DFMT_D32, // 32-bit z-buffer bit depth. - 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. - D3DFMT_D24S8, // 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel. - D3DFMT_D16, // 16-bit z-buffer bit depth. - D3DFMT_D24X8, // 32-bit z-buffer bit depth using 24 bits for the depth channel. - D3DFMT_D24X4S4, // 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel. - - D3DFMT_LIN_D24S8, - D3DFMT_LIN_F24S8, - D3DFMT_LIN_D16, - D3DFMT_LIN_F16 -#endif -}; - - -/* -#define HIGHEST_SUPPORTED_D3DFORMAT D3DFMT_X8L8V8U8 //A4L4 -WW3DFormat D3DFormatToWW3DFormatConversionArray[HIGHEST_SUPPORTED_D3DFORMAT + 1] = { - WW3D_FORMAT_UNKNOWN, // 0 - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_R8G8B8, // 20 - WW3D_FORMAT_A8R8G8B8, - WW3D_FORMAT_X8R8G8B8, - WW3D_FORMAT_R5G6B5, - WW3D_FORMAT_X1R5G5B5, - WW3D_FORMAT_A1R5G5B5, - WW3D_FORMAT_A4R4G4B4, - WW3D_FORMAT_R3G3B2, - WW3D_FORMAT_A8, - WW3D_FORMAT_A8R3G3B2, - WW3D_FORMAT_X4R4G4B4, // 30 - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_A8P8, // 40 - WW3D_FORMAT_P8, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, WW3D_FORMAT_UNKNOWN, - WW3D_FORMAT_L8, // 50 - WW3D_FORMAT_A8L8, - WW3D_FORMAT_A4L4 -}; -*/ - -#ifndef _XBOX -#define HIGHEST_SUPPORTED_D3DFORMAT D3DFMT_X8L8V8U8 -#define HIGHEST_SUPPORTED_D3DZFORMAT D3DFMT_D16 -#else -#define HIGHEST_SUPPORTED_D3DFORMAT D3DFMT_LIN_R8G8B8A8 -#define HIGHEST_SUPPORTED_D3DZFORMAT D3DFMT_LIN_F16 -#endif -WW3DFormat D3DFormatToWW3DFormatConversionArray[HIGHEST_SUPPORTED_D3DFORMAT + 1]; -WW3DZFormat D3DFormatToWW3DZFormatConversionArray[HIGHEST_SUPPORTED_D3DZFORMAT + 1]; - -D3DFORMAT WW3DFormat_To_D3DFormat(WW3DFormat ww3d_format) { - if (ww3d_format >= WW3D_FORMAT_COUNT) { - return D3DFMT_UNKNOWN; - } else { - return WW3DFormatToD3DFormatConversionArray[(unsigned int)ww3d_format]; - } -} - -WW3DFormat D3DFormat_To_WW3DFormat(D3DFORMAT d3d_format) -{ - switch (d3d_format) { - // The DXT-codes are created with FOURCC macro and thus can't be placed in the conversion table - case D3DFMT_DXT1: return WW3D_FORMAT_DXT1; - case D3DFMT_DXT2: return WW3D_FORMAT_DXT2; - case D3DFMT_DXT3: return WW3D_FORMAT_DXT3; - case D3DFMT_DXT4: return WW3D_FORMAT_DXT4; - case D3DFMT_DXT5: return WW3D_FORMAT_DXT5; - default: - if (d3d_format > HIGHEST_SUPPORTED_D3DFORMAT) { - return WW3D_FORMAT_UNKNOWN; - } else { - return D3DFormatToWW3DFormatConversionArray[(unsigned int)d3d_format]; - } - break; - } -} - -//********************************************************************************************** -//! Depth Stencil W3D to D3D format conversion -/*! KJM -*/ -D3DFORMAT WW3DZFormat_To_D3DFormat(WW3DZFormat ww3d_zformat) -{ - if (ww3d_zformat >= WW3D_ZFORMAT_COUNT) - { - return D3DFMT_UNKNOWN; - } - else - { - return WW3DZFormatToD3DFormatConversionArray[(unsigned int)ww3d_zformat]; - } -} - -//********************************************************************************************** -//! D3D to Depth Stencil W3D format conversion -/*! KJM -*/ -WW3DZFormat D3DFormat_To_WW3DZFormat(D3DFORMAT d3d_format) -{ - if (d3d_format>HIGHEST_SUPPORTED_D3DZFORMAT) - { - return WW3D_ZFORMAT_UNKNOWN; - } - else - { - return D3DFormatToWW3DZFormatConversionArray[(unsigned int)d3d_format]; - } -} - -//********************************************************************************************** -//! Init format conversion tables -/*! - * 06/27/02 KM Z Format support * -*/ -void Init_D3D_To_WW3_Conversion() -{ - int i=0; - for (;i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/formconv.h $* - * * - * Original Author:: Nathaniel Hoffman * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 1:27p $* - * * - * $Revision:: 3 $* - * * - * 06/27/02 KM Z Format support * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef FORMCONV_H -#define FORMCONV_H - -#include "ww3dformat.h" -#include - -/* -** This file is used for conversions between D3DFORMAT and WW3DFormat. -*/ - -D3DFORMAT WW3DFormat_To_D3DFormat(WW3DFormat ww3d_format); -WW3DFormat D3DFormat_To_WW3DFormat(D3DFORMAT d3d_format); - -D3DFORMAT WW3DZFormat_To_D3DFormat(WW3DZFormat ww3d_zformat); -WW3DZFormat D3DFormat_To_WW3DZFormat(D3DFORMAT d3d_format); - -void Init_D3D_To_WW3_Conversion(); - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/framgrab.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/framgrab.h deleted file mode 100644 index 67a2a44739..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/framgrab.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/framgrab.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef FRAMEGRAB_H -#define FRAMEGRAB_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#if defined (_MSC_VER) -#pragma warning (push, 3) // (gth) system headers complain at warning level 4... -#endif - -#ifndef _WINDOWS_ -#include "windows.h" -#endif - -#ifndef _INC_WINDOWSX -#include "windowsx.h" -#endif - -#ifndef _INC_VFW -#include "vfw.h" -#endif - -#if defined (_MSC_VER) -#pragma warning (pop) -#endif - -// FramGrab.h: interface for the FrameGrabClass class. -// -////////////////////////////////////////////////////////////////////// - -class FrameGrabClass -{ -public: - enum MODE { - RAW, - AVI - }; - - // depending on which mode you select, it will produce either frames or an AVI. - FrameGrabClass(const char *filename, MODE mode, int width, int height, int bitdepth, float framerate ); - - virtual ~FrameGrabClass(); - - void ConvertGrab(void *BitmapPointer); - void Grab(void *BitmapPointer); - - long * GetBuffer() { return Bitmap; } - float GetFrameRate() { return FrameRate; } - -protected: - const char *Filename; - float FrameRate; - - MODE Mode; - long Counter; // used for incrementing filename cunter, etc. - - void GrabAVI(void *BitmapPointer); - void GrabRawFrame(void *BitmapPointer); - - // avi settings - PAVIFILE AVIFile; - long *Bitmap; - PAVISTREAM Stream; - AVISTREAMINFO AVIStreamInfo; - BITMAPINFOHEADER BitmapInfoHeader; - - // general purpose cleanup routine - void CleanupAVI(); - - // convert the SR image into AVI byte ordering - void ConvertFrame(void *BitmapPointer); - -}; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanim.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanim.cpp deleted file mode 100644 index cd802914bd..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanim.cpp +++ /dev/null @@ -1,448 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/hanim.cpp 2 1/23/01 2:12p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/hanim.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 1/22/01 6:23p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "hanim.h" -#include "assetmgr.h" -#include "htree.h" -#include "motchan.h" -#include "chunkio.h" -#include "w3d_file.h" -#include "wwdebug.h" -#include -#include - - - -/* -** -** HAnimComboClass -** -** -*/ - - -NamedPivotMapClass::~NamedPivotMapClass(void) -{ -} - -NamedPivotMapClass::WeightInfoStruct & NamedPivotMapClass::WeightInfoStruct::operator = (WeightInfoStruct const &that) -{ - if(Name) delete [] Name; - assert(that.Name != 0); - Name = nstrdup(that.Name); - Weight = that.Weight; - return *this; -} - -// add a name & weight to the arrays -void NamedPivotMapClass::Add(const char *Name, float Weight) -{ - WeightInfoStruct info; - info.Name = (char *) Name; - info.Weight = Weight; - WeightInfo.Add(info); - info.Name = 0; -} - -// configure the base pivot map using the specified tree -void NamedPivotMapClass::Update_Pivot_Map(const HTreeClass *Tree) -{ - // first, resize the base pivot map to fit the tree - int numPivots = Tree->Num_Pivots(); - - Resize(numPivots); - ActiveCount = numPivots; - - // first, reset all weights to 1 (the default) - while(numPivots--) { - (*this)[numPivots] = 1.0f; - } - - // for each named pivot, find the correct index and set the weight if the indicated bone is present - // note: there is no check for redundant names - int count = WeightInfo.Count(); - while(count--) { - int actualPivot = Tree->Get_Bone_Index(WeightInfo[count].Name); - if(actualPivot != -1) { - (*this)[actualPivot] = WeightInfo[count].Weight; - } - } -} - -/* -** -*/ -DEFINE_AUTO_POOL(HAnimComboDataClass,256); - -HAnimComboDataClass::HAnimComboDataClass(bool shared) -: Shared(shared), HAnim(0), PivotMap(0), Frame(0), Weight(1) -{} - - -HAnimComboDataClass::HAnimComboDataClass(const HAnimComboDataClass &src) -: PivotMap(src.Get_Pivot_Map()), - HAnim(src.Get_HAnim()) -{ - Shared = src.Is_Shared(); - Frame = src.Get_Frame(); - Weight = src.Get_Weight(); -} - -void HAnimComboDataClass::Copy(const HAnimComboDataClass *src) -{ - if(src) { - HAnim = src->Get_HAnim(); - PivotMap = src->Get_Pivot_Map(); - Frame = src->Get_Frame(); - Weight = src->Get_Weight(); - } else { - HAnim = 0; - PivotMap = 0; - Frame = 0; - Weight = 1; - } -} - -HAnimComboDataClass::~HAnimComboDataClass(void) -{ - if(HAnim) - HAnim->Release_Ref(); - if(PivotMap) - PivotMap->Release_Ref(); -} - -void HAnimComboDataClass::Clear(void) -{ - if ( HAnim != NULL ) { - HAnim->Release_Ref(); - HAnim = NULL; - } - - // not sure if the pivot map should be deleted or just have everything set to one. - // removing it effectively sets it to one, so that's what I'm doing for now. - if(PivotMap) { - PivotMap->Release_Ref(); - PivotMap = NULL; - } - - Frame = 0.0f; - Weight = 1.0; - PivotMap = NULL; -} - -void HAnimComboDataClass::Set_HAnim(HAnimClass *motion) -{ - if ( motion != NULL ) { - motion->Add_Ref(); - } - if ( HAnim != NULL ) { - HAnim->Release_Ref(); - } - HAnim = motion; -} - - -void HAnimComboDataClass::Set_Pivot_Map(PivotMapClass *map) -{ - if ( map != NULL ) { - map->Add_Ref(); - } - if ( PivotMap != NULL ) { - PivotMap->Release_Ref(); - } - PivotMap = map; -} - -/* -** This function will replace the current pivot map (if any) with another pivot map that is -** set to 1 for only those pivot indices that actually have data. -*/ -void HAnimComboDataClass::Build_Active_Pivot_Map(void) -{ - if ( PivotMap != NULL ) { - PivotMap->Release_Ref(); - } - if(HAnim == NULL) { - PivotMap = 0; - return; - } - - int numpivots = HAnim->Get_Num_Pivots(); - PivotMap = NEW_REF( PivotMapClass, ()); - PivotMap->Resize(numpivots); - - int count = 0; - while(count < numpivots) { - if(HAnim->Is_Node_Motion_Present(count)) { - PivotMap->Add(1); - - } else { - PivotMap->Add(0); - } - count++; - } -} - -/* -** HAnimComboClass -** -** -*/ - -HAnimComboClass::HAnimComboClass(void) -{} - -HAnimComboClass::HAnimComboClass( int num_animations ) -{ - HAnimComboData.Resize(num_animations); - - while(num_animations--) { - HAnimComboData.Add(new HAnimComboDataClass()); - } -} - - -HAnimComboClass::~HAnimComboClass(void) -{ - Reset(); -} - - -void HAnimComboClass::Clear( void ) -{ - int numAnimations = HAnimComboData.Count(); - while ( numAnimations-- ) { - HAnimComboDataClass *data = HAnimComboData[numAnimations]; - if(data && (! data->Is_Shared())) - data->Clear(); - } -} - -void HAnimComboClass::Reset( void ) -{ - int numAnimations = HAnimComboData.Count(); - while ( numAnimations-- ) { - HAnimComboDataClass *data = HAnimComboData[numAnimations]; - if(data && (! data->Is_Shared())) { - delete data; - } - } - HAnimComboData.Reset_Active(); -} - -bool HAnimComboClass::Normalize_Weights(void) -{ - // NOTE: This can only work if either no anims have pivot weight maps (in which case we will - // adjust the anim weights to ensure normalization), or else if all do (in which case we will - // adjust the pivot maps). Otherwise we do nothing and return false. - int anim_count = Get_Num_Anims(); - if (!anim_count) return true; // Trivially succeeded - - // Loop over all anims. Check if all or none have pivot maps, and also calculate the minimum - // number of pivots. - int anim_idx = 0; - bool all_pivot_maps = true; - bool none_pivot_maps = true; - int num_anim_pivots = 100000; - for (anim_idx = 0; anim_idx < anim_count; anim_idx++ ) { - num_anim_pivots = MIN(num_anim_pivots, Peek_Motion(anim_idx)->Get_Num_Pivots()); - bool has_pivot_map = Peek_Pivot_Weight_Map(anim_idx) != NULL; - all_pivot_maps &= has_pivot_map; - none_pivot_maps &= !has_pivot_map; - } - if ( num_anim_pivots == 100000 ) { - num_anim_pivots = 0; - } - - if (none_pivot_maps) { - - // Calculate total weight of all active anims, ensure it is very close to 1. - float weight_total = 0.0f; - for (anim_idx = 0; anim_idx < anim_count; anim_idx++ ) { - if (Peek_Motion(anim_idx) != NULL ) { - float weight = Get_Weight(anim_idx); - weight_total += weight; - } - } - - // weight_total should be very close to 1. If not, normalize this pivot's weights - if (weight_total != 0.0 && WWMath::Fabs( weight_total - 1.0 ) > WWMATH_EPSILON) { - float oo_total = 1.0f / weight_total; - for (anim_idx = 0; anim_idx < anim_count; anim_idx++ ) { - if (Peek_Motion(anim_idx) != NULL ) { - Set_Weight(anim_idx, Get_Weight(anim_idx) * oo_total); - } - } - } - - } else { - - if (all_pivot_maps) { - - // For each pivot, calculate total weight of all active anims, ensure close to 1. - for (int piv_idx = 1; piv_idx < num_anim_pivots; piv_idx++) { - - float weight_total = 0.0f; - for (anim_idx = 0; anim_idx < anim_count; anim_idx++ ) { - if (Peek_Motion(anim_idx) != NULL ) { - float weight = Get_Weight(anim_idx) * (*Peek_Pivot_Weight_Map(anim_idx))[piv_idx]; - weight_total += weight; - } - } - - // weight_total should be very close to 1. If not, normalize this pivot's weights - if (weight_total != 0.0 && WWMath::Fabs( weight_total - 1.0 ) > WWMATH_EPSILON) { - float oo_total = 1.0f / weight_total; - for (anim_idx = 0; anim_idx < anim_count; anim_idx++ ) { - if (Peek_Motion(anim_idx) != NULL ) { - PivotMapClass *pivot_map = Get_Pivot_Weight_Map(anim_idx); - float new_weight = (*pivot_map)[piv_idx] * oo_total; - (*pivot_map)[piv_idx] = new_weight; - pivot_map->Release_Ref(); - } - } - } - - } - - } else { - return false; - } - } - - return true; - -} - -void HAnimComboClass::Set_Motion( int index, HAnimClass *motion ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - data->Set_HAnim(motion); -} - -HAnimClass *HAnimComboClass::Get_Motion( int index ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - HAnimClass *anim = data->Peek_HAnim(); - - if ( anim != NULL ) { - anim->Add_Ref(); - } - return anim; -} - -HAnimClass *HAnimComboClass::Peek_Motion( int index ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - HAnimClass *anim = data->Peek_HAnim(); - return anim; -} - -void HAnimComboClass::Set_Frame( int index, float frame ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - data->Set_Frame(frame); -} - -float HAnimComboClass::Get_Frame( int index ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - return data->Get_Frame(); -} - -void HAnimComboClass::Set_Weight( int index, float weight ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - data->Set_Weight(weight); -} - -float HAnimComboClass::Get_Weight( int index ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - return data->Get_Weight(); -} - -void HAnimComboClass::Set_Pivot_Weight_Map( int index, PivotMapClass *map ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - data->Set_Pivot_Map(map); -} - -PivotMapClass *HAnimComboClass::Get_Pivot_Weight_Map( int index ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - return data->Get_Pivot_Map(); -} - -PivotMapClass *HAnimComboClass::Peek_Pivot_Weight_Map( int index ) -{ - HAnimComboDataClass *data = HAnimComboData[index]; - WWASSERT(data); - - return data->Peek_Pivot_Map(); -} - -void HAnimComboClass::Append_Anim_Combo_Data(HAnimComboDataClass * Data) -{ - HAnimComboData.Add(Data); -} - -void HAnimComboClass::Remove_Anim_Combo_Data(HAnimComboDataClass * Data) -{ - HAnimComboData.Delete(Data); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanim.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanim.h deleted file mode 100644 index 60f77c62a1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanim.h +++ /dev/null @@ -1,260 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/hanim.h 2 6/29/01 6:41p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/hanim.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 6/27/01 7:35p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef HANIM_H -#define HANIM_H - -#include "always.h" -#include "quat.h" -#include "refcount.h" -#include "w3d_file.h" -#include "hash.h" -#include "mempool.h" -#include -#include -#include - -struct NodeMotionStruct; -class MotionChannelClass; -class BitChannelClass; -class HTreeClass; -class ChunkLoadClass; -class ChunkSaveClass; -class HTreeClass; - - - - -/********************************************************************************** - - HAnimClass - - This is the base class for all animation formats used in W3D. It - contains the virtual interface that all animations must support. - -**********************************************************************************/ -class HAnimClass : public RefCountClass, public HashableClass -{ -public: - enum - { - CLASSID_UNKNOWNANIM = 0xFFFFFFFF, - CLASSID_HRAWANIM = 0, - CLASSID_LASTANIM = 0x0000FFFF - }; - - HAnimClass(void) { } - virtual ~HAnimClass(void) { } - - virtual const char * Get_Name(void) const = 0; - virtual const char * Get_HName(void) const = 0; - - virtual const char * Get_Key( void ) { return Get_Name(); } - - virtual int Get_Num_Frames(void) = 0; - virtual float Get_Frame_Rate() = 0; - virtual float Get_Total_Time() = 0; - -// virtual Vector3 Get_Translation(int pividx,float frame) = 0; -// virtual Quaternion Get_Orientation(int pividx,float frame) = 0; - // Jani: Changed to pass in reference of destination to avoid copying - virtual void Get_Translation(int pividx,float frame) {} // todo: remove - virtual void Get_Orientation(int pividx,float frame) {} // todo: remove - virtual void Get_Translation(Vector3& translation, int pividx,float frame) const = 0; - virtual void Get_Orientation(Quaternion& orientation, int pividx,float frame) const = 0; - virtual void Get_Transform(Matrix3D&, int pividx, float frame) const = 0; - virtual bool Get_Visibility(int pividx,float frame) = 0; - - virtual int Get_Num_Pivots(void) const = 0; - virtual bool Is_Node_Motion_Present(int pividx) = 0; - - // Methods that test the presence of a certain motion channel. - virtual bool Has_X_Translation (int pividx) { return true; } - virtual bool Has_Y_Translation (int pividx) { return true; } - virtual bool Has_Z_Translation (int pividx) { return true; } - virtual bool Has_Rotation (int pividx) { return true; } - virtual bool Has_Visibility (int pividx) { return true; } - virtual int Class_ID(void) const { return CLASSID_UNKNOWNANIM; } - -}; - - -/* -** The PivotMapClass is used by the HAnimComboDataClass (sometimes) to keep track of animation -** weights per-pivot point. -*/ -class NamedPivotMapClass; - -class PivotMapClass : public DynamicVectorClass, public RefCountClass -{ -public: - virtual NamedPivotMapClass * As_Named_Pivot_Map() { return 0; } -}; - - -/* -** The NamedPivotMapClass allows us to create HAnimComboDataClass objects with pivot maps without -** having to have the HAnim available. Later, when an HAnim is retrieved from the asset manager, -** the pivot map can be updated to produce the correct map. -*/ -class NamedPivotMapClass : public PivotMapClass -{ -public: - ~NamedPivotMapClass(void); - - virtual NamedPivotMapClass * As_Named_Pivot_Map() { return this; } - - // add a name & weight to the arrays - void Add(const char *Name, float Weight); - - // configure the base pivot map using the specified tree - void Update_Pivot_Map(const HTreeClass *Tree); - -private: - - // This info is packaged into a struct to minimize DynamicVectorClass overhead - struct WeightInfoStruct { - WeightInfoStruct() : Name(0) {} - ~WeightInfoStruct() { if(Name) delete [] Name; } - - char *Name; - float Weight; - - // operators required for the DynamicVectorClass - WeightInfoStruct & operator = (WeightInfoStruct const &that); - bool operator == (WeightInfoStruct const &that) const { return &that == this; } - bool operator != (WeightInfoStruct const &that) const { return &that != this; } - }; - - DynamicVectorClass WeightInfo; -}; - - -/* -** The HAnimComboDataClass is used by the new HAnimComboClass to allow for a mix of shared/unshared data -** which will allow us to have the anim combo refer to data whereever we wish to put it. -*/ -class HAnimComboDataClass : public AutoPoolClass { - public: - HAnimComboDataClass(bool shared = false); - HAnimComboDataClass(const HAnimComboDataClass &); - ~HAnimComboDataClass(void); - - void Copy(const HAnimComboDataClass *); - - void Clear(void); - void Set_HAnim(HAnimClass *motion); - void Give_HAnim(HAnimClass *motion) { if(HAnim) HAnim->Release_Ref(); HAnim = motion; } // used for giving this object the reference - - void Set_Frame(float frame) { Frame = frame; } - void Set_Weight(float weight) { Weight = weight; } - void Set_Pivot_Map(PivotMapClass *map); - - - HAnimClass * Peek_HAnim(void) const { return HAnim; } // note: does not add reference - HAnimClass * Get_HAnim(void) const { if(HAnim) HAnim->Add_Ref(); return HAnim; } // note: does not add reference - float Get_Frame(void) const { return Frame; } - float Get_Weight(void) const { return Weight; } - PivotMapClass * Peek_Pivot_Map(void) const { return PivotMap; } - PivotMapClass * Get_Pivot_Map(void) const { if(PivotMap) PivotMap->Add_Ref(); return PivotMap; } - bool Is_Shared(void) const { return Shared; } - - void Build_Active_Pivot_Map(void); - - private: - - HAnimClass *HAnim; - float Frame; - float Weight; - PivotMapClass * PivotMap; - bool Shared; // this is set to false when the HAnimCombo allocates it -}; - -/* -** defines a combination of animations for blending/mixing -*/ -class HAnimComboClass { - -public: - - HAnimComboClass(void); - HAnimComboClass( int num_animations ); // allocates specified number of channels and sets then all to not-shared - ~HAnimComboClass(void); - - void Clear( void ); // zeros all data - - void Reset( void ); // empties the dynamic vector - - bool Normalize_Weights(void); // Normalizes all weights (returns true if succeeded) - int Get_Num_Anims( void ) { return HAnimComboData.Count(); } - - void Set_Motion( int indx, HAnimClass *motion ); - HAnimClass *Get_Motion( int indx ); - HAnimClass *Peek_Motion( int indx ); - - void Set_Frame( int indx, float frame ); - float Get_Frame( int indx ); - - void Set_Weight( int indx, float weight ); - float Get_Weight( int indx ); - - void Set_Pivot_Weight_Map( int indx, PivotMapClass * map ); - PivotMapClass * Get_Pivot_Weight_Map( int indx ); - PivotMapClass * Peek_Pivot_Weight_Map( int indx ); - - - // add an entry to the dynamic vector - void Append_Anim_Combo_Data(HAnimComboDataClass * AnimComboData); - - // remove an entry from the vector - void Remove_Anim_Combo_Data(HAnimComboDataClass * AnimComboData); - - // retrieve a specific combo data - HAnimComboDataClass * Peek_Anim_Combo_Data(int index) { return HAnimComboData[index]; } - -protected: - - DynamicVectorClass HAnimComboData; - -}; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp index ff7298a4ff..f95ee66157 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hanimmgr.cpp @@ -55,6 +55,7 @@ #include "chunkio.h" #include "wwmemlog.h" #include "w3dexclusionlist.h" +#include "animatedsoundmgr.h" /*********************************************************************************************** diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp deleted file mode 100644 index 04dfb8ba2c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hcanim.cpp +++ /dev/null @@ -1,710 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/hcanim.cpp 3 6/29/01 6:41p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/hcanim.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 6/27/01 7:50p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * NodeMotionStruct::NodeMotionStruct -- constructor * - * NodeMotionStruct::~NodeMotionStruct -- destructor * - * HCompressedAnimClass::HCompressedAnimClass -- constructor * - * HCompressedAnimClass::~HCompressedAnimClass -- Destructor * - * HCompressedAnimClass::Free -- De-allocates all memory in use * - * HCompressedAnimClass::Load -- Loads hierarchy animation from a file * - * HCompressedAnimClass::read_channel -- Reads in a single channel of motion * - * HCompressedAnimClass::add_channel -- Adds a motion channel to the animation * - * HCompressedAnimClass::Get_Translation -- returns the translation vector for the given fram* - * HCompressedAnimClass::Get_Orientation -- returns a quaternion for the orientation of the p* - * HCompressedAnimClass::read_bit_channel -- read a bit channel from the file * - * HCompressedAnimClass::add_bit_channel -- install a bit channel into the animation * - * HCompressedAnimClass::Get_Visibility -- return visibility state for given pivot/frame * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "hcanim.h" -#include "assetmgr.h" -#include "htree.h" -#include "motchan.h" -#include "chunkio.h" -#include "w3d_file.h" -#include "wwdebug.h" -#include -#include - - -struct NodeCompressedMotionStruct -{ - NodeCompressedMotionStruct(); - ~NodeCompressedMotionStruct(); - - void SetFlavor(int flavor) {Flavor = flavor;} - - int Flavor; - - union { - struct { - TimeCodedMotionChannelClass * X; - TimeCodedMotionChannelClass * Y; - TimeCodedMotionChannelClass * Z; - TimeCodedMotionChannelClass * Q; - } tc; - - struct { - AdaptiveDeltaMotionChannelClass * X; - AdaptiveDeltaMotionChannelClass * Y; - AdaptiveDeltaMotionChannelClass * Z; - AdaptiveDeltaMotionChannelClass * Q; - - } ad; - - struct { - void * X; - void * Y; - void * Z; - void * Q; - } vd; - }; - - - TimeCodedBitChannelClass * Vis; -}; - -/*********************************************************************************************** - * NodeCompressedMotionStruct::NodeCompressedMotionStruct -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -NodeCompressedMotionStruct::NodeCompressedMotionStruct() : - Vis(NULL) -{ - vd.X = NULL; - vd.Y = NULL; - vd.Z = NULL; - vd.Q = NULL; -} - - -/*********************************************************************************************** - * NodeCompressedMotionStruct::~NodeCompressedMotionStruct -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/23/98 GTH : Created. * - * 02/02/00 JGA : Compressed * - *=============================================================================================*/ -NodeCompressedMotionStruct::~NodeCompressedMotionStruct() -{ - // Needs to be changed to call the correct destructors - - switch (Flavor) { - case ANIM_FLAVOR_TIMECODED: - if (tc.X) delete tc.X; - if (tc.Y) delete tc.Y; - if (tc.Z) delete tc.Z; - if (tc.Q) delete tc.Q; - break; - case ANIM_FLAVOR_ADAPTIVE_DELTA: - if (ad.X) delete ad.X; - if (ad.Y) delete ad.Y; - if (ad.Z) delete ad.Z; - if (ad.Q) delete ad.Q; - break; - default: - WWASSERT(0); // unknown flavor - break; - } - - if (Vis) delete Vis; - -} // ~NodeCompressedMotionStruct - - -/*********************************************************************************************** - * HCompressedAnimClass::HCompressedAnimClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -HCompressedAnimClass::HCompressedAnimClass(void) : - NumFrames(0), - NumNodes(0), - Flavor(0), - FrameRate(0), - NodeMotion(NULL) -{ - memset(Name,0,W3D_NAME_LEN); - memset(HierarchyName,0,W3D_NAME_LEN); -} - - -/*********************************************************************************************** - * HCompressedAnimClass::~HCompressedAnimClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -HCompressedAnimClass::~HCompressedAnimClass(void) -{ - Free(); -} - - -/*********************************************************************************************** - * HCompressedAnimClass::Free -- De-allocates all memory in use * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HCompressedAnimClass::Free(void) -{ - if (NodeMotion != NULL) { - delete[] NodeMotion; - } -} - - -/*********************************************************************************************** - * HCompressedAnimClass::Load -- Loads hierarchy animation from a file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -int HCompressedAnimClass::Load_W3D(ChunkLoadClass & cload) -{ - int i = 0; - /* - ** First make sure we release any memory in use - */ - Free(); - - /* - ** Open the first chunk, it should be the animation header - */ - if (!cload.Open_Chunk()) return LOAD_ERROR; - - if (cload.Cur_Chunk_ID() != W3D_CHUNK_COMPRESSED_ANIMATION_HEADER) { - // ERROR: Expected Animation Header! - return LOAD_ERROR; - } - - W3dCompressedAnimHeaderStruct aheader; - if (cload.Read(&aheader,sizeof(W3dAnimHeaderStruct)) != sizeof(W3dAnimHeaderStruct)) { - return LOAD_ERROR; - } - - cload.Close_Chunk(); - - strcpy(Name,aheader.HierarchyName); - strcat(Name,"."); - strcat(Name,aheader.Name); - - // TSS chasing crash bug 05/26/99 - WWASSERT(HierarchyName != NULL); - WWASSERT(aheader.HierarchyName != NULL); - WWASSERT(sizeof(HierarchyName) >= W3D_NAME_LEN); - strncpy(HierarchyName,aheader.HierarchyName,W3D_NAME_LEN); - - HTreeClass * base_pose = WW3DAssetManager::Get_Instance()->Get_HTree(HierarchyName); - if (base_pose == NULL) { - goto Error; - } - NumNodes = base_pose->Num_Pivots(); - - NumFrames = aheader.NumFrames; - FrameRate = aheader.FrameRate; - Flavor = aheader.Flavor; - - // Just for now - WWASSERT((Flavor == ANIM_FLAVOR_TIMECODED)||(Flavor == ANIM_FLAVOR_ADAPTIVE_DELTA)); - - NodeMotion = W3DNEWARRAY NodeCompressedMotionStruct[ NumNodes ]; - if (NodeMotion == NULL) { - goto Error; - } - - // Initialize Flavor - for (i=0; iGet_Pivot() < NumNodes) { - add_channel(tc_chan); - } else { - // PWG 12-14-98: we have only allocated space for NumNode pivots. - // If we have an index thats equal or higher than NumNode we are - // gonna trash memory. Boy will we trash memory. - // GTH 09-25-2000: print a warning and survive this error - delete tc_chan; - WWDEBUG_SAY(("ERROR! animation %s indexes a bone not present in the model. Please re-export!\r\n",Name)); - } - - break; - - case ANIM_FLAVOR_ADAPTIVE_DELTA: - if (!read_channel(cload,&ad_chan)) { - goto Error; - } - if (ad_chan->Get_Pivot() < NumNodes) { - add_channel(ad_chan); - } else { - // PWG 12-14-98: we have only allocated space for NumNode pivots. - // If we have an index thats equal or higher than NumNode we are - // gonna trash memory. Boy will we trash memory. - // GTH 09-25-2000: print a warning and survive this error - delete ad_chan; - WWDEBUG_SAY(("ERROR! animation %s indexes a bone not present in the model. Please re-export!\r\n",Name)); - } - break; - } - break; - - case W3D_CHUNK_COMPRESSED_BIT_CHANNEL: - if (!read_bit_channel(cload,&newbitchan)) { - goto Error; - } - if (newbitchan->Get_Pivot() < NumNodes) { - add_bit_channel(newbitchan); - } else { - // PWG 12-14-98: we have only allocated space for NumNode pivots. - // If we have an index thats equal or higher than NumNode we are - // gonna trash memory. Boy will we trash memory. - // GTH 09-25-2000: print a warning and survive this error - delete newbitchan; - WWDEBUG_SAY(("ERROR! animation %s indexes a bone not present in the model. Please re-export!\r\n",Name)); - } - - break; - - default: - break; - } - cload.Close_Chunk(); - } - - return OK; - -Error: - - Free(); - return LOAD_ERROR; - -} // Load_W3D - -/*********************************************************************************************** - * HCompressedAnimClass::read_channel -- Reads in a single channel of motion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -bool HCompressedAnimClass::read_channel(ChunkLoadClass & cload,TimeCodedMotionChannelClass * * newchan) -{ - *newchan = W3DNEW TimeCodedMotionChannelClass; - bool result = (*newchan)->Load_W3D(cload); - - return result; - -} // read_channel - -bool HCompressedAnimClass::read_channel(ChunkLoadClass & cload,AdaptiveDeltaMotionChannelClass * * newchan) -{ - *newchan = W3DNEW AdaptiveDeltaMotionChannelClass; - bool result = (*newchan)->Load_W3D(cload); - - return result; - -} // read_channel - - -/*********************************************************************************************** - * HCompressedAnimClass::add_channel -- Adds a motion channel to the animation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HCompressedAnimClass::add_channel(TimeCodedMotionChannelClass * newchan) -{ - int idx = newchan->Get_Pivot(); - - switch (newchan->Get_Type()) - { - case ANIM_CHANNEL_X: - NodeMotion[idx].tc.X = newchan; - break; - - case ANIM_CHANNEL_Y: - NodeMotion[idx].tc.Y = newchan; - break; - - case ANIM_CHANNEL_Z: - NodeMotion[idx].tc.Z = newchan; - break; - - case ANIM_CHANNEL_Q: - NodeMotion[idx].tc.Q = newchan; - break; - } - -} // add_channel - -void HCompressedAnimClass::add_channel(AdaptiveDeltaMotionChannelClass * newchan) -{ - int idx = newchan->Get_Pivot(); - - switch (newchan->Get_Type()) - { - case ANIM_CHANNEL_X: - NodeMotion[idx].ad.X = newchan; - break; - - case ANIM_CHANNEL_Y: - NodeMotion[idx].ad.Y = newchan; - break; - - case ANIM_CHANNEL_Z: - NodeMotion[idx].ad.Z = newchan; - break; - - case ANIM_CHANNEL_Q: - NodeMotion[idx].ad.Q = newchan; - break; - } - -} // add_channel - - - - -/*********************************************************************************************** - * HCompressedAnimClass::read_bit_channel -- read a bit channel from the file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/98 GTH : Created. * - *=============================================================================================*/ -bool HCompressedAnimClass::read_bit_channel(ChunkLoadClass & cload,TimeCodedBitChannelClass * * newchan) -{ - *newchan = W3DNEW TimeCodedBitChannelClass; - bool result = (*newchan)->Load_W3D(cload); - - return result; - -} // read_bit_channel - - -/*********************************************************************************************** - * HCompressedAnimClass::add_bit_channel -- install a bit channel into the animation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/98 GTH : Created. * - *=============================================================================================*/ -void HCompressedAnimClass::add_bit_channel(TimeCodedBitChannelClass * newchan) -{ - int idx = newchan->Get_Pivot(); - - switch (newchan->Get_Type()) - { - case BIT_CHANNEL_VIS: - NodeMotion[idx].Vis = newchan; - break; - } -} - -/*********************************************************************************************** - * HCompressedAnimClass::Get_Translation -- returns the translation vector for the given frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HCompressedAnimClass::Get_Translation( Vector3& trans, int pividx, float frame ) const -{ - struct NodeCompressedMotionStruct * motion = &NodeMotion[pividx]; - - trans=Vector3(0,0,0); - - switch(Flavor) { - case ANIM_FLAVOR_TIMECODED: - if (motion->tc.X) motion->tc.X->Get_Vector(frame, &(trans[0])); - if (motion->tc.Y) motion->tc.Y->Get_Vector(frame, &(trans[1])); - if (motion->tc.Z) motion->tc.Z->Get_Vector(frame, &(trans[2])); - break; - case ANIM_FLAVOR_ADAPTIVE_DELTA: - if (motion->ad.X) motion->ad.X->Get_Vector(frame, &(trans[0])); - if (motion->ad.Y) motion->ad.Y->Get_Vector(frame, &(trans[1])); - if (motion->ad.Z) motion->ad.Z->Get_Vector(frame, &(trans[2])); - break; - default: - WWASSERT(0); // unknown flavor - break; - } -} - -/*********************************************************************************************** - * HCompressedAnimClass::Get_Orientation -- returns a quaternion for the orientation of the * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HCompressedAnimClass::Get_Orientation(Quaternion& q, int pividx,float frame) const -{ - switch(Flavor) { - case ANIM_FLAVOR_TIMECODED: - if (NodeMotion[pividx].tc.Q) q = NodeMotion[pividx].tc.Q->Get_QuatVector(frame); - else q.Make_Identity(); - break; - case ANIM_FLAVOR_ADAPTIVE_DELTA: - if (NodeMotion[pividx].ad.Q) q = NodeMotion[pividx].ad.Q->Get_QuatVector(frame); - else q.Make_Identity(); - break; - default: - WWASSERT(0); // unknown flavor - break; - } -} // Get_Orientation - -/*********************************************************************************************** - * HCompressedAnimClass::Get_Transform -- returns the transform matrix for the given frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HCompressedAnimClass::Get_Transform( Matrix3D& mtx, int pividx, float frame ) const -{ - struct NodeCompressedMotionStruct * motion = &NodeMotion[pividx]; - - switch(Flavor) { - case ANIM_FLAVOR_TIMECODED: - if (NodeMotion[pividx].tc.Q) { - Quaternion q; - q = NodeMotion[pividx].tc.Q->Get_QuatVector(frame); - ::Build_Matrix3D(q,mtx); - } - else mtx.Make_Identity(); - if (motion->tc.X) motion->tc.X->Get_Vector(frame, &(mtx[0][3])); - if (motion->tc.Y) motion->tc.Y->Get_Vector(frame, &(mtx[1][3])); - if (motion->tc.Z) motion->tc.Z->Get_Vector(frame, &(mtx[2][3])); - break; - case ANIM_FLAVOR_ADAPTIVE_DELTA: - if (NodeMotion[pividx].ad.Q) { - Quaternion q; - q = NodeMotion[pividx].ad.Q->Get_QuatVector(frame); - ::Build_Matrix3D(q,mtx); - } - else mtx.Make_Identity(); - - if (motion->ad.X) motion->ad.X->Get_Vector(frame, &(mtx[0][3])); - if (motion->ad.Y) motion->ad.Y->Get_Vector(frame, &(mtx[1][3])); - if (motion->ad.Z) motion->ad.Z->Get_Vector(frame, &(mtx[2][3])); - break; - default: - WWASSERT(0); // unknown flavor - break; - } -} - -/*********************************************************************************************** - * HCompressedAnimClass::Get_Visibility -- return visibility state for given pivot/frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/98 GTH : Created. * - *=============================================================================================*/ -bool HCompressedAnimClass::Get_Visibility(int pividx,float frame) -{ - - if (NodeMotion[pividx].Vis != NULL) { - return (NodeMotion[pividx].Vis->Get_Bit((int)frame) == 1); - } - - - // default to always visible... - return 1; -} - - - -/*********************************************************************************************** - * HAnimClass::Is_Node_Motion_Present -- return true if there is motion defined for this frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/23/99 EHC : Created. * - *=============================================================================================*/ -bool HCompressedAnimClass::Is_Node_Motion_Present(int pividx) -{ - WWASSERT((pividx >= 0) && (pividx < NumNodes)); - - if (NodeMotion[pividx].vd.X != NULL) return true; - if (NodeMotion[pividx].vd.Y != NULL) return true; - if (NodeMotion[pividx].vd.Z != NULL) return true; - if (NodeMotion[pividx].vd.Q != NULL) return true; - if (NodeMotion[pividx].Vis != NULL) return true; - - return false; -} - -bool HCompressedAnimClass::Has_X_Translation (int pividx) -{ - WWASSERT((pividx >= 0) && (pividx < NumNodes)); - return NodeMotion[pividx].vd.X != NULL; -} - -bool HCompressedAnimClass::Has_Y_Translation (int pividx) -{ - WWASSERT((pividx >= 0) && (pividx < NumNodes)); - return NodeMotion[pividx].vd.Y != NULL; -} - -bool HCompressedAnimClass::Has_Z_Translation (int pividx) -{ - WWASSERT((pividx >= 0) && (pividx < NumNodes)); - return NodeMotion[pividx].vd.Z != NULL; -} - -bool HCompressedAnimClass::Has_Rotation (int pividx) -{ - WWASSERT((pividx >= 0) && (pividx < NumNodes)); - return NodeMotion[pividx].vd.Q != NULL; -} - -bool HCompressedAnimClass::Has_Visibility (int pividx) -{ - WWASSERT((pividx >= 0) && (pividx < NumNodes)); - return NodeMotion[pividx].Vis != NULL; -} - - -// eof - hcanim.cpp diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hcanim.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hcanim.h deleted file mode 100644 index b3f646d197..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hcanim.h +++ /dev/null @@ -1,139 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/hcanim.h 2 6/29/01 6:41p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/hcanim.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 6/27/01 7:35p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef HCANIM_H -#define HCANIM_H - -#include "always.h" -#include "quat.h" -#include "refcount.h" -#include "w3d_file.h" -#include "SLIST.H" -#include "Vector.H" -#include "hanim.h" - -struct NodeCompressedMotionStruct; -class TimeCodedMotionChannelClass; -class TimeCodedBitChannelClass; -class AdaptiveDeltaMotionChannelClass; -class HTreeClass; -class ChunkLoadClass; -class ChunkSaveClass; - - -/********************************************************************************** - - Hierarchy Compressed Animation Class - - Stores motion data to be applied to a HierarchyTree. Each frame - of the motion contains deltas from the HierarchyTree's base position - to the desired position. - -**********************************************************************************/ - -class HCompressedAnimClass : public HAnimClass -{ - -public: - - enum - { - OK, - LOAD_ERROR - }; - - HCompressedAnimClass(void); - ~HCompressedAnimClass(void); - - int Load_W3D(ChunkLoadClass & cload); - - const char * Get_Name(void) const { return Name; } - const char * Get_HName(void) const { return HierarchyName; } - int Get_Num_Frames(void) { return NumFrames; } - float Get_Frame_Rate() { return FrameRate; } - float Get_Total_Time() { return (float)NumFrames / FrameRate; } - int Get_Flavor() { return Flavor; } - -// Vector3 Get_Translation(int pividx,float frame); -// Quaternion Get_Orientation(int pividx,float frame); - void Get_Translation(Vector3& translation, int pividx,float frame) const; - void Get_Orientation(Quaternion& orientation, int pividx,float frame) const; - void Get_Transform(Matrix3D& transform, int pividx,float frame) const; - bool Get_Visibility(int pividx,float frame); - - bool Is_Node_Motion_Present(int pividx); - int Get_Num_Pivots(void) const { return NumNodes; } - - // Methods that test the presence of a certain motion channel. - bool Has_X_Translation (int pividx); - bool Has_Y_Translation (int pividx); - bool Has_Z_Translation (int pividx); - bool Has_Rotation (int pividx); - bool Has_Visibility (int pividx); - -private: - - char Name[2*W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; - - int NumFrames; - int NumNodes; - int Flavor; - float FrameRate; - - NodeCompressedMotionStruct * NodeMotion; - - void Free(void); - bool read_channel(ChunkLoadClass & cload,TimeCodedMotionChannelClass * * newchan); - bool read_channel(ChunkLoadClass & cload,AdaptiveDeltaMotionChannelClass * * newchan); - void add_channel(TimeCodedMotionChannelClass * newchan); - void add_channel(AdaptiveDeltaMotionChannelClass * newchan); - - - bool read_bit_channel(ChunkLoadClass & cload,TimeCodedBitChannelClass * * newchan); - void add_bit_channel(TimeCodedBitChannelClass * newchan); - -}; - - -#endif // hcanim.h - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.H b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.H deleted file mode 100644 index 732998476c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.H +++ /dev/null @@ -1,112 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/hmdldef.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef HMDLDEF_H -#define HMDLDEF_H - -#include "always.h" -#include "w3d_file.h" - -class FileClass; -class ChunkLoadClass; -class ChunkSaveClass; -class SnapPointsClass; - -/* -** Each render object to be attached into the hierarchy model -** will be defined by an instance of the following structure. -** The HmdlNodeDefStruct associates a named render object with -** an indexed pivot/bone in the hierarchy tree. -*/ -struct HmdlNodeDefStruct -{ - char RenderObjName[2*W3D_NAME_LEN]; - int PivotID; -}; - - -/* -** HModelDefClass -** -** "Hierarchy Model Definition Class" -** This class serves as a blueprint for creating HierarchyModelClasses. -** The asset manager stores these objects internally and uses them to -** create instances of HierarchyModels for the user. -*/ -class HModelDefClass -{ - -public: - - enum { - OK, - LOAD_ERROR - }; - - HModelDefClass(void); - ~HModelDefClass(void); - - int Load_W3D(ChunkLoadClass & cload); - const char * Get_Name(void) const { return Name; } - -private: - - char Name[2*W3D_NAME_LEN]; // . - char ModelName[W3D_NAME_LEN]; // name of the model - char BasePoseName[W3D_NAME_LEN]; // name of the base pose (hierarchy tree) - - int SubObjectCount; - HmdlNodeDefStruct * SubObjects; - SnapPointsClass * SnapPoints; - - void Free(void); - bool read_header(ChunkLoadClass & cload); - bool read_connection(ChunkLoadClass & cload,HmdlNodeDefStruct * con,bool pre30); - bool read_mesh_connection(ChunkLoadClass & cload,int idx,bool pre30); - bool read_collision_connection(ChunkLoadClass & cload,int idx,bool pre30); - bool read_skin_connection(ChunkLoadClass & cload,int idx,bool pre30); - - // HModelClass requires intimate knowlege of us - friend class HModelClass; - friend class HLodClass; -}; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp deleted file mode 100644 index cb6caee841..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/hmdldef.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/hmdldef.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * HModelDefClass::HModelDefClass -- Constructor * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "hmdldef.H" -#include -#include -#include "w3d_file.h" -#include "chunkio.h" -#include "snapPts.h" - - -/*********************************************************************************************** - * HModelDefClass::HModelDefClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/15/97 GTH : Created. * - *=============================================================================================*/ -HModelDefClass::HModelDefClass(void) : - SubObjectCount(0), - SubObjects(NULL), - SnapPoints(NULL) -{ - -} - -/*********************************************************************************************** - * HModelDefClass::~HModelDefClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -HModelDefClass::~HModelDefClass(void) -{ - Free(); -} - -/*********************************************************************************************** - * HModelDefClass::Free -- de-allocate all memory in use * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HModelDefClass::Free(void) -{ - if (SubObjects != NULL) { - delete[] SubObjects; - SubObjects = NULL; - } - SubObjectCount = 0; - - if (SnapPoints != NULL) { - SnapPoints->Release_Ref(); - SnapPoints = NULL; - } -} - - -/*********************************************************************************************** - * HModelDefClass::Load -- load a set of mesh connections from a file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -int HModelDefClass::Load_W3D(ChunkLoadClass & cload) -{ - bool pre30 = false; - int subobjcounter = 0; - - Free(); - - /* - ** Read the first chunk, it should be the header - */ - if (!cload.Open_Chunk()) { - return false; - } - - if (cload.Cur_Chunk_ID() != W3D_CHUNK_HMODEL_HEADER) { - goto Error; - } - - /* - ** read in the header - */ - W3dHModelHeaderStruct header; - if (cload.Read(&header,sizeof(W3dHModelHeaderStruct)) != sizeof(W3dHModelHeaderStruct)) { - goto Error; - } - - cload.Close_Chunk(); - - /* - ** process the header info - */ - strncpy(ModelName,header.Name,W3D_NAME_LEN); - ModelName[W3D_NAME_LEN - 1] = 0; - strncpy(BasePoseName,header.HierarchyName,W3D_NAME_LEN); - BasePoseName[W3D_NAME_LEN-1] = 0; - strcpy(Name,ModelName); - - /* - ** Just allocate a node for the number of sub objects we're expecting - */ - SubObjectCount = header.NumConnections; - SubObjects = W3DNEWARRAY HmdlNodeDefStruct[SubObjectCount]; - if (SubObjects == NULL) { - goto Error; - } - - /* - ** If this is pre-3.0 set a flag so that each render object's - ** bone id will be incremented by one to account for the new - ** root node added with version3.0 of the file format. Basically, - ** I'm making all of the code assume that node 0 is the root and - ** therefore, pre-3.0 files have to have it added and all of - ** the indices adjusted - */ - if (header.Version < W3D_MAKE_VERSION(3,0)) { - pre30 = true; - } - - /* - ** Process the rest of the chunks - */ - subobjcounter = 0; - - while (cload.Open_Chunk()) { - - switch (cload.Cur_Chunk_ID()) { - - case W3D_CHUNK_NODE: - case W3D_CHUNK_COLLISION_NODE: - case W3D_CHUNK_SKIN_NODE: - if (!read_connection(cload,&(SubObjects[subobjcounter]),pre30)) { - goto Error; - } - subobjcounter++; - break; - - case W3D_CHUNK_POINTS: - SnapPoints = W3DNEW SnapPointsClass; - SnapPoints->Load_W3D(cload); - break; - - default: - break; - } - cload.Close_Chunk(); - } - - return OK; - -Error: - - return LOAD_ERROR; - -} - - -/*********************************************************************************************** - * HModelDefClass::read_connection -- read a single connection from the file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - * 10/22/97 GH : Check for mesh connections with PivotID=-1 * - *=============================================================================================*/ -bool HModelDefClass::read_connection(ChunkLoadClass & cload,HmdlNodeDefStruct * node,bool pre30) -{ - - W3dHModelNodeStruct con; - if (cload.Read(&con,sizeof(W3dHModelNodeStruct)) != sizeof(W3dHModelNodeStruct)) { - return false; - } - - strcpy(node->RenderObjName,ModelName); - strcat(node->RenderObjName,"."); - strcat(node->RenderObjName,con.RenderObjName); - - if (pre30) { - if (con.PivotIdx == 65535) { - node->PivotID = 0; - } else { - node->PivotID = con.PivotIdx + 1; - } - } else { - assert(con.PivotIdx != 65535); - node->PivotID = con.PivotIdx; - } - - return true; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp deleted file mode 100644 index b8dad6de2f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp +++ /dev/null @@ -1,1231 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/htree.cpp 14 10/01/01 6:07p Patrick $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/htree.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 10/01/01 6:06p $* - * * - * $Revision:: 14 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * HTreeClass::HTreeClass -- constructor * - * HTreeClass::~HTreeClass -- destructor * - * HTreeClass::Load -- loads a hierarchy tree from a file * - * HTreeClass::read_pivots -- reads the pivots out of a file * - * HTreeClass::Free -- de-allocate all memory in use * - * HTreeClass::Base_Update -- Computes the base pose transform for each pivot * - * HTreeClass::Anim_Update -- Computes the transform for each pivot with motion * - * HTreeClass::Blend_Update -- computes each pivot as a blend of two anims * - * HTreeClass::Combo_Update -- compute each pivot's transform using an anim combo * - * HTreeClass::Get_Transform -- returns the transformation for the desired pivot * - * HTreeClass::Find_Bone -- Find a bone by name * - * HTreeClass::Get_Bone_Name -- get the name of a bone from its index * - * HTreeClass::Update_Parent_Need_Bits -- all "needed" children force their parents to be nee* - * HTreeClass::HTreeClass -- copy constructor * - * HTreeClass::Get_Parent_Index -- returns index of the parent of the given bone * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "htree.h" -#include "hanim.h" -#include "hcanim.h" -#include -#include -#include "wwmath.h" -#include "chunkio.h" -#include "w3d_file.h" -#include "wwmemlog.h" -#include "hrawanim.h" -#include "motchan.h" - -/*********************************************************************************************** - * HTreeClass::HTreeClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -HTreeClass::HTreeClass(void) : - NumPivots(0), - Pivot(NULL), - ScaleFactor(1.0f) -{ -} - -void HTreeClass::Init_Default(void) -{ - Free (); - - NumPivots = 1; - Pivot = MSGW3DNEWARRAY("HTreeClass::Pivot") PivotClass[NumPivots]; - - Pivot[0].Index = 0; - Pivot[0].Parent = NULL; - Pivot[0].BaseTransform.Make_Identity(); - Pivot[0].Transform.Make_Identity(); - Pivot[0].IsVisible = true; - strcpy(Pivot[0].Name,"RootTransform"); - //::strcpy (Name, "Default"); - Name[0] = 0; - return ; - - - -} - -/*********************************************************************************************** - * HTreeClass::~HTreeClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -HTreeClass::~HTreeClass(void) -{ - Free(); - - - -} - - -/*********************************************************************************************** - * HTreeClass::HTreeClass -- copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/98 GTH : Created. * - *=============================================================================================*/ -HTreeClass::HTreeClass(const HTreeClass & src) : - NumPivots(0), - Pivot(NULL), - ScaleFactor(1.0f) -{ - memcpy(&Name,&src.Name,sizeof(Name)); - - NumPivots = src.NumPivots; - if (NumPivots > 0) { - Pivot = MSGW3DNEWARRAY("HTreeClass::Pivot") PivotClass[NumPivots]; - } - - for (int pi = 0; pi < NumPivots; pi++) { - Pivot[pi] = src.Pivot[pi]; - - if (src.Pivot[pi].Parent != NULL) { - Pivot[pi].Parent = &(Pivot[src.Pivot[pi].Parent->Index]); - } else { - Pivot[pi].Parent = NULL; - } - } - - ScaleFactor = src.ScaleFactor; -} - -/*********************************************************************************************** - * HTreeClass::Load -- loads a hierarchy tree from a file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -int HTreeClass::Load_W3D(ChunkLoadClass & cload) -{ - Free(); - - /* - ** Read the first chunk, it should be the hierarchy header - */ - if (!cload.Open_Chunk()) return LOAD_ERROR; - - if (cload.Cur_Chunk_ID() != W3D_CHUNK_HIERARCHY_HEADER) { - // ERROR: Expected Hierarchy Header - return LOAD_ERROR; - } - - W3dHierarchyStruct header; - if (cload.Read(&header,sizeof(W3dHierarchyStruct)) != sizeof(W3dHierarchyStruct)) { - return LOAD_ERROR; - } - - cload.Close_Chunk(); - - /* - ** Check the version, if < 3.0 add a root node for everything - ** to attach to. The load_pivots function will also have to be - ** notified of this. - */ - bool pre30 = false; - if (header.Version < W3D_MAKE_VERSION(3,0)) { - header.NumPivots ++; - pre30 = true; - } - - /* - ** Allocate the array of pivots - */ - memcpy(Name,header.Name,W3D_NAME_LEN); - NumPivots = header.NumPivots; - if (NumPivots > 0) { - Pivot = MSGW3DNEWARRAY("HTreeClass::Pivot") PivotClass[NumPivots]; - } - - /* - ** Now, read in all of the other chunks for this hierarchy. - */ - - while (cload.Open_Chunk()) { - - switch (cload.Cur_Chunk_ID()) { - - case W3D_CHUNK_PIVOTS: - if (!read_pivots(cload,pre30)) { - goto Error; - } - break; - - default: - // ERROR: expected W3D_CHUNK_PIVOTS! - break; - } - cload.Close_Chunk(); - } - - return OK; - -Error: - - Free(); - return LOAD_ERROR; -} - - -/*********************************************************************************************** - * HTreeClass::read_pivots -- reads the pivots out of a file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -bool HTreeClass::read_pivots(ChunkLoadClass & cload,bool pre30) -{ - W3dPivotStruct piv; - Matrix3D mtx; - - int first_piv = 0; - - /* - ** At (w3d file format) version 3.0, I added a node for the root. Pre-3.0 htrees didn't have - ** this so we just put one in. - */ - if (pre30) { - Pivot[0].Index = 0; - Pivot[0].Parent = NULL; - Pivot[0].BaseTransform.Make_Identity(); - Pivot[0].Transform.Make_Identity(); - Pivot[0].IsVisible = true; - strcpy(Pivot[0].Name,"RootTransform"); - first_piv++; - } - - for (int pidx=first_piv; pidx < NumPivots; pidx++) { - - if (cload.Read(&piv,sizeof(W3dPivotStruct)) != sizeof(W3dPivotStruct)) { - return false; - } - - memcpy(Pivot[pidx].Name,piv.Name,W3D_NAME_LEN); - Pivot[pidx].Index = pidx; - - Pivot[pidx].BaseTransform.Make_Identity(); - Pivot[pidx].BaseTransform.Translate(Vector3(piv.Translation.X,piv.Translation.Y,piv.Translation.Z)); - -#ifdef ALLOW_TEMPORARIES - Pivot[pidx].BaseTransform = - Pivot[pidx].BaseTransform * - Build_Matrix3D( - Quaternion( - piv.Rotation.Q[0], - piv.Rotation.Q[1], - piv.Rotation.Q[2], - piv.Rotation.Q[3] - ), - mtx - ); -#else - Pivot[pidx].BaseTransform.postMul( - Build_Matrix3D( - Quaternion( - piv.Rotation.Q[0], - piv.Rotation.Q[1], - piv.Rotation.Q[2], - piv.Rotation.Q[3] - ), - mtx - ) - ); -#endif - - /* - ** At version 3.0 a root node was added, this "fixes up" pre-3.0 files - ** to have that root node - */ - if (pre30) { - piv.ParentIdx += 1; - } - - /* - ** Set the parent pointer. The first pivot will have a parent index - ** of -1 (in post-3.0 files) so set its parent to NULL. - */ - if (piv.ParentIdx == -1) { - Pivot[pidx].Parent = NULL; - assert(pidx == 0); - } else { - Pivot[pidx].Parent = &(Pivot[piv.ParentIdx]); - } - - } - - Pivot[0].Transform.Make_Identity(); - Pivot[0].IsVisible = true; - - return true; -} - - -/*********************************************************************************************** - * HTreeClass::Free -- de-allocate all memory in use * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HTreeClass::Free(void) -{ - if (Pivot != NULL) { - delete[] Pivot; - Pivot = NULL; - } - NumPivots = 0; - - // Also clean up other members: - ScaleFactor = 1.0f; -} - - -/*********************************************************************************************** - * HTreeClass::Simple_Evaluate_Pivot -- Returns the transform of a pivot at the given frame. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/13/2000 PDS : Created. * - *=============================================================================================*/ -bool HTreeClass::Simple_Evaluate_Pivot -( - HAnimClass * motion, - int pivot_index, - float frame, - const Matrix3D & obj_tm, - Matrix3D * end_tm -) const -{ - bool retval = false; - end_tm->Make_Identity (); - - if ( motion != NULL && - end_tm != NULL && - pivot_index >= 0 && - pivot_index < NumPivots) - { - // - // Loop over the hierarchy of pivots that this pivot is - // attached to and transform each. - // - for ( PivotClass *pivot = &Pivot[pivot_index]; - pivot != NULL && pivot->Parent != NULL; - pivot = pivot->Parent) - { - // - // Build a matrix that represents the animation for this pivot - // - - Matrix3D anim_tm; - motion->Get_Transform(anim_tm, pivot->Index, frame); - -// Quaternion q; -// motion->Get_Orientation (q, pivot->Index, frame); -// Matrix3D anim_tm = ::Build_Matrix3D(q); - - Vector3 trans; - anim_tm.Get_Translation(&trans); - anim_tm.Set_Translation(trans * ScaleFactor); - - // - // Transform the animation transform by the 'relative-to-parent' transform. - // - Matrix3D curr_tm; - Matrix3D::Multiply(pivot->BaseTransform, anim_tm, &curr_tm); - - // - // Transform the return value by this transform - // -#ifdef ALLOW_TEMPORARIES - Matrix3D::Multiply (curr_tm, *end_tm, end_tm); -#else - end_tm->preMul(curr_tm); -#endif - } - - // - // Transform the return value by the object's transform - // -#ifdef ALLOW_TEMPORARIES - Matrix3D::Multiply (obj_tm, *end_tm, end_tm); -#else - end_tm->preMul(obj_tm); -#endif - - // Success! - retval = true; - } - - return retval; -} - - - -/*********************************************************************************************** - * HTreeClass::Simple_Evaluate_Pivot -- Returns the transform of a pivot at the given frame. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/13/2000 PDS : Created. * - *=============================================================================================*/ -bool HTreeClass::Simple_Evaluate_Pivot -( - int pivot_index, - const Matrix3D & obj_tm, - Matrix3D * end_tm -) const -{ - bool retval = false; - end_tm->Make_Identity (); - - if ( end_tm != NULL && - pivot_index >= 0 && - pivot_index < NumPivots) - { - // - // Loop over the hierarchy of pivots that this pivot is - // attached to and transform each. - // - for ( PivotClass *pivot = &Pivot[pivot_index]; - pivot != NULL && pivot->Parent != NULL; - pivot = pivot->Parent) - { - // - // Build a matrix that represents the animation for this pivot - // - Matrix3D anim_tm (1); - - // - // Transform the animation transform by the 'relative-to-parent' transform. - // - Matrix3D curr_tm; - Matrix3D::Multiply (pivot->BaseTransform, anim_tm, &curr_tm); - - // - // Transform the return value by this transform - // - Matrix3D::Multiply (curr_tm, *end_tm, end_tm); - } - - // - // Transform the return value by the object's transform - // - Matrix3D::Multiply (obj_tm, *end_tm, end_tm); - retval = true; - } - - return retval; -} - - -/*********************************************************************************************** - * HTreeClass::Base_Update -- Computes the base pose transform for each pivot * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HTreeClass::Base_Update(const Matrix3D & root) -{ - PivotClass *pivot; - - Pivot[0].Transform = root; - Pivot[0].IsVisible = true; - - for (int piv_idx=1; piv_idx < NumPivots; piv_idx++) { - - pivot = &Pivot[piv_idx]; - - assert(pivot->Parent != NULL); - Matrix3D::Multiply(pivot->Parent->Transform, pivot->BaseTransform, &(pivot->Transform)); - pivot->IsVisible = 1; - - if (pivot->Is_Captured()) pivot->Capture_Update(); - } -} - -/*********************************************************************************************** - * HTreeClass::Anim_Update -- Computes the transform for each pivot with motion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void HTreeClass::Anim_Update(const Matrix3D & root,HAnimClass * motion,float frame) -{ - PivotClass *pivot; - Matrix3D mtx; - - Pivot[0].Transform = root; - Pivot[0].IsVisible = true; - - int num_anim_pivots = motion->Get_Num_Pivots (); - - for (int piv_idx=1; piv_idx < NumPivots; piv_idx++) { - pivot = &Pivot[piv_idx]; - - // base pose - assert(pivot->Parent != NULL); - Matrix3D::Multiply(pivot->Parent->Transform, pivot->BaseTransform, &(pivot->Transform)); - - // Don't update this pivot if the HTree doesn't have animation data for it... - if (piv_idx < num_anim_pivots) { - - // animation - Vector3 trans; - motion->Get_Translation(trans,piv_idx,frame); - pivot->Transform.Translate(trans * ScaleFactor); - - Quaternion q; - motion->Get_Orientation(q,piv_idx,frame); - ::Build_Matrix3D(q,mtx); - -#ifdef ALLOW_TEMPORARIES - pivot->Transform = pivot->Transform * mtx; -#else - pivot->Transform.postMul(mtx); -#endif - - // visibility - pivot->IsVisible = motion->Get_Visibility(piv_idx,frame); - } - - if (pivot->Is_Captured()) - { - pivot->Capture_Update(); - pivot->IsVisible = true; - } - } -} - -/*Customized version of the above which excludes interpolation and assumes HRawAnimClass -For use by 'Generals' -MW*/ -void HTreeClass::Anim_Update(const Matrix3D & root,HRawAnimClass * motion,float frame) -{ - PivotClass *pivot,*endpivot,*lastAnimPivot; - - Pivot[0].Transform = root; - Pivot[0].IsVisible = true; - - int num_anim_pivots = motion->Get_Num_Pivots (); - - //Get integer frame - int iframe=WWMath::Float_To_Long(frame); - if (iframe >= motion->Get_Num_Frames()) - iframe = 0; - - Vector3 trans; - Quaternion q; - Matrix3D mtx; - - struct NodeMotionStruct * nodeMotion = ((HRawAnimClass*)motion)->Get_Node_Motion_Array(); - nodeMotion += 1; //skip the root node - - pivot = &Pivot[1]; - endpivot=pivot+(NumPivots-1); - lastAnimPivot = &Pivot[num_anim_pivots]; - - for (int piv_idx=1; pivot < endpivot; pivot++,nodeMotion++) { - - // base pose - assert(pivot->Parent != NULL); - Matrix3D::Multiply(pivot->Parent->Transform, pivot->BaseTransform, &(pivot->Transform)); - - // Don't update this pivot if the HTree doesn't have animation data for it... - if (pivot < lastAnimPivot) - { - - // animation - trans.Set(0.0f,0.0f,0.0f); - Matrix3D *xform=&pivot->Transform; - - if (nodeMotion->X != NULL) - nodeMotion->X->Get_Vector(iframe,&(trans[0])); - if (nodeMotion->Y != NULL) - nodeMotion->Y->Get_Vector(iframe,&(trans[1])); - if (nodeMotion->Z != NULL) - nodeMotion->Z->Get_Vector(iframe,&(trans[2])); - - if (ScaleFactor == 1.0f) - xform->Translate(trans); - else - xform->Translate(trans*ScaleFactor); - - if (nodeMotion->Q != NULL) - { nodeMotion->Q->Get_Vector_As_Quat(iframe, q); -#ifdef ALLOW_TEMPORARIES - *xform = *xform * ::Build_Matrix3D(q,mtx); -#else - xform->postMul(::Build_Matrix3D(q,mtx)); -#endif - } - - // visibility - if (nodeMotion->Vis != NULL) - pivot->IsVisible=(nodeMotion->Vis->Get_Bit(iframe) == 1); - else - pivot->IsVisible=1; - } - - if (pivot->Is_Captured()) - { - pivot->Capture_Update(); - pivot->IsVisible = true; - } - } -} - - -/*********************************************************************************************** - * HTreeClass::Blend_Update -- computes each pivot as a blend of two anims * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/98 GTH : Created. * - *=============================================================================================*/ -void HTreeClass::Blend_Update -( - const Matrix3D & root, - HAnimClass * motion0, - float frame0, - HAnimClass * motion1, - float frame1, - float percentage // 0.0 = motion0. 1.0 = motion1 -) -{ - PivotClass *pivot; - Matrix3D mtx; - - Pivot[0].Transform = root; - Pivot[0].IsVisible = true; - - int num_anim_pivots = MIN( motion0->Get_Num_Pivots (), motion1->Get_Num_Pivots () ); - - for (int piv_idx=1; piv_idx < NumPivots; piv_idx++) { - - pivot = &Pivot[piv_idx]; - - assert(pivot->Parent != NULL); - Matrix3D::Multiply(pivot->Parent->Transform,pivot->BaseTransform,&(pivot->Transform)); - - if (piv_idx < num_anim_pivots) { - // interpolated translation - Vector3 trans0; - motion0->Get_Translation(trans0,piv_idx,frame0); - Vector3 trans1; - motion1->Get_Translation(trans1,piv_idx,frame1); - Vector3 lerped = (1.0 - percentage) * trans0 + (percentage) * trans1; - pivot->Transform.Translate(lerped * ScaleFactor); - - // interpolated rotation - Quaternion q0; - motion0->Get_Orientation(q0,piv_idx,frame0); - Quaternion q1; - motion1->Get_Orientation(q1,piv_idx,frame1); - Quaternion q; - Fast_Slerp(q,q0,q1,percentage); -#ifdef ALLOW_TEMPORARIES - pivot->Transform = pivot->Transform * Build_Matrix3D(q); -#else - pivot->Transform.postMul(Build_Matrix3D(q,mtx)); -#endif - - pivot->IsVisible = (motion0->Get_Visibility(piv_idx,frame0) || motion1->Get_Visibility(piv_idx,frame1)); - } - - if (pivot->Is_Captured()) - { - pivot->Capture_Update(); - pivot->IsVisible = true; - } - } -} - - - -/*********************************************************************************************** - * HTreeClass::Combo_Update -- compute each pivot's transform using an anim combo * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/98 GTH : Created. * - *=============================================================================================*/ -void HTreeClass::Combo_Update -( - const Matrix3D & root, - HAnimComboClass *anim -) -{ - PivotClass *pivot; - Matrix3D mtx; - - Pivot[0].Transform = root; - Pivot[0].IsVisible = true; - - int num_anim_pivots = 100000; - for ( int anim_num = 0; anim_num < anim->Get_Num_Anims(); anim_num++ ) { - num_anim_pivots = MIN( num_anim_pivots, anim->Peek_Motion( anim_num )->Get_Num_Pivots() ); - } - if ( num_anim_pivots == 100000 ) { - num_anim_pivots = 0; - } - - for (int piv_idx=1; piv_idx < NumPivots; piv_idx++) { - - pivot = &Pivot[piv_idx]; - assert(pivot->Parent != NULL); - Matrix3D::Multiply(pivot->Parent->Transform,pivot->BaseTransform,&(pivot->Transform)); - - if (piv_idx < num_anim_pivots) { - -#define ASSUME_NORMALIZED_ANIM_COMBO_WEIGHTS - - Vector3 trans(0,0,0); - Quaternion q0; - Quaternion q1; -#ifndef ASSUME_NORMALIZED_ANIM_COMBO_WEIGHTS - float last_weight = 0; -#endif - float weight_total = 0; - int wcount = 0; - - int anim_num = 0; - for ( ; anim_num < anim->Get_Num_Anims(); anim_num++ ) { - - HAnimClass *motion = anim->Get_Motion( anim_num ); - - if ( motion != NULL ) { - - float frame_num = anim->Get_Frame( anim_num ); - - PivotMapClass * pivot_map = anim->Get_Pivot_Weight_Map( anim_num ); - - //float *pivot_map = anim->Get_Pivot_Weight_Map( anim_num ); - - float weight = anim->Get_Weight( anim_num ); - - if ( pivot_map != NULL ) { - weight *= (*pivot_map)[piv_idx]; - // GREG - Pivot maps are ref counted so shouldn't we - // release the rivot map here? - pivot_map->Release_Ref(); - } - - if ( weight != 0.0 ) { - - wcount++; - Vector3 temp_trans; - motion->Get_Translation( temp_trans, piv_idx, frame_num ); - trans += weight * ScaleFactor * temp_trans; - weight_total += weight; - -#ifdef ASSUME_NORMALIZED_ANIM_COMBO_WEIGHTS - motion->Get_Orientation(q1,piv_idx, frame_num ); - if ( wcount == 1 ) { - q0 = q1; - } else { - Fast_Slerp(q0, q0, q1, weight / weight_total ); - } -#else - q0 = q1; - motion->Get_Orientation(q1, piv_idx, frame_num ); - last_weight = weight; -#endif - } - - motion->Release_Ref(); - - } - } - -#ifdef ASSUME_NORMALIZED_ANIM_COMBO_WEIGHTS - - if (weight_total != 0.0f ) { - // SKB: Removed assert because I have a case where I don't want normalization. - // One anim moves X, the other moves Y. Assert was just in to warn programmers. -// WWASSERT(WWMath::Fabs( weight_total - 1.0 ) < WWMATH_EPSILON); - - pivot->Transform.Translate(trans); -#ifdef ALLOW_TEMPORARIES - pivot->Transform = pivot->Transform * Build_Matrix3D(q0); -#else - pivot->Transform.postMul(Build_Matrix3D(q0,mtx)); -#endif - } -#else - if (( weight_total != 0.0f ) && (wcount >= 2)) { - - pivot->Transform.Translate( trans / weight_total ); - Quaternion q = Slerp_( q0, q1, last_weight / weight_total ); - pivot->Transform = pivot->Transform * Build_Matrix3D(q); - - } else if (weight_total != 0.0f) { - - pivot->Transform.Translate( trans / weight_total ); - pivot->Transform = pivot->Transform * Build_Matrix3D(q1); - } -#endif - - pivot->IsVisible = false; - - for ( anim_num = 0; (anim_num < anim->Get_Num_Anims()) && (!pivot->IsVisible); anim_num++ ) { - HAnimClass *motion = anim->Get_Motion( anim_num ); - if ( motion != NULL ) { - float frame_num = anim->Get_Frame( anim_num ); - - pivot->IsVisible |= motion->Get_Visibility(piv_idx,frame_num); - - motion->Release_Ref(); - } - } - } - - if (pivot->Is_Captured()) - { - pivot->Capture_Update(); - pivot->IsVisible = true; - } - } -} - - -/*********************************************************************************************** - * HTreeClass::Find_Bone -- Find a bone by name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/4/97 GTH : Created. * - *=============================================================================================*/ -int HTreeClass::Get_Bone_Index(const char * name) const -{ - for (int i=0; i < NumPivots; i++) { - if (stricmp(Pivot[i].Name,name) == 0) { - return i; - } - } - return 0; -} - - -/*********************************************************************************************** - * HTreeClass::Get_Bone_Name -- get the name of a bone from its index * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/4/97 GTH : Created. * - *=============================================================================================*/ -const char * HTreeClass::Get_Bone_Name(int boneidx) const -{ - assert(boneidx >= 0); - assert(boneidx < NumPivots); - - return Pivot[boneidx].Name; -} - - -/*********************************************************************************************** - * HTreeClass::Get_Parent_Index -- returns index of the parent of the given bone * - * * - * INPUT: * - * boneidx - the bone you are interested in * - * * - * OUTPUT: * - * the index of that bone's parent * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/12/2000 gth : Created. * - *=============================================================================================*/ -int HTreeClass::Get_Parent_Index(int boneidx) const -{ - assert(boneidx >= 0); - assert(boneidx < NumPivots); - - if (Pivot[boneidx].Parent != NULL) { - return Pivot[boneidx].Parent->Index; - } else { - return 0; - } -} - - -// Scale this HTree by a constant factor: -void HTreeClass::Scale(float factor) -{ - if (factor == 1.0f) return; - - // Scale pivot translations - for (int i = 0; i < NumPivots; i++) { - Matrix3D &pivot_transform = Pivot[i].BaseTransform; - Vector3 pivot_translation; - pivot_transform.Get_Translation(&pivot_translation); - pivot_translation *= factor; - pivot_transform.Set_Translation(pivot_translation); - } - - // Set state used later to scale animations: - ScaleFactor *= factor; -} - - - -void HTreeClass::Capture_Bone(int boneindex) -{ - assert(boneindex >= 0); - assert(boneindex < NumPivots); -#ifdef LAZY_CAP_MTX_ALLOC - if (Pivot[boneindex].CapTransformPtr == NULL) - { - Pivot[boneindex].CapTransformPtr = MSGW3DNEW("PivotClassCaptureBoneMtx") DynamicMatrix3D; - Pivot[boneindex].CapTransformPtr->Mat.Make_Identity(); - } -#else - Pivot[boneindex].IsCaptured = true; -#endif -} - -void HTreeClass::Release_Bone(int boneindex) -{ - assert(boneindex >= 0); - assert(boneindex < NumPivots); -#ifdef LAZY_CAP_MTX_ALLOC - if (Pivot[boneindex].CapTransformPtr) - { - delete Pivot[boneindex].CapTransformPtr; - Pivot[boneindex].CapTransformPtr = NULL; - } -#else - Pivot[boneindex].IsCaptured = false; -#endif -} - -bool HTreeClass::Is_Bone_Captured(int boneindex) const -{ - assert(boneindex >= 0); - assert(boneindex < NumPivots); - return Pivot[boneindex].Is_Captured(); -} - -void HTreeClass::Control_Bone(int boneindex,const Matrix3D & relative_tm,bool world_space_translation) -{ - assert(boneindex >= 0); - assert(boneindex < NumPivots); - assert(Pivot[boneindex].Is_Captured()); - -#ifdef LAZY_CAP_MTX_ALLOC - if (Pivot[boneindex].CapTransformPtr == NULL) - return; - Pivot[boneindex].WorldSpaceTranslation = world_space_translation; - Pivot[boneindex].CapTransformPtr->Mat = relative_tm; -#else - Pivot[boneindex].WorldSpaceTranslation = world_space_translation; - Pivot[boneindex].CapTransform = relative_tm; -#endif -} - -void HTreeClass::Get_Bone_Control(int boneindex, Matrix3D & relative_tm) const -{ - assert(boneindex >= 0); - assert(boneindex < NumPivots); - - // - // Return the bone's control transform to the caller - // - if (Pivot[boneindex].IsCaptured) { - relative_tm = Pivot[boneindex].CapTransform; - } else { - relative_tm.Make_Identity (); - } - - return ; -} - -HTreeClass * HTreeClass::Alter_Avatar_HTree( const HTreeClass *tree, Vector3 &scale) -{ - // This is a specific list of pivot names used in the avatar meshes that we need to special case for scaling - // The reason is due to the fact that we want to scale the avatar's bone structure with differing amount for - // each axis, and with the T-pos of the avatar skeleton, undesirable results are caused due to the arms and hands - // being stretched out on the Y-axis instead of the Z-axis like the rest of the bodies. Hence, the list of pivots - // below are ones that I will special case and scale them based on the Z-axis scaling factor instead of the Y-axis - // scaling factor. - const char * flip_list[] = { " RIGHTFOREARM", " RIGHTHAND", " LEFTFOREARM", " LEFTHAND", "RIGHTINDEX", "RIGHTFINGERS", "RIGHTTHUMB", "LEFTINDEX", "LEFTFINGERS", "LEFTTHUMB", 0 }; - - // Clone the new tree with the tree that is passed in - HTreeClass * new_tree = new HTreeClass( *tree ); - - // Go through each of the pivots and calculate and transform the pivots to match the desired scaling factor - for(int pi = 0; pi < new_tree->NumPivots; ++pi) { - PivotClass piv = tree->Pivot[pi]; - Vector3 adjusted_scale = scale; - - // If there is no parent, skip - if(!piv.Parent) continue; - - // If the pivot is on the flip list, use the Z scale to scale both the Z & Y axis - int index = 0; - while(true) { - if(!flip_list[index]) { - break; - } else if(strcmp(piv.Name, flip_list[index]) == 0) { - adjusted_scale.Y = scale.Z; - break; - } - ++index; - } - - // Get the positions of the pivot and the pivot's parent in worldspace & apply the altering scale to it - Vector3 pivot_pos = piv.Transform.Get_Translation(); - Vector3 pivot_parent_pos = piv.Parent->Transform.Get_Translation(); - pivot_pos.Scale(adjusted_scale); - pivot_parent_pos.Scale(adjusted_scale); - - // Get the pivot's parent's inverse transform - Matrix3D parent_inverse_transform; - piv.Parent->Transform.Get_Inverse(parent_inverse_transform); - - // Get the new desired vector in worldspace - Vector3 new_relative_vector = pivot_pos - pivot_parent_pos; - - // Rotate the new vector by the pivot's parent's inverse transform to put it in local space - new_relative_vector = parent_inverse_transform.Rotate_Vector(new_relative_vector); - - // Store the final result in the new HTree - new_tree->Pivot[pi].BaseTransform.Set_Translation( new_relative_vector ); - } - - return new_tree; -} - -// Morph the bones on the HTree using weights from a number of other HTrees -HTreeClass * HTreeClass::Create_Morphed( int num_morph_sources, - const float morph_weights[], - const HTreeClass *tree_array[] ) -{ - int i; - assert(num_morph_sources>0); - for(i=0;i=0.0f && morph_weights[i]<=1.0f ); - } - for(i=0;iNumPivots == tree_array[i+1]->NumPivots ); - } - - // Clone the first one, - HTreeClass * new_tree = W3DNEWARRAY HTreeClass( *tree_array[0] ); - - // Then interpolate all the pivots translations - for (int pi = 0; pi < new_tree->NumPivots; pi++) { - - Vector3 pos(0.0f,0.0f,0.0f); - for(int nm = 0; nm < num_morph_sources; nm++) { - pos.X += tree_array[nm]->Pivot[pi].BaseTransform.Get_Translation().X*morph_weights[nm]; - pos.Y += tree_array[nm]->Pivot[pi].BaseTransform.Get_Translation().Y*morph_weights[nm]; - pos.Z += tree_array[nm]->Pivot[pi].BaseTransform.Get_Translation().Z*morph_weights[nm]; - } - - new_tree->Pivot[pi].BaseTransform.Set_Translation( pos ); - } - - return new_tree; -} - -// Create an HTree by Interpolating between others -HTreeClass * HTreeClass::Create_Interpolated( const HTreeClass * tree_a0_b0, - const HTreeClass * tree_a0_b1, - const HTreeClass * tree_a1_b0, - const HTreeClass * tree_a1_b1, - float lerp_a, float lerp_b ) -{ - assert( tree_a0_b0->NumPivots == tree_a0_b1->NumPivots ); - assert( tree_a0_b0->NumPivots == tree_a1_b0->NumPivots ); - assert( tree_a0_b0->NumPivots == tree_a1_b1->NumPivots ); - - // Clone the first one, - HTreeClass * new_tree = W3DNEW HTreeClass( *tree_a0_b0 ); - - // Then interpolate all the pivots translations - Vector3 pos_a0, pos_a1, pos; - for (int pi = 0; pi < new_tree->NumPivots; pi++) { - - Vector3::Lerp( tree_a0_b0->Pivot[pi].BaseTransform.Get_Translation(), - tree_a0_b1->Pivot[pi].BaseTransform.Get_Translation(), - lerp_b, &pos_a0 ); - Vector3::Lerp( tree_a1_b0->Pivot[pi].BaseTransform.Get_Translation(), - tree_a1_b1->Pivot[pi].BaseTransform.Get_Translation(), - lerp_b, &pos_a1 ); - Vector3::Lerp( pos_a0, pos_a1, lerp_a, &pos ); - - new_tree->Pivot[pi].BaseTransform.Set_Translation( pos ); - } - - return new_tree; -} - -// Create an HTree by Interpolating between others -HTreeClass * HTreeClass::Create_Interpolated(const HTreeClass * tree_base, - const HTreeClass * tree_a, - const HTreeClass * tree_b, - float a_scale, float b_scale ) -{ - WWMEMLOG(MEM_ANIMATION); - assert( tree_base->NumPivots == tree_a->NumPivots ); - assert( tree_base->NumPivots == tree_b->NumPivots ); - - // Clone the first one, - HTreeClass * new_tree = W3DNEW HTreeClass( *tree_base ); - - float a_scale_abs = WWMath::Fabs( a_scale ); - float b_scale_abs = WWMath::Fabs( b_scale ); - - if ( a_scale_abs + b_scale_abs > 0 ) { - - // Then interpolate all the pivots translations - Vector3 pos_a, pos_b, pos; - for (int pi = 0; pi < new_tree->NumPivots; pi++) { - - Vector3::Lerp( tree_base->Pivot[pi].BaseTransform.Get_Translation(), - tree_a->Pivot[pi].BaseTransform.Get_Translation(), - a_scale, &pos_a ); - Vector3::Lerp( tree_base->Pivot[pi].BaseTransform.Get_Translation(), - tree_b->Pivot[pi].BaseTransform.Get_Translation(), - b_scale, &pos_b ); - - pos = (pos_a * a_scale_abs + pos_b * b_scale_abs ) / ( a_scale_abs + b_scale_abs ); - - new_tree->Pivot[pi].BaseTransform.Set_Translation( pos ); - } - } - - return new_tree; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/htree.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/htree.h deleted file mode 100644 index e022194833..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/htree.h +++ /dev/null @@ -1,212 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/htree.h 6 10/01/01 5:55p Patrick $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/htree.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 9/28/01 3:05p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef HTREE_H -#define HTREE_H - -#include "always.h" -#include "pivot.h" -#include "quat.h" -#include "matrix3d.h" -#include "vector3.h" -#include "w3d_file.h" -#include "wwdebug.h" - -class HAnimClass; -class HAnimComboClass; -class MeshClass; -class ChunkLoadClass; -class ChunkSaveClass; -class HRawAnimClass; - -/* - - HTreeClass - - A hierarchy of coordinate systems in an initial - configuration. All motion data is applied to one - of these objects. Motion is stored as deltas from - the hierarchy tree's initial configuration. - - Normally, the user will probably not deal with - HTreeClasses; they are used internally - by the HierarchyModelClass. - -*/ -class HTreeClass : public W3DMPO -{ - W3DMPO_GLUE(HTreeClass) -public: - - enum - { - OK, - LOAD_ERROR - }; - - HTreeClass(void); - HTreeClass(const HTreeClass & src); - ~HTreeClass(void); - - int Load_W3D(ChunkLoadClass & cload); - void Init_Default(void); - - WWINLINE const char * Get_Name(void) const { return Name; } - WWINLINE int Num_Pivots(void) const { return NumPivots; } - int Get_Bone_Index(const char * name) const; - const char * Get_Bone_Name(int boneid) const; - int Get_Parent_Index(int bone_indx) const; - - void Base_Update(const Matrix3D & root); - - void Anim_Update( const Matrix3D & root, - HAnimClass * motion, - float frame); - void Anim_Update(const Matrix3D & root,HRawAnimClass * motion,float frame); - - void Blend_Update( const Matrix3D & root, - HAnimClass * motion0, - float frame0, - HAnimClass * motion1, - float frame1, - float percentage); - - void Combo_Update( const Matrix3D & root, - HAnimComboClass * anim); - - WWINLINE const Matrix3D & Get_Transform(int pivot) const; - WWINLINE bool Get_Visibility(int pivot) const; - - WWINLINE const Matrix3D & Get_Root_Transform(void) const; - - // User control over a bone. While a bone is captured, you can over-ride the - // animation transform used by the bone. - void Capture_Bone(int boneindex); - void Release_Bone(int boneindex); - bool Is_Bone_Captured(int boneindex) const; - void Control_Bone(int boneindex,const Matrix3D & relative_tm,bool world_space_translation = false); - void Get_Bone_Control(int boneindex, Matrix3D & relative_tm) const; - - - - // - // Simple pivot evaluation methods for when the caller doesn't want - // to update the whole animation, but needs to know the transform of - // a pivot at a given frame. - // - bool Simple_Evaluate_Pivot (HAnimClass *motion, int pivot_index, float frame, const Matrix3D &obj_tm, Matrix3D *end_tm) const; - bool Simple_Evaluate_Pivot (int pivot_index, const Matrix3D &obj_tm, Matrix3D *end_tm) const; - - // Scale this HTree by a constant factor: - void Scale(float factor); - - // Morph the bones on the HTree based on the scale passed in - static HTreeClass * Alter_Avatar_HTree( const HTreeClass *tree, Vector3 &scale ); - - // Morph the bones on the HTree using weights from a number of other HTrees - static HTreeClass * Create_Morphed( int num_morph_sources, - const float morph_weights[], - const HTreeClass *tree_array[] ); - - // Create an HTree by Interpolating between others - static HTreeClass * Create_Interpolated( const HTreeClass * tree_a0_b0, - const HTreeClass * tree_a0_b1, - const HTreeClass * tree_a1_b0, - const HTreeClass * tree_a1_b1, - float lerp_a, float lerp_b ); - - // Create an HTree by Interpolating between others - static HTreeClass * Create_Interpolated( const HTreeClass * tree_base, - const HTreeClass * tree_a, - const HTreeClass * tree_b, - float a_scale, float b_scale ); - -private: - - char Name[W3D_NAME_LEN]; - int NumPivots; - PivotClass * Pivot; - float ScaleFactor; - - void Free(void); - bool read_pivots(ChunkLoadClass & cload,bool pre30); - - friend class MeshClass; - - - -}; - -WWINLINE const Matrix3D & HTreeClass::Get_Root_Transform(void) const -{ - return Pivot[0].Transform; -} - -WWINLINE bool HTreeClass::Get_Visibility(int pivot) const -{ - WWASSERT(pivot >= 0); - WWASSERT(pivot < NumPivots); - return Pivot[pivot].IsVisible; -} - -/*********************************************************************************************** - * HTreeClass::Get_Transform -- returns the transformation for the desired pivot * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE const Matrix3D & HTreeClass::Get_Transform(int pivot) const -{ - assert(pivot >= 0); - assert(pivot < NumPivots); - - return Pivot[pivot].Transform; -} - - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.cpp deleted file mode 100644 index f912b600ae..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.cpp +++ /dev/null @@ -1,443 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/intersec.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 2/06/01 5:41p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#include "intersec.h" -#include "camera.h" -#include "scene.h" -#include "intersec.inl" - - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -// these statics are used for single-threaded use of the IntersectionClass ONLY -Vector3 IntersectionClass::_RayLocation(0,0,0); -Vector3 IntersectionClass::_RayDirection(0,0,0); -Vector3 IntersectionClass::_IntersectionNormal(0,0,0); - - -bool IntersectionClass::Intersect_Screen_Point_RenderObject(float screen_x, float screen_y, const LayerClass &Layer, RenderObjClass *RObj, IntersectionResultClass *FinalResult) -{ - Get_Screen_Ray(screen_x, screen_y, Layer); - return Intersect_RenderObject(RObj, FinalResult); -} - -bool IntersectionClass::Intersect_RenderObject(RenderObjClass *RObj, IntersectionResultClass *FinalResult) -{ - if(FinalResult == 0) - FinalResult = &Result; - - return RObj->Intersect(this, FinalResult); -} - -// iterate through the layers of a world, front to back, returning true if/when an intersection -// with an object occurs. -bool IntersectionClass::Intersect_Screen_Point_Layer_Range -( - float screen_x, - float screen_y, - const LayerClass &TopLayer, - const LayerClass &BackLayer -) -{ - - // intersect from front layer to back layers. An intersection with an object - // in any layer is assumed to be in front of any potential intersections in layers - // below it. - - // find the last layer in the list - const LayerClass *Layer = &TopLayer; - - // iterate through all layers in list - while(Layer->Is_Valid()) { - if(Intersect_Screen_Point_Layer(screen_x, screen_y, *Layer)) - return true; - - // if this is the back layer then that is all we need to test - if(Layer == &BackLayer) - return false; - - Layer = Layer->Next(); - } - return false; -} - - -bool IntersectionClass::Intersect_Screen_Point_Layer(float screen_x, float screen_y, const LayerClass &Layer) -{ - // mark this object as not intersecting yet - Result.Intersects = false; - - // first, do a test to make sure the screen coords are within the rendering area for this layer. - const ViewportClass &v = Layer.Camera->Get_Viewport(); - - if((screen_x < v.Min.X) || - (screen_x > v.Max.X) || - (screen_y < v.Min.Y) || - (screen_y > v.Max.Y)) - return false; - - Result.Range = Layer.Camera->Get_Depth(); //scene->depth * scene->zstop; - - // get the ray for these screen coordinates - Get_Screen_Ray(screen_x, screen_y, Layer); - - return Intersect_Layer(Layer, false); -} - -bool IntersectionClass::Intersect_Layer(const LayerClass &Layer, bool Test_All) -{ - IntersectionResultClass FinalResult; - - Result.Intersects = false; - - SceneIterator *it = Layer.Scene->Create_Iterator(!Test_All); - - // select the first object - it->First(); - - // loop through all render objects in this layer: - while(!it->Is_Done()) { - - // get the render object - RenderObjClass * robj = it->Current_Item(); - it->Next(); - - // only intersect if it was visible or if we must test all in layer - // Added 'Generals' code to only detect intersection on matching Collision_Type. MW - if( robj->Get_Collision_Type() & Result.CollisionType && (Test_All || robj->Is_Really_Visible()) && robj->Intersect(this, &FinalResult)) { - if(FinalResult.Range < Result.Range) { - Copy_Results(&FinalResult); - } - } - } - - Layer.Scene->Destroy_Iterator(it); - - return Result.Intersects; -} - - -void IntersectionClass::Append_Object_Array( - int MaxCount, - int &CurrentCount, - RenderObjClass **ObjectArray, - RenderObjClass *Object) -{ - if(CurrentCount < MaxCount) { - ObjectArray[CurrentCount] = Object; - CurrentCount++; - return; - } - WWDEBUG_SAY(("IntersectionClass::Append_Object_Array - Too many objects\n")); -} - -// determines if specified plane-intersection point (co-planar with polygon) is within the the passed polygon. -// If Interpolated_Normal is specified, it will interpolate the normal for the intersection point -// note: Polygon normal MUST BE CORRECT - -// this will return true if the ray intersects the specified box -// sets the point of intersection within the Request->Result.Intersection vector -bool IntersectionClass::Intersect_Box(Vector3 &Box_Min, Vector3 &Box_Max, IntersectionResultClass *FinalResult) { - // Fast Ray-Box Intersection, modified from code written by Andrew Woo from "Graphics Gems", Academic Press, 1990 - - enum { - RIGHT = 0, - LEFT, - MIDDLE, - PLANE_COUNT - }; - - bool inside = true; - char quadrant[PLANE_COUNT]; - int counter; - float distance[PLANE_COUNT]; - float candidate_plane[PLANE_COUNT]; - - register Vector3 *intersection = &FinalResult->Intersection; - - // Find candidate planes and determine if the ray is outside the box - for (counter = 0; counter < PLANE_COUNT; counter++) { - if((*RayLocation)[counter] < Box_Min[counter]) { - quadrant[counter] = LEFT; - candidate_plane[counter] = Box_Min[counter]; - inside = false; - } else { - if ((*RayLocation)[counter] > Box_Max[counter]) { - quadrant[counter] = RIGHT; - candidate_plane[counter] = Box_Max[counter]; - inside = false; - } else { - quadrant[counter] = MIDDLE; - } - } - } - - // check to see if the ray origin is inside bounding box - if(inside) { - *intersection = *RayLocation; - return FinalResult->Intersects = true; - } - - // Calculate distances to candidate planes - for (counter = 0; counter < PLANE_COUNT; counter++) { - if ((quadrant[counter] != MIDDLE) && ((*RayDirection)[counter] != 0.0f)) - distance[counter] = (candidate_plane[counter] - (*RayLocation)[counter]) / (*RayDirection)[counter]; - else - distance[counter] = -1.0f; - } - - // get the largest of the distances for final choice of intersection - int nearest_plane = 0; - for (counter = 1; counter < PLANE_COUNT; counter++) { - if (distance[nearest_plane] < distance[counter]) - nearest_plane = counter; - } - - // Check to make sure the nearest plane is not behind the ray (inside box tested above) - if (distance[nearest_plane] < 0.0f) - return FinalResult->Intersects = false; - - for (counter = 0; counter < PLANE_COUNT; counter++) { - if (nearest_plane != counter) { - (*intersection)[counter] = (*RayLocation)[counter] + distance[nearest_plane] *(*RayDirection)[counter]; - if ((*intersection)[counter] < Box_Min[counter] || (*intersection)[counter] > Box_Max[counter]) - return FinalResult->Intersects = false; - } else { - (*intersection)[counter] = candidate_plane[counter]; - } - } - return FinalResult->Intersects = true; // ray hits box -} - - -// simply returns true if a ray hits the bounding sphere of any node in a hierarchy -// note: Result will only contain range, not the intersection point/normal. -bool IntersectionClass::Intersect_Hierarchy_Sphere_Quick(RenderObjClass *Hierarchy, IntersectionResultClass *FinalResult) -{ - - int counter = Hierarchy->Get_Num_Sub_Objects(); - while(counter--) { - RenderObjClass *obj = Hierarchy->Get_Sub_Object(counter); - obj->Release_Ref(); // you already own a reference to this object indirectly.. - if(obj->Intersect_Sphere_Quick(this, FinalResult)) - return true; - } - return false; -} - -// returns true if a ray hits the bounding sphere of any node in a hierarchy -// note: Result will contain range and the intersection point/normal. -bool IntersectionClass::Intersect_Hierarchy_Sphere(RenderObjClass *Hierarchy, IntersectionResultClass *FinalResult) { - - int counter = Hierarchy->Get_Num_Sub_Objects(); - while(counter--) { - RenderObjClass *obj = Hierarchy->Get_Sub_Object(counter); - obj->Release_Ref(); // you already own a reference to this object indirectly.. - if(obj->Intersect_Sphere(this, FinalResult)) - return true; - } - return false; -} - -void IntersectionClass::Append_Hierarchy_Objects( - int MaxCount, - int &CurrentCount, - RenderObjClass **ObjectArray, - RenderObjClass *Hierarchy, - bool Test_Bounding_Sphere, - bool Convex) -{ - IntersectionResultClass result; - - // first check the bounding spheres for hits (if specified) - int counter = Hierarchy->Get_Num_Sub_Objects(); - if(Test_Bounding_Sphere) { - while(counter--) { - RenderObjClass *obj = Hierarchy->Get_Sub_Object(counter); - obj->Release_Ref(); // you already own a reference to the object indirectly - if(obj->Intersect_Sphere_Quick(this, &result)) { - Append_Object_Array(MaxCount, CurrentCount, ObjectArray, obj); -// OutputDebugString("o"); // this shows one o per sphere intersection - } else { -// OutputDebugString("."); // this shows one . per sphere miss - } - } - - } else { - // simply copy the pointers into the array - while(counter--) { - RenderObjClass *obj = Hierarchy->Get_Sub_Object(counter); - Append_Object_Array(MaxCount, CurrentCount, ObjectArray, obj); - obj->Release_Ref(); // you already own a reference to this object indirectly.. - } - } -} - -bool IntersectionClass::Intersect_Hierarchy(RenderObjClass *Hierarchy, IntersectionResultClass *FinalResult, bool Test_Bounding_Sphere, bool Convex ) { - -// OutputDebugString("\n"); -// return FinalResult->Intersects = false; - - RenderObjClass *candidate_objects[MAX_HIERARCHY_NODE_COUNT]; - int candidate_count = 0; - - Append_Hierarchy_Objects(MAX_HIERARCHY_NODE_COUNT, candidate_count, candidate_objects, Hierarchy, Test_Bounding_Sphere, Convex); - - // make sure there's at least one sphere hit before continuing to more expensive tests below.. - if(candidate_count == 0) { - // OutputDebugString("/"); // no sphere intersections - return FinalResult->Intersects = false; - } - - // note: Test_Bounding_Sphere argument is false because the Append_Hierarchy_Objects will have - // already performed that test if indicated. - if(Intersect_Object_Array(candidate_count, candidate_objects, FinalResult, false, Convex)) { - return true; - } - return false; -} - -RenderObjClass *IntersectionClass::Intersect_Sub_Object(float screenx, float screeny, LayerClass &layer, RenderObjClass *robj, IntersectionResultClass *result) -{ - if (robj->Get_Num_Sub_Objects()) { - for (int lp = 0; lp < robj->Get_Num_Sub_Objects(); lp++) { - RenderObjClass *sub = robj->Get_Sub_Object(lp); - RenderObjClass *retval = Intersect_Sub_Object(screenx, screeny, layer, sub, result); - sub->Release_Ref(); - if (retval) return retval; - } - } - if (Intersect_Screen_Point_RenderObject(screenx, screeny, layer, robj, result)) { - return robj; - } - return NULL; -} - -// finds the intersection of the nearest object in the array. -// This will usually be the last stage after determining potential intersections -// using Intersect_Sphere_Quick() and adding hits to the array for this -// more accurate test, as done in Intersect_Heirarchy(). -bool IntersectionClass::Intersect_Object_Array( - int Object_Count, - RenderObjClass **ObjectArray, - IntersectionResultClass *FinalResult, - bool Test_Bounding_Sphere, - bool Convex - ) -{ - IntersectionResultClass TemporaryResults[MAX_HIERARCHY_NODE_COUNT]; - assert(Object_Count <= MAX_HIERARCHY_NODE_COUNT); - return Intersect_Object_Array(Object_Count, ObjectArray, FinalResult, TemporaryResults, Test_Bounding_Sphere, Convex); -} - -bool IntersectionClass::Intersect_Object_Array( - int Object_Count, - RenderObjClass **ObjectArray, - IntersectionResultClass *FinalResult, - IntersectionResultClass *TemporaryResults, - bool Test_Bounding_Sphere, - bool Convex - ) -{ - // Determine ranges for all intersections - IntersectionClass temp(this); - int counter = Object_Count; - bool hit = false; - - // if it's a convex hierarchy (ie a control panel) then find the first hit otherwise use the more expensive exact intersection routine - // for use with potentially concave hierarchies. - int nearest_index = -1; - if(ConvexTest || Convex) { - if(Test_Bounding_Sphere) { - while(counter--) { - if(ObjectArray[counter]->Intersect_Sphere_Quick(this, &TemporaryResults[counter])) { - hit = ObjectArray[counter]->Intersect(this, FinalResult); - } - if(hit) { - nearest_index = counter; - counter = 0; - } - } - } else { - while(counter--) { - hit = ObjectArray[counter]->Intersect(this, FinalResult); - if(hit) { - nearest_index = counter; - counter = 0; - } - } - } - } else { - if(Test_Bounding_Sphere) { - while(counter--) { - if(ObjectArray[counter]->Intersect_Sphere_Quick(this, &TemporaryResults[counter])) { - hit |= ObjectArray[counter]->Intersect(this, &TemporaryResults[counter]); - } - } - } else { - while(counter--) { - hit |= ObjectArray[counter]->Intersect(this, &TemporaryResults[counter]); - } - } - } - // test to see if anything actually hit a mesh - if( ! hit ) { -// OutputDebugString("!"); // no mesh intersections - return FinalResult->Intersects = false; - } - - if(! (Convex || ConvexTest)) { - // now find the nearest of the actual hits - float nearest_range = (float) (2<<28); - counter = Object_Count; - while(counter--) { - if(TemporaryResults[counter].Intersects && (nearest_range > TemporaryResults[counter].Range)) { - nearest_index = counter; - nearest_range = TemporaryResults[counter].Range; - } - } - Copy_Results(FinalResult, &TemporaryResults[nearest_index]); - } -// OutputDebugString("+"); -// Debug.Print("Mesh ", Object_Array[nearest_index]); -// Intersection_Node = candidate_indices[nearest_index]; - return true; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.h deleted file mode 100644 index 770625ae29..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.h +++ /dev/null @@ -1,404 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/intersec.h $* - * * - * $Author:: Naty_h $* - * * - * $Modtime:: 3/28/01 11:29a $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -/* - - Most of the functions of this class are inline functions and if you use them you will need - to include . - - Exceptions to this are the functions most commonly used by render objects: - - - - The constructors/destructors are inline & implemented here. - -*/ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef INTERSEC_H -#define INTERSEC_H - -#include "always.h" -#include "matrix3d.h" -#include "layer.h" -#include "sphere.h" -#include "coltype.h" - - -class RenderObjClass; -typedef unsigned short POLYGONINDEX; - - -/* -** -*/ -class IntersectionResultClass -{ -public: - RenderObjClass * IntersectedRenderObject; - POLYGONINDEX IntersectedPolygon; - - Matrix3D ModelMatrix; // this is required for transforming mesh normals from model coords - Vector3 ModelLocation; // ditto - Vector3 Intersection; // location of intersection is placed here - - float Range; // distance from ray to point of intersection - float Alpha, Beta; // stored for use by Process_Intersection_Results() - used to interpolate normal across a polygon - bool Intersects; // could be in the intersection_type, but it is used in a number of bool operations - int CollisionType; // mask for which object types to intersect with (added for 'Generals'. MW) - - enum INTERSECTION_TYPE { - NONE = 0, - GENERIC, - POLYGON - } IntersectionType; -}; - - -class IntersectionClass -{ - // member data - -public: - enum { - MAX_POLY_INTERSECTION_COUNT = 1000, // arbitrary size of stack array used for storing intersection results within Intersect_Mesh(). Non-recursive function. - MAX_HIERARCHY_NODE_COUNT = 256 - }; - - // this structure is used to store all intersections on the stack for sorting before - // copying the nearest intersection to IntersectionClassObject->Result. - // note: the convex intersection functions return with the first intersection results. - - Vector3 *RayLocation; // note: these pointers must be Set() to valid pointers by external code - Vector3 *RayDirection; - Vector3 *IntersectionNormal; // if non-zero then Process_Intersection_Results() will place the (perhaps vertex interpolated) surface normal here. - - // 2d screen coordinates for use by Intersect_Screen_Point...() routines. - float ScreenX, ScreenY; - - // if true, then interpolate the normal for a polygon intersection from the vertex normals. - // note: intersection routines below which take a FinalResult argument do not interpolate - // the normal since they are intended to be used to find the nearest of several intersections - // and interpolating the normal for intersections that are tossed would be wasteful. - // If you need the normal interpolated in that case anyways then call Interpolate_Normal(). - bool InterpolateNormal; - - // if true, then perform potentially much faster convex intersection test which will return - // the first valid intersection. Generally used for producing silhouettes. - // If true, all intersections will be convex tests. If false, test mode will be determined (generally) - // by the render object or whatever called the intersection functions and passes the Convex argument. - bool ConvexTest; - - // do not consider intersections beyond this range as an intersection. - // Note: Get_Screen_Ray sets this to scene->zstop. - float MaxDistance; - - // final intersection results are contained here - IntersectionResultClass Result; - - // - // Implementation - // - - // configures the member data to use the passed pointers - inline void Set(Vector3 *location, Vector3 *direction, Vector3 *intersection_normal, bool interpolate_normal, float max_distance, bool convex_test = false) - { - RayLocation = location; - RayDirection = direction; - IntersectionNormal = intersection_normal; - InterpolateNormal = interpolate_normal; - MaxDistance = max_distance; - ConvexTest = convex_test; - } - - - - // this constructor uses static variables for the location/direction/normal variables - // so can be only used one thread at a time unless the Set() function is used to - // set them to private vector3's - inline IntersectionClass() - : ConvexTest(false) - { - RayLocation = &_RayLocation; - RayDirection = &_RayDirection; - IntersectionNormal = &_IntersectionNormal; - Result.CollisionType=COLL_TYPE_ALL; //added for 'Generals'. MW - } - - - // This will be the most commonly used constructor - inline IntersectionClass(Vector3 *location, Vector3 *direction, Vector3 *intersection_normal, bool interpolate_normal = false, float max_distance = WWMATH_FLOAT_MAX, bool convex_test = false) - { - Set(location, direction, intersection_normal, interpolate_normal, max_distance, convex_test); - } - - - virtual ~IntersectionClass() {} - - - // this copy routine is used when the model coords are needed to be copied along with the other information. - inline void Copy_Results(IntersectionResultClass *Destination, IntersectionResultClass *Source) { - Destination->ModelMatrix = Source->ModelMatrix; - Destination->ModelLocation = Source->ModelLocation; - Copy_Partial_Results(Destination, Source); - Destination->IntersectedRenderObject = Source->IntersectedRenderObject; - } - - - inline void Copy_Results(IntersectionResultClass *Source) { - Copy_Results(&Result, Source); - } - - - // this is called only for the nearest intersection. If the request passes a Interpolated_Normal pointer then it will be calculated. - // otherwise the results are copied into the request structure. - // This does not copy the matrix or location members; it is intended to be used during poly testing - // where these values are identical between results, or as a completion function for Copy_Results() - inline void Copy_Partial_Results(IntersectionResultClass *Destination, IntersectionResultClass *Source) - { - Destination->IntersectedPolygon = Source->IntersectedPolygon; - Destination->Intersection = Source->Intersection; - Destination->Range = Source->Range; - Destination->Alpha = Source->Alpha; - Destination->Beta = Source->Beta; - Destination->Intersects = true; - Destination->IntersectionType = Source->IntersectionType; - } - - - // used for creating temporary copies - inline IntersectionClass(IntersectionClass *source) - { - *this = source; - } - - - inline IntersectionClass *operator =(IntersectionClass *source) - { - Set(source->RayLocation, source->RayDirection, source->IntersectionNormal, source->InterpolateNormal, source->MaxDistance, source->ConvexTest); - Copy_Results(&source->Result); - return this; - } - - - - // find the range to the intersection of the ray and sphere (if any) - // note: Intersection_Request->RayDirection must be a unit vector - // To find the actual intersection location and perhaps the intersection normal, use Intersection_Sphere() instead. - // loosly based on code found in Graphics Gems I, p388 - // this will only set the result's range if intersection occurs; it is intended to be used as a first pass intersection test - // before intersecting the mesh polygons itself. - // Note: Does NOT do Max_Distance testing - inline bool Intersect_Sphere_Quick(SphereClass &Sphere, IntersectionResultClass *FinalResult) - { - // make a unit vector from the ray origin to the sphere center - Vector3 sphere_vector(Sphere.Center - *RayLocation); - - // get the dot product between the sphere_vector and the ray vector - FinalResult->Alpha = Vector3::Dot_Product(sphere_vector, *RayDirection); - - FinalResult->Beta = Sphere.Radius * Sphere.Radius - (Vector3::Dot_Product(sphere_vector, sphere_vector) - FinalResult->Alpha * FinalResult->Alpha); - - if(FinalResult->Beta < 0.0f) { - return FinalResult->Intersects = false; - } - return FinalResult->Intersects = true; - } - - - // this will find the intersection with the sphere and the intersection normal if needed. - inline bool Intersect_Sphere(SphereClass &Sphere, IntersectionResultClass *FinalResult) - { - if(!Intersect_Sphere_Quick(Sphere, FinalResult)) - return false; - - // determine range to intersection based on stored alpha/beta values - float d = sqrtf(FinalResult->Beta); - FinalResult->Range = FinalResult->Alpha - d; - - if(FinalResult->Range > MaxDistance) return false; - - FinalResult->Intersection = *RayLocation + FinalResult->Range * (*RayDirection); - - if(IntersectionNormal != 0) { - (*IntersectionNormal) = FinalResult->Intersection - Sphere.Center; - } - return true; - } - - - // inline declarations - // Usage of these functions requires including intersec.inl - - // determine location & direction for projected screen coordinate ray - inline void Get_Screen_Ray(float ScreenX, float ScreenY, const LayerClass &Layer); - - // uses the Result's range & the Ray_Direction to calculate the actual point of intersection. - inline void Calculate_Intersection(IntersectionResultClass *Result); - - // interpolate the normal for a polygon intersection. Will ONLY work for polygon intersections, - // and the Results.Intersection_Data must refer to a polygon with a valid ->mesh pointer. - inline void Interpolate_Intersection_Normal(IntersectionResultClass *FinalResult); - - // various methods for performing intersections. - inline bool Intersect_Plane(IntersectionResultClass *Result, Vector3 &Plane_Normal, Vector3 &Plane_Point); - inline bool Intersect_Plane_Quick(IntersectionResultClass *Result, Vector3 &Plane_Normal, Vector3 &Plane_Point); - inline bool Intersect_Polygon(IntersectionResultClass *Result, Vector3 &PolygonNormal, Vector3 &v1, Vector3 &v2, Vector3 &v3); - inline bool Intersect_Polygon(IntersectionResultClass *Result, Vector3 &v1, Vector3 &v2, Vector3 &v3); - inline bool Intersect_Polygon_Z(IntersectionResultClass *Result, Vector3 &PolygonNormal, Vector3 &v1, Vector3 &v2, Vector3 &v3); - - /* - ** This function will fill the passed array with the set of points & uv values that represent - ** the boolean operation of the anding of the ClipPoints with the TrianglePoints. The UV values - ** provided for the TrianglePoints triangle are used to generate accurate UV values for any - ** new points created by this operation. - ** The clipped points have Z values that make them sit on the ClipPoints triangle plane. - */ - static inline int _Intersect_Triangles_Z( - Vector3 ClipPoints[3], - Vector3 TrianglePoints[3], - Vector2 UV[3], - Vector3 ClippedPoints[6], - Vector2 ClippedUV[6] - ); - - /* - ** This function will find the z elevation for the passed Vector3 whose x/y components - ** are defined, using the specified vertex & surface normal to determine the correct value - */ - static inline float _Get_Z_Elevation(Vector3 &Point, Vector3 &PlanePoint, Vector3 &PlaneNormal); - - - // test a 2d screen area with the intersection's screen coords, assigning a GENERIC intersection - // to the specified object. - inline bool Intersect_Screen_Object(IntersectionResultClass *Final_Result, Vector4 &Area, RenderObjClass *obj = 0); - - - // non-inlined declarations - - - // accumulates an object array for passing into Intersect_ObjectArray - void Append_Object_Array(int MaxCount, int &CurrentCount, RenderObjClass **ObjectArray, RenderObjClass *Object); - - // traverses an RenderObjClass object and adds it's subobjects, potentially performing - // a quick sphere intersection test before adding. - void Append_Hierarchy_Objects(int MaxCount, int &CurrentCount, RenderObjClass **ObjectArray, RenderObjClass *Heirarchy, bool Test_Bounding_Spheres, bool Convex); - - // top level intersection routines, most store intersection results in the Intersection.Result - // member structure and perform normal interpolation as a final step if indicated in the member data. - - bool Intersect_Object_Array(int ObjectCount, RenderObjClass **ObjectArray,IntersectionResultClass *FinalResult, bool Test_Bounding_Sphere, bool Convex); - bool Intersect_Object_Array(int ObjectCount, RenderObjClass **ObjectArray,IntersectionResultClass *FinalResult, IntersectionResultClass *TemporaryResults, bool Test_Bounding_Sphere, bool Convex); - bool Intersect_RenderObject(RenderObjClass *RObj, IntersectionResultClass *FinalResult = 0); - bool Intersect_Screen_Point_RenderObject(float screen_x, float screen_y, const LayerClass &Layer, RenderObjClass *RObj, IntersectionResultClass *FinalResult); - - bool Intersect_Screen_Point_Layer_Range(float ScreenX, float ScreenY, const LayerClass &TopLayer, const LayerClass &BackLayer); - bool Intersect_Screen_Point_Layer(float ScreenX, float ScreenY, const LayerClass &Layer); - bool Intersect_Layer(const LayerClass &Layer, bool Test_All = true); - - // the various intersection routines, all of which store their intersection results - // in the passed Intersection_Result strucuture. - bool Intersect_Box(Vector3 &Box_Min, Vector3 &Box_Max, IntersectionResultClass *FinalResult); - bool Intersect_Hierarchy(RenderObjClass *Hierarchy, IntersectionResultClass *FinalResult, bool Test_Bounding_Sphere = true, bool Convex = false); - bool Intersect_Hierarchy_Sphere(RenderObjClass *Hierarchy, IntersectionResultClass *FinalResult); - bool Intersect_Hierarchy_Sphere_Quick(RenderObjClass *Hierarchy, IntersectionResultClass *FinalResult); - - /* - ** Identifies exactly what sub object of a render object is under the screen space vector - */ - RenderObjClass *Intersect_Sub_Object(float screenx, float screeny, LayerClass &layer, RenderObjClass *robj, IntersectionResultClass *result); - - - /* - ** Functions related to determining if a 3d point is within a triangle. - */ - static inline void _Find_Polygon_Dominant_Plane(Vector3 &Normal, int &Axis_1, int &Axis_2); - static inline int _Largest_Normal_Index(Vector3 &v); - static inline bool _Point_In_Polygon(IntersectionResultClass *FinalResult, Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3); - static inline bool _Point_In_Polygon(IntersectionResultClass *FinalResult, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3, int axis_1, int axis_2); - static inline bool _Point_In_Polygon(Vector3 &Point, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3, int axis_1, int axis_2,float &Alpha,float &Beta); - static inline bool _Point_In_Polygon_Z(Vector3 &Point, Vector3 Corners[3]); - static inline bool _Point_In_Polygon_Z(Vector3 &Point, Vector3 &Corner1, Vector3 &Corner2, Vector3 &Corner3); - -protected: - - /* - ** Find the intersection between two lines and interpolate the UV values for the intersection. - ** Designed for use with _Intersect_Triangles_Z. - */ - //static inline void _Intersect_Lines_Z(Vector3 &A, Vector3 &B, Vector2 &UVStart, Vector2 &UVEnd, Vector3 &C, Vector3 &D, Vector3 ClippedPoints[6], Vector2 ClippedUV[6], int &DestIndex); - static inline bool In_Front_Of_Line - ( - const Vector3 & p, // point to test - const Vector3 & e0, // point on edge - const Vector3 & de // direction of edge - ); - - static inline float Intersect_Lines - ( - const Vector3 & p0, // start of line segment - const Vector3 & p1, // end of line segment - const Vector3 & e0, // point on clipping edge - const Vector3 & de // direction of clipping edge - ); - - static inline int Clip_Triangle_To_LineXY( - int incount, - Vector3 * InPoints, - Vector2 * InUVs, - Vector3 * OutPoints, - Vector2 * OutUVs, - const Vector3 & edge_point0, - const Vector3 & edge_point1 - ); - - - - inline float Plane_Z_Distance(Vector3 &PlaneNormal, Vector3 &PlanePoint); - inline void Transform_Model_To_World_Coords(IntersectionResultClass *FinalResult); - - /* - ** Static vars available for use by temporary intersection class objects. - */ - static Vector3 _RayLocation, _RayDirection, _IntersectionNormal; - -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.inl b/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.inl deleted file mode 100644 index a76df398fc..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/intersec.inl +++ /dev/null @@ -1,1096 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef INTERSEC_INL -#define INTERSEC_INL - -#include "camera.h" - - -/// debug code that will be tossed - -#ifdef DEBUG_NORMALS - -#include "d:/g/app/main/debug_o.h" - -inline bool Verify_Normal(Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3) -{ - - double d1 = Vector3::Dot_Product(Normal, loc1); - double d2 = Vector3::Dot_Product(Normal, loc2); - double d3 = Vector3::Dot_Product(Normal, loc3); - - double e1 = d1 - d2; - double e2 = d2 - d3; - double e3 = d3 - d1; - - if((fabs(e1) > 0.001) || (fabs(e2) > 0.001) || (fabs(e3) > 0.001)) { - Debug.Print("----------\n"); - Debug.Print("dots", Vector3(d1,d2,d3)); - Debug.Print("err", Vector3(e1,e2,e3)); - return false; - } - return true; -} - -inline void Verify_Normal2(Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3) -{ - Vector3 v1 = loc2 - loc1; - Vector3 v2 = loc3 - loc1; - Vector3 normal = Vector3::Cross_Product(v1,v2); - normal.Normalize(); - if(!Verify_Normal(Normal, loc1,loc2,loc3)) { - Vector3 diff = Normal - normal; - if(Verify_Normal(normal, loc1,loc2,loc3)) { - Debug.Print("calculated worked.\n"); - - } - } -// Normal = normal; -} - -#endif - -//// end of debug code to toss - -/* -** Determine the ray that corresponds to the specified screen coordinates with respect -** to the camera location, direction and projection information. -*/ - -inline void IntersectionClass::Get_Screen_Ray(float screen_x, float screen_y, const LayerClass &Layer) -{ - - // copy screen coords to member data - ScreenX = screen_x; - ScreenY = screen_y; - - // extract needed pointers from the world - CameraClass *camera = Layer.Camera; - - // determine the ray corresponding to the camera and distance to projection plane - Matrix3D camera_matrix = camera->Get_Transform(); - Vector3 camera_location = camera->Get_Position(); - - // the projected ray has the same origin as the camera - *RayLocation = camera_location; - -// these 6 lines worked for SR 1.1 -// build the projected screen vector -// float x_offset = width / (float)Scene->width; // render width in pixels divided by display width in pixels = ratio of displayed area -// float y_offset = height / (float)Scene->height; -// float zmod = Scene->perspective; -// float xmod = ((ScreenX / x_offset) * width - xmid - Scene->xstart) * zmod * 16384.0f/ (Scene->axratio * 128.0f); -// float ymod = ((ScreenY / y_offset) * height - ymid - Scene->ystart) * zmod * 16384.0f/ (Scene->ayratio * 128.0f); - - // determine the location of the screen coordinate in camera-model space - const ViewportClass &viewport = camera->Get_Viewport(); - -// float aspect = camera->Get_Aspect_Ratio(); - - Vector2 min,max; - camera->Get_View_Plane(min,max); - float xscale = (max.X - min.X); - float yscale = (max.Y - min.Y); - - float zmod = -1.0; // Scene->vpd; // Note: view plane distance is now always 1.0 from the camera - float xmod = (-ScreenX + 0.5 + viewport.Min.X) * zmod * xscale;// / aspect; - float ymod = (ScreenY - 0.5 - viewport.Min.Y) * zmod * yscale;// * aspect; - -// float xmod = (ScreenX - 0.5 - viewport.Min.X) * zmod / Scene->axratio; -// float ymod = (ScreenY - 0.5 - viewport.Min.Y) * zmod / Scene->ayratio; - -// sr1.2 -// float xmod = (ScreenX - 0.5 - Scene->xstart) * zmod / Scene->axratio; -// float ymod = (ScreenY - 0.5 - Scene->ystart) * zmod / Scene->ayratio; -// sr1.1 -// float xmod = x_offset * zmod; //projection_width; -// float ymod = y_offset * zmod; //projection_height; - - // transform the screen coordinates by the camera's matrix into world coordinates. - float x = zmod * camera_matrix[0][2] + xmod * camera_matrix[0][0] + ymod * camera_matrix[0][1]; - float y = zmod * camera_matrix[1][2] + xmod * camera_matrix[1][0] + ymod * camera_matrix[1][1]; - float z = zmod * camera_matrix[2][2] + xmod * camera_matrix[2][0] + ymod * camera_matrix[2][1]; - - RayDirection->Set(x,y,z); - RayDirection->Normalize(); - - // set the maximum intersection distance to the back clipping plane - MaxDistance = camera->Get_Depth(); - //Max_Distance = Scene->zstop * Scene->depth; - -} - -/* -** This is the Point_In_Polygon_Z low level function, optimized for use by _Intersect_Triangles_Z. -** If it is inside, it will adjust the Z value of the point to be on the triangle plane. -*/ -inline bool IntersectionClass::_Point_In_Polygon_Z( - Vector3 &Point, - Vector3 &Corner1, - Vector3 &Corner2, - Vector3 &Corner3 -) -{ -// these defines could be variables if support for other axis were neccessary -#define AXIS_1 0 -#define AXIS_2 1 -#define AXIS_3 2 - - double u0 = Point[AXIS_1] - Corner1[AXIS_1]; - double v0 = Point[AXIS_2] - Corner1[AXIS_2]; - - // determine the 2d vectors on the dominant plane from the first vertex to the other two - double u1 = Corner2[AXIS_1] - Corner1[AXIS_1]; - double v1 = Corner2[AXIS_2] - Corner1[AXIS_2]; - double u2 = Corner3[AXIS_1] - Corner1[AXIS_1]; - double v2 = Corner3[AXIS_2] - Corner1[AXIS_2]; - - double alpha, beta; - bool intersect = false; - - // calculate alpha and beta as normalized (0..1) percentages across the 2d projected triangle - // and do bounds checking (sum <= 1) to determine whether or not the triangle intersection occurs. - - if (u1 == 0.0f) { - beta = u0 / u2; // beta is the percentage down the edge Corner1->Corner3 - if ((beta >= 0.0f) && (beta <= 1.0f)) { // make sure it's within the edge segment - alpha = (v0 - beta * v2) / v1; // alpha is the percentage down the edge Corner1->Corner2 - - // if alpha is valid & the sum of alpha & beta is <= 1 then it's within the triangle - // note: 0.00001 added after testing an intersection of a square in the middle indicated - // an error of 0.0000001350, apparently due to roundoff. - intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0)); - } - } else { - beta = (v0 * u1 - u0 * v1) / (v2 * u1 - u2 * v1); - if ((beta >= 0.0) && (beta <= 1.0)) { - alpha = (u0 - beta * u2) / u1; - intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0)); - } - } - - // if it is inside, adjust the Z value to sit upon the triangle plane. - if(intersect) { - float u3 = Corner2[AXIS_3] - Corner1[AXIS_3]; - float v3 = Corner3[AXIS_3] - Corner1[AXIS_3]; - - Point[AXIS_3] = u3 * alpha + v3 * beta + Corner1[AXIS_3]; - } - - return intersect; -} - -/* -** Another way to access the Point_In_Polygon function -** -*/ -inline bool IntersectionClass::_Point_In_Polygon_Z( - Vector3 &Point, - Vector3 Corners[3] -) -{ - return _Point_In_Polygon_Z(Point, Corners[0], Corners[1], Corners[2]); -} - -/* -** This is the general purpose Point_In_Polygon low level function. It can be called directly if you know -** the dominant projection axes, such as in the case of 2d intersecion with heightfields. -*/ -inline bool IntersectionClass::_Point_In_Polygon( - Vector3 &Point, - Vector3 &loc1, - Vector3 &loc2, - Vector3 &loc3, - int axis_1, - int axis_2, - float &Alpha, - float &Beta) -{ - - double u0 = Point[axis_1] - loc1[axis_1]; - double v0 = Point[axis_2] - loc1[axis_2]; - - // determine the 2d vectors on the dominant plane from the first vertex to the other two - double u1 = loc2[axis_1] - loc1[axis_1]; - double v1 = loc2[axis_2] - loc1[axis_2]; - double u2 = loc3[axis_1] - loc1[axis_1]; - double v2 = loc3[axis_2] - loc1[axis_2]; - - double alpha, beta; - bool intersect = false; - - // calculate alpha and beta as normalized (0..1) percentages across the 2d projected triangle - // and do bounds checking (sum <= 1) to determine whether or not the triangle intersection occurs. - -#ifdef DEBUG_NORMALS - bool debugmode = false; - if(FinalResult->Alpha == 777) { - debugmode = true; - } -#endif - - if (u1 == 0.0f) { - Beta = beta = u0 / u2; // beta is the percentage down the edge loc1->loc3 - if ((beta >= 0.0f) && (beta <= 1.0f)) { // make sure it's within the edge segment - Alpha = alpha = (v0 - beta * v2) / v1; // alpha is the percentage down the edge loc1->loc2 - - // if alpha is valid & the sum of alpha & beta is <= 1 then it's within the triangle - // note: 0.00001 added after testing an intersection of a square in the middle indicated - // an error of 0.0000001350, apparently due to roundoff. - intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0)); - } - } else { - Beta = beta = (v0 * u1 - u0 * v1) / (v2 * u1 - u2 * v1); - if ((beta >= 0.0) && (beta <= 1.0)) { - Alpha = alpha = (u0 - beta * u2) / u1; - intersect = ((alpha >= 0.0) && ((alpha + beta) <= 1.0)); - } - } - -#ifdef DEBUG_NORMALS - if(debugmode) { - Debug.Print("Intersect", intersect); - Debug.Print("Normal ", Normal); - Debug.Print("Point 1", loc1); - Debug.Print("Point 2", loc2); - Debug.Print("Point 3", loc3); - Debug.Print("Inter ", FinalResult->Intersection); - Debug.Print("a/b", (float) alpha, (float) beta); - Debug.Print("sum", (float) alpha + (float) beta); - Debug.Print("diff", (float) (alpha - beta)); - float d1 = Vector3::Dot_Product(Normal, loc1); - float d2 = Vector3::Dot_Product(Normal, loc2); - float d3 = Vector3::Dot_Product(Normal, loc3); - - float e1 = d1 - d2; - float e2 = d2 - d3; - float e3 = d3 - d1; - - Debug.Print("dots", Vector3(d1,d2,d3)); - Debug.Print("err", Vector3(e1,e2,e3)); - } -#endif - - - return intersect; -} - -/* -** This version calls the base form using member data from the FinalResult struct for -** some of it's arguments. -*/ -inline bool IntersectionClass::_Point_In_Polygon( - IntersectionResultClass *FinalResult, - Vector3 &loc1, - Vector3 &loc2, - Vector3 &loc3, - int axis_1, - int axis_2) -{ - return (FinalResult->Intersects = _Point_In_Polygon( FinalResult->Intersection, loc1, loc2, loc3, - axis_1, axis_2, FinalResult->Alpha, FinalResult->Beta)); -} - -/* -** This version determines the dominant plane of the 3d triangle to be point-in-poly tested -** and then calls the next form of _Point_In_Polygon -*/ -inline bool IntersectionClass::_Point_In_Polygon(IntersectionResultClass *FinalResult, Vector3 &Normal, Vector3 &loc1, Vector3 &loc2, Vector3 &loc3) { - - // first, find the dominant axis and use the plane perpendicular to it as defined by axis_1, axis_2 - int axis_1, axis_2; - _Find_Polygon_Dominant_Plane(Normal, axis_1, axis_2); - - return _Point_In_Polygon(FinalResult, loc1, loc2, loc3, axis_1, axis_2); -} - - -/* -** Determine the Z distance to the specified polygon. -*/ -inline float IntersectionClass::Plane_Z_Distance(Vector3 &PlaneNormal, Vector3 &PlanePoint) -{ - // do a parallel check - float divisor = (PlaneNormal[0] *(*RayDirection)[0] + PlaneNormal[1] *(*RayDirection)[1] + PlaneNormal[2] * (*RayDirection)[2]); - if(divisor == 0) return false; // parallel - - // determine distance to plane - double d = - (PlanePoint[0] * PlaneNormal[0] + PlanePoint[1] * PlaneNormal[1] + PlanePoint[2] * PlaneNormal[2]); - - float value = - (d + PlaneNormal[0] * (*RayLocation)[0] + PlaneNormal[1] * (*RayLocation)[1] + PlaneNormal[2] * (*RayLocation)[2]) / divisor; - - return value; -} - -/* -** This function will find the z elevation for the passed Vector3 whose x/y components -** are defined, using the specified vertex & surface normal to determine the correct value -*/ -inline float IntersectionClass::_Get_Z_Elevation( - Vector3 &Point, - Vector3 &PlanePoint, - Vector3 &PlaneNormal) -{ - - // do a parallel check - if(PlaneNormal[2] == 0) return false; - - // determine distance to plane - double d = - (PlanePoint[0] * PlaneNormal[0] + PlanePoint[1] * PlaneNormal[1] + PlanePoint[2] * PlaneNormal[2]); - - float value = - (d + PlaneNormal[0] * Point[0] + PlaneNormal[1] * Point[1] ) / PlaneNormal[2]; - - return value; -} - -/* -** Optimized intersection test that only considers the x/y component of the intersection object -** and will determine the intersection location down the Z axis. -*/ -inline bool IntersectionClass::Intersect_Polygon_Z(IntersectionResultClass *Result, Vector3 &PolygonNormal, Vector3 &v1, Vector3 &v2, Vector3 &v3) -{ - - Result->Range = Plane_Z_Distance(PolygonNormal, v1); - (Result->Intersection)[0] = (*RayLocation)[0]; - (Result->Intersection)[1] = (*RayLocation)[1]; - (Result->Intersection)[2] = (*RayLocation)[2] - Result->Range; - return _Point_In_Polygon(Result, PolygonNormal, v1, v2, v3); -} - - -/* -** Scale the normalized direction ray to the distance of intersection -*/ -void IntersectionClass::Calculate_Intersection(IntersectionResultClass *Result) -{ - (Result->Intersection)[0] = (*RayLocation)[0] + (*RayDirection)[0] * Result->Range; - (Result->Intersection)[1] = (*RayLocation)[1] + (*RayDirection)[1] * Result->Range; - (Result->Intersection)[2] = (*RayLocation)[2] + (*RayDirection)[2] * Result->Range; -} - -/* -** Plane intersection test that assumes a normalized RayDirection. Only determines if -** plane is parallel and if not, the range to it (which may be negative or beyond MaxRange). -** It doesn't determine point of intersection either. -*/ -inline bool IntersectionClass::Intersect_Plane_Quick(IntersectionResultClass *Result, Vector3 &PlaneNormal, Vector3 &PlanePoint) -{ - // do a parallel check - float divisor = (PlaneNormal[0] *(*RayDirection)[0] + PlaneNormal[1] *(*RayDirection)[1] + PlaneNormal[2] * (*RayDirection)[2]); - if(divisor == 0) return false; // parallel - - // determine distance to plane - float d = - (PlanePoint[0] * PlaneNormal[0] + PlanePoint[1] * PlaneNormal[1] + PlanePoint[2] * PlaneNormal[2]); - Result->Range = - (d + PlaneNormal[0] * (*RayLocation)[0] + PlaneNormal[1] * (*RayLocation)[1] + PlaneNormal[2] * (*RayLocation)[2]) / divisor; - - return true; -} - -/* -** Determine if the specified ray will intersect the plane; returns false for planes -** parallel and behind ray origin. -** Sets Range to the distance from the ray location to the intersection. -** Note: Range is undefined if an intersection didn't occur. -*/ -inline bool IntersectionClass::Intersect_Plane(IntersectionResultClass *Result, Vector3 &PlaneNormal, Vector3 &PlanePoint) { - - // normalize the ray direction - RayDirection->Normalize(); - - // call the quick test routine - if(!Intersect_Plane_Quick(Result, PlaneNormal, PlanePoint)) return false; - - // check to make sure it's not behind the ray's origin - if(Result->Range <= 0) return false; - - // check to make sure it's not beyond max distance - if(Result->Range > MaxDistance) return false; - - // determine point of intersection - Calculate_Intersection(Result); - - return true; -} - - - -/* -** Return the index of the largest normal component 0..2 -** used by Find_Triangle_Dominant_Plane() -*/ -inline int IntersectionClass::_Largest_Normal_Index(Vector3 &v) -{ - float x = fabsf(v[0]); - float y = fabsf(v[1]); - float z = fabsf(v[2]); - if(x > y) { - if(x > z) { - return 0; // x > y && x > z --> x is the max - } - return 2; // x > y && !(x > z) --> z is the max - } - if(y > z) - return 1; // x <= y && y > z --> y is the max - return 2; // y > x && y > z --> z is the max -} - -/* -** Use the Polygon's currently defined surface normal to determine it's dominant axis. -** Axis_1 and Axis_2 are set to the indices of the two axis that define the dominant plane. -*/ -inline void IntersectionClass::_Find_Polygon_Dominant_Plane(Vector3 &Normal, int &Axis_1, int &Axis_2) -{ - switch (_Largest_Normal_Index(Normal)) - { - case 0: - // Dominant is the X axis - Axis_1 = 2; - Axis_2 = 1; - break; - case 1: - // Dominant is the Y axis - Axis_1 = 2; - Axis_2 = 0; - break; - case 2: - // Dominant is the Z axis - Axis_1 = 0; - Axis_2 = 1; - break; - } -} - -/* -** Returns true if ray intersects polygon. -** Changes passed Intersection argument to location of intersection if it occurs, -** and sets Range to the distance from the ray location to the intersection. -** If Interpolated_Normal is specified it will interpolate the surface normal based -** on the vertex normals. -*/ -inline bool IntersectionClass::Intersect_Polygon(IntersectionResultClass *Result, Vector3 &PolygonNormal, Vector3 &v1, Vector3 &v2, Vector3 &v3) -{ - // first check to see if it hits the plane; determine plane normal and find point on plane (from a vertex) - -#ifdef DEBUG_NORMALS - Verify_Normal2(PolygonNormal, v1,v2,v3); -#endif - - if(Intersect_Plane(Result, PolygonNormal, v1)) { - // then check to see if it it actually intersects the polygon. - return _Point_In_Polygon(Result, PolygonNormal, v1, v2, v3); - } - // doesn't even hit the plane, return false. - return false; -} - -/* -** This version will calc the normal for the polygon before calling -** a lower form of Intersect_Polygon -*/ -inline bool IntersectionClass::Intersect_Polygon(IntersectionResultClass *Result, Vector3 &v1, Vector3 &v2, Vector3 &v3) -{ - Vector3 vec1 = v2 - v1; - Vector3 vec2 = v3 - v1; -#ifdef ALLOW_TEMPORARIES - Vector3 normal = Vector3::Cross_Product(vec1, vec2); -#else - Vector3 normal; - Vector3::Cross_Product(vec1, vec2, &normal); -#endif - - return Intersect_Polygon(Result, normal, v1,v2,v3); -} - - -// called after Interpolate_Intersection_Normal. -// transform the intersection and the normal from model coords into world coords -inline void IntersectionClass::Transform_Model_To_World_Coords(IntersectionResultClass *FinalResult) -{ -#ifdef ALLOW_TEMPORARIES - FinalResult->Intersection = FinalResult->ModelMatrix * FinalResult->Intersection + FinalResult->ModelLocation; - if(IntersectionNormal != 0) - { - Vector3 normal(*IntersectionNormal); - *IntersectionNormal = FinalResult->ModelMatrix * normal; - } -#else - FinalResult->ModelMatrix.mulVector3(FinalResult->Intersection); - FinalResult->Intersection += FinalResult->ModelLocation; - if(IntersectionNormal != 0) - { - FinalResult->ModelMatrix.mulVector3(*IntersectionNormal); - } -#endif -} - - - -bool IntersectionClass::Intersect_Screen_Object( IntersectionResultClass *Final_Result, - Vector4 &Area, - RenderObjClass *obj) -{ - if(Final_Result->Intersects = ((ScreenX >= Area[0]) && (ScreenX <= Area[2]) && (ScreenY >= Area[1]) && (ScreenY <= Area[3]))) { - Final_Result->IntersectionType = IntersectionResultClass::GENERIC; - Final_Result->IntersectedRenderObject = obj; - Final_Result->Range = 0; - return true; - } - return false; -} - - -/* -** Determines the point of intersection, if any between the line segments AB and CD. -** If an intersection occurs, then the UV values are interpolated along AB. -** Disregards the Z value and considers only the X/Y data except for determining -** the Z value of the intersection. -** This function could be easily modified to support other axes. -* / -void IntersectionClass::_Intersect_Lines_Z( - Vector3 &A, - Vector3 &B, - Vector2 &UVStart, - Vector2 &UVEnd, - Vector3 &C, - Vector3 &D, - Vector3 ClippedPoints[6], - Vector2 ClippedUV[6], - int &DestIndex) -{ - /* - Let A,B,C,D be 2-space position vectors. Then the directed line segments AB & CD are given by: - - AB=A+r(B-A), r in [0,1] - CD=C+s(D-C), s in [0,1] - If AB & CD intersect, then - - A+r(B-A)=C+s(D-C), or - - Ax+r(Bx-Ax)=Cx+s(Dx-Cx) - Ay+r(By-Ay)=Cy+s(Dy-Cy) for some r,s in [0,1] - Solving the above for r and s yields - - (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy) - r = ----------------------------- (eqn 1) - (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx) - (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) - s = ----------------------------- (eqn 2) - (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx) - Let P be the position vector of the intersection point, then - - P=A+r(B-A) or - - Px=Ax+r(Bx-Ax) - Py=Ay+r(By-Ay) - By examining the values of r & s, you can also determine some other limiting conditions: - - If 0<=r<=1 & 0<=s<=1, intersection exists - r<0 or r>1 or s<0 or s>1 line segments do not intersect - If the denominator in eqn 1 is zero, AB & CD are parallel - - If the numerator in eqn 1 is also zero, AB & CD are coincident - - If the intersection point of the 2 lines are needed (lines in this context mean infinite lines) regardless whether the two line segments intersect, then - - If r>1, P is located on extension of AB - If r<0, P is located on extension of BA - If s>1, P is located on extension of CD - If s<0, P is located on extension of DC - * / - - // the numerator is required for all execution routes - float numerator = (A[AXIS_2] - C[AXIS_2]) * (D[AXIS_1] - C[AXIS_1]) - (A[AXIS_1] - C[AXIS_1]) * (D[AXIS_2] - C[AXIS_2]); - - // if the denominator is zero, then the segments are parallel. - float denominator = (B[AXIS_1] - A[AXIS_1]) * (D[AXIS_2] - C[AXIS_2]) - (B[AXIS_2] - A[AXIS_2]) * (D[AXIS_1] - C[AXIS_1]); - - // r & s are percentages through the line segment. - float r, s; - - // check to see if they are parallel - if(denominator == 0) { - - // check to see if they are coincident - // a numerator of zero with a denominator of zero indicates coincident lines. - if (numerator != 0) { - - // parallel, not coincident lines (and segments) do not intersect. - return; - } - - // perform special case for parallel segments - - // determine relative position 0..1 of C and D on one of the 1d vectors of A-B - float len = B[AXIS_1] - A[AXIS_1]; - float cpos,dpos; - - // if the length of the edge on the first axis is zero, use the other axis instead. - if(len) { - len = 1.0 / len; - cpos = (C[AXIS_1] - A[AXIS_1]) * len; - dpos = (D[AXIS_1] - A[AXIS_1]) * len; - } else { - len = B[AXIS_2] - A[AXIS_2]; - - // degenerate triangle test - if(len == 0) - return; - - len = 1.0 / len; - cpos = (C[AXIS_2] - A[AXIS_2]) * len; - dpos = (D[AXIS_2] - A[AXIS_2]) * len; - } - - // check to see if there's any overlap - // one of the two pos values must be 0>pos>1 or there is no intersection. - // this test will ensure that cpos & dpos will not both be outside the same end of the segment. - if(((cpos < 0) && (dpos < 0)) || ((cpos > 1) && (dpos > 1))) - return; - - if(cpos < 0) { - // C is outside, therefore D is inside or on other side. - // use the original vertex. - ClippedPoints[DestIndex] = A; - ClippedUV[DestIndex++] = UVStart; - } else if (cpos > 1) { - // C is outside far side, therefore D is inside or on other side. - // use the far vertex. - ClippedPoints[DestIndex] = B; - ClippedUV[DestIndex++] = UVEnd; - } else { - // C is inside. - // Use C as the vertex, and interpolate the UV coords. - ClippedPoints[DestIndex] = C; - ClippedUV[DestIndex++] = (UVEnd - UVStart) * cpos + UVStart; - } - - if(dpos < 0) { - // D is outside near vertex, therefore C is inside or outside far vertex - // use near vertex - ClippedPoints[DestIndex] = A; - ClippedUV[DestIndex++] = UVStart; - } else if (dpos > 1) { - // D is outside far vertex, therefore C is inside or outside the near vertex. - // use the far vertex. - ClippedPoints[DestIndex] = B; - ClippedUV[DestIndex++] = UVEnd; - } else { - // D is inside. - // Use D as the vertex, and interpolate the UV coords. - ClippedPoints[DestIndex] = D; - ClippedUV[DestIndex++] = (UVEnd - UVStart) * dpos + UVStart; - } - return; - - } - - // determine the percentage into the line segments that the intersection occurs. - // an intersection of segments will produce r & s values between 0 & 1. - denominator = 1.0 / denominator; - r = numerator * denominator; - - numerator = (A[AXIS_2] - C[AXIS_2]) * (B[AXIS_1] - A[AXIS_1]) - (A[AXIS_1] - C[AXIS_1]) * (B[AXIS_2] - A[AXIS_2]); - s = numerator * denominator; - - // determine if the line intersect within the defined segments. - if((0.0 <= r) && (r <= 1.0) && (0.0 <= s) && (s <= 1.0)) { - - // they intersect. - // determine intersection point - Vector3 v = D - C; -// float len = v.Length(); - ClippedPoints[DestIndex] = C + v * s; - - // interpolate UV values - Vector2 uv = UVEnd - UVStart; -// len = uv.Length(); - ClippedUV[DestIndex++] = UVStart + uv * r; - } -} - -/* - A failed attempt to use a graphics gem vol 2 example - - - // Compute a1, b1, c1, where line joining points 1 and 2 - // is "a1 x + b1 y + c1 = 0". - float a1 = B[AXIS_2] - A[AXIS_2]; - float b1 = B[AXIS_1] - A[AXIS_1]; - float c1 = B[AXIS_2] * A[AXIS_1] - A[AXIS_1] * B[AXIS_2]; - - // Compute r3 & r4, the sign values - float r3 = a1 * C[AXIS_1] + b1 * C[AXIS_2] + c1; - float r4 = a1 * D[AXIS_1] + b1 * D[AXIS_2] + c1; - - // Check signs of r3 and r4. If both point 3 and point 4 lie on - // same side of line 1, the line segments do not intersect. - if ( r3 != 0 && r4 != 0 && (((r3 < 0) && (r4 < 0)) || ((r3 > 0) && (r4 > 0))) - return; // ( DONT_INTERSECT ); - - // Compute a2, b2, c2 - float a2 = D[AXIS_2] - C[AXIS_2]; - float b2 = C[AXIS_1] - D[AXIS_1]; - float c2 = D[AXIS_1] * C[AXIS_2] - C[AXIS_1] * D[AXIS_2]; - - // Compute r1 and r2 - float r1 = a2 * A[AXIS_1] + b2 * A[AXIS_2] + c2; - float r2 = a2 * B[AXIS_1] + b2 * B[AXIS_2] + c2; - - // Check signs of r1 and r2. If both point 1 and point 2 lie - // on same side of second line segment, the line segments do - // not intersect. - if ( r1 != 0 && r2 != 0 && (((r1 < 0) && (r2 < 0)) || ((r1 > 0) && (r2 > 0)))) - return; // ( DONT_INTERSECT ); - - // Line segments intersect: compute intersection point. - float denom = a1 * b2 - a2 * b1; - if ( denom == 0 ) - return; // ( COLLINEAR ); - - float offset = denom < 0 ? - denom * 0.5f : denom * 0.5f; - - // The denom/2 is to get rounding instead of truncating. It - // is added or subtracted to the numerator, depending upon the - // sign of the numerator. - - float num = b1 * c2 - b2 * c1; - float x = ( num < 0 ? num - offset : num + offset ) / denom; - - num = a2 * c1 - a1 * c2; - float y = ( num < 0 ? num - offset : num + offset ) / denom; - - ClippedPoints[DestIndex] = Vector3(x,y,0); - ClippedUV[DestIndex++] = Vector3 - return; //( DO_INTERSECT ); // lines_intersect -*/ - -inline bool IntersectionClass::In_Front_Of_Line -( - const Vector3 & p, // point to test - const Vector3 & e0, // point on edge - const Vector3 & de // direction of edge -) -{ - Vector3 dp = p - e0; - float val = de.X*dp.Y - de.Y*dp.X; - if (val > 0.0f) { - return true; - } - return false; -} - -inline float IntersectionClass::Intersect_Lines -( - const Vector3 & p0, // start of line segment - const Vector3 & p1, // end of line segment - const Vector3 & e0, // point on clipping edge - const Vector3 & de // direction of clipping edge -) -{ - float dpx = p1.X - p0.X; - float dpy = p1.Y - p0.Y; - - float den = de.Y * dpx - de.X * dpy; - - if (fabs(den) > WWMATH_EPSILON) { - - float num = p0.Y*de.X - p0.X*de.Y + e0.X*de.Y - e0.Y*de.X; - float t = num/den; - if ((t >= 0.0f) && (t <= 1.0f)) { - return t; - } - } - - return 0.0f; -} - - -#define EMIT(p,uv) OutPoints[outnum] = p; OutUVs[outnum] = uv; outnum++; - - -inline int IntersectionClass::Clip_Triangle_To_LineXY( - int incount, - Vector3 * InPoints, - Vector2 * InUVs, - Vector3 * OutPoints, - Vector2 * OutUVs, - const Vector3 & edge_point0, - const Vector3 & edge_point1 -) -{ - Vector3 e0 = edge_point0; - Vector3 de = edge_point1 - edge_point0; - - // number of verts output. - int outnum = 0; - - // start and end verts of the current edge - int p0,p1; - p0 = incount-1; - - // intersection temporaries. - float intersection; - Vector3 intersection_point; - Vector2 intersection_uv; - - // loop over each edge in the input polygon - for (p1=0; p1in, emit intersection and endpoint - intersection = Intersect_Lines(InPoints[p0], InPoints[p1], e0, de); - intersection_point = (1.0f - intersection) * InPoints[p0] + intersection * InPoints[p1]; - intersection_uv = (1.0f - intersection) * InUVs[p0] + intersection * InUVs[p1]; - EMIT(intersection_point,intersection_uv); - EMIT(InPoints[p1],InUVs[p1]); - } - } else { - - if (In_Front_Of_Line(InPoints[p0], e0, de)) { - - // edge going in->out, emit intersection - intersection = Intersect_Lines(InPoints[p0],InPoints[p1], e0, de); - intersection_point = (1.0f - intersection) * InPoints[p0] + intersection * InPoints[p1]; - intersection_uv = (1.0f - intersection) * InUVs[p0] + intersection * InUVs[p1]; - EMIT(intersection_point,intersection_uv); - - } - - } - - // move to next edge - p0 = p1; - } - - return outnum; -} - -inline int IntersectionClass::_Intersect_Triangles_Z( - Vector3 ClipPoints[3], - Vector3 TrianglePoints[3], - Vector2 UV[3], - Vector3 ClippedPoints[6], - Vector2 ClippedUV[6] -) -{ - int count; - Vector3 tmp_points[6]; - Vector2 tmp_uv[6]; - - count = Clip_Triangle_To_LineXY(3,TrianglePoints,UV,ClippedPoints,ClippedUV,ClipPoints[0],ClipPoints[1]); - count = Clip_Triangle_To_LineXY(count,ClippedPoints,ClippedUV,tmp_points,tmp_uv,ClipPoints[1],ClipPoints[2]); - count = Clip_Triangle_To_LineXY(count,tmp_points,tmp_uv,ClippedPoints,ClippedUV,ClipPoints[2],ClipPoints[0]); - - return count; -} - -/* -** This function will fill the passed array with the set of points & uv values that represent -** the boolean operation of the anding of the ClipPoints with the TrianglePoints. The UV values -** provided for the TrianglePoints triangle are used to generate accurate UV values for any -** new points created by this operation. -** This function returns the number of vertices it required to define the intersection. -* / -int IntersectionClass::_Intersect_Triangles_Z( - Vector3 ClipPoints[3], - Vector3 TrianglePoints[3], - Vector2 UV[3], - Vector3 ClippedPoints[6], - Vector2 ClippedUV[6] -) -{ - // first, check to see if all triangle points are inside clip area - // the point in polygon will drop any inside points to the clip triangle plane. - bool inside[3]; - - bool noclip; - noclip = inside[0] = _Point_In_Polygon_Z(TrianglePoints[0], ClipPoints); - noclip &= inside[1] = _Point_In_Polygon_Z(TrianglePoints[1], ClipPoints); - noclip &= inside[2] = _Point_In_Polygon_Z(TrianglePoints[2], ClipPoints); - - // if all points are inside clip area, then copy the triangle points & - // UV's to the destination & return 3 (the number of points in the clipped polygon). - if(noclip) { - ClippedPoints[0] = TrianglePoints[0]; - ClippedPoints[1] = TrianglePoints[1]; - ClippedPoints[2] = TrianglePoints[2]; - ClippedUV[0] = UV[0]; - ClippedUV[1] = UV[1]; - ClippedUV[2] = UV[2]; - - return 3; - } - - int points = 0; // number of output polygon points - - // not all uv triangle points are inside the clip triangle. - // Test to see if any clip points are inside the uv triangle - float alpha, beta; - if(_Point_In_Polygon(ClipPoints[0], TrianglePoints[0], TrianglePoints[1], TrianglePoints[2], 0, 1, alpha, beta)) { - ClippedPoints[points] = ClipPoints[0]; - Vector2 uv1 = UV[1] - UV[0]; - Vector2 uv2 = UV[2] - UV[0]; - ClippedUV[points++] = UV[0] + alpha * uv1 + beta * uv2; - } - - if(_Point_In_Polygon(ClipPoints[1], TrianglePoints[0], TrianglePoints[1], TrianglePoints[2], 0, 1, alpha, beta)) { - ClippedPoints[points] = ClipPoints[1]; - Vector2 uv1 = UV[1] - UV[0]; - Vector2 uv2 = UV[2] - UV[0]; - ClippedUV[points++] = UV[0] + alpha * uv1 + beta * uv2; - } - - if(_Point_In_Polygon(ClipPoints[2], TrianglePoints[0], TrianglePoints[1], TrianglePoints[2], 0, 1, alpha, beta)) { - ClippedPoints[points] = ClipPoints[2]; - Vector2 uv1 = UV[1] - UV[0]; - Vector2 uv2 = UV[2] - UV[0]; - ClippedUV[points++] = UV[0] + alpha * uv1 + beta * uv2; - } - - // if all 3 clip points are inside the decal triangle then return - if(points == 3) - return; - - // The clip triangle does not fully contain the uv triangle, and the uv triangle - // does not fully contain the clip triangle. - // Intersect any edge which has at least one outside point with all of the clip edges. - // First, determine which edges to test. Those points that are already clipped (by being inside) - // are immediately copied to the clipped point & uv arrays. - - // these bools indicate which edges of the triangle to be clipped are to be tested. - bool test_01 = false; - bool test_02 = false; - bool test_12 = false; - - if( inside[0] ) { ClippedPoints[points] = TrianglePoints[0]; ClippedUV[points++] = UV[0]; } - else { test_01 = test_02 = true; } - - if( inside[1] ) { ClippedPoints[points] = TrianglePoints[1]; ClippedUV[points++] = UV[1]; } - else { test_01 = test_12 = true; } - - if( inside[2] ) { ClippedPoints[points] = TrianglePoints[2]; ClippedUV[points++] = UV[2];} - else { test_02 = test_12 = true; } - - // Now test each indicated segment. - // Intersect_2D_Lines will interpolate the clipped UV values if an intersection occurs, and it - // will also increment the points variable (passed as a reference). - // Any intersections are stored in the passed ClippedPoints array. - if(test_01) { - _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[1], - UV[0], UV[1], - ClipPoints[0], ClipPoints[1], - ClippedPoints, - ClippedUV, - points); - _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[1], - UV[0], UV[1], - ClipPoints[0], ClipPoints[2], - ClippedPoints, - ClippedUV, - points); - _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[1], - UV[0], UV[1], - ClipPoints[1], ClipPoints[2], - ClippedPoints, - ClippedUV, - points); - } - if(test_02) { - _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[2], - UV[0], UV[2], - ClipPoints[0], ClipPoints[1], - ClippedPoints, - ClippedUV, - points); - _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[2], - UV[0], UV[2], - ClipPoints[0], ClipPoints[2], - ClippedPoints, - ClippedUV, - points); - _Intersect_Lines_Z( TrianglePoints[0], TrianglePoints[2], - UV[0], UV[2], - ClipPoints[1], ClipPoints[2], - ClippedPoints, - ClippedUV, - points); - } - if(test_12) { - _Intersect_Lines_Z( TrianglePoints[1], TrianglePoints[2], - UV[1], UV[2], - ClipPoints[0], ClipPoints[1], - ClippedPoints, - ClippedUV, - points); - _Intersect_Lines_Z( TrianglePoints[1], TrianglePoints[2], - UV[1], UV[2], - ClipPoints[0], ClipPoints[2], - ClippedPoints, - ClippedUV, - points); - _Intersect_Lines_Z( TrianglePoints[1], TrianglePoints[2], - UV[1], UV[2], - ClipPoints[1], ClipPoints[2], - ClippedPoints, - ClippedUV, - points); - } - - // If no intersections have occurred, then the triangle must be completely outside - // the clipping area. -/* - // if it is determined that no intersections have occurred, then copy the clip triangle points - // into the destination array and determine the correct UV values for the subset of the - // triangle that was clipped. - if(points == 0) { - ClippedPoints[0] = ClipPoints[0]; - ClippedPoints[1] = ClipPoints[1]; - ClippedPoints[2] = ClipPoints[2]; - ClippedUV[0] = UV[0]; - ClippedUV[1] = UV[1]; - ClippedUV[2] = UV[2]; - - return 3; - } -* / - // points will be 0, 3, 4, 5 or 6 - if(!((points == 0) || (points == 3) || (points == 4) || (points == 5) || (points == 6))) { - Debug.Print("points", points); - return 0; //_Intersect_Triangles_Z( ClipPoints, TrianglePoints, UV, ClippedPoints, ClippedUV); - } - - return points; - -} -*/ - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/inttest.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/inttest.h deleted file mode 100644 index e933eb64ce..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/inttest.h +++ /dev/null @@ -1,256 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/inttest.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/14/01 9:19a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef INTTEST_H -#define INTTEST_H - -#include "always.h" -#include "aabox.h" -#include "obbox.h" -#include "tri.h" -#include "colmath.h" -#include "coltype.h" - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// IntersectionTestClass -// -// This is the base class for all of the 'Intersection' functions. The intersection tests are -// purely boolean tests. The base class only contains the CollisionType of the test. -// -// Every IntersectionTestClass should have the following functions: -// -// bool Cull(const Vector3 & min,const Vector3 & max); -// bool Cull(const AABoxClass & box); -// bool Intersect_Triangle(const TriClass & tri); -// -// These are not virtual because I don't want to pay the price of virtual function -// calls at the point in the code where these are used. It may be possible to -// write template functions if we use these exact function prototpyes for all -// collision test classes though. -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class IntersectionTestClass -{ -public: - IntersectionTestClass(int collision_type) : CollisionType(collision_type) { } - IntersectionTestClass(const IntersectionTestClass & that) : CollisionType(that.CollisionType) { } - -public: - int CollisionType; -}; - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// AABoxIntersectionTestClass -// -// This is an intersection test which uses an Axis-Aligned Box -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class AABoxIntersectionTestClass : public IntersectionTestClass -{ -public: - AABoxIntersectionTestClass(const AABoxClass & box,int collision_type) : - IntersectionTestClass(collision_type), - Box(box) - { - } - - AABoxIntersectionTestClass(const AABoxIntersectionTestClass & that) : - IntersectionTestClass(that), - Box(that.Box) - { - } - - bool Cull(const Vector3 & cull_min,const Vector3 & cull_max); - bool Cull(const AABoxClass & cull_box); - bool Intersect_Triangle(const TriClass & tri); - -public: - AABoxClass Box; // world space aabox that we want to test with - -}; - -inline bool AABoxIntersectionTestClass::Cull(const Vector3 & cull_min,const Vector3 & cull_max) -{ - Vector3 box_min; - Vector3::Subtract(Box.Center,Box.Extent,&box_min); - - Vector3 box_max; - Vector3::Add(Box.Center,Box.Extent,&box_max); - - if ((box_min.X > cull_max.X) || (box_max.X < cull_min.X)) return true; - if ((box_min.Y > cull_max.Y) || (box_max.Y < cull_min.Y)) return true; - if ((box_min.Z > cull_max.Z) || (box_max.Z < cull_min.Z)) return true; - - return false; -} - -inline bool AABoxIntersectionTestClass::Cull(const AABoxClass & cull_box) -{ - Vector3 dc; - Vector3 r; - Vector3::Subtract(cull_box.Center,Box.Center,&dc); - Vector3::Add(cull_box.Extent,Box.Extent,&r); - - if (WWMath::Fabs(dc.X) > r.X) return true; - if (WWMath::Fabs(dc.Y) > r.Y) return true; - if (WWMath::Fabs(dc.Z) > r.Z) return true; - - return false; -} - -inline bool AABoxIntersectionTestClass::Intersect_Triangle(const TriClass & tri) -{ - return CollisionMath::Intersection_Test(Box,tri); -} - - -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -// OBBoxIntersectionTestClass -// -// This is an intersection test which uses an Axis-Aligned Box -// -///////////////////////////////////////////////////////////////////////////////////////////////////////////// -class OBBoxIntersectionTestClass : public IntersectionTestClass -{ -public: - - OBBoxIntersectionTestClass(const OBBoxClass & box,int collision_type); - OBBoxIntersectionTestClass(const OBBoxIntersectionTestClass & that); - OBBoxIntersectionTestClass(const OBBoxIntersectionTestClass & that,const Matrix3D & tm); - OBBoxIntersectionTestClass(const AABoxIntersectionTestClass & that,const Matrix3D & tm); - - bool Cull(const Vector3 & min,const Vector3 & max); - bool Cull(const AABoxClass & box); - bool Intersect_Triangle(const TriClass & tri); - -protected: - void update_bounding_box(void); - -public: - OBBoxClass Box; // world space obbox that we want to test with - AABoxClass BoundingBox; // axis aligned w-s bounding box -}; - - -inline OBBoxIntersectionTestClass::OBBoxIntersectionTestClass(const OBBoxClass & box,int collision_type) : - IntersectionTestClass(collision_type), - Box(box) -{ - update_bounding_box(); -} - -inline OBBoxIntersectionTestClass::OBBoxIntersectionTestClass(const OBBoxIntersectionTestClass & that) : - IntersectionTestClass(that), - Box(that.Box) -{ - update_bounding_box(); -} - -inline OBBoxIntersectionTestClass::OBBoxIntersectionTestClass -( - const OBBoxIntersectionTestClass & that, - const Matrix3D & tm -) : - IntersectionTestClass(that) -{ - OBBoxClass::Transform(tm,that.Box,&Box); - update_bounding_box(); -} - -inline OBBoxIntersectionTestClass::OBBoxIntersectionTestClass -( - const AABoxIntersectionTestClass & that, - const Matrix3D & tm -) : - IntersectionTestClass(that) -{ - Matrix3D::Transform_Vector(tm,that.Box.Center,&(Box.Center)); - Box.Extent = that.Box.Extent; - Box.Basis = tm; // copies the 3x3 rotation portion of the transform - update_bounding_box(); -} - -inline bool OBBoxIntersectionTestClass::Cull(const Vector3 & cull_min,const Vector3 & cull_max) -{ - Vector3 box_min; - Vector3::Subtract(BoundingBox.Center,BoundingBox.Extent,&box_min); - - Vector3 box_max; - Vector3::Add(BoundingBox.Center,BoundingBox.Extent,&box_max); - - if ((box_min.X > cull_max.X) || (box_max.X < cull_min.X)) return true; - if ((box_min.Y > cull_max.Y) || (box_max.Y < cull_min.Y)) return true; - if ((box_min.Z > cull_max.Z) || (box_max.Z < cull_min.Z)) return true; - - return false; -} - -inline bool OBBoxIntersectionTestClass::Cull(const AABoxClass & cull_box) -{ - Vector3 dc; - Vector3 r; - Vector3::Subtract(cull_box.Center,BoundingBox.Center,&dc); - Vector3::Add(cull_box.Extent,BoundingBox.Extent,&r); - - if (WWMath::Fabs(dc.X) > r.X) return true; - if (WWMath::Fabs(dc.Y) > r.Y) return true; - if (WWMath::Fabs(dc.Z) > r.Z) return true; - - return false; -} - -inline bool OBBoxIntersectionTestClass::Intersect_Triangle(const TriClass & tri) -{ - return CollisionMath::Intersection_Test(Box,tri); -} - -inline void OBBoxIntersectionTestClass::update_bounding_box(void) -{ - BoundingBox.Center = Box.Center; - Box.Basis.Rotate_AABox_Extent(Box.Extent,&BoundingBox.Extent); -} - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/layer.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/layer.cpp deleted file mode 100644 index d4c983a0cd..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/layer.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /VSS_Sync/ww3d2/layer.cpp $* - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * LayerClass::LayerClass -- constructor * - * LayerClass::~LayerClass -- destructor * - * LayerClass::Set_Scene -- Set the scene used by this layer * - * LayerClass::Get_Scene -- get the scene being rendered by this layer * - * LayerClass::Peek_Scene -- get the scene being rendered by this layer w/o a ref * - * LayerClass::Set_Camera -- Set the camera being used by this layer * - * LayerClass::Get_Camera -- get the camera being used by this layer * - * LayerClass::LayerClass -- default constructor * - * LC::Peek_Camera -- Get copy of camera. * - * LC::Set -- Kinda like an assignment operator. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "layer.h" -#include "scene.h" -#include "camera.h" - - -/*********************************************************************************************** - * LayerClass::LayerClass -- default constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -LayerClass::LayerClass(void) : - Scene(NULL), - Camera(NULL), - Clear(false), - ClearZ(true), - ClearColor(0,0,0) -{ -} - -LayerClass::LayerClass(const LayerClass &src) : - Scene(src.Get_Scene()), - Camera(src.Get_Camera()), - Clear(src.Clear), - ClearZ(src.ClearZ), - ClearColor(src.ClearColor) -{ -} - -/*********************************************************************************************** - * LayerClass::LayerClass -- constructor * - * * - * simply constructs a layer class, initialized with the desired settings * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -LayerClass::LayerClass -( - SceneClass * scene, - CameraClass * cam, - bool clear, - bool clearz, - const Vector3 & color -) -{ - if (scene) scene->Add_Ref(); - Scene = scene; - - if (cam) cam->Add_Ref(); - Camera = cam; - - Clear = clear; - ClearZ = clearz; - ClearColor = color; -} - - -/*********************************************************************************************** - * LayerClass::~LayerClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -LayerClass::~LayerClass(void) -{ - if (Scene) { - Scene->Release_Ref(); - Scene=0; - } - if (Camera) { - Camera->Release_Ref(); - Camera=0; - } -} - - -/*********************************************************************************************** - * LayerClass::Set_Scene -- Set the scene used by this layer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -void LayerClass::Set_Scene(SceneClass * scene) -{ - if (Scene) { - Scene->Release_Ref(); - } - Scene = scene; - if (Scene) { - Scene->Add_Ref(); - } -} - - -/*********************************************************************************************** - * LayerClass::Get_Scene -- get the scene being rendered by this layer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -SceneClass * LayerClass::Get_Scene(void) const -{ - if (Scene) { - Scene->Add_Ref(); - } - return Scene; -} - - -/*********************************************************************************************** - * LayerClass::Peek_Scene -- get the scene being rendered by this layer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/8/99 NH : Created. * - *=============================================================================================*/ -SceneClass * LayerClass::Peek_Scene(void) const -{ - return Scene; -} - - -/*********************************************************************************************** - * LayerClass::Set_Camera -- Set the camera being used by this layer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -void LayerClass::Set_Camera(CameraClass * cam) -{ - if (Camera) { - Camera->Release_Ref(); - } - Camera = cam; - if (Camera) { - Camera->Add_Ref(); - } -} - - -/*********************************************************************************************** - * LayerClass::Get_Camera -- get the camera being used by this layer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/98 GTH : Created. * - *=============================================================================================*/ -CameraClass * LayerClass::Get_Camera(void) const -{ - if (Camera) { - Camera->Add_Ref(); - } - return Camera; -} - - -/*********************************************************************************************** - * LC::Peek_Camera -- Get copy of camera. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/14/2001 SKB : Created. * - *=============================================================================================*/ -CameraClass * LayerClass::Peek_Camera(void) const -{ - return Camera; -} - - -/*********************************************************************************************** - * LC::Set -- Kinda like an assignment operator. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/14/2001 SKB : Created. * - *=============================================================================================*/ -void LayerClass::Set(const LayerClass & layer) -{ - Set_Camera(layer.Peek_Camera()); - Set_Scene(layer.Peek_Scene()); - Clear = layer.Clear; - ClearZ = layer.ClearZ; - ClearColor = layer.ClearColor; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/layer.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/layer.h deleted file mode 100644 index 35af8af283..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/layer.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /VSS_Sync/ww3d2/layer.h $* - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef LAYER_H -#define LAYER_H - -#include "always.h" -#include "LISTNODE.H" -#include "vector3.h" - -class SceneClass; -class CameraClass; - -class LayerClass; -typedef Node LayerNodeClass; - -class LayerClass : public LayerNodeClass -{ - -public: - - LayerClass(void); - LayerClass(SceneClass * s,CameraClass * c,bool clear = false,bool clearz = false,const Vector3 & color = Vector3(0,0,0)); - LayerClass(const LayerClass & src); - ~LayerClass(void); - - - /* - ** The following functions will handle the references of the Scene and Camera - ** objects properly. - */ - void Set_Scene(SceneClass * scene); - SceneClass * Get_Scene(void) const; - SceneClass * Peek_Scene(void) const; - void Set_Camera(CameraClass * cam); - CameraClass * Get_Camera(void) const; - CameraClass * Peek_Camera(void) const; - - - // [SKB: Aug 14 2001 @ 1:53pm] : - // Add a method to copy one layer to another - I would like to create an assignment - // operator but it could break old code. - void Set(const LayerClass & layer); - - /* - ** LayerClass members are public since this is a "lightweight" class - */ - bool Clear; - bool ClearZ; - Vector3 ClearColor; - - SceneClass * Scene; - CameraClass * Camera; - -}; - -typedef List LayerListClass; - - -#endif //LAYER_H - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/line3d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/line3d.cpp deleted file mode 100644 index 231abe92c2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/line3d.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/line3d.cpp $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 7/05/01 4:15p $* - * * - * $Revision:: 11 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * Line3DClass::Line3DClass -- Constructor * - * Line3DClass::Line3DClass -- Copy constructor. * - * Line3DClass::operator = -- assignment operator * - * Line3DClass::~Line3DClass -- Destructor. * - * Line3DClass::Clone -- Creates a clone of this Line3D * - * Line3DClass::Scale -- Scale object * - * Line3DClass::Scale -- Scale object * - * Line3DClass::Update_Cached_Bounding_Volumes -- update bounding vols * - * Line3DClass::Reset -- Reset line start and end points. * - * Line3DClass::Reset -- Reset line start and end points, and line width.* - * Re_Color -- Reset the line color. * - * Set_Opacity -- Reset the line opacity. * - * Line3DClass::Render -- render the 3d line * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "line3d.h" -#include "vertmaterial.h" -#include "shader.h" -#include "wwdebug.h" -#include "ww3d.h" -#include "rinfo.h" -#include "dx8wrapper.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "dx8fvf.h" - -// 12 Triangles for index buffer -const unsigned short Indices[]= -{ - 3,5,1, - 7,5,3, - 1,5,0, - 5,4,0, - 4,2,0, - 4,6,2, - 7,3,2, - 6,7,2, - 7,6,5, - 5,6,4, - 2,3,1, - 2,1,0 -}; - - -/************************************************************************** - * Line3DClass::Line3DClass -- Constructor * - * * - * INPUT: Vector3 start, end - start, end points of line (world coords).* - * float width - width of line (in world units). * - * float r, g, b - R, G, B components of line color. * - * float opacity - opacity of line. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/15/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - * 02/16/2001 HY : Ported to DX8 * - *========================================================================*/ -Line3DClass::Line3DClass (const Vector3 & start, const Vector3 & end, - float width, float r, float g, float b, float opacity) -{ - Length = (end - start).Length(); - Width = width; - - // Create box model with origin at start point (X is major axis). - - // 8 Vertices - float halfw = Width * 0.5f; - - vert[0].X = 0.0f; - vert[0].Y = -halfw; - vert[0].Z = -halfw; - vert[1].X = 0.0f; - vert[1].Y = halfw; - vert[1].Z = -halfw; - vert[2].X = 0.0f; - vert[2].Y = -halfw; - vert[2].Z = halfw; - vert[3].X = 0.0f; - vert[3].Y = halfw; - vert[3].Z = halfw; - vert[4].X = Length; - vert[4].Y = -halfw; - vert[4].Z = -halfw; - vert[5].X = Length; - vert[5].Y = halfw; - vert[5].Z = -halfw; - vert[6].X = Length; - vert[6].Y = -halfw; - vert[6].Z = halfw; - vert[7].X = Length; - vert[7].Y = halfw; - vert[7].Z = halfw; - - Color.X=r; - Color.Y=g; - Color.Z=b; - Set_Opacity(opacity); - - // Set box transform so that the origin is at the start point and it - // 'looks towards' the endpoint. - Matrix3D transform(true); - transform.Obj_Look_At(start, end, 0.0); - Set_Transform(transform); -} - - -/************************************************************************** - * Line3DClass::Line3DClass -- Copy constructor. * - * * - * INPUT: const Line3DClass & src - source to copy from. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/15/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - * 02/16/2001 HY : Ported to DX8 * - *========================================================================*/ -Line3DClass::Line3DClass(const Line3DClass & src) : - RenderObjClass(src), - Length(src.Length), - Width(src.Width), - Shader(src.Shader), - Color(src.Color) -{ - for (int i=0; i<8; i++) vert[i]=src.vert[i]; -} - - -/************************************************************************** - * Line3DClass::operator = -- assignment operator * - * * - * INPUT: const Line3DClass & that - source to copy from. * - * * - * OUTPUT: Line3DClass & - result of assignment. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/15/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - * 02/16/2001 HY : Ported to DX8 * - *========================================================================*/ -Line3DClass & Line3DClass::operator = (const Line3DClass & that) -{ - // Naty: need to add MatInfo and remapper to do this Byon - WWASSERT(0); - - RenderObjClass::operator = (that); - - if (this != &that) { - Length = that.Length; - Width = that.Width; - Shader=that.Shader; - Color=that.Color; - for (int i=0; i<8; i++) - vert[i]=that.vert[i]; - } - - return * this; -} - - -/************************************************************************** - * Line3DClass::~Line3DClass -- Destructor. * - * * - * INPUT: none. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/15/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - * 02/16/2001 HY : Ported to DX8 * - *========================================================================*/ -Line3DClass::~Line3DClass(void) -{ -} - - -/************************************************************************** - * Line3DClass::Clone -- Creates a clone of this Line3D * - * * - * INPUT: none. * - * * - * OUTPUT: RenderObjClass * - pointer to cloned object. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/15/1998 NH : Created. * - *========================================================================*/ -RenderObjClass * Line3DClass::Clone(void) const -{ - return NEW_REF( Line3DClass, (*this)); -} - -/*********************************************************************************************** - * Line3DClass::Render -- render the 3d line * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/8/98 GTH : Created. * - * 02/16/2001 HY : Ported to DX8 * - *=============================================================================================*/ - -void Line3DClass::Render(RenderInfoClass & rinfo) -{ - if (Is_Not_Hidden_At_All() == false) { - return; - } - - // If static sort lists are enabled and this mesh has a sort level, put it on the list instead - // of rendering it. - unsigned int sort_level = (unsigned int)Get_Sort_Level(); - - if (WW3D::Are_Static_Sort_Lists_Enabled() && sort_level != SORT_LEVEL_NONE) - { - WW3D::Add_To_Static_Sort_List(this, sort_level); - return; - } - - DX8Wrapper::Set_Shader(Shader); - DX8Wrapper::Set_Texture(0,NULL); - VertexMaterialClass *vm=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(vm); - REF_PTR_RELEASE(vm); - - DX8Wrapper::Set_Transform(D3DTS_WORLD,Transform); - - DynamicVBAccessClass vb(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,8); - { - DynamicVBAccessClass::WriteLockClass Lock(&vb); - const FVFInfoClass &fi=vb.FVF_Info(); - unsigned char *vb=(unsigned char*)Lock.Get_Formatted_Vertex_Array(); - int i; - unsigned int color=DX8Wrapper::Convert_Color(Color); - - for (i=0; i<8; i++) - { - *(Vector3*)(vb+fi.Get_Location_Offset())=vert[i]; - *(unsigned int*)(vb+fi.Get_Diffuse_Offset())=color; - vb+=fi.Get_FVF_Size(); - } - } - - DynamicIBAccessClass ib(BUFFER_TYPE_DYNAMIC_DX8,36); - { - DynamicIBAccessClass::WriteLockClass Lock(&ib); - unsigned short *mem=Lock.Get_Index_Array(); - for (int i=0; i<36; i++) - mem[i]=Indices[i]; - } - - DX8Wrapper::Set_Vertex_Buffer(vb); - DX8Wrapper::Set_Index_Buffer(ib,0); - DX8Wrapper::Draw_Triangles(0,36/3,0,8); -} - -/************************************************************************** - * Line3DClass::Scale -- Scale object * - * * - * INPUT: float scale - uniform scale factor. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/27/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - * 02/16/2001 HY : Ported to DX8 * - *========================================================================*/ -void Line3DClass::Scale(float scale) -{ - for (int i=0; i<8; i++) vert[i]*=scale; - Length *= scale; - Width *= scale; - - Invalidate_Cached_Bounding_Volumes(); - - // Now update the object space bounding volumes of this object's container: - RenderObjClass *container = Get_Container(); - if (container) container->Update_Obj_Space_Bounding_Volumes(); -} - - -/************************************************************************** - * Line3DClass::Scale -- Scale object * - * * - * INPUT: float scalex, scaley, scalez - axis scale factors. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/27/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - * 02/16/2001 HY : Ported to DX8 * - *========================================================================*/ -void Line3DClass::Scale(float scalex, float scaley, float scalez) -{ - // The line width is always the same in the y and z axes (the line - // approximates a cylinder). - Vector3 scale(scalex,scaley,scalez); - for (int i=0; i<8; i++) vert[i].Scale(scale); - Length *= scalex; - Width *= scaley; - - Invalidate_Cached_Bounding_Volumes(); - - // Now update the object space bounding volumes of this object's container: - RenderObjClass *container = Get_Container(); - if (container) container->Update_Obj_Space_Bounding_Volumes(); -} - - -void Line3DClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - float half_l = Length * 0.5f; - sphere.Center.Set(half_l, 0.0f, 0.0f); - sphere.Radius = half_l; -} - - -void Line3DClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - float half_l = Length * 0.5f; - box.Center.Set(half_l, 0.0f, 0.0f); - box.Extent.Set(half_l, 0.0f, 0.0f); -} - -/************************************************************************** - * Line3DClass::Reset -- Reset line start and end points. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/19/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - *========================================================================*/ -void Line3DClass::Reset(const Vector3 & new_start, const Vector3 & new_end) -{ - // Adjust length of line: - float new_length = (new_end - new_start).Length(); - if (new_length == 0) { - new_length = 0.001f; // make sure we don't have a zero length BMG - } - Scale((new_length / Length), 1.0f, 1.0f); - Length = new_length; - - // Adjust transform of line: - Matrix3D transform(true); - transform.Obj_Look_At(new_start, new_end, 0.0); - Set_Transform(transform); - - Invalidate_Cached_Bounding_Volumes(); - - // Now update the object space bounding volumes of this object's container: - RenderObjClass *container = Get_Container(); - if (container) container->Update_Obj_Space_Bounding_Volumes(); -} - - -/************************************************************************** - * Line3DClass::Reset -- Reset line start and end points, and line width. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/19/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - *========================================================================*/ -void Line3DClass::Reset(const Vector3 & new_start, const Vector3 & new_end, float new_width) -{ - // Adjust length and width of line: - float new_length = (new_end - new_start).Length(); - if (new_length == 0) { - new_length = 0.001f; // make sure we don't have a zero length BMG - } - float width_scale = new_width / Width; - Scale((new_length / Length), width_scale, width_scale); - Length = new_length; - Width = new_width; - - // Adjust transform of line: - Matrix3D transform(true); - transform.Obj_Look_At(new_start, new_end, 0.0); - Set_Transform(transform); - Matrix3D inv; - transform.Get_Orthogonal_Inverse(inv); -#ifdef ALLOW_TEMPORARIES -// Vector3 test = inv * Vector3(new_end); -#else -// Vector3 test; -// inv.mulVector3(new_end, test); -#endif - - Invalidate_Cached_Bounding_Volumes(); - - // Now update the object space bounding volumes of this object's container: - RenderObjClass *container = Get_Container(); - if (container) container->Update_Obj_Space_Bounding_Volumes(); -} - - -/************************************************************************** - * Re_Color -- Reset the line color. * - * * - * INPUT: float r, g, b - components of the new color. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 01/26/1998 NH : Created. * - * 04/21/1998 NH : Ported to SR 1.3. * - *========================================================================*/ -void Line3DClass::Re_Color(float r, float g, float b) -{ - Color=Vector4(r,g,b,Color.W); -} - - -/************************************************************************** - * Set_Opacity -- Reset the line opacity. * - * * - * INPUT: float opacity - new opacity. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/03/1998 NH : Created. * - *========================================================================*/ -void Line3DClass::Set_Opacity(float opacity) -{ - if (opacity < 1.0f) - { Shader=ShaderClass::_PresetAlphaSolidShader; - Set_Sort_Level(1); - } - else - { Shader=ShaderClass::_PresetOpaqueSolidShader; - Set_Sort_Level(SORT_LEVEL_NONE); - } - Color.W=opacity; -} - -/* -** -*/ -int Line3DClass::Get_Num_Polys(void) const -{ - return 12; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/line3d.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/line3d.h deleted file mode 100644 index 8d601e8f6b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/line3d.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/line3d.h $* - * * - * $Author:: Hector_y $* - * * - * $Modtime:: 2/16/01 3:52p $* - * * - * $Revision:: 2 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef LINE3D_H -#define LINE3D_H - -#include "always.h" -#include "rendobj.h" -#include "vector3.h" -#include "vector4.h" -#include "shader.h" - -class VertexMaterialClass; -class RenderInfoClass; - -/* -** Line3DClass -- Render3DObject for rendering 3D line segments. -** These are conceptually cylinders with a given width - some approximation -** of this will be rendered. (The current approximation assumes that -** Line3DCLass objects are unlit, therefore only the sihouette needs to be -** approximated). -*/ -class Line3DClass : public W3DMPO, public RenderObjClass -{ - W3DMPO_GLUE(Line3DClass) - - public: - - Line3DClass (const Vector3 & start, const Vector3 & end, float width, - float r, float g, float b, float opacity = 1.0f); - Line3DClass(const Line3DClass & src); - Line3DClass & operator = (const Line3DClass & that); - virtual ~Line3DClass(void); - virtual RenderObjClass * Clone(void) const; - - // class id of this render object - virtual int Class_ID(void) const { return CLASSID_LINE3D; } - - virtual void Render(RenderInfoClass & rfinfo); - - // scale the 3D line symmetrically about its center. - virtual void Scale(float scale); - virtual void Scale(float scalex, float scaley, float scalez); - - // returns the number of polygons in the render object - virtual int Get_Num_Polys(void) const; - - // Get the object space bounding volumes - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - - // The following functions are unique to Line3DClass: - - // Reset the line start and end points - void Reset(const Vector3 & new_start, const Vector3 & new_end); - - // Reset line start and end points, and the line width - void Reset(const Vector3 & new_start, const Vector3 & new_end, float new_width); - - // Reset the line color - void Re_Color(float r, float g, float b); - - // Reset the line opacity - void Set_Opacity(float opacity); - - // For non-opaque lines, allow them to render last. - void Set_Sort_Level(int level) { SortLevel = level; } - int Get_Sort_Level(void) const { return SortLevel; } - - protected: - - // This is kept to facilitate changing the line endpoints. - float Length; - - // This is kept to facilitate changing the line width. - float Width; - - // shader - ShaderClass Shader; - // vertices - Vector3 vert[8]; - // color - Vector4 Color; - char SortLevel; -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matinfo.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matinfo.cpp deleted file mode 100644 index dc49126641..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matinfo.cpp +++ /dev/null @@ -1,429 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : MatInfo.h * - * * - * $Archive:: /Commando/Code/ww3d2/matinfo.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/15/01 5:50p $* - * * - * $Revision:: 10 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "matinfo.h" -#include "wwdebug.h" -#include "meshmdl.h" -#include "texture.h" - -MaterialInfoClass::MaterialInfoClass(void) -{ -} - -MaterialInfoClass::MaterialInfoClass(const MaterialInfoClass & src) -{ - for (int mi=0; miClone(); - VertexMaterials.Add(vmat); - } - - for (int ti=0; tiAdd_Ref(); - Textures.Add(tex); - } -} - - -MaterialInfoClass::~MaterialInfoClass(void) -{ - Free(); -} - - -MaterialInfoClass * MaterialInfoClass::Clone(void) const -{ - return W3DNEW MaterialInfoClass(*this); -} - -int MaterialInfoClass::Add_Texture(TextureClass * tex) -{ - WWASSERT(tex != NULL); - tex->Add_Ref(); - int index = Textures.Count(); - Textures.Add(tex); - return index; -} - -int MaterialInfoClass::Get_Texture_Index(const char * name) -{ - for (int i=0; iGet_Texture_Name()) == 0) { - return i; - } - } - return -1; -} - -TextureClass * MaterialInfoClass::Get_Texture(int index) -{ - WWASSERT(index >= 0); - WWASSERT(index < Textures.Count()); - Textures[index]->Add_Ref(); - return Textures[index]; -} - -/* - -void MaterialInfoClass::Set_Texture_Reduction_Factor(float trf) -{ - for (int i = 0; i < Textures.Count(); i++) { - Textures[i]->Set_Reduction_Factor(trf); - } -} - - -void MaterialInfoClass::Process_Texture_Reduction(void) -{ - for (int i = 0; i < Textures.Count(); i++) { - Textures[i]->Process_Reduction(); - } -} -*/ -void MaterialInfoClass::Free(void) -{ - int i; - - for (i=0; iTexture_Count() == dest->Texture_Count()); - WWASSERT(src->Vertex_Material_Count() == dest->Vertex_Material_Count()); - - SrcMatInfo = src; - SrcMatInfo->Add_Ref(); - DestMatInfo = dest; - DestMatInfo->Add_Ref(); - - if (src->Vertex_Material_Count() > 0) { - VertexMaterialCount = src->Vertex_Material_Count(); - VertexMaterialRemaps = W3DNEWARRAY VmatRemapStruct[VertexMaterialCount]; - for (int i=0; iVertex_Material_Count(); i++) { - VertexMaterialRemaps[i].Src = src->Peek_Vertex_Material(i); - VertexMaterialRemaps[i].Dest = dest->Peek_Vertex_Material(i); - } - } - - if (src->Texture_Count() > 0) { - TextureCount = src->Texture_Count(); - TextureRemaps = W3DNEWARRAY TextureRemapStruct[TextureCount]; - for (int i=0; iTexture_Count(); i++) { - TextureRemaps[i].Src = src->Peek_Texture(i); - TextureRemaps[i].Dest = dest->Peek_Texture(i); - } - } -} - -MaterialRemapperClass::~MaterialRemapperClass(void) -{ - SrcMatInfo->Release_Ref(); - DestMatInfo->Release_Ref(); - - if (TextureRemaps) { - delete[] TextureRemaps; - } - if (VertexMaterialRemaps) { - delete[] VertexMaterialRemaps; - } -} - -TextureClass * MaterialRemapperClass::Remap_Texture(TextureClass * src) -{ - if (src == NULL) return src; - if (src == LastSrcTex) return LastDestTex; - for (int i=0; iVertex_Material_Count() >= 1) { - - for (int pass = 0;pass < srcmeshmatdesc->Get_Pass_Count(); pass++) { - - if (srcmeshmatdesc->Has_Material_Array(pass)) { - - for (int vert_index = 0; vert_index < srcmeshmatdesc->Get_Vertex_Count(); vert_index++) { - VertexMaterialClass * src = srcmeshmatdesc->Peek_Material(vert_index, pass); - destmeshmatdesc->Set_Material(vert_index, Remap_Vertex_Material(src),pass); - } - - } else { - - VertexMaterialClass * src = srcmeshmatdesc->Peek_Single_Material(pass); - destmeshmatdesc->Set_Single_Material(Remap_Vertex_Material(src), pass); - - } - } - } - - /* - ** Remap the textures if there is at least one of them - */ - if (SrcMatInfo->Texture_Count() >= 1) { - - for (int pass = 0;pass < srcmeshmatdesc->Get_Pass_Count(); pass++) { - - for (int stage = 0; stage < MeshMatDescClass::MAX_TEX_STAGES; stage++) { - - if (srcmeshmatdesc->Has_Texture_Array(pass, stage)) { - - for (int poly_index = 0; poly_index < srcmeshmatdesc->Get_Polygon_Count(); poly_index++) { - TextureClass * src = srcmeshmatdesc->Peek_Texture(poly_index, pass, stage); - destmeshmatdesc->Set_Texture(poly_index, Remap_Texture(src), pass, stage); - } - - } else { - - TextureClass * src = srcmeshmatdesc->Peek_Single_Texture(pass, stage); - destmeshmatdesc->Set_Single_Texture(Remap_Texture(src), pass, stage); - - } - } - } - } -} - -MaterialCollectorClass::MaterialCollectorClass(void) -{ - LastShader = ShaderClass(0xFFFFFFFF); - LastMaterial = NULL; - LastTexture = NULL; -} - -MaterialCollectorClass::~MaterialCollectorClass(void) -{ - Reset(); -} - -void MaterialCollectorClass::Collect_Materials(MeshModelClass * mesh) -{ - for (int pass = 0;pass < mesh->Get_Pass_Count(); pass++) { - - // Vertex materials (either single or per vertex) - if (mesh->Has_Material_Array(pass)) { - - for (int vert_index = 0;vert_index < mesh->Get_Vertex_Count(); vert_index++) { - VertexMaterialClass * mat = mesh->Peek_Material(vert_index,pass); - Add_Vertex_Material(mat); - } - - } else { - VertexMaterialClass * mat = mesh->Get_Single_Material(pass); - Add_Vertex_Material(mat); - REF_PTR_RELEASE(mat); - } - - - // Shaders (single or per poly...) - if (mesh->Has_Shader_Array(pass)) { - for (int poly_index=0; poly_index < mesh->Get_Polygon_Count(); poly_index++) { - Add_Shader(mesh->Get_Shader(poly_index,pass)); - } - } else { - ShaderClass sh = mesh->Get_Single_Shader(pass); - Add_Shader(sh); - } - - - // Textures per pass, per stage (either array or single...) - for (int stage = 0; stage < MeshMatDescClass::MAX_TEX_STAGES; stage++) { - - if (mesh->Has_Texture_Array(pass,stage)) { - - for (int poly_index = 0;poly_index < mesh->Get_Polygon_Count(); poly_index++) { - TextureClass * tex = mesh->Peek_Texture(poly_index,pass,stage); - Add_Texture(tex); - } - - } else { - - TextureClass * tex = mesh->Peek_Single_Texture(pass,stage); - Add_Texture(tex); - - } - } - } -} - -void MaterialCollectorClass::Reset(void) -{ - for (int ti=0; tiAdd_Ref(); - LastTexture = tex; -} - -void MaterialCollectorClass::Add_Shader(ShaderClass shader) -{ - if (shader == LastShader) return; - if (Find_Shader(shader) != -1) return; - Shaders.Add(shader); - LastShader = shader; -} - -void MaterialCollectorClass::Add_Vertex_Material(VertexMaterialClass * vmat) -{ - if (vmat == NULL) return; - if (vmat == LastMaterial) return; - if (Find_Vertex_Material(vmat) != -1) return; - VertexMaterials.Add(vmat); - vmat->Add_Ref(); - LastMaterial = vmat; -} - -int MaterialCollectorClass::Get_Shader_Count(void) -{ - return Shaders.Count(); -} - -int MaterialCollectorClass::Get_Vertex_Material_Count(void) -{ - return VertexMaterials.Count(); -} - -int MaterialCollectorClass::Get_Texture_Count(void) -{ - return Textures.Count(); -} - -ShaderClass MaterialCollectorClass::Peek_Shader(int i) -{ - return Shaders[i]; -} - -TextureClass * MaterialCollectorClass::Peek_Texture(int i) -{ - return Textures[i]; -} - -VertexMaterialClass * MaterialCollectorClass::Peek_Vertex_Material(int i) -{ - return VertexMaterials[i]; -} - -int MaterialCollectorClass::Find_Shader(const ShaderClass & shader) -{ - for (int si=0; si. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /VSS_Sync/ww3d2/matinfo.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MATINFO_H -#define MATINFO_H - -#include "always.h" -#include "wwdebug.h" -#include "Vector.H" -#include "vertmaterial.h" -#include "texture.h" -#include "shader.h" -#ifdef _UNIX -#include "osdep.h" -#endif - -class MeshModelClass; -class MeshMatDescClass; - -/*********************************************************************************************** -** MaterialInfoClass -** -** This class gives an interface to the "changeable" material parameters inside a -** W3D render object. Typically, this will include things like the following: -** - one or more textures, -** - the vertex material used by the mesh (defines lighting properties, etc) -** -** Another purpose of this class is to actually hold onto a ref for each material -** object that a mesh uses. The "per-triangle" pointer arrays are not ref counted -** so the material info serves as a place to hold a reference to each material object -** that the mesh is using. -** -***********************************************************************************************/ -class MaterialInfoClass : public W3DMPO, public RefCountClass -{ - W3DMPO_GLUE(MaterialInfoClass) -public: - - MaterialInfoClass(); - MaterialInfoClass(const MaterialInfoClass & src); - ~MaterialInfoClass(); - MaterialInfoClass * Clone(void) const; - - void Reset(void) { Free(); } - int Vertex_Material_Count(void) const { return VertexMaterials.Count(); } - int Texture_Count(void) const { return Textures.Count(); } - - int Add_Vertex_Material(VertexMaterialClass * vmat); - int Add_Texture(TextureClass * tex); - - int Get_Vertex_Material_Index(const char * name); - int Get_Texture_Index(const char * name); - - VertexMaterialClass * Get_Vertex_Material(int index); - VertexMaterialClass * Get_Vertex_Material(const char * name); - VertexMaterialClass * Peek_Vertex_Material(int index); - VertexMaterialClass * Peek_Vertex_Material(const char * name); - void Replace_Material(int index, VertexMaterialClass *newMaterial); - void Reset_Texture_Mappers(void); - void Make_Vertex_Materials_Unique(void); - bool Has_Time_Variant_Texture_Mappers(void); - - TextureClass * Get_Texture(int index); - TextureClass * Get_Texture(const char * name); - TextureClass * Peek_Texture(int index); - TextureClass * Peek_Texture(const char * name); - void Replace_Texture(int index, TextureClass *newTexture); - -// void Set_Texture_Reduction_Factor(float trf); -// void Process_Texture_Reduction(void); - -private: - - void Free(void); - - DynamicVectorClass VertexMaterials; - DynamicVectorClass Textures; - -}; - - - -/*********************************************************************************************** -** MaterialRemapperClass -** This class is used when we need to "remap" all of the material pointers in a mesh -** to a new set of cloned materials. Basically, it assumes that you are going to initialize -** it with two identical material info objects (src and dest) and then you can give it pointers -** to materials in the "src" material info and it will give you back pointers to materials -** in the "dest" material info class. -** -** This class attempts to take advantage of the fact that meshes should normally be sorted -** with respect to their materials so we shouldn't really be doing a linear search for -** each remap... -** -** Please Note: this class does not hold references to the materials and is meant only to -** be used in a temporary fashion. Create it, do your conversion, then delete it :-) -***********************************************************************************************/ -class MaterialRemapperClass -{ -public: - MaterialRemapperClass(MaterialInfoClass * src,MaterialInfoClass * dest); - ~MaterialRemapperClass(void); - - TextureClass * Remap_Texture(TextureClass * src); - VertexMaterialClass * Remap_Vertex_Material(VertexMaterialClass * src); - void Remap_Mesh(const MeshMatDescClass * srcmeshmatdesc, MeshMatDescClass * destmeshmatdesc); - -private: - - struct VmatRemapStruct - { - VertexMaterialClass * Src; - VertexMaterialClass * Dest; - }; - - struct TextureRemapStruct - { - TextureClass * Src; - TextureClass * Dest; - }; - - MaterialInfoClass * SrcMatInfo; - MaterialInfoClass * DestMatInfo; - - int TextureCount; - TextureRemapStruct * TextureRemaps; - int VertexMaterialCount; - VmatRemapStruct * VertexMaterialRemaps; - - VertexMaterialClass * LastSrcVmat; - VertexMaterialClass * LastDestVmat; - TextureClass * LastSrcTex; - TextureClass * LastDestTex; -}; - -/*********************************************************************************************** -** MaterialCollectorClass -** -** This class can be used to collect all of the unique instances of materials from a mesh. -** Its original motivation is to solve a problem encountered in trying to save a mesh -** to disk. There are arrays of pointers to vertex materials in the mesh but no record of -** the set of unique vertex materials (all pointers could point to the same one...) Similar -** to the remapper, it tries to take advantage of the fact that the materials and textures -** should be in sorted order to optimize the lookups... -** -** NOTE: pointer comparisons are used to determine if the objects are unique. I don't -** check whether the contents of the objects are identical. (Exporter does this, I assume -** that if there are two separate objects, they are that way for a reason here.) -***********************************************************************************************/ -class MaterialCollectorClass -{ -public: - - MaterialCollectorClass(void); - ~MaterialCollectorClass(void); - - void Reset(void); - void Collect_Materials(MeshModelClass * mesh); - void Add_Texture(TextureClass * tex); - void Add_Shader(ShaderClass shader); - void Add_Vertex_Material(VertexMaterialClass * vmat); - - int Get_Shader_Count(void); - int Get_Vertex_Material_Count(void); - int Get_Texture_Count(void); - - ShaderClass Peek_Shader(int i); - TextureClass * Peek_Texture(int i); - VertexMaterialClass * Peek_Vertex_Material(int i); - - int Find_Shader(const ShaderClass & shader); - int Find_Texture(TextureClass * tex); - int Find_Vertex_Material(VertexMaterialClass * mat); - -protected: - - DynamicVectorClass Shaders; - DynamicVectorClass VertexMaterials; - DynamicVectorClass Textures; - - ShaderClass LastShader; - VertexMaterialClass * LastMaterial; - TextureClass * LastTexture; -}; - - - -inline int MaterialInfoClass::Add_Vertex_Material(VertexMaterialClass * vmat) -{ - if (vmat != NULL) { - vmat->Add_Ref(); - } - int index = VertexMaterials.Count(); - VertexMaterials.Add(vmat); - return index; -} - -inline int MaterialInfoClass::Get_Vertex_Material_Index(const char * name) -{ - for (int i=0; iGet_Name()) == 0) { - return i; - } - } - return -1; -} - -inline VertexMaterialClass * MaterialInfoClass::Get_Vertex_Material(int index) -{ - WWASSERT(index >= 0); - WWASSERT(index < VertexMaterials.Count()); - if (VertexMaterials[index]) { - VertexMaterials[index]->Add_Ref(); - } - return VertexMaterials[index]; -} - -inline VertexMaterialClass * MaterialInfoClass::Get_Vertex_Material(const char * name) -{ - int index = Get_Vertex_Material_Index(name); - if (index == -1) { - return NULL; - } else { - return Get_Vertex_Material(index); - } -} - -inline VertexMaterialClass * MaterialInfoClass::Peek_Vertex_Material(int index) -{ - WWASSERT(index >= 0); - WWASSERT(index < VertexMaterials.Count()); - return VertexMaterials[index]; -} - -inline VertexMaterialClass * MaterialInfoClass::Peek_Vertex_Material(const char * name) -{ - int index = Get_Vertex_Material_Index(name); - if (index == -1) { - return NULL; - } else { - return Peek_Vertex_Material(index); - } -} - -inline void MaterialInfoClass::Replace_Material(int index, VertexMaterialClass *newMaterial) -{ - REF_PTR_SET(VertexMaterials[index],newMaterial); -} - -inline void MaterialInfoClass::Reset_Texture_Mappers(void) -{ - int vmat_count = VertexMaterials.Count(); - for (int i = 0; i < vmat_count; i++) { - VertexMaterials[i]->Reset_Mappers(); - } -} - -inline bool MaterialInfoClass::Has_Time_Variant_Texture_Mappers(void) -{ - int vmat_count = VertexMaterials.Count(); - for (int i = 0; i < vmat_count; i++) { - if (VertexMaterials[i]->Are_Mappers_Time_Variant()) return true; - } - return false; -} - -inline void MaterialInfoClass::Make_Vertex_Materials_Unique(void) -{ - int vmat_count = VertexMaterials.Count(); - for (int i = 0; i < vmat_count; i++) { - VertexMaterials[i]->Make_Unique(); - } -} - -inline TextureClass * MaterialInfoClass::Get_Texture(const char * name) -{ - int index = Get_Texture_Index(name); - if (index == -1) { - return NULL; - } else { - return Get_Texture(index); - } -} - -inline TextureClass * MaterialInfoClass::Peek_Texture(int index) -{ - WWASSERT(index >= 0); - WWASSERT(index < Textures.Count()); - return Textures[index]; -} - -inline void MaterialInfoClass::Replace_Texture(int index, TextureClass *newTexture) -{ - REF_PTR_SET(Textures[index],newTexture); -} - -#endif // MATINFO_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp index 321ca0adc8..ea4a07e65c 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/matpass.cpp @@ -26,12 +26,13 @@ * * * Original Author:: Greg Hjelstrom * * * - * $Author:: Greg_h $* + * Author : Kenny Mitchell * + * * + * $Modtime:: 06/27/02 1:27p $* * * - * $Modtime:: 5/13/01 11:19a $* - * * - * $Revision:: 7 $* + * $Revision:: 8 $* * * + * 06/27/02 KM Changes to max texture stage caps * *---------------------------------------------------------------------------------------------* * Functions: * * MaterialPassClass::MaterialPassClass -- Constructor * @@ -90,6 +91,7 @@ MaterialPassClass::MaterialPassClass(void) : * * * HISTORY: * * 12/9/99 gth : Created. * + * 06/27/02 kjm : Changes to max texture stage caps * *=============================================================================================*/ MaterialPassClass::~MaterialPassClass(void) { @@ -117,7 +119,8 @@ void MaterialPassClass::Install_Materials(void) const { DX8Wrapper::Set_Material(Peek_Material()); DX8Wrapper::Set_Shader(Peek_Shader()); - for (unsigned i=0;iGet_Max_Textures_Per_Pass();++i) + { DX8Wrapper::Set_Texture(i,Peek_Texture(i)); } } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshdam.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshdam.cpp deleted file mode 100644 index acbb3e091c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshdam.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/meshdam.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if 0 - - -#include "meshdam.h" -#include "w3d_file.h" -#include "w3derr.h" -#include "chunkio.h" -//#include - - -/*********************************************************************************************** - * DamageClass::DamageClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/28/1997 GH : Created. * - *=============================================================================================*/ -DamageClass::DamageClass(void): - DamageIndex(0), - NumMaterials(0), - NumVerts(0), - NumColors(0), - Verts(NULL), - Colors(NULL) -{ -} - - -/*********************************************************************************************** - * DamageClass::~DamageClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/28/1997 GH : Created. * - *=============================================================================================*/ -DamageClass::~DamageClass(void) -{ - if (Verts != NULL) { - delete [] Verts; - Verts = NULL; - } - - if (Colors != NULL) { - delete[] Colors; - Colors = NULL; - } -} - -/*********************************************************************************************** - * DamageClass::Load -- load damage data from a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/28/1997 GH : Created. * - *=============================================================================================*/ -WW3DErrorType DamageClass::Load(ChunkLoadClass & cload,MeshModelClass * basemesh) -{ -#if 0 - /* - ** Open the first chunk, it should be the damage header - */ - cload.Open_Chunk(); - - if (cload.Cur_Chunk_ID() != W3D_CHUNK_DAMAGE_HEADER) { - return WW3D_ERROR_LOAD_FAILED; - } - - W3dMeshDamageStruct header; - if (cload.Read(&header,sizeof(W3dMeshDamageStruct)) != sizeof(W3dMeshDamageStruct)) { - return WW3D_ERROR_LOAD_FAILED; - } - - cload.Close_Chunk(); - - /* - ** allocate the arrays based on the info in the header - */ - NumVerts = header.NumDamageVerts; - if (NumVerts > 0) { - Verts = W3DNEWARRAY DamageVertexStruct[NumVerts]; - } - - NumColors = header.NumDamageColors; - if (NumColors > 0) { - Colors = W3DNEWARRAY DamageColorStruct[NumColors]; - } - - // TODO: allocate materials - - /* - ** Now read in the rest of the chunks - */ - while (1) { - - /* - ** Read in the chunk header - ** If there are no more chunks within the chunk, we are done. - */ - if (!cload.Open_Chunk()) { - return WW3D_ERROR_OK; - } - - /* - ** Process the chunk - */ - int error = WW3D_ERROR_OK; - - switch (cload.Cur_Chunk_ID()) { - -// case W3D_CHUNK_DAMAGE_MATERIALS: -// //TODO: read new set of materials -// break; - - case W3D_CHUNK_DAMAGE_VERTICES: - error = read_vertices(cload,basemesh); - break; - - case W3D_CHUNK_DAMAGE_COLORS: - error = read_colors(cload,basemesh); - break; - - default: - break; - - } - - cload.Close_Chunk(); - - if (error != WW3D_ERROR_OK) { - return error; - } - } -#endif - - return WW3D_ERROR_OK; -} - -/*********************************************************************************************** - * DamageClass::read_vertices -- read damage vertices from a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/04/1997 GH : Created. * - *=============================================================================================*/ -WW3DErrorType DamageClass::read_vertices(ChunkLoadClass & cload,MeshModelClass * basemesh) -{ -#if 0 - W3dMeshDamageVertexStruct dv; - - for (int i=0; igetVertexLoc(); - - srVector3 sr_v; - sr_v = vert_array[dv.VertexIndex]; - - Verts[i].VertexIdx = dv.VertexIndex; - Verts[i].Vertex0.Set(sr_v[0],sr_v[1],sr_v[2]); - Verts[i].Vertex1.Set(dv.NewVertex.X,dv.NewVertex.Y,dv.NewVertex.Z); - } -#endif - return WW3D_ERROR_OK; -} - -/*********************************************************************************************** - * DamageClass::read_colors -- read damage colors from a w3d file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/04/1997 GH : Created. * - *=============================================================================================*/ -WW3DErrorType DamageClass::read_colors(ChunkLoadClass & cload,MeshModelClass * basemesh) -{ -#if 0 - W3dMeshDamageColorStruct dc; - - for (int i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/meshdam.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if 0 - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MESHDAM_H -#define MESHDAM_H - -#include "always.h" -#include "vector3.h" -#include "bittype.h" -#include "w3derr.h" - -class MeshModelClass; -class ChunkLoadClass; - -struct RGBStruct -{ - uint8 R,G,B; -}; - -struct DamageVertexStruct -{ - int VertexIdx; // index of the vertex to "damage" - Vector3 Vertex0; // original vertex position - Vector3 Vertex1; // damaged vertex position -}; - -struct DamageColorStruct -{ - int VertexIdx; // index of the vertex to damage. - RGBStruct Color0; // original color. - RGBStruct Color1; // damaged color. -}; - - -/* -** DamageClass - this class encapsulates the information needed -** to apply damage to meshes. It contains replacement vertices, -** vertex colors and materials -*/ -class DamageClass -{ -public: - - DamageClass(void); - ~DamageClass(void); - - WW3DErrorType Load_W3D(ChunkLoadClass & cload,MeshModelClass * basemesh); - -protected: - - WW3DErrorType read_vertices(ChunkLoadClass & cload,MeshModelClass * basemesh); - WW3DErrorType read_colors(ChunkLoadClass & cload,MeshModelClass * basemesh); - - int DamageIndex; - int NumMaterials; - int NumVerts; - int NumColors; - - DamageVertexStruct * Verts; - DamageColorStruct * Colors; - - friend class MeshClass; -}; - - -#endif - - -#endif //0 \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp index bc96aec7c5..49d1bdc338 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp @@ -102,8 +102,6 @@ MeshModelClass::MeshModelClass(const MeshModelClass & that) : MeshModelClass::~MeshModelClass(void) { -// WWDEBUG_SAY(("Note: Mesh %s was never used\n",Get_Name())); - TheDX8MeshRenderer.Unregister_Mesh_Type(this); Reset(0,0,0); REF_PTR_RELEASE(MatInfo); @@ -141,7 +139,7 @@ MeshModelClass & MeshModelClass::operator = (const MeshModelClass & that) clone_materials(that); if (GapFiller) { - delete[] GapFiller; + delete GapFiller; GapFiller=NULL; } if (that.GapFiller) GapFiller=W3DNEW GapFillerClass(*that.GapFiller); @@ -151,6 +149,11 @@ MeshModelClass & MeshModelClass::operator = (const MeshModelClass & that) void MeshModelClass::Reset(int polycount,int vertcount,int passcount) { + //DMS - We must delete the gapfiller object BEFORE the geometry is reset. Otherwise, + // the number of stages and passes gets reset and the gapfiller cannot deallocate properly. + delete GapFiller; + GapFiller=NULL; + Reset_Geometry(polycount,vertcount); // Release everything we have and reset to initial state @@ -165,9 +168,6 @@ void MeshModelClass::Reset(int polycount,int vertcount,int passcount) } CurMatDesc = DefMatDesc; - delete GapFiller; - GapFiller=NULL; - return ; } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/metalmap.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/metalmap.cpp deleted file mode 100644 index a5a034fd99..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/metalmap.cpp +++ /dev/null @@ -1,423 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/metalmap.cpp $* - * * - * $Author:: Hector_y $* - * * - * $Modtime:: 6/27/01 4:59p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * MMMC::MetalMapManagerClass -- Create metal map manager according to given metal parameters* - * MMMC::MetalMapManagerClass -- Create metal map manager from INI * - * MMMC::~MetalMapManagerClass -- MetalMapManagerClass destructor * - * MMMC::Get_Metal_Map -- Get the texture for a metal map by id number * - * MMMC::Metal_Map_Count -- Get the number of metal maps in the manager * - * MMMC::Update_Lighting -- Update the lighting parameters used for generating the maps * - * MMMC::Update_Textures -- Update metal map textures (call once/frame before rendering) * - * MMMC::initialize_normal_table -- Utility function to initialize the normal table * - * MMMC::initialize_metal_params -- Utility function (shared CTor code) * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "metalmap.h" -#include "texture.h" -#include "ww3dformat.h" -#include "ww3d.h" -#include -#include -#include -#include -#include -#include -#include - -/* -** Class static members: -*/ -Vector3 * MetalMapManagerClass::_NormalTable = 0; - -/*********************************************************************************************** - * MMMC::MetalMapManagerClass -- Create metal map manager from INI * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/1999 NH : Created. * - *=============================================================================================*/ -MetalMapManagerClass::MetalMapManagerClass(INIClass &ini) : - MapCount(0), - Textures(0), - MetalParameters(0), - CurrentAmbient(0.0f, 0.0f, 0.0f), - CurrentMainLightColor(0.0f, 0.0f, 0.0f), - CurrentMainLightDir(1.0f, 0.0f, 0.0f), - CurrentCameraDir(1.0f,0.0f,0.0f), - Use16Bit(false) -{ - - // If the static normal table has not been initialized yet, initialize it - if (!_NormalTable) { - initialize_normal_table(); - } - - // Determine how many metals are in this file - char section[255]; - - int lp = 0; - for (; ; lp++) { - sprintf(section, "Metal%02d", lp); - if (!ini.Find_Section(section)) { - break; // NAK - Mar 8, 2000: changed to a break to fix off by one error in lp - } - } - - if (lp > 0) { - // Create metal params structs and fill from INI: - MetalParams *metal_params = W3DNEWARRAY MetalParams[lp]; - TPoint3D white_tpoint(255.0f, 255.0f, 255.0f); - Vector3 white(1.0f, 1.0f, 1.0f); - Vector3 black(0.0f, 0.0f, 0.0f); - for (int i = 0; i < lp; i++) { - sprintf(section, "Metal%02d", i); - static const float cf = 0.003921568627451f; // 1 / 255 - TPoint3D color; - color = ini.Get_Point(section, "AmbientColor", white_tpoint); - metal_params[i].AmbientColor.Set(color.X * cf, color.Y * cf, color.Z * cf); - metal_params[i].AmbientColor.Update_Min(white); - metal_params[i].AmbientColor.Update_Max(black); - color = ini.Get_Point(section, "DiffuseColor", white_tpoint); - metal_params[i].DiffuseColor.Set(color.X * cf, color.Y * cf, color.Z * cf); - metal_params[i].AmbientColor.Update_Min(white); - metal_params[i].AmbientColor.Update_Max(black); - color = ini.Get_Point(section, "SpecularColor", white_tpoint); - metal_params[i].SpecularColor.Set(color.X * cf, color.Y * cf, color.Z * cf); - metal_params[i].AmbientColor.Update_Min(white); - metal_params[i].AmbientColor.Update_Max(black); - float shininess = ini.Get_Float(section, "Shininess", 0.0f); - metal_params[i].Shininess = WWMath::Clamp(shininess, 0.0f, 127.0f); - } - - initialize_metal_params(lp, metal_params); - delete [] metal_params; - } else { - assert(0); - } - - int w,h,bits; - bool windowed; - - WW3D::Get_Device_Resolution(w,h,bits,windowed); - Use16Bit=(bits<=16); - - WW3DFormat format=(Use16Bit?WW3D_FORMAT_A4R4G4B4:WW3D_FORMAT_A8R8G8B8); - - - for (int i = 0; i < lp; i++) { - Textures[i]=NEW_REF(TextureClass,(METALMAP_SIZE,METALMAP_SIZE,format,MIP_LEVELS_1)); - Textures[i]->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - Textures[i]->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - StringClass tex_name; - tex_name.Format("!m%02d.tga", i); - Textures[i]->Set_Texture_Name(tex_name); - } -} - - -/*********************************************************************************************** - * MMMC::~MetalMapManagerClass -- MetalMapManagerClass destructor * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/1999 NH : Created. * - *=============================================================================================*/ -MetalMapManagerClass::~MetalMapManagerClass(void) -{ - if (Textures) { - for (int i = 0; i < MapCount; i++) { - REF_PTR_RELEASE(Textures[i]); - } - delete [] Textures; - Textures = 0; - } - if (MetalParameters) { - delete [] MetalParameters; - MetalParameters = 0; - } -} - - -/*********************************************************************************************** - * MMMC::Get_Metal_Map -- Get the texture for a metal map by id number * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/1999 NH : Created. * - *=============================================================================================*/ -TextureClass * MetalMapManagerClass::Get_Metal_Map(int id) -{ - if (id < 0 || id >= MapCount) return 0; - Textures[id]->Add_Ref(); - return Textures[id]; -} - - -/*********************************************************************************************** - * MMMC::Metal_Map_Count -- Get the number of metal maps in the manager * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/1999 NH : Created. * - *=============================================================================================*/ -int MetalMapManagerClass::Metal_Map_Count(void) -{ - return MapCount; -} - - -/*********************************************************************************************** - * MMMC::Update_Lighting -- Update the lighting parameters used for generating the maps * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/1999 NH : Created. * - *=============================================================================================*/ -void MetalMapManagerClass::Update_Lighting(const Vector3& ambient, const Vector3& main_light_color, - const Vector3& main_light_dir, const Vector3& camera_dir) -{ - CurrentAmbient = ambient; - CurrentMainLightColor = main_light_color; - CurrentMainLightDir = main_light_dir; - CurrentCameraDir= camera_dir; -} - -/*********************************************************************************************** - * MMMC::Update_Textures -- Update metal map textures (call once/frame before rendering) * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/1999 NH : Created. * - *=============================================================================================*/ -void MetalMapManagerClass::Update_Textures(void) -{ - // Currently the lighting is done using a simple Phong (actually Blinn) model. - Vector3 &l = CurrentMainLightDir; - Vector3 &v = CurrentCameraDir; - - // Calculate halfway vector - Vector3 h = l+v; - h.Normalize(); - - // NOTE: when our lighting equation gets more complicated we might want to do some testing to - // detect zero components... - - // Calculate quantities which are the same for all metal maps - float n_dot_l[METALMAP_SIZE_2]; - float n_dot_h[METALMAP_SIZE_2]; - - VectorProcessorClass::DotProduct(n_dot_l,l,_NormalTable,METALMAP_SIZE_2); - VectorProcessorClass::ClampMin(n_dot_l, n_dot_l, 0.0f, METALMAP_SIZE_2); - VectorProcessorClass::DotProduct(n_dot_h,h,_NormalTable, METALMAP_SIZE_2); - VectorProcessorClass::ClampMin(n_dot_h, n_dot_h, 0.0f, METALMAP_SIZE_2); - - // Loop over each metal map and update it - for (int i = 0; i < MapCount; i++) { - MetalParams &cur_params = MetalParameters[i]; - - // If shinyness > 1, apply it to specular value array - float *specular = 0; - float temp_specular[METALMAP_SIZE_2]; - float shinyness = cur_params.Shininess; - if (shinyness > 1.0f) { - VectorProcessorClass::Power(temp_specular, n_dot_h, shinyness, METALMAP_SIZE_2); - specular = &(temp_specular[0]); - } else { - specular = &(n_dot_h[0]); - } - - // Generate metal map row by row - Vector3 specular_color(cur_params.SpecularColor.X * CurrentMainLightColor.X, - cur_params.SpecularColor.Y * CurrentMainLightColor.Y, - cur_params.SpecularColor.Z * CurrentMainLightColor.Z); - Vector3 diffuse_color(cur_params.DiffuseColor.X * CurrentMainLightColor.X, - cur_params.DiffuseColor.Y * CurrentMainLightColor.Y, - cur_params.DiffuseColor.Z * CurrentMainLightColor.Z); - Vector3 ambient_color(cur_params.AmbientColor.X * CurrentAmbient.X, - cur_params.AmbientColor.Y * CurrentAmbient.Y, - cur_params.AmbientColor.Z * CurrentAmbient.Z); - Vector3 white(1.0f, 1.0f, 1.0f); - - SurfaceClass * metal_map_surface = Textures[i]->Get_Surface_Level(0); - int pitch; - unsigned char *map=(unsigned char *) metal_map_surface->Lock(&pitch); - int idx=0; - for (int y = 0; y < METALMAP_SIZE; y++) { - for (int x = 0; x < METALMAP_SIZE; x++) { - Vector3 result = ambient_color + (diffuse_color * n_dot_l[idx]) + (specular_color * specular[idx]); - result.Update_Min(white); // Clamp to white - - unsigned char b,g,r,a; - b= (unsigned char)WWMath::Floor(result.Z * 255.99f); // B - g= (unsigned char)WWMath::Floor(result.Y * 255.99f); // G - r= (unsigned char)WWMath::Floor(result.X * 255.99f); // R - a= 0xFF; // A - - if (Use16Bit) { - unsigned short tmp; - tmp=(a&0xf0)<<8; - tmp|=(r&0xf0)<<4; - tmp|=(g&0xf0); - tmp|=(b&0xf0)>>4; - *(unsigned short*)&map[2*x]=tmp; - } else { - map[4*x]=b; - map[4*x+1]=g; - map[4*x+2]=r; - map[4*x+3]=a; - } - idx++; - } - map+=pitch; - } - metal_map_surface->Unlock(); - REF_PTR_RELEASE(metal_map_surface); - } // for i -} - -/*********************************************************************************************** - * MMMC::initialize_normal_table -- Utility function to initialize the normal table * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/1999 NH : Created. * - *=============================================================================================*/ -void MetalMapManagerClass::initialize_normal_table(void) -{ - // NOTE: changing the actual static _NormalTable member must be the last thing this function - // does to avoid synchronization errors. - - static Vector3 _normal_table[METALMAP_SIZE_2]; - - // Calculate vectors (area outside sphere should be filled with a radial fill of the vectors at - // the sphere's edge to avoid aliasing artifacts) - float step = 2.0f / (float)METALMAP_SIZE; - int idx = 0; - for (int y = 0; y < METALMAP_SIZE; y++) { - for (int x = 0; x < METALMAP_SIZE; x++) { - Vector3 &normal = _normal_table[idx]; - // Set vector to point to surface of unit sphere - normal.Set((step * (float)x) - 1.0f, (step * (float)y) - 1.0f, 0.0f); - float z2 = 1 - ((normal.X * normal.X) + (normal.Y * normal.Y)); - z2 = MAX(z2, 0.0f); // If outside the sphere, treat as if on its edge - normal.Z = sqrt(z2); - normal.Normalize(); // Needed for "outside sphere" case and for safety's sake - - idx++; - } - } - - _NormalTable = &(_normal_table[0]); - -} - -/*********************************************************************************************** - * MMMC::initialize_metal_params -- Utility function (shared CTor code) * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/1999 NH : Created. * - *=============================================================================================*/ -void MetalMapManagerClass::initialize_metal_params(int map_count, MetalParams *metal_params) -{ - MapCount = map_count; - if (MapCount > 0) { - Textures = W3DNEWARRAY TextureClass *[MapCount]; - MetalParameters = W3DNEWARRAY MetalParams[MapCount]; - - for (int i = 0; i < MapCount; i++) { - - // Copy metal parameters (assert if invalid) - MetalParameters[i] = metal_params[i]; - assert(MetalParameters[i].AmbientColor.X >= 0.0f && MetalParameters[i].AmbientColor.X <= 1.0f); - assert(MetalParameters[i].AmbientColor.Y >= 0.0f && MetalParameters[i].AmbientColor.Y <= 1.0f); - assert(MetalParameters[i].AmbientColor.Z >= 0.0f && MetalParameters[i].AmbientColor.Z <= 1.0f); - assert(MetalParameters[i].DiffuseColor.X >= 0.0f && MetalParameters[i].DiffuseColor.X <= 1.0f); - assert(MetalParameters[i].DiffuseColor.Y >= 0.0f && MetalParameters[i].DiffuseColor.Y <= 1.0f); - assert(MetalParameters[i].DiffuseColor.Z >= 0.0f && MetalParameters[i].DiffuseColor.Z <= 1.0f); - assert(MetalParameters[i].SpecularColor.X >= 0.0f && MetalParameters[i].SpecularColor.X <= 1.0f); - assert(MetalParameters[i].SpecularColor.Y >= 0.0f && MetalParameters[i].SpecularColor.Y <= 1.0f); - assert(MetalParameters[i].SpecularColor.Z >= 0.0f && MetalParameters[i].SpecularColor.Z <= 1.0f); - assert(MetalParameters[i].Shininess > 0.0f); - } - } -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/metalmap.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/metalmap.h deleted file mode 100644 index 00e93108e6..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/metalmap.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/metalmap.h $* - * * - * $Author:: Hector_y $* - * * - * $Modtime:: 6/27/01 4:30p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef METALMAP_H -#define METALMAP_H - -#include - -class TextureClass; -class INIClass; - -/* -** MetalMapManagerClass: This class updates the procedural environment maps -** (aka metal maps) based on the global lighting environment. -** At the moment the metal maps are shaded using a simple Phong model - in -** future this may be extended to more complex and realistic shading -** (Cook-Torrance, etc.) which would require changing the metal parameters. -** Another possible extension would be to support a large dynamic range for -** the main light source (currently its color is treated as an RGB triple -** which is bound to 0,1). -*/ - -// If this is increased too much the metal map updates will be too expensive -#define METALMAP_SIZE 16 -#define METALMAP_SIZE_2 (METALMAP_SIZE * METALMAP_SIZE) - -class MetalMapManagerClass { - -public: - - // These parameters are for a simple Phong reflectance model - struct MetalParams { - Vector3 AmbientColor; - Vector3 DiffuseColor; - Vector3 SpecularColor; - float Shininess; - }; - - // Create metal map manager with maps specified by INI file - MetalMapManagerClass(INIClass &ini); - ~MetalMapManagerClass(void); - - // Get the texture for a metal map by id number - TextureClass * Get_Metal_Map(int id); - - // Get the number of metal maps in the manager - int Metal_Map_Count(void); - - // Update the lighting parameters used for generating the maps - void Update_Lighting(const Vector3& ambient, const Vector3& main_light_color, - const Vector3& main_light_dir, const Vector3& camera_dir); - - // Update the metal map textures (should call once/frame before rendering) - void Update_Textures(void); - -private: - - // 16 x 16 table of cameraspace normals for the environment maps - static Vector3 * _NormalTable; - void initialize_normal_table(void); // Utility function - - // Utility function - shared CTor code - void initialize_metal_params(int map_count, MetalParams *metal_params); - - // Number of metal maps - int MapCount; - - // Array of metal map texture pointers - TextureClass ** Textures; - - // Array of metal parameters - MetalParams * MetalParameters; - - // Current lighting parameters - Vector3 CurrentAmbient; - Vector3 CurrentMainLightColor; - Vector3 CurrentMainLightDir; - Vector3 CurrentCameraDir; - - // Use 16-bit metal maps or not - bool Use16Bit; -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp deleted file mode 100644 index df80ba92b0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.cpp +++ /dev/null @@ -1,711 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// 08/05/02 KM Texture class redesign -#include "missingtexture.h" -#include "texture.h" -#include "dx8wrapper.h" -#include - -static unsigned missing_image_width=128; -static unsigned missing_image_height=128; -static unsigned missing_image_depth=24; - -extern unsigned int missing_image_palette[]; -extern unsigned int missing_image_pixels[]; - -static IDirect3DTexture8 * _MissingTexture = NULL; - -IDirect3DTexture8* MissingTexture::_Get_Missing_Texture() -{ - WWASSERT(_MissingTexture); - _MissingTexture->AddRef(); - return _MissingTexture; -} - -IDirect3DSurface8* MissingTexture::_Create_Missing_Surface() -{ - IDirect3DSurface8 *texture_surface = NULL; - DX8_ErrorCode(_MissingTexture->GetSurfaceLevel(0, &texture_surface)); - D3DSURFACE_DESC texture_surface_desc; - ::ZeroMemory(&texture_surface_desc, sizeof(D3DSURFACE_DESC)); - DX8_ErrorCode(texture_surface->GetDesc(&texture_surface_desc)); - - IDirect3DSurface8 *surface = NULL; - DX8CALL(CreateImageSurface( - texture_surface_desc.Width, - texture_surface_desc.Height, - texture_surface_desc.Format, - &surface)); - DX8CALL(CopyRects(texture_surface, NULL, 0, surface, NULL)); - texture_surface->Release(); - return surface; -} - -void MissingTexture::_Init() -{ - WWASSERT(!_MissingTexture); - - IDirect3DTexture8* tex=DX8Wrapper::_Create_DX8_Texture - ( - missing_image_width, - missing_image_height, - WW3D_FORMAT_A8R8G8B8, - MIP_LEVELS_ALL - ); - - D3DLOCKED_RECT locked_rect; - RECT rect; - rect.left=0; - rect.right=missing_image_width; - rect.top=0; - rect.bottom=missing_image_height; - DX8_ErrorCode( - tex->LockRect( - 0, - &locked_rect, - &rect, - 0)); - - unsigned *buffer=(unsigned*)locked_rect.pBits; - unsigned char *pixels=(unsigned char *)missing_image_pixels; - for (unsigned y=0;yUnlockRect(0)); - - for (unsigned i=1;iGetLevelCount();++i) { - IDirect3DSurface8 *src,*dst; - DX8_ErrorCode(tex->GetSurfaceLevel(i-1,&src)); - DX8_ErrorCode(tex->GetSurfaceLevel(i,&dst)); - - DX8_ErrorCode(D3DXLoadSurfaceFromSurface( - dst, - NULL, // palette - NULL, // rect - src, - NULL, // palette - NULL, // rect - D3DX_FILTER_BOX, // box is good for 2:1 filtering - 0)); - - src->Release(); - dst->Release(); - } - - _MissingTexture=tex; -/* - //Load an 8-bit tga and generate text representation - FILE *fp; - fp=fopen("missing.tga","rb"); - if (fp) - { - char image[128*128]; //make enough storage for image and palette - char palette[256*3]; - fread(image,18,1,fp); //skip over the header - fread(palette,256,3,fp); //read the palette - fread(image,1,128*128,fp); - FILE *output=fopen("missing.txt","w"); - fprintf(output,"palette:\n"); - for (int i=0; i<256; i++) - { int color=(((int)palette[i*3+0] & 0x000000ff)|(((int)palette[i*3+1] << 8)&0x0000ff00)|(((int)palette[i*3+2] << 16)&0x00ff0000)) | 0x7f000000; - fprintf(output,"0x%.8X",color); - if ((i&7) == 7) //check for end of 8 element line - fprintf(output,",\n"); //new line - else - fprintf(output,","); //continue existing line - } - fprintf(output,"image:\n"); - for (int y=0; y<128; y++) - { - for (int x=0; x<32; x++) - { int color=*((int *)(&image[y*128+x*4])); - fprintf(output,"0x%.8X",color); - if ((x&7)==7) //check for end of 8 element line - fprintf(output,",\n"); //new line - else - fprintf(output,","); //continue existing line - } - } - fclose(output); - fclose(fp); - } -*/ -} - -void MissingTexture::_Deinit() -{ - _MissingTexture->Release(); - _MissingTexture=0; -} - -static unsigned int missing_image_palette[]={ -0x7F040204,0x7F048AC4,0x7F84829C,0x7FFC0204,0x7F0442AB,0x7FFCFE04,0x7F444244,0x7F0462FC, -0x7F84CEE4,0x7FC4C6CF,0x7F9CA6B2,0x7FC4E6F4,0x7F04FE04,0x7F4C82D4,0x7F2452A1,0x7F0442D4, -0x7F446AB0,0x7FA4A6B6,0x7F2C62C2,0x7FE4E6E9,0x7F646264,0x7F0402FC,0x7FC4D6E1,0x7F44B6DC, -0x7FB4C6D4,0x7F8496A9,0x7F049ECC,0x7F0C52C9,0x7FA4B6C4,0x7FA4DEEC,0x7F0472FC,0x7F3C72C4, -0x7F84A6DF,0x7F748294,0x7F24A6D4,0x7F1442A4,0x7F0452DA,0x7FE4F6FC,0x7FD4D6D6,0x7F849EC9, -0x7F242224,0x7FBCD6F7,0x7FB4B6C2,0x7FD4F6F7,0x7F747274,0x7F0442BF,0x7F4C7ABC,0x7FACC6EC, -0x7F9496AB,0x7F343234,0x7F042A98,0x7F648ADC,0x7F1C5AD4,0x7F545254,0x7F1C62D8,0x7FDCE6E9, -0x7F0452EE,0x7F043AA2,0x7FC4CED3,0x7F2C62D4,0x7F34B6D4,0x7FB4BED9,0x7F6CA6EC,0x7F2C72EC, -0x7F94B6E8,0x7F8482A4,0x7F8CA6CC,0x7F5C72AC,0x7FE4EEEF,0x7FC4D6FC,0x7F1472FC,0x7F7C96C4, -0x7FF4F6F7,0x7FD4DEE3,0x7F6C728C,0x7F949EA4,0x7F5CC6E4,0x7F245ABC,0x7F4472C4,0x7F149ECD, -0x7F6C82BC,0x7F34AED5,0x7F242251,0x7FB4BEC9,0x7F044AC8,0x7FBCCEF0,0x7F1462FC,0x7FD4EEF4, -0x7FC4CEDC,0x7F7C7A97,0x7F0C4AB4,0x7FA4AEBC,0x7F3C62B4,0x7F646284,0x7FBCCEE4,0x7F1C52B7, -0x7F0C5AE2,0x7F043294,0x7F3472E8,0x7F9CB6E1,0x7F74C6E4,0x7F2482FC,0x7F0C42AD,0x7F44426A, -0x7F9CDEEC,0x7F5C9EFC,0x7FB4C6E1,0x7F8C9EAC,0x7FACBED0,0x7F5C7AAC,0x7FB4CEF2,0x7F35325C, -0x7F4C5274,0x7FD4E6F9,0x7F64BEDF,0x7FECEEF2,0x7FDCDEE2,0x7F747A94,0x7F949EB0,0x7F19A6D4, -0x7F342A58,0x7F0C4AC0,0x7F746A8C,0x7F96D6EC,0x7F4C82EC,0x7F345AB0,0x7F044ADA,0x7F4C72B9, -0x7FCCD6E2,0x7F141214,0x7F6496EC,0x7F0696CC,0x7F7C9ECC,0x7F1482FC,0x7F241A4C,0x7FB8E6F4, -0x7F58BEDC,0x7F7CA6E4,0x7F544A74,0x7F5C5A7D,0x7F9CAED0,0x7F443A64,0x7F8CBEFC,0x7F3C6AC9, -0x7F1C5AC8,0x7F848A9C,0x7F8CAEEC,0x7F7C8A9C,0x7F144AB4,0x7F247AFC,0x7FC4DEF4,0x7F6CC6E4, -0x7F2C2A56,0x7F146AF8,0x7F347AF4,0x7F4C4A70,0x7F448AFC,0x7F6C9EFC,0x7F8BD6EC,0x7FC8EEF4, -0x7F2C5AA4,0x7F0A7AFC,0x7FECFEFC,0x7F2C2A2C,0x7F045AF4,0x7F848AA5,0x7F94AED0,0x7FFCFEFC, -0x7F6C8AC4,0x7F646A8A,0x7F3C3A62,0x7F0A6AFC,0x7F9CAEBC,0x7F2C6ACC,0x7FACE6EC,0x7F28AED4, -0x7F043AAF,0x7F2C6ADB,0x7F157AFC,0x7F245AD4,0x7F0432A0,0x7F79CEE4,0x7F7CAEF4,0x7F3C72D8, -0x7F8C96A7,0x7F1452BC,0x7FACB6C3,0x7F7C8299,0x7F0C52D8,0x7F547AC3,0x7FB4C6EC,0x7FCCD6EC, -0x7FBCBEC5,0x7FACAEC0,0x7F94BEF4,0x7F8C8A8E,0x7F1C4AA4,0x7F2C7AEC,0x7F1C6AF0,0x7F3C7AE4, -0x7FCCE6FC,0x7F5482D0,0x7FECE6EC,0x7FBCC6D1,0x7F0C72FB,0x7FECF6F5,0x7FDCF6FA,0x7F0C3AA4, -0x7FCCCECD,0x7F3CB6D7,0x7FBCBED4,0x7FFCF6FC,0x7F74728F,0x7F9C9E9C,0x7F64C6E3,0x7F4C72C5, -0x7F1C9ED0,0x7F3CAED7,0x7FDCEEFC,0x7FCCCEDF,0x7F0C328C,0x7F2C82F4,0x7FBCC6DC,0x7F545275, -0x7FDCE6F8,0x7F9C9EB0,0x7FCCDEEC,0x7F0C5AF0,0x7F8C8AA5,0x7F748ABC,0x7F6C6A8A,0x7F0442B4, -0x7F0C62FC,0x7FC4C6DC,0x7F9CA6BC,0x7F0442E4,0x7F446ABC,0x7F2C62CC,0x7F4CB6DC,0x7F0C9ECC, -0x7FACDEEC,0x7F2CA6D4,0x7F0452E4,0x7FD4D6E4,0x7F849ED4,0x7FB4B6CC,0x7F4C7ACC,0x7FACC6FC, -0x7F9496B4,0x7F042AA4,0x7F1C62E4,0x7F74A6EC,0x7FE4EEFC,0x7F1C72FC,0x7FD4DEEC,0x7F2C5ABC}; - -static unsigned int missing_image_pixels[]={ -0x03030303,0x03030303,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0xD574A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xC3C3C3C0,0xA7A7A7C3,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0x00C3A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A700A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A700,0xA7A7A7A7,0x00000006,0xA7A70000,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0x00C3A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A70000,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A70000,0xA7A7A7A7,0xA7A70606,0xA7C300A7,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0x00C3A7A7,0xA7A7A7A7,0x3174A7A7,0xA33131A3,0x31A33131, -0x3131A331,0xA33131A3,0x31A33131,0x3131A331,0xA33131A3,0x31A33131,0x3131A331,0xA33131A3, -0x31A33131,0x3131A331,0xA33131A3,0x31A33131,0x3131A331,0xA33131A3,0x31A33131,0x3131A331, -0xA33131A3,0x74A33131,0xA7A7A7A7,0xC3C32806,0xA7C00014,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0x00C3A7A7,0xA7A7A7A7,0x0026A7A7,0x00000000,0x00000000, -0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, -0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, -0x00000000,0x26000000,0xA7A7A7A7,0x00000006,0xA7A72C00,0xA7A7A7A7,0x05050505,0x05050505, -0x03030303,0x03030303,0xA7A7A7A7,0x00C3A7A7,0xA7A7A7A7,0xD0D3A7A7,0xD0D00000,0xD0D0D0D0, -0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0, -0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0,0xD0D0D0D0, -0xD0D0D0D0,0xD3D00000,0xA7A7A7A7,0x74A70606,0xA7A7D500,0xA7A7A7A7,0x05050505,0x05050505, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x00C3A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A700A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A700,0xA7A7A7A7,0xA7A70606,0xA7A7002C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x00C3A7A7,0xC3000000,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A70606,0xA70681A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC0A7A7A7,0xC3C3C3C3,0xA7A7A7C3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x14A7A7A7,0x00000000,0xA7A7A700,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA700C3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA700C3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA700C3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA700C3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA700C3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA700C3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x48D026A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x0000A300,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x00A7A7A7,0x00002800,0xA7A7A700,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x48D348A2, -0xA7A7A7D3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x7373D3A7,0x44131313,0x73737373, -0x73737373,0xD3CD4873,0xA7A7A7D3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x1348A7A7,0x2680D026,0x44CA37FE,0xCDCDCD73, -0xCDCDCDCD,0x737348CD,0x26487373,0xA7A748C0,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x2AD226D3,0x26DB3ACB,0x73443774,0x484848CD, -0x48D348D3,0xCDCDCD48,0xFE48CDCD,0xCA2A5902,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x0973A7A7,0x2ABA5B5B,0xFEDB3ACB,0x733774FE,0xCD48A273, -0xA7A2A748,0xCDD3A7A2,0x48CD4848,0x7A30CBBF,0xA7A7CA11,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xF8E10948,0xCBF5C1EA,0x37BF0909,0xF558BFFE,0xA519F8C1, -0x5BF8B819,0xA7A28053,0xCD48A2A7,0xCBF3F374,0xA7C15930,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xF3A7A7A7,0xE1B8E4E1,0xDBD2C15B,0xEADBBF80,0x5B76BBBB,0xC0C0532A, -0x5B2A5309,0x7691A5E1,0xA7A2133D,0xBF588073,0x02E43DF3,0xA7A7A7F3,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x59C0A7A7,0xC1F8E459,0xBFFE74DB,0x0AD4BB53,0xA748CAD0,0xA7A7A7A7, -0xA7A7A7A7,0xC074D3A7,0x740A4A91,0xF3BFFE48,0xBA80BF58,0xA7A72AE6,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x59D41173,0xBF5811E4,0xBB7616FE,0xA7730911,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x4B2ACAA7,0xFEFEBA91,0xF35858BF,0xA7304AD2,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x13A7A7A7,0xB8D45D02,0x58BF583D,0x745B91F8,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x5B937609,0xBFBFFEFE,0x59A95880,0xA7A7A773,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xD426A7A7,0x58EAD48B,0xBBBABF58,0xA7A774D5,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x9109A7A7,0x58FE58B8,0xA980BFBF,0xA7A773E6,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x9B5D74A7,0x74803DD4,0x80BB76F3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xD3A7A7A7,0x135375BA,0xBFF3DBDB,0xA7485DA9,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x759BA9CA,0x58BF80F5,0xA748B8B8,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xACBBD0A7,0x588080FE,0xA77A7058,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x48A7A7A7,0x5859AAD4,0x2158BF80,0xA7A7A711,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x9173A7A7,0x80BFFEB8,0xE4AAD280,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xE4A7A7A7,0xF3807598,0xC07558FE,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x48A7A7A7,0x80FEA530,0x9811FEBF,0xA7A7A7C1, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x5211A7A7,0x49F3585D,0xA709BB58,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xFE6BE1D3,0x7549BFBF,0xA7A7DB98, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x676F74A7,0xFEBF803D,0xA7A7BABB,0xA7A7A7A7,0x48A7A7A7,0x48484848,0x48484848,0x48484848, -0x48484848,0xA7A7A748,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xF891A7A7,0xE9FE8074,0xA7A78B6F, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xEA985DA7,0xA58058F3,0xA7A7A70A,0xA7A7A7A7,0x8F55A7A7,0x4ED74ED7,0x4ED74ED7,0x4ED74ED7, -0x8F7F4ED7,0xA7A748A8,0xA7A77463,0xA7A7A7A7,0xA7A7A7A7,0xBB73A7A7,0x8058FEBA,0xA711520A, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xFEE4862A,0xBBEABF58,0xA7A7A7D3,0xA7A7A7A7,0xB45CCDA7,0xB0B039F9,0x39B0B0B0,0xB0B039B0, -0xF9B0B039,0x6EA7A742,0xA7A75039,0xA7A7A7A7,0xA7A7A7A7,0x49A7A7A7,0xDB745875,0x73AA8BFE, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x73A7A7A7, -0xBF80DF9B,0x13BB5880,0xA7A7A7A7,0xA7A7A7A7,0x043984A7,0xE7040404,0xE7545AE7,0x5A2D5A54, -0xBDB05A54,0x1FCDA7A7,0xA7DE04F9,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xBFFEB8C0,0xE452BA80, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x11A7A7A7, -0x80F3BA86,0xA7539337,0xA7A7A7A7,0xA7A7A7A7,0x39B404DB,0xB0B0B0B0,0xB0B0B0B0,0xB0B0B0B0, -0x7494B0B0,0xB089A7A7,0x737D3904,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xFEACB8A7,0x985DBFF3, -0xA7A7A7CA,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xDF48A7A7, -0xBF58808B,0xA7D3913D,0xA7A7A7A7,0xA7A7A7A7,0xBDBD7F8C,0xBDC9BDBD,0xBDBDC9BD,0xC9BDBDC9, -0xA7A6D7BD,0x041B96A7,0x47390404,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x809126A7,0x98E1F3BF, -0xA7A7A711,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x98F5A7A7, -0xBFBFBFBA,0xA7A726BB,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x5AB00DA2,0x6639045A,0xA7A7A780,0xA7A7A7A7,0xA7A7A7A7,0xEA0AA7A7,0x7058BFF3, -0xA7A773DF,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x8B5DA7A7, -0xBA74BFFE,0xA7A7D3A5,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x5A542D40,0xB0E75A5A,0xA7A7485C,0xA7A7A7A7,0xA7A7A7A7,0x91F3A7A7,0x59BFF3BF, -0xA7A72A6F,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x116F26A7, -0xB8BF80FE,0xA7A7A7D0,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xDAA7A7A7,0x545A2D90,0x045A5A2D,0xA7A7A639,0xA7A7A7A7,0xA7A7A7A7,0xE1A7A7A7,0xBAFEFEBA, -0xA7A7E667,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x589BE1A7, -0xBBDEDB58,0xA7A7A773,0xA7A7A7A7,0xFCDACDA7,0xFCFCFCFC,0xDAFCFC25,0xFCFCFCFC,0xA7CDE073, -0x82A7A7A7,0x541B247E,0x5A2D544D,0xA7E00EB0,0xA7A7A7A7,0xA7A7A7A7,0x09A7A7A7,0xD2BFFEBB, -0xA7FEDF8B,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xFE41E6A7, -0x76F8DBDB,0xA7A7A7A7,0xA7A7A7A7,0x124DD773,0xED12124D,0xB1B1ADB3,0xB1B1B1B1,0xA7553BC6, -0x246EA7A7,0xED54241B,0x5AB0BDE2,0xA7A8F9E7,0xA7A7A7A7,0xA7A7A7A7,0xD3A7A7A7,0xBFFE5875, -0xA7C09BD4,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x80CB8B73, -0xD0BB5858,0xA7A7A7A7,0xA7A7A7A7,0x39B43227,0xE7B039B0,0x542DE72D,0x3824547E,0xA74833EB, -0x383FDAA7,0x637EBCA4,0xE7B9BFA7,0x6C39E75A,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xBFFEF811, -0xA7E170B8,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xF3FE5D2A, -0xD3BB58DB,0xA7A7A7A7,0x5EA7A7A7,0x66043966,0x5A545AE7,0x24245454,0x38A4A460,0xA7A7733F, -0xA4389DA7,0xD3C97EA4,0x2D20A7A7,0x0EB05A5A,0xA7A7A737,0xA7A7A7A7,0xA7A7A7A7,0xFEFEBB26, -0x73598B0A,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x80FEBBE4, -0xA74B6CFE,0xA7A7A7A7,0xA0FCA7A7,0x04043932,0x54545AE7,0x7E540F2D,0x3838387E,0xA7A7A763, -0x56E8E845,0xA77156A4,0xD7A7A7A7,0x39045A2D,0xA7A7A7E5,0xA7A7A7A7,0xA7A7A7A7,0x805891D3, -0x13E65DF5,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xDE58F859, -0xA7C0EABF,0xA7A7A7A7,0x4713A7A7,0x045C42F4,0x5F2D5A5A,0x202020F4,0x40202020,0x48A7A7D3, -0x07AB079C,0xA7A792A4,0xF6FB89CD,0x04E75A2D,0xA7A7E966,0xA7A7A7A7,0xA7A7A7A7,0xFE3D0AA7, -0xF3E6D4DE,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xDBDBBA59, -0xA7F3B8BF,0xA7A7A7A7,0xA7A7A7A7,0x04FF48A7,0xF40454E7,0xA7A7A7A7,0xA7A7A7A7,0xC2A7A7A7, -0x0746CC1E,0xA7A7487C,0x542D0FB6,0x045A5A5A,0xA7485C39,0xA7A7A7A7,0xA7A7A7A7,0xFE5BBAA7, -0xD0E6BB58,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x73A7A7A7,0xDBE9DEE4, -0xA713BBBF,0xA7A7A7A7,0xA7A7A7A7,0xE7B0A8A7,0xD34E2D5A,0xA7A7A7A7,0xA7A7A7A7,0xB2C8A7A7, -0xABCCCCCC,0x29A7A745,0x5424BCA4,0x66E75454,0xA7276104,0xA7A7A7A7,0xA7A7A7A7,0xFEF8C0A7, -0xCBD4E458,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCAA7A7A7,0xBF585830, -0xA7D3BB58,0xA7A7A7A7,0xA7A7A7A7,0xE704CF5E,0xA7805A66,0xA7A7A7A7,0xA7A7A7A7,0x1E69A7A7, -0x3EABA1A1,0x9A48A7A7,0x0F7EF27E,0x0404E72D,0x74943904,0xA7A7A7A7,0xA7A7A7A7,0xF3B8D0A7, -0xF5BBE480,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x74A7A7A7,0xF358DEB8, -0xA7D3BB58,0xA7A7A7A7,0x48A7A7A7,0xE766398F,0xC8C80DB0,0xC8C8C80B,0xC871C8C8,0xA1858E71, -0x73DDA185,0x9AF7A7A7,0x8FC7B79A,0x04B98F8F,0x43610466,0xA7A7A7A7,0xA7A7A7A7,0xF3A580A7, -0x2ABBF858,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xF3A7A7A7,0xDBE9D2B8, -0xA7A7BBDE,0xA7A7A7A7,0x84A7A7A7,0xE7660432,0x3490905A,0x99993636,0x65B2FD46,0x85A1A165, -0xA72F1E85,0xFC48A7A7,0x73737373,0x5F554873,0x61663904,0xA7A7A7AC,0xA7A7A7A7,0xBFA526A7, -0x5302E1BF,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x26A7A7A7,0x58DBE9F8, -0xA7A79118,0xA7A7A7A7,0x0480A7A7,0xE7040439,0x542D2D5A,0xA4F2247E,0x1EAB07E8,0x8585A1CC, -0xA7A73E1E,0xA7A7A7A7,0xA7A7A7A7,0xA6A7A7A7,0x390404B0,0xA7A7370E,0xA7A7A7A7,0xF39149A7, -0xC0E4E109,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xF3A7A7A7,0xBF585830, -0xA7A741D2,0xA7A7A7A7,0x321048A7,0xE7040439,0x54542DE7,0xA4A42424,0x1EABAB07,0xA1A1A1A1, -0xA7A71365,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xB439B42E,0xA7A76D61,0xA7A7A7A7,0x80A5F3A7, -0xD2301158,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x74A7A7A7,0xBF585830, -0xA7D3BB58,0xA7A7A7A7,0x3932A6A7,0x04393939,0x542DE704,0xE3242454,0xABABE8E3,0xCC1ECCCC, -0xA7A7A7C2,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x39B46616,0xA76ADC61,0xA7A7A7A7,0xFEB8D0A7, -0xD0E111D2,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCAA7A7A7,0xBF58D2B8, -0xA773BB13,0xA7A7A7A7,0x6A3DF3A7,0xBE6A6A6A,0xBE6ABE6A,0x6E6EBE6A,0x6E6E6E6E,0x456E6E55, -0xA7A7A748,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x6A3DBFA7,0xA7746C6A,0xA7A7A7A7,0xFEA509A7, -0xDB11C13D,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x48A7A7A7,0x7358D2B8, -0xA713B8A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA2A7A7A2,0xA248A2A2,0xA7A7A2CD,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xFE0AC0A7, -0x74C12AE9,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA237BA91, -0xA7D00AA7,0xA7A7A7A7,0x4F77B5A7,0x77EF77EF,0xA7A7A2D6,0x0B77D6A7,0x48A7A7A7,0xA7A764F1, -0xF0A7A7A7,0x770B0B77,0x77777777,0xA2CD51EF,0xAFAF7797,0x9F873C77,0xA7F07B9E,0xFE1CC1A7, -0xCAF553C0,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCDD358E1, -0xA7BA5BA7,0xA7A7A7A7,0x88774F71,0x77888888,0xA7A78701,0xEE831A87,0x25A7A7A7,0xA7AE0177, -0xEFA2A7A7,0x83878783,0x6464B551,0x7BA20897,0x6464D101,0x2BD80197,0xA7F0689F,0x58DE30A7, -0x73C0D2CB,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCDCD7373, -0xA7B858A7,0xA7A7A7A7,0xA7648387,0x57A7A7A7,0xA2A75797,0x1AB52288,0x25A7A70B,0xA25183AF, -0x8397A7A7,0x8387871A,0xA7A7A77B,0xB5A7A7A7,0xA7A78783,0xCD887BA7,0xA7A7A7A7,0x26809148, -0xD3580958,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCD48CDA7, -0x73934448,0xA7A7A7A7,0xA7971A0B,0x878787A7,0x9FA7A287,0x1AA77B83,0x25A7A797,0x647797AF, -0x9E1A1DA7,0x8387871A,0x7B7297F1,0x9EA7A7A7,0x9E7B8883,0xA7251D9E,0xA7A7A7A7,0xFEFEBB09, -0xA7F3D080,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x48CD48A7, -0xC0F8A748,0xA7A7A7A7,0xA797EF87,0x1A4F22CE,0xD6A78783,0x88A2DAD8,0xCDA70B83,0xEF7B8777, -0x9F972287,0x1A87871A,0x88EF771A,0xA2A7A7A7,0xEF4F4F88,0x25D9834F,0xA7A7A7A7,0xF337EAB8, -0xA7138026,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCD7348A7, -0xB8BAA248,0xA7A7A7A7,0xA7641A0B,0x649FDAA7,0x1A258701,0x7717D91A,0x25A7D601,0xAFA7F077, -0x0BCDAF83,0x8387871A,0xA7A2A708,0xDAA7A7A7,0x25CECE9F,0x571A1757,0x73A7A7A7,0x74F3BF75, -0xA7D349FE,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCD73A7A7, -0xBB58A7CD,0xA7A7A713,0xA2D6EF87,0x08A7A2CD,0x83B59F01,0xD951D917,0x25CE1A4F,0x87A71D77, -0x87A76801,0x8387AE1A,0xA2A2A264,0xAFA7A2CD,0xA7A7A7F1,0x2B8388A7,0x53A7A7A7,0x1374FE76, -0xA7A73774,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x7373A7A7, -0xB848A248,0xA7A7A753,0x228377CE,0x4FF12222,0x88D81DEF,0xA2A2A2A2,0x2564017B,0xA7A77BEF, -0x87A74868,0x83878783,0x2222F14F,0x88CED977,0x3C3C5101,0xCD7783F1,0x30A7A7A7,0x1373FE53, -0xA7A77313,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x44D3A7A7, -0xDEA7CD48,0xA7A77375,0x88721DA7,0x88888888,0x9F72871D,0xA7A7A7A7,0xCD64B5A7,0xA7A78797, -0xDAA7A7A7,0xD6DA574C,0x88888888,0xCD25D688,0x888888B5,0xA70BD688,0xBB09A7A7,0x447373BF, -0xA7A7A713,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCDA7A7A7, -0x48A24873,0xA7A7C0BB,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x5BB8A7A7,0x4448CD48, -0xA7A7A748,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xD3A7A7A7, -0xA248CD73,0xA748D4DB,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xE07509A7,0x73CD48A2, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA248CD73,0xA75BB848,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7BABB48,0x48734848, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xCD4873D3,0xD075F3A2,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA248E40A,0xA273CD48, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xCD7373A7,0x59F5FC48,0xA7A7A737,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xC0A7A7A7,0xCDA2FE4A,0xA7487348, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x4873D3A7,0xBA74CD48,0xA7A748B8,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x7526A7A7,0xCD48A2DE,0xA7A773CD, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x7348A7A7,0xFEE07373,0xA7A730B8,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xBA7573A7,0xCD4848A7,0xA7A7D373, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x44A7A7A7,0xF3134444,0xA7E1A5BF,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7CBBB73,0x73CD48A2,0xA7A7A748, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xD3A7A7A7,0xFE3713E0,0x307680FE,0xA7A7A7D3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x74A7A7A7,0x48A73DBB,0x4873CDCD,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x49747473,0xA580FE49,0xA7A713E4,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xBB3AA7A7,0xCDD3A7BA,0xA7737348,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x26F313A7,0x74DB80DB,0xA7DB755B,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xFE2111A7,0xCDCDD3A7,0xA7A773CD,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xDB74A7A7,0x80CB093A,0xBABBBAFE,0xA7A7A748,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x13A7A7A7,0xA737194B,0x48CDCDD3,0xA7A74873,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x49A7A7A7,0xD2C0D2CB,0xB8BFFEF3,0xA7A73A59,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x4AC173A7,0x13E0FE5B,0x4473CD73,0xA7A7A7D3,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x2AF55374,0xFEBFD211,0x0902A5DB,0xA7A7A773,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x74A7A7A7,0xBFB875C1,0x5880DBFE,0x74E4D2BF,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x5BBA74A7,0xF3F5115B,0xB86C80FE,0xA726E1BB,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0x93B8CB48,0xFEFEE90A,0xFE58F3BF,0xA7C04A11,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xBACAA7A7,0x5B30E1E1,0xFEFEBFE9,0x59BBEAD2,0x48135811,0xA7A7A7A7, -0xA7A7A7A7,0xE1CB7473,0xBF5B9175,0x58F3FEFE,0xE4585858,0xA7A72659,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xD3A7A7A7,0xE4B83009,0xBF58C1E4,0x5858FEFE,0x21930ABA,0xB8E491BB, -0xBB91E4E4,0xF5EAA5BB,0xBFFEFE58,0x80585858,0x1175BADB,0xA7A7A7D3,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xE45B13A7,0xEAA5BBBB,0xFEFEF309,0x5880FEFE,0xBABAF5DE, -0xDB3DC11C,0xBF74FEBF,0xDBDBDBBF,0xC180FEF3,0xA726B802,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x26A7A7A7,0xE6E65911,0x585B3059,0xF3FE49BF,0xF3FEF3FE, -0xF3FEBFFE,0x5858BF80,0xFEBF8058,0x3041B8CB,0xA7A7A7D2,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xD411F3A7,0xD48B8B8B,0x80DEC1B8,0xF3FEF3BF, -0xDBBFF3F3,0x49FE80BF,0xE630CBF3,0xD3D0915D,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xCAA7A7A7,0x9BE6E42A,0xE6DF6767,0x0AF8A559, -0xEAEA5BEA,0xA9BBE4F8,0x11595D8B,0xA7A7A7CA,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xC073A7A7,0x8A5D5930,0x986F6F8D, -0xAA6F6F78,0x025DDF67,0xA7A7732A,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x73D3A7A7,0xD209D074, -0x74D009C0,0xA7A7A773,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x2600A3A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x00A7A7A7,0x00002800,0xA7A7A700,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x0000A300,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0x743135A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x74A7A7A7,0xC0C3C3C3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0x00000000,0xA7A7A731,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0x74A7A700,0xA7A7A700,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0x35C3C300,0xA7A7A700,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0x00000000,0xA7A7A7A3,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0xA7A7A700,0xA7A7D500,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0xC0A7A700,0xA7A7D500,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xC3A7A7A7,0x00000000,0xA7A7A706,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515, -0x0C0C0C0C,0x0C0C0C0C,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7, -0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0xA7A7A7A7,0x15151515,0x15151515}; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.h deleted file mode 100644 index d6130ea06e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/missingtexture.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DX8_MISSING_TEXTURE_H -#define DX8_MISSING_TEXTURE_H - -#include "always.h" - -struct IDirect3DTexture8; -struct IDirect3DSurface8; - -class MissingTexture -{ -public: - static void _Init(); - static void _Deinit(); - - static IDirect3DTexture8* _Get_Missing_Texture(); // Return a reference to missing texture - static IDirect3DSurface8* _Create_Missing_Surface(); // Create new surface which contain missing texture image -}; - - -#endif // DX8_MISSING_TEXTURE \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.cpp index 7f51891c29..55caafc76b 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.cpp @@ -87,6 +87,7 @@ ParticleBufferClass::ParticleBufferClass ParticlePropertyStruct &rotation, float orient_rnd, ParticlePropertyStruct &frame, + ParticlePropertyStruct &blurtime, Vector3 accel, float max_age, TextureClass *tex, @@ -135,6 +136,10 @@ ParticleBufferClass::ParticleBufferClass FrameKeyFrameTimes(NULL), FrameKeyFrameValues(NULL), FrameKeyFrameDeltas(NULL), + NumBlurTimeKeyFrames(0), + BlurTimeKeyFrameTimes(NULL), + BlurTimeKeyFrameValues(NULL), + BlurTimeKeyFrameDeltas(NULL), NumRandomColorEntriesMinus1(0), RandomColorEntries(NULL), NumRandomAlphaEntriesMinus1(0), @@ -153,6 +158,8 @@ ParticleBufferClass::ParticleBufferClass RandomOrientationEntries(NULL), NumRandomFrameEntriesMinus1(0), RandomFrameEntries(NULL), + NumRandomBlurTimeEntriesMinus1(0), + RandomBlurTimeEntries(NULL), PointGroup(NULL), LineRenderer(NULL), Diffuse(NULL), @@ -161,6 +168,7 @@ ParticleBufferClass::ParticleBufferClass Size(NULL), Orientation(NULL), Frame(NULL), + TailPosition(NULL), APT(NULL), PingPongPosition(pingpong), Velocity(NULL), @@ -190,6 +198,9 @@ ParticleBufferClass::ParticleBufferClass // Create the frame array, keyframes, and randomizer table (if needed) Reset_Frames(frame); + // Create the blur time array, keyframes, and randomizer table if needed + Reset_Blur_Times(blurtime); + // We do not add a ref for the emitter (see DTor for detailed explanation) // if (Emitter) Emitter->Add_Ref(); @@ -295,6 +306,10 @@ ParticleBufferClass::ParticleBufferClass(const ParticleBufferClass & src) : FrameKeyFrameTimes(NULL), FrameKeyFrameValues(NULL), FrameKeyFrameDeltas(NULL), + NumBlurTimeKeyFrames(src.NumBlurTimeKeyFrames), + BlurTimeKeyFrameTimes(NULL), + BlurTimeKeyFrameValues(NULL), + BlurTimeKeyFrameDeltas(NULL), RandomColorEntries(NULL), RandomAlphaEntries(NULL), RandomSizeEntries(NULL), @@ -310,14 +325,17 @@ ParticleBufferClass::ParticleBufferClass(const ParticleBufferClass & src) : RandomOrientationEntries(NULL), NumRandomFrameEntriesMinus1(0), RandomFrameEntries(NULL), + NumRandomBlurTimeEntriesMinus1(0), + RandomBlurTimeEntries(NULL), PointGroup(NULL), LineRenderer(NULL), - Diffuse(NULL), + Diffuse(NULL), Color(NULL), Alpha(NULL), Size(NULL), Orientation(NULL), Frame(NULL), + TailPosition(NULL), APT(NULL), PingPongPosition(src.PingPongPosition), Velocity(NULL), @@ -488,6 +506,31 @@ ParticleBufferClass::ParticleBufferClass(const ParticleBufferClass & src) : FrameKeyFrameValues[0] = src.FrameKeyFrameValues[0]; } + // Set up the blur times keyframes + NumRandomBlurTimeEntriesMinus1 = src.NumRandomBlurTimeEntriesMinus1; + if (NumBlurTimeKeyFrames > 0) { + // Copy blur time keyframes + BlurTimeKeyFrameTimes = new unsigned int [NumBlurTimeKeyFrames]; + BlurTimeKeyFrameValues = new float [NumBlurTimeKeyFrames]; + BlurTimeKeyFrameDeltas = new float [NumBlurTimeKeyFrames]; + for (i = 0; i < NumBlurTimeKeyFrames; i++) { + BlurTimeKeyFrameTimes[i] = src.BlurTimeKeyFrameTimes[i]; + BlurTimeKeyFrameValues[i] = src.BlurTimeKeyFrameValues[i]; + BlurTimeKeyFrameDeltas[i] = src.BlurTimeKeyFrameDeltas[i]; + } + + // Copy blur time randomizer table + if (src.RandomBlurTimeEntries) { + RandomBlurTimeEntries = new float [NumRandomBlurTimeEntriesMinus1 + 1]; + for (unsigned int j = 0; j <= NumRandomBlurTimeEntriesMinus1; j++) { + RandomBlurTimeEntries[j] = src.RandomBlurTimeEntries[j]; + } + } + } else { + BlurTimeKeyFrameValues = new float [1]; + BlurTimeKeyFrameValues[0] = src.BlurTimeKeyFrameValues[0]; + } + // We do not add a ref for the emitter (see DTor for detailed explanation) // if (Emitter) Emitter->Add_Ref(); @@ -574,12 +617,16 @@ ParticleBufferClass::~ParticleBufferClass(void) if (FrameKeyFrameTimes) delete [] FrameKeyFrameTimes; if (FrameKeyFrameValues) delete [] FrameKeyFrameValues; if (FrameKeyFrameDeltas) delete [] FrameKeyFrameDeltas; + if (BlurTimeKeyFrameTimes) delete [] BlurTimeKeyFrameTimes; + if (BlurTimeKeyFrameValues) delete [] BlurTimeKeyFrameValues; + if (BlurTimeKeyFrameDeltas) delete [] BlurTimeKeyFrameDeltas; if (RandomColorEntries) delete [] RandomColorEntries; if (RandomAlphaEntries) delete [] RandomAlphaEntries; if (RandomSizeEntries) delete [] RandomSizeEntries; if (RandomRotationEntries) delete [] RandomRotationEntries; if (RandomOrientationEntries) delete [] RandomOrientationEntries; if (RandomFrameEntries) delete [] RandomFrameEntries; + if (RandomBlurTimeEntries) delete [] RandomBlurTimeEntries; if (PointGroup) delete PointGroup; @@ -1920,6 +1967,154 @@ void ParticleBufferClass::Reset_Frames(ParticlePropertyStruct &new_props) } +void ParticleBufferClass::Reset_Blur_Times(ParticlePropertyStruct &new_blur_times) +{ + + unsigned int i; // Used in loops + float oo_intmax = 1.0f / (float)INT_MAX; + unsigned int ui_previous_key_time = 0; + unsigned int ui_current_key_time = 0; + + BlurTimeRandom = new_blur_times.Rand; + + // If the randomizer is effectively zero and there are no keyframes, then we just create a + // values array with one entry and store the starting value in it (the keyframes and random + // table will not be used in this case). + static const float eps_blur = 1e-5f; // Epsilon is equivalent to 1e-5 units per second + bool blurtime_rand_zero = (fabs(new_blur_times.Rand) < eps_blur); + if (blurtime_rand_zero && new_blur_times.NumKeyFrames == 0) { + + // Release Arrays, Reuse KeyFrameValues if the right size, + // otherwise release and reallocate. + if (BlurTimeKeyFrameTimes) { + delete [] BlurTimeKeyFrameTimes; + BlurTimeKeyFrameTimes = NULL; + } + if (BlurTimeKeyFrameDeltas) { + delete [] BlurTimeKeyFrameDeltas; + BlurTimeKeyFrameDeltas = NULL; + } + if (BlurTimeKeyFrameValues) { + if (NumBlurTimeKeyFrames > 1) { + delete [] BlurTimeKeyFrameValues; + BlurTimeKeyFrameValues = new float [1]; + } + } else { + BlurTimeKeyFrameValues = new float [1]; + } + + NumBlurTimeKeyFrames = 0; + NumRandomBlurTimeEntriesMinus1 = 0; + BlurTimeKeyFrameValues[0] = new_blur_times.Start; + + } else { + + // Check times of the keyframes (each keytime must be larger than the + // previous one by at least a millisecond, and we stop at the first + // keytime of MaxAge or larger. (If all keyframes below MaxAge, the value is + // constant during the last segment between last keyframe and MaxAge). + ui_previous_key_time = 0; + unsigned int key = 0; + for (; key < new_blur_times.NumKeyFrames; key++) { + ui_current_key_time = (unsigned int)(new_blur_times.KeyTimes[key] * 1000.0f); + WWASSERT(ui_current_key_time > ui_previous_key_time); + if (ui_current_key_time >= MaxAge) break; + ui_previous_key_time = ui_current_key_time; + } + bool blurtime_constant_at_end = (key == new_blur_times.NumKeyFrames); + + // Reuse BlurTimeKeyFrameValues, BlurTimeKeyFrameTimes and BlurTimeKeyFrameDeltas if the right size, + // otherwise release and reallocate. + unsigned int new_num_key_frames = key + 1;// Includes start keyframe (keytime == 0). + if (new_num_key_frames != NumBlurTimeKeyFrames) { + + if (BlurTimeKeyFrameTimes) { + delete [] BlurTimeKeyFrameTimes; + BlurTimeKeyFrameTimes = NULL; + } + if (BlurTimeKeyFrameValues) { + delete [] BlurTimeKeyFrameValues; + BlurTimeKeyFrameValues = NULL; + } + if (BlurTimeKeyFrameDeltas) { + delete [] BlurTimeKeyFrameDeltas; + BlurTimeKeyFrameDeltas = NULL; + } + + NumBlurTimeKeyFrames = new_num_key_frames; + BlurTimeKeyFrameTimes = new unsigned int [NumBlurTimeKeyFrames]; + BlurTimeKeyFrameValues = new float [NumBlurTimeKeyFrames]; + BlurTimeKeyFrameDeltas = new float [NumBlurTimeKeyFrames]; + } + + // Set keyframes (deltas will be set later) + BlurTimeKeyFrameTimes[0] = 0; + BlurTimeKeyFrameValues[0] = new_blur_times.Start; + for (i = 1; i < NumBlurTimeKeyFrames; i++) { + unsigned int im1 = i - 1; + BlurTimeKeyFrameTimes[i] = (unsigned int)(new_blur_times.KeyTimes[im1] * 1000.0f); + BlurTimeKeyFrameValues[i] = new_blur_times.Values[im1]; + } + + // Do deltas for all frame keyframes except last + for (i = 0; i < NumBlurTimeKeyFrames - 1; i++) { + BlurTimeKeyFrameDeltas[i] = (BlurTimeKeyFrameValues[i + 1] - BlurTimeKeyFrameValues[i]) / + (float)(BlurTimeKeyFrameTimes[i + 1] - BlurTimeKeyFrameTimes[i]); + } + + // Do delta for last frame keyframe (i is NumBlurTimeKeyFrames - 1) + if (blurtime_constant_at_end) { + BlurTimeKeyFrameDeltas[i] = 0.0f; + } else { + // This is OK because if frame_constant_at_end is false, NumBlurTimeKeyFrames is equal or + // smaller than new_props.NumKeyFrames so new_props.Values[NumBlurTimeKeyFrames - 1] and + // new_props.KeyTimes[NumBlurTimeKeyFrames - 1] exist. + BlurTimeKeyFrameDeltas[i] = (new_blur_times.Values[i] - BlurTimeKeyFrameValues[i]) / + (new_blur_times.KeyTimes[i] * 1000.0f - (float)BlurTimeKeyFrameTimes[i]); + } + + // Set up frame randomizer table + if (blurtime_rand_zero) { + + if (RandomBlurTimeEntries) { + // Reuse RandomBlurTimeEntries if the right size, otherwise release and reallocate. + if (NumRandomBlurTimeEntriesMinus1 != 0) { + delete [] RandomBlurTimeEntries; + RandomBlurTimeEntries = new float [1]; + } + } else { + RandomBlurTimeEntries = new float [1]; + } + + NumRandomBlurTimeEntriesMinus1 = 0; + RandomBlurTimeEntries[0] = 0.0f; + } else { + + // Default size of randomizer tables (tables for non-zero randomizers will be this size) + unsigned int pot_num = Find_POT(MaxNum); + unsigned int default_randomizer_entries = MIN(pot_num, MAX_RANDOM_ENTRIES); + + if (RandomBlurTimeEntries) { + // Reuse RandomBlurTimeEntries if the right size, otherwise release and reallocate. + if (NumRandomBlurTimeEntriesMinus1 != (default_randomizer_entries - 1)) { + delete [] RandomBlurTimeEntries; + RandomBlurTimeEntries = new float [default_randomizer_entries]; + } + } else { + RandomBlurTimeEntries = new float [default_randomizer_entries]; + } + + NumRandomBlurTimeEntriesMinus1 = default_randomizer_entries - 1; + + float scale = new_blur_times.Rand * oo_intmax; + for (unsigned int j = 0; j <= NumRandomBlurTimeEntriesMinus1; j++) { + RandomBlurTimeEntries[j] = rand_gen * scale; + } + } + } +} + + // This informs the buffer that the emitter is dead, so it can release // its pointer to it and be removed itself after all its particles dies // out. @@ -2046,6 +2241,7 @@ void ParticleBufferClass::Update_Visual_Particle_State(void) unsigned int skey = NumSizeKeyFrames - 1; unsigned int rkey = NumRotationKeyFrames - 1; unsigned int fkey = NumFrameKeyFrames - 1; + unsigned int bkey = NumBlurTimeKeyFrames -1; unsigned int part; Vector3 *color = Color ? Color->Get_Array(): NULL; @@ -2053,6 +2249,16 @@ void ParticleBufferClass::Update_Visual_Particle_State(void) float *size = Size ? Size->Get_Array(): NULL; uint8 *orientation = Orientation ? Orientation->Get_Array(): NULL; uint8 *frame = Frame ? Frame->Get_Array(): NULL; + Vector3 *tailposition = TailPosition ? TailPosition->Get_Array() : NULL; + + Vector3 *position=NULL; + + if (PingPongPosition) { + int pingpong = WW3D::Get_Frame_Count() & 0x1; + position = Position[pingpong]->Get_Array(); + } else { + position = Position[0]->Get_Array(); + } for (part = Start; part < sub1_end; part++) { @@ -2123,6 +2329,19 @@ void ParticleBufferClass::Update_Visual_Particle_State(void) frame[part] = (uint)(((int)(tmp_frame)) & 0xFF); } + + if (tailposition) { + // We go from older to younger particles, so we go backwards from the last keyframe until + // age >= keytime. This loop must terminate because the 0th keytime is 0. + float blur_time = BlurTimeKeyFrameValues[0]; + if (BlurTimeKeyFrameTimes) { + for (; part_age < BlurTimeKeyFrameTimes[bkey]; bkey--); + blur_time = BlurTimeKeyFrameValues[bkey] + + BlurTimeKeyFrameDeltas[bkey] * (float)(part_age - BlurTimeKeyFrameTimes[bkey]) + + RandomBlurTimeEntries[part & NumRandomBlurTimeEntriesMinus1]; + } + tailposition[part]=position[part]-Velocity[part]*blur_time*1000; + } } for (part = sub2_start; part < End; part++) { @@ -2194,6 +2413,19 @@ void ParticleBufferClass::Update_Visual_Particle_State(void) frame[part] = (uint)(((int)(tmp_frame)) & 0xFF); } + + if (tailposition) { + // We go from older to younger particles, so we go backwards from the last keyframe until + // age >= keytime. This loop must terminate because the 0th keytime is 0. + float blur_time = BlurTimeKeyFrameValues[0]; + if (BlurTimeKeyFrameTimes) { + for (; part_age < BlurTimeKeyFrameTimes[bkey]; bkey--); + blur_time = BlurTimeKeyFrameValues[bkey] + + BlurTimeKeyFrameDeltas[bkey] * (float)(part_age - BlurTimeKeyFrameTimes[bkey]) + + RandomBlurTimeEntries[part & NumRandomBlurTimeEntriesMinus1]; + } + tailposition[part]=position[part]-Velocity[part]*blur_time*1000; + } } } @@ -2710,7 +2942,7 @@ void ParticleBufferClass::Get_Frame_Key_Frames (ParticlePropertyStruct &f // // If we have more than just the start rotation, build - // an array of key times and rotation values + // an array of key times and frame values // if (real_keyframe_count > 0) { frames.KeyTimes = W3DNEWARRAY float[real_keyframe_count]; @@ -2744,6 +2976,62 @@ void ParticleBufferClass::Get_Frame_Key_Frames (ParticlePropertyStruct &f return ; } +void ParticleBufferClass::Get_Blur_Time_Key_Frames (ParticlePropertyStruct &blurtimes) const +{ + int real_keyframe_count = (NumBlurTimeKeyFrames > 0) ? (NumBlurTimeKeyFrames - 1) : 0; + bool create_last_keyframe = false; + + // + // Determine if there is a keyframe at the very end of the particle's lifetime + // + if ((BlurTimeKeyFrameDeltas != NULL) && + (BlurTimeKeyFrameDeltas[NumBlurTimeKeyFrames - 1] != 0)) { + real_keyframe_count ++; + create_last_keyframe = true; + } + + blurtimes.Start = BlurTimeKeyFrameValues[0]; + blurtimes.Rand = BlurTimeRandom; + blurtimes.NumKeyFrames = real_keyframe_count; + blurtimes.KeyTimes = NULL; + blurtimes.Values = NULL; + + // + // If we have more than just the start rotation, build + // an array of key times and blur time values + // + if (real_keyframe_count > 0) { + blurtimes.KeyTimes = new float[real_keyframe_count]; + blurtimes.Values = new float[real_keyframe_count]; + + // + // Copy the keytimes and frame values + // + unsigned int index; + for (index = 1; index < NumBlurTimeKeyFrames; index ++) { + blurtimes.KeyTimes[index - 1] = ((float)BlurTimeKeyFrameTimes[index]) / 1000; + blurtimes.Values[index - 1] = BlurTimeKeyFrameValues[index]; + } + + // + // Add a keyframe at the very end of the timeline if necessary + // + if (create_last_keyframe) { + blurtimes.KeyTimes[index - 1] = ((float)MaxAge / 1000); + + // + // Determine what the value of the last keyframe should be + // + float start_blurtime = BlurTimeKeyFrameValues[index - 1]; + float &delta = BlurTimeKeyFrameDeltas[NumBlurTimeKeyFrames - 1]; + float time_delta = MaxAge - BlurTimeKeyFrameTimes[index - 1]; + blurtimes.Values[index - 1] = start_blurtime + (delta * time_delta); + } + } + + return ; +} + void ParticleBufferClass::Set_LOD_Max_Screen_Size(int lod_level,float max_screen_size) { if ((lod_level <0) || (lod_level > 17)) { diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.h index 5c9828bd04..ec8e0cebfb 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_buf.h @@ -89,7 +89,8 @@ class ParticleBufferClass : public RenderObjClass ParticleBufferClass(ParticleEmitterClass *emitter, unsigned int buffer_size, ParticlePropertyStruct &color, ParticlePropertyStruct &opacity, ParticlePropertyStruct &size, ParticlePropertyStruct &rotation, - float orient_rnd, ParticlePropertyStruct &frame, Vector3 accel, + float orient_rnd, ParticlePropertyStruct &frame, + ParticlePropertyStruct &blurtime, Vector3 accel, float max_age, TextureClass *tex, ShaderClass shader, bool pingpong, int render_mode, int frame_mode, const W3dEmitterLinePropertiesStruct * line_props); @@ -151,6 +152,7 @@ class ParticleBufferClass : public RenderObjClass void Reset_Size(ParticlePropertyStruct &new_props); void Reset_Rotations(ParticlePropertyStruct &new_rotations, float orient_rnd); void Reset_Frames(ParticlePropertyStruct &new_frames); + void Reset_Blur_Times(ParticlePropertyStruct &new_blur_times); // This informs the buffer that the emitter is dead, so it can release // its pointer to it and be removed itself after all its particles dies @@ -217,6 +219,7 @@ class ParticleBufferClass : public RenderObjClass void Get_Size_Key_Frames (ParticlePropertyStruct &sizes) const; void Get_Rotation_Key_Frames (ParticlePropertyStruct &rotations) const; void Get_Frame_Key_Frames (ParticlePropertyStruct &frames) const; + void Get_Blur_Time_Key_Frames (ParticlePropertyStruct &blurtimes) const; float Get_Initial_Orientation_Random (void) const { return InitialOrientationRandom; } // Total Active Particle Buffer Count @@ -329,6 +332,10 @@ class ParticleBufferClass : public RenderObjClass unsigned int * FrameKeyFrameTimes; // 0th entry is always 0 float * FrameKeyFrameValues; float * FrameKeyFrameDeltas; + unsigned int NumBlurTimeKeyFrames; + unsigned int * BlurTimeKeyFrameTimes; // 0th entry is always 0 + float * BlurTimeKeyFrameValues; + float * BlurTimeKeyFrameDeltas; // These tables are indexed by the array position in the particle buffer. // The table size is either the smallest power of two equal or larger @@ -350,12 +357,15 @@ class ParticleBufferClass : public RenderObjClass float * RandomOrientationEntries; unsigned int NumRandomFrameEntriesMinus1; // 2^n - 1 so can be used as a mask also float * RandomFrameEntries; + unsigned int NumRandomBlurTimeEntriesMinus1; // 2^n - 1 so can be used as a mask also + float * RandomBlurTimeEntries; Vector3 ColorRandom; float OpacityRandom; float SizeRandom; float RotationRandom; float FrameRandom; + float BlurTimeRandom; float InitialOrientationRandom; // This object implements particle rendering @@ -375,6 +385,7 @@ class ParticleBufferClass : public RenderObjClass ShareBufferClass * Alpha; ShareBufferClass * Size; ShareBufferClass * Frame; + ShareBufferClass * TailPosition; // Only used for line groups ShareBufferClass * Orientation; ShareBufferClass * APT; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp index 46d691a97b..88a2da26bc 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.cpp @@ -73,7 +73,8 @@ ParticleEmitterClass::ParticleEmitterClass(float emit_rate, unsigned int burst_s ParticlePropertyStruct &size, ParticlePropertyStruct &rotation, float orient_rnd, ParticlePropertyStruct &frames, - Vector3 accel, float max_age, TextureClass *tex, ShaderClass shader, int max_particles, + ParticlePropertyStruct &blur_times, + Vector3 accel, float max_age, float future_start, TextureClass *tex, ShaderClass shader, int max_particles, int max_buffer_size, bool pingpong,int render_mode,int frame_mode, const W3dEmitterLinePropertiesStruct * line_props ) : @@ -111,7 +112,7 @@ ParticleEmitterClass::ParticleEmitterClass(float emit_rate, unsigned int burst_s max_num = MAX(max_num, 2); // max_num of 1 causes problems Buffer = W3DNEW ParticleBufferClass(this, max_num, color, opacity, size, rotation, orient_rnd, - frames, accel/1000000.0f,max_age, tex, shader, pingpong, render_mode, frame_mode, + frames, blur_times, accel/1000000.0f,max_age, tex, shader, pingpong, render_mode, frame_mode, line_props); SET_REF_OWNER( Buffer ); BufferSceneNeeded = true; @@ -207,11 +208,13 @@ ParticleEmitterClass::Create_From_Definition (const ParticleEmitterDefClass &def const char *ptexture_filename = definition.Get_Texture_Filename (); TextureClass *ptexture = NULL; if (ptexture_filename && ptexture_filename[0]) { - ptexture = WW3DAssetManager::Get_Instance()->Get_Texture( + ptexture = WW3DAssetManager::Get_Instance()->Get_Texture + ( ptexture_filename, MIP_LEVELS_ALL, - WW3D_FORMAT_UNKNOWN, - false); // no compression for particle textures! + WW3D_FORMAT_UNKNOWN + ); +// false); // no compression for particle textures! } ShaderClass shader; @@ -237,12 +240,14 @@ ParticleEmitterClass::Create_From_Definition (const ParticleEmitterDefClass &def ParticlePropertyStruct size_keys; ParticlePropertyStruct rotation_keys; ParticlePropertyStruct frame_keys; + ParticlePropertyStruct blur_time_keys; definition.Get_Color_Keyframes (color_keys); definition.Get_Opacity_Keyframes (opacity_keys); definition.Get_Size_Keyframes (size_keys); definition.Get_Rotation_Keyframes (rotation_keys); definition.Get_Frame_Keyframes (frame_keys); + definition.Get_Blur_Time_Keyframes (blur_time_keys); // // Create the emitter @@ -260,8 +265,10 @@ ParticleEmitterClass::Create_From_Definition (const ParticleEmitterDefClass &def rotation_keys, definition.Get_Initial_Orientation_Random(), frame_keys, + blur_time_keys, definition.Get_Acceleration (), definition.Get_Lifetime (), + 0.0f, ptexture, shader, definition.Get_Max_Emissions (), @@ -281,6 +288,8 @@ ParticleEmitterClass::Create_From_Definition (const ParticleEmitterDefClass &def if (rotation_keys.Values != NULL) delete [] rotation_keys.Values; if (frame_keys.KeyTimes != NULL) delete [] frame_keys.KeyTimes; if (frame_keys.Values != NULL) delete [] frame_keys.Values; + if (blur_time_keys.KeyTimes != NULL) delete [] blur_time_keys.KeyTimes; + if (blur_time_keys.Values != NULL) delete [] blur_time_keys.Values; // Pass the name along to the emitter pemitter->Set_Name (definition.Get_Name ()); @@ -775,6 +784,16 @@ ParticleEmitterClass::Build_Definition (void) const if (frames.KeyTimes != NULL) delete [] frames.KeyTimes; if (frames.Values != NULL) delete [] frames.Values; + // + // Pass the blur time keyframes onto the definition + // + ParticlePropertyStruct blur_times; + Get_Blur_Time_Key_Frames (blur_times); + pdefinition->Set_Blur_Time_Keyframes (blur_times); + if (blur_times.KeyTimes != NULL) delete [] blur_times.KeyTimes; + if (blur_times.Values != NULL) delete [] blur_times.Values; + + // // Set up the line parameters // diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.h index f5729f3d84..597d4f275a 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_emt.h @@ -115,7 +115,8 @@ class ParticleEmitterClass : public RenderObjClass ParticlePropertyStruct &size, ParticlePropertyStruct &rotation, float orient_rnd, ParticlePropertyStruct &frames, - Vector3 accel, float max_age, TextureClass *tex, + ParticlePropertyStruct &blur_times, + Vector3 accel, float max_age, float future_start, TextureClass *tex, ShaderClass shader = ShaderClass::_PresetAdditiveSpriteShader, int max_particles = 0, int max_buffer_size = -1, bool pingpong = false, int render_mode = W3D_EMITTER_RENDER_MODE_TRI_PARTICLES, @@ -159,7 +160,7 @@ class ParticleEmitterClass : public RenderObjClass virtual void Set_Animation_Hidden(int onoff) { RenderObjClass::Set_Animation_Hidden (onoff); Update_On_Visibilty (); } virtual void Set_Force_Visible(int onoff) { RenderObjClass::Set_Force_Visible (onoff); Update_On_Visibilty (); } - virtual void Set_LOD_Bias(float bias) { if (Buffer) Buffer->Set_LOD_Bias(bias); } + virtual void Set_LOD_Bias(float bias) { if (Buffer) Buffer->Set_LOD_Bias(bias); } // These are not part of the renderobject interface: @@ -184,6 +185,7 @@ class ParticleEmitterClass : public RenderObjClass void Reset_Size(ParticlePropertyStruct &new_props) { if (Buffer) Buffer->Reset_Size(new_props); } void Reset_Rotations(ParticlePropertyStruct &new_props, float orient_rnd) { if (Buffer) Buffer->Reset_Rotations(new_props, orient_rnd); } void Reset_Frames(ParticlePropertyStruct &new_props) { if (Buffer) Buffer->Reset_Frames(new_props); } + void Reset_Blur_Times(ParticlePropertyStruct &new_props) { if (Buffer) Buffer->Reset_Blur_Times(new_props); } // Change emission/burst rate, or tell the emitter to emit a one-time burst. // NOTE: default buffer size fits the emission/burst rate that the emitter was created with. @@ -252,6 +254,7 @@ class ParticleEmitterClass : public RenderObjClass void Get_Size_Key_Frames (ParticlePropertyStruct &sizes) const { Buffer->Get_Size_Key_Frames (sizes); } void Get_Rotation_Key_Frames (ParticlePropertyStruct &rotations) const { Buffer->Get_Rotation_Key_Frames (rotations); } void Get_Frame_Key_Frames (ParticlePropertyStruct &frames) const { Buffer->Get_Frame_Key_Frames (frames); } + void Get_Blur_Time_Key_Frames (ParticlePropertyStruct &blurtimes) const { Buffer->Get_Blur_Time_Key_Frames (blurtimes); } float Get_Initial_Orientation_Random (void) const { return Buffer->Get_Initial_Orientation_Random(); } // Line rendering accessors diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp index b186ce1932..ff05f36f6c 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.cpp @@ -95,6 +95,7 @@ ParticleEmitterDefClass::ParticleEmitterDefClass (void) ::memset (&m_SizeKeyframes, 0, sizeof (m_SizeKeyframes)); ::memset (&m_RotationKeyframes, 0, sizeof (m_RotationKeyframes)); ::memset (&m_FrameKeyframes, 0, sizeof (m_FrameKeyframes)); + ::memset (&m_BlurTimeKeyframes, 0, sizeof (m_BlurTimeKeyframes)); ::memset (&m_LineProperties, 0, sizeof (m_LineProperties)); return ; } @@ -121,6 +122,7 @@ ParticleEmitterDefClass::ParticleEmitterDefClass (const ParticleEmitterDefClass ::memset (&m_SizeKeyframes, 0, sizeof (m_SizeKeyframes)); ::memset (&m_RotationKeyframes, 0, sizeof (m_RotationKeyframes)); ::memset (&m_FrameKeyframes, 0, sizeof (m_FrameKeyframes)); + ::memset (&m_BlurTimeKeyframes, 0, sizeof (m_BlurTimeKeyframes)); ::memset (&m_LineProperties, 0, sizeof (m_LineProperties)); (*this) = src; @@ -189,6 +191,7 @@ ParticleEmitterDefClass::operator= (const ParticleEmitterDefClass &src) ::Copy_Emitter_Property_Struct (m_SizeKeyframes, src.m_SizeKeyframes); ::Copy_Emitter_Property_Struct (m_RotationKeyframes, src.m_RotationKeyframes); ::Copy_Emitter_Property_Struct (m_FrameKeyframes, src.m_FrameKeyframes); + ::Copy_Emitter_Property_Struct (m_BlurTimeKeyframes, src.m_BlurTimeKeyframes); m_InitialOrientationRandom = src.m_InitialOrientationRandom; // @@ -213,6 +216,7 @@ ParticleEmitterDefClass::Free_Props (void) m_SizeKeyframes.NumKeyFrames = 0; m_RotationKeyframes.NumKeyFrames = 0; m_FrameKeyframes.NumKeyFrames = 0; + m_BlurTimeKeyframes.NumKeyFrames = 0; SAFE_DELETE_ARRAY (m_ColorKeyframes.KeyTimes); SAFE_DELETE_ARRAY (m_ColorKeyframes.Values); @@ -224,6 +228,8 @@ ParticleEmitterDefClass::Free_Props (void) SAFE_DELETE_ARRAY (m_RotationKeyframes.Values); SAFE_DELETE_ARRAY (m_FrameKeyframes.KeyTimes); SAFE_DELETE_ARRAY (m_FrameKeyframes.Values); + SAFE_DELETE_ARRAY (m_BlurTimeKeyframes.KeyTimes); + SAFE_DELETE_ARRAY (m_BlurTimeKeyframes.Values); return ; } @@ -387,6 +393,11 @@ ParticleEmitterDefClass::Load_W3D (ChunkLoadClass &chunk_load) case W3D_CHUNK_EMITTER_FRAME_KEYFRAMES: ret_val = Read_Frame_Keyframes(chunk_load); break; + + case W3D_CHUNK_EMITTER_BLUR_TIME_KEYFRAMES: + ret_val = Read_Blur_Time_Keyframes(chunk_load); + break; + default: WWDEBUG_SAY(("Unhandled Chunk! File: %s Line: %d\r\n",__FILE__,__LINE__)); @@ -454,10 +465,11 @@ ParticleEmitterDefClass::Convert_To_Ver2 (void) if (ptexture != NULL) { // If texture has an alpha channel do alpha blending instead of additive // (which is the default for point groups): - SurfaceClass::SurfaceDescription surf_desc; - ::ZeroMemory(&surf_desc, sizeof(SurfaceClass::SurfaceDescription)); - ptexture->Get_Level_Description(surf_desc); - if (Has_Alpha(surf_desc.Format)) { +// SurfaceClass::SurfaceDescription surf_desc; +// ::ZeroMemory(&surf_desc, sizeof(SurfaceClass::SurfaceDescription)); +// ptexture->Get_Level_Description(surf_desc); +// if (Has_Alpha(surf_desc.Format)) { + if (Has_Alpha(ptexture->Get_Texture_Format())) { shader = ShaderClass::_PresetAlphaSpriteShader; } ptexture->Release_Ref(); @@ -1073,6 +1085,48 @@ ParticleEmitterDefClass::Read_Frame_Keyframes (ChunkLoadClass &chunk_load) return ret_val; } +////////////////////////////////////////////////////////////////////////////////// +// +// Read_Blur_Time_Keyframes +// +WW3DErrorType +ParticleEmitterDefClass::Read_Blur_Time_Keyframes (ChunkLoadClass &chunk_load) +{ + // Assume success + WW3DErrorType ret_val = WW3D_ERROR_OK; + + // Read the header + W3dEmitterBlurTimeHeaderStruct header; + if (chunk_load.Read(&header,sizeof(header)) != sizeof(header)) { + ret_val = WW3D_ERROR_LOAD_FAILED; + } + + // Read in the first key + W3dEmitterBlurTimeKeyframeStruct key; + if (chunk_load.Read(&key,sizeof(key)) == sizeof(key)) { + m_BlurTimeKeyframes.Start = key.BlurTime; + } + + // Allocate the keys + m_BlurTimeKeyframes.NumKeyFrames = header.KeyframeCount; + m_BlurTimeKeyframes.Rand = header.Random; + + if (m_BlurTimeKeyframes.NumKeyFrames > 0) { + m_BlurTimeKeyframes.KeyTimes = new float[m_BlurTimeKeyframes.NumKeyFrames]; + m_BlurTimeKeyframes.Values = new float[m_BlurTimeKeyframes.NumKeyFrames]; + } + + // Read in the keys + for (unsigned int i=0; (i &key return ; } +/////////////////////////////////////////////////////////////////////////////////// +// +// Set_Blur_Time_Keyframes +// +void +ParticleEmitterDefClass::Set_Blur_Time_Keyframes (ParticlePropertyStruct &keyframes) +{ + SAFE_DELETE_ARRAY (m_BlurTimeKeyframes.KeyTimes); + SAFE_DELETE_ARRAY (m_BlurTimeKeyframes.Values); + + ::Copy_Emitter_Property_Struct (m_BlurTimeKeyframes, keyframes); + return ; +} + /////////////////////////////////////////////////////////////////////////////////// // // Get_Color_Keyframes @@ -1665,6 +1780,17 @@ ParticleEmitterDefClass::Get_Frame_Keyframes (ParticlePropertyStruct &key return ; } +/////////////////////////////////////////////////////////////////////////////////// +// +// Get_Blur_Time_Keyframes +// +void +ParticleEmitterDefClass::Get_Blur_Time_Keyframes (ParticlePropertyStruct &blurtimeframes) const +{ + ::Copy_Emitter_Property_Struct (blurtimeframes, m_BlurTimeKeyframes); + return ; +} + /////////////////////////////////////////////////////////////////////////////////// // diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.h index 81e10a96d6..74107283e0 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/part_ldr.h @@ -179,6 +179,7 @@ class ParticleEmitterDefClass virtual void Get_Size_Keyframes (ParticlePropertyStruct &keyframes) const; virtual void Get_Rotation_Keyframes (ParticlePropertyStruct &rotationframes) const; virtual void Get_Frame_Keyframes (ParticlePropertyStruct &frameframes) const; + virtual void Get_Blur_Time_Keyframes (ParticlePropertyStruct &blurtimeframes) const; virtual float Get_Initial_Orientation_Random (void) const { return m_InitialOrientationRandom; } virtual void Set_Color_Keyframes (ParticlePropertyStruct &keyframes); @@ -186,6 +187,7 @@ class ParticleEmitterDefClass virtual void Set_Size_Keyframes (ParticlePropertyStruct &keyframes); virtual void Set_Rotation_Keyframes (ParticlePropertyStruct &keyframes, float orient_rnd); virtual void Set_Frame_Keyframes (ParticlePropertyStruct &keyframes); + virtual void Set_Blur_Time_Keyframes (ParticlePropertyStruct &keyframes); // // User data accessors @@ -241,6 +243,7 @@ class ParticleEmitterDefClass virtual WW3DErrorType Read_Line_Properties (ChunkLoadClass &chunk_load); virtual WW3DErrorType Read_Rotation_Keyframes (ChunkLoadClass &chunk_load); virtual WW3DErrorType Read_Frame_Keyframes (ChunkLoadClass &chunk_load); + virtual WW3DErrorType Read_Blur_Time_Keyframes (ChunkLoadClass &chunk_load); virtual bool Read_Color_Keyframe (ChunkLoadClass &chunk_load, float *key_time, Vector3 *value); virtual bool Read_Opacity_Keyframe (ChunkLoadClass &chunk_load, float *key_time, float *value); @@ -257,6 +260,7 @@ class ParticleEmitterDefClass virtual WW3DErrorType Save_Line_Properties (ChunkSaveClass &chunk_save); virtual WW3DErrorType Save_Frame_Keyframes (ChunkSaveClass & chunk_save); virtual WW3DErrorType Save_Rotation_Keyframes (ChunkSaveClass & chunk_save); + virtual WW3DErrorType Save_Blur_Time_Keyframes (ChunkSaveClass & chunk_save); virtual WW3DErrorType Save_Color_Keyframes (ChunkSaveClass &chunk_save); virtual WW3DErrorType Save_Opacity_Keyframes (ChunkSaveClass &chunk_save); @@ -298,6 +302,7 @@ class ParticleEmitterDefClass ParticlePropertyStruct m_RotationKeyframes; float m_InitialOrientationRandom; ParticlePropertyStruct m_FrameKeyframes; + ParticlePropertyStruct m_BlurTimeKeyframes; Vector3Randomizer * m_pCreationVolume; Vector3Randomizer * m_pVelocityRandomizer; }; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/pivot.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/pivot.cpp deleted file mode 100644 index 95acf22f9e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/pivot.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/pivot.cpp 1 1/22/01 3:36p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/pivot.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * PivotClass::PivotClass -- Constructor for PivotClass * - * PivotClass::Compute_Transform -- Update the pivot's transformation matrix * - * PivotClass::Compute_Transform -- Update the pivot's transformation matrix * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "pivot.h" -#include "wwmath.h" -#include - - -/*********************************************************************************************** - * PivotClass::PivotClass -- Constructor for PivotClass * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -PivotClass::PivotClass(void) : - Parent(NULL), - BaseTransform(1), - Transform(1), -#ifdef LAZY_CAP_MTX_ALLOC - CapTransformPtr(NULL), - Index(0), - IsVisible(true), - WorldSpaceTranslation(false) -#else - CapTransform(1), - Index(0), - IsVisible(true), - WorldSpaceTranslation(false), - IsCaptured(false), - Unused(false) -#endif -{ - Name[0] = 0; -} - -PivotClass::PivotClass(const PivotClass& that) : - Parent(that.Parent), - BaseTransform(that.BaseTransform), - Transform(that.Transform), -#ifdef LAZY_CAP_MTX_ALLOC - CapTransformPtr(NULL), - Index(that.Index), - IsVisible(that.IsVisible), - WorldSpaceTranslation(that.WorldSpaceTranslation) -#else - CapTransform(that.CapTransform), - Index(that.Index), - IsVisible(that.IsVisible), - WorldSpaceTranslation(that.WorldSpaceTranslation), - IsCaptured(that.IsCaptured), - Unused(that.Unused) -#endif -{ - memcpy(Name, that.Name, sizeof(Name)); -#ifdef LAZY_CAP_MTX_ALLOC - if (that.CapTransformPtr != NULL) - { - CapTransformPtr = MSGW3DNEW("PivotClassCaptureBoneMtx") DynamicMatrix3D; - CapTransformPtr->Mat = that.CapTransformPtr->Mat; - } -#endif -} - -PivotClass& PivotClass::operator=(const PivotClass& that) -{ - if (this != &that) - { - memcpy(Name, that.Name, sizeof(Name)); - Parent = that.Parent; - BaseTransform = that.BaseTransform; - Transform = that.Transform; - #ifdef LAZY_CAP_MTX_ALLOC - CapTransformPtr = NULL; - Index = that.Index; - IsVisible = that.IsVisible; - WorldSpaceTranslation = that.WorldSpaceTranslation; - if (that.CapTransformPtr != NULL) - { - CapTransformPtr = MSGW3DNEW("PivotClassCaptureBoneMtx") DynamicMatrix3D; - CapTransformPtr->Mat = that.CapTransformPtr->Mat; - } - #else - CapTransform = that.CapTransform; - Index = that.Index; - IsVisible = that.IsVisible; - WorldSpaceTranslation = that.WorldSpaceTranslation; - IsCaptured = that.IsCaptured; - Unused = that.Unused; - #endif - } - return *this; -} - -void PivotClass::Capture_Update(void) -{ -#ifdef LAZY_CAP_MTX_ALLOC - if (!CapTransformPtr) - return; - - const Matrix3D* ct = &CapTransformPtr->Mat; -#else - const Matrix3D* ct = &CapTransform; -#endif - - if ( WorldSpaceTranslation ) - { - // The Translation of CapTransform is meant to be in world space, - // so remove before applying orientation - Matrix3D CapOrientation = *ct; - CapOrientation.Set_Translation( Vector3( 0,0,0 ) ); -#ifdef ALLOW_TEMPORARIES - Matrix3D::Multiply(Transform,CapOrientation,&(Transform)); -#else - Transform.postMul(CapOrientation); -#endif - // Now apply translation in world space - Transform.Adjust_Translation( ct->Get_Translation() ); - } - else - { -#ifdef ALLOW_TEMPORARIES - Matrix3D::Multiply(Transform, *ct, &(Transform)); -#else - Transform.postMul(*ct); -#endif - } -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/pivot.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/pivot.h deleted file mode 100644 index c083133df3..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/pivot.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/pivot.h 1 1/22/01 3:36p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/pivot.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef PIVOT_H -#define PIVOT_H - -#include "always.h" -#include "vector3.h" -#include "matrix3d.h" -#include "quat.h" -#include "w3d_file.h" - - -/* - - PivotClass - - Each node of the hierarchy tree is represented by a - PivotClass. - -*/ - -//#define LAZY_CAP_MTX_ALLOC - -struct PivotClass -{ -public: - - PivotClass(void); - PivotClass(const PivotClass& that); - PivotClass& operator=(const PivotClass& that); - - ~PivotClass(void) - { -#ifdef LAZY_CAP_MTX_ALLOC - if (CapTransformPtr) - delete CapTransformPtr; -#endif - } - - void Capture_Update(void); - bool Is_Captured() const - { -#ifdef LAZY_CAP_MTX_ALLOC - return CapTransformPtr != NULL; -#else - return IsCaptured; -#endif - } - -public: - char Name[W3D_NAME_LEN]; - PivotClass * Parent; - Matrix3D BaseTransform; // base-pose transform (relative to parent). - Matrix3D Transform; // computed transform for this pivot - // User control. When a pivot is 'captured' animation data is ignored and the - // user data is used to control the pivot. -#ifdef LAZY_CAP_MTX_ALLOC - DynamicMatrix3D* CapTransformPtr; - short Index; - bool IsVisible; // result of the visibility channel - bool WorldSpaceTranslation; -#else - Matrix3D CapTransform; - int Index; - bool IsVisible; // result of the visibility channel - bool WorldSpaceTranslation; - bool IsCaptured; - bool Unused; // padding -#endif - -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp deleted file mode 100644 index eb959c193d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp +++ /dev/null @@ -1,1916 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /VSS_Sync/ww3d2/pointgr.cpp $* - * * - * Org Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 38 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *-------------------------------------------------------------------------* - * Functions: * - * PointGroupClass::PointGroupClass -- PointGroupClass CTor. * - * PointGroupClass::~PointGroupClass -- PointGroupClass DTor. * - * PointGroupClass::operator = -- PointGroupClass assignment operator. * - * PointGroupClass::Set_Arrays -- Set point location/color/enable arrays.* - * PointGroupClass::Set_Point_Size -- Set default point size. * - * PointGroupClass::Get_Point_Size -- Get default point size. * - * PointGroupClass::Set_Point_Color -- Set default point color. * - * PointGroupClass::Get_Point_Color -- Get default point color. * - * PointGroupClass::Set_Point_Alpha -- Set default point alpha. * - * PointGroupClass::Get_Point_Alpha -- Get default point alpha. * - * PointGroupClass::Set_Point_Orientation -- Set default point orientatio* - * PointGroupClass::Get_Point_Orientation -- Get default point orientatio* - * PointGroupClass::Set_Point_Frame -- Set default point frame. * - * PointGroupClass::Get_Point_Frame -- Get default point frame. * - * PointGroupClass::Set_Point_Mode -- Set point rendering method. * - * PointGroupClass::Get_Point_Mode -- Get point rendering method. * - * PointGroupClass::Set_Flag -- Set given flag to on or off. * - * PointGroupClass::Get_Flag -- Get current value (on/off) of given flag.* - * PointGroupClass::Set_Texture -- Set texture used. * - * PointGroupClass::Get_Texture -- Get texture used. * - * PointGroupClass::Set_Shader -- Set shader used. * - * PointGroupClass::Get_Shader -- Get shader used. * - * PointGroupClass::Set_Billboard -- Set whether to billboard. * - * PointGroupClass::Get_Billboard -- Get whether to billboard. * - * PointGroupClass::Get_Discrete_Orientation_Count_Log2 -- what it says * - * PointGroupClass::Set_Discrete_Orientation_Count_Log2 -- what it says. * - * PointGroupClass::Get_Frame_Row_Column_Count_Log2 -- what it says * - * PointGroupClass::Set_Frame_Row_Column_Count_Log2 -- what it says. * - * PointGroupClass::Get_Polygon_Count -- Get estimated polygon count. * - * PointGroupClass::Render -- draw point group. * - * PointGroupClass::vInstance -- Create instance of class. * - * PointGroupClass::sGetClassName -- Get name of class. * - * PointGroupClass::Update_Arrays -- Update all arrays used in rendering * - * PointGroupClass::Peek_Texture -- Peeks texture * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#include "pointgr.h" -#include "vertmaterial.h" -#include "ww3d.h" -#include "aabox.h" -#include "statistics.h" -#include "simplevec.h" -#include "texture.h" -#include "Vector.H" -#include "vp.h" -#include "matrix4.h" -#include "dx8wrapper.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "rinfo.h" -#include "camera.h" -#include "dx8fvf.h" -#include "d3dx8math.h" -#include "sortingrenderer.h" - -// Upgraded to DX8 2/2/01 HY - -// static data members -Vector3 PointGroupClass::_TriVertexLocationOrientationTable[256][3]; -Vector3 PointGroupClass::_QuadVertexLocationOrientationTable[256][4]; -Vector2 *PointGroupClass::_TriVertexUVFrameTable[5] = { NULL, NULL, NULL, NULL, NULL}; -Vector2 *PointGroupClass::_QuadVertexUVFrameTable[5] = { NULL, NULL, NULL, NULL, NULL}; -VertexMaterialClass *PointGroupClass::PointMaterial=NULL; - -// Static arrays for intermediate calcs (never resized down, just up): -VectorClass PointGroupClass::compressed_loc; // point locations 'compressed' by APT -VectorClass PointGroupClass::compressed_diffuse; // point colors 'compressed' by APT -VectorClass PointGroupClass::compressed_size; // point sizes 'compressed' by APT -VectorClass PointGroupClass::compressed_orient; // point orientations 'compressed' by APT -VectorClass PointGroupClass::compressed_frame; // point frames 'compressed' by APT -VectorClass PointGroupClass::transformed_loc; // transformed point locations - -// This array has vertex locations for screenspace mode - calculated to cover exactly 1x1 and 2x2 pixels. -Vector3 PointGroupClass::_ScreenspaceVertexLocationSizeTable[2][3] = -{ - Vector3(0.5f, 0.0f, -1.0f), - Vector3(1.0f, 1.0f, -1.0f), - Vector3(0.0f, 1.0f, -1.0f), - Vector3(1.0f, -0.5f, -1.0f), - Vector3(2.7f, 2.0f, -1.0f), - Vector3(-0.7f, 2.0f, -1.0f) -}; - -// useful for particles that aren't aligned with the screen. -static Vector3 GroundMultiplierX(1.0f, 0.0f, 0.0f); -static Vector3 GroundMultiplierY(0.0f, 1.0f, 0.0f); - -// Some internal variables -VectorClass VertexLoc; // camera-space vertex locations -VectorClass VertexDiffuse; // vertex diffuse/alpha colors -VectorClass VertexUV; // vertex texture coords - -// Some DX 8 variables -#define MAX_VB_SIZE 2048 -#define MAX_TRI_POINTS MAX_VB_SIZE/3 -#define MAX_TRI_IB_SIZE 3*MAX_TRI_POINTS -#define MAX_QUAD_POINTS MAX_VB_SIZE/4 -#define MAX_QUAD_IB_SIZE 6*MAX_QUAD_POINTS - -DX8IndexBufferClass *Tris, *Quads; // Index buffers. -SortingIndexBufferClass *SortingTris, *SortingQuads; // Sorting index buffers. - -/************************************************************************** - * PointGroupClass::PointGroupClass -- PointGroupClass CTor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -PointGroupClass::PointGroupClass(void) : - PointLoc(NULL), - PointDiffuse(NULL), - APT(NULL), - PointSize(NULL), - PointOrientation(NULL), - PointFrame(NULL), - PointCount(0), - FrameRowColumnCountLog2(0), - Texture(NULL), - Flags(0), - Shader(ShaderClass::_PresetAdditiveSpriteShader), - PointMode(TRIS), - DefaultPointSize(0.0f), - DefaultPointColor(1.0f, 1.0f, 1.0f), - DefaultPointAlpha(1.0f), - DefaultPointOrientation(0), - DefaultPointFrame(0), - VPXMin(0.0f), - VPYMin(0.0f), - VPXMax(0.0f), - VPYMax(0.0f) -{ -} - -/************************************************************************** - * PointGroupClass::~PointGroupClass -- PointGroupClass DTor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -PointGroupClass::~PointGroupClass(void) -{ - if (PointLoc) { - PointLoc->Release_Ref(); - PointLoc = NULL; - } - if (PointDiffuse) { - PointDiffuse->Release_Ref(); - PointDiffuse=NULL; - } - if (APT) { - APT->Release_Ref(); - APT = NULL; - } - if (PointSize) { - PointSize->Release_Ref(); - PointSize = NULL; - } - if (PointOrientation) { - PointOrientation->Release_Ref(); - PointOrientation = NULL; - } - if (PointFrame) { - PointFrame->Release_Ref(); - PointFrame = NULL; - } - if (Texture) { - REF_PTR_RELEASE(Texture); - Texture = NULL; - } -} - -/************************************************************************** - * PointGroupClass::operator = -- PointGroupClass assignment operator. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -PointGroupClass & PointGroupClass::operator = (const PointGroupClass & that) -{ - if (this != &that) { - WWASSERT(0); // If you hit this assert implement the function! - } - return *this; -} - - -/************************************************************************** - * PointGroupClass::Set_Arrays -- Set point location/color/enable arrays. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * NOTES: colors, alphas, APT, sizes, orientations and frames are * - * optional. active_point_count can also be used with a NULL apt.* - * In this case active_point_count is ignored if it is -1 * - * (default value) and otherwise it indicates the first N active * - * points in the arrays. * - * The view plane rectangle may optionally be passed as well - * - * this is only used in SCREENSPACE mode. * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - * 08/25/1999 NH : Alphas added. * - * 06/28/2000 NH : Orientations and frames added. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -void PointGroupClass::Set_Arrays( - ShareBufferClass *locs, - ShareBufferClass *diffuse, - ShareBufferClass *apt, - ShareBufferClass *sizes, - ShareBufferClass *orientations, - ShareBufferClass *frames, - int active_point_count, - float vpxmin, - float vpymin, - float vpxmax, - float vpymax) -{ - // The point locations array is NOT optional! - WWASSERT(locs); - - // Ensure lengths of all arrays are the same: - WWASSERT(!diffuse || locs->Get_Count() == diffuse->Get_Count()); - WWASSERT(!apt || locs->Get_Count() == apt->Get_Count()); - WWASSERT(!sizes || locs->Get_Count() == sizes->Get_Count()); - WWASSERT(!orientations || locs->Get_Count() == orientations->Get_Count()); - WWASSERT(!frames || locs->Get_Count() == frames->Get_Count()); - - REF_PTR_SET(PointLoc,locs); - REF_PTR_SET(PointDiffuse,diffuse); - REF_PTR_SET(APT,apt); - REF_PTR_SET(PointSize,sizes); - REF_PTR_SET(PointOrientation,orientations); - REF_PTR_SET(PointFrame,frames); - - if (APT) { - PointCount = active_point_count; - } else { - PointCount = (active_point_count >= 0) ? active_point_count : PointLoc->Get_Count(); - } - - // Store view plane rectangle (only used in SCREENSPACE mode) - VPXMin = vpxmin; - VPYMin = vpymin; - VPXMax = vpxmax; - VPYMax = vpymax; -} - -/************************************************************************** - * PointGroupClass::Set_Point_Size -- Set default point size. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This size is ignored if a size array is present. * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Point_Size(float size) -{ - DefaultPointSize = size; -} - - -/************************************************************************** - * PointGroupClass::Get_Point_Size -- Get default point size. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This size is ignored if a size array is present. * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -float PointGroupClass::Get_Point_Size(void) -{ - return DefaultPointSize; -} - - -/************************************************************************** - * PointGroupClass::Set_Point_Color -- Set default point color. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This color is ignored if a color array is present. * - * * - * HISTORY: * - * 04/20/1999 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Point_Color(Vector3 color) -{ - DefaultPointColor = color; -} - -/************************************************************************** - * PointGroupClass::Get_Point_Color -- Get default point color. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This color is ignored if a color array is present. * - * * - * HISTORY: * - * 04/20/1999 NH : Created. * - *========================================================================*/ -Vector3 PointGroupClass::Get_Point_Color(void) -{ - return DefaultPointColor; -} - -/************************************************************************** - * PointGroupClass::Set_Point_Alpha -- Set default point alpha. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This alpha is ignored if an alpha array is present. * - * * - * HISTORY: * - * 08/25/1999 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Point_Alpha(float alpha) -{ - DefaultPointAlpha = alpha; -} - - -/************************************************************************** - * PointGroupClass::Get_Point_Alpha -- Get default point alpha. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This alpha is ignored if an alpha array is present. * - * * - * HISTORY: * - * 08/25/1999 NH : Created. * - *========================================================================*/ -float PointGroupClass::Get_Point_Alpha(void) -{ - return DefaultPointAlpha; -} - - -/************************************************************************** - * PointGroupClass::Set_Point_Orientation -- Set default point orientation* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This is ignored if an orientation array is present. * - * * - * NOTE: No need to ensure value in valid range - it will be masked later.* - * * - * HISTORY: * - * 06/28/2000 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Point_Orientation(unsigned char orientation) -{ - DefaultPointOrientation = orientation; -} - - -/************************************************************************** - * PointGroupClass::Get_Point_Orientation -- Get default point orientation* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This is ignored if an orientation array is present. * - * * - * HISTORY: * - * 06/28/2000 NH : Created. * - *========================================================================*/ -unsigned char PointGroupClass::Get_Point_Orientation(void) -{ - return DefaultPointOrientation; -} - - -/************************************************************************** - * PointGroupClass::Set_Point_Frame -- Set default point frame. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This frame is ignored if an frame array is present. * - * * - * NOTE: No need to ensure value in valid range - it will be masked later.* - * * - * HISTORY: * - * 06/28/2000 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Point_Frame(unsigned char frame) -{ - DefaultPointFrame = frame; -} - - -/************************************************************************** - * PointGroupClass::Get_Point_Frame -- Get default point frame. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: This frame is ignored if an frame array is present. * - * * - * HISTORY: * - * 06/28/2000 NH : Created. * - *========================================================================*/ -unsigned char PointGroupClass::Get_Point_Frame(void) -{ - return DefaultPointFrame; -} - - -/************************************************************************** - * PointGroupClass::Set_Point_Mode -- Set point rendering method. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Point_Mode(PointModeEnum mode) -{ - PointMode = mode; -} - - -/************************************************************************** - * PointGroupClass::Get_Point_Mode -- Get point rendering method. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -PointGroupClass::PointModeEnum PointGroupClass::Get_Point_Mode(void) -{ - return PointMode; -} - - -/************************************************************************** - * Set_Flag -- PointGroupClass::Set given flag to on or off. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - *========================================================================*/ -void PointGroupClass::Set_Flag(FlagsType flag, bool onoff) -{ - if (onoff) Flags|=1<>flag) & 0x1; -} - -/************************************************************************** - * PointGroupClass::Set_Texture -- Set texture used. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -void PointGroupClass::Set_Texture(TextureClass* texture) -{ - REF_PTR_SET(Texture,texture); -} - -/************************************************************************** - * PointGroupClass::Get_Texture -- Get texture used. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -TextureClass * PointGroupClass::Get_Texture(void) -{ - if (Texture) Texture->Add_Ref(); - return Texture; -} - - -/*********************************************************************************************** - * PointGroupClass::Peek_Texture -- Peeks texture * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/12/2001 hy : Created. * - *=============================================================================================*/ -TextureClass * PointGroupClass::Peek_Texture(void) -{ - return Texture; -} - -/************************************************************************** - * PointGroupClass::Set_Shader -- Set shader used. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: the primary gradient will be set to MODULATE/DISABLE in * - * the shader depending on whether a color or alpha array was * - * passed in Set_Point_Arrays. also, texturing will be * - * enabled or disabled dependent on whether a non-NULL * - * texture was set. * - * these will override the primary gradient/texturing * - * settings in the given shader. * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -void PointGroupClass::Set_Shader(ShaderClass shader) -{ - Shader = shader; -} - - -/************************************************************************** - * PointGroupClass::Get_Shader -- Get shader used. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -ShaderClass PointGroupClass::Get_Shader(void) -{ - return Shader; -} - -/************************************************************************** - * PointGroupClass::Set_Billboard -- Set whether to Billboard. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/25/2002 JM : Created. * - *========================================================================*/ -void PointGroupClass::Set_Billboard(bool shouldBillboard) -{ - Billboard = shouldBillboard; -} - -/************************************************************************** - * PointGroupClass::Get_Billboard -- Get whether to Billboard. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/25/2002 JM : Created. * - *========================================================================*/ -bool PointGroupClass::Get_Billboard(void) -{ - return Billboard; -} - -/************************************************************************** - * PointGroupClass::Get_Frame_Row_Column_Count_Log2 -- what it says * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/28/2000 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -unsigned char PointGroupClass::Get_Frame_Row_Column_Count_Log2(void) -{ - return FrameRowColumnCountLog2; -} - - -/************************************************************************** - * PointGroupClass::Set_Frame_Row_Column_Count_Log2 -- what it says. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/28/2000 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -void PointGroupClass::Set_Frame_Row_Column_Count_Log2(unsigned char frccl2) -{ - FrameRowColumnCountLog2 = MIN(frccl2, 4); -} - -/************************************************************************** - * PointGroupClass::Get_Polygon_Count -- Get estimated polygon count. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/18/1998 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -int PointGroupClass::Get_Polygon_Count(void) -{ - switch (PointMode) { - case TRIS: - case SCREENSPACE: - return PointCount; - break; - case QUADS: - return PointCount * 2; - break; - } - WWASSERT(0); - return 0; -} - -/************************************************************************** - * PointGroupClass::Render -- draw point group. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/10/1998 NH : Created. * - * 02/08/2001 HY : Upgraded to DX8 * - *========================================================================*/ -static SimpleVecClass remap; -void PointGroupClass::Render(RenderInfoClass &rinfo) -{ - /// @todo lorenzen asks: is particle culling in the shader perhaps faster than in DoParticles? Fix winding and find out... - // NB: the winding for pointgroups is wrong, but we - // are disabling culling for particles anyway - Shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - - // If no points, do nothing: - if (PointCount == 0) return; - - WWASSERT(PointLoc && PointLoc->Get_Array()); - - // Process texture reductions: -// if (Texture) Texture->Process_Reduction(); - - // Pointers which point into existing buffers (member or static): - Vector3 *current_loc = NULL; - Vector4 *current_diffuse = NULL; - float *current_size = NULL; - unsigned char *current_orient = NULL; - unsigned char *current_frame = NULL; - - // If there is a color or alpha array enable gradient in shader - otherwise disable. - float value_255 = 0.9961f; //254 / 255 - bool default_white_opaque = ( DefaultPointColor.X > value_255 && - DefaultPointColor.Y > value_255 && - DefaultPointColor.Z > value_255 && - DefaultPointAlpha > value_255); - - // The reason we check for lack of texture here is that SR seems to render black triangles - // rather than white triangles as would be expected) when there is no texture AND no gradient. - if (PointDiffuse || !default_white_opaque || !Texture) { - Shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE); - } else { - Shader.Set_Primary_Gradient(ShaderClass::GRADIENT_DISABLE); - } - - // If Texture is non-NULL enable texturing in shader - otherwise disable. - if (Texture) { - Shader.Set_Texturing(ShaderClass::TEXTURING_ENABLE); - } else { - Shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE); - } - - // If there is an active point table, use it to compress the point - // locations/colors/alphas/sizes/orientations/frames. - if (APT) { - // Resize compressed result arrays if needed (2x guardband to prevent - // frequent reallocations): - - /// @todo lorenzen sez: precompute pointers to indexed array elements, below - - if (compressed_loc.Length() < PointCount) { - compressed_loc.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_loc[0], - PointLoc->Get_Array(), APT->Get_Array(), PointCount); - current_loc = &compressed_loc[0]; - if (PointDiffuse) { - if (compressed_diffuse.Length() < PointCount) { - compressed_diffuse.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_diffuse[0], - PointDiffuse->Get_Array(), APT->Get_Array(), PointCount); - current_diffuse = &compressed_diffuse[0]; - } - if (PointSize) { - if (compressed_size.Length() < PointCount) { - compressed_size.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_size[0], - PointSize->Get_Array(), APT->Get_Array(), PointCount); - current_size = &compressed_size[0]; - } - if (PointOrientation) { - if (compressed_orient.Length() < PointCount) { - compressed_orient.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_orient[0], - PointOrientation->Get_Array(), APT->Get_Array(), PointCount); - current_orient = &compressed_orient[0]; - } - if (PointFrame) { - if (compressed_frame.Length() < PointCount) { - compressed_frame.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_frame[0], - PointFrame->Get_Array(), APT->Get_Array(), PointCount); - current_frame = &compressed_frame[0]; - } - } else { - current_loc = PointLoc->Get_Array(); - if (PointDiffuse) { - current_diffuse = PointDiffuse->Get_Array(); - } - if (PointSize) { - current_size = PointSize->Get_Array(); - } - if (PointOrientation) { - current_orient = PointOrientation->Get_Array(); - } - if (PointFrame) { - current_frame = PointFrame->Get_Array(); - } - } - - // Get the world and view matrices - Matrix4x4 view; - DX8Wrapper::Get_Transform(D3DTS_VIEW,view); - - // Transform the point locations from worldspace to camera space if needed - // (i.e. if they are not already in camera space): - - // need to interrupt this processing. If we are not billboarding, then we need the actual position - // of the vertice to lay it down flat. - - // (gth) changed this 'if' to use OR rather than AND... The way it was caused all emitters to break - if (Get_Flag(TRANSFORM) && Billboard) { - // Resize transformed location array if needed (2x guardband to prevent - // frequent reallocations): - if (transformed_loc.Length() < PointCount) { - transformed_loc.Resize(PointCount * 2); - } - // Not using vector processor class because we are discarding w - // Not using T&L in DX8 because we don't want DX8 to transform - // 3 times per particle when we can do it once - for (int i=0; iGet_Count(), vnum, pnum); - - // the locations are now in view space - // so set world and view matrices to identity and render - - Matrix4x4 identity(true); - DX8Wrapper::Set_Transform(D3DTS_WORLD,identity); - DX8Wrapper::Set_Transform(D3DTS_VIEW,identity); - - DX8Wrapper::Set_Material(PointMaterial); - DX8Wrapper::Set_Shader(Shader); - DX8Wrapper::Set_Texture(0,Texture); - - // Enable sorting if the primitives are translucent and alpha testing is not enabled. - const bool sort = (Shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO) && (Shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE) && (WW3D::Is_Sorting_Enabled()); - - IndexBufferClass *indexbuffer; - int verticesperprimitive;/// lorenzen fixed - int current; - int delta; - - /// @todo lorenzen sez: if tri-based particles are not supported, elim this test - if (PointMode == QUADS) { - verticesperprimitive = 2; - indexbuffer = sort ? static_cast (SortingQuads) : static_cast (Quads); - } else { - verticesperprimitive = 3; - indexbuffer = sort ? static_cast (SortingTris) : static_cast (Tris); - } - - current = 0; - while (current MAX_VOLUME_PARTICLE_DEPTH ) - depth = MAX_VOLUME_PARTICLE_DEPTH; // sanity - - Shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - - if (PointCount == 0) - return; - - WWASSERT(PointLoc && PointLoc->Get_Array()); - - // Pointers which point into existing buffers (member or static): - Vector3 *current_loc = NULL; - Vector4 *current_diffuse = NULL; - float *current_size = NULL; - unsigned char *current_orient = NULL; - unsigned char *current_frame = NULL; - - // If there is a color or alpha array enable gradient in shader - otherwise disable. - float value_255 = 0.9961f; //254 / 255 - bool default_white_opaque = ( DefaultPointColor.X > value_255 && - DefaultPointColor.Y > value_255 && - DefaultPointColor.Z > value_255 && - DefaultPointAlpha > value_255); - - // The reason we check for lack of texture here is that SR seems to render black triangles - // rather than white triangles as would be expected) when there is no texture AND no gradient. - if (PointDiffuse || !default_white_opaque || !Texture) { - Shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE); - } else { - Shader.Set_Primary_Gradient(ShaderClass::GRADIENT_DISABLE); - } - - // If Texture is non-NULL enable texturing in shader - otherwise disable. - if (Texture) { - Shader.Set_Texturing(ShaderClass::TEXTURING_ENABLE); - } else { - Shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE); - } - - // Get the world and view matrices - Matrix4x4 view; - DX8Wrapper::Get_Transform(D3DTS_VIEW,view); - - - - //// VOLUME_PARTICLE LOOP /////////////// - for ( int t = 0; t < depth; ++t ) - { - - - - - - // If there is an active point table, use it to compress the point - // locations/colors/alphas/sizes/orientations/frames. - if (APT) { - // Resize compressed result arrays if needed (2x guardband to prevent - // frequent reallocations): - - /// @todo lorenzen sez: precompute pointers to indexed array elements, below - - if (compressed_loc.Length() < PointCount) { - compressed_loc.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_loc[0], - PointLoc->Get_Array(), APT->Get_Array(), PointCount); - current_loc = &compressed_loc[0]; - if (PointDiffuse) { - if (compressed_diffuse.Length() < PointCount) { - compressed_diffuse.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_diffuse[0], - PointDiffuse->Get_Array(), APT->Get_Array(), PointCount); - current_diffuse = &compressed_diffuse[0]; - } - if (PointSize) { - if (compressed_size.Length() < PointCount) { - compressed_size.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_size[0], - PointSize->Get_Array(), APT->Get_Array(), PointCount); - current_size = &compressed_size[0]; - } - if (PointOrientation) { - if (compressed_orient.Length() < PointCount) { - compressed_orient.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_orient[0], - PointOrientation->Get_Array(), APT->Get_Array(), PointCount); - current_orient = &compressed_orient[0]; - } - if (PointFrame) { - if (compressed_frame.Length() < PointCount) { - compressed_frame.Resize(PointCount * 2); - } - VectorProcessorClass::CopyIndexed(&compressed_frame[0], - PointFrame->Get_Array(), APT->Get_Array(), PointCount); - current_frame = &compressed_frame[0]; - } - } else { - current_loc = PointLoc->Get_Array(); - if (PointDiffuse) { - current_diffuse = PointDiffuse->Get_Array(); - } - if (PointSize) { - current_size = PointSize->Get_Array(); - } - if (PointOrientation) { - current_orient = PointOrientation->Get_Array(); - } - if (PointFrame) { - current_frame = PointFrame->Get_Array(); - } - } - - - - - - // Transform the point locations from worldspace to camera space if needed - // (i.e. if they are not already in camera space): - - // need to interrupt this processing. If we are not billboarding, then we need the actual position - // of the vertice to lay it down flat. - if (Get_Flag(TRANSFORM) && Billboard) { - // Resize transformed location array if needed (2x guardband to prevent - // frequent reallocations): - if (transformed_loc.Length() < PointCount) { - transformed_loc.Resize(PointCount * 2); - } - // Not using vector processor class because we are discarding w - // Not using T&L in DX8 because we don't want DX8 to transform - // 3 times per particle when we can do it once - float recipDepth = 0.1f / (float)depth; - - float shiftInc = ( t * *current_size * recipDepth ); - - Vector3 volumeLayerShift; - Vector3 cameraPosition = rinfo.Camera.Get_Position(); - - for (int i=0; iX *= attenuator; - //current_diffuse->Y *= attenuator; - //current_diffuse->Z *= attenuator; - //current_diffuse->W *= attenuator; - - Update_Arrays(current_loc, current_diffuse, current_size, current_orient, current_frame, - PointCount, PointLoc->Get_Count(), vnum, pnum); - - // the locations are now in view space - // so set world and view matrices to identity and render - - Matrix4x4 identity(true); - DX8Wrapper::Set_Transform(D3DTS_WORLD,identity); - DX8Wrapper::Set_Transform(D3DTS_VIEW,identity); - - DX8Wrapper::Set_Material(PointMaterial); - DX8Wrapper::Set_Shader(Shader); - DX8Wrapper::Set_Texture(0,Texture); - - // Enable sorting if the primitives are translucent and alpha testing is not enabled. - const bool sort = (Shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO) && (Shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE) && (WW3D::Is_Sorting_Enabled()); - - IndexBufferClass *indexbuffer; - int verticesperprimitive;/// lorenzen fixed - int current; - int delta; - - /// @todo lorenzen sez: if tri-based particles are not supported, elim this test - if (PointMode == QUADS) { - verticesperprimitive = 2; - indexbuffer = sort ? static_cast (SortingQuads) : static_cast (Quads); - } else { - verticesperprimitive = 3; - indexbuffer = sort ? static_cast (SortingTris) : static_cast (Tris); - } - - - float nudge = 0; - - current = 0; - while (current. -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/pointgr.h $* - * * - * $Author:: Naty_h $* - * * - * $Modtime:: 8/02/01 8:34p $* - * * - * $Revision:: 10 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef POINTGR_H -#define POINTGR_H - -#include "sharebuf.h" -#include "shader.h" -#include "vector4.h" -#include "vector3.h" -#include "vector2.h" -#include "Vector.H" - -class VertexMaterialClass; -class RenderInfoClass; -class TextureClass; - -/* -** PointGroupClass -- a custom object for rendering -** groups of points (such as particle systems). -** It is possible to change mode/number of points/shader/etc. but these -** changes tend to be expensive if done often. Expected usage is to set the -** point location/color/active arrays each frame the object is visible (with -** the same number of points) and perform other changes relatively rarely. -** NOTE: Currently it is implemented using general triangles (1 or 2 per -** point), so it is probably suboptimal for software rasterization devices -** (which would probably perform better with some kind of blit/sprite code). -*/ -class PointGroupClass -{ -public: - - enum PointModeEnum { - TRIS, // each point is a triangle - QUADS, // each point is a quad formed out of two triangles - SCREENSPACE // each point is a tri placed to affect certain pixels (should be used with 2D camera) - }; - - enum FlagsType { - TRANSFORM, // transform points w. modelview matrix (worldspace points) - }; - - PointGroupClass(void); - virtual ~PointGroupClass(void); - PointGroupClass & operator = (const PointGroupClass & that); - - // PointGroupClass interface: - void Set_Arrays(ShareBufferClass *locs, - ShareBufferClass *diffuse = NULL, - ShareBufferClass *apt = NULL, - ShareBufferClass *sizes = NULL, - ShareBufferClass *orientations = NULL, - ShareBufferClass *frames = NULL, - int active_point_count = -1, - float vpxmin = 0.0f, float vpymin = 0.0f, - float vpxmax = 0.0f, float vpymax = 0.0f); - void Set_Point_Size(float size); - float Get_Point_Size(void); - void Set_Point_Color(Vector3 color); - Vector3 Get_Point_Color(void); - void Set_Point_Alpha(float alpha); - float Get_Point_Alpha(void); - void Set_Point_Orientation(unsigned char orientation); - unsigned char Get_Point_Orientation(void); - void Set_Point_Frame(unsigned char frame); - unsigned char Get_Point_Frame(void); - void Set_Point_Mode(PointModeEnum mode); - PointModeEnum Get_Point_Mode(void); - void Set_Flag(FlagsType flag, bool onoff); - int Get_Flag(FlagsType flag); - void Set_Texture(TextureClass* texture); - TextureClass * Get_Texture(void); - TextureClass * Peek_Texture(void); - void Set_Shader(ShaderClass shader); - ShaderClass Get_Shader(void); - void Set_Billboard(bool shouldBillboard); - bool Get_Billboard(void); - - // The frame property is taken from a set of possible frames. The rows/columns in the frame - // texture determine the number of possible frames. Since it must be a power of 2, we represent - // it as its log base 2. This number cannot be greater than 4 (which corresponds to a 16x16 - // square of frames, i.e. 256 frames). - unsigned char Get_Frame_Row_Column_Count_Log2(void); - void Set_Frame_Row_Column_Count_Log2(unsigned char frccl2); - - int Get_Polygon_Count(void); - - void Render(RenderInfoClass &rinfo); - void RenderVolumeParticle(RenderInfoClass &rinfo, unsigned int depth); - -protected: - // Update arrays. - void Update_Arrays(Vector3 *point_loc, - Vector4 *point_diffuse, - float *point_size, - unsigned char *point_orientation, - unsigned char *point_frame, - int active_points, - int total_points, - int &vnum, - int &pnum); - - // These shared buffers are used for communication to the point group - to - // pass point locations, colors and enables. The location and color arrays - // are 'compressed' using the active point table (if present) and then - // are processed into other arrays which are passed to the GERD. - // SR rather than WWMath types are used so Vector Processors can be used. - // The arrays override the default value if present. - // The orientation and frame properties are "index properties": they select one out of a small - // group of possibilities for each point. - // Orientation: this is the 2D rotation of the point about its center. There are 256 discrete - // orientations. The unit circle is evenly subdivided 256 times to create the set of - // orientations. The reason we discretize orientation is for performance: this way we can - // precalculate vertex offsets. - // Frame: the texture is divided into a 2D square grid, and each point uses one grid square - // instead of the whole texture. The number of possible frames is not invariant - it depends - // on the number of rows / columns in the grid. The reason we do this instead of having - // different textures is to avoid texture state changes. Also for performance reasons, the - // number of possible frames must be a power of two - for this reason the number of frame rows - // and columns, orientations, etc. are represented as the log base 2 of the actual number. - ShareBufferClass * PointLoc; // World/cameraspace point locs - ShareBufferClass * PointDiffuse; // (NULL if not used) RGBA values - ShareBufferClass * APT; // (NULL if not used) active point table - ShareBufferClass * PointSize; // (NULL if not used) size override table - ShareBufferClass * PointOrientation; // (NULL if not used) orientation indices - ShareBufferClass * PointFrame; // (NULL if not used) frame indices - int PointCount; // Active (if APT) or total point count - - // See comments for Get/Set_Frame_Row_Column_Count_Log2 above - unsigned char FrameRowColumnCountLog2; // MUST be equal or lesser than 4 - - // These parameters are passed to the GERD: - TextureClass* Texture; - ShaderClass Shader; // (default created in CTor) - - // Internal state: - PointModeEnum PointMode; // are points tris or quads? - unsigned int Flags; // operation control flags - float DefaultPointSize; // point size (size array overrides if present) - Vector3 DefaultPointColor; // point color (color array overrides if present) - float DefaultPointAlpha; // point alpha (alpha array overrides if present) - unsigned char DefaultPointOrientation;// point orientation (orientation array overrides if present) - unsigned char DefaultPointFrame; // point texture frame (frame array overrides if present) - - // View plane rectangle (only used in SCREENSPACE mode - set by Set_Arrays - // and used in Update_GERD_Arrays). - float VPXMin; - float VPYMin; - float VPXMax; - float VPYMax; - - bool Billboard; - - // Static stuff: - // For performance / memory reasons we prepare vertex location and UV - // arrays for various orientations and texture frames, as static data - // members of this class. This avoids the need to create such arrays over - // again for each object. The values in the UV arrays are used as-is, the - // values in the location arrays normally need to be scaled to the point - // sizes and added to the point location before use. We have distinct sets - // of arrays for each point mode. - // There are tables of vertex positions for each of triangle and quad mode - // with 256 discrete orientations. Each entry contains 3 (for triangle - // mode) or 4 (for quad mode) Vector3s. - // There are five tables of texture UVs for each of triangle and quad mode: - // with 1x1(1), 2x2(4), 4x4(16), 8x8(64) and 16x16(256) frames. Each entry - // contains 3 (for triangle mode) or 4 (for quad mode) Vector2s. - // In addition, there is one array of vertex positions for screenspace mode - // with 2 entries (for size 1 and size 2). Each entry contains 3 Vector3s. - // the Init function (which is called by WW3D::Init()) creates these - // arrays, and the Shutdown function (which is called by WW3D::Shutdown() - // releases them. -public: - static void _Init(void); - static void _Shutdown(void); - -private: - static Vector3 _TriVertexLocationOrientationTable[256][3]; - static Vector3 _QuadVertexLocationOrientationTable[256][4]; - static Vector3 _ScreenspaceVertexLocationSizeTable[2][3]; - static Vector2 *_TriVertexUVFrameTable[5]; - static Vector2 *_QuadVertexUVFrameTable[5]; - static VertexMaterialClass *PointMaterial; - - // Static arrays for intermediate calcs (never resized down, just up): - static VectorClass compressed_loc; // point locations 'compressed' by APT - static VectorClass compressed_diffuse; // point colors 'compressed' by APT - static VectorClass compressed_size; // point sizes 'compressed' by APT - static VectorClass compressed_orient; // point orientations 'compressed' by APT - static VectorClass compressed_frame; // point frames 'compressed' by APT - static VectorClass transformed_loc; // transformed point locations -}; - - -class SegmentGroupClass : public PointGroupClass -{ -public: - SegmentGroupClass(void); - virtual ~SegmentGroupClass(void); - -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp deleted file mode 100644 index ab13c19fde..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/polyinfo.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 2/07/01 12:50p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "polyinfo.h" -#include "texture.h" -#include "vertmaterial.h" -#include "shader.h" - -void PolygonInfoClass::Set_Texture(TextureClass *texture) -{ - if(texture) - texture->Add_Ref(); - if(Texture) - Texture->Release_Ref(); - Texture = texture; -} -void PolygonInfoClass::Set_Vertex_Material(VertexMaterialClass *vertexMaterial) -{ - if(vertexMaterial) - vertexMaterial->Add_Ref(); - if(VertexMaterial) - VertexMaterial->Release_Ref(); - - VertexMaterial = vertexMaterial; -} - -void PolygonInfoClass::Set_Shader(ShaderClass *shader) -{ - if(Shader) - delete Shader; - - // todo : update for refcounted shaders - Shader = W3DNEW ShaderClass(* shader); -} - - -PolygonInfoClass::~PolygonInfoClass() -{ - if(Texture) - Texture->Release_Ref(); - if(VertexMaterial) - VertexMaterial->Release_Ref(); - - // todo : update for refcounted shaders - if(Shader) - delete Shader; -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.h deleted file mode 100644 index cccd45e918..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/polyinfo.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/polyinfo.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 2/07/01 12:48p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef POLYINFO_H -#define POLYINFO_H - -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -class TextureClass; -class VertexMaterialClass; -class ShaderClass; - - -/** -** PolyInfo.h -** -** This class is a simple storage class that keeps track of a texture, vertex material -** and a shader. -** -*/ -class PolygonInfoClass -{ - -public: - - TextureClass * Peek_Texture() const { return Texture; } - VertexMaterialClass * Peek_Vertex_Material() const { return VertexMaterial; } - ShaderClass * Peek_Shader() const { return Shader; } - - void Set_Texture(TextureClass *texture); - void Set_Vertex_Material(VertexMaterialClass *vertexMaterial); - void Set_Shader(ShaderClass *shader); - - void Set(TextureClass *texture, VertexMaterialClass *vertexMaterial, ShaderClass *shader) - { - Set_Texture(texture); - Set_Vertex_Material(vertexMaterial); - Set_Shader(shader); - } - - PolygonInfoClass(TextureClass *texture = 0, VertexMaterialClass *vertexMaterial = 0, ShaderClass *shader = 0) - : Texture(0), VertexMaterial(0), Shader(0) - { - Set(texture, vertexMaterial, shader); - } - - ~PolygonInfoClass(); - - -protected: - - TextureClass *Texture; - VertexMaterialClass *VertexMaterial; - ShaderClass *Shader; -}; - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/predlod.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/predlod.cpp deleted file mode 100644 index fc4e7620c2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/predlod.cpp +++ /dev/null @@ -1,406 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/predlod.cpp $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 9/20/01 10:10a $* - * * - * $Revision:: 5 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * PredictiveLODOptimizerClass::Clear -- clear object list and total cost* - * PredictiveLODOptimizerClass::Add_Object -- adds object to list, cost * - * PredictiveLODOptimizerClass::Optimize_LODs -- does LOD optimization * - * PredictiveLODOptimizerClass::Free -- releases all memory used. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "predlod.h" -#include - -/* NOTE: The LODHeapNode and LODHeap classes are defined here for use in the - * Optimize_LODs() member function. */ - -// A node entry for a heap. It has no son/father pointers since it will be -// used in an array implementation of a heap. - -/* -** NOTE: LODHeapNodes contain pointers to RenderObjClass, but these pointers -** are NOT tracked via refcounting. This is because the heaps are created and -** destroyed within one function, so all references created are necessary; -** and performing Add_Ref and Release_Ref every time a pointer is copied -** would hurt performance. -*/ - -class LODHeapNode { - public: - LODHeapNode(void) { Item = NULL; } - LODHeapNode (float key) { Item = NULL; Key = key; } - LODHeapNode (RenderObjClass * item, float key) { Item = item; Key = key; } - - ~LODHeapNode(void) { } - - RenderObjClass * Get_Item(void) { return(Item); } - - float Get_Key(void) { return(Key); } - void Set_Key(float key) { Key = key; } - - int operator < (const LODHeapNode& node) { return(Key < node.Key); } - int operator <= (const LODHeapNode& node) { return(Key <= node.Key); } - int operator > (const LODHeapNode& node) { return(Key > node.Key); } - int operator >= (const LODHeapNode& node) { return(Key >= node.Key); } - int operator == (const LODHeapNode& node) { return(Key == node.Key); } - int operator != (const LODHeapNode& node) { return(Key != node.Key); } - - private: - RenderObjClass *Item; - float Key; -}; - -// A Heap implemented as a complete binary tree in an array. -class LODHeap { - public: - // This constructor receives an array of HeapNodes and arranges it to - // fulfil the heap condition. Note: the array will be used inside the - // heap, so it should never be used or deleted outside. The resulting - // heap is full - no nodes can be added until some are removed. - LODHeap(int count, LODHeapNode *NodeArray) { - Nodes = NodeArray; - Num = Max = count; - // Now build a heap from the array by working backwards, building - // subheaps from the bottom up. (starting at the middle of the array - // since the single-node subtrees at the leaves are already heaps) - int index; - for (index = Num/2; index >= 1; index--) Downheap(index); - } - - ~LODHeap(void) { -// delete []Nodes; - } - - LODHeapNode *Top(void) { - return &(Nodes[1]); - } - - // This changes the key value of the entry at the top of the heap and - // adjusts the heap accordingly. - void Change_Key_Top(float new_key) { - Nodes[1].Set_Key(new_key); - Downheap(1); - } - - // This searches for an entry which has a certain Item value, and - // changes its key to a new one. The heap is then adjusted accordingly. - void Change_Key(RenderObjClass *item, float new_key) { - for (int i=1; i <= Num; i++) { - if (Nodes[i].Get_Item() == item) { - float old_key = Nodes[i].Get_Key(); - Nodes[i].Set_Key(new_key); - // If the key has been decreased, adjust the node downwards. - // Otherwise, adjust it upwards. - if (new_key < old_key) Downheap(i); - else Upheap(i); - break; - } - } - } - - private: - LODHeap(void) {} // Just to ensure the default constructor is not used. - - // The node and key arrays have one extra entry because entry [0] is - // reserved for various uses. - LODHeapNode * Nodes; // The nodes - - int Max; // The maximum number of nodes - int Num; // the current number of nodes - - // Two utility methods used by various other methods: both take a - // single entry which violates the heap condition and moves it in the - // heap until the heap condition is fulfilled. - - // Upheap takes an entry with a (possibly) overlarge key and moves it - // up until the heap condition is satisfied. (this is a private - // method, so no error checking is needed). - // Note that Upheap puts a sentinel in Nodes[0]. - void Upheap(int index) { - LODHeapNode node = Nodes[index]; - Nodes[0].Set_Key(FLT_MAX); - while (Nodes[index/2] <= node) { - Nodes[index] = Nodes[index/2]; - index = index/2; - } - Nodes[index] = node; - } - - // Downheap takes an entry with a (possibly) oversmall key and moves it - // down until the heap condition is satisfied. (this is a private - // method, so no error checking is needed). - void Downheap(int index) { - LODHeapNode node = Nodes[index]; - while (index <= Num/2) { - int child_index = index + index; - if ((child_index < Num) && (Nodes[child_index] < Nodes[child_index+1])) child_index++; - if (node >= Nodes[child_index]) break; - Nodes[index] = Nodes[child_index]; - index = child_index; - } - Nodes[index] = node; - } -}; - -// Static PredictiveLODOptimizerClass data members: -RenderObjClass ** PredictiveLODOptimizerClass::ObjectArray = NULL; -int PredictiveLODOptimizerClass::ArraySize = 0; -int PredictiveLODOptimizerClass::NumObjects = 0; -float PredictiveLODOptimizerClass::TotalCost = 0.0f; -LODHeapNode * PredictiveLODOptimizerClass::VisibleObjArray1; -LODHeapNode * PredictiveLODOptimizerClass::VisibleObjArray2; -int PredictiveLODOptimizerClass::VisibleObjArraySize; - - -/************************************************************************** - * PredictiveLODOptimizerClass::Clear -- clear object list and total cost * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/12/1999 NH : Created. * - *========================================================================*/ -void PredictiveLODOptimizerClass::Clear(void) -{ - if (ObjectArray) { - // Release refs to all objects in the list: - for (int i = 0; i < NumObjects; i++) { - if (ObjectArray[i]) { - ObjectArray[i]->Release_Ref(); - ObjectArray[i] = NULL; - } - } - } - - TotalCost = 0.0f; - NumObjects = 0; -} - - -/************************************************************************** - * PredictiveLODOptimizerClass::Add_Object -- adds object to list, cost * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/12/1999 NH : Created. * - *========================================================================*/ -void PredictiveLODOptimizerClass::Add_Object(RenderObjClass *robj) -{ - // If array present but too small, free it and copy it to new array. - if (ObjectArray) { - if (ArraySize <= NumObjects) { - int new_array_size = NumObjects + 100; - RenderObjClass **new_array = W3DNEWARRAY RenderObjClass *[new_array_size]; - memcpy(new_array, ObjectArray, sizeof(RenderObjClass *) * NumObjects); - delete [] ObjectArray; - ObjectArray = new_array; - ArraySize = new_array_size; - } - } else { - // Create new object array. - ObjectArray = W3DNEWARRAY RenderObjClass *[100]; - } - - // Copy pointer and add ref - ObjectArray[NumObjects] = robj; - ObjectArray[NumObjects]->Add_Ref(); - NumObjects++; - - float cost = robj->Get_Cost(); - // Some sanity checking so one object doesn't mess up the entire scene - WWASSERT (cost >= 0.0f); - WWASSERT (cost < 1.0e6); - TotalCost += cost; -} - - -/************************************************************************** - * PredictiveLODOptimizerClass::Optimize_LODs -- does LOD optimization * - * * - * INPUT: float max_cost - the upper bound on the total scene Cost. * - * * - * OUTPUT: none. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/08/1997 NH : Created. * - * 04/23/1997 NH : Ported to SR 1.3. * - * 03/12/1999 NH : Moved to PredictiveLODOptimizerClass. * - * * - * COMMENTS: * - * This function implements the algorithm outlined in "Adaptive * - * Display Algorithm for Interactive Frame Rates During Visualization * - * of Complex Virtual Environments", Thomas Funkhouser & Carlo Sequin, * - * SIGGRAPH '93 Proceedings, pp. 247-253. * - * Modifications have been made to support screensize clamping of LODs. * - *========================================================================*/ -void PredictiveLODOptimizerClass::Optimize_LODs(float max_cost) -{ - if (!ObjectArray || NumObjects == 0) return; - - AllocVisibleObjArrays(NumObjects); - - // Allocate and fill arrays. (one extra entry since the zeroth entry is not used). -// LODHeapNode *visible_obj_array1 = W3DNEWARRAY LODHeapNode[NumObjects + 1]; -// LODHeapNode *visible_obj_array2 = W3DNEWARRAY LODHeapNode[NumObjects + 1]; - - // Insert objects into arrays: (0th entry reserved for sentinel values) - for (int i = 0; i < NumObjects; i++) { - RenderObjClass *robj = ObjectArray[i]; - // We use minus Value for the first queue to make it ordered by minimum Value. - VisibleObjArray1[i + 1] = LODHeapNode(robj, -(robj->Get_Value())); - VisibleObjArray2[i + 1] = LODHeapNode(robj, robj->Get_Post_Increment_Value()); - } - - // Build priority queues: - LODHeap min_current_value_queue(NumObjects, VisibleObjArray1); - LODHeap max_post_increment_value_queue(NumObjects, VisibleObjArray2); - // These memory areas now are pointed to within the heaps: -// visible_obj_array1 = NULL; -// visible_obj_array2 = NULL; - - // Main loop: iteratively increment/decrement tuples. - bool done = false; - RenderObjClass *max_data, *min_data; - - while (!done) { - // Initialize max_data and min_data so comparison at end of loop uses correct values. - max_data = NULL; - min_data = NULL; - - // Increment incrementable tuple with maximum next value. - if (TotalCost <= max_cost) { - // If tuple with maximum next value is already at maximum lod, all - // tuples are (since AT_MAX_LOD is smaller than any Value), so stop. - if (max_post_increment_value_queue.Top()->Get_Key() == RenderObjClass::AT_MAX_LOD) { - done = true; - break; - } - - // Get (incrementable) tuple with maximum next value. - max_data = max_post_increment_value_queue.Top()->Get_Item(); - - // Increment tuple (and update TotalCost accordingly). - TotalCost -= max_data->Get_Cost(); - max_data->Increment_LOD(); - TotalCost += max_data->Get_Cost(); - - // Update priority queues with incremented tuple. - max_post_increment_value_queue.Change_Key_Top(max_data->Get_Post_Increment_Value()); - min_current_value_queue.Change_Key(max_data, -(max_data->Get_Value())); - } - - // Decrement decerementable tuples with minimum current value. - while (TotalCost > max_cost) { - // If tuple with minimum current value is already at minimum lod, all - // tuples are (since AT_MIN_LOD is smaller than any (negated) Value), - // so stop. - if (min_current_value_queue.Top()->Get_Key() == -RenderObjClass::AT_MIN_LOD) { - done = true; - break; - } - - // Get (decrementable) tuple with minimum current value. - min_data = min_current_value_queue.Top()->Get_Item(); - - // Decrement tuple (and update TotalCost accordingly). - TotalCost -= min_data->Get_Cost(); - min_data->Decrement_LOD(); - TotalCost += min_data->Get_Cost(); - - // Update priority queues with incremented tuple. - min_current_value_queue.Change_Key_Top(-(min_data->Get_Value())); - max_post_increment_value_queue.Change_Key(min_data, min_data->Get_Post_Increment_Value()); - - // Check termination criterion (same tuple incremented and decremented). - if (max_data == min_data) { - done = true; - break; - } - } - } - - // Clear optimizer: - Clear(); -} - - -/************************************************************************** - * PredictiveLODOptimizerClass::Free -- releases all memory used. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/12/1999 NH : Created. * - *========================================================================*/ -void PredictiveLODOptimizerClass::Free(void) -{ - Clear(); - - if (ObjectArray) { - delete [] ObjectArray; - ObjectArray = NULL; - ArraySize = 0; - } - - // Only the array number one has been allocated... - if (VisibleObjArray1) delete[] VisibleObjArray1; - VisibleObjArray1=NULL; - VisibleObjArray2=NULL; - VisibleObjArraySize = 0; -} - -void PredictiveLODOptimizerClass::AllocVisibleObjArrays(int num_objects) -{ - if (VisibleObjArraySize. -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/predlod.h $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 9/20/01 10:10a $* - * * - * $Revision:: 3 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef PREDLOD_H -#define PREDLOD_H - -// This file contains the classes which support predictive LOD management -// similar to that outlined in "Adaptive Display Algorithm for Interactive -// Frame Rates During Visualization of Complex Virtual Environments", -// Thomas Funkhouser & Carlo Sequin, SIGGRAPH '93 Proceedings, pp. 247-253. -// To this "pure predictive" LOD we have added distance (actually screensize) -// clamping to control quality degradation. - -#include "rendobj.h" -#include "float.h" -#include "Vector.H" - -class LODHeapNode; - -/* -** PredictiveLODOptimizerClass: Class which performs the predictive LOD -** optimization. All the members of this class are static. -*/ -class PredictiveLODOptimizerClass { - - public: - - static void Clear(void); - static void Add_Object(RenderObjClass *robj); - static void Add_Cost(float cost) { TotalCost += cost; } - static void Optimize_LODs(float max_cost); - static float Get_Total_Cost(void) { return TotalCost; } - static void Free(void); // frees all memory - - private: - static void AllocVisibleObjArrays(int num_objects); - - static RenderObjClass ** ObjectArray; - static int ArraySize; - static int NumObjects; - static float TotalCost; - - static LODHeapNode *VisibleObjArray1; - static LODHeapNode *VisibleObjArray2; - static int VisibleObjArraySize; - -}; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp deleted file mode 100644 index 79fe8e40ba..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/prim_anim.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "prim_anim.h" -#include "chunkio.h" - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.h deleted file mode 100644 index c4a00e9732..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/prim_anim.h +++ /dev/null @@ -1,391 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/prim_anim.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 1/29/01 5:43p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __PRIM_ANIM_H -#define __PRIM_ANIM_H - - -#include "simplevec.h" -#include "chunkio.h" - - -// Forward declarations -class ChunkSaveClass; -class ChunkLoadClass; - - -///////////////////////////////////////////////////////////////////// -// -// PrimitiveAnimationChannelClass -// -// This template class provides animated 'channels' of data for the -// RingRenderObjClass and SphereRenderObjClass objects. -// -///////////////////////////////////////////////////////////////////// -template -class PrimitiveAnimationChannelClass -{ -public: - - ///////////////////////////////////////////////////////// - // Public constructors/destructors - ///////////////////////////////////////////////////////// - PrimitiveAnimationChannelClass (void) - : m_LastIndex (0) { } - virtual ~PrimitiveAnimationChannelClass (void) { Reset (); } - - ///////////////////////////////////////////////////////// - // Public data types - ///////////////////////////////////////////////////////// - class KeyClass - { - public: - KeyClass (void) - : m_Time (0) {} - - KeyClass (const T &value, float time) - : m_Value (value), - m_Time (time) {} - - float Get_Time (void) const { return m_Time; } - const T & Get_Value (void) const { return m_Value; } - T & Get_Value (void) { return m_Value; } - - float Set_Time (float time) { m_Time = time; } - void Set_Value (const T &value) { m_Value = value; } - - private: - T m_Value; - float m_Time; - }; - - ///////////////////////////////////////////////////////// - // Public operators - ///////////////////////////////////////////////////////// - const PrimitiveAnimationChannelClass &operator= (const PrimitiveAnimationChannelClass &src); - const KeyClass & operator[] (int index) { return Get_Key (index); } - - ///////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////// - virtual T Evaluate (float time) = 0; - - int Get_Key_Count (void) const; - const KeyClass & Get_Key (int index) const; - void Set_Key (int index, const T &value, float time); - void Set_Key_Value (int index, const T &value); - void Add_Key (const T &value, float time); - void Insert_Key (int index, const T &value, float time); - void Delete_Key (int index); - void Reset (void); - - virtual void Save (ChunkSaveClass &csave); - virtual void Load (ChunkLoadClass &cload); - -protected: - - ///////////////////////////////////////////////////////// - // Protected constants - ///////////////////////////////////////////////////////// - enum - { - CHUNKID_VARIABLES = 0x03150809, - }; - - enum - { - VARID_KEY = 1, - }; - - ///////////////////////////////////////////////////////// - // Protected methods - ///////////////////////////////////////////////////////// - void Load_Variables (ChunkLoadClass &cload); - -protected: - - ///////////////////////////////////////////////////////// - // Protected member data - ///////////////////////////////////////////////////////// - SimpleDynVecClass< KeyClass > m_Data; - int m_LastIndex; -}; - - -///////////////////////////////////////////////////////////////////// -// -// LERPAnimationChannelClass -// -// This template class provides a simple LERP implementation of the -// Evaluate () method. -// -///////////////////////////////////////////////////////////////////// -template -class LERPAnimationChannelClass : public PrimitiveAnimationChannelClass -{ - using PrimitiveAnimationChannelClass::m_Data; - using PrimitiveAnimationChannelClass::m_LastIndex; -public: - using PrimitiveAnimationChannelClass::KeyClass; - -public: - - ///////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////// - virtual T Evaluate (float time); -}; - - -///////////////////////////////////////////////////////// -// Set_Key -///////////////////////////////////////////////////////// -template -int PrimitiveAnimationChannelClass::Get_Key_Count (void) const -{ - return m_Data.Count (); -} - -///////////////////////////////////////////////////////// -// Set_Key_Value -///////////////////////////////////////////////////////// -template -typename const PrimitiveAnimationChannelClass::KeyClass &PrimitiveAnimationChannelClass::Get_Key (int index) const -{ - return m_Data[index]; -} - -///////////////////////////////////////////////////////// -// Set_Key -///////////////////////////////////////////////////////// -template -void PrimitiveAnimationChannelClass::Set_Key (int index, const T &value, float time) -{ - m_Data[index].Set_Value (value); - m_Data[index].Set_Time (time); - return ; -} - -///////////////////////////////////////////////////////// -// Set_Key_Value -///////////////////////////////////////////////////////// -template -void PrimitiveAnimationChannelClass::Set_Key_Value (int index, const T &value) -{ - m_Data[index].Set_Value (value); - return ; -} - -///////////////////////////////////////////////////////// -// Add_Key -///////////////////////////////////////////////////////// -template -void PrimitiveAnimationChannelClass::Add_Key (const T &value, float time) -{ - m_Data.Add (KeyClass (value, time)); - return ; -} - -///////////////////////////////////////////////////////// -// Insert_Key -///////////////////////////////////////////////////////// -template -void PrimitiveAnimationChannelClass::Insert_Key (int index, const T &value, float time) -{ - m_Data.Insert (index, KeyClass (value, time)); - return ; -} - -///////////////////////////////////////////////////////// -// Delete_Key -///////////////////////////////////////////////////////// -template -void PrimitiveAnimationChannelClass::Delete_Key (int index) -{ - m_Data.Delete (index); - return ; -} - -///////////////////////////////////////////////////////// -// Reset -///////////////////////////////////////////////////////// -template -void PrimitiveAnimationChannelClass::Reset (void) -{ - m_Data.Delete_All (); - m_LastIndex = 0; - return ; -} - -///////////////////////////////////////////////////////////////////// -// operator= -///////////////////////////////////////////////////////////////////// -template const PrimitiveAnimationChannelClass & -PrimitiveAnimationChannelClass::operator= (const PrimitiveAnimationChannelClass &src) -{ - Reset (); - - // - // Copy the data array - // - for (int index = 0; index < src.Get_Key_Count (); index ++) { - m_Data.Add (src.Get_Key (index)); - } - - m_LastIndex = src.m_LastIndex; - return *this; -} - -///////////////////////////////////////////////////////////////////// -// Save -///////////////////////////////////////////////////////////////////// -template void -PrimitiveAnimationChannelClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_VARIABLES); - - // - // Save each key - // - for (int index = 0; index < m_Data.Count (); index ++) { - KeyClass &value = m_Data[index]; - WRITE_MICRO_CHUNK (csave, VARID_KEY, value); - } - - csave.End_Chunk (); - - return ; -} - -///////////////////////////////////////////////////////////////////// -// Load -///////////////////////////////////////////////////////////////////// -template void -PrimitiveAnimationChannelClass::Load (ChunkLoadClass &cload) -{ - Reset (); - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_VARIABLES: - Load_Variables (cload); - break; - } - - cload.Close_Chunk (); - } - - return ; -} - -///////////////////////////////////////////////////////////////////// -// Load_Variables -///////////////////////////////////////////////////////////////////// -template void -PrimitiveAnimationChannelClass::Load_Variables (ChunkLoadClass &cload) -{ - // - // Loop through all the microchunks that define the variables - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - case VARID_KEY: - { - KeyClass value; - cload.Read (&value, sizeof (value)); - m_Data.Add (value); - } - break; - } - - cload.Close_Micro_Chunk (); - } - - return ; -} - -///////////////////////////////////////////////////////////////////// -// Evaluate -///////////////////////////////////////////////////////////////////// -template T -LERPAnimationChannelClass::Evaluate (float time) -{ - int key_count = m_Data.Count (); - T value = m_Data[key_count - 1].Get_Value (); - - // - // Don't interpolate past the last keyframe - // - if (time < m_Data[key_count - 1].Get_Time ()) { - - // Check to see if the last key index is valid - if (time < m_Data[m_LastIndex].Get_Time ()) { - m_LastIndex = 0; - } - - KeyClass *key1 = &m_Data[m_LastIndex]; - KeyClass *key2 = &m_Data[key_count - 1]; - - // - // Search, using last_key as our starting point - // - for (int keyidx = m_LastIndex; keyidx < (key_count - 1); keyidx ++) { - - if (time < m_Data[keyidx+1].Get_Time ()) { - key1 = &m_Data[keyidx]; - key2 = &m_Data[keyidx+1]; - m_LastIndex = keyidx; - break; - } - } - - // Calculate the linear percent between the two keys - float percent = (time - key1->Get_Time ()) / (key2->Get_Time () - key1->Get_Time ()); - - // Interpolate the value - value = (key1->Get_Value () + (key2->Get_Value () - key1->Get_Value ()) * percent); - } - - return value; -} - -#endif //__PRIM_ANIM_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/projector.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/projector.cpp deleted file mode 100644 index 92d2dfcf8b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/projector.cpp +++ /dev/null @@ -1,236 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/projector.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 6 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * ProjectorClass::ProjectorClass -- Constructor * - * ProjectorClass::~ProjectorClass -- Destructor * - * ProjectorClass::Set_Transform -- Set the transform for the projector * - * ProjectorClass::Get_Transform -- Returns the current transform * - * ProjectorClass::Set_Perspective_Projection -- Set up a perspective projection * - * ProjectorClass::Set_Ortho_Projection -- Set up an orthographic projection * - * ProjectorClass::Compute_Texture_Coordinate -- computes texcoord for given world-space poi * - * ProjectorClass::Update_WS_Bounding_Volume -- Recalculate the world-space bounding box * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "projector.h" -#include "refcount.h" -#include "matrixmapper.h" - - -/*********************************************************************************************** - * ProjectorClass::ProjectorClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -ProjectorClass::ProjectorClass(void) : - Transform(1), - Projection(1), - LocalBoundingVolume(Vector3(0,0,0),Vector3(1,1,1)), - WorldBoundingVolume(Vector3(0,0,0),Vector3(1,1,1),Matrix3x3(1)) -{ - Mapper=NEW_REF(MatrixMapperClass,(0)); -} - - -/*********************************************************************************************** - * ProjectorClass::~ProjectorClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -ProjectorClass::~ProjectorClass(void) -{ - REF_PTR_RELEASE(Mapper); -} - -/*********************************************************************************************** - * ProjectorClass::Set_Transform -- Set the transform for the projector * - * * - * Projectors can be positioned in world space just like cameras! Just point the -Z axis * - * at the target. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - * 1/27/00 gth : Created. * - *=============================================================================================*/ -void ProjectorClass::Set_Transform(const Matrix3D & tm) -{ - Transform = tm; - Update_WS_Bounding_Volume(); -} - - -/*********************************************************************************************** - * ProjectorClass::Get_Transform -- Returns the current transform * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -const Matrix3D & ProjectorClass::Get_Transform(void) const -{ - return Transform; -} - - -/*********************************************************************************************** - * ProjectorClass::Set_Perspective_Projection -- Set up a perspective projection * - * * - * INPUT: * - * hfov - radians, horizontal field of view of the projection * - * vfov - radians, vertical field of view of the projection * - * znear - distance to near clipping plane * - * zfar - distance to far clipping plane * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Remember that znear and zfar are *distances*. They are positive numbers as in the OpenGL * - * convention even though the coordinates will be negative. * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void ProjectorClass::Set_Perspective_Projection(float hfov,float vfov,float znear,float zfar) -{ - Mapper->Set_Type(MatrixMapperClass::PERSPECTIVE_PROJECTION); - Projection.Init_Perspective(hfov,vfov,0.1f,zfar); // don't use znear for the projection matrix - - float tan_hfov2 = tan(hfov) * 0.5f; - float tan_vfov2 = tan(vfov) * 0.5f; - - LocalBoundingVolume.Center.Set(0.0f,0.0f,-(zfar+znear)*0.5f); // note, zcenter is negative - LocalBoundingVolume.Extent.X = zfar * tan_hfov2; - LocalBoundingVolume.Extent.Y = zfar * tan_vfov2; - LocalBoundingVolume.Extent.Z = (zfar-znear)*0.5f; - - Update_WS_Bounding_Volume(); -} - - -/*********************************************************************************************** - * ProjectorClass::Set_Ortho_Projection -- Set up an orthographic projection * - * * - * INPUT: * - * xmin - "left" x coordinate in texture (camera) space * - * xmax - "right" x coordinate * - * ymin - "bottom" y coordinate * - * ymax - "top" y coordinate * - * znear - distance to near clipping plane * - * zfar - distance to far clipping plane * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Remember that znear and zfar are *distances*. They are positive numbers as in the OpenGL * - * convention even though the coordinates will be negative. * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void ProjectorClass::Set_Ortho_Projection(float xmin,float xmax,float ymin,float ymax,float znear,float zfar) -{ - Mapper->Set_Type(MatrixMapperClass::ORTHO_PROJECTION); - Projection.Init_Ortho(xmin,xmax,ymin,ymax,0.1f,zfar); // don't use znear for the projection matrix - - LocalBoundingVolume.Center.Set((xmax+xmin)*0.5f, (ymax+ymin)*0.5f, -(zfar+znear)*0.5f); - LocalBoundingVolume.Extent.Set((xmax-xmin)*0.5f, (ymax-ymin)*0.5f, (zfar-znear)*0.5f); - - Update_WS_Bounding_Volume(); -} - - -/*********************************************************************************************** - * ProjectorClass::Compute_Texture_Coordinate -- computes texcoord for given world-space point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/27/00 gth : Created. * - *=============================================================================================*/ -void ProjectorClass::Compute_Texture_Coordinate(const Vector3 & point,Vector3 * set_stq) -{ - Mapper->Compute_Texture_Coordinate(point,set_stq); -} - - -/*********************************************************************************************** - * ProjectorClass::Update_WS_Bounding_Volume -- Recalculate the world-space bounding box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/11/00 gth : Created. * - *=============================================================================================*/ -void ProjectorClass::Update_WS_Bounding_Volume(void) -{ - /* - ** Recompute our world-space bounding volume - */ - OBBoxClass localbox(LocalBoundingVolume.Center,LocalBoundingVolume.Extent,Matrix3x3(1)); - OBBoxClass::Transform(Transform,localbox,&WorldBoundingVolume); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/projector.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/projector.h deleted file mode 100644 index 6d58c06ae4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/projector.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/projector.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 2 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef PROJECTOR_H -#define PROJECTOR_H - -#include "always.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "aabox.h" -#include "obbox.h" - - -class MatrixMapperClass; - - -/** -** ProjectorClass -** This is a class which encapsulates the data needed to describe a projection. It isn't -** really useful by itself but it is a common base class between TexProjectClass and DecalGeneratorClass. -*/ -class ProjectorClass -{ -public: - - ProjectorClass(void); - virtual ~ProjectorClass(void); - - virtual void Set_Transform(const Matrix3D & tm); - virtual const Matrix3D & Get_Transform(void) const; - - virtual void Set_Perspective_Projection(float hfov,float vfov,float znear,float zfar); - virtual void Set_Ortho_Projection(float xmin,float xmax,float ymin,float ymax,float znear,float zfar); - - const OBBoxClass & Get_Bounding_Volume(void) const { return WorldBoundingVolume; } - void Compute_Texture_Coordinate(const Vector3 & point,Vector3 * set_stq); - - MatrixMapperClass* Peek_Mapper() const { return Mapper; } - -protected: - - virtual void Update_WS_Bounding_Volume(void); - - Matrix3D Transform; - Matrix4x4 Projection; - - AABoxClass LocalBoundingVolume; - OBBoxClass WorldBoundingVolume; - - MatrixMapperClass * Mapper; -}; - - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/proto.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/proto.cpp deleted file mode 100644 index 12a543c52d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/proto.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/proto.cpp $* - * * - * Org Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 3:51p $* - * * - * $Revision:: 2 $* - * * - * 06/26/02 KM Integrating shader system - *---------------------------------------------------------------------------------------------* - * Functions: * - * MeshLoaderClass::Load -- reads in a mesh and creates a prototype for it * - * HModelLoaderClass::Load -- reads in an hmodel definition and creates a prototype for it * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "proto.h" -#include "mesh.h" -#include "hmdldef.H" -#include "hlod.h" -#include "w3derr.h" - -/* -** Global instances of the default loaders for the asset manager to install -*/ -MeshLoaderClass _MeshLoader; -HModelLoaderClass _HModelLoader; - - -/* -** Prototype Classes -** These prototypes are the "built-in" ones for the W3D library. -*/ -PrimitivePrototypeClass::PrimitivePrototypeClass(RenderObjClass * proto) -{ - Proto = proto; - assert(Proto); - Proto->Add_Ref(); -} -PrimitivePrototypeClass::~PrimitivePrototypeClass(void) -{ - if (Proto) { - Proto->Release_Ref(); - } -} - -const char * PrimitivePrototypeClass::Get_Name(void) const -{ - return Proto->Get_Name(); -} - -int PrimitivePrototypeClass::Get_Class_ID(void) const -{ - return Proto->Class_ID(); -} - -RenderObjClass * PrimitivePrototypeClass::Create(void) -{ - return (RenderObjClass *)( SET_REF_OWNER( Proto->Clone() ) ); -} - - -class HModelPrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(HModelPrototypeClass) -public: - HModelPrototypeClass(HModelDefClass * def) { HModelDef = def; assert(HModelDef); } - - virtual const char * Get_Name(void) const { return HModelDef->Get_Name(); } - virtual int Get_Class_ID(void) const { return RenderObjClass::CLASSID_HLOD; } - virtual RenderObjClass * Create(void) { return NEW_REF( HLodClass, (*HModelDef) ); } - virtual void DeleteSelf() { delete this; } - - HModelDefClass * HModelDef; - -protected: - virtual ~HModelPrototypeClass(void) { if (HModelDef) delete HModelDef; } - -}; - - -/*********************************************************************************************** - * MeshLoaderClass::Load -- reads in a mesh and creates a prototype for it * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/28/98 GTH : Created. * - *=============================================================================================*/ -PrototypeClass * MeshLoaderClass::Load_W3D(ChunkLoadClass & cload) -{ - MeshClass * mesh = NEW_REF( MeshClass, () ); - - if (mesh == NULL) { - return NULL; - } - - if (mesh->Load_W3D(cload) != WW3D_ERROR_OK) { - - // if the load failed, delete the mesh - assert(mesh->Num_Refs() == 1); - mesh->Release_Ref(); - return NULL; - - } else { - - // create the prototype and add it to the lists - PrimitivePrototypeClass * newproto = W3DNEW PrimitivePrototypeClass(mesh); - mesh->Release_Ref(); - return newproto; - - } -} - - -/*********************************************************************************************** - * HModelLoaderClass::Load -- reads in an hmodel and creates a prototype for it * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/28/98 GTH : Created. * - *=============================================================================================*/ -PrototypeClass * HModelLoaderClass::Load_W3D(ChunkLoadClass & cload) -{ - HModelDefClass * hdef = W3DNEW HModelDefClass; - - if (hdef == NULL) { - return NULL; - } - - if (hdef->Load_W3D(cload) != HModelDefClass::OK) { - - // load failed, delete the model and return an error - delete hdef; - return NULL; - - } else { - - // ok, accept this model! - HModelPrototypeClass * hproto = W3DNEW HModelPrototypeClass(hdef); - return hproto; - - } -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/proto.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/proto.h deleted file mode 100644 index dadeb29123..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/proto.h +++ /dev/null @@ -1,183 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/proto.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef PROTO_H -#define PROTO_H - -#include "always.h" -#include -#include "w3d_file.h" - -class RenderObjClass; -class ChunkLoadClass; - -/* -** W3D Prototype system -** -** Prototypes are basically abstract factories for render objects. -** Prototype Loaders are abstract factories for prototypes. -** Here is an example of the sequence of events that happen when -** a mesh is loaded into the asset manager and then used by the -** user: -** -** - At initialization time, a mesh prototype loader is installed automatically -** - User asks the asset manager to load "mesh.w3d" -** - asset manager encounters a W3D_CHUNK_MESH -** - asset manager looks through its loaders to find one that claims to handle this chunk -** - the meshloader object is found and its Load method called -** - the meshloader creates a mesh prototype object which the asset manager adds to its list -** - User asks for the render object named "Mesh" -** - asset manager searches through its prototypes to find the one named "Mesh" -** - the mesh prototype object is found and the asset manager calls its "Create" method -** - the mesh prototype creates a mesh (clones the one it contains) which is returned to the user. -*/ - -/* -** PrototypeClass -** This class is a generic interface to a render object prototype. -** The asset manager will store a these and use them whenever the -** user wants to create an instance of a named render object. -** Some simple render objects will be created through cloning. In -** that case, their associated prototype simply stores an object and -** clones it whenever the Create method is called. More complex -** composite render objects will be created from a "blueprint" object. -** Basically this class simply associates a name with a render object -** creation function. -*/ -class PrototypeClass -{ - -public: - - PrototypeClass(void) : NextHash(NULL) {} - - virtual const char * Get_Name(void) const = 0; - virtual int Get_Class_ID(void) const = 0; - virtual RenderObjClass * Create(void) = 0; - virtual void DeleteSelf() = 0; - - inline void friend_setNextHash(PrototypeClass* n) { NextHash = n; } - inline PrototypeClass* friend_getNextHash() { return NextHash; } - -protected: - virtual ~PrototypeClass(void) {}; - -private: - PrototypeClass * NextHash; - - // Not Implemented - PrototypeClass(const PrototypeClass & that); - PrototypeClass & operator = (const PrototypeClass & that); -}; - -class PrimitivePrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(PrimitivePrototypeClass) -public: - PrimitivePrototypeClass(RenderObjClass * proto); - - virtual const char * Get_Name(void) const; - virtual int Get_Class_ID(void) const; - virtual RenderObjClass * Create(void); - virtual void DeleteSelf() { delete this; } - - RenderObjClass * Proto; - -protected: - virtual ~PrimitivePrototypeClass(void); -}; - -/* -** PrototypeLoaderClass -** This is the interface for an object which recognizes a certain -** chunk type in a W3D file and can load it and create a PrototypeClass -** for it. -*/ -class PrototypeLoaderClass -{ - -public: - - PrototypeLoaderClass(void) {} - ~PrototypeLoaderClass(void) {} - - virtual int Chunk_Type(void) = 0; - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload) = 0; - -private: - - // Not Implemented: - PrototypeLoaderClass(const PrototypeLoaderClass & that); - PrototypeLoaderClass & operator = (const PrototypeLoaderClass & that); - -}; - - -/* -** Default Prototype Loaders for Meshes and HModels -*/ -class MeshLoaderClass : public PrototypeLoaderClass -{ -public: - - virtual int Chunk_Type(void) { return W3D_CHUNK_MESH; } - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload); -}; - -class HModelLoaderClass : public PrototypeLoaderClass -{ -public: - - virtual int Chunk_Type(void) { return W3D_CHUNK_HMODEL; } - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload); -}; - - -/* -** Instances of the default loaders which the asset manager can -** automatically install at creation time -*/ -extern MeshLoaderClass _MeshLoader; -extern HModelLoaderClass _HModelLoader; - - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/proxy.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/proxy.h deleted file mode 100644 index 90b3953e2d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/proxy.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/proxy.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __PROXY_H -#define __PROXY_H - -#include "wwstring.h" -#include "matrix3d.h" - - -////////////////////////////////////////////////////////////////////////////////// -// -// ProxyClass -// -////////////////////////////////////////////////////////////////////////////////// -class ProxyClass -{ -public: - - /////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////// - ProxyClass (void) { } - ProxyClass (const char *name, const Matrix3D &tm) : - Name (name), - Transform (tm) { } - - /////////////////////////////////////////////////////////// - // Public operators - /////////////////////////////////////////////////////////// - bool operator== (const ProxyClass &src); - bool operator!= (const ProxyClass &src); - - /////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////// - - // - // Accessors - // - const char * Get_Name (void) const { return Name; } - void Set_Name (const char *name) { Name = name; } - - const Matrix3D & Get_Transform (void) const { return Transform; } - void Set_Transform (const Matrix3D &tm) { Transform = tm; } - -private: - - /////////////////////////////////////////////////////////// - // Private member data - /////////////////////////////////////////////////////////// - StringClass Name; - Matrix3D Transform; -}; - - -/////////////////////////////////////////////////////////// -// operator== -/////////////////////////////////////////////////////////// -inline bool -ProxyClass::operator== (const ProxyClass &src) -{ - return ((Name == src.Name) && (Transform == src.Transform)); -} - - -/////////////////////////////////////////////////////////// -// operator!= -/////////////////////////////////////////////////////////// -inline bool -ProxyClass::operator!= (const ProxyClass &src) -{ - return ((Name != src.Name) || (Transform != src.Transform)); -} - - -#endif //__PROXY_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/rddesc.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/rddesc.h deleted file mode 100644 index 502684e2c2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/rddesc.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/rddesc.h $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 12/04/01 5:20p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef RDDESC_H -#define RDDESC_H - -#include "Vector.H" -#include "wwstring.h" -#include -#include - -class ResolutionDescClass -{ -public: - ResolutionDescClass(void) : Width(0), Height(0), BitDepth(0) { } - ResolutionDescClass(int w,int h,int bits) : Width(w), Height(h), BitDepth(bits) { } - bool operator == (const ResolutionDescClass & src) { return ((Width==src.Width) && (Height==src.Height) && (BitDepth==src.BitDepth)); } - bool operator != (const ResolutionDescClass & src) { return ((Width!=src.Width) || (Height!=src.Height) || (BitDepth!=src.BitDepth)); } - - int Width; - int Height; - int BitDepth; - int RefreshRate; -}; - - -class RenderDeviceDescClass -{ - -public: - - RenderDeviceDescClass(void) : DeviceName(NULL), DeviceVendor(NULL), DevicePlatform(NULL), - DriverName(NULL), DriverVendor(NULL), DriverVersion(NULL), - HardwareName(NULL), HardwareVendor(NULL), HardwareChipset(NULL) - { - } - - ~RenderDeviceDescClass(void) - { - } - - RenderDeviceDescClass & operator = (const RenderDeviceDescClass & src) - { - set_device_name(src.Get_Device_Name()); - set_device_vendor(src.Get_Device_Vendor()); - set_device_platform(src.Get_Device_Platform()); - set_driver_name(src.Get_Driver_Name()); - set_driver_vendor(src.Get_Driver_Vendor()); - set_driver_version(src.Get_Driver_Version()); - set_hardware_name(src.Get_Hardware_Name()); - set_hardware_vendor(src.Get_Hardware_Vendor()); - set_hardware_chipset(src.Get_Hardware_Chipset()); - Caps=src.Caps; - AdapterIdentifier=src.AdapterIdentifier; - ResArray = src.ResArray; - return *this; - } - - bool operator == (const RenderDeviceDescClass & /*src*/) { return false; } - bool operator != (const RenderDeviceDescClass & /*src*/) { return true; } - - const char * Get_Device_Name() const { return DeviceName; } - const char * Get_Device_Vendor() const { return DeviceVendor; } - const char * Get_Device_Platform() const { return DevicePlatform; } - - const char * Get_Driver_Name() const { return DriverName; } - const char * Get_Driver_Vendor() const { return DriverVendor; } - const char * Get_Driver_Version() const { return DriverVersion; } - - const char * Get_Hardware_Name() const { return HardwareName; } - const char * Get_Hardware_Vendor() const { return HardwareVendor; } - const char * Get_Hardware_Chipset() const { return HardwareChipset; } - - const DynamicVectorClass & Enumerate_Resolutions(void) const { return ResArray; } - const D3DCAPS8& Get_Caps() const { return Caps; } - const D3DADAPTER_IDENTIFIER8& Get_Adapter_Identifier() const { return AdapterIdentifier; } - -private: - - void set_device_name(const char * name) { DeviceName=name; } - void set_device_vendor(const char * name) { DeviceVendor=name; } - void set_device_platform(const char * name) { DevicePlatform=name; } - void set_driver_name(const char * name) { DriverName=name; } - void set_driver_vendor(const char * name) { DriverVendor=name; } - void set_driver_version(const char * name) { DriverVersion=name; } - void set_hardware_name(const char * name) { HardwareName=name; } - void set_hardware_vendor(const char * name) { HardwareVendor=name; } - void set_hardware_chipset(const char * name) { HardwareChipset=name; } - - void reset_resolution_list(void) { ResArray.Delete_All(); } - void add_resolution(int w,int h,int bits); - - StringClass DeviceName; - StringClass DeviceVendor; - StringClass DevicePlatform; - - StringClass DriverName; - StringClass DriverVendor; - StringClass DriverVersion; - - StringClass HardwareName; - StringClass HardwareVendor; - StringClass HardwareChipset; - - D3DCAPS8 Caps; - D3DADAPTER_IDENTIFIER8 AdapterIdentifier; - - DynamicVectorClass ResArray; - - friend class WW3D; - friend class DX8Wrapper; -}; - - -inline void RenderDeviceDescClass::add_resolution(int w,int h,int bits) -{ - bool found = false; - for (int i=0; i. -*/ - - /*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/render2dsentence.cpp $* - * * - * $Author:: Patrick $* - * * - * $Modtime:: 8/29/01 11:16a $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "render2dsentence.h" -#include "surfaceclass.h" -#include "texture.h" -#include "wwprofile.h" -#include "wwmemlog.h" -#include "dx8wrapper.h" - -#ifdef _INTERNAL -// for occasional debugging... -//#pragma optimize("", off) -//#pragma message("************************************** WARNING, optimization disabled for debugging purposes") -#endif - -//////////////////////////////////////////////////////////////////////////////////// -// Local constants -//////////////////////////////////////////////////////////////////////////////////// -#define no_TEST_PLACEMENT 1 // Shows alignment markers for text. - -#define TEXTURE_OFFSET 2 -//////////////////////////////////////////////////////////////////////////////////// -// -// Render2DSentenceClass -// -//////////////////////////////////////////////////////////////////////////////////// -Render2DSentenceClass::Render2DSentenceClass (void) : - Font (NULL), - Location (0.0F,0.0F), - Cursor (0.0F,0.0F), - TextureOffset (0, 0), - TextureStartX (0), - CurSurface (NULL), - CurrTextureSize (0), - MonoSpaced (false), - IsClippedEnabled (false), - ClipRect (0, 0, 0, 0), - BaseLocation (0, 0), - LockedPtr (NULL), - LockedStride (0), - TextureSizeHint (0), - WrapWidth (0), - Centered (false), - DrawExtents (0, 0, 0, 0), - ParseHotKey( false ), - useHardWordWrap( false) -{ - Shader = Render2DClass::Get_Default_Shader (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// ~Render2DSentenceClass -// -//////////////////////////////////////////////////////////////////////////////////// -Render2DSentenceClass::~Render2DSentenceClass (void) -{ - REF_PTR_RELEASE (Font); - Reset (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Set_Font -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Set_Font (FontCharsClass *font) -{ - Reset (); - REF_PTR_SET (Font, font); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Reset_Polys -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Reset_Polys (void) -{ - for (int index = 0; index < Renderers.Count (); index ++) { - Renderers[index].Renderer->Reset (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Reset -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Reset (void) -{ - // - // Make sure we unlock the current surface (if necessary) - // - if (LockedPtr != NULL) { - CurSurface->Unlock (); - LockedPtr = NULL; - } - - // - // Release our hold on the current surface - // - REF_PTR_RELEASE (CurSurface); - - // - // Free each renderer - // - while (Renderers.Count () > 0) { - delete Renderers[0].Renderer; - Renderers.Delete(0); - } - - Cursor.Set (0, 0); - MonoSpaced = false; - ParseHotKey = false; - - Release_Pending_Surfaces (); - Reset_Sentence_Data (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Make_Additive -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Make_Additive (void) -{ - Shader.Set_Dst_Blend_Func (ShaderClass::DSTBLEND_ONE); - Shader.Set_Src_Blend_Func (ShaderClass::SRCBLEND_ONE); - Shader.Set_Primary_Gradient (ShaderClass::GRADIENT_MODULATE); - Shader.Set_Secondary_Gradient (ShaderClass::SECONDARY_GRADIENT_DISABLE); - - Set_Shader (Shader); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Make_Additive -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Set_Shader (ShaderClass shader) -{ - Shader = shader; - - // - // Change each renderer's shader - // - for (int i = 0; i < Renderers.Count (); i ++) { - ShaderClass *curr_shader = Renderers[i].Renderer->Get_Shader (); - (*curr_shader) = Shader; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Render -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Render (void) -{ - // - // Build any textures that are pending - // - Build_Textures (); - - // - // Ask each renderer to draw its contents - // - for (int i = 0; i < Renderers.Count (); i ++) { - Renderers[i].Renderer->Render (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Set_Base_Location -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Set_Base_Location (const Vector2 &loc) -{ - Vector2 dif = loc - BaseLocation; - BaseLocation = loc; - for (int i = 0; i < Renderers.Count (); i ++) { - Renderers[i].Renderer->Move (dif); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Set_Location -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Set_Location (const Vector2 &loc) -{ - Location = loc; - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Get_Text_Extents -// -//////////////////////////////////////////////////////////////////////////////////// -Vector2 -Render2DSentenceClass::Get_Text_Extents (const WCHAR *text) -{ - Vector2 extent (0, Font->Get_Char_Height()); - - while (*text) { - WCHAR ch = *text++; - - if ( ch != (WCHAR)'\n' ) { - extent.X += Font->Get_Char_Spacing( ch ); - } - } - - return extent; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Get_Formatted_Text_Extents -// -//////////////////////////////////////////////////////////////////////////////////// -Vector2 -Render2DSentenceClass::Get_Formatted_Text_Extents (const WCHAR *text) -{ - return Build_Sentence_Not_Centered(text, NULL, NULL, true); -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Reset_Sentence_Data -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Reset_Sentence_Data (void) -{ - // - // Release our hold on each texture used in the sentence - // - for (int index = 0; index < SentenceData.Count (); index ++) { - REF_PTR_RELEASE (SentenceData[index].Surface); - } - - if (SentenceData.Count()>0) { - SentenceData.Delete_All (); - } - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Release_Pending_Surfaces -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Release_Pending_Surfaces (void) -{ - // - // Release our hold on each pending surface - // - for (int index = 0; index < PendingSurfaces.Count (); index ++) { - SurfaceClass *curr_surface = PendingSurfaces[index].Surface; - REF_PTR_RELEASE (curr_surface); - } - - if (PendingSurfaces.Count()>0) PendingSurfaces.Delete_All (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Build_Textures -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Build_Textures (void) -{ - WWMEMLOG(MEM_TEXTURE); - - // - // Make sure we unlock the current surface - // - if (LockedPtr != NULL) { - CurSurface->Unlock (); - LockedPtr = NULL; - } - - // - // Release our hold on the current surface - // - REF_PTR_RELEASE (CurSurface); - TextureOffset.Set (0, 0); - TextureStartX = 0; - - // - // Convert all pending surfaces to textures - // - for (int index = 0; index < PendingSurfaces.Count (); index ++) { - PendingSurfaceStruct &surface_info = PendingSurfaces[index]; - SurfaceClass *curr_surface = surface_info.Surface; - - // - // Get the dimensions of the surface - // - SurfaceClass::SurfaceDescription desc; - curr_surface->Get_Description (desc); - - // - // Create the new texture - // - TextureClass *new_texture = W3DNEW TextureClass (desc.Width, desc.Width, WW3D_FORMAT_A4R4G4B4, MIP_LEVELS_1); - SurfaceClass *texture_surface = new_texture->Get_Surface_Level (); - - new_texture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - new_texture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); - new_texture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_NONE); - new_texture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_NONE); - new_texture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE); - - // - // Copy the contents of the texture from the surface - // - DX8Wrapper::_Copy_DX8_Rects (curr_surface->Peek_D3D_Surface (), NULL, 0, texture_surface->Peek_D3D_Surface (), NULL); - REF_PTR_RELEASE (texture_surface); - - // - // Assign this texture to any renderers that need it - // - for (int renderer_index = 0; renderer_index < surface_info.Renderers.Count (); renderer_index ++) { - Render2DClass *renderer = surface_info.Renderers[renderer_index]; - renderer->Set_Texture (new_texture); - } - - // - // Release our hold on the objects - // - REF_PTR_RELEASE (new_texture); - REF_PTR_RELEASE (curr_surface); - } - - // - // Reset the list - // - if (PendingSurfaces.Count()>0) { - PendingSurfaces.Delete_All (); - } - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Draw_Sentence -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Draw_Sentence (uint32 color) -{ - Render2DClass *curr_renderer = NULL; - SurfaceClass *curr_surface = NULL; - - DrawExtents.Set (0, 0, 0, 0); - - int offset = 0; - // - // Loop over all the parts of the sentence - // - for (int index = 0; index < SentenceData.Count (); index ++) { - SentenceDataStruct &data = SentenceData[index]; - - // - // Has the surface changed? - // - if (data.Surface != curr_surface) { - curr_surface = data.Surface; - - // - // Try to find a renderer that uses the same "texture" - // - bool found = false; - for (int renderer_index = 0; renderer_index < Renderers.Count (); renderer_index ++) { - if (Renderers[renderer_index].Surface == curr_surface) { - found = true; - curr_renderer = Renderers[renderer_index].Renderer; - break; - } - } - - // - // Create a new renderer if we couldn't find an appropriate one - // - if (found == false) { - - // - // Allocate a new renderer - // - curr_renderer = W3DNEW Render2DClass; - curr_renderer->Set_Coordinate_Range (Render2DClass::Get_Screen_Resolution ()); - ShaderClass *curr_shader = curr_renderer->Get_Shader (); - (*curr_shader) = Shader; - - // - // Add it to our list - // - RendererDataStruct render_info; - render_info.Renderer = curr_renderer; - render_info.Surface = curr_surface; - Renderers.Add (render_info); - - // - // Now, add this renderer to the surface pending list - // - for (int surface_index = 0; surface_index < PendingSurfaces.Count (); surface_index ++) { - PendingSurfaceStruct &surface_info = PendingSurfaces[surface_index]; - if (surface_info.Surface == curr_surface) { - surface_info.Renderers.Add (curr_renderer); - } - } - } - } - - // - // Get the dimensions of the surface - // - SurfaceClass::SurfaceDescription desc; - curr_surface->Get_Description (desc); - - // - // Add a quad that contains this sentence chunk - // - RectClass screen_rect = data.ScreenRect; - screen_rect += Location; - RectClass uv_rect = data.UVRect; - - // - // Clip the quad (as necessary) - // - bool add_quad = true; - if (IsClippedEnabled) { - - // - // Check for completely clipped - // - if ( screen_rect.Right <= ClipRect.Left || - screen_rect.Bottom <= ClipRect.Top) - { - add_quad = false; - } else { - - // - // Clip the polygons to the specified area - // - RectClass clipped_rect; - clipped_rect.Left = max (screen_rect.Left, ClipRect.Left); - clipped_rect.Right = min (screen_rect.Right, ClipRect.Right); - clipped_rect.Top = max (screen_rect.Top, ClipRect.Top); - clipped_rect.Bottom = min (screen_rect.Bottom, ClipRect.Bottom); - - // - // Clip the texture to the specified area - // - RectClass clipped_uv_rect; - float percent = ((clipped_rect.Left - screen_rect.Left) / screen_rect.Width ()); - clipped_uv_rect.Left = uv_rect.Left + (uv_rect.Width () * percent); - - percent = ((clipped_rect.Right - screen_rect.Left) / screen_rect.Width ()); - clipped_uv_rect.Right = uv_rect.Left + (uv_rect.Width () * percent); - - percent = ((clipped_rect.Top - screen_rect.Top) / screen_rect.Height ()); - clipped_uv_rect.Top = uv_rect.Top + (uv_rect.Height () * percent); - - percent = ((clipped_rect.Bottom - screen_rect.Top) / screen_rect.Height ()); - clipped_uv_rect.Bottom = uv_rect.Top + (uv_rect.Height () * percent); - - // - // Use the clipped rectangles to render - // - screen_rect = clipped_rect; - uv_rect = clipped_uv_rect; - - if (screen_rect.Right <= screen_rect.Left || - screen_rect.Bottom <= screen_rect.Top) - { - add_quad = false; - } - } - } - - if (add_quad) { - //uv_rect.Bottom += 0.5f; - uv_rect *= 1.0F / ((float)desc.Width); -#ifdef TEST_PLACEMENT - screen_rect.Left += offset*3; - screen_rect.Right += offset*3; -#endif - offset++; - curr_renderer->Add_Quad (screen_rect, uv_rect, color); - - // - // Add this rectangle to the total draw extents - // - if (DrawExtents.Width () == 0) { - DrawExtents = screen_rect; - } else { - DrawExtents += screen_rect; - } - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Record_Sentence_Chunk -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Record_Sentence_Chunk (void) -{ - // - // Do we have anything to store? - // - int width = TextureOffset.I - TextureStartX; - if (width > 0) { - float char_height = Font->Get_Char_Height (); - - // - // Build a structure that contains enough information - // to hold this portion of the sentence - // - SentenceDataStruct sentence_data; - sentence_data.Surface = CurSurface; - sentence_data.Surface->Add_Ref (); - sentence_data.ScreenRect.Left = Cursor.X; - sentence_data.ScreenRect.Right = Cursor.X + width; - sentence_data.ScreenRect.Top = Cursor.Y; - sentence_data.ScreenRect.Bottom = Cursor.Y + char_height; - sentence_data.UVRect.Left = TextureStartX; - sentence_data.UVRect.Top = TextureOffset.J; - sentence_data.UVRect.Right = TextureOffset.I; - sentence_data.UVRect.Bottom = TextureOffset.J + char_height; - - // - // Add this information to our list - // - SentenceData.Add (sentence_data); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_New_Surface -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Allocate_New_Surface (const WCHAR *text, bool justCalcExtents) -{ - if (!justCalcExtents) - { - // - // Unlock the last surface (if necessary) - // - if (LockedPtr != NULL) { - CurSurface->Unlock (); - LockedPtr = NULL; - } - } - - // - // Calculate the width of the text - // - int text_width = 0; - for (int index = 0; text[index] != 0; index ++) { - text_width += Font->Get_Char_Spacing (text[index]); - } - - int char_height = Font->Get_Char_Height (); - - // - // Find the best texture size for the remaining text - // - CurrTextureSize = 256; - int best_tex_mem_usage = 999999999; - for (int pow2 = 6; pow2 <= 8; pow2 ++) { - - int size = 1 << pow2; - int row_count = (text_width / size) + 1; - int rows_per_texture = size / (char_height + 1); - - // - // Can we even fit one character on this texture? - // - if (rows_per_texture > 0) { - - // - // How many textures (at this size) would it take to render - // the remaining text? - // - int texture_count = row_count / rows_per_texture; - texture_count = max (texture_count, 1); - - // - // Is this the best usage of texture memory we've found yet? - // - int texture_mem_usage = (texture_count * size * size); - if (texture_mem_usage < best_tex_mem_usage) { - CurrTextureSize = size; - best_tex_mem_usage = texture_mem_usage; - } - } - } - - // - // Use whichever is larger, the hint or the calculated size - // - CurrTextureSize = max (TextureSizeHint, CurrTextureSize); - - if (!justCalcExtents) - { - // - // Release our extra hold on the old surface - // - REF_PTR_RELEASE (CurSurface); - - // - // Create the new surface - // - CurSurface = NEW_REF (SurfaceClass, (CurrTextureSize, CurrTextureSize, WW3D_FORMAT_A4R4G4B4)); - WWASSERT (CurSurface != NULL); - CurSurface->Add_Ref (); - - // - // Add this surface to our list - // - PendingSurfaceStruct surface_info; - surface_info.Surface = CurSurface; - PendingSurfaces.Add (surface_info); - } - - // - // Reset to the upper left corner - // - TextureOffset.Set (0, 0); - TextureStartX = 0; - return ; -} - -float FindStartingXPos( const WCHAR *text ) -{ - - return 1; -} -//////////////////////////////////////////////////////////////////////////////////// -// -// Build_Sentence_Centered -// -//////////////////////////////////////////////////////////////////////////////////// -void Render2DSentenceClass::Build_Sentence_Centered (const WCHAR *text, int *hkX, int *hkY) -{ - float char_height = Font->Get_Char_Height (); - int wordWidth = 0; - int notCenteredHotkeyX = 0; - int notCenteredHotkeyY = 0; - Vector2 extent = Build_Sentence_Not_Centered(text,¬CenteredHotkeyX, ¬CenteredHotkeyY, TRUE); //Get_Formatted_Text_Extents(text); - - // - // Start fresh - // - Reset_Sentence_Data (); - Cursor.Set (0, 0); - - // - // Ensure we have a surface to start with - // - if (CurSurface == NULL) { - Allocate_New_Surface (text); - } - - - - // - // Loop over all the characters in the string - // - bool end = false; - const WCHAR *word; - int word_width = 0; - int line_width = 0; - int charCount = 0; - int wordCount = 0; - int hotKeyPosX = 0; - int hotKeyPosY = 0; - bool calcHotKeyX = false; - bool dontBlit = false; - while (!end) - { - // - // Re-init everything for the next line - // - word = text; - word_width = 0; - line_width = 0; - charCount = 0; - wordCount = 0; - // - //first find the length of the line till we wrap - // - while ( 1 ) - { - // - // read a word - // - int charWidth = 0; - while ((*word != 0) && (*word > L' ') && (*word != L'\n')) { - if( ParseHotKey && (*word == L'&') && (*word+1 != 0) && (*word+1 > L' ') && (*word+1 != L'\n')) - { - int offset = 0; - //Added By Saad - if (word_width != 0 ) - { - const WCHAR *word_back = word; - *word_back--; - if (*word_back == L' ') - { - line_width -= word_width; - offset =-1; - } - } - // - *word++; - calcHotKeyX = true; - } - - charWidth = Font->Get_Char_Spacing (*word++); - word_width += charWidth; - wordCount++; - - if (WrapWidth > 0 && word_width >= WrapWidth && useHardWordWrap) - break; - } - // - // If this word is unworthy to be on the current line, decrement the space and break - // - if(WrapWidth > 0 && (line_width + word_width >= WrapWidth)) - { - // - //Take care of the case that the word is too big for the allocated space... - //If that's the case, drop out and process the word anyway - // - if(charCount == 0) - { - charCount +=wordCount - 1; - line_width += word_width - charWidth; - if(*word == 0) - end = true; - break; - } - charCount--; - break; - } - // - // if we reached the end of the text, set the values and break, also set the end flag - // - if( *word == 0 ) - { - charCount +=wordCount; - line_width += word_width; - end = true; - break; - } - // - // otherwise, increment the counts - // - charCount +=wordCount + 1; - line_width += word_width; - // - // We were some a new line character break and process - // - if(*word != L' ') - break; - // - // add the space to our width - // - word_width = Font->Get_Char_Spacing (*word++); - wordCount = 0; - //Added By Saad - line_width += word_width; - } - // - // we now hold the length of the line and it's width lets set our cursor position to center it - // - Cursor.X = (int)((extent.X - line_width) / 2); - if(Cursor.X < 0) - Cursor.X = 0; - if(calcHotKeyX) - { - calcHotKeyX = false; - hotKeyPosX = Cursor.X + notCenteredHotkeyX; - } - - for(int i = 0; i <= charCount; i++) { - WCHAR ch = *text++; - dontBlit = false; - // - // Determine how much horizontal space this character requires - // - if(ParseHotKey && (ch == L'&') && (*text != 0) && (*text > L' ') && (*text != L'\n')) - { - ch = *text++; - dontBlit = true; - } - float char_spacing = Font->Get_Char_Spacing (ch); - - bool exceeded_texture_width = ((TextureOffset.I + char_spacing) >= CurrTextureSize); - bool encountered_break_char = (ch == L' ' || ch == L'\n' || ch == 0); - - // - // Do we need to record this portion of the sentence to its own chunk? - // - if (exceeded_texture_width || encountered_break_char) { - Record_Sentence_Chunk (); - - // - // Adjust the positions - // - Cursor.X += (TextureOffset.I - TextureStartX); - TextureStartX = TextureOffset.I; - - // - // Adjust the output coordinates - // - if (ch == L' ') { - Cursor.X += char_spacing; - } else if ((ch == 0 )|| (ch == L'\n')) { - break; - } - - // - // Did the text extend past the edge of the texture? - // - if (exceeded_texture_width) { - TextureStartX = 0; - TextureOffset.I = TextureStartX; - TextureOffset.J += char_height; - - // - // Did the text extent completely off the texture? - // - if ((TextureOffset.J + char_height) >= CurrTextureSize) { - Allocate_New_Surface (text); - } - } - } - // - // Adjust the output coordinates - // - if (ch != L'\n' && ch != L' ') { - - // - // Ensure the surface is locked - // - if (LockedPtr == NULL) { - LockedPtr = (uint16 *)CurSurface->Lock (&LockedStride); - WWASSERT (LockedPtr != NULL); - } - - // - // Check to ensure the text will fit on this texture - // - WWASSERT (((TextureOffset.I + char_spacing) < CurrTextureSize) && ((TextureOffset.J + char_height) < CurrTextureSize)); - - // - // Blit the character to the surface - // - if(!dontBlit) - Font->Blit_Char (ch, LockedPtr, LockedStride, TextureOffset.I, TextureOffset.J); - - if (dontBlit) { - // we don't blit for a hot key character. So add extra spacing. - char_spacing += Font->Get_Extra_Overlap(); - // Brutal hack #27 Gamma - Bolded M's are just a problem. jba. - if (ch=='M') { - char_spacing++; - } - } - - TextureOffset.I += char_spacing; - } - } - // - // reset our cursor and add a line of text to the cursor position - // - Cursor.X = 0; - Cursor.Y += char_height; - line_width = 0; - } - - if(hkX) - *hkX = hotKeyPosX; - if(hkX) - *hkY = hotKeyPosY; - return ; -} -//////////////////////////////////////////////////////////////////////////////////// -// -// Build_Sentence_NotCentered -// -//////////////////////////////////////////////////////////////////////////////////// -Vector2 Render2DSentenceClass::Build_Sentence_Not_Centered (const WCHAR *text, int *hkX, int *hkY, bool justCalcExtents) -{ - Vector2 cursor = Cursor; - int textureStartX = TextureStartX; - float maxX = 0; - - int hotKeyPosX = 0; - int hotKeyPosY = 0; - bool calcHotKeyX = false; - bool dontBlit = false; - Vector2i textureOffset = TextureOffset; - - - // - // Start fresh - // - if (!justCalcExtents) - { - Reset_Sentence_Data (); - } - Cursor.Set (0, 0); - - // - // Ensure we have a surface to start with - // - if (CurSurface == NULL) { - Allocate_New_Surface (text, justCalcExtents); - } - - TextureOffset.Set (TEXTURE_OFFSET, 0); - TextureStartX = TEXTURE_OFFSET; - - float char_height = Font->Get_Char_Height (); - - // - // Loop over all the characters in the string - // - while (text != NULL) { - WCHAR ch = *text++; - dontBlit = false; - // - // Determine how much horizontal space this character requires - // - if(ParseHotKey && (ch == L'&') && (*text != 0) && (*text > L' ') && (*text != L'\n')) - { - hotKeyPosY = Cursor.Y; - if (calcHotKeyX) - hotKeyPosX = 0; - else - hotKeyPosX = Cursor.X + TextureOffset.I -TextureStartX;//TextureOffset.I; - - ch = *text++; - dontBlit = true; - } - float char_spacing = Font->Get_Char_Spacing (ch); - - bool exceeded_texture_width = ((TextureOffset.I + char_spacing) >= CurrTextureSize); - bool encountered_break_char = (ch == L' ' || ch == L'\n' || ch == 0); - bool wordBiggerThenLine = ((useHardWordWrap) && ( WrapWidth != 0 ) &&((Cursor.X + TextureOffset.I -TextureStartX + char_spacing) >= WrapWidth)); - // - // Do we need to record this portion of the sentence to its own chunk? - // - if (exceeded_texture_width || encountered_break_char|| wordBiggerThenLine) { - if (!justCalcExtents) - { - Record_Sentence_Chunk (); - } - - // - // Adjust the positions - // - Cursor.X += (TextureOffset.I - TextureStartX); - maxX = max(maxX, Cursor.X); - TextureStartX = TextureOffset.I; - - // - // Adjust the output coordinates - // - if (ch == L' ') { - //Cursor.X += char_spacing; - //maxX = max(maxX, Cursor.X); - - // - // Check to see if we need to wrap on this word-break - // - if (WrapWidth > 0) { - - // - // Find the length of the next word - // - const WCHAR *word = text; - float word_width = char_spacing; - while ((*word != 0) && (*word > L' ')) { - if(ParseHotKey && (*word == L'&') && (*word+1 != 0) && (*word+1 > L' ') && (*word+1 != L'\n')) - *word++; - word_width += Font->Get_Char_Spacing (*word++); - } - - // - // Should we wrap the next word? - // - if ((Cursor.X + word_width) >= WrapWidth) { - Cursor.X = 0; - Cursor.Y += char_height; - calcHotKeyX = true; - } - } - - } else if (ch == L'\n') { - Cursor.X = 0; - Cursor.Y += char_height; - } else if (ch == 0) { - break; - } else if (wordBiggerThenLine){ // we've entered this loop because we're greater then the wordwrap so we need to force a wordwrap - Cursor.X = 0; - Cursor.Y += char_height; - } - - - // - // Did the text extend past the edge of the texture? - // - if (exceeded_texture_width) { - TextureStartX = TEXTURE_OFFSET; - TextureOffset.I = TextureStartX; - TextureOffset.J += char_height; - - // - // Did the text extent completely off the texture? - // - if ((TextureOffset.J + char_height) >= CurrTextureSize) { - Allocate_New_Surface (text, justCalcExtents); - } - } - } - - if (ch != L'\n' ) { - - // - // Ensure the surface is locked - // - if (!justCalcExtents) - { - if (LockedPtr == NULL) { - LockedPtr = (uint16 *)CurSurface->Lock (&LockedStride); - WWASSERT (LockedPtr != NULL); - } - } - - // - // Check to ensure the text will fit on this texture - // - WWASSERT (((TextureOffset.I + char_spacing) < CurrTextureSize) && ((TextureOffset.J + char_height) < CurrTextureSize)); - - // - // Blit the character to the surface - // - if (!justCalcExtents && !dontBlit ) - { - Font->Blit_Char (ch, LockedPtr, LockedStride, TextureOffset.I, TextureOffset.J); - } - TextureOffset.I += char_spacing; - } - } - - Vector2 extent; - extent.X = maxX + Font->Get_Extra_Overlap(); - extent.Y = Cursor.Y + char_height; - - Cursor = cursor; - TextureOffset = textureOffset; - TextureStartX = textureStartX; - - if(hkX) - *hkX = hotKeyPosX; - if(hkX) - *hkY = hotKeyPosY; - - return extent; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Build_Sentence -// -//////////////////////////////////////////////////////////////////////////////////// -void -Render2DSentenceClass::Build_Sentence (const WCHAR *text, int *hkX, int *hkY) -{ - if (text == NULL) { - return ; - } - - - if(Centered && (WrapWidth > 0 || wcschr(text,L'\n'))) - Build_Sentence_Centered(text, hkX, hkY); - else - Build_Sentence_Not_Centered(text, hkX, hkY); - - return; - -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// FontCharsClass -// -//////////////////////////////////////////////////////////////////////////////////// -FontCharsClass::FontCharsClass (void) : - OldGDIFont( NULL ), - OldGDIBitmap( NULL ), - GDIFont( NULL ), - GDIBitmap( NULL ), - GDIBitmapBits ( NULL ), - MemDC( NULL ), - CurrPixelOffset( 0 ), - PointSize( 0 ), - CharHeight( 0 ), - UnicodeCharArray( NULL ), - FirstUnicodeChar( 0xFFFF ), - LastUnicodeChar( 0 ), - IsBold (false) -{ - AlternateUnicodeFont = NULL; - ::memset( ASCIICharArray, 0, sizeof (ASCIICharArray) ); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// ~FontCharsClass -// -//////////////////////////////////////////////////////////////////////////////////// -FontCharsClass::~FontCharsClass (void) -{ - while ( BufferList.Count() ) { - delete BufferList[0]; - BufferList.Delete(0); - } - - Free_GDI_Font(); - Free_Character_Arrays(); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Get_Char_Data -// -//////////////////////////////////////////////////////////////////////////////////// -const FontCharsClassCharDataStruct * -FontCharsClass::Get_Char_Data (WCHAR ch) -{ - const FontCharsClassCharDataStruct *retval = NULL; - - if ( ch < 256 ) - { - retval = ASCIICharArray[ch]; - } - else if ( AlternateUnicodeFont && this != AlternateUnicodeFont ) - { - return AlternateUnicodeFont->Get_Char_Data( ch ); - } - else - { - Grow_Unicode_Array( ch ); - retval = UnicodeCharArray[ch - FirstUnicodeChar]; - } - - // - // If the character wasn't found, then add it to our list - // - if ( retval == NULL ) { - retval = Store_GDI_Char( ch ); - } - - WWASSERT( retval->Value == ch ); - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Get_Char_Width -// -//////////////////////////////////////////////////////////////////////////////////// -int -FontCharsClass::Get_Char_Width (WCHAR ch) -{ - const FontCharsClassCharDataStruct * data = Get_Char_Data( ch ); - if ( data != NULL ) { - return data->Width; - } - - return 0; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Get_Char_Spacing -// -//////////////////////////////////////////////////////////////////////////////////// -int -FontCharsClass::Get_Char_Spacing (WCHAR ch) -{ - const FontCharsClassCharDataStruct * data = Get_Char_Data( ch ); - if ( data != NULL ) { - if ( data->Width != 0 ) { - return data->Width - PixelOverlap - CharOverhang; - } - } - - return 0; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Blit_Char -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Blit_Char (WCHAR ch, uint16 *dest_ptr, int dest_stride, int x, int y) -{ - const FontCharsClassCharDataStruct * data = Get_Char_Data( ch ); - if ( data != NULL && data->Width != 0 ) { - - // - // Setup the src and destination pointers - // - int dest_inc = (dest_stride >> 1); - uint16 *src_ptr = data->Buffer; - dest_ptr += (dest_inc * y) + x; - - // - // Simply copy the data from the src buffer to the destination - // - for ( int row = 0; row < CharHeight; row ++ ) { - for ( int col = 0; col < data->Width; col ++ ) { - uint16 curData = *src_ptr; - if (colBuffer; - curr_buffer_p += CurrPixelOffset; - - // - // Copy the BMP contents to the buffer - // - int stride = (((width * 3) + 3) & ~3); - for (int row = 0; row < char_size.cy; row ++) { - - // - // Compute the indices into the BMP and surface - // - int index = (row * stride); - - // - // Loop over each column - // - for (int col = 0; col < char_size.cx; col ++) { - - // - // Get the pixel color at this location - // - uint8 pixel_value = GDIBitmapBits[index]; - index += 3; -#ifdef TEST_PLACEMENT - if (row==CharHeight-1&&col==0) { - pixel_value = 0xff; - } - if (row==CharHeight-2&&col==1) { - pixel_value = 0xff; - } - if (row==0&&col==0) { - pixel_value = 0xff; - } - if (row==1&&col==1) { - pixel_value = 0xff; - } - if (row==CharHeight-1&&col==char_size.cx-1-PixelOverlap) { - pixel_value = 0xff; - } - if (row==CharHeight-2&&col==char_size.cx-2-PixelOverlap) { - pixel_value = 0xff; - } - if (row==0&&col==char_size.cx-1-PixelOverlap) { - pixel_value = 0xff; - } - if (row==1&&col==char_size.cx-2-PixelOverlap) { - pixel_value = 0xff; - } - if (pixel_value == 0x00) { - pixel_value = 0x40; - } -#endif - - uint16 pixel_color = 0; - if (pixel_value != 0) { - pixel_color = 0x0FFF; - } - - // - // Convert the pixel intensity from 8bit to 4bit and - // store it in our buffer - // - uint8 alpha_value = ((pixel_value >> 4) & 0xF); - *curr_buffer_p++ = pixel_color | (alpha_value << 12); - } - } - - // - // Save information about this character in our list - // - FontCharsClassCharDataStruct *char_data = W3DNEW FontCharsClassCharDataStruct; - char_data->Value = ch; - char_data->Width = char_size.cx; - char_data->Buffer = BufferList[BufferList.Count () - 1]->Buffer + CurrPixelOffset; - - // - // Insert this character into our array - // - if ( ch < 256 ) { - ASCIICharArray[ch] = char_data; - } else { - UnicodeCharArray[ch - FirstUnicodeChar] = char_data; - } - - // - // Advance the character position - // - CurrPixelOffset += ((char_size.cx+PixelOverlap) * CharHeight); - - // - // Return the index of the entry we just added - // - return char_data; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Update_Current_Buffer -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Update_Current_Buffer (int char_width) -{ - // - // Check to see if we need to allocate a new buffer - // - bool needs_new_buffer = (BufferList.Count () == 0); - if (needs_new_buffer == false) { - - // - // Would we extend past this buffer? - // - if ( (CurrPixelOffset + (char_width * CharHeight)) > CHAR_BUFFER_LEN ) { - needs_new_buffer = true; - } - } - - // - // Do we need to create a new surface? - // - if (needs_new_buffer) - { - FontCharsBuffer* new_buffer = W3DNEW FontCharsBuffer; - BufferList.Add( new_buffer ); - CurrPixelOffset = 0; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Create_GDI_Font -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Create_GDI_Font (const char *font_name) -{ - HDC screen_dc = ::GetDC ((HWND)WW3D::Get_Window()); - - const char *fontToUseForGenerals = "Arial"; - bool doingGenerals = false; - if (strcmp(font_name, "Generals")==0) { - font_name = fontToUseForGenerals; - doingGenerals = true; - } - - // - // Calculate the height of the font in logical units - // - const int dotsPerInch = 96; // always use 96. jba. - int font_height = -MulDiv (PointSize, dotsPerInch, 72); - - int fontWidth = 0; // use font default. - if (doingGenerals) { - //fontWidth = -font_height*0.35f; //2 pixels tighter. - fontWidth = -font_height*0.40f; // one pixel tighter - } - PixelOverlap = (-font_height)/8; - - // Sanity check in case of perversion. :) - if (PixelOverlap<0) PixelOverlap = 0; - if (PixelOverlap>4) PixelOverlap = 4; - // - // Create the Windows font - // - DWORD bold = IsBold ? FW_BOLD : FW_NORMAL; - DWORD italic = 0; - GDIFont = ::CreateFont (font_height, fontWidth, 0, 0, bold, italic, - FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, - CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, - VARIABLE_PITCH, font_name); - - // - // Set-up the fields of the BITMAPINFOHEADER - // Note: Top-down DIBs use negative height in Win32. - // - BITMAPINFOHEADER bitmap_info = { 0 }; - bitmap_info.biSize = sizeof (BITMAPINFOHEADER); - bitmap_info.biWidth = PointSize * 2; - bitmap_info.biHeight = -(PointSize * 2); - bitmap_info.biPlanes = 1; - bitmap_info.biBitCount = 24; - bitmap_info.biCompression = BI_RGB; - bitmap_info.biSizeImage = ((PointSize * PointSize * 4) * 3); - bitmap_info.biXPelsPerMeter = 0; - bitmap_info.biYPelsPerMeter = 0; - bitmap_info.biClrUsed = 0; - bitmap_info.biClrImportant = 0; - - // - // Create a bitmap that we can access the bits directly of - // - GDIBitmap = ::CreateDIBSection ( screen_dc, - (const BITMAPINFO *)&bitmap_info, - DIB_RGB_COLORS, - (void **)&GDIBitmapBits, - NULL, - 0L); - - // - // Create a device context we can select the font and bitmap into - // - MemDC = ::CreateCompatibleDC (screen_dc); - - // - // Release our temporary screen DC - // - ::ReleaseDC ((HWND)WW3D::Get_Window(), screen_dc); - - // - // Now select the BMP and font into the DC - // - OldGDIBitmap = (HBITMAP)::SelectObject (MemDC, GDIBitmap); - OldGDIFont = (HFONT)::SelectObject (MemDC, GDIFont); - ::SetBkColor (MemDC, RGB (0, 0, 0)); - ::SetTextColor (MemDC, RGB (255, 255, 255)); - - // - // Lookup the pixel height of the font - // - TEXTMETRIC text_metric = { 0 }; - ::GetTextMetrics (MemDC, &text_metric); - CharHeight = text_metric.tmHeight; - CharAscent = text_metric.tmAscent; - CharOverhang = text_metric.tmOverhang; - if (doingGenerals) { - CharOverhang = 0; - } -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Free_GDI_Font -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Free_GDI_Font (void) -{ - // - // Select the old font back into the DC and delete - // our font object - // - if ( GDIFont != NULL ) { - ::SelectObject( MemDC, OldGDIFont ); - ::DeleteObject( GDIFont ); - GDIFont = NULL; - } - - // - // Select the old bitmap back into the DC and delete - // our bitmap object - // - if ( GDIBitmap != NULL ) { - ::SelectObject( MemDC, OldGDIBitmap ); - ::DeleteObject( GDIBitmap ); - GDIBitmap = NULL; - } - - // - // Delete our memory DC - // - if ( MemDC != NULL ) { - ::DeleteDC( MemDC ); - MemDC = NULL; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_GDI_Font -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Initialize_GDI_Font (const char *font_name, int point_size, bool is_bold) -{ - // - // Build a unique name from the font name and its size - // - Name.Format ("%s%d", font_name, point_size); - - // - // Remember these settings - // - GDIFontName = font_name; - PointSize = point_size; - IsBold = is_bold; - - // - // Create the actual font object - // - Create_GDI_Font (font_name); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Is_Font -// -//////////////////////////////////////////////////////////////////////////////////// -bool -FontCharsClass::Is_Font (const char *font_name, int point_size, bool is_bold) -{ - bool retval = false; - - // - // Check to see if both the name and height matches... - // - if ( (GDIFontName.Compare_No_Case (font_name) == 0) && - (point_size == PointSize) && - (is_bold == IsBold)) - { - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Grow_Unicode_Array -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Grow_Unicode_Array (WCHAR ch) -{ - // - // Don't do anything if character is in the ASCII range - // - if ( ch < 256 ) { - return ; - } - - // - // Don't do anything if character is in the currently allocated range - // - if ( ch >= FirstUnicodeChar && ch <= LastUnicodeChar ) { - return ; - } - - uint16 first_index = min( FirstUnicodeChar, static_cast(ch) ); - uint16 last_index = max( LastUnicodeChar, static_cast(ch) ); - uint16 count = (last_index - first_index) + 1; - - // - // Allocate enough memory to hold the new cells - // - FontCharsClassCharDataStruct **new_array = W3DNEWARRAY FontCharsClassCharDataStruct *[count]; - ::memset (new_array, 0, sizeof (FontCharsClassCharDataStruct *) * count); - - // - // Copy the contents of the old array into the new array - // - if ( UnicodeCharArray != NULL ) { - int start_offset = (FirstUnicodeChar - first_index); - int old_count = (LastUnicodeChar - FirstUnicodeChar) + 1; - ::memcpy (&new_array[start_offset], UnicodeCharArray, sizeof (FontCharsClassCharDataStruct *) * old_count); - - // - // Delete the old array - // - delete [] UnicodeCharArray; - UnicodeCharArray = NULL; - } - - FirstUnicodeChar = first_index; - LastUnicodeChar = last_index; - UnicodeCharArray = new_array; - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////// -// -// Free_Character_Arrays -// -//////////////////////////////////////////////////////////////////////////////////// -void -FontCharsClass::Free_Character_Arrays (void) -{ - if ( UnicodeCharArray != NULL ) { - - int count = (LastUnicodeChar - FirstUnicodeChar) + 1; - - // - // Delete each member of the unicode array - // - for (int index = 0; index < count; index ++) { - if ( UnicodeCharArray[index] != NULL ) { - delete UnicodeCharArray[index]; - UnicodeCharArray[index] = NULL; - } - } - - // - // Delete the array itself - // - delete [] UnicodeCharArray; - UnicodeCharArray = NULL; - } - - // - // Delete each member of the ascii character array - // - for (int index = 0; index < 256; index ++) { - if ( ASCIICharArray[index] != NULL ) { - delete ASCIICharArray[index]; - ASCIICharArray[index] = NULL; - } - } - - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h deleted file mode 100644 index 094715d350..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h +++ /dev/null @@ -1,276 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - /*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/render2dsentence.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/29/01 10:58a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef RENDER2DSENTENCE_H -#define RENDER2DSENTENCE_H - -#include "render2d.h" -#include "refcount.h" -#include "Vector.H" -#include "vector2i.h" -#include "wwstring.h" -#include "win.h" - -/* -** FontCharsClass -*/ -class SurfaceClass; - -// -// Private data structures -// -class FontCharsClassCharDataStruct : public W3DMPO -{ - W3DMPO_GLUE(FontCharsClassCharDataStruct) -public: - WCHAR Value; - short Width; - uint16 * Buffer; -}; - -enum { CHAR_BUFFER_LEN = 32768 }; - -class FontCharsBuffer : public W3DMPO -{ - W3DMPO_GLUE(FontCharsBuffer) -public: - uint16 Buffer[CHAR_BUFFER_LEN]; -}; - - -class FontCharsClass : public W3DMPO, public RefCountClass -{ - W3DMPO_GLUE(FontCharsClass) - -public: - FontCharsClass( void ); - ~FontCharsClass(); - - // TR: Hack for unicode font support - FontCharsClass *AlternateUnicodeFont; - - - void Initialize_GDI_Font( const char *font_name, int point_size, bool is_bold ); - bool Is_Font( const char *font_name, int point_size, bool is_bold ); - const char * Get_Name( void ) { return Name; } - - int Get_Char_Height( void ) { return CharHeight; } - int Get_Char_Width( WCHAR ch ); - int Get_Char_Spacing( WCHAR ch ); - - int Get_Extra_Overlap(void) {return PixelOverlap;} - - void Blit_Char( WCHAR ch, uint16 *dest_ptr, int dest_stride, int x, int y ); - -private: - - // - // Private methods - // - void Create_GDI_Font( const char *font_name ); - void Free_GDI_Font( void ); - const FontCharsClassCharDataStruct * Store_GDI_Char( WCHAR ch ); - void Update_Current_Buffer( int char_width ); - const FontCharsClassCharDataStruct * Get_Char_Data( WCHAR ch ); - - void Grow_Unicode_Array( WCHAR ch ); - void Free_Character_Arrays( void ); - - // - // Private member data - // - StringClass Name; - DynamicVectorClass BufferList; - int CurrPixelOffset; - int CharHeight; - int CharAscent; - int CharOverhang; - int PixelOverlap; - int PointSize; - StringClass GDIFontName; - HFONT OldGDIFont; - HBITMAP OldGDIBitmap; - HBITMAP GDIBitmap; - HFONT GDIFont; - uint8 * GDIBitmapBits; - HDC MemDC; - FontCharsClassCharDataStruct * ASCIICharArray[256]; - FontCharsClassCharDataStruct ** UnicodeCharArray; - uint16 FirstUnicodeChar; - uint16 LastUnicodeChar; - bool IsBold; -}; - -/* -** Render2DSentenceClass -*/ -class Render2DSentenceClass { -public: - //Render2DSentenceClass( FontCharsClass * font ); - Render2DSentenceClass( void ); - ~Render2DSentenceClass(); - - void Render (void); - virtual void Reset (void); - void Reset_Polys (void); - - FontCharsClass * Peek_Font( void ) { return Font; } - void Set_Font( FontCharsClass *font ); - - void Set_Location( const Vector2 & loc ); - void Set_Base_Location( const Vector2 & loc ); - bool Set_Wrapping_Width (float width) { if(WrapWidth == width) - return false; - WrapWidth = width; - return true; } - bool Set_Word_Wrap_Centered( bool isCentered ) { if(Centered == isCentered) - return false; - Centered = isCentered; - return true;} - void Set_Hot_Key_Parse( bool parseHotKey ){ ParseHotKey = parseHotKey; } - void Set_Use_Hard_Word_Wrap( bool useHardWrap){ useHardWordWrap = useHardWrap; } - // - // Clipping support - // - void Set_Clipping_Rect( const RectClass &rect ) { ClipRect = rect; IsClippedEnabled = true; } - bool Is_Clipping_Enabled( void ) const { return IsClippedEnabled; } - void Enable_Clipping( bool onoff ) { IsClippedEnabled = onoff; } - - // - // Shader modification support - // - void Make_Additive (void); - ShaderClass Get_Shader (void) const { return Shader; } - void Set_Shader (ShaderClass shader); - -// void Draw_Block( const RectClass & screen, unsigned long color = 0xFFFFFFFF ); - - const RectClass & Get_Draw_Extents( void ) { return DrawExtents; } -// const RectClass & Get_Total_Extents( void ) { return TotalExtents; } -// const Vector2 & Get_Cursor( void ) { return Cursor; } - - Vector2 Get_Text_Extents( const WCHAR * text ); - Vector2 Get_Formatted_Text_Extents( const WCHAR * text ); - - // - // Sentence control - // - void Build_Sentence (const WCHAR *text, int *hkX, int *hkY); - void Draw_Sentence (uint32 color = 0xFFFFFFFF); - - // - // Texture hint - // - void Set_Texture_Size_Hint( int hint ) { TextureSizeHint = hint; } - int Get_Texture_Size_Hint( void ) const { return TextureSizeHint; } - - void Set_Mono_Spaced( bool onoff ) { MonoSpaced = onoff; } - -private: - - // - // Private structures - // - struct SentenceDataStruct { - SurfaceClass * Surface; - RectClass ScreenRect; - RectClass UVRect; - - bool operator== (const SentenceDataStruct &src) { return false; } - bool operator!= (const SentenceDataStruct &src) { return true; } - }; - - struct PendingSurfaceStruct { - SurfaceClass * Surface; - DynamicVectorClass Renderers; - - bool operator== (const PendingSurfaceStruct &src) { return false; } - bool operator!= (const PendingSurfaceStruct &src) { return true; } - }; - - struct RendererDataStruct { - Render2DClass * Renderer; - SurfaceClass * Surface; - - bool operator== (const RendererDataStruct &src) { return false; } - bool operator!= (const RendererDataStruct &src) { return true; } - }; - - // - // Private methods - // - void Reset_Sentence_Data (void); - void Build_Textures (void); - void Record_Sentence_Chunk (void); - void Allocate_New_Surface (const WCHAR *text, bool justCalcExtents = false); - void Release_Pending_Surfaces (void); - void Build_Sentence_Centered (const WCHAR *text, int *hkX, int *hkY); - Vector2 Build_Sentence_Not_Centered (const WCHAR *text, int *hkX, int *hkY,bool justCalcExtents = false ); - // - // Private member data - // - DynamicVectorClass SentenceData; - DynamicVectorClass PendingSurfaces; - DynamicVectorClass Renderers; - FontCharsClass * Font; - Vector2 BaseLocation; - Vector2 Location; - Vector2 Cursor; - Vector2i TextureOffset; - int TextureStartX; - int CurrTextureSize; - int TextureSizeHint; - SurfaceClass * CurSurface; - bool MonoSpaced; - float WrapWidth; - bool Centered; // Determines whether or not to center each line - RectClass ClipRect; - RectClass DrawExtents; - bool IsClippedEnabled; - bool ParseHotKey; - bool useHardWordWrap; - - uint16 * LockedPtr; - int LockedStride; - TextureClass * CurTexture; - ShaderClass Shader; -}; - -#endif // RENDER2DSENTENCE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp deleted file mode 100644 index 6380cb5e0c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/renderobjectrecycler.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/08/01 3:54p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RenderObjectRecyclerClass::Reset -- reset the cache * - * RenderObjectRecyclerClass::Get_Render_Object -- Create/Re-use a render object * - * RenderObjectRecyclerClass::Return_Render_Object -- Return a render object to the cache * - * RenderObjectRecyclerClass::Insert_Inactive_Model -- Internally add a render object to the * - * RenderObjectRecyclerClass::Reset_Model -- resets a render object so it can be re-used * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "renderobjectrecycler.h" -#include -#include "rendobj.h" -#include "assetmgr.h" -#include "part_emt.h" -#include "matrix3d.h" - - -/*********************************************************************************************** - * RenderObjectRecyclerClass::Reset -- reset the pool * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -void RenderObjectRecyclerClass::Reset(void) -{ - InactiveModels.Reset_List(); -} - - -/*********************************************************************************************** - * RenderObjectRecyclerClass::Get_Render_Object -- Create/Re-use a render object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -RenderObjClass * RenderObjectRecyclerClass::Get_Render_Object(const char * name,const Matrix3D & tm) -{ - RefRenderObjListIterator it(&InactiveModels); - - RenderObjClass * found = NULL; - while (!it.Is_Done()) { - if (stricmp(it.Peek_Obj()->Get_Name(),name) == 0) { - found = it.Peek_Obj(); - break; - } - it.Next(); - } - - if (found != NULL) { - found->Add_Ref(); - InactiveModels.Remove(found); - found->Set_Transform(tm); - Reset_Model(found); - return found; - - } else { - - RenderObjClass * new_model = WW3DAssetManager::Get_Instance()->Create_Render_Obj(name); - if (new_model != NULL) { - new_model->Set_Transform(tm); - return new_model; - } - } - - return NULL; -} - - -/*********************************************************************************************** - * RenderObjectRecyclerClass::Return_Render_Object -- Return a render object to the pool * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -void RenderObjectRecyclerClass::Return_Render_Object(RenderObjClass * obj) -{ - Insert_Inactive_Model(obj); -} - - -/*********************************************************************************************** - * RenderObjectRecyclerClass::Insert_Inactive_Model -- Internally add a render object to the po* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -void RenderObjectRecyclerClass::Insert_Inactive_Model(RenderObjClass * obj) -{ - WWASSERT(obj != NULL); - InactiveModels.Add(obj); -} - -/*********************************************************************************************** - * RenderObjectRecyclerClass::Reset_Model -- resets a render object so it can be re-used * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/8/2001 gth : Created. * - *=============================================================================================*/ -void RenderObjectRecyclerClass::Reset_Model(RenderObjClass * model) -{ - /* - ** recursively reset all sub-objects (if any) - */ - for (int i=0; iGet_Num_Sub_Objects(); i++) { - RenderObjClass * robj = model->Get_Sub_Object(i); - Reset_Model(robj); - robj->Release_Ref(); - } - - /* - ** particle emitters must be reset (this should release their buffers) - */ - if (model->Class_ID() == RenderObjClass::CLASSID_PARTICLEEMITTER) { - ParticleEmitterClass * emitter = (ParticleEmitterClass *)model; - emitter->Reset(); - } - - /* - ** animated models must have their animation reset (if present) - */ - if (model->Peek_Animation() != NULL) { - model->Set_Animation(model->Peek_Animation(),0.0f,RenderObjClass::ANIM_MODE_ONCE); - } -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h deleted file mode 100644 index d07b3120ce..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/renderobjectrecycler.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/renderobjectrecycler.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/08/01 3:52p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef RENDEROBJECTRECYCLER_H -#define RENDEROBJECTRECYCLER_H - -#include "always.h" -#include "robjlist.h" - -class RenderObjClass; -class Matrix3D; - -/** -** RenderObjectRecyclerClass -** This class can be used to eliminate dynamic render object allocation. An example usage would be -** the case where you have a projectile system in a game. Projectiles could be set up to use a -** variety of render objects and would be rapidly created and destroyed as the players and AI's fire -** their weapons. If all of your bullet objects request their models from a RenderObjectCache, and -** return their models to the cache when the bullet is destroyed; the model will get re-used by -** the next bullet that requests that same model type (highly likely in a game situation). -** -** Public member functions: -** Reset - release all of the models in the cache. -** Get_Render_Object - returns either recycles a model or creates a new one through the asset manager -** Return_Render_Object - give your model back to the recycler for re-use later. -*/ -class RenderObjectRecyclerClass -{ -public: - - void Reset(void); - RenderObjClass* Get_Render_Object(const char * name,const Matrix3D & tm); - void Return_Render_Object(RenderObjClass * obj); - -private: - - void Insert_Inactive_Model(RenderObjClass * obj); - void Reset_Model(RenderObjClass * model); - - - RefRenderObjListClass InactiveModels; - -}; - - - - -#endif //RENDEROBJECTRECYCLER_H \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/rendobj.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/rendobj.cpp deleted file mode 100644 index f43e1df87f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/rendobj.cpp +++ /dev/null @@ -1,1318 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/rendobj.cpp 16 12/17/01 8:06p Byon_g $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/ww3d2/rendobj.cpp $* - * * - * Org Author:: Greg_h * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 07/01/02 12:45p $* - * * - * $Revision:: 17 $* - * * - * 07/01/02 KM Coltype enum change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RenderObjClass::RenderObjClass -- constructor * - * RenderObjClass::RenderObjClass -- copy constructor * - * RenderObjClass::operator == -- assignment operator * - * RenderObjClass::Calculate_Texture_Reduction_Factor -- calculate texture reduction factor * - * RenderObjClass::Set_Texture_Reduction_Factor -- set texture reduction factor. * - * RenderObjClass::Get_Screen_Size -- get normalized area of object. * - * RenderObjClass::Get_Scene -- returns the (add_ref'd) scene pointer * - * RenderObjClass::Set_Container -- sets the container pointer * - * RenderObjClass::Get_Container -- returns the container pointer * - * RenderObjClass::Set_Transform -- set the transform for this object * - * RenderObjClass::Set_Position -- Sets the position of this object * - * RenderObjClass::Get_Transform -- returns the transform for the object * - * RenderObjClass::Get_Position -- returns the position of this render object * - * RenderObjClass::Validate_Transform -- If the transform is dirty, this causes it to be re- * - * RenderObjClass::Get_Sub_Object -- returns pointer to first sub-obj with given name * - * RenderObjClass::Add_Sub_Object_To_Bone -- add an object to a named bone * - * RenderObjClass::Prepare_LOD -- prepare object for predictive and texture LOD processing. * - * RenderObjClass::Get_Cost -- get object rendering cost for predictive LOD processing. * - * RenderObjClass::Update_Sub_Object_Bits -- updates our bits according to our sub-objects * - * RenderObjClass::Update_Sub_Object_Transforms -- re-evaluate the transforms my sub-objects * - * RenderObjClass::Add -- Generic add for render objects * - * RenderObjClass::Remove -- Generic Remove for Render Objects * - * RenderObjClass::Notify_Added -- notifies the object that it is in a scene * - * RenderObjClass::Notify_Removed -- notifies an object that it has been removed * - * RenderObjClass::Update_Cached_Bounding_Volumes -- default collision sphere. * - * RenderObjClass::Get_Obj_Space_Bounding_Sphere -- default collision sphere. * - * RenderObjClass::Get_Obj_Space_Bounding_Box -- default collision box. * - * RenderObjClass::Intersect - Returns true if specified intersection object * - * RenderObjClass::Intersect_Sphere -- tests for intersection with the bounding sphere * - * RenderObjClass::Intersect_Sphere_Quick -- tests for intersection with the bounding sphere * - * RenderObjClass::Build_Dependency_List -- Generates a list of files this obj depends on. * - * RenderObjClass::Build_Texture_List -- Builds a list of texture files this obj depends on. * - * RenderObjClass::Add_Dependencies_To_List -- Add dependent files to the list. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "rendobj.h" -#include "assetmgr.h" -#include "win.h" -#include "pot.h" -#include "scene.h" -#include "colmath.h" -#include "coltest.h" -#include "inttest.h" -#include "wwdebug.h" -#include "matinfo.h" -#include "htree.h" -#include "predlod.h" -#include "camera.h" -#include "ww3d.h" -#include "chunkio.h" -#include "persistfactory.h" -#include "saveload.h" -#include "ww3dids.h" -#include "intersec.h" - - -#ifdef _INTERNAL -// for occasional debugging... -//#pragma optimize("", off) -//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") -#endif - -// Definitions of static members: -const float RenderObjClass::AT_MIN_LOD = FLT_MAX; -const float RenderObjClass::AT_MAX_LOD = -1.0f; - -// Local inline functions -StringClass -Filename_From_Asset_Name (const char *asset_name) -{ - StringClass filename; - if (asset_name != NULL) { - - // - // Copy the model name into a new filename buffer - // - ::lstrcpy (filename.Get_Buffer (::lstrlen (asset_name) + 5), asset_name); - - // - // Do we need to strip off the model's suffix? - // - char *suffix = ::strchr (filename.Peek_Buffer(), '.'); - if (suffix != NULL) { - suffix[0] = 0; - } - - // - // Concat the w3d file extension - // - filename += ".w3d"; - } - - return filename; -} - -static inline bool Check_Is_Transform_Identity(const Matrix3D& m) -{ - const float zero=0.0f; - const float one=1.0f; - - unsigned d= - ((unsigned&)m[0][0]^(unsigned&)one) | - ((unsigned&)m[0][1]^(unsigned&)zero) | - ((unsigned&)m[0][2]^(unsigned&)zero) | - ((unsigned&)m[0][3]^(unsigned&)zero) | - ((unsigned&)m[1][0]^(unsigned&)zero) | - ((unsigned&)m[1][1]^(unsigned&)one) | - ((unsigned&)m[1][2]^(unsigned&)zero) | - ((unsigned&)m[1][3]^(unsigned&)zero) | - ((unsigned&)m[2][0]^(unsigned&)zero) | - ((unsigned&)m[2][1]^(unsigned&)zero) | - ((unsigned&)m[2][2]^(unsigned&)one) | - ((unsigned&)m[2][3]^(unsigned&)zero); - return !d; -} - - -/*********************************************************************************************** - * RenderObjClass::RenderObjClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/04/1997 GH : Created. * - *=============================================================================================*/ -RenderObjClass::RenderObjClass(void) : - Bits(DEFAULT_BITS), - Transform(1), - NativeScreenSize(WW3D::Get_Default_Native_Screen_Size()), - Scene(NULL), - Container(NULL), - User_Data(NULL), - RenderHook(NULL), - ObjectScale(1.0), - ObjectColor(0), - CachedBoundingSphere(Vector3(0,0,0),1.0f), - CachedBoundingBox(Vector3(0,0,0),Vector3(1,1,1)), - IsTransformIdentity(false) -{ -} - -/*********************************************************************************************** - * RenderObjClass::RenderObjClass -- copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/97 GTH : Created. * - * 1/28/98 EHC : Created. * - *=============================================================================================*/ -RenderObjClass::RenderObjClass(const RenderObjClass & src) : - Bits(src.Bits), - Transform(src.Transform), - NativeScreenSize(src.NativeScreenSize), - Scene(NULL), - Container(NULL), - User_Data(NULL), - RenderHook(NULL), - ObjectScale(1.0), - ObjectColor(0), - CachedBoundingSphere(src.CachedBoundingSphere), - CachedBoundingBox(src.CachedBoundingBox), - IsTransformIdentity(src.IsTransformIdentity) -{ - // Even though we're copying an object which might be in a scene - // this copy won't be so I'm clearing the scene pointer, same logic - // follows for things like the Container pointer. -} - - -/*********************************************************************************************** - * RenderObjClass -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/97 GTH : Created. * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -RenderObjClass & RenderObjClass::operator = (const RenderObjClass & that) -{ - // don't do anything if we're assigning this to this - if (this != &that) { - Set_Hidden(that.Is_Hidden()); - Set_Animation_Hidden(that.Is_Animation_Hidden()); - Set_Force_Visible(that.Is_Force_Visible()); - Set_Collision_Type(that.Get_Collision_Type()); - Set_Native_Screen_Size(that.Get_Native_Screen_Size()); - IsTransformIdentity=false; - } - return *this; -} - - -/*********************************************************************************************** - * RenderObjClass::Calculate_Texture_Reduction_Factor -- calculate texture reduction factor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/08/99 NH : Created. * - *=============================================================================================*/ -/* -float RenderObjClass::Calculate_Texture_Reduction_Factor(float norm_screensize) -{ - // NOTE: The texture reduction factor represents the number of powers of two that the texture - // must be reduced by in both dimensions. The reason that such an inherently integral quantity - // is represented as a float is for the texture reduction algorithms to incorporate hysteresis - // properly. - float reduction = sqrt(Get_Native_Screen_Size() / norm_screensize); - reduction = MAX(1.0f, reduction); - - // We want to calculate the log base 2. Since the standard libraries have no log-base-2 - // function, we use the following: log-base-2(x) = log(x)/log(2) where log is the natural - // logarithm (which does exist in the stadard libraries). - // We precalculare 1/log(2) as 1.442695f. - return log(reduction) * 1.442695f; -} -*/ - -/*********************************************************************************************** - * RenderObjClass::Set_Texture_Reduction_Factor -- set texture reduction factor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/08/99 NH : Created. * - *=============================================================================================*/ -/* -void RenderObjClass::Set_Texture_Reduction_Factor(float trf) -{ - WWASSERT(0); // Texture reduction system is broken! Don't call! - MaterialInfoClass *minfo = Get_Material_Info(); - if (minfo) { - minfo->Set_Texture_Reduction_Factor(trf); - minfo->Release_Ref(); - } else { - int num_obj = Get_Num_Sub_Objects(); - RenderObjClass *sub_obj; - - for (int i = 0; i < num_obj; i++) { - sub_obj = Get_Sub_Object(i); - if (sub_obj) { - sub_obj->Set_Texture_Reduction_Factor(trf); - sub_obj->Release_Ref(); - } - } - } -} -*/ - -/*********************************************************************************************** - * RenderObjClass::Get_Screen_Size -- get normalized area of object. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/12/99 NH : Created. * - *=============================================================================================*/ -float RenderObjClass::Get_Screen_Size(CameraClass &camera) -{ - // Currently this works by projecting the bounding sphere to the screen - // (as if the object was at the center) - in future this may be made more - // accurate (perhaps by using the object-space bounding-box) - Vector3 cam = camera.Get_Position(); - - ViewportClass viewport = camera.Get_Viewport(); - Vector2 vpr_min, vpr_max; - camera.Get_View_Plane(vpr_min, vpr_max); - float width_factor = viewport.Width() / (vpr_max.X - vpr_min.X); - float height_factor = viewport.Height() / (vpr_max.Y - vpr_min.Y); - - const SphereClass & sphere = Get_Bounding_Sphere(); - float dist = (sphere.Center - cam).Length(); - float radius = 0.0f; - if (dist) { - radius = sphere.Radius / dist; - } - - // Return area in normalized units. - return WWMATH_PI * radius * radius * width_factor * height_factor; -} - - -/*********************************************************************************************** - * RenderObjClass::Get_Scene -- returns the (add_ref'd) scene pointer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/99 GTH : Created. * - *=============================================================================================*/ -SceneClass * RenderObjClass::Get_Scene(void) -{ - if (Scene != NULL) { - Scene->Add_Ref(); - } - return Scene; -} - - -/*********************************************************************************************** - * RenderObjClass::Set_Container -- sets the container pointer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Set_Container(RenderObjClass * con) -{ - // Either we arent currently in a container or we are clearing our container, otherwise - // Houston, there is a problem! - WWASSERT((con == NULL) || (Container == NULL)); - Container = con; -} - -#ifdef GET_CONTAINER_INLINE -// nothing -#else -/*********************************************************************************************** - * RenderObjClass::Get_Container -- returns the container pointer * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/99 GTH : Created. * - *=============================================================================================*/ -RenderObjClass * RenderObjClass::Get_Container(void) const -{ - return Container; -} -#endif - -/*********************************************************************************************** - * RenderObjClass::Set_Transform -- set the transform for this object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Set_Transform(const Matrix3D &m) -{ - Transform = m; - IsTransformIdentity=Check_Is_Transform_Identity(m); - Invalidate_Cached_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * RenderObjClass::Set_Position -- Sets the position of this object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - * 07/14/2001 SKB : Add Check_Is_Transform_Identity * - *=============================================================================================*/ -void RenderObjClass::Set_Position(const Vector3 &v) -{ - Transform.Set_Translation(v); - IsTransformIdentity=Check_Is_Transform_Identity(Transform); - Invalidate_Cached_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * RenderObjClass::Validate_Transform -- If the transform is dirty, this causes it to be re-ca * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/15/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Validate_Transform(void) const -{ - /* - ** Recurse up the tree to see if any of my parents are saying that their sub-object - ** transforms are dirty - */ - RenderObjClass * con = Get_Container(); - bool dirty = false; - if (con != NULL) - { - dirty = con->Are_Sub_Object_Transforms_Dirty(); - - while (con->Get_Container() != NULL) - { - dirty |= con->Are_Sub_Object_Transforms_Dirty(); - con = con->Get_Container(); - } - - /* - ** If the transforms are dirty, update them - */ - if (dirty) - { - con->Update_Sub_Object_Transforms(); - } - } - if (dirty) - IsTransformIdentity = Check_Is_Transform_Identity(Transform); -} - -/*********************************************************************************************** - * RenderObjClass::Get_Position -- returns the position of this render object * - * * - * Similar to Get_Transform but returns only the position. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -Vector3 RenderObjClass::Get_Position(void) const -{ - Validate_Transform(); - return Transform.Get_Translation(); -} - - -/*********************************************************************************************** - * RenderObjClass::Get_Sub_Object -- returns pointer to first sub-obj with given name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/99 GTH : Created. * - *=============================================================================================*/ -RenderObjClass * RenderObjClass::Get_Sub_Object_By_Name(const char * name, int *index) const -{ - int i; - - // first try the un-altered name - for (i=0; iGet_Name(),name) == 0) { - if (index) *index=i; - return robj; - } else { - robj->Release_Ref(); - } - } - } - - // check the given name against the "suffix" names of each sub-object - for (i=0; iGet_Name(),'.'); - if (subobjname == NULL) { - subobjname = robj->Get_Name(); - } else { - // skip past the period. - subobjname = subobjname+1; - } - - if (stricmp(subobjname,name) == 0) { - if (index) *index=i; - return robj; - } else { - robj->Release_Ref(); - } - } - } - - return NULL; -} - - -/*********************************************************************************************** - * RenderObjClass::Add_Sub_Object_To_Bone -- add an object to a named bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: If the bone name is unknown then this function will add the the object to the * - * root transform rather than failing. This is due to the fact that GetBoneIndex * - * returns the root tranform for unknown bones. * - * * - * HISTORY: * - * 3/4/99 GTH : Created. * - *=============================================================================================*/ -int RenderObjClass::Add_Sub_Object_To_Bone(RenderObjClass * subobj,const char * bname) -{ - int bindex = Get_Bone_Index(bname); - return Add_Sub_Object_To_Bone(subobj,bindex); -} - - -/*********************************************************************************************** - * RenderObjClass::Remove_Sub_Objects_From_Bone -- remove all objects from a named bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/1/02 NH : Created. * - *=============================================================================================*/ -int RenderObjClass::Remove_Sub_Objects_From_Bone(int boneindex) -{ - int count = Get_Num_Sub_Objects_On_Bone(boneindex); - int remove_count = 0; - for (int i = count-1; i >= 0; i--) { - RenderObjClass *robj = Get_Sub_Object_On_Bone(i, boneindex); - if ( robj ) { - remove_count += Remove_Sub_Object(robj); - robj->Release_Ref(); - } - } - return remove_count; -} - - -/*********************************************************************************************** - * RenderObjClass::Remove_Sub_Objects_From_Bone -- remove all objects from a named bone * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/4/99 NH : Created. * - *=============================================================================================*/ -int RenderObjClass::Remove_Sub_Objects_From_Bone(const char * bname) -{ - return Remove_Sub_Objects_From_Bone(Get_Bone_Index(bname)); -} - - -/*********************************************************************************************** - * RenderObjClass::Prepare_LOD -- prepare object for predictive and texture LOD processing. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * HISTORY: * - * 3/11/99 NH : Created. * - *=============================================================================================*/ -void RenderObjClass::Prepare_LOD(CameraClass &camera) -{ - // Since most RenderObjClass derivatives are not LOD-capable, the default - // implementation just sets the texture reduction factor and doesn't do any - // predictive LOD preparation (except for adding the objects' cost to the - // total static (nonoptimizeable) cost). - - // Find the maximum screen dimension of the object in pixels -// float norm_area = Get_Screen_Size(camera); - - // Find and set texture reduction factor - // Jani: Don't set tex reduction, it's broken! -// Set_Texture_Reduction_Factor(Calculate_Texture_Reduction_Factor(norm_area)); - - // Since we are not adding this object to the predictive LOD optimizer, - // at least add its cost in. - PredictiveLODOptimizerClass::Add_Cost(Get_Cost()); -} - - -/*********************************************************************************************** - * RenderObjClass::Get_Cost -- get object rendering cost for predictive LOD processing. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * HISTORY: * - * 3/11/99 NH : Created. * - *=============================================================================================*/ -float RenderObjClass::Get_Cost(void) const -{ - int polycount = Get_Num_Polys(); - // If polycount is zero set Cost to a small nonzero amount to avoid divisions by zero. - float cost = (polycount != 0)? polycount : 0.000001f; - return cost; -} - - -/*********************************************************************************************** - * RenderObjClass::Calculate_Cost_Value_Arrays -- calc arrays for predictive LOD processing. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNING: This member function assumes that the arrays passed are large enough (# LODs for * - * the cost array and # LODs + 1 for the value array) to contain the desired data. * - * * - * NOTE: This member function is usually only called internally inside LOD objects for * - * initialization purposes, or externally by specialized LOD objects like the G * - * predictive LOD PIP proxy. * - * * - * NOTE: The screen area used is in normalized units. * - * * - * HISTORY: * - * 3/11/99 NH : Created. * - *=============================================================================================*/ -int RenderObjClass::Calculate_Cost_Value_Arrays(float screen_area, float *values, float *costs) const -{ - values[0] = AT_MIN_LOD; - values[1] = AT_MAX_LOD; - costs[0] = Get_Cost(); - - return 0; -} - - -/*********************************************************************************************** - * RenderObjClass::Update_Sub_Object_Bits -- updates our bits according to our sub-objects * - * * - * This should be called by any object that contains other objects whenever a sub object is * - * added or removed. It updates the status of the attribute bits which are supposed to be * - * the union of all of the sub-objects attributes. (I.e. if one of our sub-objects is * - * translucent, then we should be marked as translucent). * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Update_Sub_Object_Bits(void) -{ - // this doesn't do anything for non-composite objects - if (Get_Num_Sub_Objects() == 0) return; - - // go through all of our sub-objects - int coltype = 0; - int istrans = 0; - int isalpha = 0; - int isadditive = 0; - - for (int ni = 0; ni < Get_Num_Sub_Objects(); ni++) { - RenderObjClass * robj = Get_Sub_Object(ni); - coltype |= robj->Get_Collision_Type(); - istrans |= robj->Is_Translucent(); - isalpha |= robj->Is_Alpha(); - isadditive |= robj->Is_Additive(); - robj->Release_Ref(); - } - - Set_Collision_Type(coltype); - Set_Translucent(istrans); - Set_Alpha(isalpha); - Set_Additive(isadditive); - - // if we are a sub-object, tell our container to do this - if (Container) { - Container->Update_Sub_Object_Bits(); - } -} - - -/*********************************************************************************************** - * RenderObjClass::Update_Sub_Object_Transforms -- re-evaluate the transforms my sub-objects * - * * - * The default implementation is empty, derived classes which have sub-objects should * - * implement it to update the transforms of their sub-objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Update_Sub_Object_Transforms(void) -{ -} - - -/*********************************************************************************************** - * RenderObjClass::Add -- Generic add for render objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/04/1997 GH : Created. * - * 2/25/99 GTH : Moved to the base RenderObjClass * - *=============================================================================================*/ -void RenderObjClass::Add(SceneClass * scene) -{ - WWASSERT(scene); - WWASSERT(Container == NULL); - Scene = scene; - Scene->Add_Render_Object(this); -} - -/*********************************************************************************************** - * RenderObjClass::Remove -- Generic Remove for Render Objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/04/1997 GH : Created. * - * 2/25/99 GTH : moved to the base RenderObjClass * - *=============================================================================================*/ -void RenderObjClass::Remove(void) -{ - // All render objects have their scene pointers set. To check if this is a "top level" - // object, (i.e. directly in the scene) you see if its Container pointer is NULL. -#if 1 - if (Container == NULL) { - if (Scene != NULL) { - Scene->Remove_Render_Object(this); - return; - } - } else { - Container->Remove_Sub_Object(this); - return; - } -#else - if (!Scene) return; - Scene->Remove_Render_Object(this); - Scene = NULL; -#endif -} - - -/*********************************************************************************************** - * RenderObjClass::Notify_Added -- notifies the object that it is in a scene * - * * - * This function will be called whenever an object is directly or indirectly added to a scene * - * An example of "indirect" addition would be if you were added as a sub-object to an HModel * - * that was already in a scene. * - * * - * Override this function if you want to register your object for per-frame-updating or * - * as a VertexProcessor. (See the Register method of SceneClass, ParticleBufferClass, etc) * - * * - * Container objects must forward this notification to their sub objects. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Due to implementation details of some derived scenes, the SceneClass calls this function. * - * Please dont move the call to this to RenderObjClass::Add * - * Derived classes should also call the base class to ensure that the scene pointer is set * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Notify_Added(SceneClass * scene) -{ - Scene = scene; -} - - -/*********************************************************************************************** - * RenderObjClass::Notify_Removed -- notifies an object that it has been removed * - * * - * Works similar to the Notify_Added function. You can override and Unregister yourself from * - * any scene based special processing. Container objects must recurse to their sub objects. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Derived classes should also call the base class to ensure that the scene pointer is cleared * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Notify_Removed(SceneClass * scene) -{ - Scene = NULL; -} - - -/*********************************************************************************************** - * RenderObjClass::Update_Cached_Bounding_Volumes -- default collision sphere. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/7/97 GTH : Created. * - *=============================================================================================*/ -void RenderObjClass::Update_Cached_Bounding_Volumes(void) const -{ - Get_Obj_Space_Bounding_Box(CachedBoundingBox); - Get_Obj_Space_Bounding_Sphere(CachedBoundingSphere); - -#ifdef ALLOW_TEMPORARIES - CachedBoundingSphere.Center = Get_Transform() * CachedBoundingSphere.Center; -#else - Get_Transform().mulVector3(CachedBoundingSphere.Center); -#endif - CachedBoundingSphere.Radius = ObjectScale * CachedBoundingSphere.Radius; - CachedBoundingBox.Transform(Get_Transform()); - - Validate_Cached_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * RenderObjClass::Get_Obj_Space_Bounding_Sphere -- default collision sphere. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 28/8/97 NH : Created. * - * 2/25/99 GTH : Moved into RenderObjClass * - *=============================================================================================*/ -void RenderObjClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - sphere.Center.Set(0,0,0); - sphere.Radius = 1.0f; -} - - -/*********************************************************************************************** - * RenderObjClass::Get_Obj_Space_Bounding_Box -- default collision box. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 28/8/97 NH : Created. * - * 2/25/99 GTH : Moved into RenderObjClass * - *=============================================================================================*/ -void RenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - box.Center.Set(0,0,0); - box.Extent.Set(0,0,0); -} - -/*********************************************************************************************** - * RenderObjClass::Intersect - Returns true if specified intersection object * - * intersects this renderobject * - * * - * * - * * - * * - * INPUT: A properly configured Intersection object specifying ray direction & vector * - * * - * OUTPUT: * - * * - * HISTORY: * - * 2/25/99 GTH : Moved into RenderObjClass * - *=============================================================================================*/ -bool RenderObjClass::Intersect(IntersectionClass *Intersection, IntersectionResultClass *Final_Result) -{ - - // do the quick sphere test just to make sure it is worth the more expensive intersection test - if (Intersect_Sphere_Quick(Intersection, Final_Result)) { - - CastResultStruct castresult; - LineSegClass lineseg; - - Vector3 end = *Intersection->RayLocation + *Intersection->RayDirection * Intersection->MaxDistance; - lineseg.Set(* Intersection->RayLocation, end); - - RayCollisionTestClass ray(lineseg, &castresult); - ray.CollisionType = COLL_TYPE_ALL; - - if (Cast_Ray(ray)) { - lineseg.Compute_Point(ray.Result->Fraction,&(Final_Result->Intersection)); - Final_Result->Intersects = true; - Final_Result->IntersectionType = IntersectionResultClass::GENERIC; - if (Intersection->IntersectionNormal) - * Intersection->IntersectionNormal = castresult.Normal; - Final_Result->IntersectedRenderObject = this; - Final_Result->ModelMatrix = Transform; - return true; - } - } - Final_Result->Intersects = false; - return false; -} - - -/*********************************************************************************************** - * RenderObjClass::Intersect_Sphere -- tests for intersection with the bounding sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -bool RenderObjClass::Intersect_Sphere(IntersectionClass *Intersection, IntersectionResultClass *Final_Result) -{ - SphereClass sphere = Get_Bounding_Sphere(); - return Intersection->Intersect_Sphere(sphere, Final_Result); -} - - -/*********************************************************************************************** - * RenderObjClass::Intersect_Sphere_Quick -- tests for intersection with the bounding sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -bool RenderObjClass::Intersect_Sphere_Quick(IntersectionClass *Intersection, IntersectionResultClass *Final_Result) -{ - SphereClass sphere = Get_Bounding_Sphere(); - return Intersection->Intersect_Sphere_Quick(sphere, Final_Result); -} - -/*********************************************************************************************** - * RenderObjClass::Build_Dependency_List -- Generates a list of files this obj depends on. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/18/99 PDS : Created. * - *=============================================================================================*/ -bool RenderObjClass::Build_Dependency_List (DynamicVectorClass &file_list, bool recursive) -{ - if (recursive) - { - // Loop through all this object's subobj's - int subobj_count = Get_Num_Sub_Objects (); - for (int index = 0; index < subobj_count; index ++) { - - // Ask this subobj to add all of its file dependencies to the list - RenderObjClass *psub_obj = Get_Sub_Object (index); - if (psub_obj != NULL) { - psub_obj->Build_Dependency_List (file_list); - psub_obj->Release_Ref (); - } - } - } - - // Now add all of this object's dependencies to the list - Add_Dependencies_To_List (file_list); - - // Return the true/false result code - return (file_list.Count () > 0); -} - - -/*********************************************************************************************** - * RenderObjClass::Build_Texture_List -- Builds a list of texture files this obj depends on. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/18/99 PDS : Created. * - *=============================================================================================*/ -bool RenderObjClass::Build_Texture_List -( - DynamicVectorClass & texture_file_list, - bool recursive -) -{ - if (recursive) { - - // - // Loop through all this object's subobj's - // - int subobj_count = Get_Num_Sub_Objects (); - for (int index = 0; index < subobj_count; index ++) { - - // - // Ask this subobj to add all of its texture file dependencies to the list - // - RenderObjClass *sub_obj = Get_Sub_Object (index); - if (sub_obj != NULL) { - sub_obj->Build_Texture_List (texture_file_list); - sub_obj->Release_Ref (); - } - } - } - - // - // Now add all of this object's texture dependencies to the list - // - Add_Dependencies_To_List (texture_file_list, true); - - // Return the true/false result code - return (texture_file_list.Count () > 0); -} - -/*********************************************************************************************** - * RenderObjClass::Add_Dependencies_To_List -- Add dependent files to the list. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/18/99 PDS : Created. * - *=============================================================================================*/ -void RenderObjClass::Add_Dependencies_To_List -( - DynamicVectorClass &file_list, - bool textures_only -) -{ - // - // Should we add W3D files to the list? - // - if (textures_only == false) { - - // - // Main W3D file - // - const char *model_name = Get_Name (); - file_list.Add (::Filename_From_Asset_Name (model_name)); - - // - // External hierarchy file - // - const HTreeClass *phtree = Get_HTree (); - if (phtree != NULL) { - const char *htree_name = phtree->Get_Name (); - if (::lstrcmpi (htree_name, model_name) != 0) { - - // - // Add this file to the list - // - file_list.Add (::Filename_From_Asset_Name (htree_name)); - } - } - - // - // Original W3D file (if an aggregate) - // - const char *base_model_name = Get_Base_Model_Name (); - if (base_model_name != NULL) { - - // - // Add this file to the list - // - file_list.Add (::Filename_From_Asset_Name (base_model_name)); - } - } - - return; -} - - - -/**************************************************************************************** - - - RenderObjClass - Persistant object support. - - NOTE: For now, the render obj PersistFactory is going to cheat by simply storing - the name of the render object that was saved. At load time, it will ask the - asset manager for that object again. If the asset manager fails to re-create the - object, - - -****************************************************************************************/ - -class RenderObjPersistFactoryClass : public PersistFactoryClass -{ - virtual uint32 Chunk_ID(void) const; - virtual PersistClass * Load(ChunkLoadClass & cload) const; - virtual void Save(ChunkSaveClass & csave,PersistClass * obj) const; - - enum - { - RENDOBJFACTORY_CHUNKID_VARIABLES = 0x00555040, - RENDOBJFACTORY_VARIABLE_OBJPOINTER = 0x00, - RENDOBJFACTORY_VARIABLE_NAME, - RENDOBJFACTORY_VARIABLE_TRANSFORM - }; -}; - -static RenderObjPersistFactoryClass _RenderObjPersistFactory; - -uint32 RenderObjPersistFactoryClass::Chunk_ID(void) const -{ - return WW3D_PERSIST_CHUNKID_RENDEROBJ; -} - -PersistClass * RenderObjPersistFactoryClass::Load(ChunkLoadClass & cload) const -{ - RenderObjClass * old_obj = NULL; - Matrix3D tm(1); - char name[64]; - - while (cload.Open_Chunk()) { - switch (cload.Cur_Chunk_ID()) { - - case RENDOBJFACTORY_CHUNKID_VARIABLES: - - while (cload.Open_Micro_Chunk()) { - switch(cload.Cur_Micro_Chunk_ID()) { - READ_MICRO_CHUNK(cload,RENDOBJFACTORY_VARIABLE_OBJPOINTER,old_obj); - READ_MICRO_CHUNK(cload,RENDOBJFACTORY_VARIABLE_TRANSFORM,tm); - READ_MICRO_CHUNK_STRING(cload,RENDOBJFACTORY_VARIABLE_NAME,name,sizeof(name)); - } - cload.Close_Micro_Chunk(); - } - break; - - default: - WWDEBUG_SAY(("Unhandled Chunk: 0x%X File: %s Line: %d\r\n",__FILE__,__LINE__)); - break; - }; - cload.Close_Chunk(); - } - - // if the object we saved didn't have a name, replace it with null - if (strlen(name) == 0) { - static int count = 0; - if ( ++count < 10 ) { - WWDEBUG_SAY(("RenderObjPersistFactory attempted to load an un-named render object!\r\n")); - WWDEBUG_SAY(("Replacing it with a NULL render object!\r\n")); - } - strcpy(name,"NULL"); - } - - RenderObjClass * new_obj = WW3DAssetManager::Get_Instance()->Create_Render_Obj(name); - - if (new_obj == NULL) { - static int count = 0; - if ( ++count < 10 ) { - WWDEBUG_SAY(("RenderObjPersistFactory failed to create object: %s!!\r\n",name)); - WWDEBUG_SAY(("Either the asset for this object is gone or you tried to save a procedural object.\r\n")); - WWDEBUG_SAY(("Replacing it with a NULL render object!\r\n")); - } - strcpy(name,"NULL"); - new_obj = WW3DAssetManager::Get_Instance()->Create_Render_Obj(name); - } - - WWASSERT(new_obj != NULL); - if (new_obj) { - new_obj->Set_Transform(tm); - } - - SaveLoadSystemClass::Register_Pointer(old_obj,new_obj); - return new_obj; -} - -void RenderObjPersistFactoryClass::Save(ChunkSaveClass & csave,PersistClass * obj) const -{ - RenderObjClass * robj = (RenderObjClass *)obj; - const char * name = robj->Get_Name(); - Matrix3D tm = robj->Get_Transform(); - - csave.Begin_Chunk(RENDOBJFACTORY_CHUNKID_VARIABLES); - WRITE_MICRO_CHUNK(csave,RENDOBJFACTORY_VARIABLE_OBJPOINTER,robj); - WRITE_MICRO_CHUNK_STRING(csave,RENDOBJFACTORY_VARIABLE_NAME,name); - WRITE_MICRO_CHUNK(csave,RENDOBJFACTORY_VARIABLE_TRANSFORM,tm); - csave.End_Chunk(); -} - - -/* -** RenderObj save-load. -*/ -const PersistFactoryClass & RenderObjClass::Get_Factory (void) const -{ - return _RenderObjPersistFactory; -} - -bool RenderObjClass::Save (ChunkSaveClass &csave) -{ - // This should never hit with the persist factory we're using... - // Yes this looks like a design flaw but the way we're saving render objects is - // a "shortcut". We specifically designed this capability into the persistant - // object system so that we could avoid making all render object's save and - // load themselves if possible. - WWASSERT(0); - return true; -} - -bool RenderObjClass::Load (ChunkLoadClass &cload) -{ - WWASSERT(0); // this should never hit with the persist factory we're using. - return true; -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/rendobj.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/rendobj.h deleted file mode 100644 index 9560904983..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/rendobj.h +++ /dev/null @@ -1,658 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - /*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/rendobj.h $* - * * - * Org Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/27/02 9:23a $* - * * - * $Revision:: 14 $* - * * - * 06/27/02 KM Shader system classid addition * - * 07/01/02 KM Coltype enum change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef RENDOBJ_H -#define RENDOBJ_H - -#include "always.h" -#include "refcount.h" -#include "sphere.h" -#include "coltype.h" -#include "aabox.h" -#include "persist.h" -#include "multilist.h" -#include "robjlist.h" -#include - -class Vector3; -class Matrix3D; -class MaterialInfoClass; -class TextureClass; -class SceneClass; -class HTreeClass; -class HAnimClass; -class HAnimComboClass; -class HCompressedAnimClass; -class RayCollisionTestClass; -class AABoxCollisionTestClass; -class OBBoxCollisionTestClass; -class AABoxIntersectionTestClass; -class OBBoxIntersectionTestClass; -class CameraClass; -class SphereClass; -class AABoxClass; -class RenderInfoClass; -class SpecialRenderInfoClass; -class IntersectionClass; -class IntersectionResultClass; -class DecalGeneratorClass; -class RenderObjProxyClass; -class StringClass; -template class DynamicVectorClass; - -// "unreferenced formal parameter" -#pragma warning(disable : 4100) - -#ifdef DEFINE_W3DANIMMODE_NAMES -static const char* TheAnimModeNames[] = -{ - "MANUAL", - "LOOP", - "ONCE", - "LOOP_PINGPONG", - "LOOP_BACKWARDS", - "ONCE_BACKWARDS", - NULL -}; -#endif - - -////////////////////////////////////////////////////////////////////////////////// -// RenderObjClass -// This is the interface for all objects that get rendered by WW3D. -// -// Render object RTTI: If you really need to typecast a render object -// pointer that you got from the asset manager, the class id mechanism -// can be used to check what you really have. User class id's can come -// after CLASSID_LAST. -// -// Cloning: All RenderObj's need to be able to clone themselves. This function -// should create a new and separate RenderObj of the correct type and return a -// RenderObj pointer to it. The implementation of this function will be -// to simply call your copy constructor; its basically a virtual copy constructor. -// -// Rendering: If the render object is in a scene that is rendered and is determined -// to be visible by that scene, it will receive a Render call. The argument -// to the call will contain both the camera being used and the low level rendering -// interface. In addition, the Special_Render function is for all "non-normal" -// types of rendering. Some examples of this are: G-Buffer rendering (rendering -// object ID's), shadow rendering (just use black, etc) and whatever else we -// come up with. Basically it will be a function with a big switch statement -// to handle all of these extra operations. This means the main render code -// path is not cluttered with these checks while not forcing every object to -// implement millions of separate special render functions. (Many objects just -// pass the render calls onto their sub-objects). -// -// VertexProcessors: Vertex processors are classes that are not actually 'rendered' -// They insert into the system an object that performs operations on all of -// the subsequent vertices that are processed. Lights and Fogs are types of -// vertex processors. -// -// "Scene Graph": A scene is organized as a list of render objects. There is no -// implied hierarchical structure to a scene. RenderObjects can contain other -// render objects (they follow the 'Composite' pattern) which is how hierarchical -// objects are built. Hierarchical models are render objects that just -// contain other render objects and apply hierarchical transforms to them. -// Hierarchical Models can be inserted inside of other hierarchical models. -// -// Predictive LOD: The predictive LOD system selects LODs for the visible objects -// so that the various resources (polys, vertices, etc.) do not pass given -// budgets - the goal is to achieve a constant frame rate. This interface -// includes things that are needed for this optimization process. Objects which -// do not support changing their LOD should report that they have 1 LOD and -// should report their cost to the LOD optimization system. -// -// Dependency Generation: Render objects are composed of one or more W3D and -// texture files. This set of interfaces provides access to that dependency list. -// -////////////////////////////////////////////////////////////////////////////////// - -// This is a small abstract class which a render object may have a pointer to. If present, its -// Pre_Render and Post_Render calls will be called before and after the Render() call of this -// render object. Applications using WW3D may create concrete classes deriving from this for -// application-specific pre- and post- render processing. (the return value from Pre_Render -// determines whether to perform the Render() call - if false, Render() will not be called). -class RenderHookClass -{ -public: - RenderHookClass(void) { } - virtual ~RenderHookClass(void) { } - virtual bool Pre_Render(RenderObjClass *robj, RenderInfoClass &rinfo) = 0; - virtual void Post_Render(RenderObjClass *robj, RenderInfoClass &rinfo) = 0; -private: - // Enforce no-copy semantics, for this and derived classes. This is done by making these - // private and not having definitions for them. - RenderHookClass(const RenderHookClass & src); - RenderHookClass & operator=(const RenderHookClass & src); -}; - -// RenderObjClass definition -class RenderObjClass : public RefCountClass , public PersistClass, public MultiListObjectClass -{ -public: - - //Integer flag placed at the start of structure pointed to by - //User_Data to signal that it points at custom mesh material settings. - //Added for 'Generals' - MW - enum {USER_DATA_MATERIAL_OVERRIDE = 0x01234567}; - - //This strucutre is used to pass custom rendering parameters into the W3D - //mesh renderer so it can override settings which are usually shared across - //all instances of a model - typically material settings like alpha, texture - //animation, texture uv scrolling, etc. Added for 'Generals' -MW - struct Material_Override - { Material_Override(void) : Struct_ID(USER_DATA_MATERIAL_OVERRIDE),customUVOffset(0,0) {} - - int Struct_ID; //ID used to identify this structure from a pointer to it. - Vector2 customUVOffset; - }; - - // - // Note: It is very important that these values NEVER CHANGE. That means - // when adding a new class id, it should be added to the end of the enum. - // - enum - { - CLASSID_UNKNOWN = 0xFFFFFFFF, - CLASSID_MESH = 0, - CLASSID_HMODEL, - CLASSID_DISTLOD, - CLASSID_PREDLODGROUP, - CLASSID_TILEMAP, - CLASSID_IMAGE3D, // Obsolete - CLASSID_LINE3D, - CLASSID_BITMAP2D, // Obsolete - CLASSID_CAMERA, - CLASSID_DYNAMESH, - CLASSID_DYNASCREENMESH, - CLASSID_TEXTDRAW, - CLASSID_FOG, - CLASSID_LAYERFOG, - CLASSID_LIGHT, - CLASSID_PARTICLEEMITTER, - CLASSID_PARTICLEBUFFER, - CLASSID_SCREENPOINTGROUP, - CLASSID_VIEWPOINTGROUP, - CLASSID_WORLDPOINTGROUP, - CLASSID_TEXT2D, - CLASSID_TEXT3D, - CLASSID_NULL, - CLASSID_COLLECTION, - CLASSID_FLARE, - CLASSID_HLOD, - CLASSID_AABOX, - CLASSID_OBBOX, - CLASSID_SEGLINE, - CLASSID_SPHERE, - CLASSID_RING, - CLASSID_BOUNDFOG, - CLASSID_DAZZLE, - CLASSID_SOUND, - CLASSID_SEGLINETRAIL, - CLASSID_LAND, - CLASSID_SHDMESH, // mesh class that uses the scaleable shader system - CLASSID_LAST = 0x0000FFFF - }; - - RenderObjClass(void); - RenderObjClass(const RenderObjClass & src); - RenderObjClass & operator = (const RenderObjClass &); - virtual ~RenderObjClass(void) { if (RenderHook) delete RenderHook; } - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Cloning and Identification - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const = 0; - virtual int Class_ID(void) const { return CLASSID_UNKNOWN; } - virtual const char * Get_Name(void) const { return "UNNAMED"; } - virtual void Set_Name(const char * name) { } - virtual const char * Get_Base_Model_Name (void) const { return NULL; } - virtual void Set_Base_Model_Name (const char *name) { } - virtual int Get_Num_Polys(void) const { return 0; } - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Rendering - // - // Render - this object should render its polygons. Typically called from a SceneClass - // Special_Render - all special-case rendering goes here to avoid polluting the main render pipe (e.g. VIS) - // On_Frame_Update - render objects can register for an On_Frame_Update call; the scene will call this once - // per frame if they do so. - // Restart - This interface is used to facilitate model recycling. If a render object is "Restarted" it should - // put itself back into a state as if it has never been rendered (e.g. particle emitters - // should reset their "emitted particle counts" so they can be re-used.) - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual void Render(RenderInfoClass & rinfo) = 0; - virtual void Special_Render(SpecialRenderInfoClass & rinfo) { } - virtual void On_Frame_Update() { } - virtual void Restart(void) { } - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - "Scene Graph" - // Some of the functions in this group are non-virtual as they are meant - // to be never overriden or are supposed to be implemented in terms of - // the other virtual functions. We want to keep the virtual interface - // as small as possible - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual void Add(SceneClass * scene); - virtual void Remove(void); - virtual SceneClass * Get_Scene(void); - virtual SceneClass * Peek_Scene(void) { return Scene; } - virtual void Set_Container(RenderObjClass * con); - virtual void Validate_Transform(void) const; - -#define GET_CONTAINER_INLINE -#ifdef GET_CONTAINER_INLINE - // srj sez: this is called a ton and never overridden, so inline it - inline RenderObjClass * Get_Container(void) const { return Container; } -#else - virtual RenderObjClass * Get_Container(void) const; -#endif - - virtual void Set_Transform(const Matrix3D &m); - virtual void Set_Position(const Vector3 &v); - const Matrix3D & Get_Transform(void) const; - const Matrix3D & Get_Transform(bool& is_transform_identity) const; - const Matrix3D & Get_Transform_No_Validity_Check(void) const; - const Matrix3D & Get_Transform_No_Validity_Check(bool& is_transform_identity) const; - bool Is_Transform_Identity() const; - bool Is_Transform_Identity_No_Validity_Check() const; - Vector3 Get_Position(void) const; - - virtual void Notify_Added(SceneClass * scene); - virtual void Notify_Removed(SceneClass * scene); - - virtual int Get_Num_Sub_Objects(void) const { return 0; } - virtual RenderObjClass * Get_Sub_Object(int index) const { return NULL; } - virtual int Add_Sub_Object(RenderObjClass * subobj) { return 0; } - virtual int Remove_Sub_Object(RenderObjClass * robj) { return 0; } - virtual RenderObjClass * Get_Sub_Object_By_Name(const char * name, int *index=NULL) const; - - virtual int Get_Num_Sub_Objects_On_Bone(int boneindex) const { return 0; } - virtual RenderObjClass * Get_Sub_Object_On_Bone(int index,int boneindex) const { return NULL; } - virtual int Get_Sub_Object_Bone_Index(RenderObjClass * subobj) const { return 0; } - virtual int Get_Sub_Object_Bone_Index(int LodIndex, int ModelIndex) const { return 0; } - virtual int Add_Sub_Object_To_Bone(RenderObjClass * subobj,int bone_index) { return 0; } - virtual int Add_Sub_Object_To_Bone(RenderObjClass * subobj,const char * bname); - virtual int Remove_Sub_Objects_From_Bone(int boneindex); - virtual int Remove_Sub_Objects_From_Bone(const char * bname); - - // This is public only so objects can recursively call this on their sub-objects - virtual void Update_Sub_Object_Transforms(void); - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Hierarchical Animation - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - enum AnimMode - { - ANIM_MODE_MANUAL = 0, - ANIM_MODE_LOOP, - ANIM_MODE_ONCE, - ANIM_MODE_LOOP_PINGPONG, - ANIM_MODE_LOOP_BACKWARDS, //make sure only backwards playing animations after this one - ANIM_MODE_ONCE_BACKWARDS, - }; - - virtual void Set_Animation( void ) { } - virtual void Set_Animation( HAnimClass * motion, - float frame, int anim_mode = ANIM_MODE_MANUAL) { } - virtual void Set_Animation( HAnimClass * motion0, - float frame0, - HAnimClass * motion1, - float frame1, - float percentage) { } - virtual void Set_Animation( HAnimComboClass * anim_combo) { } - - virtual HAnimClass * Peek_Animation( void ) { return NULL; } - virtual int Get_Num_Bones(void) { return 0; } - virtual const char * Get_Bone_Name(int bone_index) { return NULL; } - virtual int Get_Bone_Index(const char * bonename) { return 0; } - virtual const Matrix3D & Get_Bone_Transform(const char * bonename) { return Get_Transform(); } - virtual const Matrix3D & Get_Bone_Transform(int boneindex) { return Get_Transform(); } - virtual void Capture_Bone(int bindex) { } - - - virtual void Release_Bone(int bindex) { } - virtual bool Is_Bone_Captured(int bindex) const { return false; } - virtual void Control_Bone(int bindex,const Matrix3D & objtm,bool world_space_translation = false) { } - virtual const HTreeClass * Get_HTree(void) const { return NULL; } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Collision Detection - // Cast_Ray - intersects a ray with the render object - // Cast_AABox - intersects a swept AABox with the render object - // Cast_OBBox - intersects a swept OBBox with the render object - // Intersect_AABox - boolean test for intersection between an AABox and the renderobj - // Intersect_OBBox - boolean test for intersection between an OBBox and the renderobj - // Intersect - tests a ray for intersection with the render object - // Intersect_Sphere - tests a ray for intersection with the bounding spheres - // Intersect_Sphere_Quick - tests a ray for intersection with bounding spheres - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual bool Cast_Ray(RayCollisionTestClass & raytest) { return false; } - virtual bool Cast_AABox(AABoxCollisionTestClass & boxtest) { return false; } - virtual bool Cast_OBBox(OBBoxCollisionTestClass & boxtest) { return false; } - - virtual bool Intersect_AABox(AABoxIntersectionTestClass & boxtest) { return false; } - virtual bool Intersect_OBBox(OBBoxIntersectionTestClass & boxtest) { return false; } - - virtual bool Intersect(IntersectionClass *Intersection, IntersectionResultClass *Final_Result); - virtual bool Intersect_Sphere(IntersectionClass *Intersection, IntersectionResultClass *Final_Result); - virtual bool Intersect_Sphere_Quick(IntersectionClass *Intersection, IntersectionResultClass *Final_Result); - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Bounding Volumes - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual const SphereClass & Get_Bounding_Sphere(void) const; - virtual const AABoxClass & Get_Bounding_Box(void) const; - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - virtual void Update_Obj_Space_Bounding_Volumes(void) { }; - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Predictive LOD - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - // Two constants for Value queries, which are returned instead of the - // current Value in certain cases. They are usually used as sentinels. - // AT_MIN_LOD is a very large positive number, AT_MAX_LOD is negative. - static const float AT_MIN_LOD; - static const float AT_MAX_LOD; - - virtual void Prepare_LOD(CameraClass &camera); - virtual void Recalculate_Static_LOD_Factors(void) { } - virtual void Increment_LOD(void) { } - virtual void Decrement_LOD(void) { } - virtual float Get_Cost(void) const; - virtual float Get_Value(void) const { return AT_MIN_LOD; } - virtual float Get_Post_Increment_Value(void) const { return AT_MAX_LOD; } - virtual void Set_LOD_Level(int lod) { } - virtual int Get_LOD_Level(void) const { return 0; } - virtual int Get_LOD_Count(void) const { return 1; } - virtual void Set_LOD_Bias(float bias) { } - virtual int Calculate_Cost_Value_Arrays(float screen_area, float *values, float *costs) const; - virtual RenderObjClass * Get_Current_LOD(void) { Add_Ref(); return this; } - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Dependency Generation - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - // - // Note: The strings contained in these lists need to be freed by the caller. - // They should be freed using the delete operator. - // - // Be aware, these lists WILL contain duplicate entries. - // - virtual bool Build_Dependency_List (DynamicVectorClass &file_list, bool recursive=true); - virtual bool Build_Texture_List (DynamicVectorClass &texture_file_list, bool recursive=true); - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Decals - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual void Create_Decal(DecalGeneratorClass * generator) { } - virtual void Delete_Decal(uint32 decal_id) { } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Attributes, Options, Properties, etc - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual MaterialInfoClass * Get_Material_Info(void) { return NULL; } - virtual void Set_User_Data(void *value, bool recursive = false) { User_Data = value; }; - virtual void * Get_User_Data() { return User_Data; }; - virtual int Get_Num_Snap_Points(void) { return 0; } - virtual void Get_Snap_Point(int index,Vector3 * set) { } -// virtual float Calculate_Texture_Reduction_Factor(float norm_screensize); -// virtual void Set_Texture_Reduction_Factor(float trf); - virtual float Get_Screen_Size(CameraClass &camera); - virtual void Scale(float scale) { }; - virtual void Scale(float scalex, float scaley, float scalez) { }; - virtual void Set_ObjectScale(float scale) { ObjectScale=scale;} //set's a scale factor that's factored into transform matrix. {ScaleFactor=scale; }; - const float Get_ObjectScale( void ) const { return ObjectScale; }; - void Set_ObjectColor(unsigned int color) { ObjectColor=color;} //the color that was used to modify the asset for player team color (for Generals). -MW - const unsigned int Get_ObjectColor( void ) const { return ObjectColor; }; - - virtual int Get_Sort_Level(void) const { return 0; /* SORT_LEVEL_NONE */ } - virtual void Set_Sort_Level(int level) { } - - virtual int Is_Really_Visible(void) { return ((Bits & IS_REALLY_VISIBLE) == IS_REALLY_VISIBLE); } - virtual int Is_Not_Hidden_At_All(void) { return ((Bits & IS_NOT_HIDDEN_AT_ALL) == IS_NOT_HIDDEN_AT_ALL); } - virtual int Is_Visible(void) const { return (Bits & IS_VISIBLE); } - virtual void Set_Visible(int onoff) { if (onoff) { Bits |= IS_VISIBLE; } else { Bits &= ~IS_VISIBLE; } } - -// The cheatSpy has been put on ice until later... perhaps the next patch? - M Lorenzen - // virtual int Is_VisibleWithCheatSpy(void) const { return ((Bits&=~0x80) & (IS_VISIBLE); } -// virtual void Set_VisibleWithCheatSpy(int onoff) { if (onoff) { Bits |= IS_VISIBLE|0x80; } else { Bits &= ~IS_VISIBLE; } } - - virtual int Is_Hidden(void) const { return !(Bits & IS_NOT_HIDDEN); } - virtual void Set_Hidden(int onoff) { if (onoff) { Bits &= ~IS_NOT_HIDDEN; } else { Bits |= IS_NOT_HIDDEN; } } - virtual int Is_Animation_Hidden(void) const { return !(Bits & IS_NOT_ANIMATION_HIDDEN); } - virtual void Set_Animation_Hidden(int onoff) { if (onoff) { Bits &= ~IS_NOT_ANIMATION_HIDDEN; } else { Bits |= IS_NOT_ANIMATION_HIDDEN; } } - virtual int Is_Force_Visible(void) const { return Bits & IS_FORCE_VISIBLE; } - virtual void Set_Force_Visible(int onoff) { if (onoff) { Bits |= IS_FORCE_VISIBLE; } else { Bits &= ~IS_FORCE_VISIBLE; } } - - virtual int Is_Translucent(void) const { return Bits & IS_TRANSLUCENT; } - virtual void Set_Translucent(int onoff) { if (onoff) { Bits |= IS_TRANSLUCENT; } else { Bits &= ~IS_TRANSLUCENT; } } - virtual int Is_Alpha(void) const { return Bits & IS_ALPHA; } - virtual void Set_Alpha(int onoff) { if (onoff) { Bits |= IS_ALPHA; } else { Bits &= ~IS_ALPHA; } } - virtual int Is_Additive(void) const { return Bits & IS_ADDITIVE; } - virtual void Set_Additive(int onoff) { if (onoff) { Bits |= IS_ADDITIVE; } else { Bits &= ~IS_ADDITIVE; } } - virtual int Get_Collision_Type(void) const { return (Bits & COLL_TYPE_MASK); } - virtual void Set_Collision_Type(int type) { Bits &= ~COLL_TYPE_MASK; Bits |= (type & COLL_TYPE_MASK) | COLL_TYPE_ALL; } - virtual bool Is_Complete(void) { return false; } - virtual bool Is_In_Scene(void) { return Scene != NULL; } - virtual float Get_Native_Screen_Size(void) const { return NativeScreenSize; } - virtual void Set_Native_Screen_Size(float screensize) { NativeScreenSize = screensize; } - - void Set_Sub_Objects_Match_LOD(int onoff) { if (onoff) { Bits |= SUBOBJS_MATCH_LOD; } else { Bits &= ~SUBOBJS_MATCH_LOD; } } - int Is_Sub_Objects_Match_LOD_Enabled(void) { return Bits & SUBOBJS_MATCH_LOD; } - - void Set_Sub_Object_Transforms_Dirty(bool onoff) { if (onoff) { Bits |= SUBOBJ_TRANSFORMS_DIRTY; } else { Bits &= ~SUBOBJ_TRANSFORMS_DIRTY; } } - bool Are_Sub_Object_Transforms_Dirty(void) { return (Bits & SUBOBJ_TRANSFORMS_DIRTY) != 0; } - - void Set_Ignore_LOD_Cost(bool onoff) { if (onoff) { Bits |= IGNORE_LOD_COST; } else { Bits &= ~IGNORE_LOD_COST; } } - bool Is_Ignoring_LOD_Cost(void) { return (Bits & IGNORE_LOD_COST) != 0; } - - void Set_Is_Self_Shadowed() { Bits|=IS_SELF_SHADOWED; } - void Unset_Is_Self_Shadowed() { Bits&=~IS_SELF_SHADOWED; } - int Is_Self_Shadowed() const { return (Bits&IS_SELF_SHADOWED); } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Persistant object save-load interface - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual const PersistFactoryClass & Get_Factory (void) const; - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - - // Application-specific render hook: - RenderHookClass * Get_Render_Hook(void) { return RenderHook; } - void Set_Render_Hook(RenderHookClass *hook) { if (RenderHook) delete RenderHook; RenderHook = hook; } - -protected: - - virtual void Add_Dependencies_To_List (DynamicVectorClass &file_list, bool textures_only = false); - - virtual void Update_Cached_Bounding_Volumes(void) const; - virtual void Update_Sub_Object_Bits(void); - - bool Bounding_Volumes_Valid(void) const { return (Bits & BOUNDING_VOLUMES_VALID) != 0; } - void Invalidate_Cached_Bounding_Volumes(void) const { Bits &= ~BOUNDING_VOLUMES_VALID; } - void Validate_Cached_Bounding_Volumes(void) const { Bits |= BOUNDING_VOLUMES_VALID; } - - enum - { - COLL_TYPE_MASK = 0x000000FF, - - IS_VISIBLE = 0x00000100, - IS_NOT_HIDDEN = 0x00000200, - IS_NOT_ANIMATION_HIDDEN = 0x00000400, - IS_FORCE_VISIBLE = 0x00000800, - BOUNDING_VOLUMES_VALID = 0x00002000, - IS_TRANSLUCENT = 0x00004000, // is additive or alpha blended on any poly - IGNORE_LOD_COST = 0x00008000, // used to define if we should ignore object from LOD calculations - SUBOBJS_MATCH_LOD = 0x00010000, // force sub-objects to have same LOD level - SUBOBJ_TRANSFORMS_DIRTY = 0x00020000, // my sub-objects need me to update their transform - IS_ALPHA = 0x00040000, // added for Generals so we can default these meshes not to cast shadows. -MW - IS_ADDITIVE = 0x00100000, //added for Generals so we quickly determine what type of blending is on the mesh. -MW - IS_SELF_SHADOWED = 0x00080000, // the mesh is self shadowed - IS_CHEATER = 0x00100000,// the new cheat spy code uses these bits, since nothing else now does - IS_REALLY_VISIBLE = IS_VISIBLE | IS_NOT_HIDDEN | IS_NOT_ANIMATION_HIDDEN, - IS_NOT_HIDDEN_AT_ALL = IS_NOT_HIDDEN | IS_NOT_ANIMATION_HIDDEN, - DEFAULT_BITS = COLL_TYPE_ALL | IS_NOT_HIDDEN | IS_NOT_ANIMATION_HIDDEN, - }; - - mutable unsigned long Bits; - Matrix3D Transform; - float ObjectScale; //user applied scaling factor inside Transform matrix. - unsigned int ObjectColor; //user applied coloring to the asset/prototype used to make this robj. - For Generals -MW - mutable SphereClass CachedBoundingSphere; - mutable AABoxClass CachedBoundingBox; - float NativeScreenSize; // The screen size at which the object was designed to be viewed (used in texture resizing). - mutable bool IsTransformIdentity; - - SceneClass * Scene; - RenderObjClass * Container; - void * User_Data; - - RenderHookClass * RenderHook; - - friend class SceneClass; - friend class RenderObjProxyClass; -}; - -WWINLINE const SphereClass & RenderObjClass::Get_Bounding_Sphere(void) const -{ - if (!(Bits & BOUNDING_VOLUMES_VALID)) { - Update_Cached_Bounding_Volumes(); - } - return CachedBoundingSphere; -} - -WWINLINE const AABoxClass & RenderObjClass::Get_Bounding_Box(void) const -{ - if (!(Bits & BOUNDING_VOLUMES_VALID)) { - Update_Cached_Bounding_Volumes(); - } - return CachedBoundingBox; -} - -/************************************************************************** - * Bound_Degrees -- Bounds a degree value between 0 and 360. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 09/22/1997 PWG : Created. * - *========================================================================*/ -WWINLINE float Bound_Degrees(float angle) -{ - while (angle > 359) angle -= 360; - while (angle < 0) angle += 360; - return angle; -} - -/*********************************************************************************************** - * RenderObjClass::Get_Transform -- returns the transform for the object * - * * - * If the transform is invalid (a container has been moved or animated) then the transform * - * will be recalculated. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/25/99 GTH : Created. * - *=============================================================================================*/ -WWINLINE const Matrix3D & RenderObjClass::Get_Transform(void) const -{ - Validate_Transform(); - return Transform; -} - -WWINLINE const Matrix3D & RenderObjClass::Get_Transform(bool &is_transform_identity) const -{ - Validate_Transform(); - is_transform_identity=IsTransformIdentity; - return Transform; -} - -WWINLINE bool RenderObjClass::Is_Transform_Identity() const -{ - Validate_Transform(); - return IsTransformIdentity; -} - -// Warning: Be sure to call this function only if the transform is known to be valid! -WWINLINE const Matrix3D & RenderObjClass::Get_Transform_No_Validity_Check(void) const -{ - return Transform; -} - -// Warning: Be sure to call this function only if the transform is known to be valid! -WWINLINE const Matrix3D & RenderObjClass::Get_Transform_No_Validity_Check(bool& is_transform_identity) const -{ - is_transform_identity=IsTransformIdentity; - return Transform; -} - -// Warning: Be sure to call this function only if the transform is known to be valid! -WWINLINE bool RenderObjClass::Is_Transform_Identity_No_Validity_Check() const -{ - return IsTransformIdentity; -} - - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ringobj.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ringobj.cpp deleted file mode 100644 index 7f61c168ad..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ringobj.cpp +++ /dev/null @@ -1,1650 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/ringobj.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/24/01 6:17p $* - * * - * $Revision:: 27 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RingRenderObjClass::RingRenderObjClass -- Constructor * - * RingRenderObjClass::RingRenderObjClass -- Constructor - init from a definition * - * RingRenderObjClass::RingRenderObjClass -- Copy constructor * - * RingRenderObjClass::~RingRenderObjClass -- destructor * - * RingRenderObjClass::operator -- assignment operator * - * RingRenderObjClass::Get_Num_Polys -- returns number of polygons * - * RingRenderObjClass::Get_Name -- returns name * - * RingRenderObjClass::Set_Name -- sets the name * - * RingRenderObjClass::Set_Color -- Sets the color of the Ring * - * RingRenderObjClass::Init_Ring_Render_System -- global initialization needed for Ring * - * RingRenderObjClass::Shutdown_Ring_Render_System -- cleanup Ring render system * - * RingRenderObjClass::Set_Ring_Display_Mask -- Sets global display mask for all Ringes * - * RingRenderObjClass::Get_Ring_Display_Mask -- returns the display mask * - * RingRenderObjClass::update_mesh_data -- Updates vertex positions, etc * - * RingRenderObjClass::render_Ring -- submits the Ring to the GERD * - * RingRenderObjClass::vis_render_Ring -- submits Ring to the GERD for VIS * - * RingRenderObjClass::RingRenderObjClass -- constructor * - * RingRenderObjClass::RingRenderObjClass -- Constructor - init from a definition * - * RingRenderObjClass::RingRenderObjClass -- copy constructor * - * RingRenderObjClass::RingRenderObjClass -- Constructor from a wwmath aaRing * - * RingRenderObjClass::operator -- assignment operator * - * RingRenderObjClass::Clone -- clones the Ring * - * RingRenderObjClass::Class_ID -- returns the class-id for AARing's * - * RingRenderObjClass::Render -- render this Ring * - * RingRenderObjClass::Special_Render -- special render this Ring (vis) * - * RingRenderObjClass::Set_Transform -- set the transform for this Ring * - * RingRenderObjClass::Set_Position -- Set the position of this Ring * - * RingRenderObjClass::update_cached_Ring -- update the world-space version of this Ring * - * RingRenderObjClass::Cast_Ray -- cast a ray against this Ring * - * RingRenderObjClass::Cast_AARing -- cast an AARing against this Ring * - * RingRenderObjClass::Cast_OBRing -- cast an OBRing against this Ring * - * RingRenderObjClass::Get_Obj_Space_Bounding_Sphere -- return the object-space bounding sper* - * RingRenderObjClass::Get_Obj_Space_Bounding_Box -- returns the obj-space bounding box * - * RingRenderObjClass::Scale -- scales ring uniformly. * - * RingRenderObjClass::Scale -- scales ring non-uniformly. * - * RingRenderObjClass::Update_Cached_Bounding_Volumes -- Updates world-space bounding volum * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "ringobj.h" -#include "w3d_util.h" -#include "wwdebug.h" -#include "vertmaterial.h" -#include "ww3d.h" -#include "chunkio.h" -#include "rinfo.h" -#include "coltest.h" -#include "inttest.h" -#include "matrix3.h" -#include "wwmath.h" -#include "assetmgr.h" -#include "wwstring.h" -#include "bound.h" -#include "camera.h" -#include "statistics.h" -#include "predlod.h" -#include "dx8wrapper.h" -#include "dx8indexbuffer.h" -#include "dx8vertexbuffer.h" -#include "sortingrenderer.h" -#include "Vector3i.h" -#include "visrasterizer.h" - - -static bool Ring_Array_Valid = false; - - -/** -** RingMeshClass -** A set of LODs of RingMeshes are re-used by all RingRenderObjClasses. -*/ -class RingMeshClass -{ -friend class RingRenderObjClass; - -public: - // Constructor - RingMeshClass(void); - RingMeshClass(float radius, int slices); - // Destructor - ~RingMeshClass(void); - - void Generate(float radius, int slices); - - int Get_Num_Polys(void) { return face_ct; }; - - void Scale (const Vector2 &inner_scale, const Vector2 &outer_scale); - void Set_Tiling (int count); - -private: - - void Free(void); - - float Radius; - int Slices; - int face_ct; //# of faces - - int TileCount; - Vector2 InnerScale; - Vector2 OuterScale; - - int Vertex_ct; // vertex count - Vector3 *vtx; // array of vertices - Vector2 *orig_vtx; // array of vertices representing a 'unit' ring - Vector3 *vtx_normal; // array of vertex normals - Vector2 *vtx_uv; // array of vertex uv coordinates - - TriIndex *tri_poly; // array of triangle polys, vertex indices (can be discard if switch to fan renderer) -}; - - -RingMeshClass RingMeshArray[RING_NUM_LOD]; -float RingLODCosts[RING_NUM_LOD + 1]; // RING_NUM_LOD doesn't include the null LOD - - - -/* -** RingRenderObjClass Implementation -*/ - - -/*********************************************************************************************** - * RingRenderObjClass::RingRenderObjClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -RingRenderObjClass::RingRenderObjClass(void) - : anim_time (0.0F), - IsAnimating(false), - LODBias(1.0f), - CurrentLOD(RING_NUM_LOD), // RING_NUM_LOD does not include the null LOD - AnimDuration (0.0F), - RingMaterial (NULL), - RingTexture (NULL), - Color (0.75F,0.75F,0.75F), - InnerScale (1, 1), - OuterScale (1, 1), - Alpha (1.0F), - Flags(0), - TextureTileCount(5), - ObjSpaceCenter (0, 0, 0), - ObjSpaceExtent (1, 1, 1), - InnerExtent (0.5F, 0.5F), - OuterExtent (1.0F, 1.0F) -{ - Generate_Shared_Mesh_Arrays (); - - memset(Name,0,sizeof(Name)); - - Init_Material () ; - - // So that the object is ready for use after construction, we will - // complete its initialization by initializing its value array - // according to a screen area of 1. - calculate_value_array(1.0f, Value); -} - -/*********************************************************************************************** - * RingRenderObjClass::RingRenderObjClass -- Constructor - init from a definition * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -RingRenderObjClass::RingRenderObjClass(const W3dRingStruct & def) - : anim_time (0.0F), - IsAnimating(false), - LODBias(1.0f), - CurrentLOD(RING_NUM_LOD), // RING_NUM_LOD does not include the null LOD - AnimDuration (0.0F), - RingMaterial (NULL), - RingTexture (NULL), - Color (0.75F,0.75F,0.75F), - InnerScale (1, 1), - OuterScale (1, 1), - Alpha (1.0F), - Flags(0), - TextureTileCount(5), - ObjSpaceCenter (0, 0, 0), - ObjSpaceExtent (1, 1, 1), - InnerExtent (0.5F, 0.5F), - OuterExtent (1.0F, 1.0F) -{ - Generate_Shared_Mesh_Arrays (); - Init_Material (); - - // - // Initialize from the defintion - // - Set_Name(def.Name); - Set_Local_Center_Extent ( Vector3 (def.Center.X, def.Center.Y, def.Center.Z), - Vector3 (def.Extent.X, def.Extent.Y, def.Extent.Z)); - if (def.TextureName[0] != 0) { - RingTexture = WW3DAssetManager::Get_Instance ()->Get_Texture (def.TextureName); - } - - // So that the object is ready for use after construction, we will - // complete its initialization by initializing its value array - // according to a screen area of 1. - calculate_value_array(1.0f, Value); -} - - -/*********************************************************************************************** - * RingRenderObjClass::RingRenderObjClass -- Copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -RingRenderObjClass::RingRenderObjClass(const RingRenderObjClass & src) - : anim_time (0.0F), - IsAnimating(false), - LODBias(1.0f), - CurrentLOD(RING_NUM_LOD), // RING_NUM_LOD does not include the null LOD - AnimDuration (0.0F), - RingMaterial (NULL), - RingTexture (NULL), - Color (0.75F,0.75F,0.75F), - InnerScale (1, 1), - OuterScale (1, 1), - Alpha (1.0F), - Flags(0), - TextureTileCount(5), - ObjSpaceCenter (0, 0, 0), - ObjSpaceExtent (1, 1, 1), - InnerExtent (0.5F, 0.5F), - OuterExtent (1.0F, 1.0F) -{ - Generate_Shared_Mesh_Arrays (); - Init_Material (); - - *this = src; - - // So that the object is ready for use after construction, we will - // complete its initialization by initializing its value array - // according to a screen area of 1. - calculate_value_array(1.0f, Value); -} - - -/*********************************************************************************************** - * RingRenderObjClass::~RingRenderObjClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/7/2001 gth : Created. * - *=============================================================================================*/ -RingRenderObjClass::~RingRenderObjClass() -{ - REF_PTR_RELEASE(RingMaterial); - REF_PTR_RELEASE(RingTexture); -} // destructor - - -/*********************************************************************************************** - * RingRenderObjClass::operator -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -RingRenderObjClass & RingRenderObjClass::operator = (const RingRenderObjClass & that) -{ - if (this != &that) { - RenderObjClass::operator = (that); - Set_Name(that.Get_Name()); - Color = that.Color; - Alpha = that.Alpha; - InnerScale = that.InnerScale; - OuterScale = that.OuterScale; - Flags = that.Flags; - RingShader = that.RingShader; - CachedBox = that.CachedBox; - anim_time = that.anim_time; - AnimDuration = that.AnimDuration; - ObjSpaceCenter = that.ObjSpaceCenter; - ObjSpaceExtent = that.ObjSpaceExtent; - ColorChannel = that.ColorChannel; - AlphaChannel = that.AlphaChannel; - InnerScaleChannel = that.InnerScaleChannel; - OuterScaleChannel = that.OuterScaleChannel; - InnerExtent = that.InnerExtent; - OuterExtent = that.OuterExtent; - TextureTileCount = that.TextureTileCount; - - Set_Texture (that.RingTexture); - } - - return *this; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Generate_Shared_Mesh_Arrays -- Generates mesh LOD arrays. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/08/00 pds : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Generate_Shared_Mesh_Arrays (void) -{ - // Generate shared Mesh Arrays - if (!Ring_Array_Valid) { - - float size = RING_LOWEST_LOD; - float step = (RING_HIGHEST_LOD - RING_LOWEST_LOD); - step /= RING_NUM_LOD; - - // For NULL LOD set Cost to a small nonzero amount to avoid divisions by zero. - RingLODCosts[0] = 0.000001f; - for(int i=0; i < RING_NUM_LOD; i++) { - - RingMeshArray[i].Generate(1.0f, size); - RingLODCosts[i + 1] = RingMeshArray[i].Get_Num_Polys(); - - size+=step; - } - - Ring_Array_Valid = true; - } - - return ; -} - - -// This is used both by Prepare_LOD and Calculate_Cost_Value_Arrays. -void RingRenderObjClass::calculate_value_array(float screen_area, float *values) const -{ - values[0] = AT_MIN_LOD; - for (int lod = 1; lod <= RING_NUM_LOD; lod++) { - float polycount = RingLODCosts[lod]; - float benefit_factor = 1 - (0.5f / (polycount * polycount)); - values[lod] = (benefit_factor * screen_area * LODBias) / polycount; - } - values[RING_NUM_LOD + 1] = AT_MAX_LOD; // Post-inc value will flag max LOD. -} - - -/*********************************************************************************************** - * RingRenderObjClass::Init_Material -- Sets up the material and default shader for the Ring.* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/08/00 pds : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Init_Material (void) -{ - REF_PTR_RELEASE (RingMaterial); - - RingMaterial = NEW_REF(VertexMaterialClass,()); - RingMaterial->Set_Ambient(0,0,0); - RingMaterial->Set_Diffuse(0,0,0); - RingMaterial->Set_Specular(0,0,0); - RingMaterial->Set_Emissive(1,1,1); - RingMaterial->Set_Opacity(0.25f); - RingMaterial->Set_Shininess(0.0f); - - // Texturing, zbuffer, primary gradient, alpha blending - RingShader = ShaderClass::_PresetAlphaShader; - -} // Init_Material - - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Num_Polys -- returns number of polygons * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -int RingRenderObjClass::Get_Num_Polys(void) const -{ - return RingLODCosts[CurrentLOD]; -} - -/*********************************************************************************************** - * RingRenderObjClass::Set_Texture * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Set_Texture(TextureClass *tf) -{ - REF_PTR_SET(RingTexture,tf); -} - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Name -- returns name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -const char * RingRenderObjClass::Get_Name(void) const -{ - return Name; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Set_Name -- sets the name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Set_Name(const char * name) -{ - WWASSERT(name != NULL); - WWASSERT(strlen(name) < 2*W3D_NAME_LEN); - strcpy(Name,name); -} - -/*********************************************************************************************** - * RingRenderObjClass::render_ring -- submits the box to the GERD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::render_ring(RenderInfoClass & rinfo,const Vector3 & center,const Vector3 & extent) -{ - // Should never get here with NULL LOD - if (CurrentLOD == 0) { - WWASSERT(0); - return; - } - - RingMeshClass & ring = RingMeshArray[CurrentLOD - 1]; - - if (RingTexture) { - RingShader.Set_Texturing (ShaderClass::TEXTURING_ENABLE); - } else { - RingShader.Set_Texturing (ShaderClass::TEXTURING_DISABLE); - } - DX8Wrapper::Set_Shader(RingShader); - DX8Wrapper::Set_Texture(0,RingTexture); - DX8Wrapper::Set_Material(RingMaterial); - - // Enable sorting if the primitive is translucent, alpha testing is not enabled, and sorting is enabled globally. - const bool sort = (RingShader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO) && (RingShader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE) && (WW3D::Is_Sorting_Enabled()); - const unsigned int buffer_type = sort ? BUFFER_TYPE_DYNAMIC_SORTING : BUFFER_TYPE_DYNAMIC_DX8; - - DynamicVBAccessClass vb(buffer_type, dynamic_fvf_type, ring.Vertex_ct); - { - DynamicVBAccessClass::WriteLockClass Lock(&vb); - VertexFormatXYZNDUV2 *vb = Lock.Get_Formatted_Vertex_Array(); - - // - // set up the vertex color+alpha - // - unsigned color; - if (RingShader.Get_Dst_Blend_Func () == ShaderClass::DSTBLEND_ONE) { - color = DX8Wrapper::Convert_Color(Alpha * Color,1.0f); - } else { - color = DX8Wrapper::Convert_Color(Color,Alpha); - } - - for (int i=0; ix = ring.vtx[i].X; - vb->y = ring.vtx[i].Y; - vb->z = ring.vtx[i].Z; - - vb->nx = ring.vtx_normal[i].X; // may not need this! - vb->ny = ring.vtx_normal[i].Y; - vb->nz = ring.vtx_normal[i].Z; - - vb->diffuse = color; - - if (RingTexture) { - vb->u1 = ring.vtx_uv[i].X; - vb->v1 = ring.vtx_uv[i].Y; - } - vb++; - } - } - - DynamicIBAccessClass ib(buffer_type, ring.face_ct * 3); - { - DynamicIBAccessClass::WriteLockClass Lock(&ib); - unsigned short *mem=Lock.Get_Index_Array(); - for (int i=0; iProcess_Reduction(); - - Matrix3D temp = Transform; - - // Do Time Based Animation - animate (); - - // - // Scale the inner and outer parts of the ring. - // - Vector2 inner_scale (InnerExtent.X * InnerScale.X, InnerExtent.Y * InnerScale.Y); - Vector2 outer_scale (OuterExtent.X * OuterScale.X, OuterExtent.Y * OuterScale.Y); - RingMeshArray[CurrentLOD - 1].Scale(inner_scale, outer_scale); - - // - // Make sure this mesh uses the correct UV tiling - // - if (RingTexture != NULL) { - RingMeshArray[CurrentLOD - 1].Set_Tiling (TextureTileCount); - } - - // - // Should we force the ring to be camera aligned? - // (this will cause the ring to be parallel to the screen) - // - if (Flags & USE_CAMERA_ALIGN) { - Vector3 obj_position; - Vector3 camera_z_vector; - - rinfo.Camera.Get_Transform().Get_Z_Vector(&camera_z_vector); - Transform.Get_Translation(&obj_position); - - Matrix3D temp; - temp.Look_At(obj_position, obj_position + camera_z_vector, 0.0f); - DX8Wrapper::Set_Transform(D3DTS_WORLD, temp); - } else { - DX8Wrapper::Set_Transform(D3DTS_WORLD, Transform); - } - - // - // Pass the geometry on to DX8 - // - render_ring (rinfo, ObjSpaceCenter, ObjSpaceExtent); - } -} // Render - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Default_Color - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -Vector3 RingRenderObjClass::Get_Default_Color(void) const -{ - Vector3 value; - - if (ColorChannel.Get_Key_Count () > 0) { - value = ColorChannel.Get_Key (0).Get_Value (); - } else { - value = Color; - } - - return value; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Default_Alpha - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -float RingRenderObjClass::Get_Default_Alpha(void) const -{ - float value; - - if (AlphaChannel.Get_Key_Count () > 0) { - value = AlphaChannel.Get_Key (0).Get_Value (); - } else { - value = Alpha; - } - - return value; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Default_Inner_Scale - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -Vector2 RingRenderObjClass::Get_Default_Inner_Scale(void) const -{ - Vector2 value; - - if (InnerScaleChannel.Get_Key_Count () > 0) { - value = InnerScaleChannel.Get_Key (0).Get_Value (); - } else { - value = InnerScale; - } - - return value; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Default_Outer_Scale - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -Vector2 RingRenderObjClass::Get_Default_Outer_Scale(void) const -{ - Vector2 value; - - if (OuterScaleChannel.Get_Key_Count () > 0) { - value = OuterScaleChannel.Get_Key (0).Get_Value (); - } else { - value = OuterScale; - } - - return value; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Special_Render -- special render this box (vis) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * -, * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Special_Render(SpecialRenderInfoClass & rinfo) -{ - Matrix3D temp(1); - temp.Translate(Transform.Get_Translation()); - - if (rinfo.RenderType == SpecialRenderInfoClass::RENDER_VIS) { - WWASSERT(rinfo.VisRasterizer != NULL); - rinfo.VisRasterizer->Set_Model_Transform(temp); - vis_render_ring(rinfo,ObjSpaceCenter,ObjSpaceExtent); - } -} - - -/*********************************************************************************************** - * RingRenderObjClass::Set_Transform -- set the transform for this box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Set_Transform(const Matrix3D &m) -{ - RenderObjClass::Set_Transform(m); - update_cached_box(); -} - - -/*********************************************************************************************** - * RingRenderObjClass::Set_Position -- Set the position of this box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Set_Position(const Vector3 &v) -{ - RenderObjClass::Set_Position(v); - update_cached_box(); -} - - -/*********************************************************************************************** - * RingRenderObjClass::update_cached_box -- update the world-space version of this box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::update_cached_box(void) -{ - CachedBox.Center = Transform.Get_Translation() + ObjSpaceCenter; - CachedBox.Extent = ObjSpaceExtent; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Obj_Space_Bounding_Ring -- return the object-space bounding sphe * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - sphere.Center = ObjSpaceCenter; - sphere.Radius = ObjSpaceExtent.Length(); -} - - -/*********************************************************************************************** - * RingRenderObjClass::Get_Obj_Space_Bounding_Box -- returns the obj-space bounding box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - box.Center = ObjSpaceCenter; - box.Extent = ObjSpaceExtent; -} - - -void RingRenderObjClass::Prepare_LOD(CameraClass &camera) -{ - if (Is_Not_Hidden_At_All() == false) { - return; - } - - calculate_value_array(Get_Screen_Size(camera), Value); - - PredictiveLODOptimizerClass::Add_Object(this); -} - -void RingRenderObjClass::Increment_LOD(void) -{ - if (CurrentLOD < RING_NUM_LOD) CurrentLOD++; -} - -void RingRenderObjClass::Decrement_LOD(void) -{ - if (CurrentLOD > 0) CurrentLOD--; -} - -float RingRenderObjClass::Get_Cost(void) const -{ - return Get_Num_Polys(); // Currently cost == polys -} - -float RingRenderObjClass::Get_Value(void) const -{ - return Value[CurrentLOD]; -} - -float RingRenderObjClass::Get_Post_Increment_Value(void) const -{ - return Value[CurrentLOD + 1]; -} - -void RingRenderObjClass::Set_LOD_Level(int lod) -{ - CurrentLOD = Bound(lod, 0, RING_NUM_LOD); // RING_NUM_LOD doesn't include the null LOD -} - -int RingRenderObjClass::Get_LOD_Level(void) const -{ - return CurrentLOD; -} - -int RingRenderObjClass::Get_LOD_Count(void) const -{ - return RING_NUM_LOD + 1; // RING_NUM_LOD doesn't include the null LOD -} - -int RingRenderObjClass::Calculate_Cost_Value_Arrays(float screen_area, float *values, float *costs) const -{ - calculate_value_array(screen_area, values); - for (int lod = 0; lod <= RING_NUM_LOD; lod++) { - costs[lod] = RingLODCosts[lod]; - } - - // We currently don't support max screen size or minimum LOD clamping for ring objects - return 0; -} - - -/*********************************************************************************************** - * RingRenderObjClass::Scale -- scales ring uniformly. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/01/02 NH : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Scale(float scale) -{ - if (scale == 1.0f) return; - - // Scale default values - InnerScale *= scale; - OuterScale *= scale; - - // Loop over all keys in inner and outer scale channel and scale values. - int i; - int inner_count = InnerScaleChannel.Get_Key_Count(); - for (i = 0; i < inner_count; i++) { - const PrimitiveAnimationChannelClass::KeyClass &key = InnerScaleChannel.Get_Key(i); - InnerScaleChannel.Set_Key_Value(i, key.Get_Value() * scale); - } - int outer_count = OuterScaleChannel.Get_Key_Count(); - for (i = 0; i < outer_count; i++) { - const PrimitiveAnimationChannelClass::KeyClass &key = OuterScaleChannel.Get_Key(i); - OuterScaleChannel.Set_Key_Value(i, key.Get_Value() * scale); - } -} - - -/*********************************************************************************************** - * RingRenderObjClass::Scale -- scales ring non-uniformly. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/01/02 NH : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Scale(float scalex, float scaley, float scalez) -{ - // Scale default values - InnerScale.X *= scalex; - InnerScale.Y *= scaley; - OuterScale.X *= scalex; - OuterScale.Y *= scaley; - - // Loop over all keys in inner and outer scale channel and scale values. - int i; - int inner_count = InnerScaleChannel.Get_Key_Count(); - for (i = 0; i < inner_count; i++) { - const PrimitiveAnimationChannelClass::KeyClass &key = InnerScaleChannel.Get_Key(i); - Vector2 key_val = key.Get_Value(); - key_val.X *= scalex; - key_val.Y *= scaley; - InnerScaleChannel.Set_Key_Value(i, key_val); - } - int outer_count = OuterScaleChannel.Get_Key_Count(); - for (i = 0; i < outer_count; i++) { - const PrimitiveAnimationChannelClass::KeyClass &key = OuterScaleChannel.Get_Key(i); - Vector2 key_val = key.Get_Value(); - key_val.X *= scalex; - key_val.Y *= scaley; - OuterScaleChannel.Set_Key_Value(i, key_val); - } -} - - -/*********************************************************************************************** - * RingRenderObjClass::Update_On_Visibilty -- Either starts or stops the animation based on vis* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/04/00 pds : Created. * - *=============================================================================================*/ -void RingRenderObjClass::Update_On_Visibilty(void) -{ - // Simply start or stop the animation based on - // the visibility state of the primitive. - if (Is_Not_Hidden_At_All () && Is_Animating () == false) { - Start_Animating (); - } else if ((Is_Not_Hidden_At_All () == false) && Is_Animating ()) { - Stop_Animating (); - } - - return ; -} - -/*********************************************************************************************** - * RingRenderObjClass::animate -- Update Current Display state * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void RingRenderObjClass::animate() -{ - if (Is_Animating ()) { - - if ( ColorChannel.Get_Key_Count () > 0 || - AlphaChannel.Get_Key_Count () > 0 || - InnerScaleChannel.Get_Key_Count () > 0 || - OuterScaleChannel.Get_Key_Count () > 0) - { - // - // Convert from milliseconds to seconds and normalize the time - // - if (AnimDuration > 0) { - float frametime = WW3D::Get_Frame_Time(); - frametime = (frametime * 0.001F) / AnimDuration; - anim_time += frametime; - } else { - anim_time = 1.0F; - } - WWASSERT (anim_time >= 0.0F); - - if ((Flags & USE_ANIMATION_LOOP) && anim_time > 1.0F) { - anim_time -= 1.0F; - } - - if (ColorChannel.Get_Key_Count () > 0) { - Color = ColorChannel.Evaluate (anim_time); - } - - if (AlphaChannel.Get_Key_Count () > 0) { - Alpha = AlphaChannel.Evaluate (anim_time); - } - - if (InnerScaleChannel.Get_Key_Count () > 0) { - InnerScale = InnerScaleChannel.Evaluate (anim_time); - } - - if (OuterScaleChannel.Get_Key_Count () > 0) { - OuterScale = OuterScaleChannel.Evaluate (anim_time); - ObjSpaceExtent.X = OuterScale.X * OuterExtent.X; - ObjSpaceExtent.Y = OuterScale.Y * OuterExtent.Y; - ObjSpaceExtent.Z = 0; - Update_Cached_Bounding_Volumes (); - } - } - } - - return ; -} // animate - - -/* -** RingLoaderClass Implementation -*/ -PrototypeClass * RingLoaderClass::Load_W3D(ChunkLoadClass & cload) -{ - RingPrototypeClass *prototype = W3DNEW RingPrototypeClass (); - prototype->Load (cload); - return prototype; -} - -/* -** RingPrototypeClass Implementation -*/ -RingPrototypeClass::RingPrototypeClass (void) -{ - ::memset (&Definition, 0, sizeof (Definition)); - return ; -} - -RingPrototypeClass::RingPrototypeClass(RingRenderObjClass *ring) -{ - ::memset (&Definition, 0, sizeof (Definition)); - ::strcpy (Definition.Name, ring->Get_Name ()); - - Definition.AnimDuration = ring->AnimDuration; - Definition.Attributes = ring->Get_Flags (); - Definition.DefaultAlpha = ring->Get_Default_Alpha (); - Definition.DefaultInnerScale = ring->Get_Default_Inner_Scale (); - Definition.DefaultOuterScale = ring->Get_Default_Outer_Scale (); - Definition.TextureTileCount = ring->Get_Texture_Tiling (); - - Definition.InnerExtent = ring->Get_Inner_Extent (); - Definition.OuterExtent = ring->Get_Outer_Extent (); - - Vector3 def_color = ring->Get_Default_Color (); - W3dUtilityClass::Convert_Vector (def_color, &Definition.DefaultColor); - - W3dUtilityClass::Convert_Vector (ring->Get_Box ().Center, &Definition.Center); - W3dUtilityClass::Convert_Vector (ring->Get_Box ().Extent, &Definition.Extent); - W3dUtilityClass::Convert_Shader (ring->RingShader, &Definition.Shader); - - // - // Determine the texture name for this ring - // - if (ring->RingTexture != NULL) { - StringClass name = ring->RingTexture->Get_Full_Path(); - const char *filename = ::strrchr (name, '\\'); - if (filename != NULL) { - filename ++; - } else { - filename = name; - } - - ::strcpy (Definition.TextureName, filename); - } - - // - // Save the animateable channels - // - ColorChannel = ring->Peek_Color_Channel (); - AlphaChannel = ring->Peek_Alpha_Channel (); - InnerScaleChannel = ring->Peek_Inner_Scale_Channel (); - OuterScaleChannel = ring->Peek_Outer_Scale_Channel (); - return ; -} - -RingPrototypeClass::~RingPrototypeClass (void) -{ - return ; -} - -const char * RingPrototypeClass::Get_Name(void) const -{ - return Definition.Name; -} - -int RingPrototypeClass::Get_Class_ID(void) const -{ - return RenderObjClass::CLASSID_RING; -} - -enum -{ - CHUNKID_RING_DEF = 1, - CHUNKID_COLOR_CHANNEL, - CHUNKID_ALPHA_CHANNEL, - CHUNKID_INNER_SCALE_CHANNEL, - CHUNKID_OUTER_SCALE_CHANNEL -}; - -bool RingPrototypeClass::Load (ChunkLoadClass &cload) -{ - ColorChannel.Reset (); - AlphaChannel.Reset (); - InnerScaleChannel.Reset (); - OuterScaleChannel.Reset (); - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_RING_DEF: - cload.Read (&Definition, sizeof (Definition)); - break; - - case CHUNKID_COLOR_CHANNEL: - ColorChannel.Load (cload); - break; - - case CHUNKID_ALPHA_CHANNEL: - AlphaChannel.Load (cload); - break; - - case CHUNKID_INNER_SCALE_CHANNEL: - InnerScaleChannel.Load (cload); - break; - - case CHUNKID_OUTER_SCALE_CHANNEL: - OuterScaleChannel.Load (cload); - break; - } - - cload.Close_Chunk (); - } - - return true; -} - -bool RingPrototypeClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (W3D_CHUNK_RING); - - csave.Begin_Chunk (CHUNKID_RING_DEF); - csave.Write (&Definition, sizeof (Definition)); - csave.End_Chunk (); - - if (ColorChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_COLOR_CHANNEL); - ColorChannel.Save (csave); - csave.End_Chunk (); - } - - if (AlphaChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_ALPHA_CHANNEL); - AlphaChannel.Save (csave); - csave.End_Chunk (); - } - - if (InnerScaleChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_INNER_SCALE_CHANNEL); - InnerScaleChannel.Save (csave); - csave.End_Chunk (); - } - - if (OuterScaleChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_OUTER_SCALE_CHANNEL); - OuterScaleChannel.Save (csave); - csave.End_Chunk (); - } - - csave.End_Chunk (); - return true; -} - -RenderObjClass * RingPrototypeClass::Create(void) -{ - // - // Create the new render object - // - RingRenderObjClass *ring = W3DNEW RingRenderObjClass (Definition); - - // - // Configure the ring - // - W3dUtilityClass::Convert_Shader (Definition.Shader, &ring->RingShader); - if (WW3DAssetManager::Get_Instance()->Get_Activate_Fog_On_Load()) { - ring->RingShader.Enable_Fog ("RingPrototypeClass"); - ring->RingShader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - } - W3dUtilityClass::Convert_Vector (Definition.DefaultColor, &ring->Color); - ring->InnerScale = Definition.DefaultInnerScale; - ring->OuterScale = Definition.DefaultOuterScale; - ring->Set_Animation_Duration (Definition.AnimDuration); - ring->Alpha = Definition.DefaultAlpha; - ring->Set_Flags (Definition.Attributes); - ring->Set_Inner_Extent (Definition.InnerExtent); - ring->Set_Outer_Extent (Definition.OuterExtent); - ring->Set_Texture_Tiling (Definition.TextureTileCount); - - // - // Initialize the render object with the keyframe arrays - // - ring->Set_Color_Channel (ColorChannel); - ring->Set_Alpha_Channel (AlphaChannel); - ring->Set_Inner_Scale_Channel (InnerScaleChannel); - ring->Set_Outer_Scale_Channel (OuterScaleChannel); - return ring; -} - -/* -** Global instance of the box loader -*/ -RingLoaderClass _RingLoader; - - -// -// Vertices are ordered as such -// center, followed by outer ring -// -/*********************************************************************************************** - * RingMeshClass::RingMeshClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -RingMeshClass::RingMeshClass(float radius, int slices): -Radius(radius), -Slices(slices), -Vertex_ct(0), // 1 vertex minimum, for center -vtx(NULL), -orig_vtx(NULL), -vtx_normal(NULL), -vtx_uv(NULL), -face_ct(0), -tri_poly(NULL), -TileCount (5), -InnerScale (1.0F, 1.0F), -OuterScale (1.0F, 1.0F) -{ - Generate(radius, slices); -} - -/*********************************************************************************************** - * RingMeshClass::RingMeshClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -RingMeshClass::RingMeshClass(void): -Radius(0.0f), -Slices(0), -Vertex_ct(0), // 1 vertex minimum, for center -vtx(NULL), -orig_vtx(NULL), -vtx_normal(NULL), -vtx_uv(NULL), -face_ct(0), -tri_poly(NULL), -TileCount (5), -InnerScale (1.0F, 1.0F), -OuterScale (1.0F, 1.0F) -{ -} // empty ringmesh Constructor - - -void RingMeshClass::Set_Tiling (int count) -{ - if (TileCount != count) { - TileCount = count; - - // - // Calculate the increment 'u' increment value (as in UV). - // - float u_inc = ((float)TileCount) / ((float)(Slices)); - float u_value = 0.0F; - - // - // Reassign the UVs - // - for (int index = 0; index < Vertex_ct; index += 2) { - vtx_uv[index].Set (u_value, 0.0F); - vtx_uv[index + 1].Set (u_value, 1.0F); - u_value += u_inc; - } - } - - return ; -} - - -void RingMeshClass::Scale (const Vector2 &inner_scale, const Vector2 &outer_scale) -{ - bool do_inner = (inner_scale != InnerScale); - bool do_outer = (outer_scale != OuterScale); - - // - // Only scale the inner ring if necessary - // - if (do_inner) { - - for (int index = 0; index < Vertex_ct; index += 2) { - vtx[index].X = orig_vtx[index].X * inner_scale.X; - vtx[index].Y = orig_vtx[index].Y * inner_scale.Y; - vtx[index].Z = 0; - } - - InnerScale = inner_scale; - } - - // - // Only scale the outer ring if necessary - // - if (do_outer) { - - for (int index = 1; index < Vertex_ct; index += 2) { - vtx[index].X = orig_vtx[index].X * outer_scale.X; - vtx[index].Y = orig_vtx[index].Y * outer_scale.Y; - vtx[index].Z = 0; - } - - OuterScale = outer_scale; - } - - return ; -} - - -/*********************************************************************************************** - * RingMeshClass::Generate - Create Ring Geometry * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void RingMeshClass::Generate(float radius, int slices) -{ - Free (); - - Slices = slices; - Radius = radius; - - face_ct = (Slices * 2); - Vertex_ct = (Slices * 2) + 2; - - vtx = W3DNEWARRAY Vector3[Vertex_ct]; - orig_vtx = W3DNEWARRAY Vector2[Vertex_ct]; - vtx_normal = W3DNEWARRAY Vector3[Vertex_ct]; - vtx_uv = W3DNEWARRAY Vector2[Vertex_ct]; - tri_poly = W3DNEWARRAY TriIndex[face_ct]; - - // - // Generate vertices, normals, and uv's - // - float angle_inc = DEG_TO_RADF (360) / ((float)Slices); - float u_inc = ((float)TileCount) / ((float)(Slices)); - float u_value = 0.0F; - float angle = 0; - int index = 0; - - for (index = 0; index < Vertex_ct; index += 2) { - - float x_pos = -WWMath::Sin (angle); - float y_pos = WWMath::Cos (angle); - - // - // Place the inner index - // - vtx[index].X = orig_vtx[index].X = x_pos; - vtx[index].Y = orig_vtx[index].Y = y_pos; - vtx[index].Z = 0; - - // - // Place the outer index - // - vtx[index+1].X = orig_vtx[index+1].X = x_pos; - vtx[index+1].Y = orig_vtx[index+1].Y = y_pos; - vtx[index+1].Z = 0; - - // - // Normals will just point straight up from the ring... - // - vtx_normal[index].Set (0, 0, 1); - vtx_normal[index + 1].Set (0, 0, 1); - - // - // Assign the UVs - // - vtx_uv[index].Set (u_value, 0.0F); - vtx_uv[index + 1].Set (u_value, 1.0F); - u_value += u_inc; - - angle += angle_inc; - } - - // - // Make the triangle strip... - // - for (index = 0; index < face_ct; index ++) { - tri_poly[index].I = index; - tri_poly[index].J = index+1; - tri_poly[index].K = index+2; - } - - return ; -} - - -/*********************************************************************************************** - * RingMeshClass::~RingMeshClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -RingMeshClass::~RingMeshClass(void) -{ - Free(); -} - -/*********************************************************************************************** - * RingMeshClass::Free - Release Memory, that the ring mesh is using * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void RingMeshClass::Free(void) -{ - - if (vtx) delete vtx; - if (orig_vtx) delete orig_vtx; - if (vtx_normal) delete vtx_normal; - if (vtx_uv) delete vtx_uv; - if (tri_poly) delete tri_poly; - - vtx = NULL; - orig_vtx = NULL; - vtx_normal = NULL; - vtx_uv = NULL; - tri_poly = NULL; - -} // Free - -// EOF - ringobj.cpp diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ringobj.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ringobj.h deleted file mode 100644 index 7085e6c7ba..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ringobj.h +++ /dev/null @@ -1,370 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/ringobj.h $* - * * - * Author:: Jason Andersen * - * * - * $Modtime:: 3/23/01 7:02p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef RINGOBJ_H -#define RINGOBJ_H - -#include "always.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "shader.h" -#include "proto.h" -#include "obbox.h" -#include "quat.h" -#include "vector3.h" -#include "vector2.h" -#include "prim_anim.h" - -class VertexMaterialClass; - -typedef LERPAnimationChannelClass RingColorChannelClass; -typedef LERPAnimationChannelClass RingAlphaChannelClass; -typedef LERPAnimationChannelClass RingScaleChannelClass; - - -/** -** W3dRingStruct -** This structure is used to define a ring object in the W3D file format. -*/ -struct W3dRingStruct -{ - uint32 Version; // file format version - uint32 Attributes; // box attributes (above #define's) - char Name[2*W3D_NAME_LEN]; // name is in the form . - - W3dVectorStruct Center; // center of the box - W3dVectorStruct Extent; // extent of the box - - float AnimDuration; // Animation time (in seconds) - - W3dVectorStruct DefaultColor; - float DefaultAlpha; - Vector2 DefaultInnerScale; - Vector2 DefaultOuterScale; - - Vector2 InnerExtent; - Vector2 OuterExtent; - - char TextureName[2*W3D_NAME_LEN]; - W3dShaderStruct Shader; - int TextureTileCount; - - // - // Note this structure is followed by a series of - // W3dRingKeyArrayStruct structures which define the - // variable set of keyframes for each channel -}; - -// Note: RING_NUM_LOD does not include the NULL LOD. -#define RING_NUM_LOD (20) -#define RING_LOWEST_LOD (10) -#define RING_HIGHEST_LOD (50) - -/* -** RingRenderObjClass: Procedurally generated render rings -** -*/ -class RingRenderObjClass : public RenderObjClass -{ - -public: - - // These are bit masks, so they should enum 1,2,4,8,10,20,40 etc... - enum RingFlags { - USE_CAMERA_ALIGN = 0x00000001, - USE_ANIMATION_LOOP= 0x00000002, - }; - - RingRenderObjClass(void); - RingRenderObjClass(const W3dRingStruct & def); - RingRenderObjClass(const RingRenderObjClass & src); - RingRenderObjClass & operator = (const RingRenderObjClass &); - ~RingRenderObjClass(void); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const; - virtual void Render(RenderInfoClass & rinfo); - virtual void Special_Render(SpecialRenderInfoClass & rinfo); - virtual void Set_Transform(const Matrix3D &m); - virtual void Set_Position(const Vector3 &v); - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - - virtual void Prepare_LOD(CameraClass &camera); - virtual void Increment_LOD(void); - virtual void Decrement_LOD(void); - virtual float Get_Cost(void) const; - virtual float Get_Value(void) const; - virtual float Get_Post_Increment_Value(void) const; - virtual void Set_LOD_Level(int lod); - virtual int Get_LOD_Level(void) const; - virtual int Get_LOD_Count(void) const; - virtual void Set_LOD_Bias(float bias) { LODBias = MAX(bias, 0.0f); } - virtual int Calculate_Cost_Value_Arrays(float screen_area, float *values, float *costs) const; - - virtual void Scale(float scale); - virtual void Scale(float scalex, float scaley, float scalez); - - virtual void Set_Hidden(int onoff) { RenderObjClass::Set_Hidden (onoff); Update_On_Visibilty (); } - virtual void Set_Visible(int onoff) { RenderObjClass::Set_Visible (onoff); Update_On_Visibilty (); } - virtual void Set_Animation_Hidden(int onoff) { RenderObjClass::Set_Animation_Hidden (onoff); Update_On_Visibilty (); } - virtual void Set_Force_Visible(int onoff) { RenderObjClass::Set_Force_Visible (onoff); Update_On_Visibilty (); } - - const AABoxClass & Get_Box(void); - - virtual int Get_Num_Polys(void) const; - virtual const char *Get_Name(void) const; - virtual void Set_Name(const char * name); - - unsigned int Get_Flags(void) {return Flags;} - void Set_Flags(unsigned int flags) { Flags = flags; } - void Set_Flag(unsigned int flag, bool onoff) { Flags &= (~flag); if (onoff) Flags |= flag; } - - // Animation access - bool Is_Animating (void) { return IsAnimating; } - void Start_Animating (void) { IsAnimating = true; anim_time = 0; } - void Stop_Animating (void) { IsAnimating = false; anim_time = 0; } - - // Texture tiling access - int Get_Texture_Tiling (void) const { return TextureTileCount; } - void Set_Texture_Tiling (int count) { TextureTileCount = count; } - - // Current state access - void Set_Color(const Vector3 & color) { Color = color; } - void Set_Alpha(float alpha) { Alpha = alpha; } - void Set_Inner_Scale(const Vector2 & scale) { InnerScale = scale; } - void Set_Outer_Scale(const Vector2 & scale) { OuterScale = scale; } - - const Vector3 & Get_Color(void) const { return Color; } - float Get_Alpha(void) const { return Alpha; } - const Vector2 & Get_Inner_Scale(void) const { return InnerScale; } - const Vector2 & Get_Outer_Scale(void) const { return OuterScale; } - - Vector3 Get_Default_Color(void) const; - float Get_Default_Alpha(void) const; - Vector2 Get_Default_Inner_Scale(void) const; - Vector2 Get_Default_Outer_Scale(void) const; - - // Size/position methods - const Vector2 & Get_Inner_Extent (void) const { return InnerExtent; } - const Vector2 & Get_Outer_Extent (void) const { return OuterExtent; } - void Set_Inner_Extent (const Vector2 &extent); - void Set_Outer_Extent (const Vector2 &extent); - void Set_Local_Center_Extent(const Vector3 & center,const Vector3 & extent); - void Set_Local_Min_Max(const Vector3 & min,const Vector3 & max); - - // Texture access - void Set_Texture(TextureClass *tf); - TextureClass * Peek_Texture(void) { return RingTexture; } - ShaderClass & Get_Shader(void) { return RingShader; } - void Set_Shader(ShaderClass &shader) { RingShader = shader; } - - // Animation Control - float Get_Animation_Duration(void) const { return AnimDuration; } - void Set_Animation_Duration(float time) { AnimDuration = time; Restart_Animation(); } - void Restart_Animation (void) { anim_time = 0; } - - // Animatable channel access - RingColorChannelClass & Get_Color_Channel (void) { return ColorChannel; } - const RingColorChannelClass & Peek_Color_Channel (void) { return ColorChannel; } - - RingAlphaChannelClass & Get_Alpha_Channel (void) { return AlphaChannel; } - const RingAlphaChannelClass & Peek_Alpha_Channel (void) { return AlphaChannel; } - - RingScaleChannelClass & Get_Inner_Scale_Channel (void) { return InnerScaleChannel; } - const RingScaleChannelClass & Peek_Inner_Scale_Channel (void) { return InnerScaleChannel; } - - RingScaleChannelClass & Get_Outer_Scale_Channel (void) { return OuterScaleChannel; } - const RingScaleChannelClass & Peek_Outer_Scale_Channel (void) { return OuterScaleChannel; } - - void Set_Color_Channel (const RingColorChannelClass &data) { ColorChannel = data; } - void Set_Alpha_Channel (const RingAlphaChannelClass &data) { AlphaChannel = data; } - void Set_Inner_Scale_Channel (const RingScaleChannelClass &data) { InnerScaleChannel = data; } - void Set_Outer_Scale_Channel (const RingScaleChannelClass &data) { OuterScaleChannel = data; } - -protected: - - virtual void update_cached_box(void); - void Update_On_Visibilty(void); - - // Initialization stuff - void Init_Material (void); - static void Generate_Shared_Mesh_Arrays (void); - - - // Animation Stuff - void animate(void); // animation update function - float anim_time; // what time in seconds are we in the animation - float AnimDuration; - bool IsAnimating; - - // LOD Stuff - void calculate_value_array(float screen_area, float *values) const; - float LODBias; - int CurrentLOD; - float Value[RING_NUM_LOD + 2];// Value array needs # of LODs + 1 (RING_NUM_LOD doesn't include null LOD) - - RingColorChannelClass ColorChannel; - RingAlphaChannelClass AlphaChannel; - RingScaleChannelClass InnerScaleChannel; - RingScaleChannelClass OuterScaleChannel; - - void update_mesh_data(const Vector3 & center,const Vector3 & extent); - void render_ring(RenderInfoClass & rinfo,const Vector3 & center,const Vector3 & extent); - void vis_render_ring(SpecialRenderInfoClass & rinfo,const Vector3 & center,const Vector3 & extent); - - char Name[2*W3D_NAME_LEN]; - Vector3 ObjSpaceCenter; - Vector3 ObjSpaceExtent; - - Vector2 InnerExtent; - Vector2 OuterExtent; - - int TextureTileCount; - - // Current State - Vector3 Color; - float Alpha; - Vector2 InnerScale; - Vector2 OuterScale; - - // Flags - unsigned int Flags; - - VertexMaterialClass *RingMaterial; - ShaderClass RingShader; - TextureClass *RingTexture; - - AABoxClass CachedBox; - - // Friend classes - friend class RingPrototypeClass; -}; - -inline void RingRenderObjClass::Set_Inner_Extent (const Vector2 &extent) -{ - InnerExtent = extent; -} - -inline void RingRenderObjClass::Set_Outer_Extent (const Vector2 &extent) -{ - OuterExtent = extent; - ObjSpaceExtent.X = extent.X; - ObjSpaceExtent.Y = extent.Y; - ObjSpaceExtent.Z = 0; - update_cached_box(); -} - -inline void RingRenderObjClass::Set_Local_Center_Extent(const Vector3 & center,const Vector3 & extent) -{ - ObjSpaceCenter = center; - ObjSpaceExtent = extent; - update_cached_box(); -} - -inline void RingRenderObjClass::Set_Local_Min_Max(const Vector3 & min,const Vector3 & max) -{ - ObjSpaceCenter = (max + min) / 2.0f; - ObjSpaceExtent = (max - min) / 2.0f; - update_cached_box(); -} - -inline const AABoxClass & RingRenderObjClass::Get_Box(void) -{ - Validate_Transform(); - update_cached_box(); - return CachedBox; -} - -/* -** Loader for rings -*/ -class RingLoaderClass : public PrototypeLoaderClass -{ -public: - virtual int Chunk_Type (void) { return W3D_CHUNK_RING; } - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload); -}; - -/* -** Prototype for Ring objects -*/ -class RingPrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(RingPrototypeClass) - -public: - RingPrototypeClass (void); - RingPrototypeClass (RingRenderObjClass *ring); - - virtual const char * Get_Name(void) const; - virtual int Get_Class_ID(void) const; - virtual RenderObjClass * Create(void); - virtual void DeleteSelf() { delete this; } - - bool Load (ChunkLoadClass &cload); - bool Save (ChunkSaveClass &csave); - -protected: - ~RingPrototypeClass (void); - -private: - W3dRingStruct Definition; - - RingColorChannelClass ColorChannel; - RingAlphaChannelClass AlphaChannel; - RingScaleChannelClass InnerScaleChannel; - RingScaleChannelClass OuterScaleChannel; -}; - -/* -** Instance of the loader which the asset manager installs -*/ -extern RingLoaderClass _RingLoader; - - -#endif // RINGOBJ_H - -// EOF - ringobj,h - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/robjlist.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/robjlist.h deleted file mode 100644 index 54b49a72d2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/robjlist.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/robjlist.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef ROBJLIST_H -#define ROBJLIST_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef MULTILIST_H -#include "multilist.h" -#endif - -#ifndef WWDEBUG_H -#include "wwdebug.h" -#endif - -class RenderObjClass; - -typedef RefMultiListClass RefRenderObjListClass; -typedef RefMultiListIterator RefRenderObjListIterator; - -typedef MultiListClass NonRefRenderObjListClass; -typedef MultiListIterator NonRefRenderObjListIterator; - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/segline.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/segline.cpp deleted file mode 100644 index 413d3e86cf..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/segline.cpp +++ /dev/null @@ -1,591 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /VSS_Sync/ww3d2/segline.cpp $* - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 23 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "segline.h" -#include "ww3d.h" -#include "rinfo.h" -#include "predlod.h" -#include "v3_rnd.h" -#include "texture.h" -#include "coltest.h" -#include "w3d_file.h" -#include "texture.h" -#include "dx8wrapper.h" -#include "vp.h" -#include "Vector3i.h" -#include "sortingrenderer.h" - -static SegLineRendererClass _LineRenderer; - - -/* -** SegmentedLineClass implementation: -*/ - -SegmentedLineClass::SegmentedLineClass(void) : - MaxSubdivisionLevels(0), - NormalizedScreenArea(0.0f) -{ -} - -SegmentedLineClass::SegmentedLineClass(const SegmentedLineClass & src) : - MaxSubdivisionLevels(src.MaxSubdivisionLevels), - NormalizedScreenArea(src.NormalizedScreenArea), - PointLocations(src.PointLocations), - LineRenderer(src.LineRenderer) -{ -} - -SegmentedLineClass & SegmentedLineClass::operator = (const SegmentedLineClass &that) -{ - RenderObjClass::operator = (that); - - if (this != &that) { - - MaxSubdivisionLevels = that.MaxSubdivisionLevels; - NormalizedScreenArea = that.NormalizedScreenArea; - PointLocations = that.PointLocations; - LineRenderer = that.LineRenderer; - } - - return * this; -} - -SegmentedLineClass::~SegmentedLineClass(void) -{ -} - -void SegmentedLineClass::Reset_Line(void) -{ - LineRenderer.Reset_Line(); -} - - -// These are segment points, and include the start and end point of the -// entire line. Therefore there must be at least two. -void SegmentedLineClass::Set_Points(unsigned int num_points, Vector3 *locs) -{ - if (num_points < 2 || !locs) { - WWASSERT(0); - return; - } - - PointLocations.Delete_All(); - for (unsigned int i=0; iProcess_Reduction(); - - unsigned int sort_level = SORT_LEVEL_NONE; - - if (!WW3D::Is_Sorting_Enabled()) - sort_level=Get_Shader().Guess_Sort_Level(); - - if (WW3D::Are_Static_Sort_Lists_Enabled() && sort_level!=SORT_LEVEL_NONE) { - - WW3D::Add_To_Static_Sort_List(this, sort_level); - - } else - Render_Seg_Line(rinfo); -} - -void SegmentedLineClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - // Get object-space bounding box and create bounding sphere from it - AABoxClass box; - Get_Obj_Space_Bounding_Box(box); - - // Create object-space bounding sphere from the bounding box: - sphere.Center = box.Center; - sphere.Radius = box.Extent.Length(); -} - -void SegmentedLineClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - unsigned int num_points = PointLocations.Count(); - - // Line must have at least two points to be valid - - if (num_points >= 2) { - - // Find object-space axis-aligned bounding box - Vector3 max_coords; - Vector3 min_coords; - unsigned int i; - - // We create two bounding boxes; one from the points, and if we have random noise - // subdivision we create another one from the midpoints and factor the noise amplitude - // into the second box, and then combine the two. - - // First bounding box: - max_coords = PointLocations[0]; - min_coords = PointLocations[0]; - for (i = 1; i < num_points; i++) { - max_coords.Update_Max(PointLocations[i]); - min_coords.Update_Min(PointLocations[i]); - } - // Enlarge bounding box by half the width - float enlarge_factor = LineRenderer.Get_Width() * 0.5f; - Vector3 enlarge_offset; - enlarge_offset.Set(enlarge_factor, enlarge_factor, enlarge_factor); - max_coords += enlarge_offset; - min_coords -= enlarge_offset; - - if (MaxSubdivisionLevels > 0) { - // Second bounding box: - Vector3 max_coords2; - Vector3 min_coords2; - Vector3 midpoint = (PointLocations[0] + PointLocations[1]) * 0.5f; - max_coords2 = midpoint; - min_coords2 = midpoint; - for (i = 1; i < num_points - 1; i++) { - midpoint = (PointLocations[i] + PointLocations[i + 1]) * 0.5f; - max_coords2.Update_Max(midpoint); - min_coords2.Update_Min(midpoint); - } - - // We ignore the actual number of subdivision levels: we multiply the random noise - // amplitude by 2, which is the limit as the number of subdivision levels goes to - // infinity. - enlarge_factor += (2 * LineRenderer.Get_Noise_Amplitude()); - enlarge_offset.Set(enlarge_factor, enlarge_factor, enlarge_factor); - max_coords2 += enlarge_offset; - min_coords2 -= enlarge_offset; - - // Combine the two: - max_coords.Update_Max(max_coords2); - min_coords.Update_Min(min_coords2); - } - - box.Init_Min_Max(min_coords, max_coords); - - } else { - // Invalid line - return something - box.Init(Vector3(0,0,0),Vector3(1,1,1)); - } -} - -void SegmentedLineClass::Prepare_LOD(CameraClass &camera) -{ - // Find the maximum screen dimension of the object in pixels - NormalizedScreenArea = Get_Screen_Size(camera); - -// // Find and set texture reduction factor -// Set_Texture_Reduction_Factor(Calculate_Texture_Reduction_Factor(NormalizedScreenArea)); - - // Ensure subdivision level is legal - unsigned int lvl = LineRenderer.Get_Current_Subdivision_Level(); - lvl = MIN(lvl, MaxSubdivisionLevels); - LineRenderer.Set_Current_Subdivision_Level(lvl); - - // Prepare LOD processing if the line has subdivision enabled: - if (MaxSubdivisionLevels > 0) { - // Add myself to the LOD optimizer: - PredictiveLODOptimizerClass::Add_Object(this); - } else { - // Not added to optimizer, need to add cost - PredictiveLODOptimizerClass::Add_Cost(Get_Cost()); - } -} - -void SegmentedLineClass::Increment_LOD(void) -{ - unsigned int lvl = LineRenderer.Get_Current_Subdivision_Level(); - - lvl = MIN(lvl+1,MaxSubdivisionLevels); - - LineRenderer.Set_Current_Subdivision_Level(lvl); -} - -void SegmentedLineClass::Decrement_LOD(void) -{ - int lvl = LineRenderer.Get_Current_Subdivision_Level(); - if (lvl == 0) return; - LineRenderer.Set_Current_Subdivision_Level(lvl-1); -} - -float SegmentedLineClass::Get_Cost(void) const -{ - return Get_Num_Polys(); -} - -float SegmentedLineClass::Get_Value(void) const -{ - // If we are at the minimum LOD, we must return AT_MIN_LOD. - if (LineRenderer.Get_Current_Subdivision_Level() == 0) { - return AT_MIN_LOD; - } else { - float polycount = (float)Get_Num_Polys(); - float benefit_factor = 1.0f - (0.5f / (polycount * polycount)); - return (benefit_factor * NormalizedScreenArea) / Get_Cost(); - } -} - -float SegmentedLineClass::Get_Post_Increment_Value(void) const -{ - // If we are at the maximum LOD, we must return AT_MIN_LOD. - if (LineRenderer.Get_Current_Subdivision_Level() == MaxSubdivisionLevels) { - return AT_MAX_LOD; - } else { - // Assumption: each subdivision level doubles polycount - float polycount = 2.0f * (float)Get_Num_Polys(); - float benefit_factor = 1.0f - (0.5f / (polycount * polycount)); - // Assumption: Cost() == polycount - return (benefit_factor * NormalizedScreenArea) / polycount; - } -} - -void SegmentedLineClass::Set_LOD_Level(int lod) -{ - lod = MAX(0, lod); - lod = MIN(lod, (int)MaxSubdivisionLevels); - - LineRenderer.Set_Current_Subdivision_Level((unsigned int)lod); -} - -int SegmentedLineClass::Get_LOD_Level(void) const -{ - return (int) LineRenderer.Get_Current_Subdivision_Level(); -} - -int SegmentedLineClass::Get_LOD_Count(void) const -{ - return (int)MaxSubdivisionLevels; -} -/* -void SegmentedLineClass::Set_Texture_Reduction_Factor(float trf) -{ - if (LineRenderer.Peek_Texture()) LineRenderer.Peek_Texture()->Set_Reduction_Factor(trf); -}*/ - - - -void SegmentedLineClass::Render_Seg_Line(RenderInfoClass & rinfo) -{ - // Line must have at least two points to be valid - if (PointLocations.Count() < 2) return; - - SphereClass bounding_sphere; - Get_Obj_Space_Bounding_Sphere(bounding_sphere); - - LineRenderer.Render( - rinfo, - Transform, - PointLocations.Count(), - &(PointLocations[0]), - bounding_sphere - ); -} - - -bool SegmentedLineClass::Cast_Ray(RayCollisionTestClass & raytest) -{ - if ((Get_Collision_Type() & raytest.CollisionType) == 0) return false; - - bool retval = false; - - // - // Check each line segment against the ray - // - float fraction = 1.0F; - for (uint32 index = 1; index < (unsigned int)PointLocations.Count(); index ++) - { -#ifdef ALLOW_TEMPORARIES - Vector3 curr_start = Transform * PointLocations[index-1]; - Vector3 curr_end = Transform * PointLocations[index]; - LineSegClass line_seg (curr_start, curr_end); -#else - Vector3 curr[2]; - Transform.mulVector3Array(&PointLocations[index-1], curr, 2); - LineSegClass line_seg(curr[0], curr[1]); -#endif - - Vector3 p0; - Vector3 p1; - if (raytest.Ray.Find_Intersection (line_seg, &p0, &fraction, &p1, NULL)) { - - // - // Determine if the ray was close enough to this line to be - // considered intersecting - // - float dist = (p0 - p1).Length (); - if (dist <= LineRenderer.Get_Width() && fraction >= 0 && fraction < raytest.Result->Fraction) { - //if (dist <= Width && fraction < raytest.Result->Fraction) { - retval = true; - break; - } - } - } - - // - // Fill in the raytest structure if we were successfull - // - if (retval) { - raytest.Result->Fraction = fraction; - raytest.Result->SurfaceType = SURFACE_TYPE_DEFAULT; - raytest.CollidedRenderObj = this; - } - - return retval; -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/segline.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/segline.h deleted file mode 100644 index cda5703123..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/segline.h +++ /dev/null @@ -1,182 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/segline.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 6/13/01 4:09p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SEGLINE_H -#define SEGLINE_H - -#include "rendobj.h" -#include "shader.h" -#include "simplevec.h" -#include "seglinerenderer.h" - - -class TextureClass; - -/* -** SegmentedLineClass -- a render object for rendering thick segmented lines. -*/ -class SegmentedLineClass : public RenderObjClass -{ - public: - - SegmentedLineClass(void); - SegmentedLineClass(const SegmentedLineClass & src); - SegmentedLineClass & operator = (const SegmentedLineClass &that); - virtual ~SegmentedLineClass(void); - - void Reset_Line(void); - - /* - ** SegmentedLineClass interface: - */ - - // These are segment points, and include the start and end point of the - // entire line. Therefore there must be at least two. - void Set_Points(unsigned int num_points, Vector3 *locs); - int Get_Num_Points(void); - - // Set object-space location for a given point. - // NOTE: If given position beyond end of point list, do nothing. - void Set_Point_Location(unsigned int point_idx, const Vector3 &location); - - // Get object-space location for a given point. - void Get_Point_Location(unsigned int point_idx, Vector3 &loc); - - // Modify the line by adding and removing points - void Add_Point(const Vector3 & location); - void Delete_Point(unsigned int point_idx); - - // Get/set global properties (which affect all line segments) - TextureClass * Get_Texture(void); - ShaderClass Get_Shader(void); - - float Get_Width(void); - void Get_Color(Vector3 &color); - float Get_Opacity(void); - float Get_Noise_Amplitude(void); - float Get_Merge_Abort_Factor(void); - unsigned int Get_Subdivision_Levels(void); - SegLineRendererClass::TextureMapMode Get_Texture_Mapping_Mode(void); - float Get_Texture_Tile_Factor(void); - Vector2 Get_UV_Offset_Rate(void); - int Is_Merge_Intersections(void); - int Is_Freeze_Random(void); - int Is_Sorting_Disabled(void); - int Are_End_Caps_Enabled(void); - - void Set_Texture(TextureClass *texture); - void Set_Shader(ShaderClass shader); - void Set_Width(float width); - void Set_Color(const Vector3 &color); - void Set_Opacity(float opacity); - void Set_Noise_Amplitude(float amplitude); - void Set_Merge_Abort_Factor(float factor); - void Set_Subdivision_Levels(unsigned int levels); - void Set_Texture_Mapping_Mode(SegLineRendererClass::TextureMapMode mode); - // WARNING! Do NOT set the tile factor to be too high (should be less than 8) or negative - //performance impact will result! - void Set_Texture_Tile_Factor(float factor); - void Set_UV_Offset_Rate(const Vector2 &rate); - void Set_Merge_Intersections(int onoff); - void Set_Freeze_Random(int onoff); - void Set_Disable_Sorting(int onoff); - void Set_End_Caps(int onoff); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Cloning and Identification - ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const { return CLASSID_SEGLINE; } - virtual int Get_Num_Polys(void) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Rendering - ///////////////////////////////////////////////////////////////////////////// - virtual void Render(RenderInfoClass & rinfo); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Bounding Volumes - ///////////////////////////////////////////////////////////////////////////// - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Predictive LOD - ///////////////////////////////////////////////////////////////////////////// - virtual void Prepare_LOD(CameraClass &camera); - virtual void Increment_LOD(void); - virtual void Decrement_LOD(void); - virtual float Get_Cost(void) const; - virtual float Get_Value(void) const; - virtual float Get_Post_Increment_Value(void) const; - virtual void Set_LOD_Level(int lod); - virtual int Get_LOD_Level(void) const; - virtual int Get_LOD_Count(void) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Attributes, Options, Properties, etc - ///////////////////////////////////////////////////////////////////////////// -// virtual void Set_Texture_Reduction_Factor(float trf); - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Collision Detection - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual bool Cast_Ray(RayCollisionTestClass & raytest); - - protected: - - void Render_Seg_Line(RenderInfoClass & rinfo); - - private: - - // Subdivision properties - unsigned int MaxSubdivisionLevels; - - // Normalized screen area - used for LOD purposes - float NormalizedScreenArea; - - // Per-point location array - SimpleDynVecClass PointLocations; - - // LineRenderer, contains most of the line settings. - SegLineRendererClass LineRenderer; -}; - -#endif // SEGLINE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp deleted file mode 100644 index 4ddf6f7970..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.cpp +++ /dev/null @@ -1,1231 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/seglinerenderer.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 5 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if 1 - -#include "seglinerenderer.h" -#include "ww3d.h" -#include "rinfo.h" -#include "dx8wrapper.h" -#include "sortingrenderer.h" -#include "vp.h" -#include "Vector3i.h" -#include "RANDOM.H" -#include "v3_rnd.h" -#include "meshgeometry.h" - - -/* We have chunking logic which handles N segments at a time. To simplify the subdivision logic, -** we will ensure that N is a power of two and that N >= 2^MAX_SEGLINE_SUBDIV_LEVELS, so that the -** subdivision logic can be inside the chunking loop. -*/ - -#if MAX_SEGLINE_SUBDIV_LEVELS > 7 -#define SEGLINE_CHUNK_SIZE (1 << MAX_SEGLINE_SUBDIV_LEVELS) -#else -#define SEGLINE_CHUNK_SIZE (128) -#endif - -#define MAX_SEGLINE_POINT_BUFFER_SIZE (1 + SEGLINE_CHUNK_SIZE) -// This macro depends on the assumption that each line segment is two polys. -#define MAX_SEGLINE_POLY_BUFFER_SIZE (SEGLINE_CHUNK_SIZE * 2) - - - - -SegLineRendererClass::SegLineRendererClass(void) : - Texture(NULL), - Shader(ShaderClass::_PresetAdditiveSpriteShader), - Width(0.0f), - Color(Vector3(1,1,1)), - Opacity(1.0f), - SubdivisionLevel(0), - NoiseAmplitude(0.0f), - MergeAbortFactor(1.5f), - TextureTileFactor(1.0f), - LastUsedSyncTime(WW3D::Get_Sync_Time()), - CurrentUVOffset(0.0f,0.0f), - UVOffsetDeltaPerMS(0.0f, 0.0f), - Bits(DEFAULT_BITS) -{ - -} - -SegLineRendererClass::SegLineRendererClass(const SegLineRendererClass & that) : - Texture(NULL), - Shader(ShaderClass::_PresetAdditiveSpriteShader), - Width(0.0f), - Color(Vector3(1,1,1)), - Opacity(1.0f), - SubdivisionLevel(0), - NoiseAmplitude(0.0f), - MergeAbortFactor(1.5f), - TextureTileFactor(1.0f), - LastUsedSyncTime(that.LastUsedSyncTime), - CurrentUVOffset(0.0f,0.0f), - UVOffsetDeltaPerMS(0.0f, 0.0f), - Bits(DEFAULT_BITS) -{ - *this = that; -} - -SegLineRendererClass & SegLineRendererClass::operator = (const SegLineRendererClass & that) -{ - if (this != &that) { - REF_PTR_SET(Texture,that.Texture); - Shader = that.Shader; - Width = that.Width; - Color = that.Color; - Opacity = that.Opacity; - SubdivisionLevel = that.SubdivisionLevel; - NoiseAmplitude = that.NoiseAmplitude; - MergeAbortFactor = that.MergeAbortFactor; - TextureTileFactor = that.TextureTileFactor; - LastUsedSyncTime = that.LastUsedSyncTime; - CurrentUVOffset = that.CurrentUVOffset; - UVOffsetDeltaPerMS = that.UVOffsetDeltaPerMS; - Bits = that.Bits; - } - return *this; -} - -SegLineRendererClass::~SegLineRendererClass(void) -{ - REF_PTR_RELEASE(Texture); -} - -void SegLineRendererClass::Init(const W3dEmitterLinePropertiesStruct & props) -{ - // translate the flags - Set_Merge_Intersections(props.Flags & W3D_ELINE_MERGE_INTERSECTIONS); - Set_Freeze_Random(props.Flags & W3D_ELINE_FREEZE_RANDOM); - Set_Disable_Sorting(props.Flags & W3D_ELINE_DISABLE_SORTING); - Set_End_Caps(props.Flags & W3D_ELINE_END_CAPS); - - int texture_mode = ((props.Flags & W3D_ELINE_TEXTURE_MAP_MODE_MASK) >> W3D_ELINE_TEXTURE_MAP_MODE_OFFSET); - switch (texture_mode) - { - case W3D_ELINE_UNIFORM_WIDTH_TEXTURE_MAP: - Set_Texture_Mapping_Mode(UNIFORM_WIDTH_TEXTURE_MAP); - break; - case W3D_ELINE_UNIFORM_LENGTH_TEXTURE_MAP: - Set_Texture_Mapping_Mode(UNIFORM_LENGTH_TEXTURE_MAP); - break; - case W3D_ELINE_TILED_TEXTURE_MAP: - Set_Texture_Mapping_Mode(TILED_TEXTURE_MAP); - break; - }; - - // install all other settings - Set_Current_Subdivision_Level(props.SubdivisionLevel); - Set_Noise_Amplitude(props.NoiseAmplitude); - Set_Merge_Abort_Factor(props.MergeAbortFactor); - Set_Texture_Tile_Factor(props.TextureTileFactor); - Set_UV_Offset_Rate(Vector2(props.UPerSec,props.VPerSec)); -} - - -void SegLineRendererClass::Set_Texture(TextureClass *texture) -{ - REF_PTR_SET(Texture,texture); -} - -TextureClass * SegLineRendererClass::Get_Texture(void) const -{ - if (Texture != NULL) { - Texture->Add_Ref(); - } - return Texture; -} - -void SegLineRendererClass::Set_Current_UV_Offset(const Vector2 & offset) -{ - CurrentUVOffset = offset; -} - -void SegLineRendererClass::Set_Texture_Tile_Factor(float factor) -{ - if (factor > 50.0f) { ///@todo: I raised this number and didn't see much difference on our min-spec. -MW - factor = 50.0f; - WWDEBUG_SAY(("Texture Tile Factor too large in SegLineRendererClass!\r\n")); - } else { - factor = MAX(factor, 0.0f); - } - TextureTileFactor = factor; -} - -void SegLineRendererClass::Reset_Line(void) -{ - LastUsedSyncTime = WW3D::Get_Sync_Time(); - CurrentUVOffset.Set(0.0f,0.0f); -} - - - -void SegLineRendererClass::Render -( - RenderInfoClass & rinfo, - const Matrix3D & transform, - unsigned int num_points, - Vector3 * points, - const SphereClass & obj_sphere -) -{ - Matrix4x4 view; - DX8Wrapper::Get_Transform(D3DTS_VIEW,view); - - Matrix4x4 identity(true); - DX8Wrapper::Set_Transform(D3DTS_WORLD,identity); - DX8Wrapper::Set_Transform(D3DTS_VIEW,identity); - - /* - ** Handle texture UV offset animation (done once for entire line). - */ - unsigned int delta = WW3D::Get_Sync_Time() - LastUsedSyncTime; - float del = (float)delta; - Vector2 uv_offset = CurrentUVOffset + UVOffsetDeltaPerMS * del; - - // ensure offsets are in [0, 1] range: - uv_offset.X = uv_offset.X - floorf(uv_offset.X); - uv_offset.Y = uv_offset.Y - floorf(uv_offset.Y); - - // Update state - CurrentUVOffset = uv_offset; - LastUsedSyncTime = WW3D::Get_Sync_Time(); - - // Used later - TextureMapMode map_mode = Get_Texture_Mapping_Mode(); - - /* - ** Process line geometry: - */ - - // This has been tweaked to produce empirically good results. - const float parallel_factor = 0.9f; - - // We reduce the chunk size to take account of subdivision levels (so that the # of points - // after subdivision will be no higher than the allowed maximum). We know this will not reduce - // the chunk size below 2, since the chunk size must be at least two to the power of the - // maximum allowable number of subdivisions. The plus 1 is because #points = #segments + 1. - unsigned int chunk_size = (SEGLINE_CHUNK_SIZE >> SubdivisionLevel) + 1; - if (chunk_size > num_points) chunk_size = num_points; - - // Chunk through the points (we increment by chunk_size - 1 because the last point of this - // chunk must be reused as the first point of the next chunk. This is also the reason we stop - // when chidx = NumPoints - 1: the last point has already been processed in the previous - // iteration so we don't need another one). - for (unsigned int chidx = 0; chidx < num_points - 1; chidx += (chunk_size - 1)) { - unsigned int point_cnt = num_points - chidx; - point_cnt = MIN(point_cnt, chunk_size); - - // We use these different loop indices (which loop INSIDE a chunk) to improve readability: - unsigned int pidx; // Point index - unsigned int sidx; // Segment index - unsigned int iidx; // Intersection index - - - /* - ** Transform points in chunk from objectspace to eyespace: - */ - - Vector3 xformed_pts[MAX_SEGLINE_POINT_BUFFER_SIZE]; - - Matrix3D view2( view[0].X,view[0].Y,view[0].Z,view[0].W, - view[1].X,view[1].Y,view[1].Z,view[1].W, - view[2].X,view[2].Y,view[2].Z,view[2].W); - -#ifdef ALLOW_TEMPORARIES - Matrix3D modelview=view2*transform; -#else - Matrix3D modelview; - modelview.mul(view2, transform); -#endif - - VectorProcessorClass::Transform(&xformed_pts[0], - &points[chidx], modelview, point_cnt); - - - /* - ** Prepare v parameter per point - used for texture mapping (esp. tiled mapping mode) - */ - - float base_tex_v[MAX_SEGLINE_POINT_BUFFER_SIZE]; - float u_values[2]; - switch (map_mode) { - case UNIFORM_WIDTH_TEXTURE_MAP: - for (pidx = 0; pidx < point_cnt; pidx++) { - // All 0 - base_tex_v[pidx] = 0.0f; - } - u_values[0] = 0.0f; - u_values[1] = 1.0f; - break; - case UNIFORM_LENGTH_TEXTURE_MAP: - for (pidx = 0; pidx < point_cnt; pidx++) { - // Increasing V - base_tex_v[pidx] = (float)(pidx + chidx) * TextureTileFactor; - } - u_values[0] = 0.0f; - u_values[1] = 0.0f; - break; - case TILED_TEXTURE_MAP: - for (pidx = 0; pidx < point_cnt; pidx++) { - // Increasing V - base_tex_v[pidx] = (float)(pidx + chidx) * TextureTileFactor; - } - u_values[0] = 0.0f; - u_values[1] = 1.0f; - break; - } - - - /* - ** Fractal noise recursive subdivision: - ** We find the midpoint for each section, apply a random offset, and recurse. We also find - ** the average V coordinate of the endpoints which is the midpoint V (for tiled texture - ** mapping). - */ - - Vector3 xformed_subdiv_pts[MAX_SEGLINE_POINT_BUFFER_SIZE]; - float subdiv_tex_v[MAX_SEGLINE_POINT_BUFFER_SIZE]; - unsigned int sub_point_cnt; - - subdivision_util(point_cnt, xformed_pts, base_tex_v, &sub_point_cnt, xformed_subdiv_pts, subdiv_tex_v); - - // Start using subdivided points from now on - Vector3 *points = xformed_subdiv_pts; - float *tex_v = subdiv_tex_v; - point_cnt = sub_point_cnt; - - - /* - ** Calculate line segment edge planes: - */ - - // For each line segment find the two silhouette planes from eyepoint to the line segment - // cylinder. To simplify we do not find the tangent planes but intersect the cylinder with a - // plane passing through its axis and perpendicular to the eye vector, find the edges of the - // resulting rectangle, and create planes through these edges and the eyepoint. - // Note that these planes are represented as a single normal rather than a normal and a - // distance; this is because they pass through the origin (eyepoint) so their distance is - // always zero. - - // Since the line has thickness, each segment has two edges. We name these 'top' and - // 'bottom' - note however that the top/bottom distinction does not relate to screen - // up/down and remains consistent throughout the segmented line. - enum SegmentEdge { - FIRST_EDGE = 0, // For loop conditions - TOP_EDGE = 0, // Top Edge - BOTTOM_EDGE = 1, // Bottom Edge - MAX_EDGE = 1, // For loop conditions - NUM_EDGES = 2 // For array allocations - }; - - bool switch_edges = false; - - // We have dummy segments for "before the first point" and "after the last point" - in these - // segments the top and bottom edge are the same - they are a perpendicular plane defined by - // the endpoint vertices. This is so we can merge intersections properly for the first and - // last points. - - struct LineSegment { - Vector3 StartPlane; - Vector3 EdgePlane[NUM_EDGES]; - }; - - // # segments = numpoints + 1 (numpoints - 1, plus two dummy segments) - LineSegment segment[MAX_SEGLINE_POINT_BUFFER_SIZE + 1]; - - // Intersections. This has data for two edges (top or bottom) intersecting. - struct LineSegmentIntersection { - unsigned int PointCount; // How many points does this intersection represent - unsigned int NextSegmentID; // ID of segment after this intersection - Vector3 Direction; // Calculated intersection direction line - Vector3 Point; // Averaged 3D point on the line which this represents - float TexV; // Averaged texture V coordinate of points - bool Fold; // Does the line fold over at this intersection? - bool Parallel; // Edges at this intersection are parallel (or almost-) - }; - - // Used to calculate the edge planes - float radius = Width * 0.5f; - - // The number of intersections is the number of points minus 2. However, we store - // intersection records for the first and last point, even though they are not really - // intersections. The reason we do this is for the intersection merging - the vertices for - // the first and last points can get merged just like any other intersection. Also, we have - // a dummy intersection record before the first point - this is because we want "previous - // segments" for the first point and each intersection only has an index for the next - // segment. - LineSegmentIntersection intersection[MAX_SEGLINE_POINT_BUFFER_SIZE + 1][NUM_EDGES]; - - for (sidx = 1; sidx < point_cnt; sidx++) { // #segments = #points - 1 (+ 2 dummy segments) - - Vector3 &curr_point = points[sidx - 1]; - Vector3 &next_point = points[sidx]; - - // We temporarily store the segment direction in the segment's StartPlane (since it is - // used to calculate the StartPlane later). - Vector3 &segdir = segment[sidx].StartPlane; - segdir = next_point - curr_point; - segdir.Normalize(); - - // Find nearest point on infinite line to eye (origin) - Vector3 nearest = curr_point + segdir * -Vector3::Dot_Product(segdir, curr_point); - - // Find top and bottom points on cylinder - Vector3 offset; - Vector3::Cross_Product(segdir, nearest, &offset); - offset.Normalize(); - Vector3 top = curr_point + offset * radius; - Vector3 bottom = curr_point + offset * -radius; - - // Find planes through top/bottom points and eyepoint. In addition to the two points, we - // know that the planes are parallel to the line segment. - Vector3 top_normal; - Vector3::Cross_Product(top, segdir, &top_normal); - top_normal.Normalize(); - segment[sidx].EdgePlane[TOP_EDGE] = top_normal; - - Vector3 bottom_normal; - Vector3::Cross_Product(segdir, bottom, &bottom_normal); - bottom_normal.Normalize(); - segment[sidx].EdgePlane[BOTTOM_EDGE] = bottom_normal; - - // If the visual angle between the previous and current line segments (we use the angle - // between the planes defined by each line segment and the eyepoint) is less than 90 - // degrees, switch the top and bottom edges for the current and subsequent segments and - // mark the intersection as having a fold - if (sidx > 1) { - - Vector3 prev_plane; - Vector3::Cross_Product(points[sidx - 2], curr_point, &prev_plane); - prev_plane.Normalize(); - - Vector3 curr_plane; - Vector3::Cross_Product(curr_point, next_point, &curr_plane); - curr_plane.Normalize(); - - if (Vector3::Dot_Product(prev_plane, curr_plane) < 0.0f) { - switch_edges = !switch_edges; - intersection[sidx][TOP_EDGE].Fold = true; - intersection[sidx][BOTTOM_EDGE].Fold = true; - } else { - intersection[sidx][TOP_EDGE].Fold = false; - intersection[sidx][BOTTOM_EDGE].Fold = false; - } - } - - if (switch_edges) { - // We switch signs so the normals will always point inwards - segment[sidx].EdgePlane[TOP_EDGE] = -bottom_normal; - segment[sidx].EdgePlane[BOTTOM_EDGE] = -top_normal; - } - - } - - // The two dummy segments for the clipping edges of the first and last real segments will be - // defined later, with the first and last intersections. - - - /* - ** Calculate segment edge intersections: - */ - - unsigned int numsegs = point_cnt - 1; // Doesn't include the two dummy segments - unsigned int num_intersections[NUM_EDGES]; - - // These include the 1st, last point "intersections", not the pre-first dummy intersection - num_intersections[TOP_EDGE] = point_cnt; - num_intersections[BOTTOM_EDGE] = point_cnt; - - // Initialize pre-first point dummy intersection record (only NextSegmentID will be used). - intersection[0][TOP_EDGE].PointCount = 0; // Should never be used - intersection[0][TOP_EDGE].NextSegmentID = 0; // Points to first dummy segment - intersection[0][TOP_EDGE].Direction.Set(1,0,0); // Should never be used - intersection[0][TOP_EDGE].Point.Set(0,0,0); // Should never be used - intersection[0][TOP_EDGE].TexV = 0.0f; // Should never be used - intersection[0][TOP_EDGE].Fold = true; // Should never be used - intersection[0][TOP_EDGE].Parallel = false; // Should never be used - intersection[0][BOTTOM_EDGE].PointCount = 0; // Should never be used - intersection[0][BOTTOM_EDGE].NextSegmentID = 0; // Points to first dummy segment - intersection[0][BOTTOM_EDGE].Point.Set(0,0,0); // Should never be used - intersection[0][BOTTOM_EDGE].TexV = 0.0f; // Should never be used - intersection[0][BOTTOM_EDGE].Direction.Set(1,0,0); // Should never be used - intersection[0][BOTTOM_EDGE].Fold = true; // Should never be used - intersection[0][BOTTOM_EDGE].Parallel = false; // Should never be used - - // Initialize first point "intersection" record. - intersection[1][TOP_EDGE].PointCount = 1; - intersection[1][TOP_EDGE].NextSegmentID = 1; - intersection[1][TOP_EDGE].Point = points[0]; - intersection[1][TOP_EDGE].TexV = tex_v[0]; - intersection[1][TOP_EDGE].Fold = true; - intersection[1][TOP_EDGE].Parallel = false; - intersection[1][BOTTOM_EDGE].PointCount = 1; - intersection[1][BOTTOM_EDGE].NextSegmentID = 1; - intersection[1][BOTTOM_EDGE].Point = points[0]; - intersection[1][BOTTOM_EDGE].TexV = tex_v[0]; - intersection[1][BOTTOM_EDGE].Fold = true; - intersection[1][BOTTOM_EDGE].Parallel = false; - - // Find closest point to 1st top/bottom segment edge plane, and convert to direction vector - // and dummy segment edge plane. - - Vector3 top; - Vector3 bottom; - - Vector3 &first_point = points[0]; - Vector3 *first_plane = &(segment[1].EdgePlane[0]); - top = first_point - first_plane[TOP_EDGE] * Vector3::Dot_Product(first_plane[TOP_EDGE], first_point); - top.Normalize(); - intersection[1][TOP_EDGE].Direction = top; - bottom = first_point - first_plane[BOTTOM_EDGE] * Vector3::Dot_Product(first_plane[BOTTOM_EDGE], first_point); - bottom.Normalize(); - intersection[1][BOTTOM_EDGE].Direction = bottom; - - Vector3 segdir = points[1] - points[0]; - segdir.Normalize(); // Is this needed? Probably not - remove later when all works - Vector3 start_pl; - Vector3::Cross_Product(top, bottom, &start_pl); - start_pl.Normalize(); - float dp = Vector3::Dot_Product(segdir, start_pl); - if (dp > 0.0f) { - segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = start_pl; - } else { - segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = -start_pl; - } - - // Initialize StartPlane for the first "real" segment - segment[1].StartPlane = segment[0].StartPlane; - - // Initialize last point "intersection" record. - unsigned int last_isec = num_intersections[TOP_EDGE]; // Same # top, bottom intersections - - intersection[last_isec][TOP_EDGE].PointCount = 1; - intersection[last_isec][TOP_EDGE].NextSegmentID = numsegs + 1; // Last dummy segment - intersection[last_isec][TOP_EDGE].Point = points[point_cnt - 1]; - intersection[last_isec][TOP_EDGE].TexV = tex_v[point_cnt - 1]; - intersection[last_isec][TOP_EDGE].Fold = true; - intersection[last_isec][TOP_EDGE].Parallel = false; - intersection[last_isec][BOTTOM_EDGE].PointCount = 1; - intersection[last_isec][BOTTOM_EDGE].NextSegmentID = numsegs + 1;// Last dummy segment - intersection[last_isec][BOTTOM_EDGE].Point = points[point_cnt - 1]; - intersection[last_isec][BOTTOM_EDGE].TexV = tex_v[point_cnt - 1]; - intersection[last_isec][BOTTOM_EDGE].Fold = true; - intersection[last_isec][BOTTOM_EDGE].Parallel = false; - - // Find closest point to last top/bottom segment edge plane, and convert to direction vector - // and dummy segment edge vector - - Vector3 &last_point = points[point_cnt - 1]; - Vector3 *last_plane = &(segment[numsegs].EdgePlane[0]); - top = last_point - last_plane[TOP_EDGE] * Vector3::Dot_Product(last_plane[TOP_EDGE], last_point); - top.Normalize(); - intersection[last_isec][TOP_EDGE].Direction = top; - bottom = last_point - last_plane[BOTTOM_EDGE] * Vector3::Dot_Product(last_plane[BOTTOM_EDGE], last_point); - bottom.Normalize(); - intersection[last_isec][BOTTOM_EDGE].Direction = bottom; - - segdir = points[point_cnt - 1] - points[point_cnt - 2]; - segdir.Normalize(); // Is this needed? Probably not - remove later when all works - Vector3::Cross_Product(top, bottom, &start_pl); - start_pl.Normalize(); - dp = Vector3::Dot_Product(segdir, start_pl); - if (dp > 0.0f) { - segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] = - segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = start_pl; - } else { - segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] = - segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = -start_pl; - } - - // Calculate midpoint segment intersections. There are 2 segment intersections for each - // point: top and bottom (due to the fact that the segments have width, so they have a top - // edge and a bottom edge). Note that the top/bottom distinction does not relate to screen - // up/down. Since each segment edge is represented by a plane passing through the origin - // (eyepoint), the intersection of two such is a line passing through the origin, which is - // represented as a normalized direction vector. - // We use both segment intersections to define the startplane for the segment which begins - // at that intersection. - - float vdp; - - for (iidx = 2; iidx < num_intersections[TOP_EDGE]; iidx++) { - - // Relevant midpoint: - Vector3 &midpoint = points[iidx - 1]; - float mid_tex_v = tex_v[iidx - 1]; - - // Initialize misc. fields - intersection[iidx][TOP_EDGE].PointCount = 1; - intersection[iidx][TOP_EDGE].NextSegmentID = iidx; - intersection[iidx][TOP_EDGE].Point = midpoint; - intersection[iidx][TOP_EDGE].TexV = mid_tex_v; - intersection[iidx][BOTTOM_EDGE].PointCount = 1; - intersection[iidx][BOTTOM_EDGE].NextSegmentID = iidx; - intersection[iidx][BOTTOM_EDGE].Point = midpoint; - intersection[iidx][BOTTOM_EDGE].TexV = mid_tex_v; - - // Intersection calculation: if the top/bottom planes of both adjoining segments are not - // very close to being parallel, intersect them to get top/bottom intersection lines. If - // the planes are almost parallel, pick one, find the point on the plane closest to the - // midpoint, and convert that point to a line direction vector. - - // Top: - vdp = Vector3::Dot_Product(segment[iidx - 1].EdgePlane[TOP_EDGE], segment[iidx].EdgePlane[TOP_EDGE]); - if (fabs(vdp) < parallel_factor) { - - // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is - // pointing towards the midpoint) - Vector3::Cross_Product(segment[iidx - 1].EdgePlane[TOP_EDGE], segment[iidx].EdgePlane[TOP_EDGE], - &(intersection[iidx][TOP_EDGE].Direction)); - intersection[iidx][TOP_EDGE].Direction.Normalize(); - if (Vector3::Dot_Product(intersection[iidx][TOP_EDGE].Direction, midpoint) < 0.0f) { - intersection[iidx][TOP_EDGE].Direction = -intersection[iidx][TOP_EDGE].Direction; - } - - intersection[iidx][TOP_EDGE].Parallel = false; - - } else { - - // Parallel (or almost): find point on av. plane closest to midpoint, convert to line - - // Ensure average calculation is numerically stable: - Vector3 pl; - if (vdp > 0.0f) { - pl = segment[iidx - 1].EdgePlane[TOP_EDGE] + segment[iidx].EdgePlane[TOP_EDGE]; - } else { - pl = segment[iidx - 1].EdgePlane[TOP_EDGE] - segment[iidx].EdgePlane[TOP_EDGE]; - } - pl.Normalize(); - - intersection[iidx][TOP_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint); - intersection[iidx][TOP_EDGE].Direction.Normalize(); - - intersection[iidx][TOP_EDGE].Parallel = true; - } - - // Bottom: - vdp = Vector3::Dot_Product(segment[iidx - 1].EdgePlane[BOTTOM_EDGE], segment[iidx].EdgePlane[BOTTOM_EDGE]); - if (fabs(vdp) < parallel_factor) { - - // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is - // pointing towards the midpoint) - Vector3::Cross_Product(segment[iidx - 1].EdgePlane[BOTTOM_EDGE], segment[iidx].EdgePlane[BOTTOM_EDGE], - &(intersection[iidx][BOTTOM_EDGE].Direction)); - intersection[iidx][BOTTOM_EDGE].Direction.Normalize(); - if (Vector3::Dot_Product(intersection[iidx][BOTTOM_EDGE].Direction, midpoint) < 0.0f) { - intersection[iidx][BOTTOM_EDGE].Direction = -intersection[iidx][BOTTOM_EDGE].Direction; - } - - intersection[iidx][BOTTOM_EDGE].Parallel = false; - - } else { - - // Parallel (or almost): find point on av. plane closest to midpoint, convert to line - - // Ensure average calculation is numerically stable: - Vector3 pl; - if (vdp > 0.0f) { - pl = segment[iidx - 1].EdgePlane[BOTTOM_EDGE] + segment[iidx].EdgePlane[BOTTOM_EDGE]; - } else { - pl = segment[iidx - 1].EdgePlane[BOTTOM_EDGE] - segment[iidx].EdgePlane[BOTTOM_EDGE]; - } - pl.Normalize(); - - intersection[iidx][BOTTOM_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint); - intersection[iidx][BOTTOM_EDGE].Direction.Normalize(); - - intersection[iidx][BOTTOM_EDGE].Parallel = true; - } - - // Find StartPlane: - Vector3::Cross_Product(intersection[iidx][TOP_EDGE].Direction, intersection[iidx][BOTTOM_EDGE].Direction, &start_pl); - start_pl.Normalize(); - dp = Vector3::Dot_Product(segment[iidx].StartPlane, start_pl); - if (dp > 0.0f) { - segment[iidx].StartPlane = start_pl; - } else { - segment[iidx].StartPlane = -start_pl; - } - - } // for iidx - - - /* - ** Intersection merging: when an intersection is inside an adjacent segment and certain - ** other conditions hold true, we need to merge intersections to avoid visual glitches - ** caused by the polys folding over on themselves. - */ - - if (Is_Merge_Intersections()) { - - // Since we are merging the intersections in-place, we have two index variables, a "read - // index" and a "write index". - unsigned int iidx_r; - unsigned int iidx_w; - - // The merges will be repeated in multiple passes until none are performed. The reason - // for this is that one merge may cause the need for another merge elsewhere. - bool merged = true; - - while (merged) { - - merged = false; - - SegmentEdge edge; - for (edge = FIRST_EDGE; edge <= MAX_EDGE; edge = (SegmentEdge)((int)edge + 1)) { - // Merge top and bottom edge intersections: loop through the intersections from the - // first intersection to the penultimate intersection, for each intersection check - // if it needs to be merged with the next one (which is why the loop doesn't go all - // the way to the last intersection). We start at 1 because 0 is the dummy - // "pre-first-point" intersection. - unsigned int num_isects = num_intersections[edge]; // Capture here because will change inside loop - for (iidx_r = 1, iidx_w = 1; iidx_r < num_isects; iidx_r++, iidx_w++) { - - // Check for either of two possible reasons to merge this intersection with the - // next: either the segment on the far side of the next intersection overlaps - // this intersection, or the previous segment overlaps the next intersection. - // Note that some other conditions need to be true as well. - - // Note: iidx_r is used for anything at or after the current position, iidx_w is - // used for anything before the current position (previous positions have - // potentially already been merged). - // Note: iidx_r is used for anything at or after the current position, iidx_w is - // used for anything before the current position (previous positions have - // potentially already been merged). - LineSegmentIntersection *curr_int = &(intersection[iidx_r][edge]); - LineSegmentIntersection *next_int = &(intersection[iidx_r + 1][edge]); - LineSegmentIntersection *write_int = &(intersection[iidx_w][edge]); - LineSegmentIntersection *prev_int = &(intersection[iidx_w - 1][edge]); - LineSegment *next_seg = &(segment[next_int->NextSegmentID]); - LineSegment *curr_seg = &(segment[curr_int->NextSegmentID]); - LineSegment *prev_seg = &(segment[prev_int->NextSegmentID]); - - // If this intersection is inside both the start plane and the segment edge - // plane of the segment after the next intersection, merge this edge - // intersection and the next. We repeat merging until no longer needed. - // NOTE - we do not merge across a fold. - while ( (!next_int->Fold && - (Vector3::Dot_Product(curr_int->Direction, next_seg->StartPlane) > 0.0f) && - (Vector3::Dot_Product(curr_int->Direction, next_seg->EdgePlane[edge]) > 0.0f )) || - (!curr_int->Fold && - (Vector3::Dot_Product(next_int->Direction, -curr_seg->StartPlane) > 0.0f) && - (Vector3::Dot_Product(next_int->Direction, prev_seg->EdgePlane[edge]) > 0.0f )) ) { - - // First calculate location of merged intersection - this is so we can abort - // the merge if it yields funky results. - - // Find mean point (weighted so all points have same weighting) - unsigned int new_count = curr_int->PointCount + next_int->PointCount; - float oo_new_count = 1.0f / (float)new_count; - float curr_factor = oo_new_count * (float)curr_int->PointCount; - float next_factor = oo_new_count * (float)curr_int->PointCount; - Vector3 new_point = curr_int->Point * curr_factor + next_int->Point * next_factor; - float new_tex_v = curr_int->TexV * curr_factor + next_int->TexV * next_factor; - - // Calculate new intersection direction by intersecting prev_seg with next_seg - bool new_parallel; - Vector3 new_direction; - vdp = Vector3::Dot_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge]); - if (fabs(vdp) < parallel_factor) { - - // Not parallel - intersect planes to get line (get vector, normalize it, - // ensure it is pointing towards the current point) - Vector3::Cross_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge], &new_direction); - new_direction.Normalize(); - if (Vector3::Dot_Product(new_direction, new_point) < 0.0f) { - new_direction = -new_direction; - } - - new_parallel = false; - - } else { - - // Parallel (or almost). If the current intersection is not parallel, take - // the average plane and intersect it with the skipped plane. If the - // current intersection is parallel, find the average plane, and find the - // direction vector on it closest to the current intersections direction - // vector. - - // Ensure average calculation is numerically stable: - Vector3 pl; - if (vdp > 0.0f) { - pl = prev_seg->EdgePlane[edge] + next_seg->EdgePlane[edge]; - } else { - pl = prev_seg->EdgePlane[edge] - next_seg->EdgePlane[edge]; - } - pl.Normalize(); - - if (curr_int->Parallel) { - new_direction = new_direction - pl * Vector3::Dot_Product(pl, new_direction); - new_direction.Normalize(); - } else { - Vector3::Cross_Product(curr_seg->EdgePlane[edge], pl, &new_direction); - new_direction.Normalize(); - } - - new_parallel = true; - } - - // Now check to see if the merge caused any funky results - if so abort it. - // Currently we check to see if the distance of the direction from the two - // points is larger than the radius times the merge_abort factor. - if (MergeAbortFactor > 0.0f) { - float abort_dist = radius * MergeAbortFactor; - float abort_dist2 = abort_dist * abort_dist; - Vector3 diff_curr = curr_int->Point - - new_direction * Vector3::Dot_Product(curr_int->Point, new_direction); - if (diff_curr.Length2() > abort_dist2) break; - Vector3 next_curr = next_int->Point - - new_direction * Vector3::Dot_Product(next_int->Point, new_direction); - if (next_curr.Length2() > abort_dist2) break; - } - - // Merge edge intersections (curr_int and next_int) into curr_int - merged = true; - - curr_int->Direction = new_direction; - curr_int->Parallel = new_parallel; - curr_int->Point = new_point; - curr_int->TexV = new_tex_v; - curr_int->PointCount = new_count; - curr_int->NextSegmentID = next_int->NextSegmentID; - curr_int->Fold = curr_int->Fold || next_int->Fold; - - // Decrement number of edge intersections - num_intersections[edge]--; - - // Advance iidx_r to shift subsequent entries backwards in result. - iidx_r++; - - // If we are at the end then break: - if (iidx_r == num_isects) { - break; - } - - // Advance next_int and next_seg. - next_int = &(intersection[iidx_r + 1][edge]); - next_seg = &(segment[next_int->NextSegmentID]); - - } // while - - // Copy from "read index" to "write index" - write_int->PointCount = curr_int->PointCount; - write_int->NextSegmentID = curr_int->NextSegmentID; - write_int->Point = curr_int->Point; - write_int->TexV = curr_int->TexV; - write_int->Direction = curr_int->Direction; - write_int->Fold = curr_int->Fold; - - } // for iidx - - // If iidx_r is exactly equal to num_isects (rather than being larger by one) at this - // point, this means that the last intersection was not merged with the previous one. In - // this case, we need to do one last copy: - if (iidx_r == num_isects) { - LineSegmentIntersection *write_int = &(intersection[iidx_w][edge]); - LineSegmentIntersection *curr_int = &(intersection[iidx_r][edge]); - write_int->PointCount = curr_int->PointCount; - write_int->NextSegmentID = curr_int->NextSegmentID; - write_int->Point = curr_int->Point; - write_int->TexV = curr_int->TexV; - write_int->Direction = curr_int->Direction; - write_int->Fold = curr_int->Fold; - } - -#ifdef ENABLE_WWDEBUGGING - // Testing code - ensure total PointCount fits the number of points - unsigned int total_cnt = 0; - for (unsigned int nidx = 0; nidx <= num_intersections[edge]; nidx++) { - total_cnt += intersection[nidx][edge].PointCount; - } - assert(total_cnt == point_cnt); -#endif - - } // for edge - } // while (merged) - } // if (Is_Merge_Intersections()) - - /* - ** Find vertex positions, generate vertices and triangles: - ** Since we can have top/bottom intersections merged, we need to skip points if both the top - ** and bottom intersections are merged, generate triangle fans if one of the sides is merged - ** and the other isnt, and generate triangle strips otherwise. - */ - - // Configure vertex array and setup renderer. - unsigned int vnum = num_intersections[TOP_EDGE] + num_intersections[BOTTOM_EDGE]; - VertexFormatXYZDUV1 *vArray = W3DNEWARRAY VertexFormatXYZDUV1[vnum]; - TriIndex v_index_array[MAX_SEGLINE_POLY_BUFFER_SIZE]; - - // Vertex and triangle indices - unsigned int vidx = 0; - unsigned int tidx = 0; - -// GENERALIZE FOR WHEN NO TEXTURE (DO NOT SET UV IN THESE CASES? NEED TO GENERALIZE FOR DIFFERENT TEXTURING MODES ANYWAY). - - // "Prime the pump" with two vertices (pick nearest point on each direction line): - Vector3 &top_dir = intersection[1][TOP_EDGE].Direction; - top = top_dir * Vector3::Dot_Product(points[0], top_dir); - Vector3 &bottom_dir = intersection[1][BOTTOM_EDGE].Direction; - bottom = bottom_dir * Vector3::Dot_Product(points[0], bottom_dir); - vArray[vidx].x = top.X; - vArray[vidx].y = top.Y; - vArray[vidx].z = top.Z; - vArray[vidx].u1 = u_values[0] + uv_offset.X; - vArray[vidx].v1 = intersection[1][TOP_EDGE].TexV + uv_offset.Y; - vidx++; - vArray[vidx].x = bottom.X; - vArray[vidx].y = bottom.Y; - vArray[vidx].z = bottom.Z; - vArray[vidx].u1 = u_values[1] + uv_offset.X; - vArray[vidx].v1 = intersection[1][BOTTOM_EDGE].TexV + uv_offset.Y; - vidx++; - - unsigned int last_top_vidx = 0; - unsigned int last_bottom_vidx = 1; - - // Loop over intersections, create new vertices and triangles. - unsigned int top_int_idx = 1; // Skip "pre-first-point" dummy intersection - unsigned int bottom_int_idx = 1; // Skip "pre-first-point" dummy intersection - pidx = 0; - unsigned int residual_top_points = intersection[1][TOP_EDGE].PointCount; - unsigned int residual_bottom_points = intersection[1][BOTTOM_EDGE].PointCount; - - // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points) - unsigned int delta = MIN(residual_top_points, residual_bottom_points) - 1; - residual_top_points -= delta; - residual_bottom_points -= delta; - pidx += delta; - - for (; ; ) { - - if (residual_top_points == 1 && residual_bottom_points == 1) { - // Advance both intersections, creating a tristrip segment - v_index_array[tidx].I = last_top_vidx; - v_index_array[tidx].J = last_bottom_vidx; - v_index_array[tidx].K = vidx; - tidx++; - v_index_array[tidx].I = last_bottom_vidx; - v_index_array[tidx].J = vidx + 1; - v_index_array[tidx].K = vidx; - tidx++; - last_top_vidx = vidx; - last_bottom_vidx = vidx + 1; - - // Advance both intersections. - top_int_idx++; - bottom_int_idx++; - residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount; - residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount; - - // Advance point index (must do here because the new point index is used below): - pidx++; - - // Generate two vertices for next point by picking nearest point on each direction line - Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction; - top = top_dir * Vector3::Dot_Product(points[pidx], top_dir); - Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction; - bottom = bottom_dir * Vector3::Dot_Product(points[pidx], bottom_dir); - - vArray[vidx].x = top.X; - vArray[vidx].y = top.Y; - vArray[vidx].z = top.Z; - vArray[vidx].u1 = u_values[0] + uv_offset.X; - vArray[vidx].v1 = intersection[top_int_idx][TOP_EDGE].TexV + uv_offset.Y; - vidx++; - vArray[vidx].x = bottom.X; - vArray[vidx].y = bottom.Y; - vArray[vidx].z = bottom.Z; - vArray[vidx].u1 = u_values[1] + uv_offset.X; - vArray[vidx].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV + uv_offset.Y; - vidx++; - } else { - // Exactly one of the pointcounts is greater than one - advance it and draw one triangle - if (residual_top_points > 1) { - // Draw one triangle (fan segment) - v_index_array[tidx].I = last_top_vidx; - v_index_array[tidx].J = last_bottom_vidx; - v_index_array[tidx].K = vidx; - tidx++; - last_bottom_vidx = vidx; - - // Advance bottom intersection only - residual_top_points--; - bottom_int_idx++; - residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount; - - // Advance point index (must do here because the new point index is used below): - pidx++; - - // Generate bottom vertex by picking nearest point on bottom direction line - Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction; - bottom = bottom_dir * Vector3::Dot_Product(points[pidx], bottom_dir); - - vArray[vidx].x = bottom.X; - vArray[vidx].y = bottom.Y; - vArray[vidx].z = bottom.Z; - vArray[vidx].u1 = u_values[1] + uv_offset.X; - vArray[vidx].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV + uv_offset.Y; - vidx++; - } else { - - // residual_bottom_points > 1 - - // Draw one triangle (fan segment) - v_index_array[tidx].I = last_top_vidx; - v_index_array[tidx].J = last_bottom_vidx; - v_index_array[tidx].K = vidx; - tidx++; - last_top_vidx = vidx; - - // Advance top intersection only - residual_bottom_points--; - top_int_idx++; - residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount; - - // Advance point index (must do here because the new point index is used below): - pidx++; - - // Generate top vertex by picking nearest point on top direction line - Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction; - top = top_dir * Vector3::Dot_Product(points[pidx], top_dir); - vArray[vidx].x = top.X; - vArray[vidx].y = top.Y; - vArray[vidx].z = top.Z; - vArray[vidx].u1 = u_values[0] + uv_offset.X; - vArray[vidx].v1 = intersection[top_int_idx][TOP_EDGE].TexV + uv_offset.Y; - vidx++; - } - } - - // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points) - delta = MIN(residual_top_points, residual_bottom_points) - 1; - residual_top_points -= delta; - residual_bottom_points -= delta; - pidx += delta; - - // Exit conditions - if ( (top_int_idx >= num_intersections[TOP_EDGE] && residual_top_points == 1) || - (bottom_int_idx >= num_intersections[BOTTOM_EDGE] && residual_bottom_points == 1)) { - // Debugging check - if either intersection index is before end, both of them should be - // and the points should be before the end. - assert(top_int_idx == num_intersections[TOP_EDGE]); - assert(bottom_int_idx == num_intersections[BOTTOM_EDGE]); - assert(pidx == point_cnt - 1); - break; - } - } - - /* - ** Set color, opacity, vertex flags: - */ - - // If color is not white or opacity not 100%, enable gradient in shader and in renderer - otherwise disable. - unsigned int rgba; - rgba=DX8Wrapper::Convert_Color(Color,Opacity); - bool rgba_all=(rgba==0xFFFFFFFF); - - // Enable sorting if sorting has not been disabled and line is translucent and alpha testing is not enabled. - bool sorting = (!Is_Sorting_Disabled()) && (Shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO && Shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE); - - ShaderClass shader = Shader; - shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - - VertexMaterialClass *mat; - - if (!rgba_all) { - shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE); - for (vidx = 0; vidx < vnum; vidx++) vArray[vidx].diffuse=rgba; - mat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - } else { - shader.Set_Primary_Gradient(ShaderClass::GRADIENT_DISABLE); - mat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_NODIFFUSE); - } - - // If Texture is non-NULL enable texturing in shader - otherwise disable. - if (Texture) { - shader.Set_Texturing(ShaderClass::TEXTURING_ENABLE); - } else { - shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE); - } - - - /* - ** Render - */ - - DynamicVBAccessClass Verts((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),dynamic_fvf_type,vnum); - // Copy in the data to the VB - { - DynamicVBAccessClass::WriteLockClass Lock(&Verts); - unsigned int i; - unsigned char *vb=(unsigned char*)Lock.Get_Formatted_Vertex_Array(); - const FVFInfoClass& fvfinfo=Verts.FVF_Info(); - - for (i=0; iX=vArray[i].x; - ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->Y=vArray[i].y; - ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->Z=vArray[i].z; - *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset())=vArray[i].diffuse; - ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->U=vArray[i].u1; - ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->V=vArray[i].v1; - vb+=fvfinfo.Get_FVF_Size(); - } - } // copy - - DynamicIBAccessClass ib_access((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),tidx*3); - { - unsigned int i; - DynamicIBAccessClass::WriteLockClass lock(&ib_access); - unsigned short* inds=lock.Get_Index_Array(); - - for (i=0; i= 0;) { - if (stack[tos].Level == SubdivisionLevel) { - // Generate point location and texture V coordinate - xformed_subdiv_pts[sub_pidx] = stack[tos].StartPos; - subdiv_tex_v[sub_pidx++] = stack[tos].StartTexV; - - // Pop - tos--; - } else { - // Recurse down: pop existing entry and push two subdivided ones. - if (freeze_random) { - randvec.Set(randomize * oo_int_max, randomize * oo_int_max, randomize * oo_int_max); - } else { - randomizer.Get_Vector(randvec); - } - stack[tos + 1].StartPos = stack[tos].StartPos; - stack[tos + 1].EndPos = (stack[tos].StartPos + stack[tos].EndPos) * 0.5f + randvec * stack[tos].Rand; - stack[tos + 1].StartTexV = stack[tos].StartTexV; - stack[tos + 1].EndTexV = (stack[tos].StartTexV + stack[tos].EndTexV) * 0.5f; - stack[tos + 1].Rand = stack[tos].Rand * 0.5f; - stack[tos + 1].Level = stack[tos].Level + 1; - stack[tos].StartPos = stack[tos + 1].EndPos; - // stack[tos].EndPos already has the right value - stack[tos].StartTexV = stack[tos + 1].EndTexV; - // stack[tos].EndTexV already has the right value - stack[tos].Rand = stack[tos + 1].Rand; - stack[tos].Level = stack[tos + 1].Level; - tos++; - } - } - } - // Last point - xformed_subdiv_pts[sub_pidx] = xformed_pts[point_cnt - 1]; - subdiv_tex_v[sub_pidx++] = base_tex_v[point_cnt - 1]; - - // Output: - *p_sub_point_cnt = sub_pidx; -} - - - -#endif //0 \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h deleted file mode 100644 index 9928bd1d45..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/seglinerenderer.h +++ /dev/null @@ -1,206 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/seglinerenderer.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 6/08/01 5:23p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef SEGLINERENDERER_H -#define SEGLINERENDERER_H - -#include "always.h" -#include "shader.h" -#include "texture.h" -#include "matrix3d.h" -#include "vector2.h" - -class RenderInfoClass; -class SphereClass; -struct W3dEmitterLinePropertiesStruct; - - -// The maximum allowable level of subdivision. This should be no more than 7 to avoid increasing -// the chunk buffer size too much -#define MAX_SEGLINE_SUBDIV_LEVELS 7 - - - -/** -** SegLineRendererClass -** This class implements the low-level line rendering functionality used by both SegmentedLineClass -** and ParticleBufferClass -*/ -class SegLineRendererClass -{ -public: - - SegLineRendererClass(void); - SegLineRendererClass(const SegLineRendererClass & that); - SegLineRendererClass & operator = (const SegLineRendererClass & that); - ~SegLineRendererClass(void); - - enum TextureMapMode { - UNIFORM_WIDTH_TEXTURE_MAP = 0x00000000, // Entire line uses one row of texture (constant V) - UNIFORM_LENGTH_TEXTURE_MAP = 0x00000001, // Entire line uses one row of texture stretched length-wise - TILED_TEXTURE_MAP = 0x00000002 // Tiled continuously over line - }; - - void Init(const W3dEmitterLinePropertiesStruct & props); - - // Get properties used to render this line segment - TextureClass * Get_Texture(void) const; - TextureClass * Peek_Texture(void) const { return Texture; } - ShaderClass Get_Shader(void) const { return Shader; } - float Get_Width(void) const { return Width; } - const Vector3 & Get_Color(void) const { return Color; } - float Get_Opacity(void) const { return Opacity; } - float Get_Noise_Amplitude(void) const { return NoiseAmplitude; } - float Get_Merge_Abort_Factor(void) const { return MergeAbortFactor; } - unsigned int Get_Current_Subdivision_Level(void) const { return SubdivisionLevel; } - TextureMapMode Get_Texture_Mapping_Mode(void) const; - float Get_Texture_Tile_Factor(void) const { return TextureTileFactor; } - Vector2 Get_UV_Offset_Rate(void) const; - int Is_Merge_Intersections(void) const { return Bits & MERGE_INTERSECTIONS; } - int Is_Freeze_Random(void) const { return Bits & FREEZE_RANDOM; } - int Is_Sorting_Disabled(void) const { return Bits & DISABLE_SORTING; } - int Are_End_Caps_Enabled(void) const { return Bits & END_CAPS; } - - // Set properties used to render this line segment - void Set_Texture(TextureClass *texture); - void Set_Shader(ShaderClass shader) { Shader = shader; } - void Set_Width(float width) { Width = width; } - void Set_Color(const Vector3 &color) { Color = color; } - void Set_Opacity(float opacity) { Opacity = opacity; } - void Set_Noise_Amplitude(float amplitude) { NoiseAmplitude = amplitude; } - void Set_Merge_Abort_Factor(float factor) { MergeAbortFactor = factor; } - void Set_Current_Subdivision_Level(unsigned int lv) { SubdivisionLevel = lv; } - void Set_Texture_Mapping_Mode(TextureMapMode mode); - // WARNING! Do NOT set the tile factor to be too high (should be less than 8) or negative - //performance impact will result! - void Set_Texture_Tile_Factor(float factor); - void Set_Current_UV_Offset(const Vector2 & offset); - void Set_UV_Offset_Rate(const Vector2 &rate); - void Set_Merge_Intersections(int onoff) { if (onoff) { Bits |= MERGE_INTERSECTIONS; } else { Bits &= ~MERGE_INTERSECTIONS; }; } - void Set_Freeze_Random(int onoff) { if (onoff) { Bits |= FREEZE_RANDOM; } else { Bits &= ~FREEZE_RANDOM; }; } - void Set_Disable_Sorting(int onoff) { if (onoff) { Bits |= DISABLE_SORTING; } else { Bits &= ~DISABLE_SORTING; }; } - void Set_End_Caps(int onoff) { if (onoff) { Bits |= END_CAPS; } else { Bits &= ~END_CAPS; }; } - - - void Render( RenderInfoClass & rinfo, - const Matrix3D & transform, - unsigned int point_count, - Vector3 * points, - const SphereClass & obj_sphere); - - void Reset_Line(void); - -private: - - // Utility functions - void subdivision_util(unsigned int point_cnt, const Vector3 *xformed_pts, - const float *base_tex_v, unsigned int *p_sub_point_cnt, - Vector3 *xformed_subdiv_pts, float *subdiv_tex_v); - - // Global properties - TextureClass * Texture; - ShaderClass Shader; - float Width; - Vector3 Color; - float Opacity; - - // Subdivision properties - unsigned int SubdivisionLevel; - float NoiseAmplitude; - - // If >0, will abort a merge which causes an intersection to move - // farther away than this factor * line radius from the line point. - // (defaults to 1.5, has no affect if intersection merging is disabled). - float MergeAbortFactor; - - // Affects tiled texture mapping mode only. If this is set too high, performance (and - // possibly visual) problems will result from excessive tiling over a single polygon, over - // the entire line, or both. - float TextureTileFactor; - - // Used for texture coordinate animation - unsigned int LastUsedSyncTime; // Last sync time used - Vector2 CurrentUVOffset; // Current UV offset - Vector2 UVOffsetDeltaPerMS; // Amount to increase offset each millisec - - // Various flags - enum BitShiftOffsets { - TEXTURE_MAP_MODE_OFFSET = 24 // By how many bits do I need to shift the texture mapping mode? - }; - enum { - MERGE_INTERSECTIONS = 0x00000001, // Merge intersections - FREEZE_RANDOM = 0x00000002, // Freeze random (note: offsets are in camera space) - DISABLE_SORTING = 0x00000004, // Disable sorting (even if shader has alpha-blending) - END_CAPS = 0x00000008, // Draw end caps on the line - - // Some bits are used to select the texture mapping mode: - TEXTURE_MAP_MODE_MASK = 0xFF000000, // Must cover all possible TextureMapMode values - - DEFAULT_BITS = MERGE_INTERSECTIONS | (UNIFORM_WIDTH_TEXTURE_MAP << TEXTURE_MAP_MODE_OFFSET) - }; - unsigned int Bits; - - friend class SegmentedLineClass; -}; - - - -inline SegLineRendererClass::TextureMapMode SegLineRendererClass::Get_Texture_Mapping_Mode(void) const -{ - return (TextureMapMode)((Bits & TEXTURE_MAP_MODE_MASK) >> TEXTURE_MAP_MODE_OFFSET); -} - -inline void SegLineRendererClass::Set_Texture_Mapping_Mode(SegLineRendererClass::TextureMapMode mode) -{ - Bits &= ~TEXTURE_MAP_MODE_MASK; - Bits |= ((mode << TEXTURE_MAP_MODE_OFFSET) & TEXTURE_MAP_MODE_MASK); -} - -inline Vector2 SegLineRendererClass::Get_UV_Offset_Rate(void) const -{ - return UVOffsetDeltaPerMS * 1000.0f; -} - -inline void SegLineRendererClass::Set_UV_Offset_Rate(const Vector2 &rate) -{ - UVOffsetDeltaPerMS = rate * 0.001f; -} - - -#endif //SEGLINERENDERER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp index 0eb0e2af55..5fbd20fe18 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shader.cpp @@ -531,57 +531,74 @@ void ShaderClass::Apply() return; } - if(diff & (ShaderClass::MASK_PRIGRADIENT|ShaderClass::MASK_TEXTURING)) - { - D3DTEXTUREOP cOp = D3DTOP_SELECTARG1; - D3DTEXTUREOP aOp = D3DTOP_SELECTARG1; - DWORD cArg1 = D3DTA_DIFFUSE, cArg2 = D3DTA_DIFFUSE; - DWORD aArg1 = D3DTA_DIFFUSE, aArg2 = D3DTA_DIFFUSE; + // Defaults + + D3DTEXTUREOP PricOp = D3DTOP_SELECTARG1; + DWORD PricArg1 = D3DTA_DIFFUSE; + DWORD PricArg2 = D3DTA_DIFFUSE; + + D3DTEXTUREOP PriaOp = D3DTOP_SELECTARG1; + DWORD PriaArg1 = D3DTA_DIFFUSE; + DWORD PriaArg2 = D3DTA_DIFFUSE; + + D3DTEXTUREOP SeccOp = D3DTOP_DISABLE; + DWORD SeccArg1 = D3DTA_TEXTURE; + DWORD SeccArg2 = D3DTA_CURRENT; + + D3DTEXTUREOP SecaOp = D3DTOP_DISABLE; + DWORD SecaArg1 = D3DTA_TEXTURE; + DWORD SecaArg2 = D3DTA_CURRENT; + int pri_mask=ShaderClass::MASK_PRIGRADIENT|ShaderClass::MASK_TEXTURING; + int sec_mask=ShaderClass::MASK_POSTDETAILCOLORFUNC|ShaderClass::MASK_TEXTURING; + int seca_mask=ShaderClass::MASK_POSTDETAILALPHAFUNC|ShaderClass::MASK_TEXTURING; + + if(diff & pri_mask) + { if(Get_Texturing() == ShaderClass::TEXTURING_ENABLE) { switch(Get_Primary_Gradient()) { case ShaderClass::GRADIENT_DISABLE: //Decal - cOp = D3DTOP_SELECTARG1; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; - aOp = D3DTOP_SELECTARG1; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + PricOp = D3DTOP_SELECTARG1; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_CURRENT; + PriaOp = D3DTOP_SELECTARG1; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_CURRENT; break; default: case ShaderClass::GRADIENT_MODULATE: //Modulate Alpha - cOp = D3DTOP_MODULATE; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_DIFFUSE; - aOp = D3DTOP_MODULATE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_DIFFUSE; + PricOp = D3DTOP_MODULATE; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_DIFFUSE; + PriaOp = D3DTOP_MODULATE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_DIFFUSE; break; case ShaderClass::GRADIENT_ADD: if(!(TextureOpCaps & D3DTEXOPCAPS_ADD)) - cOp = D3DTOP_MODULATE; + PricOp = D3DTOP_MODULATE; else - cOp = D3DTOP_ADD; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_DIFFUSE; - aOp = D3DTOP_MODULATE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_DIFFUSE; + PricOp = D3DTOP_ADD; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_DIFFUSE; + PriaOp = D3DTOP_MODULATE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_DIFFUSE; break; // Bump map is a hack currently as we only have two stages in use! case ShaderClass::GRADIENT_BUMPENVMAP: if(TextureOpCaps & D3DTEXOPCAPS_BUMPENVMAP) { - cOp=D3DTOP_BUMPENVMAP; - cArg1=D3DTA_TEXTURE; - cArg2=D3DTA_DIFFUSE; - aOp = D3DTOP_DISABLE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + PricOp=D3DTOP_BUMPENVMAP; + PricArg1=D3DTA_TEXTURE; + PricArg2=D3DTA_DIFFUSE; + PriaOp = D3DTOP_DISABLE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_CURRENT; } break; @@ -589,12 +606,12 @@ void ShaderClass::Apply() case ShaderClass::GRADIENT_BUMPENVMAPLUMINANCE: if(TextureOpCaps & D3DTEXOPCAPS_BUMPENVMAPLUMINANCE) { - cOp=D3DTOP_BUMPENVMAPLUMINANCE; - cArg1=D3DTA_TEXTURE; - cArg2=D3DTA_DIFFUSE; - aOp = D3DTOP_DISABLE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + PricOp=D3DTOP_BUMPENVMAPLUMINANCE; + PricArg1=D3DTA_TEXTURE; + PricArg2=D3DTA_DIFFUSE; + PriaOp = D3DTOP_DISABLE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_CURRENT; } break; @@ -602,12 +619,12 @@ void ShaderClass::Apply() case ShaderClass::GRADIENT_DOTPRODUCT3: if(TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) { - cOp=D3DTOP_DOTPRODUCT3; - cArg1=D3DTA_TEXTURE; - cArg2=D3DTA_DIFFUSE; - aOp = D3DTOP_DISABLE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + PricOp = D3DTOP_DOTPRODUCT3; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_DIFFUSE; + PriaOp = D3DTOP_DISABLE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_CURRENT; } break; } @@ -617,54 +634,50 @@ void ShaderClass::Apply() switch(Get_Primary_Gradient()) { case ShaderClass::GRADIENT_DISABLE: - cOp = D3DTOP_DISABLE; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; - aOp = D3DTOP_DISABLE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + PricOp = D3DTOP_DISABLE; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_CURRENT; + PriaOp = D3DTOP_DISABLE; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_CURRENT; break; default: case ShaderClass::GRADIENT_MODULATE: - cOp = D3DTOP_SELECTARG2; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_DIFFUSE; - aOp = D3DTOP_SELECTARG2; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_DIFFUSE; + PricOp = D3DTOP_SELECTARG2; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_DIFFUSE; + PriaOp = D3DTOP_SELECTARG2; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_DIFFUSE; break; case ShaderClass::GRADIENT_ADD: - cOp = D3DTOP_SELECTARG2; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_DIFFUSE; - aOp = D3DTOP_SELECTARG2; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_DIFFUSE; + PricOp = D3DTOP_SELECTARG2; + PricArg1 = D3DTA_TEXTURE; + PricArg2 = D3DTA_DIFFUSE; + PriaOp = D3DTOP_SELECTARG2; + PriaArg1 = D3DTA_TEXTURE; + PriaArg2 = D3DTA_DIFFUSE; break; } } if (WW3D::Is_Coloring_Enabled()) { - cArg2=aArg2=D3DTA_TFACTOR; - cOp=aOp=D3DTOP_SELECTARG2; + PricArg2=PriaArg2=D3DTA_TFACTOR; + PricOp=PriaOp=D3DTOP_SELECTARG2; } - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_COLOROP,cOp); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_COLORARG1,cArg1); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_COLORARG2,cArg2); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAOP,aOp); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAARG1,aArg1); - DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAARG2,aArg2); + DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_COLOROP,PricOp); + DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_COLORARG1,PricArg1); + DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_COLORARG2,PricArg2); + DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAOP,PriaOp); + DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAARG1,PriaArg1); + DX8Wrapper::Set_DX8_Texture_Stage_State(0,D3DTSS_ALPHAARG2,PriaArg2); diff &= ~(ShaderClass::MASK_PRIGRADIENT); } - if(diff & (ShaderClass::MASK_POSTDETAILCOLORFUNC|ShaderClass::MASK_TEXTURING)) + if(diff & sec_mask) { - D3DTEXTUREOP cOp = D3DTOP_DISABLE; - DWORD cArg1 = D3DTA_TEXTURE; - DWORD cArg2 = D3DTA_CURRENT; - if(Get_Texturing()== ShaderClass::TEXTURING_ENABLE) { switch(Get_Post_Detail_Color_Func()) @@ -676,88 +689,84 @@ void ShaderClass::Apply() case ShaderClass::DETAILCOLOR_DETAIL: if(TextureOpCaps & D3DTEXOPCAPS_MODULATE) { - cOp = D3DTOP_SELECTARG1; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_SELECTARG1; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILCOLOR_SCALE: if(TextureOpCaps & D3DTEXOPCAPS_MODULATE) { - cOp = D3DTOP_MODULATE; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_MODULATE; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILCOLOR_INVSCALE: if(TextureOpCaps & D3DTEXOPCAPS_ADDSMOOTH) { - cOp = D3DTOP_ADDSMOOTH; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_ADDSMOOTH; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILCOLOR_ADD: if(TextureOpCaps & D3DTEXOPCAPS_ADD) { - cOp = D3DTOP_ADD; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_ADD; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILCOLOR_SUB: if(TextureOpCaps & D3DTEXOPCAPS_SUBTRACT) { - cOp = D3DTOP_SUBTRACT; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_SUBTRACT; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILCOLOR_SUBR: if(TextureOpCaps & D3DTEXOPCAPS_SUBTRACT) { - cOp = D3DTOP_SUBTRACT; - cArg1 = D3DTA_CURRENT; - cArg2 = D3DTA_TEXTURE; + SeccOp = D3DTOP_SUBTRACT; + SeccArg1 = D3DTA_CURRENT; + SeccArg2 = D3DTA_TEXTURE; } break; case ShaderClass::DETAILCOLOR_BLEND: if(TextureOpCaps & D3DTEXOPCAPS_BLENDTEXTUREALPHA) { - cOp = D3DTOP_BLENDTEXTUREALPHA; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_BLENDTEXTUREALPHA; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILCOLOR_DETAILBLEND: if(TextureOpCaps & D3DTEXOPCAPS_BLENDCURRENTALPHA) { - cOp = D3DTOP_BLENDCURRENTALPHA; - cArg1 = D3DTA_TEXTURE; - cArg2 = D3DTA_CURRENT; + SeccOp = D3DTOP_BLENDCURRENTALPHA; + SeccArg1 = D3DTA_TEXTURE; + SeccArg2 = D3DTA_CURRENT; } break; } } - DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_COLOROP,cOp); - DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_COLORARG1,cArg1); - DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_COLORARG2,cArg2); + DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_COLOROP,SeccOp); + DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_COLORARG1,SeccArg1); + DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_COLORARG2,SeccArg2); } diff &= ~(ShaderClass::MASK_POSTDETAILCOLORFUNC); - if(diff & (ShaderClass::MASK_POSTDETAILALPHAFUNC|ShaderClass::MASK_TEXTURING)) + if(diff & seca_mask) { - D3DTEXTUREOP aOp = D3DTOP_DISABLE; - DWORD aArg1 = D3DTA_TEXTURE; - DWORD aArg2 = D3DTA_CURRENT; - if(Get_Texturing() == ShaderClass::TEXTURING_ENABLE) { switch(Get_Post_Detail_Alpha_Func()) @@ -769,34 +778,34 @@ void ShaderClass::Apply() case ShaderClass::DETAILALPHA_DETAIL: if(TextureOpCaps & D3DTEXOPCAPS_MODULATE) { - aOp = D3DTOP_SELECTARG1; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + SecaOp = D3DTOP_SELECTARG1; + SecaArg1 = D3DTA_TEXTURE; + SecaArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILALPHA_SCALE: if(TextureOpCaps & D3DTEXOPCAPS_MODULATE) { - aOp = D3DTOP_MODULATE; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + SecaOp = D3DTOP_MODULATE; + SecaArg1 = D3DTA_TEXTURE; + SecaArg2 = D3DTA_CURRENT; } break; case ShaderClass::DETAILALPHA_INVSCALE: if(TextureOpCaps & D3DTEXOPCAPS_ADDSMOOTH) { - aOp = D3DTOP_ADDSMOOTH; - aArg1 = D3DTA_TEXTURE; - aArg2 = D3DTA_CURRENT; + SecaOp = D3DTOP_ADDSMOOTH; + SecaArg1 = D3DTA_TEXTURE; + SecaArg2 = D3DTA_CURRENT; } break; } } - DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_ALPHAOP,aOp); - DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_ALPHAARG1,aArg1); - DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_ALPHAARG2,aArg2); + DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_ALPHAOP,SecaOp); + DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_ALPHAARG1,SecaArg1); + DX8Wrapper::Set_DX8_Texture_Stage_State(1,D3DTSS_ALPHAARG2,SecaArg2); } diff &= ~(ShaderClass::MASK_POSTDETAILALPHAFUNC); diff &= ~(ShaderClass::MASK_TEXTURING); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp deleted file mode 100644 index d62cdc45f0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.cpp +++ /dev/null @@ -1,1273 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWPhys * - * * - * $Archive:: /Commando/Code/ww3d2/shattersystem.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 7/11/01 9:49p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "shattersystem.h" -#include "assetmgr.h" -#include "mesh.h" -#include "meshmdl.h" -#include "dynamesh.h" -#include "htree.h" -#include "plane.h" -#include "simplevec.h" -#include "wwstring.h" -#include "vp.h" -#include "meshmatdesc.h" -#include - -/* -** Debug logging for the shatter system -*/ -#define SHATTER_DEBUG_LOG_ENABLED 0 -#if (SHATTER_DEBUG_LOG_ENABLED) -#define SHATTER_DEBUG_SAY(x) WWDEBUG_SAY(x) -#else -#define SHATTER_DEBUG_SAY(x) -#endif - - - -#define SHATTER_PATTERN_FORMAT "ShatterPlanes%d" - -#define BPT_FRONT 0x01 -#define BPT_BACK 0x02 -#define BPT_ON 0x04 -#define BPT_BOTH 0x08 -#define BPT_EPSILON 0.0001f -#define BPT_COINCIDENCE_EPSILON 0.000001f - - -/** -** Mesh Material Parameters -*/ -class MeshMtlParamsClass -{ -public: - MeshMtlParamsClass(MeshModelClass * model); - ~MeshMtlParamsClass(void); - - int PassCount; - - /* - ** NOTE: currently I do not fully support stage 1 textures or texture arrays in any pass. - ** The uv coordinates will be computed but the textures will not be set up. - */ - unsigned * DCG[MeshMatDescClass::MAX_PASSES]; - unsigned * DIG[MeshMatDescClass::MAX_PASSES]; - Vector2 * UV[MeshMatDescClass::MAX_PASSES][MeshMatDescClass::MAX_TEX_STAGES]; -// Vector3i * UVIndexArray[MeshMatDescClass::MAX_PASSES]; -}; - - - -/** -** VertexClass -** Temporary representation of vertices as they are being clipped -*/ -class VertexClass -{ -public: - - VertexClass(void); - VertexClass(const VertexClass & that); - VertexClass & operator = (const VertexClass & that); - - int Which_Side(const PlaneClass & plane) const; - - Vector3 Position; - Vector3 Normal; - - int PassCount; - unsigned DCG[MeshMatDescClass::MAX_PASSES]; - unsigned DIG[MeshMatDescClass::MAX_PASSES]; - Vector2 TexCoord[MeshMatDescClass::MAX_PASSES][MeshMatDescClass::MAX_TEX_STAGES]; - - static void Lerp(const VertexClass & v0,const VertexClass & v1,float lerp,VertexClass * res); - static void Intersect_Plane(const VertexClass & v0,const VertexClass & v1,const PlaneClass & plane,VertexClass * res); -}; - -/** -** PolygonClass -** Temporary representation of polygons as they are being clipped -*/ -class PolygonClass -{ -public: - - enum { BPT_POLY_MAX_VERTS = 24 }; - - PolygonClass(void); - PolygonClass(const PolygonClass & that); - PolygonClass(const VertexClass * points, int num); - PolygonClass & operator = (const PolygonClass & that); - - // Accessors - const VertexClass & operator[] (int i) const { return Verts[i]; } - VertexClass & operator[] (int i) { return Verts[i]; } - - int Get_Vertex_Count(void) const { return NumVerts; } - int Get_Material_ID(void) const { return MaterialId; } - const PlaneClass & Get_Plane(void) const { return Plane; } - - void Set_Vertex_Count(int count) { NumVerts = count; } - void Set_Material_Id(int id) { MaterialId = id; } - void Set_Plane(const PlaneClass & plane) { Plane = plane; } - - // Operations - void Compute_Plane(void); - int Which_Side(const PlaneClass & plane) const; - void Split(const PlaneClass & plane,PolygonClass & front,PolygonClass & back) const; - bool Is_Degenerate(void); - bool Salvage_Degenerate(void); - -public: - - int MaterialId; - int NumVerts; - VertexClass Verts[BPT_POLY_MAX_VERTS]; - - PlaneClass Plane; - -}; - -/** -** BSPClass -** Representation of a node in a BSP clipping tree in the shatter system -** Meshes are "shattered" by clipping them with a fixed BSP tree. -** The resulting leaf polygons are turned into separate dynamic objects -** which are thrown around in the world. The BSP tree is constructed -** using an HTree where each transform in the tree is used as a clipping -** plane. The plane is defined by the x-y plane of the coordinate system -** (i.e. z-axis is the normal of the plane, origin is a point on the plane). -** Leaf nodes of this tree will have two indices. These are indices into -** the MeshFragments array where they put the polygons in thier front and -** back half-spaces. -*/ -class BSPClass -{ -public: - BSPClass(HTreeClass * tree,int bone_index,int & leaf_index); - ~BSPClass(void); - - const PlaneClass & Get_Plane(void) { return Plane; } - BSPClass * Get_Front_Child(void) { return Front; } - BSPClass * Get_Back_Child(void) { return Back; } - - void Clip_Polygon(const PolygonClass & poly); - -protected: - - void Set_Plane_From_Transform(const Matrix3D & tm); - - PlaneClass Plane; // plane equation - BSPClass * Front; // pointers to child clipping planes - BSPClass * Back; - int FrontLeafIndex; // if a leaf node, has two mesh fragment indices - int BackLeafIndex; -}; - - -/*********************************************************************************************** -** -** Static Variables -** ShatterPatterns - Array of BSP-trees for clipping (shattering) messhes -** ClippedPolygonPool - Array of polygon arrays, one per leaf. -** MeshFragments - Array of resultant clipped meshes, one per leaf -** TmpVertPositions - Workspace for transforming vertex positions -** TmpVertNormals - Workspace for transforming vertex normals -** -***********************************************************************************************/ - -enum { MAX_MESH_FRAGMENTS = 32 }; -static SimpleDynVecClass ShatterPatterns; -static SimpleDynVecClass ClipPools[MAX_MESH_FRAGMENTS]; -static SimpleDynVecClass MeshFragments(MAX_MESH_FRAGMENTS); -static SimpleVecClass TmpVertPositions(256); -static SimpleVecClass TmpVertNormals(256); - - -/*********************************************************************************************** -** -** Local static utility functions -** -***********************************************************************************************/ -static Vector3 * _get_temp_vertex_position_array(int count) -{ - if (TmpVertPositions.Length() < count) { - TmpVertPositions.Resize(count); - } - return &(TmpVertPositions[0]); -} - -static Vector3 * _get_temp_vertex_normal_array(int count) -{ - if (TmpVertNormals.Length() < count) { - TmpVertNormals.Resize(count); - } - return &(TmpVertNormals[0]); -} - -/*********************************************************************************************** -** -** MeshMtlParamsClass Implementation -** -***********************************************************************************************/ -MeshMtlParamsClass::MeshMtlParamsClass(MeshModelClass * model) -{ - PassCount = model->Get_Pass_Count(); - - for (int ipass=0; ipassGet_DCG_Array(ipass); - DIG[ipass] = model->Get_DIG_Array(ipass); -// UVIndexArray[ipass] = model->Get_UVIndex_Array(ipass,false); - for (int istage=0; istage(model->Get_UV_Array(ipass,istage)); - } - } -} - -MeshMtlParamsClass::~MeshMtlParamsClass(void) -{ -} - - -/*********************************************************************************************** -** -** VertexClass Implementation -** -***********************************************************************************************/ -VertexClass::VertexClass(void) : - Position(0,0,0), - Normal(0,0,1), - PassCount(0) -{ - for (int ipass=0; ipass= -BPT_EPSILON); - assert(lerp <= 1.0 + BPT_EPSILON); - assert(v0.PassCount==v1.PassCount); - res->PassCount = v0.PassCount; - - // interpolate position - Vector3::Lerp(v0.Position,v1.Position,lerp,&(res->Position)); - - // interpolate normal, renormalize - Vector3::Lerp(v0.Normal,v1.Normal,lerp,&(res->Normal)); - res->Normal.Normalize(); - - // interpolate material properies - for (int ipass=0; ipassDCG[ipass]); - Vector4::Lerp(dig_v0,dig_v1,res->DIG[ipass]); -// Vector4::Lerp(v0.DCG[ipass],v1.DCG[ipass],lerp,&(res->DCG[ipass])); -// Vector4::Lerp(v0.DIG[ipass],v1.DIG[ipass],lerp,&(res->DIG[ipass])); - for (int istage=0; istageTexCoord[ipass][istage])); - } - } -} - -int VertexClass::Which_Side(const PlaneClass & plane) const -{ - float d = Vector3::Dot_Product(plane.N,Position); - d -= plane.D; - - if (d > BPT_EPSILON) { - return BPT_FRONT; - } - - if (d < -BPT_EPSILON) { - return BPT_BACK; - } - - return BPT_ON; -} - -void VertexClass::Intersect_Plane -( - const VertexClass & p0, - const VertexClass & p1, - const PlaneClass & plane, - VertexClass * res -) -{ - float alpha = 0.0f; - plane.Compute_Intersection(p0.Position,p1.Position,&alpha); - VertexClass::Lerp(p0,p1,alpha,res); -} - - - -/*********************************************************************************************** -** -** PolygonClass Implementation -** -***********************************************************************************************/ -PolygonClass::PolygonClass(void) : - NumVerts(0) -{ -} - -PolygonClass::PolygonClass(const PolygonClass & that) -{ - NumVerts = that.NumVerts; - for (int i=0;iGet_Transform(bone_index)); - int front = -1; - int back = -1; - - // search for a front and back child of this bone - for (int ibone=0; ibone < tree->Num_Pivots(); ibone++) { - if (tree->Get_Parent_Index(ibone) == bone_index) { - - // found a child, now see if it is the front or back child - Vector3 point = tree->Get_Transform(ibone).Get_Translation(); - if (Plane.In_Front(point)) { - front = ibone; - } else { - back = ibone; - } - - } - } - - // Recurse if we have children, otherwise assign leaf indices - if (front != -1) { - Front = W3DNEW BSPClass(tree,front,leaf_index); - } else { - FrontLeafIndex = leaf_index++; - } - - if (back != -1) { - Back = W3DNEW BSPClass(tree,back,leaf_index); - } else { - BackLeafIndex = leaf_index++; - } -} - -BSPClass::~BSPClass(void) -{ - if (Front != NULL) { - delete Front; - } - if (Back != NULL) { - delete Back; - } - Front = Back = NULL; -} - -void BSPClass::Set_Plane_From_Transform(const Matrix3D & tm) -{ - Plane.Set(tm.Get_Z_Vector(),tm.Get_Translation()); -} - -void BSPClass::Clip_Polygon(const PolygonClass & polygon) -{ - PolygonClass front_poly,back_poly; - front_poly.Set_Vertex_Count(0); - back_poly.Set_Vertex_Count(0); - - switch(polygon.Which_Side(Plane)) - { - case BPT_FRONT: case BPT_ON: - front_poly = polygon; - break; - case BPT_BACK: - back_poly = polygon; - break; - default: - polygon.Split(Plane,front_poly,back_poly); - break; - }; - - // Process the front halfspace: Recurse if we have a child clipping plane, - // otherwise add our polygons to our assigned clipping pool - if (Front == NULL) { - // We're a leaf node so put the polygons into the mesh fragment arrays - if (front_poly.Get_Vertex_Count() >= 3) { - ClipPools[FrontLeafIndex].Add(front_poly); - } - } else { - // Pass the polygons to our child for further clipping - if (front_poly.Get_Vertex_Count() >= 3) { - Front->Clip_Polygon(front_poly); - } - } - - // Process the back halfspace: - if (Back==NULL) { - if (back_poly.Get_Vertex_Count() >= 3) { - ClipPools[BackLeafIndex].Add(back_poly); - } - } else { - if (back_poly.Get_Vertex_Count() >= 3) { - Back->Clip_Polygon(back_poly); - } - } -} - - - - -/*********************************************************************************************** -** -** ShatterSystem Implementation - this is the interface with the outside world -** -** Transform meshes into space needed for shattering: -** Vshatter = Mscale-to-unit * Mworld-shatterview * Mobj-world * Vobj -** -***********************************************************************************************/ -void ShatterSystem::Init(void) -{ - /* - ** Resize the Mesh Fragment pointer array to handle the maximum number - ** of mesh fragments. - */ - MeshFragments.Resize(MAX_MESH_FRAGMENTS); - - /* - ** Search for ShatterPattern hierarchy tree objects, beginning with ShatterPattern00 - ** Create a BSP structure for each one. - */ - StringClass htree_name; - htree_name.Format(SHATTER_PATTERN_FORMAT,0); - - if (WW3DAssetManager::Get_Instance()==NULL) - return; // WorldBuilderTool doesn't initialize the asset manager. jba. -#if 1 - HTreeClass *htree = NULL; -#else - HTreeClass * htree = WW3DAssetManager::Get_Instance()->Get_HTree(htree_name); -#endif - while (htree != NULL) { - if ((htree->Num_Pivots() > 1) && (htree->Num_Pivots() < MAX_MESH_FRAGMENTS)) { - int leaf_counter = 0; - htree->Base_Update(Matrix3D(1)); - ShatterPatterns.Add(W3DNEW BSPClass(htree,1,leaf_counter)); - } - - /* - ** Try to load the next tree - */ - htree_name.Format(SHATTER_PATTERN_FORMAT,ShatterPatterns.Count()); - htree = WW3DAssetManager::Get_Instance()->Get_HTree(htree_name); - } -} - -void ShatterSystem::Shutdown(void) -{ - /* - ** Release all mesh fragments - */ - Release_Fragments(); - - /* - ** Release any loaded BSP trees - */ - for (int i=0; iGet_Model(); - if (model->Get_Pass_Count() > MeshMatDescClass::MAX_PASSES) { - WWDEBUG_SAY(("Failed to shatter model: %s. Too many passes (%d)\n",model->Get_Name(),model->Get_Pass_Count())); - REF_PTR_RELEASE(model); - return; - } - for (ipass=0; ipassGet_Pass_Count(); ipass++) { - if (model->Has_Material_Array(ipass) || model->Has_Shader_Array(ipass)) { - WWDEBUG_SAY(("Failed to shatter model: %s. It has shader or material arrays\n",model->Get_Name())); - REF_PTR_RELEASE(model); - return; - } - - for (istage=0; istageHas_Texture_Array(ipass,istage)) { - WWDEBUG_SAY(("Failed to shatter model: %s. Texture array in pass: %d stage: %d\n",model->Get_Name(),ipass,istage)); - REF_PTR_RELEASE(model); - return; - } - } - } - - /* - ** Grab a random shatter pattern - */ - BSPClass * clipper = ShatterPatterns[rand() % ShatterPatterns.Count()]; - - /* - ** Compute transforms which take vertices from mesh-space to shatter-space - ** and back again. Transform polygons into "shatter-space", clip, then - ** transform the results back out - ** - ** Take vertices from obj-space to shatter space: - ** Vshatter = Mscale-to-unit * Mworld-shatterview * Mobj-world * Vobj - ** - ** Clip the polygons to the BSP - ** Vclipped = BSP_CLIP(Vshatter) - ** - ** Next, take the verts back to object space: - ** Vobjclip = Inverse(Mscale-to-unit * Mworld-shatter * Mobj-world) * Vclipped - ** = Inv(Mobj-world)*Inv(Mworld-shatter)*Inv(Mscl-to-unit) * Vclipped - ** - ** Next, create separate, re-centered meshes - ** Vnewobj = Mold-obj-to-new-obj * Vobjclip - */ - - /* - ** Object-space to world-space transform - */ - Matrix3D Mobj_to_world = mesh->Get_Transform(); - - /* - ** World-space to shatter-space transform - */ - Matrix3D Mshatter_to_world; - Matrix3D Mworld_to_shatter; - Mshatter_to_world.Look_At(point,point+direction,0.0f); // TODO: could put random roll - Mshatter_to_world.Get_Orthogonal_Inverse(Mworld_to_shatter); - - /* - ** Final pair of matrices - */ - Matrix3D Mobj_to_shatter; - Matrix3D Mshatter_to_obj; - - Matrix3D::Multiply(Mworld_to_shatter,Mobj_to_world,&Mobj_to_shatter); - Mobj_to_shatter.Get_Orthogonal_Inverse(Mshatter_to_obj); - - /* - ** Scaling matrices. This could be simpler if Matrix3D had a full inverse function. - */ - SphereClass sphere; - model->Get_Bounding_Sphere(&sphere); - - float scale_factor = 5.0f / sphere.Radius; // mesh scales to 5x shatter pattern. - Matrix3D Mscale_to_shatter(1); - Matrix3D Mscale_from_shatter(1); - Mscale_to_shatter.Scale(scale_factor); - Mscale_from_shatter.Scale(1.0f / scale_factor); - - Matrix3D::Multiply(Mscale_to_shatter,Mobj_to_shatter,&Mobj_to_shatter); - Matrix3D::Multiply(Mshatter_to_obj,Mscale_from_shatter,&Mshatter_to_obj); - - /* - ** Grab the arrays out of the mesh and transform verts and vnorms - ** into "shatter-space" - */ - const TriIndex * polys = model->Get_Polygon_Array(); - const Vector3 * src_verts = model->Get_Vertex_Array(); - const Vector3 * src_vnorms = model->Get_Vertex_Normal_Array(); - - Vector3 * verts = _get_temp_vertex_position_array(model->Get_Vertex_Count()); - VectorProcessorClass::Transform(verts,src_verts,Mobj_to_shatter,model->Get_Vertex_Count()); - - /* - ** Build a description of the material parameters for the mesh - */ - MeshMtlParamsClass mtl_params(model); - - - SHATTER_DEBUG_SAY(("****************************************************\n")); - SHATTER_DEBUG_SAY((" Clipping model: %s\n",model->Get_Name())); - SHATTER_DEBUG_SAY(("****************************************************\n")); - - /* - ** Pass each polygon of the source model through the BSP clipper - */ - for (ipoly=0; ipolyGet_Polygon_Count(); ipoly++) { - - /* - ** Set up a PolygonClass for polygon 'i' in the mesh - */ - SHATTER_DEBUG_SAY(("Passing polygon %d to clipper.\n",ipoly)); - PolygonClass polygon; - for (ivert=0; ivert<3; ivert++) { - - int vert_index = polys[ipoly][ivert]; - polygon.Verts[ivert].PassCount = mtl_params.PassCount; - polygon.Verts[ivert].Position = verts[vert_index]; - polygon.Verts[ivert].Normal = src_vnorms[vert_index]; - SHATTER_DEBUG_SAY(("position: %f %f %f\n",verts[vert_index].X,verts[vert_index].Y,verts[vert_index].Z)); - SHATTER_DEBUG_SAY(("normal: %f %f %f\n",src_vnorms[vert_index].X,src_vnorms[vert_index].Y,src_vnorms[vert_index].Z)); - - for (ipass=0; ipassClip_Polygon(polygon); - } - - /* - ** convert the clipped polygons into meshes - */ - Process_Clip_Pools(Mshatter_to_obj,mesh,mtl_params); - - /* - ** release resources - */ - REF_PTR_RELEASE(model); -} - -int ShatterSystem::Get_Fragment_Count(void) -{ - return MeshFragments.Count(); -} - -RenderObjClass * ShatterSystem::Get_Fragment(int fragment_index) -{ - if (MeshFragments[fragment_index] != NULL) { - MeshFragments[fragment_index]->Add_Ref(); - } - return MeshFragments[fragment_index]; -} - -RenderObjClass * ShatterSystem::Peek_Fragment(int fragment_index) -{ - return MeshFragments[fragment_index]; -} - -void ShatterSystem::Release_Fragments(void) -{ - // release any ref's to render objects - for (int i=0; iGet_Model(); - WWASSERT(model != NULL); - - /* - ** Loop over all ClipPools and build a mesh for any that contain polygons - */ - for (int ipool=0; ipool 0) { - - int ivert,ipoly,ipass,istage; - - /* - ** Count the verts and polys - */ - int pcount = 0; - int vcount = 0; - for (ipoly=0;ipolyGet_Name())); - SHATTER_DEBUG_SAY((" polycount = %d vertexcount = %d\n",pcount,vcount)); - SHATTER_DEBUG_SAY(("****************************************************\n")); - - /* - ** Create the new mesh, install materials - */ - DynamicMeshClass * new_mesh = NEW_REF(DynamicMeshClass,(pcount,vcount)); - MaterialInfoClass * matinfo = NEW_REF(MaterialInfoClass,()); - - if (model->Get_Flag(MeshModelClass::SORT)) { - new_mesh->Enable_Sort(); - } - new_mesh->Set_Pass_Count(mtl_params.PassCount); - - bool has_textures = false; - for (ipass=0; ipassGet_Pass_Count(); ipass++) { - if (model->Peek_Single_Material(ipass) != NULL) { - matinfo->Add_Vertex_Material(model->Peek_Single_Material(ipass)); - } - if (model->Peek_Single_Texture(ipass) != NULL) { - matinfo->Add_Texture(model->Peek_Single_Texture(ipass)); - has_textures = true; - } - } - new_mesh->Set_Material_Info(matinfo); - - for (ipass=0; ipassGet_Pass_Count(); ipass++) { - new_mesh->Set_Vertex_Material(model->Peek_Single_Material(ipass),false,ipass); - new_mesh->Set_Shader(model->Get_Single_Shader(ipass),ipass); - - TextureClass * tex = model->Peek_Single_Texture(ipass,0); - if (tex != NULL) { - new_mesh->Set_Texture(tex,true,ipass); - } - } - - REF_PTR_RELEASE(matinfo); - - - /* - ** Add the polygons and vertices to the mesh, transform the vertices - ** back into the original mesh's coordinate system as we do this - */ - for (ipoly=0; ipolyBegin_Tri_Fan(); - SHATTER_DEBUG_SAY(("Begin Tri Fan\n")); - - for(ivert=0; ivertBegin_Vertex(); - SHATTER_DEBUG_SAY(("postion: %f %f %f\n",pos.X,pos.Y,pos.Z)); - new_mesh->Location_Inline(pos); - new_mesh->Normal(norm); - - for (ipass=0; ipassDCG(Vector3(vert.DCG[ipass].X,vert.DCG[ipass].Y,vert.DCG[ipass].Z),ipass); - new_mesh->Alpha(vert.DCG[ipass].W,ipass); - */ - mycolor=vert.DCG[ipass]; - } - - if (mtl_params.DIG[ipass] != NULL) { - SHATTER_DEBUG_SAY(("DIG: pass:%d: %f %f %f\n",ipass,vert.DIG[ipass].X,vert.DIG[ipass].Y,vert.DIG[ipass].Z)); - Vector4 mc=DX8Wrapper::Convert_Color(mycolor); - Vector4 dc=DX8Wrapper::Convert_Color(vert.DIG[ipass]); - mc=Vector4(mc.X*dc.X,mc.Y*dc.Y,mc.Z*dc.Z,mc.W); - mycolor=DX8Wrapper::Convert_Color(mc); - } - - new_mesh->Color(mycolor); - - /* - ** If there were UV coordinates in the original mesh for either stage, - ** then copy the vertex's uv's into into the new mesh. - */ - for (istage=0; istageUV(vert.TexCoord[ipass][istage]); - } - } - } - - new_mesh->End_Vertex(); - - /* - ** Set the texture for each pass and stage. - ** TODO: support texture arrays? - ** TODO: support stage 1 textures - */ - for (ipass=0; ipassPeek_Single_Texture(ipass,0); - if (tex != NULL) { - new_mesh->Set_Texture(tex,true,ipass); - } - } - } - new_mesh->End_Tri_Fan(); - } - - /* - ** Offset all vertices so that the bounding box center is 0,0,0 and - ** record that offset into the transform of the mesh - */ - new_mesh->Set_Dirty_Bounds(); - Vector3 center = new_mesh->Get_Bounding_Box().Center; - - new_mesh->Translate_Vertices(-center); - - Matrix3D tm(1);// = mesh->Get_Transform(); - tm.Translate(center); - Matrix3D::Multiply(tm,mesh->Get_Transform(),&tm); - new_mesh->Set_Transform(tm); - - /* - ** We gave it good vertex normals so clear their dirty flag - */ - new_mesh->Set_Dirty_Bounds(); - new_mesh->Set_Dirty_Planes(); - new_mesh->Clear_Dirty_Vertex_Normals(); - - /* - ** Install it in the mesh fragment pool, transferring our reference - ** to the fragment array... - */ - MeshFragments.Add(new_mesh); - } - } - REF_PTR_RELEASE(model); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.h deleted file mode 100644 index 14b1e7ba19..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/shattersystem.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWPhys * - * * - * $Archive:: /Commando/Code/ww3d2/shattersystem.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SHATTERSYSTEM_H -#define SHATTERSYSTEM_H - -#include "always.h" - - -class MeshClass; -class PhysicsSceneClass; -class RenderObjClass; -class Vector3; -class Matrix3D; -class MeshMtlParamsClass; - - -/** -** ShatterSystem -** This collection of static functions is used to "shatter" a mesh into fragments and -** create projectile objects which use the generated fragments as their render object. -*/ -class ShatterSystem -{ -public: - - /* - ** Init and Shutdown, these are called from the main physics system init and - ** shutdown. The BSP shatter planes are loaded up and initialized in Init - ** and released in Shutdown. - */ - static void Init(void); - static void Shutdown(void); - - /* - ** Pass in the mesh you want shattered and the scene that you want - ** the shards to be placed in. - */ - static void Shatter_Mesh(MeshClass * mesh,const Vector3 & point,const Vector3 & velocity); - - /* - ** Use these methods to get access to the resultant mesh fragments - ** Get_Fragment_Count - returns the number of meshes created - ** Get_Fragment - returns a pointer (ref-counted!) to the 'n'th mesh - ** Relese_Fragments - call this when you are done, it causes the ShatterSystem - ** to release its references to the fragments. - */ - static int Get_Fragment_Count(void); - static RenderObjClass * Get_Fragment(int fragment_index); - static RenderObjClass * Peek_Fragment(int fragment_index); - static void Release_Fragments(void); - -protected: - - static void Reset_Clip_Pools(void); - static void Process_Clip_Pools(const Matrix3D &Mshatter_to_mesh,MeshClass * mesh,MeshMtlParamsClass & mtl_params); - - -}; - - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/snapPts.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/snapPts.h deleted file mode 100644 index d9eb37942b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/snapPts.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/snappts.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SNAPPTS_H -#define SNAPPTS_H - -#include "refcount.h" -#include "Vector.H" -#include "vector3.h" -#include "w3derr.h" - - -class ChunkLoadClass; - -class SnapPointsClass : public DynamicVectorClass, public RefCountClass -{ -public: - - WW3DErrorType Load_W3D(ChunkLoadClass & cload); - -protected: - - ~SnapPointsClass(void) {} - -}; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/snappts.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/snappts.cpp deleted file mode 100644 index c9dfe9c01b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/snappts.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/snappts.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "snapPts.h" -#include "chunkio.h" -#include "w3d_file.h" -#include "w3derr.h" - -WW3DErrorType SnapPointsClass::Load_W3D(ChunkLoadClass & cload) -{ - // this function assumes that a W3D_CHUNK_POINTS has been opened - int size = cload.Cur_Chunk_Length(); - int count = size / sizeof (W3dVectorStruct); - - Resize(count); - for (int i=0; isorting_state.vertex_buffer); REF_PTR_RELEASE(state->sorting_state.index_buffer); REF_PTR_RELEASE(state->sorting_state.material); - for (unsigned i=0;iGet_Max_Textures_Per_Pass();++i) + { REF_PTR_RELEASE(state->sorting_state.Textures[i]); } } @@ -431,7 +433,7 @@ void Release_Refs(SortingNodeStruct* state) static unsigned overlapping_node_count; static unsigned overlapping_polygon_count; static unsigned overlapping_vertex_count; -const unsigned MAX_OVERLAPPING_NODES=4096; +static const unsigned MAX_OVERLAPPING_NODES=4096; static SortingNodeStruct* overlapping_nodes[MAX_OVERLAPPING_NODES]; // ---------------------------------------------------------------------------- @@ -451,6 +453,7 @@ void SortingRendererClass::Insert_To_Sorting_Pool(SortingNodeStruct* state) } // ---------------------------------------------------------------------------- +//static unsigned prevLight = 0xffffffff; static void Apply_Render_State(RenderStateStruct& render_state) { @@ -467,7 +470,7 @@ static void Apply_Render_State(RenderStateStruct& render_state) if (render_state.Textures[6]) render_state.Textures[6]->Apply(); if (render_state.Textures[7]) render_state.Textures[7]->Apply(); */ - for (unsigned i=0;iGet_Max_Textures_Per_Pass();++i) { DX8Wrapper::Set_Texture(i,render_state.Textures[i]); } @@ -478,6 +481,7 @@ static void Apply_Render_State(RenderStateStruct& render_state) if (!render_state.material->Get_Lighting()) return; //no point changing lights if they are ignored. + //prevLight = render_state.lightsHash; if (render_state.LightEnable[0]) { DX8Wrapper::Set_DX8_Light(0,&render_state.Lights[0]); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp deleted file mode 100644 index 989c98140f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.cpp +++ /dev/null @@ -1,772 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/soundrobj.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 1/16/02 10:21a $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "soundrobj.h" - -#if noWWAUDIO //(gth) removing dependency on wwaudio - -#include "AudibleSound.h" -#include "Sound3D.h" -#include "WWAudio.h" -#include "ffactory.h" -#include "WWFILE.H" -#include "chunkio.h" -#include "scene.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Global variables -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjLoaderClass _SoundRenderObjLoader; - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjClass::SoundRenderObjClass (void) - : Flags (FLAG_STOP_WHEN_HIDDEN), - Sound (NULL), - IsInitialized (false) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjClass::SoundRenderObjClass (const SoundRenderObjClass &src) - : Flags (FLAG_STOP_WHEN_HIDDEN), - Sound (NULL), - IsInitialized (false) -{ - (*this) = src; - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// ~SoundRenderObjClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjClass::~SoundRenderObjClass (void) -{ - // - // Remove the old sound from the world (if necessary) - // - if (Sound != NULL) { - Sound->Attach_To_Object (NULL); - Sound->Remove_From_Scene (); - REF_PTR_RELEASE (Sound); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -////////////////////////////////////////////////////////////////////////////////// -const SoundRenderObjClass & -SoundRenderObjClass::operator= (const SoundRenderObjClass &src) -{ - // - // Create a definition from the src sound object - // - AudibleSoundDefinitionClass definition; - definition.Initialize_From_Sound (src.Sound); - - // - // Create the internal sound object from the definition - // - Set_Sound (&definition); - - // - // Copy the other misc settings - // - Name = src.Name; - return *this; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Sound -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Sound (AudibleSoundDefinitionClass *definition) -{ - // - // Remove the old sound from the world (if necessary) - // - if (Sound != NULL) { - Sound->Remove_From_Scene (); - REF_PTR_RELEASE (Sound); - } - - // - // Create the sound object from its definition - // - if (definition != NULL) { - Sound = (AudibleSoundClass *)definition->Create (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::On_Frame_Update (void) -{ - // - // Stop the sound from playing (if necessary) - // - if ( Sound != NULL && - Sound->Is_In_Scene () && - Sound->Is_Playing () == false) - { - Sound->Attach_To_Object (NULL); - Sound->Remove_From_Scene (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Hidden -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Hidden (int onoff) -{ - int before = Is_Not_Hidden_At_All (); - RenderObjClass::Set_Hidden (onoff); - - // - // If we've changed state, then update the visibility - // - if (IsInitialized == false || Is_Not_Hidden_At_All () != before) { - IsInitialized = true; - Update_On_Visibilty (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Visible -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Visible (int onoff) -{ - int before = Is_Not_Hidden_At_All (); - RenderObjClass::Set_Visible (onoff); - - // - // If we've changed state, then update the visibility - // - if (IsInitialized == false || Is_Not_Hidden_At_All () != before) { - IsInitialized = true; - Update_On_Visibilty (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Animation_Hidden -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Animation_Hidden (int onoff) -{ - int before = Is_Not_Hidden_At_All (); - RenderObjClass::Set_Animation_Hidden (onoff); - - // - // If we've changed state, then update the visibility - // - if (IsInitialized == false || Is_Not_Hidden_At_All () != before) { - IsInitialized = true; - Update_On_Visibilty (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Force_Visible -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Force_Visible (int onoff) -{ - int before = Is_Not_Hidden_At_All (); - RenderObjClass::Set_Force_Visible (onoff); - - // - // If we've changed state, then update the visibility - // - if (IsInitialized == false || Is_Not_Hidden_At_All () != before) { - IsInitialized = true; - Update_On_Visibilty (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Update_On_Visibilty -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Update_On_Visibilty (void) -{ - if (Sound == NULL) { - return ; - } - - // - // Ensure our transform is correct - // - Validate_Transform (); - - // - // Either add the sound object to the sound scene - // or remove it from the sound scene depending - // on the visibility state of the render object. - // - if ( Is_Not_Hidden_At_All () && - Sound->Is_In_Scene () == false && - Peek_Scene () != NULL) - { - // - // Make sure the sound is properly attached to this render - // object and then add it to the scene - // - Sound->Attach_To_Object (this); - Sound->Add_To_Scene (true); - - } else if ((Is_Not_Hidden_At_All () == false) || (Peek_Scene () == NULL)) { - - // - // Remove the sound from the scene (it will stop playing) - // - if ((Flags & FLAG_STOP_WHEN_HIDDEN) != 0 || (Peek_Scene () == NULL)) { - Sound->Attach_To_Object (NULL); - Sound->Remove_From_Scene (); - } - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Get_Sound -// -////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -SoundRenderObjClass::Get_Sound (void) const -{ - if (Sound != NULL) { - Sound->Add_Ref (); - } - - return Sound; -} - - -////////////////////////////////////////////////////////////////////////////// -// -// Set_Flag -// -////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Flag (uint32 flag, bool onoff) -{ - Flags &= ~flag; - if (onoff) { - Flags |= flag; - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Notify_Added -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Notify_Added (SceneClass *scene) -{ - RenderObjClass::Notify_Added (scene); - scene->Register (this, SceneClass::ON_FRAME_UPDATE); - - Update_On_Visibilty (); - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Notify_Removed -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Notify_Removed (SceneClass *scene) -{ - scene->Unregister (this, SceneClass::ON_FRAME_UPDATE); - RenderObjClass::Notify_Removed (scene); - - Update_On_Visibilty (); - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Transform -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Transform (const Matrix3D &tm) -{ - RenderObjClass::Set_Transform (tm); - - if (IsInitialized == false) { - IsInitialized = true; - Update_On_Visibilty (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_Position -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjClass::Set_Position (const Vector3 &pos) -{ - RenderObjClass::Set_Position (pos); - - if (IsInitialized == false) { - IsInitialized = true; - Update_On_Visibilty (); - } - - return ; -} - - -//********************************************************************************* -// -// Start of SoundRenderObjDefClass -// -//********************************************************************************* - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjDefClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjDefClass::SoundRenderObjDefClass (void) - : Version (W3D_CURRENT_SOUNDROBJ_VERSION), - Flags (SoundRenderObjClass::FLAG_STOP_WHEN_HIDDEN) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjDefClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjDefClass::SoundRenderObjDefClass (SoundRenderObjClass &render_obj) - : Version (W3D_CURRENT_SOUNDROBJ_VERSION), - Flags (SoundRenderObjClass::FLAG_STOP_WHEN_HIDDEN) -{ - Initialize (render_obj); - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjDefClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjDefClass::SoundRenderObjDefClass (const SoundRenderObjDefClass &src) - : Version (W3D_CURRENT_SOUNDROBJ_VERSION), - Flags (SoundRenderObjClass::FLAG_STOP_WHEN_HIDDEN) -{ - (*this) = src; - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// ~SoundRenderObjDefClass -// -////////////////////////////////////////////////////////////////////////////////// -SoundRenderObjDefClass::~SoundRenderObjDefClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -////////////////////////////////////////////////////////////////////////////////// -const SoundRenderObjDefClass & -SoundRenderObjDefClass::operator= (const SoundRenderObjDefClass &src) -{ - Definition = src.Definition; - Version = src.Version; - Name = src.Name; - return (*this); -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Create -// -////////////////////////////////////////////////////////////////////////////////// -RenderObjClass * -SoundRenderObjDefClass::Create (void) -{ - // - // Allocate and initialize a new instance - // - SoundRenderObjClass *render_obj = W3DNEW SoundRenderObjClass; - render_obj->Set_Name (Name); - render_obj->Set_Sound (&Definition); - render_obj->Set_Flags (Flags); - - return render_obj; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundRenderObjDefClass::Initialize (SoundRenderObjClass &render_obj) -{ - // - // Copy the settings from the sound object into our definition - // - Definition.Initialize_From_Sound (render_obj.Peek_Sound ()); - - // - // Copy the flags from the render object - // - Flags = (SoundRenderObjClass::FLAGS)render_obj.Get_Flags (); - - // - // Copy the name - // - Name = render_obj.Get_Name (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -/////////////////////////////////////////////////////////////////////////////////// -WW3DErrorType -SoundRenderObjDefClass::Load_W3D (ChunkLoadClass &cload) -{ - WW3DErrorType retval = WW3D_ERROR_LOAD_FAILED; - - // - // Attempt to read the different sections of the definition - // - if ((Read_Header (cload) == WW3D_ERROR_OK) && - (Read_Definition (cload) == WW3D_ERROR_OK)) - { - retval = WW3D_ERROR_OK; - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save_W3D -// -////////////////////////////////////////////////////////////////////////////////// -WW3DErrorType -SoundRenderObjDefClass::Save_W3D (ChunkSaveClass &csave) -{ - WW3DErrorType retval = WW3D_ERROR_SAVE_FAILED; - - // - // Begin a chunk that identifies a sound render object - // - if (csave.Begin_Chunk (W3D_CHUNK_SOUNDROBJ) == TRUE) { - - // - // Attempt to save the different sections of the aggregate definition - // - if ((Write_Header (csave) == WW3D_ERROR_OK) && - (Write_Definition (csave) == WW3D_ERROR_OK)) - { - retval = WW3D_ERROR_OK; - } - - csave.End_Chunk (); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Read_Header -// -/////////////////////////////////////////////////////////////////////////////////// -WW3DErrorType -SoundRenderObjDefClass::Read_Header (ChunkLoadClass &cload) -{ - WW3DErrorType retval = WW3D_ERROR_LOAD_FAILED; - - // - // Is this the header chunk? - // - if (cload.Open_Chunk () && - (cload.Cur_Chunk_ID () == W3D_CHUNK_SOUNDROBJ_HEADER)) - { - // - // Read the header from the chunk - // - W3dSoundRObjHeaderStruct header = { 0 }; - if (cload.Read (&header, sizeof (header)) == sizeof (header)) { - - // - // Copy the names from the header structure - // - Name = header.Name; - Version = header.Version; - Flags = (SoundRenderObjClass::FLAGS)header.Flags; - retval = WW3D_ERROR_OK; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Read_Definition -// -/////////////////////////////////////////////////////////////////////////////////// -WW3DErrorType -SoundRenderObjDefClass::Read_Definition (ChunkLoadClass &cload) -{ - WW3DErrorType retval = WW3D_ERROR_LOAD_FAILED; - - // - // Is this the right chunk? - // - if (cload.Open_Chunk () && - (cload.Cur_Chunk_ID () == W3D_CHUNK_SOUNDROBJ_DEFINITION)) - { - // - // Ask the definition to load its settings from the chunk - // - if (Definition.Load (cload)) { - retval = WW3D_ERROR_OK; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Write_Header -// -/////////////////////////////////////////////////////////////////////////////////// -WW3DErrorType -SoundRenderObjDefClass::Write_Header (ChunkSaveClass &csave) -{ - WW3DErrorType retval = WW3D_ERROR_SAVE_FAILED; - - // - // Begin a chunk that identifies the aggregate - // - if (csave.Begin_Chunk (W3D_CHUNK_SOUNDROBJ_HEADER) == TRUE) { - - // - // Fill the header structure - // - W3dSoundRObjHeaderStruct header = { 0 }; - header.Version = W3D_CURRENT_AGGREGATE_VERSION; - header.Flags = Flags; - ::lstrcpyn (header.Name, (const char *)Name, sizeof (header.Name)); - header.Name[sizeof (header.Name) - 1] = 0; - - // - // Write the header out to the chunk - // - if (csave.Write (&header, sizeof (header)) == sizeof (header)) { - retval = WW3D_ERROR_OK; - } - - // End the header chunk - csave.End_Chunk (); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Write_Definition -// -/////////////////////////////////////////////////////////////////////////////////// -WW3DErrorType -SoundRenderObjDefClass::Write_Definition (ChunkSaveClass &csave) -{ - WW3DErrorType retval = WW3D_ERROR_SAVE_FAILED; - - // - // Save the definition to its own chunk - // - if (csave.Begin_Chunk (W3D_CHUNK_SOUNDROBJ_DEFINITION) == TRUE) { - if (Definition.Save (csave)) { - retval = WW3D_ERROR_OK; - } - csave.End_Chunk (); - } - - return retval; -} - - -//********************************************************************************* -// -// Start of SoundRenderObjDefClass -// -//********************************************************************************* - - -/////////////////////////////////////////////////////////////////////////////////// -// -// Load_W3D -// -/////////////////////////////////////////////////////////////////////////////////// -PrototypeClass * -SoundRenderObjLoaderClass::Load_W3D (ChunkLoadClass &cload) -{ - SoundRenderObjPrototypeClass *prototype = NULL; - - // - // Create a definition object - // - SoundRenderObjDefClass *definition = W3DNEW SoundRenderObjDefClass; - if (definition != NULL) { - - // - // Ask the definition object to load the sound data - // - if (definition->Load_W3D (cload) == WW3D_ERROR_OK) { - - // - // Success! Create a prototype from the definition - // - prototype = W3DNEW SoundRenderObjPrototypeClass (definition); - } - - REF_PTR_RELEASE (definition); - } - - return prototype; -} - -#endif // noWWAUDIO - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.h deleted file mode 100644 index a57ba7beb1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/soundrobj.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/soundrobj.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 1/15/02 5:57p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDROBJ_H -#define __SOUNDROBJ_H - -// TheSuperHackers @compile xezon 05/04/2025 Compile in WWAUDIO for Renegade's w3dview tool. -#define noWWAUDIO 1 - -#if noWWAUDIO // (gth) removing dependency on WWAUDIO - -#include "rendobj.h" -#include "wwstring.h" -#include "proto.h" -#include "w3d_file.h" -#include "w3derr.h" -#include "AudibleSound.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Forward declarations -////////////////////////////////////////////////////////////////////////////////// -class ChunkSaveClass; -class ChunkLoadClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjClass -// -// This object is used to trigger a sound effect in the world. When the object -// is shown, its associated sound is added to the world and played, when the object -// is hidden, the associated sound is stopped and removed from the world. -// -// This is handy when used in conjunction with the aggregate system for creating -// complex animations. -// -////////////////////////////////////////////////////////////////////////////////// -class SoundRenderObjClass : public RenderObjClass -{ -public: - - //////////////////////////////////////////////////////////////// - // Public flags - //////////////////////////////////////////////////////////////// - typedef enum - { - FLAG_STOP_WHEN_HIDDEN = 0x00000001, - - } FLAGS; - - /////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////// - SoundRenderObjClass (void); - SoundRenderObjClass (const SoundRenderObjClass &src); - virtual ~SoundRenderObjClass (void); - - /////////////////////////////////////////////////////////// - // Public operators - /////////////////////////////////////////////////////////// - const SoundRenderObjClass &operator= (const SoundRenderObjClass &src); - - /////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////// - - // - // From RenderObjClass - // - RenderObjClass * Clone (void) const { return W3DNEW SoundRenderObjClass (*this); } - int Class_ID (void) const { return CLASSID_SOUND; } - const char * Get_Name (void) const { return Name; } - void Set_Name (const char *name) { Name = name; } - void Render (RenderInfoClass &rinfo) { } - void On_Frame_Update (void); - void Set_Hidden (int onoff); - void Set_Visible (int onoff); - void Set_Animation_Hidden (int onoff); - void Set_Force_Visible (int onoff); - void Notify_Added (SceneClass *scene); - void Notify_Removed (SceneClass *scene); - void Set_Transform(const Matrix3D &m); - void Set_Position(const Vector3 &v); - - // - // SoundRenderObjClass specific - // - virtual void Set_Sound (AudibleSoundDefinitionClass *definition); - virtual AudibleSoundClass * Get_Sound (void) const; - virtual AudibleSoundClass * Peek_Sound (void) const { return Sound; } - - // - // Flag support - // - uint32 Get_Flags (void) const { return Flags; } - void Set_Flags (uint32 flags) { Flags = flags; } - bool Get_Flag (uint32 flag) { return bool((Flags & flag) == flag); } - void Set_Flag (uint32 flag, bool onoff); - - -protected: - - /////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////// - virtual void Update_On_Visibilty (void); - -private: - - /////////////////////////////////////////////////////////// - // Private member data - /////////////////////////////////////////////////////////// - bool IsInitialized; - StringClass Name; - AudibleSoundClass * Sound; - uint32 Flags; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjDefClass -// -////////////////////////////////////////////////////////////////////////////////// -class SoundRenderObjDefClass : public RefCountClass -{ -public: - - /////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////// - SoundRenderObjDefClass (void); - SoundRenderObjDefClass (SoundRenderObjClass &render_obj); - SoundRenderObjDefClass (const SoundRenderObjDefClass &src); - virtual ~SoundRenderObjDefClass (void); - - /////////////////////////////////////////////////////////// - // Public operators - /////////////////////////////////////////////////////////// - const SoundRenderObjDefClass &operator= (const SoundRenderObjDefClass &src); - - /////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////// - RenderObjClass * Create (void); - WW3DErrorType Load_W3D (ChunkLoadClass &cload); - WW3DErrorType Save_W3D (ChunkSaveClass &csave); - const char * Get_Name (void) const { return Name; } - void Set_Name (const char *name) { Name = name; } - SoundRenderObjDefClass * Clone (void) const { return NEW_REF( SoundRenderObjDefClass, (*this) ); } - - // - // Initialization - // - void Initialize (SoundRenderObjClass &render_obj); - -protected: - - /////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////// - - // - // Loading methods - // - WW3DErrorType Read_Header (ChunkLoadClass &cload); - WW3DErrorType Read_Definition (ChunkLoadClass &cload); - - // - // Saving methods - // - WW3DErrorType Write_Header (ChunkSaveClass &csave); - WW3DErrorType Write_Definition (ChunkSaveClass &csave); - -private: - - /////////////////////////////////////////////////////////// - // Private member data - /////////////////////////////////////////////////////////// - uint32 Version; - StringClass Name; - AudibleSoundDefinitionClass Definition; - SoundRenderObjClass::FLAGS Flags; -}; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjPrototypeClass -// -/////////////////////////////////////////////////////////////////////////////////// -class SoundRenderObjPrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(SoundRenderObjPrototypeClass) -public: - - /////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////// - SoundRenderObjPrototypeClass (SoundRenderObjDefClass *def) - : Definition (NULL) { Set_Definition (def); } - - /////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////// - const char * Get_Name(void) const { return Definition->Get_Name (); } - int Get_Class_ID(void) const { return RenderObjClass::CLASSID_SOUND; } - RenderObjClass * Create (void) { return Definition->Create (); } - virtual void DeleteSelf() { delete this; } - - SoundRenderObjDefClass * Peek_Definition (void) const { return Definition; } - void Set_Definition (SoundRenderObjDefClass *def) { REF_PTR_SET (Definition, def); } - -protected: - virtual ~SoundRenderObjPrototypeClass (void) { REF_PTR_RELEASE (Definition); } - -private: - - /////////////////////////////////////////////////////////// - // Private member data - /////////////////////////////////////////////////////////// - SoundRenderObjDefClass * Definition; -}; - - -/////////////////////////////////////////////////////////////////////////////////// -// -// SoundRenderObjLoaderClass -// -/////////////////////////////////////////////////////////////////////////////////// -class SoundRenderObjLoaderClass : public PrototypeLoaderClass -{ -public: - virtual int Chunk_Type (void) { return W3D_CHUNK_SOUNDROBJ; } - virtual PrototypeClass * Load_W3D (ChunkLoadClass &cload); -}; - - -/////////////////////////////////////////////////////////////////////////////////// -// Global variables -/////////////////////////////////////////////////////////////////////////////////// -extern SoundRenderObjLoaderClass _SoundRenderObjLoader; - -#endif //noWWAUDIO (gth) removing dependency on wwaudio - -#endif //__SOUNDROBJ_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp deleted file mode 100644 index f293b75e19..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.cpp +++ /dev/null @@ -1,1754 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/sphereobj.cpp $* - * * - * Org Author:: Greg Hjelstrom * - * * - * $Author:: Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 24 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * SphereRenderObjClass::SphereRenderObjClass -- Constructor * - * SphereRenderObjClass::SphereRenderObjClass -- Constructor - init from a definition * - * SphereRenderObjClass::SphereRenderObjClass -- Copy constructor * - * SphereRenderObjClass::operator -- assignment operator * - * SphereRenderObjClass::Get_Num_Polys -- returns number of polygons * - * SphereRenderObjClass::Get_Name -- returns name * - * SphereRenderObjClass::Set_Name -- sets the name * - * SphereRenderObjClass::render_Sphere -- submits the Sphere to the GERD * - * SphereRenderObjClass::vis_render_Sphere -- submits Sphere to the GERD for VIS * - * SphereRenderObjClass::SphereRenderObjClass -- constructor * - * SphereRenderObjClass::SphereRenderObjClass -- Constructor - init from a definition * - * SphereRenderObjClass::SphereRenderObjClass -- copy constructor * - * SphereRenderObjClass::SphereRenderObjClass -- Constructor from a wwmath aaSphere * - * SphereRenderObjClass::operator -- assignment operator * - * SphereRenderObjClass::Clone -- clones the Sphere * - * SphereRenderObjClass::Class_ID -- returns the class-id for AASphere's * - * SphereRenderObjClass::Render -- render this Sphere * - * SphereRenderObjClass::Special_Render -- special render this Sphere (vis) * - * SphereRenderObjClass::Set_Transform -- set the transform for this Sphere * - * SphereRenderObjClass::Set_Position -- Set the position of this Sphere * - * SphereRenderObjClass::update_cached_Sphere -- update the world-space version of this Spher* - * SphereRenderObjClass::Cast_Ray -- cast a ray against this Sphere * - * SphereRenderObjClass::Cast_AASphere -- cast an AASphere against this Sphere * - * SphereRenderObjClass::Cast_OBSphere -- cast an OBSphere against this Sphere * - * SphereRenderObjClass::Intersect_AASphere -- intersect this Sphere with an AASphere * - * SphereRenderObjClass::Intersect_OBSphere -- Intersect this Sphere with an OBSphere * - * SphereRenderObjClass::Get_Obj_Space_Bounding_Sphere -- return the object-space bounding sp* - * SphereRenderObjClass::Get_Obj_Space_Bounding_Sphere -- returns the obj-space bounding Sphe* - * SphereRenderObjClass::Scale -- scales sphere uniformly. * - * SphereRenderObjClass::Scale -- scales sphere non-uniformly. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "sphereobj.h" -#include "w3d_util.h" -#include "wwdebug.h" -#include "vertmaterial.h" -#include "ww3d.h" -#include "chunkio.h" -#include "rinfo.h" -#include "coltest.h" -#include "bound.h" -#include "inttest.h" -#include "predlod.h" -#include "matrix3.h" -#include "wwmath.h" -#include "assetmgr.h" -#include "wwstring.h" -#include "camera.h" -#include "statistics.h" -#include "dx8wrapper.h" -#include "dx8vertexbuffer.h" -#include "dx8indexbuffer.h" -#include "sortingrenderer.h" -#include "visrasterizer.h" - -static bool Sphere_Array_Valid = false; - -SphereMeshClass SphereMeshArray[SPHERE_NUM_LOD]; -float SphereLODCosts[SPHERE_NUM_LOD + 1]; // SPHERE_NUM_LOD doesn't include the null LOD - - -/* -** SphereRenderObjClass Implementation -*/ - -/*********************************************************************************************** - * SphereRenderObjClass::SphereRenderObjClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -SphereRenderObjClass::SphereRenderObjClass(void) - : anim_time (0.0F), - IsAnimating (true), - LODBias(1.0f), - CurrentLOD(SPHERE_NUM_LOD), // SPHERE_NUM_LOD does not include the null LOD - AnimDuration (0.0F), - SphereMaterial (NULL), - SphereTexture (NULL), - CurrentColor(0.75f, 0.75f, 0.75F), - CurrentAlpha(1.0f), - CurrentScale(1.0f, 1.0f, 1.0f), - CurrentVector(), - Flags(USE_ALPHA_VECTOR), - ObjSpaceCenter (0, 0, 0), - ObjSpaceExtent (1, 1, 1) -{ - Generate_Shared_Mesh_Arrays ( CurrentVector ); - - Orientation.Make_Identity(); - memset(Name,0,sizeof(Name)); - - Init_Material (); - - // So that the object is ready for use after construction, we will - // complete its initialization by initializing its value array - // according to a screen area of 1. - calculate_value_array(1.0f, Value); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::SphereRenderObjClass -- Constructor - init from a definition * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -SphereRenderObjClass::SphereRenderObjClass(const W3dSphereStruct & def) - : anim_time (0.0F), - IsAnimating (true), - LODBias(1.0f), - CurrentLOD(SPHERE_NUM_LOD), // SPHERE_NUM_LOD does not include the null LOD - AnimDuration (0.0F), - SphereMaterial (NULL), - SphereTexture (NULL), - CurrentColor(0.75f, 0.75f, 0.75F), - CurrentAlpha(1.0f), - CurrentScale(1.0f, 1.0f, 1.0f), - CurrentVector(), - Flags(USE_ALPHA_VECTOR), - ObjSpaceCenter (0, 0, 0), - ObjSpaceExtent (1, 1, 1) -{ - Generate_Shared_Mesh_Arrays ( CurrentVector ); - Init_Material (); - Orientation.Make_Identity(); - - // - // Initialize from the defintion - // - Set_Name(def.Name); - Set_Local_Center_Extent ( Vector3 (def.Center.X, def.Center.Y, def.Center.Z), - Vector3 (def.Extent.X, def.Extent.Y, def.Extent.Z)); - - if (def.TextureName[0] != 0) { - SphereTexture = WW3DAssetManager::Get_Instance ()->Get_Texture (def.TextureName); - } - - // So that the object is ready for use after construction, we will - // complete its initialization by initializing its value array - // according to a screen area of 1. - calculate_value_array(1.0f, Value); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::SphereRenderObjClass -- Copy constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -SphereRenderObjClass::SphereRenderObjClass(const SphereRenderObjClass & src) - : anim_time (0.0F), - IsAnimating (true), - LODBias(1.0f), - CurrentLOD(SPHERE_NUM_LOD), // SPHERE_NUM_LOD does not include the null LOD - AnimDuration (0.0F), - SphereMaterial (NULL), - SphereTexture (NULL), - CurrentColor(0.75f, 0.75f, 0.75F), - CurrentAlpha(1.0f), - CurrentScale(1.0f, 1.0f, 1.0f), - CurrentVector(), - Flags(USE_ALPHA_VECTOR), - ObjSpaceCenter (0, 0, 0), - ObjSpaceExtent (1, 1, 1) -{ - Generate_Shared_Mesh_Arrays ( CurrentVector ); - Init_Material (); - Orientation.Make_Identity(); - - *this = src; - - // So that the object is ready for use after construction, we will - // complete its initialization by initializing its value array - // according to a screen area of 1. - calculate_value_array(1.0f, Value); -} - -SphereRenderObjClass::~SphereRenderObjClass() -{ - REF_PTR_RELEASE(SphereMaterial); -} // destructor - -/*********************************************************************************************** - * SphereRenderObjClass::operator -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -SphereRenderObjClass & SphereRenderObjClass::operator = (const SphereRenderObjClass & that) -{ - if (this != &that) { - RenderObjClass::operator = (that); - Set_Name(that.Get_Name()); - CurrentColor = that.CurrentColor; - CurrentAlpha = that.CurrentAlpha; - CurrentScale = that.CurrentScale; - CurrentVector = that.CurrentVector; - Flags = that.Flags; - Orientation = that.Orientation; - SphereShader = that.SphereShader; - CachedBox = that.CachedBox; - anim_time = that.anim_time; - AnimDuration = that.AnimDuration; - ObjSpaceCenter = that.ObjSpaceCenter; - ObjSpaceExtent = that.ObjSpaceExtent; - ColorChannel = that.ColorChannel; - AlphaChannel = that.AlphaChannel; - ScaleChannel = that.ScaleChannel; - VectorChannel = that.VectorChannel; - - Set_Texture (that.SphereTexture); - } - - return *this; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Generate_Shared_Mesh_Arrays -- Generates mesh LOD arrays. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/08/00 pds : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Generate_Shared_Mesh_Arrays (const AlphaVectorStruct &alphavector) -{ - // Generate shared Mesh Arrays - if (!Sphere_Array_Valid) { - - float size = SPHERE_LOWEST_LOD; - float step = (SPHERE_HIGHEST_LOD - SPHERE_LOWEST_LOD); - step /= SPHERE_NUM_LOD; - - // For NULL LOD set Cost to a small nonzero amount to avoid divisions by zero. - SphereLODCosts[0] = 0.000001f; - for(int i=0; i < SPHERE_NUM_LOD; i++) { - - SphereMeshArray[i].Generate(1.0f, size, size); - SphereLODCosts[i + 1] = SphereMeshArray[i].Get_Num_Polys(); - - size+=step; - - SphereMeshArray[i].Set_Alpha_Vector( alphavector, false, false ); - - } - - Sphere_Array_Valid = true; - } - - return ; -} - - -// This is used both by Prepare_LOD and Calculate_Cost_Value_Arrays. -void SphereRenderObjClass::calculate_value_array(float screen_area, float *values) const -{ - values[0] = AT_MIN_LOD; - for (int lod = 1; lod <= SPHERE_NUM_LOD; lod++) { - float polycount = SphereLODCosts[lod]; - float benefit_factor = 1 - (0.5f / (polycount * polycount)); - values[lod] = (benefit_factor * screen_area * LODBias) / polycount; - } - values[SPHERE_NUM_LOD + 1] = AT_MAX_LOD; // Post-inc value will flag max LOD. -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Init_Material -- Sets up the material and default shader for the sphere.* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/08/00 pds : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Init_Material (void) -{ - REF_PTR_RELEASE (SphereMaterial); - - SphereMaterial = NEW_REF(VertexMaterialClass,()); - SphereMaterial->Set_Ambient(0,0,0); - SphereMaterial->Set_Diffuse(0,0,0); - SphereMaterial->Set_Specular(0,0,0); - SphereMaterial->Set_Emissive(1,1,1); - SphereMaterial->Set_Opacity(0.25f); - SphereMaterial->Set_Shininess(0.0f); - SphereMaterial->Set_Lighting(true); - - // Texturing, zbuffer, primary gradient, alpha blending - SphereShader = ShaderClass::_PresetAlphaShader; - - // (gth) Looks like sphere's were coded with backwards normals! Quick fix (though expensive) - // is to turn off backface culling... ug... - SphereShader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - -} // Init_Material - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Num_Polys -- returns number of polygons * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -int SphereRenderObjClass::Get_Num_Polys(void) const -{ - return SphereLODCosts[CurrentLOD]; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Set_Texture * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Set_Texture(TextureClass *tf) -{ - REF_PTR_SET(SphereTexture,tf); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Name -- returns name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -const char * SphereRenderObjClass::Get_Name(void) const -{ - return Name; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Set_Name -- sets the name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Set_Name(const char * name) -{ - WWASSERT(name != NULL); - WWASSERT(strlen(name) < 2*W3D_NAME_LEN); - strcpy(Name,name); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::render_sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/01/00 jga : Created. * - * 2/19/01 HY : upgraded to DX8 * - *=============================================================================================*/ -void SphereRenderObjClass::render_sphere() -{ - // Should never get here with NULL LOD - if (CurrentLOD == 0) { - WWASSERT(0); - return; - } - - SphereMeshClass & mesh = SphereMeshArray[CurrentLOD - 1]; - - if (SphereTexture) { - SphereShader.Set_Texturing (ShaderClass::TEXTURING_ENABLE); - } else { - SphereShader.Set_Texturing (ShaderClass::TEXTURING_DISABLE); - } - DX8Wrapper::Set_Shader(SphereShader); - DX8Wrapper::Set_Texture(0,SphereTexture); - DX8Wrapper::Set_Material(SphereMaterial); - - // Enable sorting if the primitive is translucent, alpha testing is not enabled, and sorting is enabled globally. - const bool sort = (SphereShader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO) && (SphereShader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE) && (WW3D::Is_Sorting_Enabled()); - const unsigned int buffer_type = sort ? BUFFER_TYPE_DYNAMIC_SORTING : BUFFER_TYPE_DYNAMIC_DX8; - - DynamicVBAccessClass vb(buffer_type, dynamic_fvf_type, mesh.Vertex_ct); - { - DynamicVBAccessClass::WriteLockClass Lock(&vb); - VertexFormatXYZNDUV2 *vb = Lock.Get_Formatted_Vertex_Array(); - - for (int i=0; ix = mesh.vtx[i].X; - vb->y = mesh.vtx[i].Y; - vb->z = mesh.vtx[i].Z; - - vb->nx = mesh.vtx_normal[i].X; // may not need this! - vb->ny = mesh.vtx_normal[i].Y; - vb->nz = mesh.vtx_normal[i].Z; - - if (Flags & USE_ALPHA_VECTOR) { - vb->diffuse = DX8Wrapper::Convert_Color(mesh.dcg[i]); - } else { - vb->diffuse = 0xFFFFFFFF; // TODO could combine the material color with this and turn off lighting - } - - if (SphereTexture) { - vb->u1 = mesh.vtx_uv[i].X; - vb->v1 = mesh.vtx_uv[i].Y; - } - vb++; - } - } - - DynamicIBAccessClass ib(buffer_type, mesh.face_ct*3); - { - DynamicIBAccessClass::WriteLockClass Lock(&ib); - unsigned short *mem=Lock.Get_Index_Array(); - for (int i=0; iProcess_Reduction(); - - Matrix3D temp = Transform; - - // Do Time Based Animation - animate(); - - // Scale - - Vector3 real_scale; - real_scale.X = ObjSpaceExtent.X * CurrentScale.X; - real_scale.Y = ObjSpaceExtent.Y * CurrentScale.Y; - real_scale.Z = ObjSpaceExtent.Z * CurrentScale.Z; - temp.Scale(real_scale); - - // - // Configure the alpha - // - bool is_additive = (SphereShader.Get_Dst_Blend_Func () == ShaderClass::DSTBLEND_ONE); - if (is_additive) { - SphereMaterial->Set_Emissive (CurrentAlpha * CurrentColor); - } else { - SphereMaterial->Set_Opacity (CurrentAlpha); - SphereMaterial->Set_Emissive (CurrentColor); - } - - // If using Alpha Vector, check to see if it needs updated - if (Flags & USE_ALPHA_VECTOR) { - - bool use_inverse = false; - - if (Flags & USE_INVERSE_ALPHA) { - use_inverse = true; - } - - SphereMeshArray[CurrentLOD - 1].Set_Alpha_Vector( CurrentVector, use_inverse, is_additive ); - } - - // Camera Align - if (Flags & USE_CAMERA_ALIGN) { - Matrix4x4 view,ident(true); - DX8Wrapper::Get_Transform(D3DTS_VIEW,view); - - Vector4 wpos(Transform[0][3],Transform[1][3],Transform[2][3],1); - Vector4 cpos; - - Matrix4x4::Transform_Vector(view,wpos,&cpos); - Matrix3D tm(0.0f, 1.0f, 0.0f, cpos.X, - 0.0f, 0.0f, 1.0f, cpos.Y, - 1.0f, 0.0f, 0.0f, cpos.Z); - - tm.Scale(real_scale); - DX8Wrapper::Set_Transform(D3DTS_WORLD,ident); - DX8Wrapper::Set_Transform(D3DTS_VIEW,tm); - render_sphere(); - DX8Wrapper::Set_Transform(D3DTS_VIEW,view); - } else { - DX8Wrapper::Set_Transform(D3DTS_WORLD,temp); - render_sphere(); - } - } -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Special_Render -- special render this box (vis) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Special_Render(SpecialRenderInfoClass & rinfo) -{ - Matrix3D temp(1); - temp.Translate(Transform.Get_Translation()); - - if (rinfo.RenderType == SpecialRenderInfoClass::RENDER_VIS) { - WWASSERT(rinfo.VisRasterizer != NULL); - rinfo.VisRasterizer->Set_Model_Transform(temp); - vis_render_sphere(rinfo,ObjSpaceCenter,ObjSpaceExtent); - } -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Set_Transform -- set the transform for this box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Set_Transform(const Matrix3D &m) -{ - RenderObjClass::Set_Transform(m); - update_cached_box(); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Set_Position -- Set the position of this box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Set_Position(const Vector3 &v) -{ - RenderObjClass::Set_Position(v); - update_cached_box(); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::update_cached_box -- update the world-space version of this box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::update_cached_box(void) -{ - CachedBox.Center = Transform.Get_Translation() + ObjSpaceCenter; - CachedBox.Extent = ObjSpaceExtent; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Obj_Space_Bounding_Sphere -- return the object-space bounding sphe * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - sphere.Init(ObjSpaceCenter,ObjSpaceExtent.Length()); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Obj_Space_Bounding_Box -- returns the obj-space bounding box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - box.Init(ObjSpaceCenter,ObjSpaceExtent); -} - - -void SphereRenderObjClass::Prepare_LOD(CameraClass &camera) -{ - if (Is_Not_Hidden_At_All() == false) { - return; - } - - calculate_value_array(Get_Screen_Size(camera), Value); - - PredictiveLODOptimizerClass::Add_Object(this); -} - -void SphereRenderObjClass::Increment_LOD(void) -{ - if (CurrentLOD < SPHERE_NUM_LOD) CurrentLOD++; -} - -void SphereRenderObjClass::Decrement_LOD(void) -{ - if (CurrentLOD > 0) CurrentLOD--; -} - -float SphereRenderObjClass::Get_Cost(void) const -{ - return Get_Num_Polys(); // Currently cost == polys -} - -float SphereRenderObjClass::Get_Value(void) const -{ - return Value[CurrentLOD]; -} - -float SphereRenderObjClass::Get_Post_Increment_Value(void) const -{ - return Value[CurrentLOD + 1]; -} - -void SphereRenderObjClass::Set_LOD_Level(int lod) -{ - CurrentLOD = Bound(lod, 0, SPHERE_NUM_LOD); // SPHERE_NUM_LOD doesn't include the null LOD -} - -int SphereRenderObjClass::Get_LOD_Level(void) const -{ - return CurrentLOD; -} - -int SphereRenderObjClass::Get_LOD_Count(void) const -{ - return SPHERE_NUM_LOD + 1; // SPHERE_NUM_LOD doesn't include the null LOD -} - -int SphereRenderObjClass::Calculate_Cost_Value_Arrays(float screen_area, float *values, float *costs) const -{ - calculate_value_array(screen_area, values); - for (int lod = 0; lod <= SPHERE_NUM_LOD; lod++) { - costs[lod] = SphereLODCosts[lod]; - } - - // We currently don't support max screen size or minimum LOD clamping for sphere objects - return 0; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Scale -- scales sphere uniformly. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/01/02 NH : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Scale(float scale) -{ - if (scale == 1.0f) return; - - // Scale default value - CurrentScale *= scale; - - // Loop over all keys in scale channel and scale values. - int i; - int count = ScaleChannel.Get_Key_Count(); - for (i = 0; i < count; i++) { - const PrimitiveAnimationChannelClass::KeyClass &key = ScaleChannel.Get_Key(i); - ScaleChannel.Set_Key_Value(i, key.Get_Value() * scale); - } -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Scale -- scales sphere non-uniformly. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/01/02 NH : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Scale(float scalex, float scaley, float scalez) -{ - // Scale default value - CurrentScale.X *= scalex; - CurrentScale.Y *= scaley; - CurrentScale.Z *= scalez; - - // Loop over all keys in scale channel and scale values. - int i; - int count = ScaleChannel.Get_Key_Count(); - for (i = 0; i < count; i++) { - const PrimitiveAnimationChannelClass::KeyClass &key = ScaleChannel.Get_Key(i); - Vector3 key_val = key.Get_Value(); - key_val.X *= scalex; - key_val.Y *= scaley; - key_val.Z *= scalez; - ScaleChannel.Set_Key_Value(i, key_val); - } -} - - - -/*********************************************************************************************** - * SphereRenderObjClass::Update_Cached_Bounding_Volumes -- Updates world-space bounding volumes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/19/00 gth : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Update_Cached_Bounding_Volumes(void) const -{ - CachedBoundingBox.Extent.X = ObjSpaceExtent.X * CurrentScale.X; - CachedBoundingBox.Extent.Y = ObjSpaceExtent.Y * CurrentScale.Y; - CachedBoundingBox.Extent.Z = ObjSpaceExtent.Z * CurrentScale.Z; - - CachedBoundingSphere.Center = CachedBoundingBox.Center = Get_Position() + ObjSpaceCenter; - CachedBoundingSphere.Radius = CachedBoundingBox.Extent.Length(); - - Validate_Cached_Bounding_Volumes(); -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Default_Color - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -Vector3 SphereRenderObjClass::Get_Default_Color(void) const -{ - Vector3 value; - - if (ColorChannel.Get_Key_Count () > 0) { - value = ColorChannel.Get_Key (0).Get_Value (); - } else { - value = CurrentColor; - } - - return value; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Default_Alpha - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -float SphereRenderObjClass::Get_Default_Alpha(void) const -{ - float value; - - if (AlphaChannel.Get_Key_Count () > 0) { - value = AlphaChannel.Get_Key (0).Get_Value (); - } else { - value = CurrentAlpha; - } - - return value; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Default_Scale - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -Vector3 SphereRenderObjClass::Get_Default_Scale(void) const -{ - Vector3 value; - - if (ScaleChannel.Get_Key_Count () > 0) { - value = ScaleChannel.Get_Key (0).Get_Value (); - } else { - value = CurrentScale; - } - - return value; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Get_Default_Vector - get the default (or first frame) value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/13/2000 pds : Created. * - *=============================================================================================*/ -AlphaVectorStruct SphereRenderObjClass::Get_Default_Vector(void) const -{ - AlphaVectorStruct value; - - if (VectorChannel.Get_Key_Count () > 0) { - value = VectorChannel.Get_Key (0).Get_Value (); - } else { - value = CurrentVector; - } - - return value; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::Update_On_Visibilty -- Either starts or stops the animation based on visibility* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/04/00 pds : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::Update_On_Visibilty(void) -{ - // Simply start or stop the animation based on - // the visibility state of the primitive. - if (Is_Not_Hidden_At_All () && Is_Animating () == false) { - Start_Animating (); - } else if ((Is_Not_Hidden_At_All () == false) && Is_Animating ()) { - Stop_Animating (); - } - - return ; -} - - -/*********************************************************************************************** - * SphereRenderObjClass::animate -- Update Current Display state * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void SphereRenderObjClass::animate (void) -{ - if (Is_Animating ()) { - - if ( ColorChannel.Get_Key_Count () > 0 || - AlphaChannel.Get_Key_Count () > 0 || - ScaleChannel.Get_Key_Count () > 0 || - VectorChannel.Get_Key_Count () > 0) - { - // - // Convert from milliseconds to seconds and normalize the time - // - if (AnimDuration > 0) { - float frametime = WW3D::Get_Frame_Time(); - frametime = (frametime * 0.001F) / AnimDuration; - anim_time += frametime; - } else { - anim_time = 1.0F; - } - WWASSERT (anim_time >= 0.0F); - - if ((Flags & USE_ANIMATION_LOOP) && anim_time > 1.0F) { - anim_time -= 1.0F; - } - - if (ColorChannel.Get_Key_Count () > 0) { - CurrentColor = ColorChannel.Evaluate (anim_time); - } - - if (AlphaChannel.Get_Key_Count () > 0) { - CurrentAlpha = AlphaChannel.Evaluate (anim_time); - } - - if (ScaleChannel.Get_Key_Count () > 0) { - CurrentScale = ScaleChannel.Evaluate (anim_time); - Update_Cached_Bounding_Volumes (); - } - - if (VectorChannel.Get_Key_Count () > 0) { - CurrentVector = VectorChannel.Evaluate (anim_time); - } - } - } - - return ; - -} // animate - - -/* -** SphereLoaderClass Implementation -*/ -PrototypeClass * SphereLoaderClass::Load_W3D(ChunkLoadClass & cload) -{ - SpherePrototypeClass *prototype = W3DNEW SpherePrototypeClass; - prototype->Load (cload); - return prototype; -} - -/* -** SpherePrototypeClass Implementation -*/ -SpherePrototypeClass::SpherePrototypeClass (void) -{ - ::memset (&Definition, 0, sizeof (Definition)); - return ; -} - -SpherePrototypeClass::SpherePrototypeClass(SphereRenderObjClass *sphere) -{ - ::memset (&Definition, 0, sizeof (Definition)); - ::strcpy (Definition.Name, sphere->Get_Name ()); - - Definition.DefaultAlpha = sphere->Get_Default_Alpha (); - Definition.AnimDuration = sphere->AnimDuration; - Definition.Attributes = sphere->Get_Flags (); - Definition.DefaultVector = sphere->Get_Default_Vector (); - - Vector3 def_color = sphere->Get_Default_Color (); - Vector3 def_scale = sphere->Get_Default_Scale (); - W3dUtilityClass::Convert_Vector (def_color, &Definition.DefaultColor); - W3dUtilityClass::Convert_Vector (def_scale, &Definition.DefaultScale); - - W3dUtilityClass::Convert_Vector (sphere->Get_Box ().Center, &Definition.Center); - W3dUtilityClass::Convert_Vector (sphere->Get_Box ().Extent, &Definition.Extent); - W3dUtilityClass::Convert_Shader (sphere->SphereShader, &Definition.Shader); - - // - // Determine the texture name for this sphere - // - if (sphere->SphereTexture != NULL) { - StringClass name = sphere->SphereTexture->Get_Full_Path(); - const char *filename = ::strrchr (name, '\\'); - if (filename != NULL) { - filename ++; - } else { - filename = name; - } - - ::strcpy (Definition.TextureName, filename); - - } - - // - // Save the animateable channels - // - ColorChannel = sphere->Peek_Color_Channel (); - AlphaChannel = sphere->Peek_Alpha_Channel (); - ScaleChannel = sphere->Peek_Scale_Channel (); - VectorChannel = sphere->Peek_Vector_Channel (); - return ; -} - -SpherePrototypeClass::~SpherePrototypeClass (void) -{ - return ; -} - -enum -{ - CHUNKID_SPHERE_DEF = 1, - CHUNKID_COLOR_CHANNEL, - CHUNKID_ALPHA_CHANNEL, - CHUNKID_SCALE_CHANNEL, - CHUNKID_VECTOR_CHANNEL -}; - -bool SpherePrototypeClass::Load (ChunkLoadClass &cload) -{ - ColorChannel.Reset (); - AlphaChannel.Reset (); - ScaleChannel.Reset (); - VectorChannel.Reset (); - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_SPHERE_DEF: - cload.Read (&Definition, sizeof (Definition)); - break; - - case CHUNKID_COLOR_CHANNEL: - ColorChannel.Load (cload); - break; - - case CHUNKID_ALPHA_CHANNEL: - AlphaChannel.Load (cload); - break; - - case CHUNKID_SCALE_CHANNEL: - ScaleChannel.Load (cload); - break; - - case CHUNKID_VECTOR_CHANNEL: - VectorChannel.Load (cload); - break; - } - - cload.Close_Chunk (); - } - - return true; -} - -bool SpherePrototypeClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (W3D_CHUNK_SPHERE); - - csave.Begin_Chunk (CHUNKID_SPHERE_DEF); - csave.Write (&Definition, sizeof (Definition)); - csave.End_Chunk (); - - if (ColorChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_COLOR_CHANNEL); - ColorChannel.Save (csave); - csave.End_Chunk (); - } - - if (AlphaChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_ALPHA_CHANNEL); - AlphaChannel.Save (csave); - csave.End_Chunk (); - } - - - if (ScaleChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_SCALE_CHANNEL); - ScaleChannel.Save (csave); - csave.End_Chunk (); - } - - if (VectorChannel.Get_Key_Count () > 0) { - csave.Begin_Chunk (CHUNKID_VECTOR_CHANNEL); - VectorChannel.Save (csave); - csave.End_Chunk (); - } - - csave.End_Chunk (); - return true; -} - -const char * SpherePrototypeClass::Get_Name(void) const -{ - return Definition.Name; -} - -int SpherePrototypeClass::Get_Class_ID(void) const -{ - return RenderObjClass::CLASSID_SPHERE; -} - -RenderObjClass * SpherePrototypeClass::Create(void) -{ - // - // Create the new render object - // - SphereRenderObjClass *sphere = W3DNEW SphereRenderObjClass (Definition); - - // - // Configure the sphere - // - W3dUtilityClass::Convert_Shader (Definition.Shader, &sphere->SphereShader); - if (WW3DAssetManager::Get_Instance()->Get_Activate_Fog_On_Load()) { - sphere->SphereShader.Enable_Fog ("SpherePrototypeClass"); - } - W3dUtilityClass::Convert_Vector (Definition.DefaultColor, &sphere->CurrentColor); - W3dUtilityClass::Convert_Vector (Definition.DefaultScale, &sphere->CurrentScale); - sphere->CurrentVector = Definition.DefaultVector; - sphere->Set_Animation_Duration (Definition.AnimDuration); - sphere->CurrentAlpha = Definition.DefaultAlpha; - sphere->Set_Flags (Definition.Attributes); - - // - // Initialize the render object with the keyframe arrays - // - sphere->Set_Color_Channel (ColorChannel); - sphere->Set_Alpha_Channel (AlphaChannel); - sphere->Set_Scale_Channel (ScaleChannel); - sphere->Set_Vector_Channel (VectorChannel); - return sphere; -} - -/* -** Global instance of the box loader -*/ -SphereLoaderClass _SphereLoader; - - -// -// Vertices are ordered as such -// North Pole, stack 1, stack 2, stack x..., SouthPole -// -/*********************************************************************************************** - * SphereMeshClass::SphereMeshClass -- Constructor for SphereMesh Geometry * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -SphereMeshClass::SphereMeshClass(float radius, int slices, int stacks): -Radius(radius), -Slices(slices), -Stacks(stacks), -Vertex_ct(0), -vtx(NULL), -vtx_normal(NULL), -vtx_uv(NULL), -strip_ct(0), -strip_size(0), -strips(NULL), -fan_ct(0), -fan_size(0), -fans(NULL), -face_ct(0), -tri_poly(NULL), -inverse_alpha(false) -{ - // compute # of vertices - // 1st 2 vertices, represent, north, and south pole (Y - axis) - - Generate(radius, slices, stacks); - -} // SphereMesh Constructor - -/*********************************************************************************************** - * SphereMeshClass::SphereMeshClass -- Constructor for SphereMesh Geometry * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -SphereMeshClass::SphereMeshClass(void): -Radius(0.0f), -Slices(0), -Stacks(0), -Vertex_ct(0), -vtx(NULL), -vtx_normal(NULL), -vtx_uv(NULL), -strip_ct(0), -strip_size(0), -strips(NULL), -fan_ct(0), -fan_size(0), -fans(NULL), -face_ct(0), -tri_poly(NULL), -inverse_alpha(false) -{ - -} // Empty SphereMesh Constructor - - - -/*********************************************************************************************** - * SphereMeshClass::Set_Alpha_Vector -- Unit Direction Vector, for Alpha hole effects * - * * - * INPUT: vector4 v ; Unit Vector pointing into the sphere in object space * - * .W = Intensity ; Percent Effect * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void SphereMeshClass::Set_Alpha_Vector (const AlphaVectorStruct &v, bool inverse, bool is_additive, bool force) -{ - // - // Exit if there is nothing to do... - // - if ( alpha_vector == v && - inverse == inverse_alpha && - is_additive == IsAdditive && - !force) - { - return ; - } - - inverse_alpha = inverse; - alpha_vector = v; - - float Intensity = v.intensity; - assert(Intensity >= 0.0f); - - Vector3 vec = alpha_vector.angle.Rotate_Vector (Vector3 (1, 0, 0)); - - if (inverse_alpha) { - for (int idx=0; idx < Vertex_ct; idx++) { - - float temp; - temp = Vector3::Dot_Product(vec, vtx_normal[idx]); - temp*= Intensity; - - temp = fabs(temp); - - if (temp > 1.0f) temp = 1.0f; - - Set_DCG (is_additive, idx, temp); - } - - } else { - - for (int idx=0; idx < Vertex_ct; idx++) { - - float temp; - temp = Vector3::Dot_Product(vec, vtx_normal[idx]); - temp*= Intensity; - - temp = fabs(temp); - - if (temp > 1.0f) temp = 1.0f; - - Set_DCG (is_additive, idx, 1.0F - temp); - } - } - - return ; -} // Set_Alpha_Vector - - -/*********************************************************************************************** - * SphereMeshClass::Generate -- Alloc Memory, and Generate Geometry, for the SphereMesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void SphereMeshClass::Generate(float radius, int slices, int stacks) -{ - // compute # of vertices - // 1st 2 vertices, represent, north, and south pole (Y - axis) - - Free(); - - Slices = slices; - Stacks = stacks; - Radius = radius; - - face_ct = (Slices * Stacks * 2); - - Vertex_ct = ((Slices+1) * Stacks) + 2; - - vtx = W3DNEWARRAY Vector3[Vertex_ct]; - vtx_normal = W3DNEWARRAY Vector3[Vertex_ct]; - vtx_uv = W3DNEWARRAY Vector2[Vertex_ct]; - dcg = W3DNEWARRAY Vector4[Vertex_ct]; - - Matrix3x3 mat; - Vector3 vec(0.0f, 0.0f, radius); - - Vector3 *veclist = vtx; - Vector2 *uv = vtx_uv; - - *veclist = vec; // assign north pole - veclist++; - - // Generate Vertex UV coordinates - // - // 0,0 _____ 1,0 - // Texture maps UV's look something like this |_____| - // 0,1 1,1 - // - // - - uv->U = 0.5f; uv->V = 0.0f; // assign uv for north pole - uv++; - - for (stacks = 0; stacks < Stacks; stacks++) { - - float stackstep = ((float)stacks + 1) / ((float) Stacks+1); - float XAxisAngle = WWMATH_PI * stackstep; - - for (slices = 0; slices <= Slices; slices++) { - - float slicestep = ((float)slices) / ((float)Slices); - float YAxisAngle = (WWMATH_PI * 2.0f) * slicestep; - - - mat.Make_Identity(); - mat.Rotate_Z( YAxisAngle ); - mat.Rotate_X( XAxisAngle ); - *veclist = mat * vec; - - veclist++; - - // update UV - - uv->U = slicestep; - uv->V = stackstep; - uv++; - - } // for slices - } // for stacks - - // Assign vertex for south pole; - *veclist = -1.0f * vec; - uv->U = 0.5f; uv->V = 1.0f; // uv for south pole - - // Generate Vertex Normals - - Vector3 *src = vtx; - Vector3 *dst = vtx_normal; - - for(int idx = 0; idx < Vertex_ct; idx++) { - - Vector3 temp; - - temp = src[idx]; - temp.Normalize(); - dst[idx] = temp; - } - - - // Generate Fans for North + south pole - fan_ct = 2; - fan_size = Slices+2; - fans = W3DNEWARRAY int[fan_size * fan_ct]; - - // Do Fan #1 - int ct = 0; - for (; ct < fan_size; ct++) { - fans[ct] = ct; - } - //fans[ct] = 1; - - // Do Fan #2 - int vtx_idx = Vertex_ct - 1; - for (ct = fan_size; ct < (fan_size * 2); ct++) { - fans[ct] = vtx_idx; - vtx_idx--; - } - //fans[ct] = Vertex_ct - 2; - - // Generate Strips, for the inbetween stacks - - strip_size = ((Slices+1) * 2); - strip_ct = Stacks - 1; - if (strip_ct) { - strips = W3DNEWARRAY int[strip_size * strip_ct]; - for (stacks = 0; stacks < strip_ct; stacks++) { - // outer loop for each stack - int store_idx = stacks * strip_size; - int base_vtx = 1 + (stacks * (Slices+1)); - int cur_vtx = base_vtx; - - for(ct = 0; ct <= Slices; ct++) { - - strips[store_idx] = cur_vtx + (Slices+1); - strips[store_idx+1] = cur_vtx; - - cur_vtx++; - store_idx+=2; - - } - - // Last, special case +2 - //strips[store_idx] = base_vtx + Slices; - //strips[store_idx+1] = base_vtx; - } - } - - // Generate Tri-Poly Indices - - tri_poly = W3DNEWARRAY TriIndex[face_ct]; // 3 indices per triangle - - TriIndex *out = tri_poly; - int *in; - - for (stacks = 0; stacks < strip_ct; stacks++) { - - in = &strips[strip_size * stacks]; - - // Strip to Poly Function - // IJK - for(int fidx=0; fidx < (strip_size - 2); fidx++) { - - out->I = in[0]; - out->J = in[1]; - out->K = in[2]; - - out++; - in++; - - fidx++; - if (fidx >= (strip_size-2)) break; - - out->I = in[0]; - out->J = in[2]; - out->K = in[1]; - out++; - in++; - - } - - // End Strip to Poly Function - } - - - // Fans to Poly Function - - for(slices = 0; slices < fan_ct; slices++) { - - in = &fans[fan_size * slices]; - int *base_idx = in; - - for (int fidx=0; fidx < (fan_size - 2); fidx++) { - - out->I = base_idx[0]; - out->J = in[2]; - out->K = in[1]; - - in++; - out++; - } - - } - - // Make Sure ptr is where I expect it to be - WWASSERT(((int)out) == ((int)(tri_poly + face_ct))); - - // - // Fill in the DCG array - // - Set_Alpha_Vector (alpha_vector, inverse_alpha, IsAdditive, true); - return ; - -} // Generate - - - -/*********************************************************************************************** - * SphereMeshClass::~SphereMeshClass -- Destructor * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -SphereMeshClass::~SphereMeshClass(void) -{ - - Free(); - -} // Destructor - - -/*********************************************************************************************** - * SphereMeshClass::Free Memory used by geometry for the SphereMesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/07/00 jga : Created. * - *=============================================================================================*/ -void SphereMeshClass::Free(void) -{ - if (vtx) delete [] vtx; - if (vtx_normal) delete [] vtx_normal; - if (vtx_uv) delete [] vtx_uv; - if (dcg) delete [] dcg; - if (strips) delete [] strips; - if (fans) delete [] fans; - if (tri_poly) delete [] tri_poly; - - vtx = NULL; - vtx_normal = NULL; - vtx_uv = NULL; - dcg = NULL; - strips = NULL; - fans = NULL; - tri_poly = NULL; - -} - -// EOF - sphereobj.cpp - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.h deleted file mode 100644 index 4620509efa..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/sphereobj.h +++ /dev/null @@ -1,479 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/sphereobj.h $* - * * - * Author:: Jason Andersen * - * * - * $Modtime:: 11/24/01 6:21p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SPHEREOBJ_H -#define SPHEREOBJ_H - -#include "always.h" -#include "rendobj.h" -#include "w3d_file.h" -#include "shader.h" -#include "proto.h" -#include "obbox.h" -#include "Vector3i.h" -#include "quat.h" -#include "prim_anim.h" -#include "meshgeometry.h" - -class TextureClass; - -struct AlphaVectorStruct -{ - AlphaVectorStruct (void) - : angle (true), - intensity (1.0F) { } - AlphaVectorStruct (const AlphaVectorStruct &src) { *this = src; } - - bool operator== (const AlphaVectorStruct &src) { return (angle.X == src.angle.X) && (angle.Y == src.angle.Y) && (angle.Z == src.angle.Z) && (intensity == src.intensity); } - bool operator!= (const AlphaVectorStruct &src) { return ! operator== (src); } - - const AlphaVectorStruct & operator= (const AlphaVectorStruct &src) { angle = src.angle; intensity = src.intensity; return *this; } - - Quaternion angle; - float intensity; -}; - -class AlphaVectorChannel : public PrimitiveAnimationChannelClass -{ -public: - AlphaVectorStruct Evaluate (float time) - { - int key_count = m_Data.Count (); - AlphaVectorStruct value = m_Data[key_count - 1].Get_Value (); - - // - // Don't interpolate past the last keyframe - // - if (time < m_Data[key_count - 1].Get_Time ()) { - - // Check to see if the last key index is valid - if (time < m_Data[m_LastIndex].Get_Time ()) { - m_LastIndex = 0; - } - - KeyClass *key1 = &m_Data[m_LastIndex]; - KeyClass *key2 = &m_Data[key_count - 1]; - - // - // Search, using last_key as our starting point - // - for (int keyidx = m_LastIndex; keyidx < (key_count - 1); keyidx ++) { - - if (time < m_Data[keyidx+1].Get_Time ()) { - key1 = &m_Data[keyidx]; - key2 = &m_Data[keyidx+1]; - m_LastIndex = keyidx; - break; - } - } - - // Calculate the linear percent between the two keys - float percent = (time - key1->Get_Time ()) / (key2->Get_Time () - key1->Get_Time ()); - - // Slerp the quaternions and lerp the intensities - value.intensity = (key1->Get_Value ().intensity + (key2->Get_Value ().intensity - key1->Get_Value ().intensity) * percent); - Fast_Slerp (value.angle, key1->Get_Value ().angle, key2->Get_Value ().angle, percent); - } - - return value; - } -}; - -struct W3dSphereStruct -{ - uint32 Version; // file format version - uint32 Attributes; // sphere attributes (above #define's) - char Name[2*W3D_NAME_LEN]; // name is in the form . - - W3dVectorStruct Center; // center of the sphere - W3dVectorStruct Extent; // extent of the sphere - - float AnimDuration; // Animation time (in seconds) - - W3dVectorStruct DefaultColor; - float DefaultAlpha; - W3dVectorStruct DefaultScale; - AlphaVectorStruct DefaultVector; - - char TextureName[2*W3D_NAME_LEN]; - W3dShaderStruct Shader; - - // - // Note this structure is followed by a series of - // W3dSphereKeyArrayStruct structures which define the - // variable set of keyframes for each channel. - // -}; - -typedef LERPAnimationChannelClass SphereColorChannelClass; -typedef LERPAnimationChannelClass SphereAlphaChannelClass; -typedef LERPAnimationChannelClass SphereScaleChannelClass; -typedef AlphaVectorChannel SphereVectorChannelClass; -//typedef AlphaVectorChannel ; - -class VertexMaterialClass; - - -class SphereMeshClass -{ -friend class SphereRenderObjClass; - -public: - // Constructor - SphereMeshClass(void); - SphereMeshClass(float radius, int slices, int stacks); - // Destructor - ~SphereMeshClass(void); - - void Generate (float radius, int slices, int stacks); - int Get_Num_Polys (void) { return face_ct; }; - void Set_Alpha_Vector (const AlphaVectorStruct &v, bool inverse, bool is_additive, bool force = false); - -private: - - void Set_DCG (bool is_additive, int index, float value); - - void Free(void); - - float Radius; - int Slices; - int Stacks; - int face_ct; // # of faces - - int Vertex_ct; // vertex count - Vector3 *vtx; // array of vertices - Vector3 *vtx_normal; // array of vertex normals - Vector2 *vtx_uv; // array of vertex uv coordinates - Vector4 *dcg; - - AlphaVectorStruct alpha_vector; // vector last used to computer vtx_alpha array - bool inverse_alpha; // inverse alpha, or not - bool IsAdditive; - - int strip_ct; // number of strips - int strip_size; // size of each strip - int *strips; // array of vertex indices for each strip (# stripbs x sizeof strip) - - int fan_ct; // number of fans - int fan_size; // size of each fan - int *fans; // array of vertex indices for each fan (# of fans by fan_size) - - TriIndex *tri_poly; // array of triangle poly's, vertex indices (can be discard if switched to strips + fans) - -}; - -inline void -SphereMeshClass::Set_DCG (bool is_additive, int index, float value) -{ - if (is_additive) { - dcg[index].X = value; - dcg[index].Y = value; - dcg[index].Z = value; - dcg[index].W = 0; - } else { - dcg[index].X = 1.0F; - dcg[index].Y = 1.0F; - dcg[index].Z = 1.0F; - dcg[index].W = value; - } - - return ; -} - -// Note: SPHERE_NUM_LOD does not include the NULL LOD. -#define SPHERE_NUM_LOD (10) -#define SPHERE_LOWEST_LOD (7) -#define SPHERE_HIGHEST_LOD (17) - -/* -** SphereRenderObjClass: Procedurally generated render spheres -** -*/ -class SphereRenderObjClass : public RenderObjClass -{ - -public: - - // These are bit masks, so they should enum 1,2,4,8,10,20,40 etc... - enum SphereFlags { - USE_ALPHA_VECTOR = 0x00000001, - USE_CAMERA_ALIGN = 0x00000002, - USE_INVERSE_ALPHA = 0x00000004, - USE_ANIMATION_LOOP= 0x00000008, - }; - - SphereRenderObjClass(void); - SphereRenderObjClass(const W3dSphereStruct & def); - SphereRenderObjClass(const SphereRenderObjClass & src); - SphereRenderObjClass & operator = (const SphereRenderObjClass &); - ~SphereRenderObjClass(void); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const; - virtual void Render(RenderInfoClass & rinfo); - virtual void Special_Render(SpecialRenderInfoClass & rinfo); - virtual void Set_Transform(const Matrix3D &m); - virtual void Set_Position(const Vector3 &v); - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & aabox) const; - - virtual void Prepare_LOD(CameraClass &camera); - virtual void Increment_LOD(void); - virtual void Decrement_LOD(void); - virtual float Get_Cost(void) const; - virtual float Get_Value(void) const; - virtual float Get_Post_Increment_Value(void) const; - virtual void Set_LOD_Level(int lod); - virtual int Get_LOD_Level(void) const; - virtual int Get_LOD_Count(void) const; - virtual void Set_LOD_Bias(float bias) { LODBias = MAX(bias, 0.0f); } - virtual int Calculate_Cost_Value_Arrays(float screen_area, float *values, float *costs) const; - - virtual void Scale(float scale); - virtual void Scale(float scalex, float scaley, float scalez); - virtual void Set_Hidden(int onoff) { RenderObjClass::Set_Hidden (onoff); Update_On_Visibilty (); } - virtual void Set_Visible(int onoff) { RenderObjClass::Set_Visible (onoff); Update_On_Visibilty (); } - virtual void Set_Animation_Hidden(int onoff) { RenderObjClass::Set_Animation_Hidden (onoff); Update_On_Visibilty (); } - virtual void Set_Force_Visible(int onoff) { RenderObjClass::Set_Force_Visible (onoff); Update_On_Visibilty (); } - - - const AABoxClass & Get_Box(void); - - virtual int Get_Num_Polys(void) const; - virtual const char * Get_Name(void) const; - virtual void Set_Name(const char * name); - - unsigned int Get_Flags(void) { return Flags; } - void Set_Flags(unsigned int flags) { Flags = flags; } - void Set_Flag(unsigned int flag, bool onoff) { Flags &= (~flag); if (onoff) Flags |= flag; } - - // Animation access - bool Is_Animating (void) { return IsAnimating; } - void Start_Animating (void) { IsAnimating = true; anim_time = 0; } - void Stop_Animating (void) { IsAnimating = false; anim_time = 0; } - - // Current state access - void Set_Color(const Vector3 & color) { CurrentColor = color; } - void Set_Alpha(float alpha) { CurrentAlpha = alpha; } - void Set_Scale(const Vector3 & scale) { CurrentScale = scale; } - void Set_Vector(const AlphaVectorStruct &v) { CurrentVector = v; } - - const Vector3 & Get_Color(void) const { return CurrentColor; } - float Get_Alpha(void) const { return CurrentAlpha; } - const Vector3 & Get_Scale(void) const { return CurrentScale; } - const AlphaVectorStruct & Get_Vector(void) const { return CurrentVector; } - - Vector3 Get_Default_Color(void) const; - float Get_Default_Alpha(void) const; - Vector3 Get_Default_Scale(void) const; - AlphaVectorStruct Get_Default_Vector(void) const; - - // Size/position methods - void Set_Extent (const Vector3 &extent); - void Set_Local_Center_Extent(const Vector3 & center,const Vector3 & extent); - void Set_Local_Min_Max(const Vector3 & min,const Vector3 & max); - - // Texture access - void Set_Texture(TextureClass *tf); - TextureClass * Peek_Texture(void) {return SphereTexture;} - ShaderClass & Get_Shader(void) {return SphereShader;} - void Set_Shader(ShaderClass &shader) {SphereShader=shader;} - - // Animation control - float Get_Animation_Duration (void) const { return AnimDuration; } - void Set_Animation_Duration (float time) { AnimDuration = time; Restart_Animation (); } - void Restart_Animation (void) { anim_time = 0; } - - // Animatable channel access - SphereColorChannelClass & Get_Color_Channel (void) { return ColorChannel; } - const SphereColorChannelClass & Peek_Color_Channel (void) { return ColorChannel; } - - SphereAlphaChannelClass & Get_Alpha_Channel (void) { return AlphaChannel; } - const SphereAlphaChannelClass & Peek_Alpha_Channel (void) { return AlphaChannel; } - - SphereScaleChannelClass & Get_Scale_Channel (void) { return ScaleChannel; } - const SphereScaleChannelClass & Peek_Scale_Channel (void) { return ScaleChannel; } - - SphereVectorChannelClass & Get_Vector_Channel (void) { return VectorChannel; } - const SphereVectorChannelClass & Peek_Vector_Channel (void) { return VectorChannel; } - - void Set_Color_Channel (const SphereColorChannelClass &data) { ColorChannel = data; } - void Set_Alpha_Channel (const SphereAlphaChannelClass &data) { AlphaChannel = data; } - void Set_Scale_Channel (const SphereScaleChannelClass &data) { ScaleChannel = data; } - void Set_Vector_Channel (const SphereVectorChannelClass &data) { VectorChannel = data; } - -protected: - - virtual void update_cached_box(void); - virtual void Update_Cached_Bounding_Volumes(void) const; - void Update_On_Visibilty(void); - - // Initialization stuff - void Init_Material (void); - static void Generate_Shared_Mesh_Arrays (const AlphaVectorStruct &alphavector); - - // Animation Stuff - void animate(void); // animation update function - float anim_time; // what time in seconds are we in the animation - float AnimDuration; - bool IsAnimating; - - // LOD Stuff - void calculate_value_array(float screen_area, float *values) const; - float LODBias; - int CurrentLOD; - float Value[SPHERE_NUM_LOD + 2];// Value array needs # of LODs + 1 (RING_NUM_LOD doesn't include null LOD) - - SphereColorChannelClass ColorChannel; - SphereAlphaChannelClass AlphaChannel; - SphereScaleChannelClass ScaleChannel; - SphereVectorChannelClass VectorChannel; - - void update_mesh_data(const Vector3 & center,const Vector3 & extent); - void render_sphere(); - void vis_render_sphere(SpecialRenderInfoClass & rinfo,const Vector3 & center,const Vector3 & extent); - - char Name[2*W3D_NAME_LEN]; - Vector3 ObjSpaceCenter; - Vector3 ObjSpaceExtent; - - // Current State - Vector3 CurrentColor; - float CurrentAlpha; - Vector3 CurrentScale; - AlphaVectorStruct CurrentVector; - - Quaternion Orientation; - - // Flags - unsigned int Flags; - - VertexMaterialClass *SphereMaterial; - ShaderClass SphereShader; - TextureClass *SphereTexture; - - AABoxClass CachedBox; - - // Friend classes - friend class SpherePrototypeClass; -}; - -inline void SphereRenderObjClass::Set_Extent (const Vector3 &extent) -{ - ObjSpaceExtent = extent; - update_cached_box(); - Update_Cached_Bounding_Volumes(); -} - -inline void SphereRenderObjClass::Set_Local_Center_Extent(const Vector3 & center,const Vector3 & extent) -{ - ObjSpaceCenter = center; - ObjSpaceExtent = extent; - update_cached_box(); -} - -inline void SphereRenderObjClass::Set_Local_Min_Max(const Vector3 & min,const Vector3 & max) -{ - ObjSpaceCenter = (max + min) / 2.0f; - ObjSpaceExtent = (max - min) / 2.0f; - update_cached_box(); -} - - -inline const AABoxClass & SphereRenderObjClass::Get_Box(void) -{ - Validate_Transform(); - update_cached_box(); - return CachedBox; -} - -/* -** Loader for spheres -*/ -class SphereLoaderClass : public PrototypeLoaderClass -{ -public: - virtual int Chunk_Type (void) { return W3D_CHUNK_SPHERE; } - virtual PrototypeClass * Load_W3D(ChunkLoadClass & cload); -}; - -/* -** Prototype for Sphere objects -*/ -class SpherePrototypeClass : public W3DMPO, public PrototypeClass -{ - W3DMPO_GLUE(SpherePrototypeClass) -public: - SpherePrototypeClass (void); - SpherePrototypeClass (SphereRenderObjClass *sphere); - - virtual const char * Get_Name(void) const; - virtual int Get_Class_ID(void) const; - virtual RenderObjClass * Create(void); - virtual void DeleteSelf() { delete this; } - - bool Load (ChunkLoadClass &cload); - bool Save (ChunkSaveClass &csave); - -protected: - ~SpherePrototypeClass (void); - -private: - W3dSphereStruct Definition; - - SphereColorChannelClass ColorChannel; - SphereAlphaChannelClass AlphaChannel; - SphereScaleChannelClass ScaleChannel; - SphereVectorChannelClass VectorChannel; -}; - -/* -** Instance of the loader which the asset manager installs -*/ -extern SphereLoaderClass _SphereLoader; - -#endif // SPHEREOBJ_H - -// EOF - sphereobj,h - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp deleted file mode 100644 index 8f7f65cef1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: $* - * * - * Creator::Scott K. Bowen - 7/15/2002 * - * * - * $Author:: $* - * * - * $Modtime:: $* - * * - * $Revision:: $* - * * - *-------------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Include files /////////////////////////////////////////////////////////////////////////////////// - -#include "static_sort_list.h" - -#include "rendobj.h" -#include "dx8renderer.h" - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Initialization Functions //////////////////////////////////////////////////////////////////////// - -DefaultStaticSortListClass::DefaultStaticSortListClass(void) : - StaticSortListClass(), - SortLists(), - MinSort(1), - MaxSort(MAX_SORT_LEVEL) -{ -} - -DefaultStaticSortListClass::~DefaultStaticSortListClass(void) -{ -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Virtual functions /////////////////////////////////////////////////////////////////////////////// - -void DefaultStaticSortListClass::Add_To_List(RenderObjClass * robj, unsigned int sort_level) -{ - if(sort_level < 1 || sort_level > MAX_SORT_LEVEL) { - WWASSERT(0); - return; - } - SortLists[sort_level].Add_Tail(robj, false); -} - -void DefaultStaticSortListClass::Render_And_Clear(RenderInfoClass & rinfo) -{ - // We go from higher sort level to lower, since lower sort level means higher priority (in - // front), so lower sort level meshes need to be rendered later. - for(unsigned int sort_level = MaxSort; sort_level >= MinSort; sort_level--) { - bool render=false; - for ( RenderObjClass *robj = SortLists[sort_level].Remove_Head(); robj; - robj->Release_Ref(), robj = SortLists[sort_level].Remove_Head()) - { - robj->Render(rinfo); - render = true; - } - if (render) TheDX8MeshRenderer.Flush(); - } -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.h deleted file mode 100644 index 127ee0c46f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/static_sort_list.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/***************************************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - ***************************************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: $* - * * - * Creator::Scott K. Bowen - 7/15/2002 * - * * - * $Author:: $* - * * - * $Modtime:: $* - * * - * $Revision:: $* - * * - *---------------------------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef STATIC_SORT_LIST_H -#define STATIC_SORT_LIST_H - -#include "robjlist.h" -#include "w3d_file.h" - -class RenderInfoClass; - -// Just defines the interface for the class as used by WW3D.. -class StaticSortListClass -{ - public: - /////////////////////////////////////////////////////////////////////////////////// - // Construction. - StaticSortListClass(void) {} - virtual ~StaticSortListClass(void) {} - - virtual void Add_To_List(RenderObjClass * robj, unsigned int sort_level) = 0; - virtual void Render_And_Clear(RenderInfoClass & rinfo) = 0; - -}; // end StaticSortListClass - -// The actual implementation for the standard ww3d StaticSortList. -class DefaultStaticSortListClass : public StaticSortListClass -{ - public: - /////////////////////////////////////////////////////////////////////////////////// - // Construction. - DefaultStaticSortListClass(void); - virtual ~DefaultStaticSortListClass(void); - - virtual void Add_To_List(RenderObjClass * robj, unsigned int sort_level); - virtual void Render_And_Clear(RenderInfoClass & rinfo); - - - unsigned int Get_Min_Sort(void) const {return MinSort;}; - unsigned int Get_Max_Sort(void) const {return MaxSort;}; - - void Set_Min_Sort(unsigned int value) {MinSort = (value > MAX_SORT_LEVEL) ? MAX_SORT_LEVEL : value;} - void Set_Max_Sort(unsigned int value) {MaxSort = (value > MAX_SORT_LEVEL) ? MAX_SORT_LEVEL : value;} - - private: - // These are for use by controlling classes to allow control of what levels - // to render when Render_And_Clear() is called. As for this class, the values - // are set to 1..MAX_SORT_LEVEL and then never changed. - unsigned int MinSort; - unsigned int MaxSort; - - // An array of lists - each object in a given list has same SortLevel. - RefRenderObjListClass SortLists[MAX_SORT_LEVEL + 1]; - -}; // end StaticSortListClass - - - - -#endif //STATIC_SORT_LIST_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/statistics.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/statistics.cpp deleted file mode 100644 index 04fe233f52..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/statistics.cpp +++ /dev/null @@ -1,394 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "statistics.h" -#include "wwstring.h" -#include "simplevec.h" -#include "dx8renderer.h" -#include "dx8wrapper.h" -#include "dx8caps.h" -#include "textureloader.h" -#include "texture.h" -#include - -#include -#ifdef _UNIX -#include "osdep.h" -#endif - -// ---------------------------------------------------------------------------- -// -// Texture memory tracking system -// -// ---------------------------------------------------------------------------- - -static int texture_memory; -static int texture_count; -static int lightmap_texture_memory; -static int lightmap_texture_count; -static int procedural_texture_memory; -static int procedural_texture_count; -static int record_count; -static int texture_change_count; -static int last_frame_texture_memory; -static int last_frame_texture_count; -static int last_frame_lightmap_texture_memory; -static int last_frame_lightmap_texture_count; -static int last_frame_procedural_texture_memory; -static int last_frame_procedural_texture_count; -static int last_frame_record_count; -static int last_frame_texture_change_count; -static TextureClass* latest_texture; -static Debug_Statistics::RecordTextureMode record_texture_mode; -static StringClass texture_statistics_string; - -struct TextureStatisticsStruct -{ - TextureClass* tex; - int usage_count; - int change_count; -}; - -static SimpleDynVecClass texture_statistics; - -static void Record_Texture_Begin() -{ - texture_memory=0; - texture_count=0; - lightmap_texture_memory=0; - lightmap_texture_count=0; - procedural_texture_memory=0; - procedural_texture_count=0; - record_count=0; - texture_change_count=0; - latest_texture=NULL; - texture_statistics.Resize(0); -} - -static void Record_Texture_End() -{ - last_frame_texture_memory=texture_memory; - last_frame_texture_count=texture_count; - last_frame_lightmap_texture_memory=lightmap_texture_memory; - last_frame_lightmap_texture_count=lightmap_texture_count; - last_frame_procedural_texture_memory=procedural_texture_memory; - last_frame_procedural_texture_count=procedural_texture_count; - last_frame_record_count=record_count; - last_frame_texture_change_count=texture_change_count; - - texture_statistics_string=""; - if (record_texture_mode==Debug_Statistics::RECORD_TEXTURE_DETAILS) { - char tmp_text[1024]; - _snprintf(tmp_text,sizeof(tmp_text), - "Set_DX8_Texture count: %d\nactual changes: %d\n\n" - "id refs changes size name\n" - "--------------------------------------\n", - - last_frame_record_count,last_frame_texture_change_count); - texture_statistics_string+=tmp_text; - for (int a=0;agetClassID() == ID_TEXTURE_FILE_CLASS) { -// TextureFileClass* tfc=static_cast(t); -// id=tfc->ID(); -// if (tfc->Get_Texture_Flash()) flash="F"; -// } - - working_string.Format("%4.4d %3.3d %3.3d %s ",id,texture_statistics[a].usage_count,texture_statistics[a].change_count,flash.Peek_Buffer()); - texture_statistics_string+=working_string; - - StringClass error=""; - if (t) { -// int red_factor=t->Get_Current_Reduction_Factor(); - unsigned bytes=t->Get_Texture_Memory_Usage(); -// unsigned non_red_bytes=t->Get_Non_Reduced_Texture_Memory_Usage(); - if (!t->Is_Initialized()) { -// non_red_bytes=bytes; - texture_statistics_string+="*"; - } - else { - texture_statistics_string+=" "; - } -// if (!non_red_bytes) non_red_bytes=1; -// int percents=100-100*bytes/non_red_bytes; - working_string.Format("%4.4dkb ",bytes/1024); - texture_statistics_string+=working_string; - } - else { - texture_statistics_string+="N/A "; - } - texture_statistics_string+=t->Get_Texture_Name();//getTextureName(); - texture_statistics_string+=error; - texture_statistics_string+="\n"; - } - texture_statistics_string+="\nid = id of texture. Use with command 'flash_texture [id]'\n"; - texture_statistics_string+="refs = # of times texture is used when rendering\n"; - texture_statistics_string+="changes = # of times texture change needed - BAD IF HIGH!\n"; - texture_statistics_string+="red = texture reduction factor\n"; - texture_statistics_string+="size = amount of memory needed for texture\n"; - texture_statistics_string+="(w/o red) = size of reduction not used\n"; - texture_statistics_string+="percent = savings of reduction system, in percents\n"; - texture_statistics_string+="\n* = thumbnail used\n"; - texture_statistics_string+="\n"; -// texture_statistics_string+=TextureFileClass::List_Missing_Files(); - - } - -} - -void Debug_Statistics::Record_Texture_Mode(RecordTextureMode mode) -{ - record_texture_mode=mode; -} - -Debug_Statistics::RecordTextureMode Debug_Statistics::Get_Record_Texture_Mode() -{ - return record_texture_mode; -} - -static bool Find_Record_Texture(TextureClass* t) -{ - for (int a=0;aIs_Lightmap()) lightmap_texture_count++; - if (t->Is_Procedural()) procedural_texture_count++; -} - -void Debug_Statistics::Record_Texture(TextureClass* t) -{ - record_count++; - if (t!=latest_texture) { - texture_change_count++; - } - - if (record_texture_mode==RECORD_TEXTURE_NONE) { - latest_texture=t; - return; - } - if (!t) { - latest_texture=t; - return; - } - - if (Find_Record_Texture(t)) { - latest_texture=t; - return; - } - Add_Record_Texture(t); - - texture_memory+=t->Get_Texture_Memory_Usage(); - latest_texture=t; - if (t->Is_Lightmap()) lightmap_texture_memory+=t->Get_Texture_Memory_Usage(); - if (t->Is_Procedural()) procedural_texture_memory+=t->Get_Texture_Memory_Usage(); - -} - -int Debug_Statistics::Get_Record_Texture_Size() // Return total textures used during latest frame, in bytes -{ - return last_frame_texture_memory; -} - -int Debug_Statistics::Get_Record_Texture_Count() // Return total textures used during latest frame, in bytes -{ - return last_frame_texture_count; -} - -int Debug_Statistics::Get_Record_Texture_Change_Count() -{ - return last_frame_texture_change_count; -} - -int Debug_Statistics::Get_Record_Lightmap_Texture_Size() // Return total lightmap textures used during latest frame, in bytes -{ - return last_frame_lightmap_texture_memory; -} - -int Debug_Statistics::Get_Record_Lightmap_Texture_Count() // Return total lightmap textures used during latest frame, in bytes -{ - return last_frame_lightmap_texture_count; -} - -int Debug_Statistics::Get_Record_Procedural_Texture_Size() // Return total procedural textures used during latest frame, in bytes -{ - return last_frame_procedural_texture_memory; -} - -int Debug_Statistics::Get_Record_Procedural_Texture_Count() // Return total procedural textures used during latest frame, in bytes -{ - return last_frame_procedural_texture_count; -} - -const StringClass& Debug_Statistics::Get_Record_Texture_String() -{ - return texture_statistics_string; -} - -// ---------------------------------------------------------------------------- - -static int dx8_skin_renders; -static int last_frame_dx8_skin_renders; -static int dx8_skin_polygons; -static int last_frame_dx8_skin_polygons; -static int dx8_skin_vertices; -static int last_frame_dx8_skin_vertices; -static int dx8_polygons; -static int last_frame_dx8_polygons; -static int dx8_vertices; -static int last_frame_dx8_vertices; -static int sorting_polygons; -static int last_frame_sorting_polygons; -static int sorting_vertices; -static int last_frame_sorting_vertices; -static int draw_calls; -static int last_frame_draw_calls; - -void Debug_Statistics::Record_DX8_Skin_Polys_And_Vertices(int pcount,int vcount) -{ - dx8_skin_polygons+=pcount; - dx8_skin_vertices+=vcount; - dx8_skin_renders++; - draw_calls++; -} - -void Debug_Statistics::Record_DX8_Polys_And_Vertices(int pcount,int vcount,const ShaderClass& shader) -{ - if (shader.Get_NPatch_Enable()==ShaderClass::NPATCH_ENABLE && DX8Wrapper::Get_Current_Caps()->Support_NPatches()) { - unsigned level=WW3D::Get_NPatches_Level(); - level*=level; - pcount*=level; - } - dx8_polygons+=pcount; - dx8_vertices+=vcount; - draw_calls++; -} - -int Debug_Statistics::Get_DX8_Skin_Renders() -{ - return last_frame_dx8_skin_renders; -} - -int Debug_Statistics::Get_DX8_Skin_Polygons() -{ - return last_frame_dx8_skin_polygons; -} - -int Debug_Statistics::Get_DX8_Skin_Vertices() -{ - return last_frame_dx8_skin_vertices; -} - -int Debug_Statistics::Get_DX8_Polygons() -{ - return last_frame_dx8_polygons; -} - -int Debug_Statistics::Get_DX8_Vertices() -{ - return last_frame_dx8_vertices; -} - -void Debug_Statistics::Record_Sorting_Polys_And_Vertices(int pcount,int vcount) -{ - sorting_polygons+=pcount; - sorting_vertices+=vcount; - draw_calls++; -} - -int Debug_Statistics::Get_Sorting_Polygons() -{ - return last_frame_sorting_polygons; -} - -int Debug_Statistics::Get_Sorting_Vertices() -{ - return last_frame_sorting_vertices; -} - -int Debug_Statistics::Get_Draw_Calls() -{ - return last_frame_draw_calls; -} - -// ---------------------------------------------------------------------------- -// -// -// -// ---------------------------------------------------------------------------- - -void Debug_Statistics::Begin_Statistics() -{ - dx8_polygons=0; - dx8_vertices=0; - dx8_skin_polygons=0; - dx8_skin_vertices=0; - dx8_skin_renders=0; - sorting_polygons=0; - sorting_vertices=0; - draw_calls=0; - Record_Texture_Begin(); - DX8Wrapper::Begin_Statistics(); -// DX8MeshRendererClass::Begin_Statistics(); -} - -void Debug_Statistics::End_Statistics() -{ - Record_Texture_End(); - last_frame_dx8_skin_polygons=dx8_skin_polygons; - last_frame_dx8_skin_vertices=dx8_skin_vertices; - last_frame_dx8_skin_renders=dx8_skin_renders; - last_frame_dx8_polygons=dx8_polygons; - last_frame_dx8_vertices=dx8_vertices; - last_frame_sorting_polygons=sorting_polygons; - last_frame_sorting_vertices=sorting_vertices; - last_frame_draw_calls=draw_calls; -// DX8MeshRendererClass::End_Statistics(); - DX8Wrapper::End_Statistics(); -} - -void Debug_Statistics::Shutdown_Statistics() -{ - texture_statistics_string.Release_Resources(); -} -// ---------------------------------------------------------------------------- - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/statistics.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/statistics.h deleted file mode 100644 index a50e5de60e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/statistics.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef WW3D_STATISTICS_H -#define WW3D_STATISTICS_H - -#if defined(_MSC_VER) -#pragma once -#endif - -#include "always.h" -//#include "wwstring.h" - -class TextureClass; -class StringClass; -class ShaderClass; - -namespace Debug_Statistics -{ - enum RecordTextureMode - { - RECORD_TEXTURE_NONE, - RECORD_TEXTURE_SIMPLE, - RECORD_TEXTURE_DETAILS - }; - - // Texture memory tracking system - void Record_Texture_Mode(RecordTextureMode m); - RecordTextureMode Get_Record_Texture_Mode(); - - void Record_Texture(TextureClass* t); - int Get_Record_Texture_Size(); // Return total size of textures used during latest frame, in bytes - int Get_Record_Lightmap_Texture_Size(); // Return total size of lightmap textures used during latest frame, in bytes - int Get_Record_Procedural_Texture_Size(); // Return total size of procedural textures used during latest frame, in bytes - int Get_Record_Texture_Count(); // Return total number of textures used during latest frame - int Get_Record_Texture_Change_Count(); - int Get_Record_Lightmap_Texture_Count(); // Return total number of lightmap textures used during latest frame - int Get_Record_Procedural_Texture_Count(); // Return total number of procedutal textures used during latest frame - const StringClass& Get_Record_Texture_String(); - - void Record_DX8_Skin_Polys_And_Vertices(int pcount,int vcount); - void Record_DX8_Polys_And_Vertices(int pcount,int vcount,const ShaderClass& shader); - void Record_Sorting_Polys_And_Vertices(int pcount,int vcount); - int Get_DX8_Polygons(); - int Get_DX8_Vertices(); - int Get_DX8_Skin_Renders(); - int Get_DX8_Skin_Polygons(); - int Get_DX8_Skin_Vertices(); - int Get_Sorting_Polygons(); - int Get_Sorting_Vertices(); - int Get_Draw_Calls(); - - void Begin_Statistics(); - void End_Statistics(); - void Shutdown_Statistics(); -}; - -#define ADD_STATISTICS_VERTEX_PROCESSOR_PUSH Debug_Statistics::Add_Vertex_Processor() -#define DX8_RECORD_TEXTURE(t) Debug_Statistics::Record_Texture(t) -#define DX8_RECORD_TEXTURE_ARRAY(t,c) Debug_Statistics::Record_Texture_Array(t,c) -#define DX8_RECORD_RENDER(polys,verts,shader) Debug_Statistics::Record_DX8_Polys_And_Vertices(polys,verts,shader) -#define DX8_RECORD_SORTING_RENDER(polys,verts) Debug_Statistics::Record_Sorting_Polys_And_Vertices(polys,verts) -#define DX8_RECORD_SKIN_RENDER(polys,verts) Debug_Statistics::Record_DX8_Skin_Polys_And_Vertices(polys,verts) - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/streak.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/streak.cpp deleted file mode 100644 index 3a9fe42c6d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/streak.cpp +++ /dev/null @@ -1,745 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /VSS_Sync/ww3d2/segline.cpp $* - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 23 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "streak.h" -#include "ww3d.h" -#include "rinfo.h" -#include "predlod.h" -#include "v3_rnd.h" -#include "texture.h" -#include "coltest.h" -#include "w3d_file.h" -#include "texture.h" -#include "dx8wrapper.h" -#include "vp.h" -#include "Vector3i.h" -#include "sortingrenderer.h" - -static SegLineRendererClass _LineRenderer; - - -/* -** StreakLineClass implementation: -*/ - -StreakLineClass::StreakLineClass(void) : - MaxSubdivisionLevels(0), - NormalizedScreenArea(0.0f) -{ - Personalities = NULL; - -} - -StreakLineClass::StreakLineClass(const StreakLineClass & src) : - MaxSubdivisionLevels(src.MaxSubdivisionLevels), - NormalizedScreenArea(src.NormalizedScreenArea), - PointLocations(src.PointLocations), - PointColors(src.PointColors), - PointWidths(src.PointWidths), - LineRenderer(src.LineRenderer), - StreakRenderer(src.StreakRenderer), - Personalities(src.Personalities) -{ -} - -StreakLineClass & StreakLineClass::operator = (const StreakLineClass &that) -{ - RenderObjClass::operator = (that); - - if (this != &that) { - - MaxSubdivisionLevels = that.MaxSubdivisionLevels; - NormalizedScreenArea = that.NormalizedScreenArea; - PointLocations = that.PointLocations; - PointColors = that.PointColors; - PointWidths = that.PointWidths; - LineRenderer = that.LineRenderer; - StreakRenderer = that.StreakRenderer; - Personalities = that.Personalities; - } - - return * this; -} - -//StreakLineClass::~StreakLineClass(void) -//{ -//} - - - - - -void StreakLineClass::Reset_Line(void) -{ - LineRenderer.Reset_Line(); - StreakRenderer.Reset_Line(); -} - - - - - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -// These are segment points, and include the start and end point of the -// entire line. Therefore there must be at least two. -void StreakLineClass::Set_Locs( unsigned int num_points, Vector3 *locs ) -{ - if (num_points < 2 || !locs) { - WWASSERT(0); - return; - } - - PointLocations.Delete_All(); - for (unsigned int i=0; iProcess_Reduction(); - - unsigned int sort_level = SORT_LEVEL_NONE; - - if (!WW3D::Is_Sorting_Enabled()) - sort_level=Get_Shader().Guess_Sort_Level(); - - if (WW3D::Are_Static_Sort_Lists_Enabled() && sort_level!=SORT_LEVEL_NONE) { - - WW3D::Add_To_Static_Sort_List(this, sort_level); - - } - else - { - if ( !PointColors.Count() || !PointWidths.Count() ) - { - Render_Seg_Line(rinfo); - } - else - { - Render_Streak_Line(rinfo); - } - } -} - -void StreakLineClass::Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const -{ - // Get object-space bounding box and create bounding sphere from it - AABoxClass box; - Get_Obj_Space_Bounding_Box(box); - - // Create object-space bounding sphere from the bounding box: - sphere.Center = box.Center; - sphere.Radius = box.Extent.Length(); -} - -void StreakLineClass::Get_Obj_Space_Bounding_Box(AABoxClass & box) const -{ - unsigned int num_points = PointLocations.Count(); - - // Line must have at least two points to be valid - - if (num_points >= 2) { - - // Find object-space axis-aligned bounding box - Vector3 max_coords; - Vector3 min_coords; - unsigned int i; - - // We create two bounding boxes; one from the points, and if we have random noise - // subdivision we create another one from the midpoints and factor the noise amplitude - // into the second box, and then combine the two. - - // First bounding box: - max_coords = PointLocations[0]; - min_coords = PointLocations[0]; - for (i = 1; i < num_points; i++) { - max_coords.Update_Max(PointLocations[i]); - min_coords.Update_Min(PointLocations[i]); - } - // Enlarge bounding box by half the width - float enlarge_factor = LineRenderer.Get_Width() * 0.5f; - Vector3 enlarge_offset; - enlarge_offset.Set(enlarge_factor, enlarge_factor, enlarge_factor); - max_coords += enlarge_offset; - min_coords -= enlarge_offset; - - if (MaxSubdivisionLevels > 0) { - // Second bounding box: - Vector3 max_coords2; - Vector3 min_coords2; - Vector3 midpoint = (PointLocations[0] + PointLocations[1]) * 0.5f; - max_coords2 = midpoint; - min_coords2 = midpoint; - for (i = 1; i < num_points - 1; i++) { - midpoint = (PointLocations[i] + PointLocations[i + 1]) * 0.5f; - max_coords2.Update_Max(midpoint); - min_coords2.Update_Min(midpoint); - } - - // We ignore the actual number of subdivision levels: we multiply the random noise - // amplitude by 2, which is the limit as the number of subdivision levels goes to - // infinity. - enlarge_factor += (2 * LineRenderer.Get_Noise_Amplitude()); - enlarge_offset.Set(enlarge_factor, enlarge_factor, enlarge_factor); - max_coords2 += enlarge_offset; - min_coords2 -= enlarge_offset; - - // Combine the two: - max_coords.Update_Max(max_coords2); - min_coords.Update_Min(min_coords2); - } - - box.Init_Min_Max(min_coords, max_coords); - - } else { - // Invalid line - return something - box.Init(Vector3(0,0,0),Vector3(1,1,1)); - } -} - -void StreakLineClass::Prepare_LOD(CameraClass &camera) -{ - // Find the maximum screen dimension of the object in pixels - NormalizedScreenArea = Get_Screen_Size(camera); - -// // Find and set texture reduction factor -// Set_Texture_Reduction_Factor(Calculate_Texture_Reduction_Factor(NormalizedScreenArea)); - - // Ensure subdivision level is legal - unsigned int lvl = LineRenderer.Get_Current_Subdivision_Level(); - lvl = MIN(lvl, MaxSubdivisionLevels); - LineRenderer.Set_Current_Subdivision_Level(lvl); - - // Prepare LOD processing if the line has subdivision enabled: - if (MaxSubdivisionLevels > 0) { - // Add myself to the LOD optimizer: - PredictiveLODOptimizerClass::Add_Object(this); - } else { - // Not added to optimizer, need to add cost - PredictiveLODOptimizerClass::Add_Cost(Get_Cost()); - } -} - -void StreakLineClass::Increment_LOD(void) -{ - unsigned int lvl = LineRenderer.Get_Current_Subdivision_Level(); - - lvl = MIN(lvl+1,MaxSubdivisionLevels); - - LineRenderer.Set_Current_Subdivision_Level(lvl); -} - -void StreakLineClass::Decrement_LOD(void) -{ - int lvl = LineRenderer.Get_Current_Subdivision_Level(); - if (lvl == 0) return; - LineRenderer.Set_Current_Subdivision_Level(lvl-1); -} - -float StreakLineClass::Get_Cost(void) const -{ - return Get_Num_Polys(); -} - -float StreakLineClass::Get_Value(void) const -{ - // If we are at the minimum LOD, we must return AT_MIN_LOD. - if (LineRenderer.Get_Current_Subdivision_Level() == 0) { - return AT_MIN_LOD; - } else { - float polycount = (float)Get_Num_Polys(); - float benefit_factor = 1.0f - (0.5f / (polycount * polycount)); - return (benefit_factor * NormalizedScreenArea) / Get_Cost(); - } -} - -float StreakLineClass::Get_Post_Increment_Value(void) const -{ - // If we are at the maximum LOD, we must return AT_MIN_LOD. - if (LineRenderer.Get_Current_Subdivision_Level() == MaxSubdivisionLevels) { - return AT_MAX_LOD; - } else { - // Assumption: each subdivision level doubles polycount - float polycount = 2.0f * (float)Get_Num_Polys(); - float benefit_factor = 1.0f - (0.5f / (polycount * polycount)); - // Assumption: Cost() == polycount - return (benefit_factor * NormalizedScreenArea) / polycount; - } -} - -void StreakLineClass::Set_LOD_Level(int lod) -{ - lod = MAX(0, lod); - lod = MIN(lod, (int)MaxSubdivisionLevels); - - LineRenderer.Set_Current_Subdivision_Level((unsigned int)lod); -} - -int StreakLineClass::Get_LOD_Level(void) const -{ - return (int) LineRenderer.Get_Current_Subdivision_Level(); -} - -int StreakLineClass::Get_LOD_Count(void) const -{ - return (int)MaxSubdivisionLevels; -} -/* -void StreakLineClass::Set_Texture_Reduction_Factor(float trf) -{ - if (LineRenderer.Peek_Texture()) LineRenderer.Peek_Texture()->Set_Reduction_Factor(trf); -}*/ - - - -void StreakLineClass::Render_Seg_Line(RenderInfoClass & rinfo) -{ - // Line must have at least two points to be valid - if (PointLocations.Count() < 2) return; - - SphereClass bounding_sphere; - Get_Obj_Space_Bounding_Sphere(bounding_sphere); - -// LineRenderer.Set_Width(rand()%3); - - LineRenderer.Render( - rinfo, - Transform, - PointLocations.Count(), - &(PointLocations[0]), - bounding_sphere - ); -} - - -void StreakLineClass::Render_Streak_Line(RenderInfoClass & rinfo) -{ - - WWASSERT(PointLocations.Count() == PointColors.Count()); - WWASSERT(PointLocations.Count() == PointWidths.Count()); - - // Line must have at least two points to be valid - if (PointLocations.Count() < 2) return; - if (PointColors.Count() < 2) return; - if (PointWidths.Count() < 2) return; - - if(PointLocations.Count() != PointColors.Count()) return; - if(PointLocations.Count() != PointWidths.Count()) return; - - SphereClass bounding_sphere; - Get_Obj_Space_Bounding_Sphere(bounding_sphere); - - -// StreakRenderer.Render( -// rinfo, -// Transform, -// PointLocations.Count(), -// &(PointLocations[0]), -// bounding_sphere -// ); - StreakRenderer.RenderStreak( - rinfo, - Transform, - PointLocations.Count(), - &(PointLocations[0]), - &(PointColors[0]), - &(PointWidths[0]), - bounding_sphere, - Personalities - ); -} - - -bool StreakLineClass::Cast_Ray(RayCollisionTestClass & raytest) -{ - if ((Get_Collision_Type() & raytest.CollisionType) == 0) return false; - - bool retval = false; - - // - // Check each line segment against the ray - // - float fraction = 1.0F; - for (uint32 index = 1; index < (unsigned int)PointLocations.Count(); index ++) - { -#ifdef ALLOW_TEMPORARIES - Vector3 curr_start = Transform * PointLocations[index-1]; - Vector3 curr_end = Transform * PointLocations[index]; - LineSegClass line_seg (curr_start, curr_end); -#else - Vector3 curr[2]; - Transform.mulVector3Array(&PointLocations[index-1], curr, 2); - LineSegClass line_seg(curr[0], curr[1]); -#endif - - Vector3 p0; - Vector3 p1; - if (raytest.Ray.Find_Intersection (line_seg, &p0, &fraction, &p1, NULL)) { - - // - // Determine if the ray was close enough to this line to be - // considered intersecting - // - float dist = (p0 - p1).Length (); - if (dist <= LineRenderer.Get_Width() && fraction >= 0 && fraction < raytest.Result->Fraction) { - //if (dist <= Width && fraction < raytest.Result->Fraction) { - retval = true; - break; - } - } - } - - // - // Fill in the raytest structure if we were successfull - // - if (retval) { - raytest.Result->Fraction = fraction; - raytest.Result->SurfaceType = SURFACE_TYPE_DEFAULT; - raytest.CollidedRenderObj = this; - } - - return retval; -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/streak.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/streak.h deleted file mode 100644 index 962362ba2d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/streak.h +++ /dev/null @@ -1,220 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/********************************************************************************* - *** C O N F I D E N T I A L --- E A P A C I F I C *** - ********************************************************************************* - * * - * Project Name : G * - * * - * $Archive:: ww3d2/streak.h $* - * * - * $Author:: Mark Lorenzen $* - * * - * $Modtime:: 8/6/02 4:09p $* - * * - * $Revision:: 1 $* - * * - *-------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef STREAK_H -#define STREAK_H - -#include "rendobj.h" -#include "shader.h" -#include "simplevec.h" -#include "seglinerenderer.h" -#include "streakRender.h" - -class TextureClass; - -/* -** StreakLineClass -- a render object for rendering thick segmented lines. -** essentially it is segmentedlineclass++ -** with added characteristics, such as varying thickness, opacity -** color and precise texture tiling... -** The reason this does not descend from segmentedlineclass, is to streamline -** the upcoming merge with the LasVegas code (to keep our changes out of their code) -*/ - -class StreakLineClass : public RenderObjClass -{ - public: - - StreakLineClass(void); - StreakLineClass(const StreakLineClass & src); - StreakLineClass & operator = (const StreakLineClass &that); -// virtual ~StreakLineClass(void); - - void Reset_Line(void); - - /* - ** StreakLineClass interface: - */ - - // These are segment points, and include the start and end point of the - // entire line. Therefore there must be at least two. - int Get_Num_Points(void); - - - // Set object-space location for a given point. - // NOTE: If given position beyond end of point list, do nothing. - void Set_Point_Location(unsigned int point_idx, const Vector3 &location); - - // Get object-space location for a given point. - void Get_Point_Location(unsigned int point_idx, Vector3 &loc); - - // Modify the line by adding and removing points - void Add_Point(const Vector3 & location); - void Delete_Point(unsigned int point_idx); - - // Get/set global properties (which affect all line segments) - TextureClass * Get_Texture(void); - ShaderClass Get_Shader(void); - - float Get_Width(void); - void Get_Color(Vector3 &color); - float Get_Opacity(void); - float Get_Noise_Amplitude(void); - float Get_Merge_Abort_Factor(void); - unsigned int Get_Subdivision_Levels(void); - SegLineRendererClass::TextureMapMode Get_Texture_Mapping_Mode(void); - float Get_Texture_Tile_Factor(void); - Vector2 Get_UV_Offset_Rate(void); - int Is_Merge_Intersections(void); - int Is_Freeze_Random(void); - int Is_Sorting_Disabled(void); - int Are_End_Caps_Enabled(void); - - void Set_Texture(TextureClass *texture); - void Set_Shader(ShaderClass shader); - void Set_Width(float width); - void Set_Color(const Vector3 &color); - void Set_Opacity(float opacity); - void Set_Noise_Amplitude(float amplitude); - void Set_Merge_Abort_Factor(float factor); - void Set_Subdivision_Levels(unsigned int levels); - void Set_Texture_Mapping_Mode(SegLineRendererClass::TextureMapMode mode); - // WARNING! Do NOT set the tile factor to be too high (should be less than 8) or negative - //performance impact will result! - void Set_Texture_Tile_Factor(float factor); - void Set_UV_Offset_Rate(const Vector2 &rate); - void Set_Merge_Intersections(int onoff); - void Set_Freeze_Random(int onoff); - void Set_Disable_Sorting(int onoff); - void Set_End_Caps(int onoff); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Cloning and Identification - ///////////////////////////////////////////////////////////////////////////// - virtual RenderObjClass * Clone(void) const; - virtual int Class_ID(void) const { return CLASSID_SEGLINE; } - virtual int Get_Num_Polys(void) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Rendering - ///////////////////////////////////////////////////////////////////////////// - virtual void Render( RenderInfoClass & rinfo ); - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Bounding Volumes - ///////////////////////////////////////////////////////////////////////////// - virtual void Get_Obj_Space_Bounding_Sphere(SphereClass & sphere) const; - virtual void Get_Obj_Space_Bounding_Box(AABoxClass & box) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Predictive LOD - ///////////////////////////////////////////////////////////////////////////// - virtual void Prepare_LOD(CameraClass &camera); - virtual void Increment_LOD(void); - virtual void Decrement_LOD(void); - virtual float Get_Cost(void) const; - virtual float Get_Value(void) const; - virtual float Get_Post_Increment_Value(void) const; - virtual void Set_LOD_Level(int lod); - virtual int Get_LOD_Level(void) const; - virtual int Get_LOD_Count(void) const; - - ///////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Attributes, Options, Properties, etc - ///////////////////////////////////////////////////////////////////////////// -// virtual void Set_Texture_Reduction_Factor(float trf); - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Render Object Interface - Collision Detection - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual bool Cast_Ray(RayCollisionTestClass & raytest); - - void Set_LocsWidthsColors( unsigned int num_points, - Vector3 *locs, - float *widths = NULL, - Vector4 *colors = NULL, - unsigned int *personalities = NULL); - - - protected: - - void Set_Locs(unsigned int num_points, Vector3 *locs); - void Set_Widths(unsigned int num_points, float *widths); - void Set_Colors(unsigned int num_points, Vector4 *colors); - - void Render_Seg_Line(RenderInfoClass & rinfo); - void Render_Streak_Line(RenderInfoClass & rinfo); - - private: - - // Subdivision properties - unsigned int MaxSubdivisionLevels; - - - // per-particle seeds - unsigned int *Personalities; - - // Normalized screen area - used for LOD purposes - float NormalizedScreenArea; - - // Per-point location array - //ShareBufferClass *PointLocations; - SimpleDynVecClass PointLocations; // World/cameraspace point locs - SimpleDynVecClass PointColors; // RGBA - SimpleDynVecClass PointWidths; // float line thickness - - - - - - // LineRenderer, contains most of the line settings. - SegLineRendererClass LineRenderer; - StreakRendererClass StreakRenderer;//special, per-point alpha/color/size -}; - - - - - - - - - -#endif // SEGLINE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/streakRender.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/streakRender.cpp deleted file mode 100644 index 402c38ea80..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/streakRender.cpp +++ /dev/null @@ -1,1412 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** EA PACIFIC CONFIDENTIAL *** - *********************************************************************************************** - * * - * Original Author:: Mark Lorenzen * - * * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "streakRender.h" -#include "ww3d.h" -#include "rinfo.h" -#include "dx8wrapper.h" -#include "sortingrenderer.h" -#include "vp.h" -#include "Vector3i.h" -#include "RANDOM.H" -#include "v3_rnd.h" - - -/* We have chunking logic which handles N segments at a time. To simplify the subdivision logic, -** we will ensure that N is a power of two and that N >= 2^MAX_STREAK_SUBDIV_LEVELS, so that the -** subdivision logic can be inside the chunking loop. -*/ - -#if MAX_STREAK_SUBDIV_LEVELS > 7 -#define STREAK_CHUNK_SIZE (1 << MAX_STREAK_SUBDIV_LEVELS) -#else -#define STREAK_CHUNK_SIZE (128) -#endif - -#define MAX_STREAK_POINT_BUFFER_SIZE (1 + STREAK_CHUNK_SIZE) -// This macro depends on the assumption that each line segment is two polys. -#define MAX_STREAK_POLY_BUFFER_SIZE (STREAK_CHUNK_SIZE * 2) - - - - -StreakRendererClass::StreakRendererClass(void) : - Texture(NULL), - Shader(ShaderClass::_PresetAdditiveSpriteShader), - Width(0.0f), - Color(Vector3(1,1,1)), - Opacity(1.0f), - SubdivisionLevel(0), - NoiseAmplitude(0.0f), - MergeAbortFactor(1.5f), - TextureTileFactor(1.0f), - LastUsedSyncTime(WW3D::Get_Sync_Time()), - CurrentUVOffset(0.0f,0.0f), - UVOffsetDeltaPerMS(0.0f, 0.0f), - Bits(DEFAULT_BITS) -{ - -} - -StreakRendererClass::StreakRendererClass(const StreakRendererClass & that) : - Texture(NULL), - Shader(ShaderClass::_PresetAdditiveSpriteShader), - Width(0.0f), - Color(Vector3(1,1,1)), - Opacity(1.0f), - SubdivisionLevel(0), - NoiseAmplitude(0.0f), - MergeAbortFactor(1.5f), - TextureTileFactor(1.0f), - LastUsedSyncTime(that.LastUsedSyncTime), - CurrentUVOffset(0.0f,0.0f), - UVOffsetDeltaPerMS(0.0f, 0.0f), - Bits(DEFAULT_BITS) -{ - *this = that; -} - -StreakRendererClass & StreakRendererClass::operator = (const StreakRendererClass & that) -{ - if (this != &that) { - REF_PTR_SET(Texture,that.Texture); - Shader = that.Shader; - Width = that.Width; - Color = that.Color; - Opacity = that.Opacity; - SubdivisionLevel = that.SubdivisionLevel; - NoiseAmplitude = that.NoiseAmplitude; - MergeAbortFactor = that.MergeAbortFactor; - TextureTileFactor = that.TextureTileFactor; - LastUsedSyncTime = that.LastUsedSyncTime; - CurrentUVOffset = that.CurrentUVOffset; - UVOffsetDeltaPerMS = that.UVOffsetDeltaPerMS; - Bits = that.Bits; - } - return *this; -} - -StreakRendererClass::~StreakRendererClass(void) -{ - REF_PTR_RELEASE(Texture); -} - -void StreakRendererClass::Init(const W3dEmitterLinePropertiesStruct & props) -{ - // translate the flags - Set_Merge_Intersections(props.Flags & W3D_ELINE_MERGE_INTERSECTIONS); - Set_Freeze_Random(props.Flags & W3D_ELINE_FREEZE_RANDOM); - Set_Disable_Sorting(props.Flags & W3D_ELINE_DISABLE_SORTING); - Set_End_Caps(props.Flags & W3D_ELINE_END_CAPS); - - int texture_mode = ((props.Flags & W3D_ELINE_TEXTURE_MAP_MODE_MASK) >> W3D_ELINE_TEXTURE_MAP_MODE_OFFSET); - switch (texture_mode) - { - case W3D_ELINE_UNIFORM_WIDTH_TEXTURE_MAP: - Set_Texture_Mapping_Mode(UNIFORM_WIDTH_TEXTURE_MAP); - break; - case W3D_ELINE_UNIFORM_LENGTH_TEXTURE_MAP: - Set_Texture_Mapping_Mode(UNIFORM_LENGTH_TEXTURE_MAP); - break; - case W3D_ELINE_TILED_TEXTURE_MAP: - Set_Texture_Mapping_Mode(TILED_TEXTURE_MAP); - break; - }; - - // install all other settings - Set_Current_Subdivision_Level(props.SubdivisionLevel); - Set_Noise_Amplitude(props.NoiseAmplitude); - Set_Merge_Abort_Factor(props.MergeAbortFactor); - Set_Texture_Tile_Factor(props.TextureTileFactor); - Set_UV_Offset_Rate(Vector2(props.UPerSec,props.VPerSec)); -} - - -void StreakRendererClass::Set_Texture(TextureClass *texture) -{ - REF_PTR_SET(Texture,texture); -} - -TextureClass * StreakRendererClass::Get_Texture(void) const -{ - if (Texture != NULL) { - Texture->Add_Ref(); - } - return Texture; -} - -void StreakRendererClass::Set_Current_UV_Offset(const Vector2 & offset) -{ - CurrentUVOffset = offset; -} - -void StreakRendererClass::Set_Texture_Tile_Factor(float factor) -{ - if (factor > 8.0f) { - factor = 8.0f; - WWDEBUG_SAY(("Texture Tile Factor too large in StreakRendererClass!\r\n")); - } else { - factor = MAX(factor, 0.0f); - } - TextureTileFactor = factor; -} - -void StreakRendererClass::Reset_Line(void) -{ - LastUsedSyncTime = WW3D::Get_Sync_Time(); - CurrentUVOffset.Set(0.0f,0.0f); -} - -/////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////// -void StreakRendererClass::Render -( - RenderInfoClass & rinfo, - const Matrix3D & transform, - unsigned int num_points, - Vector3 * points, - const SphereClass & obj_sphere -) -{ - //NOTHING! - - int a = 5; - ++a; - ++a; - - if (a) - return; - -} - -/////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////// - - - - -void StreakRendererClass::subdivision_util(unsigned int point_cnt, const Vector3 *xformed_pts, - const float *base_tex_v, unsigned int *p_sub_point_cnt, Vector3 *xformed_subdiv_pts, - float *subdiv_tex_v) -{ - // CAUTION: freezing the random offsets will make it more readily apparent that the offsets - // are in camera space rather than worldspace. - int freeze_random = Is_Freeze_Random(); - Random3Class randomize; - const float oo_int_max = 1.0f / (float)INT_MAX; - Vector3SolidBoxRandomizer randomizer(Vector3(1,1,1)); - Vector3 randvec(0,0,0); - unsigned int sub_pointIndex = 0; - - struct StreakSubdivision { - Vector3 StartPos; - Vector3 EndPos; - float StartTexV; // V texture coordinate of start point - float EndTexV; // V texture coordinate of end point - float Rand; - unsigned int Level; // Subdivision level - }; - - StreakSubdivision stack[2 * MAX_STREAK_SUBDIV_LEVELS]; // Maximum number needed - int tos = 0; - - for (unsigned int pointIndex = 0; pointIndex < point_cnt - 1; pointIndex++) { - - // Subdivide the (pointIndex, pointIndex + 1) segment. Produce pointIndex and all subdivided points up to - // (not including) pointIndex + 1. - tos = 0; - stack[0].StartPos = xformed_pts[pointIndex]; - stack[0].EndPos = xformed_pts[pointIndex + 1]; - stack[0].StartTexV = base_tex_v[pointIndex]; - stack[0].EndTexV = base_tex_v[pointIndex + 1]; - stack[0].Rand = NoiseAmplitude; - stack[0].Level = 0; - - for (; tos >= 0;) { - if (stack[tos].Level == SubdivisionLevel) { - // Generate point location and texture V coordinate - xformed_subdiv_pts[sub_pointIndex] = stack[tos].StartPos; - subdiv_tex_v[sub_pointIndex++] = stack[tos].StartTexV; - - // Pop - tos--; - } else { - // Recurse down: pop existing entry and push two subdivided ones. - if (freeze_random) { - randvec.Set(randomize * oo_int_max, randomize * oo_int_max, randomize * oo_int_max); - } else { - randomizer.Get_Vector(randvec); - } - stack[tos + 1].StartPos = stack[tos].StartPos; - stack[tos + 1].EndPos = (stack[tos].StartPos + stack[tos].EndPos) * 0.5f + randvec * stack[tos].Rand; - stack[tos + 1].StartTexV = stack[tos].StartTexV; - stack[tos + 1].EndTexV = (stack[tos].StartTexV + stack[tos].EndTexV) * 0.5f; - stack[tos + 1].Rand = stack[tos].Rand * 0.5f; - stack[tos + 1].Level = stack[tos].Level + 1; - stack[tos].StartPos = stack[tos + 1].EndPos; - // stack[tos].EndPos already has the right value - stack[tos].StartTexV = stack[tos + 1].EndTexV; - // stack[tos].EndTexV already has the right value - stack[tos].Rand = stack[tos + 1].Rand; - stack[tos].Level = stack[tos + 1].Level; - tos++; - } - } - } - // Last point - xformed_subdiv_pts[sub_pointIndex] = xformed_pts[point_cnt - 1]; - subdiv_tex_v[sub_pointIndex++] = base_tex_v[point_cnt - 1]; - - // Output: - *p_sub_point_cnt = sub_pointIndex; -} - - -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// -/////// /////// /////// /////// /////// /////// /////// /////// - - - -void StreakRendererClass::RenderStreak -( - RenderInfoClass & rinfo, - const Matrix3D & transform, - unsigned int num_points, - Vector3 * points, - Vector4 * colors, /////////////// DIFFERENT FROM RENDER( ) - float * widths, /////////////// DIFFERENT FROM RENDER( ) - const SphereClass & obj_sphere, - unsigned int *personalities /////////////// DIFFERENT FROM RENDER( ) -) -{ - Matrix4x4 view; - DX8Wrapper::Get_Transform(D3DTS_VIEW,view); - - Matrix4x4 identity(true); - DX8Wrapper::Set_Transform(D3DTS_WORLD,identity); - DX8Wrapper::Set_Transform(D3DTS_VIEW,identity); - - /* - ** Handle texture UV offset animation (done once for entire line). - */ - unsigned int delta = WW3D::Get_Sync_Time() - LastUsedSyncTime; - float del = (float)delta; - //Vector2 uv_offset = CurrentUVOffset + UVOffsetDeltaPerMS * del; - - // ensure offsets are in [0, 1] range: - //uv_offset.X = uv_offset.X - floorf(uv_offset.X); - //uv_offset.Y = uv_offset.Y - floorf(uv_offset.Y); - - // Update state - //CurrentUVOffset = uv_offset; - LastUsedSyncTime = WW3D::Get_Sync_Time(); - - // Used later - TextureMapMode map_mode = Get_Texture_Mapping_Mode(); - - /* - ** Process line geometry: - */ - - // This has been tweaked to produce empirically good results. - const float parallel_factor = 0.9f; - - // We reduce the chunk size to take account of subdivision levels (so that the # of points - // after subdivision will be no higher than the allowed maximum). We know this will not reduce - // the chunk size below 2, since the chunk size must be at least two to the power of the - // maximum allowable number of subdivisions. The plus 1 is because #points = #segments + 1. - unsigned int chunk_size = (STREAK_CHUNK_SIZE >> SubdivisionLevel) + 1; - if (chunk_size > num_points) chunk_size = num_points; - - // Chunk through the points (we increment by chunk_size - 1 because the last point of this - // chunk must be reused as the first point of the next chunk. This is also the reason we stop - // when chunkIndex = NumPoints - 1: the last point has already been processed in the previous - // iteration so we don't need another one). - for (unsigned int chunkIndex = 0; chunkIndex < num_points - 1; chunkIndex += (chunk_size - 1)) - { - unsigned int point_cnt = num_points - chunkIndex; - point_cnt = MIN(point_cnt, chunk_size); - - // We use these different loop indices (which loop INSIDE a chunk) to improve readability: - unsigned int pointIndex; // Point index - unsigned int segmentIndex; // Segment index - unsigned int intersectionIndex; // Intersection index - - - /* - ** Transform points in chunk from objectspace to eyespace: - */ - - Vector3 xformed_pts[MAX_STREAK_POINT_BUFFER_SIZE]; - - Matrix3D view2( view[0].X,view[0].Y,view[0].Z,view[0].W, - view[1].X,view[1].Y,view[1].Z,view[1].W, - view[2].X,view[2].Y,view[2].Z,view[2].W); - -#ifdef ALLOW_TEMPORARIES - Matrix3D modelview=view2*transform; -#else - Matrix3D modelview; - modelview.mul(view2, transform); -#endif - - VectorProcessorClass::Transform(&xformed_pts[0], - &points[chunkIndex], modelview, point_cnt); - - - /* - ** Prepare v parameter per point - used for texture mapping (esp. tiled mapping mode) - */ - - float base_tex_v[MAX_STREAK_POINT_BUFFER_SIZE]; - float u_values[2]; - - - // I HAVE HARD CODED IT TO USE UNIFORM WIDTH AND LENGTH - for (pointIndex = 0; pointIndex < point_cnt; pointIndex++) - { - // All 0 - base_tex_v[pointIndex] = 0.0f; - } - u_values[0] = 0.0f; - u_values[1] = 1.0f; - - - - - - -// switch (map_mode) -// { -// case UNIFORM_WIDTH_TEXTURE_MAP:// only non-dead case -// for (pointIndex = 0; pointIndex < point_cnt; pointIndex++) -// { -// // All 0 -// base_tex_v[pointIndex] = 0.0f; -// } -// u_values[0] = 0.0f; -// u_values[1] = 1.0f; -// break; -// case UNIFORM_LENGTH_TEXTURE_MAP: -// for (pointIndex = 0; pointIndex < point_cnt; pointIndex++) -// { -// // Increasing V -// base_tex_v[pointIndex] = (float)(pointIndex + chunkIndex) * TextureTileFactor; -// } -// u_values[0] = 0.0f; -// u_values[1] = 0.0f; -// break; -// case TILED_TEXTURE_MAP: -// for (pointIndex = 0; pointIndex < point_cnt; pointIndex++) -// { -// // Increasing V -// base_tex_v[pointIndex] = (float)(pointIndex + chunkIndex) * TextureTileFactor; -// } -// u_values[0] = 0.0f; -// u_values[1] = 1.0f; -// break; -// } - - - /* - ** Fractal noise recursive subdivision: - ** We find the midpoint for each section, apply a random offset, and recurse. We also find - ** the average V coordinate of the endpoints which is the midpoint V (for tiled texture - ** mapping). - */ - - Vector3 xformed_subdiv_pts[MAX_STREAK_POINT_BUFFER_SIZE]; - float subdiv_tex_v[MAX_STREAK_POINT_BUFFER_SIZE]; - unsigned int sub_point_cnt; - - subdivision_util(point_cnt, xformed_pts, base_tex_v, &sub_point_cnt, xformed_subdiv_pts, subdiv_tex_v); - - // Start using subdivided points from now on - Vector3 *points = xformed_subdiv_pts; - float *tex_v = subdiv_tex_v; - point_cnt = sub_point_cnt; - - - /* - ** Calculate line segment edge planes: - */ - - // For each line segment find the two silhouette planes from eyepoint to the line segment - // cylinder. To simplify we do not find the tangent planes but intersect the cylinder with a - // plane passing through its axis and perpendicular to the eye vector, find the edges of the - // resulting rectangle, and create planes through these edges and the eyepoint. - // Note that these planes are represented as a single normal rather than a normal and a - // distance; this is because they pass through the origin (eyepoint) so their distance is - // always zero. - - // Since the line has thickness, each segment has two edges. We name these 'top' and - // 'bottom' - note however that the top/bottom distinction does not relate to screen - // up/down and remains consistent throughout the segmented line. - enum SegmentEdge - { - FIRST_EDGE = 0, // For loop conditions - TOP_EDGE = 0, // Top Edge - BOTTOM_EDGE = 1, // Bottom Edge - MAX_EDGE = 1, // For loop conditions - NUM_EDGES = 2 // For array allocations - }; - - bool switch_edges = false; - - // We have dummy segments for "before the first point" and "after the last point" - in these - // segments the top and bottom edge are the same - they are a perpendicular plane defined by - // the endpoint vertices. This is so we can merge intersections properly for the first and - // last points. - - struct LineSegment - { - Vector3 StartPlane; - Vector3 EdgePlane[NUM_EDGES]; - }; - - // # segments = numpoints + 1 (numpoints - 1, plus two dummy segments) - LineSegment segment[MAX_STREAK_POINT_BUFFER_SIZE + 1]; - - // Intersections. This has data for two edges (top or bottom) intersecting. - struct LineSegmentIntersection - { - unsigned int PointCount; // How many points does this intersection represent - unsigned int NextSegmentID; // ID of segment after this intersection - Vector3 Direction; // Calculated intersection direction line - Vector3 Point; // Averaged 3D point on the line which this represents - float TexV; // Averaged texture V coordinate of points - bool Fold; // Does the line fold over at this intersection? - bool Parallel; // Edges at this intersection are parallel (or almost-) - }; - - // Used to calculate the edge planes - float radius = Width * 0.5f; - - - // The number of intersections is the number of points minus 2. However, we store - // intersection records for the first and last point, even though they are not really - // intersections. The reason we do this is for the intersection merging - the vertices for - // the first and last points can get merged just like any other intersection. Also, we have - // a dummy intersection record before the first point - this is because we want "previous - // segments" for the first point and each intersection only has an index for the next - // segment. - LineSegmentIntersection intersection[MAX_STREAK_POINT_BUFFER_SIZE + 1][NUM_EDGES]; - - - - - for (segmentIndex = 1; segmentIndex < point_cnt; segmentIndex++) - { // #segments = #points - 1 (+ 2 dummy segments) - - radius = widths[segmentIndex]; /// NEW ///// - - Vector3 &curr_point = points[segmentIndex - 1]; - Vector3 &next_point = points[segmentIndex]; - - // We temporarily store the segment direction in the segment's StartPlane (since it is - // used to calculate the StartPlane later). - Vector3 &segdir = segment[segmentIndex].StartPlane; - segdir = next_point - curr_point; - segdir.Normalize(); - - // Find nearest point on infinite line to eye (origin) - Vector3 nearest = curr_point + segdir * -Vector3::Dot_Product(segdir, curr_point); - - // Find top and bottom points on cylinder - Vector3 offset; - Vector3::Cross_Product(segdir, nearest, &offset); - offset.Normalize(); - Vector3 top = curr_point + offset * radius; - Vector3 bottom = curr_point + offset * -radius; - - // Find planes through top/bottom points and eyepoint. In addition to the two points, we - // know that the planes are parallel to the line segment. - Vector3 top_normal; - Vector3::Cross_Product(top, segdir, &top_normal); - top_normal.Normalize(); - segment[segmentIndex].EdgePlane[TOP_EDGE] = top_normal; - - Vector3 bottom_normal; - Vector3::Cross_Product(segdir, bottom, &bottom_normal); - bottom_normal.Normalize(); - segment[segmentIndex].EdgePlane[BOTTOM_EDGE] = bottom_normal; - - // If the visual angle between the previous and current line segments (we use the angle - // between the planes defined by each line segment and the eyepoint) is less than 90 - // degrees, switch the top and bottom edges for the current and subsequent segments and - // mark the intersection as having a fold - if (segmentIndex > 1) - { - - Vector3 prev_plane; - Vector3::Cross_Product(points[segmentIndex - 2], curr_point, &prev_plane); - prev_plane.Normalize(); - - Vector3 curr_plane; - Vector3::Cross_Product(curr_point, next_point, &curr_plane); - curr_plane.Normalize(); - - if (Vector3::Dot_Product(prev_plane, curr_plane) < 0.0f) - { - switch_edges = !switch_edges; - intersection[segmentIndex][TOP_EDGE].Fold = true; - intersection[segmentIndex][BOTTOM_EDGE].Fold = true; - } - else - { - intersection[segmentIndex][TOP_EDGE].Fold = false; - intersection[segmentIndex][BOTTOM_EDGE].Fold = false; - } - } - - if (switch_edges) - { - // We switch signs so the normals will always point inwards - segment[segmentIndex].EdgePlane[TOP_EDGE] = -bottom_normal; - segment[segmentIndex].EdgePlane[BOTTOM_EDGE] = -top_normal; - } - - } - - - - - - // The two dummy segments for the clipping edges of the first and last real segments will be - // defined later, with the first and last intersections. - - - /* - ** Calculate segment edge intersections: - */ - - unsigned int numsegs = point_cnt - 1; // Doesn't include the two dummy segments - unsigned int num_intersections[NUM_EDGES]; - - // These include the 1st, last point "intersections", not the pre-first dummy intersection - num_intersections[TOP_EDGE] = point_cnt; - num_intersections[BOTTOM_EDGE] = point_cnt; - - // Initialize pre-first point dummy intersection record (only NextSegmentID will be used). - intersection[0][TOP_EDGE].PointCount = 0; // Should never be used - intersection[0][TOP_EDGE].NextSegmentID = 0; // Points to first dummy segment - intersection[0][TOP_EDGE].Direction.Set(1,0,0); // Should never be used - intersection[0][TOP_EDGE].Point.Set(0,0,0); // Should never be used - intersection[0][TOP_EDGE].TexV = 0.0f; // Should never be used - intersection[0][TOP_EDGE].Fold = true; // Should never be used - intersection[0][TOP_EDGE].Parallel = false; // Should never be used - intersection[0][BOTTOM_EDGE].PointCount = 0; // Should never be used - intersection[0][BOTTOM_EDGE].NextSegmentID = 0; // Points to first dummy segment - intersection[0][BOTTOM_EDGE].Point.Set(0,0,0); // Should never be used - intersection[0][BOTTOM_EDGE].TexV = 0.0f; // Should never be used - intersection[0][BOTTOM_EDGE].Direction.Set(1,0,0); // Should never be used - intersection[0][BOTTOM_EDGE].Fold = true; // Should never be used - intersection[0][BOTTOM_EDGE].Parallel = false; // Should never be used - - // Initialize first point "intersection" record. - intersection[1][TOP_EDGE].PointCount = 1; - intersection[1][TOP_EDGE].NextSegmentID = 1; - intersection[1][TOP_EDGE].Point = points[0]; - intersection[1][TOP_EDGE].TexV = tex_v[0]; - intersection[1][TOP_EDGE].Fold = true; - intersection[1][TOP_EDGE].Parallel = false; - intersection[1][BOTTOM_EDGE].PointCount = 1; - intersection[1][BOTTOM_EDGE].NextSegmentID = 1; - intersection[1][BOTTOM_EDGE].Point = points[0]; - intersection[1][BOTTOM_EDGE].TexV = tex_v[0]; - intersection[1][BOTTOM_EDGE].Fold = true; - intersection[1][BOTTOM_EDGE].Parallel = false; - - // Find closest point to 1st top/bottom segment edge plane, and convert to direction vector - // and dummy segment edge plane. - - Vector3 top; - Vector3 bottom; - - Vector3 &first_point = points[0]; - Vector3 *first_plane = &(segment[1].EdgePlane[0]); - top = first_point - first_plane[TOP_EDGE] * Vector3::Dot_Product(first_plane[TOP_EDGE], first_point); - top.Normalize(); - intersection[1][TOP_EDGE].Direction = top; - bottom = first_point - first_plane[BOTTOM_EDGE] * Vector3::Dot_Product(first_plane[BOTTOM_EDGE], first_point); - bottom.Normalize(); - intersection[1][BOTTOM_EDGE].Direction = bottom; - - Vector3 segdir = points[1] - points[0]; - segdir.Normalize(); // Is this needed? Probably not - remove later when all works - Vector3 start_pl; - Vector3::Cross_Product(top, bottom, &start_pl); - start_pl.Normalize(); - float dp = Vector3::Dot_Product(segdir, start_pl); - if (dp > 0.0f) - { - segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = start_pl; - } - else - { - segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = -start_pl; - } - - // Initialize StartPlane for the first "real" segment - segment[1].StartPlane = segment[0].StartPlane; - - // Initialize last point "intersection" record. - unsigned int last_isec = num_intersections[TOP_EDGE]; // Same # top, bottom intersections - - intersection[last_isec][TOP_EDGE].PointCount = 1; - intersection[last_isec][TOP_EDGE].NextSegmentID = numsegs + 1; // Last dummy segment - intersection[last_isec][TOP_EDGE].Point = points[point_cnt - 1]; - intersection[last_isec][TOP_EDGE].TexV = tex_v[point_cnt - 1]; - intersection[last_isec][TOP_EDGE].Fold = true; - intersection[last_isec][TOP_EDGE].Parallel = false; - intersection[last_isec][BOTTOM_EDGE].PointCount = 1; - intersection[last_isec][BOTTOM_EDGE].NextSegmentID = numsegs + 1;// Last dummy segment - intersection[last_isec][BOTTOM_EDGE].Point = points[point_cnt - 1]; - intersection[last_isec][BOTTOM_EDGE].TexV = tex_v[point_cnt - 1]; - intersection[last_isec][BOTTOM_EDGE].Fold = true; - intersection[last_isec][BOTTOM_EDGE].Parallel = false; - - // Find closest point to last top/bottom segment edge plane, and convert to direction vector - // and dummy segment edge vector - - Vector3 &last_point = points[point_cnt - 1]; - Vector3 *last_plane = &(segment[numsegs].EdgePlane[0]); - top = last_point - last_plane[TOP_EDGE] * Vector3::Dot_Product(last_plane[TOP_EDGE], last_point); - top.Normalize(); - intersection[last_isec][TOP_EDGE].Direction = top; - bottom = last_point - last_plane[BOTTOM_EDGE] * Vector3::Dot_Product(last_plane[BOTTOM_EDGE], last_point); - bottom.Normalize(); - intersection[last_isec][BOTTOM_EDGE].Direction = bottom; - - segdir = points[point_cnt - 1] - points[point_cnt - 2]; - segdir.Normalize(); // Is this needed? Probably not - remove later when all works - Vector3::Cross_Product(top, bottom, &start_pl); - start_pl.Normalize(); - dp = Vector3::Dot_Product(segdir, start_pl); - if (dp > 0.0f) - { - segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] = - segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = start_pl; - } - else - { - segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] = - segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = -start_pl; - } - - // Calculate midpoint segment intersections. There are 2 segment intersections for each - // point: top and bottom (due to the fact that the segments have width, so they have a top - // edge and a bottom edge). Note that the top/bottom distinction does not relate to screen - // up/down. Since each segment edge is represented by a plane passing through the origin - // (eyepoint), the intersection of two such is a line passing through the origin, which is - // represented as a normalized direction vector. - // We use both segment intersections to define the startplane for the segment which begins - // at that intersection. - - float vdp; - - for (intersectionIndex = 2; intersectionIndex < num_intersections[TOP_EDGE]; intersectionIndex++) - { - - // Relevant midpoint: - Vector3 &midpoint = points[intersectionIndex - 1]; - float mid_tex_v = tex_v[intersectionIndex - 1]; - - // Initialize misc. fields - intersection[intersectionIndex][TOP_EDGE].PointCount = 1; - intersection[intersectionIndex][TOP_EDGE].NextSegmentID = intersectionIndex; - intersection[intersectionIndex][TOP_EDGE].Point = midpoint; - -// intersection[intersectionIndex][TOP_EDGE].TexV = mid_tex_v; - intersection[intersectionIndex][TOP_EDGE].TexV = personalities[intersectionIndex]&1;//LORENZEN LORENZEN - - intersection[intersectionIndex][BOTTOM_EDGE].PointCount = 1; - intersection[intersectionIndex][BOTTOM_EDGE].NextSegmentID = intersectionIndex; - intersection[intersectionIndex][BOTTOM_EDGE].Point = midpoint; - -// intersection[intersectionIndex][BOTTOM_EDGE].TexV = mid_tex_v; - intersection[intersectionIndex][BOTTOM_EDGE].TexV = personalities[intersectionIndex]&1;//LORENZEN LORENZEN - - // Intersection calculation: if the top/bottom planes of both adjoining segments are not - // very close to being parallel, intersect them to get top/bottom intersection lines. If - // the planes are almost parallel, pick one, find the point on the plane closest to the - // midpoint, and convert that point to a line direction vector. - - // Top: - vdp = Vector3::Dot_Product(segment[intersectionIndex - 1].EdgePlane[TOP_EDGE], segment[intersectionIndex].EdgePlane[TOP_EDGE]); - if (fabs(vdp) < parallel_factor) - { - - // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is - // pointing towards the midpoint) - Vector3::Cross_Product(segment[intersectionIndex - 1].EdgePlane[TOP_EDGE], segment[intersectionIndex].EdgePlane[TOP_EDGE], - &(intersection[intersectionIndex][TOP_EDGE].Direction)); - intersection[intersectionIndex][TOP_EDGE].Direction.Normalize(); - if (Vector3::Dot_Product(intersection[intersectionIndex][TOP_EDGE].Direction, midpoint) < 0.0f) - { - intersection[intersectionIndex][TOP_EDGE].Direction = -intersection[intersectionIndex][TOP_EDGE].Direction; - } - - intersection[intersectionIndex][TOP_EDGE].Parallel = false; - - } - else - { - - // Parallel (or almost): find point on av. plane closest to midpoint, convert to line - - // Ensure average calculation is numerically stable: - Vector3 pl; - if (vdp > 0.0f) - { - pl = segment[intersectionIndex - 1].EdgePlane[TOP_EDGE] + segment[intersectionIndex].EdgePlane[TOP_EDGE]; - } - else - { - pl = segment[intersectionIndex - 1].EdgePlane[TOP_EDGE] - segment[intersectionIndex].EdgePlane[TOP_EDGE]; - } - pl.Normalize(); - - intersection[intersectionIndex][TOP_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint); - intersection[intersectionIndex][TOP_EDGE].Direction.Normalize(); - - intersection[intersectionIndex][TOP_EDGE].Parallel = true; - } - - // Bottom: - vdp = Vector3::Dot_Product(segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE], segment[intersectionIndex].EdgePlane[BOTTOM_EDGE]); - if (fabs(vdp) < parallel_factor) - { - - // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is - // pointing towards the midpoint) - Vector3::Cross_Product(segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE], segment[intersectionIndex].EdgePlane[BOTTOM_EDGE], - &(intersection[intersectionIndex][BOTTOM_EDGE].Direction)); - intersection[intersectionIndex][BOTTOM_EDGE].Direction.Normalize(); - if (Vector3::Dot_Product(intersection[intersectionIndex][BOTTOM_EDGE].Direction, midpoint) < 0.0f) - { - intersection[intersectionIndex][BOTTOM_EDGE].Direction = -intersection[intersectionIndex][BOTTOM_EDGE].Direction; - } - - intersection[intersectionIndex][BOTTOM_EDGE].Parallel = false; - - } - else - { - - // Parallel (or almost): find point on av. plane closest to midpoint, convert to line - - // Ensure average calculation is numerically stable: - Vector3 pl; - if (vdp > 0.0f) - { - pl = segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE] + segment[intersectionIndex].EdgePlane[BOTTOM_EDGE]; - } - else - { - pl = segment[intersectionIndex - 1].EdgePlane[BOTTOM_EDGE] - segment[intersectionIndex].EdgePlane[BOTTOM_EDGE]; - } - pl.Normalize(); - - intersection[intersectionIndex][BOTTOM_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint); - intersection[intersectionIndex][BOTTOM_EDGE].Direction.Normalize(); - - intersection[intersectionIndex][BOTTOM_EDGE].Parallel = true; - } - - // Find StartPlane: - Vector3::Cross_Product(intersection[intersectionIndex][TOP_EDGE].Direction, intersection[intersectionIndex][BOTTOM_EDGE].Direction, &start_pl); - start_pl.Normalize(); - dp = Vector3::Dot_Product(segment[intersectionIndex].StartPlane, start_pl); - if (dp > 0.0f) - { - segment[intersectionIndex].StartPlane = start_pl; - } - else - { - segment[intersectionIndex].StartPlane = -start_pl; - } - - } // for intersectionIndex - - - /* - ** Intersection merging: when an intersection is inside an adjacent segment and certain - ** other conditions hold true, we need to merge intersections to avoid visual glitches - ** caused by the polys folding over on themselves. - */ - - if (Is_Merge_Intersections()) - { - - // Since we are merging the intersections in-place, we have two index variables, a "read - // index" and a "write index". - unsigned int intersectionIndex_r; - unsigned int intersectionIndex_w; - - // The merges will be repeated in multiple passes until none are performed. The reason - // for this is that one merge may cause the need for another merge elsewhere. - bool merged = true; - - while (merged) - { - - merged = false; - - SegmentEdge edge; - for (edge = FIRST_EDGE; edge <= MAX_EDGE; edge = (SegmentEdge)((int)edge + 1)) - { - // Merge top and bottom edge intersections: loop through the intersections from the - // first intersection to the penultimate intersection, for each intersection check - // if it needs to be merged with the next one (which is why the loop doesn't go all - // the way to the last intersection). We start at 1 because 0 is the dummy - // "pre-first-point" intersection. - unsigned int num_isects = num_intersections[edge]; // Capture here because will change inside loop - for (intersectionIndex_r = 1, intersectionIndex_w = 1; intersectionIndex_r < num_isects; intersectionIndex_r++, intersectionIndex_w++) { - - // Check for either of two possible reasons to merge this intersection with the - // next: either the segment on the far side of the next intersection overlaps - // this intersection, or the previous segment overlaps the next intersection. - // Note that some other conditions need to be true as well. - - // Note: intersectionIndex_r is used for anything at or after the current position, intersectionIndex_w is - // used for anything before the current position (previous positions have - // potentially already been merged). - // Note: intersectionIndex_r is used for anything at or after the current position, intersectionIndex_w is - // used for anything before the current position (previous positions have - // potentially already been merged). - LineSegmentIntersection *curr_int = &(intersection[intersectionIndex_r][edge]); - LineSegmentIntersection *next_int = &(intersection[intersectionIndex_r + 1][edge]); - LineSegmentIntersection *write_int = &(intersection[intersectionIndex_w][edge]); - LineSegmentIntersection *prev_int = &(intersection[intersectionIndex_w - 1][edge]); - LineSegment *next_seg = &(segment[next_int->NextSegmentID]); - LineSegment *curr_seg = &(segment[curr_int->NextSegmentID]); - LineSegment *prev_seg = &(segment[prev_int->NextSegmentID]); - - // If this intersection is inside both the start plane and the segment edge - // plane of the segment after the next intersection, merge this edge - // intersection and the next. We repeat merging until no longer needed. - // NOTE - we do not merge across a fold. - while ( (!next_int->Fold && - (Vector3::Dot_Product(curr_int->Direction, next_seg->StartPlane) > 0.0f) && - (Vector3::Dot_Product(curr_int->Direction, next_seg->EdgePlane[edge]) > 0.0f )) || - (!curr_int->Fold && - (Vector3::Dot_Product(next_int->Direction, -curr_seg->StartPlane) > 0.0f) && - (Vector3::Dot_Product(next_int->Direction, prev_seg->EdgePlane[edge]) > 0.0f )) ) - { - - // First calculate location of merged intersection - this is so we can abort - // the merge if it yields funky results. - - // Find mean point (weighted so all points have same weighting) - unsigned int new_count = curr_int->PointCount + next_int->PointCount; - float oo_new_count = 1.0f / (float)new_count; - float curr_factor = oo_new_count * (float)curr_int->PointCount; - float next_factor = oo_new_count * (float)curr_int->PointCount; - Vector3 new_point = curr_int->Point * curr_factor + next_int->Point * next_factor; - float new_tex_v = curr_int->TexV * curr_factor + next_int->TexV * next_factor; - - // Calculate new intersection direction by intersecting prev_seg with next_seg - bool new_parallel; - Vector3 new_direction; - vdp = Vector3::Dot_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge]); - if (fabs(vdp) < parallel_factor) - { - - // Not parallel - intersect planes to get line (get vector, normalize it, - // ensure it is pointing towards the current point) - Vector3::Cross_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge], &new_direction); - new_direction.Normalize(); - if (Vector3::Dot_Product(new_direction, new_point) < 0.0f) - { - new_direction = -new_direction; - } - - new_parallel = false; - - } - else - { - - // Parallel (or almost). If the current intersection is not parallel, take - // the average plane and intersect it with the skipped plane. If the - // current intersection is parallel, find the average plane, and find the - // direction vector on it closest to the current intersections direction - // vector. - - // Ensure average calculation is numerically stable: - Vector3 pl; - if (vdp > 0.0f) - { - pl = prev_seg->EdgePlane[edge] + next_seg->EdgePlane[edge]; - } - else - { - pl = prev_seg->EdgePlane[edge] - next_seg->EdgePlane[edge]; - } - pl.Normalize(); - - if (curr_int->Parallel) - { - new_direction = new_direction - pl * Vector3::Dot_Product(pl, new_direction); - new_direction.Normalize(); - } - else - { - Vector3::Cross_Product(curr_seg->EdgePlane[edge], pl, &new_direction); - new_direction.Normalize(); - } - - new_parallel = true; - } - - // Now check to see if the merge caused any funky results - if so abort it. - // Currently we check to see if the distance of the direction from the two - // points is larger than the radius times the merge_abort factor. - if (MergeAbortFactor > 0.0f) - { - float abort_dist = radius * MergeAbortFactor; - float abort_dist2 = abort_dist * abort_dist; - Vector3 diff_curr = curr_int->Point - - new_direction * Vector3::Dot_Product(curr_int->Point, new_direction); - if (diff_curr.Length2() > abort_dist2) break; - Vector3 next_curr = next_int->Point - - new_direction * Vector3::Dot_Product(next_int->Point, new_direction); - if (next_curr.Length2() > abort_dist2) break; - } - - // Merge edge intersections (curr_int and next_int) into curr_int - merged = true; - - curr_int->Direction = new_direction; - curr_int->Parallel = new_parallel; - curr_int->Point = new_point; - curr_int->TexV = new_tex_v; - curr_int->PointCount = new_count; - curr_int->NextSegmentID = next_int->NextSegmentID; - curr_int->Fold = curr_int->Fold || next_int->Fold; - - // Decrement number of edge intersections - num_intersections[edge]--; - - // Advance intersectionIndex_r to shift subsequent entries backwards in result. - intersectionIndex_r++; - - // If we are at the end then break: - if (intersectionIndex_r == num_isects) - { - break; - } - - // Advance next_int and next_seg. - next_int = &(intersection[intersectionIndex_r + 1][edge]); - next_seg = &(segment[next_int->NextSegmentID]); - - } // while - - // Copy from "read index" to "write index" - write_int->PointCount = curr_int->PointCount; - write_int->NextSegmentID = curr_int->NextSegmentID; - write_int->Point = curr_int->Point; - write_int->TexV = curr_int->TexV; - write_int->Direction = curr_int->Direction; - write_int->Fold = curr_int->Fold; - - } // for intersectionIndex - - // If intersectionIndex_r is exactly equal to num_isects (rather than being larger by one) at this - // point, this means that the last intersection was not merged with the previous one. In - // this case, we need to do one last copy: - if (intersectionIndex_r == num_isects) - { - LineSegmentIntersection *write_int = &(intersection[intersectionIndex_w][edge]); - LineSegmentIntersection *curr_int = &(intersection[intersectionIndex_r][edge]); - write_int->PointCount = curr_int->PointCount; - write_int->NextSegmentID = curr_int->NextSegmentID; - write_int->Point = curr_int->Point; - write_int->TexV = curr_int->TexV; - write_int->Direction = curr_int->Direction; - write_int->Fold = curr_int->Fold; - } - -#ifdef ENABLE_WWDEBUGGING - // Testing code - ensure total PointCount fits the number of points - unsigned int total_cnt = 0; - for (unsigned int nidx = 0; nidx <= num_intersections[edge]; nidx++) - { - total_cnt += intersection[nidx][edge].PointCount; - } - assert(total_cnt == point_cnt); -#endif - - } // for edge - } // while (merged) - } // if (Is_Merge_Intersections()) - - /* - ** Find vertex positions, generate vertices and triangles: - ** Since we can have top/bottom intersections merged, we need to skip points if both the top - ** and bottom intersections are merged, generate triangle fans if one of the sides is merged - ** and the other isnt, and generate triangle strips otherwise. - */ - - // Configure vertex array and setup renderer. - unsigned int vnum = num_intersections[TOP_EDGE] + num_intersections[BOTTOM_EDGE]; - VertexFormatXYZDUV1 *vertexArray=W3DNEWARRAY VertexFormatXYZDUV1[vnum]; - Vector3i v_index_array[MAX_STREAK_POLY_BUFFER_SIZE]; - - // Vertex and triangle indices - unsigned int vertexIndex = 0; - unsigned int triangleIndex = 0; - - - - - - - - - - - - - -char p[]=" && && && && && && && && && && && && && && && && && && && && && && && "; -char f[]=" && && && && && && && && && && && && && && && && && && && && && && && "; -char e[]="&& && && && && && && && && && && && && && && && && && && && && && && "; - -// GENERALIZE FOR WHEN NO TEXTURE (DO NOT SET UV IN THESE CASES? NEED TO GENERALIZE FOR DIFFERENT TEXTURING MODES ANYWAY). - - // "Prime the pump" with two vertices (pick nearest point on each direction line): - Vector3 &top_dir = intersection[1][TOP_EDGE].Direction; - top = top_dir * Vector3::Dot_Product(points[0], top_dir); - Vector3 &bottom_dir = intersection[1][BOTTOM_EDGE].Direction; - bottom = bottom_dir * Vector3::Dot_Product(points[0], bottom_dir); - vertexArray[vertexIndex].x = top.X; - vertexArray[vertexIndex].y = top.Y; - vertexArray[vertexIndex].z = top.Z; - vertexArray[vertexIndex].u1 = u_values[0] ; - vertexArray[vertexIndex].v1 = intersection[1][TOP_EDGE].TexV ; - vertexIndex++; - vertexArray[vertexIndex].x = bottom.X; - vertexArray[vertexIndex].y = bottom.Y; - vertexArray[vertexIndex].z = bottom.Z; - vertexArray[vertexIndex].u1 = u_values[1] ; - vertexArray[vertexIndex].v1 = intersection[1][BOTTOM_EDGE].TexV ; - vertexIndex++; - - unsigned int last_top_vertexIndex = 0; - unsigned int last_bottom_vertexIndex = 1; - - // Loop over intersections, create new vertices and triangles. - unsigned int top_int_idx = 1; // Skip "pre-first-point" dummy intersection - unsigned int bottom_int_idx = 1; // Skip "pre-first-point" dummy intersection - pointIndex = 0; - unsigned int residual_top_points = intersection[1][TOP_EDGE].PointCount; - unsigned int residual_bottom_points = intersection[1][BOTTOM_EDGE].PointCount; - - // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points) - unsigned int delta = MIN(residual_top_points, residual_bottom_points) - 1; - residual_top_points -= delta; - residual_bottom_points -= delta; - pointIndex += delta; - - for (; ; ) - { - - if (residual_top_points == 1 && residual_bottom_points == 1) - { - // Advance both intersections, creating a tristrip segment - v_index_array[triangleIndex].I = last_top_vertexIndex; - v_index_array[triangleIndex].J = last_bottom_vertexIndex; - v_index_array[triangleIndex].K = vertexIndex; - triangleIndex++; - v_index_array[triangleIndex].I = last_bottom_vertexIndex; - v_index_array[triangleIndex].J = vertexIndex + 1; - v_index_array[triangleIndex].K = vertexIndex; - triangleIndex++; - last_top_vertexIndex = vertexIndex; - last_bottom_vertexIndex = vertexIndex + 1; - - // Advance both intersections. - top_int_idx++; - bottom_int_idx++; - residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount; - residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount; - - // Advance point index (must do here because the new point index is used below): - pointIndex++; - - // Generate two vertices for next point by picking nearest point on each direction line - Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction; - top = top_dir * Vector3::Dot_Product(points[pointIndex], top_dir); - Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction; - bottom = bottom_dir * Vector3::Dot_Product(points[pointIndex], bottom_dir); - - vertexArray[vertexIndex].x = top.X; - vertexArray[vertexIndex].y = top.Y; - vertexArray[vertexIndex].z = top.Z; - vertexArray[vertexIndex].u1 = u_values[0] ; - vertexArray[vertexIndex].v1 = intersection[top_int_idx][TOP_EDGE].TexV ; - vertexIndex++; - vertexArray[vertexIndex].x = bottom.X; - vertexArray[vertexIndex].y = bottom.Y; - vertexArray[vertexIndex].z = bottom.Z; - vertexArray[vertexIndex].u1 = u_values[1] ; - vertexArray[vertexIndex].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV ; - vertexIndex++; - } - else - { - // Exactly one of the pointcounts is greater than one - advance it and draw one triangle - if (residual_top_points > 1) - { - // Draw one triangle (fan segment) - v_index_array[triangleIndex].I = last_top_vertexIndex; - v_index_array[triangleIndex].J = last_bottom_vertexIndex; - v_index_array[triangleIndex].K = vertexIndex; - triangleIndex++; - last_bottom_vertexIndex = vertexIndex; - - // Advance bottom intersection only - residual_top_points--; - bottom_int_idx++; - residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount; - - // Advance point index (must do here because the new point index is used below): - pointIndex++; - - // Generate bottom vertex by picking nearest point on bottom direction line - Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction; - bottom = bottom_dir * Vector3::Dot_Product(points[pointIndex], bottom_dir); - - vertexArray[vertexIndex].x = bottom.X; - vertexArray[vertexIndex].y = bottom.Y; - vertexArray[vertexIndex].z = bottom.Z; - vertexArray[vertexIndex].u1 = u_values[1] ; - vertexArray[vertexIndex].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV ; - vertexIndex++; - } - else - { - - // residual_bottom_points > 1 - - // Draw one triangle (fan segment) - v_index_array[triangleIndex].I = last_top_vertexIndex; - v_index_array[triangleIndex].J = last_bottom_vertexIndex; - v_index_array[triangleIndex].K = vertexIndex; - triangleIndex++; - last_top_vertexIndex = vertexIndex; - - // Advance top intersection only - residual_bottom_points--; - top_int_idx++; - residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount; - - // Advance point index (must do here because the new point index is used below): - pointIndex++; - - // Generate top vertex by picking nearest point on top direction line - Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction; - top = top_dir * Vector3::Dot_Product(points[pointIndex], top_dir); - vertexArray[vertexIndex].x = top.X; - vertexArray[vertexIndex].y = top.Y; - vertexArray[vertexIndex].z = top.Z; - vertexArray[vertexIndex].u1 = u_values[0] ; - vertexArray[vertexIndex].v1 = intersection[top_int_idx][TOP_EDGE].TexV ; - vertexIndex++; - } - } - - // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points) - delta = MIN(residual_top_points, residual_bottom_points) - 1; - residual_top_points -= delta; - residual_bottom_points -= delta; - pointIndex += delta; - // Exit conditions - if ( (top_int_idx >= num_intersections[TOP_EDGE] && residual_top_points == 1) || - (bottom_int_idx >= num_intersections[BOTTOM_EDGE] && residual_bottom_points == 1)) - { - // Debugging check - if either intersection index is before end, both of them should be - // and the points should be before the end. - assert(top_int_idx == num_intersections[TOP_EDGE]); - assert(bottom_int_idx == num_intersections[BOTTOM_EDGE]); - assert(pointIndex == point_cnt - 1); - break; - } - } -char d[]=" && && && && && && && && && && && && && && && && && && && && && && && "; -char w[]=" && && && && && && && && && && && && && && && && && && && && && && && "; -char q[]="&& && && && && && && && && && && && && && && && && && && && && && && "; - - - - - /* - ** Set color, opacity, vertex flags: - */ - - // If color is not white or opacity not 100%, enable gradient in shader and in renderer - otherwise disable. - //unsigned int rgba; - //rgba=DX8Wrapper::Convert_Color(Color,Opacity); - //bool rgba_all=(rgba==0xFFFFFFFF); - -// int colorIndex = 0; -// for (vertexIndex = 0; vertexIndex < vnum; vertexIndex++) -// { -// //vertexArray[vertexIndex].diffuse = rgba;/// OLD WAY COLORS THEM ALL TO THE COLOR,OPACITY MEMBERS ///////////////// -// unsigned int perPointARGB; -// colorIndex = MIN(vertexIndex / 2, point_cnt); -// perPointARGB = DX8Wrapper::Convert_Color( colors[colorIndex] );// twice as many verts as points? or so? -// vertexArray[vertexIndex].diffuse = perPointARGB; -// vertexArray[vertexIndex].u1 = (float)((vertexIndex&2) == 2); -// vertexArray[vertexIndex].v1 = (float)((vertexIndex&1) == 1); -// } - - - - // Enable sorting if sorting has not been disabled and line is translucent and alpha testing is not enabled. - bool sorting = (!Is_Sorting_Disabled()) && (Shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO && Shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE); - /////////////////////////////////////////////////////////////////////////////////////// - ShaderClass shader = Shader; - shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE); - shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE); - - VertexMaterialClass *mat; - mat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE); - DX8Wrapper::Set_Material(mat); - REF_PTR_RELEASE(mat); - - // If Texture is non-NULL enable texturing in shader - otherwise disable. - if (Texture) - { - shader.Set_Texturing(ShaderClass::TEXTURING_ENABLE); - } - else - { - shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE); - } - /////////////////////////////////////////////////////////////////////////////////////////// - - - /* - ** Render - */ - - DynamicVBAccessClass Verts((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),dynamic_fvf_type,vnum); - // Copy in the data to the VB - { - DynamicVBAccessClass::WriteLockClass Lock(&Verts); - unsigned int i; - unsigned char *vb=(unsigned char*)Lock.Get_Formatted_Vertex_Array(); - const FVFInfoClass& fvfinfo=Verts.FVF_Info(); - int segIdx = 0; - unsigned int argb = 0x00000000; - - unsigned int oddEven = 0; - - //oddEven = ( personalities[0] & 1 ); - - for (i=0; iX = vertexArray[i].x; - ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->Y = vertexArray[i].y; - ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->Z = vertexArray[i].z; - *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset()) = vertexArray[i].diffuse; - - *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset()) = argb; - - - - // ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->V = (float)( ((i+oddEven)&1) == 1 );//mirror tiling - // ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->U = (float)( ((i+oddEven)&2) == 2 );//mirror tiling - ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->V = vertexArray[i].v1; - ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->U = vertexArray[i].u1; - - - - vb+=fvfinfo.Get_FVF_Size(); - } - } // copy - - DynamicIBAccessClass ib_access((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),triangleIndex*3); - { - unsigned int i; - DynamicIBAccessClass::WriteLockClass lock(&ib_access); - unsigned short* inds=lock.Get_Index_Array(); - - for (i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/Streakrender.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 6/08/01 5:23p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef STREAKRENDER_H -#define STREAKRENDER_H - -#include "always.h" -#include "shader.h" -#include "texture.h" -#include "matrix3d.h" -#include "vector2.h" - -class RenderInfoClass; -class SphereClass; -struct W3dEmitterLinePropertiesStruct; - - -// The maximum allowable level of subdivision. This should be no more than 7 to avoid increasing -// the chunk buffer size too much -#define MAX_STREAK_SUBDIV_LEVELS 7 - - - -/** -** StreakRendererClass -** This class implements the low-level line rendering functionality used by both SegmentedLineClass -** and ParticleBufferClass -*/ -class StreakRendererClass -{ -public: - - StreakRendererClass(void); - StreakRendererClass(const StreakRendererClass & that); - StreakRendererClass & operator = (const StreakRendererClass & that); - ~StreakRendererClass(void); - - enum TextureMapMode { - UNIFORM_WIDTH_TEXTURE_MAP = 0x00000000, // Entire line uses one row of texture (constant V) - UNIFORM_LENGTH_TEXTURE_MAP = 0x00000001, // Entire line uses one row of texture stretched length-wise - TILED_TEXTURE_MAP = 0x00000002 // Tiled continuously over line - }; - - void Init(const W3dEmitterLinePropertiesStruct & props); - - // Get properties used to render this line segment - TextureClass * Get_Texture(void) const; - TextureClass * Peek_Texture(void) const { return Texture; } - ShaderClass Get_Shader(void) const { return Shader; } - float Get_Width(void) const { return Width; } - const Vector3 & Get_Color(void) const { return Color; } - float Get_Opacity(void) const { return Opacity; } - float Get_Noise_Amplitude(void) const { return NoiseAmplitude; } - float Get_Merge_Abort_Factor(void) const { return MergeAbortFactor; } - unsigned int Get_Current_Subdivision_Level(void) const { return SubdivisionLevel; } - TextureMapMode Get_Texture_Mapping_Mode(void) const; - float Get_Texture_Tile_Factor(void) const { return TextureTileFactor; } - Vector2 Get_UV_Offset_Rate(void) const; - int Is_Merge_Intersections(void) const { return Bits & MERGE_INTERSECTIONS; } - int Is_Freeze_Random(void) const { return Bits & FREEZE_RANDOM; } - int Is_Sorting_Disabled(void) const { return Bits & DISABLE_SORTING; } - int Are_End_Caps_Enabled(void) const { return Bits & END_CAPS; } - - // Set properties used to render this line segment - void Set_Texture(TextureClass *texture); - void Set_Shader(ShaderClass shader) { Shader = shader; } - void Set_Width(float width) { Width = width; } - void Set_Color(const Vector3 &color) { Color = color; } - void Set_Opacity(float opacity) { Opacity = opacity; } - void Set_Noise_Amplitude(float amplitude) { NoiseAmplitude = amplitude; } - void Set_Merge_Abort_Factor(float factor) { MergeAbortFactor = factor; } - void Set_Current_Subdivision_Level(unsigned int lv) { SubdivisionLevel = lv; } - void Set_Texture_Mapping_Mode(TextureMapMode mode); - // WARNING! Do NOT set the tile factor to be too high (should be less than 8) or negative - //performance impact will result! - void Set_Texture_Tile_Factor(float factor); - void Set_Current_UV_Offset(const Vector2 & offset); - void Set_UV_Offset_Rate(const Vector2 &rate); - void Set_Merge_Intersections(int onoff) { if (onoff) { Bits |= MERGE_INTERSECTIONS; } else { Bits &= ~MERGE_INTERSECTIONS; }; } - void Set_Freeze_Random(int onoff) { if (onoff) { Bits |= FREEZE_RANDOM; } else { Bits &= ~FREEZE_RANDOM; }; } - void Set_Disable_Sorting(int onoff) { if (onoff) { Bits |= DISABLE_SORTING; } else { Bits &= ~DISABLE_SORTING; }; } - void Set_End_Caps(int onoff) { if (onoff) { Bits |= END_CAPS; } else { Bits &= ~END_CAPS; }; } - - void Reset_Line(void); - - - void Render( RenderInfoClass & rinfo, - const Matrix3D & transform, - unsigned int point_count, - Vector3 * points, - const SphereClass & obj_sphere); - - void RenderStreak( RenderInfoClass & rinfo, - const Matrix3D & transform, - unsigned int point_count, - Vector3 * points, - Vector4 * colors, - float * widths, - const SphereClass & obj_sphere, - unsigned int *personalities); - -private: - - // Utility functions - void subdivision_util(unsigned int point_cnt, const Vector3 *xformed_pts, - const float *base_tex_v, unsigned int *p_sub_point_cnt, - Vector3 *xformed_subdiv_pts, float *subdiv_tex_v); - - // Global properties - TextureClass * Texture; - ShaderClass Shader; - float Width; - Vector3 Color; - float Opacity; - - // Subdivision properties - unsigned int SubdivisionLevel; - float NoiseAmplitude; - - // If >0, will abort a merge which causes an intersection to move - // farther away than this factor * line radius from the line point. - // (defaults to 1.5, has no affect if intersection merging is disabled). - float MergeAbortFactor; - - // Affects tiled texture mapping mode only. If this is set too high, performance (and - // possibly visual) problems will result from excessive tiling over a single polygon, over - // the entire line, or both. - float TextureTileFactor; - - // Used for texture coordinate animation - unsigned int LastUsedSyncTime; // Last sync time used - Vector2 CurrentUVOffset; // Current UV offset - Vector2 UVOffsetDeltaPerMS; // Amount to increase offset each millisec - - // Various flags - enum BitShiftOffsets { - TEXTURE_MAP_MODE_OFFSET = 24 // By how many bits do I need to shift the texture mapping mode? - }; - enum { - MERGE_INTERSECTIONS = 0x00000001, // Merge intersections - FREEZE_RANDOM = 0x00000002, // Freeze random (note: offsets are in camera space) - DISABLE_SORTING = 0x00000004, // Disable sorting (even if shader has alpha-blending) - END_CAPS = 0x00000008, // Draw end caps on the line - - // Some bits are used to select the texture mapping mode: - TEXTURE_MAP_MODE_MASK = 0xFF000000, // Must cover all possible TextureMapMode values - - DEFAULT_BITS = MERGE_INTERSECTIONS | (UNIFORM_WIDTH_TEXTURE_MAP << TEXTURE_MAP_MODE_OFFSET) - }; - unsigned int Bits; - - friend class SegmentedLineClass; -}; - - - -inline StreakRendererClass::TextureMapMode StreakRendererClass::Get_Texture_Mapping_Mode(void) const -{ - return (TextureMapMode)((Bits & TEXTURE_MAP_MODE_MASK) >> TEXTURE_MAP_MODE_OFFSET); -} - -inline void StreakRendererClass::Set_Texture_Mapping_Mode(StreakRendererClass::TextureMapMode mode) -{ - Bits &= ~TEXTURE_MAP_MODE_MASK; - Bits |= ((mode << TEXTURE_MAP_MODE_OFFSET) & TEXTURE_MAP_MODE_MASK); -} - -inline Vector2 StreakRendererClass::Get_UV_Offset_Rate(void) const -{ - return UVOffsetDeltaPerMS * 1000.0f; -} - -inline void StreakRendererClass::Set_UV_Offset_Rate(const Vector2 &rate) -{ - UVOffsetDeltaPerMS = rate * 0.001f; -} - - -#endif //STREAKRENDER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp deleted file mode 100644 index 18b740a057..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.cpp +++ /dev/null @@ -1,1019 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "stripoptimizer.h" -#include "hashtemplate.h" -#include "wwdebug.h" - -template inline void swap (T& a, T& b) -{ - T t(a); - a = b; - b = t; -} - -//------------------------------------------------------------------------ -// Prototypes for sort functions. Note that class T must have -// operators =, > and < in order for the functions to compile. -//------------------------------------------------------------------------ - -template inline void Insertion_Sort (T* a, int N); -template inline void Quick_Sort (T* a, int N); - -template inline void Insertion_Sort (T* a, int N) -{ - for (int i = 1; i < N; i++) - if (a[i-1] > a[i]) - { - T v = a[i]; - int j = i; - while (a[j-1]> v) - { - a[j] = a[j-1]; // copy data - j--; - if (!j) - break; - }; - a[j] = v; - } -} - - -template inline void Quick_Sort (T* a, int l, int r) -{ - if (r-l <= 16) - { - Insertion_Sort(a+l,r-l+1); - return; - } - T v = a[r]; - int i = l-1; - int j = r; - do - { - do { i++; } while (i < r && a[i] < v); - do { j--; } while (j > 0 && a[j] > v); - swap(a[i],a[j]); - } while (j > i); - - T t = a[j]; - a[j] = a[i]; - a[i] = a[r]; - a[r] = t; - if ((i-1) > l) - Quick_Sort (a,l,i-1); - if (r > (i+1)) - Quick_Sort (a,i+1,r); -} - -template inline void Quick_Sort (T* a, int N) -{ - Quick_Sort(a,0,N-1); -} - -//------------------------------------------------------------------------ -// Implementation -//------------------------------------------------------------------------ - -/***************************************************************************** - * - * Function: StripOptimizerClass::getStripIndexCount() - * - * Description: Returns number of indices in a set of strips - * - * Parameters: - * - *****************************************************************************/ - -int StripOptimizerClass::Get_Strip_Index_Count (const int* strips, int strip_count) -{ - int cnt = 0; - for (int i = 0; i < strip_count; i++) - { - int len = *strips++; // read len - cnt += len; - strips += len; // skip data - } - return cnt; -} - -/***************************************************************************** - * - * Function: StripOptimizerClass::optimizeStripOrder() - * - * Description: - * - * Parameters: - * - *****************************************************************************/ - -// compares two strips and returns number of shared indices -static inline int Get_Strip_Similarity (const int* A, const int* B) -{ - int cnt = 0; - int lenA = *A++; - int lenB = *B++; - - for (int i = 0; i < lenA; i++) - { - int index = A[i]; // index of A - for (int j = 0; j < lenB; j++) - if (B[j] == index) // match - { - cnt++; - break; - } - } - - return cnt; -} - -// copies a strip, returns new destination pointer -static inline int* Copy_Strip (int* d, const int* s) -{ - int len = *s++; - *d++ = len; - for (int i = 0; i < len; i++) - *d++ = *s++; - return d; -} - -void StripOptimizerClass::Optimize_Strip_Order (int* strips, int strip_count) -{ - if (strip_count <= 0) - return; -// WWASSERT(strips); - - int** ss = W3DNEWARRAY int*[strip_count]; // pointers to beginning of strips - int* s = strips; - int i = 0; - for (; i < strip_count; i++) - { - ss[i] = s; - int len = *s++; // read len - s+=len; // skip - } - int outSize = Get_Strip_Index_Count(strips, strip_count)+strip_count; // output memory alloc size - int* out = W3DNEWARRAY int[outSize]; - int* o = out; // output pointer - - const int* prev = ss[0]; // previous strip - o = Copy_Strip (o, ss[0]); // output first strip - ss[0] = 0; - - for (;;) - { - int bestIndex = -1; - int bestSimilarity = -1; - - for (int j = 0; j < strip_count; j++) - if (ss[j]) - { - int sim = Get_Strip_Similarity (prev, ss[j]); // get similarity - if (sim > bestSimilarity) - { - bestSimilarity = sim; - bestIndex = j; - } - } - - if (bestIndex==-1) // we're done - break; - - o = Copy_Strip(o, ss[bestIndex]); // copy the strip - prev = ss[bestIndex]; // set to prev - ss[bestIndex] = NULL; // mark as selected - } - -// WWASSERT((out+outSize)==o); // HUH? - - for (i = 0; i < outSize; i++) // copy output - strips[i] = out[i]; - - delete[] out; - delete[] ss; -} - -/***************************************************************************** - * - * Function: StripOptimizerClass::optimizeTriangleOrder() - * - * Description: - * - * Parameters: - * - *****************************************************************************/ - -struct Tri -{ -public: - int a,b,c; - - bool operator< (const Tri& s) const { return a < s.a; } - bool operator> (const Tri& s) const { return a > s.a; } -}; - -static inline int Get_Similarity (const Tri& A, const Tri& B) -{ - int sim = 0; - - if (A.a == B.a || A.a == B.b || A.a == B.c) sim++; - if (A.b == B.a || A.b == B.b || A.b == B.c) sim++; - if (A.c == B.a || A.c == B.b || A.c == B.c) sim++; - - return sim; -} - -void StripOptimizerClass::Optimize_Triangle_Order (int *tris, int triangle_count) -{ - if (triangle_count<=0) - return; - WWASSERT(tris); - - Tri** t = W3DNEWARRAY Tri*[triangle_count]; - int i = 0; - for (; i < triangle_count; i++) - { - t[i] = (Tri*)(tris + i*3); - } - - Tri* out = W3DNEWARRAY Tri[triangle_count]; - Tri* o = out; - - Tri* prev = t[0]; - - *o++ = *prev; - t[0] = NULL; - - for (;;) - { - // match best - int bestIndex = -1; - int bestSim = -1; - - for (int j = 0; j < triangle_count; j++) - if (t[j]) - { - int sim = Get_Similarity (*prev, *t[j]); - if (sim > bestSim) - { - bestSim = sim; - bestIndex = j; - if (sim >= 2) // that's the best we could get - break; - } - } - - if (bestIndex == -1) // we're done - break; - - *o++ = *t[bestIndex]; - prev = t[bestIndex]; - t[bestIndex] = NULL; - } - - - WWASSERT(o == (out+triangle_count)); - - for (i = 0; i < triangle_count; i++) - { - Tri* d = (Tri*)(tris)+i; - *d = out[i]; - } - - delete[] t; - delete[] out; - -} - - -/***************************************************************************** - * - * Function: StripOptimizerClass::combineStrips() - * - * Description: Combines a number of strips into one - * - * Parameters: - * - *****************************************************************************/ - -int* StripOptimizerClass::Combine_Strips (const int* strips, int strip_count) -{ - int check = Get_Strip_Index_Count(strips,strip_count) + (strip_count-1)*3; - - int* out = W3DNEWARRAY int[check+1]; - int* o = out + 1; - - int* tmp = W3DNEWARRAY int[check]; // DEBUG DEBUG - - bool prevEven = true; - - for (int i = 0; i < strip_count; i++) - { - int len = *strips++; - - if (i != 0) - { - *o++ = *strips; // duplicate first - - if (!prevEven) - *o++ = *strips; - } - - for (int j = 0; j < len; j++) - *o++ = *strips++; // copy the strip - - if (i != (strip_count-1)) - *o++ = o[-1]; - - prevEven = (!(len&1)); - } - - delete[] tmp; -// WWASSERT(check == (o-out-1)); - *out = (o-out-1); // set length - return out; -} - -//------------------------------------------------------------------------ -// New striping code -//------------------------------------------------------------------------ - -namespace Strip -{ - -/***************************************************************************** - * - * Struct: Vector3i - * - * Description: Internal class for representing an edge - * - *****************************************************************************/ - -struct Vector3i -{ - int v[3]; - Vector3i () {} - Vector3i (int a, int b, int c) { v[0]=a; v[1]=b; v[2]=c; } - - int& operator[](int i) { return v[i]; } - const int& operator[](int i) const { return v[i]; } - -}; - -/***************************************************************************** - * - * Struct: Edge - * - * Description: Internal class for representing an edge - * - *****************************************************************************/ - -struct Edge -{ - Edge (void) {} - Edge (int v0, int v1) { v[0] = v0; v[1] = v1; } - bool operator== (const Edge& s) const { return v[0]==s.v[0] && v[1] == s.v[1]; } - void sort (void) { if (v[0]>v[1]) swap(v[0],v[1]); } - - int v[2]; // edge -}; - -/***************************************************************************** - * - * Struct: Triangle - * - * Description: Internal class for representing a triangle and - * associated connectivity information - * - *****************************************************************************/ - -struct Triangle -{ - Triangle (void) - { - m_neighbors[0] = 0; - m_neighbors[1] = 0; - m_neighbors[2] = 0; - m_vertices[0] = 0; - m_vertices[1] = 0; - m_vertices[2] = 0; - m_prev = 0; - m_next = 0; - m_bin = -1; - } - - Triangle* m_neighbors[3]; // pointers to neighbors of the triangle - Vector3i m_vertices; // vertices of the triangle - - Triangle* m_prev; // previous triangle in same bin - Triangle* m_next; // next triangle in same bin - int m_bin; // current bin (-1 == not in any bin) - - int getConnectivity (void) const { int cnt = 0; if (m_neighbors[0]) cnt++; if (m_neighbors[1]) cnt++; if (m_neighbors[2]) cnt++; return cnt;} - const Edge getEdge (int i) const { WWASSERT(i>=0 && i<3); return Edge(m_vertices[i],i==2?m_vertices[0]:m_vertices[i+1]); } - -}; - -/***************************************************************************** - * - * Class: TriangleQueue - * - * Description: Internal class for maintaining triangles sorted by - * connectivity - * - *****************************************************************************/ - -class TriangleQueue -{ -public: - TriangleQueue (Triangle* tris, int N); - ~TriangleQueue (void); - void removeTriangle (Triangle* t); - Triangle* getTop (void) const; - int getVertexConnectivity (int i) const; -private: - TriangleQueue (const TriangleQueue&); - TriangleQueue& operator= (const TriangleQueue&); - void reinsert (Triangle* t); - - Triangle* m_bin[4]; // bins (0 = triangles with zero neighbors, etc.) - int* m_nodeConnectivity; // node connectivity count - int m_vertexCount; -}; - -/***************************************************************************** - * - * Class: Stripify - * - * Description: Class for performing stripification - * - *****************************************************************************/ - -class Stripify -{ -public: - static int* stripify (const Vector3i* tris, int N); -private: - Stripify (void); // not permitted - Stripify (const Stripify&); - Stripify& operator= (const Stripify&); - - static Triangle* generateTriangleList (const Vector3i* tris, int N); - static Vector3i getTriangleNodeConnectivityWeights (const TriangleQueue& queue, const Triangle& tri); - static int getMod3 (int i) { WWASSERT(i>=0 && i<6); return s_mod[i]; } - static int s_mod[6]; // small lookup table for mod3 operation (see getMod3()) -}; - -int Stripify::s_mod[6] = {0,1,2,0,1,2}; -} // Strip - - -template <> inline unsigned int HashTemplateKeyClass::Get_Hash_Value(const Strip::Edge& s) -{ - return (s.v[0]*139) + (s.v[1]*7); -} - -namespace Strip -{ -/***************************************************************************** - * - * Function: TriangleQueue::getTop() - * - * Description: Returns pointer to triangle with smallest connectivity - * - * Returns: pointer to triangle with smallest connectivity or NULL - * if the queue is empty - * - *****************************************************************************/ - -inline Triangle* TriangleQueue::getTop (void) const -{ - for (int i = 0; i < 4; i++) - if (m_bin[i]) - return m_bin[i]; // return head - return 0; // end -} - -/***************************************************************************** - * - * Function: TriangleQueue::getVertexConnectivity() - * - * Description: Returns current connectivity count of specified vertex - * - * Parameters: i = vertex index - * - * Returns: connectivity count - * - *****************************************************************************/ - -inline int TriangleQueue::getVertexConnectivity (int i) const -{ - WWASSERT(i>=0 && i< m_vertexCount); - return m_nodeConnectivity[i]; -} - -/***************************************************************************** - * - * Function: TriangleQueue::~TriangleQueue() - * - * Description: Destructor - * - *****************************************************************************/ - -inline TriangleQueue::~TriangleQueue () -{ - delete[] m_nodeConnectivity; -} - -/***************************************************************************** - * - * Function: TriangleQueue::reinsert() - * - * Description: Internal function for recalculating a triangle's - * connectivity - * - * Parameters: t = pointer to triangle (non-NULL) - * - *****************************************************************************/ - -inline void TriangleQueue::reinsert (Triangle* t) -{ - WWASSERT (t && t->m_bin!=-1); // must be in some bin - int w = t->getConnectivity(); - - // remove from bin - if (t->m_prev) - t->m_prev->m_next = t->m_next; - else - { - WWASSERT(t->m_bin != -1); - WWASSERT(t == m_bin[t->m_bin]); // must be head - m_bin[t->m_bin] = t->m_next; // new head - } - - if (t->m_next) - t->m_next->m_prev = t->m_prev; - - t->m_prev = 0; - t->m_next = m_bin[w]; - if (t->m_next) - t->m_next->m_prev = t; - - m_bin[w] = t; // head of bin - t->m_bin = w; // set bin -} - -/***************************************************************************** - * - * Function: TriangleQueue::removeTriangle() - * - * Description: Removes a triangle from the queue - * - * Parameters: t = pointer to triangle (non-NULL) - * - *****************************************************************************/ - -inline void TriangleQueue::removeTriangle (Triangle* t) -{ - WWASSERT(t); - if (t->m_prev) - t->m_prev->m_next = t->m_next; - else - { - WWASSERT(t->m_bin != -1); - WWASSERT(t == m_bin[t->m_bin]); // must be head - m_bin[t->m_bin] = t->m_next; // new head - } - - if (t->m_next) - t->m_next->m_prev = t->m_prev; - t->m_bin = -1; - - // update connectivity of t's neighbors - - Triangle* update[3]; - int i; - - for (i = 0; i < 3; i++) - { - update[i] = 0; - if (t->m_neighbors[i]) - { - Triangle* n = t->m_neighbors[i]; - int k=0; - for (k = 0; k < 3; k++) - if (n->m_neighbors[k]==t) - break; - WWASSERT (k!=3); // WASS?? - n->m_neighbors[k] = 0; // reduce connection - t->m_neighbors[i] = 0; - update[i] = n; - } - } - - // update connectivity count of t's vertices - - for (i = 0; i < 3; i++) - { - m_nodeConnectivity[t->m_vertices[i]]--; - WWASSERT(m_nodeConnectivity[t->m_vertices[i]] >= 0); // WASS? - } - - for (i = 0; i < 3; i++) // perform reinsertions now... - if (update[i]) - reinsert(update[i]); - -} - -/***************************************************************************** - * - * Function: TriangleQueue::TriangleQueue() - * - * Description: Constructor - * - * Parameters: tris = array of triangles - * N = number of triangles in the array - * - *****************************************************************************/ - -inline TriangleQueue::TriangleQueue (Triangle* tris, int N) -{ - int i; - for (i = 0; i < 4; i++) - m_bin[i] = 0; // initialize to zero - - int largestIndex = 0; - - for (i = 0; i < N; i++) - for (int j = 0; j < 3; j++) - { - WWASSERT(tris[i].m_vertices[j]>=0); - if (tris[i].m_vertices[j] > largestIndex) - largestIndex = tris[i].m_vertices[j]; - } - - m_vertexCount = largestIndex+1; - m_nodeConnectivity = W3DNEWARRAY int[m_vertexCount]; // - for (i = 0; i < m_vertexCount; i++) - m_nodeConnectivity[i] = 0; - - - for (i = 0; i < N; i++) - { - Triangle* t = tris+i; - int w = t->getConnectivity(); - WWASSERT(w>=0 && w <=3); - WWASSERT(!t->m_prev && !t->m_next && t->m_bin==-1); // must not be in a bin - t->m_prev = 0; - t->m_next = m_bin[w]; - if (t->m_next) - t->m_next->m_prev = t; - m_bin[w] = t; // head of bin - t->m_bin = w; // set bin - for (int j = 0; j < 3; j++) - m_nodeConnectivity[t->m_vertices[j]]++; - } -} - - -/***************************************************************************** - * - * Function: Stripify::getTriangleConnectivityWeights() - * - * Description: Returns "node connectivity" weights for each triangle vertex - * - * Parameters: queue = reference to triangle queue - * tri = reference to triangle - * - * Returns: Vector structure containing three weights - * - *****************************************************************************/ - -inline Vector3i Stripify::getTriangleNodeConnectivityWeights (const TriangleQueue& queue, const Triangle& tri) -{ - int weight[3]; - int i = 0; - for (; i < 3; i++) - { - weight[i] = queue.getVertexConnectivity(tri.m_vertices[i]); - } - int highestVal = weight[0]; - if (weight[1] > highestVal) highestVal = weight[1]; - if (weight[2] > highestVal) highestVal = weight[2]; - - Vector3i v(-1,-1,-1); - - for (i = 0; i < 3; i++) { - if (weight[0] == highestVal) v[i] = +1; - } - - return v; -} - -/***************************************************************************** - * - * Function: Stripify::generateTriangleList() - * - * Description: Converts input triangles into internal Triangle structure - * - * Parameters: inTris = input triangles - * N = number of input triangles - * - * Returns: pointer to Triangle array - * - * Notes: The function sets up the initial connectivity information - * - *****************************************************************************/ - -Triangle* Stripify::generateTriangleList (const Vector3i* inTris, int N) -{ - WWASSERT (inTris && N>=0); - - Triangle* tris = W3DNEWARRAY Triangle[N]; // allocate triangles - int i; - - //-------------------------------------------------------------------- - // Copy triangle vertex data - //-------------------------------------------------------------------- - - for (i = 0; i < N; i++) - { - //-------------------------------------------------------------------- - // We could perform random rotation here (this way we don't need random - // comparisons later in the algo in equality cases). - //-------------------------------------------------------------------- - - tris[i].m_vertices[0] = inTris[i][0]; - tris[i].m_vertices[1] = inTris[i][1]; - tris[i].m_vertices[2] = inTris[i][2]; - } - - //-------------------------------------------------------------------- - // Build connectivity information using a hash table - //-------------------------------------------------------------------- - - HashTemplateClass hash; - Triangle* t = tris; - - for (i = 0; i < N; i++, t++) - { - for (int j = 0; j < 3; j++) - if (!t->m_neighbors[j]) // if neighbor not defined yet - { - Edge edge = tris[i].getEdge(j); - Edge e = edge; - e.sort(); // sort vertices (smaller first) - - Triangle* n = hash.Get(e); - if (n) // if edge is already in the hash... - { - int k=0; - for (k = 0; k < 3; k++) // find matching edge - if (!n->m_neighbors[k]) // this neighbor not located yet - { - Edge ek = n->getEdge(k); // get edge - if (ek.v[0] == edge.v[1] && ek.v[1] == edge.v[0]) // if matching edge (note that order must be different) - break; // .. we found the edge - } - - if (k < 3) // (k==3) -> no match - { - t->m_neighbors[j] = n; // set neighbor - n->m_neighbors[k] = t; // set neighbor - hash.Remove(e); // remove from hash (this speeds up the hash queries considerably) - } - } else - hash.Insert(e, t); // insert triangle into hash - } - } - - return tris; // return pointer to output data -} - -/***************************************************************************** - * - * Function: Stripify::stripify() - * - * Description: Builds a set of triangle strips out of a triangle array - * - * Parameters: inTris = input triangles (three vertices per triangle) - * N = number of input triangles - * - * Returns: pointer to strip data array - * - * Notes: The strip data array layout is as follows: - * - * [int] number of strips - * [int] length of first strip (in vertices) - * [int,..] vertex indices of the first strip - * [int] length of second strip - * ... - * - * The routine assumes that degenerate triangles have been - * remove and input vertices have been welded - * - *****************************************************************************/ - -int* Stripify::stripify (const Vector3i* inTris, int N) -{ - if (!inTris || N<=0) // boo! - return 0; - - //-------------------------------------------------------------------- - // Initial setup - //-------------------------------------------------------------------- - - Triangle* tris = generateTriangleList(inTris,N); // build connectivity info - int* out = W3DNEWARRAY int[N*5]; // absolute worst case situation - int* o = out; // internal ptr (save entry[0] for later use) - int strip_count = 0; // number of output strips - TriangleQueue queue (tris, N); // insert triangles into priority queue - - int nSwaps = 0; - int nLen = 0; - - //-------------------------------------------------------------------- - // Main loop. Always select triangle with smallest weight. - //-------------------------------------------------------------------- - - for (;;) - { - Triangle* t = queue.getTop(); // get triangle with smallest weight - if (!t) // ok, we ran out of triangles (we're done) - break; - - //-------------------------------------------------------------------- - // Choose initial direction by selecting neighbor with smallest - // weight - //-------------------------------------------------------------------- - - int* pLen = o; // get current pointer (as we need to take care of it later) - int len = 3; // initial length - int best = 0; // best edge - int bestWeight = 0x7fffffff; // initialize to maximum width - - Vector3i nodeWeights = getTriangleNodeConnectivityWeights(queue, *t); - - for (int i = 0; i < 3; i++) - if (t->m_neighbors[i]) // if triangle has a neighbor in this direction - { - int weight = t->m_neighbors[i]->getConnectivity(); // get connectivity of neighbor - - weight += nodeWeights[i]; // add node weights - weight += nodeWeights[getMod3(i+1)]; - - // DEBUG DEBUG ADD SWAP COST HERE? - if (weight <= bestWeight) - { - bestWeight = weight; - best = i; - } - } - - *o++ = len; // output the first three vertices - *o++ = t->m_vertices[getMod3(best+2)]; - *o++ = t->m_vertices[getMod3(best+0)]; - *o++ = t->m_vertices[getMod3(best+1)]; - - for (;;) - { - Triangle* next = 0; // find next triangle - - int i; - for (i = 0; i < 3; i++) - if (t->m_neighbors[i]) - { - Triangle* n = t->m_neighbors[i]; - for (int j = 0; j < 3; j++) - { - Edge e = n->getEdge(j); - if (!(len&1)) - swap(e.v[0],e.v[1]); // swap - if (e.v[0] == o[-1] && e.v[1] == o[-2]) - { - next = n; - break; - } - } - } - - queue.removeTriangle(t); // get rid of the old triangle - - if (!next) // we're done - break; - - //-------------------------------------------------------------------- - // Find out where we want to continue... - //-------------------------------------------------------------------- - - int bestEdge = -1; - int bestWeight = 0x7fffffff; - bool bestSwap = false; - - Vector3i nodeWeights = getTriangleNodeConnectivityWeights(queue, *next); - - for (i = 0; i < 3; i++) - if (next->m_neighbors[i]) // is there a neighbor? - { - Edge e = next->getEdge(i); // a swap happens if it contains the prevprev - - bool swap = (e.v[0] == o[-2] || e.v[1] == o[-2]); - - Triangle* n = next->m_neighbors[i]; // get pointer to neighbor - int w = n->getConnectivity(); - - - w += nodeWeights[i]; // add vertex weight - w += nodeWeights[getMod3(i+1)]; // add vertex weight - - w += (swap) ? 1 : -1; // add swap penalty - - if (w <= bestWeight) - { - bestWeight = w; - bestEdge = i; - bestSwap = swap; - } - } - - if (bestEdge != -1 && bestSwap) // if we're going to continue... - { - *o = o[-2]; // introduce swap vertex - o++; - len++; // adjust length - nSwaps++; // update statistics - } - - //-------------------------------------------------------------------- - // Find out which was the new vertex (store it to vIndex) - //-------------------------------------------------------------------- - - int vIndex = 0; - - if (next->m_vertices[1] != o[-1] && next->m_vertices[1] != o[-2]) vIndex = 1; else - if (next->m_vertices[2] != o[-1] && next->m_vertices[2] != o[-2]) vIndex = 2; else - WWASSERT (next->m_vertices[0] != o[-1] && next->m_vertices[0] != o[-2]); - - //-------------------------------------------------------------------- - // Output the vertex and move to next triangle - //-------------------------------------------------------------------- - - *o++ = next->m_vertices[vIndex]; // output the vertex - len++; // increase strip length - t = next; // move to next triangle - } - - *pLen = len; // patch final length - strip_count++; // increase strip count - - nLen += len; -// printf ("strip len = %d\n",len); - } - - //-------------------------------------------------------------------- - // Allocate new optimal-size array and copy output there. Then release - // all temporary memory allocations. - //-------------------------------------------------------------------- - -// printf ("total indices = %d\n",nLen); -// printf ("total swaps = %d\n",nSwaps); - - int len = o-out; // allocation length - int* rOut = W3DNEWARRAY int[len+1]; - - *rOut = strip_count; // first entry is number of strips - for (int i = 0; i < len; i++) - { - WWASSERT(out[i] >= 0); // would be nice to test for len as well - rOut[i+1] = out[i]; - } - - delete[] out; // delete internal output - delete[] tris; // delete internal triangle list - - return rOut; -} -} // Strip -int* StripOptimizerClass::Stripify(const int* tris, int N) -{ - return Strip::Stripify::stripify((const Strip::Vector3i*)tris,N); -} - -//------------------------------------------------------------------------ - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h deleted file mode 100644 index 1396369a29..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/stripoptimizer.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WW3D2_STRIP_OPTIMIZER_H__ -#define WW3D2_STRIP_OPTIMIZER_H__ - -#include "always.h" - - -// strip data = -// -// len = number of vertices in strip -// [vertex indices] -// len -// [vertex indices] -// .. - -class StripOptimizerClass -{ -public: - static int* Stripify(const int* tris, int tri_count); // Outputs a set of strips - static int* Combine_Strips(const int* strips, int strip_count); - static void Optimize_Strip_Order(int* strips, int strip_count); // Sorts strips for optimal access order - static void Optimize_Triangle_Order(int* tris, int triangle_count); // Sorts triangles (three indices each) into near-optimal access order - - static int Get_Strip_Index_Count(const int* strips, int strips_count); -}; - -#endif // WW3D2_STRIP_OPTIMIZER_H__ diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp deleted file mode 100644 index 73c8d1c566..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/surfaceclass.cpp +++ /dev/null @@ -1,1007 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /VSS_Sync/ww3d2/surfaceclass.cpp $* - * * - * Original Author:: Nathaniel Hoffman * - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 24 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * SurfaceClass::Clear -- Clears a surface to 0 * - * SurfaceClass::Copy -- Copies a region from one surface to another of the same format * - * SurfaceClass::FindBBAlpha -- Finds the bounding box of non zero pixels in the region (x0, * - * PixelSize -- Helper Function to find the size in bytes of a pixel * - * SurfaceClass::Is_Transparent_Column -- Tests to see if the column is transparent or not * - * SurfaceClass::Copy -- Copies from a byte array to the surface * - * SurfaceClass::CreateCopy -- Creates a byte array copy of the surface * - * SurfaceClass::DrawHLine -- draws a horizontal line * - * SurfaceClass::DrawPixel -- draws a pixel * - * SurfaceClass::Copy -- Copies a block of system ram to the surface * - * SurfaceClass::Hue_Shift -- changes the hue of the surface * - * SurfaceClass::Is_Monochrome -- Checks if surface is monochrome or not * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "surfaceclass.h" -#include "formconv.h" -#include "dx8wrapper.h" -#include "vector2i.h" -#include "colorspace.h" -#include "bound.h" -#include - -/*********************************************************************************************** - * PixelSize -- Helper Function to find the size in bytes of a pixel * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ - -unsigned int PixelSize(const SurfaceClass::SurfaceDescription &sd) -{ - unsigned int size=0; - - switch (sd.Format) - { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - size=4; - break; - case WW3D_FORMAT_R8G8B8: - size=3; - break; - case WW3D_FORMAT_R5G6B5: - case WW3D_FORMAT_X1R5G5B5: - case WW3D_FORMAT_A1R5G5B5: - case WW3D_FORMAT_A4R4G4B4: - case WW3D_FORMAT_A8R3G3B2: - case WW3D_FORMAT_X4R4G4B4: - case WW3D_FORMAT_A8P8: - case WW3D_FORMAT_A8L8: - size=2; - break; - case WW3D_FORMAT_R3G3B2: - case WW3D_FORMAT_A8: - case WW3D_FORMAT_P8: - case WW3D_FORMAT_L8: - case WW3D_FORMAT_A4L4: - size=1; - break; - } - - return size; -} - -void Convert_Pixel(Vector3 &rgb, const SurfaceClass::SurfaceDescription &sd, const unsigned char * pixel) -{ - const float scale=1/255.0f; - switch (sd.Format) - { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - case WW3D_FORMAT_R8G8B8: - { - rgb.X=pixel[2]; // R - rgb.Y=pixel[1]; // G - rgb.Z=pixel[0]; // B - } - break; - case WW3D_FORMAT_A4R4G4B4: - { - unsigned short tmp; - tmp=*(unsigned short*)&pixel[0]; - rgb.X=((tmp&0x0f00)>>4); // R - rgb.Y=((tmp&0x00f0)); // G - rgb.Z=((tmp&0x000f)<<4); // B - } - break; - case WW3D_FORMAT_A1R5G5B5: - { - unsigned short tmp; - tmp=*(unsigned short*)&pixel[0]; - rgb.X=(tmp>>7)&0xf8; // R - rgb.Y=(tmp>>2)&0xf8; // G - rgb.Z=(tmp<<3)&0xf8; // B - } - break; - case WW3D_FORMAT_R5G6B5: - { - unsigned short tmp; - tmp=*(unsigned short*)&pixel[0]; - rgb.X=(tmp>>8)&0xf8; - rgb.Y=(tmp>>3)&0xfc; - rgb.Z=(tmp<<3)&0xf8; - } - break; - - default: - // TODO: Implement other pixel formats - WWASSERT(0); - } - rgb*=scale; -} - -// Note: This function must never overwrite the original alpha -void Convert_Pixel(unsigned char * pixel,const SurfaceClass::SurfaceDescription &sd, const Vector3 &rgb) -{ - unsigned char r,g,b; - r=(unsigned char) (rgb.X*255.0f); - g=(unsigned char) (rgb.Y*255.0f); - b=(unsigned char) (rgb.Z*255.0f); - switch (sd.Format) - { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - case WW3D_FORMAT_R8G8B8: - pixel[0]=b; - pixel[1]=g; - pixel[2]=r; - break; - case WW3D_FORMAT_A4R4G4B4: - { - unsigned short tmp; - tmp=*(unsigned short*)&pixel[0]; - tmp&=0xF000; - tmp|=(r&0xF0) << 4; - tmp|=(g&0xF0); - tmp|=(b&0xF0) >> 4; - *(unsigned short*)&pixel[0]=tmp; - } - break; - case WW3D_FORMAT_A1R5G5B5: - { - unsigned short tmp; - tmp=*(unsigned short*)&pixel[0]; - tmp&=0x8000; - tmp|=(r&0xF8) << 7; - tmp|=(g&0xF8) << 2; - tmp|=(b&0xF8) >> 3; - *(unsigned short*)&pixel[0]=tmp; - } - break; - case WW3D_FORMAT_R5G6B5: - { - unsigned short tmp; - tmp=(r&0xf8) << 8; - tmp|=(g&0xfc) << 3; - tmp|=(b&0xf8) >> 3; - *(unsigned short*)&pixel[0]=tmp; - } - break; - default: - // TODO: Implement other pixel formats - WWASSERT(0); - } -} - -/************************************************************************* -** SurfaceClass -*************************************************************************/ -SurfaceClass::SurfaceClass(unsigned width, unsigned height, WW3DFormat format): - D3DSurface(NULL), - SurfaceFormat(format) -{ - WWASSERT(width); - WWASSERT(height); - D3DSurface = DX8Wrapper::_Create_DX8_Surface(width, height, format); -} - -SurfaceClass::SurfaceClass(const char *filename): - D3DSurface(NULL) -{ - D3DSurface = DX8Wrapper::_Create_DX8_Surface(filename); - SurfaceDescription desc; - Get_Description(desc); - SurfaceFormat=desc.Format; -} - -SurfaceClass::SurfaceClass(IDirect3DSurface8 *d3d_surface) : - D3DSurface (NULL) -{ - Attach (d3d_surface); - SurfaceDescription desc; - Get_Description(desc); - SurfaceFormat=desc.Format; -} - -SurfaceClass::~SurfaceClass(void) -{ - if (D3DSurface) { - D3DSurface->Release(); - D3DSurface = NULL; - } -} - -void SurfaceClass::Get_Description(SurfaceDescription &surface_desc) -{ - D3DSURFACE_DESC d3d_desc; - ::ZeroMemory(&d3d_desc, sizeof(D3DSURFACE_DESC)); - DX8_ErrorCode(D3DSurface->GetDesc(&d3d_desc)); - surface_desc.Format = D3DFormat_To_WW3DFormat(d3d_desc.Format); - surface_desc.Height = d3d_desc.Height; - surface_desc.Width = d3d_desc.Width; -} - -void * SurfaceClass::Lock(int * pitch) -{ - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect, 0, 0)); - *pitch = lock_rect.Pitch; - return (void *)lock_rect.pBits; -} - -void SurfaceClass::Unlock(void) -{ - DX8_ErrorCode(D3DSurface->UnlockRect()); -} - -/*********************************************************************************************** - * SurfaceClass::Clear -- Clears a surface to 0 * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::Clear() -{ - SurfaceDescription sd; - Get_Description(sd); - - // size of each pixel in bytes - unsigned int size=PixelSize(sd); - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,0,0)); - unsigned int i; - unsigned char *mem=(unsigned char *) lock_rect.pBits; - - for (i=0; iUnlockRect()); -} - - -/*********************************************************************************************** - * SurfaceClass::Copy -- Copies from a byte array to the surface * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/15/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::Copy(const unsigned char *other) -{ - SurfaceDescription sd; - Get_Description(sd); - - // size of each pixel in bytes - unsigned int size=PixelSize(sd); - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,0,0)); - unsigned int i; - unsigned char *mem=(unsigned char *) lock_rect.pBits; - - for (i=0; iUnlockRect()); -} - - -/*********************************************************************************************** - * SurfaceClass::Copy -- Copies a block of system ram to the surface * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/2/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::Copy(Vector2i &min,Vector2i &max, const unsigned char *other) -{ - SurfaceDescription sd; - Get_Description(sd); - - // size of each pixel in bytes - unsigned int size=PixelSize(sd); - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - RECT rect; - rect.left=min.I; - rect.right=max.I; - rect.top=min.J; - rect.bottom=max.J; - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,&rect,0)); - int i; - unsigned char *mem=(unsigned char *) lock_rect.pBits; - int dx=max.I-min.I; - - for (i=min.J; iUnlockRect()); -} - - -/*********************************************************************************************** - * SurfaceClass::CreateCopy -- Creates a byte array copy of the surface * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/16/2001 hy : Created. * - *=============================================================================================*/ -unsigned char *SurfaceClass::CreateCopy(int *width,int *height,int*size,bool flip) -{ - SurfaceDescription sd; - Get_Description(sd); - - // size of each pixel in bytes - unsigned int mysize=PixelSize(sd); - - *width=sd.Width; - *height=sd.Height; - *size=mysize; - - unsigned char *other=W3DNEWARRAY unsigned char [sd.Height*sd.Width*mysize]; - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,0,D3DLOCK_READONLY)); - unsigned int i; - unsigned char *mem=(unsigned char *) lock_rect.pBits; - - for (i=0; iUnlockRect()); - - return other; -} - - -/*********************************************************************************************** - * SurfaceClass::Copy -- Copies a region from one surface to another * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::Copy( - unsigned int dstx, unsigned int dsty, - unsigned int srcx, unsigned int srcy, - unsigned int width, unsigned int height, - const SurfaceClass *other) -{ - WWASSERT(other); - WWASSERT(width); - WWASSERT(height); - - SurfaceDescription sd,osd; - Get_Description(sd); - const_cast (other)->Get_Description(osd); - - RECT src; - src.left=srcx; - src.right=srcx+width; - src.top=srcy; - src.bottom=srcy+height; - - if (src.right>int(osd.Width)) src.right=int(osd.Width); - if (src.bottom>int(osd.Height)) src.bottom=int(osd.Height); - - if (sd.Format==osd.Format && sd.Width==osd.Width && sd.Height==osd.Height) - { - POINT dst; - dst.x=dstx; - dst.y=dsty; - DX8Wrapper::_Copy_DX8_Rects(other->D3DSurface,&src,1,D3DSurface,&dst); - } - else - { - RECT dest; - dest.left=dstx; - dest.right=dstx+width; - dest.top=dsty; - dest.bottom=dsty+height; - - if (dest.right>int(sd.Width)) dest.right=int(sd.Width); - if (dest.bottom>int(sd.Height)) dest.bottom=int(sd.Height); - - DX8_ErrorCode(D3DXLoadSurfaceFromSurface(D3DSurface,NULL,&dest,other->D3DSurface,NULL,&src,D3DX_FILTER_NONE,0)); - } -} - -/*********************************************************************************************** - * SurfaceClass::Copy -- Copies a region from one surface to another * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::Stretch_Copy( - unsigned int dstx, unsigned int dsty, unsigned int dstwidth, unsigned int dstheight, - unsigned int srcx, unsigned int srcy, unsigned int srcwidth, unsigned int srcheight, - const SurfaceClass *other) -{ - WWASSERT(other); - - SurfaceDescription sd,osd; - Get_Description(sd); - const_cast (other)->Get_Description(osd); - - RECT src; - src.left=srcx; - src.right=srcx+srcwidth; - src.top=srcy; - src.bottom=srcy+srcheight; - - RECT dest; - dest.left=dstx; - dest.right=dstx+dstwidth; - dest.top=dsty; - dest.bottom=dsty+dstheight; - - DX8_ErrorCode(D3DXLoadSurfaceFromSurface(D3DSurface,NULL,&dest,other->D3DSurface,NULL,&src,D3DX_FILTER_TRIANGLE ,0)); -} - -/*********************************************************************************************** - * SurfaceClass::FindBB -- Finds the bounding box of non zero pixels in the region * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::FindBB(Vector2i *min,Vector2i*max) -{ - SurfaceDescription sd; - Get_Description(sd); - - WWASSERT(Has_Alpha(sd.Format)); - - int alphabits=Alpha_Bits(sd.Format); - int mask=0; - switch (alphabits) - { - case 1: mask=1; - break; - case 4: mask=0xf; - break; - case 8: mask=0xff; - break; - } - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - RECT rect; - ::ZeroMemory(&rect, sizeof(RECT)); - - rect.bottom=max->J; - rect.top=min->J; - rect.left=min->I; - rect.right=max->I; - - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,&rect,D3DLOCK_READONLY)); - - int x,y; - unsigned int size=PixelSize(sd); - Vector2i realmin=*max; - Vector2i realmax=*min; - - // the assumption here is that whenever a pixel has alpha it's in the MSB - for (y = min->J; y < max->J; y++) { - for (x = min->I; x < max->I; x++) { - - // HY - this is not endian safe - unsigned char *alpha=(unsigned char*) ((unsigned int)lock_rect.pBits+(y-min->J)*lock_rect.Pitch+(x-min->I)*size); - unsigned char myalpha=alpha[size-1]; - myalpha=(myalpha>>(8-alphabits)) & mask; - if (myalpha) { - realmin.I = MIN(realmin.I, x); - realmax.I = MAX(realmax.I, x); - realmin.J = MIN(realmin.J, y); - realmax.J = MAX(realmax.J, y); - } - } - } - - DX8_ErrorCode(D3DSurface->UnlockRect()); - - *max=realmax; - *min=realmin; -} - - -/*********************************************************************************************** - * SurfaceClass::Is_Transparent_Column -- Tests to see if the column is transparent or not * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ -bool SurfaceClass::Is_Transparent_Column(unsigned int column) -{ - SurfaceDescription sd; - Get_Description(sd); - - WWASSERT(columnLockRect(&lock_rect,&rect,D3DLOCK_READONLY)); - - int y; - - // the assumption here is that whenever a pixel has alpha it's in the MSB - for (y = 0; y < (int) sd.Height; y++) - { - // HY - this is not endian safe - unsigned char *alpha=(unsigned char*) ((unsigned int)lock_rect.pBits+y*lock_rect.Pitch); - unsigned char myalpha=alpha[size-1]; - myalpha=(myalpha>>(8-alphabits)) & mask; - if (myalpha) { - DX8_ErrorCode(D3DSurface->UnlockRect()); - return false; - } - } - - DX8_ErrorCode(D3DSurface->UnlockRect()); - return true; -} - -/*********************************************************************************************** - * SurfaceClass::Get_Pixel -- Returns the pixel's RGB valus to the caller * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/13/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::Get_Pixel(Vector3 &rgb, int x,int y) -{ - SurfaceDescription sd; - Get_Description(sd); - - x = min(x,(int)sd.Width - 1); - y = min(y,(int)sd.Height - 1); - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - RECT rect; - ::ZeroMemory(&rect, sizeof(RECT)); - - rect.bottom=y+1; - rect.top=y; - rect.left=x; - rect.right=x+1; - - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,&rect,D3DLOCK_READONLY)); - Convert_Pixel(rgb,sd,(unsigned char *) lock_rect.pBits); - DX8_ErrorCode(D3DSurface->UnlockRect()); -} - -/*********************************************************************************************** - * SurfaceClass::Attach -- Attaches a surface pointer to the object, releasing the current ptr.* - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/2001 pds : Created. * - *=============================================================================================*/ -void SurfaceClass::Attach (IDirect3DSurface8 *surface) -{ - Detach (); - D3DSurface = surface; - - // - // Lock a reference onto the object - // - if (D3DSurface != NULL) { - D3DSurface->AddRef (); - } - - return ; -} - - -/*********************************************************************************************** - * SurfaceClass::Detach -- Releases the reference on the internal surface ptr, and NULLs it. .* - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/27/2001 pds : Created. * - *=============================================================================================*/ -void SurfaceClass::Detach (void) -{ - // - // Release the hold we have on the D3D object - // - if (D3DSurface != NULL) { - D3DSurface->Release (); - } - - D3DSurface = NULL; - return ; -} - - -/*********************************************************************************************** - * SurfaceClass::DrawPixel -- draws a pixel * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void SurfaceClass::DrawPixel(const unsigned int x,const unsigned int y, unsigned int color) -{ - SurfaceDescription sd; - Get_Description(sd); - - unsigned int size=PixelSize(sd); - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - RECT rect; - ::ZeroMemory(&rect, sizeof(RECT)); - - rect.bottom=y+1; - rect.top=y; - rect.left=x; - rect.right=x+1; - - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,&rect,0)); - unsigned char *cptr=(unsigned char*)lock_rect.pBits; - unsigned short *sptr=(unsigned short*)lock_rect.pBits; - unsigned int *lptr=(unsigned int*)lock_rect.pBits; - - switch (size) - { - case 1: - *cptr=(unsigned char) (color & 0xFF); - break; - case 2: - *sptr=(unsigned short) (color & 0xFFFF); - break; - case 4: - *lptr=color; - break; - } - - DX8_ErrorCode(D3DSurface->UnlockRect()); -} - -/*********************************************************************************************** - * SurfaceClass::DrawHLine -- draws a horizontal line * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/9/2001 hy : Created. * - * 4/9/2001 hy : Created. * - *=============================================================================================*/ -void SurfaceClass::DrawHLine(const unsigned int y,const unsigned int x1, const unsigned int x2, unsigned int color) -{ - SurfaceDescription sd; - Get_Description(sd); - - unsigned int size=PixelSize(sd); - - D3DLOCKED_RECT lock_rect; - ::ZeroMemory(&lock_rect, sizeof(D3DLOCKED_RECT)); - RECT rect; - ::ZeroMemory(&rect, sizeof(RECT)); - - rect.bottom=y+1; - rect.top=y; - rect.left=x1; - rect.right=x2+1; - - DX8_ErrorCode(D3DSurface->LockRect(&lock_rect,&rect,0)); - unsigned char *cptr=(unsigned char*)lock_rect.pBits; - unsigned short *sptr=(unsigned short*)lock_rect.pBits; - unsigned int *lptr=(unsigned int*)lock_rect.pBits; - - unsigned int x; - // the assumption here is that whenever a pixel has alpha it's in the MSB - for (x=x1; x<=x2; x++) - { - switch (size) - { - case 1: - *cptr++=(unsigned char) (color & 0xFF); - break; - case 2: - *sptr++=(unsigned short) (color & 0xFFFF); - break; - case 4: - *lptr++=color; - break; - } - } - - DX8_ErrorCode(D3DSurface->UnlockRect()); -} - - -/*********************************************************************************************** - * SurfaceClass::Is_Monochrome -- Checks if surface is monochrome or not * - * * - * * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/5/2001 hy : Created. * - *=============================================================================================*/ -bool SurfaceClass::Is_Monochrome(void) -{ - unsigned int x,y; - SurfaceDescription sd; - Get_Description(sd); - - switch (sd.Format) - { - case WW3D_FORMAT_A8L8: - case WW3D_FORMAT_A8: - case WW3D_FORMAT_L8: - case WW3D_FORMAT_A4L4: - return true; - break; - } - - int pitch,size; - - size=PixelSize(sd); - unsigned char *bits=(unsigned char*) Lock(&pitch); - - Vector3 rgb; - bool mono=true; - - for (y=0; y. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /VSS_Sync/ww3d2/surfaceclass.h $* - * * - * Original Author:: Nathaniel Hoffman * - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 9:32p $* - * * - * $Revision:: 17 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SURFACECLASS_H -#define SURFACECLASS_H - -#include "ww3dformat.h" -#include "refcount.h" - -struct IDirect3DSurface8; -class Vector2i; -class Vector3; - -/************************************************************************* -** SurfaceClass -** -** This is our surface class, which wraps IDirect3DSurface8. -** -** Hector Yee 2/12/01 - added in fills, blits etc for font3d class -** -*************************************************************************/ -class SurfaceClass : public W3DMPO, public RefCountClass -{ - W3DMPO_GLUE(SurfaceClass) - public: - - struct SurfaceDescription { - WW3DFormat Format; // Surface format - unsigned int Width; // Surface width in pixels - unsigned int Height; // Surface height in pixels - }; - - // Create surface with desired height, width and format. - SurfaceClass(unsigned width, unsigned height, WW3DFormat format); - - // Create surface from a file. - SurfaceClass(const char *filename); - - // Create the surface from a D3D pointer - SurfaceClass(IDirect3DSurface8 *d3d_surface); - - ~SurfaceClass(void); - - // Get surface description - void Get_Description(SurfaceDescription &surface_desc); - - // Lock / unlock the surface - void * Lock(int * pitch); - void Unlock(void); - - // HY -- The following functions are support functions for font3d - // zaps the surface memory to zero - void Clear(); - - // copies the contents of one surface to another - void Copy( - unsigned int dstx, unsigned int dsty, - unsigned int srcx, unsigned int srcy, - unsigned int width, unsigned int height, - const SurfaceClass *other); - - // support for copying from a byte array - void Copy(const unsigned char *other); - - // support for copying from a byte array - void Copy(Vector2i &min,Vector2i &max, const unsigned char *other); - - // copies the contents of one surface to another, stretches - void Stretch_Copy( - unsigned int dstx, unsigned int dsty,unsigned int dstwidth, unsigned int dstheight, - unsigned int srcx, unsigned int srcy, unsigned int srcwidth, unsigned int srcheight, - const SurfaceClass *source); - - // finds the bounding box of non-zero pixels, used in font3d - void FindBB(Vector2i *min,Vector2i*max); - - // tests a column to see if the alpha is nonzero, used in font3d - bool Is_Transparent_Column(unsigned int column); - - // makes a copy of the surface into a byte array - unsigned char *CreateCopy(int *width,int *height,int*size,bool flip=false); - - // For use by TextureClass: - IDirect3DSurface8 *Peek_D3D_Surface(void) { return D3DSurface; } - - // Attaching and detaching a surface pointer - void Attach (IDirect3DSurface8 *surface); - void Detach (void); - - // draws a horizontal line - void DrawHLine(const unsigned int y,const unsigned int x1, const unsigned int x2, unsigned int color); - - void DrawPixel(const unsigned int x,const unsigned int y, unsigned int color); - - // get pixel function .. to be used infrequently - void Get_Pixel(Vector3 &rgb, int x,int y); - - void Hue_Shift(const Vector3 &hsv_shift); - - bool Is_Monochrome(void); - - WW3DFormat Get_Surface_Format() const { return SurfaceFormat; } - - private: - - // Direct3D surface object - IDirect3DSurface8 *D3DSurface; - - WW3DFormat SurfaceFormat; - friend class TextureClass; -}; - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp index 5bb9fce148..ca510e310b 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texproject.cpp @@ -734,10 +734,6 @@ void TexProjectClass::Set_Texture(TextureClass * texture) texture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); texture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP); MaterialPass->Set_Texture(texture); - - SurfaceClass::SurfaceDescription surface_desc; - texture->Get_Level_Description(surface_desc); - Set_Texture_Size(surface_desc.Width); } } @@ -1319,6 +1315,14 @@ void TexProjectClass::Pre_Render_Update(const Matrix3D & camera) } else { Mapper->Set_Type(MatrixMapperClass::ORTHO_PROJECTION); } + + if (Get_Texture_Size() == 0) { +// SurfaceClass::SurfaceDescription surface_desc; +// MaterialPass->Peek_Texture()->Get_Level_Description(surface_desc); + Set_Texture_Size(MaterialPass->Peek_Texture()->Get_Width()); + WWASSERT(Get_Texture_Size() != 0); + } + Mapper->Set_Texture_Transform(view_to_texture,Get_Texture_Size()); if (Mapper1) { Mapper1->Set_Texture_Transform(view_to_texture,Get_Texture_Size()); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textdraw.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textdraw.cpp deleted file mode 100644 index 2d53223abc..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textdraw.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /Commando/Code/ww3d2/textdraw.cpp $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 3/22/01 8:03p $* - * * - * $Revision:: 7 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "textdraw.h" -#include "font3d.h" -#include "simplevec.h" - -/*********************************************************************************************** - * * - * TextDrawClass::TextDrawClass( int ) -- Constructor * - * * - * Creates a TextDrawClass object by creating and initializing a Dynamic Mesh, inserting it * - * into the given scene, and allocating space for the given number of maximum chars. * - * * - ***********************************************************************************************/ -TextDrawClass::TextDrawClass( int max_chars ) : - DynamicMeshClass( max_chars * 2, max_chars * 4 ), - TextColor( 1.0f, 1.0f, 1.0f ) -{ - // Build the default Vertex Material - DefaultVertexMaterial = NEW_REF( VertexMaterialClass, () ); - DefaultVertexMaterial->Set_Diffuse( 0, 0, 0 ); - DefaultVertexMaterial->Set_Opacity(1); - DefaultVertexMaterial->Set_Emissive( 1, 1, 1 ); - Set_Vertex_Material( DefaultVertexMaterial ); - - // Build the default Shader - DefaultShader.Set_Depth_Mask( ShaderClass::DEPTH_WRITE_DISABLE ); - DefaultShader.Set_Depth_Compare( ShaderClass::PASS_ALWAYS ); - DefaultShader.Set_Dst_Blend_Func( ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA ); - DefaultShader.Set_Src_Blend_Func( ShaderClass::SRCBLEND_SRC_ALPHA ); - DefaultShader.Set_Texturing( ShaderClass::TEXTURING_ENABLE ); - DefaultShader.Set_Cull_Mode( ShaderClass::CULL_MODE_DISABLE ); - Set_Shader( DefaultShader ); - Enable_Sort(); - - Set_Coordinate_Ranges( Vector2( 0,0 ), Vector2( 1,1 ), Vector2( -1,0.75f ), Vector2( 1,-0.75 ) ); -// Set_Coordinate_Ranges( Vector2( -320,240 ), Vector2( 320,-240 ), Vector2( -320,240 ), Vector2( 320,-240 ) ); -} - -/*********************************************************************************************** - * * - * TextDrawClass::~TextDrawClass( void ) -- Destructor * - * * - ***********************************************************************************************/ -TextDrawClass::~TextDrawClass( void ) -{ - DefaultVertexMaterial->Release_Ref(); -} - -/*********************************************************************************************** - * * - * TextDrawClass::Reset( void ) -- Flush the mesh - * * - ***********************************************************************************************/ -void TextDrawClass::Reset( void ) -{ - Reset_Flags(); - Reset_Mesh_Counters(); - - // Reinstall the default vertex material and shader - Enable_Sort(); - Set_Vertex_Material( DefaultVertexMaterial ); - Set_Shader( DefaultShader ); -} - -/* -** -*/ -void TextDrawClass::Set_Coordinate_Ranges( - const Vector2 & src_ul, const Vector2 & src_lr, - const Vector2 & dest_ul, const Vector2 & dest_lr ) -{ - TranslateScale.X = (dest_lr.X - dest_ul.X) / (src_lr.X - src_ul.X); - TranslateScale.Y = (dest_lr.Y - dest_ul.Y) / (src_lr.Y - src_ul.Y); - TranslateOffset.X = dest_ul.X - TranslateScale.X * src_ul.X; - TranslateOffset.Y = dest_ul.Y - TranslateScale.Y * src_ul.Y; - - PixelSize.X = fabs((src_lr.X - src_ul.X) / 640.0f); - PixelSize.Y = fabs((src_lr.Y - src_ul.Y) / 480.0f); -} - - -/* -** -*/ -void TextDrawClass::Quad( float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1 ) -{ - // Translate coordinates - x0 = x0 * TranslateScale.X + TranslateOffset.X; - x1 = x1 * TranslateScale.X + TranslateOffset.X; - y0 = y0 * TranslateScale.Y + TranslateOffset.Y; - y1 = y1 * TranslateScale.Y + TranslateOffset.Y; - - bool flip_faces = ((x1-x0) * (y1-y0)) > 0; - - Begin_Tri_Strip(); - Vertex( x0, y0, 0, u0, v0); - if ( flip_faces ) { - Vertex( x1, y0, 0, u1, v0); - Vertex( x0, y1, 0, u0, v1); - } else { - Vertex( x0, y1, 0, u0, v1); - Vertex( x1, y0, 0, u1, v0); - } - Vertex( x1, y1, 0, u1, v1); - End_Tri_Strip(); -} - -void TextDrawClass::Quad( const RectClass & rect, const RectClass & uv ) -{ - TextDrawClass::Quad( rect.Left, rect.Top, rect.Right, rect.Bottom, uv.Left, uv.Top, uv.Right, uv.Bottom ); -} - -void TextDrawClass::Line( const Vector2 & _a, const Vector2 & _b, float width ) -{ - // Translate coordinates - Vector2 a; - Vector2 b; - a.X = _a.X * TranslateScale.X + TranslateOffset.X; - a.Y = _a.Y * TranslateScale.Y + TranslateOffset.Y; - b.X = _b.X * TranslateScale.X + TranslateOffset.X; - b.Y = _b.Y * TranslateScale.Y + TranslateOffset.Y; - width *= WWMath::Fabs(TranslateScale.X); - - Vector2 corner_offset = a - b; // get line relative to b - float temp = corner_offset.X; // Rotate 90 - corner_offset.X = corner_offset.Y; - corner_offset.Y = -temp; - corner_offset.Normalize(); // scale to length width/2 - corner_offset *= width / 2; - - Begin_Tri_Strip(); - Vertex( a + corner_offset ); - Vertex( a - corner_offset ); - Vertex( b + corner_offset ); - Vertex( b - corner_offset ); - End_Tri_Strip(); -} - -void TextDrawClass::Line_Ends( const Vector2 & a, const Vector2 & b, float width, float end_percent ) -{ - Vector2 a_ = b - a; - a_ *= end_percent; - a_ += a; - Line( a, a_, width ); - Vector2 b_ = a - b; - b_ *= end_percent; - b_ += b; - Line( b, b_, width ); -} - - -/*********************************************************************************************** - * * - * float TextDrawClass::Get_Width( Font3DInstanceClass *, char * ) * - * * - * WARNING: Should not be used to draw characters which need to wrap or have embedded line * - * feeds. * - * * - * Returns the scaled string width in normalized screen unit * - * * - ***********************************************************************************************/ -float TextDrawClass::Get_Width( Font3DInstanceClass *font, const char *message ) -{ - float total_width = 0.0f; - - /* - ** for each character, get_width it - */ - while (*message != 0) { - total_width += font->Char_Spacing( *message++ ); - } - - return total_width; -} - -float TextDrawClass::Get_Inter_Char_Width( Font3DInstanceClass *font ) -{ - // Get rid of this... -// return font->Get_Inter_Char_Spacing(); - return 1; -} - -float TextDrawClass::Get_Height( Font3DInstanceClass *font, const char *message ) -{ - return font->Char_Height(); -} - - -/*********************************************************************************************** - * * - * float TextDrawClass::Print( Font3DInstanceClass *, char, float, float, float ) * - * * - * Draws (actually creates two trianlges to display) a character on the screen at the given * - * normalized screen unit coordinates at the current font scale. * - * * - * Returns the scaled character width in normalized screen unit * - * * - ***********************************************************************************************/ -float TextDrawClass::Print( Font3DInstanceClass *font, char ch, float screen_x, float screen_y ) -{ - /* - ** Get the char width in scaled normalized screen units - */ - float width = font->Char_Width( ch ); // in scaled normalized screen units - float spacing = font->Char_Spacing( ch ); // in scaled normalized screen units - - /* - ** If asked to draw the space char (' '), don't add any triangles, just return the scaled spacing - */ - if (ch == ' ' ) - return spacing; - - /* - ** Calculate the lower right edge of the displayed rectangle - */ - // center each char in its spacing (in case mono spaced ) - // also, round to the nearest 640x480 pixels (needs to change for other reses) - float screen_x0 = screen_x + spacing/2 - width/2; - screen_x0 = floor(screen_x0 / PixelSize.X + 0.5f) * PixelSize.X; - float screen_x1 = screen_x0 + width; - screen_x1 = floor(screen_x1 / PixelSize.X + 0.5f) * PixelSize.X; - float screen_y0 = screen_y; - screen_y0 = floor(screen_y0 / PixelSize.Y + 0.5f) * PixelSize.Y; - float screen_y1 = screen_y0 + (font->Char_Height() * WWMath::Sign( -TranslateScale.Y )); - screen_y1 = floor(screen_y1 / PixelSize.Y + 0.5f) * PixelSize.Y; - - if ( WW3D::Is_Screen_UV_Biased() ) { // Global bais setting - screen_x0 += PixelSize.X / 2; - screen_x1 += PixelSize.X / 2; - screen_y0 += PixelSize.Y / 2; - screen_y1 += PixelSize.Y / 2; - } - - /* - ** Get the font texture uv coordinate for teh upper right and lower left corners of the rect - */ - RectClass font_uv = font->Char_UV( ch ); - - /* - ** Set the triangles' texture - */ - Set_Texture( font->Peek_Texture( ch ) ); - - /* - ** Draw the quad - */ - Quad( screen_x0, screen_y0, screen_x1, screen_y1, font_uv.Left, font_uv.Top, font_uv.Right, font_uv.Bottom ); - - /* - ** return the scaled spacing - */ - return spacing; -} - - -/*********************************************************************************************** - * * - * float TextDrawClass::Print( Font3DInstanceClass *, char *, float, float, float ) * - * * - * Draws the given string at the given pixel coordinates. Uses the given font and its current * - * scale. Passes each character to the above routine and moves the x-coordinate forward after * - * each char. * * - * * - * WARNING: Should not be used to draw characters which need to wrap or have embedded line * - * feeds. * * - * * - * Returns the string pixel width * - * * - ***********************************************************************************************/ -float TextDrawClass::Print( Font3DInstanceClass *font, const char *message, float screen_x, float screen_y ) -{ - /* - ** Keep track of the total drawn width - */ - float total_width = 0.0f; - - /* - ** for each character, print it and moved screen_x forward - */ - while (*message != 0) { - float width = Print( font, *message++, screen_x, screen_y ); - screen_x += width; - total_width += width; - } - - /* - ** return the total drawn width - */ - return total_width; -} - - -/*********************************************************************************************** - * * - * void TextDrawClass::Show_Font( Font3DInstanceClass *, float, float, float ) * - * * - * Dumps the font texture to the screen as two triangles. For debugging only. * - * * - ***********************************************************************************************/ -void TextDrawClass::Show_Font( Font3DInstanceClass *font, float screen_x, float screen_y ) -{ - // normalize coordinates - float size_x = PixelSize.X * 256; - float size_y = PixelSize.Y * 256; - - Set_Texture( font->Peek_Texture('A') ); - - Quad( screen_x, screen_y, screen_x + size_x, screen_y + size_y * WWMath::Sign( -TranslateScale.Y ) ); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textdraw.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textdraw.h deleted file mode 100644 index 21fe760224..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textdraw.h +++ /dev/null @@ -1,120 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /Commando/Code/ww3d2/textdraw.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/15/01 3:41p $* - * * - * $Revision:: 4 $* - * * - *-------------------------------------------------------------------------*/ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef TEXTDRAW_H -#define TEXTDRAW_H - -#include "always.h" -#include "dynamesh.h" - -// sgc : wwlib and wwmath contain different rect.h files... -#include "../WWMath/rect.h" - -class Font3DInstanceClass; - -/****************************************************************** -** -** TextDrawClass -** -** This class provides a simple method to draw 2D text into a scene. -** Both strings and individual characters can be drawn to any normalized -** screen coordinates ( 0.. 1 ), or any scale/offset. -** This class uses a dynamic mesh for all polygon and vertex management -** -*******************************************************************/ - -class TextDrawClass : public DynamicMeshClass -{ - -public: - /* - ** Constructor and Destructor - */ - TextDrawClass( int max_chars ); - ~TextDrawClass(); - - // Set Coordinate Range - void Set_Coordinate_Ranges( const Vector2 & param_ul, const Vector2 & param_lr, - const Vector2 & dest_ul, const Vector2 & dest_lr ); - - // Reset all polys and verts - virtual void Reset( void ); - - /* - ** class id of this render object - */ - virtual int Class_ID(void) const { return CLASSID_TEXTDRAW; } - - /* - ** - */ - float Get_Width( Font3DInstanceClass *font, const char *message ); - float Get_Char_Width( Font3DInstanceClass *font, const char c ); - float Get_Inter_Char_Width( Font3DInstanceClass *font ); - float Get_Height( Font3DInstanceClass *font, const char *message = "" ); - - /* - ** Print the given char/string with the given font at the given loation in screen pixels - ** returns the pixel width of the drawn data. - */ - float Print( Font3DInstanceClass *font, char ch, float screen_x, float screen_y); - float Print( Font3DInstanceClass *font, const char *message, float screen_x, float screen_y); - - void Set_Text_Color( const Vector3 & color ) { Set_Vertex_Color(color); } - - /* - ** dump the font image (debuging) - */ - void Show_Font( Font3DInstanceClass *font, float screen_x, float screen_y ); - - void Quad( float x0, float y0, float x1, float y1, float u0 = 0, float v0 = 0, float u1 = 1, float v1 = 1); - void Quad( const RectClass & rect, const RectClass & uv = RectClass( 0, 0, 1, 1 ) ); - void Line( const Vector2 & a, const Vector2 & b, float width ); - void Line_Ends( const Vector2 & a, const Vector2 & b, float width, float end_percent ); - -private: - Vector3 TextColor; - VertexMaterialClass *DefaultVertexMaterial; - ShaderClass DefaultShader; - Vector2 TranslateScale; - Vector2 TranslateOffset; - Vector2 PixelSize; -}; - -#endif // TEXTDRAW_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp index f6e378694c..af58d03265 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp @@ -94,7 +94,9 @@ TextureClass::TextureClass(unsigned width, unsigned height, WW3DFormat format, M Name(""), TextureFormat(format), IsCompressionAllowed(false), - TextureLoadTask(NULL) + TextureLoadTask(NULL), + Width(width), + Height(height) { switch (format) { @@ -126,8 +128,8 @@ TextureClass::TextureClass(unsigned width, unsigned height, WW3DFormat format, M height, format, mip_level_count, - rendertarget, - this + this, + rendertarget ); DX8TextureManagerClass::Add(track); } @@ -155,7 +157,9 @@ TextureClass::TextureClass IsProcedural(false), TextureFormat(texture_format), IsCompressionAllowed(allow_compression), - TextureLoadTask(NULL) + TextureLoadTask(NULL), + Width(0), + Height(0) { switch (TextureFormat) { @@ -241,10 +245,14 @@ TextureClass::TextureClass(SurfaceClass *surface, MipCountType mip_level_count) IsProcedural(true), TextureFormat(surface->Get_Surface_Format()), IsCompressionAllowed(false), - TextureLoadTask(NULL) + TextureLoadTask(NULL), + Width(0), + Height(0) { SurfaceClass::SurfaceDescription sd; surface->Get_Description(sd); + Width=sd.Width; + Height=sd.Height; switch (sd.Format) { case WW3D_FORMAT_DXT1: @@ -276,14 +284,18 @@ TextureClass::TextureClass(IDirect3DTexture8* d3d_texture) Name(""), IsProcedural(true), IsCompressionAllowed(false), - TextureLoadTask(NULL) + TextureLoadTask(NULL), + Width(0), + Height(0) { D3DTexture->AddRef(); IDirect3DSurface8* surface; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(0,&surface)); + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0,&surface)); D3DSURFACE_DESC d3d_desc; ::ZeroMemory(&d3d_desc, sizeof(D3DSURFACE_DESC)); DX8_ErrorCode(surface->GetDesc(&d3d_desc)); + Width=d3d_desc.Width; + Height=d3d_desc.Height; TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); switch (TextureFormat) { @@ -358,6 +370,35 @@ void TextureClass::Invalidate() } } +//********************************************************************************************** +//! Returns a pointer to the d3d texture +/*! +*/ +IDirect3DBaseTexture8 * TextureClass::Peek_D3D_Base_Texture() const +{ + LastAccessed=WW3D::Get_Sync_Time(); + return D3DTexture; +} + +//********************************************************************************************** +//! Set the d3d texture pointer. Handles ref counts properly. +/*! +*/ +void TextureClass::Set_D3D_Base_Texture(IDirect3DBaseTexture8* tex) +{ + // (gth) Generals does stuff directly with the D3DTexture pointer so lets + // reset the access timer whenever someon messes with this pointer. + LastAccessed=WW3D::Get_Sync_Time(); + + if (D3DTexture != NULL) { + D3DTexture->Release(); + } + D3DTexture = tex; + if (D3DTexture != NULL) { + D3DTexture->AddRef(); + } +} + // ---------------------------------------------------------------------------- void TextureClass::Load_Locked_Surface() @@ -412,7 +453,7 @@ void TextureClass::Get_Level_Description(SurfaceClass::SurfaceDescription &surfa } D3DSURFACE_DESC d3d_surf_desc; - DX8_ErrorCode(D3DTexture->GetLevelDesc(level, &d3d_surf_desc)); + DX8_ErrorCode(Peek_D3D_Texture()->GetLevelDesc(level, &d3d_surf_desc)); surface_desc.Format = D3DFormat_To_WW3DFormat(d3d_surf_desc.Format); surface_desc.Height = d3d_surf_desc.Height; surface_desc.Width = d3d_surf_desc.Width; @@ -423,7 +464,7 @@ void TextureClass::Get_Level_Description(SurfaceClass::SurfaceDescription &surfa SurfaceClass *TextureClass::Get_Surface_Level(unsigned int level) { IDirect3DSurface8 *d3d_surface = NULL; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(level, &d3d_surface)); + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(level, &d3d_surface)); SurfaceClass *surface = W3DNEW SurfaceClass(d3d_surface); d3d_surface->Release(); return surface; @@ -508,12 +549,14 @@ void TextureClass::Apply_New_Surface(bool initialized) WWASSERT(D3DTexture); IDirect3DSurface8* surface; - DX8_ErrorCode(D3DTexture->GetSurfaceLevel(0,&surface)); + DX8_ErrorCode(Peek_D3D_Texture()->GetSurfaceLevel(0,&surface)); D3DSURFACE_DESC d3d_desc; ::ZeroMemory(&d3d_desc, sizeof(D3DSURFACE_DESC)); DX8_ErrorCode(surface->GetDesc(&d3d_desc)); // if (TextureFormat==WW3D_FORMAT_UNKNOWN) { TextureFormat=D3DFormat_To_WW3DFormat(d3d_desc.Format); + Width=d3d_desc.Width; + Height=d3d_desc.Height; // } // else { // WWASSERT(D3DFormat_To_WW3DFormat(d3d_desc.Format)==TextureFormat); diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h index a3395a3a9e..bfc67c16d7 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/texture.h @@ -50,8 +50,10 @@ #include "wwstring.h" #include "texturefilter.h" -class DX8Wrapper; +struct IDirect3DBaseTexture8; struct IDirect3DTexture8; + +class DX8Wrapper; class TextureLoader; class LoaderThreadClass; class DX8TextureManagerClass; @@ -69,6 +71,8 @@ class TextureClass : public W3DMPO, public RefCountClass { W3DMPO_GLUE(TextureClass) + friend class DX8TextureTrackerClass; //(gth) so it can call Poke_Texture, + friend DX8Wrapper; friend TextureLoader; friend LoaderThreadClass; @@ -82,6 +86,11 @@ class TextureClass : public W3DMPO, public RefCountClass POOL_SYSTEMMEM }; + enum TexAssetType + { + TEX_REGULAR, + }; + // Create texture with desired height, width and format. TextureClass( unsigned width, @@ -108,6 +117,8 @@ class TextureClass : public W3DMPO, public RefCountClass TextureClass(IDirect3DTexture8* d3d_texture); + virtual TexAssetType Get_Asset_Type() const { return TEX_REGULAR; } + virtual ~TextureClass(void); // Names @@ -120,6 +131,16 @@ class TextureClass : public W3DMPO, public RefCountClass // The number of Mip levels in the texture unsigned int Get_Mip_Level_Count(void); + + // Note! Width and Height may be zero and may change if texture uses mipmaps + int Get_Width() const + { + return Width; + } + int Get_Height() const + { + return Height; + } // Get surface description of a Mip level (defaults to the highest-resolution one) void Get_Level_Description(SurfaceClass::SurfaceDescription &surface_desc, unsigned int level = 0); @@ -155,15 +176,19 @@ class TextureClass : public W3DMPO, public RefCountClass // This utility function processes the texture reduction (used during rendering) void Invalidate(); - IDirect3DTexture8 *Peek_D3D_Texture() - { - return D3DTexture; - } + IDirect3DTexture8 *Peek_D3D_Texture() const { return (IDirect3DTexture8 *)Peek_D3D_Base_Texture(); } + + // texture accessors (dx8) + IDirect3DBaseTexture8 *Peek_D3D_Base_Texture() const; + void Set_D3D_Base_Texture(IDirect3DBaseTexture8* tex); + + PoolType Get_Pool() const { return Pool; } bool Is_Missing_Texture(); // Support for self managed textures bool Is_Dirty() { WWASSERT(Pool==POOL_DEFAULT); return Dirty; }; + void Set_Dirty() { WWASSERT(Pool==POOL_DEFAULT); Dirty=true; } void Clean() { Dirty=false; }; unsigned Get_Reduction() const; @@ -171,6 +196,8 @@ class TextureClass : public W3DMPO, public RefCountClass bool Is_Compression_Allowed() const { return IsCompressionAllowed; } protected: + void Poke_Texture(IDirect3DBaseTexture8* tex) { D3DTexture = tex; } + // Apply this texture's settings into D3D virtual void Apply(unsigned int stage); void Load_Locked_Surface(); @@ -184,7 +211,7 @@ class TextureClass : public W3DMPO, public RefCountClass TextureFilterClass Filter; // Direct3D texture object - IDirect3DTexture8 *D3DTexture; + IDirect3DBaseTexture8 *D3DTexture; bool Initialized; // Name @@ -205,9 +232,12 @@ class TextureClass : public W3DMPO, public RefCountClass bool IsProcedural; bool IsCompressionAllowed; - unsigned LastAccessed; + mutable unsigned LastAccessed; WW3DFormat TextureFormat; + int Width; + int Height; + // Support for self-managed textures PoolType Pool; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp index d8a43ee686..eda68049a0 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/textureloader.cpp @@ -72,9 +72,8 @@ static bool Is_Format_Compressed(WW3DFormat texture_format,bool allow_compressio // If hardware supports DXTC compression, load a compressed texture. Proceed only if the texture format hasn't been // defined as non-compressed. compressed|=( - texture_format==WW3D_FORMAT_UNKNOWN && - DX8Wrapper::Get_Current_Caps()->Support_DXTC() && - WW3D::Get_Texture_Compression_Mode()==WW3D::TEXTURE_COMPRESSION_ENABLE && + texture_format==WW3D_FORMAT_UNKNOWN && + DX8Wrapper::Get_Current_Caps()->Support_DXTC() && allow_compression); return compressed; @@ -1115,10 +1114,10 @@ void TextureLoadTaskClass::Begin_Texture_Load() MipLevels++; //Adjust the reduction factor to keep textures above some minimum dimensions - if (MipLevels <= WW3D::Get_Texture_Min_Mip_Levels()) + if (MipLevels <= WW3D::Get_Texture_Min_Dimension()) ReductionFactor=0; else - { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Mip_Levels(); + { int mipToDrop=MipLevels-WW3D::Get_Texture_Min_Dimension(); if (ReductionFactor >= mipToDrop) ReductionFactor=mipToDrop; } diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp deleted file mode 100644 index 123f12a15a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.cpp +++ /dev/null @@ -1,730 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/visrasterizer.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 11/24/01 5:42p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "visrasterizer.h" -#include "camera.h" -#include "plane.h" -#include "vp.h" - - -/** -** VisPolyClass - This class is used to clip polygons as they are -** sent through the vis rasterization system -*/ -class VisPolyClass -{ -public: - void Reset(void); - void Add_Vertex(const Vector3 & point); - void Clip(const PlaneClass & plane,VisPolyClass & dest) const; - - SimpleDynVecClass Verts; -}; - - -void VisPolyClass::Reset(void) -{ - Verts.Delete_All(false); -} - -void VisPolyClass::Add_Vertex(const Vector3 & point) -{ - Verts.Add(point); -} - -void VisPolyClass::Clip(const PlaneClass & plane,VisPolyClass & dest) const -{ - dest.Reset(); - - // temporary variables used in clipping - int i = 0; - int vcount = Verts.Count(); - int iprev = vcount - 1; - bool cur_point_in_front; - bool prev_point_in_front; - float alpha; - Vector3 int_point; - - if (vcount <= 2) return; - - // perform clipping - prev_point_in_front = !plane.In_Front(Verts[iprev]); // Note, plane normal is outward so we invert this test - for (int j=0; j=vcount) { - i = 0; - } - } -} - -static VisPolyClass _VisPoly0; -static VisPolyClass _VisPoly1; - - - -/********************************************************************************************* - - VisRasterizerClass Implementation - -*********************************************************************************************/ - - -VisRasterizerClass::VisRasterizerClass(void) : - ModelTransform(1), - Camera(NULL), - MVTransform(1) -{ -} - -VisRasterizerClass::~VisRasterizerClass(void) -{ - REF_PTR_RELEASE(Camera); -} - -void VisRasterizerClass::Set_Resolution(int width,int height) -{ - IDBuffer.Set_Resolution(width,height); -} - -void VisRasterizerClass::Get_Resolution(int * set_width,int * set_height) -{ - IDBuffer.Get_Resolution(set_width,set_height); -} - -void VisRasterizerClass::Set_Model_Transform(const Matrix3D & model) -{ - ModelTransform = model; - Update_MV_Transform(); -} - -void VisRasterizerClass::Set_Camera(CameraClass * camera) -{ - REF_PTR_SET(Camera,camera); - Update_MV_Transform(); -} - -CameraClass * VisRasterizerClass::Get_Camera(void) -{ - if (Camera != NULL) { - Camera->Add_Ref(); - } - return Camera; -} - -CameraClass * VisRasterizerClass::Peek_Camera(void) -{ - return Camera; -} - -void VisRasterizerClass::Update_MV_Transform(void) -{ - Matrix3D view_tm(1); - - if (Camera) { - Camera->Get_View_Matrix(&view_tm); - } - -#ifdef ALLOW_TEMPORARIES - MVTransform = view_tm * ModelTransform; -#else - MVTransform.mul(view_tm, ModelTransform); -#endif -} - -const Matrix3D & VisRasterizerClass::Get_MV_Transform(void) -{ - // TODO: optimize this - Update_MV_Transform(); // the user can and does mess with the camera directly! - return MVTransform; -} - -Vector3 * VisRasterizerClass::Get_Temp_Vertex_Buffer(int count) -{ - TempVertexBuffer.Uninitialised_Grow(count); - return &(TempVertexBuffer[0]); -} - - -bool VisRasterizerClass::Render_Triangles -( - const Vector3 * verts, - int vcount, - const TriIndex * tris, - int tcount,const - AABoxClass & bounds -) -{ - WWASSERT(verts != NULL); - WWASSERT(tris != NULL); - WWASSERT(vcount > 0); - WWASSERT(tcount > 0); - - /* - ** if the user supplied bounds, check if we need to clip - */ - if (CollisionMath::Overlap_Test(Camera->Get_Frustum(),bounds) == CollisionMath::INSIDE) { - return Render_Triangles_No_Clip(verts,vcount,tris,tcount); - } else { - return Render_Triangles_Clip(verts,vcount,tris,tcount); - } -} - - -bool VisRasterizerClass::Render_Triangles_No_Clip -( - const Vector3 * verts, - int vcount, - const TriIndex * tris, - int tcount -) -{ - bool pixel_passed = false; - - /* - ** 1. transform verts into homogeneous view space and project - */ - const Matrix3D & tm = Get_MV_Transform(); - Vector3 * tverts = Get_Temp_Vertex_Buffer(vcount); - - VectorProcessorClass::Transform(tverts,verts,tm,vcount); - - for (int i=0; iProject_Camera_Space_Point(tverts[i],tverts[i]); - } - - /* - ** 2. Pass triangles on to the ID buffer for scan conversion - */ - for (int tri_index=0; tri_indexGet_View_Space_Frustum_Planes(); - - /* - ** 3. Clip triangles to the view volume and pass on to the ID buffer for scan conversion - */ - for (int tri_index=0; tri_index= 3) { - - Vector3 * final_verts = &(_VisPoly0.Verts[0]); - - int i; - for (i=0; iProject_Camera_Space_Point(final_verts[i],final_verts[i]); - } - - /* - ** Pass the resulting triangle fan to the IDBuffer - */ - for (i=1; i 0) { - IDBuffer = W3DNEWARRAY uint32 [bufsize]; - ZBuffer = W3DNEWARRAY float [bufsize]; - } -} - -void IDBufferClass::Clear(void) -{ - if ((ResWidth > 0) && (ResHeight > 0)) { - int byte_count = ResWidth * ResWidth * sizeof(uint32); - - WWASSERT(IDBuffer != NULL); - WWASSERT(ZBuffer != NULL); - memset(IDBuffer,0,byte_count); - memset(ZBuffer,0,byte_count); - } -} - - -/** -** GradientsStruct -** Computes the gradients for a triangle. -*/ -struct GradientsStruct -{ - GradientsStruct(const Vector3 * verts) - { - float oodx = 1 / ( ((verts[1].X - verts[2].X) * (verts[0].Y - verts[2].Y)) - - ((verts[0].X - verts[2].X) * (verts[1].Y - verts[2].Y))); - float oody = -oodx; - - for(int i=0; i<3; i++) { - OOZ[i] = 1/verts[i].Z; - } - - DOOZ_DX = oodx * ( ((OOZ[1] - OOZ[2]) * (verts[0].Y - verts[2].Y)) - - ((OOZ[0] - OOZ[2]) * (verts[1].Y - verts[2].Y))); - - DOOZ_DY = oody * ( ((OOZ[1] - OOZ[2]) * (verts[0].X - verts[2].X)) - - ((OOZ[0] - OOZ[2]) * (verts[1].X - verts[2].X))); - } - - float OOZ[3]; // 1/z for each vertex - float DOOZ_DX; // change in 1/z per change in x - float DOOZ_DY; // change in 1/z per change in y -}; - - -/** -** EdgeStruct -** Can accurately scan convert an edge of a triangle. -*/ -struct EdgeStruct -{ - EdgeStruct(const GradientsStruct & grad,const Vector3 * verts,int top,int bottom) - { - Y = WWMath::Ceil(verts[top].Y); - Height = WWMath::Ceil(verts[bottom].Y) - Y; - - float y_prestep = Y - verts[top].Y; - float real_height = verts[bottom].Y - verts[top].Y; - float real_width = verts[bottom].X - verts[top].X; - - X = ((real_width * y_prestep)/real_height) + verts[top].X; - XStep = real_width / real_height; - float x_prestep = X - verts[top].X; - - OOZ = grad.OOZ[top] + y_prestep * grad.DOOZ_DY + x_prestep * grad.DOOZ_DX; - OOZStep = XStep * grad.DOOZ_DX + grad.DOOZ_DY; - } - - inline int Step(void) - { - X+=XStep; - Y++; - Height--; - OOZ+=OOZStep; - return Height; - } - - float X; // fractional x coord - float XStep; // change in x per scanline - int Y; // current y coord - int Height; // number of scanlines left - float OOZ; // current 1/z - float OOZStep; // change in 1/z per scanline -}; - - -bool IDBufferClass::Render_Triangle(const Vector3 & p0,const Vector3 & p1,const Vector3 & p2) -{ - if ((ZBuffer == NULL) || (IDBuffer == NULL)) { - return false; - } - - int pixels_passed = 0; - bool is_backfacing = Is_Backfacing(p0,p1,p2); - - if ((is_backfacing) && (TwoSidedRenderingEnabled == false)) { - if (RenderMode == NON_OCCLUDER_MODE) { - return false; - } - CurID = BackfaceID; - } else { - CurID = FrontfaceID; - } - - - - /* - ** Transform the coordinates to device coords - ** All coordinates come in with the range -1 -> +1 - */ - Vector3 points[3]; - points[0].X = 0.5f * (p0.X + 1.0f) * ResWidth; - points[1].X = 0.5f * (p1.X + 1.0f) * ResWidth; - points[2].X = 0.5f * (p2.X + 1.0f) * ResWidth; - - points[0].Y = 0.5f * (1.0f - p0.Y) * ResHeight; - points[1].Y = 0.5f * (1.0f - p1.Y) * ResHeight; - points[2].Y = 0.5f * (1.0f - p2.Y) * ResHeight; - - points[0].Z = 0.5f * (p0.Z + 1.001f) * 1000.0f; - points[1].Z = 0.5f * (p1.Z + 1.001f) * 1000.0f; - points[2].Z = 0.5f * (p2.Z + 1.001f) * 1000.0f; - - /* - ** Sort points based on Y - */ - float y0 = points[0].Y; - float y1 = points[1].Y; - float y2 = points[2].Y; - - int top,middle,bottom,middle_for_compare,bottom_for_compare; - - if(y0 < y1) { - if(y2 < y0) { - top = 2; middle = 0; bottom = 1; - middle_for_compare = 0; bottom_for_compare = 1; - } else { - top = 0; - if(y1 < y2) { - middle = 1; bottom = 2; - middle_for_compare = 1; bottom_for_compare = 2; - } else { - middle = 2; bottom = 1; - middle_for_compare = 2; bottom_for_compare = 1; - } - } - } else { - if(y2 < y1) { - top = 2; middle = 1; bottom = 0; - middle_for_compare = 1; bottom_for_compare = 0; - } else { - top = 1; - if(y0 < y2) { - middle = 0; bottom = 2; - middle_for_compare = 3; bottom_for_compare = 2; - } else { - middle = 2; bottom = 0; - middle_for_compare = 2; bottom_for_compare = 3; - } - } - } - - /* - ** Compute the gradients and set up the edge structures - */ - GradientsStruct grads(points); - EdgeStruct top_to_bottom_edge(grads,points,top,bottom); - EdgeStruct top_to_middle_edge(grads,points,top,middle); - EdgeStruct middle_to_bottom_edge(grads,points,middle,bottom); - - EdgeStruct * left_edge = NULL; - EdgeStruct * right_edge = NULL; - - bool middle_is_left = false; - if (bottom_for_compare > middle_for_compare) { - middle_is_left = 1 ^ is_backfacing; - } else { - middle_is_left = 0 ^ is_backfacing; - } - if (middle_is_left) { - left_edge = &top_to_middle_edge; - right_edge = &top_to_bottom_edge; - } else { - left_edge = &top_to_bottom_edge; - right_edge = &top_to_middle_edge; - } - - /* - ** Fill scanlines - */ - int height = top_to_middle_edge.Height; - - while (height--) { - if (RenderMode == OCCLUDER_MODE) { - pixels_passed += Render_Occluder_Scanline(grads,left_edge,right_edge); - } else { - pixels_passed += Render_Non_Occluder_Scanline(grads,left_edge,right_edge); - } - left_edge->Step(); - right_edge->Step(); - } - - if (middle_is_left) { - left_edge = &middle_to_bottom_edge; - right_edge = &top_to_bottom_edge; - } else { - left_edge = &top_to_bottom_edge; - right_edge = &middle_to_bottom_edge; - } - - height = middle_to_bottom_edge.Height; - - while (height--) { - if (RenderMode == OCCLUDER_MODE) { - pixels_passed += Render_Occluder_Scanline(grads,left_edge,right_edge); - } else { - pixels_passed += Render_Non_Occluder_Scanline(grads,left_edge,right_edge); - } - left_edge->Step(); - right_edge->Step(); - } - return (pixels_passed > 0); -} - - -int IDBufferClass::Render_Occluder_Scanline(GradientsStruct & grads,EdgeStruct * left,EdgeStruct * right) -{ - if ((left->Y < 1) || (left->Y >= ResHeight)) { - return 0; - } - - int xstart = WWMath::Float_To_Long(WWMath::Max(WWMath::Ceil(left->X),1.0f)); - int width = WWMath::Float_To_Long(WWMath::Ceil(right->X)) - xstart; - if (xstart + width > ResWidth) { - width = ResWidth - xstart; - } - - float xprestep = (float)xstart - left->X; - int address = Pixel_Coords_To_Address(xstart,left->Y); - float ooz = left->OOZ + xprestep * grads.DOOZ_DX; - int pixel_counter = 0; - - /* - ** Two separate loops, backfaces only render when LESS THAN - */ - if (CurID == BackfaceID) { - while (width-- > 0) { - if (ooz > ZBuffer[address]) { - IDBuffer[address] = CurID; - ZBuffer[address] = ooz; - pixel_counter++; - } - ooz += grads.DOOZ_DX; - address++; - } - /* - ** Front faces render when LESS THAN OR EQUAL TO - */ - } else { - while (width-- > 0) { - if (ooz >= ZBuffer[address]) { - IDBuffer[address] = CurID; - ZBuffer[address] = ooz; - pixel_counter++; - } - ooz += grads.DOOZ_DX; - address++; - } - } - - PixelCounter += pixel_counter; - return pixel_counter; -} - - -int IDBufferClass::Render_Non_Occluder_Scanline(GradientsStruct & grads,EdgeStruct * left,EdgeStruct * right) -{ - if ((left->Y < 1) || (left->Y >= ResHeight)) { - return 0; - } - - int xstart = WWMath::Float_To_Long(WWMath::Max(WWMath::Ceil(left->X),1)); - int width = WWMath::Float_To_Long(WWMath::Ceil(right->X)) - xstart; - if (xstart + width > ResWidth) { - width = ResWidth - xstart; - } - - float xprestep = (float)xstart - left->X; - int address = Pixel_Coords_To_Address(xstart,left->Y); - float ooz = left->OOZ + xprestep * grads.DOOZ_DX; - - while (width-- > 0) { - if (ooz >= ZBuffer[address]) { - PixelCounter++; - return 1; - } - ooz += grads.DOOZ_DX; - address++; - } - - return 0; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.h deleted file mode 100644 index 84fc42fd9e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/visrasterizer.h +++ /dev/null @@ -1,213 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : ww3d * - * * - * $Archive:: /Commando/Code/ww3d2/visrasterizer.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 11/24/01 5:42p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VISRASTERIZER_H -#define VISRASTERIZER_H - -#include "always.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "Vector3i.h" -#include "vector3.h" -#include "simplevec.h" -#include "bittype.h" -#include "plane.h" -#include "meshgeometry.h" - - -class CameraClass; -class AABoxClass; -struct GradientsStruct; -struct EdgeStruct; - -/** -** IDBufferClass -** This class manages the ID buffer and the Z buffer. It provides the low level -** rasterization code and stats about how many pixels and triangles are drawn. -*/ -class IDBufferClass -{ -public: - IDBufferClass(void); - ~IDBufferClass(void); - - /* - ** State interface - */ - void Set_Resolution(int w,int h); - void Get_Resolution(int * get_w,int * get_h); - - void Set_Backface_ID(uint32 id) { BackfaceID = id; } - void Set_Frontface_ID(uint32 id) { FrontfaceID = id; } - uint32 Get_Backface_ID(void) { return BackfaceID; } - uint32 Get_Frontface_ID(void) { return FrontfaceID; } - - void Enable_Two_Sided_Rendering(bool onoff) { TwoSidedRenderingEnabled = onoff; } - bool Is_Two_Sided_Rendering_Enabled(void) { return TwoSidedRenderingEnabled; } - - enum ModeType { OCCLUDER_MODE = 0, NON_OCCLUDER_MODE }; - void Set_Render_Mode(ModeType mode) { RenderMode = mode; } - ModeType Get_Render_Mode(void) { return RenderMode; } - - void Reset_Pixel_Counter(void) { PixelCounter = 0; } - int Get_Pixel_Counter(void) { return PixelCounter; } - - /* - ** Rendering interface - */ - void Clear(void); - bool Render_Triangle(const Vector3 & p0,const Vector3 & p1,const Vector3 & p2); - const uint32 * Get_Pixel_Row(int y,int min_x,int max_x); - -protected: - void Reset(void); - void Allocate_Buffers(void); - bool Is_Backfacing(const Vector3 & p0,const Vector3 & p1,const Vector3 & p2); - int Render_Occluder_Scanline(GradientsStruct & grads,EdgeStruct * left,EdgeStruct * right); - int Render_Non_Occluder_Scanline(GradientsStruct & grads,EdgeStruct * left,EdgeStruct * right); - int Pixel_Coords_To_Address(int x,int y) { return y*ResWidth + x; } - - uint32 BackfaceID; - uint32 FrontfaceID; - uint32 CurID; - int PixelCounter; - ModeType RenderMode; - bool TwoSidedRenderingEnabled; - - int ResWidth; - int ResHeight; - uint32 * IDBuffer; - float * ZBuffer; // actually a 1/z buffer... -}; - -inline const uint32 * IDBufferClass::Get_Pixel_Row(int y,int min_x,int max_x) -{ - WWASSERT(y>=0); - WWASSERT(y=0); - WWASSERT(max_x<=ResWidth); - - int addr = Pixel_Coords_To_Address(min_x,y); - return &(IDBuffer[addr]); -} - -inline bool IDBufferClass::Is_Backfacing(const Vector3 & p0,const Vector3 & p1,const Vector3 & p2) -{ - float x1=p1[0]-p0[0]; - float y1=p1[1]-p0[1]; - float x2=p2[0]-p0[0]; - float y2=p2[1]-p0[1]; - float r=x1*y2-x2*y1; - if (r<0.0f) return true; - return false; -} - - - - -/** -** VisRasterizerClass -** This class encapsulates the "ID buffer rasterization" code needed by the vis system. Basically -** it is a floating point z-buffer and an id buffer which is used by the visiblity precalculation system. -** The VisRasterizer will transform and clip triangles into homogeneous view space; then the clipped -** triangles will be passed on to the IDBufferClass which will scan convert them. -*/ -class VisRasterizerClass -{ -public: - - VisRasterizerClass(void); - ~VisRasterizerClass(void); - - /* - ** ID Buffer Interface - */ - void Set_Render_Mode(IDBufferClass::ModeType mode) { IDBuffer.Set_Render_Mode(mode); } - IDBufferClass::ModeType Get_Render_Mode(void) { return IDBuffer.Get_Render_Mode(); } - - void Set_Backface_ID(uint32 id) { IDBuffer.Set_Backface_ID(id); } - void Set_Frontface_ID(uint32 id) { IDBuffer.Set_Frontface_ID(id); } - uint32 Get_Backface_ID(void) { return IDBuffer.Get_Backface_ID(); } - uint32 Get_Frontface_ID(void) { return IDBuffer.Get_Frontface_ID(); } - - void Enable_Two_Sided_Rendering(bool onoff) { IDBuffer.Enable_Two_Sided_Rendering(onoff); } - bool Is_Two_Sided_Rendering_Enabled(void) { return IDBuffer.Is_Two_Sided_Rendering_Enabled(); } - - void Set_Resolution(int width,int height); - void Get_Resolution(int * set_width,int * set_height); - - void Reset_Pixel_Counter(void) { IDBuffer.Reset_Pixel_Counter(); } - int Get_Pixel_Counter(void) { return IDBuffer.Get_Pixel_Counter(); } - - /* - ** Rendering Interface - */ - void Set_Model_Transform(const Matrix3D & model); - void Set_Camera(CameraClass * camera); - - const Matrix3D & Get_Model_Transform(void); - CameraClass * Get_Camera(void); - CameraClass * Peek_Camera(void); - - void Clear(void) { IDBuffer.Clear(); } - bool Render_Triangles(const Vector3 * verts,int vcount,const TriIndex * tris, int tcount,const AABoxClass & bounds); - const uint32 * Get_Pixel_Row(int y,int min_x,int max_x) { return IDBuffer.Get_Pixel_Row(y,min_x,max_x); } - -protected: - - void Update_MV_Transform(void); - const Matrix3D & Get_MV_Transform(void); - Vector3 * Get_Temp_Vertex_Buffer(int count); - bool Render_Triangles_Clip(const Vector3 * verts,int vcount,const TriIndex * tris, int tcount); - bool Render_Triangles_No_Clip(const Vector3 * verts,int vcount,const TriIndex * tris, int tcount); - - Matrix3D ModelTransform; // AKA "World Transform" - CameraClass * Camera; - Matrix3D MVTransform; - - IDBufferClass IDBuffer; - - SimpleVecClass TempVertexBuffer; -}; - -#endif //VISRASTERIZER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp deleted file mode 100644 index 9cb674162e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.cpp +++ /dev/null @@ -1,575 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/w3d_dep.cpp $* - * * - * $Author:: Byon_g $* - * * - * $Modtime:: 7/23/01 6:17p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Get_W3D_Dependencies -- Scans a W3D file to determine which other files it depends on. * - * Scan_Chunk -- Chooses the correct chunk loader for this chunk. * - * Scan_Mesh -- Scans a mesh for references to other files. * - * Scan_Mesh_Header -- Scans a mesh's header for file references. * - * Scan_Mesh_Textures -- Scans a mesh's textures. * - * Scan_HTree -- Scans an HTree for references to other files. * - * Scan_Anim -- Scans an animation for references to other files. * - * Scan_Compressed_Anim -- Scans an animation for references to other files. * - * Scan_HModel -- Scans an HModel for references to other files. * - * Scan_Emitter -- Scans an emitter for references to other files. * - * Scan_Aggregate -- Scans an aggregate for references to other files. * - * Scan_HLOD -- Scans an HLOD for references to other files. * - * Get_W3D_Name -- Gets a W3D object name from a W3D filename. * - * Make_W3D_Filename -- Converts a W3D object name into a W3D filename. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -//----------------------------------------------------------------------------- -// srj sez: hack festival :-( -class STLSpecialAlloc -{ -public: - // this one is needed for proper simple_alloc wrapping - static void* allocate(size_t __n) { return ::operator new(__n); } - static void deallocate(void* __p, size_t) { ::operator delete(__p); } -}; - - -#include "w3d_dep.h" -#include "w3d_file.h" -#include -#include -#include "ffactory.h" - - -/* -** Forward declarations. -*/ - -static void Scan_Chunk (ChunkLoadClass &cload, StringList &files, const char *w3d_name); - -static void Scan_Mesh (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_Mesh_Header (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_Mesh_Textures (ChunkLoadClass &cload, StringList &files, const char *w3d_name); - -static void Scan_Anim (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_Compressed_Anim (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_HModel (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_Emitter (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_Aggregate (ChunkLoadClass &cload, StringList &files, const char *w3d_name); -static void Scan_HLOD (ChunkLoadClass &cload, StringList &files, const char *w3d_name); - -static void Get_W3D_Name (const char *filename, char *w3d_name); -static const char * Make_W3D_Filename (const char *w3d_name); - - -/*********************************************************************************************** - * Get_W3D_Dependencies -- Scans a W3D file to determine which other files it depends on. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/3/00 AJA : Created. * - *=============================================================================================*/ -bool Get_W3D_Dependencies (const char *w3d_filename, StringList &files) -{ - assert(w3d_filename); - - // Open the W3D file. - FileClass *file=_TheFileFactory->Get_File(w3d_filename); - if ( file ) { - file->Open(); - if ( ! file->Is_Open()) { - _TheFileFactory->Return_File(file); - file=NULL; - return false; - } - } else { - return false; - } - - // Get the W3D name from the filename. - char w3d_name[W3D_NAME_LEN]; - Get_W3D_Name(w3d_filename, w3d_name); - - // Create a chunk loader for this file, and scan the file. - ChunkLoadClass cload(file); - while (cload.Open_Chunk()) - { - Scan_Chunk(cload, files, w3d_name); - cload.Close_Chunk(); - } - - // Close the file. - file->Close(); - _TheFileFactory->Return_File(file); - file=NULL; - - // Sort the set of filenames, and remove any duplicates. - files.sort(); - files.unique(); - - return true; -} - - -/*********************************************************************************************** - * Scan_Chunk -- Chooses the correct chunk loader for this chunk. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/3/00 AJA : Created. * - *=============================================================================================*/ -static void Scan_Chunk (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - assert(w3d_name); - - switch (cload.Cur_Chunk_ID()) - { - case W3D_CHUNK_MESH: - Scan_Mesh(cload, files, w3d_name); - break; - - case W3D_CHUNK_ANIMATION: - Scan_Anim(cload, files, w3d_name); - break; - - case W3D_CHUNK_COMPRESSED_ANIMATION: - Scan_Compressed_Anim(cload, files, w3d_name); - break; - - case W3D_CHUNK_HMODEL: - Scan_HModel(cload, files, w3d_name); - break; - - case W3D_CHUNK_EMITTER: - Scan_Emitter(cload, files, w3d_name); - break; - - case W3D_CHUNK_AGGREGATE: - Scan_Aggregate(cload, files, w3d_name); - break; - - case W3D_CHUNK_HLOD: - Scan_HLOD(cload, files, w3d_name); - break; - } -} - - -/*********************************************************************************************** - * Scan_Mesh -- Scans a mesh for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_Mesh (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - // Scan the mesh's sub-chunks. - while (cload.Open_Chunk()) - { - switch (cload.Cur_Chunk_ID()) - { - case W3D_CHUNK_MESH_HEADER3: - // Ahh, the mesh header. - Scan_Mesh_Header(cload, files, w3d_name); - break; - - case W3D_CHUNK_TEXTURES: - // We sure want textures... - Scan_Mesh_Textures(cload, files, w3d_name); - break; - } - cload.Close_Chunk(); - } -} - -/*********************************************************************************************** - * Scan_Mesh_Header -- Scans a mesh's header for file references. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/3/00 AJA : Created. * - *=============================================================================================*/ -static void Scan_Mesh_Header (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - // In the mesh header, we want the 'ContainerName' string. - W3dMeshHeader3Struct hdr; - cload.Read(&hdr, sizeof(hdr)); - if (strcmp(hdr.ContainerName, w3d_name) != 0) - { - // The container is not this file... Create a W3D filename - // for the container object and add it to the list of - // files we refer to. - const char *filename = Make_W3D_Filename(hdr.ContainerName); - if (*filename) // don't push empty filenames - files.push_back(filename); - } -} - -/*********************************************************************************************** - * Scan_Mesh_Textures -- Scans a mesh's textures. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/3/00 AJA : Created. * - *=============================================================================================*/ -static void Scan_Mesh_Textures (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - // Let's see which textures are used by this mesh... - while (cload.Open_Chunk()) - { - // We're interested in the TEXTURE sub-chunk. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_TEXTURE) - { - while (cload.Open_Chunk()) - { - // We're interested in the TEXTURE_NAME sub-chunk. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_TEXTURE_NAME) - { - // This chunk's data is a NULL-terminated string - // which is the texture filename. Read it and - // add it to the list of files referred to. - char texture[_MAX_PATH]; - cload.Read(texture, cload.Cur_Chunk_Length()); - if (*texture) // don't push empty filenames - files.push_back(texture); - } - cload.Close_Chunk(); - } - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Scan_Anim -- Scans an animation for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_Anim (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - while (cload.Open_Chunk()) - { - // We only want the animation header, because it can refer to an HTree. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_ANIMATION_HEADER) - { - // Read in the header. - W3dAnimHeaderStruct hdr; - cload.Read(&hdr, sizeof(hdr)); - if (strcmp(hdr.HierarchyName, w3d_name) != 0) - { - const char *hierarchy = Make_W3D_Filename(hdr.HierarchyName); - if (*hierarchy) // don't push an empty filename - files.push_back(hierarchy); - } - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Scan_Compressed_Anim -- Scans a compressed animation mesh for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_Compressed_Anim (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - while (cload.Open_Chunk()) - { - // We only want the animation header, because it can refer to an HTree. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_ANIMATION_HEADER) - { - // Read in the header. - W3dCompressedAnimHeaderStruct hdr; - cload.Read(&hdr, sizeof(hdr)); - if (strcmp(hdr.HierarchyName, w3d_name) != 0) - { - const char *hierarchy = Make_W3D_Filename(hdr.HierarchyName); - if (*hierarchy) // don't push an empty filename - files.push_back(hierarchy); - } - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Scan_HModel -- Scans an HModel for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_HModel (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - while (cload.Open_Chunk()) - { - // We only want the header because it can refer to an HTree. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_HMODEL_HEADER) - { - // Read in the header. - W3dHModelHeaderStruct hdr; - cload.Read(&hdr, sizeof(hdr)); - if (strcmp(hdr.HierarchyName, w3d_name) != 0) - { - const char *hierarchy = Make_W3D_Filename(hdr.HierarchyName); - if (*hierarchy) // don't push an empty filename - files.push_back(hierarchy); - } - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Scan_Emitter -- Scans an emitter for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_Emitter (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - while (cload.Open_Chunk()) - { - // We only want the emitter info chunk, it has a texture name in it. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_EMITTER_INFO) - { - // Read in the header. - W3dEmitterInfoStruct hdr; - cload.Read(&hdr, sizeof(hdr)); - if (hdr.TextureFilename[0]) // don't push an empty texture name - files.push_back(hdr.TextureFilename); - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Scan_Aggregate -- Scans an aggregate for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_Aggregate (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - while (cload.Open_Chunk()) - { - // We want the aggregate info chunk. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_AGGREGATE_INFO) - { - W3dAggregateInfoStruct chunk; - cload.Read(&chunk, sizeof(chunk)); - if (strcmp(chunk.BaseModelName, w3d_name) != 0) - { - // Check the name of the base model against the name of this file. - const char *base_model = Make_W3D_Filename(chunk.BaseModelName); - if (*base_model) - files.push_back(base_model); - } - - // Iterate through the sub-objects. - unsigned int i; - for (i = 0; i < chunk.SubobjectCount; ++i) - { - W3dAggregateSubobjectStruct subchunk; - cload.Read(&subchunk, sizeof(subchunk)); - if (strcmp(subchunk.SubobjectName, w3d_name) != 0) - { - // Check the name of the subobject against the name of this file. - const char *subobject = Make_W3D_Filename(subchunk.SubobjectName); - if (*subobject) - files.push_back(subobject); - } - } - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Scan_HLOD -- Scans an HLOD for references to other files. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -static void Scan_HLOD (ChunkLoadClass &cload, StringList &files, const char *w3d_name) -{ - while (cload.Open_Chunk()) - { - // We only want the header. - if (cload.Cur_Chunk_ID() == W3D_CHUNK_HLOD_HEADER) - { - W3dHLodHeaderStruct hdr; - cload.Read(&hdr, sizeof(hdr)); - if (strcmp(hdr.HierarchyName, w3d_name) != 0) - { - const char *hierarchy = Make_W3D_Filename(hdr.HierarchyName); - if (*hierarchy) - files.push_back(hierarchy); - } - } - cload.Close_Chunk(); - } -} - - -/*********************************************************************************************** - * Get_W3D_Name -- Gets a W3D object name from a W3D filename. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/3/00 AJA : Created. * - *=============================================================================================*/ -static void Get_W3D_Name (const char *filename, char *w3d_name) -{ - assert(filename); - assert(w3d_name); - - // Figure out the first character of the name of the file - // (bypass the path if it was given). - const char *start = strrchr(filename, '\\'); - if (start) - ++start; // point to first character after the last backslash - else - start = filename; // point to the start of the filename - - // We don't want to copy the .w3d extension. Find where - // it occurs. - const char *end = strrchr(start, '.'); - if (!end) - end = start + strlen(start); // point to the null character - - // Copy all characters from start to end (excluding 'end') - // into the w3d_name buffer. Then capitalize the string. - memset(w3d_name, 0, W3D_NAME_LEN); // blank out the buffer - int num_chars = end - start; - strncpy(w3d_name, start, num_chars < W3D_NAME_LEN ? num_chars : W3D_NAME_LEN-1); - strupr(w3d_name); -} - - -/*********************************************************************************************** - * Make_W3D_Filename -- Converts a W3D object name into a W3D filename. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/3/00 AJA : Created. * - *=============================================================================================*/ -static const char * Make_W3D_Filename (const char *w3d_name) -{ - assert(w3d_name); - assert(strlen(w3d_name) < W3D_NAME_LEN); - - // Copy the w3d name into a static buffer, turn it into lowercase - // letters, and append a ".w3d" file extension. That's the filename. - static char buffer[64]; - if (*w3d_name == 0) - { - // Empty W3D name case. - buffer[0] = 0; - return buffer; - } - strcpy(buffer, w3d_name); - char *dot = strchr(buffer, '.'); - if (dot) - *dot = 0; - strlwr(buffer); - strcat(buffer, ".w3d"); - return buffer; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.h deleted file mode 100644 index e834ad3ad8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_dep.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/ww3d2/w3d_dep.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef W3D_DEP_H -#define W3D_DEP_H - -#pragma warning (push, 3) -#pragma warning (disable: 4018 4284 4786 4788) -#include -#pragma warning (pop) - -#pragma warning (push, 3) -#pragma warning (disable: 4018 4146 4284 4503) -#include -#include -#pragma warning (pop) - -typedef std::list StringList; -bool Get_W3D_Dependencies (const char *w3d_filename, StringList &files); - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h index 0840151476..2da572dc5e 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h @@ -309,6 +309,17 @@ June 5, 2001 (gth) Adding line rendering options to particle systems today. This involves a new line-properties chunk and a RenderMode variable added to the InfoV2 struct. +TheSuperHackers @forwardport: +April 5, 2025 + + Added W3D_CHUNK_FX_SHADERS and subchunks, which were added in BFME2. These + chunks are used to define usage of a specific shader and pass params. + +April 21, 2025 + + Added W3D_CHUNK_VERTEX_TANGENT and W3D_CHUNK_VERTEX_BINORMAL chunks. These are used to define + normal mapping information for a mesh. They were added in BFME2. + ********************************************************************************/ @@ -374,20 +385,28 @@ enum { W3D_CHUNK_DCG =0x0000003B, // per-vertex diffuse color values (array of W3dRGBAStruct's) W3D_CHUNK_DIG =0x0000003C, // per-vertex diffuse illumination values (array of W3dRGBStruct's) W3D_CHUNK_SCG =0x0000003E, // per-vertex specular color values (array of W3dRGBStruct's) + W3D_CHUNK_FXSHADER_IDS =0x0000003F, // single or per-tri array of uint32 fx shader indices (check chunk size) W3D_CHUNK_TEXTURE_STAGE =0x00000048, // wrapper around a texture stage. W3D_CHUNK_TEXTURE_IDS =0x00000049, // single or per-tri array of uint32 texture indices (check chunk size) W3D_CHUNK_STAGE_TEXCOORDS =0x0000004A, // per-vertex texture coordinates (array of W3dTexCoordStruct's) W3D_CHUNK_PER_FACE_TEXCOORD_IDS =0x0000004B, // indices to W3D_CHUNK_STAGE_TEXCOORDS, (array of Vector3i) - + W3D_CHUNK_FX_SHADERS =0x00000050, // define an array of shaders to be used in the mesh + W3D_CHUNK_FX_SHADER =0x00000051, // a single shader entry + W3D_CHUNK_FX_SHADER_INFO =0x00000052, // information about the shader to be used (W3dFXShaderInfoStruct) + W3D_CHUNK_FX_SHADER_CONSTANT =0x00000053, // contains a constant name and value for the shader + W3D_CHUNK_DEFORM =0x00000058, // mesh deform or 'damage' information. W3D_CHUNK_DEFORM_SET =0x00000059, // set of deform information W3D_CHUNK_DEFORM_KEYFRAME =0x0000005A, // a keyframe of deform information in the set W3D_CHUNK_DEFORM_DATA =0x0000005B, // deform information about a single vertex W3D_CHUNK_PS2_SHADERS =0x00000080, // Shader info specific to the Playstation 2. - + + W3D_CHUNK_VERTEX_TANGENTS = 0x00000060, // array of tangents (array of W3dVectorStruct's) + W3D_CHUNK_VERTEX_BINORMALS = 0x00000061, // array of binormals (array of W3dVectorStruct's) + W3D_CHUNK_AABTREE =0x00000090, // Axis-Aligned Box Tree for hierarchical polygon culling W3D_CHUNK_AABTREE_HEADER, // catalog of the contents of the AABTree W3D_CHUNK_AABTREE_POLYINDICES, // array of uint32 polygon indices with count=mesh.PolyCount @@ -922,6 +941,24 @@ struct W3dPS2ShaderStruct uint8 pad[3]; }; +struct W3dFXShaderInfoStruct +{ + char ShaderName[W3D_NAME_LEN * 2]; + uint8 Technique; + uint8 Pad[3]; +}; + +typedef enum +{ + CONSTANT_TYPE_TEXTURE = 1, + CONSTANT_TYPE_FLOAT1 = 2, + CONSTANT_TYPE_FLOAT2 = 3, + CONSTANT_TYPE_FLOAT3 = 4, + CONSTANT_TYPE_FLOAT4 = 5, + CONSTANT_TYPE_INT = 6, + CONSTANT_TYPE_BOOL = 7 +} W3D_FX_SHADER_CONSTANT_TYPES; + inline void W3d_Shader_Reset(W3dShaderStruct * s) { s->DepthCompare = W3DSHADER_DEPTHCOMPARE_PASS_LEQUAL; s->DepthMask = W3DSHADER_DEPTHMASK_WRITE_ENABLE; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h deleted file mode 100644 index c96ecf70b5..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_obsolete.h +++ /dev/null @@ -1,333 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/w3d_obsolete.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3D_OBSOLETE_H -#define W3D_OBSOLETE_H - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Obsolete chunk id's -// At one point in time I was using the 'O' prefix to mean obsolete. Now we just move stuff -// into this file... -///////////////////////////////////////////////////////////////////////////////////////////// -enum -{ - W3D_CHUNK_MESH_HEADER =0x00000001, // header for a mesh - W3D_CHUNK_SURRENDER_NORMALS =0x00000004, // array of surrender normals (one per vertex as req. by surrender) - W3D_CHUNK_TEXCOORDS =0x00000005, // array of texture coordinates - O_W3D_CHUNK_MATERIALS =0x00000006, // array of materials - O_W3D_CHUNK_TRIANGLES =0x00000007, // array of triangles - O_W3D_CHUNK_QUADRANGLES =0x00000008, // array of quads - O_W3D_CHUNK_SURRENDER_TRIANGLES =0x00000009, // array of surrender format tris - O_W3D_CHUNK_POV_TRIANGLES =0x0000000A, // POV format triangles - O_W3D_CHUNK_POV_QUADRANGLES =0x0000000B, // POV format quads - W3D_CHUNK_VERTEX_COLORS =0x0000000D, // Pre-set vertex coloring - W3D_CHUNK_DAMAGE =0x0000000F, // Mesh damage, new set of materials, vertex positions, vertex colors - W3D_CHUNK_DAMAGE_HEADER =0x00000010, // Header for the damage data, tells what is coming - W3D_CHUNK_DAMAGE_VERTICES =0x00000011, // Array of modified vertices (W3dMeshDamageVertexStruct's) - W3D_CHUNK_DAMAGE_COLORS =0x00000012, // Array of modified vert colors (W3dMeshDamageColorStruct's) - W3D_CHUNK_DAMAGE_MATERIALS =0x00000013, - - O_W3D_CHUNK_MATERIALS2 =0x00000014, // array of version 2 materials (with animation frame counts) - - W3D_CHUNK_MATERIALS3 =0x00000015, // array of version 3 materials (all new surrender features supported) - W3D_CHUNK_MATERIAL3 =0x00000016, // Each version 3 material wrapped with this chunk ID - W3D_CHUNK_MATERIAL3_NAME =0x00000017, // Name of the material (array of chars, null terminated) - W3D_CHUNK_MATERIAL3_INFO =0x00000018, // contains a W3dMaterial3Struct, general material info - W3D_CHUNK_MATERIAL3_DC_MAP =0x00000019, // wraps the following two chunks, diffuse color texture - W3D_CHUNK_MAP3_FILENAME =0x0000001A, // filename of the texture - W3D_CHUNK_MAP3_INFO =0x0000001B, // a W3dMap3Struct - W3D_CHUNK_MATERIAL3_DI_MAP =0x0000001C, // diffuse illimination map, same format as other maps - W3D_CHUNK_MATERIAL3_SC_MAP =0x0000001D, // specular color map, same format as other maps - W3D_CHUNK_MATERIAL3_SI_MAP =0x0000001E, // specular illumination map, same format as other maps - W3D_CHUNK_PER_TRI_MATERIALS =0x00000021, // Multi-Mtl meshes - An array of uint16 material id's -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 1.0 Material, array of these are found inside the W3D_CHUNK_MATERIALS chunk. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterialStruct -{ - char MaterialName[W3D_NAME_LEN]; // name of the material (NULL terminated) - char PrimaryName[W3D_NAME_LEN]; // primary texture name (NULL terminated) - char SecondaryName[W3D_NAME_LEN]; // secondary texture name (NULL terminated) - uint32 RenderFlags; // Rendering flags - uint8 Red; // Rgb colors - uint8 Green; - uint8 Blue; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 2.0 Material, array of these are found inside the W3D_CHUNK_MATERIALS2 chunk. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterial2Struct -{ - char MaterialName[W3D_NAME_LEN]; // name of the material (NULL terminated) - char PrimaryName[W3D_NAME_LEN]; // primary texture name (NULL terminated) - char SecondaryName[W3D_NAME_LEN]; // secondary texture name (NULL terminated) - uint32 RenderFlags; // Rendering flags - uint8 Red; // Rgb colors - uint8 Green; - uint8 Blue; - uint8 Alpha; - - uint16 PrimaryNumFrames; // number of animated frames (if 1, not animated) - uint16 SecondaryNumFrames; // number of animated frames (if 1, not animated) - - char Pad[12]; // expansion room -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// MATERIAL ATTRIBUTES (version 3.0 onward) -///////////////////////////////////////////////////////////////////////////////////////////// -// Use alpha enables alpha channels, etc, Use sorting causes display lists using -// this material to be sorted (even with z-buf, translucent materials need to be sorted) -#define W3DMATERIAL_USE_ALPHA 0x00000001 -#define W3DMATERIAL_USE_SORTING 0x00000002 - -// Hints for render devices that cannot support all features -#define W3DMATERIAL_HINT_DIT_OVER_DCT 0x00000010 -#define W3DMATERIAL_HINT_SIT_OVER_SCT 0x00000020 -#define W3DMATERIAL_HINT_DIT_OVER_DIG 0x00000040 -#define W3DMATERIAL_HINT_SIT_OVER_SIG 0x00000080 -#define W3DMATERIAL_HINT_FAST_SPECULAR_AFTER_ALPHA 0x00000100 - -// Last byte is for PSX: Translucency type and a lighting disable flag. -#define W3DMATERIAL_PSX_MASK 0xFF000000 -#define W3DMATERIAL_PSX_TRANS_MASK 0x07000000 -#define W3DMATERIAL_PSX_TRANS_NONE 0x00000000 -#define W3DMATERIAL_PSX_TRANS_100 0x01000000 -#define W3DMATERIAL_PSX_TRANS_50 0x02000000 -#define W3DMATERIAL_PSX_TRANS_25 0x03000000 -#define W3DMATERIAL_PSX_TRANS_MINUS_100 0x04000000 -#define W3DMATERIAL_PSX_NO_RT_LIGHTING 0x08000000 - -///////////////////////////////////////////////////////////////////////////////////////////// -// MAPPING TYPES (version 3.0 onward) -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3DMAPPING_UV 0 -#define W3DMAPPING_ENVIRONMENT 1 - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 3.0 Material, A W3D_CHUNK_MATERIALS3 chunk will wrap a bunch of -// W3D_CHUNK_MATERIAL3 chunks. Inside each chunk will be a name chunk, an 'info' chunk which -// contains the following struct, and one or more map chunks. a mesh with 2 materials might -// look like: -// -// W3D_CHUNK_MATERIALS3 <-- simply a wrapper around the array of mtls -// W3D_CHUNK_MATERIAL3 <-- a wrapper around each material -// W3D_CHUNK_STRING <-- name of the material -// W3D_CHUNK_MATERIAL3_INFO <-- standard material properties, a W3dMaterial3Struct -// W3D_CHUNK_MATERIAL3_DC_MAP <-- a map, W3dMap3Struct -// W3D_CHUNK_STRING <-- filename of the map -// W3D_CHUNK_MAP_INFO <-- map parameters -// W3D_CHUNK_MATERIAL3_SC_MAP -// W3D_CHUNK_STRING <-- filename of the map -// W3D_CHUNK_MAP_INFO -// W3D_CHUNK_MATERIAL3 -// W3D_CHUNK_MATERIAL3_NAME -// W3D_CHUNK_MATERIAL3_INFO -// W3D_CHUNK_MATERIAL3_SI_MAP -// -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterial3Struct -{ - uint32 Attributes; // flags,hints,etc. - - W3dRGBStruct DiffuseColor; // diffuse color - W3dRGBStruct SpecularColor; // specular color - - W3dRGBStruct EmissiveCoefficients; // emmissive coefficients, default to 0,0,0 - W3dRGBStruct AmbientCoefficients; // ambient coefficients, default to 1,1,1 - W3dRGBStruct DiffuseCoefficients; // diffuse coeficients, default to 1,1,1 - W3dRGBStruct SpecularCoefficients; // specular coefficients, default to 0,0,0 - - float32 Shininess; // how tight the specular highlight will be, 1 - 1000 (default = 1) - float32 Opacity; // how opaque the material is, 0.0 = invisible, 1.0 = fully opaque (default = 1) - float32 Translucency; // how much light passes through the material. (default = 0) - float32 FogCoeff; // effect of fog (0.0=not fogged, 1.0=fogged) (default = 1) -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A map, only occurs as part of a material, will be preceeded by its name. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMap3Struct -{ - uint16 MappingType; // Mapping type, will be one of the above #defines (e.g. W3DMAPPING_UV) - uint16 FrameCount; // Number of frames (1 if not animated) - float32 FrameRate; // Frame rate, frames per second in floating point -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A triangle, occurs inside the W3D_CHUNK_SURRENDER_TRIANGLES chunk -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dSurrenderTriStruct -{ - uint32 Vindex[3]; // vertex, vert normal, and texture coord indexes (all use same index) - W3dTexCoordStruct TexCoord[3]; // texture coordinates (OBSOLETE!!!) - uint32 MaterialIdx; // material index - W3dVectorStruct Normal; // Face normal - uint32 Attributes; // collision flags, sort method, etc - W3dRGBStruct Gouraud[3]; // Pre-set shading values (OBSOLETE!!!) -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Original (Obsolete) Mesh Header -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMeshHeaderStruct -{ - uint32 Version; // Currently version 0x100 - char MeshName[W3D_NAME_LEN]; // name of the mesh (Null terminated) - uint32 Attributes; - - // - // Counts, these can be regarded as an inventory of what is to come in the file. - // - uint32 NumTris; // number of triangles (OBSOLETE!) - uint32 NumQuads; // number of quads; (OBSOLETE!) - uint32 NumSrTris; // number of triangles - - uint32 NumPovTris; // (NOT USED) - uint32 NumPovQuads; // (NOT USED) - - uint32 NumVertices; // number of unique vertices - uint32 NumNormals; // number of unique normals (OBSOLETE!) - uint32 NumSrNormals; // number of surrender normals (MUST EQUAL NumVertices or 0) - - uint32 NumTexCoords; // number of unique texture coords (MUST EQUAL NumVertices or 0) - uint32 NumMaterials; // number of unique materials needed - - uint32 NumVertColors; // number of vertex colors (MUST EQUAL NumVertices or 0) - uint32 NumVertInfluences;// vertex influences(MUST EQUAL NumVertices or 0) - uint32 NumDamageStages; // number of damage offset chunks - uint32 FutureCounts[5]; // reserve space for future counts (set to zero). - - // - // LOD controls - // - float32 LODMin; // min LOD distance - float32 LODMax; // max LOD distance - - // - // Collision / rendering quick-rejection - // - W3dVectorStruct Min; // Min corner of the bounding box - W3dVectorStruct Max; // Max corner of the bounding box - W3dVectorStruct SphCenter; // Center of bounding sphere - float32 SphRadius; // Bounding sphere radius - - // - // Default transformation - // - W3dVectorStruct Translation; - float32 Rotation[9]; - - // - // Physics Properties - // - W3dVectorStruct MassCenter; // Center of mass in object space - float32 Inertia[9]; // Inertia tensor (relative to MassCenter) - float32 Volume; // volume of the object - - // - // Name of possible hierarchy this mesh should be attached to - // - char HierarchyTreeName[W3D_NAME_LEN]; - char HierarchyModelName[W3D_NAME_LEN]; - uint32 FutureUse[24]; // Reserved for future use -}; - - -// -// Mesh Damage. This can include a new set of materials for the mesh, -// new positions for certain vertices in the mesh, and new vertex -// colors for certain vertices. -// -struct W3dMeshDamageStruct -{ - uint32 NumDamageMaterials; // number of materials to replace - uint32 NumDamageVerts; // number of vertices to replace - uint32 NumDamageColors; // number of vertex colors to replace - uint32 DamageIndex; // what index is this damage chunk assigned to - uint32 FutureUse[4]; -}; - -struct W3dMeshDamageVertexStruct -{ - uint32 VertexIndex; - W3dVectorStruct NewVertex; -}; - -struct W3dMeshDamageColorStruct -{ - uint32 VertexIndex; - W3dRGBStruct NewColor; -}; - - - -// -// W3dHModelAuxDataStruct. HModels had this extra chunk defining the counts of individual -// types of objects to be found in the model and some obsolete distance-based LOD settings. -// As changes were made to the ww3d library, all of this became useles so the chunk was -// "retired". -// -struct W3dHModelAuxDataStruct -{ - uint32 Attributes; - uint32 MeshCount; - uint32 CollisionCount; - uint32 SkinCount; - uint32 ShadowCount; - uint32 NullCount; - uint32 FutureCounts[6]; - - float32 LODMin; - float32 LODMax; - uint32 FutureUse[32]; -}; - - -#endif // W3D_OBSOLETE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp deleted file mode 100644 index 63ce64c147..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/w3d_util.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 7/23/01 5:31p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "w3d_util.h" -#include "vector3.h" -#include "vector4.h" -#include "quat.h" -#include "shader.h" - - -void W3dUtilityClass::Convert_Vector(const W3dVectorStruct & v,Vector3 * set) -{ - set->X = v.X; - set->Y = v.Y; - set->Z = v.Z; -} - -void W3dUtilityClass::Convert_Vector(const Vector3 & v,W3dVectorStruct * set) -{ - set->X = v.X; - set->Y = v.Y; - set->Z = v.Z; -} - -void W3dUtilityClass::Convert_Quaternion(const W3dQuaternionStruct & q,Quaternion * set) -{ - set->X = q.Q[0]; - set->Y = q.Q[1]; - set->Z = q.Q[2]; - set->W = q.Q[3]; -} - -void W3dUtilityClass::Convert_Quaternion(const Quaternion & q,W3dQuaternionStruct * set) -{ - set->Q[0] = q.X; - set->Q[1] = q.Y; - set->Q[2] = q.Z; - set->Q[3] = q.W; -} - -void W3dUtilityClass::Convert_Color(const W3dRGBStruct & rgb,Vector3 * set) -{ - set->X = (float)rgb.R / 255.0f; - set->Y = (float)rgb.G / 255.0f; - set->Z = (float)rgb.B / 255.0f; -} - -void W3dUtilityClass::Convert_Color(const Vector3 & v,W3dRGBStruct * color) -{ - color->R = (uint8)(255.0f * v.X); - color->G = (uint8)(255.0f * v.Y); - color->B = (uint8)(255.0f * v.Z); - color->pad = 0; -} - -void W3dUtilityClass::Convert_Color(const W3dRGBAStruct & rgb,Vector4 * set) -{ - set->X = (float)rgb.R / 255.0f; - set->Y = (float)rgb.G / 255.0f; - set->Z = (float)rgb.B / 255.0f; - set->W = (float)rgb.A / 255.0f; -} - -void W3dUtilityClass::Convert_Color(const Vector4 & v,W3dRGBAStruct * color) -{ - color->R = (uint8)(255.0f * v.X); - color->G = (uint8)(255.0f * v.Y); - color->B = (uint8)(255.0f * v.Z); - color->A = (uint8)(255.0f * v.W); -} - -void W3dUtilityClass::Convert_Shader(const W3dShaderStruct & shader,ShaderClass * set) -{ - set->Set_Depth_Compare ((ShaderClass::DepthCompareType)W3d_Shader_Get_Depth_Compare(&shader)); - set->Set_Depth_Mask ((ShaderClass::DepthMaskType)W3d_Shader_Get_Depth_Mask(&shader)); - set->Set_Color_Mask (ShaderClass::COLOR_WRITE_ENABLE); - set->Set_Dst_Blend_Func ((ShaderClass::DstBlendFuncType)W3d_Shader_Get_Dest_Blend_Func(&shader)); - set->Set_Fog_Func (ShaderClass::FOG_DISABLE); - set->Set_Primary_Gradient ((ShaderClass::PriGradientType)W3d_Shader_Get_Pri_Gradient(&shader)); - set->Set_Secondary_Gradient((ShaderClass::SecGradientType)W3d_Shader_Get_Sec_Gradient(&shader)); - set->Set_Src_Blend_Func ((ShaderClass::SrcBlendFuncType)W3d_Shader_Get_Src_Blend_Func(&shader)); - set->Set_Texturing ((ShaderClass::TexturingType)W3d_Shader_Get_Texturing(&shader)); - set->Set_Alpha_Test ((ShaderClass::AlphaTestType)W3d_Shader_Get_Alpha_Test(&shader)); -// Jani: No cull mode settings for w3d shader - problem? -// set->Set_Dither_Mask (ShaderClass::DITHER_ENABLE); - // The tools do not enable setting post-detail stuff, and in any case we probably wouldn't - // want to confuse the artists with the distinction between detail and post-detail settings at - // this point, so we just copy the detail settings into the post-detail settings. -// set->Set_Post_Detail_Color_Func ((ShaderClass::DetailColorFuncType) W3d_Shader_Get_Post_Detail_Color_Func (&shader)); -// set->Set_Post_Detail_Alpha_Func ((ShaderClass::DetailAlphaFuncType) W3d_Shader_Get_Post_Detail_Alpha_Func (&shader)); - set->Set_Post_Detail_Color_Func ((ShaderClass::DetailColorFuncType) W3d_Shader_Get_Detail_Color_Func (&shader)); - set->Set_Post_Detail_Alpha_Func ((ShaderClass::DetailAlphaFuncType) W3d_Shader_Get_Detail_Alpha_Func (&shader)); -} - -void W3dUtilityClass::Convert_Shader(const ShaderClass & shader,W3dShaderStruct * set) -{ - W3d_Shader_Reset(set); - W3d_Shader_Set_Depth_Compare(set,shader.Get_Depth_Compare()); - W3d_Shader_Set_Depth_Mask(set,shader.Get_Depth_Mask()); - W3d_Shader_Set_Dest_Blend_Func(set,shader.Get_Dst_Blend_Func()); - W3d_Shader_Set_Pri_Gradient(set,shader.Get_Primary_Gradient()); - W3d_Shader_Set_Sec_Gradient(set,shader.Get_Secondary_Gradient()); - W3d_Shader_Set_Src_Blend_Func(set,shader.Get_Src_Blend_Func()); - W3d_Shader_Set_Texturing(set,shader.Get_Texturing()); - W3d_Shader_Set_Alpha_Test(set,shader.Get_Alpha_Test()); - W3d_Shader_Set_Post_Detail_Color_Func(set,shader.Get_Post_Detail_Color_Func()); - W3d_Shader_Set_Post_Detail_Alpha_Func(set,shader.Get_Post_Detail_Alpha_Func()); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.h deleted file mode 100644 index a3ca9353c4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3d_util.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/w3d_util.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3D_UTIL_H -#define W3D_UTIL_H - -#include "always.h" -#include "w3d_file.h" - -class Vector3; -class Vector4; -class Quaternion; -class ShaderClass; - -/* -** These functions are just simple helpers which convert to and from the W3D file-format -** structures and the equivalent runtime classes. -*/ -class W3dUtilityClass -{ -public: - - static void Convert_Vector(const W3dVectorStruct & v,Vector3 * set); - static void Convert_Vector(const Vector3 & v,W3dVectorStruct * set); - - static void Convert_Quaternion(const W3dQuaternionStruct & q,Quaternion * set); - static void Convert_Quaternion(const Quaternion & q,W3dQuaternionStruct * set); - - static void Convert_Color(const W3dRGBStruct & rgb,Vector3 * set); - static void Convert_Color(const Vector3 & v,W3dRGBStruct * set); - - static void Convert_Color(const W3dRGBAStruct & rgb,Vector4 * set); - static void Convert_Color(const Vector4 & v,W3dRGBAStruct * set); - - static void Convert_Shader(const W3dShaderStruct & shader,ShaderClass * set); - static void Convert_Shader(const ShaderClass & shader,W3dShaderStruct * set); - -}; - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3derr.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3derr.h deleted file mode 100644 index 8f2129ba24..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3derr.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/w3derr.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3DERR_H -#define W3DERR_H - -#include "always.h" - -/* -** These are the error codes which should be returned by all WW3D functions that can fail -*/ -enum WW3DErrorType -{ - WW3D_ERROR_OK = 0, - WW3D_ERROR_GENERIC, - WW3D_ERROR_LOAD_FAILED, - WW3D_ERROR_SAVE_FAILED, - WW3D_ERROR_WINDOW_NOT_OPEN, - WW3D_ERROR_INITIALIZATION_FAILED, -}; - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp deleted file mode 100644 index c5ea49a6b3..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/w3dexclusionlist.cpp 1 12/12/02 3:36p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/w3dexclusionlist.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 12/12/02 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "w3dexclusionlist.h" -#include "proto.h" -#include "htree.h" -#include "hanim.h" - - -W3DExclusionListClass::W3DExclusionListClass(const DynamicVectorClass & names) : - Names(names) -{ - for (int i=0; iGet_Name(); - char * root_name = copy.Peek_Buffer(); - - // don't preserve munged prototypes - if (strchr(root_name,'#') != NULL) { - return false; - } - - // chop off the sub-object name if present ( - char * tmp = strchr(root_name,'.'); - if (tmp != NULL) { - *tmp = 0; - } - - return Is_Excluded(root_name); -} - - -bool W3DExclusionListClass::Is_Excluded(HTreeClass * htree) const -{ - // plain old name... - return Is_Excluded(htree->Get_Name()); -} - - -bool W3DExclusionListClass::Is_Excluded(HAnimClass * hanim) const -{ - // For HAnims, the name to check is the one trailing the '.' - StringClass copy = hanim->Get_Name(); - char * root_name = copy.Peek_Buffer(); - - char * tmp = strchr(root_name,'.'); - if (tmp) { - return Is_Excluded(tmp + 1); - } else { - return false; // should never happen... - } -} - - -bool W3DExclusionListClass::Is_Excluded(const char * root_name) const -{ - return NameHash.Exists(StringClass(root_name)); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h deleted file mode 100644 index 06926556aa..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/w3dexclusionlist.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d2/w3dexclusionlist.h 1 12/12/02 3:36p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d2/w3dexclusionlist.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 12/12/02 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3DEXCLUSIONLIST_H -#define W3DEXCLUSIONLIST_H - -#include "always.h" -#include "Vector.H" -#include "wwstring.h" -#include "hashtemplate.h" - -class PrototypeClass; -class HTreeClass; -class HAnimClass; - - -/** -** W3DExclusionListClass -** This class ecapsulates an "exclusion list" which the asset manager and related classes use -** to filter what resources get released. This is useful between level loads for example. -** The Is_Excluded function uses w3d naming convention assumptions to determine whether the given -** asset name is in the list or is a child of something in the list. -*/ - -class W3DExclusionListClass -{ -public: - W3DExclusionListClass(const DynamicVectorClass & names); - ~W3DExclusionListClass(void); - - bool Is_Excluded(PrototypeClass * proto) const; - bool Is_Excluded(HTreeClass * htree) const; - bool Is_Excluded(HAnimClass * hanim) const; - - bool Is_Excluded(const char * root_name) const; - -protected: - - - const DynamicVectorClass & Names; - HashTemplateClass NameHash; -}; - - - -#endif //EXCLUSIONLIST_H \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp index ff7019bce1..003268ad80 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.cpp @@ -22,14 +22,18 @@ * * * Project Name : WW3D * * * - * $Archive:: /VSS_Sync/ww3d2/ww3d.cpp $* + * $Archive:: /Commando/Code/ww3d2/ww3d.cpp $* * * - * Author:: Greg_h * + * Org Author:: Greg_h * * * - * $Modtime:: 8/29/01 7:29p $* + * Author : Kenny Mitchell * + * * + * $Modtime:: 08/05/02 10:03a $* * * - * $Revision:: 82 $* + * $Revision:: 98 $* * * + * 07/01/02 KM Scalable shader library integration * + * 08/05/02 KM Texture class redesign *---------------------------------------------------------------------------------------------* * Functions: * * WW3D::Init -- Initialize the WW3D Library * @@ -50,7 +54,6 @@ * WW3D::Sync -- Time sychronization * * WW3D::Set_Ext_Swap_Interval -- Sets the swap interval the device should aim sync for. * * WW3D::Get_Ext_Swap_Interval -- Queries the swap interval the device is aiming sync for. * - * WW3D::Set_Polygon_Mode -- set the drawing mode * * WW3D::Get_Polygon_Mode -- returns the current rendering mode * * WW3D::Set_Collision_Box_Display_Mask -- control rendering of collision boxes * * WW3D::Get_Collision_Box_Display_Mask -- returns the current display mask for collision bo * @@ -113,6 +116,7 @@ #include "cpudetect.h" #include "dx8texman.h" #include "formconv.h" +#include "animatedsoundmgr.h" #include "static_sort_list.h" @@ -180,6 +184,8 @@ float WW3D::DecalRejectionDistance = 1000000.0f; bool WW3D::AreStaticSortListsEnabled = false; bool WW3D::MungeSortOnLoad = false; +bool WW3D::OverbrightModifyOnLoad = false; + FrameGrabClass * WW3D::Movie = NULL; bool WW3D::PauseRecord; bool WW3D::RecordNextFrame; @@ -206,7 +212,6 @@ bool WW3D::SnapshotActivated=false; bool WW3D::ThumbnailEnabled=true; WW3D::MeshDrawModeEnum WW3D::MeshDrawMode = MESH_DRAW_MODE_OLD; -WW3D::TextureCompressionModeEnum WW3D::TextureCompressionMode = TEXTURE_COMPRESSION_ENABLE; WW3D::NPatchesGapFillingModeEnum WW3D::NPatchesGapFillingMode = NPATCHES_GAP_FILLING_ENABLED; unsigned WW3D::NPatchesLevel=1; bool WW3D::IsTexturingEnabled=true; @@ -214,24 +219,21 @@ bool WW3D::IsColoringEnabled=false; static HWND _Hwnd = NULL; // Not a member to hide windows from WW3D users static int _TextureReduction = 0; -static int _TextureMinMipLevels = 1; +static int _TextureMinDim = 1; +static bool _LargeTextureExtraReductionEnabled = false; int WW3D::LastFrameMemoryAllocations; int WW3D::LastFrameMemoryFrees; +int WW3D::TextureFilter = 0; + +bool WW3D::Lite = false; + /********************************************************************************** ** ** WW3D Static Functions ** ***********************************************************************************/ -void WW3D::Set_Texture_Compression_Mode(TextureCompressionModeEnum mode) -{ - if (TextureCompressionMode!=mode) { - TextureCompressionMode = mode; - _Invalidate_Textures(); - } -} - void WW3D::Set_NPatches_Gap_Filling_Mode(NPatchesGapFillingModeEnum mode) { if (NPatchesGapFillingMode!=mode) { @@ -246,7 +248,7 @@ void WW3D::Set_NPatches_Level(unsigned level) if (level<1) level=1; if (NPatchesLevel==1 && level>1) TheDX8MeshRenderer.Invalidate(); if (NPatchesLevel>1 && level==1) TheDX8MeshRenderer.Invalidate(); - NPatchesLevel = level; + NPatchesLevel = level; } void WW3D::Set_Thumbnail_Enabled (bool b) @@ -269,18 +271,22 @@ void WW3D::Set_Thumbnail_Enabled (bool b) * HISTORY: * * 3/24/98 GTH : Created. * *=============================================================================================*/ -WW3DErrorType WW3D::Init(void *hwnd, char *defaultpal) +WW3DErrorType WW3D::Init(void *hwnd, char *defaultpal, bool lite) { assert(IsInitted == false); WWDEBUG_SAY(("WW3D::Init hwnd = %p\n",hwnd)); _Hwnd = (HWND)hwnd; + Lite = lite; /* ** Initialize d3d, this also enumerates the available devices and resolutions. */ Init_D3D_To_WW3_Conversion(); - if (!DX8Wrapper::Init(_Hwnd)) - return WW3D_ERROR_INITIALIZATION_FAILED; + WWDEBUG_SAY(("Init DX8Wrapper\n")); + if (!DX8Wrapper::Init(_Hwnd, lite)) { + return(WW3D_ERROR_INITIALIZATION_FAILED); + } + WWDEBUG_SAY(("Allocate Debug Resources\n")); Allocate_Debug_Resources(); MMRESULT r=timeBeginPeriod(1); @@ -289,13 +295,15 @@ WW3DErrorType WW3D::Init(void *hwnd, char *defaultpal) /* ** Initialize the dazzle system */ - FileClass * dazzle_ini_file = _TheFileFactory->Get_File(DAZZLE_INI_FILENAME); - if (dazzle_ini_file) { - INIClass dazzle_ini(*dazzle_ini_file); - DazzleRenderObjClass::Init_From_INI(&dazzle_ini); - _TheFileFactory->Return_File(dazzle_ini_file); + if (!lite) { + WWDEBUG_SAY(("Init Dazzles\n")); + FileClass * dazzle_ini_file = _TheFileFactory->Get_File(DAZZLE_INI_FILENAME); + if (dazzle_ini_file) { + INIClass dazzle_ini(*dazzle_ini_file); + DazzleRenderObjClass::Init_From_INI(&dazzle_ini); + _TheFileFactory->Return_File(dazzle_ini_file); + } } - /* ** Initialize the default static sort lists ** Note that DefaultStaticSortLists[0] is unused. @@ -303,7 +311,14 @@ WW3DErrorType WW3D::Init(void *hwnd, char *defaultpal) DefaultStaticSortLists = W3DNEW DefaultStaticSortListClass(); Reset_Current_Static_Sort_Lists_To_Default(); - IsInitted = true; + /* + ** Initialize the animation-triggered sound system + */ + if (!lite) { + AnimatedSoundMgrClass::Initialize (); + IsInitted = true; + } + WWDEBUG_SAY(("WW3D Init completed\n")); return WW3D_ERROR_OK; } @@ -322,7 +337,7 @@ WW3DErrorType WW3D::Init(void *hwnd, char *defaultpal) *=============================================================================================*/ WW3DErrorType WW3D::Shutdown(void) { - assert(IsInitted == true); + assert(Lite || IsInitted == true); // WWDEBUG_SAY(("WW3D::Shutdown\n")); #ifdef WW3D_DX8 @@ -334,7 +349,6 @@ WW3DErrorType WW3D::Shutdown(void) //restore the previous timer resolution MMRESULT r=timeEndPeriod(1); WWASSERT(r==TIMERR_NOERROR); - /* ** Free memory in predictive LOD optimizer */ @@ -343,7 +357,9 @@ WW3DErrorType WW3D::Shutdown(void) /* ** Free the DazzleRenderObject class stuff. Whatever it is. ST - 6/11/2001 8:20PM */ - DazzleRenderObjClass::Deinit (); + if (!Lite) { + DazzleRenderObjClass::Deinit (); + } /* ** Release all of our assets @@ -354,13 +370,20 @@ WW3DErrorType WW3D::Shutdown(void) } DX8TextureManagerClass::Shutdown(); - DX8Wrapper::Shutdown(); + if (!Lite) { + DX8Wrapper::Shutdown(); + } /* ** Clear the default static sort lists */ delete DefaultStaticSortLists; + /* + ** Release the animation-triggered sound data + */ + AnimatedSoundMgrClass::Shutdown (); + IsInitted = false; return WW3D_ERROR_OK; } @@ -736,6 +759,8 @@ void WW3D::_Invalidate_Mesh_Cache() void WW3D::_Invalidate_Textures() { + if (!WW3DAssetManager::Get_Instance()) return; + TextureLoader::Flush_Pending_Load_Tasks(); HashTemplateIterator ite(WW3DAssetManager::Get_Instance()->Texture_Hash()); @@ -748,6 +773,15 @@ void WW3D::_Invalidate_Textures() } } +void WW3D::Set_Texture_Filter(int texture_filter) +{ + if (texture_filter<0) texture_filter=0; + if (texture_filter>TextureFilterClass::TEXTURE_FILTER_ANISOTROPIC) texture_filter=TextureFilterClass::TEXTURE_FILTER_ANISOTROPIC; + TextureFilter=texture_filter; + TextureFilterClass::_Init_Filters(); +} + + /*********************************************************************************************** * WW3D::Begin_Render -- mark the start of rendering for a new frame * * * @@ -760,12 +794,20 @@ void WW3D::_Invalidate_Textures() * HISTORY: * * 3/24/98 GTH : Created. * *=============================================================================================*/ -WW3DErrorType WW3D::Begin_Render(bool clear,bool clearz,const Vector3 & color, float dest_alpha) +WW3DErrorType WW3D::Begin_Render(bool clear,bool clearz,const Vector3 & color, float dest_alpha, void(*network_callback)(void)) { + if (!IsInitted) { + return(WW3D_ERROR_OK); + } + WWPROFILE("WW3D::Begin_Render"); WWASSERT(IsInitted); HRESULT hr; + SNAPSHOT_SAY(("==========================================\r\n")); + SNAPSHOT_SAY(("========== WW3D::Begin_Render ============\r\n")); + SNAPSHOT_SAY(("==========================================\r\n\r\n")); + if (DX8Wrapper::_Get_D3D_Device8() && (hr=DX8Wrapper::_Get_D3D_Device8()->TestCooperativeLevel()) != D3D_OK) { // If the device was lost, do not render until we get it back @@ -837,6 +879,10 @@ WW3DErrorType WW3D::Begin_Render(bool clear,bool clearz,const Vector3 & color, f *=============================================================================================*/ WW3DErrorType WW3D::Render(const LayerListClass &LayerList) { + if (!IsInitted) { + return(WW3D_ERROR_OK); + } + WWASSERT(IsRendering); LayerClass *layer = LayerList.Last(); @@ -868,6 +914,9 @@ WW3DErrorType WW3D::Render(const LayerListClass &LayerList) *=============================================================================================*/ WW3DErrorType WW3D::Render(const LayerClass &Layer) { + if (!IsInitted) { + return(WW3D_ERROR_OK); + } WWASSERT(IsRendering); return Render(Layer.Scene, Layer.Camera, Layer.Clear, Layer.ClearZ, Layer.ClearColor); @@ -889,6 +938,10 @@ WW3DErrorType WW3D::Render(const LayerClass &Layer) *=============================================================================================*/ WW3DErrorType WW3D::Render(SceneClass * scene,CameraClass * cam,bool clear,bool clearz,const Vector3 & color) { + if (!IsInitted) { + return(WW3D_ERROR_OK); + } + WWPROFILE("WW3D::Render"); WWMEMLOG(MEM_GAMEDATA); WWASSERT(IsInitted); @@ -922,8 +975,7 @@ WW3DErrorType WW3D::Render(SceneClass * scene,CameraClass * cam,bool clear,bool // Set the global ambient light value here. If the scene is using the LightEnvironment system // this setting will get overriden. - Vector3 ambient = scene->Get_Ambient_Light(); - DX8Wrapper::Set_DX8_Render_State(D3DRS_AMBIENT, DX8Wrapper::Convert_Color(ambient,0.0f)); + DX8Wrapper::Set_Ambient(scene->Get_Ambient_Light()); // render the scene @@ -954,6 +1006,10 @@ WW3DErrorType WW3D::Render( RenderInfoClass & rinfo ) { + if (!IsInitted) { + return(WW3D_ERROR_OK); + } + WWPROFILE("WW3D::Render"); WWASSERT(IsInitted); WWASSERT(IsRendering); @@ -1027,10 +1083,14 @@ void WW3D::Flush(RenderInfoClass & rinfo) *=============================================================================================*/ WW3DErrorType WW3D::End_Render(bool flip_frame) { + if (!IsInitted) { + return(WW3D_ERROR_OK); + } + WWPROFILE("WW3D::End_Render"); - assert(IsRendering); - assert(IsInitted); + WWASSERT(IsRendering); + WWASSERT(IsInitted); // If sorting renderer flush isn't called from within any of the render functions // the sorting arrays will overflow! @@ -1039,12 +1099,28 @@ WW3DErrorType WW3D::End_Render(bool flip_frame) IsRendering = false; - DX8Wrapper::End_Scene(flip_frame); + { + WWPROFILE("DX8Wrapper::End_Scene"); + DX8Wrapper::End_Scene(flip_frame); + } FrameCount++; - Debug_Statistics::End_Statistics(); + { + WWPROFILE("End_Statistics"); + Debug_Statistics::End_Statistics(); + } + + SNAPSHOT_SAY(("==========================================\r\n")); + SNAPSHOT_SAY(("========== WW3D::End_Render ==============\r\n")); + SNAPSHOT_SAY(("==========================================\r\n\r\n")); + Activate_Snapshot(false); + + // (gth) I've found some cases where its not safe to rely on our "shadow" copy (of + // matrices for example) across multiple frames. So even though this is slightly + // less "optimal", lets just reset the caches each frame. + DX8Wrapper::Invalidate_Cached_Render_States(); return WW3D_ERROR_OK; } @@ -1221,18 +1297,32 @@ void WW3D::Normalize_Coordinates(int x, int y, float &fx, float &fy) * 5/19/99 GTH : Created. * * 2/26/2001 hy : Updated to DX8 * *=============================================================================================*/ -void WW3D::Make_Screen_Shot( const char * filename_base ) +void WW3D::Make_Screen_Shot( const char * filename_base , const float gamma, const ScreenShotFormatEnum format) { WWASSERT(!IsRendering); char filename[80]; + char ext[4]; + switch (format) { + case TGA: + sprintf(ext,"tga"); + break; + case BMP: + sprintf(ext,"bmp"); + break; + default: + WWASSERT(0); + return; + break; + } + static int frame_number = 1; bool done = false; while (!done) { - sprintf( filename, "%s%.2d.tga", filename_base, frame_number++); + sprintf( filename, "%s%.2d.%s", filename_base, frame_number++, ext); FileClass*file=_TheFileFactory->Get_File( filename ); if ( file ) { file->Open(); @@ -1245,6 +1335,17 @@ void WW3D::Make_Screen_Shot( const char * filename_base ) WWDEBUG_SAY(( "Creating Screen Shot %s\n", filename )); + // make the gamma look up table + int i; + unsigned char gamma_lut[256]; + float recip = 1.0f; + if (gamma > WWMATH_EPSILON) { + recip = 1.0f / gamma; + } + for (i = 0; i < 256; i++) { + gamma_lut[i] = (unsigned char) (256.0f * powf(i / 256.0f, recip)); + } + // Lock front buffer and copy IDirect3DSurface8 *fb; @@ -1264,7 +1365,7 @@ void WW3D::Make_Screen_Shot( const char * filename_base ) width=bounds.right-bounds.left; height=bounds.bottom-bounds.top; - char *image=W3DNEWARRAY char[3*width*height]; + unsigned char *image=W3DNEWARRAY unsigned char[3*width*height]; for (y=0; yRelease(); - Targa targ; - memset(&targ.Header,0,sizeof(targ.Header)); - targ.Header.Width=width; - targ.Header.Height=height; - targ.Header.PixelDepth=24; - targ.Header.ImageType=TGA_TRUECOLOR; - targ.SetImage(image); - targ.YFlip(); - - RawFileClass*file=(RawFileClass*)_TheWritingFileFactory->Get_File( filename ); - if ( file ) { - file->Create(); - file->Close(); - _TheWritingFileFactory->Return_File( file ); + switch (format) { + case TGA: + { + Targa targ; + memset(&targ.Header,0,sizeof(targ.Header)); + targ.Header.Width=width; + targ.Header.Height=height; + targ.Header.PixelDepth=24; + targ.Header.ImageType=TGA_TRUECOLOR; + targ.SetImage((char *) image); + targ.YFlip(); + + FileClass*file=_TheWritingFileFactory->Get_File( filename ); + if ( file ) { + file->Create(); + file->Close(); + _TheWritingFileFactory->Return_File( file ); + } + + targ.Save(filename,TGAF_IMAGE,false); + } + break; + case BMP: + { + BITMAPFILEHEADER fileheader; + BITMAPINFOHEADER header; + memset(&header, 0, sizeof(BITMAPINFOHEADER)); + header.biSize = sizeof(BITMAPINFOHEADER); + header.biWidth = width; + header.biHeight = height; + header.biPlanes = 1; + header.biBitCount = 24; + header.biCompression = BI_RGB; + header.biXPelsPerMeter = 0xB12; + header.biYPelsPerMeter = 0xB12; + int len = ((width * 24 +31) & ~31) /8; + + memset(&fileheader, 0, sizeof(BITMAPFILEHEADER)); + fileheader.bfType = 19778; // BM + fileheader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); + fileheader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + 3 * len * height * sizeof(char); + + FileClass *file = _TheWritingFileFactory->Get_File( filename ); + if ( file ) { + file->Create(); + file->Open(FileClass::WRITE); + int num; + num = file->Write(&fileheader, sizeof(BITMAPFILEHEADER)); + WWASSERT(num == sizeof(BITMAPFILEHEADER)); + num = file->Write(&header, sizeof(BITMAPINFOHEADER)); + WWASSERT(num == sizeof(BITMAPINFOHEADER)); + char *temp = new char [3 * len]; + memset(temp, 0, 3 * len * sizeof(char)); + // invert image, pad and swap R and B + for (y = 0; y < (int) height; y++) { + memcpy(&temp[0], &image[ 3 * width * (height - y - 1)], 3 * width * sizeof(char)); + for (x = 0; x < width; x++) { + char t2 = temp[3 * x]; + temp[3 * x] = temp[3 * x + 2]; + temp[3 * x + 2] = t2; + } + num = file->Write(&temp[0], len * sizeof(char)); + WWASSERT(num == len * (int)sizeof(char)); + } + delete [] temp; + file->Close(); + _TheWritingFileFactory->Return_File( file ); + } + } + break; } - targ.Save(filename,TGAF_IMAGE,false); - delete [] image; - } @@ -1605,11 +1759,13 @@ float WW3D::Get_Movie_Capture_Frame_Rate( void ) * HISTORY: * * 5/19/99 GTH : Created. * *=============================================================================================*/ -void WW3D::Set_Texture_Reduction( int value, int min_mip_levels ) +void WW3D::Set_Texture_Reduction( int value, int minDim ) { - _TextureReduction=value; - _TextureMinMipLevels=min_mip_levels; - _Invalidate_Textures(); + if (_TextureReduction != value || _TextureMinDim != minDim) { + _TextureReduction=value; + _TextureMinDim=minDim; + _Invalidate_Textures(); + } } @@ -1654,9 +1810,22 @@ int WW3D::Get_Texture_Reduction( void ) * HISTORY: * * 11/25/99 TSS : Created. * *=============================================================================================*/ -int WW3D::Get_Texture_Min_Mip_Levels( void ) +int WW3D::Get_Texture_Min_Dimension( void ) +{ + return _TextureMinDim; +} + +void WW3D::Enable_Large_Texture_Extra_Reduction(bool onoff) +{ + if (_LargeTextureExtraReductionEnabled != onoff) { + _LargeTextureExtraReductionEnabled = onoff; + _Invalidate_Textures(); + } +} + +bool WW3D::Is_Large_Texture_Extra_Reduction_Enabled(void) { - return _TextureMinMipLevels; + return _LargeTextureExtraReductionEnabled; } /*********************************************************************************************** @@ -1764,6 +1933,9 @@ void WW3D::Release_Debug_Resources(void) WW3DErrorType WW3D::On_Deactivate_App(void) { + _Invalidate_Textures(); + _Invalidate_Mesh_Cache(); + return WW3D_ERROR_OK; } @@ -1847,4 +2019,9 @@ void WW3D::Override_Current_Static_Sort_Lists(StaticSortListClass * sort_list) void WW3D::Reset_Current_Static_Sort_Lists_To_Default(void) { CurrentStaticSortLists = DefaultStaticSortLists; +} + +void WW3D::Set_Gamma(float gamma,float bright,float contrast,bool calibrate) +{ + DX8Wrapper::Set_Gamma(gamma,bright,contrast,calibrate); } \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h index 52ce4d79b5..a632cd5df1 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h +++ b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3d.h @@ -22,13 +22,13 @@ * * * Project Name : WW3D * * * - * $Archive:: /VSS_Sync/ww3d2/ww3d.h $* + * $Archive:: /Commando/Code/ww3d2/ww3d.h $* * * - * $Author:: Vss_sync $* + * $Author:: Steve_t $* * * - * $Modtime:: 8/29/01 9:39p $* + * $Modtime:: 1/02/02 4:17p $* * * - * $Revision:: 32 $* + * $Revision:: 42 $* * * *---------------------------------------------------------------------------------------------* * Functions: * @@ -64,6 +64,7 @@ class LightEnvironmentClass; class MaterialPassClass; class StaticSortListClass; +#define MESH_RENDER_SNAPSHOT_ENABLED #define SNAPSHOT_SAY(x) if (WW3D::Is_Snapshot_Activated()) { WWDEBUG_SAY(x); } //#define SNAPSHOT_SAY(x) @@ -93,19 +94,19 @@ class WW3D MESH_DRAW_MODE_DX8_ONLY }; - enum TextureCompressionModeEnum { - TEXTURE_COMPRESSION_DISABLE, - TEXTURE_COMPRESSION_ENABLE - }; - enum NPatchesGapFillingModeEnum { NPATCHES_GAP_FILLING_DISABLED, NPATCHES_GAP_FILLING_ENABLED, NPATCHES_GAP_FILLING_FORCE }; + enum ScreenShotFormatEnum { + TGA, + BMP + }; + - static WW3DErrorType Init(void * hwnd, char *defaultpal = NULL); + static WW3DErrorType Init(void * hwnd, char *defaultpal = NULL, bool lite = false); static WW3DErrorType Shutdown(void); static bool Is_Initted(void) { return IsInitted; } @@ -115,7 +116,7 @@ class WW3D static int Get_Render_Device(void); static WW3DErrorType Set_Render_Device( int dev=-1, int resx=-1, int resy=-1, int bits=-1, int windowed=-1, bool resize_window = false, bool reset_device=false, bool restore_assets=true); - static WW3DErrorType Set_Render_Device( const char *dev_name, int resx=-1, int resy=-1, int bits=-1, int windowed=-1, bool resize_window = false ); + static WW3DErrorType Set_Render_Device( const char *dev_name, int resx=-1, int resy=-1, int bits=-1, int windowed=-1, bool resize_window = false ); static WW3DErrorType Set_Next_Render_Device(void); static WW3DErrorType Set_Any_Render_Device( void ); @@ -135,7 +136,11 @@ class WW3D static WW3DErrorType Registry_Save_Render_Device( const char * sub_key ); static WW3DErrorType Registry_Save_Render_Device( const char * sub_key, int device, int width, int height, int depth, bool windowed, int texture_depth ); static WW3DErrorType Registry_Load_Render_Device( const char * sub_key, bool resize_window = false ); - static bool Registry_Load_Render_Device( const char * sub_key, char *device, int device_len, int &width, int &height, int &depth, int &windowed, int& texture_depth); + static bool Registry_Load_Render_Device( const char * sub_key, char *device, int device_len, int &width, int &height, int &depth, int &windowed, int& texture_depth); + + // 0 = bilinear, 1 = trilinear, 2 = anisotropic + static void Set_Texture_Filter(int filter); + static int Get_Texture_Filter() { return TextureFilter; } /* ** Rendering functions @@ -144,8 +149,7 @@ class WW3D ** special cases like generating a shadow texture for an object. Basically this function will have the ** entire scene rendering overhead. */ - static WW3DErrorType Begin_Render(bool clear = false,bool clearz = true,const Vector3 & color = Vector3(0,0,0), float dest_alpha=0.0f); - + static WW3DErrorType Begin_Render(bool clear = false,bool clearz = true,const Vector3 & color = Vector3(0,0,0), float dest_alpha=0.0f, void(*network_callback)(void) = NULL); static WW3DErrorType Render(const LayerListClass & layerlist); static WW3DErrorType Render(const LayerClass & layer); static WW3DErrorType Render(SceneClass * scene,CameraClass * cam,bool clear = false,bool clearz = false,const Vector3 & color = Vector3(0,0,0)); @@ -154,6 +158,8 @@ class WW3D static WW3DErrorType End_Render(bool flip_frame = true); + static bool Is_Rendering( void ) { return( IsRendering ); } + static void Flip_To_Primary(void); @@ -173,7 +179,7 @@ class WW3D ** Screen/Movie capturing ** These functions allow you to create screenshots and movies. */ - static void Make_Screen_Shot( const char * filename = "ScreenShot"); + static void Make_Screen_Shot( const char * filename = "ScreenShot", const float gamma = 1.3f, const ScreenShotFormatEnum format = TGA); static void Start_Movie_Capture( const char * filename_base = "Movie", float frame_rate = 15); static void Stop_Movie_Capture( void); static void Toggle_Movie_Capture( const char * filename_base = "Movie", float frame_rate = 15); @@ -183,8 +189,8 @@ class WW3D static float Get_Movie_Capture_Frame_Rate( void); static void Pause_Movie(bool mode); static bool Is_Movie_Paused(); - static bool Is_Recording_Next_Frame(); - static bool Is_Movie_Ready(); + static bool Is_Recording_Next_Frame(); + static bool Is_Movie_Ready(); /* ** Set_Ext_Swap_Interval - how many vertical retraces to wait before flipping frames @@ -199,9 +205,11 @@ class WW3D ** all textures to be half their normal resolution. Passing in 3 causes them to ** be cut in half twice, etc */ - static void Set_Texture_Reduction( int value, int min_mip_levels=1 ); + static void Set_Texture_Reduction( int value, int min_dim=1 ); static int Get_Texture_Reduction( void ); - static int Get_Texture_Min_Mip_Levels( void ); + static int Get_Texture_Min_Dimension(void); + static void Enable_Large_Texture_Extra_Reduction(bool onoff); + static bool Is_Large_Texture_Extra_Reduction_Enabled(void); static void _Invalidate_Mesh_Cache(); static void _Invalidate_Textures(); @@ -239,9 +247,6 @@ class WW3D static void Set_Mesh_Draw_Mode (MeshDrawModeEnum mode) { MeshDrawMode = mode; } static MeshDrawModeEnum Get_Mesh_Draw_Mode () { return (MeshDrawMode); } - static void Set_Texture_Compression_Mode (TextureCompressionModeEnum mode); - static TextureCompressionModeEnum Get_Texture_Compression_Mode () { return (TextureCompressionMode); } - static void Set_NPatches_Gap_Filling_Mode (NPatchesGapFillingModeEnum mode); static NPatchesGapFillingModeEnum Get_NPatches_Gap_Filling_Mode () { return (NPatchesGapFillingMode); } @@ -282,6 +287,14 @@ class WW3D static void Override_Current_Static_Sort_Lists(StaticSortListClass * sort_list); static void Reset_Current_Static_Sort_Lists_To_Default(void); + /* + ** Overbright modify on load - when this mode is set meshes will be + ** modified at load time. All shaders which originally had the primary + ** gradient set to MODULATE will be changed to MODULATE2X instead. + */ + static void Enable_Overbright_Modify_On_Load(bool onoff) { OverbrightModifyOnLoad = onoff; } + static bool Is_Overbright_Modify_On_Load_Enabled(void) { return OverbrightModifyOnLoad; } + static bool Is_Snapshot_Activated() { return SnapshotActivated; } static void Activate_Snapshot(bool b) { SnapshotActivated=b; } @@ -291,6 +304,9 @@ class WW3D static long UserStat1; static long UserStat2; + // Gamma control + static void Set_Gamma(float gamma,float bright,float contrast,bool calibrate=true); + private: enum @@ -302,7 +318,6 @@ class WW3D static void Read_Gerd_Render_Device_Description(RenderDeviceDescClass &desc); static void Update_Pixel_Center(void); - static void Set_Polygon_Mode(int mode); static void Allocate_Debug_Resources(void); static void Release_Debug_Resources(void); @@ -334,6 +349,8 @@ class WW3D static bool AreStaticSortListsEnabled; static bool MungeSortOnLoad; + static bool OverbrightModifyOnLoad; + static FrameGrabClass * Movie; static bool PauseRecord; static bool RecordNextFrame; @@ -347,16 +364,19 @@ class WW3D static PrelitModeEnum PrelitMode; static bool ExposePrelit; + static int TextureFilter; + static bool SnapshotActivated; static bool ThumbnailEnabled; static MeshDrawModeEnum MeshDrawMode; - static TextureCompressionModeEnum TextureCompressionMode; static NPatchesGapFillingModeEnum NPatchesGapFillingMode; static unsigned NPatchesLevel; static bool IsTexturingEnabled; static bool IsColoringEnabled; + static bool Lite; + // This is the default native screen size which will be set for each // RenderObject on construction. The native screen size is the screen size // at which the object was designed to be viewed, and it is used in the diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp deleted file mode 100644 index 35b1e2c296..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.cpp +++ /dev/null @@ -1,442 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/ww3dformat.cpp $* - * * - * Original Author:: Hector Yee * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 8/20/01 11:51a $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "ww3dformat.h" -#include "vector4.h" -#include "wwdebug.h" -#include "TARGA.H" -#include "dx8wrapper.h" -#include "dx8caps.h" -#include - - /* - WW3D_FORMAT_UNKNOWN=0, - WW3D_FORMAT_R8G8B8, - WW3D_FORMAT_A8R8G8B8, - WW3D_FORMAT_X8R8G8B8, - WW3D_FORMAT_R5G6B5, - WW3D_FORMAT_X1R5G5B5, - WW3D_FORMAT_A1R5G5B5, - WW3D_FORMAT_A4R4G4B4, - WW3D_FORMAT_R3G3B2, - WW3D_FORMAT_A8, - WW3D_FORMAT_A8R3G3B2, - WW3D_FORMAT_X4R4G4B4, - WW3D_FORMAT_A8P8, - WW3D_FORMAT_P8, - WW3D_FORMAT_L8, - WW3D_FORMAT_A8L8, - WW3D_FORMAT_A4L4, - WW3D_FORMAT_COUNT // Used only to determine number of surface formats -*/ - -void Get_WW3D_Format_Name(WW3DFormat format, StringClass& name) -{ - switch (format) { - default: - case WW3D_FORMAT_UNKNOWN: name="Unknown"; break; - case WW3D_FORMAT_R8G8B8: name="R8G8B8"; break; - case WW3D_FORMAT_A8R8G8B8: name="A8R8G8B8"; break; - case WW3D_FORMAT_X8R8G8B8: name="X8R8G8B8"; break; - case WW3D_FORMAT_R5G6B5: name="R5G6B5"; break; - case WW3D_FORMAT_X1R5G5B5: name="X1R5G5B5"; break; - case WW3D_FORMAT_A1R5G5B5: name="A1R5G5B5"; break; - case WW3D_FORMAT_A4R4G4B4: name="A4R4G4B4"; break; - case WW3D_FORMAT_R3G3B2: name="R3G3B2"; break; - case WW3D_FORMAT_A8: name="A8"; break; - case WW3D_FORMAT_A8R3G3B2: name="A8R3G3B2"; break; - case WW3D_FORMAT_X4R4G4B4: name="X4R4G4B4"; break; - case WW3D_FORMAT_A8P8: name="A8P8"; break; - case WW3D_FORMAT_P8: name="P8"; break; - case WW3D_FORMAT_L8: name="L8"; break; - case WW3D_FORMAT_A8L8: name="A8L8"; break; - case WW3D_FORMAT_A4L4: name="A4L4"; break; - case WW3D_FORMAT_U8V8: name="U8V8"; break; // Bumpmap - case WW3D_FORMAT_L6V5U5: name="L6V5U5"; break; // Bumpmap - case WW3D_FORMAT_X8L8V8U8: name="X8L8V8U8"; break; // Bumpmap - case WW3D_FORMAT_DXT1: name="DXT1"; break; - case WW3D_FORMAT_DXT2: name="DXT2"; break; - case WW3D_FORMAT_DXT3: name="DXT3"; break; - case WW3D_FORMAT_DXT4: name="DXT4"; break; - case WW3D_FORMAT_DXT5: name="DXT5"; break; - } -} - -//********************************************************************************************** -//! Get W3D depth stencil format string name -/*! 06/27/02 KJM -*/ -void Get_WW3D_ZFormat_Name(WW3DZFormat format, StringClass& name) -{ - switch (format) - { - default: - case WW3D_FORMAT_UNKNOWN : name="Unknown"; break; - case WW3D_ZFORMAT_D16_LOCKABLE: name="D16Lockable"; break; // 16-bit z-buffer bit depth. This is an application-lockable surface format. - case WW3D_ZFORMAT_D32 : name="D32"; break; // 32-bit z-buffer bit depth. - case WW3D_ZFORMAT_D15S1 : name="D15S1"; break; // 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 WW3D_ZFORMAT_D24S8 : name="D24S8"; break; // 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel. - case WW3D_ZFORMAT_D16 : name="D16"; break; // 16-bit z-buffer bit depth. - case WW3D_ZFORMAT_D24X8 : name="D24X8"; break; // 32-bit z-buffer bit depth using 24 bits for the depth channel. - case WW3D_ZFORMAT_D24X4S4 : name="D24X4S4"; break; // 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel. -#ifdef _XBOX - case WW3D_ZFORMAT_LIN_D24S8 : name="D24S8LIN"; break; - case WW3D_ZFORMAT_LIN_F24S8 : name="F24S8LIN"; break; - case WW3D_ZFORMAT_LIN_D16 : name="D16LIN"; break; - case WW3D_ZFORMAT_LIN_F16 : name="F16LIN"; break; -#endif - } -} - -// extract the luminance from the RGB using the CIE 709 standard -unsigned char RGB_to_CIEY(Vector4 color) -{ - float lum=0.2126f*color.X + 0.7152f*color.Y + 0.0722f*color.Z; - return (unsigned char) (255.0f*lum); -} - -void Vector4_to_Color(unsigned int *outc,const Vector4 &inc,const WW3DFormat format) -{ - // convert to ARGB 32-bit - unsigned int color=DX8Wrapper::Convert_Color(inc); - unsigned char *argb=(unsigned char*) &color; - unsigned char r,g,b,a,lum; - - switch (format) - { - case WW3D_FORMAT_R8G8B8: - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - *outc=color; - break; - case WW3D_FORMAT_R5G6B5: - r=argb[1] >> 3; - g=argb[2] >> 2; - b=argb[3] >> 3; - *outc=(r << 11) | (g<<5) | b; - break; - case WW3D_FORMAT_X1R5G5B5: - case WW3D_FORMAT_A1R5G5B5: - a=argb[0] >> 7; - r=argb[1] >> 3; - g=argb[2] >> 3; - b=argb[3] >> 3; - *outc=(a<<15) | (r<<10) | (g<<5) | b; - break; - - case WW3D_FORMAT_A4R4G4B4: - case WW3D_FORMAT_X4R4G4B4: - a=argb[0] >> 4; - r=argb[1] >> 4; - g=argb[2] >> 4; - b=argb[3] >> 4; - *outc=(a<<12) | (r<<8) | (g<<4) | b; - break; - case WW3D_FORMAT_R3G3B2: - case WW3D_FORMAT_A8R3G3B2: - a=argb[0]; - r=argb[1] >> 5; - g=argb[2] >> 5; - b=argb[3] >> 6; - *outc=(a<<8) | (r<<5) | (g<<2) | b; - break; - case WW3D_FORMAT_A8: - *outc=argb[0]; - break; - case WW3D_FORMAT_L8: - lum=RGB_to_CIEY(inc); - *outc=lum; - break; - case WW3D_FORMAT_A8L8: - a=argb[0]; - lum=RGB_to_CIEY(inc); - *outc=(a<<8) | lum; - break; - case WW3D_FORMAT_A4L4: - a=argb[0] >> 4; - lum=RGB_to_CIEY(inc); - lum=lum>>4; - *outc=(a<<4) | lum; - break; - default: - WWASSERT(0); - } -} - -void Color_to_Vector4(Vector4* outc,const unsigned int inc,const WW3DFormat format) -{ - WWASSERT(outc); - - unsigned char *argb=(unsigned char*) &inc; - unsigned char a,r,g,b; - a=r=g=b=0; - - switch (format) - { - case WW3D_FORMAT_R8G8B8: - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_X8R8G8B8: - a=argb[0]; - r=argb[1]; - g=argb[2]; - b=argb[3]; - break; - case WW3D_FORMAT_R5G6B5: - r=argb[1]<<3; - g=argb[2]<<2; - b=argb[3]<<3; - break; - case WW3D_FORMAT_X1R5G5B5: - case WW3D_FORMAT_A1R5G5B5: - a=argb[0]<<7; - r=argb[1]<<3; - g=argb[2]<<3; - b=argb[3]<<3; - break; - case WW3D_FORMAT_A4R4G4B4: - a=argb[0]<<4; - r=argb[1]<<4; - g=argb[2]<<4; - b=argb[3]<<4; - break; - case WW3D_FORMAT_R3G3B2: - r=argb[1]<<5; - g=argb[2]<<5; - b=argb[3]<<6; - break; - case WW3D_FORMAT_A8: - a=argb[0]; - break; - case WW3D_FORMAT_A8R3G3B2: - a=argb[0]; - r=argb[1]<<5; - g=argb[2]<<5; - b=argb[3]<<6; - break; - case WW3D_FORMAT_X4R4G4B4: - r=argb[1]<<4; - g=argb[2]<<4; - b=argb[3]<<4; - break; - default: - WWASSERT(0); - } - outc->X=r/255.0f; - outc->Y=g/255.0f; - outc->Z=b/255.0f; - outc->W=a/255.0f; -} - -// ---------------------------------------------------------------------------- -// -// Utility function for determining WW3D format from TGA file header. -// -// ---------------------------------------------------------------------------- - -void Get_WW3D_Format(WW3DFormat& dest_format,WW3DFormat& src_format,unsigned& src_bpp,const Targa& targa) -{ - // Guess the format from the TGA Header bits: - src_format = WW3D_FORMAT_UNKNOWN; - src_bpp=0; - switch (targa.Header.PixelDepth) { - case 32: src_format = WW3D_FORMAT_A8R8G8B8; src_bpp=4; break; - case 24: src_format = WW3D_FORMAT_R8G8B8; src_bpp=3; break; - case 16: src_format = WW3D_FORMAT_A1R5G5B5; src_bpp=2; break; - case 8: - src_bpp=1; - if (targa.Header.ColorMapType == 1) src_format = WW3D_FORMAT_P8; - else if (targa.Header.ImageType == TGA_MONO) src_format = WW3D_FORMAT_L8; - else src_format = WW3D_FORMAT_A8; - break; - default: - WWDEBUG_SAY(("TextureClass: Targa has unsupported bitdepth(%i)\n",targa.Header.PixelDepth)); - WWASSERT(0); - break; - } - dest_format=src_format; - if ((dest_format==WW3D_FORMAT_P8) || (dest_format==WW3D_FORMAT_L8)) { - dest_format=WW3D_FORMAT_X8R8G8B8; - } - dest_format=Get_Valid_Texture_Format(dest_format,false); // No compressed destination format if reading from targa... - -} - -// ---------------------------------------------------------------------------- -// -// Utility function for determining valid WW3D format -// -// ---------------------------------------------------------------------------- - -WW3DFormat Get_Valid_Texture_Format(WW3DFormat format, bool is_compression_allowed) -{ - int w,h,bits; - bool windowed; - - if (!DX8Wrapper::Get_Current_Caps()->Support_DXTC() || - !is_compression_allowed || - WW3D::Get_Texture_Compression_Mode()==WW3D::TEXTURE_COMPRESSION_DISABLE) { - switch (format) { - case WW3D_FORMAT_DXT1: format=WW3D_FORMAT_R8G8B8; break; - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: format=WW3D_FORMAT_A8R8G8B8; break; - default: break; - } - } - else { - switch (format) { - case WW3D_FORMAT_DXT1: - // NVidia hack - switch to DXT2 is there is no DXT1 support (which is disabled on NVidia cards) - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_DXT1) && - DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(WW3D_FORMAT_DXT2)) { - format=WW3D_FORMAT_DXT2; - } - break; - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(format)) format=WW3D_FORMAT_A8R8G8B8; - break; - } - } - - if (format==WW3D_FORMAT_R8G8B8) { - format=WW3D_FORMAT_X8R8G8B8; - } - - WW3D::Get_Device_Resolution(w,h,bits,windowed); - // if the device bitdepth is 16, don't allow 32 bit textures - if (bits<=16) { - switch (format) { - case WW3D_FORMAT_A8R8G8B8: return WW3D_FORMAT_A4R4G4B4; - case WW3D_FORMAT_X8R8G8B8: - case WW3D_FORMAT_R8G8B8: return WW3D_FORMAT_R5G6B5; - case WW3D_FORMAT_A4R4G4B4: - case WW3D_FORMAT_A1R5G5B5: - case WW3D_FORMAT_R5G6B5: - case WW3D_FORMAT_L8: - case WW3D_FORMAT_A8: - case WW3D_FORMAT_P8: - default: - // Basically, anything goes here (just make sure the most common 32 bit formats are converted to 16 bit - break; - } - - } - - // Fallback if the hardware doesn't support the texture format - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(format)) { - format=WW3D_FORMAT_A8R8G8B8; - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(format)) { - format=WW3D_FORMAT_A4R4G4B4; - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(format)) { - // If still no luck, try non-alpha formats - format=WW3D_FORMAT_A8R8G8B8; - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(format)) { - format=WW3D_FORMAT_R5G6B5; - if (!DX8Wrapper::Get_Current_Caps()->Support_Texture_Format(format)) { - WWASSERT_PRINT(0,("No valid texture format found")); - } - } - } - } - } - - return format; -} - -unsigned Get_Bytes_Per_Pixel(WW3DFormat format) -{ - switch (format) { - case WW3D_FORMAT_X8R8G8B8: - case WW3D_FORMAT_A8R8G8B8: return 4; - case WW3D_FORMAT_R8G8B8: return 3; - case WW3D_FORMAT_A4R4G4B4: - case WW3D_FORMAT_A1R5G5B5: - case WW3D_FORMAT_R5G6B5: return 2; - case WW3D_FORMAT_L8: - case WW3D_FORMAT_A8: - case WW3D_FORMAT_P8: return 1; - default: WWASSERT(0); break; - } - return 0; -} - -unsigned Get_Num_Depth_Bits(WW3DZFormat zformat) -{ - switch (zformat) - { - case WW3D_ZFORMAT_D16_LOCKABLE: return 16; break; - case WW3D_ZFORMAT_D32 : return 32; break; - case WW3D_ZFORMAT_D15S1 : return 15; break; - case WW3D_ZFORMAT_D24S8 : return 24; break; - case WW3D_ZFORMAT_D16 : return 16; break; - case WW3D_ZFORMAT_D24X8 : return 24; break; - case WW3D_ZFORMAT_D24X4S4 : return 24; break; -#ifdef _XBOX - case WW3D_ZFORMAT_LIN_D24S8 : return 24; break; - case WW3D_ZFORMAT_LIN_F24S8 : return 24; break; - case WW3D_ZFORMAT_LIN_D16 : return 16; break; - case WW3D_ZFORMAT_LIN_F16 : return 16; break; -#endif - }; - return 0; -}; - -unsigned Get_Num_Stencil_Bits(WW3DZFormat zformat) -{ - switch (zformat) - { - case WW3D_ZFORMAT_D16_LOCKABLE: return 0; break; - case WW3D_ZFORMAT_D32 : return 0; break; - case WW3D_ZFORMAT_D15S1 : return 1; break; - case WW3D_ZFORMAT_D24S8 : return 8; break; - case WW3D_ZFORMAT_D16 : return 0; break; - case WW3D_ZFORMAT_D24X8 : return 0; break; - case WW3D_ZFORMAT_D24X4S4 : return 4; break; -#ifdef _XBOX - case WW3D_ZFORMAT_LIN_D24S8 : return 8; break; - case WW3D_ZFORMAT_LIN_F24S8 : return 8; break; - case WW3D_ZFORMAT_LIN_D16 : return 0; break; - case WW3D_ZFORMAT_LIN_F16 : return 0; break; -#endif - }; - return 0; -}; diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.h deleted file mode 100644 index 396cf6603b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dformat.h +++ /dev/null @@ -1,205 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/ww3dformat.h $* - * * - * Original Author:: Nathaniel Hoffman * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 8/20/01 9:41a $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Vector4_to_Color - converts a vector4 to the format in format * - * Color_to_Vector4 - converts a color in the format described in format to a Vector4 * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WW3DFORMAT_H -#define WW3DFORMAT_H - -#include "always.h" -#include "wwstring.h" - -class Vector4; -class Targa; - -/* -** Enum for possible surface formats. This is a small subset of the D3DFORMAT -** enum which lists the formats supported by DX8; we will add new members to -** this list as needed (keeping it in the same order as D3DFORMAT). -** NOTE: Whenever this is changed, formconv.h/.cpp must be modified as well -** (that contains the code for converting between this and D3DFORMAT).. -** -** The format names use the D3DFORMAT conventions: -** A = Alpha -** R = Red -** G = Green -** B = Blue -** X = Unused Bits -** P = Palette -** L = Luminance -** -** Further, the order of the pieces are from MSB first; hence -** WW3D_FORMAT_A8L8 indicates that the high byte of this two byte -** format is alpha. -*/ -enum WW3DFormat { - WW3D_FORMAT_UNKNOWN=0, - WW3D_FORMAT_R8G8B8, - WW3D_FORMAT_A8R8G8B8, - WW3D_FORMAT_X8R8G8B8, - WW3D_FORMAT_R5G6B5, - WW3D_FORMAT_X1R5G5B5, - WW3D_FORMAT_A1R5G5B5, - WW3D_FORMAT_A4R4G4B4, - WW3D_FORMAT_R3G3B2, - WW3D_FORMAT_A8, - WW3D_FORMAT_A8R3G3B2, - WW3D_FORMAT_X4R4G4B4, - WW3D_FORMAT_A8P8, - WW3D_FORMAT_P8, - WW3D_FORMAT_L8, - WW3D_FORMAT_A8L8, - WW3D_FORMAT_A4L4, - WW3D_FORMAT_U8V8, // Bumpmap - WW3D_FORMAT_L6V5U5, // Bumpmap - WW3D_FORMAT_X8L8V8U8, // Bumpmap - WW3D_FORMAT_DXT1, - WW3D_FORMAT_DXT2, - WW3D_FORMAT_DXT3, - WW3D_FORMAT_DXT4, - WW3D_FORMAT_DXT5, - WW3D_FORMAT_COUNT // Used only to determine number of surface formats -}; - -// depth stencil buffer formats -enum WW3DZFormat -{ - WW3D_ZFORMAT_UNKNOWN=0, - WW3D_ZFORMAT_D16_LOCKABLE, // 16-bit z-buffer bit depth. This is an application-lockable surface format. - WW3D_ZFORMAT_D32, // 32-bit z-buffer bit depth. - WW3D_ZFORMAT_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. - WW3D_ZFORMAT_D24S8, // 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel. - WW3D_ZFORMAT_D16, // 16-bit z-buffer bit depth. - WW3D_ZFORMAT_D24X8, // 32-bit z-buffer bit depth using 24 bits for the depth channel. - WW3D_ZFORMAT_D24X4S4, // 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel. -#ifdef _XBOX - WW3D_ZFORMAT_LIN_D24S8, - WW3D_ZFORMAT_LIN_F24S8, - WW3D_ZFORMAT_LIN_D16, - WW3D_ZFORMAT_LIN_F16, -#endif - WW3D_ZFORMAT_COUNT -}; - -// Utility function - not much used otherwise it would use an array. -// NOTE: when adding values to WW3DFormat add here also (if they have alpha). -inline bool Has_Alpha(WW3DFormat format) { - switch (format) { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_A1R5G5B5: - case WW3D_FORMAT_A4R4G4B4: - case WW3D_FORMAT_A8: - case WW3D_FORMAT_A8R3G3B2: - case WW3D_FORMAT_A8P8: - case WW3D_FORMAT_A8L8: - case WW3D_FORMAT_A4L4: - case WW3D_FORMAT_DXT2: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - return true; - break; - default: - return false; - break; - }; -} - -inline int Alpha_Bits(WW3DFormat format) { - switch (format) { - case WW3D_FORMAT_A8R8G8B8: - case WW3D_FORMAT_A8: - case WW3D_FORMAT_A8R3G3B2: - case WW3D_FORMAT_A8P8: - case WW3D_FORMAT_A8L8: - return 8; - break; - case WW3D_FORMAT_A4R4G4B4: - case WW3D_FORMAT_A4L4: - case WW3D_FORMAT_DXT3: - case WW3D_FORMAT_DXT4: - case WW3D_FORMAT_DXT5: - return 4; - break; - case WW3D_FORMAT_A1R5G5B5: - case WW3D_FORMAT_DXT2: - return 1; - break; - default: - return 0; - break; - }; -} - -// Color convertion routines - -// The color will be returned as an unsigned int always -// any unused bits will be garbage -void Vector4_to_Color(unsigned int *outc,const Vector4 &inc,const WW3DFormat format); - -// If the format does not support alpha -// the alpha will be garbage -void Color_to_Vector4(Vector4* outc,const unsigned int inc,const WW3DFormat format); - -// Define matching WW3D format based from Targa header. -// -// dest_format - WW3DFormat that can be used as a destination (D3D surface) on current hardware -// src_format - WW3DFormat that represents the format the bitmap is stored in the targa file. -// src_bpp - bytes per pixel in the source surface -// targa - reference to the targa object... -void Get_WW3D_Format(WW3DFormat& dest_format,WW3DFormat& src_format,unsigned& src_bpp,const Targa& targa); - -// Get valid texture format (on current hardware) that is closest to the given format (for instance, 32 bit ARGB8888 would -// return 16 bit ARGB4444 if the device doesn't support 32 bit textures). -// Pass false to the second parameter if you don't wish to consider compressed textures on hardware that supports them. -// The parameter has no effect on hardware that doesn't support compression. -WW3DFormat Get_Valid_Texture_Format(WW3DFormat format,bool is_compression_allowed); - -unsigned Get_Bytes_Per_Pixel(WW3DFormat format); - -void Get_WW3D_Format_Name(WW3DFormat format, StringClass& name); -void Get_WW3D_ZFormat_Name(WW3DZFormat format, StringClass& name); - -unsigned Get_Num_Depth_Bits(WW3DZFormat zformat); -unsigned Get_Num_Stencil_Bits(WW3DZFormat zformat); - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dids.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dids.h deleted file mode 100644 index 83e2f64018..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dids.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/ww3dids.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef WW3DIDS_H -#define WW3DIDS_H - -#include "saveloadids.h" - -/* -** These are the chunk-id's used by all persistant objects in WW3D. The persistant object -** framework is defined in the WWSaveLoad library. -** -** Sept 23, 1999 -** - Initial implementation of making the Commando engine persistant included making some -** of WW3D persistant. For this initial implementation, we're going to assume that we -** can re-create all of our game objects from the asset manager and patch up any state -** changes with custom game object code. Therefore, the base class RenderObjClass has -** a persist manager which simply saves the name of the render object and its transform -** and re-creates that render object from the asset manager. -** -** - Currently lights are procedurally created rather than created from the asset manager. -** For this reason, I'm implementing a persist manager and save-load functionality for -** light class. In the future lights may come from the asset manager in which case we -** could remove this code. -** -** - It is also possible that later on when we make the save game stuff more robust we may -** need to implement actual save load calls for more render objects but hopefully we can -** avoid that since it will at least double the size of our files and just seems like a -** lot of work to solve a few specific problems. -*/ -enum -{ - WW3D_PERSIST_CHUNKID_RENDEROBJ = CHUNKID_WW3D_BEGIN, - WW3D_PERSIST_CHUNKID_LIGHT, - WW3D_PERSIST_CHUNKID_DAZZLE, -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h b/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h deleted file mode 100644 index 257989c2df..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WW3D2/ww3dtrig.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/ww3d2/ww3dtrig.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/08/01 10:04a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WW3DTRIG_H -#define WW3DTRIG_H - - -/* -** The WW3D Library will check for debugging triggers using the following ID's -** Your application may install a trigger handler into the WWDebug library and then -** watch for these ID's coming through. Then if you wish to "trigger" one, then -** assign a key or something to the trigger and when your trigger handler is called, -** check if the key is down. The trigger can be enabled in any way you want but -** in practice, most things will probably be tied to keys. -*/ -enum -{ - WW3D_TRIGGER_RENDER_STATS = 0x100, // display render stats in the debug window - WW3D_TRIGGER_SURFACE_CACHE_STATS = 0x101, // display surface cache info in the debug window - WW3D_TRIGGER_PROCESS_STATS = 0x102 // render stats for last frame only -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h deleted file mode 100644 index 8ca02bbe63..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AABTreeSoundCullClass.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/AABTreeSoundCullClass.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 4/12/99 11:07a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __AABTREESOUNDCULLCLASS_H -#define __AABTREESOUNDCULLCLASS_H - -#include "aabtreecull.h" - - -///////////////////////////////////////////////////////////////////////////////// -// -// AABTreeSoundCullClass -// -// Simple derived class that implements 2 required methods from AABTreeCullClass. -// -class AABTreeSoundCullClass : public AABTreeCullClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - AABTreeSoundCullClass (void) - : AABTreeCullClass (NULL) { } - - virtual ~AABTreeSoundCullClass (void) { } - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - void Load (ChunkLoadClass & cload) { } - void Save (ChunkSaveClass & csave) { } - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - virtual void Load_Node_Contents (AABTreeNodeClass * node,ChunkLoadClass & cload) { }; - virtual void Save_Node_Contents (AABTreeNodeClass * node,ChunkSaveClass & csave) { }; - -}; - -#endif //__AABTREESOUNDCULLCLASS_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp deleted file mode 100644 index 395f9da62b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.cpp +++ /dev/null @@ -1,1792 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/AudibleSound.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/27/01 7:25p $* - * * - * $Revision:: 27 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "AudibleSound.h" -#include "WWAudio.h" -#include "ww3d.h" -#include "wwdebug.h" -#include "SoundBuffer.h" -#include "Utils.h" -#include "SoundScene.h" -#include "FilteredSound.h" -#include "Threads.h" -#include "SoundChunkIDs.h" -#include "simpledefinitionfactory.h" -#include "persistfactory.h" -#include "LogicalSound.h" -#include "definitionclassids.h" -#include "soundstreamhandle.h" -#include "sound2dhandle.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Static factories -////////////////////////////////////////////////////////////////////////////////// -DECLARE_DEFINITION_FACTORY(AudibleSoundDefinitionClass, CLASSID_SOUND_DEF, "Sound") _SoundDefFactory; -SimplePersistFactoryClass _AudibleSoundDefPersistFactory; -SimplePersistFactoryClass _AudibleSoundPersistFactory; - - -////////////////////////////////////////////////////////////////////////////////// -// Save/Load constants -////////////////////////////////////////////////////////////////////////////////// - -namespace AUDIBLE_SOUND_SAVELOAD -{ - enum - { - CHUNKID_VARIABLES = 0x00000100, - CHUNKID_BASE_CLASS - }; - - enum - { - VARID_STATE = 0x01, - VARID_TYPE, - - VARID_PRIORITY, - VARID_VOLUME, - VARID_PAN, - VARID_LOOP_COUNT, - VARID_LOOPS_LEFT, - VARID_SOUND_LENGTH, - VARID_CURR_POS, - VARID_TRANSFORM, - VARID_PREV_TRANSFORM, - VARID_IS_CULLED, - VARID_IS_DIRTY, - VARID_DROP_OFF, - VARID_FILENAME, - VARID_THIS_PTR, - VARID_START_OFFSET, - VARID_LISTENER_TRANSFORM, - VARID_PITCH_FACTOR - }; -} - -namespace AUDIBLE_SOUND_DEF_SAVELOAD -{ - enum - { - CHUNKID_VARIABLES = 0x00000100, - CHUNKID_BASE_CLASS = 0x00000200, - }; - - enum - { - VARID_UNUSED1 = 0x01, - VARID_UNUSED2, - VARID_PRIORITY, - VARID_VOLUME, - VARID_PAN, - VARID_LOOP_COUNT, - VARID_DROP_OFF, - VARID_MAX_VOL, - VARID_TYPE, - VARID_IS3D, - VARID_FILENAME, - VARID_DISPLAY_TEXT, - VARID_LOGICAL_MASK, - VARID_LOGICAL_DELAY, - VARID_CREATE_LOGICAL, - VARID_LOGICAL_DROP_OFF, - VARID_SPHERE_COLOR, - VARID_START_OFFSET, - VARID_PITCH_FACTOR - }; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// AudibleSoundClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass::AudibleSoundClass (void) - : m_Priority (0.5F), - m_RuntimePriority (0), - m_SoundHandle (NULL), - m_Length (0), - m_CurrentPosition (0), - m_Timestamp (0), - m_State (STATE_STOPPED), - m_Buffer (NULL), - m_Volume (1.0F), - m_Pan (0.5F), - m_LoopCount (1), - m_LoopsLeft (0), - m_Type (TYPE_SOUND_EFFECT), - m_bDirty (true), - m_DropOffRadius (1), - m_IsCulled (true), - m_pConvertedFormat (NULL), - m_PrevTransform (1), - m_Transform (1), - m_ListenerTransform (1), - m_Definition (NULL), - m_LogicalSound (NULL), - m_StartOffset (0), - m_PitchFactor (1.0F) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// AudibleSoundClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass::AudibleSoundClass (const AudibleSoundClass &src) - : m_Priority (0.5F), - m_RuntimePriority (0), - m_SoundHandle (NULL), - m_Length (0), - m_CurrentPosition (0), - m_Timestamp (0), - m_State (STATE_STOPPED), - m_Buffer (NULL), - m_Volume (1.0F), - m_Pan (0.5F), - m_LoopCount (1), - m_LoopsLeft (0), - m_Type (TYPE_SOUND_EFFECT), - m_bDirty (true), - m_DropOffRadius (1), - m_IsCulled (true), - m_pConvertedFormat (NULL), - m_PrevTransform (1), - m_Transform (1), - m_Definition (NULL), - m_LogicalSound (NULL), - m_StartOffset (0), - m_PitchFactor (1.0F) -{ - (*this) = src; - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~AudibleSoundClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass::~AudibleSoundClass (void) -{ - m_State = STATE_STOPPED; - Free_Conversion (); - REF_PTR_RELEASE (m_LogicalSound); - - // - // Delay the release of the buffer (fixes a sync bug - // with Miles internals). - // - if (m_Buffer != NULL) { - WWAudioThreadsClass::Add_Delayed_Release_Object (m_Buffer); - m_Buffer = NULL; - } - - Free_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const AudibleSoundClass & -AudibleSoundClass::operator= (const AudibleSoundClass &src) -{ - m_Timestamp = src.m_Timestamp; - m_Type = src.m_Type; - m_LoopCount = src.m_LoopCount; - m_LoopsLeft = src.m_LoopsLeft; - m_Length = src.m_Length; - m_CurrentPosition = src.m_CurrentPosition; - m_bDirty = src.m_bDirty; - m_DropOffRadius = src.m_DropOffRadius; - m_PrevTransform = src.m_PrevTransform; - - m_State = STATE_STOPPED; - Set_Buffer (src.m_Buffer); - m_State = src.m_State; - - Cull_Sound (src.m_IsCulled); - Set_Volume (src.m_Volume); - Set_Pan (src.m_Pan); - Set_Priority (src.m_Priority); - Set_Transform (src.m_Transform); - Set_Listener_Transform (src.m_ListenerTransform); - return (*this); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Buffer (SoundBufferClass *buffer) -{ - // - // Delay the release of the buffer (fixes a sync bug - // with Miles internals). - // - if (m_Buffer != NULL) { - WWAudioThreadsClass::Add_Delayed_Release_Object (m_Buffer); - m_Buffer = NULL; - } - REF_PTR_SET (m_Buffer, buffer); - - // Stop playing if necessary - bool resume = false; - if (m_State == STATE_PLAYING) { - resume = Stop (false); - } - - // Get the time (in ms) that this buffer will play for... - if (m_Buffer != NULL) { - m_Length = m_Buffer->Get_Duration (); - } - - // Reinitialize the handle with this new data - Initialize_Miles_Handle (); - - // Resume playing if necessary - if (resume) { - Play (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -AudibleSoundClass::Get_Buffer (void) const -{ - if (m_Buffer) { - m_Buffer->Add_Ref (); - } - - return m_Buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Peek_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -AudibleSoundClass::Peek_Buffer (void) const -{ - return m_Buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Play -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::Play (bool alloc_handle) -{ - MMSLockClass lock; - - // If we don't have a valid handle already, try to get one from miles - if (alloc_handle && (m_pConvertedFormat == NULL)) { - Allocate_Miles_Handle (); - } - - // Let the audio system know this sound is playing - if (m_State != STATE_PLAYING) { - WWAudioClass::Get_Instance ()->Add_To_Playlist (this); - m_State = STATE_PLAYING; - m_Timestamp = ::GetTickCount (); - m_LoopsLeft = m_LoopCount; - - // If we have a valid handle, then start playing the sample - if (m_SoundHandle != NULL) { - m_SoundHandle->Start_Sample (); - } - - m_CurrentPosition = m_StartOffset * m_Length; - if (m_CurrentPosition > 0) { - Seek (m_CurrentPosition); - } - - - // Fire an event - On_Event (AudioCallbackClass::EVENT_SOUND_STARTED); - - // - // Create the associate logical sound (if necessary) - // - if (m_LogicalSound == NULL && m_Definition != NULL) { - m_LogicalSound = m_Definition->Create_Logical (); - } - - // - // Add this logical sound to the scene - // - if (m_LogicalSound != NULL) { - m_LogicalSound->Set_User_Data (m_UserObj, m_UserData); - m_LogicalSound->Set_Transform (m_Transform); - m_LogicalSound->Add_To_Scene (); - } - - // - // Should we send off the text notification? - // - if (m_IsCulled == false && m_Definition != NULL) { - const StringClass &text = m_Definition->Get_Display_Text (); - WWAudioClass::Get_Instance ()->Fire_Text_Callback (this, text); - } - } - - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Pause -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::Pause (void) -{ - MMSLockClass lock; - - // Assume failure - bool retval = false; - - if (m_State == STATE_PLAYING) { - - // Pass the pause request onto miles - if (m_SoundHandle != NULL) { - m_SoundHandle->Stop_Sample (); - } - - // Remember our new state - m_State = STATE_PAUSED; - retval = true; - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Resume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::Resume (void) -{ - MMSLockClass lock; - - // Assume failure - bool retval = false; - - if (m_State == STATE_PAUSED) { - - // Pass the resume request onto miles - if (m_SoundHandle != NULL) { - m_SoundHandle->Resume_Sample (); - } - - // Remember our new state - m_State = STATE_PLAYING; - retval = true; - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Stop -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::Stop (bool remove_from_playlist) -{ - MMSLockClass lock; - - // Assume failure - bool retval = false; - - if ((m_State == STATE_PAUSED) || - (m_State == STATE_PLAYING)) { - - // Actually stop the sample from playing - if (m_SoundHandle != NULL) { - m_SoundHandle->Stop_Sample (); - } - - // Free up the handle we have been using - Free_Miles_Handle (); - m_State = STATE_STOPPED; - retval = true; - - // Reset some of the playing attributes - m_Timestamp = 0; - m_CurrentPosition = 0; - - if (remove_from_playlist) { - WWAudioClass::Get_Instance ()->Remove_From_Playlist (this); - } - - // - // Stop the logical portion of the sound - // - if (m_LogicalSound != NULL && m_LogicalSound->Is_Single_Shot () == false) { - m_LogicalSound->Remove_From_Scene (); - } - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Seek -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Seek (unsigned long milliseconds) -{ - MMSLockClass lock; - - if ((milliseconds >= 0) && (milliseconds < m_Length)) { - - // Record our new position and recalculate the 'starting' timestamp - // from this information - m_CurrentPosition = milliseconds; - if (m_State == STATE_PLAYING) { - m_Timestamp = ::GetTickCount () - m_CurrentPosition; - } - - // Update the actual sound data if we are playing the sound - if (m_SoundHandle != NULL) { - m_SoundHandle->Set_Sample_MS_Position (m_CurrentPosition); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Miles_Handle (MILES_HANDLE handle) -{ - // - // Start fresh - // - Free_Miles_Handle (); - - // - // Is our data valid? - // - if (handle != INVALID_MILES_HANDLE && m_Buffer != NULL) { - - // - // Determine which type of sound handle to create, streaming or standard 2D - // - if (m_Buffer->Is_Streaming ()) { - m_SoundHandle = W3DNEW SoundStreamHandleClass; - } else { - m_SoundHandle = W3DNEW Sound2DHandleClass; - } - - // - // Configure the sound handle - // - m_SoundHandle->Set_Miles_Handle (handle); - - // - // Use this new handle - // - Initialize_Miles_Handle (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Initialize_Miles_Handle (void) -{ - MMSLockClass lock; - - // If this sound is already playing, then update its - // playing position to make sure we really should - // be playing it... (it will free the miles handle if not) - if (m_State == STATE_PLAYING) { - Update_Play_Position (); - } - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - - // - // Initialize the handle - // - m_SoundHandle->Initialize (m_Buffer); - - // - // Record the total length of the sample in milliseconds... - // - m_SoundHandle->Get_Sample_MS_Position ((S32 *)&m_Length, NULL); - - // - // Pass our cached settings onto miles - // - m_SoundHandle->Set_Sample_Volume (0); - m_SoundHandle->Set_Sample_Pan (int(m_Pan * 127.0F)); - m_SoundHandle->Set_Sample_Loop_Count (m_LoopCount); - - // - // Apply the pitch factor (if necessary) - // - if (m_PitchFactor != 1.0F) { - Set_Pitch_Factor (m_PitchFactor); - } - - // If this sound is already playing (and just now got a handle) - // then make sure we start it. - if (m_State == STATE_PLAYING) { - m_SoundHandle->Start_Sample (); - - // Update the loop count based on the number of loops left - m_SoundHandle->Set_Sample_Loop_Count (m_LoopsLeft); - } - - // Seek to the position of the sound where we last left off. - // For example, this sound could have gotten bumped due to a low priority, - // but is now back and ready to resume at the position it would have been - // at if it was never bumped. - Seek (m_CurrentPosition); - - // - // Pass the 'real' volume onto miles - // - float real_volume = Determine_Real_Volume (); - m_SoundHandle->Set_Sample_Volume (int(real_volume * 127.0F)); - - // - // Associate this object instance with the handle - // - m_SoundHandle->Set_Sample_User_Data (INFO_OBJECT_PTR, (S32)this); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Free_Miles_Handle (void) -{ - MMSLockClass lock; - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - - // - // Release our hold on this handle - // - m_SoundHandle->Set_Sample_User_Data (INFO_OBJECT_PTR, NULL); - m_SoundHandle->End_Sample (); - - // - // Remove the association between file handle and AudibleSoundClass object - // - //m_SoundHandle->Set_Sample_User_Data (INFO_OBJECT_PTR, NULL); - - // - // Free the sound handle object - // - delete m_SoundHandle; - m_SoundHandle = NULL; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Pan -// -//////////////////////////////////////////////////////////////////////////////////////////////// -float -AudibleSoundClass::Get_Pan (void) -{ - MMSLockClass lock; - - // - // Do we have a valid sample handle from miles? - // - if (m_SoundHandle != NULL) { - m_Pan = ((float)m_SoundHandle->Get_Sample_Pan ()) / 127.0F; - } - - return m_Pan; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Pan -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Pan (float pan) -{ - MMSLockClass lock; - - // - // Cache the normalized pan value - // - m_Pan = min (pan, 1.0F); - m_Pan = max (m_Pan, 0.0F); - - // - // Do we have a valid sample handle from miles? - // - if (m_SoundHandle != NULL) { - m_SoundHandle->Set_Sample_Pan (int(m_Pan * 127.0F)); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Pitch_Factor -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Pitch_Factor (float factor) -{ - MMSLockClass lock; - - m_PitchFactor = factor; - - // - // Do we have a valid sample handle from miles? - // - if (m_SoundHandle != NULL) { - - if (m_Buffer != NULL) { - - // - // Get the base rate of the sound and scale our playback rate - // based on the factor - // - int base_rate = m_Buffer->Get_Rate (); - int new_rate = base_rate * m_PitchFactor; - m_SoundHandle->Set_Sample_Playback_Rate (new_rate); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Playback_Rate -// -//////////////////////////////////////////////////////////////////////////////////////////////// -int -AudibleSoundClass::Get_Playback_Rate (void) -{ - MMSLockClass lock; - int retval = 0; - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - retval = m_SoundHandle->Get_Sample_Playback_Rate (); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Playback_Rate -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Playback_Rate (int rate_in_hz) -{ - MMSLockClass lock; - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - m_SoundHandle->Set_Sample_Playback_Rate (rate_in_hz); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -float -AudibleSoundClass::Get_Volume (void) -{ - MMSLockClass lock; - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - m_Volume = ((float)m_SoundHandle->Get_Sample_Volume ()) / 127.0F; - } - - // Return the current pan value - return m_Volume; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Volume (float volume) -{ - MMSLockClass lock; - - // Cache the normalized volume value - m_Volume = min (volume, 1.0F); - m_Volume = max (m_Volume, 0.0F); - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - - // Calculate the 'real' volume to set based on the global volume and the sound - // effect volume. - float real_volume = Determine_Real_Volume (); - m_SoundHandle->Set_Sample_Volume (int(real_volume * 127.0F)); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Loops_Left -// -//////////////////////////////////////////////////////////////////////////////////////////////// -int -AudibleSoundClass::Get_Loops_Left (void) const -{ - return m_LoopsLeft; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Loop_Count -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Loop_Count (int count) -{ - MMSLockClass lock; - - // Cache the loop count - m_LoopCount = count; - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - m_SoundHandle->Set_Sample_Loop_Count (m_LoopCount); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Priority -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Priority (float priority) -{ - MMSLockClass lock; - - // Cache the normalized priority - m_Priority = min (priority, 1.0F); - m_Priority = max (m_Priority, 0.0F); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::On_Frame_Update (unsigned int milliseconds) -{ - // - // Do we need to track this sound's play-progress? - // - if ((m_LoopCount != INFINITE_LOOPS) && - (m_State == STATE_PLAYING) && - (m_Length > 0)) - { - Update_Play_Position (); - } - - if (m_pConvertedFormat != NULL) { - m_pConvertedFormat->Re_Sync (*this); - } - - // - // Move the logical sound with the audible one... - // - if (m_LogicalSound != NULL) { - m_LogicalSound->Set_Transform (m_Transform); - } - - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Play_Position -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Update_Play_Position (void) -{ - // Determine the current offset from the beginning of the sound buffer. - unsigned long play_time = ::GetTickCount () - m_Timestamp; - m_CurrentPosition = play_time; - - // Have we gone past the end of a sounds play-time? - if ((m_CurrentPosition > m_Length) && (m_Length > 0)) { - - // Normalize our position and timestamp information - m_CurrentPosition = m_CurrentPosition % m_Length; - m_Timestamp = ::GetTickCount () - m_CurrentPosition; - - // Decrement our count of remaining loops (if necessary) - if (m_LoopCount != INFINITE_LOOPS) { - m_LoopsLeft -= (play_time / m_Length); - } - - // Trigger the 'end loop' event - On_Loop_End (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Allocate_Miles_Handle (void) -{ - // - // If we need to, get a play-handle from the audio system - // - if (m_SoundHandle == NULL) { - Set_Miles_Handle ((MILES_HANDLE)WWAudioClass::Get_Instance ()->Get_2D_Sample (*this)); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Loop_End -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::On_Loop_End (void) -{ - // Determine if the sound is actually finished or still looping - if ((m_LoopCount != INFINITE_LOOPS) && (m_LoopsLeft < 1)) { - - // Let the audio system know that we are done with this sound - Stop (); - if (m_Scene != NULL) { - Remove_From_Scene (); - } - - // Fire an event - On_Event (AudioCallbackClass::EVENT_SOUND_ENDED); - - } else { - Restart_Loop (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Determine_Real_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -float -AudibleSoundClass::Determine_Real_Volume (void) const -{ - float volume = m_Volume; - - // Is this a piece of music or is it a sound effect? - if (m_Type == TYPE_MUSIC) { - volume = volume * WWAudioClass::Get_Instance ()->Get_Music_Volume (); - } else if (m_Type == TYPE_SOUND_EFFECT) { - volume = volume * WWAudioClass::Get_Instance ()->Get_Sound_Effects_Volume (); - } - - // Return the 'real' volume - return volume; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Filename -// -//////////////////////////////////////////////////////////////////////////////////////////////// -LPCTSTR -AudibleSoundClass::Get_Filename (void) const -{ - LPCTSTR filename = NULL; - if (m_Buffer != NULL) { - filename = m_Buffer->Get_Filename (); - } - - return filename; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Cull_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Cull_Sound (bool culled) -{ - // Is our state changing? - if (m_IsCulled != culled) { - m_IsCulled = culled; - - // - // If this sound is culled, then throw away its play-handle. - // Otherwise, make sure we have a valid handle. - // - // Note: We also free the handle if a converted form - // of the sound is currently playing. - // - if (m_IsCulled || (m_pConvertedFormat != NULL)) { - Free_Miles_Handle (); - } else { - Allocate_Miles_Handle (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Transform -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Transform (const Matrix3D &transform) -{ - // Update our internal transform - m_PrevTransform = m_Transform; - m_Transform = transform; - Set_Dirty (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Position -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_Position (const Vector3 &position) -{ - // Update our internal transform - m_Transform.Set_Translation (position); - Set_Dirty (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_To_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Add_To_Scene (bool start_playing) -{ - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if ((scene != NULL) && (m_Scene == NULL)) { - - // - // Add this sound to the static culling system - // - m_Scene = scene; - scene->Add_Static_Sound (this, start_playing); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_From_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Remove_From_Scene (void) -{ - if (m_Scene != NULL) { - - // - // Remove this sound from the static culling system - // - m_Scene->Remove_Static_Sound (this); - m_Scene = NULL; - m_PhysWrapper = NULL; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_DropOff_Radius -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Set_DropOff_Radius (float radius) -{ - m_DropOffRadius = radius; - Set_Dirty (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Re_Sync -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Re_Sync (AudibleSoundClass &src) -{ - m_Timestamp = src.m_Timestamp; - m_State = src.m_State; - m_Type = src.m_Type; - m_LoopCount = src.m_LoopCount; - m_LoopsLeft = src.m_LoopsLeft; - m_Length = src.m_Length; - m_CurrentPosition = src.m_CurrentPosition; - m_bDirty = src.m_bDirty; - m_DropOffRadius = src.m_DropOffRadius; - m_PrevTransform = src.m_PrevTransform; - - Cull_Sound (src.m_IsCulled); - Set_Volume (src.m_Volume); - Set_Pan (src.m_Pan); - Set_Priority (src.m_Priority); - Set_Transform (src.m_Transform); - Set_Listener_Transform (src.m_ListenerTransform); - - if (m_State != STATE_PLAYING) { - Free_Miles_Handle (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_Conversion -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Free_Conversion (void) -{ - if (m_pConvertedFormat != NULL) { - m_pConvertedFormat->Stop (); - REF_PTR_RELEASE (m_pConvertedFormat); - } - - // - // Reacquire a play-handle if necessary - // - if ((m_IsCulled == false) && (m_State == STATE_PLAYING)) { - Allocate_Miles_Handle (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Convert_To_Filtered -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundClass::Convert_To_Filtered (void) -{ - if (m_pConvertedFormat == NULL) { - - // - // Make a copy of the sound in its new format - // - m_pConvertedFormat = W3DNEW FilteredSoundClass; - switch (Get_Class_ID ()) - { - case CLASSID_3D: - (*m_pConvertedFormat) = (const Sound3DClass &)(*this); - break; - - case CLASSID_PSEUDO3D: - (*m_pConvertedFormat) = (const SoundPseudo3DClass &)(*this); - break; - - case CLASSID_FILTERED: - (*m_pConvertedFormat) = (const FilteredSoundClass &)(*this); - break; - - default: - (*m_pConvertedFormat) = (*this); - break; - } - - Free_Miles_Handle (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// As_Converted_Format -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -AudibleSoundClass::As_Converted_Format (void) -{ - if (m_pConvertedFormat == NULL) { - Convert_To_Filtered (); - } - - return m_pConvertedFormat; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -AudibleSoundClass::Get_Factory (void) const -{ - return _AudibleSoundPersistFactory; -} - - -//************************************************************************************************ -//* -//* Start of AudibleSoundDefinitionClass -//* -//************************************************************************************************ - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// AudibleSoundDefinitionClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundDefinitionClass::AudibleSoundDefinitionClass (void) - : m_Priority (0.5F), - m_Volume (1.0F), - m_Pan (0.5F), - m_LoopCount (1), - m_DropOffRadius (40.0F), - m_LogicalDropOffRadius (-1.0F), - m_MaxVolRadius (20.0F), - m_Is3D (true), - m_Type (AudibleSoundClass::TYPE_SOUND_EFFECT), - m_LogicalTypeMask (0), - m_LogicalNotifyDelay (2), - m_CreateLogical (false), - m_AttenuationSphereColor (0, 0.75F, 0.75F), - m_StartOffset (0), - m_PitchFactor (1.0F) -{ - // - // Audible sound params - // - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_SOUND_FILENAME, m_Filename, "Filename"); - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_FLOAT, m_DropOffRadius, "Drop-off Radius"); - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_FLOAT, m_MaxVolRadius, "Max-Vol Radius"); - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_BOOL, m_Is3D, "Is 3D Sound"); - INT_EDITABLE_PARAM (AudibleSoundDefinitionClass, m_LoopCount, 0, 1000000); - FLOAT_EDITABLE_PARAM (AudibleSoundDefinitionClass, m_Volume, 0, 1.0F); - FLOAT_EDITABLE_PARAM (AudibleSoundDefinitionClass, m_Pan, 0, 1.0F); - FLOAT_EDITABLE_PARAM (AudibleSoundDefinitionClass, m_Priority, 0, 1.0F); - ENUM_PARAM (AudibleSoundDefinitionClass, m_Type, ("Sound Effect", AudibleSoundClass::TYPE_SOUND_EFFECT, "Music", AudibleSoundClass::TYPE_MUSIC, 0)); - FLOAT_EDITABLE_PARAM (AudibleSoundDefinitionClass, m_StartOffset, 0, 1.0F); - FLOAT_EDITABLE_PARAM (AudibleSoundDefinitionClass, m_PitchFactor, 0, 1.0F); - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_STRING, m_DisplayText, "Display Text"); - - // - // Logical sound params - // - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_BOOL, m_CreateLogical, "Create Logical Sound"); - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_FLOAT, m_LogicalDropOffRadius, "Logical Drop-off Radius"); - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_FLOAT, m_LogicalNotifyDelay, "Logical Notif Delay"); - -#ifdef PARAM_EDITING_ON - // - // Configure the logical type mask enumeration - // - EnumParameterClass *param = W3DNEW EnumParameterClass (&m_LogicalTypeMask); - param->Set_Name ("Logical Type"); - int count = WWAudioClass::Get_Instance ()->Get_Logical_Type_Count (); - for (int index = 0; index < count; index ++) { - StringClass display_name(0,true); - int id = WWAudioClass::Get_Instance ()->Get_Logical_Type (index, display_name); - param->Add_Value (display_name, id); - } - GENERIC_EDITABLE_PARAM(AudibleSoundDefinitionClass, param); -#endif - - NAMED_EDITABLE_PARAM (AudibleSoundDefinitionClass, ParameterClass::TYPE_COLOR, m_AttenuationSphereColor, "Sphere Color"); - - return ; -} - -// SKB: Put here because of conficts with CLASSID_???? with other projects. -uint32 AudibleSoundDefinitionClass::Get_Class_ID (void) const -{ - return CLASSID_SOUND; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_From_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -AudibleSoundDefinitionClass::Initialize_From_Sound (AudibleSoundClass *sound) -{ - // - // Read the settings from the sound object - // - if (sound != NULL) { - Sound3DClass *sound_3d = sound->As_Sound3DClass (); - - // - // Choose defaults for the values that we can't get from - // the sound. - // - m_LogicalDropOffRadius = -1.0F; - m_LogicalNotifyDelay = 2; - m_LogicalTypeMask = 0; - m_CreateLogical = false; - m_Pan = 0.5F; - m_DisplayText = ""; - - // - // Copy the values that we can from the sound object - // - m_Filename = sound->Get_Filename (); - m_DropOffRadius = sound->Get_DropOff_Radius (); - m_Priority = sound->Peek_Priority (); - m_Is3D = (sound_3d != NULL); - m_Type = sound->Get_Type (); - m_LoopCount = sound->Get_Loop_Count (); - m_Volume = sound->Get_Volume (); - m_StartOffset = sound->Get_Start_Offset (); - m_PitchFactor = sound->Get_Pitch_Factor (); - - if (sound_3d != NULL) { - m_MaxVolRadius = sound_3d->Get_Max_Vol_Radius (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -AudibleSoundDefinitionClass::Get_Factory (void) const -{ - return _AudibleSoundDefPersistFactory; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundDefinitionClass::Save (ChunkSaveClass &csave) -{ - using namespace AUDIBLE_SOUND_DEF_SAVELOAD; - bool retval = true; - - csave.Begin_Chunk (CHUNKID_VARIABLES); - retval &= Save_Variables (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - retval &= DefinitionClass::Save (csave); - csave.End_Chunk (); - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundDefinitionClass::Load (ChunkLoadClass &cload) -{ - using namespace AUDIBLE_SOUND_DEF_SAVELOAD; - bool retval = true; - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_VARIABLES: - retval &= Load_Variables (cload); - break; - - case CHUNKID_BASE_CLASS: - retval &= DefinitionClass::Load (cload); - break; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundDefinitionClass::Save_Variables (ChunkSaveClass &csave) -{ - using namespace AUDIBLE_SOUND_DEF_SAVELOAD; - - // - // Save the audible variables - // - WRITE_MICRO_CHUNK (csave, VARID_PRIORITY, m_Priority) - WRITE_MICRO_CHUNK (csave, VARID_VOLUME, m_Volume) - WRITE_MICRO_CHUNK (csave, VARID_PAN, m_Pan) - WRITE_MICRO_CHUNK (csave, VARID_LOOP_COUNT, m_LoopCount) - WRITE_MICRO_CHUNK (csave, VARID_DROP_OFF, m_DropOffRadius) - WRITE_MICRO_CHUNK (csave, VARID_MAX_VOL, m_MaxVolRadius) - WRITE_MICRO_CHUNK (csave, VARID_TYPE, m_Type) - WRITE_MICRO_CHUNK (csave, VARID_IS3D, m_Is3D) - WRITE_MICRO_CHUNK_WWSTRING (csave, VARID_FILENAME, m_Filename) - WRITE_MICRO_CHUNK_WWSTRING (csave, VARID_DISPLAY_TEXT, m_DisplayText) - WRITE_MICRO_CHUNK (csave, VARID_START_OFFSET, m_StartOffset); - WRITE_MICRO_CHUNK (csave, VARID_PITCH_FACTOR, m_PitchFactor); - - // - // Save the logical variables - // - WRITE_MICRO_CHUNK (csave, VARID_LOGICAL_MASK, m_LogicalTypeMask) - WRITE_MICRO_CHUNK (csave, VARID_LOGICAL_DELAY, m_LogicalNotifyDelay) - WRITE_MICRO_CHUNK (csave, VARID_CREATE_LOGICAL, m_CreateLogical) - WRITE_MICRO_CHUNK (csave, VARID_LOGICAL_DROP_OFF, m_LogicalDropOffRadius) - WRITE_MICRO_CHUNK (csave, VARID_SPHERE_COLOR, m_AttenuationSphereColor) - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundDefinitionClass::Load_Variables (ChunkLoadClass &cload) -{ - using namespace AUDIBLE_SOUND_DEF_SAVELOAD; - - // - // Loop through all the microchunks that define the variables - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_PRIORITY, m_Priority) - READ_MICRO_CHUNK (cload, VARID_VOLUME, m_Volume) - READ_MICRO_CHUNK (cload, VARID_PAN, m_Pan) - READ_MICRO_CHUNK (cload, VARID_LOOP_COUNT, m_LoopCount) - READ_MICRO_CHUNK (cload, VARID_DROP_OFF, m_DropOffRadius) - READ_MICRO_CHUNK (cload, VARID_MAX_VOL, m_MaxVolRadius) - READ_MICRO_CHUNK (cload, VARID_TYPE, m_Type) - READ_MICRO_CHUNK (cload, VARID_IS3D, m_Is3D) - READ_MICRO_CHUNK_WWSTRING (cload, VARID_FILENAME, m_Filename) - READ_MICRO_CHUNK_WWSTRING (cload, VARID_DISPLAY_TEXT, m_DisplayText) - READ_MICRO_CHUNK (cload, VARID_LOGICAL_MASK, m_LogicalTypeMask) - READ_MICRO_CHUNK (cload, VARID_LOGICAL_DELAY, m_LogicalNotifyDelay) - READ_MICRO_CHUNK (cload, VARID_CREATE_LOGICAL, m_CreateLogical) - READ_MICRO_CHUNK (cload, VARID_LOGICAL_DROP_OFF, m_LogicalDropOffRadius) - READ_MICRO_CHUNK (cload, VARID_SPHERE_COLOR, m_AttenuationSphereColor) - READ_MICRO_CHUNK (cload, VARID_START_OFFSET, m_StartOffset); - READ_MICRO_CHUNK (cload, VARID_PITCH_FACTOR, m_PitchFactor); - } - - cload.Close_Micro_Chunk (); - } - - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Create -// -////////////////////////////////////////////////////////////////////////////////// -PersistClass * -AudibleSoundDefinitionClass::Create (void) const -{ - return Create_Sound (CLASSID_3D); -} - -////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound -// -////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -AudibleSoundDefinitionClass::Create_Sound (int classid_hint) const -{ - AudibleSoundClass *new_sound = NULL; - - // - // If this is a relative path, strip it off and assume - // the current directory is set correctly. - // - StringClass real_filename(m_Filename,true); - const char *dir_delimiter = ::strrchr (m_Filename, '\\'); - if (dir_delimiter != NULL && m_Filename.Get_Length () > 2 && m_Filename[1] != ':') { - real_filename = (dir_delimiter + 1); - } - - // - // Should we create a 2D or 3D sound? - // - if (m_Is3D) { - new_sound = WWAudioClass::Get_Instance ()->Create_3D_Sound (real_filename, classid_hint); - } else { - new_sound = WWAudioClass::Get_Instance ()->Create_Sound_Effect (real_filename); - } - - // - // Did we successfully create the sound? - // - if (new_sound != NULL) { - - // - // Configure the sound - // - new_sound->Set_Type ((AudibleSoundClass::SOUND_TYPE)m_Type); - new_sound->Set_Priority (m_Priority); - new_sound->Set_Volume (m_Volume); - new_sound->Set_Loop_Count (m_LoopCount); - new_sound->Set_DropOff_Radius (m_DropOffRadius); - new_sound->Set_Definition ((AudibleSoundDefinitionClass *)this); - new_sound->Set_Start_Offset (m_StartOffset); - new_sound->Set_Pitch_Factor (m_PitchFactor); - - if (m_Is3D) { - ((Sound3DClass *)new_sound)->Set_Max_Vol_Radius (m_MaxVolRadius); - } - } - - return new_sound; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Create_Logical -// -////////////////////////////////////////////////////////////////////////////////// -LogicalSoundClass * -AudibleSoundDefinitionClass::Create_Logical (void) -{ - LogicalSoundClass *logical_sound = NULL; - - if (m_CreateLogical) { - - // - // Create and configure the logical sound - // - logical_sound = W3DNEW LogicalSoundClass; - logical_sound->Set_Type_Mask (m_LogicalTypeMask); - logical_sound->Set_Notify_Delay (m_LogicalNotifyDelay); - logical_sound->Set_Single_Shot (m_LoopCount != 0); - - // - // Use the audible sound's drop-off radius if the logical - // isn't set... - // - if (m_LogicalDropOffRadius < 0) { - logical_sound->Set_DropOff_Radius (m_DropOffRadius); - } else { - logical_sound->Set_DropOff_Radius (m_LogicalDropOffRadius); - } - } - - return logical_sound; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::Save (ChunkSaveClass &csave) -{ - using namespace AUDIBLE_SOUND_SAVELOAD; - - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - SoundSceneObjClass::Save (csave); - csave.End_Chunk (); - - uint32 temp_position = 0; - csave.Begin_Chunk (CHUNKID_VARIABLES); - WRITE_MICRO_CHUNK (csave, VARID_STATE, m_State); - WRITE_MICRO_CHUNK (csave, VARID_TYPE, m_Type); - - WRITE_MICRO_CHUNK (csave, VARID_PRIORITY, m_Priority); - WRITE_MICRO_CHUNK (csave, VARID_VOLUME, m_Volume); - WRITE_MICRO_CHUNK (csave, VARID_PAN, m_Pan); - WRITE_MICRO_CHUNK (csave, VARID_LOOP_COUNT, m_LoopCount); - WRITE_MICRO_CHUNK (csave, VARID_LOOPS_LEFT, m_LoopsLeft); - WRITE_MICRO_CHUNK (csave, VARID_SOUND_LENGTH, m_Length); - WRITE_MICRO_CHUNK (csave, VARID_CURR_POS, temp_position); - WRITE_MICRO_CHUNK (csave, VARID_TRANSFORM, m_Transform); - WRITE_MICRO_CHUNK (csave, VARID_PREV_TRANSFORM, m_PrevTransform); - WRITE_MICRO_CHUNK (csave, VARID_IS_CULLED, m_IsCulled); - WRITE_MICRO_CHUNK (csave, VARID_IS_DIRTY, m_bDirty); - WRITE_MICRO_CHUNK (csave, VARID_DROP_OFF, m_DropOffRadius); - WRITE_MICRO_CHUNK (csave, VARID_START_OFFSET, m_StartOffset); - WRITE_MICRO_CHUNK (csave, VARID_PITCH_FACTOR, m_PitchFactor); - WRITE_MICRO_CHUNK (csave, VARID_LISTENER_TRANSFORM, m_ListenerTransform); - - if (m_Buffer != NULL) { - WRITE_MICRO_CHUNK_STRING (csave, VARID_FILENAME, m_Buffer->Get_Filename ()); - } - - AudibleSoundClass *this_ptr = this; - WRITE_MICRO_CHUNK (csave, VARID_THIS_PTR, this_ptr); - - csave.End_Chunk (); - - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -AudibleSoundClass::Load (ChunkLoadClass &cload) -{ - using namespace AUDIBLE_SOUND_SAVELOAD; - - StringClass filename(0,true); - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_BASE_CLASS: - SoundSceneObjClass::Load (cload); - break; - - case CHUNKID_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_STATE, m_State); - READ_MICRO_CHUNK (cload, VARID_TYPE, m_Type); - - READ_MICRO_CHUNK (cload, VARID_PRIORITY, m_Priority); - READ_MICRO_CHUNK (cload, VARID_VOLUME, m_Volume); - READ_MICRO_CHUNK (cload, VARID_PAN, m_Pan); - READ_MICRO_CHUNK (cload, VARID_LOOP_COUNT, m_LoopCount); - READ_MICRO_CHUNK (cload, VARID_LOOPS_LEFT, m_LoopsLeft); - READ_MICRO_CHUNK (cload, VARID_SOUND_LENGTH, m_Length); - READ_MICRO_CHUNK (cload, VARID_CURR_POS, m_CurrentPosition); - READ_MICRO_CHUNK (cload, VARID_TRANSFORM, m_Transform); - READ_MICRO_CHUNK (cload, VARID_PREV_TRANSFORM, m_PrevTransform); - READ_MICRO_CHUNK (cload, VARID_IS_CULLED, m_IsCulled); - READ_MICRO_CHUNK (cload, VARID_IS_DIRTY, m_bDirty); - READ_MICRO_CHUNK (cload, VARID_DROP_OFF, m_DropOffRadius); - READ_MICRO_CHUNK (cload, VARID_START_OFFSET, m_StartOffset); - READ_MICRO_CHUNK (cload, VARID_PITCH_FACTOR, m_PitchFactor); - READ_MICRO_CHUNK (cload, VARID_LISTENER_TRANSFORM, m_ListenerTransform); - - READ_MICRO_CHUNK_WWSTRING (cload, VARID_FILENAME, filename); - - case VARID_THIS_PTR: - { - AudibleSoundClass *old_ptr = NULL; - cload.Read(&old_ptr, sizeof (old_ptr)); - SaveLoadSystemClass::Register_Pointer (old_ptr, this); - } - break; - } - - cload.Close_Micro_Chunk (); - } - } - break; - } - - cload.Close_Chunk (); - } - - // - // Reconstruct the sound buffer we had before we saved - // - if (filename.Get_Length () > 0) { - bool is_3d = (As_Sound3DClass () != NULL); - SoundBufferClass *buffer = WWAudioClass::Get_Instance ()->Get_Sound_Buffer (filename, is_3d); - Set_Buffer (buffer); - REF_PTR_RELEASE (buffer); - } - - return true; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.h deleted file mode 100644 index 80b3688001..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudibleSound.h +++ /dev/null @@ -1,464 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/AudibleSound.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 12:08p $* - * * - * $Revision:: 22 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDOBJ_H -#define __SOUNDOBJ_H - -#pragma warning (push, 3) -#include "mss.h" -#pragma warning (pop) - -//#include -#include "vector3.h" -#include "matrix3d.h" -#include "refcount.h" -#include "RAWFILE.H" -#include "SoundSceneObj.h" -#include "Vector.H" -#include "wwstring.h" -#include "definition.h" - - -///////////////////////////////////////////////////////////////////////////////// -// Forward declarations -///////////////////////////////////////////////////////////////////////////////// -class SoundBufferClass; -class RenderObjClass; -class LogicalSoundClass; -class AudibleSoundDefinitionClass; -class Sound3DClass; -class SoundPseudo3DClass; -class FilteredSoundClass; -class Listener3DClass; -class SoundHandleClass; - - -///////////////////////////////////////////////////////////////////////////////// -// -// Typedefs -// -typedef unsigned long MILES_HANDLE; - -typedef enum -{ - INFO_OBJECT_PTR = 0, - INFO_MAX -} HANDLE_USER_INDEX; - - -///////////////////////////////////////////////////////////////////////////////// -// -// Constants -// -///////////////////////////////////////////////////////////////////////////////// -const MILES_HANDLE INVALID_MILES_HANDLE = (MILES_HANDLE)-1; -const int INFINITE_LOOPS = 0; - - -///////////////////////////////////////////////////////////////////////////////// -// -// AudibleSoundClass -// -// Base class defining a common interface to all sound object types. -// -///////////////////////////////////////////////////////////////////////////////// -class AudibleSoundClass : public SoundSceneObjClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Friend classes - ////////////////////////////////////////////////////////////////////// - friend class WWAudioClass; - - ////////////////////////////////////////////////////////////////////// - // Public data types - ////////////////////////////////////////////////////////////////////// - typedef enum - { - TYPE_MUSIC = 0, - TYPE_SOUND_EFFECT, - TYPE_COUNT - } SOUND_TYPE; - - typedef enum - { - STATE_STOPPED = 0, - STATE_PLAYING, - STATE_PAUSED, - STATE_COUNT - } SOUND_STATE; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - AudibleSoundClass (const AudibleSoundClass &src); - AudibleSoundClass (void); - virtual ~AudibleSoundClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////// - const AudibleSoundClass &operator= (const AudibleSoundClass &src); - - ////////////////////////////////////////////////////////////////////// - // Identification methods - ////////////////////////////////////////////////////////////////////// - virtual SOUND_CLASSID Get_Class_ID (void) const { return CLASSID_2D; } - virtual SOUND_TYPE Get_Type (void) const { return m_Type; } - virtual void Set_Type (SOUND_TYPE type) { m_Type = type; } - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual AudibleSoundClass * As_AudibleSoundClass(void) { return this; } - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); - - ////////////////////////////////////////////////////////////////////// - // State control methods - ////////////////////////////////////////////////////////////////////// - virtual bool Play (bool alloc_handle = true); - virtual bool Pause (void); - virtual bool Resume (void); - virtual bool Stop (bool remove_from_playlist = true); - virtual void Seek (unsigned long milliseconds); - virtual SOUND_STATE Get_State (void) const { return m_State; } - - // The timestamp represents when the sound started playing - virtual unsigned long Get_Timestamp (void) const { return m_Timestamp; } - - ////////////////////////////////////////////////////////////////////// - // Informational methods - ////////////////////////////////////////////////////////////////////// - virtual LPCTSTR Get_Filename (void) const; - virtual bool Is_Playing (void) const {return(Get_State() == STATE_PLAYING);} - - ////////////////////////////////////////////////////////////////////// - // Pan control - ////////////////////////////////////////////////////////////////////// - - // - // Note: Pan values are normalized values from 0 (hard left) to - // 1.0F (hard right). Dead center is 0.5F. - // - virtual float Get_Pan (void); - virtual void Set_Pan (float pan = 0.5F); - - ////////////////////////////////////////////////////////////////////// - // Volume control - ////////////////////////////////////////////////////////////////////// - virtual float Get_Volume (void); - virtual void Set_Volume (float volume = 1.0F); - virtual void Update_Volume (void) { Set_Volume (m_Volume); } - - ////////////////////////////////////////////////////////////////////// - // Loop control - ////////////////////////////////////////////////////////////////////// - virtual int Get_Loop_Count (void) const { return m_LoopCount; } - virtual int Get_Loops_Left (void) const; - - // Note: Use the INFINITE_LOOPS constant for an infinite number of loops. (i.e. for use w/ music) - virtual void Set_Loop_Count (int count = 1); - - ////////////////////////////////////////////////////////////////////// - // Priority control - ////////////////////////////////////////////////////////////////////// - virtual float Get_Priority (void) const { return m_Priority; } - virtual float Peek_Priority (void) const { return m_Priority; } - virtual void Set_Priority (float priority = 0.5F); - - virtual float Get_Runtime_Priority (void) const { return m_RuntimePriority; } - virtual void Set_Runtime_Priority (float priority) { m_RuntimePriority = priority; } - - ////////////////////////////////////////////////////////////////////// - // Playback rate control - ////////////////////////////////////////////////////////////////////// - virtual int Get_Playback_Rate (void); - virtual void Set_Playback_Rate (int rate_in_hz); - - virtual float Get_Pitch_Factor (void) { return m_PitchFactor; } - virtual void Set_Pitch_Factor (float factor); - - ////////////////////////////////////////////////////////////////////// - // Buffer position manipulation - ////////////////////////////////////////////////////////////////////// - - // - // Note: The duration is in milliseconds. The play position - // can either be set as a normalized value from 0 to 1 or a millisecond - // offset from the start of the sound. - // - virtual unsigned long Get_Duration (void) const { return m_Length; } - virtual unsigned long Get_Play_Position (void) const { return m_CurrentPosition; } - virtual void Set_Play_Position (float position) { Seek (position * m_Length); } - virtual void Set_Play_Position (unsigned long milliseconds) { Seek (milliseconds); } - - virtual void Set_Start_Offset (float offset) { m_StartOffset = offset; } - virtual float Get_Start_Offset (void) const { return m_StartOffset; } - - ////////////////////////////////////////////////////////////////////// - // Position/direction methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Position (const Vector3 &position); - virtual Vector3 Get_Position (void) const { return m_Transform.Get_Translation (); } - - virtual void Set_Listener_Transform (const Matrix3D &tm) { m_ListenerTransform = tm; } - virtual void Set_Transform (const Matrix3D &transform); - virtual Matrix3D Get_Transform (void) const { return m_Transform; } - - ////////////////////////////////////////////////////////////////////// - // Culling methods - ////////////////////////////////////////////////////////////////////// - virtual void Cull_Sound (bool culled = true); - virtual bool Is_Sound_Culled (void) const { return m_IsCulled; } - - ////////////////////////////////////////////////////////////////////// - // Scene integration - ////////////////////////////////////////////////////////////////////// - virtual void Add_To_Scene (bool start_playing = true); - virtual void Remove_From_Scene (void); - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - - // - // This is the distance where the sound can not be heard any longer. (its vol is 0) - // - virtual void Set_DropOff_Radius (float radius = 1); - virtual float Get_DropOff_Radius (void) const { return m_DropOffRadius; } - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Dirty (bool dirty = true) { m_bDirty = dirty; } - virtual bool Is_Dirty (void) const { return m_bDirty; } - - ////////////////////////////////////////////////////////////////////// - // Definition managmenent - ////////////////////////////////////////////////////////////////////// - virtual void Set_Definition (AudibleSoundDefinitionClass *def) { m_Definition = def; } - virtual AudibleSoundDefinitionClass * Get_Definition (void) { return m_Definition; } - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual void Re_Sync (AudibleSoundClass &src); - virtual void Free_Conversion (void); - virtual void Convert_To_Filtered (void); - virtual AudibleSoundClass *As_Converted_Format (void); - - ////////////////////////////////////////////////////////////////////// - // From PersistClass - ////////////////////////////////////////////////////////////////////// - const PersistFactoryClass & Get_Factory (void) const; - bool Save (ChunkSaveClass &csave); - bool Load (ChunkLoadClass &cload); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - virtual float Determine_Real_Volume (void) const; - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual SoundHandleClass * Get_Miles_Handle (void) const { return m_SoundHandle; } - virtual void Set_Miles_Handle (MILES_HANDLE handle = INVALID_MILES_HANDLE); - virtual void Free_Miles_Handle (void); - virtual void Initialize_Miles_Handle (void); - virtual void Allocate_Miles_Handle (void); - - ////////////////////////////////////////////////////////////////////// - // Buffer information - ////////////////////////////////////////////////////////////////////// - virtual SoundBufferClass * Get_Buffer (void) const; - virtual SoundBufferClass * Peek_Buffer (void) const; - virtual void Set_Buffer (SoundBufferClass *buffer); - - ////////////////////////////////////////////////////////////////////// - // Loop methods - ////////////////////////////////////////////////////////////////////// - virtual void Restart_Loop (void) {} - virtual void Update_Play_Position (void); - - ////////////////////////////////////////////////////////////////////// - // Event handling - ////////////////////////////////////////////////////////////////////// - virtual void On_Loop_End (void); - - ////////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////////// - SoundHandleClass * m_SoundHandle; - unsigned long m_Timestamp; - SOUND_STATE m_State; - SOUND_TYPE m_Type; - - // Buffer information - SoundBufferClass * m_Buffer; - - // Cached settings - float m_RuntimePriority; - float m_Priority; - float m_Volume; - float m_Pan; - int m_LoopCount; - int m_LoopsLeft; - - // Offset and length information (in milliseconds) - unsigned long m_Length; - unsigned long m_CurrentPosition; - float m_StartOffset; - float m_PitchFactor; - - // 3D scene information - Matrix3D m_ListenerTransform; - Matrix3D m_Transform; - Matrix3D m_PrevTransform; - bool m_IsCulled; - bool m_bDirty; - float m_DropOffRadius; - - // Conversion data - AudibleSoundClass * m_pConvertedFormat; - - // Definition pointer - AudibleSoundDefinitionClass * m_Definition; - - // Logical sound information - LogicalSoundClass * m_LogicalSound; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// AudibleSoundDefinitionClass -// -////////////////////////////////////////////////////////////////////////////////// -class AudibleSoundDefinitionClass : public DefinitionClass -{ - -public: - - ///////////////////////////////////////////////////////////////////// - // Editable interface requirements - ///////////////////////////////////////////////////////////////////// - DECLARE_EDITABLE(AudibleSoundDefinitionClass, DefinitionClass); - - ////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////// - AudibleSoundDefinitionClass (void); - virtual ~AudibleSoundDefinitionClass (void) { } - - // From DefinitionClass - virtual uint32 Get_Class_ID (void) const; - - // From PersistClass - virtual const PersistFactoryClass & Get_Factory (void) const; - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - virtual PersistClass * Create (void) const; - virtual AudibleSoundClass * Create_Sound (int classid_hint) const; - - // Initialization - virtual void Initialize_From_Sound (AudibleSoundClass *sound); - - // Accessors - virtual const StringClass & Get_Filename (void) const { return m_Filename; } - virtual const StringClass & Get_Display_Text (void) const { return m_DisplayText; } - virtual float Get_Max_Vol_Radius (void) const { return m_MaxVolRadius; } - virtual float Get_DropOff_Radius (void) const { return m_DropOffRadius; } - virtual const Vector3 & Get_Sphere_Color (void) const { return m_AttenuationSphereColor; } - virtual float Get_Volume (void) const { return m_Volume; } - virtual float Get_Start_Offset (void) const { return m_StartOffset; } - virtual float Get_Pitch_Factor (void) const { return m_PitchFactor; } - - virtual void Set_Volume (float volume) { m_Volume = volume; } - virtual void Set_Max_Vol_Radius (float radius){ m_MaxVolRadius = radius; } - virtual void Set_DropOff_Radius (float radius){ m_DropOffRadius = radius; } - virtual void Set_Start_Offset (float offset) { m_StartOffset = offset; } - virtual void Set_Pitch_Factor (float factor) { m_PitchFactor = factor; } - - // Logical sound creation - virtual LogicalSoundClass * Create_Logical (void); - -protected: - - ///////////////////////////////////////////////////////////////////// - // Private methods - ///////////////////////////////////////////////////////////////////// - bool Save_Variables (ChunkSaveClass &csave); - bool Load_Variables (ChunkLoadClass &cload); - - ////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////// - float m_Priority; - float m_Volume; - float m_Pan; - int m_LoopCount; - float m_DropOffRadius; - float m_MaxVolRadius; - bool m_Is3D; - StringClass m_Filename; - int m_Type; - StringClass m_DisplayText; - float m_StartOffset; - float m_PitchFactor; - - int m_LogicalTypeMask; - float m_LogicalNotifyDelay; - float m_LogicalDropOffRadius; - bool m_CreateLogical; - - // Misc UI info - Vector3 m_AttenuationSphereColor; -}; - - -#endif //__SOUNDOBJ_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioEvents.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioEvents.h deleted file mode 100644 index 7bc7c5e6a8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioEvents.h +++ /dev/null @@ -1,214 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/AudioEvents.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 5/24/00 5:40p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __AUDIO_EVENTS_H -#define __AUDIO_EVENTS_H - -#include "simplevec.h" -#include "bittype.h" - - -///////////////////////////////////////////////////////////////////////////////// -// Forward declarations -///////////////////////////////////////////////////////////////////////////////// -class SoundSceneObjClass; -class LogicalListenerClass; -class LogicalSoundClass; -class AudibleSoundClass; -class StringClass; - - -///////////////////////////////////////////////////////////////////////////////// -// -// Global callbacks (C Style) -// -///////////////////////////////////////////////////////////////////////////////// - -// -// Callback declarations. These functions are called when a registered event occurs -// in the sound library/ -// -typedef void (_stdcall *LPFNSOSCALLBACK) (SoundSceneObjClass *sound_obj, uint32 user_param); -typedef void (_stdcall *LPFNEOSCALLBACK) (SoundSceneObjClass *sound_obj, uint32 user_param); -typedef void (_stdcall *LPFNHEARDCALLBACK) (LogicalListenerClass *listener, LogicalSoundClass *sound_obj, uint32 user_param); -typedef void (_stdcall *LPFNTEXTCALLBACK) (AudibleSoundClass *sound_obj, const StringClass &text, uint32 user_param); - - -///////////////////////////////////////////////////////////////////////////////// -// -// Object callbacks (C++ Style) -// -///////////////////////////////////////////////////////////////////////////////// - -///////////////////////////////////////////////////////////////////////////////// -// -// AudioCallbackClass -// -// To use this callback mechanism, simply derive from this class and override -// the methods you want notifications of. These methods will be called when -// the event occurs. -// -///////////////////////////////////////////////////////////////////////////////// -class AudioCallbackClass -{ - -public: - - ///////////////////////////////////////////////////////////////////////////////// - // Event identifiers - ///////////////////////////////////////////////////////////////////////////////// - typedef enum - { - EVENT_NONE = 0x0000, - EVENT_SOUND_STARTED = 0x0001, - EVENT_SOUND_ENDED = 0x0002, - EVENT_LOGICAL_HEARD = 0x0004 - } EVENTS; - - ///////////////////////////////////////////////////////////////////////////////// - // Overrideables (callback-methods) - ///////////////////////////////////////////////////////////////////////////////// - virtual void On_Sound_Started (SoundSceneObjClass *sound_obj) { } - virtual void On_Sound_Ended (SoundSceneObjClass *sound_obj) { } - virtual void On_Logical_Heard (LogicalListenerClass *listener, LogicalSoundClass *sound_obj) { } -}; - - -///////////////////////////////////////////////////////////////////////////////// -// -// Internal implementation -// -///////////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////////// -// -// AudioCallbackListClass -// -///////////////////////////////////////////////////////////////////////////////// - -///////////////////////////////////////////////////////////////////////////////// -// Protected structures -///////////////////////////////////////////////////////////////////////////////// -template -struct AUDIO_CALLBACK_STRUCT -{ - T callback_ptr; - uint32 user_data; - - AUDIO_CALLBACK_STRUCT (void) - : callback_ptr (NULL), user_data (0) {} - - AUDIO_CALLBACK_STRUCT (T _ptr, uint32 _data) - : callback_ptr (_ptr), user_data (_data) {} - -}; - - -///////////////////////////////////////////////////////////////////////////////// -// Protected structures -///////////////////////////////////////////////////////////////////////////////// -template -class AudioCallbackListClass : public SimpleDynVecClass< AUDIO_CALLBACK_STRUCT > -{ - using SimpleDynVecClass< AUDIO_CALLBACK_STRUCT >::Vector; - using SimpleDynVecClass< AUDIO_CALLBACK_STRUCT >::ActiveCount; - using SimpleDynVecClass< AUDIO_CALLBACK_STRUCT >::Delete; - -public: - - ///////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ///////////////////////////////////////////////////////////////////////////////// - AudioCallbackListClass (void) { } - virtual ~AudioCallbackListClass (void) { } - - ///////////////////////////////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////////////////////////////// - void Add_Callback (T pointer, uint32 user_data); - T Get_Callback (int index, uint32 *user_data); - void Remove_Callback (T pointer); -}; - - -///////////////////////////////////////////////////////////////////////////////// -// Add_Callback -///////////////////////////////////////////////////////////////////////////////// -template void -AudioCallbackListClass::Add_Callback (T pointer, uint32 user_data) -{ - Add ( AUDIO_CALLBACK_STRUCT (pointer, user_data)); - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// Get_Callback -///////////////////////////////////////////////////////////////////////////////// -template T -AudioCallbackListClass::Get_Callback (int index, uint32 *user_data) -{ - if (user_data != NULL) { - (*user_data) = Vector[index].user_data; - } - - return Vector[index].callback_ptr; -} - -///////////////////////////////////////////////////////////////////////////////// -// Remove_Callback -///////////////////////////////////////////////////////////////////////////////// -template void -AudioCallbackListClass::Remove_Callback (T pointer) -{ - for (int index = 0; index < ActiveCount; index ++) { - if (Vector[index].callback_ptr == pointer) { - Delete (index); - break; - } - } - - return ; -} - - -#endif //__AUDIO_EVENTS_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp deleted file mode 100644 index 2287fe9514..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.cpp +++ /dev/null @@ -1,275 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : LevelEdit * - * * - * $Archive:: /Commando/Code/WWAudio/AudioSaveLoad.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/14/01 11:46a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "always.h" -#include "AudioSaveLoad.h" -#include "persist.h" -#include "persistfactory.h" -#include "definition.h" -#include "SoundChunkIDs.h" -#include "chunkio.h" -#include "SoundScene.h" -#include "wwmemlog.h" - - -/////////////////////////////////////////////////////////////////////// -// Global singleton instance -/////////////////////////////////////////////////////////////////////// -StaticAudioSaveLoadClass _StaticAudioSaveLoadSubsystem; -DynamicAudioSaveLoadClass _DynamicAudioSaveLoadSubsystem; - - -/////////////////////////////////////////////////////////////////////// -// Constants -/////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_STATIC_SCENE = 0x10291220, - CHUNKID_DYNAMIC_SCENE, - CHUNKID_DYNAMIC_VARIABLES -}; - - -enum -{ - VARID_INCLUDE_FILE = 0x01, - VARID_CAMERA_TM, - VARID_BACK_COLOR, - VARID_LOGICAL_LISTENER_GLOBAL_SCALE -}; - - -/////////////////////////////////////////////////////////////////////// -// -// Chunk_ID -// -/////////////////////////////////////////////////////////////////////// -uint32 -StaticAudioSaveLoadClass::Chunk_ID (void) const -{ - return CHUNKID_STATIC_SAVELOAD; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Contains_Data -// -/////////////////////////////////////////////////////////////////////// -bool -StaticAudioSaveLoadClass::Contains_Data (void) const -{ - return true; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Save -// -/////////////////////////////////////////////////////////////////////// -bool -StaticAudioSaveLoadClass::Save (ChunkSaveClass &csave) -{ - WWMEMLOG(MEM_SOUND); - - bool retval = true; - - // - // Save the static sounds - // - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if (scene != NULL) { - csave.Begin_Chunk (CHUNKID_STATIC_SCENE); - scene->Save_Static (csave); - csave.End_Chunk (); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Load -// -/////////////////////////////////////////////////////////////////////// -bool -StaticAudioSaveLoadClass::Load (ChunkLoadClass &cload) -{ - WWMEMLOG(MEM_SOUND); - - bool retval = true; - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - // - // Load the static scene information - // - case CHUNKID_STATIC_SCENE: - { - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if (scene != NULL) { - scene->Load_Static (cload); - } - } - break; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -//*******************************************************************// -//* -//* Start of DynamicAudioSaveLoadClass -//* -//*******************************************************************// - - - -/////////////////////////////////////////////////////////////////////// -// -// Chunk_ID -// -/////////////////////////////////////////////////////////////////////// -uint32 -DynamicAudioSaveLoadClass::Chunk_ID (void) const -{ - return CHUNKID_DYNAMIC_SAVELOAD; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Contains_Data -// -/////////////////////////////////////////////////////////////////////// -bool -DynamicAudioSaveLoadClass::Contains_Data (void) const -{ - return true; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Save -// -/////////////////////////////////////////////////////////////////////// -bool -DynamicAudioSaveLoadClass::Save (ChunkSaveClass &csave) -{ - bool retval = true; - - // - // Save the static sounds - // - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if (scene != NULL) { - - csave.Begin_Chunk (CHUNKID_DYNAMIC_VARIABLES); - float global_scale = LogicalListenerClass::Get_Global_Scale (); - WRITE_MICRO_CHUNK (csave, VARID_LOGICAL_LISTENER_GLOBAL_SCALE, global_scale); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_DYNAMIC_SCENE); - scene->Save_Dynamic (csave); - csave.End_Chunk (); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Load -// -/////////////////////////////////////////////////////////////////////// -bool -DynamicAudioSaveLoadClass::Load (ChunkLoadClass &cload) -{ - bool retval = true; - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_DYNAMIC_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - // - // Load the global scale for logical listeners - // - case VARID_LOGICAL_LISTENER_GLOBAL_SCALE: - { - float global_scale = 1.0F; - LOAD_MICRO_CHUNK (cload, global_scale); - LogicalListenerClass::Set_Global_Scale (global_scale); - break; - } - } - - cload.Close_Micro_Chunk (); - } - } - break; - - // - // Load the static scene information - // - case CHUNKID_DYNAMIC_SCENE: - { - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if (scene != NULL) { - scene->Load_Dynamic (cload); - } - } - break; - } - - cload.Close_Chunk (); - } - - return retval; -} \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h deleted file mode 100644 index a82b6890cf..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/AudioSaveLoad.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : LevelEdit * - * * - * $Archive:: /Commando/Code/WWAudio/AudioSaveLoad.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 6/12/00 4:29p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __AUDIO_SAVE_LOAD_H -#define __AUDIO_SAVE_LOAD_H - -#include "saveloadsubsystem.h" -#include "Vector.H" -#include "bittype.h" - - -// Singleton instances -extern class StaticAudioSaveLoadClass _StaticAudioSaveLoadSubsystem; -extern class DynamicAudioSaveLoadClass _DynamicAudioSaveLoadSubsystem; - - -////////////////////////////////////////////////////////////////////////// -// -// StaticAudioSaveLoadClass -// -////////////////////////////////////////////////////////////////////////// -class StaticAudioSaveLoadClass : public SaveLoadSubSystemClass -{ -public: - - ////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////// - StaticAudioSaveLoadClass (void) { } - virtual ~StaticAudioSaveLoadClass (void) { } - - ////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////// - - // From SaveLoadSubSystemClass - virtual uint32 Chunk_ID (void) const; - -protected: - - ////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////// - virtual bool Contains_Data(void) const; - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - virtual const char* Name() const { return "StaticAudioSaveLoadClass"; } -}; - - -////////////////////////////////////////////////////////////////////////// -// -// DynamicAudioSaveLoadClass -// -////////////////////////////////////////////////////////////////////////// -class DynamicAudioSaveLoadClass : public SaveLoadSubSystemClass -{ -public: - - ////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////// - DynamicAudioSaveLoadClass (void) { } - virtual ~DynamicAudioSaveLoadClass (void) { } - - ////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////// - - // From SaveLoadSubSystemClass - virtual uint32 Chunk_ID (void) const; - -protected: - - ////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////// - virtual bool Contains_Data(void) const; - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - virtual const char* Name() const { return "DynamicAudioSaveLoadClass"; } - - //bool Save_Micro_Chunks (ChunkSaveClass &csave); - //bool Load_Micro_Chunks (ChunkLoadClass &cload); -}; - - -#endif //__AUDIO_SAVE_LOAD_H - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt new file mode 100644 index 0000000000..071eddc29b --- /dev/null +++ b/Generals/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt @@ -0,0 +1,7 @@ +add_library(g_wwaudio STATIC) +set_target_properties(g_wwaudio PROPERTIES OUTPUT_NAME wwaudio) + +target_link_libraries(g_wwaudio PRIVATE + corei_wwaudio + g_wwcommon +) diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp deleted file mode 100644 index c55616ced7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/FilteredSound.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:03p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "FilteredSound.h" -#include "WWAudio.h" -#include "SoundScene.h" -#include "SoundChunkIDs.h" -#include "persistfactory.h" -#include "soundhandle.h" - - -////////////////////////////////////////////////////////////////////////////////// -// -// Static factories -// -////////////////////////////////////////////////////////////////////////////////// -SimplePersistFactoryClass _FilteredSoundPersistFactory; - - -///////////////////////////////////////////////////////////////////////////////// -// -// FilteredSoundClass -// -///////////////////////////////////////////////////////////////////////////////// -FilteredSoundClass::FilteredSoundClass (void) - : m_hFilter (INVALID_MILES_HANDLE) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// FilteredSoundClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -FilteredSoundClass::FilteredSoundClass (const FilteredSoundClass &src) - : m_hFilter (INVALID_MILES_HANDLE), - SoundPseudo3DClass (src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// ~FilteredSoundClass -// -///////////////////////////////////////////////////////////////////////////////// -FilteredSoundClass::~FilteredSoundClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const FilteredSoundClass & -FilteredSoundClass::operator= (const FilteredSoundClass &src) -{ - // Call the base class - SoundPseudo3DClass::operator= (src); - return (*this); -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Miles_Handle -// -///////////////////////////////////////////////////////////////////////////////// -void -FilteredSoundClass::Initialize_Miles_Handle (void) -{ - SoundPseudo3DClass::Initialize_Miles_Handle (); - m_hFilter = WWAudioClass::Get_Instance ()->Get_Reverb_Filter (); - if ((m_SoundHandle != NULL) && - (m_hFilter != INVALID_MILES_HANDLE)) { - - // - // Pass the filter onto the sample - // - ::AIL_set_sample_processor (m_SoundHandle->Get_HSAMPLE (), DP_FILTER, m_hFilter); - - // - // Change the reverb's settings to simulate a 'tinny' effect. - // - F32 reverb_level = 0.3F; - F32 reverb_reflect = 0.01F; - F32 reverb_decay = 0.535F; - ::AIL_set_filter_sample_preference (m_SoundHandle->Get_HSAMPLE (), - "Reverb level", - &reverb_level); - - ::AIL_set_filter_sample_preference (m_SoundHandle->Get_HSAMPLE (), - "Reverb reflect time", - &reverb_reflect); - - ::AIL_set_filter_sample_preference (m_SoundHandle->Get_HSAMPLE (), - "Reverb decay time", - &reverb_decay); - } - - Update_Volume (); - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Update_Volume -// -///////////////////////////////////////////////////////////////////////////////// -void -FilteredSoundClass::Update_Volume (void) -{ - if (m_SoundHandle != NULL) { - - // Determine the listener's position and the sound's position - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - Listener3DClass *listener = scene->Peek_2nd_Listener (); - if (listener != NULL) { - Vector3 listener_pos = listener->Get_Position (); - Vector3 sound_pos = m_Transform.Get_Translation (); - - // Determine a normalized volume from the position - float distance = (sound_pos - listener_pos).Quick_Length (); - Update_Pseudo_Volume (distance); - } - } - - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -///////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -FilteredSoundClass::Get_Factory (void) const -{ - return _FilteredSoundPersistFactory; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.h deleted file mode 100644 index fbf3295276..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/FilteredSound.h +++ /dev/null @@ -1,106 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/FilteredSound.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 10/11/00 12:01p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __FILTERED_SOUND_H -#define __FILTERED_SOUND_H - - -#include "SoundPseudo3D.h" - - -///////////////////////////////////////////////////////////////////////////////// -// -// FilteredSoundClass -// -// Sound object that applies the specified 'reverb' filter so as to sound 'tinny'. -// -///////////////////////////////////////////////////////////////////////////////// -class FilteredSoundClass : public SoundPseudo3DClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - FilteredSoundClass (const FilteredSoundClass &src); - FilteredSoundClass (void); - virtual ~FilteredSoundClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////// - const FilteredSoundClass &operator= (const FilteredSoundClass &src); - - ////////////////////////////////////////////////////////////////////// - // Identification methods - ////////////////////////////////////////////////////////////////////// - virtual SOUND_CLASSID Get_Class_ID (void) { return CLASSID_FILTERED; } - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual FilteredSoundClass * As_FilteredSoundClass (void) { return this; } - - ////////////////////////////////////////////////////////////////////// - // Volume control - ////////////////////////////////////////////////////////////////////// - virtual void Update_Volume (void); - - // From PersistClass - const PersistFactoryClass & Get_Factory (void) const; - - protected: - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual void Initialize_Miles_Handle (void); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - HPROVIDER m_hFilter; -}; - - -#endif //__FILTERED_SOUND_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Listener.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Listener.cpp deleted file mode 100644 index 2ade6c8386..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Listener.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Listener.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:05p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "Listener.h" -#include "WWAudio.h" -#include "Utils.h" -#include "soundhandle.h" - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Listener3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Listener3DClass::Listener3DClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~Listener3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Listener3DClass::~Listener3DClass (void) -{ - Free_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Listener3DClass::Initialize_Miles_Handle (void) -{ - MMSLockClass lock; - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - - ::AIL_set_3D_position (m_SoundHandle->Get_H3DSAMPLE (), 0.0F, 0.0F, 0.0F); - ::AIL_set_3D_orientation (m_SoundHandle->Get_H3DSAMPLE (), - 0.0F, 0.0F, 1.0F, - 0.0F, 1.0F, 0.0F); - - - // Associate this object instance with the handle - m_SoundHandle->Set_Sample_User_Data (INFO_OBJECT_PTR, (S32)this); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Listener3DClass::Allocate_Miles_Handle (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Listener3DClass::Free_Miles_Handle (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Added_To_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Listener3DClass::On_Added_To_Scene (void) -{ - Allocate_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Removed_From_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Listener3DClass::On_Removed_From_Scene (void) -{ - Free_Miles_Handle (); - return ; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Listener.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Listener.h deleted file mode 100644 index 31f7b797d2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Listener.h +++ /dev/null @@ -1,147 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Listener.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 2/07/01 6:10p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __LISTENER_H -#define __LISTENER_H - - -#include "Sound3D.h" - - -///////////////////////////////////////////////////////////////////////////////// -// -// Listener3DClass -// -// Class defining the 'listeners' 3D position/velocity in the world. This should -// only be used by the SoundSceneClass. -// -class Listener3DClass : public Sound3DClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Friend classes - ////////////////////////////////////////////////////////////////////// - friend class SoundSceneClass; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - Listener3DClass (void); - virtual ~Listener3DClass (void); - - ////////////////////////////////////////////////////////////////////// - // Identification methods - ////////////////////////////////////////////////////////////////////// - virtual SOUND_CLASSID Get_Class_ID (void) const { return CLASSID_LISTENER; } - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual Listener3DClass * As_Listener3DClass (void) { return this; } - - ////////////////////////////////////////////////////////////////////// - // Initialization methods - ////////////////////////////////////////////////////////////////////// - virtual void On_Added_To_Scene (void); - virtual void On_Removed_From_Scene (void); - - ////////////////////////////////////////////////////////////////////// - // State control methods - ////////////////////////////////////////////////////////////////////// - //virtual bool Play (void) { return false; } - virtual bool Pause (void) { return false; } - virtual bool Resume (void) { return false; } - virtual bool Stop (bool /*remove*/) { return false; } - virtual void Seek (unsigned long milliseconds) { } - virtual SOUND_STATE Get_State (void) const { return STATE_STOPPED; } - - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - virtual void Set_Max_Vol_Radius (float radius = 0) { } - virtual float Get_Max_Vol_Radius (void) const { return 0; } - virtual void Set_DropOff_Radius (float radius = 1) { } - virtual float Get_DropOff_Radius (void) const { return 0; } - - ////////////////////////////////////////////////////////////////////// - // Velocity methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Velocity (const Vector3 &velocity) { } - - - protected: - - ////////////////////////////////////////////////////////////////////// - // Internal representations - ////////////////////////////////////////////////////////////////////// - virtual void Start_Sample (void) { } - virtual void Stop_Sample (void) { } - virtual void Resume_Sample (void) { } - virtual void End_Sample (void) { } - virtual void Set_Sample_Volume (S32 volume) { } - virtual S32 Get_Sample_Volume (void) { return 0; } - virtual void Set_Sample_Pan (S32 pan) { } - virtual S32 Get_Sample_Pan (void) { return 64; } - virtual void Set_Sample_Loop_Count (U32 count) { } - virtual U32 Get_Sample_Loop_Count (void) { return 0; } - virtual void Set_Sample_MS_Position (U32 ms) { } - virtual void Get_Sample_MS_Position (S32 *len, S32 *pos) { } - virtual S32 Get_Sample_Playback_Rate (void) { return 0; } - virtual void Set_Sample_Playback_Rate (S32 rate) { } - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual void Initialize_Miles_Handle (void); - virtual void Allocate_Miles_Handle (void); - virtual void Free_Miles_Handle (void); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// -}; - - -#endif //__LISTENER_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp deleted file mode 100644 index 673ea9e5b1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/LogicalListener.cpp $* - * * - * $Modtime:: 8/14/01 11:45a $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "LogicalListener.h" -#include "WWAudio.h" -#include "SoundScene.h" -#include "SoundChunkIDs.h" -#include "persistfactory.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Static member initialization -////////////////////////////////////////////////////////////////////////////////// -uint32 LogicalListenerClass::m_OldestTimestamp = 0; -uint32 LogicalListenerClass::m_NewestTimestamp = 1; -float LogicalListenerClass::m_GlobalScale = 1.0F; - - -////////////////////////////////////////////////////////////////////////////////// -// Static factories -////////////////////////////////////////////////////////////////////////////////// -SimplePersistFactoryClass _LogicalListenerPersistFactory; - - -////////////////////////////////////////////////////////////////////////////////// -// Save/Load constants -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_VARIABLES = 0x03270542, - CHUNKID_BASE_CLASS -}; - -enum -{ - XXXVARID_DROP_OFF_RADIUS = 0x01, - VARID_TYPE_MASK, - VARID_XXX1, - VARID_POSITION, - VARID_SCALE -}; - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// LogicalListenerClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -LogicalListenerClass::LogicalListenerClass (void) - : m_Scale (1), - m_TypeMask (0), - m_Position (0, 0, 0), - m_Timestamp (0) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~LogicalListenerClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -LogicalListenerClass::~LogicalListenerClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_To_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -LogicalListenerClass::Add_To_Scene (bool /*start_playing*/) -{ - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if ((scene != NULL) && (m_Scene == NULL)) { - - // - // Add this listener to the culling system - // - m_Scene = scene; - scene->Add_Logical_Listener (this); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_From_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -LogicalListenerClass::Remove_From_Scene (void) -{ - if (m_Scene != NULL) { - - // - // Remove this listener from the culling system - // - m_Scene->Remove_Logical_Listener (this); - m_Scene = NULL; - m_PhysWrapper = NULL; - } - - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -///////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -LogicalListenerClass::Get_Factory (void) const -{ - return _LogicalListenerPersistFactory; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -LogicalListenerClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - SoundSceneObjClass::Save (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_VARIABLES); - - WRITE_MICRO_CHUNK (csave, VARID_SCALE, m_Scale); - WRITE_MICRO_CHUNK (csave, VARID_TYPE_MASK, m_TypeMask); - WRITE_MICRO_CHUNK (csave, VARID_POSITION, m_Position); - - csave.End_Chunk (); - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -LogicalListenerClass::Load (ChunkLoadClass &cload) -{ - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_BASE_CLASS: - PersistClass::Load (cload); - break; - - case CHUNKID_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_SCALE, m_Scale); - READ_MICRO_CHUNK (cload, VARID_TYPE_MASK, m_TypeMask); - READ_MICRO_CHUNK (cload, VARID_POSITION, m_Position); - } - - cload.Close_Micro_Chunk (); - } - } - break; - } - - cload.Close_Chunk (); - } - - return true; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.h deleted file mode 100644 index 5ae4b9c000..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalListener.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/LogicalListener.h $Modtime:: 7/01/99 10:18a $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __LOGICAL_LISTENER_H -#define __LOGICAL_LISTENER_H - -#include "SoundSceneObj.h" -#include "bittype.h" -#include "vector3.h" -#include "matrix3d.h" - -///////////////////////////////////////////////////////////////////////////////// -// -// LogicalListenerClass -// -// This class represents listeners in the 'world' that can hear and react to -// logical sounds. -// -///////////////////////////////////////////////////////////////////////////////// -class LogicalListenerClass : public SoundSceneObjClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - LogicalListenerClass (void); - virtual ~LogicalListenerClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////// - // LogicalSoundClass specific - ////////////////////////////////////////////////////////////////////// - virtual void Set_Type_Mask (uint32 mask = 0) { m_TypeMask = mask; } - virtual uint32 Get_Type_Mask (void) const { return m_TypeMask; } - - ////////////////////////////////////////////////////////////////////// - // Position/direction methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Position (const Vector3 &position) { m_Position = position; } - virtual Vector3 Get_Position (void) const { return m_Position; } - - virtual void Set_Transform (const Matrix3D &transform) { m_Position = transform.Get_Translation (); } - virtual Matrix3D Get_Transform (void) const { Matrix3D tm(1); tm.Set_Translation (m_Position); return tm; } - - ////////////////////////////////////////////////////////////////////// - // Culling methods (not used for listeners) - ////////////////////////////////////////////////////////////////////// - virtual void Cull_Sound (bool culled = true) { }; - virtual bool Is_Sound_Culled (void) const { return false; }; - - ////////////////////////////////////////////////////////////////////// - // Scene integration - ////////////////////////////////////////////////////////////////////// - virtual void Add_To_Scene (bool /*start_playing*/ = true); - virtual void Remove_From_Scene (void); - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - - // - // This is the distance where the listener can no longer hear sounds. - // - virtual void Set_Scale (float scale = 1.0F) { m_Scale = scale; } - virtual float Get_Scale (void) const { return m_Scale; } - virtual float Get_Effective_Scale (void) const { return m_Scale * m_GlobalScale; } - - static float Get_Global_Scale (void) { return m_GlobalScale; } - static void Set_Global_Scale (float scale) { m_GlobalScale = scale; } - - virtual void Set_DropOff_Radius (float radius = 1) {} - virtual float Get_DropOff_Radius (void) const { return 1.0F; } - - ////////////////////////////////////////////////////////////////////// - // From PersistClass - ////////////////////////////////////////////////////////////////////// - bool Save (ChunkSaveClass &csave); - bool Load (ChunkLoadClass &cload); - const PersistFactoryClass & Get_Factory (void) const; - - - ////////////////////////////////////////////////////////////////////// - // Timestamp - ////////////////////////////////////////////////////////////////////// - uint32 Get_Timestamp (void) const { return m_Timestamp; } - void Set_Timestamp (int timestamp) { m_Timestamp = timestamp; } - - static uint32 Get_New_Timestamp (void) { return m_NewestTimestamp ++; } - static uint32 Get_Newest_Timestamp (void) { return m_NewestTimestamp - 1; } - - static uint32 Get_Oldest_Timestamp (void) { return m_OldestTimestamp; } - static void Set_Oldest_Timestamp (uint32 timestamp) { WWASSERT (m_OldestTimestamp < timestamp); m_OldestTimestamp = timestamp; } - - protected: - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - static float m_GlobalScale; - float m_Scale; - uint32 m_TypeMask; - Vector3 m_Position; - uint32 m_Timestamp; - static uint32 m_OldestTimestamp; - static uint32 m_NewestTimestamp; -}; - - -#endif //__LOGICAL_LISTENER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp deleted file mode 100644 index 051b20801c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/LogicalSound.cpp $Modtime:: 7/02/99 10:18a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "LogicalSound.h" -#include "WWAudio.h" -#include "SoundScene.h" -#include "SoundChunkIDs.h" -#include "persistfactory.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Static factories -////////////////////////////////////////////////////////////////////////////////// -SimplePersistFactoryClass _LogicalSoundPersistFactory; - - -////////////////////////////////////////////////////////////////////////////////// -// Save/Load constants -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_VARIABLES = 0x03270459, - CHUNKID_BASE_CLASS -}; - -enum -{ - VARID_DROP_OFF_RADIUS = 0x01, - VARID_IS_SINGLE_SHOT, - VARID_TYPE_MASK, - VARID_XXX1, - VARID_POSITION, - VARID_MAX_LISTENERS, - VARID_NOTIFY_DELAY, - VARID_LAST_NOTIFY, -}; - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// LogicalSoundClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -LogicalSoundClass::LogicalSoundClass (void) - : m_DropOffRadius (1), - m_TypeMask (0), - m_Position (0, 0, 0), - m_IsSingleShot (false), - m_OldestListenerTimestamp (0), - m_MaxListeners (0), - m_NotifyDelayInMS (2000), - m_LastNotification (0) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~LogicalSoundClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -LogicalSoundClass::~LogicalSoundClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_To_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -LogicalSoundClass::Add_To_Scene (bool /*start_playing*/) -{ - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if ((scene != NULL) && (m_Scene == NULL)) { - - // - // Add this sound to the culling system - // - m_Scene = scene; - scene->Add_Logical_Sound (this, m_IsSingleShot); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_From_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -LogicalSoundClass::Remove_From_Scene (void) -{ - if (m_Scene != NULL) { - - // - // Remove this sound from the culling system - // - m_Scene->Remove_Logical_Sound (this, m_IsSingleShot); - m_Scene = NULL; - m_PhysWrapper = NULL; - m_LastNotification = 0; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Allow_Notify -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -LogicalSoundClass::Allow_Notify (uint32 timestamp) -{ - bool retval = false; - - if (m_IsSingleShot || timestamp > (m_LastNotification + m_NotifyDelayInMS)) { - retval = true; - m_LastNotification = timestamp; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -LogicalSoundClass::On_Frame_Update (unsigned int milliseconds) -{ - // - // Update the sound's position if its linked to a render object - // - Apply_Auto_Position (); - return SoundSceneObjClass::On_Frame_Update (milliseconds);; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -///////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -LogicalSoundClass::Get_Factory (void) const -{ - return _LogicalSoundPersistFactory; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -LogicalSoundClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - SoundSceneObjClass::Save (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_VARIABLES); - - WRITE_MICRO_CHUNK (csave, VARID_DROP_OFF_RADIUS, m_DropOffRadius); - WRITE_MICRO_CHUNK (csave, VARID_IS_SINGLE_SHOT, m_IsSingleShot); - WRITE_MICRO_CHUNK (csave, VARID_TYPE_MASK, m_TypeMask); - WRITE_MICRO_CHUNK (csave, VARID_POSITION, m_Position); - WRITE_MICRO_CHUNK (csave, VARID_MAX_LISTENERS, m_MaxListeners); - WRITE_MICRO_CHUNK (csave, VARID_NOTIFY_DELAY, m_NotifyDelayInMS); - WRITE_MICRO_CHUNK (csave, VARID_LAST_NOTIFY, m_LastNotification); - - csave.End_Chunk (); - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -LogicalSoundClass::Load (ChunkLoadClass &cload) -{ - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_BASE_CLASS: - PersistClass::Load (cload); - break; - - case CHUNKID_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_DROP_OFF_RADIUS, m_DropOffRadius); - READ_MICRO_CHUNK (cload, VARID_IS_SINGLE_SHOT, m_IsSingleShot); - READ_MICRO_CHUNK (cload, VARID_TYPE_MASK, m_TypeMask); - READ_MICRO_CHUNK (cload, VARID_POSITION, m_Position); - READ_MICRO_CHUNK (cload, VARID_MAX_LISTENERS, m_MaxListeners); - READ_MICRO_CHUNK (cload, VARID_NOTIFY_DELAY, m_NotifyDelayInMS); - READ_MICRO_CHUNK (cload, VARID_LAST_NOTIFY, m_LastNotification); - } - - cload.Close_Micro_Chunk (); - } - } - break; - } - - cload.Close_Chunk (); - } - - return true; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.h deleted file mode 100644 index e8c6f4114b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/LogicalSound.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/LogicalSound.h $Modtime:: 7/01/99 10:18a $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __LOGICAL_SOUND_H -#define __LOGICAL_SOUND_H - -#include "SoundSceneObj.h" -#include "bittype.h" -#include "vector3.h" -#include "matrix3d.h" - -///////////////////////////////////////////////////////////////////////////////// -// -// LogicalSoundClass -// -// This class represents 'logical' sounds that affect gameplay but do not -// actually make an audible sound -// -class LogicalSoundClass : public SoundSceneObjClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public friends - ////////////////////////////////////////////////////////////////////// - friend class SoundSceneClass; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - LogicalSoundClass (void); - virtual ~LogicalSoundClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////// - // LogicalSoundClass specific - ////////////////////////////////////////////////////////////////////// - virtual bool Is_Single_Shot (void) const { return m_IsSingleShot; } - virtual void Set_Single_Shot (bool single_shot) { m_IsSingleShot = single_shot; } - - virtual void Set_Type_Mask (uint32 mask = 0) { m_TypeMask = mask; } - virtual uint32 Get_Type_Mask (void) const { return m_TypeMask; } - - virtual float Get_Notify_Delay (void) const { return (float)m_NotifyDelayInMS / 1000.0F; } - virtual void Set_Notify_Delay (float secs) { m_NotifyDelayInMS = uint32(secs * 1000.0F); } - virtual bool Allow_Notify (uint32 timestamp); - - virtual uint32 Get_Listener_Timestamp (void) const { return m_OldestListenerTimestamp; } - virtual void Set_Listener_Timestamp (int timestamp) { m_OldestListenerTimestamp = timestamp; } - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); - - ////////////////////////////////////////////////////////////////////// - // Position/direction methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Position (const Vector3 &position) { m_Position = position; } - virtual Vector3 Get_Position (void) const { return m_Position; } - - virtual void Set_Transform (const Matrix3D &transform) { m_Position = transform.Get_Translation (); } - virtual Matrix3D Get_Transform (void) const { Matrix3D tm(1); tm.Set_Translation (m_Position); return tm; } - - ////////////////////////////////////////////////////////////////////// - // Culling methods - ////////////////////////////////////////////////////////////////////// - virtual void Cull_Sound (bool culled = true) { }; - virtual bool Is_Sound_Culled (void) const { return false; }; - - ////////////////////////////////////////////////////////////////////// - // Scene integration - ////////////////////////////////////////////////////////////////////// - virtual void Add_To_Scene (bool start_playing = true); - virtual void Remove_From_Scene (void); - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - - // - // This is the distance where the sound can not be heard any longer. (its vol is 0) - // - virtual void Set_DropOff_Radius (float radius = 1) { m_DropOffRadius = radius; } - virtual float Get_DropOff_Radius (void) const { return m_DropOffRadius; } - - ////////////////////////////////////////////////////////////////////// - // From PersistClass - ////////////////////////////////////////////////////////////////////// - bool Save (ChunkSaveClass &csave); - bool Load (ChunkLoadClass &cload); - const PersistFactoryClass & Get_Factory (void) const; - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - float m_DropOffRadius; - bool m_IsSingleShot; - uint32 m_TypeMask; - Vector3 m_Position; - uint32 m_OldestListenerTimestamp; - int m_MaxListeners; - uint32 m_NotifyDelayInMS; - uint32 m_LastNotification; -}; - - -#endif //__LOGICAL_SOUND_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/PriorityVector.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/PriorityVector.h deleted file mode 100644 index c584ef7b1f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/PriorityVector.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio.h * - * * - * $Archive:: /Commando/Code/WWAudio/PriorityVector.h $Modtime:: 7/02/99 11:43a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __PRIORITY_VECTOR_H -#define __PRIORITY_VECTOR_H - -#include "Vector.H" - -//////////////////////////////////////////////////////////////////// -// -// PriorityVectorClass -// -//////////////////////////////////////////////////////////////////// -template -class PriorityVectorClass : public DynamicVectorClass -{ - public: - - virtual bool Process_Head (T &object); - virtual bool Add_Low (T const &object); - virtual bool Add_High (T const &object); - - /*PriorityVectorClass & operator= (PriorityVectorClass const & rvalue) { - DynamicVectorClass::operator= (rvalue); - return(*t8his); - }*/ -}; - - -//////////////////////////////////////////////////////////////////// -// -// Process_Head -// -//////////////////////////////////////////////////////////////////// -template -__inline bool PriorityVectorClass::Process_Head (T &object) -{ - bool retval = false; - if (Vector != NULL) { - - // Pass the object back to the caller - object = Vector[0]; - - // - // Move the head object to the end of the list - // - for (int index = 1; index < ActiveCount; index ++) { - Vector[index - 1] = Vector[index]; - } - Vector[ActiveCount - 1] = object; - - // Success! - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////// -// -// Add_Low -// -//////////////////////////////////////////////////////////////////// -template -__inline bool PriorityVectorClass::Add_Low (T const &object) -{ - return DynamicVectorClass::Add (object); -} - - -//////////////////////////////////////////////////////////////////// -// -// Add_High -// -//////////////////////////////////////////////////////////////////// -template -__inline bool PriorityVectorClass::Add_High (T const &object) -{ - return DynamicVectorClass::Add_Head (object); -} - -#endif //__PRIORITY_VECTOR_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp deleted file mode 100644 index 17efc134eb..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.cpp +++ /dev/null @@ -1,736 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Sound3D.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:50p $* - * * - * $Revision:: 18 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "Sound3D.h" -#include "SoundBuffer.h" -#include "WWAudio.h" -#include "SoundScene.h" -#include "Utils.h" -#include "SoundChunkIDs.h" -#include "persistfactory.h" -#include "chunkio.h" -#include "sound3dhandle.h" - - -////////////////////////////////////////////////////////////////////////////////// -// -// Static factories -// -////////////////////////////////////////////////////////////////////////////////// -SimplePersistFactoryClass _Sound3DPersistFactory; - - -enum -{ - CHUNKID_VARIABLES = 0x11090955, - CHUNKID_BASE_CLASS -}; - -enum -{ - VARID_AUTO_CALC_VEL = 0x01, - VARID_CURR_VEL, - VARID_XXX1, - VARID_XXX2, - VARID_MAX_VOL_RADIUS, - VARID_IS_STATIC, -}; - - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Sound3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Sound3DClass::Sound3DClass (void) - : m_bAutoCalcVel (true), - m_CurrentVelocity (0, 0, 0), - m_MaxVolRadius (0), - m_LastUpdate (0), - m_IsStatic (false), - m_IsTransformInitted (false) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Sound3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Sound3DClass::Sound3DClass (const Sound3DClass &src) - : m_bAutoCalcVel (true), - m_CurrentVelocity (0, 0, 0), - m_MaxVolRadius (0), - m_LastUpdate (0), - m_IsStatic (false), - m_IsTransformInitted (false), - AudibleSoundClass (src) -{ - (*this) = src; - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~Sound3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Sound3DClass::~Sound3DClass (void) -{ - Free_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const Sound3DClass & -Sound3DClass::operator= (const Sound3DClass &src) -{ - m_bAutoCalcVel = src.m_bAutoCalcVel; - m_CurrentVelocity = src.m_CurrentVelocity; - m_MaxVolRadius = src.m_MaxVolRadius; - m_IsStatic = src.m_IsStatic; - m_LastUpdate = src.m_LastUpdate; - - // Call the base class - AudibleSoundClass::operator= (src); - return (*this); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Play -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -Sound3DClass::Play (bool alloc_handle) -{ - // Record our first 'tick' if we just started playing - if (m_State != STATE_PLAYING) { - m_LastUpdate = ::GetTickCount (); - } - - // Allow the base class to process this call - return AudibleSoundClass::Play (m_IsCulled == false); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -Sound3DClass::On_Frame_Update (unsigned int milliseconds) -{ - Matrix3D prev_tm = m_PrevTransform; - - if (m_bDirty && (m_PhysWrapper != NULL)) { - m_Scene->Update_Sound (m_PhysWrapper); - m_bDirty = false; - } - - // - // Update the sound's position if its linked to a render object - // - Apply_Auto_Position (); - - // - // Make sure the transform is initialized - // - if (m_IsTransformInitted == false) { - prev_tm = m_Transform; - } - - // - // Update the current velocity if we are 'auto-calcing'. - // - if (m_bAutoCalcVel && Get_Class_ID () != CLASSID_LISTENER) { - Vector3 last_pos = prev_tm.Get_Translation (); - Vector3 curr_pos = m_Transform.Get_Translation (); - - // - // Don't update the velocity if we haven't moved (optimization -- Miles calls - // can be really slow) - // - if (last_pos != curr_pos) { - Vector3 curr_vel; - - // - // Extrapolate our current velocity given the last time slice and the distance - // we moved. - // - float secs_since_last_update = (::GetTickCount () - m_LastUpdate); - if (secs_since_last_update > 0) { - curr_vel = ((curr_pos - last_pos) / secs_since_last_update); - } else { - curr_vel.Set (0, 0, 0); - } - - Set_Velocity (curr_vel); - } - } - - // Remember when the last time we updated our 'auto-calc' - // variables. - m_LastUpdate = ::GetTickCount (); - m_PrevTransform = m_Transform; - - // Allow the base class to process this call - return AudibleSoundClass::On_Frame_Update (); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Transform -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_Transform (const Matrix3D &transform) -{ - if (transform == m_Transform) { - return ; - } - - - // Update our internal transform - m_PrevTransform = m_Transform; - m_Transform = transform; - Set_Dirty (); - - if (m_IsTransformInitted == false) { - m_PrevTransform = transform; - m_IsTransformInitted = true; - } - - Update_Miles_Transform (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Listener_Transform -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_Listener_Transform (const Matrix3D &tm) -{ - // - // If the transform has changed, then cache the new transform - // and update the sound's position in the "Mile's" world - // - if (m_ListenerTransform != tm) { - m_ListenerTransform = tm; - - Update_Miles_Transform (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Miles_Transform -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Update_Miles_Transform (void) -{ - // - // Do we have a valid miles handle? - // - if (m_SoundHandle != NULL) { - - // - // Build a matrix to transform coordinates from world-space to listener-space - // - Matrix3D world_to_listener_tm; - m_ListenerTransform.Get_Orthogonal_Inverse (world_to_listener_tm); - - // - // Transform the object's TM into "listener-space" - // -#ifdef ALLOW_TEMPORARIES - Matrix3D listener_space_tm = world_to_listener_tm * m_Transform; -#else - Matrix3D listener_space_tm; - listener_space_tm.mul(world_to_listener_tm, m_Transform); -#endif - - // - // Pass the sound's position onto miles - // - Vector3 position = listener_space_tm.Get_Translation (); - ::AIL_set_3D_position (m_SoundHandle->Get_H3DSAMPLE (), -position.Y, position.Z, position.X); - - // - // Pass the sound's orientation (facing) onto miles - // - Vector3 facing = listener_space_tm.Get_X_Vector (); - Vector3 up = listener_space_tm.Get_Z_Vector (); - - ::AIL_set_3D_orientation (m_SoundHandle->Get_H3DSAMPLE (), - -facing.Y, - facing.Z, - facing.X, - -up.Y, - up.Z, - up.X); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Position -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_Position (const Vector3 &position) -{ - // - // Pass the sound's position onto miles - // - if (m_Transform.Get_Translation () != position) { - // Update our internal transform - // - // SKB: 4/13/01 - Confirmed to be OK by Pat Smith. - // Took Set_Transform() outside of condition because even if sound is - // not playing I need to be able to change it's position. - // I had a problem that sounds would never be added to the scene because - // their positions stayed at 0,0,0 even after this Set_Postion() call. - m_PrevTransform = m_Transform; - m_Transform.Set_Translation (position); - Set_Dirty (); - - if (m_IsTransformInitted == false) { - m_PrevTransform = m_Transform; - m_IsTransformInitted = true; - } - - if (m_SoundHandle != NULL) { - - // - // Transform the sound's position into 'listener-space' - // - Vector3 sound_pos = position; - Vector3 listener_space_pos; - Matrix3D::Inverse_Transform_Vector (m_ListenerTransform, sound_pos, &listener_space_pos); - - // - // Update the object's position inside of Miles - // - ::AIL_set_3D_position (m_SoundHandle->Get_H3DSAMPLE (), -listener_space_pos.Y, - listener_space_pos.Z, listener_space_pos.X); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Velocity -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_Velocity (const Vector3 &velocity) -{ - MMSLockClass lock; - - m_CurrentVelocity = velocity; - Set_Dirty (); - - // - // Pass the sound's velocity onto miles - // - if (m_SoundHandle != NULL) { - - //WWDEBUG_SAY (("Current Velocity: %.2f %.2f %.2f\n", m_CurrentVelocity.X, m_CurrentVelocity.Y, m_CurrentVelocity.Z)); - ::AIL_set_3D_velocity_vector (m_SoundHandle->Get_H3DSAMPLE (), - -m_CurrentVelocity.Y, - m_CurrentVelocity.Z, - m_CurrentVelocity.X); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_DropOff_Radius -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_DropOff_Radius (float radius) -{ - //MMSLockClass lock; - - m_DropOffRadius = radius; - Set_Dirty (); - - // Pass attenuation settings onto miles - if (m_SoundHandle != NULL) { - ::AIL_set_3D_sample_distances ( m_SoundHandle->Get_H3DSAMPLE (), - m_DropOffRadius, - (m_MaxVolRadius > 1.0F) ? m_MaxVolRadius : 1.0F); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Max_Vol_Radius -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_Max_Vol_Radius (float radius) -{ - m_MaxVolRadius = radius; - Set_Dirty (); - - // Pass attenuation settings onto miles - if (m_SoundHandle != NULL) { - ::AIL_set_3D_sample_distances ( m_SoundHandle->Get_H3DSAMPLE (), - m_DropOffRadius, - (m_MaxVolRadius > 1.0F) ? m_MaxVolRadius : 1.0F); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Initialize_Miles_Handle (void) -{ - MMSLockClass lock; - - // If this sound is already playing, then update its - // playing position to make sure we really should - // be playing it... (it will free the miles handle if not) - if (m_State == STATE_PLAYING) { - Update_Play_Position (); - } - - // Do we have a valid sample handle from miles? - if (m_SoundHandle != NULL) { - - // - // Pass the actual sound data onto the sample - // - m_SoundHandle->Initialize (m_Buffer); - - // - // Record the total length of the sample in milliseconds... - // - m_SoundHandle->Get_Sample_MS_Position ((S32 *)&m_Length, NULL); - - // - // Pass our cached settings onto miles - // - float real_volume = Determine_Real_Volume (); - m_SoundHandle->Set_Sample_Volume (int(real_volume * 127.0F)); - m_SoundHandle->Set_Sample_Pan (int(m_Pan * 127.0F)); - m_SoundHandle->Set_Sample_Loop_Count (m_LoopCount); - - // - // Pass attenuation settings onto miles - // - ::AIL_set_3D_sample_distances ( m_SoundHandle->Get_H3DSAMPLE (), - m_DropOffRadius, - (m_MaxVolRadius > 1.0F) ? m_MaxVolRadius : 1.0F); - - - // - // Assign the 3D effects level accordingly (for reverb, etc) - // - ::AIL_set_3D_sample_effects_level (m_SoundHandle->Get_H3DSAMPLE (), - WWAudioClass::Get_Instance ()->Get_Effects_Level ()); - - // - // Pass the sound's position and orientation onto Miles - // - Update_Miles_Transform (); - - // - // Apply the pitch factor (if necessary) - // - if (m_PitchFactor != 1.0F) { - Set_Pitch_Factor (m_PitchFactor); - } - - // If this sound is already playing (and just now got a handle) - // then make sure we start it. - if (m_State == STATE_PLAYING) { - m_SoundHandle->Start_Sample (); - - // Update the loop count based on the number of loops left - m_SoundHandle->Set_Sample_Loop_Count (m_LoopsLeft); - } - - // Seek to the position of the sound where we last left off. - // For example, this sound could have gotten bumped due to a low priority, - // but is now back and ready to resume at the position it would have been - // at if it was never bumped. - Seek (m_CurrentPosition); - - // Associate this object instance with the handle - m_SoundHandle->Set_Sample_User_Data (INFO_OBJECT_PTR, (S32)this); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Allocate_Miles_Handle (void) -{ - //MMSLockClass lock; - - // - // If we need to, get a play-handle from the audio system - // - if (m_SoundHandle == NULL) { - Set_Miles_Handle ((MILES_HANDLE)WWAudioClass::Get_Instance ()->Get_3D_Sample (*this)); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_To_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Add_To_Scene (bool start_playing) -{ - SoundSceneClass *scene = WWAudioClass::Get_Instance ()->Get_Sound_Scene (); - if ((scene != NULL) && (m_Scene == NULL)) { - - // Determine what culling system this sound belongs to - if (m_IsStatic) { - scene->Add_Static_Sound (this, start_playing); - } else { - scene->Add_Sound (this, start_playing); - } - m_Scene = scene; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_From_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Remove_From_Scene (void) -{ - if (m_Scene != NULL) { - - // Determine what culling system this sound belongs to - if (m_IsStatic) { - m_Scene->Remove_Static_Sound (this); - } else { - m_Scene->Remove_Sound (this); - } - - m_Scene = NULL; - m_PhysWrapper = NULL; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Loop_End -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::On_Loop_End (void) -{ - // Allow the base class to process this message - AudibleSoundClass::On_Loop_End (); - return ; -} - -///////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -///////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -Sound3DClass::Get_Factory (void) const -{ - return _Sound3DPersistFactory; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -Sound3DClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - AudibleSoundClass::Save (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_VARIABLES); - - WRITE_MICRO_CHUNK (csave, VARID_AUTO_CALC_VEL, m_bAutoCalcVel); - WRITE_MICRO_CHUNK (csave, VARID_CURR_VEL, m_CurrentVelocity); - - WRITE_MICRO_CHUNK (csave, VARID_MAX_VOL_RADIUS, m_MaxVolRadius); - WRITE_MICRO_CHUNK (csave, VARID_IS_STATIC, m_IsStatic); - - csave.End_Chunk (); - - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -Sound3DClass::Load (ChunkLoadClass &cload) -{ - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_BASE_CLASS: - AudibleSoundClass::Load (cload); - break; - - case CHUNKID_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_AUTO_CALC_VEL, m_bAutoCalcVel); - READ_MICRO_CHUNK (cload, VARID_CURR_VEL, m_CurrentVelocity); - READ_MICRO_CHUNK (cload, VARID_MAX_VOL_RADIUS, m_MaxVolRadius); - READ_MICRO_CHUNK (cload, VARID_IS_STATIC, m_IsStatic); - } - - cload.Close_Micro_Chunk (); - } - } - break; - } - - cload.Close_Chunk (); - } - - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -Sound3DClass::Set_Miles_Handle (MILES_HANDLE handle) -{ - // - // Start fresh - // - Free_Miles_Handle (); - - // - // Is our data valid? - // - if (handle != INVALID_MILES_HANDLE && m_Buffer != NULL) { - - // - // Configure the sound handle - // - m_SoundHandle = W3DNEW Sound3DHandleClass; - m_SoundHandle->Set_Miles_Handle (handle); - - // - // Use this new handle - // - Initialize_Miles_Handle (); - } - - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.h deleted file mode 100644 index d18a7cd01c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Sound3D.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Sound3D.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 12:06p $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUND3DOBJ_H -#define __SOUND3DOBJ_H - -#include "AudibleSound.h" -#include "mempool.h" - - - - -///////////////////////////////////////////////////////////////////////////////// -// -// Sound3DClass -// -// Class defining a 3D sound. A 3D sound uses position and velocity information -// to determine volume/panning/doppler etc. -// -// A 3D sound should be added to the SoundScene rather than explicitly played. The -// SoundScene will determine when a 3D sound is 'in range' and play it... -// -class Sound3DClass : public AudibleSoundClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Friend classes - ////////////////////////////////////////////////////////////////////// - friend class SoundSceneClass; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - Sound3DClass (const Sound3DClass &src); - Sound3DClass (void); - virtual ~Sound3DClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////// - const Sound3DClass &operator= (const Sound3DClass &src); - - - ////////////////////////////////////////////////////////////////////// - // Identification methods - ////////////////////////////////////////////////////////////////////// - virtual SOUND_CLASSID Get_Class_ID (void) const { return CLASSID_3D; } - virtual void Make_Static (bool is_static = true) { m_IsStatic = is_static; } - virtual bool Is_Static (void) const { return m_IsStatic; } - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual Sound3DClass * As_Sound3DClass (void) { return this; } - - ////////////////////////////////////////////////////////////////////// - // State control methods - ////////////////////////////////////////////////////////////////////// - virtual bool Play (bool alloc_handle = true); - - ////////////////////////////////////////////////////////////////////// - // Priority control - ////////////////////////////////////////////////////////////////////// - virtual float Get_Priority (void) const { if (m_IsCulled) return 0; return m_Priority; } - - ////////////////////////////////////////////////////////////////////// - // Scene integration - ////////////////////////////////////////////////////////////////////// - virtual void Add_To_Scene (bool start_playing = true); - virtual void Remove_From_Scene (void); - - ////////////////////////////////////////////////////////////////////// - // Position/direction methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Position (const Vector3 &position); - virtual Vector3 Get_Position (void) const { return m_Transform.Get_Translation (); } - - virtual void Set_Listener_Transform (const Matrix3D &tm); - virtual void Set_Transform (const Matrix3D &transform); - virtual Matrix3D Get_Transform (void) const { return m_Transform; } - void Update_Miles_Transform (void); - - ////////////////////////////////////////////////////////////////////// - // Velocity methods - ////////////////////////////////////////////////////////////////////// - - // - // The velocity settings are in meters per millisecond. - // - virtual void Set_Velocity (const Vector3 &velocity); - virtual Vector3 Get_Velocity (void) const { return m_CurrentVelocity; } - virtual void Get_Velocity (Vector3 &velocity) const { velocity = m_CurrentVelocity; } - - virtual void Auto_Calc_Velocity (bool autocalc = true) { m_bAutoCalcVel = autocalc; } - virtual bool Is_Auto_Calc_Velocity_On (void) const { return m_bAutoCalcVel; } - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - - // - // The maximum-volume radius is the distance from the sound-emitter where - // it seems as loud as it is going to get. Volume does not increase after this - // point. Volume is linerally interpolated from the DropOff distance to the MaxVol - // distance. For some objects (like an airplane) the max-vol distance is - // not 0, but would be 100 or so meters away. - // - virtual void Set_Max_Vol_Radius (float radius = 0); - virtual float Get_Max_Vol_Radius (void) const { return m_MaxVolRadius; } - - // - // This is the distance where the sound can not be heard any longer. (its vol is 0) - // - virtual void Set_DropOff_Radius (float radius = 1); - virtual float Get_DropOff_Radius () {return(m_DropOffRadius);} - - // From PersistClass - const PersistFactoryClass & Get_Factory (void) const; - - // - // From PersistClass - // - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual SoundCullObjClass * Peek_Cullable_Wrapper (void) const { return m_PhysWrapper; } - virtual void Set_Cullable_Wrapper (SoundCullObjClass *obj) { m_PhysWrapper = obj; } - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual void Set_Miles_Handle (MILES_HANDLE handle); - virtual void Initialize_Miles_Handle (void); - virtual void Allocate_Miles_Handle (void); - - ////////////////////////////////////////////////////////////////////// - // Event handling - ////////////////////////////////////////////////////////////////////// - virtual void On_Loop_End (void); - - ////////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////////// - bool m_IsTransformInitted; - bool m_bAutoCalcVel; - Vector3 m_CurrentVelocity; - float m_MaxVolRadius; - bool m_IsStatic; - unsigned int m_LastUpdate; -}; - - -#endif //__SOUND3DOBJ_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp deleted file mode 100644 index 8f25bbca7b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.cpp +++ /dev/null @@ -1,381 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundBuffer.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/17/01 11:22a $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "SoundBuffer.h" -#include "RAWFILE.H" -#include "wwdebug.h" -#include "Utils.h" -#include "ffactory.h" -#include "win.h" - - - -///////////////////////////////////////////////////////////////////////////////// -// FileMappingClass -///////////////////////////////////////////////////////////////////////////////// -class FileMappingClass -{ -public: - StringClass Filename; - HANDLE FileMapping; - int RefCount; - - bool operator== (const FileMappingClass &src) { return false; } - bool operator!= (const FileMappingClass &src) { return false; } -}; - -static DynamicVectorClass MappingList; - - - -///////////////////////////////////////////////////////////////////////////////// -// -// SoundBufferClass -// -SoundBufferClass::SoundBufferClass (void) - : m_Buffer (NULL), - m_Length (0), - m_Filename (NULL), - m_Duration (0), - m_Rate (0), - m_Bits (0), - m_Channels (0), - m_Type (WAVE_FORMAT_IMA_ADPCM) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// ~SoundBufferClass -// -SoundBufferClass::~SoundBufferClass (void) -{ - SAFE_FREE (m_Filename); - Free_Buffer (); - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Free_Buffer -// -void -SoundBufferClass::Free_Buffer (void) -{ - // Free the buffer's memory - if (m_Buffer != NULL) { - delete [] m_Buffer; - m_Buffer = NULL; - } - - // Make sure we reset the length - m_Length = 0L; - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Determine_Stats -// -void -SoundBufferClass::Determine_Stats (unsigned char *buffer) -{ - MMSLockClass lock; - - m_Duration = 0; - m_Rate = 0; - m_Channels = 0; - m_Bits = 0; - m_Type = WAVE_FORMAT_IMA_ADPCM; - - // Attempt to get statistical information about this sound - AILSOUNDINFO info = { 0 }; - if ((buffer != NULL) && (::AIL_WAV_info (buffer, &info) != 0)) { - - // Cache this information - m_Rate = info.rate; - m_Channels = info.channels; - m_Bits = info.bits; - m_Type = info.format; - - // Determine how long this sound will play for - float bytes_sec = float((m_Channels * m_Rate * m_Bits) >> 3); - m_Duration = (unsigned long)((((float)m_Length) / bytes_sec) * 1000.0F); - } - - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Set_Filename -// -void -SoundBufferClass::Set_Filename (const char *name) -{ - SAFE_FREE (m_Filename); - if (name != NULL) { - m_Filename = ::strdup (name); - } - - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Load_From_File -// -bool -SoundBufferClass::Load_From_File (const char *filename) -{ - // Assume failure - bool retval = false; - - // Param OK? - WWASSERT (filename != NULL); - if (filename != NULL) { - - // Create a file object and pass it onto the appropriate function - FileClass *file=_TheFileFactory->Get_File(filename); - if ( file ) { - retval = Load_From_File(*file); - _TheFileFactory->Return_File(file); - } - file=NULL; - } - - // Return the true/false result code - return retval; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Load_From_File -// -bool -SoundBufferClass::Load_From_File (FileClass &file) -{ - MMSLockClass lock; - - // Assume failure - bool retval = false; - - // Start from scratch - Free_Buffer (); - Set_Filename (file.File_Name ()); - - // Open the file if necessary - bool we_opened = false; - if (file.Is_Open () == false) { - we_opened = (file.Open () == TRUE); - } - - // Determine the size of the buffer - m_Length = file.Size (); - WWASSERT (m_Length > 0L); - if (m_Length > 0L) { - - // Allocate a new buffer of the correct length and read the contents - // of the file into the buffer - m_Buffer = W3DNEWARRAY unsigned char[m_Length]; - retval = bool(file.Read (m_Buffer, m_Length) == (int)m_Length); - - // If we failed, free the buffer - if (retval == false) { - Free_Buffer (); - } - Determine_Stats (m_Buffer); - } - - // Close the file if necessary - if (we_opened) { - file.Close (); - } - - // Return the true/false result code - return retval; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Load_From_Memory -// -bool -SoundBufferClass::Load_From_Memory -( - unsigned char *mem_buffer, - unsigned long size -) -{ - MMSLockClass lock; - - // Assume failure - bool retval = false; - - // Start from scratch - Free_Buffer (); - Set_Filename ("unknown.wav"); - - // Params OK? - WWASSERT (mem_buffer != NULL); - WWASSERT (size > 0L); - if ((mem_buffer != NULL) && (size > 0L)) { - - // Allocate a new buffer of the correct length and copy the contents - // into the buffer - m_Length = size; - m_Buffer = W3DNEWARRAY unsigned char[m_Length]; - ::memcpy (m_Buffer, mem_buffer, size); - retval = true; - - // If we failed, free the buffer - if (retval == false) { - Free_Buffer (); - } - Determine_Stats (m_Buffer); - } - - // Return the true/false result code - return retval; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// StreamSoundBufferClass -// -StreamSoundBufferClass::StreamSoundBufferClass (void) : - SoundBufferClass () -{ - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// ~StreamSoundBufferClass -// -StreamSoundBufferClass::~StreamSoundBufferClass (void) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Free_Buffer -// -void -StreamSoundBufferClass::Free_Buffer (void) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Load_From_File -// -///////////////////////////////////////////////////////////////////////////////// -bool -StreamSoundBufferClass::Load_From_File -( - HANDLE /*hfile*/, - unsigned long /*size*/, - unsigned long /*offset*/ -) -{ - return true; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Load_From_File -// -///////////////////////////////////////////////////////////////////////////////// -bool -StreamSoundBufferClass::Load_From_File (const char *filename) -{ - return true; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Load_From_File -// -///////////////////////////////////////////////////////////////////////////////// -bool -StreamSoundBufferClass::Load_From_File (FileClass &file) -{ - MMSLockClass lock; - - // Start from scratch - Free_Buffer (); - Set_Filename (file.File_Name ()); - - // Open the file if necessary - bool we_opened = false; - if (file.Is_Open () == false) { - we_opened = (file.Open () == TRUE); - } - - m_Length = file.Size (); - - // Allocate a new buffer of the correct length and read the contents - // of the file into the buffer - unsigned char buffer[4096] = { 0 }; - file.Read (buffer, sizeof (buffer)); - Determine_Stats (buffer); - - // Close the file if necessary - if (we_opened) { - file.Close (); - } - - return true; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h deleted file mode 100644 index 15ad673083..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundBuffer.h +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundBuffer.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/17/01 11:12a $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDBUFFER_H -#define __SOUNDBUFFER_H - -#pragma warning (push, 3) -#include "mss.h" -#pragma warning (pop) - -#include "refcount.h" - - -// Forward declarations -class FileClass; - - -///////////////////////////////////////////////////////////////////////////////// -// -// SoundBufferClass -// -// A sound buffer manages the raw sound data for any of the SoundObj types -// except for the StreamSoundClass object. -// -class SoundBufferClass : public RefCountClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - SoundBufferClass (void); - virtual ~SoundBufferClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////// - operator unsigned char * (void) { return Get_Raw_Buffer (); } - - ////////////////////////////////////////////////////////////////////// - // File methods - ////////////////////////////////////////////////////////////////////// - virtual bool Load_From_File (const char *filename); - virtual bool Load_From_File (FileClass &file); - - ////////////////////////////////////////////////////////////////////// - // Memory methods - ////////////////////////////////////////////////////////////////////// - virtual bool Load_From_Memory (unsigned char *mem_buffer, unsigned long size); - - ////////////////////////////////////////////////////////////////////// - // Buffer access - ////////////////////////////////////////////////////////////////////// - virtual unsigned char * Get_Raw_Buffer (void) const { return m_Buffer; } - virtual unsigned long Get_Raw_Length (void) const { return m_Length; } - - ////////////////////////////////////////////////////////////////////// - // Information methods - ////////////////////////////////////////////////////////////////////// - virtual const char * Get_Filename (void) const { return m_Filename; } - virtual void Set_Filename (const char *name); - virtual unsigned long Get_Duration (void) const { return m_Duration; } - virtual unsigned long Get_Rate (void) const { return m_Rate; } - virtual unsigned long Get_Bits (void) const { return m_Bits; } - virtual unsigned long Get_Channels (void) const { return m_Channels; } - virtual unsigned long Get_Type (void) const { return m_Type; } - - ////////////////////////////////////////////////////////////////////// - // Type methods - ////////////////////////////////////////////////////////////////////// - virtual bool Is_Streaming (void) const { return false; } - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - virtual void Free_Buffer (void); - virtual void Determine_Stats (unsigned char *buffer); - - ////////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////////// - unsigned char * m_Buffer; - unsigned long m_Length; - char * m_Filename; - unsigned long m_Duration; - unsigned long m_Rate; - unsigned long m_Bits; - unsigned long m_Channels; - unsigned long m_Type; -}; - - -///////////////////////////////////////////////////////////////////////////////// -// -// StreamSoundBufferClass -// -// A sound buffer manages the raw sound data for any of the SoundObj types -// except for the StreamSoundClass object. -// -class StreamSoundBufferClass : public SoundBufferClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - StreamSoundBufferClass (void); - virtual ~StreamSoundBufferClass (void); - - ////////////////////////////////////////////////////////////////////// - // File methods - ////////////////////////////////////////////////////////////////////// - virtual bool Load_From_File (const char *filename); - virtual bool Load_From_File (FileClass &file); - - ////////////////////////////////////////////////////////////////////// - // Memory methods - ////////////////////////////////////////////////////////////////////// - virtual bool Load_From_Memory (unsigned char *mem_buffer, unsigned long size) { return false; } - - ////////////////////////////////////////////////////////////////////// - // Type methods - ////////////////////////////////////////////////////////////////////// - virtual bool Is_Streaming (void) const { return true; } - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - virtual void Free_Buffer (void); - virtual bool Load_From_File (HANDLE hfile, unsigned long size, unsigned long offset); - - ////////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////////// -}; - - -#endif //__SOUNDBUFFER_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h deleted file mode 100644 index c6750a7293..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundChunkIDs.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : LevelEdit * - * * - * $Archive:: /Commando/Code/WWAudio/SoundChunkIDs.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 3/27/00 5:43p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUND_CHUNK_IDS_H -#define __SOUND_CHUNK_IDS_H - -#include "saveloadids.h" -#include "definitionclassids.h" - - -////////////////////////////////////////////////////////////////////////////////// -// -// These are the chunk IDs that serve as 'globally-unique' persist identifiers for -// all persist objects inside the editor. These are used when building the -// PersistFactoryClass's for definitions. -// -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_SOUND_DEF = CHUNKID_WWAUDIO_BEGIN, - CHUNKID_AUDIBLE_SOUND, - CHUNKID_FILTERED_SOUND, - CHUNKID_SOUND3D, - CHUNKID_PSEUDO_SOUND3D, - CHUNKID_STATIC_SAVELOAD, - CHUNKID_DYNAMIC_SAVELOAD, - CHUNKID_LOGICALSOUND, - CHUNKID_LOGICALLISTENER -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// These are the globally-unique class identifiers that the definition system -// uses inside the editor. -// -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CLASSID_SOUND_DEF = CLASSID_SOUND, -}; - - -#endif //__SOUND_CHUNK_IDS_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h deleted file mode 100644 index 92b8852ef8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundCullObj.h +++ /dev/null @@ -1,173 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundCullObj.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 6/26/01 5:36p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDCULLOBJ_H -#define __SOUNDCULLOBJ_H - -#include "SoundSceneObj.h" -#include "cullsys.h" -#include "refcount.h" -#include "mempool.h" -#include "multilist.h" - - -///////////////////////////////////////////////////////////////////////////// -// -// SoundCullObjClass -// -// Simple 'sound physics' object that wraps a SoundClass object and is derived -// from PhysClass so it can be used with the different culling systems. -// -class SoundCullObjClass : public MultiListObjectClass, public CullableClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - SoundCullObjClass (void) - : m_SoundObj (NULL), - m_Transform (1) {} - - virtual ~SoundCullObjClass (void) { REF_PTR_RELEASE (m_SoundObj); } - - ////////////////////////////////////////////////////////////////////// - // Get the 'bounds' of this sound - ////////////////////////////////////////////////////////////////////// - virtual const AABoxClass & Get_Bounding_Box (void) const; - - ////////////////////////////////////////////////////////////////////// - // Access to the Position/Orientation state of the object - ////////////////////////////////////////////////////////////////////// - virtual const Matrix3D & Get_Transform (void) const; - virtual void Set_Transform (const Matrix3D &transform); - - ////////////////////////////////////////////////////////////////////// - // Timestep methods - ////////////////////////////////////////////////////////////////////// - virtual void Timestep (float dt) {} - - ////////////////////////////////////////////////////////////////////// - // Sound object wrapping - ////////////////////////////////////////////////////////////////////// - virtual void Set_Sound_Obj (SoundSceneObjClass *sound_obj); - virtual SoundSceneObjClass * Peek_Sound_Obj (void) const { return m_SoundObj; } - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - SoundSceneObjClass * m_SoundObj; - mutable Matrix3D m_Transform; - mutable AABoxClass m_AABox; -}; - - -__inline const Matrix3D & -SoundCullObjClass::Get_Transform (void) const -{ - // Determine the transform to use - if (m_SoundObj != NULL) { - m_Transform = m_SoundObj->Get_Transform (); - } - - // Return a reference to the matrix - return m_Transform; -} - - -__inline void -SoundCullObjClass::Set_Transform (const Matrix3D &transform) -{ - m_Transform = transform; - - // Pass the tranform on - if (m_SoundObj != NULL) { - m_SoundObj->Set_Transform (m_Transform); - Set_Cull_Box (Get_Bounding_Box ()); - } - - return ; -} - - -__inline void -SoundCullObjClass::Set_Sound_Obj (SoundSceneObjClass *sound_obj) -{ - // Start using this sound object - REF_PTR_SET (m_SoundObj, sound_obj); - //m_SoundObj = sound_obj; - if (m_SoundObj != NULL) { - m_Transform = m_SoundObj->Get_Transform (); - Set_Cull_Box (Get_Bounding_Box ()); - } - - return ; -} - - -__inline const AABoxClass & -SoundCullObjClass::Get_Bounding_Box (void) const -{ - // Get the 'real' values from the - if (m_SoundObj != NULL) { - m_Transform = m_SoundObj->Get_Transform (); - m_AABox.Extent.X = m_SoundObj->Get_DropOff_Radius (); - m_AABox.Extent.Y = m_SoundObj->Get_DropOff_Radius (); - m_AABox.Extent.Z = m_SoundObj->Get_DropOff_Radius (); - } else { - m_AABox.Extent.X = 0; - m_AABox.Extent.Y = 0; - m_AABox.Extent.Z = 0; - } - - m_AABox.Center = m_Transform.Get_Translation (); - return m_AABox; -} - -#endif //__SOUNDCULLOBJ_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp deleted file mode 100644 index e454af8344..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundPseudo3D.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 12:09p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "SoundPseudo3D.h" -#include "WWAudio.h" -#include "SoundScene.h" -#include "Utils.h" -#include "SoundChunkIDs.h" -#include "persistfactory.h" -#include "soundhandle.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Static factories -////////////////////////////////////////////////////////////////////////////////// -SimplePersistFactoryClass _PseudoSound3DPersistFactory; - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// SoundPseudo3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundPseudo3DClass::SoundPseudo3DClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// SoundPseudo3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundPseudo3DClass::SoundPseudo3DClass (const SoundPseudo3DClass &src) - : Sound3DClass (src) -{ - (*this) = src; - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~SoundPseudo3DClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundPseudo3DClass::~SoundPseudo3DClass (void) -{ - Free_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const SoundPseudo3DClass & -SoundPseudo3DClass::operator= (const SoundPseudo3DClass &src) -{ - // Call the base class - Sound3DClass::operator= (src); - return (*this); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Set_Miles_Handle (MILES_HANDLE handle) -{ - AudibleSoundClass::Set_Miles_Handle (handle); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Initialize_Miles_Handle (void) -{ - AudibleSoundClass::Initialize_Miles_Handle (); - Update_Pseudo_Volume (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Pseudo_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Update_Pseudo_Volume (float distance) -{ - MMSLockClass lock; - - // - // Only do this if the sound is really playing - // - if (m_SoundHandle != NULL) { - - float volume_mod = Determine_Real_Volume (); - float max_distance = Get_DropOff_Radius (); - float min_distance = Get_Max_Vol_Radius (); - float delta = max_distance - min_distance; - - // Determine a normalized volume from the position - float volume = 1.0F; - if (distance > min_distance) { - volume = 1.0F - ((distance - min_distance) / delta); - volume = min (volume, 1.0F); - volume = max (volume, 0.0F); - } - - // Multiply the 'max' volume with the calculated volume - volume = volume * volume_mod; - - // - // Pass the volume on - // - m_SoundHandle->Set_Sample_Volume (int(volume * 127.0F)); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Pseudo_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Update_Pseudo_Volume (void) -{ - MMSLockClass lock; - - // Only do this if the sound is really playing - if (m_SoundHandle != NULL) { - - // - // Find the difference in the sound position and its listener's position - // - Vector3 sound_pos = m_ListenerTransform.Get_Translation () - m_Transform.Get_Translation (); - float distance = sound_pos.Quick_Length (); - - // - // Determine a normalized volume from the position - // - Update_Pseudo_Volume (distance); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Pseudo_Pan -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Update_Pseudo_Pan (void) -{ - MMSLockClass lock; - - // - // Only do this if the sound is really playing - // - if (m_SoundHandle != NULL) { - - // - // Transform the sound's position into 'listener-space' - // - Vector3 sound_pos = m_Transform.Get_Translation (); - Vector3 rel_sound_pos; - Matrix3D::Inverse_Transform_Vector (m_ListenerTransform, sound_pos, &rel_sound_pos); - - // - // Calculate a normalized pan from 0 (hard left) to 1.0F (hard right) - // - float angle = WWMath::Atan2 (rel_sound_pos.Y, rel_sound_pos.X); - float pan = -WWMath::Fast_Sin (angle); - pan = (pan / 2.0F) + 0.5F; - - // - // Pass the pan on - // - m_SoundHandle->Set_Sample_Pan (S32(pan * 127.0F)); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Allocate_Miles_Handle (void) -{ - AudibleSoundClass::Allocate_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_Miles_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundPseudo3DClass::Free_Miles_Handle (void) -{ - AudibleSoundClass::Free_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundPseudo3DClass::On_Frame_Update (unsigned int milliseconds) -{ - // If necessary, update the volume based on the distance - // from the listener - if (m_SoundHandle != NULL) { - Update_Pseudo_Volume (); - Update_Pseudo_Pan (); - } - - // Allow the base Sound3DClass to process this call - return Sound3DClass::On_Frame_Update (); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -SoundPseudo3DClass::Get_Factory (void) const -{ - return _PseudoSound3DPersistFactory; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h deleted file mode 100644 index 2c9a26bd0b..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundPseudo3D.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundPseudo3D.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 12:06p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUND_PSEUDO_3DOBJ_H -#define __SOUND_PSEUDO_3DOBJ_H - - -#include "Sound3D.h" - - -///////////////////////////////////////////////////////////////////////////////// -// -// SoundPseudo3DClass -// -// Pseudo-3D objects are not true 3D sounds. They have the -// same properties as 3D 'sound effects' but do not use 3D -// hardware, are not restricted to mono, uncompressed, WAV data, -// and do not calculate doppler and reverb effects. -// -class SoundPseudo3DClass : public Sound3DClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - SoundPseudo3DClass (const SoundPseudo3DClass &src); - SoundPseudo3DClass (void); - virtual ~SoundPseudo3DClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////// - const SoundPseudo3DClass &operator= (const SoundPseudo3DClass &src); - - ////////////////////////////////////////////////////////////////////// - // Identification methods - ////////////////////////////////////////////////////////////////////// - virtual SOUND_CLASSID Get_Class_ID (void) const { return CLASSID_PSEUDO3D; } - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual SoundPseudo3DClass * As_SoundPseudo3DClass (void) { return this; } - - ////////////////////////////////////////////////////////////////////// - // Volume control - ////////////////////////////////////////////////////////////////////// - virtual void Update_Volume (void) { Update_Pseudo_Volume (); } - - ////////////////////////////////////////////////////////////////////// - // Position/direction methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Listener_Transform (const Matrix3D &tm) { m_ListenerTransform = tm; } - virtual void Set_Position (const Vector3 &position) { Set_Dirty (); m_Transform.Set_Translation (position); } - virtual void Set_Transform (const Matrix3D &transform) { Set_Dirty (); m_Transform = transform; } - - ////////////////////////////////////////////////////////////////////// - // Velocity methods - ////////////////////////////////////////////////////////////////////// - - // - // The velocity settings are in meters per millisecond. - // - virtual void Set_Velocity (const Vector3 &velocity) { } - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - - // - // The maximum-volume radius is the distance from the sound-emitter where - // it seems as loud as it is going to get. Volume does not increase after this - // point. Volume is linerally interpolated from the DropOff distance to the MaxVol - // distance. For some objects (like an airplane) the max-vol distance is - // not 0, but would be 100 or so meters away. - // - virtual void Set_Max_Vol_Radius (float radius = 0) { m_MaxVolRadius = radius; } - virtual float Get_Max_Vol_Radius (void) const { return m_MaxVolRadius; } - - // - // This is the distance where the sound can not be heard any longer. (its vol is 0) - // - virtual void Set_DropOff_Radius (float radius = 1) { m_DropOffRadius = radius; } - virtual float Get_DropOff_Radius (void) const { return m_DropOffRadius; } - - ////////////////////////////////////////////////////////////////////// - // Volume control - ////////////////////////////////////////////////////////////////////// - virtual void Update_Pseudo_Volume (void); - virtual void Update_Pseudo_Volume (float distance); - - ////////////////////////////////////////////////////////////////////// - // Pan control - ////////////////////////////////////////////////////////////////////// - virtual void Update_Pseudo_Pan (void); - - // From PersistClass - const PersistFactoryClass & Get_Factory (void) const; - - protected: - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual void Set_Miles_Handle (MILES_HANDLE handle); - virtual void Initialize_Miles_Handle (void); - virtual void Allocate_Miles_Handle (void); - virtual void Free_Miles_Handle (void); - - virtual void On_Loop_End (void) { Sound3DClass::On_Loop_End (); } - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// -}; - - -#endif //__SOUND_PSEUDO_3DOBJ_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp deleted file mode 100644 index 9d7ee88616..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.cpp +++ /dev/null @@ -1,1301 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundScene.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/14/01 2:55p $* - * * - * $Revision:: 32 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "SoundScene.h" -#include "SoundCullObj.h" -#include "LogicalSound.h" -#include "LogicalListener.h" -#include "chunkio.h" -#include "persistfactory.h" -#include "wwprofile.h" -#include "Threads.h" -#include "wwmemlog.h" - - -DEFINE_AUTO_POOL(SoundSceneClass::AudibleInfoClass, 64); - - -////////////////////////////////////////////////////////////////////////////////// -// Generic constants -////////////////////////////////////////////////////////////////////////////////// -const int MAX_LOGICAL_LISTENER_UPDATES_PER_FRAME = 4; - - -////////////////////////////////////////////////////////////////////////////////// -// Save/Load constants -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_VARIABLES = 0x00000100, - CHUNKID_STATIC_SOUNDS, - CHUNKID_DYNAMIC_SOUNDS -}; - -enum -{ - VARID_MIN_DIM = 0x01, - VARID_MAX_DIM, -}; - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// SoundSceneClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundSceneClass::SoundSceneClass (void) - : m_Listener (NULL), - m_2ndListener (NULL), - m_MinExtents (-500, -500, -500), - m_MaxExtents (500, 500, 500), - m_IsBatchMode (false) -{ - WWMEMLOG(MEM_SOUND); - m_Listener = W3DNEW Listener3DClass; - m_DynamicCullingSystem.Re_Partition (m_MinExtents, m_MaxExtents, 100.00F); - m_LogicalCullingSystem.Re_Partition (m_MinExtents, m_MaxExtents, 100.00F); - m_ListenerCullingSystem.Re_Partition (m_MinExtents, m_MaxExtents, 40.00F); - m_StaticCullingSystem.Re_Partition (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~SoundSceneClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundSceneClass::~SoundSceneClass (void) -{ - REF_PTR_RELEASE (m_Listener); - REF_PTR_RELEASE (m_2ndListener); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Re_Partition -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Re_Partition -( - const Vector3 &min_dimension, - const Vector3 &max_dimension -) -{ - m_DynamicCullingSystem.Re_Partition (min_dimension, max_dimension, 100.00F); - m_LogicalCullingSystem.Re_Partition (min_dimension, max_dimension, 100.00F); - m_ListenerCullingSystem.Re_Partition (min_dimension, max_dimension, 40.00F); - m_StaticCullingSystem.Re_Partition (); - - m_MinExtents = min_dimension; - m_MaxExtents = max_dimension; - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Collect_Logical_Sounds -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Collect_Logical_Sounds (int listener_count) -{ - WWPROFILE ("Collect_Logical_Sounds"); - - uint32 timestamp = ::GetTickCount (); - - // - // Determine how many listeners to process - // - int count = listener_count; - int max = MAX_LOGICAL_LISTENER_UPDATES_PER_FRAME; - if ((count < 0) || (count > max)) { - count = max; - } - - PriorityMultiListIterator priority_queue (&m_LogicalListeners); - LogicalListenerClass *listener = NULL; - - // - // Loop over as many of the listeners as we want to process this - // frame. - // - for ( int total = 0; - total < count && priority_queue.Process_Head (&listener); - total ++) - { - LogicalListenerClass::Set_Oldest_Timestamp (listener->Get_Timestamp ()); - listener->Set_Timestamp (LogicalListenerClass::Get_New_Timestamp ()); - listener->On_Frame_Update (); - - // - // Collect a list of the sounds this listener can hear. - // - Vector3 position = listener->Get_Position (); - m_LogicalCullingSystem.Reset_Collection (); - m_LogicalCullingSystem.Collect_Objects (position); - - // - // Now loop through the list of sounds this listener can hear - // and notify their callback. - // - SoundCullObjClass * cull_obj; - for ( cull_obj = m_LogicalCullingSystem.Get_First_Collected_Object(); - cull_obj != NULL; - cull_obj = m_LogicalCullingSystem.Get_Next_Collected_Object (cull_obj)) - { - // - // Get a pointer to the current 'cull-sound' object. - // - LogicalSoundClass *sound_obj = (LogicalSoundClass *)cull_obj->Peek_Sound_Obj (); - - // - // Test this sound against the scale associated with the current listener to - // see if the listener can really "hear" the sound. - // - const Vector3 &sound_pos = cull_obj->Get_Bounding_Box ().Center; - Vector3 listener_pos = listener->Get_Position (); - float dropoff_radius = sound_obj->Get_DropOff_Radius (); - float scale = listener->Get_Effective_Scale (); - float test_radius2 = (dropoff_radius * scale) * (dropoff_radius * scale); - if ((listener_pos - sound_pos).Length2 () <= test_radius2) { - - // - // Is the sound ready to notify? - // - if (sound_obj->Allow_Notify (timestamp)) { - listener->On_Event (AudioCallbackClass::EVENT_LOGICAL_HEARD, (uint32)listener, (uint32)sound_obj); - } - } - } - } - - // - // Loop through and remove any single shot sounds that have - // been completely processed - // - MultiListIterator single_shot_it (&m_SingleShotLogicalSounds); - for (single_shot_it.First (); !single_shot_it.Is_Done (); single_shot_it.Next ()) { - LogicalSoundClass *sound_obj = single_shot_it.Peek_Obj (); - - // - // Remove this sound if its been completely processed - // - if (sound_obj->Get_Listener_Timestamp () <= LogicalListenerClass::Get_Oldest_Timestamp ()) { - sound_obj->Remove_From_Scene (); - single_shot_it.Remove_Current_Object (); - single_shot_it.Prev (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Collect_Audible_Sounds -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Collect_Audible_Sounds -( - Listener3DClass * listener, - COLLECTED_SOUNDS &list -) -{ - WWPROFILE ("Collect_Audible_Sounds"); - - // - // Collect a list of the audible dynamic sounds - // - Vector3 listener_pos = listener->Get_Position (); - m_DynamicCullingSystem.Reset_Collection (); - m_DynamicCullingSystem.Collect_Objects (listener_pos); - - // - // Collect a list of the audible static sounds - // - m_StaticCullingSystem.Reset_Collection (); - m_StaticCullingSystem.Collect_Objects (listener_pos); - - // - // Loop through all the dynamic sounds that are currently audible and make sure - // they are 'really' audible. The culling systems just check bounding boxes - // but we need to be able to check attenuation spheres. - // - SoundCullObjClass * cull_obj = NULL; - for ( cull_obj = m_DynamicCullingSystem.Get_First_Collected_Object(); - cull_obj != NULL; - cull_obj = m_DynamicCullingSystem.Get_Next_Collected_Object(cull_obj)) - { - // Get a pointer to the current 'cull-sound' object - AudibleSoundClass *sound_obj = (AudibleSoundClass *)cull_obj->Peek_Sound_Obj (); - - // Perform a quick sphere-cull check to make sure this - // sound should really be audible - Vector3 pos = sound_obj->Get_Position (); - float radius = sound_obj->Get_DropOff_Radius (); - float radius2 = radius * radius; - float length2 = (pos - listener_pos).Length2 (); - if (length2 <= radius2) { - - AudibleInfoClass *audible_info = W3DNEW AudibleInfoClass (sound_obj, length2); - list.Add (audible_info); - - // - // Update this sound's runtime priority based on its distance - // from the sound emitter. - // - float length = (pos - listener_pos).Quick_Length (); - float priority = (length > 0) ? 1 - (length / radius) : 1.0F; - sound_obj->Set_Runtime_Priority (priority); - } - } - - // - // Loop through all the static sounds that are currently audible and make sure - // they are 'really' audible. The culling systems just check bounding boxes - // but we need to be able to check attenuation spheres. - // - for ( cull_obj = m_StaticCullingSystem.Get_First_Collected_Object(); - cull_obj != NULL; - cull_obj = m_StaticCullingSystem.Get_Next_Collected_Object(cull_obj)) - { - AudibleSoundClass *sound_obj = (AudibleSoundClass *)cull_obj->Peek_Sound_Obj (); - - // Perform a quick sphere-cull check to make sure this - // sound should really be audible - Vector3 pos = sound_obj->Get_Position (); - float radius = sound_obj->Get_DropOff_Radius (); - float radius2 = radius * radius; - float length2 = (pos - listener_pos).Length2 (); - if (length2 <= radius2) { - - AudibleInfoClass *audible_info = W3DNEW AudibleInfoClass (sound_obj, length2); - list.Add (audible_info); - - // - // Update this sound's runtime priority based on its distance - // from the sound emitter. - // - float length = (pos - listener_pos).Quick_Length (); - float priority = (length > 0) ? 1 - (length / radius) : 1.0F; - sound_obj->Set_Runtime_Priority (priority); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -// Note: This method could be made more efficient by using another data structure besides -// linked lists. However the differece may be negligable due to the low density of 3D sounds -// that are audible at once. -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::On_Frame_Update (unsigned int milliseconds) -{ - WWPROFILE ("On_Frame_Update"); - - COLLECTED_SOUNDS auxiliary_sounds; - COLLECTED_SOUNDS primary_sounds; - - // - // First, collect any auxiliary sounds that are audible - // - if (m_2ndListener != NULL) { - m_2ndListener->On_Frame_Update (milliseconds); - Collect_Audible_Sounds (m_2ndListener, auxiliary_sounds); - } - - // - // Update the listener's position/velocity, etc - // - m_Listener->On_Frame_Update (milliseconds); - - // - // Collect the primary sounds that are audible - // - Collect_Audible_Sounds (m_Listener, primary_sounds); - - // - // Loop through the auxiliary sounds and make sure - // sounds are only played once, either primary or auxiliary. - // - MultiListIterator aux_iterator (&auxiliary_sounds); - MultiListIterator pri_iterator (&primary_sounds); - AUDIBLE_SOUND_LIST audible_sounds; - - for (aux_iterator.First (); !aux_iterator.Is_Done (); aux_iterator.Next ()) { - AudibleInfoClass *aux_info = aux_iterator.Peek_Obj (); - - // - // Loop through all the primary sounds and remove any - // that are 'overpowered' by the same sound in the - // other listener. - // - bool found = false; - for (pri_iterator.First (); !pri_iterator.Is_Done () && !found; pri_iterator.Next ()) { - AudibleInfoClass *pri_info = pri_iterator.Peek_Obj (); - - // - // Is this sound in both lists? - // - found = (aux_info->sound_obj == pri_info->sound_obj); - if (found) { - if (aux_info->distance2 < pri_info->distance2) { - delete pri_info; - primary_sounds.Remove (pri_info); - } else { - delete aux_info; - auxiliary_sounds.Remove (aux_info); - } - } - } - } - - // - // Add the primary audible sounds into the master list - // - for (pri_iterator.First (); !pri_iterator.Is_Done (); pri_iterator.Next ()) { - AudibleInfoClass *pri_info = pri_iterator.Peek_Obj (); - audible_sounds.Add (pri_info->sound_obj); - - // - // Let the sound know what it's listener's position is - // - pri_info->sound_obj->Set_Listener_Transform (m_Listener->Get_Transform ()); - - // - // Free the audible info object - // - pri_iterator.Remove_Current_Object (); - pri_iterator.Prev (); - delete pri_info; - } - - // - // Add the auxiliary audible sounds into the master list - // - for (aux_iterator.First (); !aux_iterator.Is_Done (); aux_iterator.Next ()) { - AudibleInfoClass *aux_info = aux_iterator.Peek_Obj (); - audible_sounds.Add (aux_info->sound_obj); - - // - // Let the sound know what it's listener's position is - // - aux_info->sound_obj->Set_Listener_Transform (m_2ndListener->Get_Transform ()); - - // - // Convert the sound to a Pseudo-3D sound that has - // a 'tinny' filter applied to it. - // - /*aux_info.sound_obj->Convert_To_Filtered (); - AudibleSoundClass *tinny_sound = aux_info.sound_obj->As_Converted_Format (); - if (tinny_sound != NULL) { - audible_sounds.Add (tinny_sound); - }*/ - - // - // Free the audible info object - // - aux_iterator.Remove_Current_Object (); - aux_iterator.Prev (); - delete aux_info; - } - - // - // Loop through all the sounds that were audible last frame - // and see if they are still audible this frame. - // - MultiListIterator audible_iterator (&m_LastSoundsAudible); - for (audible_iterator.First (); !audible_iterator.Is_Done (); audible_iterator.Next ()) { - AudibleSoundClass *sound_obj = audible_iterator.Peek_Obj (); - - // - // Is this sound still audible? - // - if (audible_sounds.Is_In_List (sound_obj)) { - - // - // Make sure the sound is playing, then remove it from - // the newly-audible list so we don't process it again - // - sound_obj->Cull_Sound (false); - audible_sounds.Remove (sound_obj); - - } else { - - // - // If the sound isn't audible any more then remove - // it from the list - // - audible_iterator.Remove_Current_Object (); - audible_iterator.Prev (); - - // - // Make sure we cull the sound - // - WWASSERT(sound_obj != NULL); - sound_obj->Cull_Sound (true); - sound_obj->Set_Runtime_Priority (0); - } - } - - // - // Loop through all the newly-audible sounds and - // make sure they are playing. - // - MultiListIterator newly_audible_it (&audible_sounds); - for (newly_audible_it.First (); !newly_audible_it.Is_Done (); newly_audible_it.Next ()) { - AudibleSoundClass *sound_obj = newly_audible_it.Peek_Obj (); - - // - // Make sure the sound has a valid Miles handle (so it can make noise) - // - sound_obj->Cull_Sound (false); - - // - // If this sound is still in the scene (it may have 'stopped' - // while it was culled) then start playing it... - // - if (sound_obj->Is_In_Scene ()) { - m_LastSoundsAudible.Add (sound_obj); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Add_Sound -( - AudibleSoundClass * sound_obj, - bool start_playing -) -{ - WWPROFILE ("Add_Sound"); - WWMEMLOG(MEM_SOUND); - - WWASSERT (sound_obj != NULL); - if (sound_obj != NULL && sound_obj->Is_In_Scene () == false) { - bool cull_sound = true; - - - // Create a wrapper object for the sound that we can use - // with the different culling systems. - SoundCullObjClass *cullable_sound = W3DNEW SoundCullObjClass; - cullable_sound->Set_Sound_Obj (sound_obj); - sound_obj->Set_Cullable_Wrapper (cullable_sound); - - // - // Add this object to the dynamic culling system - // - m_DynamicCullingSystem.Add_Object (cullable_sound); - m_DynamicSounds.Add (cullable_sound); - Update_Sound (cullable_sound); - - // - // If the listener can hear this sound, then make sure - // we start it off non-culled - // - if (m_IsBatchMode == false) { - - Vector3 listener_pos = m_Listener->Get_Position (); - Vector3 sound_pos = sound_obj->Get_Position (); - float radius = sound_obj->Get_DropOff_Radius (); - float radius2 = radius * radius; - - if (((listener_pos - sound_pos).Length2 ()) < radius2) { - cull_sound = false; - m_LastSoundsAudible.Add (sound_obj); - start_playing = true; - sound_obj->Set_Listener_Transform (m_Listener->Get_Transform ()); - } - } - - // - // Make sure the sound is appropriately culled - // - sound_obj->Cull_Sound (cull_sound); - - // - // Start the sound playing if requested - // - if (start_playing) { - sound_obj->Play (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_Sound -// -// Note: This method should really be rewritten to use a different list type. Linked lists -// are probably too inefficient (especially if we have 100s or 1000s of sounds) -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Remove_Sound -( - AudibleSoundClass *sound_obj, - bool stop_playing -) -{ - WWPROFILE ("Remove_Sound"); - - if (sound_obj == NULL) { - return ; - } - - // - // Make sure we remove this sound from the list of last audible sounds. - // - if (m_LastSoundsAudible.Is_In_List (sound_obj)) { - m_LastSoundsAudible.Remove (sound_obj); - } - - // - // Is this sound really in the scene? - // - SoundCullObjClass *cull_obj = sound_obj->Peek_Cullable_Wrapper (); - if (cull_obj != NULL && m_DynamicSounds.Is_In_List (cull_obj)) { - - // - // Stop playing the sound if necessary - // - if (stop_playing) { - sound_obj->Stop (); - } - - // - // Flush the sound's cull-wrapper since we are removing it from the scene - // - sound_obj->Set_Cullable_Wrapper (NULL); - - // - // Remove this sound from the dynamic culling system - // - m_DynamicCullingSystem.Remove_Object (cull_obj); - m_DynamicSounds.Remove (cull_obj); - - // - // Register the sound for deletion at an appropriate time - // - WWAudioThreadsClass::Add_Delayed_Release_Object (cull_obj); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_Static_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Add_Static_Sound -( - AudibleSoundClass * sound_obj, - bool start_playing -) -{ - WWPROFILE ("Add_Static_Sound"); - - WWASSERT (sound_obj != NULL); - if (sound_obj != NULL) { - - // - // Check to see if this sound is already in the scene - // - SoundCullObjClass *cull_obj = sound_obj->Peek_Cullable_Wrapper (); - if (cull_obj == NULL) { - - // - // Create a wrapper object for the sound that we can use - // with the different culling systems. - // - cull_obj = W3DNEW SoundCullObjClass; - cull_obj->Set_Sound_Obj (sound_obj); - sound_obj->Set_Cullable_Wrapper (cull_obj); - - // - // Add this object to the static culling system - // - m_StaticCullingSystem.Add_Object (cull_obj); - m_StaticSounds.Add (cull_obj); - Update_Sound (cull_obj); - - // - // If the listener can hear this sound, then make sure - // we start it off non-culled - // - bool cull_sound = true; - if (m_IsBatchMode == false) { - - Vector3 listener_pos = m_Listener->Get_Position (); - Vector3 sound_pos = sound_obj->Get_Position (); - float radius = sound_obj->Get_DropOff_Radius (); - float radius2 = radius * radius; - - if (((listener_pos - sound_pos).Length2 ()) < radius2) { - cull_sound = false; - m_LastSoundsAudible.Add (sound_obj); - start_playing = true; - sound_obj->Set_Listener_Transform (m_Listener->Get_Transform ()); - } - } - - // - // Make sure the sound is appropriately culled - // - sound_obj->Cull_Sound (cull_sound); - - // - // Start the sound playing if requested - // - if (start_playing) { - sound_obj->Play (); - } - - // - // Add a ref to the static sound object - // - //sound_obj->Add_Ref (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_Static_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Remove_Static_Sound -( - AudibleSoundClass * sound_obj, - bool stop_playing -) -{ - WWPROFILE ("Remove_Static_Sound"); - - if (sound_obj == NULL) { - return ; - } - - // - // Make sure we remove this sound from the list of last audible sounds. - // - if (m_LastSoundsAudible.Is_In_List (sound_obj)) { - m_LastSoundsAudible.Remove (sound_obj); - } - - // - // Is this sound really in the scene? - // - SoundCullObjClass *cull_obj = sound_obj->Peek_Cullable_Wrapper (); - if (cull_obj != NULL && m_StaticSounds.Is_In_List (cull_obj)) { - - // - // Stop playing the sound if necessary - // - if (stop_playing) { - sound_obj->Stop (); - } - - // - // Flush the sound's cull-wrapper since we are removing it from the scene - // - sound_obj->Set_Cullable_Wrapper (NULL); - - // - // Remove this sound from the static culling system - // - m_StaticCullingSystem.Remove_Object (cull_obj); - m_StaticSounds.Remove (cull_obj); - - // - // Register the sound for deletion at an appropriate time - // - WWAudioThreadsClass::Add_Delayed_Release_Object (cull_obj); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_Logical_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Add_Logical_Sound -( - LogicalSoundClass * sound_obj, - bool single_shot -) -{ - WWPROFILE ("Add_Logical_Sound"); - - WWASSERT (sound_obj != NULL); - if (sound_obj != NULL) { - - // - // Check to make sure we don't add this sound twice - // - if (Is_Logical_Sound_In_Scene (sound_obj, single_shot) == false) { - sound_obj->Set_Listener_Timestamp (LogicalListenerClass::Get_Newest_Timestamp ()); - - // - // Create a wrapper object for the sound that we can use - // with the different culling systems. - // - SoundCullObjClass *cullable_sound = W3DNEW SoundCullObjClass; - cullable_sound->Set_Sound_Obj (sound_obj); - sound_obj->Set_Cullable_Wrapper (cullable_sound); - - // - // Add this object to the logical culling system - // - m_LogicalCullingSystem.Add_Object (cullable_sound); - - // - // Add this sound to our current sounds list - // - if (single_shot) { - m_SingleShotLogicalSounds.Add (sound_obj); - } else { - m_LogicalSounds.Add (sound_obj); - } - - // - // Keep a reference on this sound object - // - sound_obj->Add_Ref (); - - // - // Make sure the cull-object has the most up-to-date information - // about this sound object's bounding volume - // - Update_Sound (cullable_sound); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_Logical_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Remove_Logical_Sound -( - LogicalSoundClass * sound_obj, - bool single_shot, - bool remove_from_list -) -{ - WWPROFILE ("Remove_Logical_Sound"); - - if (sound_obj == NULL) { - return ; - } - - if (single_shot) { - - // - // Only do this if the logical sound is really in our list - // - if (m_SingleShotLogicalSounds.Is_In_List (sound_obj)) { - - // - // Remove this sound from logical sound list - // - if (remove_from_list) { - m_SingleShotLogicalSounds.Remove (sound_obj); - } - - // - // Remove this sound from the culling system - // - SoundCullObjClass *cull_obj = sound_obj->Peek_Cullable_Wrapper (); - m_LogicalCullingSystem.Remove_Object (cull_obj); - - // - // Remove this sound obj's wrapper - // - sound_obj->Set_Cullable_Wrapper (NULL); - WWAudioThreadsClass::Add_Delayed_Release_Object (cull_obj); - - // - // Release our reference on this object - // - REF_PTR_RELEASE (sound_obj); - } - - } else { - - // - // Only do this if the logical sound is really in our list - // - if (m_LogicalSounds.Is_In_List (sound_obj)) { - - // - // Remove this sound from logical sound list - // - if (remove_from_list) { - m_LogicalSounds.Remove (sound_obj); - } - - // - // Remove this sound from the culling system - // - SoundCullObjClass *cull_obj = sound_obj->Peek_Cullable_Wrapper (); - m_LogicalCullingSystem.Remove_Object (cull_obj); - - // - // Remove this sound obj's wrapper - // - sound_obj->Set_Cullable_Wrapper (NULL); - WWAudioThreadsClass::Add_Delayed_Release_Object (cull_obj); - - // - // Release our reference on this object - // - REF_PTR_RELEASE (sound_obj); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_Logical_Listener -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Add_Logical_Listener (LogicalListenerClass *listener_obj) -{ - WWPROFILE ("Add_Logical_Listener"); - - WWASSERT (listener_obj != NULL); - if (listener_obj != NULL) { - - // - // Add the listener to the 'scene' if its in our list - // - if (m_LogicalListeners.Is_In_List (listener_obj) == false) { - listener_obj->Set_Timestamp (LogicalListenerClass::Get_New_Timestamp ()); - m_LogicalListeners.Add_Tail (listener_obj); - listener_obj->Add_Ref (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_Logical_Listener -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Remove_Logical_Listener (LogicalListenerClass *listener_obj) -{ - WWPROFILE ("Remove_Logical_Listener"); - - WWASSERT (listener_obj != NULL); - if (listener_obj != NULL) { - - // - // Remove the listener from the 'scene' if its in our list - // - if (m_LogicalListeners.Is_In_List (listener_obj)) { - m_LogicalListeners.Remove (listener_obj); - listener_obj->Release_Ref (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Update_Sound (SoundCullObjClass *sound_obj) -{ - if (sound_obj != NULL) { - sound_obj->Set_Cull_Box(sound_obj->Get_Bounding_Box()); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Initialize (void) -{ - m_Listener->Free_Miles_Handle (); - m_Listener->Allocate_Miles_Handle (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Is_Sound_In_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneClass::Is_Sound_In_Scene (AudibleSoundClass *sound_obj, bool all) -{ - bool retval = false; - - // - // Try to find this sound's cull-object in either the static or dynamic - // lists. - // - SoundCullObjClass *cull_obj = sound_obj->Peek_Cullable_Wrapper (); - if (cull_obj != NULL) { - retval = (m_DynamicSounds.Is_In_List (cull_obj) || m_StaticSounds.Is_In_List (cull_obj)); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Is_Logical_Sound_In_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneClass::Is_Logical_Sound_In_Scene -( - LogicalSoundClass * sound_obj, - bool single_shot -) -{ - bool retval = false; - - // - // Check to see if this sound is in either the continuous list or the single shot list. - // - if (single_shot == false) { - retval = m_LogicalSounds.Is_In_List (sound_obj); - } else { - retval = m_SingleShotLogicalSounds.Is_In_List (sound_obj); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Save_Static -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneClass::Save_Static (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_VARIABLES); - WRITE_MICRO_CHUNK (csave, VARID_MIN_DIM, m_MinExtents); - WRITE_MICRO_CHUNK (csave, VARID_MAX_DIM, m_MaxExtents); - csave.End_Chunk (); - - // - // Save the list of static sounds that are currently in the scene - // - csave.Begin_Chunk (CHUNKID_STATIC_SOUNDS); - Save_Static_Sounds (csave); - csave.End_Chunk (); - - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Save_Static_Sounds -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Save_Static_Sounds (ChunkSaveClass &csave) -{ - Re_Partition (m_MinExtents, m_MaxExtents); - - // - // Loop over all the static sounds that are in the scene - // and save each to its own chunk. - // - MultiListIterator static_iterator (&m_StaticSounds); - for (static_iterator.First (); !static_iterator.Is_Done (); static_iterator.Next ()) { - SoundCullObjClass *cull_obj = static_iterator.Peek_Obj (); - - // - // Get the sound from its cull object - // - AudibleSoundClass *sound_obj = (AudibleSoundClass *)cull_obj->Peek_Sound_Obj (); - if (sound_obj != NULL) { - - // - // Have the sound's factory save it - // - csave.Begin_Chunk (sound_obj->Get_Factory ().Chunk_ID ()); - sound_obj->Get_Factory ().Save (csave, sound_obj); - csave.End_Chunk (); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Load_Static_Sounds -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Load_Static_Sounds (ChunkLoadClass &cload) -{ - while (cload.Open_Chunk ()) { - - // - // Load this sound from the chunk (if possible) - // - PersistFactoryClass *factory = SaveLoadSystemClass::Find_Persist_Factory (cload.Cur_Chunk_ID ()); - if (factory != NULL) { - AudibleSoundClass *sound_obj = (AudibleSoundClass *)factory->Load (cload); - if (sound_obj != NULL) { - sound_obj->Add_To_Scene (true); - REF_PTR_RELEASE (sound_obj); - } - } - - cload.Close_Chunk (); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Load_Static -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneClass::Load_Static (ChunkLoadClass &cload) -{ - m_IsBatchMode = true; - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_STATIC_SOUNDS: - Load_Static_Sounds (cload); - break; - - case CHUNKID_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - READ_MICRO_CHUNK (cload, VARID_MIN_DIM, m_MinExtents); - READ_MICRO_CHUNK (cload, VARID_MAX_DIM, m_MaxExtents); - } - - cload.Close_Micro_Chunk (); - } - } - break; - } - - cload.Close_Chunk (); - } - - Re_Partition (m_MinExtents, m_MaxExtents); - On_Frame_Update (0); - m_IsBatchMode = false; - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Save_Dynamic -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneClass::Save_Dynamic (ChunkSaveClass &csave) -{ - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Load_Dynamic -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneClass::Load_Dynamic (ChunkLoadClass &cload) -{ - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Flush_Scene -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Flush_Scene (void) -{ - RefMultiListClass temp_static; - RefMultiListClass temp_dynamic; - - // - // Build temporary lists of the static and dynamic sounds - // - MultiListIterator static_iterator (&m_StaticSounds); - for (static_iterator.First (); !static_iterator.Is_Done (); static_iterator.Next ()) { - SoundCullObjClass *cull_obj = static_iterator.Peek_Obj (); - temp_static.Add (cull_obj); - } - - MultiListIterator dynamic_iterator (&m_DynamicSounds); - for (dynamic_iterator.First (); !dynamic_iterator.Is_Done (); dynamic_iterator.Next ()) { - SoundCullObjClass *cull_obj = dynamic_iterator.Peek_Obj (); - temp_dynamic.Add (cull_obj); - } - - // - // Remove all the static sounds from the scene - // - RefMultiListIterator temp_static_it (&temp_static); - for (temp_static_it.First (); !temp_static_it.Is_Done (); temp_static_it.Next ()) { - SoundCullObjClass *cull_obj = temp_static_it.Peek_Obj (); - - AudibleSoundClass *sound_obj = (AudibleSoundClass *)cull_obj->Peek_Sound_Obj (); - if (sound_obj != NULL) { - Remove_Static_Sound (sound_obj); - } - } - - // - // Remove all the dynamic sounds from the scene - // - RefMultiListIterator temp_dynamic_it (&temp_dynamic); - for (temp_dynamic_it.First (); !temp_dynamic_it.Is_Done (); temp_dynamic_it.Next ()) { - SoundCullObjClass *cull_obj = temp_dynamic_it.Peek_Obj (); - - AudibleSoundClass *sound_obj = (AudibleSoundClass *)cull_obj->Peek_Sound_Obj (); - if (sound_obj != NULL) { - Remove_Sound (sound_obj); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_2nd_Listener -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneClass::Set_2nd_Listener (Listener3DClass *listener) -{ - if (m_2ndListener != NULL) { - m_2ndListener->On_Removed_From_Scene (); - } - - if (listener != NULL) { - listener->On_Added_To_Scene (); - } - - REF_PTR_SET (m_2ndListener, listener); - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.h deleted file mode 100644 index f9c90a627e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundScene.h +++ /dev/null @@ -1,227 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundScene.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 2/07/01 6:10p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDSCENE_H -#define __SOUNDSCENE_H - -#include "aabtreecull.h" -#include "gridcull.h" -#include "Listener.h" -#include "Vector.H" -#include "PriorityVector.h" -#include "SoundCullObj.h" -#include "LogicalListener.h" -#include "multilist.h" - -// Forward declarations -class RenderObjClass; -class ChunkSaveClass; -class ChunkLoadClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// Typedefs -// -////////////////////////////////////////////////////////////////////////////////// -typedef TypedGridCullSystemClass DynamicSoundCullClass; -typedef TypedAABTreeCullSystemClass StaticSoundCullClass; -typedef MultiListClass AUDIBLE_SOUND_LIST; -typedef MultiListClass SOUND_LIST; -typedef MultiListClass LOGICAL_SOUND_LIST; -typedef MultiListClass LOGICAL_LISTENER_LIST; - - -///////////////////////////////////////////////////////////////////////////////// -// -// SoundSceneClass -// -// Mimics the 'SceneClass' for render objects. Used to insert 3D sounds into -// a virtual world. Used to efficiently cull sounds that are too far away -// from the listner to be heard. -// -class SoundSceneClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Friend classes - ////////////////////////////////////////////////////////////////////// - friend class WWAudioClass; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - SoundSceneClass (void); - virtual ~SoundSceneClass (void); - - ////////////////////////////////////////////////////////////////////// - // Partition methods - ////////////////////////////////////////////////////////////////////// - virtual void Re_Partition (const Vector3 &min_dimension, const Vector3 &max_dimension); - - ////////////////////////////////////////////////////////////////////// - // Logical sound methods - ////////////////////////////////////////////////////////////////////// - virtual void Collect_Logical_Sounds (int listener_count = -1); - - ////////////////////////////////////////////////////////////////////// - // Listener methods - ////////////////////////////////////////////////////////////////////// - virtual void Attach_Listener_To_Obj (RenderObjClass *render_obj, int bone_index = -1) { m_Listener->Attach_To_Object (render_obj, bone_index); } - - virtual void Set_Listener_Position (const Vector3 &pos) { m_Listener->Set_Position (pos); } - virtual Vector3 Get_Listener_Position (void) const { return m_Listener->Get_Position (); } - - virtual void Set_Listener_Transform (const Matrix3D &transform) { m_Listener->Set_Transform (transform); } - virtual Matrix3D Get_Listener_Transform (void) const { return m_Listener->Get_Transform (); } - - virtual Listener3DClass *Peek_2nd_Listener (void) const { return m_2ndListener; } - virtual void Set_2nd_Listener (Listener3DClass *listener); - - ////////////////////////////////////////////////////////////////////// - // Sound insertion - ////////////////////////////////////////////////////////////////////// - virtual void Flush_Scene (void); - virtual void Update_Sound (SoundCullObjClass *sound_obj); - - // - // These methods are for inserting audible-dynamic sounds into the scene. - // - virtual void Add_Sound (AudibleSoundClass *sound_obj, bool start_playing = true); - virtual void Remove_Sound (AudibleSoundClass *sound_obj, bool stop_playing = true); - - // - // Static sounds are those that will never change position in the world. - // These sounds can be more efficiently culled. - // - virtual void Add_Static_Sound (AudibleSoundClass *sound_obj, bool start_playing = true); - virtual void Remove_Static_Sound (AudibleSoundClass *sound_obj, bool stop_playing = true); - - // - // These methods are for inserting logical sounds and listeners into the scene. - // - virtual void Add_Logical_Sound (LogicalSoundClass *sound_obj, bool single_shot = false); - virtual void Remove_Logical_Sound (LogicalSoundClass *sound_obj, bool single_shot = false, bool remove_from_list = true); - - virtual void Add_Logical_Listener (LogicalListenerClass *listener_obj); - virtual void Remove_Logical_Listener (LogicalListenerClass *listener_obj); - - ////////////////////////////////////////////////////////////////////// - // Save/Load - ////////////////////////////////////////////////////////////////////// - bool Save_Static (ChunkSaveClass &csave); - bool Load_Static (ChunkLoadClass &cload); - bool Save_Dynamic (ChunkSaveClass &csave); - bool Load_Dynamic (ChunkLoadClass &cload); - - bool Is_Batch_Mode (void) const { return m_IsBatchMode; } - void Set_Batch_Mode (bool batch_mode) { m_IsBatchMode = batch_mode; } - - ////////////////////////////////////////////////////////////////////// - // Debugging - ////////////////////////////////////////////////////////////////////// - bool Is_Sound_In_Scene (AudibleSoundClass *sound_obj, bool all = true); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - virtual void On_Frame_Update (unsigned int milliseconds = 0); - virtual void Initialize (void); - - virtual bool Is_Logical_Sound_In_Scene (LogicalSoundClass *sound_obj, bool single_shot = false); - - // Save/load methods - virtual void Save_Static_Sounds (ChunkSaveClass &csave); - virtual void Load_Static_Sounds (ChunkLoadClass &cload); - - ////////////////////////////////////////////////////////////////////// - // Collection methods - ////////////////////////////////////////////////////////////////////// - class AudibleInfoClass : public MultiListObjectClass, public AutoPoolClass - { - public: - AudibleInfoClass (void) - : sound_obj (NULL), - distance2 (0) { } - - AudibleInfoClass (AudibleSoundClass *obj, float dist2) - : sound_obj (obj), - distance2 (dist2) { } - - AudibleSoundClass * sound_obj; - float distance2; - }; - - typedef MultiListClass COLLECTED_SOUNDS; - - virtual void Collect_Audible_Sounds (Listener3DClass *listener, COLLECTED_SOUNDS &list); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - Listener3DClass * m_Listener; - Listener3DClass * m_2ndListener; - AUDIBLE_SOUND_LIST m_LastSoundsAudible; - SOUND_LIST m_DynamicSounds; - SOUND_LIST m_StaticSounds; - - LOGICAL_SOUND_LIST m_LogicalSounds; - LOGICAL_SOUND_LIST m_SingleShotLogicalSounds; - LOGICAL_LISTENER_LIST m_LogicalListeners; - - DynamicSoundCullClass m_ListenerCullingSystem; - DynamicSoundCullClass m_LogicalCullingSystem; - DynamicSoundCullClass m_DynamicCullingSystem; - StaticSoundCullClass m_StaticCullingSystem; - - Vector3 m_MinExtents; - Vector3 m_MaxExtents; - - bool m_IsBatchMode; -}; - - -#endif //__SOUNDSCENE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp deleted file mode 100644 index 836ac1fd0f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.cpp +++ /dev/null @@ -1,503 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundSceneObj.cpp $* - * * - * $Modtime:: 8/24/01 5:10p $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "SoundSceneObj.h" -#include "camera.h" -#include "rendobj.h" -#include "persistfactory.h" -#include "SoundChunkIDs.h" -#include "Utils.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Save/Load constants -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_VARIABLES = 0x03270459, - CHUNKID_BASE_CLASS -}; - -enum -{ - VARID_ATTACHED_OBJ = 0x01, - VARID_ATTACHED_BONE, - VARID_USER_DATA, - VARID_USER_OBJ, - VARID_ID -}; - - -////////////////////////////////////////////////////////////////////////////////// -// Static member initialization -////////////////////////////////////////////////////////////////////////////////// -DynamicVectorClass SoundSceneObjClass::m_GlobalSoundList; -uint32 SoundSceneObjClass::m_NextAvailableID = SOUND_OBJ_START_ID; -CriticalSectionClass SoundSceneObjClass::m_IDListMutex; - - -////////////////////////////////////////////////////////////////////////////////// -// Mutex managment -////////////////////////////////////////////////////////////////////////////////// -/* -class HandleMgrClass -{ -public: - HandleMgrClass (void) { SoundSceneObjClass::m_IDListMutex = ::CreateMutex (NULL, FALSE, NULL); } - ~HandleMgrClass (void) { ::CloseHandle (SoundSceneObjClass::m_IDListMutex); } - -}; - -HandleMgrClass _GlobalMutexHandleMgr; -*/ - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// SoundSceneObjClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundSceneObjClass::SoundSceneObjClass (void) - : m_Scene (NULL), - m_PhysWrapper (NULL), - m_pCallback (NULL), - m_AttachedObject (NULL), - m_UserData (0), - m_UserObj (NULL), - m_ID (SOUND_OBJ_DEFAULT_ID), - m_RegisteredEvents (AudioCallbackClass::EVENT_NONE) -{ - m_ID = m_NextAvailableID ++; - - Register_Sound_Object (this); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// SoundSceneObjClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundSceneObjClass::SoundSceneObjClass (const SoundSceneObjClass &src) - : m_Scene (NULL), - m_PhysWrapper (NULL), - m_pCallback (NULL), - m_AttachedObject (NULL), - m_UserData (0), - m_UserObj (NULL), - m_ID (SOUND_OBJ_DEFAULT_ID), - m_RegisteredEvents (AudioCallbackClass::EVENT_NONE) -{ - m_ID = m_NextAvailableID ++; - - (*this) = src; - Register_Sound_Object (this); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~SoundSceneObjClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundSceneObjClass::~SoundSceneObjClass (void) -{ - REF_PTR_RELEASE (m_UserObj); - REF_PTR_RELEASE (m_AttachedObject); - Unregister_Sound_Object (this); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// operator= -// -//////////////////////////////////////////////////////////////////////////////////////////////// -const SoundSceneObjClass & -SoundSceneObjClass::operator= (const SoundSceneObjClass &src) -{ - m_Scene = src.m_Scene; - m_pCallback = src.m_pCallback; - m_RegisteredEvents = src.m_RegisteredEvents; - - Attach_To_Object (src.m_AttachedObject, src.m_AttachedBone); - - PersistClass::operator= ((const PersistClass &)src); - return (*this); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Attach_To_Object -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneObjClass::Attach_To_Object -( - RenderObjClass * render_obj, - const char * bone_name -) -{ - REF_PTR_SET (m_AttachedObject, render_obj); - - if (m_AttachedObject != NULL && bone_name != NULL) { - m_AttachedBone = m_AttachedObject->Get_Bone_Index (bone_name); - } else { - m_AttachedBone = -1; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Attach_To_Object -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneObjClass::Attach_To_Object -( - RenderObjClass * render_obj, - int bone_index -) -{ - if (m_AttachedObject != render_obj || m_AttachedBone != bone_index) { - - // - // Record the attachment - // - REF_PTR_SET (m_AttachedObject, render_obj); - m_AttachedBone = bone_index; - - // - // Update the transform - // - Apply_Auto_Position (); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////// -// -// Apply_Auto_Position -// -////////////////////////////////////////////////////////////////////////////// -void -SoundSceneObjClass::Apply_Auto_Position (void) -{ - // If the sound is attached to an object, then update its transform - // based on this link. - if (m_AttachedObject != NULL) { - - // Determine which transform to use - Matrix3D transform (1); - if (m_AttachedBone >= 0) { - transform = m_AttachedObject->Get_Bone_Transform (m_AttachedBone); - } else { - transform = m_AttachedObject->Get_Transform (); - - // - // Convert the camera's transform to an object transform - // - if (m_AttachedObject->Class_ID () == RenderObjClass::CLASSID_CAMERA) { - Matrix3D cam_to_world (Vector3 (0, 0, -1), Vector3 (-1, 0, 0), Vector3 (0, 1, 0), Vector3 (0, 0, 0)); -#ifdef ALLOW_TEMPORARIES - transform = transform * cam_to_world; -#else - transform.postMul(cam_to_world); -#endif - } - } - - // Update the sound's transform - Set_Transform (transform); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneObjClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - PersistClass::Save (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_VARIABLES); - WRITE_MICRO_CHUNK (csave, VARID_ATTACHED_OBJ, m_AttachedObject); - WRITE_MICRO_CHUNK (csave, VARID_ATTACHED_BONE, m_AttachedBone); - WRITE_MICRO_CHUNK (csave, VARID_USER_DATA, m_UserData); - WRITE_MICRO_CHUNK (csave, VARID_USER_OBJ, m_UserObj); - WRITE_MICRO_CHUNK (csave, VARID_ID, m_ID); - csave.End_Chunk (); - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneObjClass::Load (ChunkLoadClass &cload) -{ - uint32 id = SOUND_OBJ_DEFAULT_ID; - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_BASE_CLASS: - PersistClass::Load (cload); - break; - - case CHUNKID_VARIABLES: - { - // - // Read all the variables from their micro-chunks - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_ATTACHED_OBJ, m_AttachedObject); - READ_MICRO_CHUNK (cload, VARID_ATTACHED_BONE, m_AttachedBone); - READ_MICRO_CHUNK (cload, VARID_USER_DATA, m_UserData); - READ_MICRO_CHUNK (cload, VARID_USER_OBJ, m_UserObj); - READ_MICRO_CHUNK (cload, VARID_ID, id); - } - - cload.Close_Micro_Chunk (); - } - } - break; - } - - cload.Close_Chunk (); - } - - // - // Set the ID (this will cause the sound object to - // be re-inserted in the master sorted list) - // - if (id != SOUND_OBJ_DEFAULT_ID) { - Set_ID (id); - } - - // - // Max sure the next available ID is the largest ID in existence - // - m_NextAvailableID = max (m_NextAvailableID, m_ID + 1); - - // - // We need to 'swizzle' the attached object pointer. We saved the pointer's - // value, and need to map it (hopefully) to the new value. - // - if (m_AttachedObject != NULL) { - SaveLoadSystemClass::Request_Ref_Counted_Pointer_Remap ((RefCountClass **)&m_AttachedObject); - } - - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneObjClass::On_Frame_Update (unsigned int /*milliseconds*/) -{ - Apply_Auto_Position (); - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_ID -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneObjClass::Set_ID (uint32 id) -{ - // - // Remove the sound object from our sorted list - // - Unregister_Sound_Object (this); - - // - // Change the sound object's ID - // - m_ID = id; - - // - // Reinsert the sound object in our sorted list - // - Register_Sound_Object (this); - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Register_Sound_Object -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneObjClass::Register_Sound_Object (SoundSceneObjClass *sound_obj) -{ - int sound_id = sound_obj->Get_ID (); - CriticalSectionClass::LockClass lock(m_IDListMutex); - - // - // Special case a non-ID - // - if (sound_id == SOUND_OBJ_DEFAULT_ID) { - m_GlobalSoundList.Insert (0, sound_obj); - } else { - - // - // Check to ensure the object isn't already in the list - // - int index = 0; - if (Find_Sound_Object (sound_id, &index) == false) { - - // - // Insert the object into the list - // - m_GlobalSoundList.Insert (index, sound_obj); - } - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Unregister_Sound_Object -// -////////////////////////////////////////////////////////////////////////////////// -void -SoundSceneObjClass::Unregister_Sound_Object (SoundSceneObjClass *sound_obj) -{ - CriticalSectionClass::LockClass lock(m_IDListMutex); - - // - // Try to find the object in the list - // - int index = 0; - if (Find_Sound_Object (sound_obj->Get_ID (), &index)) { - - // - // Remove the object from the list - // - m_GlobalSoundList.Delete (index); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Find_Sound_Object -// -////////////////////////////////////////////////////////////////////////////////// -bool -SoundSceneObjClass::Find_Sound_Object (uint32 id_to_find, int *index) -{ - CriticalSectionClass::LockClass lock(m_IDListMutex); - - bool found = false; - (*index) = 0; - int min_index = 0; - int max_index = m_GlobalSoundList.Count () - 1; - - // - // Keep looping until we've closed the window of possiblity - // - bool keep_going = (max_index >= min_index); - while (keep_going) { - - // - // Calculate what slot we are currently looking at - // - int curr_index = min_index + ((max_index - min_index) / 2); - uint32 curr_id = m_GlobalSoundList[curr_index]->Get_ID (); - - // - // Did we find the right slot? - // - if (id_to_find == curr_id) { - (*index) = curr_index; - keep_going = false; - found = true; - } else { - - // - // Stop if we've narrowed the window to one entry - // - keep_going = (max_index > min_index); - - // - // Move the window to the appropriate side - // of the test index. - // - if (id_to_find < curr_id) { - max_index = curr_index - 1; - (*index) = curr_index; - } else { - min_index = curr_index + 1; - (*index) = curr_index + 1; - } - } - } - - return found; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h deleted file mode 100644 index 03370995a7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/SoundSceneObj.h +++ /dev/null @@ -1,279 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/SoundSceneObj.h $* - * * - * $Modtime:: 8/24/01 3:51p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUND_SCENE_OBJ_H -#define __SOUND_SCENE_OBJ_H - -#include "refcount.h" -#include "WWAudio.h" -#include "bittype.h" -#include "persist.h" -#include "multilist.h" -#include "mutex.h" - -///////////////////////////////////////////////////////////////////////////////// -// Forward declarations -///////////////////////////////////////////////////////////////////////////////// -class SoundCullObjClass; -class SoundSceneClass; -class RenderObjClass; -class Vector3; -class Matrix3D; -class LogicalListenerClass; -class LogicalSoundClass; -class Sound3DClass; -class SoundPseudo3DClass; -class FilteredSoundClass; -class Listener3DClass; -class AudibleSoundClass; - - -///////////////////////////////////////////////////////////////////////////////// -// Constants -///////////////////////////////////////////////////////////////////////////////// -const uint32 SOUND_OBJ_DEFAULT_ID = 0; -const uint32 SOUND_OBJ_START_ID = 1000000000; - - -///////////////////////////////////////////////////////////////////////////////// -// -// SoundSceneObjClass -// -// Abstract base class to defines an interface for any sound -// object that will be inserted in the culling system. -// -///////////////////////////////////////////////////////////////////////////////// -class SoundSceneObjClass : public MultiListObjectClass, public PersistClass, public RefCountClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public friends - ////////////////////////////////////////////////////////////////////// - friend class SoundSceneClass; - friend class WWAudioClass; - friend class HandleMgrClass; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - SoundSceneObjClass (void); - SoundSceneObjClass (const SoundSceneObjClass &src); - virtual ~SoundSceneObjClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////// - const SoundSceneObjClass &operator= (const SoundSceneObjClass &src); - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////// - // Conversion methods - ////////////////////////////////////////////////////////////////////// - virtual Sound3DClass * As_Sound3DClass (void) { return NULL; } - virtual SoundPseudo3DClass * As_SoundPseudo3DClass (void) { return NULL; } - virtual FilteredSoundClass * As_FilteredSoundClass (void) { return NULL; } - virtual Listener3DClass * As_Listener3DClass (void) { return NULL; } - virtual AudibleSoundClass * As_AudibleSoundClass(void) { return NULL; } - - ////////////////////////////////////////////////////////////////////// - // Identification methods - ////////////////////////////////////////////////////////////////////// - virtual uint32 Get_ID (void) const { return m_ID; } - virtual void Set_ID (uint32 id); - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - virtual bool On_Frame_Update (unsigned int milliseconds = 0); - - ////////////////////////////////////////////////////////////////////// - // Event handling - ////////////////////////////////////////////////////////////////////// - virtual void On_Event (AudioCallbackClass::EVENTS event, uint32 param1 = 0, uint32 param2 = 0); - virtual void Register_Callback (AudioCallbackClass::EVENTS events, AudioCallbackClass *callback); - - ////////////////////////////////////////////////////////////////////// - // Position/direction methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_Position (const Vector3 &position) = 0; - virtual Vector3 Get_Position (void) const = 0; - - virtual void Set_Listener_Transform (const Matrix3D &tm) {}; - virtual void Set_Transform (const Matrix3D &transform) = 0; - virtual Matrix3D Get_Transform (void) const = 0; - - ////////////////////////////////////////////////////////////////////// - // Culling methods - ////////////////////////////////////////////////////////////////////// - virtual void Cull_Sound (bool culled = true) = 0; - virtual bool Is_Sound_Culled (void) const = 0; - - ////////////////////////////////////////////////////////////////////// - // User data methods - ////////////////////////////////////////////////////////////////////// - virtual void Set_User_Data (RefCountClass *user_obj = NULL, uint32 user = 0) { REF_PTR_SET (m_UserObj, user_obj); m_UserData = user; } - virtual uint32 Get_User_Data (void) const { return m_UserData; } - virtual RefCountClass *Peek_User_Obj (void) const { return m_UserObj; } - - ////////////////////////////////////////////////////////////////////// - // Attached object methods - ////////////////////////////////////////////////////////////////////// - virtual void Attach_To_Object (RenderObjClass *render_obj, int bone_index = -1); - virtual void Attach_To_Object (RenderObjClass *render_obj, const char *bone_name); - virtual RenderObjClass *Peek_Parent_Object (void) { return m_AttachedObject; } - virtual int Get_Parent_Bone (void) { return m_AttachedBone; } - virtual void Apply_Auto_Position (void); - - ////////////////////////////////////////////////////////////////////// - // Scene integration - ////////////////////////////////////////////////////////////////////// - virtual void Add_To_Scene (bool start_playing = true) = 0; - virtual void Remove_From_Scene (void) = 0; - virtual bool Is_In_Scene (void) const { return m_Scene != NULL; } - - ////////////////////////////////////////////////////////////////////// - // Attenuation settings - ////////////////////////////////////////////////////////////////////// - - // - // This is the distance where the sound can not be heard any longer. (its vol is 0) - // - virtual void Set_DropOff_Radius (float radius = 1) = 0; - virtual float Get_DropOff_Radius (void) const = 0; - - ////////////////////////////////////////////////////////////////////// - // From PersistClass - ////////////////////////////////////////////////////////////////////// - bool Save (ChunkSaveClass &csave); - bool Load (ChunkLoadClass &cload); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Handle information - ////////////////////////////////////////////////////////////////////// - virtual SoundCullObjClass * Peek_Cullable_Wrapper (void) const { return m_PhysWrapper; } - virtual void Set_Cullable_Wrapper (SoundCullObjClass *obj) { m_PhysWrapper = obj; } - - ////////////////////////////////////////////////////////////////////// - // Sound object managment - ////////////////////////////////////////////////////////////////////// - static void Register_Sound_Object (SoundSceneObjClass *sound_obj); - static void Unregister_Sound_Object (SoundSceneObjClass *sound_obj); - static bool Find_Sound_Object (uint32 id_to_find, int *index); - - ////////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////////// - SoundSceneClass * m_Scene; - SoundCullObjClass * m_PhysWrapper; - AudioCallbackClass * m_pCallback; - AudioCallbackClass::EVENTS m_RegisteredEvents; - uint32 m_ID; - - RenderObjClass * m_AttachedObject; - int m_AttachedBone; - uint32 m_UserData; - RefCountClass * m_UserObj; - - static DynamicVectorClass m_GlobalSoundList; - static uint32 m_NextAvailableID; - static CriticalSectionClass m_IDListMutex; -}; - - -////////////////////////////////////////////////////////////////////////////// -// -// On_Event -// -////////////////////////////////////////////////////////////////////////////// -__inline void -SoundSceneObjClass::On_Event -( - AudioCallbackClass::EVENTS event, - uint32 param1, - uint32 param2 -) -{ - if ((m_pCallback != NULL) && (m_RegisteredEvents & event)) { - - switch (event) - { - case AudioCallbackClass::EVENT_SOUND_STARTED: - m_pCallback->On_Sound_Started (this); - break; - - case AudioCallbackClass::EVENT_SOUND_ENDED: - m_pCallback->On_Sound_Ended (this); - break; - - case AudioCallbackClass::EVENT_LOGICAL_HEARD: - m_pCallback->On_Logical_Heard ((LogicalListenerClass *)param1, (LogicalSoundClass *)param2); - break; - } - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////// -// -// Register_Callback -// -////////////////////////////////////////////////////////////////////////////// -__inline void -SoundSceneObjClass::Register_Callback -( - AudioCallbackClass::EVENTS events, - AudioCallbackClass * callback -) -{ - m_RegisteredEvents = events; - m_pCallback = callback; - return ; -} - - - -#endif //__SOUND_SCENE_OBJ_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Threads.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Threads.cpp deleted file mode 100644 index f9962a77bf..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Threads.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Threads.cpp $Modtime:: 7/17/99 3:32p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "Threads.h" -#include "refcount.h" -#include "Utils.h" -#include -#include "wwdebug.h" - - -/////////////////////////////////////////////////////////////////////////////////////////// -// Static member initialization -/////////////////////////////////////////////////////////////////////////////////////////// -WWAudioThreadsClass::DELAYED_RELEASE_INFO * WWAudioThreadsClass::m_ReleaseListHead = NULL; -CriticalSectionClass WWAudioThreadsClass::m_ListMutex; -HANDLE WWAudioThreadsClass::m_hDelayedReleaseThread = (HANDLE)-1; -HANDLE WWAudioThreadsClass::m_hDelayedReleaseEvent = (HANDLE)-1; -CriticalSectionClass WWAudioThreadsClass::m_CriticalSection; -bool WWAudioThreadsClass::m_IsShuttingDown = false; - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// WWAudioThreadsClass -// -/////////////////////////////////////////////////////////////////////////////////////////// -WWAudioThreadsClass::WWAudioThreadsClass (void) -{ - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// ~WWAudioThreadsClass -// -/////////////////////////////////////////////////////////////////////////////////////////// -WWAudioThreadsClass::~WWAudioThreadsClass (void) -{ - return ; -} - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Delayed_Release_Thread -// -/////////////////////////////////////////////////////////////////////////////////////////// -HANDLE -WWAudioThreadsClass::Create_Delayed_Release_Thread (LPVOID param) -{ - // - // If the thread isn't already running, then - // - if (m_hDelayedReleaseThread == (HANDLE)-1) { - m_hDelayedReleaseEvent = ::CreateEvent (NULL, FALSE, FALSE, NULL); - m_hDelayedReleaseThread = (HANDLE)::_beginthread (Delayed_Release_Thread_Proc, 0, param); - } - - return m_hDelayedReleaseThread; -} - - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// End_Delayed_Release_Thread -// -/////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioThreadsClass::End_Delayed_Release_Thread (DWORD timeout) -{ - m_IsShuttingDown = true; - - // - // If the thread is running, then wait for it to finish - // - if (m_hDelayedReleaseThread != (HANDLE)-1) { - ::SetEvent (m_hDelayedReleaseEvent); - ::WaitForSingleObject (m_hDelayedReleaseThread, timeout); - - m_hDelayedReleaseEvent = (HANDLE)-1; - m_hDelayedReleaseThread = (HANDLE)-1; - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_Delayed_Release_Object -// -/////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioThreadsClass::Add_Delayed_Release_Object -( - RefCountClass * object, - DWORD delay -) -{ - if (m_IsShuttingDown) { - REF_PTR_RELEASE (object); - } else { - - // - // Make sure we have a thread running that will handle - // the operation for us. - // - if (m_hDelayedReleaseThread == (HANDLE)-1) { - Create_Delayed_Release_Thread (); - } - - // - // Wait for the release thread to finish using the - // list pointer - // - { - CriticalSectionClass::LockClass lock(m_ListMutex); - - // - // Create a new delay-information structure and - // add it to our list - // - DELAYED_RELEASE_INFO *info = W3DNEW DELAYED_RELEASE_INFO; - info->object = object; - info->time = ::GetTickCount () + delay; - info->next = m_ReleaseListHead; - - m_ReleaseListHead = info; - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// Flush_Delayed_Release_Objects -// -/////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioThreadsClass::Flush_Delayed_Release_Objects (void) -{ - CriticalSectionClass::LockClass lock(m_CriticalSection); - - // - // Loop through all the objects in our delay list, and - // free them now. - // - DELAYED_RELEASE_INFO *info = NULL; - DELAYED_RELEASE_INFO *next = NULL; - for (info = m_ReleaseListHead; info != NULL; info = next) { - next = info->next; - - // - // Free the object - // - REF_PTR_RELEASE (info->object); - SAFE_DELETE (info); - } - - m_ReleaseListHead = NULL; - return ; -} - - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// Delayed_Release_Thread_Proc -// -/////////////////////////////////////////////////////////////////////////////////////////// -void __cdecl -WWAudioThreadsClass::Delayed_Release_Thread_Proc (LPVOID /*param*/) -{ - const DWORD base_timeout = 2000; - DWORD timeout = base_timeout + rand () % 1000; - - // - // Keep looping forever until we are singalled to quit (or an error occurs) - // - while (::WaitForSingleObject (m_hDelayedReleaseEvent, timeout) == WAIT_TIMEOUT) { - - { - CriticalSectionClass::LockClass lock(m_ListMutex); - - // - // Loop through all the objects in our delay list, and - // free any that have expired. - // - DWORD current_time = ::GetTickCount (); - DELAYED_RELEASE_INFO *curr = NULL; - DELAYED_RELEASE_INFO *prev = NULL; - DELAYED_RELEASE_INFO *next = NULL; - for (curr = m_ReleaseListHead; curr != NULL; curr = next) { - next = curr->next; - - // - // If the time has expired, free the object - // - if (current_time >= curr->time) { - - // - // Unlink the object - // - if (prev == NULL) { - m_ReleaseListHead = next; - } else { - prev->next = next; - } - - // - // Free the object - // - REF_PTR_RELEASE (curr->object); - SAFE_DELETE (curr); - - } else { - prev = curr; - } - } - } - - // - // To avoid 'periodic' releases, randomize our timeout - // - timeout = base_timeout + rand () % 1000; - } - - Flush_Delayed_Release_Objects (); - return ; -} - -/* -/////////////////////////////////////////////////////////////////////////////////////////// -// -// Begin_Modify_List -// -/////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioThreadsClass::Begin_Modify_List (void) -{ - bool retval = false; - - // - // Wait for up to one second to modify the list object - // - if (m_ListMutex != NULL) { - retval = (::WaitForSingleObject (m_ListMutex, 1000) == WAIT_OBJECT_0); - WWASSERT (retval); - } - - return retval; -} - - -/////////////////////////////////////////////////////////////////////////////////////////// -// -// End_Modify_List -// -/////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioThreadsClass::End_Modify_List (void) -{ - // - // Release this thread's hold on the mutex object. - // - if (m_ListMutex != NULL) { - ::ReleaseMutex (m_ListMutex); - } - - return ; -} -*/ - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Threads.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Threads.h deleted file mode 100644 index 74ea4e5b12..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Threads.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Threads.h $Modtime:: 7/17/99 3:32p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __WWAUDIO_THREADS_H -#define __WWAUDIO_THREADS_H - -#include "windows.h" -#include "Vector.H" -#include "mutex.h" - -// Forward declarations -class RefCountClass; - - -////////////////////////////////////////////////////////////////////////// -// -// WWAudioThreadsClass -// -// Simple class that provides a common namespace for tying thread -// information together. -// -////////////////////////////////////////////////////////////////////////// -class WWAudioThreadsClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - WWAudioThreadsClass (void); - ~WWAudioThreadsClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - - // - // Delayed release mechanism - // - static HANDLE Create_Delayed_Release_Thread (LPVOID param = NULL); - static void End_Delayed_Release_Thread (DWORD timeout = 20000); - static void Add_Delayed_Release_Object (RefCountClass *object, DWORD delay = 2000); - static void Flush_Delayed_Release_Objects (void); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private methods - ////////////////////////////////////////////////////////////////////// - static void __cdecl Delayed_Release_Thread_Proc (LPVOID param); - - ////////////////////////////////////////////////////////////////////// - // Private data types - ////////////////////////////////////////////////////////////////////// - typedef struct _DELAYED_RELEASE_INFO - { - RefCountClass * object; - DWORD time; - - _DELAYED_RELEASE_INFO *next; - - } DELAYED_RELEASE_INFO; - - //typedef DynamicVectorClass RELEASE_LIST; - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - static HANDLE m_hDelayedReleaseThread; - static HANDLE m_hDelayedReleaseEvent; - //static RELEASE_LIST m_ReleaseList; - static CriticalSectionClass m_CriticalSection; - static DELAYED_RELEASE_INFO * m_ReleaseListHead; - static CriticalSectionClass m_ListMutex; - static bool m_IsShuttingDown; -}; - -#endif //__WWAUDIO_THREADS_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Utils.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Utils.cpp deleted file mode 100644 index de008df64e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Utils.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Utils.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 6/15/00 11:40a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma warning (disable : 4514) - -#include "Utils.h" - - -CRITICAL_SECTION MMSLockClass::_MSSLockCriticalSection; diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Utils.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/Utils.h deleted file mode 100644 index 9be00c72a6..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/Utils.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/Utils.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/24/01 4:37p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef __UTILS_H -#define __UTILS_H - -#pragma warning (push, 3) -#include "mss.h" -#pragma warning (pop) - -///////////////////////////////////////////////////////////////////////////// -// -// Macros -// -#define SAFE_DELETE(pobject) \ - if (pobject) { \ - delete pobject; \ - pobject = NULL; \ - } \ - -#define SAFE_DELETE_ARRAY(pobject) \ - if (pobject) { \ - delete [] pobject; \ - pobject = NULL; \ - } \ - -#define SAFE_FREE(pobject) \ - if (pobject) { \ - ::free (pobject); \ - pobject = NULL; \ - } \ - - -///////////////////////////////////////////////////////////////////////////// -// -// MMSLockClass -// -///////////////////////////////////////////////////////////////////////////// -class MMSLockClass -{ - public: - MMSLockClass (void) { ::AIL_lock (); } - ~MMSLockClass (void) { ::AIL_unlock (); } - - - static CRITICAL_SECTION _MSSLockCriticalSection; -}; - - -//////////////////////////////////////////////////////////////////////////// -// -// Get_Filename_From_Path -// -__inline LPCTSTR -Get_Filename_From_Path (LPCTSTR path) -{ - // Find the last occurance of the directory deliminator - LPCTSTR filename = ::strrchr (path, '\\'); - if (filename != NULL) { - // Increment past the directory deliminator - filename ++; - } else { - filename = path; - } - - // Return the filename part of the path - return filename; -} - - -#endif //__UTILS_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp deleted file mode 100644 index 4f1b9f7017..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.cpp +++ /dev/null @@ -1,2862 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio * - * * - * $Archive:: /Commando/Code/WWAudio/WWAudio.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/14/01 2:27p $* - * * - * $Revision:: 52 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "always.h" -#include -#include "WWAudio.h" -#include "wwdebug.h" -#include "Utils.h" -#include "realcrc.h" -#include "SoundBuffer.h" -#include "AudibleSound.h" -#include "Sound3D.h" -#include "RAWFILE.H" -#include "ww3d.h" -#include "SoundScene.h" -#include "SoundPseudo3D.h" -#include "ffactory.h" -#include "registry.h" -#include "Threads.h" -#include "LogicalSound.h" -#include "LogicalListener.h" -#include "definitionclassids.h" -#include "wwmemlog.h" -#include "wwprofile.h" - - -#ifdef G_CODE_BASE -#include "../WWLib/argv.h" -#endif - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// Static member initialization -//////////////////////////////////////////////////////////////////////////////////////////////// -WWAudioClass *WWAudioClass::_theInstance = NULL; -HANDLE WWAudioClass::_TimerSyncEvent = NULL; - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// Registry value names -//////////////////////////////////////////////////////////////////////////////////////////////// -const char *VALUE_NAME_IS_STEREO = "stereo"; -const char *VALUE_NAME_BITS = "bits"; -const char *VALUE_NAME_HERTZ = "hertz"; -const char *VALUE_NAME_DEVICE_NAME = "device name"; -const char *VALUE_NAME_MUSIC_ENABLED = "music enabled"; -const char *VALUE_NAME_SOUND_ENABLED = "sound enabled"; -const char *VALUE_NAME_MUSIC_VOL = "music volume"; -const char *VALUE_NAME_SOUND_VOL = "sound volume"; - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// Local inlines -//////////////////////////////////////////////////////////////////////////////////////////////// -__inline bool -WWAudioClass::Is_OK_To_Give_Handle (const AudibleSoundClass &sound_obj) -{ - bool is_ok = false; - AudibleSoundClass::SOUND_TYPE type = sound_obj.Get_Type (); - if (((type == AudibleSoundClass::TYPE_SOUND_EFFECT) && m_AreSoundEffectsEnabled) || - ((type == AudibleSoundClass::TYPE_MUSIC) && m_IsMusicEnabled)) { - is_ok = true; - } - return is_ok; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// WWAudioClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -WWAudioClass::WWAudioClass (void) - : m_Driver2D (NULL), - m_Driver3D (NULL), - m_PlaybackRate (44100), - m_PlaybackBits (16), - m_PlaybackStereo (true), - m_ReverbFilter (INVALID_MILES_HANDLE), - m_UpdateTimer (-1), - m_Driver3DPseudo (NULL), - m_MusicVolume (DEF_MUSIC_VOL), - m_SoundVolume (DEF_SFX_VOL), - m_MaxCacheSize (DEF_CACHE_SIZE * 1024), - m_CurrentCacheSize (0), - m_Max2DSamples (DEF_2D_SAMPLE_COUNT), - m_Max3DSamples (DEF_3D_SAMPLE_COUNT), - m_Max2DBufferSize (DEF_MAX_2D_BUFFER_SIZE), - m_Max3DBufferSize (DEF_MAX_3D_BUFFER_SIZE), - m_SoundScene (NULL), - m_IsMusicEnabled (true), - m_AreSoundEffectsEnabled (true), - m_FileFactory (NULL), - m_EffectsLevel (0), - m_ReverbRoomType (ENVIRONMENT_GENERIC) -{ - ::InitializeCriticalSection (&MMSLockClass::_MSSLockCriticalSection); - - // - // Start Miles Sound System - // - AIL_startup (); - _theInstance = this; - _TimerSyncEvent = ::CreateEvent (NULL, TRUE, FALSE, "WWAUDIO_TIMER_SYNC"); - - // - // Set some default values - // - Set_Sound_Effects_Volume (); - Set_Music_Volume (); - - // Create a new sound scene to manage our 3D sounds... - m_SoundScene = W3DNEW SoundSceneClass; - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// ~WWAudioClass -// -//////////////////////////////////////////////////////////////////////////////////////////////// -WWAudioClass::~WWAudioClass (void) -{ - // - // Make sure the delayed-release thread is terminated - // before we exit (otherwise the process will crash). - // - WWAudioThreadsClass::End_Delayed_Release_Thread (); - - Shutdown (); - _theInstance = NULL; - ::CloseHandle(_TimerSyncEvent); - _TimerSyncEvent = NULL; - - ::DeleteCriticalSection (&MMSLockClass::_MSSLockCriticalSection); - - // - // Free the list of logical "types". - // - Reset_Logical_Types (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Flush_Cache -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Flush_Cache (void) -{ - // Loop through all the hash indicies - for (int hash_index = 0; hash_index < MAX_CACHE_HASH; hash_index ++) { - - // Loop through all the buffers at this hash index and free them all - for (int index = 0; index < m_CachedBuffers[hash_index].Count (); index ++) { - CACHE_ENTRY_STRUCT &info = m_CachedBuffers[hash_index][index]; - - // Free the buffer data - SAFE_FREE (info.string_id); - REF_PTR_RELEASE (info.buffer); - } - - // Remove all the entries for this hash index - m_CachedBuffers[hash_index].Delete_All (); - } - - m_CurrentCacheSize = 0; - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Open_2D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -WWAudioClass::DRIVER_TYPE_2D -WWAudioClass::Open_2D_Device (LPWAVEFORMAT format) -{ - MMSLockClass lock; - - // - // Store the playback settings for future reference - // - m_PlaybackRate = format->nSamplesPerSec; - m_PlaybackBits = (format->nAvgBytesPerSec << 3) / (format->nChannels * format->nSamplesPerSec); - m_PlaybackStereo = bool(format->nChannels > 1); - - // - // Assume we will open the DirectSound driver - // - DRIVER_TYPE_2D type = DRIVER2D_DSOUND; - - // First close the current 2D device and take - // all the sound handles away from the sound objects. - Close_2D_Device (); - - AIL_set_preference (AIL_LOCK_PROTECTION, NO); - - // Try to use DirectSound if possible - S32 success = ::AIL_set_preference (DIG_USE_WAVEOUT, FALSE); - WWASSERT (success == AIL_NO_ERROR); - - // Open the driver - success = ::AIL_waveOutOpen (&m_Driver2D, NULL, 0, format); - - // Do we need to switch from direct sound to waveout? - if ((success == AIL_NO_ERROR) && - (m_Driver2D != NULL) && - (m_Driver2D->emulated_ds == TRUE)) { - ::AIL_waveOutClose (m_Driver2D); - success = 2; - WWDEBUG_SAY (("WWAudio: Detected 2D DirectSound emulation, switching to WaveOut.\r\n")); - } - - // If we couldn't open the direct sound device, then use the - // default wave out device - if (success != AIL_NO_ERROR) { - - // Try to use the default wave out driver - success = ::AIL_set_preference (DIG_USE_WAVEOUT, TRUE); - WWASSERT (success == AIL_NO_ERROR); - - // Open the driver - success = ::AIL_waveOutOpen (&m_Driver2D, NULL, 0, format); - WWASSERT (success == AIL_NO_ERROR); - type = (success == AIL_NO_ERROR) ? DRIVER2D_WAVEOUT : DRIVER2D_ERROR; - } - - // Allocate all the available handles if we were successful - if (success == AIL_NO_ERROR) { - Allocate_2D_Handles (); - ReAssign_2D_Handles (); - } else { - Close_2D_Device (); - WWDEBUG_SAY (("WWAudio: Error initializing 2D device.\r\n")); - } - - // Return the opened device type - return type; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Open_2D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -WWAudioClass::DRIVER_TYPE_2D -WWAudioClass::Open_2D_Device -( - bool stereo, - int bits, - int hertz -) -{ - // Build a wave format structure from the params - PCMWAVEFORMAT wave_format = { 0 }; - wave_format.wf.wFormatTag = WAVE_FORMAT_PCM; - wave_format.wf.nChannels = stereo ? 2 : 1; - wave_format.wf.nSamplesPerSec = hertz; - wave_format.wf.nAvgBytesPerSec = (wave_format.wf.nChannels * wave_format.wf.nSamplesPerSec * bits) >> 3; - wave_format.wf.nBlockAlign = (wave_format.wf.nChannels * bits) >> 3; - wave_format.wBitsPerSample = bits; - - DRIVER_TYPE_2D type = DRIVER2D_ERROR; - while (((type = Open_2D_Device ((LPWAVEFORMAT)&wave_format)) == DRIVER2D_ERROR) && - (wave_format.wf.nSamplesPerSec >= 11025)) { - - // - // Cut the playback rate in half and try again - // - wave_format.wf.nSamplesPerSec = wave_format.wf.nSamplesPerSec >> 1; - wave_format.wf.nAvgBytesPerSec = (wave_format.wf.nChannels * wave_format.wf.nSamplesPerSec * bits) >> 3; - wave_format.wf.nBlockAlign = (wave_format.wf.nChannels * bits) >> 3; - } - - // Pass this structure onto the function that actually opens the device - return type; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Close_2D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Close_2D_Device (void) -{ - MMSLockClass lock; - - bool retval = false; - - // - // Free any 2D sound handles - // - Remove_2D_Sound_Handles (); - Release_2D_Handles (); - - // - // Do we have an open driver handle to close? - // - if (m_Driver2D != NULL) { - - // - // Close the driver - // - ::AIL_waveOutClose (m_Driver2D); - m_Driver2D = NULL; - retval = true; - } - - // - // Return the true/false result code - // - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Sound_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -WWAudioClass::Get_Sound_Buffer (const char *filename, bool is_3d) -{ - // - // Try to find the buffer in our cache, otherwise create a new buffer. - // - SoundBufferClass *buffer = Find_Cached_Buffer (filename); - if (buffer == NULL) { - FileClass *file = Get_File (filename); - if (file != NULL && file->Is_Available ()) { - buffer = Create_Sound_Buffer (*file, filename, is_3d); - } else { - static int count = 0; - if ( ++count < 10 ) { - WWDEBUG_SAY(( "Sound \"%s\" not found\r\n", filename )); - } - } - Return_File (file); - } - - return buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Sound_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -WWAudioClass::Get_Sound_Buffer (FileClass &file, const char *string_id, bool is_3d) -{ - WWMEMLOG(MEM_SOUND); - - // - // Try to find the buffer in our cache, otherwise create a new buffer. - // - SoundBufferClass *buffer = Find_Cached_Buffer (string_id); - if (buffer == NULL) { - buffer = Create_Sound_Buffer (file, string_id, is_3d); - } - - return buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Find_Cached_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -WWAudioClass::Find_Cached_Buffer (const char *string_id) -{ - SoundBufferClass *sound_buffer = NULL; - - // Param OK? - WWASSERT (string_id != NULL); - if (string_id != NULL) { - - // - // Determine which index in our hash table to use - // - int hash_index = ::CRC_Stringi (string_id) & CACHE_HASH_MASK; - - // - // Loop through all the buffers at this hash index and try to find - // one that matches the requested name - // - for (int index = 0; index < m_CachedBuffers[hash_index].Count (); index ++) { - - // - // Is this the sound buffer we were looking for? - // - CACHE_ENTRY_STRUCT &info = m_CachedBuffers[hash_index][index]; - if (::lstrcmpi (info.string_id, string_id) == 0) { - sound_buffer = info.buffer; - sound_buffer->Add_Ref (); - break; - } - } - } - - // - // Return a pointer to the cached sound buffer - // - return sound_buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_Cache_Space -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Free_Cache_Space (int bytes) -{ - int bytes_freed = 0; - - // Loop through all the hash indicies - for (int hash_index = 0; - (hash_index < MAX_CACHE_HASH) && (bytes_freed < bytes); - hash_index ++) { - - // Loop through all the buffers at this hash index - for (int index = 0; - (index < m_CachedBuffers[hash_index].Count ()) && (bytes_freed < bytes); - index ++) { - - // Can we free this cached buffer? - CACHE_ENTRY_STRUCT &info = m_CachedBuffers[hash_index][index]; - if ((info.buffer != NULL) && (info.buffer->Num_Refs () == 1)) { - - // Add the size of this buffer to our count of bytes freed - bytes_freed += info.buffer->Get_Raw_Length (); - - // Free the buffer data - SAFE_FREE (info.string_id); - REF_PTR_RELEASE (info.buffer); - - // Remove this entry from the hash table - m_CachedBuffers[hash_index].Delete (index); - index --; - } - } - } - - // Make sure to recompute out current cache size - m_CurrentCacheSize -= bytes_freed; - WWASSERT (m_CurrentCacheSize >= 0); - - // Return true if we freed enough bytes in the cache - return (bytes_freed >= bytes); -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Cache_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Cache_Buffer -( - SoundBufferClass *buffer, - const char *string_id -) -{ - // Assume failure - bool retval = false; - - // Params OK? - WWASSERT (buffer != NULL); - WWASSERT (string_id != NULL); - if ((buffer != NULL) && - (string_id != NULL) && - (buffer->Get_Raw_Length () < (U32)(m_MaxCacheSize / 2))) { - - // Attempt to free space in the cache (if needed) - int space_needed = (m_CurrentCacheSize + buffer->Get_Raw_Length ()) - (int)m_MaxCacheSize; - if (space_needed > 0) { - Free_Cache_Space (space_needed); - } - - // Do we have enough space in the cache for this buffer? - space_needed = (m_CurrentCacheSize + buffer->Get_Raw_Length ()) - (int)m_MaxCacheSize; - if (space_needed <= 0) { - - // Determine which index in our hash table to use - int hash_index = ::CRC_Stringi (string_id) & CACHE_HASH_MASK; - - // - // Add this buffer to the hash table at the given index. - // Note: The assignment operator caused by the Add call - // will add a reference to the sound buffer. - // - CACHE_ENTRY_STRUCT info; - info.string_id = (char *)string_id; - info.buffer = buffer; - m_CachedBuffers[hash_index].Add (info); - - // Update our current cache size - m_CurrentCacheSize += buffer->Get_Raw_Length (); - retval = true; - } - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -WWAudioClass::Create_Sound_Buffer -( - FileClass & file, - const char *string_id, - bool is_3d -) -{ - SoundBufferClass *sound_buffer = NULL; - - // - // Determine how large this buffer can be - // - int max_size = is_3d ? m_Max3DBufferSize : m_Max2DBufferSize; - - // - // Create a streaming sound buffer object if the - // file is too large to preload. - // - if (file.Size () > max_size) { - sound_buffer = W3DNEW StreamSoundBufferClass; - } else { - sound_buffer = W3DNEW SoundBufferClass; - } - SET_REF_OWNER(sound_buffer); - - // - // Create a new sound buffer from the provided file - // - bool success = sound_buffer->Load_From_File (file); - sound_buffer->Set_Filename (string_id); - WWASSERT (success); - - // If we were successful in creating the sound buffer, then - // try to cache it as well, otherwise free the buffer and return NULL. - if (success && (string_id != NULL)) { - Cache_Buffer (sound_buffer, string_id); - } else if (success == false) { - REF_PTR_RELEASE (sound_buffer); - } - - // Return a pointer to the new sound buffer - return sound_buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -SoundBufferClass * -WWAudioClass::Create_Sound_Buffer -( - unsigned char * file_image, - unsigned long bytes, - const char * string_id, - bool is_3d -) -{ - // Create a new sound buffer from the provided file - SoundBufferClass *sound_buffer = W3DNEW SoundBufferClass; - SET_REF_OWNER(sound_buffer); - - // - // Initialize the sound from this piece of memory - // - bool success = sound_buffer->Load_From_Memory (file_image, bytes); - sound_buffer->Set_Filename (string_id); - WWASSERT (success); - - // If we were successful in creating the sound buffer, then - // try to cache it as well, otherwise free the buffer and return NULL. - if (success && (string_id != NULL)) { - Cache_Buffer (sound_buffer, string_id); - } else if (success == false) { - REF_PTR_RELEASE (sound_buffer); - } - - // Return a pointer to the new sound buffer - return sound_buffer; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound_Effect -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Sound_Effect (FileClass &file, const char *string_id) -{ - // Create a new sound object - AudibleSoundClass *sound_obj = W3DNEW AudibleSoundClass; - if (Is_Disabled () == false) { - - // Try to find the buffer in our cache, otherwise create a new buffer. - SoundBufferClass *buffer = Get_Sound_Buffer (file, string_id, false); - - // Pass the actual sound data onto the sound object - sound_obj->Set_Buffer (buffer); - REF_PTR_RELEASE (buffer); - } - - // Return a pointer to the sound effect - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound_Effect -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Sound_Effect (const char *filename) -{ - // Assume failure - AudibleSoundClass *sound_obj = NULL; - if (Is_Disabled () == false) { - - // Param OK? - WWASSERT (filename != NULL); - if (filename != NULL) { - - // Create a file object and pass it onto the appropriate function - FileClass *file = Get_File (filename); - if (file && file->Is_Available()) { - sound_obj = Create_Sound_Effect (*file, filename); - } else { - WWDEBUG_SAY(( "Sound %s not found\r\n", filename )); - } - Return_File (file); - - } - } - - // Return a pointer to the sound effect - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound_Effect -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Sound_Effect -( - const char * string_id, - unsigned char *raw_wave_data, - unsigned long bytes -) -{ - // Create a new sound object - AudibleSoundClass *sound_obj = W3DNEW AudibleSoundClass; - if (Is_Disabled () == false) { - - // Try to find the buffer in our cache, otherwise create a new buffer. - SoundBufferClass *buffer = Find_Cached_Buffer (string_id); - if (buffer == NULL) { - buffer = Create_Sound_Buffer (raw_wave_data, bytes, string_id, false); - } - - // Pass the actual sound data onto the sound object - sound_obj->Set_Buffer (buffer); - REF_PTR_RELEASE (buffer); - } - - // Return a pointer to the sound effect - return sound_obj; -} - - -///////////////////////////////////////////////////////////////////////////////// -// -// Create_3D_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Sound3DClass * -WWAudioClass::Create_3D_Sound (FileClass &file, const char *string_id, int classid_hint) -{ - Sound3DClass *sound_obj = NULL; - if (Is_Disabled () == false) { - - // Try to find the buffer in our cache, otherwise create a new buffer. - SoundBufferClass *buffer = Get_Sound_Buffer (file, string_id, true); - - // - // What type of sound object should we create? A true 3D sound or one of - // our pseudo-3d sounds? (volume and panning only) - // - if ( classid_hint == CLASSID_PSEUDO3D || - Validate_3D_Sound_Buffer (buffer) == false) - { - sound_obj = W3DNEW SoundPseudo3DClass; - sound_obj->Set_Buffer (buffer); - } else if (buffer != NULL) { - sound_obj = W3DNEW Sound3DClass; - sound_obj->Set_Buffer (buffer); - } - - REF_PTR_RELEASE (buffer); - } - - // Return a pointer to the sound effect - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_3D_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Sound3DClass * -WWAudioClass::Create_3D_Sound -( - const char * filename, - int classid_hint -) -{ - WWMEMLOG(MEM_SOUND); - - // Assume failure - Sound3DClass *sound_obj = NULL; - if (Is_Disabled () == false) { - - // Param OK? - WWASSERT (filename != NULL); - if (filename != NULL) { - - // Try to find the buffer in our cache, otherwise create a new buffer. - SoundBufferClass *buffer = Get_Sound_Buffer (filename, true); - - // - // What type of sound object should we create? A true 3D sound or one of - // our pseudo-3d sounds? (volume and panning only) - // - if ( classid_hint == CLASSID_PSEUDO3D || - Validate_3D_Sound_Buffer (buffer) == false) - { - sound_obj = W3DNEW SoundPseudo3DClass; - sound_obj->Set_Buffer (buffer); - } else if (buffer != NULL) { - sound_obj = W3DNEW Sound3DClass; - sound_obj->Set_Buffer (buffer); - } else { - static int count = 0; - if ( ++count < 10 ) { - WWDEBUG_SAY(( "Sound File not Found \"%s\"\r\n", filename )); - } - } - - REF_PTR_RELEASE (buffer); - } - } - - // Return a pointer to the sound effect - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_3D_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -Sound3DClass * -WWAudioClass::Create_3D_Sound -( - const char * string_id, - unsigned char * raw_wave_data, - unsigned long bytes, - int classid_hint -) -{ - Sound3DClass *sound_obj = NULL; - if (Is_Disabled () == false) { - - // - // Try to find the buffer in our cache, otherwise create a new buffer. - // - SoundBufferClass *buffer = Find_Cached_Buffer (string_id); - if (buffer == NULL) { - buffer = Create_Sound_Buffer (raw_wave_data, bytes, string_id, true); - } - - // - // What type of sound object should we create? A true 3D sound or one of - // our pseudo-3d sounds? (volume and panning only) - // - if ( classid_hint == CLASSID_PSEUDO3D || - Validate_3D_Sound_Buffer (buffer) == false) - { - sound_obj = W3DNEW SoundPseudo3DClass; - sound_obj->Set_Buffer (buffer); - } else if (buffer != NULL) { - sound_obj = W3DNEW Sound3DClass; - sound_obj->Set_Buffer (buffer); - } - - REF_PTR_RELEASE (buffer); - } - - // Return a pointer to the sound effect - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Sound -( - int definition_id, - RefCountClass *user_obj, - uint32 user_data, - int classid_hint -) -{ - AudibleSoundClass *sound = NULL; - - // - // Find the definition - // - DefinitionClass *definition = DefinitionMgrClass::Find_Definition (definition_id); - if (definition != NULL ) { - - // - // Make sure this is really a sound definition - // - WWASSERT (definition->Get_Class_ID () == CLASSID_SOUND); - if (definition->Get_Class_ID () == CLASSID_SOUND) { - AudibleSoundDefinitionClass *sound_def = reinterpret_cast (definition); - - // - // Create an instance of the sound - // - sound = sound_def->Create_Sound (classid_hint); - if (sound != NULL) { - sound->Set_User_Data (user_obj, user_data); - } - } - } - - return sound; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Sound -( - const char * def_name, - RefCountClass *user_obj, - uint32 user_data, - int classid_hint -) -{ - AudibleSoundClass *sound = NULL; - - // - // Find the definition - // - DefinitionClass *definition = DefinitionMgrClass::Find_Typed_Definition (def_name, CLASSID_SOUND, true); - if (definition != NULL ) { - - // - // Make sure this is really a sound definition - // - WWASSERT (definition->Get_Class_ID () == CLASSID_SOUND); - if (definition->Get_Class_ID () == CLASSID_SOUND) { - AudibleSoundDefinitionClass *sound_def = reinterpret_cast (definition); - - // - // Create an instance of the sound - // - sound = sound_def->Create_Sound (classid_hint); - if (sound != NULL) { - sound->Set_User_Data (user_obj, user_data); - } - } - } - - return sound; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Continuous_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Continuous_Sound -( - int definition_id, - RefCountClass *user_obj, - uint32 user_data, - int classid_hint -) -{ - // - // Create an instance of the sound and play it - // - AudibleSoundClass *sound = Create_Sound (definition_id, user_obj, user_data, classid_hint); - if (sound != NULL) { - - if (sound->Get_Loop_Count () != INFINITE_LOOPS) { - WWDEBUG_SAY (("Audio Error: Creating a continuous sound with a finite loop count!\r\n")); - } - } - - return sound; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Instant_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -int -WWAudioClass::Create_Instant_Sound -( - int definition_id, - const Matrix3D & tm, - RefCountClass * user_obj, - uint32 user_data, - int classid_hint -) -{ - int sound_id = 0; - - // - // Create an instance of the sound and play it - // - AudibleSoundClass *sound = Create_Sound (definition_id, user_obj, user_data, classid_hint); - if (sound != NULL) { - - if (sound->Get_Loop_Count () == INFINITE_LOOPS) { - WWDEBUG_SAY (("Audio Error: Creating an instant sound %s with an infinite loop count!\r\n",sound->Get_Definition()->Get_Name())); - } - - sound_id = sound->Get_ID (); - sound->Set_Transform (tm); - sound->Add_To_Scene (); - sound->Release_Ref (); - } - - return sound_id; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Continuous_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Create_Continuous_Sound -( - const char * def_name, - RefCountClass *user_obj, - uint32 user_data, - int classid_hint -) -{ - // - // Create an instance of the sound and play it - // - AudibleSoundClass *sound = Create_Sound (def_name, user_obj, user_data, classid_hint); - if (sound != NULL) { - - if (sound->Get_Loop_Count () != INFINITE_LOOPS) { - WWDEBUG_SAY (("Audio Error: Creating a continuous sound with a finite loop count!\r\n")); - } - - } - - return sound; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Instant_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////////// -int -WWAudioClass::Create_Instant_Sound -( - const char * def_name, - const Matrix3D & tm, - RefCountClass * user_obj, - uint32 user_data, - int classid_hint -) -{ - int sound_id = 0; - - // - // Create an instance of the sound and play it - // - AudibleSoundClass *sound = Create_Sound (def_name, user_obj, user_data, classid_hint); - if (sound != NULL) { - - if (sound->Get_Loop_Count () == INFINITE_LOOPS) { - WWDEBUG_SAY (("Audio Error: Creating an instant sound %s with an infinite loop count!\r\n",sound->Get_Definition()->Get_Name())); - } - - sound_id = sound->Get_ID (); - sound->Set_Transform (tm); - sound->Add_To_Scene (); - sound->Release_Ref (); - } - - return sound_id; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Flush_Playlist -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Flush_Playlist (void) -{ - // First make sure to free any completed sounds - Free_Completed_Sounds (); - - // Loop through all the entries in the playlist - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - REF_PTR_RELEASE (sound_obj); - } - - // Free the list structure - m_Playlist.Delete_All (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_Completed_Sounds -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Free_Completed_Sounds (void) -{ - if (m_CompletedSounds.Count () > 0) { - - // Loop through all the entries in the completed sounds list - for (int index = 0; index < m_CompletedSounds.Count (); index ++) { - AudibleSoundClass *sound_obj = m_CompletedSounds[index]; - - WWASSERT(sound_obj != NULL); //TSS 05/24/99 - - // Remove this sound from the playlist - bool found = false; - for (int play_index = 0; (play_index < m_Playlist.Count ()) && !found; play_index ++) { - if (m_Playlist[play_index] == sound_obj) { - - // Free our hold on this sound object - m_Playlist.Delete (play_index); - REF_PTR_RELEASE (sound_obj); - found = true; - } - } - } - - // Free the list structure - m_CompletedSounds.Delete_All (); - - // Try to give a play-handle back to a sound that was priority-bumped. - Reprioritize_Playlist (); - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Playlist_Entry -// -//////////////////////////////////////////////////////////////////////////////////////////////// -AudibleSoundClass * -WWAudioClass::Get_Playlist_Entry (int index) const -{ - AudibleSoundClass *sound_obj = NULL; - - // Params OK? - WWASSERT (index >= 0 && index < m_Playlist.Count ()); - if ((index >= 0) && (index < m_Playlist.Count ())) { - m_Playlist[index]->Add_Ref (); - m_Playlist[index]; - } - - // Return a pointer to the sound object - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_To_Playlist -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Add_To_Playlist (AudibleSoundClass *sound) -{ - // Assume failure - bool retval = false; - - WWASSERT (sound != NULL); - if (sound != NULL) { - - // Loop through all the entries in the playlist - bool already_added = false; - for (int index = 0; (index < m_Playlist.Count ()) && (already_added == false); index ++) { - already_added = (sound == m_Playlist[index]); - } - - // Add this sound to our playlist - if (already_added == false) { - sound->Add_Ref (); - m_Playlist.Add (sound); - } - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_From_Playlist -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Remove_From_Playlist (AudibleSoundClass *sound_obj) -{ - // Assume failure - bool retval = false; - - WWASSERT (sound_obj != NULL); - if (sound_obj != NULL) { - - // Loop through all the entries in the playlist - for (int index = 0; (index < m_Playlist.Count ()) && (retval == false); index ++) { - - // Is this the entry we are looking for? - if (sound_obj == m_Playlist[index]) { - - // Add this sound to the 'completed' list - m_CompletedSounds.Add (sound_obj); - retval = true; - } - } - - // - // Notify any callbacks that this sound is ending... - // - if (sound_obj->Get_Loop_Count () != INFINITE_LOOPS) { - for (index = 0; index < m_EOSCallbackList.Count (); index ++) { - uint32 user_data = NULL; - LPFNEOSCALLBACK callback = m_EOSCallbackList.Get_Callback (index, &user_data); - if (callback != NULL) { - (*callback) (sound_obj, user_data); - } - } - } - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Is_Sound_In_Playlist -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Is_Sound_In_Playlist (AudibleSoundClass *sound_obj) -{ - // Assume failure - bool retval = false; - - // Loop through all the entries in the playlist - for (int index = 0; (index < m_Playlist.Count ()) && (retval == false); index ++) { - if (sound_obj == m_Playlist[index]) { - retval = true; - } - } - - // Return the true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Reprioritize_Playlist -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Reprioritize_Playlist (void) -{ - AudibleSoundClass *sound_to_get_handle = NULL; - float hightest_priority = 0; - - // Loop through all the entries in the playlist - for (int index = 0; index < m_Playlist.Count (); index ++) { - - // Is this the highest priority without a miles handle? - AudibleSoundClass *sound_obj = m_Playlist[index]; - if ((sound_obj->Get_Miles_Handle () == NULL) && - (sound_obj->Is_Sound_Culled () == false) && - (sound_obj->Get_Priority () > hightest_priority)) - { - // This is now the highest priority sound effect without - // a play-handle. - sound_to_get_handle = sound_obj; - hightest_priority = sound_obj->Get_Priority (); - } - } - - // Get a new handle for this sound if necessary - if (sound_to_get_handle != NULL) { - sound_to_get_handle->Allocate_Miles_Handle (); - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// On_Frame_Update -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::On_Frame_Update (unsigned int milliseconds) -{ - // - // Free any sounds we completed last frame - // - Free_Completed_Sounds (); - - // - // Calculate the time in ms since the last frame - // - unsigned int time_delta = milliseconds; - if (time_delta == 0) { - time_delta = WW3D::Get_Frame_Time (); - } - - if (m_SoundScene != NULL) { - m_SoundScene->On_Frame_Update (milliseconds); - m_SoundScene->Collect_Logical_Sounds (); - } - - // - // Loop through all the entries in the playlist - // - for (int index = 0; index < m_Playlist.Count (); index ++) { - - // - // Update this sound object - // - AudibleSoundClass *sound_obj = m_Playlist[index]; - sound_obj->On_Frame_Update (time_delta); - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Release_2D_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Release_2D_Handles (void) -{ - MMSLockClass lock; - - // Release our hold on all the samples we've allocated - for (int index = 0; index < m_2DSampleHandles.Count (); index ++) { - HSAMPLE sample = m_2DSampleHandles[index]; - if (sample != NULL) { - ::AIL_release_sample_handle (sample); - } - } - - m_2DSampleHandles.Delete_All (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_2D_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Allocate_2D_Handles (void) -{ - MMSLockClass lock; - - // Start fresh - Release_2D_Handles (); - - if (m_Driver2D != NULL) { - - // Attempt to allocate our share of 2D sample handles - for (int index = 0; index < m_Max2DSamples; index ++) { - HSAMPLE sample = ::AIL_allocate_sample_handle (m_Driver2D); - if (sample != NULL) { - ::AIL_set_sample_user_data (sample, INFO_OBJECT_PTR, NULL); - m_2DSampleHandles.Add (sample); - } - } - - // Record our actual number of available 2D sample handles - m_Max2DSamples = m_2DSampleHandles.Count (); - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_2D_Sample -// -//////////////////////////////////////////////////////////////////////////////////////////// -HSAMPLE -WWAudioClass::Get_2D_Sample (const AudibleSoundClass &sound_obj) -{ - if (Is_OK_To_Give_Handle (sound_obj) == false) { - return (HSAMPLE)INVALID_MILES_HANDLE; - } - - MMSLockClass lock; - - float lowest_priority = sound_obj.Get_Priority (); - float lowest_runtime_priority = sound_obj.Get_Runtime_Priority (); - AudibleSoundClass *lowest_pri_sound = NULL; - HSAMPLE lowest_pri_sample = NULL; - HSAMPLE free_sample = (HSAMPLE)INVALID_MILES_HANDLE; - - // Loop through all the available sample handles and try to find - // one that isn't being used to play a sound. - bool found = false; - for (int index = 0; (index < m_2DSampleHandles.Count ()) && !found; index ++) { - - HSAMPLE sample = m_2DSampleHandles[index]; - if (sample != NULL) { - - // Get a pointer to the object that is currently using this sample - AudibleSoundClass *sound_obj = (AudibleSoundClass *)::AIL_sample_user_data (sample, INFO_OBJECT_PTR); - if (sound_obj == NULL) { - - // Return this sample handle to the caller - free_sample = sample; - found = true; - } else { - - // - // Determine if this sound's priority is lesser then the sound we want to play. - // This is done by comparing both the designer-specified priority and the current - // runtime priority (which is calculated by distance to the listener). - // - float priority = sound_obj->Get_Priority (); - float runtime_priority = sound_obj->Get_Runtime_Priority (); - if ( (priority < lowest_priority) || - (priority == lowest_priority && runtime_priority <= lowest_runtime_priority)) - { - lowest_priority = priority; - lowest_pri_sound = sound_obj; - lowest_pri_sample = sample; - lowest_runtime_priority = runtime_priority; - } - } - } - } - - // Steal the sample handle from the lower priority - // sound and return the handle to the caller. - if ((found == false) && (lowest_pri_sound != NULL)) { - lowest_pri_sound->Free_Miles_Handle (); - free_sample = lowest_pri_sample; - } - - // Return the free sample handle if we found one - return free_sample; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_3D_Sample -// -//////////////////////////////////////////////////////////////////////////////////////////////// -H3DSAMPLE -WWAudioClass::Get_3D_Sample (const Sound3DClass &sound_obj) -{ - if (Is_OK_To_Give_Handle (sound_obj) == false) { - return (H3DSAMPLE)INVALID_MILES_HANDLE; - } - - MMSLockClass lock; - - float lowest_priority = sound_obj.Get_Priority (); - float lowest_runtime_priority = sound_obj.Get_Runtime_Priority (); - AudibleSoundClass *lowest_pri_sound = NULL; - H3DSAMPLE lowest_pri_sample = NULL; - H3DSAMPLE free_sample = (H3DSAMPLE)INVALID_MILES_HANDLE; - - - // Loop through all the available sample handles and try to find - // one that isn't being used to play a sound. - bool found = false; - for (int index = 0; (index < m_3DSampleHandles.Count ()) && !found; index ++) { - - H3DSAMPLE sample = m_3DSampleHandles[index]; - if (sample != NULL) { - - // Get a pointer to the object that is currently using this sample - AudibleSoundClass *sound_obj = (AudibleSoundClass *)::AIL_3D_object_user_data (sample, INFO_OBJECT_PTR); - if (sound_obj == NULL) { - - // Return this sample handle to the caller - free_sample = sample; - found = true; - } else { - - // - // Determine if this sound's priority is lesser then the sound we want to play. - // This is done by comparing both the designer-specified priority and the current - // runtime priority (which is calculated by distance to the listener). - // - float priority = sound_obj->Get_Priority (); - float runtime_priority = sound_obj->Get_Runtime_Priority (); - if ( (priority < lowest_priority) || - (priority == lowest_priority && runtime_priority <= lowest_runtime_priority)) - { - lowest_priority = priority; - lowest_pri_sound = sound_obj; - lowest_pri_sample = sample; - lowest_runtime_priority = runtime_priority; - } - } - } - } - - // Steal the sample handle from the lower priority - // sound and return the handle to the caller. - if ((found == false) && (lowest_pri_sound != NULL)) { - lowest_pri_sound->Free_Miles_Handle (); - free_sample = lowest_pri_sample; - } - - // Return the free sample handle if we found one - return free_sample; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Listener_Handle -// -//////////////////////////////////////////////////////////////////////////////////////////////// -H3DPOBJECT -WWAudioClass::Get_Listener_Handle (void) -{ - MMSLockClass lock; - return ::AIL_3D_open_listener (m_Driver3D); -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Build_3D_Driver_List -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Build_3D_Driver_List (void) -{ - MMSLockClass lock; - - HPROENUM next = HPROENUM_FIRST; - HPROVIDER provider = NULL; - char *name = NULL; - while (::AIL_enumerate_3D_providers (&next, &provider, &name) > 0) { - - // Can we successfully open this provider? - if (::AIL_open_3D_provider (provider) == M3D_NOERR) { - DRIVER_INFO_STRUCT *info = W3DNEW DRIVER_INFO_STRUCT; - info->driver = provider; - info->name = ::strdup (name); - m_Driver3DList.Add (info); - ::AIL_close_3D_provider (provider); - } else { - char *error_info = ::AIL_last_error (); - WWDEBUG_SAY (("WWAudio: Unable to open %s.\r\n", name)); - WWDEBUG_SAY (("WWAudio: Reason %s.\r\n", error_info)); - } - } - - // Attempt to select one of the known drivers (in the following order). - if ((Select_3D_Device (DRIVER3D_A3D) == false) && - (Select_3D_Device (DRIVER3D_EAX) == false) && - (Select_3D_Device (DRIVER3D_D3DSOUND) == false) && - (Select_3D_Device (DRIVER3D_DOLBY) == false)) { - - // Couldn't select a known driver, so just use the first possible. - if (m_Driver3DList.Count () > 0) { - Select_3D_Device ((int)0); - //DRIVER_INFO_STRUCT *info = m_Driver3DList[0]; - //m_Driver3D = info->driver; - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Free_3D_Driver_List -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Free_3D_Driver_List (void) -{ - MMSLockClass lock; - - // - // Remove all the handles - // - Remove_3D_Sound_Handles (); - Release_3D_Handles (); - - // - // Loop through all the driver entries and free them all - // - for (int index = 0; index < m_Driver3DList.Count (); index ++) { - DRIVER_INFO_STRUCT *info = m_Driver3DList[index]; - if (info != NULL) { - - // - // Free the information we have stored with this driver - // - if (info->name != NULL) { - ::free (info->name); - } - delete info; - } - } - - if (m_Driver3D != NULL) { - ::AIL_close_3D_provider (m_Driver3D); - m_Driver3D = NULL; - } - - // - // Clear the list - // - m_Driver3DList.Delete_All (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Select_3D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Select_3D_Device (const char *device_name) -{ - bool retval = false; - - // - // Loop through all the drivers until we've found the one we want - // - for (int index = 0; index < m_Driver3DList.Count (); index ++) { - DRIVER_INFO_STRUCT *info = m_Driver3DList[index]; - if (info != NULL) { - - // - // Is this the device we were looking for? - // - if (::lstrcmpi (info->name, device_name) == 0) { - retval = Select_3D_Device (device_name, info->driver); - break; - } - } - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Select_3D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Select_3D_Device (const char *device_name, HPROVIDER provider) -{ - bool retval = false; - if ((provider != NULL) && (provider != m_Driver3D)) { - - // - // Remove all the handles - // - Remove_3D_Sound_Handles (); - Release_3D_Handles (); - - // - // Close the previous driver if needs be - // - if (m_Driver3D != NULL) { - ::AIL_close_3D_provider (m_Driver3D); - m_Driver3D = NULL; - } - - // - // Select this device and re-allocate all handles - // - if (::AIL_open_3D_provider (provider) == M3D_NOERR) { - m_Driver3D = provider; - m_SoundScene->Initialize (); - Allocate_3D_Handles (); - AIL_set_3D_speaker_type (provider, AIL_3D_2_SPEAKER); - - // - // Adjust the effects level to 1.0 if this is an EAX based driver - // - StringClass lower_name = device_name; - ::strlwr (lower_name.Peek_Buffer ()); - if (::strstr (device_name, "eax") != 0) { - m_EffectsLevel = 1.0F; - } else { - m_EffectsLevel = 0.0F; - } - } - - retval = true; - } - - // Return true if we successfully selected the device - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Select_3D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Select_3D_Device (int index) -{ - bool retval = false; - - // - // Index valid? - // - if ((index >= 0) && (index < m_Driver3DList.Count ())) { - Select_3D_Device (m_Driver3DList[index]->name, m_Driver3DList[index]->driver); - WWDEBUG_SAY (("WWAudio: Selecting 3D sound device: %s.\r\n", m_Driver3DList[index]->name)); - retval = true; - } - - // - // Return true if we successfully selected the device - // - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Select_3D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Select_3D_Device (DRIVER_TYPE_3D type) -{ - // Return true if we successfully selected the device - return Select_3D_Device (Find_3D_Device (type)); -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Find_3D_Device -// -//////////////////////////////////////////////////////////////////////////////////////////////// -int -WWAudioClass::Find_3D_Device (DRIVER_TYPE_3D type) -{ - // Determine which substring to search for in the - // name of the driver. - const char *sub_string = "RSX"; - switch (type) { - case DRIVER3D_D3DSOUND: - sub_string = "DirectSound"; - break; - - case DRIVER3D_EAX: - sub_string = "EAX"; - break; - - case DRIVER3D_A3D: - sub_string = "A3D"; - break; - - case DRIVER3D_PSEUDO: - sub_string = "Fast"; - break; - - case DRIVER3D_DOLBY: - sub_string = "Dolby"; - break; - } - - // Loop through all the driver entries and free them all - int driver_index = -1; - for (int index = 0; (index < m_Driver3DList.Count ()) && (driver_index == -1); index ++) { - DRIVER_INFO_STRUCT *info = m_Driver3DList[index]; - if ((info != NULL) && (info->name != NULL)) { - - // Is this the driver we were looking for? - if (::strstr (info->name, sub_string) != NULL) { - driver_index = index; - } - } - } - - // Return -1 if not found, otherwise the 0 based index - return driver_index; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Allocate_3D_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Allocate_3D_Handles (void) -{ - MMSLockClass lock; - - // Start fresh - Release_3D_Handles (); - - if (m_Driver3D != NULL) { - - // Attempt to allocate our share of 3D sample handles - for (int index = 0; index < m_Max3DSamples; index ++) { - H3DSAMPLE sample = ::AIL_allocate_3D_sample_handle (m_Driver3D); - if (sample != NULL) { - ::AIL_set_3D_object_user_data (sample, INFO_OBJECT_PTR, NULL); - m_3DSampleHandles.Add (sample); - } - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Release_3D_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Release_3D_Handles (void) -{ - MMSLockClass lock; - - // - // Release our hold on all the samples we've allocated - // - for (int index = 0; index < m_3DSampleHandles.Count (); index ++) { - H3DSAMPLE sample = m_3DSampleHandles[index]; - if (sample != NULL) { - ::AIL_release_3D_sample_handle (sample); - } - } - - m_3DSampleHandles.Delete_All (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Validate_3D_Sound_Buffer -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Validate_3D_Sound_Buffer (SoundBufferClass *buffer) -{ - bool retval = false; - - // - // 3D sound buffer MUST be uncompressed mono WAV data - // - if ((buffer != NULL) && - (buffer->Get_Channels () == 1) && - (buffer->Get_Type () == WAVE_FORMAT_PCM) && - (buffer->Is_Streaming () == false)) - { - retval = true; - } - - // Return a true/false result code - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// ReAssign_2D_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::ReAssign_2D_Handles (void) -{ - // Loop through all the entries in the playlist - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - - // If this is a 2D sound effect, then force it to 'get' a new - // sound handle. - if ((sound_obj->Get_Class_ID () == CLASSID_2D) || - (sound_obj->Get_Class_ID () == CLASSID_PSEUDO3D) || - (sound_obj->Get_Class_ID () == CLASSID_2DTRIGGER)) - { - sound_obj->Free_Miles_Handle (); - sound_obj->Allocate_Miles_Handle (); - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// ReAssign_3D_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::ReAssign_3D_Handles (void) -{ - // Loop through all the entries in the playlist - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - - // If this is a 3D sound effect, then force it to 'get' a new - // sound handle. - if (sound_obj->Get_Class_ID () == CLASSID_3D) { - sound_obj->Free_Miles_Handle (); - sound_obj->Allocate_Miles_Handle (); - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_2D_Sound_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Remove_2D_Sound_Handles (void) -{ - // Loop through all the entries in the playlist - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - - // If this is a 2D sound effect, then take its handle away - if (sound_obj->Get_Class_ID () == CLASSID_2D) { - sound_obj->Free_Miles_Handle (); - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Remove_3D_Sound_Handles -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Remove_3D_Sound_Handles (void) -{ - // Loop through all the entries in the playlist - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - - // If this is a 3D sound effect, then force take its handle away - if (sound_obj->Get_Class_ID () == CLASSID_3D) { - sound_obj->Free_Miles_Handle (); - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Sound_Effects_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Set_Sound_Effects_Volume (float volume) -{ - m_SoundVolume = volume; - m_SoundVolume = min (1.0F, m_SoundVolume); - m_SoundVolume = max (0.0F, m_SoundVolume); - - // Update all the currently playing 'Sound Effects' to - // reflect this new volume - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - if (sound_obj->Get_Type () == AudibleSoundClass::TYPE_SOUND_EFFECT) { - sound_obj->Update_Volume (); - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Set_Music_Volume -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Set_Music_Volume (float volume) -{ - m_MusicVolume = volume; - m_MusicVolume = min (1.0F, m_MusicVolume); - m_MusicVolume = max (0.0F, m_MusicVolume); - - // Update all currently playing music to - // reflect this new volume - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - if (sound_obj->Get_Type () == AudibleSoundClass::TYPE_MUSIC) { - sound_obj->Update_Volume (); - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Is_Disabled -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Is_Disabled (void) const -{ - static bool _firsttime = true; - static bool _disabled = false; - - if (_firsttime) { - _firsttime = false; - - #ifdef G_CODE_BASE - // - // Use command line arguement. - // - ArgvClass argv; - if (argv.Find("-NOAUDIO")) { - _disabled = true; - } - #endif - - // - // Read the disabled key from the registry - // - RegistryClass registry ("SOFTWARE\\Westwood\\WWAudio"); - if (registry.Is_Valid ()) { - if (registry.Get_Int ("Disabled", 0) == 1) { - _disabled = true; - WWDEBUG_SAY (("WWAudio: Audio system disabled in registry.\r\n")); - } - } - } - - return _disabled; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Initialize (const char *registry_subkey_name) -{ - WWMEMLOG(MEM_SOUND); - - if (Is_Disabled () == false) { - - // - // Initialize the audio system from the registry settings - // - Load_From_Registry (registry_subkey_name); - - // - // Grab the first (and only) filter for use with our 'tinny' effect. - // - HPROENUM next = HPROENUM_FIRST; - char *name = NULL; - if (::AIL_enumerate_filters (&next, &m_ReverbFilter, &name) == 0) { - m_ReverbFilter = INVALID_MILES_HANDLE; - } - } - - // - // Register the file callbacks so we can support streaming from MIX files... - // - ::AIL_set_file_callbacks (File_Open_Callback, File_Close_Callback, - File_Seek_Callback, File_Read_Callback); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Initialize -( - bool stereo, - int bits, - int hertz -) -{ - // Open the default 2D device, then build a list of 3D - // devices and open the default. - if (Is_Disabled () == false) { - - Open_2D_Device (stereo, bits, hertz); - Build_3D_Driver_List (); - - // - // Grab the first (and only) filter for use with our 'tinny' effect. - // - HPROENUM next = HPROENUM_FIRST; - char *name = NULL; - if (::AIL_enumerate_filters (&next, &m_ReverbFilter, &name) == 0) { - m_ReverbFilter = INVALID_MILES_HANDLE; - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Shutdown -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Shutdown (void) -{ - // - // If there is a timer running, then stop the timer... - // - if (m_UpdateTimer != -1) { - - // Kill the timer - ::AIL_stop_timer (m_UpdateTimer); - ::AIL_release_timer_handle (m_UpdateTimer); - m_UpdateTimer = -1; - - // Wait for the timer callback function to end - ::WaitForSingleObject (_TimerSyncEvent, 20000); - ::CloseHandle (_TimerSyncEvent); - _TimerSyncEvent = NULL; - } - - // - // Stop all sounds from playing - // - Flush_Playlist (); - if (m_SoundScene != NULL) { - m_SoundScene->Flush_Scene (); - } - - // - // Free all our cached sound buffers - // - Flush_Cache (); - - // - // Close-out our hold on any driver resources - // - Remove_2D_Sound_Handles (); - Remove_3D_Sound_Handles (); - Release_2D_Handles (); - Release_3D_Handles (); - Free_3D_Driver_List (); - SAFE_DELETE (m_SoundScene); - Close_2D_Device (); - - // - // Shutdown Miles Sound System - // - ::AIL_shutdown (); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Register_EOS_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Register_EOS_Callback (LPFNEOSCALLBACK callback, DWORD user_param) -{ - m_EOSCallbackList.Add_Callback (callback, user_param); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// UnRegister_EOS_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::UnRegister_EOS_Callback (LPFNEOSCALLBACK callback) -{ - m_EOSCallbackList.Remove_Callback (callback); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Register_Text_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Register_Text_Callback (LPFNTEXTCALLBACK callback, DWORD user_param) -{ - m_TextCallbackList.Add_Callback (callback, user_param); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// UnRegister_Text_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::UnRegister_Text_Callback (LPFNTEXTCALLBACK callback) -{ - m_TextCallbackList.Remove_Callback (callback); - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Fire_Text_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Fire_Text_Callback (AudibleSoundClass *sound_obj, const StringClass &text) -{ - if (text.Get_Length () > 0) { - - // - // Loop over all the text-callbacks that have been registered - // - for (int index = 0; index < m_TextCallbackList.Count (); index ++) { - uint32 user_data = 0L; - LPFNTEXTCALLBACK callback = m_TextCallbackList.Get_Callback (index, &user_data); - if (callback != NULL) { - - // - // Fire the notification - // - (*callback) (sound_obj, text, user_data); - } - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Allow_Sound_Effects -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Allow_Sound_Effects (bool onoff) -{ - // Is the state changing? - if (m_AreSoundEffectsEnabled != onoff) { - m_AreSoundEffectsEnabled = onoff; - - // Update all the currently playing 'Sound Effects' to - // reflect this new state. - if (m_AreSoundEffectsEnabled) { - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - if (sound_obj->Get_Type () == AudibleSoundClass::TYPE_SOUND_EFFECT) { - sound_obj->Allocate_Miles_Handle (); - } - } - } else { - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - if (sound_obj->Get_Type () == AudibleSoundClass::TYPE_SOUND_EFFECT) { - sound_obj->Free_Miles_Handle (); - } - } - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Allow_Music -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Allow_Music (bool onoff) -{ - // Is the state changing? - if (m_IsMusicEnabled != onoff) { - m_IsMusicEnabled = onoff; - - // Update all the currently playing 'music tracks' to - // reflect this new state. - if (m_IsMusicEnabled) { - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - if (sound_obj->Get_Type () == AudibleSoundClass::TYPE_MUSIC) { - sound_obj->Stop (false); - sound_obj->Play (); - } - } - } else { - for (int index = 0; index < m_Playlist.Count (); index ++) { - AudibleSoundClass *sound_obj = m_Playlist[index]; - if (sound_obj->Get_Type () == AudibleSoundClass::TYPE_MUSIC) { - sound_obj->Free_Miles_Handle (); - } - } - } - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Simple_Play_2D_Sound_Effect -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Simple_Play_2D_Sound_Effect -( - const char *filename, - float priority, - float volume -) -{ - bool retval = false; - AudibleSoundClass *sound = Create_Sound_Effect (filename); - if (sound != NULL) { - sound->Set_Priority (priority); - sound->Set_Loop_Count (1); - sound->Set_Volume(volume); - sound->Play (); - sound->Release_Ref (); - sound = NULL; - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Simple_Play_2D_Sound_Effect -// -//////////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Simple_Play_2D_Sound_Effect -( - FileClass &file, - float priority, - float volume -) -{ - bool retval = false; - AudibleSoundClass *sound = Create_Sound_Effect (file); - if (sound != NULL) { - sound->Set_Priority (priority); - sound->Set_Loop_Count (1); - sound->Set_Volume(volume); - sound->Play (); - sound->Release_Ref (); - sound = NULL; - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_File -// -//////////////////////////////////////////////////////////////////////////////////////////////// -FileClass * -WWAudioClass::Get_File (LPCTSTR filename) -{ - FileClass *file = NULL; - if (m_FileFactory != NULL) { - file = m_FileFactory->Get_File (filename); - } else { - file = _TheFileFactory->Get_File(filename); - } - - // Return a pointer to the file - return file; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Return_File -// -//////////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Return_File (FileClass *file) -{ - if (m_FileFactory != NULL) { - m_FileFactory->Return_File (file); - } else { - SAFE_DELETE (file); - } - - return; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Logical_Sound -// -//////////////////////////////////////////////////////////////////////////////////////////// -LogicalSoundClass * -WWAudioClass::Create_Logical_Sound (void) -{ - return W3DNEW LogicalSoundClass; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Logical_Listener -// -//////////////////////////////////////////////////////////////////////////////////////////// -LogicalListenerClass * -WWAudioClass::Create_Logical_Listener (void) -{ - return W3DNEW LogicalListenerClass; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Add_Logical_Type -// -//////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Add_Logical_Type (int id, LPCTSTR display_name) -{ - m_LogicalTypes.Add (LOGICAL_TYPE_STRUCT (id, display_name)); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Reset_Logical_Types -// -//////////////////////////////////////////////////////////////////////////////////////////// -void -WWAudioClass::Reset_Logical_Types (void) -{ - m_LogicalTypes.Delete_All (); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Get_Logical_Type -// -//////////////////////////////////////////////////////////////////////////////////////////// -int -WWAudioClass::Get_Logical_Type (int index, StringClass &name) -{ - int type_id = 0; - - WWASSERT (index >= 0 && index < m_LogicalTypes.Count ()); - if (index >= 0 && index < m_LogicalTypes.Count ()) { - type_id = m_LogicalTypes[index].id; - name = m_LogicalTypes[index].display_name; - } - - return type_id; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Find_Sound_Object -// -//////////////////////////////////////////////////////////////////////////////////////////// -SoundSceneObjClass * -WWAudioClass::Find_Sound_Object (uint32 sound_obj_id) -{ - SoundSceneObjClass *sound_obj = NULL; - - // - // Lookup the sound object and return it to the caller - // - int index = 0; - if (SoundSceneObjClass::Find_Sound_Object (sound_obj_id, &index)) { - sound_obj = SoundSceneObjClass::m_GlobalSoundList[index]; - } - - return sound_obj; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Load_From_Registry -// -//////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Load_From_Registry (const char *subkey_name) -{ - bool retval = true; - - StringClass device_name; - bool is_stereo = true; - int bits = 16; - int hertz = 44100; - - // - // Load the settings from the registry - // - if (Load_From_Registry (subkey_name, device_name, is_stereo, bits, hertz, - m_AreSoundEffectsEnabled, m_IsMusicEnabled, m_SoundVolume, m_MusicVolume)) - { - // - // Close any open devices - // - Free_3D_Driver_List (); - Close_2D_Device (); - - // - // Open the 2D device as specified - // - Open_2D_Device (is_stereo, bits, hertz); - - // - // Find and open the 3D device specified - // - Build_3D_Driver_List (); - Select_3D_Device (device_name); - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Load_From_Registry -// -//////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Load_From_Registry -( - const char * subkey_name, - StringClass & device_name, - bool & is_stereo, - int & bits, - int & hertz, - bool & sound_enabled, - bool & music_enabled, - float & sound_volume, - float & music_volume -) -{ - bool retval = false; - - // - // Attempt to open the registry key - // - RegistryClass registry (subkey_name); - if (registry.Is_Valid ()) { - - // - // Read the device name into a string object - // - char temp_buffer[256] = { 0 }; - registry.Get_String (VALUE_NAME_DEVICE_NAME, temp_buffer, sizeof (temp_buffer)); - device_name = temp_buffer; - - // - // Read the 2D settings - // - is_stereo = (registry.Get_Int (VALUE_NAME_IS_STEREO, true) == 1); - bits = registry.Get_Int (VALUE_NAME_BITS, 16); - hertz = registry.Get_Int (VALUE_NAME_HERTZ, 44100); - - // - // Read the sound/music enabled settings - // - music_enabled = (registry.Get_Int (VALUE_NAME_MUSIC_ENABLED, 1) == 1); - sound_enabled = (registry.Get_Int (VALUE_NAME_SOUND_ENABLED, 1) == 1); - - // - // Read the volume information - // - music_volume = registry.Get_Int (VALUE_NAME_MUSIC_VOL, 100) / 100.0F; - sound_volume = registry.Get_Int (VALUE_NAME_SOUND_VOL, 100) / 100.0F; - music_volume = WWMath::Clamp (music_volume, 0, 1.0F); - sound_volume = WWMath::Clamp (sound_volume, 0, 1.0F); - - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Save_To_Registry -// -//////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Save_To_Registry (const char *subkey_name) -{ - StringClass device_name; - - // - // Get the name of the current 3D driver - // - for (int index = 0; index < m_Driver3DList.Count (); index ++) { - DRIVER_INFO_STRUCT *info = m_Driver3DList[index]; - - // - // Is this the device we were looking for? - // - if (info != NULL && info->driver == m_Driver3D) { - device_name = info->name; - break; - } - } - - // - // Save these settings to the registry - // - return Save_To_Registry (subkey_name, device_name, m_PlaybackStereo, m_PlaybackBits, m_PlaybackRate, - m_AreSoundEffectsEnabled, m_IsMusicEnabled, m_SoundVolume, m_MusicVolume); -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Save_To_Registry -// -//////////////////////////////////////////////////////////////////////////////////////////// -bool -WWAudioClass::Save_To_Registry -( - const char * subkey_name, - const StringClass & device_name, - bool is_stereo, - int bits, - int hertz, - bool sound_enabled, - bool music_enabled, - float sound_volume, - float music_volume - -) -{ - bool retval = false; - - // - // Attempt to open the registry key - // - RegistryClass registry (subkey_name); - if (registry.Is_Valid ()) { - - // - // Save the settings to the registry - // - registry.Set_String (VALUE_NAME_DEVICE_NAME, device_name); - registry.Set_Int (VALUE_NAME_IS_STEREO, is_stereo); - registry.Set_Int (VALUE_NAME_BITS, bits); - registry.Set_Int (VALUE_NAME_HERTZ, hertz); - registry.Set_Int (VALUE_NAME_MUSIC_ENABLED, music_enabled); - registry.Set_Int (VALUE_NAME_SOUND_ENABLED, sound_enabled); - registry.Set_Int (VALUE_NAME_MUSIC_VOL, music_volume * 100); - registry.Set_Int (VALUE_NAME_SOUND_VOL, sound_volume * 100); - - retval = true; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// File_Open_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////// -U32 AILCALLBACK -WWAudioClass::File_Open_Callback (char const *filename, U32 *file_handle) -{ - U32 retval = false; - - if (Get_Instance () != NULL) { - - // - // Open the file - // - FileClass *file = Get_Instance ()->Get_File (filename); - if (file != NULL && file->Open ()) { - (*file_handle) = (U32)file; - retval = true; - } - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// File_Close_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////// -void AILCALLBACK -WWAudioClass::File_Close_Callback (U32 file_handle) -{ - if (Get_Instance () != NULL) { - - // - // Close the file (if necessary) - // - FileClass *file = reinterpret_cast (file_handle); - if (file != NULL) { - Get_Instance ()->Return_File (file); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// File_Seek_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////// -S32 AILCALLBACK -WWAudioClass::File_Seek_Callback (U32 file_handle, S32 offset, U32 type) -{ - S32 retval = 0; - - // - // Convert the handle to a file handle type - // - FileClass *file = reinterpret_cast (file_handle); - if (file != NULL) { - - // - // Convert the Miles seek type to one of our own - // - int seek_type = SEEK_CUR; - switch (type) - { - case AIL_FILE_SEEK_BEGIN: - seek_type = SEEK_SET; - break; - - case AIL_FILE_SEEK_CURRENT: - seek_type = SEEK_CUR; - break; - - case AIL_FILE_SEEK_END: - seek_type = SEEK_END; - break; - } - - // - // Perform the seek - // - retval = file->Seek (offset, seek_type); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// File_Read_Callback -// -//////////////////////////////////////////////////////////////////////////////////////////// -U32 AILCALLBACK -WWAudioClass::File_Read_Callback (U32 file_handle, void *buffer, U32 bytes) -{ - U32 retval = 0; - - // - // Convert the handle to a file handle type - // - FileClass *file = reinterpret_cast (file_handle); - if (file != NULL) { - - // - // Read the bytes from the file - // - retval = file->Read (buffer, bytes); - } - - return retval; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.h deleted file mode 100644 index 5921094307..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/WWAudio.h +++ /dev/null @@ -1,586 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWAudio.h * - * * - * $Archive:: /Commando/Code/WWAudio/WWAudio.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/14/01 2:27p $* - * * - * $Revision:: 19 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __WWAUDIO_H -#define __WWAUDIO_H - -#include "always.h" -#pragma warning (push, 3) -#include "mss.h" -#pragma warning (pop) - -#include "Vector.H" -#include "SoundBuffer.h" -#include "AudioEvents.h" -#include "wwstring.h" - -///////////////////////////////////////////////////////////////////////////////// -// Forward declaration -///////////////////////////////////////////////////////////////////////////////// -class AudibleSoundClass; -class Sound3DClass; -class Sound2DTriggerClass; -class StreamSoundClass; -class FileClass; -class SoundSceneClass; -class FileFactoryClass; -class SoundSceneObjClass; -class LogicalListenerClass; -class LogicalSoundClass; -class Matrix3D; - - -///////////////////////////////////////////////////////////////////////////////// -// Class IDs -///////////////////////////////////////////////////////////////////////////////// -typedef enum -{ - CLASSID_UNKNOWN = 0, - CLASSID_2D, - CLASSID_3D, - CLASSID_LISTENER, - CLASSID_PSEUDO3D, - CLASSID_2DTRIGGER, - CLASSID_LOGICAL, - CLASSID_FILTERED, - CLASSID_COUNT -} SOUND_CLASSID; - - -///////////////////////////////////////////////////////////////////////////////// -// Default values -///////////////////////////////////////////////////////////////////////////////// -const int DEF_2D_SAMPLE_COUNT = 16; -const int DEF_3D_SAMPLE_COUNT = 16; -const float DEF_MUSIC_VOL = 1.0F; -const float DEF_SFX_VOL = 1.0F; -const int DEF_CACHE_SIZE = 1024; -const int DEF_MAX_2D_BUFFER_SIZE = 20000; -const int DEF_MAX_3D_BUFFER_SIZE = 100000; - - -///////////////////////////////////////////////////////////////////////////////// -// Constants -///////////////////////////////////////////////////////////////////////////////// -enum -{ - MAX_CACHE_HASH = 256, - CACHE_HASH_MASK = 0x000000FF -}; - - -///////////////////////////////////////////////////////////////////////////////// -// -// WWAudioClass -// -// Main controlling entity for all music and sound effects in a game. Used -// to: -// -// -- Select hardware devices -// -- Modify quality preferences -// -- Modify global volume settings -// -- Allocate new sounds -// -- Cache reuseable sounds -// -- Play music and sound effects -// -// -///////////////////////////////////////////////////////////////////////////////// -class WWAudioClass -{ -public: - - ////////////////////////////////////////////////////////////////////// - // Public data types - ////////////////////////////////////////////////////////////////////// - typedef enum - { - DRIVER2D_ERROR = 0, - DRIVER2D_DSOUND, - DRIVER2D_WAVEOUT, - DRIVER2D_COUNT - } DRIVER_TYPE_2D; - - typedef enum - { - DRIVER3D_ERROR = 0, - DRIVER3D_D3DSOUND, - DRIVER3D_EAX, - DRIVER3D_A3D, - DRIVER3D_RSX, - DRIVER3D_PSEUDO, - DRIVER3D_DOLBY, - DRIVER3D_COUNT - } DRIVER_TYPE_3D; - - typedef struct _DRIVER_INFO_STRUCT - { - HPROVIDER driver; - char * name; - } DRIVER_INFO_STRUCT; - - ////////////////////////////////////////////////////////////////////// - // Friend classes - ////////////////////////////////////////////////////////////////////// - friend class AudibleSoundClass; - friend class Sound3DClass; - friend class Listener3DClass; - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - WWAudioClass (void); - virtual ~WWAudioClass (void); - - ////////////////////////////////////////////////////////////////////// - // Static methods - ////////////////////////////////////////////////////////////////////// - static WWAudioClass * Get_Instance (void) { return _theInstance; } - - ////////////////////////////////////////////////////////////////////// - // Initialization methods - ////////////////////////////////////////////////////////////////////// - - // - // Note: After call Initialize () you can begin using the library, you don't - // need to explicity call Open_2D_Device () or Select_3D_Device (). Those - // methods were provided as a means of opening devices other than the default. - // - // The Initialize () method defaults to a stereo, 16bit, 44100hz 2D DirectSound - // driver and a RSX 3D provider. If RSX isn't available, it trys A3D, then - // EAX, then D3DSound, then whatever driver is first available. - // - void Initialize (bool stereo = true, int bits = 16, int hertz = 44100); - void Initialize (const char *registry_subkey_name); - void Shutdown (void); - - ////////////////////////////////////////////////////////////////////// - // Driver methods - ////////////////////////////////////////////////////////////////////// - HDIGDRIVER Get_2D_Driver (void) const { return m_Driver2D; } - HPROVIDER Get_3D_Driver (void) const { return m_Driver3D; } - HPROVIDER Get_Reverb_Filter (void) const { return m_ReverbFilter; } - - ////////////////////////////////////////////////////////////////////// - // 2D Hardware/driver selection methods - ////////////////////////////////////////////////////////////////////// - DRIVER_TYPE_2D Open_2D_Device (LPWAVEFORMAT format = NULL); - DRIVER_TYPE_2D Open_2D_Device (bool stereo, int bits, int hertz); - bool Close_2D_Device (void); - int Get_Playback_Rate (void) const { return m_PlaybackRate; } - int Get_Playback_Bits (void) const { return m_PlaybackBits; } - bool Get_Playback_Stereo (void) const { return m_PlaybackStereo; } - - ////////////////////////////////////////////////////////////////////// - // 3D Hardware/driver selection methods - ////////////////////////////////////////////////////////////////////// - - // Device information - int Get_3D_Device_Count (void) const { return m_Driver3DList.Count (); } - bool Get_3D_Device (int index, DRIVER_INFO_STRUCT **info) { (*info) = m_Driver3DList[index]; return true; } - bool Is_3D_Device_Available (DRIVER_TYPE_3D type) { return Find_3D_Device (type) >= 0; } - int Find_3D_Device (DRIVER_TYPE_3D type); - - // Device selection - bool Select_3D_Device (int index); - bool Select_3D_Device (const char *device_name, HPROVIDER provider); - bool Select_3D_Device (DRIVER_TYPE_3D type); - - bool Select_3D_Device (const char *device_name); - - ////////////////////////////////////////////////////////////////////// - // Registry settings - ////////////////////////////////////////////////////////////////////// - bool Load_From_Registry (const char *subkey_name); - bool Load_From_Registry (const char *subkey_name, StringClass &device_name, bool &is_stereo, int &bits, int &hertz, bool &sound_enabled, bool &music_enabled, float &sound_volume, float &music_volume); - bool Save_To_Registry (const char *subkey_name); - bool Save_To_Registry (const char *subkey_name, const StringClass &device_name, bool is_stereo, int bits, int hertz, bool sound_enabled, bool music_enabled, float sound_volume, float music_volume); - - ////////////////////////////////////////////////////////////////////// - // File interface methods - ////////////////////////////////////////////////////////////////////// - - // - // Note: The user is responsible for freeing this file factory, the - // sound library does not. - // - void Set_File_Factory (FileFactoryClass *ffactory) { m_FileFactory = ffactory; } - - ////////////////////////////////////////////////////////////////////// - // Preference settings methods - ////////////////////////////////////////////////////////////////////// - bool Set_Max_2D_Sample_Count (int count = DEF_2D_SAMPLE_COUNT); - int Get_Max_2D_Sample_Count (void) const; - int Get_Avail_2D_Sample_Count (void) const; - - bool Set_Max_3D_Sample_Count (int count = DEF_3D_SAMPLE_COUNT); - int Get_Max_3D_Sample_Count (void) const; - int Get_Avail_3D_Sample_Count (void) const; - - // - // Reverb Support: Only works with Create Labs EAX chipset. - // - float Get_Effects_Level (void) { return m_EffectsLevel; } - - // See ENVIRONMENT_ defines in MSS.H for a list of possible values. - int Get_Reverb_Room_Type (void) { return m_ReverbRoomType; } - void Set_Reverb_Room_Type (int type); - - ////////////////////////////////////////////////////////////////////// - // Volume methods - ////////////////////////////////////////////////////////////////////// - void Set_Sound_Effects_Volume (float volume = DEF_SFX_VOL); - float Get_Sound_Effects_Volume (void) const { return m_SoundVolume; } - - void Set_Music_Volume (float volume = DEF_MUSIC_VOL); - float Get_Music_Volume (void) const { return m_MusicVolume; } - - void Allow_Sound_Effects (bool onoff = true); - bool Are_Sound_Effects_On (void) const { return m_AreSoundEffectsEnabled; } - - void Allow_Music (bool onoff = true); - bool Is_Music_On (void) const { return m_IsMusicEnabled; } - - ////////////////////////////////////////////////////////////////////// - // Update methods - ////////////////////////////////////////////////////////////////////// - void On_Frame_Update (unsigned int milliseconds = 0); - - ////////////////////////////////////////////////////////////////////// - // Callback methods - ////////////////////////////////////////////////////////////////////// - void Register_EOS_Callback (LPFNEOSCALLBACK callback, DWORD user_param); - void UnRegister_EOS_Callback (LPFNEOSCALLBACK callback); - - void Register_Text_Callback (LPFNTEXTCALLBACK callback, DWORD user_param); - void UnRegister_Text_Callback (LPFNTEXTCALLBACK callback); - - void Fire_Text_Callback (AudibleSoundClass *sound_obj, const StringClass &text); - - ////////////////////////////////////////////////////////////////////// - // Sound allocation methods - ////////////////////////////////////////////////////////////////////// - - // - // Note: The string_id is either the filename (for file-based sounds) - // or the string_id passed into the create-from-memory methods. - // It is important to note that the AudibleSoundClass object is not cached, but - // the raw sound data the AudibleSoundClass object plays. - // - bool Is_Sound_Cached (const char *string_id); - - // - // Note: We differentiate between a 'music' object and - // a 'sound effect' for volume control. A music object - // is simply a sound effect with a 'SOUND_TYPE' of TYPE_MUSIC. - // When the user adjusts the 'music' volume, we loop through - // the sound effects marked 'music' and update their volume. - // Same for 'sound effect' volume. - // - - // - // Note: The sound data these objects support can be PCM WAV, - // ADPCM WAV, VOC, or MP3. - // - AudibleSoundClass * Create_Sound_Effect (FileClass &file, const char *string_id); - AudibleSoundClass * Create_Sound_Effect (const char *filename); - AudibleSoundClass * Create_Sound_Effect (const char *string_id, unsigned char *raw_wave_data, unsigned long bytes); - - // - // Note: 3D sound effects should be inserted into the SoundScene. - // They should not be manually played/stopped/etc. - // - // True 3D sound effects require mono, uncompressed, WAV data. - // If the supplied data is not in this format the sound will - // become a pseudo-3D sound. - // - // Pseudo-3D sounds are not true 3D sounds. They have the - // same properties as 3D 'sound effects' but do not use 3D - // hardware, are not restricted to mono, uncompressed, WAV data, - // and do not calculate doppler and reverb effects. - // - Sound3DClass * Create_3D_Sound (FileClass &file, const char *string_id, int classid_hint = CLASSID_3D); - Sound3DClass * Create_3D_Sound (const char *filename, int classid_hint = CLASSID_3D); - Sound3DClass * Create_3D_Sound (const char *string_id, unsigned char *raw_wave_data, unsigned long bytes, int classid_hint = CLASSID_3D); - - - ////////////////////////////////////////////////////////////////////// - // Logical-sound related methods - ////////////////////////////////////////////////////////////////////// - LogicalSoundClass * Create_Logical_Sound (void); - LogicalListenerClass * Create_Logical_Listener (void); - - // - // Logical type identification for use with the definition system - // - void Add_Logical_Type (int id, LPCTSTR display_name); - void Reset_Logical_Types (void); - int Get_Logical_Type_Count (void) const { return m_LogicalTypes.Count (); } - int Get_Logical_Type (int index, StringClass &name); - - ////////////////////////////////////////////////////////////////////// - // Definition related methods - ////////////////////////////////////////////////////////////////////// - - // - // Sound creation methods - // - int Create_Instant_Sound (int definition_id, const Matrix3D &tm, RefCountClass *user_obj = NULL, uint32 user_data = 0, int classid_hint = CLASSID_3D); - int Create_Instant_Sound (const char *def_name, const Matrix3D &tm, RefCountClass *user_obj = NULL, uint32 user_data = 0, int classid_hint = CLASSID_3D); - AudibleSoundClass * Create_Continuous_Sound (int definition_id, RefCountClass *user_obj = NULL, uint32 user_data = 0, int classid_hint = CLASSID_3D); - AudibleSoundClass * Create_Continuous_Sound (const char *def_name, RefCountClass *user_obj = NULL, uint32 user_data = 0, int classid_hint = CLASSID_3D); - AudibleSoundClass * Create_Sound (int definition_id, RefCountClass *user_obj = NULL, uint32 user_data = 0, int classid_hint = CLASSID_3D); - AudibleSoundClass * Create_Sound (const char *def_name, RefCountClass *user_obj = NULL, uint32 user_data = 0, int classid_hint = CLASSID_3D); - - ////////////////////////////////////////////////////////////////////// - // Sound object lookup - ////////////////////////////////////////////////////////////////////// - SoundSceneObjClass * Find_Sound_Object (uint32 sound_obj_id); - - ////////////////////////////////////////////////////////////////////// - // Sound scene methods (for 3D sounds) - ////////////////////////////////////////////////////////////////////// - SoundSceneClass * Get_Sound_Scene (void) const { return m_SoundScene; } - - ////////////////////////////////////////////////////////////////////// - // Cache methods - ////////////////////////////////////////////////////////////////////// - - // - // Note: The cache sizes are in kilo-bytes. The default - // is currently set to 1MB. - // - bool Set_Cache_Size (int kbytes = DEF_CACHE_SIZE) { m_MaxCacheSize = (kbytes * 1024); } - int Get_Cache_Size (void) const { return m_MaxCacheSize / 1024; } - int Get_Current_Cache_Size (void) const { return m_CurrentCacheSize; } - - // - // This settings determines whether a sound buffer is loaded - // into memory or streamed from file. - // - // Note: True 3D sounds can't be streamed, so if the buffer size - // is larger then the following setting, the sound is created as - // a pseudo-3d sound effect and streamed. - // - void Set_Max_2D_Sound_Buffer (int bytes = DEF_MAX_2D_BUFFER_SIZE) { m_Max2DBufferSize = bytes; } - void Set_Max_3D_Sound_Buffer (int bytes = DEF_MAX_3D_BUFFER_SIZE) { m_Max3DBufferSize = bytes; } - - ////////////////////////////////////////////////////////////////////// - // Play control methods - ////////////////////////////////////////////////////////////////////// - bool Simple_Play_2D_Sound_Effect (const char *filename, float priority = 1.0F, float volume = DEF_SFX_VOL); - bool Simple_Play_2D_Sound_Effect (FileClass &file, float priority = 1.0F, float volume = DEF_SFX_VOL); - - ////////////////////////////////////////////////////////////////////// - // Playlist methods - ////////////////////////////////////////////////////////////////////// - bool Add_To_Playlist (AudibleSoundClass *sound); - bool Remove_From_Playlist (AudibleSoundClass *sound); - int Get_Playlist_Count (void) const { return m_Playlist.Count (); } - AudibleSoundClass * Get_Playlist_Entry (int index) const; - AudibleSoundClass * Peek_Playlist_Entry (int index) const { return m_Playlist[index]; } - void Flush_Playlist (void); - bool Is_Sound_In_Playlist (AudibleSoundClass *sound_obj); - - ////////////////////////////////////////////////////////////////////// - // Statistics methods - ////////////////////////////////////////////////////////////////////// - - // - // This CPU percent includes total CPU being used for: - // Mixing - // Format conversions - // ADPCM or MP3 decompression - // System buffer fills - // - float Get_Digital_CPU_Percent (void) const; - - ////////////////////////////////////////////////////////////////////// - // Debug methods - ////////////////////////////////////////////////////////////////////// - bool Is_Disabled (void) const; - - // Um somtimes you need to get rid of all the completed sounds without - // being in the update render function and without totally shutting down - // the sound system. This is primarily because completed (non static) sounds - // still may have a reference to the object they're attached to. - void Free_Completed_Sounds (void); - -protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - void Build_3D_Driver_List (void); - void Free_3D_Driver_List (void); - void Reprioritize_Playlist (void); - bool Validate_3D_Sound_Buffer (SoundBufferClass *buffer); - FileClass * Get_File (LPCTSTR filename); - void Return_File (FileClass *file); - - ////////////////////////////////////////////////////////////////////// - // Handle management - ////////////////////////////////////////////////////////////////////// - void Allocate_2D_Handles (void); - void Release_2D_Handles (void); - void Allocate_3D_Handles (void); - void Release_3D_Handles (void); - HSAMPLE Get_2D_Sample (const AudibleSoundClass &sound_obj); - H3DSAMPLE Get_3D_Sample (const Sound3DClass &sound_obj); - H3DPOBJECT Get_Listener_Handle (void); - void ReAssign_2D_Handles (void); - void ReAssign_3D_Handles (void); - void Remove_2D_Sound_Handles (void); - void Remove_3D_Sound_Handles (void); - bool Is_OK_To_Give_Handle (const AudibleSoundClass &sound_obj); - - ////////////////////////////////////////////////////////////////////// - // Cache methods - ////////////////////////////////////////////////////////////////////// - SoundBufferClass * Get_Sound_Buffer (FileClass &file, const char *string_id, bool is_3d); - SoundBufferClass * Get_Sound_Buffer (const char *filename, bool is_3d); - SoundBufferClass * Find_Cached_Buffer (const char *string_id); - SoundBufferClass * Create_Sound_Buffer (FileClass &file, const char *string_id, bool is_3d); - SoundBufferClass * Create_Sound_Buffer (unsigned char *file_image, unsigned long bytes, const char *string_id, bool is_3d); - bool Cache_Buffer (SoundBufferClass *buffer, const char *string_id); - bool Free_Cache_Space (int bytes); - void Flush_Cache (void); - - ////////////////////////////////////////////////////////////////////// - // Miles File Callbacks - ////////////////////////////////////////////////////////////////////// - static U32 AILCALLBACK File_Open_Callback (char const *filename, U32 *file_handle); - static void AILCALLBACK File_Close_Callback (U32 file_handle); - static S32 AILCALLBACK File_Seek_Callback (U32 file_handle, S32 offset, U32 type); - static U32 AILCALLBACK File_Read_Callback (U32 file_handle, void *buffer, U32 bytes); - -private: - - ////////////////////////////////////////////////////////////////////// - // Static member data - ////////////////////////////////////////////////////////////////////// - static WWAudioClass * _theInstance; - static HANDLE _TimerSyncEvent; - - ////////////////////////////////////////////////////////////////////// - // Private data types - ////////////////////////////////////////////////////////////////////// - typedef struct _CACHE_ENTRY_STRUCT - { - char * string_id; - SoundBufferClass * buffer; - - _CACHE_ENTRY_STRUCT (void) - : string_id (0), buffer (NULL) {} - - _CACHE_ENTRY_STRUCT &operator= (const _CACHE_ENTRY_STRUCT &src) { string_id = ::strdup (src.string_id); REF_PTR_SET (buffer, src.buffer); return *this; } - bool operator== (const _CACHE_ENTRY_STRUCT &src) { return false; } - bool operator!= (const _CACHE_ENTRY_STRUCT &src) { return true; } - } CACHE_ENTRY_STRUCT; - - - typedef struct _LOGICAL_TYPE_STRUCT - { - StringClass display_name; - int id; - - _LOGICAL_TYPE_STRUCT (void) - : id (0) {} - - _LOGICAL_TYPE_STRUCT (int _id, LPCTSTR name) - : display_name (name), id (_id) {} - - bool operator== (const _LOGICAL_TYPE_STRUCT &src) { return false; } - bool operator!= (const _LOGICAL_TYPE_STRUCT &src) { return true; } - } LOGICAL_TYPE_STRUCT; - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - int m_PlaybackRate; - int m_PlaybackBits; - bool m_PlaybackStereo; - float m_MusicVolume; - float m_SoundVolume; - int m_Max2DSamples; - int m_Max3DSamples; - int m_Max2DBufferSize; - int m_Max3DBufferSize; - HTIMER m_UpdateTimer; - bool m_IsMusicEnabled; - bool m_AreSoundEffectsEnabled; - FileFactoryClass * m_FileFactory; - - // Callback lists - AudioCallbackListClass m_EOSCallbackList; - AudioCallbackListClass m_TextCallbackList; - - // Sound scene management - SoundSceneClass * m_SoundScene; - - // Driver information - HDIGDRIVER m_Driver2D; - HPROVIDER m_Driver3D; - HPROVIDER m_Driver3DPseudo; - HPROVIDER m_ReverbFilter; - DynamicVectorClass m_Driver3DList; - - // Available sample handles - DynamicVectorClass m_2DSampleHandles; - DynamicVectorClass m_3DSampleHandles; - - // Playlist managment - DynamicVectorClass m_Playlist; - DynamicVectorClass m_CompletedSounds; - - // Buffer caching - DynamicVectorClass m_CachedBuffers[MAX_CACHE_HASH]; - int m_MaxCacheSize; - int m_CurrentCacheSize; - - // Logical type management - DynamicVectorClass m_LogicalTypes; - - // Reverb support - float m_EffectsLevel; - int m_ReverbRoomType; -}; - - -#endif //__WWAUDIO_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp deleted file mode 100644 index 12c47aeb48..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/listenerhandle.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 11:54a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "listenerhandle.h" -#include "AudibleSound.h" - - -////////////////////////////////////////////////////////////////////// -// -// Sound3DHandleClass -// -////////////////////////////////////////////////////////////////////// -ListenerHandleClass::ListenerHandleClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// ~ListenerHandleClass -// -////////////////////////////////////////////////////////////////////// -ListenerHandleClass::~ListenerHandleClass (void) -{ - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.h deleted file mode 100644 index cb020885ca..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/listenerhandle.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/listenerhandle.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 11:54a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __LISTENERHANDLE_H -#define __LISTENERHANDLE_H - -#include "sound3dhandle.h" - - -////////////////////////////////////////////////////////////////////// -// -// ListenerHandleClass -// -////////////////////////////////////////////////////////////////////// -class ListenerHandleClass : public Sound3DHandleClass -{ -public: - - /////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////// - ListenerHandleClass (void); - ~ListenerHandleClass (void); - - /////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////// - - // - // RTTI - // - ListenerHandleClass * As_ListenerHandleClass (void) { return this; } - - // - // Inherited - // - void Initialize (SoundBufferClass *buffer); - void Start_Sample (void) { } - void Stop_Sample (void) { } - void Resume_Sample (void) { } - void End_Sample (void) { } - void Set_Sample_Volume (S32 volume) { } - S32 Get_Sample_Volume (void) { return 0; } - void Set_Sample_Pan (S32 pan) { } - S32 Get_Sample_Pan (void) { return 64; } - void Set_Sample_Loop_Count (U32 count) { } - U32 Get_Sample_Loop_Count (void) { return 0; } - void Set_Sample_MS_Position (U32 ms) { } - void Get_Sample_MS_Position (S32 *len, S32 *pos) { } - S32 Get_Sample_Playback_Rate (void) { return 0; } - void Set_Sample_Playback_Rate (S32 rate) { } - -protected: - - /////////////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////// - // Protected member data - /////////////////////////////////////////////////////////////////// -}; - - -#endif //__LISTENERHANDLE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp deleted file mode 100644 index 5fea55a545..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/sound2dhandle.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/23/01 5:07p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "sound2dhandle.h" -#include "AudibleSound.h" - - -////////////////////////////////////////////////////////////////////// -// -// Sound2DHandleClass -// -////////////////////////////////////////////////////////////////////// -Sound2DHandleClass::Sound2DHandleClass (void) : - SampleHandle ((HSAMPLE)INVALID_MILES_HANDLE) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// ~Sound2DHandleClass -// -////////////////////////////////////////////////////////////////////// -Sound2DHandleClass::~Sound2DHandleClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Initialize -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Initialize (SoundBufferClass *buffer) -{ - SoundHandleClass::Initialize (buffer); - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - - // - // Make sure this handle is fresh - // - ::AIL_init_sample (SampleHandle); - - // - // Pass the actual sound data onto the sample - // - if (Buffer != NULL) { - ::AIL_set_named_sample_file (SampleHandle, (char *)Buffer->Get_Filename (), - Buffer->Get_Raw_Buffer (), Buffer->Get_Raw_Length (), 0); - } - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Start_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Start_Sample (void) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_start_sample (SampleHandle); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Stop_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Stop_Sample (void) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_stop_sample (SampleHandle); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Resume_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Resume_Sample (void) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_resume_sample (SampleHandle); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// End_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::End_Sample (void) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_end_sample (SampleHandle); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Pan -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Sample_Pan (S32 pan) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_pan (SampleHandle, pan); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Pan -// -////////////////////////////////////////////////////////////////////// -S32 -Sound2DHandleClass::Get_Sample_Pan (void) -{ - S32 retval = 0; - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_sample_pan (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Volume -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Sample_Volume (S32 volume) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_volume (SampleHandle, volume); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Volume -// -////////////////////////////////////////////////////////////////////// -S32 -Sound2DHandleClass::Get_Sample_Volume (void) -{ - S32 retval = 0; - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_sample_volume (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Loop_Count -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Sample_Loop_Count (U32 count) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_loop_count (SampleHandle, count); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Loop_Count -// -////////////////////////////////////////////////////////////////////// -U32 -Sound2DHandleClass::Get_Sample_Loop_Count (void) -{ - U32 retval = 0; - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_sample_loop_count (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_MS_Position -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Sample_MS_Position (U32 ms) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_ms_position (SampleHandle, ms); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_MS_Position -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Get_Sample_MS_Position (S32 *len, S32 *pos) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_sample_ms_position (SampleHandle, len, pos); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_User_Data -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Sample_User_Data (S32 i, U32 val) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_user_data (SampleHandle, i, val); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_User_Data -// -////////////////////////////////////////////////////////////////////// -U32 -Sound2DHandleClass::Get_Sample_User_Data (S32 i) -{ - U32 retval = 0; - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_sample_user_data (SampleHandle, i); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Playback_Rate -// -////////////////////////////////////////////////////////////////////// -S32 -Sound2DHandleClass::Get_Sample_Playback_Rate (void) -{ - S32 retval = 0; - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_sample_playback_rate (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Playback_Rate -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Sample_Playback_Rate (S32 rate) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_playback_rate (SampleHandle, rate); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Miles_Handle -// -////////////////////////////////////////////////////////////////////// -void -Sound2DHandleClass::Set_Miles_Handle (uint32 handle) -{ - SampleHandle = (HSAMPLE)handle; - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h deleted file mode 100644 index 39702eae2d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound2dhandle.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/sound2dhandle.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:10p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUND2DHANDLE_H -#define __SOUND2DHANDLE_H - -#include "soundhandle.h" - - -////////////////////////////////////////////////////////////////////// -// -// Sound2DHandleClass -// -////////////////////////////////////////////////////////////////////// -class Sound2DHandleClass : public SoundHandleClass -{ -public: - - /////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////// - Sound2DHandleClass (void); - ~Sound2DHandleClass (void); - - /////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////// - - // - // RTTI - // - Sound2DHandleClass * As_Sound2DHandleClass (void) { return this; } - - // - // Handle access - // - HSAMPLE Get_HSAMPLE (void) { return SampleHandle; } - - // - // Inherited - // - void Set_Miles_Handle (uint32 handle); - void Initialize (SoundBufferClass *buffer); - void Start_Sample (void); - void Stop_Sample (void); - void Resume_Sample (void); - void End_Sample (void); - void Set_Sample_Pan (S32 pan); - S32 Get_Sample_Pan (void); - void Set_Sample_Volume (S32 volume); - S32 Get_Sample_Volume (void); - void Set_Sample_Loop_Count (U32 count); - U32 Get_Sample_Loop_Count (void); - void Set_Sample_MS_Position (U32 ms); - void Get_Sample_MS_Position (S32 *len, S32 *pos); - void Set_Sample_User_Data (S32 i, U32 val); - U32 Get_Sample_User_Data (S32 i); - S32 Get_Sample_Playback_Rate (void); - void Set_Sample_Playback_Rate (S32 rate); - -protected: - - /////////////////////////////////////////////////////////////////// - // Protected member data - /////////////////////////////////////////////////////////////////// - HSAMPLE SampleHandle; -}; - - -#endif //__SOUND2DHANDLE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp deleted file mode 100644 index b35bb6f89a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/sound3dhandle.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/23/01 4:54p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "sound3dhandle.h" -#include "AudibleSound.h" - - -////////////////////////////////////////////////////////////////////// -// -// Sound3DHandleClass -// -////////////////////////////////////////////////////////////////////// -Sound3DHandleClass::Sound3DHandleClass (void) : - SampleHandle ((H3DSAMPLE)INVALID_MILES_HANDLE) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// ~Sound3DHandleClass -// -////////////////////////////////////////////////////////////////////// -Sound3DHandleClass::~Sound3DHandleClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Initialize -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Initialize (SoundBufferClass *buffer) -{ - SoundHandleClass::Initialize (buffer); - - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE && Buffer != NULL) { - - // - // Configure the 3D sample - // - U32 success = ::AIL_set_3D_sample_file (SampleHandle, Buffer->Get_Raw_Buffer ()); - - S32 test1 = 0; - S32 test2 = 0; - Get_Sample_MS_Position (&test1, &test2); - - // - // Check for success - // - WWASSERT (success != 0); - if (success == 0) { - WWDEBUG_SAY (("WWAudio: Couldn't set 3d sample file. Reason %s\r\n", ::AIL_last_error ())); - } - - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Start_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Start_Sample (void) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_start_3D_sample (SampleHandle); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Stop_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Stop_Sample (void) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_stop_3D_sample (SampleHandle); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Resume_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Resume_Sample (void) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_resume_3D_sample (SampleHandle); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// End_Sample -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::End_Sample (void) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_end_3D_sample (SampleHandle); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Pan -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Sample_Pan (S32 /*pan*/) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Pan -// -////////////////////////////////////////////////////////////////////// -S32 -Sound3DHandleClass::Get_Sample_Pan (void) -{ - return 64; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Volume -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Sample_Volume (S32 volume) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_3D_sample_volume (SampleHandle, volume); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Volume -// -////////////////////////////////////////////////////////////////////// -S32 -Sound3DHandleClass::Get_Sample_Volume (void) -{ - S32 retval = 0; - - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_3D_sample_volume (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Loop_Count -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Sample_Loop_Count (U32 count) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_3D_sample_loop_count (SampleHandle, count); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Loop_Count -// -////////////////////////////////////////////////////////////////////// -U32 -Sound3DHandleClass::Get_Sample_Loop_Count (void) -{ - U32 retval = 0; - - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_3D_sample_loop_count (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_MS_Position -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Sample_MS_Position (U32 ms) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - - WWASSERT (Buffer != NULL); - U32 bytes_per_sec = (Buffer->Get_Rate () * Buffer->Get_Bits ()) >> 3; - U32 bytes = (ms * bytes_per_sec) / 1000; - bytes += (bytes & 1); - ::AIL_set_3D_sample_offset (SampleHandle, bytes); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_MS_Position -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Get_Sample_MS_Position (S32 *len, S32 *pos) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - - WWASSERT (Buffer != NULL); - if (pos != NULL) { - U32 bytes = ::AIL_3D_sample_offset (SampleHandle); - U32 bytes_per_sec = (Buffer->Get_Rate () * Buffer->Get_Bits ()) >> 3; - U32 ms = (bytes * 1000) / bytes_per_sec; - (*pos) = ms; - } - - if (len != NULL) { - U32 bytes = ::AIL_3D_sample_length (SampleHandle); - U32 bytes_per_sec = (Buffer->Get_Rate () * Buffer->Get_Bits ()) >> 3; - U32 ms = (bytes * 1000) / bytes_per_sec; - (*len) = ms; - } - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_User_Data -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Sample_User_Data (S32 i, U32 val) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_3D_object_user_data (SampleHandle, i, val); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_User_Data -// -////////////////////////////////////////////////////////////////////// -U32 -Sound3DHandleClass::Get_Sample_User_Data (S32 i) -{ - U32 retval = 0; - - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - retval = AIL_3D_object_user_data (SampleHandle, i); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Playback_Rate -// -////////////////////////////////////////////////////////////////////// -S32 -Sound3DHandleClass::Get_Sample_Playback_Rate (void) -{ - S32 retval = 0; - - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_3D_sample_playback_rate (SampleHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Playback_Rate -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Sample_Playback_Rate (S32 rate) -{ - if (SampleHandle != (H3DSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_3D_sample_playback_rate (SampleHandle, rate); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Miles_Handle -// -////////////////////////////////////////////////////////////////////// -void -Sound3DHandleClass::Set_Miles_Handle (uint32 handle) -{ - WWASSERT (SampleHandle == (H3DSAMPLE)INVALID_MILES_HANDLE); - - SampleHandle = (H3DSAMPLE)handle; - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h deleted file mode 100644 index fb90bd619e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/sound3dhandle.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/sound3dhandle.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:11p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUND3DHANDLE_H -#define __SOUND3DHANDLE_H - -#include "soundhandle.h" - - -////////////////////////////////////////////////////////////////////// -// -// Sound3DHandleClass -// -////////////////////////////////////////////////////////////////////// -class Sound3DHandleClass : public SoundHandleClass -{ -public: - - /////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////// - Sound3DHandleClass (void); - ~Sound3DHandleClass (void); - - /////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////// - - // - // RTTI - // - Sound3DHandleClass * As_Sound3DHandleClass (void) { return this; } - - // - // Handle access - // - H3DSAMPLE Get_H3DSAMPLE (void) { return SampleHandle; } - - - // - // Inherited - // - void Set_Miles_Handle (uint32 handle); - void Initialize (SoundBufferClass *buffer); - void Start_Sample (void); - void Stop_Sample (void); - void Resume_Sample (void); - void End_Sample (void); - void Set_Sample_Pan (S32 pan); - S32 Get_Sample_Pan (void); - void Set_Sample_Volume (S32 volume); - S32 Get_Sample_Volume (void); - void Set_Sample_Loop_Count (U32 count); - U32 Get_Sample_Loop_Count (void); - void Set_Sample_MS_Position (U32 ms); - void Get_Sample_MS_Position (S32 *len, S32 *pos); - void Set_Sample_User_Data (S32 i, U32 val); - U32 Get_Sample_User_Data (S32 i); - S32 Get_Sample_Playback_Rate (void); - void Set_Sample_Playback_Rate (S32 rate); - -protected: - - /////////////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////// - // Protected member data - /////////////////////////////////////////////////////////////////// - H3DSAMPLE SampleHandle; -}; - - -#endif //__SOUND3DHANDLE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp deleted file mode 100644 index fb157b5454..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/soundhandle.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 12:18p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "soundhandle.h" -#include "Threads.h" - - -////////////////////////////////////////////////////////////////////// -// -// SoundHandleClass -// -////////////////////////////////////////////////////////////////////// -SoundHandleClass::SoundHandleClass (void) : - Buffer (NULL) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// ~SoundHandleClass -// -////////////////////////////////////////////////////////////////////// -SoundHandleClass::~SoundHandleClass (void) -{ - // - // Delay the release of the buffer (fixes a sync bug - // with Miles internals). - // - if (Buffer != NULL) { - WWAudioThreadsClass::Add_Delayed_Release_Object (Buffer); - Buffer = NULL; - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Initialize -// -////////////////////////////////////////////////////////////////////// -void -SoundHandleClass::Initialize (SoundBufferClass *buffer) -{ - REF_PTR_SET (Buffer, buffer); - return ; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.h deleted file mode 100644 index df01429a72..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundhandle.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/soundhandle.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:11p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDHANDLE_H -#define __SOUNDHANDLE_H - -#include "WWAudio.h" - -////////////////////////////////////////////////////////////////////// -// Forward declarations -////////////////////////////////////////////////////////////////////// -class Sound3DHandleClass; -class Sound2DHandleClass; -class SoundStreamHandleClass; -class SoundBufferClass; -class ListenerHandleClass; - - -////////////////////////////////////////////////////////////////////// -// -// SoundHandleClass -// -////////////////////////////////////////////////////////////////////// -class SoundHandleClass -{ -public: - - /////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////// - SoundHandleClass (void); - virtual ~SoundHandleClass (void); - - /////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////// - - // - // RTTI - // - virtual Sound3DHandleClass * As_Sound3DHandleClass (void) { return NULL; } - virtual Sound2DHandleClass * As_Sound2DHandleClass (void) { return NULL; } - virtual SoundStreamHandleClass * As_SoundStreamHandleClass (void) { return NULL; } - virtual ListenerHandleClass * As_ListenerHandleClass (void) { return NULL; } - - // - // Handle access - // - virtual H3DSAMPLE Get_H3DSAMPLE (void) { return NULL; } - virtual HSAMPLE Get_HSAMPLE (void) { return NULL; } - virtual HSTREAM Get_HSTREAM (void) { return NULL; } - - // - // Initialization - // - virtual void Set_Miles_Handle (uint32 handle) = 0; - virtual void Initialize (SoundBufferClass *buffer); - - // - // Sample control - // - virtual void Start_Sample (void) = 0; - virtual void Stop_Sample (void) = 0; - virtual void Resume_Sample (void) = 0; - virtual void End_Sample (void) = 0; - virtual void Set_Sample_Pan (S32 pan) = 0; - virtual S32 Get_Sample_Pan (void) = 0; - virtual void Set_Sample_Volume (S32 volume) = 0; - virtual S32 Get_Sample_Volume (void) = 0; - virtual void Set_Sample_Loop_Count (U32 count) = 0; - virtual U32 Get_Sample_Loop_Count (void) = 0; - virtual void Set_Sample_MS_Position (U32 ms) = 0; - virtual void Get_Sample_MS_Position (S32 *len, S32 *pos) = 0; - virtual void Set_Sample_User_Data (S32 i, U32 val) = 0; - virtual U32 Get_Sample_User_Data (S32 i) = 0; - virtual S32 Get_Sample_Playback_Rate (void) = 0; - virtual void Set_Sample_Playback_Rate (S32 rate) = 0; - -protected: - - /////////////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////// - // Protected member data - /////////////////////////////////////////////////////////////////// - SoundBufferClass * Buffer; -}; - - -#endif //__SOUNDHANDLE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp b/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp deleted file mode 100644 index 8b5533aa76..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.cpp +++ /dev/null @@ -1,366 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/soundstreamhandle.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/23/01 4:47p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "soundstreamhandle.h" -#include "AudibleSound.h" - - -////////////////////////////////////////////////////////////////////// -// -// SoundStreamHandleClass -// -////////////////////////////////////////////////////////////////////// -SoundStreamHandleClass::SoundStreamHandleClass (void) : - SampleHandle ((HSAMPLE)INVALID_MILES_HANDLE), - StreamHandle ((HSTREAM)INVALID_MILES_HANDLE) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// ~SoundStreamHandleClass -// -////////////////////////////////////////////////////////////////////// -SoundStreamHandleClass::~SoundStreamHandleClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Initialize -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Initialize (SoundBufferClass *buffer) -{ - SoundHandleClass::Initialize (buffer); - - if (Buffer != NULL) { - - // - // Create a stream from the sample handle - // - StreamHandle = ::AIL_open_stream_by_sample (WWAudioClass::Get_Instance ()->Get_2D_Driver (), - SampleHandle, buffer->Get_Filename (), 0); - - /*StreamHandle = ::AIL_open_stream (WWAudioClass::Get_Instance ()->Get_2D_Driver (), - buffer->Get_Filename (), 0);*/ - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Start_Sample -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Start_Sample (void) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_start_stream (StreamHandle); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Stop_Sample -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Stop_Sample (void) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_pause_stream (StreamHandle, 1); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Resume_Sample -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Resume_Sample (void) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_pause_stream (StreamHandle, 0); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// End_Sample -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::End_Sample (void) -{ - // - // Stop the sample and then release our hold on the stream handle - // - Stop_Sample (); - - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_close_stream (StreamHandle); - StreamHandle = (HSTREAM)INVALID_MILES_HANDLE; - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Pan -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Sample_Pan (S32 pan) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_set_stream_pan (StreamHandle, pan); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Pan -// -////////////////////////////////////////////////////////////////////// -S32 -SoundStreamHandleClass::Get_Sample_Pan (void) -{ - S32 retval = 0; - - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - retval = ::AIL_stream_pan (StreamHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Volume -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Sample_Volume (S32 volume) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_set_stream_volume (StreamHandle, volume); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Volume -// -////////////////////////////////////////////////////////////////////// -S32 -SoundStreamHandleClass::Get_Sample_Volume (void) -{ - S32 retval = 0; - - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - retval = ::AIL_stream_volume (StreamHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Loop_Count -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Sample_Loop_Count (U32 count) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_set_stream_loop_block (StreamHandle, 0, -1); - ::AIL_set_stream_loop_count (StreamHandle, count); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Loop_Count -// -////////////////////////////////////////////////////////////////////// -U32 -SoundStreamHandleClass::Get_Sample_Loop_Count (void) -{ - U32 retval = 0; - - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_stream_loop_count (StreamHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_MS_Position -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Sample_MS_Position (U32 ms) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_set_stream_ms_position (StreamHandle, ms); - } - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_MS_Position -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Get_Sample_MS_Position (S32 *len, S32 *pos) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_stream_ms_position (StreamHandle, len, pos); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_User_Data -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Sample_User_Data (S32 i, U32 val) -{ - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - ::AIL_set_sample_user_data (SampleHandle, i, val); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_User_Data -// -////////////////////////////////////////////////////////////////////// -U32 -SoundStreamHandleClass::Get_Sample_User_Data (S32 i) -{ - U32 retval = 0; - - if (SampleHandle != (HSAMPLE)INVALID_MILES_HANDLE) { - retval = ::AIL_sample_user_data (SampleHandle, i); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Sample_Playback_Rate -// -////////////////////////////////////////////////////////////////////// -S32 -SoundStreamHandleClass::Get_Sample_Playback_Rate (void) -{ - S32 retval = 0; - - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - retval = ::AIL_stream_playback_rate (StreamHandle); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Sample_Playback_Rate -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Sample_Playback_Rate (S32 rate) -{ - if (StreamHandle != (HSTREAM)INVALID_MILES_HANDLE) { - ::AIL_set_stream_playback_rate (StreamHandle, rate); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Set_Miles_Handle -// -////////////////////////////////////////////////////////////////////// -void -SoundStreamHandleClass::Set_Miles_Handle (uint32 handle) -{ - SampleHandle = (HSAMPLE)handle; - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h b/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h deleted file mode 100644 index 8e09e61455..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWAudio/soundstreamhandle.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwaudio * - * * - * $Archive:: /Commando/Code/WWAudio/soundstreamhandle.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/13/01 3:10p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __SOUNDSTREAMHANDLE_H -#define __SOUNDSTREAMHANDLE_H - - -#include "soundhandle.h" - - -////////////////////////////////////////////////////////////////////// -// -// SoundStreamHandleClass -// -////////////////////////////////////////////////////////////////////// -class SoundStreamHandleClass : public SoundHandleClass -{ -public: - - /////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////// - SoundStreamHandleClass (void); - ~SoundStreamHandleClass (void); - - /////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////// - - // - // RTTI - // - SoundStreamHandleClass * As_SoundStreamHandleClass (void) { return this; } - - // - // Handle access - // - HSAMPLE Get_HSAMPLE (void) { return SampleHandle; } - HSTREAM Get_HSTREAM (void) { return StreamHandle; } - - // - // Inherited - // - void Set_Miles_Handle (uint32 handle); - void Initialize (SoundBufferClass *buffer); - void Start_Sample (void); - void Stop_Sample (void); - void Resume_Sample (void); - void End_Sample (void); - void Set_Sample_Pan (S32 pan); - S32 Get_Sample_Pan (void); - void Set_Sample_Volume (S32 volume); - S32 Get_Sample_Volume (void); - void Set_Sample_Loop_Count (U32 count); - U32 Get_Sample_Loop_Count (void); - void Set_Sample_MS_Position (U32 ms); - void Get_Sample_MS_Position (S32 *len, S32 *pos); - void Set_Sample_User_Data (S32 i, U32 val); - U32 Get_Sample_User_Data (S32 i); - S32 Get_Sample_Playback_Rate (void); - void Set_Sample_Playback_Rate (S32 rate); - -protected: - - /////////////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////// - // Protected member data - /////////////////////////////////////////////////////////////////// - HSAMPLE SampleHandle; - HSTREAM StreamHandle; -}; - - -#endif //__SOUNDSTREAMHANDLE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt index 3b804d6824..b55deed164 100644 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt +++ b/Generals/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt @@ -1,25 +1,8 @@ -# Set source files -set(WWDOWNLOAD_SRC - Download.cpp - Download.h - DownloadDebug.h - downloaddefs.h - FTP.CPP - ftp.h - ftpdefs.h - registry.cpp - Registry.h - urlBuilder.cpp - urlBuilder.h -) - -# Targets to build. add_library(g_wwdownload STATIC) set_target_properties(g_wwdownload PROPERTIES OUTPUT_NAME wwdownload) -target_sources(g_wwdownload PRIVATE ${WWDOWNLOAD_SRC}) - target_link_libraries(g_wwdownload PRIVATE - g_wwcommon + corei_wwdownload + gi_always gi_gameengine_include ) diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/Download.cpp b/Generals/Code/Libraries/Source/WWVegas/WWDownload/Download.cpp deleted file mode 100644 index a8b923249c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/Download.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Download.cpp : Implementation of CDownload -#include "DownloadDebug.h" -#include "Download.h" -#include -#include -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////////////// -// CDownload - - -// -// Kick off a download - copys the parameters for the download to the appropriate -// data members, then sets the status flag to start the download when PumpMessages() -// is called. -// - -HRESULT CDownload::DownloadFile(LPCSTR server, LPCSTR username, LPCSTR password, LPCSTR file, LPCSTR localfile, LPCSTR regkey, bool tryresume) -{ - // Check we're not in the middle of another download. - if((m_Status != DOWNLOADSTATUS_DONE ) && (m_Status != DOWNLOADSTATUS_FINDINGFILE)) - { - return( DOWNLOAD_STATUSERROR ); - } - - // If we're still connected, make sure we're on the right server - if (m_Status == DOWNLOADSTATUS_FINDINGFILE) - { - if ((strcmp(m_Server, server)) || (strcmp(m_Login, username))) - { - // Damn, a server switch. Close conn & fix state - m_Ftp->DisconnectFromServer(); - m_Status=DOWNLOADSTATUS_DONE; - } - } - - // Check all parameters are non-null. - - if( ( server == NULL ) || ( username == NULL ) || - ( password == NULL ) || ( file == NULL ) || - ( localfile == NULL ) || ( regkey == NULL ) ) - { - //////////DBGMSG("Download Paramerror"); - return( DOWNLOAD_PARAMERROR ); - } - - // Make sure we have a download directory - _mkdir("download"); - - // Copy parameters to member variables. - strncpy( m_Server, server, sizeof( m_Server ) ); - strncpy( m_Login, username, sizeof( m_Login ) ); - strncpy( m_Password, password, sizeof( m_Password ) ); - strncpy( m_File, file, sizeof( m_File ) ); - strncpy( m_LocalFile, localfile, sizeof( m_LocalFile ) ); - - strncpy( m_LastLocalFile, localfile, sizeof( m_LastLocalFile ) ); - - strncpy( m_RegKey, regkey, sizeof( m_RegKey ) ); - m_TryResume = tryresume; - m_StartPosition=0; - -/********* - // figure out file offset - if (m_TryResume == false) - { - m_StartPosition=0; - } - else if(( m_StartPosition = m_Ftp->FileRecoveryPosition( m_LocalFile, m_RegKey ) ) != 0 ) - { - if( Listener->OnQueryResume() == DOWNLOADEVENT_DONOTRESUME ) - { - m_Ftp->RestartFrom( 0 ); - m_StartPosition = 0; - } - } -************/ - - // Set status so we start to connect at the next PumpMessages() - if (m_Status != DOWNLOADSTATUS_FINDINGFILE) - m_Status = DOWNLOADSTATUS_GO; - - //////////DBGMSG("Ready to download"); - return S_OK; -} - - -// -// Get the local filename of the last file we requested to download.... -// -HRESULT CDownload::GetLastLocalFile(char *local_file, int maxlen) { - if (local_file==0) - return(E_FAIL); - - strncpy(local_file, m_LastLocalFile, maxlen); - local_file[maxlen-1]=0; - - return(S_OK); -} - - -// -// Abort the current download - disconnects from the server and sets the -// status flag to stop PumpMessages() from doing anything. -// - -HRESULT CDownload::Abort() -{ - - if( m_Status != DOWNLOADSTATUS_NONE ) - { - m_Ftp->DisconnectFromServer(); - m_Status = DOWNLOADSTATUS_NONE; - } - - m_TimeStarted = 0; - m_StartPosition = 0; - m_FileSize = 0; - m_BytesRead = 0; - m_Server[ 0 ] = '\0'; - m_Login[ 0 ] = '\0'; - m_Password[ 0 ] = '\0'; - m_File[ 0 ] = '\0'; - m_LocalFile[ 0 ] = '\0'; - m_RegKey[ 0 ] = '\0'; - - return S_OK; -} - - -// -// PumpMessages() does all the work - checks for possible resumption of a previous -// download, connects to the server, finds the file and downloads it. -// - -HRESULT CDownload::PumpMessages() -{ - int iResult = 0; - int timetaken = 0; - int averagetimepredicted = -1; - static int reenter = 0; - - /* Avoid reentrancy. */ - - ////DBGMSG("Download Pump"); - - if( reenter != 0 ) - { - return( DOWNLOAD_REENTERERROR ); - } - - reenter = 1; - - - if( m_Status == DOWNLOADSTATUS_GO ) - { - // Check to see whether the file already exists locally - -/*********** - if (m_TryResume == false) - { - m_StartPosition = 0; - } - else if( ( m_StartPosition = m_Ftp->FileRecoveryPosition( m_LocalFile, m_RegKey ) ) != 0 ) - { - if( Listener->OnQueryResume() == DOWNLOADEVENT_DONOTRESUME ) - { - m_Ftp->RestartFrom( 0 ); - m_StartPosition = 0; - } - } -************/ - - // Tell the client that we're starting to connect. - - Listener->OnStatusUpdate( DOWNLOADSTATUS_CONNECTING ); - - m_Status = DOWNLOADSTATUS_CONNECTING; - } - - - if( m_Status == DOWNLOADSTATUS_CONNECTING ) - { - // Connect to the server - //////////DBGMSG("Connect to Server"); - - iResult = m_Ftp->ConnectToServer( m_Server ); - ////////////DBGMSG("out of FTP connect"); - - if( iResult == FTP_SUCCEEDED ) - { - m_Status = DOWNLOADSTATUS_LOGGINGIN; - } - else - { - if( iResult == FTP_FAILED ) - { - // Tell the client we couldn't connect - ///////////DBGMSG("Couldn't connect"); - Listener->OnError( DOWNLOADEVENT_COULDNOTCONNECT ); - reenter = 0; - return DOWNLOAD_NETWORKERROR; - } - } - reenter = 0; - return DOWNLOAD_SUCCEEDED; - } - - if( m_Status == DOWNLOADSTATUS_LOGGINGIN ) - { - // Login to the server - ////////////DBGMSG("Login to server"); - - iResult = m_Ftp->LoginToServer( m_Login, m_Password ); - - if( iResult == FTP_SUCCEEDED ) - { - Listener->OnStatusUpdate( DOWNLOADSTATUS_FINDINGFILE ); - m_Status = DOWNLOADSTATUS_FINDINGFILE; - } - - if( iResult == FTP_FAILED ) - { - // Tell the client we couldn't log in - - Listener->OnError( DOWNLOADEVENT_LOGINFAILED ); - reenter = 0; - return( DOWNLOAD_NETWORKERROR ); - } - - reenter = 0; - return DOWNLOAD_SUCCEEDED; - } - - if(( m_Status == DOWNLOADSTATUS_FINDINGFILE ) && (strlen(m_File))) - { - - // Find the file on the server - ///////////DBGMSG("Find File"); - - if( m_Ftp->FindFile( m_File, &m_FileSize ) == FTP_FAILED ) - { - // Tell the client we couldn't find the file - - Listener->OnError( DOWNLOADEVENT_NOSUCHFILE ); - reenter = 0; - return( DOWNLOAD_FILEERROR ); - } - - if( m_FileSize > 0 ) - { - // First check to see if we already have the complete file in the proper dest location... - // - // Note, we will only skip the download if the file is a patch. Patch files should - // never ever change so this is not a concern. - // - // We identify patches because they are written into the patches folder. - struct _stat statdata; - if ( (_stat(m_LocalFile, &statdata) == 0) && - (statdata.st_size == m_FileSize) && - (_strnicmp(m_LocalFile, "patches\\", strlen("patches\\"))==0)) { - // OK, no need to download this again.... - - m_Status = DOWNLOADSTATUS_FINDINGFILE; // ready to find another file - m_TimeStarted = 0; - m_StartPosition = 0; - m_FileSize = 0; - m_BytesRead = 0; - m_File[ 0 ] = '\0'; - m_LocalFile[ 0 ] = '\0'; - - Listener->OnEnd(); - - reenter = 0; - return DOWNLOAD_SUCCEEDED; - } - - - // - // Check if we can do a file resume - // - if (m_TryResume == false) - { - m_StartPosition = 0; - } - else if( ( m_StartPosition = m_Ftp->FileRecoveryPosition( m_LocalFile, m_RegKey ) ) != 0 ) - { - if( Listener->OnQueryResume() == DOWNLOADEVENT_DONOTRESUME ) - { - m_Ftp->RestartFrom( 0 ); - m_StartPosition = 0; - } - } - // end resume check - - - m_Status = DOWNLOADSTATUS_DOWNLOADING; - - // Tell the client we're starting to download - - Listener->OnStatusUpdate( DOWNLOADSTATUS_DOWNLOADING ); - } - - reenter = 0; - return DOWNLOAD_SUCCEEDED; - } - - if( m_Status == DOWNLOADSTATUS_DOWNLOADING ) - { - - // Get the next chunk of the file - ///DBGMSG("Get Next File Block"); - - iResult = m_Ftp->GetNextFileBlock( m_LocalFile, &m_BytesRead ); - - if( m_TimeStarted == 0 ) - { - // This is the first time through here - record the starting time. - m_TimeStarted = timeGetTime(); - } - - if( iResult == FTP_SUCCEEDED ) - { - m_Status = DOWNLOADSTATUS_FINISHING; - } - else - { - if( iResult == FTP_FAILED ) - { - Listener->OnError( DOWNLOADEVENT_TCPERROR ); - reenter = 0; - return( DOWNLOAD_NETWORKERROR ); - } - } - - // Calculate time taken so far, and predict how long there is left. - // The prediction returned is the average of the last 8 predictions. - - timetaken = ( timeGetTime() - m_TimeStarted ) / 1000; - - //////////if( m_BytesRead > 0 ) // NAK - RP said this is wrong - if( ( m_BytesRead - m_StartPosition ) > 0 ) - { - // Not the first read. - int predictionIndex = ( m_predictions++ ) & 0x7; - m_predictionTimes[ predictionIndex ] = MulDiv( timetaken, (m_FileSize - m_BytesRead), (m_BytesRead - m_StartPosition) ); - //__int64 numerator = ( m_FileSize - m_BytesRead ) * timetaken; - //__int64 denominator = ( m_BytesRead - m_StartPosition ); - //m_predictionTimes[ predictionIndex ] = numerator/denominator; - //m_predictionTimes[ predictionIndex ] = ( ( m_FileSize - m_BytesRead ) * timetaken ) / ( m_BytesRead - m_StartPosition ); - //m_predictionTimes[ predictionIndex ] = ( ( m_FileSize - m_BytesRead ) / ( m_BytesRead - m_StartPosition ) * timetaken ); - - DEBUG_LOG(("About to OnProgressUpdate() - m_FileSize=%d, m_BytesRead=%d, timetaken=%d, numerator=%d", - m_FileSize, m_BytesRead, timetaken, ( ( m_FileSize - m_BytesRead ) * timetaken ))); - DEBUG_LOG((", m_startPosition=%d, denominator=%d, predictionTime=%d\n", - m_StartPosition, ( m_BytesRead - m_StartPosition ), predictionIndex)); - DEBUG_LOG(("vals are %d %d %d %d %d %d %d %d\n", - m_predictionTimes[ 0 ], m_predictionTimes[ 1 ], m_predictionTimes[ 2 ], m_predictionTimes[ 3 ], - m_predictionTimes[ 4 ], m_predictionTimes[ 5 ], m_predictionTimes[ 6 ], m_predictionTimes[ 7 ])); - - if( m_predictions > 8 ) - { - // We've had enough time to build up a few predictions, so calculate - // an average. - averagetimepredicted = ( m_predictionTimes[ 0 ] + m_predictionTimes[ 1 ] + - m_predictionTimes[ 2 ] + m_predictionTimes[ 3 ] + - m_predictionTimes[ 4 ] + m_predictionTimes[ 5 ] + - m_predictionTimes[ 6 ] + m_predictionTimes[ 7 ] ) / 8; - } - else - { - // Wait a while longer before passing a "real" prediction - averagetimepredicted = -1; - } - - } - else - { - averagetimepredicted = -1; - } - - // Update the client's progress bar (or whatever) - - Listener->OnProgressUpdate( m_BytesRead, m_FileSize, timetaken, averagetimepredicted + 1); - } - - - if( m_Status == DOWNLOADSTATUS_FINISHING ) - { - if (m_Ftp->m_iCommandSocket) - m_Status = DOWNLOADSTATUS_FINDINGFILE; // ready to find another file - else - m_Status = DOWNLOADSTATUS_DONE; // command channel closed, connect again... - - m_TimeStarted = 0; - m_StartPosition = 0; - m_FileSize = 0; - m_BytesRead = 0; - m_File[ 0 ] = '\0'; - m_LocalFile[ 0 ] = '\0'; - - Listener->OnEnd(); - } - - reenter = 0; - return DOWNLOAD_SUCCEEDED; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/Download.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/Download.h deleted file mode 100644 index 2434c951a4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/Download.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Download.h : Declaration of the CDownload - -#ifndef __DOWNLOAD_H_ -#define __DOWNLOAD_H_ - -//#include "../resource.h" // main symbols -#include "WWDownload/ftp.h" -#include "WWDownload/downloaddefs.h" - -///////////////////////////////////////////////////////////////////////////// -// CDownload - -class IDownload -{ - public: - virtual HRESULT OnError( int error )=0; - virtual HRESULT OnEnd()=0; - virtual HRESULT OnQueryResume()=0; - virtual HRESULT OnProgressUpdate(int bytesread, int totalsize, int timetaken, int timeleft)=0; - virtual HRESULT OnStatusUpdate(int status)=0; -}; - -class CDownload -{ -public: - CDownload(IDownload *listener) : - Listener(listener) - { - m_Status = DOWNLOADSTATUS_NONE; - m_TimeStarted = 0; - m_StartPosition = 0; - m_FileSize = 0; - m_BytesRead = 0; - m_Server[ 0 ] = '\0'; - m_Login[ 0 ] = '\0'; - m_Password[ 0 ] = '\0'; - m_File[ 0 ] = '\0'; - m_LocalFile[ 0 ] = '\0'; - m_RegKey[ 0 ] = '\0'; - m_Ftp = new( Cftp ); - m_TryResume = false; - - m_predictions = 0; - for (int i=0; i<8; ++i) - { - m_predictionTimes[i] = 0; - } - } - ~CDownload() { delete m_Ftp; } - -public: - virtual HRESULT PumpMessages(); - virtual HRESULT Abort(); - virtual HRESULT DownloadFile(LPCSTR server, LPCSTR username, LPCSTR password, LPCSTR file, LPCSTR localfile, LPCSTR regkey, bool tryresume=true); - virtual HRESULT GetLastLocalFile(char *local_file, int maxlen); - -private: - char m_Server[ 256 ]; - char m_Login[ 64 ]; - char m_Password[ 64 ]; - char m_File[ 256 ]; - char m_LocalFile[ 256 ]; - - char m_LastLocalFile[ 256 ]; - - char m_RegKey[ 256 ]; - int m_Status; - int m_TimeStarted; - int m_StartPosition; - int m_FileSize; - int m_BytesRead; - bool m_TryResume; - - int m_predictions; - int m_predictionTimes[8]; - - Cftp *m_Ftp; - IDownload *Listener; -}; - -#endif //__DOWNLOAD_H_ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h deleted file mode 100644 index 7f54664f73..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/DownloadDebug.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// DownloadDebug.h - -#ifndef __DOWNLOADDEBUG_H_ -#define __DOWNLOADDEBUG_H_ - -#include "Common/Debug.h" - -#endif //__DOWNLOADDEBUG_H_ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/FTP.CPP b/Generals/Code/Libraries/Source/WWVegas/WWDownload/FTP.CPP deleted file mode 100644 index 8741b59801..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/FTP.CPP +++ /dev/null @@ -1,1847 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// ftp.cpp : Implementation of Cftp - -/*************************************************************************/ -/*_$ Include Files */ -/*************************************************************************/ - - -#include -#include -#include -#include -#include -#include -#include -#include -#include "assert.h" -#include "ftp.h" -#include -#include -#include -//#include "wlib/wstring.h" - -#include "DownloadDebug.h" - -// umm... what?? BGC 3/27/03 -//#ifndef _DEBUG -//#define _DEBUG -//#endif - -/*************************************************************************/ -/*_$ External References */ -/*************************************************************************/ - -/*************************************************************************/ -/*_$ Private Datatypes */ -/*************************************************************************/ - -/*************************************************************************/ -/*_$ Public Data */ -/*************************************************************************/ - -/*************************************************************************/ -/*_$ Private Data */ -/*************************************************************************/ - -//static HOSTENT gThreadHost; -struct sockaddr_in gThreadAddress; - -static int gThreadFlag; - -/*************************************************************************/ -/*_$ Private Prototypes */ -/*************************************************************************/ - -/*************************************************************************/ -/*_$ Private Macros */ -/*************************************************************************/ - - -/* Status flags */ - -#define FTPSTAT_INIT 0 -#define FTPSTAT_CONNECTING 10 -#define FTPSTAT_WAITINGSERVEROK 15 -#define FTPSTAT_CONNECTED 20 -#define FTPSTAT_SENDINGUSER 30 -#define FTPSTAT_SENTUSER 40 -#define FTPSTAT_SENDINGPASS 50 -#define FTPSTAT_LOGGEDIN 60 -#define FTPSTAT_LOGGINGOFF 70 -#define FTPSTAT_SENDINGQUIT 80 -#define FTPSTAT_SENTQUIT 90 -#define FTPSTAT_FILEFOUND 100 -#define FTPSTAT_SENDINGCWD 110 -#define FTPSTAT_SENTCWD 120 -#define FTPSTAT_SENTPORT 130 -#define FTPSTAT_SENDINGLIST 140 -#define FTPSTAT_SENTLIST 150 -#define FTPSTAT_LISTDATAOPEN 160 -#define FTPSTAT_LISTDATARECVD 170 -#define FTPSTAT_FILEOPEN 180 -#define FTPSTAT_SENTFILEPORT 190 -#define FTPSTAT_SENDINGTYPE 200 -#define FTPSTAT_SENTTYPE 210 -#define FTPSTAT_SENDINGREST 220 -#define FTPSTAT_SENTREST 230 -#define FTPSTAT_SENDINGRETR 240 -#define FTPSTAT_SENTRETR 250 -#define FTPSTAT_FILEDATAOPEN 260 -#define FTPSTAT_FILEDATACLOSED 270 -#define FTPSTAT_TRANSFERREPLY 280 - - -// Utility functions -bool Prepare_Directories(const char *rootdir, const char *filename); - -// -// This is here as a hack... -// Some firewalls break the TCP stack so non-blocking sockets don't work right... -// -static bool Use_Non_Blocking_Mode(void) -{ - HKEY regKey; - LONG regRetval; - DWORD bufsiz=0; - DWORD type=0; - DWORD value=0; - - - // Try and open the named key - regRetval=RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Westwood\\Earth And Beyond Beta 2",0,KEY_READ,®Key); - if (regRetval!=ERROR_SUCCESS) - return(TRUE); // default TRUE - - // Fetch the flag - bufsiz=sizeof(value); - type=REG_DWORD; - regRetval=RegQueryValueEx(regKey, "UseNonBlockingFTP", 0, &type, (BYTE*) &value, &bufsiz); - - RegCloseKey(regKey); - - if ((regRetval!=ERROR_SUCCESS) || (type != REG_DWORD)) - return(TRUE); - - return(bool(value)); -} - - - - -///////////////////////////////////////////////////////////////////////////// -// Cftp - - -/*$_Function**************************************************************** -* $_Name : -* Cftp::Cftp() -* -* $_Description : -* Constructor for the ftp class - initialises more or less all data -* members to zero. -* -* $_Parameters : -* None. -* -* $_ReturnValue : -* None. -* -***************************************************************************/ - - -Cftp::Cftp() -{ - ZeroStuff(); -} - - - - -/*$_Function**************************************************************** -* $_Name : -* Cftp::Cftp() -* -* $_Description : -* Destructor for the ftp class - close sockets behind us as we leave. -* -* $_Parameters : -* None. -* -* $_ReturnValue : -* None. -* -***************************************************************************/ - - -Cftp::~Cftp() -{ - CloseSockets(); - - if (m_pfLocalFile) - { - fclose(m_pfLocalFile); - m_pfLocalFile = NULL; - } -} - -void Cftp::CloseSockets(void) -{ - - if( m_iDataSocket ) - { - closesocket( m_iDataSocket ); - m_iDataSocket=0; - } - - if( m_iCommandSocket ) - { - closesocket( m_iCommandSocket ); - m_iCommandSocket=0; - } - -} - -void Cftp::ZeroStuff(void) -{ - m_iBytesRead = 0; - m_iFileSize = 0; - m_szRemoteFilePath[ 0 ] = (char)0; - m_szRemoteFileName[ 0 ] = (char)0; - m_szLocalFilePath[ 0 ] = (char)0; - m_szLocalFileName[ 0 ] = (char)0; - m_szServerName[ 0 ] = (char)0; - m_szUserName[ 0 ] = (char)0; - m_szPassword[ 0 ] = (char)0; - m_iDataSocket = 0; - m_iCommandSocket = 0; - m_iFilePos = 0; - m_iStatus = FTPSTAT_INIT; - m_sendNewPortStatus = 0; - m_pfLocalFile = NULL; - m_findStart = 0; - memset(&m_CommandSockAddr, 0, sizeof(m_CommandSockAddr)); - memset(&m_DataSockAddr, 0, sizeof(m_DataSockAddr)); -} - - -DWORD WINAPI gethostbynameA( void * szName ) -{ - HOSTENT *he = gethostbyname( (const char *)szName ); - //////DBGMSG("Hostname copy start"); - - if (he) - memcpy((char *)&(gThreadAddress.sin_addr), he->h_addr, he->h_length ); - else - memcpy((char *)&(gThreadAddress.sin_addr),"",strlen("")+1); - /////DBGMSG("Hostname copy complete"); - - gThreadFlag = 1; - return 0; -} - - -int Cftp::AsyncGetHostByName(char * szName, struct sockaddr_in &address ) -{ - static int stat = 0; - static unsigned long threadid; - - if( stat == 0 ) - { - /* Kick off gethostname thread */ - gThreadFlag = 0; - memset(&gThreadAddress,0,sizeof(gThreadAddress)); - - if( CreateThread( NULL, 0, gethostbynameA, szName, 0, &threadid ) == NULL ) - { - return( FTP_FAILED ); - } - stat = 1; - } - if( stat == 1 ) - { - if( gThreadFlag ) - { - /* Thread finished */ - address = gThreadAddress; - address.sin_family=AF_INET; - stat = 0; - return( FTP_SUCCEEDED ); - } - } - - return( FTP_TRYING ); -} - - - - - - -/*$_Function**************************************************************** -* $_Name : -* HRESULT Cftp::ConnectToServer(LPCSTR szServerName) -* -* $_Description : -* Overloaded funciton that makes a connection to a server. Will probably -* fail on (at least) the first call, as it may take a while for the server -* to send it's "ready" reply. -* -* $_Parameters : -* -> const char * szServerName -* Optionally, the name of the server to connect to. This must be specified -* in the first call to the function. -* -* $_ReturnValue : -* FTP_TRYING until the connection has succeeded, then FTP_SUCCEEDED. -* FTP_FAILED on error. -* -***************************************************************************/ - - -HRESULT Cftp::ConnectToServer(LPCSTR szServerName) -{ - struct sockaddr_in address; - unsigned long uTemp; - unsigned long serverIP; - char buffer[ 256 ]; - int iReply, error; - - strncpy( m_szServerName, szServerName, 128 ); - - if( m_iStatus == FTPSTAT_INIT ) - { - /* Find the IP address of the server */ - - serverIP = inet_addr( m_szServerName ); - - memset( &m_CommandSockAddr, 0, sizeof( m_CommandSockAddr ) ); - m_CommandSockAddr.sin_family = AF_INET; - - if( serverIP == INADDR_NONE ) - { - /* It's an FQDN - hopefully. */ - ////////DBGMSG("Async gethostbyname"); - if( AsyncGetHostByName( m_szServerName, address ) == FTP_TRYING ) - { - return( FTP_TRYING ); - } - //////DBGMSG("Got hostbyname"); - - if( address.sin_addr.s_addr == 0 ) - { - ///////DBGMSG("gethostbyname failed"); - return( FTP_FAILED ); - } - - m_CommandSockAddr=address; - - ///////memcpy( (char *)&(m_CommandSockAddr.sin_addr), he.h_addr, he.h_length ); - - serverIP = m_CommandSockAddr.sin_addr.s_addr; - //////DBGMSG("ServerIP = "< LPCSTR szUserName -* The username under which to log in. -* -* -> LPCSTR szPassword -* The password to use. -* -* $_ReturnValue : -* FTP_TRYING until the login has succeeded, then FTP_SUCCEEDED. -* FTP_FAILED on error. -* -***************************************************************************/ - - -HRESULT Cftp::LoginToServer( LPCSTR szUserName, LPCSTR szPassword ) -{ - char command[ 256 ]; - int iReply; - - strncpy( m_szUserName, szUserName, 128 ); - strncpy( m_szPassword, szPassword, 128 ); - - memset( command, 0, 256 ); - - if( m_iStatus == FTPSTAT_CONNECTED ) - { - sprintf( command, "USER %s\r\n", m_szUserName ); - - if( SendCommand( command, 7 + strlen( m_szUserName ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGUSER; - } - - if( m_iStatus == FTPSTAT_SENDINGUSER ) - { - if(RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) - return( FTP_TRYING ); - - if (iReply != FTPREPLY_PASSWORD) - return( FTP_FAILED ); - - m_iStatus = FTPSTAT_SENTUSER; - } - - if( m_iStatus == FTPSTAT_SENTUSER ) - { - sprintf( command, "PASS %s\r\n", m_szPassword ); - - if( SendCommand( command, 7 + strlen( m_szPassword ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGPASS; - } - - if( m_iStatus == FTPSTAT_SENDINGPASS ) - { - if( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) - { - return( FTP_TRYING ); - } - - if( iReply != FTPREPLY_LOGGEDIN ) - { - if( iReply == FTPREPLY_CONTROLCLOSED ) - { - return( FTP_FAILED ); - } - - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_LOGGEDIN; - - return( FTP_SUCCEEDED ); - } - - return( FTP_FAILED ); -} - - -/*$_Function**************************************************************** -* $_Name : -* STDMETHOD Cftp::LogoffFromServer( void ) -* -* $_Description : -* Logs off from a server. LoginToServer() must have succeeded before this -* call is made. -* -* $_Parameters : -* None. -* -* $_ReturnValue : -* FTP_TRYING until the logoff has succeeded, then FTP_SUCCEEDED. -* FTP_FAILED on error. -* -***************************************************************************/ - - -HRESULT Cftp::LogoffFromServer( void ) -{ - char command[ 256 ]; - int iReply, iRetCode; - - memset( command, 0, 256 ); - - switch( m_iStatus ) - { - case FTPSTAT_LOGGINGOFF: - if( SendCommand( "QUIT\r\n", 6 ) == FTP_SUCCEEDED ) - { - m_iStatus = FTPSTAT_SENDINGQUIT; - } - else - { - return( FTP_FAILED ); - } - - case FTPSTAT_SENDINGQUIT: - { - char buf[ 50 ]; - - if( ( iReply = RecvReply( buf, 50, &iRetCode ) ) == FTP_SUCCEEDED ) - { - if( iRetCode == 221 ) - { - //m_iStatus = FTPSTAT_SENTQUIT; - - //m_iStatus = FTPSTAT_INIT; // NAK - - CloseSockets(); - ZeroStuff(); - - return( FTP_SUCCEEDED ); - } - } - else - { - if( iReply == FTP_FAILED ) - { - return( FTP_FAILED ); - } - return( FTP_TRYING ); - } - } - - default: - m_iStatus = FTPSTAT_LOGGINGOFF; - return( FTP_TRYING ); - - } - -} - - - - - - -/*$_Function**************************************************************** -* $_Name : -* HRESULT Cftp::FindFile( LPCSTR szRemoteFileName, int * piSize ) -* -* $_Description : -* Locates a file on the remote server. -* -* $_Parameters : -* -> LPCSTR szRemoteFileName -* Full path and file name of the file to be downloaded. -* -* <- int * piSize -* A pointer to an integer in which to return the size of the file, in bytes. -* -* $_ReturnValue : -* FTP_SUCCEEDED on success. Otherwise FTP_TRYING, or FTP_FAILED on error. -* -* $_Warnings : -* This function will continue to return FTP_TRYING if the file does not exist on -* the server. -* -***************************************************************************/ - - - -HRESULT Cftp::FindFile( LPCSTR szRemoteFileName, int * piSize ) -{ - char command[ 256 ]; - static char listline[ 256 ]; - - int i, iReply; - char ext[ 10 ]; - - if (m_findStart==0) - m_findStart=time(NULL); - - if((time(NULL)-m_findStart) > 30) // try for 30 seconds - { - /////////DBGMSG("FindFile: Tried for too long"); - m_findStart=0; - return( FTP_FAILED ); - } - - //strcpy(m_szRemoteFilePath, "/"); // start at home - _splitpath( szRemoteFileName, NULL, m_szRemoteFilePath+strlen(m_szRemoteFilePath), - m_szRemoteFileName, ext ); - - strcat( m_szRemoteFileName, ext ); - - for( i = 0; i < (int)strlen( m_szRemoteFilePath ); i++ ) - { - if( m_szRemoteFilePath[ i ] == '\\' ) - { - m_szRemoteFilePath[ i ] = '/'; - } - } - - memset( command, 0, 256 ); - - /* Change directory */ - - if( ( m_iStatus == FTPSTAT_LOGGEDIN ) || ( m_iStatus == FTPSTAT_FILEFOUND ) ) - { - sprintf( command, "CWD %s\r\n", m_szRemoteFilePath ); - - if( SendCommand( command, 6 + strlen( m_szRemoteFilePath ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGCWD; - } - - - /* Get reply */ - - if( m_iStatus == FTPSTAT_SENDINGCWD ) - { - HRESULT reply=RecvReply( command, 256, &iReply ); - - if ((reply == FTP_SUCCEEDED) && (iReply == 550)) { - m_findStart=0; - return(FTP_FAILED); - } - - if( ( reply != FTP_SUCCEEDED ) || - ( iReply != FTPREPLY_CWDOK ) ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENTCWD; - } - - /* Set up data connection port */ - - if( m_iStatus == FTPSTAT_SENTCWD ) - { - i = 0; - while( SendNewPort() == FTP_TRYING ) - { - i++; - - if( i == 1000 ) - { - return( FTP_TRYING ); - } - } - - m_iStatus = FTPSTAT_SENTPORT; - } - - /* Get directory listing for file. */ - - if( m_iStatus == FTPSTAT_SENTPORT ) - { - sprintf( command, "LIST %s\r\n", m_szRemoteFileName ); - - if( SendCommand( command, 7 + strlen( m_szRemoteFileName ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGLIST; - } - - - /* Get reply */ - - if( m_iStatus == FTPSTAT_SENDINGLIST ) - { - if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) || - ( iReply != FTPREPLY_OPENASCII ) ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENTLIST; - } - - /* Open data connection */ - - if( m_iStatus == FTPSTAT_SENTLIST ) - { - i = OpenDataConnection(); - if( i != FTP_SUCCEEDED ) - { - /////////DBGMSG("FindFile: OpenDataConnection failed: "< 0 ) - { -#ifdef _DEBUG - OutputDebugString( "-->" ); - OutputDebugString( pCommand ); -#endif - return( FTP_SUCCEEDED ); - } - else - { - return( FTP_FAILED ); - } -} - - - - -/*$_Function**************************************************************** -* $_Name : -* HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode ) -* -* $_Description : -* Receives a reply from the server and extracts the numerical reply -* code. -* -* $_Parameters : -* -> LPCSTR pReplyBuffer -* A buffer for the reply - must be specified and be at least 4 bytes in -* length. -* -* -> iSize -* The size of the reply buffer. -* -* <- piRetCode -* A pointer to an integer to store the numeric return code for the message received. -* -* $_ReturnValue : -* FTP_SUCCEEDED on success, FTP_FAILED otherwise. -* -***************************************************************************/ - - -HRESULT Cftp::RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode ) -{ - int readval; - char * pc = (char *)pReplyBuffer; - - while(1) { - // Preview whats on the socket so we can make the decision if there is enough - // there to use. - readval = recv(m_iCommandSocket, pc, iSize-1, MSG_PEEK); - pc[iSize-1]=0; - if (readval > 0) - pc[readval]=0; - - // Did the endpoint close? - if (readval < 0) { - if ((WSAGetLastError() == WSAECONNRESET ) || ((WSAGetLastError() == WSAENOTCONN))) - readval=0; - else { - // nothing to read right now.... - return(FTP_TRYING); - } - } - - if (readval == 0) { - // endpoint closed - *piRetCode=FTPREPLY_CONTROLCLOSED; - return(FTP_SUCCEEDED); // we succeeded in getting a reply - } - - if (readval < 3) // minimal response - return(FTP_TRYING); - - // Verify that this is a complete line, if not we will keep trying til - // we have one. - char *end=strstr(pc, "\r\n"); - if (end == 0) - return(FTP_TRYING); - - // OK, we've got a line, pull it from the socket... - recv(m_iCommandSocket, pc, end-pc+strlen("\r\n"), 0); -#ifdef _DEBUG - OutputDebugString( "<--" ); - OutputDebugString( pc ); -#endif - - // Is this an unrecognized command? It's probably in response to our BOGUSCOMMAND, ignore it. - // If we got this for some other reason then this FTP server doesn't support our required command set. - // If this were a general purpose FTP library we probably couldn't get away with this because it's pretty lame. - const char *BOGUS_RESPONSE="500"; - if (_strnicmp(pc, BOGUS_RESPONSE, strlen(BOGUS_RESPONSE))==0) - continue; - - // If the line starts with a non-digit then we ignore it... - if (isdigit(pc[0])==0) - continue; - - if (piRetCode) - *piRetCode=atol(pc); - - return( FTP_SUCCEEDED ); - } -} - - -/*$_Function**************************************************************** -* $_Name : -* unsigned long MyIPAddress( int sockfd ) -* -* $_Description : -* Finds the IP address of the local host. -* -* $_Parameters : -* -> int sockfd -* An optional socket descriptor - if this is given and the socket is connected -* then the answer will guaranteed to be on the same interface as the connected -* socket. -* -* $_ReturnValue : -* A unsigned integer containing the IP address of the local host. -* -***************************************************************************/ - - -unsigned long MyIPAddress( int sockfd ) -{ - - int test = 99; - int i; - char pBuffer[ 256 ]; - char * pAddr; - struct hostent * pHE; - unsigned long ip; - struct sockaddr_in sin; - - if( sockfd != -1 ) - { - i = sizeof( sin ); - getsockname( sockfd, (struct sockaddr *)&sin, &i ); - - ip = sin.sin_addr.S_un.S_addr; - } - else - { - /* Get this machine's name. */ - - if( gethostname( pBuffer, 256 ) != 0 ) - { - return( FTP_FAILED ); - } - - /* Look up the machine in "DNS" or whatever. */ - - pHE = gethostbyname( pBuffer ); - - if( pHE == NULL ) - { - return( FTP_FAILED ); - } - - /* Find a good IP address. */ - - ip = 0; - - i = 0; - - while( ( pAddr = pHE->h_addr_list[ i++ ] ) != NULL ) - { - - ip = *((unsigned long *)pAddr ); - - if( ( ip != 0 ) && ( ip != inet_addr( "127.0.0.1" ) ) ) - { - break; - } - else - { - ip = 0; - } - - } - } - - if( ip == 0 ) - { - return( FTP_FAILED ); - } - - - return( ip ); -} - - - -/*$_Function**************************************************************** -* $_Name : -* int Cftp::SendNewPort( void ) -* -* $_Description : -* Sends a PORT command to the server specifying a new ephemeral port to -* use for a data connection. Opens the port in the process. -* -* $_Parameters : -* bool reset -* Should be TRUE for the first attempt, FALSE subsequently. -* -* $_ReturnValue : -* FTP_SUCCEEDED on success, FTP_FAILED on error, FTP_TRYING while -* going through the stages. -* -***************************************************************************/ - - -int Cftp::SendNewPort( void ) -{ - unsigned long uTemp; - char command[ 256 ]; - int i, iReply; - - /* Open a socket */ - - if( m_sendNewPortStatus == 0 ) - { - - m_iDataSocket = socket( AF_INET, SOCK_STREAM, 0 ); - - if( m_iDataSocket < 0 ) - { - return( FTP_FAILED ); - } - - /* Set socket to non-blocking */ - - uTemp = 1; - - if (Use_Non_Blocking_Mode()) { - if( ioctlsocket( m_iCommandSocket, FIONBIO, &uTemp ) == SOCKET_ERROR ) - { - return( FTP_FAILED ); - } - } - - memset( &m_DataSockAddr, 0, sizeof( m_DataSockAddr ) ); - - m_DataSockAddr.sin_family = AF_INET; - m_DataSockAddr.sin_addr.s_addr = htonl( INADDR_ANY ); - m_DataSockAddr.sin_port = 0; // Winsock fills in an ephemeral port during bind... - - if( bind( m_iDataSocket, (struct sockaddr *)&m_DataSockAddr, sizeof( m_DataSockAddr ) ) < 0 ) - { - return( FTP_FAILED ); - } - - - i = sizeof( m_DataSockAddr); - - getsockname( m_iDataSocket, (struct sockaddr *)&m_DataSockAddr, &i ); - - listen( m_iDataSocket, 5 ); - - - // Set socket to non-blocking - - uTemp = 1; - - - if (Use_Non_Blocking_Mode()) { - if( ioctlsocket( m_iDataSocket, FIONBIO, &uTemp ) == SOCKET_ERROR ) - { - return( FTP_FAILED ); - } - } - - - m_sendNewPortStatus = 1; - } - - /* Send a port command. */ - - if( m_sendNewPortStatus == 1 ) - { - memset( command, 0, 256 ); - - i = MyIPAddress( m_iCommandSocket ); - - if( i == FTP_FAILED ) - { - return( FTP_FAILED ); - } - - sprintf( command, "PORT %d,%d,%d,%d,%d,%d\r\n", - i & 0xFF, - ( i >> 8 ) & 0xFF, - ( i >> 16 ) & 0xFF, - ( i >> 24 ) & 0xFF, - m_DataSockAddr.sin_port & 0xFF, - m_DataSockAddr.sin_port >> 8 ); - - if( SendCommand( command, strlen(command) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_sendNewPortStatus = 2; - } - - /* Get reply */ - - if( m_sendNewPortStatus == 2 ) - { - if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) || - ( iReply != FTPREPLY_PORTOK ) ) - { - return( FTP_TRYING ); - } - - m_sendNewPortStatus = 0; - } - - return( FTP_SUCCEEDED ); -} - - -/*$_Function**************************************************************** -* $_Name : -* int Cftp::OpenDataConnection() -* -* $_Description : -* Opens the data connection to the server. Actually, the socket for the -* data connection should have been opened by a call to SendNewPort before -* this method is called - this just calls accept. -* -* $_Parameters : -* None. -* -* $_ReturnValue : -* FTP_SUCCEEDED on success, FTP_FAILED otherwise. -* -* $_Warnings : -* This call may block. -* -***************************************************************************/ - - - -int Cftp::OpenDataConnection() -{ - int iNewSocket; - - if( m_iDataSocket == 0 ) - { - return( FTP_FAILED ); - } - - if( ( iNewSocket = accept( m_iDataSocket, NULL, 0 ) ) < 0 ) - { - if( WSAGetLastError() != (WSAEWOULDBLOCK ) ) - { - return( FTP_FAILED ); - } - else - { - return( FTP_TRYING ); - } - } - - m_iDataSocket = iNewSocket; - - return( FTP_SUCCEEDED ); -} - - - -/*$_Function**************************************************************** -* $_Name : -* void Cftp::CloseDataConnection() -* -* $_Description : -* Closes the data connection. -* -* $_Parameters : -* None. -* -* $_ReturnValue : -* None. -* -***************************************************************************/ - - -void Cftp::CloseDataConnection() -{ - closesocket( m_iDataSocket ); - m_iDataSocket = 0; -} - -/*$_Function**************************************************************** -* $_Name : -* HRESULT Cftp::DisconnectFromServer() -* -* $_Description : -* Disconnects from the server. -* -* $_Parameters : -* None. -* -* $_ReturnValue : -* None. -* -***************************************************************************/ - -HRESULT Cftp::DisconnectFromServer() -{ - // Make the download file read-only so it's still there the next time - // we're run. - - closesocket( m_iCommandSocket ); - return( FTP_SUCCEEDED ); -} - - - - -/*$_Function**************************************************************** -* $_Name : -* int Cftp::SendData( char * pData, int iSize ) -* -* $_Description : -* Sends data to the server. -* -* $_Parameters : -* -> char * pData -* A pointer to some data to be sent. -* -* -> int iSize -* The size, in bytes, of the data. -* -* $_ReturnValue : -* The number of bytes sent, or -1 on error. -* -***************************************************************************/ - -int Cftp::SendData( char * pData, int iSize ) -{ - return( send( m_iDataSocket, pData, iSize, 0 ) ); -} - - -/*$_Function**************************************************************** -* $_Name : -* int Cftp::RecvData( char * pData, int iSize ) -* -* $_Description : -* Receives data from the server. -* -* $_Parameters : -* -> LPCSTR pData -* A pointer to a buffer for the data to be received. -* -* -> int iSize -* The size, in bytes, of the data buffer. -* -* $_ReturnValue : -* The number of bytes received, or -1 on error. -* -***************************************************************************/ - -int Cftp::RecvData( char * pData, int iSize ) -{ -/***** testing... - int readval = recv(m_iDataSocket, pData, iSize, MSG_PEEK); - if (readval <= 0) // If there's nothing to read, don't read now... - return(readval); -******/ - - return( recv( m_iDataSocket, pData, iSize, 0 ) ); -} - - -/*$_Function**************************************************************** -* $_Name : -* HRESULT Cftp::GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead ) -* -* $_Description : -* Retrieves the next block of data from the remote file and writes it into -* the local file. Deals with opening the local file and restarting a -* failed transfer if FileRecoveryPosition() returns non-zero. To prevent -* a restart after FileRecoveryPosition() returns non-zero, call -* Cftp::RestartFrom() with 0 as the offset parameter. -* -* The file is initally written to a temporary file and then copied to the local -* file name when the transfer is complete. If the transfer is halted, the -* temporary file will be used as the starting point for subsequent retries. -* -* $_Parameters : -* -> LPCSTR szLocalFileName -* A pointer to a string containing the local file name for the transferred file. -* -* <- int * piTotalRead -* A pointer to an integer in which to store the total number of bytes -* transferred so far. -* -* $_ReturnValue : -* FTP_TRYING while the transfer is in progress, FTP_SUCCEEDED on completion, -* FTP_FAILED on error. -* -***************************************************************************/ - -HRESULT Cftp::GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead ) -{ - char command[ 256 ]; - int read, totread = 0; - - const int max_data_len=10240; - - char data[ max_data_len ]; - int res, iReply; - - char downloadfilename[256]; - GetDownloadFilename(szLocalFileName, downloadfilename); - - - //char str[ 256 ]; - - strncpy( m_szLocalFileName, szLocalFileName, 256 ); - - // Open local file - - if( m_iStatus == FTPSTAT_FILEFOUND ) - { - if( m_iFilePos == 0 ) - { - if( ( m_pfLocalFile = fopen( downloadfilename, "wb" ) ) == NULL ) - { - return( FTP_FAILED ); - } - } - else - { - if( ( m_pfLocalFile = fopen( downloadfilename, "ab" ) ) == NULL ) - { - return( FTP_FAILED ); - } - } - m_iStatus = FTPSTAT_FILEOPEN; - } - - // Send the PORT command - - if( m_iStatus == FTPSTAT_FILEOPEN ) - { - if( SendNewPort() == FTP_SUCCEEDED ) - { - m_iStatus = FTPSTAT_SENTFILEPORT; - } - else - { - return( FTP_TRYING ); - } - } - - // Set type to BINARY - - if( m_iStatus == FTPSTAT_SENTFILEPORT ) - { - sprintf( command, "TYPE I\r\n"); - - if( SendCommand( command, strlen( command ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGTYPE; - } - - /* Get reply */ - - if( m_iStatus == FTPSTAT_SENDINGTYPE ) - { - if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) || - ( iReply != FTPREPLY_TYPEOK ) ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENTTYPE; - } - - // Send the RESTART command - if we are restarting a previous transfer. - - if( m_iStatus == FTPSTAT_SENTTYPE ) - { - if( m_iFilePos == 0 ) - { - m_iStatus = FTPSTAT_SENTREST; - } - else - { - sprintf( command, "REST %d\r\n", m_iFilePos ); - - if( SendCommand( command, strlen( command ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGREST; - } - } - - /* Get reply */ - - if( m_iStatus == FTPSTAT_SENDINGREST ) - { - HRESULT res=RecvReply( command, 256, &iReply ); - - if ((res == FTP_FAILED) || (iReply == 502)) // unsupported command - { - m_iFilePos=0; - fclose(m_pfLocalFile); - m_pfLocalFile = fopen( downloadfilename, "wb" ); - } - else if( ( res != FTP_SUCCEEDED ) || - ( iReply != FTPREPLY_RESTARTOK ) ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENTREST; - } - - - // Send the RETR command - - if( m_iStatus == FTPSTAT_SENTREST ) - { - sprintf( command, "RETR %s\r\n", m_szRemoteFileName ); - - if( SendCommand( command, strlen( command ) ) < 0 ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENDINGRETR; - } - - /* Get reply */ - - if( m_iStatus == FTPSTAT_SENDINGRETR ) - { - - if( ( RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) || - ( iReply != FTPREPLY_OPENBINARY ) ) - { - return( FTP_TRYING ); - } - - m_iStatus = FTPSTAT_SENTRETR; - } - - /* Open data connection */ - - if( m_iStatus == FTPSTAT_SENTRETR ) - { - res = OpenDataConnection(); - if( res != FTP_SUCCEEDED ) - { - return( res ); - } - m_iStatus = FTPSTAT_FILEDATAOPEN; - } - - - /* Get data */ - - if( m_iStatus == FTPSTAT_FILEDATAOPEN ) - { - do - { - read = RecvData( data, max_data_len ); - if( read > 0 ) - { - fwrite( data, 1, read, m_pfLocalFile ); - totread += read; - } - } - while( ( read > 0 ) && ( totread < (max_data_len * 20) ) ); // Don't read too much - - // must not block for too long - - - m_iFilePos += totread; // update read position - - if( piTotalRead != NULL ) - *piTotalRead = m_iFilePos; - - - // look for all notices about endpoint closed... - if (read < 0) { - int wsa_err=WSAGetLastError(); - - if ((wsa_err == WSAECONNRESET) || (wsa_err == WSAENOTCONN)) - read = 0; // just treat it as a close.... - } - - - /* See if the download has finished */ - - if( read == 0 ) - { - // Data connection reset - if( m_iFilePos != m_iFileSize ) { - // Haven't got all the data - return( FTP_FAILED ); - } else { - // got all the data and the connection is closed so mark it so - m_iStatus = FTPSTAT_FILEDATACLOSED; - } - } else { - return( FTP_TRYING ); - } - } - - // if we have gotten to here, we have all the data and the connection is - // closed. The case where the connection was closed but we didn't get - // everything is handled above. - if( m_iStatus == FTPSTAT_FILEDATACLOSED ) { - CloseDataConnection(); - fclose( m_pfLocalFile ); - m_pfLocalFile = NULL; - - /* - * Move the file from the temporary download location to its - * final resting place - */ - - char downloadfilename[256]; - GetDownloadFilename(m_szLocalFileName, downloadfilename); - - // Make sure the path exists for the new file - char curdir[256]; - _getcwd(curdir,256); - Prepare_Directories(curdir, m_szLocalFileName); - DEBUG_LOG(("CWD: %s\n", curdir)); - - if( rename( downloadfilename, m_szLocalFileName ) != 0 ) { - DEBUG_LOG(("First rename of %s to %s failed with errno of %d\n", downloadfilename, m_szLocalFileName, errno)); - /* Error moving file - remove file that's already there and try again. */ - _chmod( m_szLocalFileName, _S_IWRITE | _S_IREAD); // make sure it's not readonly - DEBUG_LOG(("_chmod of %s failed with errno of %d\n", m_szLocalFileName, errno)); - remove( m_szLocalFileName ); - DEBUG_LOG(("remove of %s failed with errno of %d\n", m_szLocalFileName, errno)); - - if( rename( downloadfilename, m_szLocalFileName ) != 0 ) { - DEBUG_LOG(("Second rename of %s to %s failed with errno of %d\n", downloadfilename, m_szLocalFileName, errno)); - return( FTP_FAILED ); - } - } - - // Send a bogus command. If the firewall has closed our ftp command channel connection this - // will allow us to detect it. (Obviously the data channel is closed or we wouldn't be here) - // There are cases (firewall) where the connection will go away without having a close command - // but writing to it will allow us to detect this case. - // We will ignore the response because we don't know in which order the server will respond - SendCommand("BOGUSCOMMAND\r\n", strlen("BOGUSCOMMAND\r\n")); - - OutputDebugString("File closed, waiting for response.\n"); - - m_iStatus = FTPSTAT_TRANSFERREPLY; - } - - - if( m_iStatus == FTPSTAT_TRANSFERREPLY ) { - iReply=0; - - // Get the file complete reply - if (RecvReply( command, 256, &iReply ) != FTP_SUCCEEDED ) - return(FTP_TRYING); - - if (iReply == FTPREPLY_CONTROLCLOSED) { - m_iStatus = FTPSTAT_INIT; - m_iFilePos=0; - CloseSockets(); - } else { - m_iStatus = FTPSTAT_LOGGEDIN; - m_iFilePos=0; - } - return(FTP_SUCCEEDED); - } - return( FTP_FAILED ); -} - - - -/*$_Function**************************************************************** -* $_Name : -* HRESULT Cftp::FileRecoveryPosition( LPCSTR szLocalFileName ) -* -* $_Description : -* Finds the size of the specified file. This size can be used -* -* $_Parameters : -* char & szLocalFileName -* The full path name of the local file. -* -* $_ReturnValue : -* The size of that file on the local disk. 0 if the file does not exist. -* -***************************************************************************/ - - -// -// Do we have this file in the download directory? If so then it's a partial download. -// -// -HRESULT Cftp::FileRecoveryPosition( LPCSTR szLocalFileName, LPCSTR szRegistryRoot ) -{ - char downloadfilename[256]; - GetDownloadFilename(szLocalFileName, downloadfilename); - - FILE *testfp = fopen( downloadfilename, "rb" ); - if( testfp == NULL ) - { - m_iFilePos = 0; - return 0; - } - - fseek( testfp, 0, SEEK_END ); - m_iFilePos = ftell( testfp ); - fclose( testfp ); - - return( m_iFilePos ); -} - -/*************8 - FILE * testfp; - HKEY hkey; - unsigned char regfilename[ 256 ]; - char regkey[ 512 ]; - unsigned long t1, t2; - - if( ( szRegistryRoot == NULL ) || ( szLocalFileName == NULL ) ) - { - // Bail out - return( 0 ); - } - - // Concatenate the registry key together - - strcpy( regkey, szRegistryRoot ); - if( regkey[ strlen( regkey ) - 1 ] != '\\' ) - { - strcat( regkey, "\\Download" ); - } - else - { - strcat( regkey, "Download" ); - } - - if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, (LPCTSTR)regkey, - 0, KEY_ALL_ACCESS, &hkey ) != ERROR_SUCCESS ) - { - // Key doesn't exist, create it - if( RegCreateKey( HKEY_LOCAL_MACHINE, (LPCTSTR)regkey, - &hkey ) != ERROR_SUCCESS ) - { - // Error, bail out - return( 0 ); - } - - RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 ); - RegCloseKey(hkey); - - return( 0 ); - } - - t2 = 256; - - if( RegQueryValueEx( hkey, (LPCTSTR)"File", 0, &t1, regfilename, &t2 ) != ERROR_SUCCESS ) - { - RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 ); - RegCloseKey(hkey); - return( 0 ); - } - - if( strcmp( szLocalFileName, (const char *)regfilename ) == 0 ) - { - // File previously downloaded - testfp = fopen( FTP_TEMPFILENAME, "rb" ); - - if( testfp == NULL ) - { - m_iFilePos = 0; - RegCloseKey(hkey); - return 0; - } - - fseek( testfp, 0, SEEK_END ); - - m_iFilePos = ftell( testfp ); - - fclose( testfp ); - - RegCloseKey(hkey); - return( m_iFilePos ); - } - - // Download file doesn't exist - RegSetValueEx( hkey, (LPCTSTR)"File", 0, REG_SZ, (const unsigned char *)szLocalFileName, strlen( szLocalFileName ) + 1 ); - RegCloseKey(hkey); - - // get rid of any temp downloads - _unlink(FTP_TEMPFILENAME); - - return( 0 ); -} -**************************************/ - - - -// -// convert a local name to a temp filename to use for downloading -// -void Cftp::GetDownloadFilename(const char *localname, char *downloadname) -{ - char *name = strdup(localname); - char *s = name; - while (*s) - { - if (*s == '\\' || *s == '.' || *s == ' ') - *s = '_'; - ++s; - } - sprintf(downloadname,"download\\%s_%d.tmp",name,m_iFileSize); - free(name); - /* - Wstring name; - name.set(localname); - name.replace("\\","_"); - name.replace(".","_"); - name.replace(" ","_"); - sprintf(downloadname,"download\\%s_%d.tmp",name.get(),m_iFileSize); - */ - return; -} - - - - -// -// Build all the subdirectories for a given filename -// -bool Prepare_Directories(const char *rootdir, const char *filename) -{ - char tempstr[256]; - char newdir[256]; - - const char *cptr=filename; - while(cptr=strchr(cptr,'\\')) - { - memset(tempstr,0,256); - strncpy(tempstr,filename,cptr-filename); - sprintf(newdir,"%s\\%s",rootdir, tempstr); - if (!CreateDirectory(newdir, NULL)) - return false; - //if ((_mkdir(newdir) == -1) && ((errno == ENOENT || errno==EACCES))) - //return(false); - cptr++; - } - return(true); -} - - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/Registry.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/Registry.h deleted file mode 100644 index b22acd6278..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/Registry.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Registry.h -// Simple interface for storing/retreiving registry values -// Author: Matthew D. Campbell, December 2001 - -#pragma once - -#ifndef __WWDOWNLOAD_REGISTRY_H__ -#define __WWDOWNLOAD_REGISTRY_H__ - -#include - -/** - * Get a string from the registry - */ -bool GetStringFromRegistry(std::string path, std::string key, std::string& val); - -/** - * Get an unsigned int from the registry - */ -bool GetUnsignedIntFromRegistry(std::string path, std::string key, unsigned int& val); - -/** - * Store a string in the registry - returns true on success - */ -bool SetStringInRegistry(std::string path, std::string key, std::string val); - -/** - * Store an unsigned int in the registry - returns true on success - */ -bool SetUnsignedIntInRegistry(std::string path, std::string key, unsigned int val); - -#endif // __WWDOWNLOAD_REGISTRY_H__ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/downloaddefs.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/downloaddefs.h deleted file mode 100644 index a47ccc05eb..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/downloaddefs.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef _DOWNLOADDEFS_H -#define _DOWNLOADDEFS_H - -// CDownload statuses - -#define DOWNLOADSTATUS_NONE 0 -#define DOWNLOADSTATUS_GO 1 -#define DOWNLOADSTATUS_CONNECTING 2 -#define DOWNLOADSTATUS_LOGGINGIN 3 -#define DOWNLOADSTATUS_FINDINGFILE 4 -#define DOWNLOADSTATUS_QUERYINGRESUME 5 -#define DOWNLOADSTATUS_DOWNLOADING 6 -#define DOWNLOADSTATUS_DISCONNECTING 7 -#define DOWNLOADSTATUS_FINISHING 8 -#define DOWNLOADSTATUS_DONE 0 - -// CDownload return codes - -#define DOWNLOAD_SUCCEEDED S_OK -#define DOWNLOAD_PARAMERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 1 ) -#define DOWNLOAD_STATUSERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 2 ) -#define DOWNLOAD_NETWORKERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 3 ) -#define DOWNLOAD_FILEERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 4 ) -#define DOWNLOAD_REENTERERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 4 ) - -// CDownloadEvent return codes. - -#define DOWNLOADEVENT_SUCCEEDED S_OK -#define DOWNLOADEVENT_FAILED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 5 ) -#define DOWNLOADEVENT_RESUME S_OK -#define DOWNLOADEVENT_DONOTRESUME MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 6 ) - -// CDownloadEvent error codes for OnError() - -#define DOWNLOADEVENT_NOSUCHSERVER 1 -#define DOWNLOADEVENT_COULDNOTCONNECT 2 -#define DOWNLOADEVENT_LOGINFAILED 3 -#define DOWNLOADEVENT_NOSUCHFILE 4 -#define DOWNLOADEVENT_LOCALFILEOPENFAILED 5 -#define DOWNLOADEVENT_TCPERROR 6 -#define DOWNLOADEVENT_DISCONNECTERROR 7 - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/ftp.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/ftp.h deleted file mode 100644 index 9c515c8603..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/ftp.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// ftp.h : Declaration of the Cftp - -#ifndef __FTP_H_ -#define __FTP_H_ - - -//#include "../resource.h" // main symbols - -#include "winsock.h" -#include "stdio.h" - -#include "WWDownload/ftpdefs.h" - -// FTP server return codes. See RFC 959 - -#define FTPREPLY_SERVEROK 220 -#define FTPREPLY_PASSWORD 331 -#define FTPREPLY_LOGGEDIN 230 -#define FTPREPLY_PORTOK 200 -#define FTPREPLY_TYPEOK 200 -#define FTPREPLY_RESTARTOK 350 -#define FTPREPLY_CWDOK 250 -#define FTPREPLY_OPENASCII 150 -#define FTPREPLY_OPENBINARY 150 -#define FTPREPLY_COMPLETE 226 -#define FTPREPLY_CONTROLCLOSED 421 - -// Temporary download file name - -#define FTP_TEMPFILENAME "..\\__~DOWN_L~D" - - -///////////////////////////////////////////////////////////////////////////// -// Cftp -class Cftp -{ -private: - friend class CDownload; - - int m_iCommandSocket; // Socket for commands - int m_iDataSocket; // Socket for data - - struct sockaddr_in m_CommandSockAddr; // Address for commands - struct sockaddr_in m_DataSockAddr; // Address for data - - int m_iFilePos; // Byte offset into file - int m_iBytesRead; // Number of bytes downloaded - int m_iFileSize; // Total size of the file - char m_szRemoteFilePath[128]; - char m_szRemoteFileName[128]; - char m_szLocalFilePath[128]; - char m_szLocalFileName[128]; - char m_szServerName[128]; - char m_szUserName[128]; - char m_szPassword[128]; - FILE * m_pfLocalFile; - int m_iStatus; - - int m_sendNewPortStatus; - int m_findStart; - - int SendData( char * pData, int iSize ); - int RecvData( char * pData, int iSize ); - int SendNewPort(); - int OpenDataConnection(); - void CloseDataConnection(); - int AsyncGetHostByName( char * szName, struct sockaddr_in &address ); - - // Convert a local filename into a temp filename to download into - void GetDownloadFilename( const char* localname, char* downloadname); - - void CloseSockets(void); - void ZeroStuff(void); - - -public: - Cftp(); - virtual ~Cftp(); - -public: - HRESULT ConnectToServer(LPCSTR szServerName); - HRESULT DisconnectFromServer(); - - HRESULT LoginToServer( LPCSTR szUserName, LPCSTR szPassword ); - HRESULT LogoffFromServer( void ); - - HRESULT FindFile( LPCSTR szRemoteFileName, int * piSize ); - - HRESULT FileRecoveryPosition( LPCSTR szLocalFileName, LPCSTR szRegistryRoot ); - HRESULT RestartFrom( int i ) { m_iFilePos = i; return FTP_SUCCEEDED; }; - - HRESULT GetNextFileBlock( LPCSTR szLocalFileName, int * piTotalRead ); - - HRESULT RecvReply( LPCSTR pReplyBuffer, int iSize, int * piRetCode ); - HRESULT SendCommand( LPCSTR pCommand, int iSize ); - -}; - -#endif //__FTP_H_ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/ftpdefs.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/ftpdefs.h deleted file mode 100644 index 50897637a3..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/ftpdefs.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __FTPDEFS_H_INCLUDED__ -#define __FTPDEFS_H_INCLUDED__ - - -// CFtp return codes. - -#define FTP_SUCCEEDED S_OK -#define FTP_FAILED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 1 ) -#define FTP_TRYING MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 2 ) - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/registry.cpp b/Generals/Code/Libraries/Source/WWVegas/WWDownload/registry.cpp deleted file mode 100644 index a8c334b8ab..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/registry.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Registry.cpp -// Simple interface for storing/retreiving registry values -// Author: Matthew D. Campbell, December 2001 - -#include - -#define WIN32_LEAN_AND_MEAN -#include - -#include "Registry.h" - -bool getStringFromRegistry(HKEY root, std::string path, std::string key, std::string& val) -{ - HKEY handle; - unsigned char buffer[256]; - unsigned long size = 256; - unsigned long type; - int returnValue; - - if ((returnValue = RegOpenKeyEx( root, path.c_str(), 0, KEY_READ, &handle )) == ERROR_SUCCESS) - { - returnValue = RegQueryValueEx(handle, key.c_str(), NULL, &type, (unsigned char *) &buffer, &size); - RegCloseKey( handle ); - } - - if (returnValue == ERROR_SUCCESS) - { - val = (char *)buffer; - return true; - } - - return false; -} - -bool getUnsignedIntFromRegistry(HKEY root, std::string path, std::string key, unsigned int& val) -{ - HKEY handle; - unsigned long buffer; - unsigned long size = sizeof(buffer); - unsigned long type; - int returnValue; - - if ((returnValue = RegOpenKeyEx( root, path.c_str(), 0, KEY_READ, &handle )) == ERROR_SUCCESS) - { - returnValue = RegQueryValueEx(handle, key.c_str(), NULL, &type, (unsigned char *) &buffer, &size); - RegCloseKey( handle ); - } - - if (returnValue == ERROR_SUCCESS) - { - val = buffer; - return true; - } - - return false; -} - -bool setStringInRegistry( HKEY root, std::string path, std::string key, std::string val) -{ - HKEY handle; - unsigned long type; - unsigned long returnValue; - int size; - char lpClass[] = "REG_NONE"; - - if ((returnValue = RegCreateKeyEx( root, path.c_str(), 0, lpClass, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &handle, NULL )) == ERROR_SUCCESS) - { - type = REG_SZ; - size = val.length()+1; - returnValue = RegSetValueEx(handle, key.c_str(), 0, type, (unsigned char *)val.c_str(), size); - RegCloseKey( handle ); - } - - return (returnValue == ERROR_SUCCESS); -} - -bool setUnsignedIntInRegistry( HKEY root, std::string path, std::string key, unsigned int val) -{ - HKEY handle; - unsigned long type; - unsigned long returnValue; - int size; - char lpClass[] = "REG_NONE"; - - if ((returnValue = RegCreateKeyEx( root, path.c_str(), 0, lpClass, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &handle, NULL )) == ERROR_SUCCESS) - { - type = REG_DWORD; - size = 4; - returnValue = RegSetValueEx(handle, key.c_str(), 0, type, (unsigned char *)&val, size); - RegCloseKey( handle ); - } - - return (returnValue == ERROR_SUCCESS); -} - -bool GetStringFromRegistry(std::string path, std::string key, std::string& val) -{ - std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; - - fullPath.append(path); - if (getStringFromRegistry(HKEY_LOCAL_MACHINE, fullPath.c_str(), key.c_str(), val)) - { - return true; - } - - return getStringFromRegistry(HKEY_CURRENT_USER, fullPath.c_str(), key.c_str(), val); -} - -bool GetUnsignedIntFromRegistry(std::string path, std::string key, unsigned int& val) -{ - std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; - - fullPath.append(path); - if (getUnsignedIntFromRegistry(HKEY_LOCAL_MACHINE, fullPath.c_str(), key.c_str(), val)) - { - return true; - } - - return getUnsignedIntFromRegistry(HKEY_CURRENT_USER, fullPath.c_str(), key.c_str(), val); -} - -bool SetStringInRegistry( std::string path, std::string key, std::string val) -{ - std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; - fullPath.append(path); - - if (setStringInRegistry( HKEY_LOCAL_MACHINE, fullPath, key, val)) - return true; - - return setStringInRegistry( HKEY_CURRENT_USER, fullPath, key, val ); -} - -bool SetUnsignedIntInRegistry( std::string path, std::string key, unsigned int val) -{ - std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; - fullPath.append(path); - - if (setUnsignedIntInRegistry( HKEY_LOCAL_MACHINE, fullPath, key, val)) - return true; - - return setUnsignedIntInRegistry( HKEY_CURRENT_USER, fullPath, key, val ); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp b/Generals/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp deleted file mode 100644 index 636c53f4ec..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include -#include -#include "Registry.h" - -void FormatURLFromRegistry( std::string& gamePatchURL, std::string& mapPatchURL, - std::string& configURL, std::string& motdURL ) -{ - std::string sku = "generals"; - std::string language = "english"; - unsigned int version = 0; // invalid version - can't get on with a corrupt reg. - unsigned int mapVersion = 0; // invalid version - can't get on with a corrupt reg. - std::string baseURL = "http://servserv.generals.ea.com/servserv/"; - baseURL.append(sku); - baseURL.append("/"); - - GetStringFromRegistry("", "BaseURL", baseURL); - GetStringFromRegistry("", "Language", language); - GetUnsignedIntFromRegistry("", "Version", version); - GetUnsignedIntFromRegistry("", "MapPackVersion", mapVersion); - - char buf[256]; - _snprintf(buf, 256, "%s%s-%d.txt", baseURL.c_str(), language.c_str(), version); - gamePatchURL = buf; - _snprintf(buf, 256, "%smaps-%d.txt", baseURL.c_str(), mapVersion); - mapPatchURL = buf; - _snprintf(buf, 256, "%sconfig.txt", baseURL.c_str()); - configURL = buf; - _snprintf(buf, 256, "%sMOTD-%s.txt", baseURL.c_str(), language.c_str()); - motdURL = buf; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.h b/Generals/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.h deleted file mode 100644 index da541f1b64..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWDownload/urlBuilder.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef _URLBUILDER_H_ -#define _URLBUILDER_H_ -void FormatURLFromRegistry( std::string& gamePatchURL, std::string& mapPatchURL, - std::string& configURL, std::string& motdURL ); - -#endif // _URLBUILDER_H_ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/WWMath/CMakeLists.txt deleted file mode 100644 index 1c4833f1e8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/CMakeLists.txt +++ /dev/null @@ -1,93 +0,0 @@ -set(WWMATH_SRC - aabox.cpp - aabox.h - aabtreecull.cpp - aabtreecull.h - aaplane.h - cardinalspline.cpp - cardinalspline.h - castres.h - catmullromspline.cpp - catmullromspline.h - colmath.cpp - colmath.h - colmathaabox.cpp - colmathaabox.h - colmathaabtri.cpp - colmathfrustum.cpp - colmathfrustum.h - colmathinlines.h - colmathline.cpp - colmathline.h - colmathobbobb.cpp - colmathobbox.cpp - colmathobbtri.cpp - colmathplane.cpp - colmathplane.h - colmathsphere.cpp - cullsys.cpp - cullsys.h - culltype.h - curve.cpp - curve.h - euler.cpp - euler.h - frustum.cpp - frustum.h - gridcull.cpp - gridcull.h - hermitespline.cpp - hermitespline.h - lineseg.cpp - lineseg.h - lookuptable.cpp - lookuptable.h - matrix3.cpp - matrix3.h - matrix3d.cpp - matrix3d.h - matrix4.cpp - matrix4.h - obbox.cpp - obbox.h - ode.cpp - ode.h - plane.h - pot.cpp - pot.h - quat.cpp - quat.h - rect.h - sphere.h - tcbspline.cpp - tcbspline.h - tri.cpp - tri.h - v3_rnd.cpp - v3_rnd.h - vector2.h - vector2i.h - vector3.h - Vector3i.h - vector4.h - vehiclecurve.cpp - vehiclecurve.h - vp.cpp - vp.h - wwmath.cpp - wwmath.h - wwmathids.h -) - -# Targets to build. -add_library(g_wwmath STATIC) -set_target_properties(g_wwmath PROPERTIES OUTPUT_NAME wwmath) - -target_sources(g_wwmath PRIVATE ${WWMATH_SRC}) - -target_link_libraries(g_wwmath PRIVATE - g_wwcommon -) - -# @todo Test its impact and see what to do with the legacy functions. -#add_compile_definitions(z_wwmath PUBLIC ALLOW_TEMPORARIES) # Enables legacy math with "temporaries" diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/Vector3i.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/Vector3i.h deleted file mode 100644 index c662880156..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/Vector3i.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/vector3i.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/24/01 5:24p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR3I_H -#define VECTOR3I_H - -#include "always.h" - -class Vector3i -{ -public: - - int I; - int J; - int K; - - WWINLINE Vector3i(void); - WWINLINE Vector3i(int i,int j,int k); - - WWINLINE bool operator== (const Vector3i & v) const; - WWINLINE bool operator!= (const Vector3i& v) const; - WWINLINE const int& operator[] (int n) const; - WWINLINE int& operator[] (int n); -}; - - -WWINLINE Vector3i::Vector3i(void) -{ -} - -WWINLINE Vector3i::Vector3i(int i,int j,int k) -{ - I = i; J = j; K = k; -} - -WWINLINE bool Vector3i::operator == (const Vector3i & v) const -{ - return (I == v.I && J == v.J && K == v.K); -} - -WWINLINE bool Vector3i::operator != (const Vector3i& v) const -{ - return !(I == v.I && J == v.J && K == v.K); -} - -WWINLINE const int& Vector3i::operator[] (int n) const -{ - return ((int*)this)[n]; -} - -WWINLINE int& Vector3i::operator[] (int n) -{ - return ((int*)this)[n]; -} - -// ---------------------------------------------------------------------------- - -class Vector3i16 -{ -public: - - unsigned short I; - unsigned short J; - unsigned short K; - - WWINLINE Vector3i16(void); - WWINLINE Vector3i16(unsigned short i,unsigned short j,unsigned short k); - - WWINLINE bool operator== (const Vector3i & v) const; - WWINLINE bool operator!= (const Vector3i& v) const; - WWINLINE const unsigned short & operator[] (int n) const; - WWINLINE unsigned short & operator[] (int n); -}; - - -WWINLINE Vector3i16::Vector3i16(void) -{ -} - -WWINLINE Vector3i16::Vector3i16(unsigned short i,unsigned short j,unsigned short k) -{ - I = i; J = j; K = k; -} - -WWINLINE bool Vector3i16::operator == (const Vector3i & v) const -{ - return (I == v.I && J == v.J && K == v.K); -} - -WWINLINE bool Vector3i16::operator != (const Vector3i& v) const -{ - return !(I == v.I && J == v.J && K == v.K); -} - -WWINLINE const unsigned short & Vector3i16::operator[] (int n) const -{ - return ((unsigned short *)this)[n]; -} - -WWINLINE unsigned short & Vector3i16::operator[] (int n) -{ - return ((unsigned short *)this)[n]; -} - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabox.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/aabox.cpp deleted file mode 100644 index fe90beff7a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabox.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/aabox.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 5/08/01 6:33p $* - * * - * $Revision:: 18 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * AABoxClass::Init_Random -- initializes this box to a random state * - * AABoxClass::Contains -- test whether this box contains the given point * - * AABoxClass::Contains -- Test whether this box contains the given box * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "aabox.h" -#include "colmath.h" -#include "colmathinlines.h" -#include - - -/*********************************************************************************************** - * AABoxClass::Init_Random -- initializes this box to a random state * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/17/2000 gth : Created. * - *=============================================================================================*/ -void AABoxClass::Init_Random(float min_center,float max_center,float min_extent,float max_extent) -{ - Center.X = min_center + WWMath::Random_Float() * (max_center - min_center); - Center.Y = min_center + WWMath::Random_Float() * (max_center - min_center); - Center.Z = min_center + WWMath::Random_Float() * (max_center - min_center); - - Extent.X = min_extent + WWMath::Random_Float() * (max_extent - min_extent); - Extent.Y = min_extent + WWMath::Random_Float() * (max_extent - min_extent); - Extent.Z = min_extent + WWMath::Random_Float() * (max_extent - min_extent); -} - - -void AABoxClass::Transform(const Matrix3D & tm,const AABoxClass & in,AABoxClass * out) -{ - tm.Transform_Center_Extent_AABox(in.Center,in.Extent,&(out->Center),&(out->Extent)); -} - -void MinMaxAABoxClass::Init_Empty(void) -{ - MinCorner.Set(FLT_MAX,FLT_MAX,FLT_MAX); - MaxCorner.Set(-FLT_MAX,-FLT_MAX,-FLT_MAX); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabox.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/aabox.h deleted file mode 100644 index c12f00742e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabox.h +++ /dev/null @@ -1,679 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/aabox.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 5/08/01 6:35p $* - * * - * $Revision:: 30 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * AABoxClass::Transform -- transform an aabox * - * AABoxClass::Translate -- transform an aabox * - * AABoxClass::Init -- create a box which bounds the given points * - * AABoxClass::Init -- initialize from a min-max form of a box * - * AABoxClass::Init_Min_Max -- init the box from a min and max vector * - * AABoxClass::Add_Point -- expand the box to contain the given point * - * AABoxClass::Project_To_Axis -- compute projection onto the given axis * - * AABoxClass::Intersects -- test for intersection with another static aabox * - * AABoxClass::Add_Box -- expand this box to enclose the passed box * - * AABoxClass::Add_Box -- Expand this box to enclose the passed box * - * MinMaxAABoxClass::Init -- init the box from an array of points * - * MinMaxAABoxClass::Init -- initializes this box from a center-extent box * - * MinMaxAABoxClass::Add_Point -- updates this box so it encloses the given point * - * MinMaxAABoxClass::Add_Box -- update this box to enclose the given box * - * MinMaxAABoxClass::Add_Box -- Updates this box to enclose the specified box * - * MinMaxAABoxClass::Transform -- Updates this box to enclose its transformed version * - * MinMaxAABoxClass::Translate -- translates the box * - * AABoxClass::Init -- Init from a line segment * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AABOX_H -#define AABOX_H - -#include "always.h" -#include "matrix3d.h" -#include "lineseg.h" -#include "colmath.h" - -class AABoxClass; -class MinMaxAABoxClass; -class OBBoxClass; -class TriClass; -class PlaneClass; -struct CastResultStruct; - - -/* -** AABoxClass -** -** Axis-Aligned Boxes. I've coded these similar to the OrientedBoxClass only -** without a rotation matrix. A similar algorithm is used to test the box -** for intersection. -*/ -class AABoxClass -{ - -public: - - WWINLINE AABoxClass(void) { } - - WWINLINE AABoxClass(const Vector3 & center,const Vector3 & extent) : - Center(center), - Extent(extent) - { } - - AABoxClass(const MinMaxAABoxClass & minmaxbox) { Init(minmaxbox); } - - AABoxClass(Vector3 * points,int num) { Init(points,num); } - - bool operator== (const AABoxClass &src); - bool operator!= (const AABoxClass &src); - - WWINLINE void Init(const Vector3& center,const Vector3 & extent) { Center = center; Extent = extent; } - WWINLINE void Init(Vector3 * points,int num); - WWINLINE void Init(const MinMaxAABoxClass & minmaxbox); - void Init(const LineSegClass & line); - void Init_Min_Max(const Vector3 & min,const Vector3 & max); - void Init_Random(float min_center = -1.0f,float max_center = 1.0f,float min_extent = 0.5f,float max_extent = 1.0f); - - void Add_Point(const Vector3 & point); - void Add_Box(const AABoxClass & b); - void Add_Box(const MinMaxAABoxClass & b); - float Project_To_Axis(const Vector3 & axis) const; - - void Transform(const Matrix3D & tm); - void Translate(const Vector3 & pos); - - WWINLINE float Volume(void) const { return 2.0*Extent.X * 2.0*Extent.Y * 2.0*Extent.Z; } - WWINLINE bool Contains(const Vector3 & point) const; - WWINLINE bool Contains(const AABoxClass & other_box) const; - WWINLINE bool Contains(const MinMaxAABoxClass & other_box) const; - - static void Transform(const Matrix3D & tm,const AABoxClass & in,AABoxClass * out); - - Vector3 Center; // world space center - Vector3 Extent; // size of the box in the three directions - -}; - -/* -** MinMaxAABoxClass -** This is another form of an AABox. It can be faster to build one of these -** and then convert it into a center-extent AABox in some cases. Its purpose -** is basically that. -*/ -class MinMaxAABoxClass -{ -public: - - WWINLINE MinMaxAABoxClass(void) { } - - WWINLINE MinMaxAABoxClass(const Vector3 & min_corner,const Vector3 & max_corner) : - MinCorner(min_corner), - MaxCorner(max_corner) - { - } - - WWINLINE MinMaxAABoxClass(Vector3 * points,int num) { Init(points,num); } - - WWINLINE MinMaxAABoxClass(const AABoxClass & that) { Init(that); } - - WWINLINE void Init(Vector3 * points,int num); - WWINLINE void Init(const AABoxClass & box); - void Init_Empty(void); - - void Add_Point(const Vector3 & point); - void Add_Box(const MinMaxAABoxClass & box); - void Add_Box(const AABoxClass & box); - void Add_Box(const Vector3 & min_corner,const Vector3 & max_corner); - - void Transform(const Matrix3D & tm); - void Translate(const Vector3 & pos); - - WWINLINE float Volume(void) const { Vector3 size = MaxCorner - MinCorner; return size.X*size.Y*size.Z; } - - Vector3 MinCorner; - Vector3 MaxCorner; -}; - - - - -/*********************************************************************************************** - * AABoxClass::Transform -- transform an aabox * - * * - * Note that this function expands the box to enclose its transformed form. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Transform(const Matrix3D & tm) -{ - Vector3 oldcenter = Center; - Vector3 oldextent = Extent; - tm.Transform_Center_Extent_AABox(oldcenter,oldextent,&Center,&Extent); -} - - -/*********************************************************************************************** - * AABoxClass::Translate -- translate an aabox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Translate(const Vector3 & trans) -{ - Center += trans; -} - - -/*********************************************************************************************** - * AABoxClass::operator== -- Comparison operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/21/00 PDS : Created. * - *=============================================================================================*/ -WWINLINE bool AABoxClass::operator== (const AABoxClass &src) -{ - return (Center == src.Center) && (Extent == src.Extent); -} - - -/*********************************************************************************************** - * AABoxClass::operator!= -- Comparison operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/21/00 PDS : Created. * - *=============================================================================================*/ -WWINLINE bool AABoxClass::operator!= (const AABoxClass &src) -{ - return (Center != src.Center) || (Extent != src.Extent); -} - - -/*********************************************************************************************** - * AABoxClass::Init -- create a box which bounds the given points * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Init(Vector3 * points,int num) -{ - Vector3 Min = points[0]; - Vector3 Max = points[0]; - - for (int i=1; i points[i].X) Min.X = points[i].X; - if (Min.Y > points[i].Y) Min.Y = points[i].Y; - if (Min.Z > points[i].Z) Min.Z = points[i].Z; - - if (Max.X < points[i].X) Max.X = points[i].X; - if (Max.Y < points[i].Y) Max.Y = points[i].Y; - if (Max.Z < points[i].Z) Max.Z = points[i].Z; - } - - Center = (Max + Min) * 0.5f; - Extent = (Max - Min) * 0.5f; -} - - -/*********************************************************************************************** - * AABoxClass::Init -- initialize from a min-max form of a box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/31/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Init(const MinMaxAABoxClass & mmbox) -{ - Center = (mmbox.MaxCorner + mmbox.MinCorner) * 0.5f; - Extent = (mmbox.MaxCorner - mmbox.MinCorner) * 0.5f; -} - - -/*********************************************************************************************** - * AABoxClass::Init -- Init from a line segment * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Init(const LineSegClass & line) -{ - Vector3 min_corner = line.Get_P0(); - Vector3 max_corner = line.Get_P0(); - - if (min_corner.X > line.Get_P1().X) min_corner.X = line.Get_P1().X; - if (min_corner.Y > line.Get_P1().Y) min_corner.Y = line.Get_P1().Y; - if (min_corner.Z > line.Get_P1().Z) min_corner.Z = line.Get_P1().Z; - - if (max_corner.X < line.Get_P1().X) max_corner.X = line.Get_P1().X; - if (max_corner.Y < line.Get_P1().Y) max_corner.Y = line.Get_P1().Y; - if (max_corner.Z < line.Get_P1().Z) max_corner.Z = line.Get_P1().Z; - - Center = (max_corner + min_corner) * 0.5f; - Extent = (max_corner - min_corner) * 0.5f; -} - -/*********************************************************************************************** - * AABoxClass::Init_Min_Max -- init the box from a min and max vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/9/99 GTH : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Init_Min_Max(const Vector3 & min,const Vector3 & max) -{ - Center = (max + min) * 0.5f; - Extent = (max - min) * 0.5f; -} - - -/*********************************************************************************************** - * AABoxClass::Add_Point -- expand the box to contain the given point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void AABoxClass::Add_Point(const Vector3 & point) -{ - Vector3 Min = Center - Extent; - Vector3 Max = Center + Extent; - - if (Min.X > point.X) Min.X = point.X; - if (Min.Y > point.Y) Min.Y = point.Y; - if (Min.Z > point.Z) Min.Z = point.Z; - - if (Max.X < point.X) Max.X = point.X; - if (Max.Y < point.Y) Max.Y = point.Y; - if (Max.Z < point.Z) Max.Z = point.Z; - - Center = (Max + Min) / 2.0f; - Extent = (Max - Min) / 2.0f; -} - - -/*********************************************************************************************** - * AABoxClass::Add_Box -- expand this box to enclose the passed box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/31/98 GTH : Created. * - * 9/29/2000 gth : Ok to add boxes with zero extent * - *=============================================================================================*/ -WWINLINE void AABoxClass::Add_Box(const AABoxClass & b) -{ - Vector3 newmin = Center - Extent; - Vector3 newmax = Center + Extent; - newmin.Update_Min(b.Center - b.Extent); - newmax.Update_Max(b.Center + b.Extent); - - Center = (newmax + newmin) * 0.5f; - Extent = (newmax - newmin) * 0.5f; -} - - -/*********************************************************************************************** - * AABoxClass::Add_Box -- Expand this box to enclose the passed box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/31/98 GTH : Created. * - * 9/29/2000 gth : Ok to add boxes with zero extent * - *=============================================================================================*/ -WWINLINE void AABoxClass::Add_Box(const MinMaxAABoxClass & b) -{ - Vector3 newmin = Center - Extent; - Vector3 newmax = Center + Extent; - newmin.Update_Min(b.MinCorner); - newmax.Update_Max(b.MaxCorner); - - Center = (newmax + newmin) * 0.5f; - Extent = (newmax - newmin) * 0.5f; -} - -/*********************************************************************************************** - * AABoxClass::Project_To_Axis -- compute projection onto the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE float AABoxClass::Project_To_Axis(const Vector3 & axis) const -{ - float x = Extent[0] * axis[0]; - float y = Extent[1] * axis[1]; - float z = Extent[2] * axis[2]; - - // projection is the sum of the absolute values of the projections of the three extents - return (WWMath::Fabs(x) + WWMath::Fabs(y) + WWMath::Fabs(z)); -} - -/*********************************************************************************************** - * AABoxClass::Contains -- Test whether this box contains the given box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/2/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE bool AABoxClass::Contains(const AABoxClass & other_box) const -{ - return CollisionMath::Overlap_Test(*this,other_box) == CollisionMath::INSIDE; -} - -/*********************************************************************************************** - * AABoxClass::Contains -- Test whether this box contains the given box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/2/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE bool AABoxClass::Contains(const MinMaxAABoxClass & other_box) const -{ - Vector3 bmin = Center - Extent; - Vector3 bmax = Center + Extent; - - if (other_box.MinCorner.X < bmin.X) return false; - if (other_box.MinCorner.Y < bmin.Y) return false; - if (other_box.MinCorner.Z < bmin.Z) return false; - - if (other_box.MaxCorner.X > bmax.X) return false; - if (other_box.MaxCorner.Y > bmax.Y) return false; - if (other_box.MaxCorner.Z > bmax.Z) return false; - - return true; -} - -/*********************************************************************************************** - * AABoxClass::Contains -- test whether this box contains the given point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/2/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE bool AABoxClass::Contains(const Vector3 & point) const -{ - return CollisionMath::Overlap_Test(*this,point) == CollisionMath::INSIDE; -} - -/*********************************************************************************************** - * MinMaxAABoxClass::Init -- init the box from an array of points * - * * - * Makes a box which encloses the given array of points * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/31/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void MinMaxAABoxClass::Init(Vector3 * points,int num) -{ - assert(num > 0); - assert(points != NULL); - MinCorner = points[0]; - MaxCorner = points[0]; - for (int i=0; i= min_corner.X); - assert(max_corner.Y >= min_corner.Y); - assert(max_corner.Z >= min_corner.Z); - - if (min_corner == max_corner) return; - - MinCorner.Update_Min(min_corner); - MaxCorner.Update_Max(max_corner); -} - - -/*********************************************************************************************** - * MinMaxAABoxClass::Transform -- Updates this box to enclose its transformed version * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/31/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void MinMaxAABoxClass::Transform(const Matrix3D & tm) -{ - Vector3 oldmin = MinCorner; - Vector3 oldmax = MaxCorner; - tm.Transform_Min_Max_AABox(oldmin,oldmax,&MinCorner,&MaxCorner); -} - - -/*********************************************************************************************** - * MinMaxAABoxClass::Translate -- translates the box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/31/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void MinMaxAABoxClass::Translate(const Vector3 & pos) -{ - MinCorner+=pos; - MaxCorner+=pos; -} - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp deleted file mode 100644 index af8a4213d5..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.cpp +++ /dev/null @@ -1,1616 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/aabtreecull.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/26/01 2:18p $* - * * - * $Revision:: 25 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "aabtreecull.h" -#include "chunkio.h" -#include "iostruct.h" -#include -#include "sphere.h" -#include "colmath.h" -#include "colmathinlines.h" - - - -/* -** Declare the pools -*/ -DEFINE_AUTO_POOL(AABTreeLinkClass,256); -DEFINE_AUTO_POOL(AABTreeNodeClass,256); - - -/* -** Current version of the file format -*/ -const uint32 AABTREE_CURRENT_VERSION = 0x00010000; - - -/* -** Chunk Id's used by the aabtree code to save itself into a file -*/ -enum -{ - AABTREE_CHUNK_VERSION = 0x00000001, // version wrapper, contains 32bit version # - AABTREE_CHUNK_AABNODE = 0x00000101, // generic aab-node wrapper - AABTREE_CHUNK_AABNODE_INFO, // OBSOLETE! generic aab-node definition (IOAABNodeStruct) - AABTREE_CHUNK_AABNODE_CONTENTS, // wrapper around contents of the node - AABTREE_CHUNK_AABNODE_VARIABLES, // wrapper around variables for a node - - AABTREE_CHUNK_NODE_INDEX = 0x00000200, // wrapper around the node index for an object - - AABTREE_VARIABLE_NODESTRUCT = 0x00, - AABTREE_VARIABLE_USERDATA -}; - - -/* -** IOAABNodeStruct -** Data structure for the contents of a node in the AAB-Tree -*/ -#define AABNODE_ATTRIBUTE_FRONT_CHILD 0x00000001 -#define AABNODE_ATTRIBUTE_BACK_CHILD 0x00000002 - -struct IOAABNodeStruct -{ - IOVector3Struct Center; - IOVector3Struct Extent; - uint32 Attributes; -}; - - -/************************************************************************* -** -** Utility functions for walking the object list in an AABTree Node -** -*************************************************************************/ -static inline CullableClass * get_first_object(AABTreeNodeClass * node) -{ - return node->Object; -} - -static inline CullableClass * get_next_object(CullableClass * obj) -{ - return ((AABTreeLinkClass *)obj->Get_Cull_Link())->NextObject; -} - - -/************************************************************************* -** -** AABTreeCullSystemClass Implementation -** -*************************************************************************/ -AABTreeCullSystemClass::AABTreeCullSystemClass(void) : - ObjectCount(0), - NodeCount(0), - IndexedNodes(NULL) -{ - RootNode = new AABTreeNodeClass; - Re_Index_Nodes(); -} - -AABTreeCullSystemClass::~AABTreeCullSystemClass(void) -{ - // Delete all links and release-ref all cullables: - int nidx; - for (nidx = 0; nidx < NodeCount; nidx++) { - while(IndexedNodes[nidx]->Object) Remove_Object_Internal(IndexedNodes[nidx]->Object); - } - - // Delete node tree (deleting the root recursively deletes all nodes) - delete RootNode; - - // Delete indexed node pointer array - if (IndexedNodes) { - delete[] IndexedNodes; - IndexedNodes = NULL; - } -} - - -void AABTreeCullSystemClass::Add_Object_Internal(CullableClass * obj,int node_index) -{ - WWASSERT_PRINT - ( - (obj->Get_Culling_System() == NULL), - "AABTreeCullSystemClass::Add -- Object is already in another culling system!\n" - ); - - AABTreeLinkClass * new_link = new AABTreeLinkClass(this); - obj->Set_Cull_Link(new_link); - - if (node_index == -1) { - Add_Object_Recursive(RootNode,obj); - } else { - WWASSERT(node_index < NodeCount); - IndexedNodes[node_index]->Add_Object(obj,false); - ObjectCount++; - } - - obj->Add_Ref(); -} - - -void AABTreeCullSystemClass::Remove_Object_Internal(CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - - AABTreeLinkClass * link = (AABTreeLinkClass *)obj->Get_Cull_Link(); - WWASSERT(link); - - AABTreeNodeClass * node = link->Node; - WWASSERT(node); - - node->Remove_Object(obj); - link->Set_Culling_System(NULL); - delete link; - obj->Set_Cull_Link(NULL); - - ObjectCount--; - WWASSERT(ObjectCount >= 0); - obj->Release_Ref(); -} - -void AABTreeCullSystemClass::Update_Culling(CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - - // unlink it from the node it is currently in - AABTreeLinkClass * link = (AABTreeLinkClass *)obj->Get_Cull_Link(); - WWASSERT(link); - AABTreeNodeClass * node = link->Node; - WWASSERT(node); - node->Remove_Object(obj); - // decrement the object counter, the node can't - // decrement it for us... - ObjectCount--; - - // drop it into the tree again - Add_Object_Recursive(RootNode,obj); -} - -void AABTreeCullSystemClass::Collect_Objects(const Vector3 & point) -{ - Collect_Objects_Recursive(RootNode,point); -} - -void AABTreeCullSystemClass::Collect_Objects(const AABoxClass & box) -{ - Collect_Objects_Recursive(RootNode,box); -} - -void AABTreeCullSystemClass::Collect_Objects(const OBBoxClass & box) -{ - Collect_Objects_Recursive(RootNode,box); -} - -void AABTreeCullSystemClass::Collect_Objects(const FrustumClass & frustum) -{ - Collect_Objects_Recursive(RootNode,frustum,0); -} - -void AABTreeCullSystemClass::Collect_Objects(const SphereClass & sphere) -{ - Collect_Objects_Recursive(RootNode,sphere); -} - -int AABTreeCullSystemClass::Partition_Node_Count(void) const -{ - return Partition_Node_Count_Recursive(RootNode); -} - -int AABTreeCullSystemClass::Partition_Tree_Depth(void) const -{ - int get_max_depth = 0; - Partition_Tree_Depth_Recursive(RootNode,0,get_max_depth); - return get_max_depth; -} - -int AABTreeCullSystemClass::Object_Count(void) const -{ - return ObjectCount; -} - -int AABTreeCullSystemClass::Partition_Node_Count_Recursive(AABTreeNodeClass * node) const -{ - int curcount = 1; - if (node->Front) { - curcount += Partition_Node_Count_Recursive(node->Front); - } - if (node->Back) { - curcount += Partition_Node_Count_Recursive(node->Back); - } - return curcount; -} - -void AABTreeCullSystemClass::Partition_Tree_Depth_Recursive(AABTreeNodeClass * node,int cur_depth,int & max_depth) const -{ - cur_depth++; - if (cur_depth > max_depth) { - max_depth = cur_depth; - } - if (node->Front) { - Partition_Tree_Depth_Recursive(node->Front,cur_depth,max_depth); - } - if (node->Back) { - Partition_Tree_Depth_Recursive(node->Back,cur_depth,max_depth); - } -} - -void AABTreeCullSystemClass::Add_Object_Recursive(AABTreeNodeClass * node,CullableClass * obj) -{ - // order the children in terms of size - AABTreeNodeClass * big_child = node->Front; - AABTreeNodeClass * small_child = node->Back; - - if (big_child && small_child && (big_child->Compute_Volume() < small_child->Compute_Volume())) { - AABTreeNodeClass * tmp = big_child; - big_child = small_child; - small_child = tmp; - } - - // Can we fit in the smaller child? - if (small_child && small_child->Box.Contains(obj->Get_Cull_Box())) { - Add_Object_Recursive(small_child,obj); - return; - } - - // Can we fit in the bigger child? - if (big_child && big_child->Box.Contains(obj->Get_Cull_Box())) { - Add_Object_Recursive(big_child,obj); - return; - } - - // Ok, we have to fit in this node. - node->Add_Object(obj); - ObjectCount++; -} - -void AABTreeCullSystemClass::Add_Loaded_Object(AABTreeNodeClass * node,CullableClass * obj) -{ - WWASSERT(node); - WWASSERT(obj); - - WWASSERT_PRINT - ( - (obj->Get_Culling_System() == NULL), - "AABTreeCullSystemClass::Add_Loaded_Object -- Object is already in another culling system!\n" - ); - - AABTreeLinkClass * new_link = new AABTreeLinkClass(this); - obj->Set_Cull_Link(new_link); - - node->Add_Object(obj); - ObjectCount++; - obj->Add_Ref(); -} - -void AABTreeCullSystemClass::Re_Partition(void) -{ - /* - ** transfer all objects to a temporary node - */ - AABTreeNodeClass * dummy_node = new AABTreeNodeClass; - RootNode->Transfer_Objects(dummy_node); - - /* - ** delete the old tree and make the dummy node the new root - */ - delete RootNode; - RootNode = dummy_node; - - /* - ** partition the objects - */ - RootNode->Partition(); - - /* - ** re-index the nodes - */ - Re_Index_Nodes(); - - /* - ** reset the statistics - */ - Reset_Statistics(); - -} - -void AABTreeCullSystemClass::Re_Partition(const AABoxClass & bounds,SimpleDynVecClass & boxes) -{ - /* - ** transfer all objects to a temporary node - */ - AABTreeNodeClass * dummy_node = new AABTreeNodeClass; - RootNode->Transfer_Objects(dummy_node); - - /* - ** delete the old tree - */ - delete RootNode; - - /* - ** allocate a new root node and tell it to partition the given array of boxes - */ - RootNode = new AABTreeNodeClass; - RootNode->Partition(bounds,boxes); - - /* - ** re-index the nodes - */ - Re_Index_Nodes(); - - /* - ** reset statistics - */ - Reset_Statistics(); - - /* - ** re-insert all objects and delete the temporary node - */ - dummy_node->Box.Extent.Set(0,0,0); - CullableClass * obj = get_first_object(dummy_node); - while (obj != NULL) { - Update_Culling(obj); - obj = get_first_object(dummy_node); - } - - delete dummy_node; - - /* - ** Modify the root node so that any object can be added into the tree - */ - RootNode->Box.Extent.Set(FLT_MAX,FLT_MAX,FLT_MAX); -} - -void AABTreeCullSystemClass::Update_Bounding_Boxes(void) -{ - Update_Bounding_Boxes_Recursive(RootNode); -} - -const AABoxClass & AABTreeCullSystemClass::Get_Bounding_Box(void) -{ - WWASSERT(RootNode); - return RootNode->Box; -} - -void AABTreeCullSystemClass::Get_Node_Bounds(int node_id,AABoxClass * set_bounds) -{ - if ((node_id >= 0) && (node_id < NodeCount)) { - *set_bounds = IndexedNodes[node_id]->Box; - } else { - *set_bounds = IndexedNodes[0]->Box; - } -} - -void AABTreeCullSystemClass::Reset_Statistics(void) -{ - Stats.NodeCount = NodeCount; - Stats.NodesAccepted = 0; - Stats.NodesTriviallyAccepted = 0; - Stats.NodesRejected = 0; -} - -const AABTreeCullSystemClass::StatsStruct & AABTreeCullSystemClass::Get_Statistics(void) -{ - return Stats; -} - -void AABTreeCullSystemClass::Collect_Objects_Recursive(AABTreeNodeClass * node) -{ - /* - ** Collect any objects in this node - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - Add_To_Collection(obj); - obj = get_next_object(obj); - } - } - - /* - ** Statistics - */ - NODE_TRIVIALLY_ACCEPTED(); - - /* - ** Descend into the children - */ - if (node->Back) { - Collect_Objects_Recursive(node->Back); - } - if (node->Front) { - Collect_Objects_Recursive(node->Front); - } -} - - -void AABTreeCullSystemClass::Collect_Objects_Recursive(AABTreeNodeClass * node,const Vector3 & point) -{ - /* - ** Is the point inside this volume? - */ - if (node->Box.Contains(point) == false) { - NODE_REJECTED(); - return; - } - - NODE_ACCEPTED(); - - /* - ** Collect any objects in this node - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - if (obj->Get_Cull_Box().Contains(point)) { - Add_To_Collection(obj); - } - obj = get_next_object(obj); - } - } - - /* - ** Descend into the children - */ - if (node->Back) { - Collect_Objects_Recursive(node->Back,point); - } - if (node->Front) { - Collect_Objects_Recursive(node->Front,point); - } -} - -void AABTreeCullSystemClass::Collect_Objects_Recursive(AABTreeNodeClass * node,const AABoxClass & box) -{ - /* - ** Cull the given box against the bounding volume of this node - ** If it is culled, stop descending the tree. If the current node is - ** completely contained inside the given box, jump into the collection function - ** that doesn't do any more volume checking... - */ - CollisionMath::OverlapType overlap = CollisionMath::Overlap_Test(box,node->Box); - if (overlap == CollisionMath::OUTSIDE) { - NODE_REJECTED(); - return; - } else if (overlap == CollisionMath::INSIDE) { - Collect_Objects_Recursive(node); - return; - } - - NODE_ACCEPTED(); - - /* - ** Test any objects in this node - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - if (CollisionMath::Overlap_Test(box,obj->Get_Cull_Box()) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - obj = get_next_object(obj); - } - } - - /* - ** Recurse into any children - */ - if (node->Back) { - Collect_Objects_Recursive(node->Back,box); - } - if (node->Front) { - Collect_Objects_Recursive(node->Front,box); - } -} - - -void AABTreeCullSystemClass::Collect_Objects_Recursive(AABTreeNodeClass * node,const OBBoxClass & box) -{ - /* - ** Cull the given box against the bounding volume of this node - ** If it is culled, stop descending the tree. If the current node is - ** completely contained inside the given box, jump into the collection function - ** that doesn't do any more volume checking... - */ - CollisionMath::OverlapType overlap = CollisionMath::Overlap_Test(box,node->Box); - if (overlap == CollisionMath::OUTSIDE) { - NODE_REJECTED(); - return; - } else if (overlap == CollisionMath::INSIDE) { - Collect_Objects_Recursive(node); - return; - } - - NODE_ACCEPTED(); - - /* - ** Test any objects in this node - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - if (CollisionMath::Overlap_Test(box,obj->Get_Cull_Box()) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - obj = get_next_object(obj); - } - } - - /* - ** Recurse into any children - */ - if (node->Back) { - Collect_Objects_Recursive(node->Back,box); - } - if (node->Front) { - Collect_Objects_Recursive(node->Front,box); - } -} - -void AABTreeCullSystemClass::Collect_Objects_Recursive -( - AABTreeNodeClass * node, - const FrustumClass & frustum, - int planes_passed -) -{ - /* - ** Cull the bounding volume of this node against the frustum. - ** If it is culled, stop descending the tree. - */ - CollisionMath::OverlapType overlap = CollisionMath::Overlap_Test(frustum,node->Box,planes_passed); - if (overlap == CollisionMath::OUTSIDE) { - NODE_REJECTED(); - return; - } else if (overlap == CollisionMath::INSIDE) { - Collect_Objects_Recursive(node); - return; - } - - NODE_ACCEPTED(); - - /* - ** Test any objects in this node - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - if (CollisionMath::Overlap_Test(frustum,obj->Get_Cull_Box()) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - obj = get_next_object(obj); - } - } - - /* - ** Recurse into any children - */ - if (node->Back) { - Collect_Objects_Recursive(node->Back,frustum,planes_passed); - } - if (node->Front) { - Collect_Objects_Recursive(node->Front,frustum,planes_passed); - } -} - - -void AABTreeCullSystemClass::Collect_Objects_Recursive(AABTreeNodeClass * node,const SphereClass & sphere) -{ - /* - ** Is the point inside this volume? - */ - if (CollisionMath::Overlap_Test (node->Box, sphere) == CollisionMath::OUTSIDE) { - NODE_REJECTED(); - return; - } - NODE_ACCEPTED(); - - /* - ** Collect any objects in this node - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - if (CollisionMath::Overlap_Test (obj->Get_Cull_Box(), sphere) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - obj = get_next_object(obj); - } - } - - /* - ** Descend into the children - */ - if (node->Back) { - Collect_Objects_Recursive(node->Back,sphere); - } - if (node->Front) { - Collect_Objects_Recursive(node->Front,sphere); - } -} - -void AABTreeCullSystemClass::Update_Bounding_Boxes_Recursive(AABTreeNodeClass * node) -{ - MinMaxAABoxClass minmaxbox(node->Box); - - /* - ** Update child boxes first and ensure that we bound them - */ - if (node->Front) { - Update_Bounding_Boxes_Recursive(node->Front); - minmaxbox.Add_Box(node->Front->Box); - } - if (node->Back) { - Update_Bounding_Boxes_Recursive(node->Back); - minmaxbox.Add_Box(node->Back->Box); - } - - /* - ** Make sure we bound our contained objects - */ - if (node->Object) { - CullableClass * obj = get_first_object(node); - while (obj) { - minmaxbox.Add_Box(obj->Get_Cull_Box()); - obj = get_next_object(obj); - } - } - - node->Box.Init_Min_Max(minmaxbox.MinCorner,minmaxbox.MaxCorner); -} - - -void AABTreeCullSystemClass::Load(ChunkLoadClass & cload) -{ - WWASSERT_PRINT(Object_Count() == 0, "Remove all objects from AAB-Culling system before loading!\n"); - - delete RootNode; - RootNode = new AABTreeNodeClass; - - // The first chunk should be a version chunk - cload.Open_Chunk(); - if (cload.Cur_Chunk_ID() != AABTREE_CHUNK_VERSION) { - WWDEBUG_SAY(("Attempting to read an obsolete AAB-Tree!")); - cload.Close_Chunk(); - return; - } - - // read in the version and verify that it is the current version - uint32 version; - cload.Read(&version,sizeof(version)); - if (version != AABTREE_CURRENT_VERSION) { - WWDEBUG_SAY(("Attempting to read an obsolete AAB-Tree!")); - cload.Close_Chunk(); - return; - } - cload.Close_Chunk(); - - // read in the tree - Load_Nodes(RootNode,cload); - - // re-index all nodes - Re_Index_Nodes(); - - // reset the statistics - Reset_Statistics(); -} - -void AABTreeCullSystemClass::Load_Nodes(AABTreeNodeClass * node,ChunkLoadClass & cload) -{ - // Open the node description - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == AABTREE_CHUNK_AABNODE); - - // Load the node description. - // Older files will contain a chunk named AABTREE_CHUNK_AABNODE_INFO while newer - // files will contain AABTREE_CHUNK_AABNODE_VARIABLES which contains the IOAABNodeStruct - // in a micro-chunk. - IOAABNodeStruct node_desc; - memset(&node_desc,0,sizeof(IOAABNodeStruct)); - - cload.Open_Chunk(); - if (cload.Cur_Chunk_ID() == AABTREE_CHUNK_AABNODE_INFO) { - - // Loading the legacy format... - WWASSERT(cload.Cur_Chunk_ID() == AABTREE_CHUNK_AABNODE_INFO); - cload.Read(&node_desc,sizeof(node_desc)); - - } else if (cload.Cur_Chunk_ID() == AABTREE_CHUNK_AABNODE_VARIABLES) { - - // Loading the new format, contains micro chunks... - while (cload.Open_Micro_Chunk()) { - switch(cload.Cur_Micro_Chunk_ID()) { - READ_MICRO_CHUNK(cload,AABTREE_VARIABLE_NODESTRUCT,node_desc); - READ_MICRO_CHUNK(cload,AABTREE_VARIABLE_USERDATA,node->UserData); - } - cload.Close_Micro_Chunk(); - } - } - cload.Close_Chunk(); - - // Initialize the node bounds. - node->Box.Center.X = node_desc.Center.X; - node->Box.Center.Y = node_desc.Center.Y; - node->Box.Center.Z = node_desc.Center.Z; - - node->Box.Extent.X = node_desc.Extent.X; - node->Box.Extent.Y = node_desc.Extent.Y; - node->Box.Extent.Z = node_desc.Extent.Z; - - // Load the contents of the node. - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == AABTREE_CHUNK_AABNODE_CONTENTS); - Load_Node_Contents(node,cload); - cload.Close_Chunk(); - - // Close the node description - cload.Close_Chunk(); - - // if we are supposed to have a front child, load it - if (node_desc.Attributes & AABNODE_ATTRIBUTE_FRONT_CHILD) { - WWASSERT(node->Front == NULL); - node->Front = new AABTreeNodeClass(); - node->Front->Parent = node; - Load_Nodes(node->Front,cload); - } - - // if we have a back child, load it - if (node_desc.Attributes & AABNODE_ATTRIBUTE_BACK_CHILD) { - WWASSERT(node->Back == NULL); - node->Back = new AABTreeNodeClass(); - node->Back->Parent = node; - Load_Nodes(node->Back,cload); - } -} - -void AABTreeCullSystemClass::Save(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(AABTREE_CHUNK_VERSION); - uint32 version = AABTREE_CURRENT_VERSION; - csave.Write(&version,sizeof(uint32)); - csave.End_Chunk(); - - Save_Nodes(RootNode,csave); -} - -void AABTreeCullSystemClass::Save_Nodes(AABTreeNodeClass * node,ChunkSaveClass & csave) -{ - WWASSERT(node); - csave.Begin_Chunk(AABTREE_CHUNK_AABNODE); - - csave.Begin_Chunk(AABTREE_CHUNK_AABNODE_VARIABLES); - IOAABNodeStruct node_desc; - memset(&node_desc,0,sizeof(node_desc)); - - node_desc.Center.X = node->Box.Center.X; - node_desc.Center.Y = node->Box.Center.Y; - node_desc.Center.Z = node->Box.Center.Z; - - node_desc.Extent.X = node->Box.Extent.X; - node_desc.Extent.Y = node->Box.Extent.Y; - node_desc.Extent.Z = node->Box.Extent.Z; - - if (node->Front) { - node_desc.Attributes |= AABNODE_ATTRIBUTE_FRONT_CHILD; - } - - if (node->Back) { - node_desc.Attributes |= AABNODE_ATTRIBUTE_BACK_CHILD; - } - - WRITE_MICRO_CHUNK(csave,AABTREE_VARIABLE_NODESTRUCT,node_desc); - WRITE_MICRO_CHUNK(csave,AABTREE_VARIABLE_USERDATA,node->UserData); - csave.End_Chunk(); - - csave.Begin_Chunk(AABTREE_CHUNK_AABNODE_CONTENTS); - Save_Node_Contents(node,csave); - csave.End_Chunk(); - - csave.End_Chunk(); - - if (node->Front) { - Save_Nodes(node->Front,csave); - } - - if (node->Back) { - Save_Nodes(node->Back,csave); - } -} - -void AABTreeCullSystemClass::Load_Object_Linkage(ChunkLoadClass & cload,CullableClass * obj) -{ - uint32 index; - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == AABTREE_CHUNK_NODE_INDEX); - cload.Read(&index,sizeof(index)); - cload.Close_Chunk(); - - Add_Object_Internal(obj,index); -} - -void AABTreeCullSystemClass::Save_Object_Linkage(ChunkSaveClass & csave,CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - - AABTreeLinkClass * link = (AABTreeLinkClass *)obj->Get_Cull_Link(); - WWASSERT(link); - - AABTreeNodeClass * node = link->Node; - WWASSERT(node); - - uint32 index = node->Index; - csave.Begin_Chunk(AABTREE_CHUNK_NODE_INDEX); - csave.Write(&index,sizeof(index)); - csave.End_Chunk(); -} - - -void AABTreeCullSystemClass::Re_Index_Nodes(void) -{ - if (IndexedNodes != NULL) { - delete[] IndexedNodes; - IndexedNodes = NULL; - } - NodeCount = Partition_Node_Count(); - WWASSERT(NodeCount > 0); - IndexedNodes = new AABTreeNodeClass *[NodeCount]; - - int counter = 0; - Re_Index_Nodes_Recursive(RootNode,counter); - WWASSERT(counter == NodeCount); -} - - -void AABTreeCullSystemClass::Re_Index_Nodes_Recursive(AABTreeNodeClass * node,int & counter) -{ - node->Index = counter; - IndexedNodes[counter] = node; - counter++; - - if (node->Front) { - Re_Index_Nodes_Recursive(node->Front,counter); - } - if (node->Back) { - Re_Index_Nodes_Recursive(node->Back,counter); - } -} - - - -/************************************************************************* -** -** AABTreeNodeClass Implementation -** -*************************************************************************/ -AABTreeNodeClass::AABTreeNodeClass(void) : - Index(0), - Box(Vector3(0,0,0),Vector3(0,0,0)), - Parent(NULL), - Front(NULL), - Back(NULL), - Object(NULL), - UserData(0) -{ -} - -AABTreeNodeClass::~AABTreeNodeClass(void) -{ - // objects should be removed before deleting the partition tree - WWASSERT(Object == NULL); - - // delete our children - if (Front) { - delete Front; - Front = NULL; - } - if (Back) { - delete Back; - Back = NULL; - } -} - -void AABTreeNodeClass::Compute_Bounding_Box(void) -{ - /* - ** make the children update their boxes first - */ - if (Front) { - Front->Compute_Bounding_Box(); - } - - if (Back) { - Back->Compute_Bounding_Box(); - } - - Compute_Local_Bounding_Box(); -} - -void AABTreeNodeClass::Compute_Local_Bounding_Box(void) -{ - /* - ** Now make sure we bound our children - */ - MinMaxAABoxClass box(Vector3(FLT_MAX,FLT_MAX,FLT_MAX),Vector3(-FLT_MAX,-FLT_MAX,-FLT_MAX)); - - if (Front) { - box.Add_Box(Front->Box); - } - - if (Back) { - box.Add_Box(Back->Box); - } - - /* - ** bound the objects in this node - */ - CullableClass * obj = Object; - while (obj) { - box.Add_Box(obj->Get_Cull_Box()); - AABTreeLinkClass * link = (AABTreeLinkClass *)obj->Get_Cull_Link(); - obj = link->NextObject; - } - - Box.Init(box); -} - -float AABTreeNodeClass::Compute_Volume(void) -{ - return Box.Volume(); -} - -void AABTreeNodeClass::Add_Object(CullableClass * obj,bool update_bounds) -{ - AABTreeLinkClass * link = (AABTreeLinkClass *)obj->Get_Cull_Link(); - WWASSERT(link); - - link->Node = this; - link->NextObject = Object; - Object = obj; - - if (update_bounds) { - // if this is the only object and we have no children, just copy - // the object's bounding box, otherwise, add it to what we have - if ((Object_Count() == 1) && (Front == NULL) && (Back == NULL)) { - Box = obj->Get_Cull_Box(); - } else { - Box.Add_Box(obj->Get_Cull_Box()); - } - } -} - -void AABTreeNodeClass::Remove_Object(CullableClass * obj) -{ - WWASSERT(obj); - - // find the given object in our linked list - CullableClass * prevobj = NULL; - CullableClass * curobj = Object; - - while (curobj) { - - AABTreeLinkClass * link = (AABTreeLinkClass *)curobj->Get_Cull_Link(); - - if (curobj == obj) { - // found the object, unlink it. - if (prevobj) { - AABTreeLinkClass * prevlink = (AABTreeLinkClass *)prevobj->Get_Cull_Link(); - prevlink->NextObject = link->NextObject; - } else { - Object = link->NextObject; - } - - link->NextObject = NULL; - link->Node = NULL; - return; - } - - // move to the next object - prevobj = curobj; - curobj = link->NextObject; - } -} - -void AABTreeNodeClass::Transfer_Objects(AABTreeNodeClass * dummy_node) -{ - // unlink all of our objects, relinking them to the dummy_node - while (Object) { - CullableClass * obj = Object; - Remove_Object(obj); - dummy_node->Add_Object(obj); - } - - // do the same with our children - if (Front) { - Front->Transfer_Objects(dummy_node); - } - - if (Back) { - Back->Transfer_Objects(dummy_node); - } -} - -int AABTreeNodeClass::Object_Count(void) -{ - CullableClass * obj = Object; - int count = 0; - - while (obj) { - count++; - obj = ((AABTreeLinkClass *)obj->Get_Cull_Link())->NextObject; - } - - return count; -} - -CullableClass * AABTreeNodeClass::Peek_Object(int index) -{ - int count = 0; - CullableClass * obj = Object; - WWASSERT(obj != NULL); - - while (obj && (count != index)) { - count++; - obj = ((AABTreeLinkClass *)obj->Get_Cull_Link())->NextObject; - } - WWASSERT(count == index); - return obj; -} - - -/****************************************************************************************** -** -** Partitioning code which partitions the objects in the tree and passes them into -** the new children -** -******************************************************************************************/ - -void AABTreeNodeClass::Partition(void) -{ - /* - ** if we're down to only 2 objects, we're done - */ - int obj_count = Object_Count(); - if (obj_count <= 2) return; - - /* - ** Create an array of the bounding boxes of our objects - */ - SimpleDynVecClass boxes(obj_count); - CullableClass * obj = Object; - while (obj != NULL) { - boxes.Add(obj->Get_Cull_Box()); - obj = get_next_object(obj); - } - - /* - ** Select and assign the splitting plane - ** De-allocate the array of boxes to conserve memory - */ - SplitChoiceStruct sc; - Select_Splitting_Plane(&sc,boxes); - boxes.Resize(0); - - /* - ** If there was no good split, just leave all of - ** the objects in this node - */ - if (sc.Cost == FLT_MAX) { - return; - } - - /* - ** Split the tiles - */ - AABTreeNodeClass * front = new AABTreeNodeClass; - AABTreeNodeClass * back = new AABTreeNodeClass; - Split_Objects(sc,front,back); - - /* - ** Build a front tree if necessary. - */ - if (front->Object_Count() > 0) { - Front = front; - Front->Parent = this; - Front->Partition(); - } else { - delete front; - front = NULL; - } - - /* - ** Build a back tree if necessary. - */ - if (back->Object_Count() > 0) { - Back = back; - Back->Parent = this; - Back->Partition(); - } else { - delete back; - back = NULL; - } -} - - - -void AABTreeNodeClass::Split_Objects(const AABTreeNodeClass::SplitChoiceStruct & sc,AABTreeNodeClass * front,AABTreeNodeClass * back) -{ - // This function assumes that this node is a leaf - WWASSERT(Front == NULL); - WWASSERT(Back == NULL); - WWASSERT(Object_Count() == sc.FrontCount + sc.BackCount); - - int fcount = 0; - int bcount = 0; - - // unlink all of our objects, relinking them to the appropriate node - while (Object) { - - // pull the object out of this node - CullableClass * obj = Object; - Remove_Object(Object); - - // decide which node to add the object to, - // NOTE: we have to use the same convention as Compute_Score! - const AABoxClass & box = obj->Get_Cull_Box(); - - if (CollisionMath::Overlap_Test(sc.Plane,box.Center) == CollisionMath::FRONT) { - - front->Add_Object(obj); - fcount++; - - } else { - - back->Add_Object(obj); - bcount++; - - } - } - - // copy the bounding boxes - front->Box = sc.FrontBox; - front->Box.Extent += Vector3(WWMATH_EPSILON,WWMATH_EPSILON,WWMATH_EPSILON); - back->Box = sc.BackBox; - back->Box.Extent += Vector3(WWMATH_EPSILON,WWMATH_EPSILON,WWMATH_EPSILON); - - // when we are all done, the counts should match. - WWASSERT(fcount == sc.FrontCount); - WWASSERT(bcount == sc.BackCount); -} - - - - -/****************************************************************************************** -** -** Partitioning code which generates the tree based on a set of input boxes -** -******************************************************************************************/ -void AABTreeNodeClass::Partition(const AABoxClass & bounds,SimpleDynVecClass & boxes) -{ - Box = bounds; - - /* - ** if we're down to only 1 box, we're done - */ - if (boxes.Count() <= 1) return; - - /* - ** Select and assign the splitting plane - */ - SplitChoiceStruct sc; - Select_Splitting_Plane(&sc,boxes); - - /* - ** If there was no good split, just leave all of - ** the objects in this node - */ - if (sc.Cost == FLT_MAX) { - return; - } - - /* - ** Split the boxes - ** Deallocate the input box array to conserve RAM - */ - SimpleDynVecClass frontboxes(sc.FrontCount); - SimpleDynVecClass backboxes(sc.BackCount); - Split_Boxes(sc,boxes,frontboxes,backboxes); - boxes.Delete_All(); - - /* - ** Build a front tree if necessary. - */ - if (frontboxes.Count() > 0) { - Front = new AABTreeNodeClass; - Front->Parent = this; - Front->Partition(sc.FrontBox,frontboxes); - } else { - Front = NULL; - } - - /* - ** Build a back tree if necessary. - */ - if (backboxes.Count() > 0) { - Back = new AABTreeNodeClass; - Back->Parent = this; - Back->Partition(sc.BackBox,backboxes); - } else { - Back = NULL; - } -} - -void AABTreeNodeClass::Split_Boxes -( - const AABTreeNodeClass::SplitChoiceStruct & sc, - SimpleDynVecClass & boxes, - SimpleDynVecClass & frontboxes, - SimpleDynVecClass & backboxes -) -{ - WWASSERT(boxes.Count() == sc.FrontCount + sc.BackCount); - - // copy each box in the input array into the appropriate output array - for (int i=0; i & boxes -) -{ - const int NUM_TRYS = 300; - - /* - ** Try putting axis-aligned planes through some random vertices - */ - int objcount = boxes.Count(); - int trys = 0; - for (trys = 0; trys < MIN(NUM_TRYS,objcount); trys++) { - - int obj_index; - SplitChoiceStruct test; - - /* - ** Select a random object - */ - obj_index = rand() % objcount; - const AABoxClass & box = boxes[obj_index]; - - /* - ** Select a random plane which co-incides with one of the faces - ** of the object's bounding box - */ - switch(rand() % 6) { - case 0: test.Plane.Set(AAPlaneClass::XNORMAL,box.Center.X + box.Extent.X); break; - case 1: test.Plane.Set(AAPlaneClass::XNORMAL,box.Center.X - box.Extent.X); break; - case 2: test.Plane.Set(AAPlaneClass::YNORMAL,box.Center.Y + box.Extent.Y); break; - case 3: test.Plane.Set(AAPlaneClass::YNORMAL,box.Center.Y - box.Extent.Y); break; - case 4: test.Plane.Set(AAPlaneClass::ZNORMAL,box.Center.Z + box.Extent.Z); break; - case 5: test.Plane.Set(AAPlaneClass::ZNORMAL,box.Center.Z - box.Extent.Z); break; - }; - - /* - ** Get the score for this plane - */ - Compute_Score(&test,boxes); - if (test.Cost < sc->Cost) { - *sc = test; - } - - } - - /* - ** Still haven't found a valid splitting plane, uh-oh. - */ - if ((trys >= MIN(NUM_TRYS,objcount)) && (sc->Cost == FLT_MAX)) { - Select_Splitting_Plane_Brute_Force(sc,boxes); - return; - } -} - -void AABTreeNodeClass::Select_Splitting_Plane_Brute_Force -( - AABTreeNodeClass::SplitChoiceStruct * sc, - SimpleDynVecClass & boxes -) -{ - /* - ** Try putting axis-aligned planes along each face of each box - */ - int objcount = boxes.Count(); - for (int obj_index = 0; obj_index < objcount; obj_index++) { - - AAPlaneClass plane; - const AABoxClass & box = boxes[obj_index]; - - /* - ** Try each face of this box - */ - for (int plane_index = 0; plane_index < 6; plane_index++) { - SplitChoiceStruct test; - switch(plane_index % 6) { - case 0: test.Plane.Set(AAPlaneClass::XNORMAL,box.Center.X + box.Extent.X); break; - case 1: test.Plane.Set(AAPlaneClass::XNORMAL,box.Center.X - box.Center.Y); break; - case 2: test.Plane.Set(AAPlaneClass::YNORMAL,box.Center.Y + box.Center.Y); break; - case 3: test.Plane.Set(AAPlaneClass::YNORMAL,box.Center.Y - box.Center.Y); break; - case 4: test.Plane.Set(AAPlaneClass::ZNORMAL,box.Center.Z + box.Center.Z); break; - case 5: test.Plane.Set(AAPlaneClass::ZNORMAL,box.Center.Z - box.Center.Z); break; - }; - - test.FrontBox.Init_Empty(); - test.BackBox.Init_Empty(); - - /* - ** Get the score for this plane - */ - Compute_Score(&test,boxes); - if (test.Cost < sc->Cost) { - *sc = test; - } - } - } - - /* - ** Notify user that we couldn't split this node - */ -#ifdef WWDEBUG - if (sc->Cost == FLT_MAX) { - WWDEBUG_SAY(("Unable to split node! objcount = %d. (%.2f,%.2f,%.2f)\r\n",objcount,Box.Center.X, Box.Center.Y, Box.Center.Z)); - } -#endif -} - - -void AABTreeNodeClass::Compute_Score -( - AABTreeNodeClass::SplitChoiceStruct * sc, - SimpleDynVecClass & boxes -) -{ - /* - ** Suitability of a plane as a partition plane is based on the following factors: - ** - How many "tiles" are on each side of the plane, - */ - for (int i=0; iPlane,box.Center) == CollisionMath::FRONT) { - - sc->FrontCount++; - sc->FrontBox.Add_Box(box); - - } else { - - sc->BackCount++; - sc->BackBox.Add_Box(box); - - } - } - - /* - ** Compute the cost. - */ - float back_cost = sc->BackBox.Volume() * sc->BackCount; - float front_cost = sc->FrontBox.Volume() * sc->FrontCount; - - sc->Cost = front_cost + back_cost; - - if ((sc->FrontCount == 0) || (sc->BackCount == 0)) { - sc->Cost = FLT_MAX; - } -} - - - -/************************************************************************************** - - AABTreeIterator Implemenation - -**************************************************************************************/ - - -AABTreeIterator::AABTreeIterator(AABTreeCullSystemClass * tree) : - Tree(tree), - CurNodeIndex(0) -{ - WWASSERT(Tree != NULL); -} - -void AABTreeIterator::Reset(void) -{ - CurNodeIndex = 0; -} - -bool AABTreeIterator::Enter_Parent(void) -{ - validate(); - if (CurNodeIndex != 0) { - CurNodeIndex = Tree->IndexedNodes[CurNodeIndex]->Parent->Index; - return true; - } else { - return false; - } -} - -bool AABTreeIterator::Enter_Sibling(void) -{ - validate(); - if (CurNodeIndex != 0) { - - /* - ** find which child of our parent we are - */ - AABTreeNodeClass * parent = Tree->IndexedNodes[CurNodeIndex]->Parent; - AABTreeNodeClass * parent_front = parent->Front; - AABTreeNodeClass * parent_back = parent->Back; - - /* - ** if our parent doesn't have two children, we don't have a sibling - */ - if ((parent_front == NULL) || (parent_back == NULL)) { - return false; - } - - /* - ** if we our our parent's front child, go to its back child - */ - if ((int)parent_front->Index == CurNodeIndex) { - CurNodeIndex = parent_back->Index; - return true; - } - - /* - ** if we our our parent's back child, go to its front child - */ - if ((int)parent_back->Index == (int)CurNodeIndex) { - CurNodeIndex = parent_front->Index; - return true; - } - } - return false; -} - -bool AABTreeIterator::Has_Front_Child(void) -{ - validate(); - return (Tree->IndexedNodes[CurNodeIndex]->Front != NULL); -} - -bool AABTreeIterator::Enter_Front_Child(void) -{ - validate(); - if (Has_Front_Child()) { - CurNodeIndex = Tree->IndexedNodes[CurNodeIndex]->Front->Index; - return true; - } - return false; -} - -bool AABTreeIterator::Has_Back_Child(void) -{ - validate(); - return (Tree->IndexedNodes[CurNodeIndex]->Back != NULL); -} - -bool AABTreeIterator::Enter_Back_Child(void) -{ - if (Has_Back_Child()) { - CurNodeIndex = Tree->IndexedNodes[CurNodeIndex]->Back->Index; - return true; - } - return false; -} - -int AABTreeIterator::Get_Current_Node_Index(void) -{ - return CurNodeIndex; -} - -void AABTreeIterator::Get_Current_Box(AABoxClass * set_box) -{ - Tree->Get_Node_Bounds(CurNodeIndex,set_box); -} - -void AABTreeIterator::validate(void) -{ - if ((CurNodeIndex < 0) || (CurNodeIndex >= Tree->NodeCount)) { - CurNodeIndex = 0; - } -} - -/* - - Can we make a more compact AABTree? - - Here is the existing data in each Node: - - uint32 Index; // Index of this node - AABoxClass Box; // Bounding box of the node - AABTreeNodeClass * Parent; // parent of this node - AABTreeNodeClass * Front; // front node - AABTreeNodeClass * Back; // back node - CullableClass * Object; // objects in this node - uint32 UserData; // 32bit field for the user, initialized to 0 - - Total Size: 48 bytes - - Here is a possible replacement: - - uint16 Index; - short x,y,z,w,l,h; // Need origin and scale factors for the boxes stored in tree - uint16 ParentIndex; - uint16 FrontIndex; - uint16 BackIndex; - CullableClass * Object; - uint32 UserData; - - Total Size: 28 bytes - -*/ \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.h deleted file mode 100644 index 14f0f7d079..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/aabtreecull.h +++ /dev/null @@ -1,344 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/aabtreecull.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 7/24/01 10:00a $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AABTREECULL_H -#define AABTREECULL_H - -#include "cullsys.h" -#include "aaplane.h" -#include "wwmath.h" -#include "mempool.h" -#include "simplevec.h" -#include -#include - -class AABTreeNodeClass; -class ChunkLoadClass; -class ChunkSaveClass; -class SphereClass; - -/** -** AABTreeCullSystemClass -** Derived culling system that uses an Axis-Aligned Bounding Box Tree -*/ -class AABTreeCullSystemClass : public CullSystemClass -{ -public: - - AABTreeCullSystemClass(void); - virtual ~AABTreeCullSystemClass(void); - - /* - ** Re-partition the tree. Two methods can be used to accomplish this. The - ** first re-partitions the tree based on the objects contained within, the second - ** re-partitions the tree based solely on a set of input "seed" boxes. Each seed - ** box will become a leaf; then the objects will be re-inserted in the new tree. - */ - void Re_Partition(void); - void Re_Partition(const AABoxClass & bounds,SimpleDynVecClass & boxes); - - /* - ** Update_Bounding_Boxes. This function causes all bounding boxes in the tree to update themselves. - ** If any box is found to not bound the objects it is supposed to contain, the box is updated - ** Note that this is normally not necessary, the reason this function existsis due to the fact - ** that the renegade level editor tries to do everything possible to not discard the precalculated - ** visibilty data for a level. In some cases, we want to load geometry that has been edited back - ** into the same AABTree without re-partitioning. - */ - void Update_Bounding_Boxes(void); - - /* - ** Re-insert an object into the tree - */ - virtual void Update_Culling(CullableClass * obj); - - /* - ** Statistics about the AAB-Tree - */ - int Partition_Node_Count(void) const; - int Partition_Tree_Depth(void) const; - int Object_Count(void) const; - - /* - ** Collect objects which overlap the given primitive - */ - virtual void Collect_Objects(const Vector3 & point); - virtual void Collect_Objects(const AABoxClass & box); - virtual void Collect_Objects(const OBBoxClass & box); - virtual void Collect_Objects(const FrustumClass & frustum); - virtual void Collect_Objects(const SphereClass & sphere); - - /* - ** Load and Save a description of this AAB-Tree and its contents - */ - virtual void Load(ChunkLoadClass & cload); - virtual void Save(ChunkSaveClass & csave); - - /* - ** Save an objects linkage, load the linkage and re-link the object - */ - void Load_Object_Linkage(ChunkLoadClass & cload,CullableClass * obj); - void Save_Object_Linkage(ChunkSaveClass & csave,CullableClass * obj); - - /* - ** Bounding box of the entire tree - */ - const AABoxClass & Get_Bounding_Box(void); - void Get_Node_Bounds(int node_id,AABoxClass * set_bounds); - - /* - ** Statistics - */ - struct StatsStruct - { - int NodeCount; - int NodesAccepted; - int NodesTriviallyAccepted; - int NodesRejected; - }; - - void Reset_Statistics(void); - const StatsStruct & Get_Statistics(void); - -protected: - - /* - ** Internal stat tracking - */ -#ifdef WWDEBUG - void NODE_ACCEPTED(void) { Stats.NodesAccepted ++; } - void NODE_TRIVIALLY_ACCEPTED(void) { Stats.NodesTriviallyAccepted ++; } - void NODE_REJECTED(void) { Stats.NodesRejected ++; } -#else - void NODE_ACCEPTED(void) { } - void NODE_TRIVIALLY_ACCEPTED(void) { } - void NODE_REJECTED(void) { } -#endif - - /* - ** Internal functions - */ - void Add_Object_Internal(CullableClass * obj,int node_index = -1); - void Remove_Object_Internal(CullableClass * obj); - - void Re_Index_Nodes(void); - void Re_Index_Nodes_Recursive(AABTreeNodeClass * node,int & counter); - - int Partition_Node_Count_Recursive(AABTreeNodeClass * node) const; - void Partition_Tree_Depth_Recursive(AABTreeNodeClass * node,int cur_depth,int & max_depth) const; - void Add_Object_Recursive(AABTreeNodeClass * node,CullableClass * obj); - void Add_Loaded_Object(AABTreeNodeClass * node,CullableClass * obj); - - void Collect_Objects_Recursive(AABTreeNodeClass * node); - void Collect_Objects_Recursive(AABTreeNodeClass * node,const Vector3 & point); - void Collect_Objects_Recursive(AABTreeNodeClass * node,const AABoxClass & box); - void Collect_Objects_Recursive(AABTreeNodeClass * node,const OBBoxClass & box); - void Collect_Objects_Recursive(AABTreeNodeClass * node,const FrustumClass & frustum); - void Collect_Objects_Recursive(AABTreeNodeClass * node,const FrustumClass & frustum,int planes_passed); - void Collect_Objects_Recursive(AABTreeNodeClass * node,const SphereClass & sphere); - - void Update_Bounding_Boxes_Recursive(AABTreeNodeClass * node); - - void Load_Nodes(AABTreeNodeClass * node,ChunkLoadClass & cload); - void Save_Nodes(AABTreeNodeClass * node,ChunkSaveClass & csave); - - virtual void Load_Node_Contents(AABTreeNodeClass * /*node*/,ChunkLoadClass & /*cload*/) { } - virtual void Save_Node_Contents(AABTreeNodeClass * /*node*/,ChunkSaveClass & /*csave*/) { } - - AABTreeNodeClass * RootNode; // root of the AAB-Tree - int ObjectCount; // number of objects in the system - - int NodeCount; // number of nodes - AABTreeNodeClass ** IndexedNodes; // index access to the nodes - - StatsStruct Stats; - - friend class AABTreeIterator; -}; - - -/** -** AABTreeIterator -** This iterator allows the user to walk a tree. It can return the index of the current -** node and the bounds of the current node. -*/ -class AABTreeIterator -{ -public: - AABTreeIterator(AABTreeCullSystemClass * tree); - - void Reset(void); - bool Enter_Parent(void); - bool Enter_Sibling(void); - bool Has_Front_Child(void); - bool Enter_Front_Child(void); - bool Has_Back_Child(void); - bool Enter_Back_Child(void); - - int Get_Current_Node_Index(void); - void Get_Current_Box(AABoxClass * set_box); - -private: - - void validate(void); - - AABTreeCullSystemClass * Tree; - int CurNodeIndex; - -}; - - -/** -** TypedAABTreeCullSystemClass -** This template adds type-safety to an AABTree. It allows you to create trees -** containing a particular type of object (the class must be derived from CullableClass though) -*/ -template class TypedAABTreeCullSystemClass : public AABTreeCullSystemClass -{ -public: - - virtual void Add_Object(T * obj,int node_index=-1) { Add_Object_Internal(obj,node_index); } - virtual void Remove_Object(T * obj) { Remove_Object_Internal(obj); } - - T * Get_First_Collected_Object(void) { return (T*)Get_First_Collected_Object_Internal(); } - T * Get_Next_Collected_Object(T * obj) { return (T*)Get_Next_Collected_Object_Internal(obj); } - T * Peek_First_Collected_Object(void) { return (T*)Peek_First_Collected_Object_Internal(); } - T * Peek_Next_Collected_Object(T * obj) { return (T*)Peek_Next_Collected_Object_Internal(obj); } -}; - - - - -/** -** AABTreeNodeClass - the aab-tree is built out of these objects -** CullableClass's can be linked into any of these nodes. Whenever the -** tree is re-built, all objects will end up in the leaf nodes. Between -** re-builds, as objects are added, they will be placed as deep into the -** tree as possible. -*/ -class AABTreeNodeClass : public AutoPoolClass -{ - -public: - - AABTreeNodeClass(void); - ~AABTreeNodeClass(void); - - void Add_Object(CullableClass * obj,bool update_bounds = true); - void Remove_Object(CullableClass * obj); - int Object_Count(void); - CullableClass * Peek_Object(int index); - - uint32 Index; // Index of this node - AABoxClass Box; // Bounding box of the node - AABTreeNodeClass * Parent; // parent of this node - AABTreeNodeClass * Front; // front node - AABTreeNodeClass * Back; // back node - CullableClass * Object; // objects in this node - uint32 UserData; // 32bit field for the user, initialized to 0 - - /* - ** Construction support: - */ - struct SplitChoiceStruct - { - SplitChoiceStruct(void) : Cost(FLT_MAX),FrontCount(0),BackCount(0),Plane(AAPlaneClass::XNORMAL,0.0f) - { - FrontBox.Init_Empty(); - BackBox.Init_Empty(); - } - - float Cost; - int FrontCount; - int BackCount; - MinMaxAABoxClass FrontBox; - MinMaxAABoxClass BackBox; - AAPlaneClass Plane; - }; - - void Compute_Bounding_Box(void); - void Compute_Local_Bounding_Box(void); - float Compute_Volume(void); - void Transfer_Objects(AABTreeNodeClass * dummy_node); - - /* - ** Partition the tree based on the objects contained. - */ - void Partition(void); - void Split_Objects( const SplitChoiceStruct & sc, - AABTreeNodeClass * front, - AABTreeNodeClass * back); - - /* - ** Partition the tree based on a set of input "seed" boxes. - */ - void Partition(const AABoxClass & bounds,SimpleDynVecClass & boxes); - void Split_Boxes( const SplitChoiceStruct & sc, - SimpleDynVecClass & boxes, - SimpleDynVecClass & frontboxes, - SimpleDynVecClass & backboxes); - - /* - ** Functions used by both partitioning algorithms - */ - void Select_Splitting_Plane(SplitChoiceStruct * sc,SimpleDynVecClass & boxes); - void Select_Splitting_Plane_Brute_Force(SplitChoiceStruct * sc,SimpleDynVecClass & boxes); - void Compute_Score(SplitChoiceStruct * sc,SimpleDynVecClass & boxes); -}; - - -/* -** AABTreeLinkClass -** This structure is used to link objects into an AAB-Tree culling system. -*/ -class AABTreeLinkClass : public CullLinkClass, public AutoPoolClass -{ -public: - AABTreeLinkClass(AABTreeCullSystemClass * system) : CullLinkClass(system),Node(NULL), NextObject(NULL) { } - - AABTreeNodeClass * Node; // partition node containing this object - CullableClass * NextObject; // next object in the node -}; - - - - -#endif // AABTREECULL_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/aaplane.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/aaplane.h deleted file mode 100644 index 2f52f7633f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/aaplane.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/aaplane.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/19/00 3:12p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AAPLANE_H -#define AAPLANE_H - -#include "always.h" -#include "vector3.h" - - -/* -** This class is used to describe an "axis-aligned" plane. I.e, the normal -** of the plane is one of the three coordinate axes. -*/ -class AAPlaneClass -{ -public: - - enum AxisEnum { XNORMAL = 0, YNORMAL = 1, ZNORMAL = 2 }; - - AAPlaneClass(void) { } - AAPlaneClass(AxisEnum normal,float dist) : Normal(normal),Dist(dist) { } - - void Set(AxisEnum normal,float dist); - void Get_Normal(Vector3 * normal) const; - -public: - - AxisEnum Normal; - float Dist; - -}; - -inline void AAPlaneClass::Set(AxisEnum normal,float dist) -{ - Normal = normal; - Dist = dist; -} - -inline void AAPlaneClass::Get_Normal(Vector3 * normal) const -{ - normal->Set(0,0,0); - (*normal)[Normal] = 1.0f; -} - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp deleted file mode 100644 index 8cee401122..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/cardinalspline.cpp +++ /dev/null @@ -1,355 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/cardinalspline.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "cardinalspline.h" -#include "wwdebug.h" -#include "persistfactory.h" -#include "wwmathids.h" -#include "wwhack.h" - -/* -** Force-Link this module because the linker can't detect that we actually need it... -*/ -DECLARE_FORCE_LINK(cardinalspline); - - -/* -** Save-Load stuff -*/ -SimplePersistFactoryClass _CardinalSpline3DFactory; -SimplePersistFactoryClass _CardinalSpline1DFactory; - -enum -{ - // ID's used by CardinalSpline3D - CARDINAL3D_CHUNK_HERMITE3D = 0x02070957, - CARDINAL3D_CHUNK_TIGHTNESSKEYS, - - // ID's used by CardinalSpline1D - CARDINAL1D_CHUNK_HERMITE1D = 0x02070959, - CARDINAL1D_CHUNK_TIGHTNESSKEYS -}; - - -/* -** CardinalSpline3DClass Implementation -*/ -int CardinalSpline3DClass::Add_Key(const Vector3 & point,float t) -{ - int index = HermiteSpline3DClass::Add_Key(point,t); - float tightness = 0.5f; - Tightness.Insert(index,tightness); - return index; -} - -void CardinalSpline3DClass::Remove_Key(int i) -{ - Tightness.Delete(i); - HermiteSpline3DClass::Remove_Key(i); -} - -void CardinalSpline3DClass::Clear_Keys(void) -{ - Tightness.Clear(); - HermiteSpline3DClass::Clear_Keys(); -} - -void CardinalSpline3DClass::Set_Tightness(int i,float tightness) -{ - WWASSERT(i >= 0); - WWASSERT(i < Tightness.Count()); - Tightness[i] = tightness; - TangentsDirty = true; -} - -float CardinalSpline3DClass::Get_Tightness(int i) -{ - return Tightness[i]; -} - -void CardinalSpline3DClass::Update_Tangents(void) -{ - if (Keys.Count() < 2) { - for (int i=0; i= 0); - WWASSERT(i < Tightness.Count()); - Tightness[i] = tightness; - TangentsDirty = true; -} - -float CardinalSpline1DClass::Get_Tightness(int i) -{ - return Tightness[i]; -} - -void CardinalSpline1DClass::Update_Tangents(void) -{ - if (Keys.Count() < 2) { - for (int i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/cardinalspline.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CARDINALSPLINE_H -#define CARDINALSPLINE_H - -#include "hermitespline.h" - -/** -** CardinalSpline3DClass -** 3-Dimensional cardinal splines -*/ -class CardinalSpline3DClass : public HermiteSpline3DClass -{ -public: - - virtual int Add_Key(const Vector3 & point,float t); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - - virtual void Set_Tightness(int i,float tightness); - virtual float Get_Tightness(int i); - - virtual void Update_Tangents(void); - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); - -protected: - - DynamicVectorClass Tightness; -}; - - -/** -** CardinalSpline1DClass -** 1-Dimensional cardinal splines -*/ -class CardinalSpline1DClass : public HermiteSpline1DClass -{ -public: - - virtual int Add_Key(float point,float t); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - - virtual void Set_Tightness(int i,float tightness); - virtual float Get_Tightness(int i); - - virtual void Update_Tangents(void); - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); - -protected: - - DynamicVectorClass Tightness; -}; - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/castres.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/castres.h deleted file mode 100644 index e1bf216998..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/castres.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/castres.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 11/14/00 2:59p $* - * * - * $Revision:: 10 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CASTRES_H -#define CASTRES_H - -#include "always.h" -#include "vector3.h" -#include "bittype.h" - - -/** -** CastResultStruct -** Result of a volume or ray cast operation will be stored in the following structure -** NOTE: If you can avoid it, do not enable ComputeContactPoint. When casting rays, it is more -** efficient to use the resulting Fraction to compute the contact point outside of the -** collision detection code. In the case of AABox sweeping for character collision detection, -** you don't usually need the actual point of contact, etc etc. -** -** The default state of ComputeContactPoint is *false* -*/ -struct CastResultStruct -{ - CastResultStruct(void) { Reset(); } - void Reset(void) { StartBad = false; Fraction = 1.0f; Normal.Set(0,0,0); SurfaceType = 0; ComputeContactPoint = false; ContactPoint.Set(0,0,0); } - - bool StartBad; // was the inital configuration interpenetrating something? - float Fraction; // fraction of the move up until collision - Vector3 Normal; // surface normal at the collision point - uint32 SurfaceType; // surface type of polygon at collision point (see W3D_SURFACE_TYPES in w3d_file.h) - - bool ComputeContactPoint; // This signals the collision code to compute the point of collision - Vector3 ContactPoint; // This will be set to the point of collision if ComputeContactPoint is true - -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp deleted file mode 100644 index e6e70b983f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/catmullromspline.cpp +++ /dev/null @@ -1,354 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/catmullromspline.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/08/00 8:50p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CatmullRomSpline3DClass::Update_Tangents -- computes the tangents at each key * - * CatmullRomSpline3DClass::Get_Factory -- returns the factory for CatmullRomSpline3D * - * CatmullRomSpline3DClass::Save -- save this curve * - * CatmullRomSpline3DClass::Load -- load this curve * - * CatmullRomSpline1DClass::Update_Tangents -- Computes the tangents at each key * - * CatmullRomSpline1DClass::Get_Factory -- returns the factory for CatmullRomSpline1D * - * CatmullRomSpline1DClass::Save -- Save this curve * - * CatmullRomSpline1DClass::Load -- Load this curve * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "catmullromspline.h" -#include "persistfactory.h" -#include "wwmathids.h" -#include "wwhack.h" - -/* -** Force-Link this module because the linker can't detect that we actually need it... -*/ -DECLARE_FORCE_LINK(catmullromspline); - -/* -** Save-Load stuff -*/ -SimplePersistFactoryClass _CatmullRomSpline3DFactory; -SimplePersistFactoryClass _CatmullRomSpline1DFactory; - -enum -{ - // ID's used by CatmullRomSpline3D - CATMULLROM3D_CHUNK_HERMITE3D = 0x00020727, - - // ID's used by CatmullRomSpline1D - CATMULLROM1D_CHUNK_HERMITE1D = 0x00020729, -}; - - -/* -** Catmull-Rom 3D spline implementation -*/ - -/*********************************************************************************************** - * CatmullRomSpline3DClass::Update_Tangents -- computes the tangents at each key * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * I'm not sure about the tangents for the endpoints of the curve. * - * * - * HISTORY: * - * 3/7/2000 gth : Created. * - *=============================================================================================*/ -void CatmullRomSpline3DClass::Update_Tangents(void) -{ - if (Keys.Count() < 2) { - for (int i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/catmullromspline.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/07/00 9:51a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CATMULLROMSPLINE_H -#define CATMULLROMSPLINE_H - -#include "hermitespline.h" - -/** -** CatmullRomSpline3DClass -** This is is an implementation of 3D catmull-rom splines -*/ -class CatmullRomSpline3DClass : public HermiteSpline3DClass -{ -public: - void Update_Tangents(void); - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); -}; - - -/** -** CatmullRomSpline1DClass -** This is is an implementation of 1D catmull-rom splines -*/ -class CatmullRomSpline1DClass : public HermiteSpline1DClass -{ -public: - void Update_Tangents(void); - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmath.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmath.cpp deleted file mode 100644 index 86cae720b2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmath.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmath.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/16/00 2:19p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" - -const float CollisionMath::COINCIDENCE_EPSILON = 0.000001f; -CollisionMath::ColmathStatsStruct CollisionMath::Stats; - -CollisionMath::ColmathStatsStruct::ColmathStatsStruct(void) -{ - Reset(); -} - -void CollisionMath::ColmathStatsStruct::Reset(void) -{ - TotalCollisionCount = 0; - TotalCollisionHitCount = 0; - - CollisionRayTriCount = 0; - CollisionRayTriHitCount = 0; - - CollisionAABoxTriCount = 0; - CollisionAABoxTriHitCount = 0; - CollisionAABoxAABoxCount = 0; - CollisionAABoxAABoxHitCount = 0; - - CollisionOBBoxTriCount = 0; - CollisionOBBoxTriHitCount = 0; - CollisionOBBoxAABoxCount = 0; - CollisionOBBoxAABoxHitCount = 0; - CollisionOBBoxOBBoxCount = 0; - CollisionOBBoxOBBoxHitCount = 0; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmath.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmath.h deleted file mode 100644 index 41a1c85e0c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmath.h +++ /dev/null @@ -1,312 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmath.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/04/01 8:25p $* - * * - * $Revision:: 19 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLMATH_H -#define COLMATH_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef VECTOR3_H -#include "vector3.h" -#endif - -#ifndef CASTRES_H -#include "castres.h" -#endif - -class AAPlaneClass; -class PlaneClass; -class LineSegClass; -class TriClass; -class SphereClass; -class AABoxClass; -class OBBoxClass; -class FrustumClass; - -const float COLLISION_EPSILON = 0.001f; - -/* -** #define COLMATH_STAT_TRACKING to enable stat tracking for the collision math functions -*/ -#ifdef WWDEBUG -#define COLMATH_STAT_TRACKING -#endif - - -/** -** CollisionMath -** This is a collection of the low-level math functions for collision detection. -*/ -class CollisionMath -{ -public: - - //////////////////////////////////////////////////////////////////////////////////////// - // Intersect Functions. - // These functions simply return a bool indicating whether the two operands intersect. - //////////////////////////////////////////////////////////////////////////////////////// - static bool Intersection_Test(const AABoxClass & box,const TriClass & tri); - static bool Intersection_Test(const AABoxClass & box,const AABoxClass & box2); - static bool Intersection_Test(const AABoxClass & box,const OBBoxClass & box2); - static bool Intersection_Test(const OBBoxClass & box,const TriClass & tri); - static bool Intersection_Test(const OBBoxClass & box,const AABoxClass & box2); - static bool Intersection_Test(const OBBoxClass & box,const OBBoxClass & box2); - static bool Intersection_Test(const SphereClass & sphere,const AABoxClass & box); - static bool Intersection_Test(const SphereClass & sphere,const OBBoxClass & box); - - //////////////////////////////////////////////////////////////////////////////////////// - // Overlap Functions. - // Classify the second operand with respect to the first operand. - // For example Overlap_Test(plane,point) tests whether 'point' is in front of or - // behind 'plane'. - // OverlapType: This enumeration is the result of an overlap test. - // It indicates whether the the object is in the positive (front/outside) space - // of the volume, the negative (back/inside) space of the volume, or both (overlapping) - //////////////////////////////////////////////////////////////////////////////////////// - enum OverlapType - { - POS = 0x01, - NEG = 0x02, - ON = 0x04, - BOTH = 0x08, - OUTSIDE = POS, - INSIDE = NEG, - OVERLAPPED = BOTH, - FRONT = POS, - BACK = NEG - }; - - // AAPlane functions. Where is operand B with respect to this AAPlane - static OverlapType Overlap_Test(const AAPlaneClass & plane,const Vector3 & point); - static OverlapType Overlap_Test(const AAPlaneClass & plane,const LineSegClass & line); - static OverlapType Overlap_Test(const AAPlaneClass & plane,const TriClass & tri); - static OverlapType Overlap_Test(const AAPlaneClass & plane,const SphereClass & sphere); - static OverlapType Overlap_Test(const AAPlaneClass & plane,const AABoxClass & box); - static OverlapType Overlap_Test(const AAPlaneClass & plane,const OBBoxClass & box); - - // Plane functions. Where is operand B with respect to the plane - static OverlapType Overlap_Test(const PlaneClass & plane,const Vector3 & point); - static OverlapType Overlap_Test(const PlaneClass & plane,const LineSegClass & line); - static OverlapType Overlap_Test(const PlaneClass & plane,const TriClass & tri); - static OverlapType Overlap_Test(const PlaneClass & plane,const SphereClass & sphere); - static OverlapType Overlap_Test(const PlaneClass & plane,const Vector3 & center,const Vector3 & extent); - inline static OverlapType Overlap_Test(const PlaneClass & plane,const AABoxClass & box); - static OverlapType Overlap_Test(const PlaneClass & plane,const OBBoxClass & box); - - // Sphere functions. Where is operand B with respect to the sphere - static OverlapType Overlap_Test(const SphereClass & sphere,const Vector3 & point); - static OverlapType Overlap_Test(const SphereClass & sphere,const LineSegClass & line); - static OverlapType Overlap_Test(const SphereClass & sphere,const TriClass & tri); - static OverlapType Overlap_Test(const SphereClass & sphere,const SphereClass & sphere2); - static OverlapType Overlap_Test(const SphereClass & sphere,const AABoxClass & aabox); - static OverlapType Overlap_Test(const SphereClass & sphere,const OBBoxClass & obbox); - - // AABox functions. Where is operand B with respect to the AABox - static OverlapType Overlap_Test(const AABoxClass & box,const Vector3 & point); - static OverlapType Overlap_Test(const AABoxClass & box,const LineSegClass & line); - static OverlapType Overlap_Test(const AABoxClass & box,const TriClass & tri); - static OverlapType Overlap_Test(const AABoxClass & box,const AABoxClass & box2); - static OverlapType Overlap_Test(const AABoxClass & box,const OBBoxClass & obbox); - static OverlapType Overlap_Test(const AABoxClass & box,const SphereClass & sphere); - - // OBBox functions, where is operand B with respect to the OBBox - static OverlapType Overlap_Test(const OBBoxClass & box,const Vector3 & point); - static OverlapType Overlap_Test(const OBBoxClass & box,const LineSegClass & line); - static OverlapType Overlap_Test(const OBBoxClass & box,const TriClass & tri); - static OverlapType Overlap_Test(const OBBoxClass & box,const AABoxClass & box2); - static OverlapType Overlap_Test(const OBBoxClass & box,const OBBoxClass & box2); - - // Frustum functions - static OverlapType Overlap_Test(const FrustumClass & frustum,const Vector3 & point); - static OverlapType Overlap_Test(const FrustumClass & frustum,const TriClass & tri); - static OverlapType Overlap_Test(const FrustumClass & frustum,const SphereClass & sphere); - static OverlapType Overlap_Test(const FrustumClass & frustum,const AABoxClass & box); - static OverlapType Overlap_Test(const FrustumClass & frustum,const OBBoxClass & box); - - // Frustum functions for hierachical culling systems. - // At your root node, just pass in planes_passed = 0, then the variable will be modified to - // indicate which planes that volume was inside. You can then pass that value in for the - // test of all child nodes and optimize away some of the tests. See AABTreeCullSystemClass - // for an example usage. - static OverlapType Overlap_Test(const FrustumClass & frustum,const AABoxClass & box,int & planes_passed); - static OverlapType Overlap_Test(const FrustumClass & frustum,const OBBoxClass & box,int & planes_passed); - - // Miscellaneous other Overlap tests - static OverlapType Overlap_Test(const Vector3 & min,const Vector3 & max,const LineSegClass & line); - - //////////////////////////////////////////////////////////////////////////////////////// - // Collision Functions. - // Collide the first operand into the last operand. - // For example Collide(box,move,tri) tests for collision between a box moving into - // a triangle. - //////////////////////////////////////////////////////////////////////////////////////// - - // Line segment functions. Intersect this line segment with the given object - static bool Collide(const LineSegClass & line,const AAPlaneClass & plane,CastResultStruct * result); - static bool Collide(const LineSegClass & line,const PlaneClass & plane,CastResultStruct * result); - static bool Collide(const LineSegClass & line,const TriClass & tri,CastResultStruct * result); - static bool Collide(const LineSegClass & line,const SphereClass & sphere,CastResultStruct * result); - static bool Collide(const LineSegClass & line,const AABoxClass & box,CastResultStruct * result); - static bool Collide(const LineSegClass & line,const OBBoxClass & box,CastResultStruct * result); - - // AABox functions - static bool Collide(const AABoxClass & box,const Vector3 & move,const PlaneClass & plane,CastResultStruct * result); - static bool Collide(const AABoxClass & box,const Vector3 & move,const TriClass & tri,CastResultStruct * result); - static bool Collide(const AABoxClass & box,const Vector3 & move,const AABoxClass & box2,CastResultStruct * result); - static bool Collide(const AABoxClass & box,const Vector3 & move,const OBBoxClass & box2,const Vector3 & move2,CastResultStruct * result); - - // OBBox functions - static bool Collide(const OBBoxClass & box,const Vector3 & move,const PlaneClass & plane,CastResultStruct * result); - static bool Collide(const OBBoxClass & box,const Vector3 & move,const TriClass & tri,const Vector3 & move2,CastResultStruct * result); - static bool Collide(const OBBoxClass & box,const Vector3 & move,const AABoxClass & box2,const Vector3 & move2,CastResultStruct * result); - static bool Collide(const OBBoxClass & box,const Vector3 & move,const OBBoxClass & box2,const Vector3 & move2,CastResultStruct * result); - - //////////////////////////////////////////////////////////////////////////////////////// - // Stats - // Note that these functions will only work if you have stat tracking enabled - //////////////////////////////////////////////////////////////////////////////////////// - struct ColmathStatsStruct - { - ColmathStatsStruct(void); - void Reset(void); - - int TotalCollisionCount; - int TotalCollisionHitCount; - - int CollisionRayTriCount; - int CollisionRayTriHitCount; - - int CollisionAABoxTriCount; - int CollisionAABoxTriHitCount; - int CollisionAABoxAABoxCount; - int CollisionAABoxAABoxHitCount; - - int CollisionOBBoxTriCount; - int CollisionOBBoxTriHitCount; - int CollisionOBBoxAABoxCount; - int CollisionOBBoxAABoxHitCount; - int CollisionOBBoxOBBoxCount; - int CollisionOBBoxOBBoxHitCount; - }; - - static void Reset_Stats(void) { Stats.Reset(); } - static const ColmathStatsStruct & Get_Current_Stats(void) { return Stats; } - -private: - - static OverlapType eval_overlap_mask(int mask); - static OverlapType eval_overlap_collision(const CastResultStruct & res); - - static const float COINCIDENCE_EPSILON; - - static ColmathStatsStruct Stats; -}; - - -inline CollisionMath::OverlapType CollisionMath::eval_overlap_mask(int mask) -{ - // check if all verts are "ON" - if (mask == ON) { - return ON; - } - - // check if all verts are either "ON" or "POS" - if ((mask & ~(POS | ON)) == 0) { - return POS; - } - - // check if all verts are either "ON" or "BACK" - if ((mask & ~(NEG | ON)) == 0) { - return NEG; - } - - // otherwise, poly spans the plane. - return BOTH; -} - - -inline CollisionMath::OverlapType CollisionMath::eval_overlap_collision(const CastResultStruct & res) -{ - if (res.Fraction < 1.0f) { - return BOTH; - } else { - if (res.StartBad) { - return NEG; - } else { - return POS; - } - } -} - - -/* -** Stat tracking Macros -*/ -#ifdef COLMATH_STAT_TRACKING -#define TRACK_COLLISION_RAY_TRI Stats.CollisionRayTriCount++; Stats.TotalCollisionCount++; -#define TRACK_COLLISION_RAY_TRI_HIT Stats.CollisionRayTriHitCount++; Stats.TotalCollisionHitCount; -#define TRACK_COLLISION_AABOX_TRI Stats.CollisionAABoxTriCount++; Stats.TotalCollisionCount++; -#define TRACK_COLLISION_AABOX_TRI_HIT Stats.CollisionAABoxTriHitCount++; Stats.TotalCollisionHitCount++; -#define TRACK_COLLISION_AABOX_AABOX Stats.CollisionAABoxAABoxCount++; Stats.TotalCollisionCount++; -#define TRACK_COLLISION_AABOX_AABOX_HIT Stats.CollisionAABoxAABoxHitCount++; Stats.TotalCollisionHitCount++; -#define TRACK_COLLISION_OBBOX_TRI Stats.CollisionOBBoxTriCount++; Stats.TotalCollisionCount++; -#define TRACK_COLLISION_OBBOX_TRI_HIT Stats.CollisionOBBoxTriHitCount++; Stats.TotalCollisionHitCount++; -#define TRACK_COLLISION_OBBOX_AABOX Stats.CollisionOBBoxAABoxCount++; Stats.TotalCollisionCount++; -#define TRACK_COLLISION_OBBOX_AABOX_HIT Stats.CollisionOBBoxAABoxHitCount++; Stats.TotalCollisionHitCount++; -#define TRACK_COLLISION_OBBOX_OBBOX Stats.CollisionOBBoxOBBoxCount++; Stats.TotalCollisionCount++; -#define TRACK_COLLISION_OBBOX_OBBOX_HIT Stats.CollisionOBBoxOBBoxHitCount++; Stats.TotalCollisionHitCount++; -#else -#define TRACK_COLLISION_RAY_TRI -#define TRACK_COLLISION_RAY_TRI_HIT -#define TRACK_COLLISION_AABOX_TRI -#define TRACK_COLLISION_AABOX_TRI_HIT -#define TRACK_COLLISION_AABOX_AABOX -#define TRACK_COLLISION_AABOX_AABOX_HIT -#define TRACK_COLLISION_OBBOX_TRI -#define TRACK_COLLISION_OBBOX_TRI_HIT -#define TRACK_COLLISION_OBBOX_AABOX -#define TRACK_COLLISION_OBBOX_AABOX_HIT -#define TRACK_COLLISION_OBBOX_OBBOX -#define TRACK_COLLISION_OBBOX_OBBOX_HIT -#endif - -#endif // COLMATH_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp deleted file mode 100644 index e5e86e4b86..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.cpp +++ /dev/null @@ -1,595 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathaabox.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/14/00 2:46p $* - * * - * $Revision:: 21 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CollisionMath::Intersection_Test -- Test intersection between two AABoxes * - * CollisionMath::Overlap_Test -- Tests overlap between an AABox and a sphere * - * CollisionMath::Overlap_Test -- Tests overlap between an AABox and a triangle * - * CollisionMath::Overlap_Test -- Tests overlap between an AABox and a line segment * - * CollisionMath::Collide -- Collision test for a moving AABox and a plane * - * aab_separation_test -- tests two AAB's for separation on an axis * - * CollisionMath::Collide -- Collision test for two moving AABoxes * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "colmathinlines.h" -#include "aaplane.h" -#include "plane.h" -#include "lineseg.h" -#include "tri.h" -#include "sphere.h" -#include "aabox.h" -#include "obbox.h" -#include "wwdebug.h" - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- Test intersection between two AABoxes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const AABoxClass & box,const AABoxClass & box2) -{ - Vector3 dc = box2.Center - box.Center; - - if (box.Extent.X + box2.Extent.X < WWMath::Fabs(dc.X)) return false; - if (box.Extent.Y + box2.Extent.Y < WWMath::Fabs(dc.Y)) return false; - if (box.Extent.Z + box2.Extent.Z < WWMath::Fabs(dc.Z)) return false; - return true; -} - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Tests overlap between an AABox and a sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType CollisionMath::Overlap_Test(const AABoxClass & box,const SphereClass & sphere) -{ - // TODO: this function seems incorrect. Not currently using it though - Vector3 dist = sphere.Center - box.Center; - - Vector3 extent; - extent.X = box.Extent.X + sphere.Radius; - extent.Y = box.Extent.Y + sphere.Radius; - extent.Z = box.Extent.Z + sphere.Radius; - - // - // Check to see if the sphere is completely outside the box - // - if (WWMath::Fabs(dist.X) > extent.X) return OUTSIDE; - if (WWMath::Fabs(dist.Y) > extent.Y) return OUTSIDE; - if (WWMath::Fabs(dist.Z) > extent.Z) return OUTSIDE; - - return INSIDE; -} - - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Tests overlap between an AABox and a line segment * - * * - * This function uses separating axes to determine whether an AABox and a line segment overlap * - * I wrote it when we found that ray-casting was taking a huge amount of time in Renegade. * - * Here are some statistics comparing this function to the previous function which used the * - * same algorithm that Collide(box,ray) uses. * - * * - * collide algorithm (Gems) separating axis (this one) * - * ----------------------------------------------------------------------------------------- * - * number of tests 10000 10000 * - * avg cycles 641 464 * - * outside cycles 652 390 * - * overlap cycles 610 683 * - * * - * The idea for this test is that it will early-exit when it can while the old test can't. * - * When we are passing a ray down our culling trees, it is common to encounter boxes that * - * are not intersecting the ray. The faster we can reject these, the better! * - * * - * INPUT: * - * box - box to test * - * line - line to test * - * * - * OUTPUT: * - * overlap status of the line with respect to the box, either INSIDE, OUTSIDE, or OVERLAPPED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType CollisionMath::Overlap_Test(const AABoxClass & box,const LineSegClass & line) -{ - // If both endpoints are in, return INSIDE - // If either was inside, return OVERLAPPED - int inside_point_count = 0; - if (CollisionMath::Overlap_Test(box,line.Get_P0()) == INSIDE) inside_point_count++; - if (CollisionMath::Overlap_Test(box,line.Get_P1()) == INSIDE) inside_point_count++; - - if (inside_point_count == 2) { - - return INSIDE; - - } else if (inside_point_count == 1) { - - return OVERLAPPED; - - } else { - - // Here I'm using the separating axis theorem to test if the line-segment - // and the box can be separated by a plane. Any two convex objects that are - // not intersecting can be separated by a plane defined by either a - // face normal from one of the objects or the cross-product of an edge from - // each object. In the case of an axis-aligned box and a line-segment, we - // have to check the three coordinate axes and the cross product between - // each and the direction vector of the line segment. - // - // Here is the general test for an arbitrary axis: - // ----------------------------------------------- - // box_proj = fabs(extent.X*axis.X) + fabs(extent.Y*axis.Y) + fabs(extent.Z*axis.Z) - // p0_proj = fabs(dot_product(dp0,axis)) - // dp_proj = fabs(dot_product(dp,axis)) - // if (p0_proj > 0) { - // if (p0_proj > box_proj - WWMath::Min(dp_proj,0.0f)) return OUTSIDE; - // } else { - // if (-p0_proj > box_proj + WWMath::Max(dp_proj,0.0f)) return OUTSIDE; - // } - // - // In practice, there are optimizations you can make on each of the axes that - // we need to test (see below). - - float box_proj,p0_proj,dp_proj; - Vector3 dp0; - Vector3::Subtract(line.Get_P0(),box.Center,&dp0); - - // Project box and line onto the x-axis - // Since I know the axis is the x-axis, just take the x components of each - // vector instead of doing the dot-product. The projection of 'dp' is only - // counted if it points towards the center of the box (i.e. it decreases the - // chances of them being separated...) - box_proj = box.Extent.X; - p0_proj = dp0.X; - dp_proj = line.Get_DP().X; - if (p0_proj > 0) { - if (p0_proj > box_proj - WWMath::Min(dp_proj,0.0f)) return OUTSIDE; - } else { - if (-p0_proj > box_proj + WWMath::Max(dp_proj,0.0f)) return OUTSIDE; - } - - // Project box and line onto the y-axis - box_proj = box.Extent.Y; - p0_proj = dp0.Y; - dp_proj = line.Get_DP().Y; - if (p0_proj > 0) { - if (p0_proj > box_proj - WWMath::Min(dp_proj,0.0f)) return OUTSIDE; - } else { - if (-p0_proj > box_proj + WWMath::Max(dp_proj,0.0f)) return OUTSIDE; - } - - // Project box and line onto the z-axis - box_proj = box.Extent.Z; - p0_proj = dp0.Z; - dp_proj = line.Get_DP().Z; - if (p0_proj > 0) { - if (p0_proj > box_proj - WWMath::Min(dp_proj,0.0f)) return OUTSIDE; - } else { - if (-p0_proj > box_proj + WWMath::Max(dp_proj,0.0f)) return OUTSIDE; - } - - // Project box and line onto (x cross line) - // I'm manually optimizing the cross-product and taking advantage of the fact - // that 'dp' will always project to zero for this axis. - Vector3 axis; - axis.Set(0,-line.Get_Dir().Z,line.Get_Dir().Y); // == (1,0,0) cross (x,y,z) - box_proj = WWMath::Fabs(axis.Y*box.Extent.Y) + WWMath::Fabs(axis.Z*box.Extent.Z); - p0_proj = Vector3::Dot_Product(axis,dp0); - if (WWMath::Fabs(p0_proj) > box_proj) return OUTSIDE; - - // Project box and line onto (y cross line) - axis.Set(line.Get_Dir().Z,0,-line.Get_Dir().X); // == (0,1,0) cross (x,y,z) - box_proj = WWMath::Fabs(axis.X*box.Extent.X) + WWMath::Fabs(axis.Z*box.Extent.Z); - p0_proj = Vector3::Dot_Product(axis,dp0); - if (WWMath::Fabs(p0_proj) > box_proj) return OUTSIDE; - - // Project box and line onto (z cross line) - axis.Set(-line.Get_Dir().Y,line.Get_Dir().X,0); // == (0,0,1) cross (x,y,z) - box_proj = WWMath::Fabs(axis.X*box.Extent.X) + WWMath::Fabs(axis.Y*box.Extent.Y); - p0_proj = Vector3::Dot_Product(axis,dp0); - if (WWMath::Fabs(p0_proj) > box_proj) return OUTSIDE; - - } - return OVERLAPPED; -} - -#if 0 // Alternate Overlap Test for AABox-Ray -CollisionMath::OverlapType CollisionMath::Overlap_Test(const AABoxClass & box,const LineSegClass & line) -{ - // If both endpoints are in, return INSIDE - // If either was inside, return OVERLAPPED - int inside_point_count = 0; - if (CollisionMath::Overlap_Test(box,line.Get_P0()) == INSIDE) inside_point_count++; - if (CollisionMath::Overlap_Test(box,line.Get_P1()) == INSIDE) inside_point_count++; - - if (inside_point_count == 2) { - - return INSIDE; - - } else if (inside_point_count == 1) { - - return OVERLAPPED; - - } else { - - // Now we know that both points are outside of the box so we - // have to detect if the ray penetrates the box. - // I found this algorithm in one of the GEMS books... - Vector3 boxmin,boxmax; - Vector3::Subtract(box.Center,box.Extent,&boxmin); - Vector3::Add(box.Center,box.Extent,&boxmax); - - float candidateplane[3]; // candidate intersection plane distance for each axis - float maxt[3]; // t value along the ray for each axis - Vector3 coord; // intersection point - - const int BOX_SIDE_NEGATIVE = -1; - const int BOX_SIDE_MIDDLE = 0; - const int BOX_SIDE_POSITIVE = 1; - - int quadrant[3]; - for (int i=0; i<3; i++) { - if (line.Get_P0()[i] < boxmin[i]) { - quadrant[i] = BOX_SIDE_NEGATIVE; - candidateplane[i] = boxmin[i]; - } else if (line.Get_P0()[i] > boxmax[i]) { - quadrant[i] = BOX_SIDE_POSITIVE; - candidateplane[i] = boxmax[i]; - } else { - quadrant[i] = BOX_SIDE_MIDDLE; - } - } - - // Calculate the 3 distances to the candidate planes - for (i=0; i<3; i++) { - if (quadrant[i] != BOX_SIDE_MIDDLE && line.Get_DP()[i] != 0.0f) { - maxt[i] = (candidateplane[i] - line.Get_P0()[i]) / line.Get_DP()[i]; - } else { - maxt[i] = -1.0f; - } - } - - // Get the largest of the maxt's for the final choice of intersection - int intersection_plane = 0; - for (i=1; i<3; i++) { - if (maxt[i] > maxt[intersection_plane]) { - intersection_plane = i; - } - } - - // If the ray is "in front" of all of the planes, return - if (maxt[intersection_plane] < 0.0f) { - return OUTSIDE; - } - - // If the intersection is beyond the end of the ray, return - if (maxt[intersection_plane] > 1.0f) { - return OUTSIDE; - } - - // Check if the ray is inside the box, i.e. on the two planes which - // are not the intersection planes, the intersection point should - // be between the min and max of the box. - for (i=0; i<3; i++) { - - if (intersection_plane != i) { - - coord[i] = line.Get_P0()[i] + maxt[intersection_plane] * line.Get_DP()[i]; - if ((coord[i] < boxmin[i]) || (coord[i] > boxmax[i])) { - return OUTSIDE; // ray is outside the box - } - - } else { - - coord[i] = candidateplane[i]; - - } - } - } - return OVERLAPPED; -} -#endif // Alternate Overlap Test for AABox-Ray - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Tests overlap between an AABox and a triangle * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType CollisionMath::Overlap_Test(const AABoxClass & box,const TriClass & tri) -{ - CastResultStruct res; - CollisionMath::Collide(box,Vector3(0,0,0),tri,&res); - return eval_overlap_collision(res); -} - - -/*********************************************************************************************** - * CollisionMath::Collide -- Collision test for a moving AABox and a plane * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide -( - const AABoxClass & box, - const Vector3 & move_vector, - const PlaneClass & plane, - CastResultStruct * result -) -{ - float frac; - - float extent = box.Project_To_Axis(plane.N); - float dist = Vector3::Dot_Product(plane.N,box.Center) + plane.D; - float move = Vector3::Dot_Product(plane.N,move_vector); - - if (dist > extent) { - if (dist + move > extent) { - // entire move ok! - frac = 1.0f; - } else { - // partial move allowed - frac = (extent - dist) / move; - } - - } else if (dist < -extent) { - if (dist + move < -extent) { - // entire move ok! - frac = 1.0f; - } else { - // partial move allowed - frac = (-extent - dist) / move; - } - - } else { - result->StartBad = true; - result->Normal = plane.N; - return true; - } - - if (frac < result->Fraction) { - result->Fraction = frac; - result->Normal = plane.N; - if (result->ComputeContactPoint) { - Vector3 move_dir(move_vector); - move_dir.Normalize(); - float move_extent = Vector3::Dot_Product(box.Extent,move_dir); - result->ContactPoint = box.Center + result->Fraction * move_vector + move_extent * move_dir; - } - return true; - } - - return false; -} - - - - - -/* -** AABCollisionStruct -** Contains all of the intermediate and temporary values used by -** the set of functions used in detecting collisions for aab's -*/ -struct AABCollisionStruct -{ - AABCollisionStruct(const AABoxClass &box0,const Vector3 &move0,const AABoxClass & box1,const Vector3 &move1) : - StartBad(true), // Startbad is true until one of the axes clears it - AxisId(-1), // AxisId will be the axis that allowed the longest move - MaxFrac(0.0f), // MaxFrac is the longest allowed move so far - Box0(box0), - Box1(box1) - { - Vector3::Subtract(box1.Center,box0.Center,&C); // vector from center of box0 to center of box1 - Vector3::Subtract(move1,move0,&M); // move vector relative to stationary box0 - } - - bool StartBad; // Inital configuration is intersecting? - float MaxFrac; // Longest move allowed so far - int AxisId; // Last separating axis - int Side; // which side of the interval - - Vector3 C; // Vector from the center0 to center1 - Vector3 M; // Move vector relative to stationary box0 - - const AABoxClass & Box0; - const AABoxClass & Box1; - -private: - - //not implemented - AABCollisionStruct(const AABCollisionStruct&); - AABCollisionStruct & operator = (const AABCollisionStruct&); -}; - - -/*********************************************************************************************** - * aab_separation_test -- tests two AAB's for separation on an axis * - * * - * This function is very similar to the obb_separation_test. If a flaw is found in either, * - * we should update the other... * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -static inline bool aab_separation_test -( - AABCollisionStruct & context, - int axis -) -{ - // ra = box0 projection onto the axis - // rb = box1 projection onto the axis - // u0 = projected distance between the box centers at t0 - // u1 = projected distance between the box centers at t1 - float ra = context.Box0.Extent[axis]; - float rb = context.Box1.Extent[axis]; - float u0 = context.C[axis]; - float u1 = u0 + context.M[axis]; - - float tmp; - float rsum = ra+rb; - - if ( u0 + WWMATH_EPSILON > rsum ) { - context.StartBad = false; - if ( u1 > rsum ) { - context.MaxFrac = 1.0f; - return true; - } else { - tmp = (rsum-u0)/(u1-u0); - if ( tmp > context.MaxFrac ) { - context.MaxFrac = tmp; - context.AxisId = axis; - context.Side = +1; - } - } - } else if ( u0 - WWMATH_EPSILON < -rsum ) { - context.StartBad = false; - if ( u1 < -rsum ) { - context.MaxFrac = 1.0f; - return true; - } else { - tmp = (-rsum-u0)/(u1-u0); - if ( tmp > context.MaxFrac ) { - context.MaxFrac = tmp; - context.AxisId = axis; - context.Side = -1; - } - } - } - return false; -} - - -/*********************************************************************************************** - * CollisionMath::Collide -- Collision test for two moving AABoxes * - * * - * this function sweeps two AABoxes and finds the first time of collision. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * currently there is no parateter for the movement of the second box. the internal code * - * can handle it though. * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide(const AABoxClass & box,const Vector3 & move,const AABoxClass & box2,CastResultStruct * result) -{ - /* - ** Test the X-axis - ** ra = box projection onto the axis - ** rb = box2 projection onto the axis - ** u0 = projected distance between the box centers at t0 - ** u1 = projected distance between the box centers at t1 - */ - AABCollisionStruct context(box,move,box2,Vector3(0,0,0)); - - if (aab_separation_test(context,0)) { - goto exit; - } - - if (aab_separation_test(context,1)) { - goto exit; - } - - if (aab_separation_test(context,2)) { - goto exit; - } - -exit: - - if (context.StartBad) { - result->StartBad = true; - result->Fraction = 0.0f; - return true; - } - - if (context.MaxFrac < result->Fraction) { - - result->Fraction = context.MaxFrac; - result->Normal.Set(0,0,0); - result->Normal[context.AxisId] = context.Side; - - if (result->ComputeContactPoint) { - WWASSERT(0); // TODO - } - - return true; - } - return false; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.h deleted file mode 100644 index a37b7aadd7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabox.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathaabox.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 5/08/01 5:01p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CollisionMath::Overlap_Test -- test overlap between an AABox and a point * - * CollisionMath::Overlap_Test -- Tests overlap between two AABoxes * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLMATHAABOX_H -#define COLMATHAABOX_H - -#include "always.h" -#include "aabox.h" -#include "vector3.h" -#include "lineseg.h" - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- test overlap between an AABox and a point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/14/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE CollisionMath::OverlapType CollisionMath::Overlap_Test(const AABoxClass & box,const Vector3 & point) -{ - if (WWMath::Fabs(point.X - box.Center.X) > box.Extent.X) return POS; - if (WWMath::Fabs(point.Y - box.Center.Y) > box.Extent.Y) return POS; - if (WWMath::Fabs(point.Z - box.Center.Z) > box.Extent.Z) return POS; - - return NEG; -} - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Tests overlap between two AABoxes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/19/99 gth : Created. * - *=============================================================================================*/ -WWINLINE CollisionMath::OverlapType CollisionMath::Overlap_Test(const AABoxClass & box,const AABoxClass & box2) -{ - Vector3 dc; - Vector3::Subtract(box2.Center,box.Center,&dc); - - if (box.Extent.X + box2.Extent.X < WWMath::Fabs(dc.X)) return POS; - if (box.Extent.Y + box2.Extent.Y < WWMath::Fabs(dc.Y)) return POS; - if (box.Extent.Z + box2.Extent.Z < WWMath::Fabs(dc.Z)) return POS; - - if ( (dc.X + box2.Extent.X <= box.Extent.X) && - (dc.Y + box2.Extent.Y <= box.Extent.Y) && - (dc.Z + box2.Extent.Z <= box.Extent.Z) && - (dc.X - box2.Extent.X >= -box.Extent.X) && - (dc.Y - box2.Extent.Y >= -box.Extent.Y) && - (dc.Z - box2.Extent.Z >= -box.Extent.Z)) - { - return NEG; // inside; - } - - return BOTH; -} - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp deleted file mode 100644 index f5d9f1b7bf..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathaabtri.cpp +++ /dev/null @@ -1,1183 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathaabtri.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/08/01 9:52a $* - * * - * $Revision:: 17 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * aabtri_separation_test -- test the projected extents for separation * - * aabtri_check_axis -- project the aab and tri onto an arbitrary axis * - * aabtri_check_cross_axis -- projects aab and tri onto a "cross" axis * - * aabtri_check_basis_axis -- projects the aab and tri onto a basis axis * - * aabtri_check_normal_axis -- project the box and tri onto the tri-normal * - * eval_side -- returns -1,0,+1 depending on the sign of val and side * - * aabtri_compute_contact_normal -- computes the normal of the collision * - * CollisionMath::Collide -- collide an aabox into a triangle * - * aabtri_intersect_cross_axis -- intersection check for a "cross-product" axis * - * aabtri_intersect_basis_axis -- intersection check for a basis axis * - * aabtri_intersect_normal_axis -- intersection check for the triangle normal * - * CollisionMath::Intersection_Test -- Intersection check for an AABox and a triangle * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "aabox.h" -#include "tri.h" -#include "wwdebug.h" - - -/* -** Separating Axes have to be rejected if their length is smaller than some epsilon. -** Otherwise, erroneous results can be reported. -*/ -#define AXISLEN_EPSILON2 WWMATH_EPSILON * WWMATH_EPSILON // squared length of a separating axis must be larger than this - - -/* -** Axes used in Box-Tri intersection tests -** The axes of the box are A0,A1,A2. N is the normal of the triangle, -** E0,E1,E2 are direction vectors for the edges of the triangle. -** (the box axes are labeled A0,A1,A2 as a holdover from the obbox-obbox -** collision code which this was derived from where there are two boxes -** A and B) -*/ -enum -{ - INTERSECTION = 0, - AXIS_N, // normal of the triangle - AXIS_A0, // first basis vector of the box - AXIS_A1, // second basis vector of the box - AXIS_A2, // third basis vector of the box - - AXIS_A0E0, // box0 x edge0... - AXIS_A1E0, - AXIS_A2E0, - AXIS_A0E1, - AXIS_A1E1, - AXIS_A2E1, - AXIS_A0E2, - AXIS_A1E2, - AXIS_A2E2 -}; - - -/****************************************************************************************** - - AABox->Triangle collision - - This code is basically a special-case optimization of the OBBox->Triangle collision - detection code. There are many dot and cross products that can be simplified due - to the fact that we know the axes of the boxes are always the same and are aligned - with the world coordinate axes. - - Each axis test will use the following logic: - Project D onto the axis being used, it is the separation distance. If the - projection of the extent of the box + the projection of the extent of the - tri is greater than D*axis then the two intersect - - March 13, 2000 - Modified these routines to all use a static instance of - the BTCollisionStruct. The compiler was generating lots of extra code for the - constructor of this object and testing determined that re-using the same static - struct was slightly faster anyway. - NOTE: this makes the code not Thread-Safe!!!! - - -******************************************************************************************/ - -/* -** BoxTriColStruct -** Scratchpad variables for the AABox-Triangle collision detection functions. One instance -** of this structure will be used for all of the local variables and its pointer will be -** handed of to various inline functions for the axis tests. -** Note that much of the code needs the un-normalized triangle normal. For this reason, -** I have to compute N rather than copying it from the triangle. (commenting this to -** avoid re-generating a difficult to find bug that I had) -*/ -struct BTCollisionStruct -{ - BTCollisionStruct(void) {} - - void Init(const AABoxClass &box,const Vector3 &move,const TriClass &tri,const Vector3 &trimove) - { - StartBad = true; // true until an axis clears it - MaxFrac = -0.01f; // maximum move allowed so far - AxisId = INTERSECTION; // axis that allowed the longest move - Point = 0; // index of triangle point that was closest to the box - Side = 0; // side of the interval - Box = &box; - Tri = &tri; - BoxMove = &move; - TriMove = &trimove; - - Vector3::Subtract(*tri.V[0],box.Center,&D); // vector from center of box to vertex 0 - Vector3::Subtract(move,trimove,&Move); // move vector relative to stationary triangle - - Vector3::Subtract(*tri.V[1],*tri.V[0],&E[0]); - Vector3::Subtract(*tri.V[2],*tri.V[0],&E[1]); - Vector3::Subtract(E[1],E[0],&E[2]); - - Vector3::Cross_Product(E[0],E[1],&N); - } - - bool StartBad; // Inital configuration is intersecting? - float MaxFrac; // Longest move allowed so far - - int AxisId; // Last separating axis - int Side; // which side of the interval - int Point; // Index of the "closest" triangle point (or one of them) - - int TestAxisId; // Axis 'id' we're working on - int TestSide; // Was the axis we're working on flipped - int TestPoint; // Index of the closest vertex - Vector3 TestAxis; // Axis we're working on - - Vector3 D; // Vector from the center of the box to v0 - Vector3 Move; // Move vector relative to stationary triangle - float AE[3][3]; // Dot products of the Basis vectors and edges - float AN[3]; // Dot products of the Basis vectors and the normal - Vector3 AxE[3][3]; // Cross products of the Basis vectors and edges - - Vector3 E[3]; // edge vectors for the triangle - Vector3 N; // normal (NOT normalized!!!) - Vector3 FinalD; // Vector from center of box to v0 at end of move - - const AABoxClass * Box; - const TriClass * Tri; - const Vector3 * BoxMove; - const Vector3 * TriMove; - -private: - - // not implemented - BTCollisionStruct(const BTCollisionStruct &); - BTCollisionStruct & operator = (const BTCollisionStruct &); -}; - -static BTCollisionStruct CollisionContext; - -/*********************************************************************************************** - * aabtri_separation_test -- test the projected extents for separation * - * * - * Once the extents are projected onto the axis, this function contains * - * the logic that determines the allowed fraction. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - * 7/12/99 GTH : Converted original OBBox code to AABox * - *=============================================================================================*/ -static inline bool aabtri_separation_test -( - float lp,float leb0,float leb1 -) -{ - /* - ** - If (I'm no more than 'EPSILON' embedded in the wall) - ** - not startbad - ** - If (I'm moving towards) - ** - fraction = How far I can move before embedding (can be negative if started embedded) - ** - If (I can take entire move) - ** - accept entire move - ** - Else If (I can move more than I could have before; *negative always fails!) - ** - update fraction - ** - Else - ** - Accept entire move since I'm not moving towards - */ - float eps = 0.0f; - if (lp - leb0 <= 0.0f) { - eps = COLLISION_EPSILON * CollisionContext.TestAxis.Length(); // trying to only compute epsilon if I have to - } - - if (lp - leb0 > -eps) { - CollisionContext.StartBad = false; - if (leb1 - leb0 > 0.0f) { - float frac = (lp-leb0)/(leb1-leb0); - if (frac >= 1.0f) { - /* moving toward but not hitting triangle */ - CollisionContext.AxisId = CollisionContext.TestAxisId; - CollisionContext.MaxFrac = 1.0f; - return true; - } else { - /* moving toward, hitting triangle */ - if (frac > CollisionContext.MaxFrac) { - CollisionContext.MaxFrac = frac; - CollisionContext.AxisId = CollisionContext.TestAxisId; - CollisionContext.Side = CollisionContext.TestSide; - CollisionContext.Point = CollisionContext.TestPoint; - } - } - } else { - /* moving away or not moving */ - CollisionContext.AxisId = CollisionContext.TestAxisId; - CollisionContext.MaxFrac = 1.0f; - return true; - } - } - return false; -} - - -/*********************************************************************************************** - * aabtri_check_axis -- project the aab and tri onto an arbitrary axis * - * * - * projects the box and the triangle onto the given axis and calls * - * obbtri_separation_test. return true if separation was detected * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - * 7/12/99 GTH : converted to AABox * - *=============================================================================================*/ -static inline bool aabtri_check_axis(void) -{ - float dist; // separation along the axis - float axismove; // size of the move along the axis. - float leb0; // initial coordinate of the leading edge of the box - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - float tmp; // temporary - - dist = Vector3::Dot_Product(CollisionContext.D,CollisionContext.TestAxis); - axismove = Vector3::Dot_Product(CollisionContext.Move,CollisionContext.TestAxis); - - // I want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axismove = -axismove; - CollisionContext.TestAxis = -CollisionContext.TestAxis; - CollisionContext.TestSide = -1.0f; - } else { - CollisionContext.TestSide = 1.0f; - } - - // compute coordinates of the leading edge of the box at t0 and t1 - leb0 = CollisionContext.Box->Extent.X * WWMath::Fabs(CollisionContext.TestAxis.X) + - CollisionContext.Box->Extent.Y * WWMath::Fabs(CollisionContext.TestAxis.Y) + - CollisionContext.Box->Extent.Z * WWMath::Fabs(CollisionContext.TestAxis.Z); - leb1 = leb0 + axismove; - - // compute coordinate of "leading edge of the triangle" relative to the box center. - lp = 0; - tmp = Vector3::Dot_Product(CollisionContext.E[0],CollisionContext.TestAxis); if (tmp < lp) lp = tmp; - tmp = Vector3::Dot_Product(CollisionContext.E[1],CollisionContext.TestAxis); if (tmp < lp) lp = tmp; - lp = dist + lp; - - return aabtri_separation_test(/*CollisionContext,*/lp,leb0,leb1); -} - - -/*********************************************************************************************** - * aabtri_check_cross_axis -- projects aab and tri onto a "cross" axis * - * * - * Assumes that the axis given is one generated from a cross product of one of the edge and * - * basis vectors. In this case, the box extent can be optimized and only two triangle verts * - * need to be checked. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool aabtri_check_cross_axis -( - float dp, - int dpi, - float leb0 -) -{ - float p0; // distance from box center to vertex 0 - float axismove; // size of the move along the axis. - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - p0 = Vector3::Dot_Product(CollisionContext.D,CollisionContext.TestAxis); - axismove = Vector3::Dot_Product(CollisionContext.Move,CollisionContext.TestAxis); - - // I want the axis centered at the box, pointing towards the triangle - if (p0 < 0) { - p0 = -p0; - axismove = -axismove; - dp = -dp; - CollisionContext.TestAxis = -CollisionContext.TestAxis; - CollisionContext.TestSide = -1.0f; - } else { - CollisionContext.TestSide = 1.0f; - } - - // compute coordinates of the leading edge of the box at t1 - leb1 = leb0 + axismove; - - // compute coordinate of "leading edge of the triangle" relative to the box center. - lp = 0; CollisionContext.TestPoint = 0; - if (dp < 0) { lp = dp; CollisionContext.TestPoint = dpi; } - lp = p0 + lp; - - return aabtri_separation_test(/*CollisionContext,*/lp,leb0,leb1); -} - - -/*********************************************************************************************** - * aabtri_check_basis_axis -- projects the aab and tri onto a basis axis * - * * - * Projects the box and triangle onto an axis that is assumed to be a basis * - * vector from the box. In this case, we can skip a dot-product and use the * - * corresponding extent of the box (which is passed in as leb0). * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool aabtri_check_basis_axis -( - float leb0, - float dp1, - float dp2 -) -{ - float dist; // separation along the axis - float axismove; // size of the move along the axis. - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(CollisionContext.D,CollisionContext.TestAxis); - axismove = Vector3::Dot_Product(CollisionContext.Move,CollisionContext.TestAxis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axismove = -axismove; - dp1 = -dp1; - dp2 = -dp2; - CollisionContext.TestAxis = -CollisionContext.TestAxis; - CollisionContext.TestSide = -1.0f; - } else { - CollisionContext.TestSide = 1.0f; - } - - // this is the "optimization", leb0 = one of the extents - leb1 = leb0 + axismove; - - // compute coordinate of "leading edge of the polygon" relative to the box center. - lp = 0; CollisionContext.TestPoint = 0; - if (dp1 < lp) { lp = dp1; CollisionContext.TestPoint = 1; } - if (dp2 < lp) { lp = dp2; CollisionContext.TestPoint = 2; } - lp = dist + lp; - - return aabtri_separation_test(/*CollisionContext,*/lp,leb0,leb1); -} - - -/*********************************************************************************************** - * aabtri_check_normal_axis -- project the box and tri onto the tri-normal * - * * - * Projects the box and triangle onto an axis that is assumed to be the normal * - * vector from the triangle. In this case, the triangle extents are zero. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool aabtri_check_normal_axis(void) -{ - float dist; // separation along the axis - float axismove; // size of the move along the axis. - float leb0; // initial coordinate of the leading edge of the box - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(CollisionContext.D,CollisionContext.TestAxis); - axismove = Vector3::Dot_Product(CollisionContext.Move,CollisionContext.TestAxis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axismove = -axismove; - CollisionContext.TestAxis = -CollisionContext.TestAxis; - CollisionContext.TestSide = -1.0f; - } else { - CollisionContext.TestSide = 1.0f; - } - - leb0 = CollisionContext.Box->Extent.X * WWMath::Fabs(CollisionContext.AN[0]) + - CollisionContext.Box->Extent.Y * WWMath::Fabs(CollisionContext.AN[1]) + - CollisionContext.Box->Extent.Z * WWMath::Fabs(CollisionContext.AN[2]); - leb1 = leb0 + axismove; - CollisionContext.TestPoint = 0; - lp = dist; // this is the "optimization", don't have to find lp - - return aabtri_separation_test(/*CollisionContext,*/lp,leb0,leb1); -} - -/*********************************************************************************************** - * eval_side -- returns -1,0,+1 depending on the sign of val and side * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline float eval_side(float val,int side) -{ - if (val > 0.0f) { - return side; - } else if (val < 0.0f) { - return -side; - } else { - return 0.0f; - } -} - -/*********************************************************************************************** - * aabtri_compute_contact_normal -- computes the normal of the collision * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void aabtri_compute_contact_normal -( - Vector3 & set_norm -) -{ -#if 1 - switch(CollisionContext.AxisId) - { - case INTERSECTION: - set_norm = *CollisionContext.Tri->N; - break; - case AXIS_N: - set_norm = -CollisionContext.Side * *CollisionContext.Tri->N; - set_norm.Normalize(); - break; - case AXIS_A0: - set_norm = -CollisionContext.Side * Vector3(1.0f,0.0f,0.0f); - break; - case AXIS_A1: - set_norm = -CollisionContext.Side * Vector3(0.0f,1.0f,0.0f); - break; - case AXIS_A2: - set_norm = -CollisionContext.Side * Vector3(0.0f,0.0f,1.0f); - break; - case AXIS_A0E0: - set_norm = -CollisionContext.Side * CollisionContext.AxE[0][0]; - set_norm.Normalize(); - break; - case AXIS_A1E0: - set_norm = -CollisionContext.Side * CollisionContext.AxE[1][0]; - set_norm.Normalize(); - break; - case AXIS_A2E0: - set_norm = -CollisionContext.Side * CollisionContext.AxE[2][0]; - set_norm.Normalize(); - break; - case AXIS_A0E1: - set_norm = -CollisionContext.Side * CollisionContext.AxE[0][1]; - set_norm.Normalize(); - break; - case AXIS_A1E1: - set_norm = -CollisionContext.Side * CollisionContext.AxE[1][1]; - set_norm.Normalize(); - break; - case AXIS_A2E1: - set_norm = -CollisionContext.Side * CollisionContext.AxE[2][1]; - set_norm.Normalize(); - break; - case AXIS_A0E2: - set_norm = -CollisionContext.Side * CollisionContext.AxE[0][2]; - set_norm.Normalize(); - break; - case AXIS_A1E2: - set_norm = -CollisionContext.Side * CollisionContext.AxE[1][2]; - set_norm.Normalize(); - break; - case AXIS_A2E2: - set_norm = -CollisionContext.Side * CollisionContext.AxE[2][2]; - set_norm.Normalize(); - break; - } - - WWASSERT(set_norm.Length2() > 0.0f); - -#else - set_norm = *CollisionContext.Tri.N; - if (Vector3::Dot_Product(set_norm,CollisionContext.Move) > 0.0f) { - set_norm = -(set_norm); - } -#endif -} - -inline void VERIFY_CROSS(const Vector3 & a, const Vector3 & b,const Vector3 & cross) -{ -#ifdef WWDEBUG - Vector3 tmp_cross; - Vector3::Cross_Product(a,b,&tmp_cross); - Vector3 diff = cross - tmp_cross; - WWASSERT(WWMath::Fabs(diff.Length()) < 0.0001f); -#endif -} - -/*********************************************************************************************** - * CollisionMath::Collide -- collide an aabox into a triangle * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide -( - const AABoxClass & box, - const Vector3 & move, - const TriClass & tri, - CastResultStruct * result -) -{ - TRACK_COLLISION_AABOX_TRI; - - float dp,leb0; - - CollisionContext.Init(box,move,tri,Vector3(0,0,0)); - - /* - ** AXIS_N - */ - CollisionContext.TestAxis = CollisionContext.N; - CollisionContext.TestAxisId = AXIS_N; - CollisionContext.AN[0] = CollisionContext.N.X; - CollisionContext.AN[1] = CollisionContext.N.Y; - CollisionContext.AN[2] = CollisionContext.N.Z; - if (aabtri_check_normal_axis()) goto exit; - - /* - ** AXIS_A0 - */ - CollisionContext.TestAxis.Set(1,0,0); - CollisionContext.TestAxisId = AXIS_A0; - CollisionContext.AE[0][0] = CollisionContext.E[0].X; - CollisionContext.AE[0][1] = CollisionContext.E[1].X; - if (aabtri_check_basis_axis(box.Extent.X,CollisionContext.AE[0][0],CollisionContext.AE[0][1])) goto exit; - - /* - ** AXIS_A1 - */ - CollisionContext.TestAxis.Set(0,1,0); - CollisionContext.TestAxisId = AXIS_A1; - CollisionContext.AE[1][0] = CollisionContext.E[0].Y; - CollisionContext.AE[1][1] = CollisionContext.E[1].Y; - if (aabtri_check_basis_axis(box.Extent.Y,CollisionContext.AE[1][0],CollisionContext.AE[1][1])) goto exit; - - /* - ** AXIS_A2 - */ - CollisionContext.TestAxis.Set(0,0,1); - CollisionContext.TestAxisId = AXIS_A2; - CollisionContext.AE[2][0] = CollisionContext.E[0].Z; - CollisionContext.AE[2][1] = CollisionContext.E[1].Z; - if (aabtri_check_basis_axis(box.Extent.Z,CollisionContext.AE[2][0],CollisionContext.AE[2][1])) goto exit; - - /* - ** AXIS_A0xE0 - */ - CollisionContext.AxE[0][0].Set(0,-CollisionContext.E[0].Z,CollisionContext.E[0].Y); - VERIFY_CROSS(Vector3(1,0,0),CollisionContext.E[0],CollisionContext.AxE[0][0]); - CollisionContext.TestAxis = CollisionContext.AxE[0][0]; - CollisionContext.TestAxisId = AXIS_A0E0; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = CollisionContext.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(CollisionContext.AE[2][0]) + box.Extent[2]*WWMath::Fabs(CollisionContext.AE[1][0]); - if (aabtri_check_cross_axis(dp,2,leb0)) goto exit; - } - - /* - ** AXIS_A0xE1 - */ - CollisionContext.AxE[0][1].Set(0,-CollisionContext.E[1].Z,CollisionContext.E[1].Y); - VERIFY_CROSS(Vector3(1,0,0),CollisionContext.E[1],CollisionContext.AxE[0][1]); - CollisionContext.TestAxis = CollisionContext.AxE[0][1]; - CollisionContext.TestAxisId = AXIS_A0E1; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -CollisionContext.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(CollisionContext.AE[2][1]) + box.Extent[2]*WWMath::Fabs(CollisionContext.AE[1][1]); - if (aabtri_check_cross_axis(dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A0xE2 - */ - CollisionContext.AE[0][2] = CollisionContext.E[2].X; - CollisionContext.AE[1][2] = CollisionContext.E[2].Y; - CollisionContext.AE[2][2] = CollisionContext.E[2].Z; - - CollisionContext.AxE[0][2].Set(0,-CollisionContext.E[2].Z,CollisionContext.E[2].Y); - VERIFY_CROSS(Vector3(1,0,0),CollisionContext.E[2],CollisionContext.AxE[0][2]); - CollisionContext.TestAxis = CollisionContext.AxE[0][2]; - CollisionContext.TestAxisId = AXIS_A0E2; - - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -CollisionContext.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(CollisionContext.AE[2][2]) + box.Extent[2]*WWMath::Fabs(CollisionContext.AE[1][2]); - if (aabtri_check_cross_axis(dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A1xE0 - */ - CollisionContext.AxE[1][0].Set(CollisionContext.E[0].Z,0,-CollisionContext.E[0].X); - VERIFY_CROSS(Vector3(0,1,0),CollisionContext.E[0],CollisionContext.AxE[1][0]); - CollisionContext.TestAxis = CollisionContext.AxE[1][0]; - CollisionContext.TestAxisId = AXIS_A1E0; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = CollisionContext.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(CollisionContext.AE[2][0]) + box.Extent[2]*WWMath::Fabs(CollisionContext.AE[0][0]); - if (aabtri_check_cross_axis(dp,2,leb0)) goto exit; - } - - /* - ** AXIS_A1xE1 - */ - CollisionContext.AxE[1][1].Set(CollisionContext.E[1].Z,0,-CollisionContext.E[1].X); - VERIFY_CROSS(Vector3(0,1,0),CollisionContext.E[1],CollisionContext.AxE[1][1]); - CollisionContext.TestAxis = CollisionContext.AxE[1][1]; - CollisionContext.TestAxisId = AXIS_A1E1; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -CollisionContext.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(CollisionContext.AE[2][1]) + box.Extent[2]*WWMath::Fabs(CollisionContext.AE[0][1]); - if (aabtri_check_cross_axis(dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A1xE2 - */ - CollisionContext.AxE[1][2].Set(CollisionContext.E[2].Z,0,-CollisionContext.E[2].X); - VERIFY_CROSS(Vector3(0,1,0),CollisionContext.E[2],CollisionContext.AxE[1][2]); - CollisionContext.TestAxis = CollisionContext.AxE[1][2]; - CollisionContext.TestAxisId = AXIS_A1E2; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -CollisionContext.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(CollisionContext.AE[2][2]) + box.Extent[2]*WWMath::Fabs(CollisionContext.AE[0][2]); - if (aabtri_check_cross_axis(dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A2xE0 - */ - CollisionContext.AxE[2][0].Set(-CollisionContext.E[0].Y,CollisionContext.E[0].X,0); - VERIFY_CROSS(Vector3(0,0,1),CollisionContext.E[0],CollisionContext.AxE[2][0]); - CollisionContext.TestAxis = CollisionContext.AxE[2][0]; - CollisionContext.TestAxisId = AXIS_A2E0; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = CollisionContext.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(CollisionContext.AE[1][0]) + box.Extent[1]*WWMath::Fabs(CollisionContext.AE[0][0]); - if (aabtri_check_cross_axis(dp,2,leb0)) goto exit; - } - - /* - ** AXIS_A2xE1 - */ - CollisionContext.AxE[2][1].Set(-CollisionContext.E[1].Y,CollisionContext.E[1].X,0); - VERIFY_CROSS(Vector3(0,0,1),CollisionContext.E[1],CollisionContext.AxE[2][1]); - CollisionContext.TestAxis = CollisionContext.AxE[2][1]; - CollisionContext.TestAxisId = AXIS_A2E1; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -CollisionContext.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(CollisionContext.AE[1][1]) + box.Extent[1]*WWMath::Fabs(CollisionContext.AE[0][1]); - if (aabtri_check_cross_axis(dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A2xE2 - */ - CollisionContext.AxE[2][2].Set(-CollisionContext.E[2].Y,CollisionContext.E[2].X,0); - VERIFY_CROSS(Vector3(0,0,1),CollisionContext.E[2],CollisionContext.AxE[2][2]); - CollisionContext.TestAxis = CollisionContext.AxE[2][2]; - CollisionContext.TestAxisId = AXIS_A2E2; - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -CollisionContext.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(CollisionContext.AE[1][2]) + box.Extent[1]*WWMath::Fabs(CollisionContext.AE[0][2]); - if (aabtri_check_cross_axis(dp,1,leb0)) goto exit; - } - - /* - ** Last ditch effort, check an axis based on the move vector - */ - if (!CollisionContext.StartBad) { - CollisionContext.TestPoint = CollisionContext.Point; - CollisionContext.TestAxisId = CollisionContext.AxisId; - - CollisionContext.TestAxis.Set(0,-CollisionContext.Move.Z,CollisionContext.Move.Y); // A0 X Move - VERIFY_CROSS(Vector3(1,0,0),CollisionContext.Move,CollisionContext.TestAxis); - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - if (aabtri_check_axis()) goto exit; - } - CollisionContext.TestAxis.Set(CollisionContext.Move.Z,0,-CollisionContext.Move.X); // A1 X Move - VERIFY_CROSS(Vector3(0,1,0),CollisionContext.Move,CollisionContext.TestAxis); - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - if (aabtri_check_axis()) goto exit; - } - CollisionContext.TestAxis.Set(-CollisionContext.Move.Y,CollisionContext.Move.X,0); // A2 X Move - VERIFY_CROSS(Vector3(0,0,1),CollisionContext.Move,CollisionContext.TestAxis); - if (CollisionContext.TestAxis.Length2() > AXISLEN_EPSILON2) { - if (aabtri_check_axis()) goto exit; - } - } - -exit: - - /* - ** If MaxFrac is less than zero, clamp it to zero. Negative fractions can - ** leak through this routine due to the epsilon in the separation test. - */ - if (CollisionContext.MaxFrac < 0.0f) { - CollisionContext.MaxFrac = 0.0f; - } - - /* - ** If the triangle and box are intersecting before the move, return that - ** result. - */ - if (CollisionContext.StartBad) { - result->StartBad = true; - result->Fraction = 0.0f; - result->Normal = *tri.N; - TRACK_COLLISION_AABOX_TRI_HIT; - return true; - } - - /* - ** If the fraction allowed is basically equal to the fraction allowed by - ** another polygon, try to pick the polygon which is least "edge-on" to the - ** move. - */ - if ((CollisionContext.MaxFrac <= result->Fraction) && (CollisionContext.MaxFrac < 1.0f)) { - - /* - ** Reflect the normal if it is pointing the same way as our move - ** (probably hitting the back side of a polygon) - */ - Vector3 tmp_norm(0.0f,0.0f,0.0f); - aabtri_compute_contact_normal(tmp_norm); -// if (Vector3::Dot_Product(tmp_norm,move) > 0.0f) { -// tmp_norm = -tmp_norm; -// } - - /* - ** If this polygon cuts off more of the move -OR- this polygon cuts - ** of the same amount but has a "better" normal, then use this normal - */ - if ( (WWMath::Fabs(CollisionContext.MaxFrac - result->Fraction) > WWMATH_EPSILON) || - (Vector3::Dot_Product(tmp_norm,move) < Vector3::Dot_Product(result->Normal,move))) - { - result->Normal = tmp_norm; -#pragma message("fatal assert disabled for demo") - //WWASSERT(WWMath::Fabs(result->Normal.Length() - 1.0f) < WWMATH_EPSILON); - } - - result->Fraction = CollisionContext.MaxFrac; - - TRACK_COLLISION_AABOX_TRI_HIT; - return true; - } - - return false; -} - - - -/* -** AABTIntersectStruct -** Scratchpad variables for the AABox-Triangle intersection functions. One instance -** of this structure will be used for all of the local variables and its pointer will be -** handed of to various inline functions for the axis tests. -** Note that much of the code needs the un-normalized triangle normal. For this reason, -** I have to compute N rather than copying it from the triangle. (commenting this to -** avoid re-generating a difficult to find bug that I had) -*/ -struct AABTIntersectStruct -{ - AABTIntersectStruct(void) : - Box(NULL), - Tri(NULL) - { - } - - void Init(const AABoxClass &box,const TriClass &tri) - { - Box = &box; - Tri = &tri; - Vector3::Subtract(*tri.V[0],box.Center,&D); // vector from center of box to vertex 0 - Vector3::Subtract(*tri.V[1],*tri.V[0],&E[0]); - Vector3::Subtract(*tri.V[2],*tri.V[0],&E[1]); - Vector3::Subtract(E[1],E[0],&E[2]); - - Vector3::Cross_Product(E[0],E[1],&N); - } - - - Vector3 D; // Vector from the center of the box to v0 - float AE[3][3]; // Dot products of the Basis vectors and edges - float AN[3]; // Dot products of the Basis vectors and the normal - Vector3 AxE[3][3]; // Cross produts of the Basis vectors and edges - - Vector3 E[3]; // edge vectors for the triangle - Vector3 N; // normal (NOT normalized!!!) - - const AABoxClass * Box; - const TriClass * Tri; - -private: - - // not implemented - AABTIntersectStruct(const AABTIntersectStruct &); - AABTIntersectStruct & operator = (const AABTIntersectStruct &); -}; - -static AABTIntersectStruct IntersectContext; - - -/*********************************************************************************************** - * aabtri_intersect_cross_axis -- intersection check for a "cross-product" axis * - * * - * axis being checked is a cross product between a triangle edge and a box basis vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool aabtri_intersect_cross_axis -( - Vector3 & axis, - float dp, - float leb0 -) -{ - float p0; // distance from box center to vertex 0 - float lp; // leading edge of the polygon. - - p0 = Vector3::Dot_Product(IntersectContext.D,axis); - - // I want the axis centered at the box, pointing towards the triangle - if (p0 < 0) { - p0 = -p0; - axis = -axis; - dp = -dp; - } - - // compute coordinate of "leading edge of the triangle" relative to the box center. - lp = 0; - if (dp < 0) { lp = dp; } - lp = p0 + lp; - - return (lp - leb0 > -WWMATH_EPSILON); -} - - -/*********************************************************************************************** - * aabtri_intersect_basis_axis -- intersection check for a basis axis * - * * - * axis being checked is one of the basis vectors for the box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool aabtri_intersect_basis_axis -( - Vector3 & axis, - float leb0, - float dp1, - float dp2 -) -{ - float dist; // separation along the axis - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(IntersectContext.D,axis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axis = -axis; - dp1 = -dp1; - dp2 = -dp2; - } - - // compute coordinate of "leading edge of the polygon" relative to the box center. - lp = 0; - if (dp1 < lp) { lp = dp1; } - if (dp2 < lp) { lp = dp2; } - lp = dist + lp; - - return (lp - leb0 > -WWMATH_EPSILON); -} - - -/*********************************************************************************************** - * aabtri_intersect_normal_axis -- intersection check for the triangle normal * - * * - * axis being checked is the triangle's normal * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool aabtri_intersect_normal_axis -( - Vector3 & axis -) -{ - float dist; // separation along the axis - float leb0; // initial coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(IntersectContext.D,axis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axis = -axis; - } - - leb0 = IntersectContext.Box->Extent.X * WWMath::Fabs(IntersectContext.AN[0]) + - IntersectContext.Box->Extent.Y * WWMath::Fabs(IntersectContext.AN[1]) + - IntersectContext.Box->Extent.Z * WWMath::Fabs(IntersectContext.AN[2]); - lp = dist; // this is the "optimization", don't have to find lp - - return (lp - leb0 > -WWMATH_EPSILON); -} - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- Intersection check for an AABox and a triangle * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/20/00 gth : copied from OBBox version and removed some Dot-products * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const AABoxClass & box,const TriClass & tri) -{ - Vector3 axis; - float dp,leb0; - - IntersectContext.Init(box,tri); - - /* - ** AXIS_N - */ - axis = IntersectContext.N; - IntersectContext.AN[0] = IntersectContext.N.X; - IntersectContext.AN[1] = IntersectContext.N.Y; - IntersectContext.AN[2] = IntersectContext.N.Z; - if (aabtri_intersect_normal_axis(axis)) return false; - - /* - ** AXIS_A0 - */ - axis.Set(1,0,0); - IntersectContext.AE[0][0] = IntersectContext.E[0].X; - IntersectContext.AE[0][1] = IntersectContext.E[1].Y; - if (aabtri_intersect_basis_axis(axis,box.Extent.X,IntersectContext.AE[0][0],IntersectContext.AE[0][1])) return false; - - /* - ** AXIS_A1 - */ - axis.Set(0,1,0); - IntersectContext.AE[1][0] = IntersectContext.E[0].Y; - IntersectContext.AE[1][1] = IntersectContext.E[1].Y; - if (aabtri_intersect_basis_axis(axis,box.Extent.Y,IntersectContext.AE[1][0],IntersectContext.AE[1][1])) return false; - - /* - ** AXIS_A2 - */ - axis.Set(0,0,1); - IntersectContext.AE[2][0] = IntersectContext.E[0].Z; - IntersectContext.AE[2][1] = IntersectContext.E[1].Z; - if (aabtri_intersect_basis_axis(axis,box.Extent.Z,IntersectContext.AE[2][0],IntersectContext.AE[2][1])) return false; - - /* - ** AXIS_A0xE0 - */ - Vector3::Cross_Product(Vector3(1,0,0),IntersectContext.E[0],&IntersectContext.AxE[0][0]); - axis = IntersectContext.AxE[0][0]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = IntersectContext.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(IntersectContext.AE[2][0]) + box.Extent[2]*WWMath::Fabs(IntersectContext.AE[1][0]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A0xE1 - */ - Vector3::Cross_Product(Vector3(1,0,0),IntersectContext.E[1],&IntersectContext.AxE[0][1]); - axis = IntersectContext.AxE[0][1]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = -IntersectContext.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(IntersectContext.AE[2][1]) + box.Extent[2]*WWMath::Fabs(IntersectContext.AE[1][1]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A0xE2 - */ - Vector3::Cross_Product(Vector3(1,0,0),IntersectContext.E[2],&IntersectContext.AxE[0][2]); - axis = IntersectContext.AxE[0][2]; - IntersectContext.AE[1][2] = IntersectContext.E[2].Y; - IntersectContext.AE[2][2] = IntersectContext.E[2].Z; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = -IntersectContext.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(IntersectContext.AE[2][2]) + box.Extent[2]*WWMath::Fabs(IntersectContext.AE[1][2]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A1xE0 - */ - Vector3::Cross_Product(Vector3(0,1,0),IntersectContext.E[0],&IntersectContext.AxE[1][0]); - axis = IntersectContext.AxE[1][0]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = IntersectContext.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(IntersectContext.AE[2][0]) + box.Extent[2]*WWMath::Fabs(IntersectContext.AE[0][0]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A1xE1 - */ - Vector3::Cross_Product(Vector3(0,1,0),IntersectContext.E[1],&IntersectContext.AxE[1][1]); - axis = IntersectContext.AxE[1][1]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = -IntersectContext.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(IntersectContext.AE[2][1]) + box.Extent[2]*WWMath::Fabs(IntersectContext.AE[0][1]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A1xE2 - */ - Vector3::Cross_Product(Vector3(0,1,0),IntersectContext.E[2],&IntersectContext.AxE[1][2]); - axis = IntersectContext.AxE[1][2]; - IntersectContext.AE[0][2] = IntersectContext.E[2].X; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = -IntersectContext.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(IntersectContext.AE[2][2]) + box.Extent[2]*WWMath::Fabs(IntersectContext.AE[0][2]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A2xE0 - */ - Vector3::Cross_Product(Vector3(0,0,1),IntersectContext.E[0],&IntersectContext.AxE[2][0]); - axis = IntersectContext.AxE[2][0]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = IntersectContext.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(IntersectContext.AE[1][0]) + box.Extent[1]*WWMath::Fabs(IntersectContext.AE[0][0]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A2xE1 - */ - Vector3::Cross_Product(Vector3(0,0,1),IntersectContext.E[1],&IntersectContext.AxE[2][1]); - axis = IntersectContext.AxE[2][1]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = -IntersectContext.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(IntersectContext.AE[1][1]) + box.Extent[1]*WWMath::Fabs(IntersectContext.AE[0][1]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - /* - ** AXIS_A2xE2 - */ - Vector3::Cross_Product(Vector3(0,0,1),IntersectContext.E[2],&IntersectContext.AxE[2][2]); - axis = IntersectContext.AxE[2][2]; - if (axis.Length2() > AXISLEN_EPSILON2) { - dp = -IntersectContext.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(IntersectContext.AE[1][2]) + box.Extent[1]*WWMath::Fabs(IntersectContext.AE[0][2]); - if (aabtri_intersect_cross_axis(axis,dp,leb0)) return false; - } - - return true; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp deleted file mode 100644 index bc4853578e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathfrustum.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathfrustum.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/29/00 5:40p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "colmathinlines.h" -#include "aaplane.h" -#include "plane.h" -#include "lineseg.h" -#include "tri.h" -#include "sphere.h" -#include "aabox.h" -#include "obbox.h" -#include "frustum.h" -#include "wwdebug.h" - - -// TODO: Most of these overlap functions actually do not catch all cases of when -// the primitive is outside of the frustum... - - -// Frustum functions -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const Vector3 & point) -{ - int mask = 0; - - for (int i = 0; i < 6; i++) { - int result = CollisionMath::Overlap_Test(frustum.Planes[i],point); - if (result == OUTSIDE) { - return OUTSIDE; - } - mask |= result; - } - - if (mask == INSIDE) { - return INSIDE; - } - return OVERLAPPED; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const TriClass & tri) -{ - int mask = 0; - - // TODO: doesn't catch all cases... - for (int i = 0; i < 6; i++) { - int result = CollisionMath::Overlap_Test(frustum.Planes[i],tri); - if (result == OUTSIDE) { - return OUTSIDE; - } - mask |= result; - } - - if (mask == INSIDE) { - return INSIDE; - } - return OVERLAPPED; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const SphereClass & sphere) -{ - int mask = 0; - - // TODO: doesn't catch all cases... - for (int i = 0; i < 6; i++) { - int result = CollisionMath::Overlap_Test(frustum.Planes[i],sphere); - if (result == OUTSIDE) { - return OUTSIDE; - } - mask |= result; - } - - if (mask == INSIDE) { - return INSIDE; - } - return OVERLAPPED; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const AABoxClass & box) -{ - int mask = 0; - - // TODO: doesn't catch all cases... - for (int i = 0; i < 6; i++) { - int result = CollisionMath::Overlap_Test(frustum.Planes[i],box); - if (result == OUTSIDE) { - return OUTSIDE; - } - mask |= result; - } - - if (mask == INSIDE) { - return INSIDE; - } - return OVERLAPPED; -} - - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const OBBoxClass & box) -{ - int mask = 0; - - // TODO: doesn't catch all cases... - for (int i = 0; i < 6; i++) { - int result = CollisionMath::Overlap_Test(frustum.Planes[i],box); - if (result == OUTSIDE) { - return OUTSIDE; - } - mask |= result; - } - - if (mask == INSIDE) { - return INSIDE; - } - return OVERLAPPED; -} - - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const OBBoxClass & box,int & planes_passed) -{ - int mask = 0; - - // TODO: doesn't catch all cases... - for (int i = 0; i < 6; i++) { - - int plane_bit = (1<. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathfrustum.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 5/04/01 8:25p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CollisionMath::Overlap_Test -- test a frustum and an AABox for overlap * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLMATHFRUSTUM_H -#define COLMATHFRUSTUM_H - -#include "always.h" -#include "aabox.h" -#include "vector3.h" -#include "lineseg.h" -#include "frustum.h" - -/* -** Inline collision functions dealing with frustums -*/ - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- test a frustum and an AABox for overlap * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/29/2000 gth : Created. * - *=============================================================================================*/ -inline -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const FrustumClass & frustum,const AABoxClass & box,int & planes_passed) -{ - int mask = 0; - - // TODO: doesn't catch all cases... - for (int i = 0; i < 6; i++) { - - int plane_bit = (1<. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathinlines.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/29/00 5:36p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLMATHINLINES_H -#define COLMATHINLINES_H - -#include "colmathaabox.h" -#include "colmathfrustum.h" -#include "colmathline.h" -#include "colmathplane.h" - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathline.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathline.cpp deleted file mode 100644 index 7f255ba487..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathline.cpp +++ /dev/null @@ -1,484 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/colmathline.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/29/01 10:25p $* - * * - * $Revision:: 10 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "aaplane.h" -#include "plane.h" -#include "lineseg.h" -#include "tri.h" -#include "sphere.h" -#include "aabox.h" -#include "obbox.h" -#include "wwdebug.h" - - -/* -** Structure used in the line->box test. There was a lot of common code between the axis- -** aligned and oriented box tests so I package all of the truely relevant information into -** this struct and pass it into a function local to this module. In the case of oriented -** boxes, the ray must be transformed into the box's coordinate system prior to the call -** and the normal is calculated slightly differently. -*/ -struct BoxTestStruct -{ - Vector3 Min; - Vector3 Max; - Vector3 P0; - Vector3 DP; - float Fraction; - bool Inside; - int Axis; - int Side; -}; - -/* -** Enumeration which can be used to categorize a point with respect to the projection -** of a box onto an axis. The point will either be to the negative side of the span, in the -** span, or on the positive side of the span. -*/ -enum BoxSideType { - BOX_SIDE_NEGATIVE = 0, - BOX_SIDE_POSITIVE = 1, - BOX_SIDE_MIDDLE = 2 -}; - - -/* -** Table of normals for an axis aligned box. -** access like this: -** -** _box_normal[AXIS][SIDE] -** -** is 0,1,2 meaning x,y,z -** is BOX_SIDE_NEGATIVE or BOX_SIDE_POSITIVE -*/ -static Vector3 _box_normal[3][2] = -{ - // plane = 0 (x axis) - { - Vector3(-1,0,0), // Left - Vector3(1,0,0) // Right - }, - // plane = 1 (y axis) - { - Vector3(0,-1,0), - Vector3(0,1,0) - }, - // plane = 2 (z axis) - { - Vector3(0,0,-1), - Vector3(0,0,1) - } -}; - -/* -** Local function prototypes -*/ -inline bool Test_Aligned_Box(BoxTestStruct * test); - - -bool CollisionMath::Collide(const LineSegClass & line,const AAPlaneClass & plane,CastResultStruct * result) -{ - float num,den,t; - - den = line.Get_DP()[plane.Normal]; - - /* - ** Check if line is parallel to this plane - */ - if (den == 0.0f) { - return false; - } - - num = -(line.Get_P0()[plane.Normal] - plane.Dist); - t = num/den; - - /* - ** If t is not between 0 and 1, the line containing the segment intersects - ** the plane but the segment does not - */ - if ((t < 0.0f) || (t > 1.0f)) { - return false; - } - - /* - ** Ok, we hit the plane! - */ - if (t < result->Fraction) { - result->Fraction = t; - result->Normal.Set(0,0,0); - result->Normal[plane.Normal] = 1.0f; - return true; - } - return false; -} - - -bool CollisionMath::Collide(const LineSegClass & line,const PlaneClass & plane,CastResultStruct * result) -{ - float num,den,t; - den = Vector3::Dot_Product(plane.N,line.Get_DP()); - - /* - ** If the denominator is zero, the ray is parallel to the plane - */ - if (den == 0.0f) { - return false; - } - - num = -(Vector3::Dot_Product(plane.N,line.Get_P0()) - plane.D); - t = num/den; - - /* - ** If t is not between 0 and 1, the line containing the segment intersects - ** the plane but the segment does not - */ - if ((t < 0.0f) || (t > 1.0f)) { - return false; - } - - /* - ** Ok, we hit the plane! - */ - if (t < result->Fraction) { - result->Fraction = t; - result->Normal = plane.N; - - /* - ** if user is asking for the point, compute it. - */ - if (result->ComputeContactPoint) { - result->ContactPoint = line.Get_P0() + result->Fraction * line.Get_DP(); - } - return true; - } - return false; -} - -bool CollisionMath::Collide(const LineSegClass & line,const TriClass & tri,CastResultStruct * res) -{ - TRACK_COLLISION_RAY_TRI; - - /* - ** Compute intersection of the line with the plane of the polygon - */ - PlaneClass plane(*tri.N,*tri.V[0]); - Vector3 ipoint; - float num,den,t; - - den = Vector3::Dot_Product(plane.N,line.Get_DP()); - - /* - ** If the denominator is zero, the ray is parallel to the plane - */ - if (den == 0.0f) { - return false; - } - num = -(Vector3::Dot_Product(plane.N,line.Get_P0()) - plane.D); - t = num/den; - - /* - ** If t is not between 0 and 1, the line containing the segment intersects - ** the plane but the segment does not - */ - if ((t < 0.0f) || (t > 1.0f)) { - return false; - } - - ipoint = line.Get_P0() + t*line.Get_DP(); - - /* - ** Check if this point is inside the triangle - */ - if (!tri.Contains_Point(ipoint)) { - return false; - } - - /* - ** Ok, we hit the triangle, set the collision results - */ - if (t < res->Fraction) { - res->Fraction = t; - res->Normal = plane.N; - if (res->ComputeContactPoint) { - res->ContactPoint = line.Get_P0() + res->Fraction * line.Get_DP(); - } - TRACK_COLLISION_RAY_TRI_HIT; - return true; - } - return false; -} - -bool CollisionMath::Collide(const LineSegClass & line,const SphereClass & sphere,CastResultStruct * res) -{ - // this game from graphics gems 1, page 388 - // intersection of a ray with a sphere - Vector3 dc = sphere.Center - line.Get_P0(); - float clen = Vector3::Dot_Product((dc) , line.Get_Dir()); - float disc = (sphere.Radius * sphere.Radius) - (dc.Length2() - clen*clen); - if (disc < 0.0f) { - return false; - } else { - float d = WWMath::Sqrt(disc); - float frac = (clen - d) / line.Get_Length(); - if (frac<0.0f) - frac = (clen + d) / line.Get_Length(); - if (frac<0.0f) return false; - if (frac < res->Fraction) { - - res->Fraction = frac; - - Vector3 p = line.Get_P0() + (clen - d)*line.Get_Dir(); - Vector3 norm = p - sphere.Center; - norm /= sphere.Radius; - - res->Normal = norm; - if (res->ComputeContactPoint) { - res->ContactPoint = line.Get_P0() + res->Fraction * line.Get_DP(); - } - return true; - } - } - return false; -} - -bool CollisionMath::Collide(const LineSegClass & line,const AABoxClass & box,CastResultStruct * res) -{ - // set up the test struct - BoxTestStruct test; - test.Min = box.Center - box.Extent; - test.Max = box.Center + box.Extent; - test.P0 = line.Get_P0(); - test.DP = line.Get_DP(); - - // check ray against the box, exit if the ray totally missed the box, - if (!Test_Aligned_Box(&test)) { - return false; - } - - // if ray starts inside the box, note that fact and bail. - if (test.Inside) { - res->StartBad = true; - return true; - } - - // Now, if this intersection is before any current intersection - // that we've found, install our intersection - if (test.Fraction < res->Fraction) { - res->Fraction = test.Fraction; - assert(test.Side != BOX_SIDE_MIDDLE); - res->Normal = _box_normal[test.Axis][test.Side]; - if (res->ComputeContactPoint) { - res->ContactPoint = line.Get_P0() + res->Fraction * line.Get_DP(); - } - return true; - } - return false; -} - -bool CollisionMath::Collide(const LineSegClass & line,const OBBoxClass & box,CastResultStruct * result) -{ - // set up the test struct - BoxTestStruct test; - test.Min = box.Center - box.Extent; - test.Max = box.Center + box.Extent; - - test.P0 = (box.Basis.Transpose() * (line.Get_P0() - box.Center)) + box.Center; - test.DP = box.Basis.Transpose() * line.Get_DP(); - - // check ray against the box, exit if the ray totally missed the box, - if (!Test_Aligned_Box(&test)) { - return false; - } - - // if ray starts inside the box, don't collide - if (test.Inside) { - result->StartBad = true; - return true; - } - - // Now, if this intersection is before any current intersection - // that we've found, install our intersection - if (test.Fraction < result->Fraction) { - result->Fraction = test.Fraction; - assert(test.Side != BOX_SIDE_MIDDLE); - - switch (test.Axis) { - case 0: - result->Normal.Set(box.Basis[0][0],box.Basis[1][0],box.Basis[2][0]); - break; - - case 1: - result->Normal.Set(box.Basis[0][1],box.Basis[1][1],box.Basis[2][1]); - break; - - case 2: - result->Normal.Set(box.Basis[0][2],box.Basis[1][2],box.Basis[2][2]); - break; - } - - if (test.Side == BOX_SIDE_NEGATIVE) { - result->Normal = -result->Normal; - } - if (result->ComputeContactPoint) { - result->ContactPoint = line.Get_P0() + result->Fraction * line.Get_DP(); - } - return true; - } - return false; -} - - - -/*********************************************************************************************** - * Test_Aligned_Box -- used as the guts of the Box intersection tests * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/20/98 GTH : Created. * - *=============================================================================================*/ -inline bool Test_Aligned_Box(BoxTestStruct * test) -{ - int i; - - // candidate intersection plane distance for each axis - float candidateplane[3]; - - // t value along the ray for each axis - float maxt[3]; - - // intersection point - Vector3 coord; - - // which "side" of the box for each axis - int quadrant[3]; - bool inside = true; - - for (i=0; i<3; i++) { - if (test->P0[i] < test->Min[i]) { - quadrant[i] = BOX_SIDE_NEGATIVE; - candidateplane[i] = test->Min[i]; - inside = false; - } else if (test->P0[i] > test->Max[i]) { - quadrant[i] = BOX_SIDE_POSITIVE; - candidateplane[i] = test->Max[i]; - inside = false; - } else { - quadrant[i] = BOX_SIDE_MIDDLE; - } - } - - /* - ** Ray started out inside the box... - */ - if (inside) { - test->Fraction = 0.0f; - test->Inside = true; - return true; - } - - /* - ** Calculate the 3 distances to the candidate planes - */ - for (i=0; i<3; i++) { - if (quadrant[i] != BOX_SIDE_MIDDLE && test->DP[i] != 0.0f) { - maxt[i] = (candidateplane[i] - test->P0[i]) / test->DP[i]; - } else { - maxt[i] = -1.0f; - } - } - - /* - ** Get the largest of the maxt's for the final choice of intersection - */ - int intersection_plane = 0; - - for (i=1; i<3; i++) { - if (maxt[i] > maxt[intersection_plane]) { - intersection_plane = i; - } - } - - /* - ** If the ray is "in front" of all of the planes, return - */ - if (maxt[intersection_plane] < 0.0f) { - return false; - } - - /* - ** Check if the ray is inside the box, i.e. on the two planes which - ** are not the intersection planes, the intersection point should - ** be between the min and max of the box. - */ - for (i=0; i<3; i++) { - - if (intersection_plane != i) { - - coord[i] = test->P0[i] + maxt[intersection_plane] * test->DP[i]; - - if ((coord[i] < test->Min[i]) || (coord[i] > test->Max[i])) { - - return false; // ray is outside the box - - } - - } else { - - coord[i] = candidateplane[i]; - - } - } - - /* - ** Fill in the intersection values - */ - test->Fraction = maxt[intersection_plane]; - test->Inside = false; - test->Axis = intersection_plane; - test->Side = quadrant[intersection_plane]; - return true; -} - - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathline.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathline.h deleted file mode 100644 index e583e014d4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathline.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathline.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/16/00 3:46p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef COLMATHLINE_H -#define COLMATHLINE_H - -/* -** Inline collision functions dealing with line segments -*/ - - -inline CollisionMath::OverlapType CollisionMath::Overlap_Test -( - const Vector3 & min, - const Vector3 & max, - const LineSegClass & line -) -{ - AABoxClass box; - box.Init_Min_Max(min,max); - return CollisionMath::Overlap_Test(box,line); -} - - - - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp deleted file mode 100644 index 684cdcb7cc..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbobb.cpp +++ /dev/null @@ -1,1409 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathobbobb.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/04/01 8:37p $* - * * - * $Revision:: 14 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * obb_intersect_box0_basis -- intersection test for a basis vector from box0 * - * obb_intersect_box1_basis -- intersection test for a basis vector from box1 * - * obb_intersect_axis -- intersection test for a axis * - * intersect_obb_obb -- test two OBBoxes for intersection * - * CollisionMath::Intersection_Test -- test two obb's for intersection * - * CollisionMath::Intersection_Test -- test an OBB for intersection with an AAB * - * CollisionMath::Intersection_Test -- Test an AAB for intersection with an OBB * - * obb_separation_test -- test the projections of two obb's for separation * - * obb_check_box0_basis -- projects the boxes onto a basis vector from box0 * - * obb_check_box1_basis -- projects the two obbs onto a basis vector from box1 * - * obb_check_axis -- projects the obbs onto an arbitrary axis * - * obb_compute_projections -- computes projections of two boxes onto an arbitrary axis * - * compute_contact_normal -- computes the contact normal (after contact is detected) * - * eval_side -- returns -1,0,1 depending on ab and side * - * compute_contact_point -- computes the contact point (after contact is detected) * - * collide_obb_obb -- test two obb's for collision * - * CollisionMath::Collide -- collide two OBB's * - * CollisionMath::Collide -- collide an OBB with an AAB * - * CollisionMath::Collide -- collide an AAB with an OBB * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "colmath.h" -#include "obbox.h" -#include "aabox.h" -#include "wwdebug.h" - - -/* -** Separating Axes have to be rejected if their length is smaller than some epsilon. -** Otherwise, erroneous results can be reported. -*/ -#define AXISLEN_EPSILON2 WWMATH_EPSILON * WWMATH_EPSILON // squared length of a separating axis must be larger than this - - -enum -{ - /* Axes used in Box-Box intersection tests */ - INTERSECTION = 0, - AXIS_A0, - AXIS_A1, - AXIS_A2, - AXIS_B0, - AXIS_B1, - AXIS_B2, - AXIS_A0B0, - AXIS_A0B1, - AXIS_A0B2, - AXIS_A1B0, - AXIS_A1B1, - AXIS_A1B2, - AXIS_A2B0, - AXIS_A2B1, - AXIS_A2B2 -}; - - - -/******************************************************************************** - - OBBox-OBBox intersection detection - - As with most of the collision detection functions, this code is based on the theorem - that given any two non-intersecting convex polyhedra, a separating plane/axis - can be found that will be defined by one of the face normals of one of the polyhedra - or the cross product of an edge from each polyhedra. - - In the case of two oriented 3D boxes, 15 separating axes must be tested. - Each of the basis vectors from box A, each of the basis vectors from box B, and - the cross products of any combination of a basis vector from A and a basis vector - from B. Some of these separating axis tests can be optimized. For example, if - the axis being tested is a basis vector from the first box, then that box's - extent does not need to be projected onto the axis... - - The first batch of functions in this module implement a intersection test. - A boolean is returned indicating whether the two boxes intersect each other - in any way. - - The OBB-ABB and ABB-OBB functions are also implemented in a way that re-uses - the OBB-OBB code. - -********************************************************************************/ - - -/** -** ObbIntersectionStruct -** Contains all of the intermediate and temporary values used by -** the set of functions used in detecting intersection for obb's -*/ -struct ObbIntersectionStruct -{ - ObbIntersectionStruct(const OBBoxClass &box0,const OBBoxClass & box1) : - Box0(box0), - Box1(box1) - { - Vector3::Subtract(box1.Center,box0.Center,&C); // vector from center of box0 to center of box1 - - A[0].Set(box0.Basis[0][0],box0.Basis[1][0],box0.Basis[2][0]); - A[1].Set(box0.Basis[0][1],box0.Basis[1][1],box0.Basis[2][1]); - A[2].Set(box0.Basis[0][2],box0.Basis[1][2],box0.Basis[2][2]); - - B[0].Set(box1.Basis[0][0],box1.Basis[1][0],box1.Basis[2][0]); - B[1].Set(box1.Basis[0][1],box1.Basis[1][1],box1.Basis[2][1]); - B[2].Set(box1.Basis[0][2],box1.Basis[1][2],box1.Basis[2][2]); - } - - Vector3 C; // Vector from the center0 to center1 - Vector3 A[3]; // basis vectors for box0 - Vector3 B[3]; // basis vectors for box1 - float AB[3][3]; // dot products of the basis vectors - - const OBBoxClass & Box0; - const OBBoxClass & Box1; - -private: - //not implemented - ObbIntersectionStruct(const ObbIntersectionStruct&); - ObbIntersectionStruct & operator = (const ObbIntersectionStruct&); -}; - - - -/*********************************************************************************************** - * obb_intersect_box0_basis -- intersection test for a basis vector from box0 * - * * - * The optimization here is that the projection of the first box is known since the axis is * - * one of its basis vectors. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static bool obb_intersect_box0_basis -( - ObbIntersectionStruct & context, - int axis_index -) -{ - // ra = box0 projection onto the axis - // rb = box1 projection onto the axis - float ra = context.Box0.Extent[axis_index]; - float rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[axis_index][0]) + - WWMath::Fabs(context.Box1.Extent[1]*context.AB[axis_index][1]) + - WWMath::Fabs(context.Box1.Extent[2]*context.AB[axis_index][2]); - float rsum = ra+rb; - - // u = projected distance between the box centers - float u = Vector3::Dot_Product(context.C,context.A[axis_index]); - - // (gth) the epsilon here was not scaled to the length of the axis so it - // caused problems when the axis being tested became very small - return ((u /*+ WWMATH_EPSILON*/ > rsum) || (u /*- WWMATH_EPSILON*/ < -rsum)); -} - - -/*********************************************************************************************** - * obb_intersect_box1_basis -- intersection test for a basis vector from box1 * - * * - * The "optimization" here is that the extent for the second box is known since the axis is * - * one of its basis vectors. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static bool obb_intersect_box1_basis -( - ObbIntersectionStruct & context, - int axis_index -) -{ - // ra = box0 projection onto the axis - // rb = box1 projection onto the axis - float ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[0][axis_index]) + - WWMath::Fabs(context.Box0.Extent[1]*context.AB[1][axis_index]) + - WWMath::Fabs(context.Box0.Extent[2]*context.AB[2][axis_index]); - float rb = context.Box1.Extent[axis_index]; - float rsum = ra+rb; - - // u = projected distance between the box centers - float u = Vector3::Dot_Product(context.C,context.B[axis_index]); - - // (gth) the epsilon here was not scaled to the length of the axis so it - // caused problems when the axis being tested became very small - return ((u /*+ WWMATH_EPSILON*/ > rsum) || (u /*- WWMATH_EPSILON*/ < -rsum)); -} - - -/*********************************************************************************************** - * obb_intersect_axis -- intersection test for a axis * - * * - * Checks intersection on an arbitrary axis where you've already computed the projectsions. * - * Many of the later tests in the OBB-OBB algorigthm fall into here since there are * - * optimizations in computing the projections but they are all specific to the axis being used * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obb_intersect_axis -( - ObbIntersectionStruct & context, - const Vector3 & axis, - float ra, - float rb -) -{ - float rsum = ra+rb; - float u = Vector3::Dot_Product(context.C,axis); - - // (gth) the epsilon here was not scaled to the length of the axis so it - // caused problems when the axis being tested became very small - return ((u /*+ WWMATH_EPSILON*/ > rsum) || (u /*- WWMATH_EPSILON*/ < -rsum)); -} - - -/*********************************************************************************************** - * intersect_obb_obb -- test two OBBoxes for intersection * - * * - * This function works in a very similar (but simplified) way as the Collide function. See * - * the comments in that function for more clues regarding the math involved... * - * * - * Due to the re-usage of intermediate calculations, this function is ~2x faster than the * - * equivalent Oriented_Boxes_Intersect. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -bool intersect_obb_obb -( - ObbIntersectionStruct & context -) -{ - Vector3 axis; - float ra,rb; - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0 - ///////////////////////////////////////////////////////////////////////// - context.AB[0][0] = Vector3::Dot_Product(context.A[0],context.B[0]); - context.AB[0][1] = Vector3::Dot_Product(context.A[0],context.B[1]); - context.AB[0][2] = Vector3::Dot_Product(context.A[0],context.B[2]); - if (context.Box0.Extent[0] > 0.0f) { - if (obb_intersect_box0_basis(context,0)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axsis A1 - ///////////////////////////////////////////////////////////////////////// - context.AB[1][0] = Vector3::Dot_Product(context.A[1],context.B[0]); - context.AB[1][1] = Vector3::Dot_Product(context.A[1],context.B[1]); - context.AB[1][2] = Vector3::Dot_Product(context.A[1],context.B[2]); - if (context.Box0.Extent[1] > 0.0f) { - if (obb_intersect_box0_basis(context,1)) return false; - } - - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2 - ///////////////////////////////////////////////////////////////////////// - context.AB[2][0] = Vector3::Dot_Product(context.A[2],context.B[0]); - context.AB[2][1] = Vector3::Dot_Product(context.A[2],context.B[1]); - context.AB[2][2] = Vector3::Dot_Product(context.A[2],context.B[2]); - if (context.Box0.Extent[2] > 0.0f) { - if (obb_intersect_box0_basis(context,2)) return false; - } - - - ///////////////////////////////////////////////////////////////////////// - // Axis B0,B1,B2 - ///////////////////////////////////////////////////////////////////////// - if (context.Box1.Extent[0] > 0.0f) { - if (obb_intersect_box1_basis(context,0)) return false; - } - - if (context.Box1.Extent[1] > 0.0f) { - if (obb_intersect_box1_basis(context,1)) return false; - } - - if (context.Box1.Extent[2] > 0.0f) { - if (obb_intersect_box1_basis(context,2)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.B[0],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[1]*context.AB[2][0])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[1][0]); - rb = WWMath::Fabs(context.Box1.Extent[1]*context.AB[0][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[0][1]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.B[1],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[1]*context.AB[2][1])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[1][1]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[0][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[0][0]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.B[2],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[1]*context.AB[2][2])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[1][2]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[0][1])+WWMath::Fabs(context.Box1.Extent[1]*context.AB[0][0]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.B[0],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[2][0])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[0][0]); - rb = WWMath::Fabs(context.Box1.Extent[1]*context.AB[1][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[1][1]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.B[1],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[2][1])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[0][1]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[1][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[1][0]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.B[2],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[2][2])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[0][2]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[1][1])+WWMath::Fabs(context.Box1.Extent[1]*context.AB[1][0]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.B[0],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[1][0])+WWMath::Fabs(context.Box0.Extent[1]*context.AB[0][0]); - rb = WWMath::Fabs(context.Box1.Extent[1]*context.AB[2][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[2][1]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.B[1],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[1][1])+WWMath::Fabs(context.Box0.Extent[1]*context.AB[0][1]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[2][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[2][0]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.B[2],&axis); - if (axis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[1][2])+WWMath::Fabs(context.Box0.Extent[1]*context.AB[0][2]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[2][1])+WWMath::Fabs(context.Box1.Extent[1]*context.AB[2][0]); - if (obb_intersect_axis(context,axis,ra,rb)) return false; - } - - return true; -} - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- test two obb's for intersection * - * * - * Simply sets up the context and calls intersect_obb_obb * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/25/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const OBBoxClass & box0,const OBBoxClass & box1) -{ - ObbIntersectionStruct context(box0,box1); - return intersect_obb_obb(context); -} - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- test an OBB for intersection with an AAB * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/25/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const OBBoxClass & box0,const AABoxClass & box1) -{ - OBBoxClass obbox1(box1.Center,box1.Extent); - ObbIntersectionStruct context(box0,obbox1); - return intersect_obb_obb(context); -} - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- Test an AAB for intersection with an OBB * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/25/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const AABoxClass & box0,const OBBoxClass & box1) -{ - OBBoxClass obbox0(box0.Center,box0.Extent); - ObbIntersectionStruct context(obbox0,box1); - return intersect_obb_obb(context); -} - - -/******************************************************************************** - - OBBox-OBBox collision detection - - This batch of functions implement collision detection for moving oriented - boxes. Assuming that the two arbitrarily oriented boxes are moving at a constant - velocity along a path and not rotating, the time of collision can be found. - The OBB-ABB and ABB-OBB functions are also implemented in a way that re-uses - the OBB-OBB code. - - For the code which computes the point of collision and collision normal, you'll - have to refer to the paper by Dave Eberly on oriented bounding boxes. The - formulas for the collision point are the only part of this I was unable to - derive myself (they are pretty nasty...) - -********************************************************************************/ - - -/** -** ObbCollisionStruct -** Contains all of the intermediate and temporary values used by -** the set of functions used in detecting collisions for obb's -*/ -struct ObbCollisionStruct -{ - ObbCollisionStruct(const OBBoxClass &box0,const Vector3 &move0,const OBBoxClass & box1,const Vector3 &move1) : - StartBad(true), // Startbad is true until one of the axes clears it - AxisId(INTERSECTION), // AxisId will be the axis that allowed the longest move - MaxFrac(0.0f), // MaxFrac is the longest allowed move so far - Box0(box0), - Move0(move0), - Box1(box1), - Move1(move1) - { - Vector3::Subtract(box1.Center,box0.Center,&C); // vector from center of box0 to center of box1 - Vector3::Subtract(move1,move0,&M); // move vector relative to stationary box0 - - A[0].Set(box0.Basis[0][0],box0.Basis[1][0],box0.Basis[2][0]); - A[1].Set(box0.Basis[0][1],box0.Basis[1][1],box0.Basis[2][1]); - A[2].Set(box0.Basis[0][2],box0.Basis[1][2],box0.Basis[2][2]); - - B[0].Set(box1.Basis[0][0],box1.Basis[1][0],box1.Basis[2][0]); - B[1].Set(box1.Basis[0][1],box1.Basis[1][1],box1.Basis[2][1]); - B[2].Set(box1.Basis[0][2],box1.Basis[1][2],box1.Basis[2][2]); - } - - bool StartBad; // Inital configuration is intersecting? - float MaxFrac; // Longest move allowed so far - int AxisId; // Last separating axis - int Side; // which side of the interval - - int TestAxisId; // Axis 'id' we're working on - Vector3 TestAxis; // Axis that we're working on - - Vector3 C; // Vector from the center0 to center1 - Vector3 M; // Move vector relative to stationary box0 - - Vector3 A[3]; // basis vectors for box0 - Vector3 B[3]; // basis vectors for box1 - float AB[3][3]; // dot products of the basis vectors - - const OBBoxClass & Box0; - const Vector3 & Move0; - const OBBoxClass & Box1; - const Vector3 & Move1; - -private: - //not implemented - ObbCollisionStruct(const ObbCollisionStruct&); - ObbCollisionStruct & operator = (const ObbCollisionStruct&); -}; - - - -/*********************************************************************************************** - * obb_separation_test -- test the projections of two obb's for separation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obb_separation_test -( - ObbCollisionStruct & context, - float ra, - float rb, - float u0, - float u1 -) -{ - float tmp; - float rsum = ra+rb; - - if ( u0 + WWMATH_EPSILON > rsum ) { - context.StartBad = false; - if ( u1 > rsum ) { - context.MaxFrac = 1.0f; - return true; - } else { - tmp = (rsum-u0)/(u1-u0); - if ( tmp > context.MaxFrac ) { - context.MaxFrac = tmp; - context.AxisId = context.TestAxisId; - context.Side = +1; - } - } - } else if ( u0 - WWMATH_EPSILON < -rsum ) { - context.StartBad = false; - if ( u1 < -rsum ) { - context.MaxFrac = 1.0f; - return true; - } else { - tmp = (-rsum-u0)/(u1-u0); - if ( tmp > context.MaxFrac ) { - context.MaxFrac = tmp; - context.AxisId = context.TestAxisId; - context.Side = -1; - } - } - } - return false; -} - - -/*********************************************************************************************** - * obb_check_box0_basis -- projects the boxes onto a basis vector from box0 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static bool obb_check_box0_basis -( - ObbCollisionStruct & context, - int axis_index -) -{ - // ra = box0 projection onto the axis - // rb = box1 projection onto the axis - float ra = context.Box0.Extent[axis_index]; - float rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[axis_index][0]) + - WWMath::Fabs(context.Box1.Extent[1]*context.AB[axis_index][1]) + - WWMath::Fabs(context.Box1.Extent[2]*context.AB[axis_index][2]); - - // u0 = projected distance between the box centers at t0 - // u1 = projected distance between the box centers at t1 - float u0 = Vector3::Dot_Product(context.C,context.A[axis_index]); - float u1 = u0 + Vector3::Dot_Product(context.M,context.A[axis_index]); - - return obb_separation_test(context,ra,rb,u0,u1); -} - - -/*********************************************************************************************** - * obb_check_box1_basis -- projects the two obbs onto a basis vector from box1 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static bool obb_check_box1_basis -( - ObbCollisionStruct & context, - int axis_index -) -{ - // ra = box0 projection onto the axis - // rb = box1 projection onto the axis - float ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[0][axis_index]) + - WWMath::Fabs(context.Box0.Extent[1]*context.AB[1][axis_index]) + - WWMath::Fabs(context.Box0.Extent[2]*context.AB[2][axis_index]); - float rb = context.Box1.Extent[axis_index]; - - // u0 = projected distance between the box centers at t0 - // u1 = projected distance between the box centers at t1 - float u0 = Vector3::Dot_Product(context.C,context.B[axis_index]); - float u1 = u0 + Vector3::Dot_Product(context.M,context.B[axis_index]); - return obb_separation_test(context,ra,rb,u0,u1); -} - - -/*********************************************************************************************** - * obb_check_axis -- projects the obbs onto an arbitrary axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obb_check_axis -( - ObbCollisionStruct & context, - float ra, - float rb -) -{ - float u0 = Vector3::Dot_Product(context.C,context.TestAxis); - float u1 = u0 + Vector3::Dot_Product(context.M,context.TestAxis); - return obb_separation_test(context,ra,rb,u0,u1); -} - - -/*********************************************************************************************** - * obb_compute_projections -- computes projections of two boxes onto an arbitrary axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void obb_compute_projections -( - const ObbCollisionStruct & context, - float * ra, - float * rb -) -{ - *ra = context.Box0.Extent.X * WWMath::Fabs(Vector3::Dot_Product(context.A[0],context.TestAxis)) + - context.Box0.Extent.Y * WWMath::Fabs(Vector3::Dot_Product(context.A[1],context.TestAxis)) + - context.Box0.Extent.Z * WWMath::Fabs(Vector3::Dot_Product(context.A[2],context.TestAxis)); - - *rb = context.Box1.Extent.X * WWMath::Fabs(Vector3::Dot_Product(context.B[0],context.TestAxis)) + - context.Box1.Extent.Y * WWMath::Fabs(Vector3::Dot_Product(context.B[1],context.TestAxis)) + - context.Box1.Extent.Z * WWMath::Fabs(Vector3::Dot_Product(context.B[2],context.TestAxis)); -} - - -/*********************************************************************************************** - * compute_contact_normal -- computes the contact normal (after contact is detected) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void compute_contact_normal(ObbCollisionStruct & context,CastResultStruct * result) -{ - switch(context.AxisId) - { - case INTERSECTION: -#pragma message("Fatal assert disabled for demo, obb-obb collision") -// WWASSERT(0); -// break; - - case AXIS_A0: - result->Normal = context.A[0]; - break; - - case AXIS_A1: - result->Normal = context.A[1]; - break; - - case AXIS_A2: - result->Normal = context.A[2]; - break; - - case AXIS_B0: - result->Normal = context.B[0]; - break; - - case AXIS_B1: - result->Normal = context.B[1]; - break; - - case AXIS_B2: - result->Normal = context.B[2]; - break; - - case AXIS_A0B0: - Vector3::Cross_Product(context.A[0],context.B[0],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A0B1: - Vector3::Cross_Product(context.A[0],context.B[1],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A0B2: - Vector3::Cross_Product(context.A[0],context.B[2],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A1B0: - Vector3::Cross_Product(context.A[1],context.B[0],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A1B1: - Vector3::Cross_Product(context.A[1],context.B[1],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A1B2: - Vector3::Cross_Product(context.A[1],context.B[2],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A2B0: - Vector3::Cross_Product(context.A[2],context.B[0],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A2B1: - Vector3::Cross_Product(context.A[2],context.B[1],&result->Normal); - result->Normal.Normalize(); - break; - - case AXIS_A2B2: - Vector3::Cross_Product(context.A[2],context.B[2],&result->Normal); - result->Normal.Normalize(); - break; - } - - result->Normal *= -context.Side; -} - - -/*********************************************************************************************** - * eval_side -- returns -1,0,1 depending on ab and side * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline float eval_side(float ab,float side) -{ - if (ab > 0.0f) { - return side; - } else if (ab < 0.0f) { - return -side; - } else { - return 0.0f; - } -} - - -/*********************************************************************************************** - * compute_contact_point -- computes the contact point (after contact is detected) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void compute_contact_point(ObbCollisionStruct & context,CastResultStruct * result) -{ - int i,j; - float x[3]; // box0 parameters - float y[3]; // box1 parameters - float den; - Vector3 dcnew(0,0,0); - -//again: - - if (context.AxisId >= AXIS_A0B0) { - Vector3 cnew0; - Vector3 cnew1; - Vector3::Add(context.Box0.Center,context.MaxFrac * context.Move0,&cnew0); - Vector3::Add(context.Box1.Center,context.MaxFrac * context.Move1,&cnew1); - Vector3::Subtract(cnew1,cnew0,&dcnew); - } - - //PROBLEMS: - //in case of edge-face or face-face or perfectly aligned edge-edge this - //routine is only computing a single point. - switch(context.AxisId) - { - case AXIS_A0: - case AXIS_A1: - case AXIS_A2: - i = context.AxisId - AXIS_A0; - for (j=0; j<3; j++) { - y[j] = -eval_side(context.AB[i][j],context.Side); - } - context.Box1.Compute_Point(y,&(result->ContactPoint)); - result->ContactPoint += result->Fraction * context.Move1; - return; - - case AXIS_B0: - case AXIS_B1: - case AXIS_B2: - j = context.AxisId - AXIS_B0; - for (i=0; i<3; i++) { - x[i] = eval_side(context.AB[i][j],context.Side); - } - context.Box0.Compute_Point(x,&(result->ContactPoint)); - result->ContactPoint += result->Fraction * context.Move0; - return; - - case AXIS_A0B0: - x[1] = -eval_side(context.AB[2][0],context.Side) * context.Box0.Extent[1]; - x[2] = eval_side(context.AB[1][0],context.Side) * context.Box0.Extent[2]; - y[1] = -eval_side(context.AB[0][2],context.Side) * context.Box1.Extent[1]; - y[2] = eval_side(context.AB[0][1],context.Side) * context.Box1.Extent[2]; - - den = (1.0f - context.AB[0][0] * context.AB[0][0]); - if (WWMath::Fabs(den) > 0.0f) { - x[0] = Vector3::Dot_Product(context.A[0],dcnew); - x[0] += context.AB[0][0] * (Vector3::Dot_Product(-context.B[0],dcnew) + context.AB[1][0]*x[1] + context.AB[2][0]*x[2]); - x[0] += context.AB[0][1] * y[1] + context.AB[0][2] * y[2]; - x[0] /= den; - } else { - x[0] = 0.0f; - } - break; - - case AXIS_A0B1: - x[1] = -eval_side(context.AB[2][1],context.Side) * context.Box0.Extent[1]; - x[2] = eval_side(context.AB[1][1],context.Side) * context.Box0.Extent[2]; - y[0] = eval_side(context.AB[0][2],context.Side) * context.Box1.Extent[0]; - y[2] = -eval_side(context.AB[0][0],context.Side) * context.Box1.Extent[2]; - - den = (1.0f - context.AB[0][1] * context.AB[0][1]); - if (WWMath::Fabs(den) > 0.0f) { - x[0] = Vector3::Dot_Product(context.A[0],dcnew); - x[0] += context.AB[0][1] * (Vector3::Dot_Product(-context.B[1],dcnew) + context.AB[1][1]*x[1] + context.AB[2][1]*x[2]); - x[0] += context.AB[0][0] * y[0] + context.AB[0][2] * y[2]; - x[0] /= den; - } else { - x[0] = 0.0f; - } - break; - - case AXIS_A0B2: - x[1] = -eval_side(context.AB[2][2],context.Side) * context.Box0.Extent[1]; - x[2] = eval_side(context.AB[1][2],context.Side) * context.Box0.Extent[2]; - y[0] = -eval_side(context.AB[0][1],context.Side) * context.Box1.Extent[0]; - y[1] = eval_side(context.AB[0][0],context.Side) * context.Box1.Extent[1]; - - den = (1.0f - context.AB[0][2] * context.AB[0][2]); - if (WWMath::Fabs(den) > 0.0f) { - x[0] = Vector3::Dot_Product(context.A[0],dcnew); - x[0] += context.AB[0][2] * (Vector3::Dot_Product(-context.B[2],dcnew) + context.AB[1][2]*x[1] + context.AB[2][2]*x[2]); - x[0] += context.AB[0][0] * y[0] + context.AB[0][1] * y[1]; - x[0] /= den; - } else { - x[0] = 0.0f; - } - break; - - case AXIS_A1B0: - x[0] = eval_side(context.AB[2][0],context.Side) * context.Box0.Extent[0]; - x[2] = -eval_side(context.AB[0][0],context.Side) * context.Box0.Extent[2]; - y[1] = -eval_side(context.AB[1][2],context.Side) * context.Box1.Extent[1]; - y[2] = eval_side(context.AB[1][1],context.Side) * context.Box1.Extent[2]; - - den = (1.0f - context.AB[1][0] * context.AB[1][0]); - if (WWMath::Fabs(den) > 0.0f) { - x[1] = Vector3::Dot_Product(context.A[1],dcnew); - x[1] += context.AB[1][0] * (Vector3::Dot_Product(-context.B[0],dcnew) + context.AB[0][0]*x[0] + context.AB[2][0]*x[2]); - x[1] += context.AB[1][1] * y[1] + context.AB[1][2] * y[2]; - x[1] /= den; - } else { - x[1] = 0.0f; - } - break; - - case AXIS_A1B1: - x[0] = eval_side(context.AB[2][1],context.Side) * context.Box0.Extent[0]; - x[2] = -eval_side(context.AB[0][1],context.Side) * context.Box0.Extent[2]; - y[0] = eval_side(context.AB[1][2],context.Side) * context.Box1.Extent[0]; - y[2] = -eval_side(context.AB[1][0],context.Side) * context.Box1.Extent[2]; - - den = 1.0f / (1.0f - context.AB[1][1] * context.AB[1][1]); - if (WWMath::Fabs(den) > 0.0f) { - x[1] = Vector3::Dot_Product(context.A[1],dcnew); - x[1] += context.AB[1][1] * (Vector3::Dot_Product(-context.B[1],dcnew) + context.AB[0][1]*x[0] + context.AB[2][1]*x[2]); - x[1] += context.AB[1][0] * y[0] + context.AB[1][2] * y[2]; - x[1] /= den; - } else { - x[1] = 0.0f; - } - break; - - case AXIS_A1B2: - x[0] = eval_side(context.AB[2][2],context.Side) * context.Box0.Extent[0]; - x[2] = -eval_side(context.AB[0][2],context.Side) * context.Box0.Extent[2]; - y[0] = -eval_side(context.AB[1][1],context.Side) * context.Box1.Extent[0]; - y[1] = eval_side(context.AB[1][0],context.Side) * context.Box1.Extent[1]; - - den = (1.0f - context.AB[1][2] * context.AB[1][2]); - if (WWMath::Fabs(den) > 0.0f) { - x[1] = Vector3::Dot_Product(context.A[1],dcnew); - x[1] += context.AB[1][2] * (Vector3::Dot_Product(-context.B[2],dcnew) + context.AB[0][2]*x[0] + context.AB[2][2]*x[2]); - x[1] += context.AB[1][0] * y[0] + context.AB[1][1] * y[1]; - x[1] /= den; - } else { - x[1] = 0.0f; - } - break; - - case AXIS_A2B0: - x[0] = -eval_side(context.AB[1][0],context.Side) * context.Box0.Extent[0]; - x[1] = eval_side(context.AB[0][0],context.Side) * context.Box0.Extent[1]; - y[1] = -eval_side(context.AB[2][2],context.Side) * context.Box1.Extent[1]; - y[2] = eval_side(context.AB[2][1],context.Side) * context.Box1.Extent[2]; - - den = (1.0f - context.AB[2][0] * context.AB[2][0]); - if (WWMath::Fabs(den) > 0.0f) { - x[2] = Vector3::Dot_Product(context.A[2],dcnew); - x[2] += context.AB[2][0] * (Vector3::Dot_Product(-context.B[0],dcnew) + context.AB[0][0]*x[0] + context.AB[1][0]*x[1]); - x[2] += context.AB[2][1] * y[1] + context.AB[2][2] * y[2]; - x[2] /= den; - } else { - x[2] = 0.0f; - } - break; - - case AXIS_A2B1: - x[0] = -eval_side(context.AB[1][1],context.Side) * context.Box0.Extent[0]; - x[1] = eval_side(context.AB[0][1],context.Side) * context.Box0.Extent[1]; - y[0] = eval_side(context.AB[2][2],context.Side) * context.Box1.Extent[0]; - y[2] = -eval_side(context.AB[2][0],context.Side) * context.Box1.Extent[2]; - - den = (1.0f - context.AB[2][1] * context.AB[2][1]); - if (WWMath::Fabs(den) > 0.0f) { - x[2] = Vector3::Dot_Product(context.A[2],dcnew); - x[2] += context.AB[2][1] * (Vector3::Dot_Product(-context.B[1],dcnew) + context.AB[0][1]*x[0] + context.AB[1][1]*x[1]); - x[2] += context.AB[2][0] * y[0] + context.AB[2][2] * y[2]; - x[2] /= den; - } else { - x[2] = 0.0f; - } - break; - - case AXIS_A2B2: - x[0] = -eval_side(context.AB[1][2],context.Side) * context.Box0.Extent[0]; - x[1] = eval_side(context.AB[0][2],context.Side) * context.Box0.Extent[1]; - y[0] = -eval_side(context.AB[2][1],context.Side) * context.Box1.Extent[0]; - y[1] = eval_side(context.AB[2][0],context.Side) * context.Box1.Extent[1]; - - den = (1.0f - context.AB[2][2] * context.AB[2][2]); - if (WWMath::Fabs(den) > 0.0f) { - x[2] = Vector3::Dot_Product(context.A[2],dcnew); - x[2] += context.AB[2][2] * (Vector3::Dot_Product(-context.B[2],dcnew) + context.AB[0][2]*x[0] + context.AB[1][2]*x[1]); - x[2] += context.AB[2][0] * y[0] + context.AB[2][1] * y[1]; - x[2] /= den; - } else { - x[2] = 0.0f; - } - break; - } - - // all but the first two cases fall through to here - result->ContactPoint.X = context.Box0.Center.X + - x[0]*context.A[0].X + - x[1]*context.A[1].X + - x[2]*context.A[2].X; - - result->ContactPoint.Y = context.Box0.Center.Y + - x[0]*context.A[0].Y + - x[1]*context.A[1].Y + - x[2]*context.A[2].Y; - - result->ContactPoint.Z = context.Box0.Center.Z + - x[0]*context.A[0].Z + - x[1]*context.A[1].Z + - x[2]*context.A[2].Z; - - Vector3::Add(result->ContactPoint,result->Fraction * context.Move0,&(result->ContactPoint)); - -} - - -/*********************************************************************************************** - * collide_obb_obb -- test two obb's for collision * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/25/99 GTH : Created. * - *=============================================================================================*/ -bool collide_obb_obb -( - ObbCollisionStruct & context, - CastResultStruct * result -) -{ - Vector3 axis; - float ra,rb; - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0 - // Projecting the two boxes onto Box0's X axis. If their intervals - // on this line do not intersect, the boxes are not intersecting! - // Each of the tests in this function work in a similar way. - // For this function I compute the AB's that are needed. The first - // three tests compute all of these constants. - ///////////////////////////////////////////////////////////////////////// - context.TestAxisId = AXIS_A0; - context.AB[0][0] = Vector3::Dot_Product(context.A[0],context.B[0]); - context.AB[0][1] = Vector3::Dot_Product(context.A[0],context.B[1]); - context.AB[0][2] = Vector3::Dot_Product(context.A[0],context.B[2]); - if (obb_check_box0_basis(context,0)) goto exit; - - ///////////////////////////////////////////////////////////////////////// - // Axsis A1 - ///////////////////////////////////////////////////////////////////////// - context.TestAxisId = AXIS_A1; - context.AB[1][0] = Vector3::Dot_Product(context.A[1],context.B[0]); - context.AB[1][1] = Vector3::Dot_Product(context.A[1],context.B[1]); - context.AB[1][2] = Vector3::Dot_Product(context.A[1],context.B[2]); - if (obb_check_box0_basis(context,1)) goto exit; - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2 - ///////////////////////////////////////////////////////////////////////// - context.TestAxisId = AXIS_A2; - context.AB[2][0] = Vector3::Dot_Product(context.A[2],context.B[0]); - context.AB[2][1] = Vector3::Dot_Product(context.A[2],context.B[1]); - context.AB[2][2] = Vector3::Dot_Product(context.A[2],context.B[2]); - if (obb_check_box0_basis(context,2)) goto exit; - - ///////////////////////////////////////////////////////////////////////// - // Axis = B0 - ///////////////////////////////////////////////////////////////////////// - context.TestAxisId = AXIS_B0; - if (obb_check_box1_basis(context,0)) goto exit; - - ///////////////////////////////////////////////////////////////////////// - // Axis = B1 - ///////////////////////////////////////////////////////////////////////// - context.TestAxisId = AXIS_B1; - if (obb_check_box1_basis(context,1)) goto exit; - - ///////////////////////////////////////////////////////////////////////// - // Axis = B2 - ///////////////////////////////////////////////////////////////////////// - context.TestAxisId = AXIS_B2; - if (obb_check_box1_basis(context,2)) goto exit; - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0xB0 - // The axes defined by the cross product between the boxes' basis - // vectors are optimized in a similar way to this one: - // - // ra = |ex*A0*(A0xB0)| + |ey*A1*(A0xB0)| + |ez*A2*(A0xB0)| - // = |ey*A1*(A0xB0)| + |ez*A2*(A0xB0)| A0*(A0xB0)=0 - // = |ey*B0*(A1xA0)| + |ez*B0*(A2xA0)| A*(BxC)=B*(CxA)=C*(AxB) - // = |-ey*A2*B0| + |ez*A1*B0| A0xA1=A2 - // = |ey*AB[2][0]| + |ez*AB[1][0]| already computed these dot products! - // - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.B[0],&context.TestAxis); - context.TestAxisId = AXIS_A0B0; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[1]*context.AB[2][0])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[1][0]); - rb = WWMath::Fabs(context.Box1.Extent[1]*context.AB[0][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[0][1]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.B[1],&context.TestAxis); - context.TestAxisId = AXIS_A0B1; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[1]*context.AB[2][1])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[1][1]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[0][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[0][0]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A0xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.B[2],&context.TestAxis); - context.TestAxisId = AXIS_A0B2; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[1]*context.AB[2][2])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[1][2]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[0][1])+WWMath::Fabs(context.Box1.Extent[1]*context.AB[0][0]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.B[0],&context.TestAxis); - context.TestAxisId = AXIS_A1B0; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[2][0])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[0][0]); - rb = WWMath::Fabs(context.Box1.Extent[1]*context.AB[1][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[1][1]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.B[1],&context.TestAxis); - context.TestAxisId = AXIS_A1B1; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[2][1])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[0][1]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[1][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[1][0]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.B[2],&context.TestAxis); - context.TestAxisId = AXIS_A1B2; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[2][2])+WWMath::Fabs(context.Box0.Extent[2]*context.AB[0][2]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[1][1])+WWMath::Fabs(context.Box1.Extent[1]*context.AB[1][0]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.B[0],&context.TestAxis); - context.TestAxisId = AXIS_A2B0; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[1][0])+WWMath::Fabs(context.Box0.Extent[1]*context.AB[0][0]); - rb = WWMath::Fabs(context.Box1.Extent[1]*context.AB[2][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[2][1]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.B[1],&context.TestAxis); - context.TestAxisId = AXIS_A2B1; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[1][1])+WWMath::Fabs(context.Box0.Extent[1]*context.AB[0][1]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[2][2])+WWMath::Fabs(context.Box1.Extent[2]*context.AB[2][0]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.B[2],&context.TestAxis); - context.TestAxisId = AXIS_A2B2; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - ra = WWMath::Fabs(context.Box0.Extent[0]*context.AB[1][2])+WWMath::Fabs(context.Box0.Extent[1]*context.AB[0][2]); - rb = WWMath::Fabs(context.Box1.Extent[0]*context.AB[2][1])+WWMath::Fabs(context.Box1.Extent[1]*context.AB[2][0]); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - if (!result->StartBad) { - - context.TestAxisId = context.AxisId; - - ///////////////////////////////////////////////////////////////////////// - // Final three checks are for eliminating false collisions - // Axis = A0xMove - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[0],context.Move0,&context.TestAxis); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - obb_compute_projections(context,&ra,&rb); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A1xMove - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[1],context.Move0,&context.TestAxis); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - obb_compute_projections(context,&ra,&rb); - if (obb_check_axis(context,ra,rb)) goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // Axis = A2xMove - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(context.A[2],context.Move0,&context.TestAxis); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - obb_compute_projections(context,&ra,&rb); - if (obb_check_axis(context,ra,rb)) goto exit; - } - } - -exit: - - if (context.StartBad) { - result->StartBad = true; - result->Fraction = 0.0f; - return true; - } - - - /* - ** If our fraction is smaller, override the previous - ** values because our collision occured first. - */ - if (context.MaxFrac < result->Fraction) { - - result->Fraction = context.MaxFrac; - - compute_contact_normal(context,result); - if (result->ComputeContactPoint) { - compute_contact_point(context,result); - } - return true; - } - return false; -} - -/*********************************************************************************************** - * CollisionMath::Collide -- collide two obb's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide -( - const OBBoxClass & box0, - const Vector3 & move0, - const OBBoxClass & box1, - const Vector3 & move1, - CastResultStruct * result -) -{ - ObbCollisionStruct context(box0,move0,box1,move1); - return collide_obb_obb(context,result); -} - - -/*********************************************************************************************** - * CollisionMath::Collide -- collide an OBB with an AAB * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/25/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide -( - const OBBoxClass & box0, - const Vector3 & move0, - const AABoxClass & box1, - const Vector3 & move1, - CastResultStruct * result -) -{ - OBBoxClass obbox1(box1.Center,box1.Extent); - ObbCollisionStruct context(box0,move0,obbox1,move1); - return collide_obb_obb(context,result); -} - - -/*********************************************************************************************** - * CollisionMath::Collide -- collide an AAB with an OBB * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/25/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide -( - const AABoxClass & box0, - const Vector3 & move0, - const OBBoxClass & box1, - const Vector3 & move1, - CastResultStruct * result -) -{ - OBBoxClass obbox0(box0.Center,box0.Extent); - ObbCollisionStruct context(obbox0,move0,box1,move1); - return collide_obb_obb(context,result); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp deleted file mode 100644 index 0d7d879eda..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbox.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathobbox.cpp $* - * * - * Org Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 9 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "aaplane.h" -#include "plane.h" -#include "lineseg.h" -#include "tri.h" -#include "sphere.h" -#include "aabox.h" -#include "obbox.h" -#include "wwdebug.h" - - - -// OBBox functions, where is operand B with respect to the OBBox -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const OBBoxClass & box,const Vector3 & point) -{ - // transform point into box coordinate system - Vector3 localpoint; - Matrix3x3::Transpose_Rotate_Vector(box.Basis,(point - box.Center),&localpoint); - - // if the point is outside any of the extents, it is outside the box - if (WWMath::Fabs(localpoint.X) > box.Extent.X) { - return OUTSIDE; - } - if (WWMath::Fabs(localpoint.Y) > box.Extent.Y) { - return OUTSIDE; - } - if (WWMath::Fabs(localpoint.Z) > box.Extent.Z) { - return OUTSIDE; - } - return INSIDE; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const OBBoxClass & box,const LineSegClass & line) -{ - CastResultStruct res; - Collide(line,box,&res); - return eval_overlap_collision(res); -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const OBBoxClass & box,const TriClass & tri) -{ - CastResultStruct res; - Collide(box,Vector3(0,0,0),tri,Vector3(0,0,0),&res); - return eval_overlap_collision(res); -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AABoxClass & aabox,const OBBoxClass & obbox) -{ - if (CollisionMath::Intersection_Test(aabox,obbox)) { - return BOTH; // inside or overlapping - } else { - return OUTSIDE; - } -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const OBBoxClass & obbox,const AABoxClass & aabox) -{ - if (CollisionMath::Intersection_Test(obbox,aabox)) { - return BOTH; // inside or overlapping - } else { - return OUTSIDE; - } -} - - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const OBBoxClass & box,const OBBoxClass & box2) -{ - CastResultStruct res; - Collide(box,Vector3(0,0,0),box2,Vector3(0,0,0),&res); - return eval_overlap_collision(res); -} - -bool CollisionMath::Collide -( - const OBBoxClass & box, - const Vector3 & move_vector, - const PlaneClass & plane, - CastResultStruct * result -) -{ - float frac; - - float extent = box.Project_To_Axis(plane.N); - float dist = Vector3::Dot_Product(plane.N,box.Center) + plane.D; - float move = Vector3::Dot_Product(plane.N,move_vector); - - if (dist > extent) { - if (dist + move > extent) { - // entire move ok! - frac = 1.0f; - } else { - // partial move allowed - frac = (extent - dist) / move; - } - - } else if (dist < -extent) { - if (dist + move < -extent) { - // entire move ok! - frac = 1.0f; - } else { - // partial move allowed - frac = (-extent - dist) / move; - } - } else { - result->StartBad = true; - result->Normal = plane.N; - return true; - } - - if (frac < result->Fraction) { - result->Fraction = frac; - result->Normal = plane.N; - if (result->ComputeContactPoint) { - - Vector3 move_dir(move_vector); - move_dir.Normalize(); - float move_extent = Vector3::Dot_Product(move_dir,box.Extent); - result->ContactPoint = box.Center + result->Fraction*move_vector + move_extent*move_dir; - - } - return true; - } - return false; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp deleted file mode 100644 index 71052820c8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathobbtri.cpp +++ /dev/null @@ -1,1507 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathobbtri.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/04/01 8:37p $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * obbtri_collision_separation_test -- test the projected extents for separation * - * obbtri_check_collision_axis -- project the obb and tri onto an arbitrary axis * - * obbtri_check_collision_cross_axis -- intersection check for a "cross-product" axis * - * obbtri_check_collision_basis_axis -- intersection check for a basis axis * - * obbtri_check_collision_normal_axis -- intersection check for the triangle normal * - * eval_side -- returns -1,0,+1 depending on the signe of val and side * - * obbtri_compute_contact_normal -- computes the normal of the collision * - * eval_A0_point -- contact point parameters for A0xEx * - * eval_A1_point -- contact point parameters for A1xEx * - * eval_A2_point -- contact point parameters for A2xEx * - * obbtri_compute_contact_point -- compute the contact point * - * CollisionMath::Collide -- collide an obbox into a triangle * - * obbtri_intersection_separation_test -- test the projected extents for intersection * - * obbtri_check_intersection_cross_axis -- intersection check for a "cross-product" axis * - * obbtri_check_intersection_basis_axis -- intersection check for a basis axis * - * obbtri_check_intersection_normal_axis -- intersection check for the triangle normal * - * CollisionMath::Intersection_Test -- Intersection check for an OBBox and a triangle * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "colmath.h" -#include "obbox.h" -#include "tri.h" -#include "wwdebug.h" - - -/* -** Separating Axes have to be rejected if their length is smaller than some epsilon. -** Otherwise, erroneous results can be reported. -*/ -#define AXISLEN_EPSILON2 WWMATH_EPSILON * WWMATH_EPSILON // squared length of a separating axis must be larger than this - -/* -** Axes used in Box-Tri intersection tests -** The axes of the box are A0,A1,A2. N is the normal of the triangle, -** E0,E1,E2 are direction vectors for the edges of the triangle. -** (the box axes are labeled A0,A1,A2 as a holdover from the obbox-obbox -** collision code which this was derived from where there are two boxes -** A and B) -*/ -enum -{ - INTERSECTION = 0, - AXIS_N, // normal of the triangle - AXIS_A0, // first basis vector of the box - AXIS_A1, // second basis vector of the box - AXIS_A2, // third basis vector of the box - - AXIS_A0E0, // box0 x edge0... - AXIS_A1E0, - AXIS_A2E0, - AXIS_A0E1, - AXIS_A1E1, - AXIS_A2E1, - AXIS_A0E2, - AXIS_A1E2, - AXIS_A2E2 -}; - - -/****************************************************************************************** - - OBBox->Triangle collision - - As with most of the collision detection functions, this code is based on the theorem - that given any two non-intersecting convex polyhedra, a separating plane/axis - can be found that will be defined by one of the face normals of one of the polyhedra - or the cross product of an edge from each polyhedra. The key optimization for - boxes is that many of these axes are the same. The normal to a face is the same - as the axis for four of the edges of the box, etc. - - This test must be done using the tri normal, the three basis vectors - for the box, and three vectors defined by the cross products of the basis - and edge vectors. When testing the basis vectors, there will be two extents for - the tri (the other two vectors projected onto the axis being tested). - The appropriate extent must be used in the test (largest value which is pointing - towards the direction of the box). In addition, I've found that I must test axes - defined by the cross products of the move vector and the box axes. These tests - catch "false collisions" where the box passes very close to the triangle but does - not actually hit it. - - Each axis test will use the following logic: - Project D onto the axis being used, it is the separation distance. If the - projection of the extent of the box + the projection of the extent of the - tri is greater than D*axis then the two intersect - -******************************************************************************************/ - -/** -** BoxTriColStruct -** Scratchpad variables for the OBBox-Triangle collision detection functions. One instance -** of this structure will be used for all of the local variables and its pointer will be -** handed of to various inline functions for the axis tests. -** Note that much of the code needs the un-normalized triangle normal. For this reason, -** I have to compute N rather than copying it from the triangle. (commenting this to -** avoid re-generating a difficult to find bug that I had) -** -** Note that the MaxFrac variable starts negative so that we can accept slightly negative -** fractions (interpenetrations). But we clamp the returned result to 0.0 so that we never -** allow an object to get more embedded, just to possibly break itself free if it is within -** the epsilon. This is important because sometimes objects seem to intersect simply due to -** floating point roundoff error... -*/ -struct BTCollisionStruct -{ - BTCollisionStruct(const OBBoxClass &box,const Vector3 &move,const TriClass &tri,const Vector3 &trimove) : - Box(box), - Tri(tri), - BoxMove(move), - TriMove(trimove) - { - Reset(); - } - - void Reset(void) - { - StartBad = true; // true until an axis clears it - MaxFrac = -1.0f; // maximum move allowed so far (accept slightly negative but clamp to zero at end) - AxisId = INTERSECTION; // axis that allowed the longest move - Point = 0; // index of triangle point that was closest to the box - Side = 0; // side of the interval - - Vector3::Subtract(*Tri.V[0],Box.Center,&D); // vector from center of box to vertex 0 - Vector3::Subtract(BoxMove,TriMove,&Move); // move vector relative to stationary triangle - - Vector3::Subtract(*Tri.V[1],*Tri.V[0],&E[0]); - Vector3::Subtract(*Tri.V[2],*Tri.V[0],&E[1]); - Vector3::Subtract(E[1],E[0],&E[2]); - - A[0].Set(Box.Basis[0][0],Box.Basis[1][0],Box.Basis[2][0]); - A[1].Set(Box.Basis[0][1],Box.Basis[1][1],Box.Basis[2][1]); - A[2].Set(Box.Basis[0][2],Box.Basis[1][2],Box.Basis[2][2]); - - Vector3::Cross_Product(E[0],E[1],&N); - } - - bool StartBad; // Inital configuration is intersecting? - float MaxFrac; // Longest move allowed so far - int AxisId; // Last separating axis - int Point; // Index of the "closest" triangle point (or one of them) - int Side; // which side of the interval - - int TestSide; // Was the axis we're working on flipped - int TestAxisId; // Axis 'id' we're working on - int TestPoint; // Index of the closest vertex - Vector3 TestAxis; // Axis we're working on - - Vector3 D; // Vector from the center of the box to v0 - Vector3 Move; // Move vector relative to stationary triangle - float AE[3][3]; // Dot products of the Basis vectors and edges - float AN[3]; // Dot products of the Basis vectors and the normal - Vector3 AxE[3][3]; // Cross produts of the Basis vectors and edges - - Vector3 A[3]; // basis vectors for the box - Vector3 E[3]; // edge vectors for the triangle - Vector3 N; // normal (NOT normalized!!!) - Vector3 FinalD; // Vector from center of box to v0 at end of move - - const OBBoxClass & Box; - const TriClass & Tri; - const Vector3 & BoxMove; - const Vector3 & TriMove; - -private: - - // not implemented - BTCollisionStruct(const BTCollisionStruct &); - BTCollisionStruct & operator = (const BTCollisionStruct &); -}; - - - - - -/*********************************************************************************************** - * obbtri_collision_separation_test -- test the projected extents for separation * - * * - * Once the extents are projected onto the axis, this function contains * - * the logic that determines the allowed fraction. * - * * - * INPUT: * - * * - * OUTPUT: * - * true = objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_collision_separation_test -( - BTCollisionStruct & context, - float lp,float leb0,float leb1 -) -{ - /* - ** - compute 'EPSILON' normalized to the length of the axis - ** - If (I'm no more than 'EPSILON' embedded in the polygon) - ** - not startbad - ** - If (I'm moving towards) - ** - fraction = How far I can move before embedding (can be negative if started embedded) - ** - If (I can take entire move) - ** - accept entire move - ** - Else If (I can move more than I could have before; *negative always fails!) - ** - update fraction - ** - Else - ** - Accept entire move since I'm not moving towards the polygon - */ - float eps = 0.0f; - if (lp - leb0 <= 0.0f) { - eps = COLLISION_EPSILON * context.TestAxis.Length(); // trying to only compute epsilon if I have to - } - - if (lp - leb0 > -eps) { - context.StartBad = false; - if (leb1 - leb0 > 0.0f) { - float frac = (lp-leb0)/(leb1-leb0); - if (frac >= 1.0f) { - /* moving toward but not hitting triangle */ - context.AxisId = context.TestAxisId; - context.MaxFrac = 1.0f; - return true; - } else { - /* moving toward, hitting triangle */ - if (frac > context.MaxFrac) { - context.MaxFrac = frac; - context.AxisId = context.TestAxisId; - context.Side = context.TestSide; - context.Point = context.TestPoint; - } - } - } else { - /* moving away or not moving */ - context.AxisId = context.TestAxisId; - context.MaxFrac = 1.0f; - return true; - } - } - return false; -} - - -/*********************************************************************************************** - * obbtri_check_collision_axis -- project the obb and tri onto an arbitrary axis * - * * - * projects the box and the triangle onto the given axis and calls * - * obbtri_separation_test. return true if separation was detected * - * * - * INPUT: * - * * - * OUTPUT: * - * true = objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_collision_axis(BTCollisionStruct & context) -{ - float dist; // separation along the axis - float axismove; // size of the move along the axis. - float leb0; // initial coordinate of the leading edge of the box - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - float tmp; // temporary - - dist = Vector3::Dot_Product(context.D,context.TestAxis); - axismove = Vector3::Dot_Product(context.Move,context.TestAxis); - - // I want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axismove = -axismove; - context.TestAxis = -context.TestAxis; - context.TestSide = -1.0f; - } else { - context.TestSide = 1.0f; - } - - // compute coordinates of the leading edge of the box at t0 and t1 - leb0 = context.Box.Extent.X * WWMath::Fabs(Vector3::Dot_Product(context.TestAxis,context.A[0])) + - context.Box.Extent.Y * WWMath::Fabs(Vector3::Dot_Product(context.TestAxis,context.A[1])) + - context.Box.Extent.Z * WWMath::Fabs(Vector3::Dot_Product(context.TestAxis,context.A[2])); - leb1 = leb0 + axismove; - - // compute coordinate of "leading edge of the triangle" relative to the box center. - lp = 0; - tmp = Vector3::Dot_Product(context.E[0],context.TestAxis); if (tmp < lp) lp = tmp; - tmp = Vector3::Dot_Product(context.E[1],context.TestAxis); if (tmp < lp) lp = tmp; - lp = dist + lp; - - return obbtri_collision_separation_test(context,lp,leb0,leb1); -} - - -/*********************************************************************************************** - * obbtri_check_collision_cross_axis -- projects obb and tri onto a "cross" axis * - * * - * Assumes that the axis given is one generated from a cross product of one of the edge and * - * basis vectors. In this case, the box extent can be optimized and only two triangle verts * - * need to be checked. * - * * - * INPUT: * - * * - * OUTPUT: * - * true = objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_collision_cross_axis -( - BTCollisionStruct & context, - float dp, - int dpi, - float leb0 -) -{ - float p0; // distance from box center to vertex 0 - float axismove; // size of the move along the axis. - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - p0 = Vector3::Dot_Product(context.D,context.TestAxis); - axismove = Vector3::Dot_Product(context.Move,context.TestAxis); - - // I want the axis centered at the box, pointing towards the triangle - if (p0 < 0) { - p0 = -p0; - axismove = -axismove; - dp = -dp; - context.TestAxis = -context.TestAxis; - context.TestSide = -1.0f; - } else { - context.TestSide = 1.0f; - } - - // compute coordinates of the leading edge of the box at t1 - leb1 = leb0 + axismove; - - // compute coordinate of "leading edge of the triangle" relative to the box center. - lp = 0; context.TestPoint = 0; - if (dp < 0) { lp = dp; context.TestPoint = dpi; } - lp = p0 + lp; - - return obbtri_collision_separation_test(context,lp,leb0,leb1); -} - - -/*********************************************************************************************** - * obbtri_check_collision_basis_axis -- projects the obb and tri onto a basis axis * - * * - * Projects the box and triangle onto an axis that is assumed to be a basis * - * vector from the box. In this case, we can skip a dot-product and use the * - * corresponding extent of the box (which is passed in as leb0). * - * * - * INPUT: * - * * - * OUTPUT: * - * true = objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_collision_basis_axis -( - BTCollisionStruct & context, - float leb0, - float dp1, - float dp2 -) -{ - float dist; // separation along the axis - float axismove; // size of the move along the axis. - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(context.D,context.TestAxis); - axismove = Vector3::Dot_Product(context.Move,context.TestAxis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axismove = -axismove; - dp1 = -dp1; - dp2 = -dp2; - context.TestAxis = -context.TestAxis; - context.TestSide = -1.0f; - } else { - context.TestSide = 1.0f; - } - - // this is the "optimization", leb0 = one of the extents - leb1 = leb0 + axismove; - - // compute coordinate of "leading edge of the polygon" relative to the box center. - lp = 0; context.TestPoint = 0; - if (dp1 < lp) { lp = dp1; context.TestPoint = 1; } - if (dp2 < lp) { lp = dp2; context.TestPoint = 2; } - lp = dist + lp; - - return obbtri_collision_separation_test(context,lp,leb0,leb1); -} - - -/*********************************************************************************************** - * obbtri_check_collision_normal_axis -- project the box and tri onto the tri-normal * - * * - * Projects the box and triangle onto an axis that is assumed to be the normal * - * vector from the triangle. In this case, the triangle extents are zero. * - * * - * INPUT: * - * * - * OUTPUT: * - * true = objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_collision_normal_axis(BTCollisionStruct & context) -{ - float dist; // separation along the axis - float axismove; // size of the move along the axis. - float leb0; // initial coordinate of the leading edge of the box - float leb1; // final coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(context.D,context.TestAxis); - axismove = Vector3::Dot_Product(context.Move,context.TestAxis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - dist = -dist; - axismove = -axismove; - context.TestAxis = -context.TestAxis; - context.TestSide = -1.0f; - } else { - context.TestSide = 1.0f; - } - - leb0 = context.Box.Extent.X * WWMath::Fabs(context.AN[0]) + - context.Box.Extent.Y * WWMath::Fabs(context.AN[1]) + - context.Box.Extent.Z * WWMath::Fabs(context.AN[2]); - leb1 = leb0 + axismove; - context.TestPoint = 0; - lp = dist; // this is the "optimization", don't have to find lp - - return obbtri_collision_separation_test(context,lp,leb0,leb1); -} - -/*********************************************************************************************** - * eval_side -- returns -1,0,+1 depending on the sign of val and side * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline float eval_side(float val,int side) -{ - if (val > 0.0f) { - return side; - } else if (val < 0.0f) { - return -side; - } else { - return 0.0f; - } -} - -/*********************************************************************************************** - * obbtri_compute_contact_normal -- computes the normal of the collision * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void obbtri_compute_contact_normal -( - const BTCollisionStruct & context, - CastResultStruct * result -) -{ - switch(context.AxisId) - { - case INTERSECTION: -// WWASSERT(0); - break; - case AXIS_N: - result->Normal = -context.Side * *context.Tri.N; - break; - case AXIS_A0: - result->Normal = -context.Side * context.A[0]; - break; - case AXIS_A1: - result->Normal = -context.Side * context.A[1]; - break; - case AXIS_A2: - result->Normal = -context.Side * context.A[2]; - break; - case AXIS_A0E0: - result->Normal = -context.Side * context.AxE[0][0]; - result->Normal.Normalize(); - break; - case AXIS_A1E0: - result->Normal = -context.Side * context.AxE[1][0]; - result->Normal.Normalize(); - break; - case AXIS_A2E0: - result->Normal = -context.Side * context.AxE[2][0]; - result->Normal.Normalize(); - break; - case AXIS_A0E1: - result->Normal = -context.Side * context.AxE[0][1]; - result->Normal.Normalize(); - break; - case AXIS_A1E1: - result->Normal = -context.Side * context.AxE[1][1]; - result->Normal.Normalize(); - break; - case AXIS_A2E1: - result->Normal = -context.Side * context.AxE[2][1]; - result->Normal.Normalize(); - break; - case AXIS_A0E2: - result->Normal = -context.Side * context.AxE[0][2]; - result->Normal.Normalize(); - break; - case AXIS_A1E2: - result->Normal = -context.Side * context.AxE[1][2]; - result->Normal.Normalize(); - break; - case AXIS_A2E2: - result->Normal = -context.Side * context.AxE[2][2]; - result->Normal.Normalize(); - break; - } - WWASSERT(result->Normal.Length2() > 0.0f); -} - - -/*********************************************************************************************** - * eval_A0_point -- contact point parameters for A0xEx * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void eval_A0_point(const BTCollisionStruct & context,float * x,int edge) -{ - float yval,den; - Vector3 DxE; - - x[1] = -eval_side(context.AE[2][edge],context.Side) * context.Box.Extent[1]; - x[2] = eval_side(context.AE[1][edge],context.Side) * context.Box.Extent[2]; - if (context.Point == 0) { yval = 0.0f; } else { yval = 1.0f; } - - den = Vector3::Dot_Product(context.N,context.AxE[0][edge]); - if (WWMath::Fabs(den) > 0.0f) { - - Vector3::Cross_Product(context.FinalD,context.E[edge],&DxE); - x[0] = Vector3::Dot_Product(context.N,DxE); - if (edge == 0) { - x[0] -= context.N.Length2() * yval; - } else { - x[0] += context.N.Length2() * yval; - } - x[0] -= Vector3::Dot_Product(context.N,context.AxE[1][edge]) * x[1]; - x[0] -= Vector3::Dot_Product(context.N,context.AxE[2][edge]) * x[2]; - x[0] /= den; - - } else { - - x[0] = 0.0f; - - } -} - - -/*********************************************************************************************** - * eval_A1_point -- contact point parameters for A1xEx * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void eval_A1_point(const BTCollisionStruct & context,float * x,int edge) -{ - float yval,den; - Vector3 DxE; - - x[0] = eval_side(context.AE[2][edge],context.Side) * context.Box.Extent[0]; - x[2] = -eval_side(context.AE[0][edge],context.Side) * context.Box.Extent[2]; - if (context.Point == 0) { yval = 0.0f; } else { yval = 1.0f; } - - den = Vector3::Dot_Product(context.N,context.AxE[1][edge]); - if (WWMath::Fabs(den) > 0.0f) { - - Vector3::Cross_Product(context.FinalD,context.E[edge],&DxE); - x[1] = Vector3::Dot_Product(context.N,DxE); - if (edge == 0) { - x[1] -= context.N.Length2() * yval; - } else { - x[1] += context.N.Length2() * yval; - } - x[1] -= Vector3::Dot_Product(context.N,context.AxE[0][edge]) * x[0]; - x[1] -= Vector3::Dot_Product(context.N,context.AxE[2][edge]) * x[2]; - x[1] /= den; - - } else { - - x[1] = 0.0f; - - } -} - -/*********************************************************************************************** - * eval_A2_point -- contact point parameters for A2xEx * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void eval_A2_point(const BTCollisionStruct & context,float * x,int edge) -{ - float yval,den; - Vector3 DxE; - - x[0] = -eval_side(context.AE[1][edge],context.Side) * context.Box.Extent[0]; - x[1] = eval_side(context.AE[0][edge],context.Side) * context.Box.Extent[1]; - if (context.Point == 0) { yval = 0.0f; } else { yval = 1.0f; } - - den = Vector3::Dot_Product(context.N,context.AxE[2][edge]); - if (WWMath::Fabs(den) > 0.0f) { - - Vector3::Cross_Product(context.FinalD,context.E[edge],&DxE); - x[2] = Vector3::Dot_Product(context.N,DxE); - if (edge == 0) { - x[2] -= context.N.Length2() * yval; - } else { - x[2] += context.N.Length2() * yval; - } - x[2] -= Vector3::Dot_Product(context.N,context.AxE[0][edge]) * x[0]; - x[2] -= Vector3::Dot_Product(context.N,context.AxE[1][edge]) * x[1]; - x[2] /= den; - - } else { - - x[2] = 0.0f; - - } -} - - -/*********************************************************************************************** - * obbtri_compute_contact_point -- compute the contact point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -static inline void obbtri_compute_contact_point -( - BTCollisionStruct & context, - CastResultStruct * result -) -{ - int i; - float x[3]; - - if (context.AxisId >= AXIS_A0E0) { - Vector3 newc = context.Box.Center + result->Fraction * context.BoxMove; - Vector3 newv0 = *context.Tri.V[0] + result->Fraction * context.TriMove; - context.FinalD = newv0 - newc; - } - - switch (context.AxisId) - { - - case INTERSECTION: - WWASSERT(0); - return; - - case AXIS_N: // part of the box is touching the face of the triangle - - for (i = 0; i < 3; i++) { - x[i] = eval_side(context.AN[i],context.Side) * context.Box.Extent[i]; - } - break; - - case AXIS_A0: // part of the triangle is touching a face of the box - case AXIS_A1: - case AXIS_A2: - - if (context.Point == 0) { - result->ContactPoint = *context.Tri.V[0]; - } else if (context.Point == 1) { - result->ContactPoint = *context.Tri.V[1]; - } else { - result->ContactPoint = *context.Tri.V[2]; - } - Vector3::Add(result->ContactPoint,result->Fraction * context.TriMove,&(result->ContactPoint)); - return; - - case AXIS_A0E0: // one of the x-aligned edges of the box is contacting edge0 - eval_A0_point(context,x,0); - break; - - case AXIS_A0E1: // one of the x-aligned edges of the box is contacting edge1 - eval_A0_point(context,x,1); - break; - - case AXIS_A0E2: // one of the x-aligned edges of the box is contacting edge2 - eval_A0_point(context,x,2); - break; - - case AXIS_A1E0: // one of the y-aligned edges of the box is contacting edge0 - eval_A1_point(context,x,0); - break; - - case AXIS_A1E1: // one of the y-aligned edges of the box is contacting edge1 - eval_A1_point(context,x,1); - break; - - case AXIS_A1E2: // one of the y-aligned edges of the box is contacting edge2 - eval_A1_point(context,x,2); - break; - - case AXIS_A2E0: // one of the z-aligned edges of the box is contacting edge0 - eval_A2_point(context,x,0); - break; - - case AXIS_A2E1: // one of the z-aligned edges of the box is contacting edge1 - eval_A2_point(context,x,1); - break; - - case AXIS_A2E2: // one of the z-aligned edges of the box is contacting edge3 - eval_A2_point(context,x,2); - break; - - } - - /* - ** In certain circumstances, the x's computed above are outside the size of - ** the box. I have tracked at least one of these cases to a situation where the - ** separating axis is the triangle normal but one of the AxE axes also lines up - ** with the normal. In this case, the Normal was 0,0,25 and the A0xE0 axis - ** was 0,0,5. When the fraction was calculated for both of these, they were - ** the same up to the six decimal places that MSVC will show me in the debugger. - ** However, the fraction computed for the 0,0,5 axis was larger by some very small - ** amount. This causes it to be used as the "separating axis". Looks like floating - ** point roundoff error to me. The problem is that since the axis was perpendicular - ** to the triangle, the "nearest-point" logic chose V0 which resulted in the - ** calculation for x[0] being way off. The equations for finding the contact point - ** in the AxE axis case assume that the axis is not normal to the triangle since - ** that should be handled in the simpler routine for the N separating axis... - ** Since I am at a loss for how to deal with this problem, I'm going to clamp all - ** of the x's to be within the box here... - */ - if (x[0] > context.Box.Extent.X) { - x[0] = context.Box.Extent.X; - } else if (x[0] < -context.Box.Extent.X) { - x[0] = -context.Box.Extent.X; - } - - if (x[1] > context.Box.Extent.Y) { - x[1] = context.Box.Extent.Y; - } else if (x[1] < -context.Box.Extent.Y) { - x[1] = -context.Box.Extent.Y; - } - - if (x[2] > context.Box.Extent.Z) { - x[2] = context.Box.Extent.Z; - } else if (x[2] < -context.Box.Extent.Z) { - x[2] = -context.Box.Extent.Z; - } - - /* - ** Now, compute the point - */ - result->ContactPoint.X = context.Box.Center.X + - x[0]*context.A[0].X + - x[1]*context.A[1].X + - x[2]*context.A[2].X; - - result->ContactPoint.Y = context.Box.Center.Y + - x[0]*context.A[0].Y + - x[1]*context.A[1].Y + - x[2]*context.A[2].Y; - - result->ContactPoint.Z = context.Box.Center.Z + - x[0]*context.A[0].Z + - x[1]*context.A[1].Z + - x[2]*context.A[2].Z; - - Vector3::Add(result->ContactPoint,result->Fraction * context.BoxMove,&(result->ContactPoint)); -} - - - -/*********************************************************************************************** - * CollisionMath::Collide -- collide an obbox into a triangle * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/8/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Collide -( - const OBBoxClass & box, - const Vector3 & move, - const TriClass & tri, - const Vector3 & trimove, - CastResultStruct * result -) -{ - TRACK_COLLISION_OBBOX_TRI; - float dp,leb0; - BTCollisionStruct context(box,move,tri,trimove); - - /* - ** AXIS_N - */ - context.TestAxis = context.N; - context.TestAxisId = AXIS_N; - context.AN[0] = Vector3::Dot_Product(context.A[0],context.N); - context.AN[1] = Vector3::Dot_Product(context.A[1],context.N); - context.AN[2] = Vector3::Dot_Product(context.A[2],context.N); - if (obbtri_check_collision_normal_axis(context)) goto exit; - - /* - ** AXIS_A0 - */ - context.TestAxis = context.A[0]; - context.TestAxisId = AXIS_A0; - context.AE[0][0] = Vector3::Dot_Product(context.A[0],context.E[0]); - context.AE[0][1] = Vector3::Dot_Product(context.A[0],context.E[1]); - if (obbtri_check_collision_basis_axis(context,box.Extent.X,context.AE[0][0],context.AE[0][1])) goto exit; - - /* - ** AXIS_A1 - */ - context.TestAxis = context.A[1]; - context.TestAxisId = AXIS_A1; - context.AE[1][0] = Vector3::Dot_Product(context.A[1],context.E[0]); - context.AE[1][1] = Vector3::Dot_Product(context.A[1],context.E[1]); - if (obbtri_check_collision_basis_axis(context,box.Extent.Y,context.AE[1][0],context.AE[1][1])) goto exit; - - /* - ** AXIS_A2 - */ - context.TestAxis = context.A[2]; - context.TestAxisId = AXIS_A2; - context.AE[2][0] = Vector3::Dot_Product(context.A[2],context.E[0]); - context.AE[2][1] = Vector3::Dot_Product(context.A[2],context.E[1]); - if (obbtri_check_collision_basis_axis(context,box.Extent.Z,context.AE[2][0],context.AE[2][1])) goto exit; - - /* - ** AXIS_A0xE0 - */ - Vector3::Cross_Product(context.A[0],context.E[0],&context.AxE[0][0]); - context.TestAxis = context.AxE[0][0]; - context.TestAxisId = AXIS_A0E0; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = context.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(context.AE[2][0]) + box.Extent[2]*WWMath::Fabs(context.AE[1][0]); - if (obbtri_check_collision_cross_axis(context,dp,2,leb0)) goto exit; - } - - /* - ** AXIS_A0xE1 - */ - Vector3::Cross_Product(context.A[0],context.E[1],&context.AxE[0][1]); - context.TestAxis = context.AxE[0][1]; - context.TestAxisId = AXIS_A0E1; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(context.AE[2][1]) + box.Extent[2]*WWMath::Fabs(context.AE[1][1]); - if (obbtri_check_collision_cross_axis(context,dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A0xE2 - */ - Vector3::Cross_Product(context.A[0],context.E[2],&context.AxE[0][2]); - context.TestAxis = context.AxE[0][2]; - context.TestAxisId = AXIS_A0E2; - context.AE[1][2] = Vector3::Dot_Product(context.A[1],context.E[2]); - context.AE[2][2] = Vector3::Dot_Product(context.A[2],context.E[2]); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(context.AE[2][2]) + box.Extent[2]*WWMath::Fabs(context.AE[1][2]); - if (obbtri_check_collision_cross_axis(context,dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A1xE0 - */ - Vector3::Cross_Product(context.A[1],context.E[0],&context.AxE[1][0]); - context.TestAxis = context.AxE[1][0]; - context.TestAxisId = AXIS_A1E0; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = context.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[2][0]) + box.Extent[2]*WWMath::Fabs(context.AE[0][0]); - if (obbtri_check_collision_cross_axis(context,dp,2,leb0)) goto exit; - } - - /* - ** AXIS_A1xE1 - */ - Vector3::Cross_Product(context.A[1],context.E[1],&context.AxE[1][1]); - context.TestAxis = context.AxE[1][1]; - context.TestAxisId = AXIS_A1E1; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[2][1]) + box.Extent[2]*WWMath::Fabs(context.AE[0][1]); - if (obbtri_check_collision_cross_axis(context,dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A1xE2 - */ - Vector3::Cross_Product(context.A[1],context.E[2],&context.AxE[1][2]); - context.TestAxis = context.AxE[1][2]; - context.TestAxisId = AXIS_A1E2; - context.AE[0][2] = Vector3::Dot_Product(context.A[0],context.E[2]); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[2][2]) + box.Extent[2]*WWMath::Fabs(context.AE[0][2]); - if (obbtri_check_collision_cross_axis(context,dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A2xE0 - */ - Vector3::Cross_Product(context.A[2],context.E[0],&context.AxE[2][0]); - context.TestAxis = context.AxE[2][0]; - context.TestAxisId = AXIS_A2E0; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = context.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[1][0]) + box.Extent[1]*WWMath::Fabs(context.AE[0][0]); - if (obbtri_check_collision_cross_axis(context,dp,2,leb0)) goto exit; - } - - /* - ** AXIS_A2xE1 - */ - Vector3::Cross_Product(context.A[2],context.E[1],&context.AxE[2][1]); - context.TestAxis = context.AxE[2][1]; - context.TestAxisId = AXIS_A2E1; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[1][1]) + box.Extent[1]*WWMath::Fabs(context.AE[0][1]); - if (obbtri_check_collision_cross_axis(context,dp,1,leb0)) goto exit; - } - - /* - ** AXIS_A2xE2 - */ - Vector3::Cross_Product(context.A[2],context.E[2],&context.AxE[2][2]); - context.TestAxis = context.AxE[2][2]; - context.TestAxisId = AXIS_A2E2; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[1][2]) + box.Extent[1]*WWMath::Fabs(context.AE[0][2]); - if (obbtri_check_collision_cross_axis(context,dp,1,leb0)) goto exit; - } - - /* - ** Last ditch effort, check an axis based on the move vector - */ - if (!context.StartBad) { - context.TestPoint = context.Point; - context.TestAxisId = context.AxisId; - - Vector3::Cross_Product(context.Move,context.A[0],&context.TestAxis); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - if (obbtri_check_collision_axis(context)) goto exit; - } - Vector3::Cross_Product(context.Move,context.A[1],&context.TestAxis); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - if (obbtri_check_collision_axis(context)) goto exit; - } - Vector3::Cross_Product(context.Move,context.A[2],&context.TestAxis); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - if (obbtri_check_collision_axis(context)) goto exit; - } - } - -exit: - -#pragma message ("(gth) disabling an assert in obb->tri collision, investigate later\n") -#if 0 - WWASSERT((context.AxisId != INTERSECTION) || (context.StartBad)); -#else - if (context.AxisId == INTERSECTION) { - context.StartBad = true; - } -#endif - - /* - ** If the triangle and box are intersecting before the move, return that - ** result. - */ - if (context.StartBad) { - result->StartBad = true; - result->Fraction = 0.0f; - result->Normal = *tri.N; - TRACK_COLLISION_OBBOX_TRI_HIT; - return true; - } - - /* - ** If the fraction allowed is basically equal to the fraction allowed by - ** another polygon, try to pick the polygon which is least "edge-on" to the - ** move. - */ - if (context.MaxFrac < 0.0f) { - context.MaxFrac = 0.0f; - } - - if ((context.MaxFrac < 1.0f) && (context.MaxFrac <= result->Fraction)) { - - if ( (WWMath::Fabs(context.MaxFrac - result->Fraction) > WWMATH_EPSILON) || - (Vector3::Dot_Product(*(tri.N),move) < Vector3::Dot_Product(result->Normal,move)) ) - { - obbtri_compute_contact_normal(context,result); - } - - result->Fraction = context.MaxFrac; - - if (result->ComputeContactPoint) { - obbtri_compute_contact_point(context,result); - } - TRACK_COLLISION_OBBOX_TRI_HIT; - return true; - } - - return false; -} - - -/*********************************************************************************************** - - OBBox-Triangle Intersection - - The following code implements a simple boolean intersection check. It uses the same - algorithm as the collision function but can avoid some of the calculations. For a very - simple implementation of this algorithm, see Oriented_Box_Intersects_Tri in obbox.h - -***********************************************************************************************/ - -/** -** BTIntersectStruct -** Scratchpad variables for the OBBox-Triangle intersection functions. One instance -** of this structure will be used for all of the local variables and its pointer will be -** handed of to various inline functions for the axis tests. -** Note that much of the code needs the un-normalized triangle normal. For this reason, -** I have to compute N rather than copying it from the triangle. (commenting this to -** avoid re-generating a difficult to find bug that I had) -*/ -struct BTIntersectStruct -{ - BTIntersectStruct(const OBBoxClass &box,const TriClass &tri) : - Box(box), - Tri(tri) - { - Vector3::Subtract(*tri.V[0],box.Center,&D); // vector from center of box to vertex 0 - Vector3::Subtract(*tri.V[1],*tri.V[0],&E[0]); - Vector3::Subtract(*tri.V[2],*tri.V[0],&E[1]); - Vector3::Subtract(E[1],E[0],&E[2]); - - A[0].Set(box.Basis[0][0],box.Basis[1][0],box.Basis[2][0]); - A[1].Set(box.Basis[0][1],box.Basis[1][1],box.Basis[2][1]); - A[2].Set(box.Basis[0][2],box.Basis[1][2],box.Basis[2][2]); - - Vector3::Cross_Product(E[0],E[1],&N); - } - - Vector3 D; // Vector from the center of the box to v0 - float AE[3][3]; // Dot products of the Basis vectors and edges - float AN[3]; // Dot products of the Basis vectors and the normal - Vector3 AxE[3][3]; // Cross produts of the Basis vectors and edges - - Vector3 A[3]; // basis vectors for the box - Vector3 E[3]; // edge vectors for the triangle - Vector3 N; // normal (NOT normalized!!!) - - Vector3 TestAxis; // separating axis currently being tested - - const OBBoxClass & Box; - const TriClass & Tri; - -private: - - // not implemented - BTIntersectStruct(const BTIntersectStruct &); - BTIntersectStruct & operator = (const BTIntersectStruct &); -}; - - -/*********************************************************************************************** - * obbtri_intersection_separation_test -- test the projected extents for intersection * - * * - * Once the extents are projected onto the axis, this function contains * - * the logic that determines whether the box and triangle intersect. * - * * - * INPUT: * - * context - the BTIntersectStruct containing the data for this intersection test * - * lp - the leading edge of the polygon projected onto the axis * - * leb0 - the leading edge of the box projected onto the axis * - * * - * OUTPUT: * - * true = objects are separated * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/3/2000 gth : Created. * - *=============================================================================================*/ -static inline bool obbtri_intersection_separation_test -( - BTIntersectStruct & context, - float lp, - float leb0 -) -{ - /* - ** Only compute the normalized epsilon if we need to. - ** - compute 'EPSILON' normalized to the length of the axis - ** - If (I'm no more than 'EPSILON' embedded in the polygon) then the box and tri are separated - */ - float eps = 0.0f; - if (lp - leb0 <= 0.0f) { - eps = COLLISION_EPSILON * context.TestAxis.Length(); // trying to only compute epsilon if I have to - } - - return (lp - leb0 > -eps); -} - - -/*********************************************************************************************** - * obbtri_check_intersection_cross_axis -- intersection check for a "cross-product" axis * - * * - * axis being checked is a cross product between a triangle edge and a box basis vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * true = the objects are SEPARATED * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_intersection_cross_axis -( - BTIntersectStruct & context, - float dp, - float leb0 -) -{ - float p0; // distance from box center to vertex 0 - float lp; // leading edge of the polygon. - - p0 = Vector3::Dot_Product(context.D,context.TestAxis); - - // I want the axis centered at the box, pointing towards the triangle - if (p0 < 0) { - context.TestAxis = -context.TestAxis; - p0 = -p0; - dp = -dp; - } - - // compute coordinate of "leading edge of the triangle" relative to the box center. - lp = 0; - if (dp < 0) { lp = dp; } - lp = p0 + lp; - - return obbtri_intersection_separation_test(context,lp,leb0); -} - - -/*********************************************************************************************** - * obbtri_check_intersection_basis_axis -- intersection check for a basis axis * - * * - * axis being checked is one of the basis vectors for the box * - * * - * INPUT: * - * * - * OUTPUT: * - * true = the objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_intersection_basis_axis -( - BTIntersectStruct & context, - float leb0, - float dp1, - float dp2 -) -{ - float dist; // separation along the axis - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(context.D,context.TestAxis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - context.TestAxis = -context.TestAxis; - dist = -dist; - dp1 = -dp1; - dp2 = -dp2; - } - - // compute coordinate of "leading edge of the polygon" relative to the box center. - lp = 0; - if (dp1 < lp) { lp = dp1; } - if (dp2 < lp) { lp = dp2; } - lp = dist + lp; - - return obbtri_intersection_separation_test(context,lp,leb0); -} - - -/*********************************************************************************************** - * obbtri_check_intersection_normal_axis -- intersection check for the triangle normal * - * * - * axis being checked is the triangle's normal * - * * - * INPUT: * - * * - * OUTPUT: * - * true = the objects are SEPARATED * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -static inline bool obbtri_check_intersection_normal_axis -( - BTIntersectStruct & context -) -{ - float dist; // separation along the axis - float leb0; // initial coordinate of the leading edge of the box - float lp; // leading edge of the polygon. - - dist = Vector3::Dot_Product(context.D,context.TestAxis); - - // we want the axis centered at the box, pointing towards the triangle - if (dist < 0) { - context.TestAxis = -context.TestAxis; - dist = -dist; - } - - leb0 = context.Box.Extent.X * WWMath::Fabs(context.AN[0]) + - context.Box.Extent.Y * WWMath::Fabs(context.AN[1]) + - context.Box.Extent.Z * WWMath::Fabs(context.AN[2]); - lp = dist; // this is the "optimization", don't have to find lp - - return obbtri_intersection_separation_test(context,lp,leb0); -} - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- Intersection check for an OBBox and a triangle * - * * - * INPUT: * - * box - obbox to be tested * - * tri - triangle to be tested * - * * - * OUTPUT: * - * true = objects INTERSECT * - * * - * WARNINGS: * - * note that the other inline functions are "quick-reject" functions which return true when * - * the objects are separated. * - * * - * HISTORY: * - * 5/4/99 GTH : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const OBBoxClass & box,const TriClass & tri) -{ - float dp,leb0; - BTIntersectStruct context(box,tri); - - /* - ** AXIS_N - */ - context.TestAxis = context.N; - context.AN[0] = Vector3::Dot_Product(context.A[0],context.N); - context.AN[1] = Vector3::Dot_Product(context.A[1],context.N); - context.AN[2] = Vector3::Dot_Product(context.A[2],context.N); - if (obbtri_check_intersection_normal_axis(context)) return false; - - /* - ** AXIS_A0 - */ - context.TestAxis = context.A[0]; - context.AE[0][0] = Vector3::Dot_Product(context.A[0],context.E[0]); - context.AE[0][1] = Vector3::Dot_Product(context.A[0],context.E[1]); - if (obbtri_check_intersection_basis_axis(context,box.Extent.X,context.AE[0][0],context.AE[0][1])) return false; - - /* - ** AXIS_A1 - */ - context.TestAxis = context.A[1]; - context.AE[1][0] = Vector3::Dot_Product(context.A[1],context.E[0]); - context.AE[1][1] = Vector3::Dot_Product(context.A[1],context.E[1]); - if (obbtri_check_intersection_basis_axis(context,box.Extent.Y,context.AE[1][0],context.AE[1][1])) return false; - - /* - ** AXIS_A2 - */ - context.TestAxis = context.A[2]; - context.AE[2][0] = Vector3::Dot_Product(context.A[2],context.E[0]); - context.AE[2][1] = Vector3::Dot_Product(context.A[2],context.E[1]); - if (obbtri_check_intersection_basis_axis(context,box.Extent.Z,context.AE[2][0],context.AE[2][1])) return false; - - /* - ** AXIS_A0xE0 - */ - Vector3::Cross_Product(context.A[0],context.E[0],&context.AxE[0][0]); - context.TestAxis = context.AxE[0][0]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = context.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(context.AE[2][0]) + box.Extent[2]*WWMath::Fabs(context.AE[1][0]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A0xE1 - */ - Vector3::Cross_Product(context.A[0],context.E[1],&context.AxE[0][1]); - context.TestAxis = context.AxE[0][1]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(context.AE[2][1]) + box.Extent[2]*WWMath::Fabs(context.AE[1][1]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A0xE2 - */ - Vector3::Cross_Product(context.A[0],context.E[2],&context.AxE[0][2]); - context.TestAxis = context.AxE[0][2]; - context.AE[1][2] = Vector3::Dot_Product(context.A[1],context.E[2]); - context.AE[2][2] = Vector3::Dot_Product(context.A[2],context.E[2]); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[0]; - leb0 = box.Extent[1]*WWMath::Fabs(context.AE[2][2]) + box.Extent[2]*WWMath::Fabs(context.AE[1][2]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A1xE0 - */ - Vector3::Cross_Product(context.A[1],context.E[0],&context.AxE[1][0]); - context.TestAxis = context.AxE[1][0]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = context.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[2][0]) + box.Extent[2]*WWMath::Fabs(context.AE[0][0]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A1xE1 - */ - Vector3::Cross_Product(context.A[1],context.E[1],&context.AxE[1][1]); - context.TestAxis = context.AxE[1][1]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[2][1]) + box.Extent[2]*WWMath::Fabs(context.AE[0][1]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A1xE2 - */ - Vector3::Cross_Product(context.A[1],context.E[2],&context.AxE[1][2]); - context.TestAxis = context.AxE[1][2]; - context.AE[0][2] = Vector3::Dot_Product(context.A[0],context.E[2]); - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[1]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[2][2]) + box.Extent[2]*WWMath::Fabs(context.AE[0][2]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A2xE0 - */ - Vector3::Cross_Product(context.A[2],context.E[0],&context.AxE[2][0]); - context.TestAxis = context.AxE[2][0]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = context.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[1][0]) + box.Extent[1]*WWMath::Fabs(context.AE[0][0]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A2xE1 - */ - Vector3::Cross_Product(context.A[2],context.E[1],&context.AxE[2][1]); - context.TestAxis = context.AxE[2][1]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[1][1]) + box.Extent[1]*WWMath::Fabs(context.AE[0][1]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - /* - ** AXIS_A2xE2 - */ - Vector3::Cross_Product(context.A[2],context.E[2],&context.AxE[2][2]); - context.TestAxis = context.AxE[2][2]; - if (context.TestAxis.Length2() > AXISLEN_EPSILON2) { - dp = -context.AN[2]; - leb0 = box.Extent[0]*WWMath::Fabs(context.AE[1][2]) + box.Extent[1]*WWMath::Fabs(context.AE[0][2]); - if (obbtri_check_intersection_cross_axis(context,dp,leb0)) return false; - } - - return true; -} - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathplane.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathplane.cpp deleted file mode 100644 index f0822cccd9..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathplane.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathplane.cpp $* - * * - * Org Author:: Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 10 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "colmathplane.h" -#include "aaplane.h" -#include "plane.h" -#include "lineseg.h" -#include "tri.h" -#include "sphere.h" -#include "aabox.h" -#include "obbox.h" -#include "wwdebug.h" - - - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AAPlaneClass & plane,const Vector3 & point) -{ - float delta = point[plane.Normal] - plane.Dist; - if (delta > COINCIDENCE_EPSILON) { - return POS; - } - if (delta < -COINCIDENCE_EPSILON) { - return NEG; - } - return ON; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AAPlaneClass & plane,const LineSegClass & line) -{ - int mask = 0; - mask |= CollisionMath::Overlap_Test(plane,line.Get_P0()); - mask |= CollisionMath::Overlap_Test(plane,line.Get_P1()); - return eval_overlap_mask(mask); -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AAPlaneClass & plane,const TriClass & tri) -{ - int mask = 0; - mask |= CollisionMath::Overlap_Test(plane,*tri.V[0]); - mask |= CollisionMath::Overlap_Test(plane,*tri.V[1]); - mask |= CollisionMath::Overlap_Test(plane,*tri.V[2]); - return eval_overlap_mask(mask); -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AAPlaneClass & plane,const SphereClass & sphere) -{ - float delta = sphere.Center[plane.Normal] - plane.Dist; - if (delta > sphere.Radius) { - return POS; - } - if (delta < sphere.Radius) { - return NEG; - } - return BOTH; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AAPlaneClass & plane,const AABoxClass & box) -{ - float delta; - int mask = 0; - - // check the 'min' side of the box - delta = (box.Center[plane.Normal] - box.Extent[plane.Normal]) - plane.Dist; - if (delta > WWMATH_EPSILON) { - mask |= POS; - } else if (delta < -WWMATH_EPSILON) { - mask |= NEG; - } else { - mask |= ON; - } - - // check the 'max' side of the box - delta = (box.Center[plane.Normal] + box.Extent[plane.Normal]) - plane.Dist; - if (delta > WWMATH_EPSILON) { - mask |= POS; - } else if (delta < -WWMATH_EPSILON) { - mask |= NEG; - } else { - mask |= ON; - } - - return eval_overlap_mask(mask); -} - - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const AAPlaneClass & /*plane*/,const OBBoxClass & /*box*/) -{ -// TODO - WWASSERT(0); - return POS; -} - - -// Plane functions. Where is operand B with respect to the plane - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const PlaneClass & plane,const LineSegClass & line) -{ - int mask = 0; - mask |= CollisionMath::Overlap_Test(plane,line.Get_P0()); - mask |= CollisionMath::Overlap_Test(plane,line.Get_P1()); - return eval_overlap_mask(mask); -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const PlaneClass & plane,const TriClass & tri) -{ - int mask = 0; - mask |= CollisionMath::Overlap_Test(plane,*tri.V[0]); - mask |= CollisionMath::Overlap_Test(plane,*tri.V[1]); - mask |= CollisionMath::Overlap_Test(plane,*tri.V[2]); - return eval_overlap_mask(mask); -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const PlaneClass & plane,const SphereClass & sphere) -{ - float dist = Vector3::Dot_Product(sphere.Center,plane.N) - plane.D; - if (dist > sphere.Radius) { - return POS; - } - if (dist < -sphere.Radius) { - return NEG; - } - return BOTH; -} - -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const PlaneClass & plane,const OBBoxClass & box) -{ - // rotate the plane normal into box coordinates - Vector3 local_normal; - Vector3 posfarpt; - Vector3 negfarpt; - Matrix3x3::Transpose_Rotate_Vector(box.Basis,plane.N,&local_normal); - - get_far_extent(local_normal,box.Extent,&posfarpt); - - // transform the two extreme box coordinates into world space - Matrix3x3::Rotate_Vector(box.Basis,posfarpt,&posfarpt); - negfarpt = -posfarpt; - posfarpt += box.Center; - negfarpt += box.Center; - - // overlap test - if (Overlap_Test(plane,negfarpt) == POS) { - return POS; - } - if (Overlap_Test(plane,posfarpt) == NEG) { - return NEG; - } - return BOTH; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathplane.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathplane.h deleted file mode 100644 index 2c59e3c162..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathplane.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathplane.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/29/00 4:42p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * get_far_extent -- gets extents of a box projected onto an axis * - * CollisionMath::Overlap_Test -- Tests overlap between a plane and a point * - * CollisionMath::Overlap_Test -- Tests overlap between a plane and an AABox * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef COLMATHPLANE_H -#define COLMATHPLANE_H - -#include "always.h" -#include "plane.h" -#include "aabox.h" - -/* -** Inline collision functions dealing with planes -** This module is meant to be included only in .CPP files after you include colmath.h -** It is not automatically included in order to reduce file dependencies... -*/ - -/*********************************************************************************************** - * get_far_extent -- gets extents of a box projected onto an axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/29/2000 gth : Created. * - *=============================================================================================*/ -inline void get_far_extent(const Vector3 & normal,const Vector3 & extent,Vector3 * posfarpt) -{ - if (WWMath::Fast_Is_Float_Positive(normal.X)) { - posfarpt->X = extent.X; - } else { - posfarpt->X = -extent.X; - } - - if (WWMath::Fast_Is_Float_Positive(normal.Y)) { - posfarpt->Y = extent.Y; - } else { - posfarpt->Y = -extent.Y; - } - - if (WWMath::Fast_Is_Float_Positive(normal.Z)) { - posfarpt->Z = extent.Z; - } else { - posfarpt->Z = -extent.Z; - } -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Tests overlap between a plane and a point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/29/2000 gth : Created. * - *=============================================================================================*/ -inline -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const PlaneClass & plane,const Vector3 & point) -{ - float delta = Vector3::Dot_Product(point,plane.N) - plane.D; - if (delta > COINCIDENCE_EPSILON) { - return POS; - } - if (delta < -COINCIDENCE_EPSILON) { - return NEG; - } - return ON; -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Tests overlap between a plane and an AABox * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/29/2000 gth : Created. * - *=============================================================================================*/ -inline -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const PlaneClass & plane,const AABoxClass & box) -{ - // First, we determine the the near and far points of the box in the - // direction of the plane normal - Vector3 posfarpt; - Vector3 negfarpt; - - get_far_extent(plane.N,box.Extent,&posfarpt); - - negfarpt = -posfarpt; - posfarpt += box.Center; - negfarpt += box.Center; - if (Overlap_Test(plane,negfarpt) == POS) { - return POS; - } - if (Overlap_Test(plane,posfarpt) == NEG) { - return NEG; - } - return BOTH; -} - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp deleted file mode 100644 index 6a5f861a50..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/colmathsphere.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/colmathsphere.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 4/25/01 2:05p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CollisionMath::Intersection_Test -- Sphere - AAbox intersection * - * CollisionMath::Intersection_Test -- Sphere - OBBox intersection * - * CollisionMath::Overlap_Test -- Sphere - Point overlap test * - * CollisionMath::Overlap_Test -- sphere line overlap test * - * CollisionMath::Overlap_Test -- sphere triangle overlap test * - * CollisionMath::Overlap_Test -- Sphere - Sphere overlap test * - * CollisionMath::Overlap_Test -- Sphere - AABox overlap test * - * CollisionMath::Overlap_Test -- Sphere - OBBox overlap test * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colmath.h" -#include "aaplane.h" -#include "plane.h" -#include "lineseg.h" -#include "tri.h" -#include "sphere.h" -#include "aabox.h" -#include "obbox.h" -#include "wwdebug.h" - - -// Sphere Intersection fucntions. Does the sphere intersect the passed in object -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- Sphere - AAbox intersection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const SphereClass & sphere,const AABoxClass & box) -{ - /* - ** Simple but slightly inaccurate test, expand the box by the sphere's radius, then - ** test whether the sphere is contained in that new box. This is actually testing - ** against a cube which encloses the sphere... - */ - Vector3 dc = box.Center - sphere.Center; - if (WWMath::Fabs(dc.X) < box.Extent.X + sphere.Radius) return false; - if (WWMath::Fabs(dc.Y) < box.Extent.Y + sphere.Radius) return false; - if (WWMath::Fabs(dc.Z) < box.Extent.Z + sphere.Radius) return false; - return true; -} - - -/*********************************************************************************************** - * CollisionMath::Intersection_Test -- Sphere - OBBox intersection * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -bool CollisionMath::Intersection_Test(const SphereClass & sphere,const OBBoxClass & box) -{ - /* - ** Compute the sphere's position in the box's coordinate system - */ - Matrix3D tm(box.Basis,box.Center); - Vector3 box_rel_center; - Matrix3D::Inverse_Transform_Vector(tm,sphere.Center,&box_rel_center); - - if (box.Extent.X < WWMath::Fabs(box_rel_center.X)) return false; - if (box.Extent.Y < WWMath::Fabs(box_rel_center.Y)) return false; - if (box.Extent.Z < WWMath::Fabs(box_rel_center.Z)) return false; - - return true; -} - -// Sphere Overlap functions. Where is operand B with respect to the sphere -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Sphere - Point overlap test * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const SphereClass & sphere,const Vector3 & point) -{ - float r2 = (point - sphere.Center).Length2(); - if (r2 < sphere.Radius * sphere.Radius - COINCIDENCE_EPSILON) { - return NEG; - } - if (r2 > sphere.Radius * sphere.Radius + COINCIDENCE_EPSILON) { - return POS; - } - return ON; -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- sphere line overlap test * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const SphereClass & /*sphere*/,const LineSegClass & /*line*/) -{ - WWASSERT(0); //TODO - return POS; -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- sphere triangle overlap test * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const SphereClass & /*sphere*/,const TriClass & /*tri*/) -{ - WWASSERT(0); //TODO - return POS; -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Sphere - Sphere overlap test * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const SphereClass & sphere,const SphereClass & sphere2) -{ - CollisionMath::OverlapType retval = OUTSIDE; - - float radius = sphere.Radius + sphere2.Radius; - float dist2 = (sphere2.Center - sphere.Center).Length2(); - - if (dist2 == 0 && sphere.Radius == sphere2.Radius) { - retval = OVERLAPPED; - } else if (dist2 <= radius * radius - COINCIDENCE_EPSILON) { - retval = INSIDE; - } - - return retval; -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Sphere - AABox overlap test * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const SphereClass & sphere,const AABoxClass & aabox) -{ - // TODO: overlap function that detects containment? - return ( Intersection_Test(sphere,aabox) ? BOTH : POS ); -} - - -/*********************************************************************************************** - * CollisionMath::Overlap_Test -- Sphere - OBBox overlap test * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/25/2001 gth : Created. * - *=============================================================================================*/ -CollisionMath::OverlapType -CollisionMath::Overlap_Test(const SphereClass & sphere,const OBBoxClass & obbox) -{ - // TODO: overlap function that detects containment? - return ( Intersection_Test(sphere,obbox) ? BOTH : POS ); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/cullsys.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/cullsys.cpp deleted file mode 100644 index aca4729f79..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/cullsys.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/cullsys.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 10/16/00 11:42a $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "cullsys.h" -#include "wwdebug.h" -#include "wwprofile.h" - - -/************************************************************************* -** -** CullableClass Implementation -** -*************************************************************************/ -CullableClass::CullableClass(void) : - CullLink(NULL), - NextCollected(NULL) -{ - CullBox.Init(Vector3(0,0,0),Vector3(1,1,1)); -} - -CullableClass::~CullableClass(void) -{ - // the cull system that contains us is responsible for any culling link - // so we better be out of it and it should have cleared our pointer before - // we are deleted. - WWASSERT(CullLink == NULL); -} - -void CullableClass::Set_Cull_Box(const AABoxClass & box,bool just_loaded) -{ - CullBox = box; - - WWPROFILE("Cullable::Set_Cull_Box"); - - // Just_loaded flag allows us to update the box without notifying the - // culling system. Use this when you've saved and loaded the linkage - // so you know you're in the right node of the culling system... - if (!just_loaded) { - CullSystemClass * sys = Get_Culling_System(); - if (sys != NULL) { - sys->Update_Culling(this); - } - } -} - -void CullableClass::Set_Culling_System(CullSystemClass * sys) -{ - if (CullLink) { - CullLink->Set_Culling_System(sys); - } -} - -CullSystemClass * CullableClass::Get_Culling_System(void) const -{ - if (CullLink) { - return CullLink->Get_Culling_System(); - } - return NULL; -} - - -/************************************************************************* -** -** CullSystemClass Implementation -** -** The base CullSystemClass mainly contains code for maintaining the -** current collection list and iterating through it. -** -*************************************************************************/ -CullSystemClass::CullSystemClass(void) : - CollectionHead(NULL) -{ -} - -CullSystemClass::~CullSystemClass(void) -{ -} - -// NOTE: THE Get_() functions currently are the same as the Peek_() functions (e.g., they do not -// add a Ref). This is wrong and will be fixed. -CullableClass * CullSystemClass::Get_First_Collected_Object_Internal(void) -{ - return CollectionHead; -} - -CullableClass * CullSystemClass::Get_Next_Collected_Object_Internal(CullableClass * obj) -{ - if (obj != NULL) { - return obj->NextCollected; - } - return NULL; -} - -CullableClass * CullSystemClass::Peek_First_Collected_Object_Internal(void) -{ - return CollectionHead; -} - -CullableClass * CullSystemClass::Peek_Next_Collected_Object_Internal(CullableClass * obj) -{ - if (obj != NULL) { - return obj->NextCollected; - } - return NULL; -} - -void CullSystemClass::Reset_Collection(void) -{ - CollectionHead = NULL; -} - -void CullSystemClass::Add_To_Collection(CullableClass * obj) -{ - WWASSERT(obj != NULL); - obj->NextCollected = CollectionHead; - CollectionHead = obj; -} - - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/cullsys.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/cullsys.h deleted file mode 100644 index e23791d9f4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/cullsys.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/cullsys.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/08/01 6:33p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CULLSYS_H -#define CULLSYS_H - -#include "wwdebug.h" -#include "stdlib.h" -#include "refcount.h" -#include "aabox.h" - -class CullableClass; -class CullSystemClass; -class FrustumClass; - -/* -** CullLinkClass -** This class will serve as a base class for the various types of linkage information -** that the Cullable instances will need. Each CullableClass will have a pointer to -** a class derived from CullLinkClass where the different culling systems can store -** things. -*/ -class CullLinkClass -{ -public: - WWINLINE CullLinkClass(CullSystemClass * system) { System = system; WWASSERT(System); } - virtual ~CullLinkClass(void) { WWASSERT(System == NULL); } - - WWINLINE void Set_Culling_System(CullSystemClass * sys) { System = sys; } - WWINLINE CullSystemClass * Get_Culling_System(void) { return System; } - -protected: - CullSystemClass * System; -}; - - -/* -** CullableClass -** This is the base class for any object that can be inserted into a culling system -** This class provides an axis aligned bounding box and some linkage variables which -** allow it to be processed by any culling system. -*/ -class CullableClass : public RefCountClass -{ -public: - - CullableClass(void); - virtual ~CullableClass(void); - - /* - ** Access to the culling box for this object. When you set the cull box, you are - ** basically guaranteeing that the object is contained within the given box. The - ** object will automatically be updated in whatever culling system it is currently - ** contained in (if any) - */ - WWINLINE const AABoxClass & Get_Cull_Box(void) const { return CullBox; } - void Set_Cull_Box(const AABoxClass & box,bool just_loaded = false); - - /* - ** These functions are used by various culling systems to manage the linkage - ** pointers. *The average user should NEVER call these* - */ - void Set_Culling_System(CullSystemClass * sys); - CullSystemClass * Get_Culling_System(void) const; - WWINLINE void Set_Cull_Link(CullLinkClass * c) { CullLink = c; } - WWINLINE CullLinkClass * Get_Cull_Link(void) const { return CullLink; } - -private: - - WWINLINE void Set_Next_Collected(CullableClass * c) { NextCollected = c; } - WWINLINE CullableClass * Get_Next_Collected(void) { return NextCollected; } - - /* - ** Culling Data - ** Each object can be linked into various types of culling systems. - ** Each culling system can use its own linkage data structure (derived - ** from CullLinkClass) to keep track of the object. The CullData pointer - ** will point to one of the culling link objects and NULL - ** if its not in any system. - */ - CullLinkClass * CullLink; - - /* - ** Bounding Box - ** Any objects derived from Cullable should update the bounding box - ** whenever the object moves or changes size. In order to do this, - ** call Set_Cull_Box... - */ - AABoxClass CullBox; - - /* - ** NextCollected - ** This pointer is used by the culling system to keep a singly linked - ** list of cullable object that have been "collected". - */ - CullableClass * NextCollected; - - // Not Implemented: - CullableClass(const CullableClass & src); - CullableClass & operator = (const CullableClass & src); - - friend class CullSystemClass; -}; - - - - -/* -** CullSystemClass -** Base class of any culling system. This interface exists so that things can -** be shuffled around without having explicit knowledge of what system they are in. -*/ -class CullSystemClass -{ -public: - - CullSystemClass(void); - virtual ~CullSystemClass(void); - - /* - ** Collect_Objects. Updates the internal collection list with the - ** objects that overlap the given primitive. - ** WARNING: This builds an internal list that is only valid until - ** another list is built, only one list can be valid at any time. - ** WARNING: Always call Reset_Collection if you want to start a - ** fresh collection! - */ - void Reset_Collection(void); - virtual void Collect_Objects(const Vector3 & point) = 0; - virtual void Collect_Objects(const AABoxClass & box) = 0; - virtual void Collect_Objects(const OBBoxClass & box) = 0; - virtual void Collect_Objects(const FrustumClass & frustum) = 0; - - /* - ** This object has moved or changed size, update it - */ - virtual void Update_Culling(CullableClass * obj) = 0; - -protected: - - /* - ** Iterate through the collected objects - */ - CullableClass * Get_First_Collected_Object_Internal(void); - CullableClass * Get_Next_Collected_Object_Internal(CullableClass * obj); - CullableClass * Peek_First_Collected_Object_Internal(void); - CullableClass * Peek_Next_Collected_Object_Internal(CullableClass * obj); - - /* - ** Build the list of collected objects - */ - void Add_To_Collection(CullableClass * obj); - - /* - ** Pointer to the head of the current collection of objects - */ - CullableClass * CollectionHead; - - friend class CullableClass; -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/culltype.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/culltype.h deleted file mode 100644 index 696b744382..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/culltype.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/culltype.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 10/23/98 2:34p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CULLTYPE_H -#define CULLTYPE_H - -#include "always.h" - -/* -** CullType is an enumeration of the possible results of a culling -** operation. It is placed here so that all of the different cull functions -** (which are scattered throughout WWMath, WW3D, WWPhys, etc) can -** communicate the result in a consistent way -*/ - -typedef enum CULLTYPE -{ - CULL_OUTSIDE = 0, // the object was completely outside the culling volume - CULL_INTERSECTING, // the object intersects an edge of the culling volume - CULL_INSIDE // the object is completely inside the culling volume -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/curve.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/curve.cpp deleted file mode 100644 index 4f2961b067..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/curve.cpp +++ /dev/null @@ -1,591 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/curve.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "curve.h" -#include "wwdebug.h" -#include "persistfactory.h" -#include "wwmathids.h" -#include "wwhack.h" - -/* -** Force-Link this module because the linker can't detect that we actually need it... -*/ -DECLARE_FORCE_LINK(curve); - -/* -** Persist factories and chunk-id's used to save and load. -*/ -SimplePersistFactoryClass _LinearCurve3DFactory; -SimplePersistFactoryClass _LinearCurve1DFactory; - -enum -{ - // ID's used by Curve3D - CURVE3D_CHUNK_VARIABLES = 0x00020651, - CURVE3D_CHUNK_KEYS, - - CURVE3D_VARIABLE_ISLOOPING = 0x00, - CURVE3D_VARIABLE_KEYCOUNT, - - // ID's used by LinearCurve3D - LINEARCURVE3D_CHUNK_CURVE3D = 0x00020653, - - // ID's used by Curve1D - CURVE1D_CHUNK_VARIABLES = 0x00020655, - CURVE1D_CHUNK_KEYS, - - CURVE1D_VARIABLE_ISLOOPING = 0x00, - CURVE1D_VARIABLE_KEYCOUNT, - - // ID's used by LinearCurve1D - LINEARCURVE1D_CHUNK_CURVE1D = 0x00020657, - -}; - - -/*********************************************************************************************** -** -** Curve3DCLass Implementation -** -***********************************************************************************************/ -Curve3DClass::Curve3DClass(void) : - IsLooping(false) -{ -} - -Curve3DClass::Curve3DClass(const Curve3DClass & that) -{ - *this = that; -} - -Curve3DClass::~Curve3DClass(void) -{ -} - -Curve3DClass & Curve3DClass::operator = (const Curve3DClass & that) -{ - IsLooping = that.IsLooping; - Keys = that.Keys; - return *this; -} - -bool Curve3DClass::Is_Looping(void) -{ - return IsLooping; -} - -void Curve3DClass::Set_Looping(bool onoff) -{ - IsLooping = onoff; -} - -float Curve3DClass::Get_Start_Time(void) -{ - if (Keys.Count() > 0) { - return Keys[0].Time; - } else { - return 0.0f; - } -} - -float Curve3DClass::Get_End_Time(void) -{ - if (Keys.Count() > 0) { - return Keys[Keys.Count() - 1].Time; - } else { - return 0.0f; - } -} - -int Curve3DClass::Key_Count(void) -{ - return Keys.Count(); -} - -void Curve3DClass::Get_Key(int i,Vector3 * set_point,float * set_t) -{ - assert(i >= 0); - assert(i < Keys.Count()); - if (set_point != NULL) { - *set_point = Keys[i].Point; - } - if (set_t != NULL) { - *set_t = Keys[i].Time; - } -} - -void Curve3DClass::Set_Key(int i,const Vector3 & point) -{ - assert(i >= 0); - assert(i < Keys.Count()); - Keys[i].Point = point; -} - - -int Curve3DClass::Add_Key(const Vector3 & point,float t) -{ - int idx = 0; - while (idx < Keys.Count() && Keys[idx].Time < t) { - idx++; - } - - KeyClass newkey; - newkey.Point = point; - newkey.Time = t; - - Keys.Insert(idx,newkey); - return idx; -} - -void Curve3DClass::Remove_Key(int i) -{ - assert(i >= 0); - assert(i < Keys.Count()); - Keys.Delete(i); -} - -void Curve3DClass::Clear_Keys(void) -{ - Keys.Clear(); -} - -void Curve3DClass::Find_Interval(float time,int * i0,int * i1,float * t) -{ - WWASSERT(time >= Keys[0].Time); - WWASSERT(time <= Keys[Keys.Count()-1].Time); - - int i=0; - while (time > Keys[i+1].Time) { - i++; - } - *i0 = i; - *i1 = i+1; - *t = (time - Keys[i].Time) / (Keys[i+1].Time - Keys[i].Time); -} - -bool Curve3DClass::Save(ChunkSaveClass & csave) -{ - int keycount = Keys.Count(); - csave.Begin_Chunk(CURVE3D_CHUNK_VARIABLES); - WRITE_MICRO_CHUNK(csave,CURVE3D_VARIABLE_ISLOOPING,IsLooping); - WRITE_MICRO_CHUNK(csave,CURVE3D_VARIABLE_KEYCOUNT,keycount); - csave.End_Chunk(); - - // Saving the keys, Note that if the format of a key changes we'll - // need a new chunk. (I didn't wrap each variable in its own chunk) - csave.Begin_Chunk(CURVE3D_CHUNK_KEYS); - for (int i=0; i= Keys[Keys.Count() - 1].Time) { - *set_val = Keys[Keys.Count() - 1].Point; - return; - } - - int i0,i1; - float t; - Find_Interval(time,&i0,&i1,&t); - - *set_val = Keys[i0].Point + t * (Keys[i1].Point - Keys[i0].Point); -} - -const PersistFactoryClass & LinearCurve3DClass::Get_Factory(void) const -{ - return _LinearCurve3DFactory; -} - -bool LinearCurve3DClass::Save(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(LINEARCURVE3D_CHUNK_CURVE3D); - Curve3DClass::Save(csave); - csave.End_Chunk(); - return true; -} - -bool LinearCurve3DClass::Load(ChunkLoadClass & cload) -{ - while (cload.Open_Chunk()) { - - switch(cload.Cur_Chunk_ID()) - { - case LINEARCURVE3D_CHUNK_CURVE3D: - Curve3DClass::Load(cload); - break; - - default: - WWDEBUG_SAY(("Unhandled Chunk: 0x%X File: %s Line: %d\r\n",__FILE__,__LINE__)); - break; - } - cload.Close_Chunk(); - } - - return true; -} - - -/*********************************************************************************************** -** -** Curve1DClass -** -***********************************************************************************************/ -Curve1DClass::Curve1DClass(void) : - IsLooping(false) -{ -} - -Curve1DClass::Curve1DClass(const Curve1DClass & that) -{ - *this = that; -} - -Curve1DClass::~Curve1DClass(void) -{ -} - -Curve1DClass & Curve1DClass::operator = (const Curve1DClass & that) -{ - IsLooping = that.IsLooping; - Keys = that.Keys; - return *this; -} - -bool Curve1DClass::Is_Looping(void) -{ - return IsLooping; -} - -void Curve1DClass::Set_Looping(bool onoff) -{ - IsLooping = onoff; -} - -float Curve1DClass::Get_Start_Time(void) -{ - if (Keys.Count() > 0) { - return Keys[0].Time; - } else { - return 0.0f; - } -} - -float Curve1DClass::Get_End_Time(void) -{ - if (Keys.Count() > 0) { - return Keys[Keys.Count() - 1].Time; - } else { - return 0.0f; - } -} - -int Curve1DClass::Key_Count(void) -{ - return Keys.Count(); -} - -void Curve1DClass::Get_Key(int i,float * set_point,float * set_t,unsigned int * extra) -{ - assert(i >= 0); - assert(i < Keys.Count()); - if (set_point != NULL) { - *set_point = Keys[i].Point; - } - if (set_t != NULL) { - *set_t = Keys[i].Time; - } - if (extra != NULL) { - *extra = Keys[i].Extra; - } -} - -void Curve1DClass::Set_Key(int i,float point,unsigned int extra) -{ - assert(i >= 0); - assert(i < Keys.Count()); - Keys[i].Point = point; - Keys[i].Extra = extra; -} - - -int Curve1DClass::Add_Key(float point,float t,unsigned int extra) -{ - int idx = 0; - while (idx < Keys.Count() && Keys[idx].Time < t) { - idx++; - } - - KeyClass newkey; - newkey.Point = point; - newkey.Time = t; - newkey.Extra = extra; - - Keys.Insert(idx,newkey); - return idx; -} - -void Curve1DClass::Remove_Key(int i) -{ - assert(i >= 0); - assert(i < Keys.Count()); - Keys.Delete(i); -} - -void Curve1DClass::Clear_Keys(void) -{ - Keys.Clear(); -} - -void Curve1DClass::Find_Interval(float time,int * i0,int * i1,float * t) -{ - if (IsLooping) { - if (time < Keys[0].Time) { - *i0 = Keys.Count() - 1; - *i1 = 0; - float interval = 1.0f - Keys[*i0].Time + Keys[*i1].Time; - *t = (1.0f - Keys[*i0].Time + time) / interval; - return; - } - else if (time > Keys[Keys.Count() - 1].Time) { - *i0 = Keys.Count() - 1; - *i1 = 0; - float interval = 1.0f - Keys[*i0].Time + Keys[*i1].Time; - *t = (time - Keys[*i0].Time) / interval; - return; - } - } - else { - WWASSERT(time >= Keys[0].Time); - WWASSERT(time <= Keys[Keys.Count()-1].Time); - } - - int i=0; - while (time > Keys[i+1].Time) { - i++; - } - *i0 = i; - *i1 = i+1; - *t = (time - Keys[i].Time) / (Keys[i+1].Time - Keys[i].Time); -} - -bool Curve1DClass::Save(ChunkSaveClass & csave) -{ - int keycount = Keys.Count(); - csave.Begin_Chunk(CURVE1D_CHUNK_VARIABLES); - WRITE_MICRO_CHUNK(csave,CURVE1D_VARIABLE_ISLOOPING,IsLooping); - WRITE_MICRO_CHUNK(csave,CURVE1D_VARIABLE_KEYCOUNT,keycount); - csave.End_Chunk(); - - // Saving the keys, Note that if the format of a key changes we'll - // need a new chunk. (I didn't wrap each variable in its own chunk) - csave.Begin_Chunk(CURVE1D_CHUNK_KEYS); - for (int i=0; i= Keys[Keys.Count() - 1].Time) { - *set_val = Keys[Keys.Count() - 1].Point; - return; - } - } - - int i0,i1; - float t; - Find_Interval(time,&i0,&i1,&t); - - *set_val = Keys[i0].Point + t * (Keys[i1].Point - Keys[i0].Point); -} - -const PersistFactoryClass & LinearCurve1DClass::Get_Factory(void) const -{ - return _LinearCurve1DFactory; -} - -bool LinearCurve1DClass::Save(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(LINEARCURVE1D_CHUNK_CURVE1D); - Curve1DClass::Save(csave); - csave.End_Chunk(); - return true; -} - -bool LinearCurve1DClass::Load(ChunkLoadClass & cload) -{ - while (cload.Open_Chunk()) { - - switch(cload.Cur_Chunk_ID()) - { - case LINEARCURVE1D_CHUNK_CURVE1D: - Curve1DClass::Load(cload); - break; - - default: - WWDEBUG_SAY(("Unhandled Chunk: 0x%X File: %s Line: %d\r\n",__FILE__,__LINE__)); - break; - } - cload.Close_Chunk(); - } - - return true; -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/curve.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/curve.h deleted file mode 100644 index e86d910c31..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/curve.h +++ /dev/null @@ -1,179 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/curve.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef CURVE_H -#define CURVE_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef VECTOR_H -#include "Vector.H" -#endif - -#ifndef VECTOR3_H -#include "vector3.h" -#endif - -#ifndef PERSIST_H -#include "persist.h" -#endif - -class ChunkLoadClass; -class ChunkSaveClass; - - -class Curve3DClass : public PersistClass -{ -public: - - Curve3DClass(void); - Curve3DClass(const Curve3DClass & that); - virtual ~Curve3DClass(void); - Curve3DClass & operator = (const Curve3DClass & that); - - virtual void Evaluate(float time,Vector3 * set_val) = 0; - virtual bool Is_Looping(void); - virtual void Set_Looping(bool onoff); - virtual int Key_Count(void); - virtual void Get_Key(int i,Vector3 * set_point,float * set_t); - virtual void Set_Key(int i,const Vector3 & point); - virtual int Add_Key(const Vector3 & point,float t); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - float Get_Start_Time(void); - float Get_End_Time(void); - - // persistant object support - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - -protected: - - void Find_Interval(float time,int * i0,int * i1,float * t); - - class KeyClass - { - public: - Vector3 Point; - float Time; - bool operator == (const KeyClass & that) { return ((Point == that.Point) && (Time == that.Time)); } - bool operator != (const KeyClass & that) { return !KeyClass::operator==(that); } - }; - - bool IsLooping; - DynamicVectorClass Keys; -}; - - -class LinearCurve3DClass : public Curve3DClass -{ -public: - virtual void Evaluate(float time,Vector3 * set_val); - - // persistant object support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); -}; - - -/* -** 1-Dimensional curve classes. -*/ -class Curve1DClass : public PersistClass -{ -public: - - Curve1DClass(void); - Curve1DClass(const Curve1DClass & that); - virtual ~Curve1DClass(void); - Curve1DClass & operator = (const Curve1DClass & that); - - virtual void Evaluate(float time,float * set_val) = 0; - virtual bool Is_Looping(void); - virtual void Set_Looping(bool onoff); - virtual int Key_Count(void); - virtual void Get_Key(int i,float * set_point,float * set_t,unsigned int * extra=NULL); - virtual void Set_Key(int i,float point,unsigned int extra=0); - virtual int Add_Key(float point,float t,unsigned int extra=0); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - float Get_Start_Time(void); - float Get_End_Time(void); - - // persistant object support - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - -protected: - - void Find_Interval(float time,int * i0,int * i1,float * t); - - class KeyClass - { - public: - float Point; - float Time; - unsigned int Extra; - bool operator == (const KeyClass & that) { return ((Point == that.Point) && (Time == that.Time) && (Extra == that.Extra)); } - bool operator != (const KeyClass & that) { return !KeyClass::operator==(that); } - }; - - bool IsLooping; - DynamicVectorClass Keys; -}; - - -class LinearCurve1DClass : public Curve1DClass -{ -public: - virtual void Evaluate(float time,float * set_val); - - // persistant object support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); -}; - - -#endif //CURVE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/euler.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/euler.cpp deleted file mode 100644 index 4e15ea4ce5..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/euler.cpp +++ /dev/null @@ -1,373 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/euler.cpp 5 4/27/01 11:51a Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G Math Library * - * * - * $Archive:: /Commando/Code/wwmath/euler.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 4/23/01 6:08p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * EulerAnglesClass::EulerAnglesClass -- constructor * - * EulerAnglesClass::Get_Angle -- returns angle 'i' of the euler angles * - * EulerAnglesClass::From_Matrix -- computes the equivalent euler angles for the given matrix* - * EulerAnglesClass::To_Matrix -- Builds a matrix from the given euler angles * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "euler.h" -#include - - -/********************************************************************* - - There are 24 possible conventions for Euler angles. They can - be designated by: - - EulerAxis = Axis used initially - EulerParity = parity of axis permutation (even = x,y,z) - EulerRepeat = is last axis a repeat of the initial axis? - EulerFrame = frame from which axes are taken (rotating or static) - - For example, in this system an euler angle convention of: - - Rotate_X(a0); - Rotate_Y(a1); - Rotate_Z(a2); - - would be described as EulerOrderXYZr. - -*********************************************************************/ - -#define EULER_FRAME_STATIC 0x00000000 -#define EULER_FRAME_ROTATING 0x00000001 -#define EULER_FRAME(order) ((unsigned)(order) & 1) - -#define EULER_REPEAT_NO 0x00000000 -#define EULER_REPEAT_YES 0x00000001 -#define EULER_REPEAT(order) (((unsigned)(order) >> 1) & 1) - -#define EULER_PARITY_EVEN 0x00000000 -#define EULER_PARITY_ODD 0x00000001 -#define EULER_PARITY(order) (((unsigned)(order) >> 2) & 1) - -#define EULER_BUILD_ORDER(i,p,r,f) (((((((i) << 1) + (p)) << 1) + (r)) << 1) + (f)) - - -/* static axes */ -int EulerOrderXYZs = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderXYXs = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderXZYs = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderXZXs = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderYZXs = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderYZYs = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderYXZs = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderYXYs = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderZXYs = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderZXZs = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderZYXs = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderZYZs = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_STATIC); - -/* rotating axes */ -int EulerOrderZYXr = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderXYXr = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderYZXr = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderXZXr = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderXZYr = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderYZYr = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderZXYr = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderYXYr = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderYXZr = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderZXZr = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderXYZr = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderZYZr = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_ROTATING); - - -#define EULER_SAFE "\000\001\002\000" -#define EULER_NEXT "\001\002\000\001" - -#define EULER_AXIS_I(order) ((int)(EULER_SAFE[(((unsigned)(ord)>>3) & 3)])) -#define EULER_AXIS_J(order) ((int)(EULER_NEXT[EULER_AXIS_I(order) + (EULER_PARITY(order) == EULER_PARITY_ODD)])) -#define EULER_AXIS_K(order) ((int)(EULER_NEXT[EULER_AXIS_I(order) + (EULER_PARITY(order) != EULER_PARITY_ODD)])) -#define EULER_AXIS_H(order) ((EULER_REPEAT(order) == EULER_REPEAT_NO) ? EULER_AXIS_K(order) : EULER_AXIS_I(order)) - - - -/* local functions */ -static void _euler_unpack_order(int order,int &i,int &j,int &k,int &h,int &n,int &s,int &f); -static int _euler_axis_i(int order); -static int _euler_axis_j(int order); -static int _euler_axis_k(int order); -static int _euler_axis_h(int order); - - -/*********************************************************************************************** - * EulerAnglesClass::EulerAnglesClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -EulerAnglesClass::EulerAnglesClass(const Matrix3D & M,int order) -{ - this->From_Matrix(M,order); -} - -/*********************************************************************************************** - * EulerAnglesClass::Get_Angle -- returns angle 'i' of the euler angles * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -double EulerAnglesClass::Get_Angle(int i) -{ - return Angle[i]; -} - -/*********************************************************************************************** - * EulerAnglesClass::From_Matrix -- computes the equivalent euler angles for the given matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void EulerAnglesClass::From_Matrix(const Matrix3D & M, int order) -{ - int i,j,k,h,n,s,f; - - Order = order; - _euler_unpack_order(order,i,j,k,h,n,s,f); - - if (s == EULER_REPEAT_YES) { - double sy = sqrt(M[i][j]*M[i][j] + M[i][k]*M[i][k]); - - if (sy > 16*FLT_EPSILON) { - - Angle[0] = WWMath::Atan2(M[i][j],M[i][k]); - Angle[1] = WWMath::Atan2(sy,M[i][i]); - Angle[2] = WWMath::Atan2(M[j][i],-M[k][i]); - - } else { - - Angle[0] = WWMath::Atan2(-M[j][k],M[j][j]); - Angle[1] = WWMath::Atan2(sy,M[i][i]); - Angle[2] = 0.0; - } - - } else { - - double cy = sqrt(M[i][i]*M[i][i] + M[j][i]*M[j][i]); - - if (cy > 16*FLT_EPSILON) { - - Angle[0] = WWMath::Atan2(M[k][j],M[k][k]); - Angle[1] = WWMath::Atan2(-M[k][i],cy); - Angle[2] = WWMath::Atan2(M[j][i],M[i][i]); - - } else { - - Angle[0] = WWMath::Atan2(-M[j][k],M[j][j]); - Angle[1] = WWMath::Atan2(-M[k][i],cy); - Angle[2] = 0; - } - } - - if (n==EULER_PARITY_ODD) { Angle[0] = -Angle[0]; Angle[1] = -Angle[1]; Angle[2] = -Angle[2]; } - if (f==EULER_FRAME_ROTATING) { double t = Angle[0]; Angle[0] = Angle[2]; Angle[2] = t; } - - // Trying to "clean" up the eulers, special cased for XYZr - if (order == EulerOrderXYZr) { - - const double PI = 3.141592654; - - double x2 = PI + Angle[0]; - double y2 = PI - Angle[1]; - double z2 = PI + Angle[2]; - - if (x2 > PI) { - x2 = x2 - 2*PI; - } - - if (y2 > PI) { - y2 = y2 - 2*PI; - } - - if (z2 > PI) { - z2 = z2 - 2*PI; - } - - double mag0 = Angle[0]*Angle[0] + Angle[1]*Angle[1] + Angle[2]*Angle[2]; - double mag1 = x2*x2 + y2*y2 + z2*z2; - - if (mag1 < mag0) { - Angle[0] = x2; - Angle[1] = y2; - Angle[2] = z2; - } - } -} - - - -/*********************************************************************************************** - * EulerAnglesClass::To_Matrix -- Builds a matrix from the given euler angles * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void EulerAnglesClass::To_Matrix(Matrix3D & M) -{ - M.Make_Identity(); - - double a0,a1,a2; - double ti,tj,th,ci,cj,ch,si,sj,sh,cc,cs,sc,ss; - int i,j,k,h,n,s,f; - - a0 = Angle[0]; - a1 = Angle[1]; - a2 = Angle[2]; - - _euler_unpack_order(Order,i,j,k,h,n,s,f); - if (f == EULER_FRAME_ROTATING) { - double t = a0; a0 = a2; a2 = t; - } - - if (n == EULER_PARITY_ODD) { - a0 = -a0; a1 = -a1; a2 = -a2; - } - - ti = a0; tj = a1; th = a2; - ci = WWMath::Cos(ti); cj = WWMath::Cos(tj); ch = WWMath::Cos(th); - si = WWMath::Sin(ti); sj = WWMath::Sin(tj); sh = WWMath::Sin(th); - - cc = ci*ch; - cs = ci*sh; - sc = si*ch; - ss = si*sh; - - if (s == EULER_REPEAT_YES) { - - M[i][i] = (float)(cj); M[i][j] = (float)(sj*si); M[i][k] = (float)(sj*ci); - M[j][i] = (float)(sj*sh); M[j][j] = (float)(-cj*ss+cc); M[j][k] = (float)(-cj*cs-sc); - M[k][i] = (float)(-sj*ch); M[k][j] = (float)(cj*sc+cs); M[k][k] = (float)(cj*cc-ss); - - } else { - - M[i][i] = (float)(cj*ch); M[i][j] = (float)(sj*sc-cs); M[i][k] = (float)(sj*cc+ss); - M[j][i] = (float)(cj*sh); M[j][j] = (float)(sj*ss+cc); M[j][k] = (float)(sj*cs-sc); - M[k][i] = (float)(-sj); M[k][j] = (float)(cj*si); M[k][k] = (float)(cj*ci); - - } -} - - -/* -** Local functions -*/ - -static int _euler_safe[] = { 0,1,2,0 }; -static int _euler_next[] = { 1,2,0,1 }; - -int _euler_axis_i(int order) -{ - return _euler_safe[ (order>>3) & 3 ]; -} - -int _euler_axis_j(int order) -{ - int index = _euler_axis_i(order); - if (EULER_PARITY(order) == 1) { - index++; - } - - return _euler_next[ index ]; -} - -int _euler_axis_k(int order) -{ - int index = _euler_axis_i(order); - if (EULER_PARITY(order) != 1) { - index++; - } - - return _euler_next[ index ]; -} - -int _euler_axis_h(int order) -{ - if (EULER_REPEAT(order) == 1) { - return _euler_axis_k(order); - } else { - return _euler_axis_i(order); - } -} - -void _euler_unpack_order(int order,int &i,int &j,int &k,int &h,int &n,int &s,int &f) -{ - - f = order & 1; - order >>= 1; - - s = order & 1; - order >>= 1; - - n = order & 1; - order >>= 1; - - i = _euler_safe[order & 3]; - j = _euler_next[i+n]; - k = _euler_next[i+1-n]; - h = (s ? k : i); -} - - - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/euler.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/euler.h deleted file mode 100644 index bf7a90bd36..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/euler.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/euler.h 5 5/05/01 5:48p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G Math Library * - * * - * $Archive:: /Commando/Code/wwmath/euler.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 5/04/01 8:37p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef EULER_H -#define EULER_H - -#include "always.h" -#include "matrix3d.h" -#include "quat.h" - - -/********************************************************************* - - Euler Order Types - - When creating an EulerAngles object, use one of the below - constants to describe the axis convention. - - XYZ - order of the axes - s/r - whether the rotations are applied to a static or - rotating frame. - -*********************************************************************/ - - -/* static axes */ -extern int EulerOrderXYZs; -extern int EulerOrderXYXs; -extern int EulerOrderXZYs; -extern int EulerOrderXZXs; -extern int EulerOrderYZXs; -extern int EulerOrderYZYs; -extern int EulerOrderYXZs; -extern int EulerOrderYXYs; -extern int EulerOrderZXYs; -extern int EulerOrderZXZs; -extern int EulerOrderZYXs; -extern int EulerOrderZYZs; - -/* rotating axes */ -extern int EulerOrderXYZr; -extern int EulerOrderXYXr; -extern int EulerOrderXZYr; -extern int EulerOrderXZXr; -extern int EulerOrderYZXr; -extern int EulerOrderYZYr; -extern int EulerOrderYXZr; -extern int EulerOrderYXYr; -extern int EulerOrderZXYr; -extern int EulerOrderZXZr; -extern int EulerOrderZYXr; -extern int EulerOrderZYZr; - - -/********************************************************************* - - EulerAnglesClass - - The purpose for this class is mainly for conversion. You can - choose a convention for the order of your rotations and then - convert matrices into a set of euler angles. You don't really - want to use this at run-time to convert matrices into angles. - - The guts of this implementation is based on the article in Graphics - Gems IV by Ken Shoemake. The original article is on page 222. - -*********************************************************************/ -class EulerAnglesClass -{ - -public: - - EulerAnglesClass(void) : Order(0) { Angle[0] = 0.0; Angle[1] = 0.0; Angle[2] = 0.0; }; - EulerAnglesClass(const Matrix3D & from,int order); - void From_Matrix(const Matrix3D & from,int order); - void To_Matrix(Matrix3D & M); - - double Get_Angle(int i); - -private: - - double Angle[3]; - int Order; - -}; - - -#endif /*EULER_H*/ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/frustum.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/frustum.cpp deleted file mode 100644 index 7bb5e12409..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/frustum.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/frustum.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 4/01/01 12:47p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * FrustumClass::Init -- Initialize a frustum object * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "frustum.h" - - -/*********************************************************************************************** - * FrustumClass::Init -- Initialize a frustum object * - * * - * This function initializes a frustum from the description of a camera * - * * - * INPUT: * - * camera - camera transform, note that the camera looks down the -Z axis * - * vpmin - min corner of the z=-1.0 view plane (not necessarily the near clip plane) * - * vpmax - max corner of the z=-1.0 view plane (not necessarily the near clip plane) * - * znear - near clip plane (should be negative, negated if it is not) * - * zfar - far clip plane (should be negative, negated if it is not) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * The vpmin and vpmax variables are the min and max of a view-plane at z=-1.0 * - * * - * * - * HISTORY: * - * 2/17/2000 gth : Created. * - *=============================================================================================*/ -void FrustumClass::Init -( - const Matrix3D & camera, - const Vector2 & vpmin, - const Vector2 & vpmax, - float znear, - float zfar -) -{ - int i; - - // Store the camera transform - CameraTransform = camera; - - // Forward is negative Z in our viewspace coordinate system. - // Just flip the sign if the user passed in positive values. - if ((znear > 0.0f) && (zfar > 0.0f)) { - znear = -znear; - zfar = -zfar; - } - - // Calculate the corners of the camera frustum. - // Generate the camera-space frustum corners by linearly - // extrapolating the viewplane to the near and far z clipping planes. - - // The camera frustum corners are defined in the following order: - // When looking at the frustum from the position of the camera, the near four corners are - // numbered: upper left 0, upper right 1, lower left 2, lower right 3. The far plane's - // Frustum corners are numbered from 4 to 7 in an analogous fashion. - // (remember: the camera space has x going to the right, y up and z backwards). - - //calculate a proper z-vector assuming our right-handed coordinate system - Vector3 zv; - Vector3::Cross_Product(CameraTransform.Get_X_Vector(),CameraTransform.Get_Y_Vector(),&zv); - - //compare correct z-vector with the one in the camera matrix. If they point in - //opposite directions, we have a reflected camera matrix. - if (Vector3::Dot_Product(CameraTransform.Get_Z_Vector(),zv) < 0) - { //flip the frustum corners horizontally for a reflected matrix - Corners[1].Set(vpmin.X, vpmax.Y, 1.0); - Corners[5] = Corners[1]; - Corners[1] *= znear; - Corners[5] *= zfar; - Corners[0].Set(vpmax.X, vpmax.Y, 1.0); - Corners[4] = Corners[0]; - Corners[0] *= znear; - Corners[4] *= zfar; - Corners[3].Set(vpmin.X, vpmin.Y, 1.0); - Corners[7] = Corners[3]; - Corners[3] *= znear; - Corners[7] *= zfar; - Corners[2].Set(vpmax.X, vpmin.Y, 1.0); - Corners[6] = Corners[2]; - Corners[2] *= znear; - Corners[6] *= zfar; - } - else - { //normal camera - Corners[0].Set(vpmin.X, vpmax.Y, 1.0); - Corners[4] = Corners[0]; - Corners[0] *= znear; - Corners[4] *= zfar; - Corners[1].Set(vpmax.X, vpmax.Y, 1.0); - Corners[5] = Corners[1]; - Corners[1] *= znear; - Corners[5] *= zfar; - Corners[2].Set(vpmin.X, vpmin.Y, 1.0); - Corners[6] = Corners[2]; - Corners[2] *= znear; - Corners[6] *= zfar; - Corners[3].Set(vpmax.X, vpmin.Y, 1.0); - Corners[7] = Corners[3]; - Corners[3] *= znear; - Corners[7] *= zfar; - } - - - // Transform the eight corners of the view frustum from camera space to world space. - for (i = 0; i < 8; i++) { - Matrix3D::Transform_Vector(CameraTransform, Corners[i], &(Corners[i])); - } - - // Create the six frustum bounding planes from the eight corner Corners. - // The bounding planes are oriented so that their normals point outward - PlaneClass frustum_planes[6]; - Planes[0].Set(Corners[0], Corners[3], Corners[1]); // near - Planes[1].Set(Corners[0], Corners[5], Corners[4]); // bottom - Planes[2].Set(Corners[0], Corners[6], Corners[2]); // right - Planes[3].Set(Corners[2], Corners[7], Corners[3]); // top - Planes[4].Set(Corners[1], Corners[7], Corners[5]); // left - Planes[5].Set(Corners[4], Corners[7], Corners[6]); // far - - // find the bounding box of the entire frustum (may be used for sloppy quick rejection) - BoundMin = BoundMax = Corners[0]; - - for (i=1; i<8;i++) { - if (Corners[i].X < BoundMin.X) BoundMin.X = Corners[i].X; - if (Corners[i].X > BoundMax.X) BoundMax.X = Corners[i].X; - - if (Corners[i].Y < BoundMin.Y) BoundMin.Y = Corners[i].Y; - if (Corners[i].Y > BoundMax.Y) BoundMax.Y = Corners[i].Y; - - if (Corners[i].Z < BoundMin.Z) BoundMin.Z = Corners[i].Z; - if (Corners[i].Z > BoundMax.Z) BoundMax.Z = Corners[i].Z; - } -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/frustum.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/frustum.h deleted file mode 100644 index a849eb84be..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/frustum.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/frustum.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/29/00 10:20a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef FRUSTUM_H -#define FRUSTUM_H - -#include "vector3.h" -#include "plane.h" - - -class FrustumClass -{ -public: - void Init( const Matrix3D & camera, - const Vector2 & viewport_min, - const Vector2 & viewport_max, - float znear, - float zfar ); - - const Vector3 & Get_Bound_Min(void) const { return BoundMin; } - const Vector3 & Get_Bound_Max(void) const { return BoundMax; } - -public: - - Matrix3D CameraTransform; - PlaneClass Planes[6]; - Vector3 Corners[8]; - Vector3 BoundMin; - Vector3 BoundMax; -}; - - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/gridcull.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/gridcull.cpp deleted file mode 100644 index 1d628382c2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/gridcull.cpp +++ /dev/null @@ -1,1024 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/gridcull.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 4/27/00 7:00p $* - * * - * $Revision:: 18 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GridCullSystemClass::GridCullSystemClass -- Constructor * - * GridCullSystemClass::~GridCullSystemClass -- Destructor * - * GridCullSystemClass::Collect_Objects -- Collect all objects touching the given point * - * GridCullSystemClass::Collect_Objects -- Collect all objects touching the given AABox * - * GridCullSystemClass::Collect_Objects -- Collect all objects touching the given OBBox * - * GridCullSystemClass::Collect_Objects -- Collect all objects touching the given Frustum * - * GridCullSystemClass::Re_Partition -- re-compute grid parameters for the given volume * - * GridCullSystemClass::Collect_And_Unlink_All -- collects all objects and removes them from * - * GridCullSystemClass::Update_Culling -- updates an objects position in the grid * - * GridCullSystemClass::Load -- load function * - * GridCullSystemClass::Save -- Save function * - * GridCullSystemClass::Reset_Statistics -- reset debugging stats * - * GridCullSystemClass::Get_Statistics -- returns reference to the statistics structure * - * GridCullSystemClass::Add_Object_Internal -- links an object into the system * - * GridCullSystemClass::Remove_Object_Internal -- unlinks an object from the system * - * GridCullSystemClass::link_object -- figures out which cell the object is in and links it * - * GridCullSystemClass::unlink_object -- unlinks the object from the cell it is in * - * GridCullSystemClass::link_object_to_list -- grid list link function * - * GridCullSystemClass::unlink_object_from_list -- grid list unlink function * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "gridcull.h" -#include "chunkio.h" -#include "iostruct.h" -#include "colmath.h" -#include "colmathinlines.h" - - - -/* -** Declare the pool for GridLinks -*/ -DEFINE_AUTO_POOL(GridLinkClass,256); - - -/* -** Current version of the file format -*/ -const uint32 GRID_CURRENT_VERSION = 0x00010000; - - -/* -** Chunk Id's used by the aabtree code to save itself into a file -*/ -enum -{ - GRID_CHUNK_VERSION = 0x00000001, // version wrapper, contains 32bit version # - GRID_CHUNK_PARAMETERS = 0x00000100, // parameters for the grid cull system -}; - - -/* -** IOGridParametersStruct -** Data structure for the contents of a node in the AAB-Tree -*/ -struct IOGridParametersStruct -{ - IOVector3Struct MinCellSize; - IOVector3Struct Origin; - IOVector3Struct CellDim; - uint32 CellCount[3]; - float32 MaxObjExtent; -}; - - -/************************************************************************* -** -** Utility functions for walking the object list in an AABTree Node -** -*************************************************************************/ -static inline CullableClass * get_next_object(CullableClass * obj) -{ - return ((GridLinkClass *)obj->Get_Cull_Link())->Next; -} - -/************************************************************************* -** -** GridLinkClass Implementation -** -*************************************************************************/ -GridLinkClass::GridLinkClass(GridCullSystemClass * system) : - CullLinkClass(system), - GridAddress(-1), - Prev(NULL), - Next(NULL) -{ -} - -GridLinkClass::~GridLinkClass(void) -{ -} - - - - - -/************************************************************************* -** -** GridCullSystemClass Implementation -** -*************************************************************************/ - - -/*********************************************************************************************** - * GridCullSystemClass::GridCullSystemClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -GridCullSystemClass::GridCullSystemClass(void) : - MinCellSize(10,10,10), - MaxObjExtent(15), - Origin(-100,-100,-100), - CellDim(10,10,10), - Cells(NULL), - NoGridList(NULL), - ObjCount(0), - TerminationCellCount(TERMINATION_CELL_COUNT) -{ - CellCount[0] = CellCount[1] = CellCount[2] = 0; - Re_Partition(Vector3(-100,-100,-100),Vector3(100,100,100),15); - Reset_Statistics(); -} - - -/*********************************************************************************************** - * GridCullSystemClass::~GridCullSystemClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -GridCullSystemClass::~GridCullSystemClass(void) -{ - if (Cells != NULL) { - delete Cells; - Cells = NULL; - } -} - - -/*********************************************************************************************** - * GridCullSystemClass::Collect_Objects -- Collect all objects touching the given point * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Collect_Objects(const Vector3 & point) -{ - /* - ** Collect the objects in the grid - */ - VolumeStruct vol; - init_volume(point,point,&vol); - if (!vol.Is_Empty()) { - - int delta_x = vol.Max[0] - vol.Min[0]; - int i,j,k; - int address = map_indices_to_address(vol.Min[0],vol.Min[1],vol.Min[2]); - - for (k=vol.Min[2]; k 0.0f); - WWASSERT(world_dim.Y > 0.0f); - WWASSERT(world_dim.Z > 0.0f); - - /* - ** how many cells should we use on each dimension? - */ - CellCount[0] = CellCount[1] = CellCount[2] = 1; - CellDim = world_dim; - bool done = false; - - while (!done) { - - /* - ** find biggest dimension - */ - int bigdim = 0; - if (CellDim[1]/MinCellSize[1] > CellDim[bigdim]/MinCellSize[bigdim]) bigdim = 1; - if (CellDim[2]/MinCellSize[2] > CellDim[bigdim]/MinCellSize[bigdim]) bigdim = 2; - - /* - ** split dimension in two if possible - */ - if (CellDim[bigdim] >= 2.0f * MinCellSize[bigdim]) { - CellDim[bigdim] /= 2.0f; - CellCount[bigdim] *= 2; - } - - /* - ** check termination conditions - */ - if (total_cell_count() >= TerminationCellCount) { - done = true; - } - - if ( (CellDim[0] < 2.0*MinCellSize[0]) && - (CellDim[1] < 2.0*MinCellSize[1]) && - (CellDim[2] < 2.0*MinCellSize[2]) ) { - done = true; - } - } - - OOCellDim.X = 1.0f / CellDim.X; - OOCellDim.Y = 1.0f / CellDim.Y; - OOCellDim.Z = 1.0f / CellDim.Z; - - if (Cells != NULL) { - delete[] Cells; - } - Cells = W3DNEWARRAY CullableClass * [total_cell_count()]; - memset(&(Cells[0]),0,total_cell_count() * sizeof(CullableClass *)); - - /* - ** iterate the collection list and re-insert all objects into the grid - */ - CullableClass * obj; - for ( obj = Get_First_Collected_Object_Internal(); - obj != NULL; - obj = Get_Next_Collected_Object_Internal(obj)) - { - link_object(obj); - } -} - - -/*********************************************************************************************** - * GridCullSystemClass::Collect_And_Unlink_All -- collects all objects and removes them from t * - * * - * This is used when re-partitioning the grid. All objects are pulled out and linked into * - * the collection list. When the grid has been re-initialized, the objects are put back in. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Collect_And_Unlink_All(void) -{ - Reset_Collection(); - - /* - ** pull all objects out of the grid - */ - for (int k=0; kGet_Culling_System() == this); - - int address; - GridLinkClass * link = (GridLinkClass *)obj->Get_Cull_Link(); - map_point_to_address(obj->Get_Cull_Box().Center,address); - - if (address != link->GridAddress) { - unlink_object(obj); - link_object(obj,address); - } -} - - -/*********************************************************************************************** - * GridCullSystemClass::Load -- load function * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Load(ChunkLoadClass & cload) -{ - /* - ** read the version chunk - */ - uint32 version; - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == GRID_CHUNK_VERSION); - cload.Read(&version,sizeof(version)); - cload.Close_Chunk(); - - /* - ** read the parameters chunk - */ - IOGridParametersStruct params; - memset(¶ms,0,sizeof(params)); - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == GRID_CHUNK_PARAMETERS); - cload.Read(¶ms,sizeof(params)); - cload.Close_Chunk(); - - /* - ** unlink all objects - */ - Collect_And_Unlink_All(); - - /* - ** partition the grid according to the loaded parameters - */ - CellCount[0] = params.CellCount[0]; - CellCount[1] = params.CellCount[1]; - CellCount[2] = params.CellCount[2]; - CellDim.X = params.CellDim.X; - CellDim.Y = params.CellDim.Y; - CellDim.Z = params.CellDim.Z; - MaxObjExtent = params.MaxObjExtent; - MinCellSize.X = params.MinCellSize.X; - MinCellSize.Y = params.MinCellSize.Y; - MinCellSize.Z = params.MinCellSize.Z; - Origin.X = params.Origin.X; - Origin.Y = params.Origin.Y; - Origin.Z = params.Origin.Z; - - OOCellDim.X = 1.0f / CellDim.X; - OOCellDim.Y = 1.0f / CellDim.Y; - OOCellDim.Z = 1.0f / CellDim.Z; - - if (Cells != NULL) { - delete [] Cells; - Cells = NULL; - } - - Cells = W3DNEWARRAY CullableClass * [total_cell_count()]; - memset(&(Cells[0]),0,total_cell_count() * sizeof(CullableClass *)); - - /* - ** re-link the objects in - */ - CullableClass * obj; - for ( obj = Get_First_Collected_Object_Internal(); - obj != NULL; - obj = Get_Next_Collected_Object_Internal(obj)) - { - link_object(obj); - } -} - - -/*********************************************************************************************** - * GridCullSystemClass::Save -- Save function * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Save(ChunkSaveClass & csave) -{ - /* - ** write the version chunk - */ - uint32 version = GRID_CURRENT_VERSION; - csave.Begin_Chunk(GRID_CHUNK_VERSION); - csave.Write(&version,sizeof(version)); - csave.End_Chunk(); - - /* - ** write the grid parameters - */ - IOGridParametersStruct params; - memset(¶ms,0,sizeof(params)); - params.CellCount[0] = CellCount[0]; - params.CellCount[1] = CellCount[1]; - params.CellCount[2] = CellCount[2]; - params.CellDim.X = CellDim.X; - params.CellDim.Y = CellDim.Y; - params.CellDim.Z = CellDim.Z; - params.MaxObjExtent = MaxObjExtent; - params.MinCellSize.X = MinCellSize.X; - params.MinCellSize.Y = MinCellSize.Y; - params.MinCellSize.Z = MinCellSize.Z; - params.Origin.X = Origin.X; - params.Origin.Y = Origin.Y; - params.Origin.Z = Origin.Z; - - csave.Begin_Chunk(GRID_CHUNK_PARAMETERS); - csave.Write(¶ms,sizeof(params)); - csave.End_Chunk(); -} - - -/*********************************************************************************************** - * GridCullSystemClass::Reset_Statistics -- reset debugging stats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Reset_Statistics(void) -{ - // number of (virtual) nodes = 2n-1 - Stats.NodeCount = 2 * (CellCount[0] * CellCount[1] * CellCount[2]) - 1; - Stats.NodesAccepted = 0; - Stats.NodesTriviallyAccepted = 0; - Stats.NodesRejected = 0; -} - - -/*********************************************************************************************** - * GridCullSystemClass::Get_Statistics -- returns reference to the statistics structure * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -const GridCullSystemClass::StatsStruct & GridCullSystemClass::Get_Statistics(void) -{ - return Stats; -} - - -/*********************************************************************************************** - * GridCullSystemClass::Add_Object_Internal -- links an object into the system * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Add_Object_Internal(CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == NULL); - - GridLinkClass * link = new GridLinkClass(this); - obj->Set_Cull_Link(link); - link_object(obj); - - ObjCount++; - obj->Add_Ref(); -} - - -/*********************************************************************************************** - * GridCullSystemClass::Remove_Object_Internal -- unlinks an object from the system * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::Remove_Object_Internal(CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - GridLinkClass * link = (GridLinkClass *)obj->Get_Cull_Link(); - - unlink_object(obj); - link->Set_Culling_System(NULL); - delete link; - obj->Set_Cull_Link(NULL); - - ObjCount--; - obj->Release_Ref(); -} - - -/*********************************************************************************************** - * GridCullSystemClass::link_object -- figures out which cell the object is in and links it * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::link_object(CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - - int address; - map_point_to_address(obj->Get_Cull_Box().Center,address); - - link_object(obj,address); -} - -void GridCullSystemClass::link_object(CullableClass * obj,int address) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - GridLinkClass * link = (GridLinkClass *)obj->Get_Cull_Link(); - WWASSERT(link != NULL); - - /* - ** if obj cannot be inserted into the grid, add it to the NoGridList - ** otherwise, insert it into the cell - */ - const AABoxClass & box = obj->Get_Cull_Box(); - if ( - (box.Extent.X > MaxObjExtent) || - (box.Extent.Y > MaxObjExtent) || - (box.Extent.Z > MaxObjExtent) || - (address == UNGRIDDED_ADDRESS) - ) - { - link->GridAddress = UNGRIDDED_ADDRESS; - link_object_to_list(&NoGridList,obj); - } else { - link->GridAddress = address; - link_object_to_list(&(Cells[address]),obj); - } -} - -/*********************************************************************************************** - * GridCullSystemClass::unlink_object -- unlinks the object from the cell it is in * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::unlink_object(CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - GridLinkClass * link = (GridLinkClass *)obj->Get_Cull_Link(); - - if (link->GridAddress == UNGRIDDED_ADDRESS) { - unlink_object_from_list(&NoGridList,obj); - } else { - unlink_object_from_list(&(Cells[link->GridAddress]),obj); - } -} - - -/*********************************************************************************************** - * GridCullSystemClass::link_object_to_list -- grid list link function * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::link_object_to_list(CullableClass ** head,CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - GridLinkClass * link = (GridLinkClass *)obj->Get_Cull_Link(); - - /* - ** Insert this object as the new head of the list. - */ - link->Next = *head; - link->Prev = NULL; - - if (link->Next != NULL) { - GridLinkClass * next_link = (GridLinkClass *)link->Next->Get_Cull_Link(); - WWASSERT(next_link != NULL); - next_link->Prev = obj; - } - - *head = obj; -} - - -/*********************************************************************************************** - * GridCullSystemClass::unlink_object_from_list -- grid list unlink function * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/2000 gth : Created. * - *=============================================================================================*/ -void GridCullSystemClass::unlink_object_from_list(CullableClass ** head,CullableClass * obj) -{ - WWASSERT(obj); - WWASSERT(obj->Get_Culling_System() == this); - GridLinkClass * link = (GridLinkClass *)obj->Get_Cull_Link(); - - /* - ** check to see that the object is actually in this list - */ -#ifdef WWDEBUG - CullableClass * tmp = *head; - bool found = false; - while (tmp && !found) { - if (tmp == obj) found = true; - tmp = ((GridLinkClass *)(tmp->Get_Cull_Link()))->Next; - } - WWASSERT(found); -#endif - - /* - ** If we were the head of the list, make the head point to the next object - */ - if (obj == *head) { - *head = link->Next; - } - - /* - ** Link the object previous to us to our next... - */ - if (link->Prev) { - GridLinkClass * prev_link = (GridLinkClass *)link->Prev->Get_Cull_Link(); - prev_link->Next = link->Next; - } - - /* - ** Link the objects after us to our previous... - */ - if (link->Next) { - GridLinkClass * next_link = (GridLinkClass *)link->Next->Get_Cull_Link(); - next_link->Prev = link->Prev; - } - - link->Prev = NULL; - link->Next = NULL; -} - - - -/************************************************************************* -** -** GridCullSystem Internal Leaf-iterating collection functions -** -*************************************************************************/ -void GridCullSystemClass::collect_objects_in_leaf(const Vector3 & point,CullableClass * head) -{ - if (head != NULL) { - GridListIterator it(head); - for (;!it.Is_Done(); it.Next()) { - CullableClass * obj = it.Peek_Obj(); - if (obj->Get_Cull_Box ().Contains (point) == true) { - Add_To_Collection(obj); - } - } - } -} - -void GridCullSystemClass::collect_objects_in_leaf(const AABoxClass & box,CullableClass * head) -{ - if (head != NULL) { - GridListIterator it(head); - for (;!it.Is_Done(); it.Next()) { - CullableClass * obj = it.Peek_Obj(); - if (CollisionMath::Overlap_Test(box,obj->Get_Cull_Box()) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - } - } -} - -void GridCullSystemClass::collect_objects_in_leaf(const OBBoxClass & obbox,CullableClass * head) -{ - if (head != NULL) { - GridListIterator it(head); - for (;!it.Is_Done(); it.Next()) { - CullableClass * obj = it.Peek_Obj(); - if (CollisionMath::Overlap_Test(obbox,obj->Get_Cull_Box()) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - } - } -} - -void GridCullSystemClass::collect_objects_in_leaf(const FrustumClass & frustum,CullableClass * head) -{ - if (head != NULL) { - GridListIterator it(head); - for (;!it.Is_Done(); it.Next()) { - CullableClass * obj = it.Peek_Obj(); - if (CollisionMath::Overlap_Test(frustum,obj->Get_Cull_Box()) != CollisionMath::OUTSIDE) { - Add_To_Collection(obj); - } - } - } -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/gridcull.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/gridcull.h deleted file mode 100644 index 2e7bc89abe..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/gridcull.h +++ /dev/null @@ -1,706 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/gridcull.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/10/01 10:42a $* - * * - * $Revision:: 14 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GridCullSystemClass::clamp_indices_to_grid -- constrains indices to be a valid location * - * GridCullSystemClass::map_point_to_cell -- determines which cell the point is in * - * GridCullSystemClass::map_point_to_address -- determines the address of a point in the gri * - * GridCullSystemClass::map_indices_to_address -- computes the address for given index tripl * - * GridCullSystemClass::total_cell_count -- returns the total number of cells in the grid * - * GridCullSystemClass::compute_box -- computes the bounding box for a grid cell * - * GridCullSystemClass::compute_box -- computes bounding box for a range of grid cells * - * GridCullSystemClass::init_volume -- inits volume to contain the given range * - * GridCullSystemClass::init_volume -- inits volume to contain the given line segment * - * GridCullSystemClass::init_volume -- inits volume to contain the given box * - * GridCullSystemClass::init_volume -- inits volume to contain the given oriented box * - * GridCullSystemClass::init_volume -- inits volume to contain the given frustum * - * GridCullSystemClass::VolumeStruct::VolumeStruct -- constructor * - * GridCullSystemClass::VolumeStruct::VolumeStruct -- constructor * - * GridCullSystemClass::VolumeStruct::Is_Leaf -- check if volume is a leaf * - * GridCullSystemClass::VolumeStruct::Is_Empty -- check if volume is empty (or invalid) * - * GridCullSystemClass::VolumeStruct::Split -- split this volume * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#include "cullsys.h" -#include "mempool.h" -#include "frustum.h" -#include "aabox.h" -#include "lineseg.h" -#include "obbox.h" -#include - -class ChunkLoadClass; -class ChunkSaveClass; - -/* -** GridCullSystemClass -** This is a culling system designed for dynamic objects (objects which are moving or -** changing bounding box size). It features O(1) insertion as opposed to -** the AABTree, QuadTree, or Octree insertion times which are O(logn). It's disadvantages -** compared to the above mentioned systems are that it must uniformly divide space. The -** AABTree conforms to the geometry placed in it and can therefore cull things more -** efficiently. In actual use, this system is like an AAB-tree which is uniformly subdivided, -** its just that we can jump straight to the leaves of the tree for insertion... -** -** The bounding volume for each grid cell is considered to be the volume of the cell, expanded -** by the maximum object size. Inserting an object into the grid is a matter of determining -** which cell its center point is in. Objects which are larger than the maximum size are -** allowed but they are simply put into a linked list which is iterated with each call to -** the culling system (linearly culled rather than logarithmic...) -*/ -class GridCullSystemClass : public CullSystemClass -{ - -public: - - GridCullSystemClass(void); - ~GridCullSystemClass(void); - - virtual void Collect_Objects(const Vector3 & point); - virtual void Collect_Objects(const AABoxClass & box); - virtual void Collect_Objects(const OBBoxClass & box); - virtual void Collect_Objects(const FrustumClass & frustum); - - virtual void Re_Partition(const Vector3 & min,const Vector3 & max,float objdim); - virtual void Update_Culling(CullableClass * obj); - - virtual void Load(ChunkLoadClass & cload); - virtual void Save(ChunkSaveClass & csave); - - virtual int Get_Object_Count (void) const { return ObjCount; } - - /* - ** Statistics - */ - struct StatsStruct - { - int NodeCount; - int NodesAccepted; - int NodesTriviallyAccepted; - int NodesRejected; - }; - - void Reset_Statistics(void); - const StatsStruct & Get_Statistics(void); - - void Get_Min_Cell_Size (Vector3 &size) const { size = MinCellSize; } - void Set_Min_Cell_Size (const Vector3 &size) { MinCellSize = size; } - - int Get_Termination_Count (void) const { return TerminationCellCount; } - void Set_Termination_Count (int count) { TerminationCellCount = count; } - -protected: - - void Collect_And_Unlink_All(void); - void Add_Object_Internal(CullableClass * obj); - void Remove_Object_Internal(CullableClass * obj); - - enum - { - TERMINATION_CELL_COUNT = 16384, // algorithm terminates if we ever have more than this many cells. - UNGRIDDED_ADDRESS = 0xFFFFFFFF // address given to objs that didn't fit in grid - }; - - // Constants which control the division of space: - Vector3 MinCellSize; // min dimensions for a cell (don't go below this...) - float MaxObjExtent; // max extent/radius (objects bigger than this are just put in a list) - int TerminationCellCount; - - // Constants that define the division of space - Vector3 Origin; - Vector3 CellDim; - Vector3 OOCellDim; - int CellCount[3]; - - // 3D array of pointers to objects in each cell - CullableClass ** Cells; - - // list of objs that were outside or too big for the grid. - CullableClass * NoGridList; - - // number of objects in the system - int ObjCount; - - // statistics - StatsStruct Stats; - - // Structure used to define a volume in the grid. The volume spans from the cell indexed - // by Min[0],Min[1],Min[2] to the cell indexed by Max[0]-1,Max[1]-1,Max[2]-1. - struct VolumeStruct - { - VolumeStruct(void); - VolumeStruct(int i0,int j0,int k0,int i1,int j1,int k1); - bool Is_Leaf(void) const; - bool Is_Empty(void) const; - void Split(VolumeStruct & v0,VolumeStruct & v1) const; - - int Min[3]; - int Max[3]; - }; - - void link_object(CullableClass * obj); - void link_object(CullableClass * obj,int address); - void unlink_object(CullableClass * obj); - void link_object_to_list(CullableClass ** head,CullableClass * obj); - void unlink_object_from_list(CullableClass ** head,CullableClass * obj); - - bool map_point_to_cell(const Vector3 & pt,int & set_i,int & set_j,int & set_k); - bool map_point_to_address(const Vector3 & pt,int & set_address); - WWINLINE int map_indices_to_address(int i,int j,int k); - void clamp_indices_to_grid(int * i,int * j,int * k); - - int total_cell_count(void); - void compute_box(int i,int j,int k,AABoxClass * set_box); - void compute_box(const VolumeStruct & area, AABoxClass * set_box); - - void init_volume(const Vector3 & bound_min,const Vector3 & bound_max,VolumeStruct * set_volume); - void init_volume(const Vector3 & point,VolumeStruct * set_volume); - void init_volume(const LineSegClass & line,VolumeStruct * set_volume); - void init_volume(const AABoxClass & box,VolumeStruct * set_volume); - void init_volume(const OBBoxClass & box,VolumeStruct * set_volume); - void init_volume(const FrustumClass & frustum,VolumeStruct * set_volume); - - void collect_objects_in_leaf(const Vector3 & point,CullableClass * head); - void collect_objects_in_leaf(const AABoxClass & aabox,CullableClass * head); - void collect_objects_in_leaf(const OBBoxClass & obbox,CullableClass * head); - void collect_objects_in_leaf(const FrustumClass & frustum,CullableClass * head); -}; - -/* -** Macros for gathering statistics. Placed here in the header file so that -** derived classes can use them as well. -*/ -#ifdef WWDEBUG - -#define GRIDCULL_NODE_ACCEPTED Stats.NodesAccepted ++; -#define GRIDCULL_NODE_TRIVIALLY_ACCEPTED Stats.NodesTriviallyAccepted ++; -#define GRIDCULL_NODE_REJECTED Stats.NodesRejected ++; - -#else - -#define GRIDCULL_NODE_ACCEPTED -#define GRIDCULL_NODE_TRIVIALLY_ACCEPTED -#define GRIDCULL_NODE_REJECTED - -#endif - - -/* -** TypedGridCullSystemClass -** This class simply enforces that a certain type of object is inserted into the grid cull system. -** It exposes the add, remove, and collection iterating functions and is intended to be the class -** actually used by the end user. -*/ -template class TypedGridCullSystemClass : public GridCullSystemClass -{ -public: - - virtual void Add_Object(T * obj) { Add_Object_Internal(obj); } - virtual void Remove_Object(T * obj) { Remove_Object_Internal(obj); } - - T * Get_First_Collected_Object(void) { return (T*)Get_First_Collected_Object_Internal(); } - T * Get_Next_Collected_Object(T * obj) { return (T*)Get_Next_Collected_Object_Internal(obj); } - -}; - - -/* -** GridLinkClass -** This structure is used to link cullable objects into a Grid culling system -** This class is should only be used by classes which derive from GridCullSystemClass -** not normal users. -*/ -class GridLinkClass : public CullLinkClass, public AutoPoolClass -{ -public: - GridLinkClass(GridCullSystemClass * system); - virtual ~GridLinkClass(void); - - int GridAddress; // address in the grid. - CullableClass * Prev; // prev object in this cell - CullableClass * Next; // next object in this cell -}; - - -/* -** GridListIterator -** This is just a simple iterator that contains the code for traversing the -** list of objects either in a cell in the grid or in the NoGridList... -** This class should only be used by classes which derive from GridCullSystemClass -** not normal users. -*/ -class GridListIterator -{ -public: - - GridListIterator(CullableClass * head) { First(head); } - - void First(CullableClass * head) { Head = head; CurObj = head; } - void First(void) { CurObj = Head; } - void Next(void) { if (CurObj) { CurObj = ((GridLinkClass *)CurObj->Get_Cull_Link())->Next; } } - void Prev(void) { if (CurObj) { CurObj = ((GridLinkClass *)CurObj->Get_Cull_Link())->Prev; } } - bool Is_Done(void) { return (CurObj == NULL); } - - CullableClass * Get_Obj(void) { if (CurObj) { CurObj->Add_Ref(); } return CurObj; } - CullableClass * Peek_Obj(void) { return CurObj; } - -private: - - CullableClass * Head; // head of the list we're working in - CullableClass * CurObj; // node we're currently at. - -}; - - - -/*********************************************************************************************** - * GridCullSystemClass::clamp_indices_to_grid -- constrains indices to be a valid location * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::clamp_indices_to_grid(int * i,int * j,int * k) -{ - if (*i < 0) *i = 0; - if (*i >= CellCount[0]) *i = CellCount[0] - 1; - if (*j < 0) *j = 0; - if (*j >= CellCount[1]) *j = CellCount[1] - 1; - if (*k < 0) *k = 0; - if (*k >= CellCount[2]) *k = CellCount[2] - 1; -} - - -/*********************************************************************************************** - * GridCullSystemClass::map_point_to_cell -- determines which cell the point is in * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE bool GridCullSystemClass::map_point_to_cell(const Vector3 & pt,int & set_i,int & set_j,int & set_k) -{ - Vector3 dp = pt - Origin; - set_i = floor(dp.X * OOCellDim.X); - set_j = floor(dp.Y * OOCellDim.Y); - set_k = floor(dp.Z * OOCellDim.Z); - - if ( (set_i >= 0) && (set_j >= 0) && (set_k >= 0) && - (set_i < CellCount[0]) && (set_j < CellCount[1]) && (set_k < CellCount[2]) ) - { - return true; - } - return false; -} - - -/*********************************************************************************************** - * GridCullSystemClass::map_point_to_address -- determines the address of a point in the grid * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE bool GridCullSystemClass::map_point_to_address(const Vector3 & pt,int &set_address) -{ - int i,j,k; - bool res = map_point_to_cell(pt,i,j,k); - - if (res) { - set_address = map_indices_to_address(i,j,k); - return true; - } else { - set_address = UNGRIDDED_ADDRESS; - return false; - } -} - - -/*********************************************************************************************** - * GridCullSystemClass::map_indices_to_address -- computes the address for given index triplet * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE int GridCullSystemClass::map_indices_to_address(int i,int j,int k) -{ - return i + j*CellCount[0] + k*CellCount[0]*CellCount[1]; -} - - -/*********************************************************************************************** - * GridCullSystemClass::total_cell_count -- returns the total number of cells in the grid * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE int GridCullSystemClass::total_cell_count(void) -{ - return CellCount[0] * CellCount[1] * CellCount[2]; -} - - -/*********************************************************************************************** - * GridCullSystemClass::compute_box -- computes the bounding box for a grid cell * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::compute_box(int i,int j,int k,AABoxClass * set_box) -{ - WWASSERT(set_box != NULL); - WWASSERT((i >= 0) && (j >= 0) && (k >= 0)); - WWASSERT((i < CellCount[0]) && (j < CellCount[1]) && (k < CellCount[2])); - - Vector3 min,max; - - min.X = Origin.X + i * CellDim.X - MaxObjExtent; - min.Y = Origin.Y + j * CellDim.Y - MaxObjExtent; - min.Z = Origin.Z + k * CellDim.Z - MaxObjExtent; - - max.X = min.X + CellDim.X + 2.0f*MaxObjExtent; - max.Y = min.Y + CellDim.Y + 2.0f*MaxObjExtent; - max.Z = min.Z + CellDim.Z + 2.0f*MaxObjExtent; - - set_box->Init((min+max)*0.5f, (min-max)*0.5f); -} - - -/*********************************************************************************************** - * GridCullSystemClass::compute_box -- computes bounding box for a range of grid cells * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::compute_box(const GridCullSystemClass::VolumeStruct & vol, AABoxClass * set_box) -{ - WWASSERT(set_box != NULL); - WWASSERT((vol.Min[0] >= 0) && (vol.Min[1] >= 0) && (vol.Min[2] >= 0)); - WWASSERT((vol.Max[0] <= CellCount[0]) && (vol.Max[1] <= CellCount[1]) && (vol.Max[2] <= CellCount[2])); - - Vector3 min,max; - - min.X = Origin.X + vol.Min[0] * CellDim.X - MaxObjExtent; - min.Y = Origin.Y + vol.Min[1] * CellDim.Y - MaxObjExtent; - min.Z = Origin.Z + vol.Min[2] * CellDim.Z - MaxObjExtent; - - max.X = Origin.X + vol.Max[0] * CellDim.X + MaxObjExtent; - max.Y = Origin.Y + vol.Max[1] * CellDim.Y + MaxObjExtent; - max.Z = Origin.Z + vol.Max[2] * CellDim.Z + MaxObjExtent; - - Vector3 center((max.X+min.X)*0.5f,(max.Y+min.Y)*0.5f,(max.Z+min.Z)*0.5f); - Vector3 extent((max.X-min.X)*0.5f,(max.Y-min.Y)*0.5f,(max.Z-min.Z)*0.5f); - set_box->Init(center,extent); -} - - -/*********************************************************************************************** - * GridCullSystemClass::init_volume -- inits volume to contain the given range * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::init_volume -( - const Vector3 & bound_min, - const Vector3 & bound_max, - VolumeStruct * set_vol -) -{ - // expand the box by the maximum size of any object - Vector3 grid_min = bound_min; - grid_min.X -= MaxObjExtent; - grid_min.Y -= MaxObjExtent; - grid_min.Z -= MaxObjExtent; - - Vector3 grid_max = bound_max; - grid_max.X += MaxObjExtent; - grid_max.Y += MaxObjExtent; - grid_max.Z += MaxObjExtent; - - // now compute the grid coordinates of the corners of the box - GridCullSystemClass::map_point_to_cell(grid_min,set_vol->Min[0],set_vol->Min[1],set_vol->Min[2]); - GridCullSystemClass::map_point_to_cell(grid_max,set_vol->Max[0],set_vol->Max[1],set_vol->Max[2]); - - // now clamp the volume to the actual grid - clamp_indices_to_grid(&(set_vol->Min[0]),&(set_vol->Min[1]),&(set_vol->Min[2])); - clamp_indices_to_grid(&(set_vol->Max[0]),&(set_vol->Max[1]),&(set_vol->Max[2])); - - // increment the outer edge of the box due to the way we traverse the grid... - set_vol->Max[0] ++; - set_vol->Max[1] ++; - set_vol->Max[2] ++; -} - - -/*********************************************************************************************** - * GridCullSystemClass::init_volume -- inits volume to contain the given line segment * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::init_volume(const LineSegClass & line,VolumeStruct * set_volume) -{ - Vector3 min_pt,max_pt; - min_pt.X = WWMath::Min(line.Get_P0().X,line.Get_P1().X); - max_pt.X = WWMath::Max(line.Get_P0().X,line.Get_P1().X); - min_pt.Y = WWMath::Min(line.Get_P0().Y,line.Get_P1().Y); - max_pt.Y = WWMath::Max(line.Get_P0().Y,line.Get_P1().Y); - min_pt.Z = WWMath::Min(line.Get_P0().Z,line.Get_P1().Z); - max_pt.Z = WWMath::Max(line.Get_P0().Z,line.Get_P1().Z); - init_volume(min_pt,max_pt,set_volume); -} - - -/*********************************************************************************************** - * GridCullSystemClass::init_volume -- inits volume to contain the given box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::init_volume(const AABoxClass & box,VolumeStruct * set_volume) -{ - init_volume(box.Center - box.Extent,box.Center + box.Extent,set_volume); -} - - -/*********************************************************************************************** - * GridCullSystemClass::init_volume -- inits volume to contain the given oriented box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::init_volume(const OBBoxClass & box,VolumeStruct * set_volume) -{ - Vector3 aaextent; - box.Compute_Axis_Aligned_Extent(&aaextent); - init_volume(box.Center - aaextent,box.Center + aaextent,set_volume); -} - - -/*********************************************************************************************** - * GridCullSystemClass::init_volume -- inits volume to contain the given frustum * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::init_volume(const FrustumClass & frustum,VolumeStruct * set_volume) -{ - init_volume(frustum.Get_Bound_Min(),frustum.Get_Bound_Max(),set_volume); -} - - -/*********************************************************************************************** - * GridCullSystemClass::VolumeStruct::VolumeStruct -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -WWINLINE GridCullSystemClass::VolumeStruct::VolumeStruct(void) -{ -} - - -/*********************************************************************************************** - * GridCullSystemClass::VolumeStruct::VolumeStruct -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE GridCullSystemClass::VolumeStruct::VolumeStruct(int i0,int j0,int k0,int i1,int j1,int k1) -{ - Min[0] = i0; - Min[1] = j0; - Min[2] = k0; - Max[0] = i1; - Max[1] = j1; - Max[2] = k1; - WWASSERT(Max[0] > Min[0]); - WWASSERT(Max[1] > Min[1]); - WWASSERT(Max[2] > Min[2]); -} - - -/*********************************************************************************************** - * GridCullSystemClass::VolumeStruct::Is_Leaf -- check if volume is a leaf * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE bool GridCullSystemClass::VolumeStruct::Is_Leaf(void) const -{ - return ((Max[0]-Min[0] == 1) && (Max[1]-Min[1] == 1) && (Max[2]-Min[2] == 1)); -} - - -/*********************************************************************************************** - * GridCullSystemClass::VolumeStruct::Is_Empty -- check if volume is empty (or invalid) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE bool GridCullSystemClass::VolumeStruct::Is_Empty(void) const -{ - return ((Max[0]-Min[0] <= 0) || (Max[1]-Min[1] <= 0) || (Max[2]-Min[2] <= 0)); -} - - -/*********************************************************************************************** - * GridCullSystemClass::VolumeStruct::Split -- split this volume * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void GridCullSystemClass::VolumeStruct::Split(VolumeStruct & v0,VolumeStruct & v1) const -{ - // find the longest dimension - int split_axis = 0; - int delta[3]; - - delta[0] = Max[0] - Min[0]; - delta[1] = Max[1] - Min[1]; - delta[2] = Max[2] - Min[2]; - - if (delta[1] > delta[split_axis]) split_axis = 1; - if (delta[2] > delta[split_axis]) split_axis = 2; - - WWASSERT(delta[split_axis] > 0); - - // split the volume perpendicularly to that dimension - memcpy(&v0,this,sizeof(VolumeStruct)); - memcpy(&v1,this,sizeof(VolumeStruct)); - - v0.Max[split_axis] = v1.Min[split_axis] = Min[split_axis] + (delta[split_axis] >> 1); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/hermitespline.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/hermitespline.cpp deleted file mode 100644 index 77cda843ee..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/hermitespline.cpp +++ /dev/null @@ -1,437 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/hermitespline.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "hermitespline.h" -#include "wwmathids.h" -#include "persistfactory.h" -#include "wwhack.h" - - -/* -** Force-Link this module because the linker can't detect that we actually need it... -*/ -DECLARE_FORCE_LINK(hermitespline); - -/* -** Save-Load stuff -*/ -SimplePersistFactoryClass _HermiteSpline3DFactory; -SimplePersistFactoryClass _HermiteSpline1DFactory; - -enum -{ - // ID's used by HermiteSpline3D - HERMITE3D_CHUNK_CURVE3D = 0x00020727, - HERMITE3D_CHUNK_TANGENTS, - - // ID's used by HermiteSpline1D - HERMITE1D_CHUNK_CURVE1D = 0x00020729, - HERMITE1D_CHUNK_TANGENTS, -}; - - -/* -** Hermite Spline -*/ -const HermiteSpline3DClass &HermiteSpline3DClass::operator= (const HermiteSpline3DClass &that) -{ - // - // This is included for completeness only, it basically - // implements the default bitwise copy operator. - // - TangentsDirty = that.TangentsDirty; - Tangents = that.Tangents; - Curve3DClass::operator= (that); - return (*this); -} - -void HermiteSpline3DClass::Set_Looping(bool onoff) -{ - if (onoff != IsLooping) { - Curve3DClass::Set_Looping(onoff); - TangentsDirty = true; - } -} - -void HermiteSpline3DClass::Evaluate(float time,Vector3 * set_val) -{ - // if we're outside the range, return the start or end... - if (time < Keys[0].Time) { - *set_val = Keys[0].Point; - return; - } - - if (time > Keys[Keys.Count() - 1].Time) { - *set_val = Keys[Keys.Count() - 1].Point; - return; - } - - // if the tangents are marked dirty, give derived classes a chance to recompute them - if (TangentsDirty) { - Update_Tangents(); - } - - // ok find the segment - int i0,i1; - float t; - Find_Interval(time,&i0,&i1,&t); - - float t2 = t*t; - float t3 = t2*t; - - // hermite basis functions: - float h0 = 2*t3 - 3*t2 + 1; - float h1 = -2*t3 + 3*t2; - float h2 = t3 - 2*t2 + t; - float h3 = t3 - t2; - - set_val->X = h0*Keys[i0].Point.X + h1*Keys[i1].Point.X + - h2*Tangents[i0].OutTangent.X + h3*Tangents[i1].InTangent.X; - - set_val->Y = h0*Keys[i0].Point.Y + h1*Keys[i1].Point.Y + - h2*Tangents[i0].OutTangent.Y + h3*Tangents[i1].InTangent.Y; - - set_val->Z = h0*Keys[i0].Point.Z + h1*Keys[i1].Point.Z + - h2*Tangents[i0].OutTangent.Z + h3*Tangents[i1].InTangent.Z; -} - -void HermiteSpline3DClass::Evaluate_Derivative(float time,Vector3 * set_val) -{ - // if we're outside the range, return the value for the start or end... - float min_time = Keys[0].Time; - float max_time = Keys[Keys.Count() - 1].Time; - time = MAX(time, min_time); - time = MIN(time, max_time); - - // if the tangents are marked dirty, give derived classes a chance to recompute them - if (TangentsDirty) { - Update_Tangents(); - } - - // ok find the segment - int i0,i1; - float t; - Find_Interval(time,&i0,&i1,&t); - - float t2 = t*t; - - // derivatives of hermite basis functions: - float dh0 = 6*t2 - 6*t; - float dh1 = -6*t2 + 6*t; - float dh2 = 3*t2 - 4*t + 1; - float dh3 = 3*t2 - 2*t; - - set_val->X = dh0*Keys[i0].Point.X + dh1*Keys[i1].Point.X + - dh2*Tangents[i0].OutTangent.X + dh3*Tangents[i1].InTangent.X; - - set_val->Y = dh0*Keys[i0].Point.Y + dh1*Keys[i1].Point.Y + - dh2*Tangents[i0].OutTangent.Y + dh3*Tangents[i1].InTangent.Y; - - set_val->Z = dh0*Keys[i0].Point.Z + dh1*Keys[i1].Point.Z + - dh2*Tangents[i0].OutTangent.Z + dh3*Tangents[i1].InTangent.Z; -} - -void HermiteSpline3DClass::Set_Key(int i,const Vector3 & point) -{ - Curve3DClass::Set_Key(i,point); - TangentsDirty = true; -} - -int HermiteSpline3DClass::Add_Key(const Vector3 & point,float t) -{ - int index = Curve3DClass::Add_Key(point,t); - TangentsDirty = true; - TangentsClass tan; - tan.InTangent.Set(0,0,0); - tan.OutTangent.Set(0,0,0); - Tangents.Insert(index,tan); - return index; -} - -void HermiteSpline3DClass::Remove_Key(int i) -{ - Tangents.Delete(i); - Curve3DClass::Remove_Key(i); - TangentsDirty = true; -} - -void HermiteSpline3DClass::Clear_Keys(void) -{ - Tangents.Clear(); - Curve3DClass::Clear_Keys(); - TangentsDirty = true; -} - -void HermiteSpline3DClass::Set_Tangents(int i,const Vector3 & in_tan,const Vector3 & out_tan) -{ - assert(i>=0); - assert(i=0); - assert(i Keys[Keys.Count() - 1].Time) { - *set_val = Keys[Keys.Count() - 1].Point; - return; - } - } - - // if the tangents are marked dirty, give derived classes a chance to recompute them - if (TangentsDirty) { - Update_Tangents(); - } - - // ok find the segment - int i0,i1; - float t; - Find_Interval(time,&i0,&i1,&t); - - float t2 = t*t; - float t3 = t2*t; - - // hermite basis functions: - float h0 = 2*t3 - 3*t2 + 1; - float h1 = -2*t3 + 3*t2; - float h2 = t3 - 2*t2 + t; - float h3 = t3 - t2; - - *set_val = h0*Keys[i0].Point + h1*Keys[i1].Point + - h2*Tangents[i0].OutTangent + h3*Tangents[i1].InTangent; -} - -void HermiteSpline1DClass::Set_Key(int i,float point,unsigned int extra) -{ - Curve1DClass::Set_Key(i,point,extra); - TangentsDirty = true; -} - -int HermiteSpline1DClass::Add_Key(float point,float t,unsigned int extra) -{ - int index = Curve1DClass::Add_Key(point,t,extra); - TangentsDirty = true; - TangentsClass tan; - tan.InTangent = 0.0f; - tan.OutTangent = 0.0f; - Tangents.Insert(index,tan); - return index; -} - -void HermiteSpline1DClass::Remove_Key(int i) -{ - Tangents.Delete(i); - Curve1DClass::Remove_Key(i); - TangentsDirty = true; -} - -void HermiteSpline1DClass::Clear_Keys(void) -{ - Tangents.Clear(); - Curve1DClass::Clear_Keys(); - TangentsDirty = true; -} - -void HermiteSpline1DClass::Set_Tangents(int i,float in_tan,float out_tan) -{ - assert(i>=0); - assert(i=0); - assert(i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/hermitespline.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef HERMITE_H -#define HERMITE_H - -#include "curve.h" - -/* -** HermiteSpline3DClass -** 3-Dimensional hermite spline interpolation -** Hermite splines require you to input all of the tangents... -*/ -class HermiteSpline3DClass : public Curve3DClass -{ -public: - HermiteSpline3DClass(void) - : TangentsDirty (true) { } - - HermiteSpline3DClass(const HermiteSpline3DClass &that) - : TangentsDirty (true) { (*this) = that; } - - const HermiteSpline3DClass &operator= (const HermiteSpline3DClass &that); - - virtual void Evaluate(float time,Vector3 * set_val); - virtual void Evaluate_Derivative(float time,Vector3 * set_val); - virtual void Set_Looping(bool onoff); - - virtual void Set_Key(int i,const Vector3 & point); - virtual int Add_Key(const Vector3 & point,float t); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - - virtual void Set_Tangents(int i,const Vector3 & in_tan,const Vector3 & out_tan); - virtual void Get_Tangents(int i,Vector3 * set_in,Vector3 * set_out); - - virtual void Update_Tangents(void) { TangentsDirty = false; } - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); - -protected: - - class TangentsClass - { - public: - Vector3 InTangent; - Vector3 OutTangent; - bool operator == (const TangentsClass & that) { return ((InTangent == that.InTangent) && (OutTangent == that.OutTangent)); } - bool operator != (const TangentsClass & that) { return !TangentsClass::operator == (that); } - }; - - bool TangentsDirty; - DynamicVectorClass Tangents; -}; - - -/* -** HermiteSpline1DClass -** 1-Dimensional hermite spline interpolation -** Hermite splines require you to input all of the tangents... -*/ -class HermiteSpline1DClass : public Curve1DClass -{ -public: - HermiteSpline1DClass (void) - : TangentsDirty (true) { } - - virtual void Evaluate(float time,float * set_val); - virtual void Set_Looping(bool onoff); - - virtual void Set_Key(int i,float point,unsigned int extra=0); - virtual int Add_Key(float point,float t,unsigned int extra=0); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - - virtual void Set_Tangents(int i,float in_tan,float out_tan); - virtual void Get_Tangents(int i,float * set_in,float * set_out); - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); - -protected: - - class TangentsClass - { - public: - float InTangent; - float OutTangent; - bool operator == (const TangentsClass & that) { return ((InTangent == that.InTangent) && (OutTangent == that.OutTangent)); } - bool operator != (const TangentsClass & that) { return !TangentsClass::operator == (that); } - }; - - virtual void Update_Tangents(void) { TangentsDirty = false; } - - bool TangentsDirty; - DynamicVectorClass Tangents; -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/lineseg.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/lineseg.cpp deleted file mode 100644 index 88fec4e9ca..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/lineseg.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/lineseg.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 3/16/00 3:16p $* - * * - * $Revision:: 25 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * LineSegClass::Set -- Initialize this 'lineseg' by transforming another 'lineseg' * - * LineSegClass::Set_Random -- create a random linesegment within the given space * - * LineSegClass::Find_Point_Closest_To -- Finds point on line closest to point supplied. * - * LineSegClass::Find_Intersection -- Finds the closest points on the two lines * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "lineseg.h" -//#include - -#include "matrix3d.h" - -/*********************************************************************************************** - * LineSegClass::Set -- Initialize this 'lineseg' by transforming another 'lineseg' * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/17/98 GTH : Created. * - *=============================================================================================*/ -void LineSegClass::Set(const LineSegClass & that,const Matrix3D & tm) -{ - /* - ** Transform P0 and P1 - */ - Matrix3D::Transform_Vector(tm,that.P0,&P0); - Matrix3D::Transform_Vector(tm,that.P1,&P1); - - /* - ** Just calculate DP - */ - DP = P1 - P0; - - /* - ** Rotate the direction vector - */ - Matrix3D::Rotate_Vector(tm,that.Dir,&Dir); - - /* - ** Length should be un-changed - */ - Length = that.Length; -} - -/*********************************************************************************************** - * LineSegClass::Set_Random -- create a random linesegment within the given space * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/21/98 GTH : Created. * - *=============================================================================================*/ -void LineSegClass::Set_Random(const Vector3 & min,const Vector3 & max) -{ - float frac; - - frac = WWMath::Random_Float(); - P0.X = min.X + frac * (max.X - min.X); - frac = WWMath::Random_Float(); - P0.Y = min.Y + frac * (max.Y - min.Y); - frac = WWMath::Random_Float(); - P0.Z = min.Z + frac * (max.Z - min.Z); - - frac = WWMath::Random_Float(); - P1.X = min.X + frac * (max.X - min.X); - frac = WWMath::Random_Float(); - P1.Y = min.Y + frac * (max.Y - min.Y); - frac = WWMath::Random_Float(); - P1.Z = min.Z + frac * (max.Z - min.Z); - - DP = P1 - P0; - Dir = DP; - Dir.Normalize(); - Length = DP.Length(); -} - - - - -/*********************************************************************************************** - * LineSegClass::Find_Point_Closest_To -- Finds point on line closest to point supplied. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/26/1999 SKB : Created. * - *=============================================================================================*/ -Vector3 LineSegClass::Find_Point_Closest_To(const Vector3 &pos) const -{ - // Get a vector from one line endpoint to point in question. - Vector3 v_0_pos = (pos - P0); - float dotprod = Vector3::Dot_Product(Dir, v_0_pos); - - // Check to see if point is past either of the endpoints. - // (Unable to draw a perpendicular line from the point to the line segment.) - if (dotprod <= 0.0) { - return(P0); - } else if (dotprod >= Length) { - return(P1); - } - - // Find point on line seg that is closest to pos passed in. - Vector3 point = P0 + (dotprod * Dir); - return(point); -} - - -/*********************************************************************************************** - * LineSegClass::Find_Intersection -- Finds the closest points on the two lines.. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/03/2000 PDS : Created. * - *=============================================================================================*/ -bool -LineSegClass::Find_Intersection -( - const LineSegClass & other_line, - Vector3 * p1, - float * fraction1, - Vector3 * p2, - float * fraction2 -) const -{ - bool retval = false; - -#ifdef ALLOW_TEMPORARIES - Vector3 cross1 = Vector3::Cross_Product (Dir, other_line.Dir); - Vector3 cross2 = Vector3::Cross_Product (other_line.P0 - P0, other_line.Dir); - float top1 = cross2 * cross1; - float bottom1 = cross1 * cross1; - - Vector3 cross3 = Vector3::Cross_Product (other_line.Dir, Dir); - Vector3 cross4 = Vector3::Cross_Product (P0 - other_line.P0, Dir); - float top2 = cross4 * cross3; - float bottom2 = cross3 * cross3; -#else - Vector3 cross1, cross2, cross3, cross4; - - Vector3::Cross_Product(Dir, other_line.Dir, &cross1); - Vector3::Cross_Product(other_line.P0 - P0, other_line.Dir, &cross2); - float top1 = Vector3::Dot_Product(cross2, cross1); - float bottom1 = Vector3::Dot_Product(cross1, cross1); - - Vector3::Cross_Product(other_line.Dir, Dir, &cross3); - Vector3::Cross_Product(P0 - other_line.P0, Dir, &cross4); - float top2 = Vector3::Dot_Product(cross4, cross3); - float bottom2 = Vector3::Dot_Product(cross3, cross3); -#endif - - // - // If either of the divisors are 0, then the lines are parallel - // - if (bottom1 != 0 && bottom2 != 0) { - float length1 = top1 / bottom1; - float length2 = top2 / bottom2; - - // - // Calculate the closest points on both lines. - // Note: If the points are the same, then the lines intersect. - // - (*p1) = P0 + (Dir * length1); - (*p2) = other_line.P0 + (other_line.Dir * length2); - - // - // Return the fractions if they caller wants them - // - if (fraction1 != NULL) { - (*fraction1) = length1 / Length; - } - - if (fraction2 != NULL) { - (*fraction2) = length2 / Length; - } - - retval = true; - } - - return retval; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/lineseg.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/lineseg.h deleted file mode 100644 index d0b7ee79f1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/lineseg.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/lineseg.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 3/16/00 3:16p $* - * * - * $Revision:: 21 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef LINESEG_H -#define LINESEG_H - -#include "always.h" -#include "vector3.h" -#include "castres.h" - -class TriClass; -class AABoxClass; -class OBBoxClass; -class PlaneClass; -class SphereClass; -class Matrix3D; - - -class LineSegClass -{ - -public: - - LineSegClass(void) { } - LineSegClass(const Vector3 & p0,const Vector3 & p1) : P0(p0), P1(p1) { recalculate(); } - LineSegClass(const LineSegClass & that,const Matrix3D & tm) { Set(that,tm); } - - void Set(const Vector3 & p0,const Vector3 & p1) { P0 = p0; P1 = p1; recalculate(); } - void Set(const LineSegClass & that,const Matrix3D & tm); - void Set_Random(const Vector3 & min,const Vector3 & max); - - const Vector3 & Get_P0() const { return P0; } // start point - const Vector3 & Get_P1() const { return P1; } // end point - const Vector3 & Get_DP() const { return DP; } // difference of the two points - const Vector3 & Get_Dir() const { return Dir; } // normalized direction. - float Get_Length() const { return Length; } // length of the segment - - void Compute_Point(float t,Vector3 * set) const { Vector3::Add(P0,t*DP,set); } - - Vector3 Find_Point_Closest_To(const Vector3 &pos) const; - bool Find_Intersection (const LineSegClass &other_line, Vector3 *p1, float *fraction1, Vector3 *p2, float *fraction2) const; - -protected: - - void recalculate(void) { DP = P1 - P0; Dir = DP; Dir.Normalize(); Length = DP.Length(); } - - Vector3 P0; // start point - Vector3 P1; // end point - Vector3 DP; // difference of the two points - Vector3 Dir; // normalized direction. - float Length; // length of the segment -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/lookuptable.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/lookuptable.cpp deleted file mode 100644 index 4608cfbb75..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/lookuptable.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWPhys * - * * - * $Archive:: /Commando/Code/wwmath/lookuptable.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Byon_g $* - * * - * $Modtime:: 7/23/01 6:18p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "lookuptable.h" -#include "curve.h" -#include "WWFILE.H" -#include "ffactory.h" -#include "chunkio.h" -#include "persistfactory.h" -#include "vector2.h" - - -/* -** Static members -*/ -RefMultiListClass LookupTableMgrClass::Tables; - -/* -** Save-Load stuff. Lookup tables are basically saved 1D curve classes. They are turned -** into tables at load time. For future expansion, the curve is wrapped in a chunk. -*/ -enum -{ - LOOKUPTABLE_CHUNK_CURVE = 03071200, - LOOKUPTABLE_CHUNK_EXTENTS, -}; - - -/*********************************************************************************************** -** -** LookupTableClass Implementation -** -***********************************************************************************************/ -LookupTableClass::LookupTableClass(int sample_count) : - MinInputValue(0.0f), - MaxInputValue(0.0f), - OutputSamples(sample_count) -{ -} - -LookupTableClass::~LookupTableClass(void) -{ -} - -void LookupTableClass::Init(const char * name,Curve1DClass * curve) -{ - // copy the name - Name = name; - - // Store the min and max input values for the table - curve->Get_Key(0,NULL,&MinInputValue,NULL); - curve->Get_Key(curve->Key_Count()-1,NULL,&MaxInputValue,NULL); - OOMaxMinusMin = 1.0f / (MaxInputValue - MinInputValue); - - // Sample the curve and store the output values - for (int i=0; iEvaluate(x,&y); - OutputSamples[i] = y; - } -} - - - -/*********************************************************************************************** -** -** LookupTableManager Implementation -** -***********************************************************************************************/ -void LookupTableMgrClass::Init(void) -{ - // create a default table that the user can use in an emergency - LookupTableClass * default_table = NEW_REF(LookupTableClass,(2)); - LinearCurve1DClass * default_curve = W3DNEW LinearCurve1DClass; - - default_curve->Add_Key(0.5f,0.0f); - default_curve->Add_Key(0.5f,1.0f); - default_table->Init("DefaultTable",default_curve); - Add_Table(default_table); - - delete default_curve; - default_table->Release_Ref(); -} - -void LookupTableMgrClass::Shutdown(void) -{ - Reset(); -} - -void LookupTableMgrClass::Reset(void) -{ - while (Tables.Peek_Head() != NULL) { - Tables.Release_Head(); - } -} - -bool LookupTableMgrClass::Add_Table(LookupTableClass * table) -{ - return Tables.Add(table); -} - -bool LookupTableMgrClass::Remove_Table(LookupTableClass * table) -{ - return Tables.Remove(table); -} - -LookupTableClass * LookupTableMgrClass::Get_Table(const char * name,bool try_to_load) -{ - // check if we already have this table loaded... - RefMultiListIterator it(&Tables); - for (it.First(); !it.Is_Done(); it.Next()) { - if (stricmp(it.Peek_Obj()->Get_Name(),name) == 0) { - return it.Get_Obj(); // add a reference for the user... - } - } - - // otherwise we can try to load it. - LookupTableClass * new_table = NULL; - if (try_to_load) { - - FileClass * file = _TheFileFactory->Get_File(name); - if (file && file->Open()) { - - ChunkLoadClass cload(file); - - Curve1DClass * curve = NULL; - Load_Table_Desc(cload,&curve); - if (curve != NULL) { - new_table = NEW_REF(LookupTableClass,()); - new_table->Init(name,curve); - Add_Table(new_table); - delete curve; - } - } - _TheFileFactory->Return_File(file); - } - - return new_table; // constructor ref is returned to user. -} - -void LookupTableMgrClass::Save_Table_Desc -( - ChunkSaveClass & csave, - Curve1DClass * curve, - const Vector2 & min_corner, - const Vector2 & max_corner -) -{ - // save the curve - csave.Begin_Chunk(LOOKUPTABLE_CHUNK_CURVE); - csave.Begin_Chunk(curve->Get_Factory().Chunk_ID()); - curve->Get_Factory().Save(csave,curve); - csave.End_Chunk(); - csave.End_Chunk(); - - // save the extents - csave.Begin_Chunk(LOOKUPTABLE_CHUNK_EXTENTS); - csave.Write(&(min_corner.X),sizeof(float)); - csave.Write(&(min_corner.Y),sizeof(float)); - csave.Write(&(max_corner.X),sizeof(float)); - csave.Write(&(max_corner.Y),sizeof(float)); - csave.End_Chunk(); -} - -void LookupTableMgrClass::Load_Table_Desc -( - ChunkLoadClass & cload, - Curve1DClass ** curve_ptr, - Vector2 * set_min_corner, - Vector2 * set_max_corner -) -{ - *curve_ptr = NULL; - PersistFactoryClass * factory; - - float xmin,xmax; - float ymin,ymax; - xmin = xmax = ymin = ymax = 0.0f; - - while (cload.Open_Chunk()) { - switch(cload.Cur_Chunk_ID()) { - case LOOKUPTABLE_CHUNK_CURVE: - cload.Open_Chunk(); - factory = SaveLoadSystemClass::Find_Persist_Factory(cload.Cur_Chunk_ID()); - WWASSERT(factory != NULL); - if (factory != NULL) { - *curve_ptr = (Curve1DClass *)factory->Load(cload); - } - cload.Close_Chunk(); - break; - case LOOKUPTABLE_CHUNK_EXTENTS: - cload.Read(&xmin,sizeof(xmin)); - cload.Read(&ymin,sizeof(ymin)); - cload.Read(&xmax,sizeof(xmax)); - cload.Read(&ymax,sizeof(ymax)); - break; - - default: - WWDEBUG_SAY(("Unhandled Chunk: 0x%X File: %s Line: %d\r\n",__FILE__,__LINE__)); - break; - } - cload.Close_Chunk(); - } - - if (set_min_corner != NULL) { - set_min_corner->Set(xmin,ymin); - } - if (set_max_corner != NULL) { - set_max_corner->Set(xmax,ymax); - } -} - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/lookuptable.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/lookuptable.h deleted file mode 100644 index 33b70ee8e1..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/lookuptable.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWPhys * - * * - * $Archive:: /Commando/Code/wwmath/lookuptable.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 4/18/00 1:20p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef LOOKUPTABLE_H -#define LOOKUPTABLE_H - -#include "always.h" -#include "simplevec.h" -#include "wwstring.h" -#include "refcount.h" -#include "multilist.h" -#include "wwmath.h" - - -class Vector2; -class Curve1DClass; -class ChunkSaveClass; -class ChunkLoadClass; - - -/** -** LookupTableClass -** This class contains the tabulated values for a function. -*/ -class LookupTableClass : public RefCountClass, public MultiListObjectClass -{ -public: - - LookupTableClass(int sample_count = 256); - virtual ~LookupTableClass(void); - - void Init(const char * name,Curve1DClass * curve); - float Get_Value(float input); - float Get_Value_Quick(float input); - const char * Get_Name(void) { return Name; } -protected: - - StringClass Name; // name of this table, if it came from a file, this is also the filename - float MinInputValue; - float MaxInputValue; - float OOMaxMinusMin; - SimpleVecClass OutputSamples; - -}; - -inline float LookupTableClass::Get_Value(float input) -{ - if (input <= MinInputValue) { - return OutputSamples[0]; - } - if (input >= MaxInputValue) { - return OutputSamples[OutputSamples.Length()-1]; - } - - float normalized_input = (float)(OutputSamples.Length()-1) * (input - MinInputValue) * OOMaxMinusMin; - float input0 = WWMath::Floor(normalized_input); - - int index0 = WWMath::Float_To_Long(input0); - int index1 = index0+1; - float lerp = normalized_input - input0; - - return OutputSamples[index0] + lerp * (OutputSamples[index1] - OutputSamples[index0]); -} - -inline float LookupTableClass::Get_Value_Quick(float input) -{ - if (input <= MinInputValue) { - return OutputSamples[0]; - } - if (input >= MaxInputValue) { - return OutputSamples[OutputSamples.Length()-1]; - } - - int index = (OutputSamples.Length()-1) * WWMath::Float_To_Long((input - MinInputValue) * OOMaxMinusMin); - return OutputSamples[index]; -} - - -/** -** LookupTableMgrClass -** This class tracks all of the LookupTableClass's that have been loaded or installed. -** LookupTables can be created using the "SimpleGraph" tool. It basically allows you -** to edit a curve which will be used to generate the table. These curves are stored -** in .TBL files. -** -** NOTE: Use the SimpleGraph program to create lookup tables! Then just ask for them -** by filename and it will load the table for you (unless it is already loaded). -** -** NOTE: I add a table called "DefaultTable" so that you can revert to that if -** your table isn't found. -*/ -class LookupTableMgrClass -{ -public: - LookupTableMgrClass(void); - ~LookupTableMgrClass(void); - - // init and shutdown are automatically called from WWMath::Init, WWMath::Shutdown... - static void Init(void); - static void Shutdown(void); - - static bool Add_Table(LookupTableClass * table); - static bool Remove_Table(LookupTableClass * table); - static LookupTableClass * Get_Table(const char * name,bool try_to_load = true); - - static void Save_Table_Desc( ChunkSaveClass & csave, - Curve1DClass * curve, - const Vector2 & min, - const Vector2 & max ); - - static void Load_Table_Desc( ChunkLoadClass & cload, - Curve1DClass ** curve_ptr, - Vector2 * set_min = NULL, - Vector2 * set_max = NULL ); - - static void Reset(void); - -protected: - - static RefMultiListClass Tables; - -}; - - -#endif // LOOKUPTABLE_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3.cpp deleted file mode 100644 index 70cbfbf07c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/matrix3.cpp $* - * * - * Org Author:: Greg_h * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 17 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "matrix3.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "quat.h" - - -/* -** Some pre-initialized Matrix3x3's -*/ -const Matrix3x3 Matrix3x3::Identity -( - 1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0 -); - -const Matrix3x3 Matrix3x3::RotateX90 -( - 1.0, 0.0, 0.0, - 0.0, 0.0, -1.0, - 0.0, 1.0, 0.0 -); - -const Matrix3x3 Matrix3x3::RotateX180 -( - 1.0, 0.0, 0.0, - 0.0, -1.0, 0.0, - 0.0, 0.0, -1.0 -); - -const Matrix3x3 Matrix3x3::RotateX270 -( - 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, - 0.0, -1.0, 0.0 -); - -const Matrix3x3 Matrix3x3::RotateY90 -( - 0.0, 0.0, 1.0, - 0.0, 1.0, 0.0, - -1.0, 0.0, 0.0 -); - -const Matrix3x3 Matrix3x3::RotateY180 -( - -1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, -1.0 -); - -const Matrix3x3 Matrix3x3::RotateY270 -( - 0.0, 0.0, -1.0, - 0.0, 1.0, 0.0, - 1.0, 0.0, 0.0 -); - -const Matrix3x3 Matrix3x3::RotateZ90 -( - 0.0, -1.0, 0.0, - 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0 -); - -const Matrix3x3 Matrix3x3::RotateZ180 -( - -1.0, 0.0, 0.0, - 0.0, -1.0, 0.0, - 0.0, 0.0, 1.0 -); - -const Matrix3x3 Matrix3x3::RotateZ270 -( - 0.0, 1.0, 0.0, - -1.0, 0.0, 0.0, - 0.0, 0.0, 1.0 -); - - - -/*********************************************************************************************** - * Matrix3x3::Matrix3x3 -- Convert a Matrix3D (fake 4x4) to a Matrix3x3 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -Matrix3x3::Matrix3x3(const Matrix3D & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -Matrix3x3::Matrix3x3(const Matrix4x4 & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -void Matrix3x3::Set(const Matrix3D & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -void Matrix3x3::Set(const Matrix4x4 & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -void Matrix3x3::Set(const Quaternion & q) -{ - Row[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - Row[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - Row[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - Row[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - Row[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - Row[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - Row[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - Row[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - Row[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); -} - - -Matrix3x3 & Matrix3x3::operator = (const Matrix3D & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); - return *this; -} - -Matrix3x3 & Matrix3x3::operator = (const Matrix4x4 & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); - return *this; -} - -void Matrix3x3::Multiply(const Matrix3D & a, const Matrix3x3 & b,Matrix3x3 * res) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - - #undef ROWCOL -} - -void Matrix3x3::Multiply(const Matrix3x3 & a, const Matrix3D & b,Matrix3x3 * res) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - - #undef ROWCOL -} - -Matrix3x3 operator * (const Matrix3D & a, const Matrix3x3 & b) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - return Matrix3x3( - Vector3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2) ), - Vector3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2) ), - Vector3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2) ) - ); - - #undef ROWCOL -} - -Matrix3x3 operator * (const Matrix3x3 & a, const Matrix3D & b) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - return Matrix3x3( - Vector3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2) ), - Vector3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2) ), - Vector3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2) ) - ); - - #undef ROWCOL -} - - -#if 0 - -void Matrix3x3::Compute_Jacobi_Rotation(int i,int j,Matrix3x3 * r,Matrix3x3 * rinv) -{ - -} - -void Matrix3x3::Symmetric_Eigen_Solve(void) -{ - Matrix3x3 eigen_vals = *this; - Matrix3x3 eigen_vecs(1); - - Matrix3x3 jr,jrinv; - - while (!done) { - eigen_vals.Compute_Jacobi_Rotation(i,j,&jr,&jrinv); - eigen_vals = jr * (eigenvals) * jrinv; - eigen_vecs = eigen_vecs * jr; - } - - /* - ** Done! Eigen values are the diagonals of - ** the eigen_vals matrix and the eigen vectors - ** are the columns of the eigen_vecs matrix - */ - -} - -#endif - - -void Matrix3x3::Multiply(const Matrix3x3 & A,const Matrix3x3 & B,Matrix3x3 * set_res) -{ - Matrix3x3 tmp; - Matrix3x3 * Aptr; - float tmp1,tmp2,tmp3; - - // Check for aliased parameters, copy the 'A' matrix into a temporary if the - // result is going into 'A'. (in this case, this function is no better than - // the overloaded C++ operator...) - if (set_res == &A) { - tmp = A; - Aptr = &tmp; - } else { - Aptr = (Matrix3x3 *)&A; - } - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - (*set_res)[0][0] = (float)((*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3); - (*set_res)[1][0] = (float)((*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3); - (*set_res)[2][0] = (float)((*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3); - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - (*set_res)[0][1] = (float)((*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3); - (*set_res)[1][1] = (float)((*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3); - (*set_res)[2][1] = (float)((*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3); - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - (*set_res)[0][2] = (float)((*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3); - (*set_res)[1][2] = (float)((*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3); - (*set_res)[2][2] = (float)((*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3); -} - -int Matrix3x3::Is_Orthogonal(void) const -{ - Vector3 x(Row[0].X,Row[0].Y,Row[0].Z); - Vector3 y(Row[1].X,Row[1].Y,Row[1].Z); - Vector3 z(Row[2].X,Row[2].Y,Row[2].Z); - - if (Vector3::Dot_Product(x,y) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(y,z) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(z,x) > WWMATH_EPSILON) return 0; - - if (WWMath::Fabs(x.Length() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(y.Length() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(z.Length() - 1.0f) > WWMATH_EPSILON) return 0; - - return 1; -} - -void Matrix3x3::Re_Orthogonalize(void) -{ - Vector3 x(Row[0][0],Row[0][1],Row[0][2]); - Vector3 y(Row[1][0],Row[1][1],Row[1][2]); - Vector3 z; - - Vector3::Cross_Product(x,y,&z); - Vector3::Cross_Product(z,x,&y); - - float len = x.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - x /= len; - } - - len = y.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - y /= len; - } - - len = z.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - z /= len; - } - - Row[0][0] = x.X; - Row[0][1] = x.Y; - Row[0][2] = x.Z; - - Row[1][0] = y.X; - Row[1][1] = y.Y; - Row[1][2] = y.Z; - - Row[2][0] = z.X; - Row[2][1] = z.Y; - Row[2][2] = z.Z; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3.h deleted file mode 100644 index a2c447de01..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3.h +++ /dev/null @@ -1,1032 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/matrix3.h 36 5/11/01 7:11p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * File Name : MATRIX3.H * - * * - * Org Programmer : Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * Start Date : 06/02/97 * - * * - * Last Update : June 6, 2002 [KM] * - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix3x3::Matrix3x3 -- Constructor, optionally initialize to Identitiy matrix * - * Matrix3x3::Matrix3x3 -- Copy Constructor * - * Matrix3x3::Matrix3x3 -- Convert a Matrix3D (fake 4x4) to a Matrix3x3 * - * Matrix3x3::Matrix3x3 -- Constructor * - * Matrix3x3::Transpose -- Returns transpose of the matrix * - * Matrix3x3::Inverse -- returns the inverse of the matrix * - * Matrix3x3::Determinant -- returns the determinant of the matrix * - * Matrix3x3::operator = -- assignment operator * - * Matrix3x3::operator += -- "plus equals" operator * - * Matrix3x3::operator-= -- "minus equals" operator * - * Matrix3x3::operator *= -- "times equals" operator * - * Matrix3x3::operator /= -- "divide equals" operator * - * Create_X_Rotation_Matrix3 -- creates a matrix3 which is a rotation about X * - * Create_Y_Rotation_Matrix3 -- Creates a Matrix3x3 which is a rotation about Y * - * Create_Z_Rotation_Matrix3 -- Creates a matrix3 which is a rotation about Z * - * Matrix3x3::Rotate_X -- Post-mutiplies an x rotation onto the current matrix * - * Matrix3x3::Rotate_Y -- Post-multiplies the matrix with a rotation about Y * - * Matrix3x3::Rotate_Z -- Post-multiplies the matrix with a rotation about Z * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef Matrix3_H -#define Matrix3_H - -#include "always.h" -#include "vector3.h" -#include "wwdebug.h" -#ifdef _UNIX -#include "osdep.h" -#endif - - -class Matrix3D; -class Matrix4x4; -class Quaternion; - -class Matrix3x3 -{ -public: - - /* - ** Constructors - */ - WWINLINE Matrix3x3(void) {}; - WWINLINE Matrix3x3(const Matrix3x3 & m); - - WWINLINE explicit Matrix3x3(bool identity); - WWINLINE explicit Matrix3x3(const Vector3 & v0, const Vector3 & v1, const Vector3 & v2); - explicit Matrix3x3(const Matrix3D & m); - explicit Matrix3x3(const Matrix4x4 & m); - WWINLINE explicit Matrix3x3( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 - ); - WWINLINE explicit Matrix3x3(const Vector3 & axis,float angle); - WWINLINE explicit Matrix3x3(const Vector3 & axis,float s_angle,float c_angle); - WWINLINE explicit Matrix3x3(const Quaternion & q); - - /* - ** 'Set' functions - */ - void Set(const Matrix3D & m); - void Set(const Matrix4x4 & m); - WWINLINE void Set(const Vector3 & v0, const Vector3 & v1, const Vector3 & v2); - WWINLINE void Set( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 - ); - WWINLINE void Set(const Vector3 & axis,float angle); - WWINLINE void Set(const Vector3 & axis,float s_angle,float c_angle); - void Set(const Quaternion & q); - - /* - ** Access operators - */ - WWINLINE Vector3 & operator [] (int i) { return Row[i]; } - WWINLINE const Vector3 & operator [] (int i) const { return Row[i]; } - - /* - ** Transpose and Inverse - */ - WWINLINE Matrix3x3 Transpose (void) const; - WWINLINE Matrix3x3 Inverse (void) const; - WWINLINE float Determinant (void) const; - - /* - ** Assignment operators - */ - WWINLINE Matrix3x3 & operator = (const Matrix3x3 & m); - Matrix3x3 & operator = (const Matrix3D & m); - Matrix3x3 & operator = (const Matrix4x4 & m); - - WWINLINE Matrix3x3 & operator += (const Matrix3x3 & m); - WWINLINE Matrix3x3 & operator -= (const Matrix3x3 & m); - WWINLINE Matrix3x3 & operator *= (float d); - WWINLINE Matrix3x3 & operator /= (float d); - - WWINLINE void Make_Identity(void); - - /* - ** Automatically concatenate a rotation onto the current matrix - */ - WWINLINE void Rotate_X(float theta); - WWINLINE void Rotate_X(float s,float c); - - WWINLINE void Rotate_Y(float theta); - WWINLINE void Rotate_Y(float s,float c); - - WWINLINE void Rotate_Z(float theta); - WWINLINE void Rotate_Z(float s,float c); - - /* - ** These functions will give you the approximate amount that the - ** matrix has been rotated about a given axis. These functions - ** cannot be used to re-build a matrx. Use the EulerAnglesClass - ** to convert a matrix into a set of three Euler angles. - */ - float Get_X_Rotation(void) const; - float Get_Y_Rotation(void) const; - float Get_Z_Rotation(void) const; - - /* - ** These functions return a vector representing the direction an - ** axis is pointing. - */ - WWINLINE Vector3 Get_X_Vector(void) const; - WWINLINE Vector3 Get_Y_Vector(void) const; - WWINLINE Vector3 Get_Z_Vector(void) const; - WWINLINE void Get_X_Vector(Vector3 * set_x) const; - WWINLINE void Get_Y_Vector(Vector3 * set_y) const; - WWINLINE void Get_Z_Vector(Vector3 * set_z) const; - - /* - ** Negation - */ - WWINLINE friend Matrix3x3 operator - (const Matrix3x3& a); - - /* - ** Scalar multiplication and division - */ - WWINLINE friend Matrix3x3 operator * (const Matrix3x3& a,float d); - WWINLINE friend Matrix3x3 operator * (float d,const Matrix3x3& a); - WWINLINE friend Matrix3x3 operator / (const Matrix3x3& a,float d); - - /* - ** matrix addition - */ - WWINLINE friend Matrix3x3 operator + (const Matrix3x3& a, const Matrix3x3& b); - static WWINLINE void Add(const Matrix3x3 & a, const Matrix3x3 & b,Matrix3x3 * res); - - /* - ** matrix subtraction - */ - WWINLINE friend Matrix3x3 operator - (const Matrix3x3 & a, const Matrix3x3 & b); - static WWINLINE void Subtract(const Matrix3x3 & a, const Matrix3x3 & b,Matrix3x3 * res); - - /* - ** matrix multiplication - */ - WWINLINE friend Matrix3x3 operator * (const Matrix3x3 & a, const Matrix3x3 & b); - WWINLINE friend Matrix3x3 operator * (const Matrix3D & a, const Matrix3x3 & b); - WWINLINE friend Matrix3x3 operator * (const Matrix3x3 & a, const Matrix3D & b); - - static void Multiply(const Matrix3x3 & a, const Matrix3x3 & b,Matrix3x3 * res); - static void Multiply(const Matrix3D & a, const Matrix3x3 & b,Matrix3x3 * res); - static void Multiply(const Matrix3x3 & a, const Matrix3D & b,Matrix3x3 * res); - - /* - ** Matrix-Vector multiplication - */ - WWINLINE friend Vector3 operator * (const Matrix3x3 & a, const Vector3 & v); - static WWINLINE void Rotate_Vector(const Matrix3x3 & tm,const Vector3 & in,Vector3 * out); - static WWINLINE void Transpose_Rotate_Vector(const Matrix3x3 & tm,const Vector3 & in,Vector3 * out); - - /* - ** Comparison operators - */ - WWINLINE friend int operator == (const Matrix3x3 & a, const Matrix3x3 & b); - WWINLINE friend int operator != (const Matrix3x3 & a, const Matrix3x3 & b); - - /* - ** Swap two matrices in place - */ - WWINLINE friend void Swap(Matrix3x3 & a,Matrix3x3 & b); - - /* - ** Check whether a matrix is orthogonal, make it orthogonal - */ - int Is_Orthogonal(void) const; - void Re_Orthogonalize(void); - - /* - ** Miscellaneous - */ - WWINLINE void Rotate_AABox_Extent(const Vector3 & extent,Vector3 * new_extent); - - /* - ** Some useful pre-initialized Matrix3x3's - */ - static const Matrix3x3 Identity; - static const Matrix3x3 RotateX90; - static const Matrix3x3 RotateX180; - static const Matrix3x3 RotateX270; - static const Matrix3x3 RotateY90; - static const Matrix3x3 RotateY180; - static const Matrix3x3 RotateY270; - static const Matrix3x3 RotateZ90; - static const Matrix3x3 RotateZ180; - static const Matrix3x3 RotateZ270; - -protected: - - Vector3 Row[3]; - -}; - - -/*********************************************************************************************** - * Matrix3x3::Matrix3x3 -- Constructor, optionally initialize to Identitiy matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3::Matrix3x3(bool identity) -{ - if (identity) { - Row[0].Set(1.0,0.0,0.0); - Row[1].Set(0.0,1.0,0.0); - Row[2].Set(0.0,0.0,1.0); - } -} - -/*********************************************************************************************** - * Matrix3x3::Matrix3x3 -- Copy Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3::Matrix3x3(const Matrix3x3 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; -} - -/*********************************************************************************************** - * Matrix3x3::Matrix3x3 -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3::Matrix3x3(const Vector3 & r0, const Vector3 & r1, const Vector3 & r2) -{ - Row[0] = r0; - Row[1] = r1; - Row[2] = r2; -} - -WWINLINE void Matrix3x3::Set(const Vector3 & r0, const Vector3 & r1, const Vector3 & r2) -{ - Row[0] = r0; - Row[1] = r1; - Row[2] = r2; -} - -WWINLINE void Matrix3x3::Make_Identity(void) -{ - Row[0].Set(1.0f,0.0f,0.0f); - Row[1].Set(0.0f,1.0f,0.0f); - Row[2].Set(0.0f,0.0f,1.0f); -} - - -WWINLINE Matrix3x3::Matrix3x3 -( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 -) -{ - Row[0].Set(m11,m12,m13); - Row[1].Set(m21,m22,m23); - Row[2].Set(m31,m32,m33); -} - -WWINLINE void Matrix3x3::Set -( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 -) -{ - Row[0].Set(m11,m12,m13); - Row[1].Set(m21,m22,m23); - Row[2].Set(m31,m32,m33); -} - -WWINLINE Matrix3x3::Matrix3x3(const Vector3 & axis,float angle) -{ - Set(axis,angle); -} - -WWINLINE Matrix3x3::Matrix3x3(const Vector3 & axis,float s_angle,float c_angle) -{ - Set(axis,s_angle,c_angle); -} - -WWINLINE void Matrix3x3::Set(const Vector3 & axis,float angle) -{ - Set(axis,sinf(angle),cosf(angle)); -} - -WWINLINE void Matrix3x3::Set(const Vector3 & axis,float s,float c) -{ - WWASSERT(WWMath::Fabs(axis.Length2() - 1.0f) < 0.001f); - - Row[0].Set( - (float)(axis[0]*axis[0] + c*(1.0f - axis[0]*axis[0])), - (float)(axis[0]*axis[1]*(1.0f - c) - axis[2]*s), - (float)(axis[2]*axis[0]*(1.0f - c) + axis[1]*s) - ); - - Row[1].Set( - (float)(axis[0]*axis[1]*(1.0f - c) + axis[2]*s), - (float)(axis[1]*axis[1] + c*(1.0f - axis[1]*axis[1])), - (float)(axis[1]*axis[2]*(1.0f - c) - axis[0]*s) - ); - - Row[2].Set( - (float)(axis[2]*axis[0]*(1.0f - c) - axis[1]*s), - (float)(axis[1]*axis[2]*(1.0f - c) + axis[0]*s), - (float)(axis[2]*axis[2] + c*(1 - axis[2]*axis[2])) - ); -} - -WWINLINE Matrix3x3::Matrix3x3(const Quaternion & q) -{ - this->Set(q); -} - -/*********************************************************************************************** - * Matrix3x3::Transpose -- Returns transpose of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3 Matrix3x3::Transpose() const -{ - return Matrix3x3( - Vector3(Row[0][0], Row[1][0], Row[2][0]), - Vector3(Row[0][1], Row[1][1], Row[2][1]), - Vector3(Row[0][2], Row[1][2], Row[2][2]) - ); -} - -/*********************************************************************************************** - * Matrix3x3::Inverse -- returns the inverse of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3 Matrix3x3::Inverse() const // Gauss-Jordan elimination with partial pivoting -{ - Matrix3x3 a(*this); // As a evolves from original mat into identity - Matrix3x3 b(true); // b evolves from identity into inverse(a) - int i, j, i1; - - // Loop over cols of a from left to right, eliminating above and below diagonal - for (j=0; j<3; j++) { - - // Find largest pivot in column j among rows j..3 - i1 = j; - for (i=j+1; i<3; i++) { - if (WWMath::Fabs(a[i][j]) > WWMath::Fabs(a[i1][j])) { - i1 = i; - } - } - - // Swap rows i1 and j in a and b to put pivot on diagonal - Swap(a.Row[i1], a.Row[j]); - Swap(b.Row[i1], b.Row[j]); - - // Scale row j to have a unit diagonal - if (a[j][j]==0.) { - //Matrix3x3::inverse: singular matrix; can't invert - } - b.Row[j] /= a.Row[j][j]; - a.Row[j] /= a.Row[j][j]; - - // Eliminate off-diagonal elems in col j of a, doing identical ops to b - for (i=0; i<3; i++) { - if (i != j) { - b.Row[i] -= a[i][j] * b.Row[j]; - a.Row[i] -= a[i][j] * a.Row[j]; - } - } - } - return b; -} - - -/*********************************************************************************************** - * Matrix3x3::Determinant -- returns the determinant of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/7/20 DRM : Created. * - *=============================================================================================*/ -WWINLINE float Matrix3x3::Determinant(void) const -{ - return Row[0][0] * (Row[1][1] * Row[2][2] - Row[1][2] * Row[2][1]) - - Row[0][1] * (Row[1][0] * Row[2][2] - Row[1][2] * Row[2][0]) - - Row[0][2] * (Row[1][0] * Row[2][1] - Row[1][1] * Row[2][0]); -} - -/*********************************************************************************************** - * Matrix3x3::operator = -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3 & Matrix3x3::operator = (const Matrix3x3 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; - return *this; -} - -/*********************************************************************************************** - * Matrix3x3::operator += -- "plus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3& Matrix3x3::operator += (const Matrix3x3 & m) -{ - Row[0] += m.Row[0]; Row[1] += m.Row[1]; Row[2] += m.Row[2]; - return *this; -} - -/*********************************************************************************************** - * Matrix3x3::operator-= -- "minus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3& Matrix3x3::operator -= (const Matrix3x3 & m) -{ - Row[0] -= m.Row[0]; Row[1] -= m.Row[1]; Row[2] -= m.Row[2]; - return *this; -} - -/*********************************************************************************************** - * Matrix3x3::operator *= -- "times equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3& Matrix3x3::operator *= (float d) -{ - Row[0] *= d; Row[1] *= d; Row[2] *= d; - return *this; -} - -/*********************************************************************************************** - * Matrix3x3::operator /= -- "divide equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3& Matrix3x3::operator /= (float d) -{ - Row[0] /= d; Row[1] /= d; Row[2] /= d; - return *this; -} - -/*********************************************************************************************** - * Matrix3x3::Get_X_Rotation -- approximates the rotation about the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE float Matrix3x3::Get_X_Rotation(void) const -{ - Vector3 v = (*this) * Vector3(0.0,1.0,0.0); - return WWMath::Atan2(v[2], v[1]); -} - -/*********************************************************************************************** - * Matrix3x3::Get_Y_Rotation -- approximates the rotation about the Y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE float Matrix3x3::Get_Y_Rotation(void) const -{ - Vector3 v = (*this) * Vector3(0.0,0.0,1.0); - return WWMath::Atan2(v[0],v[2]); -} - -/*********************************************************************************************** - * Matrix3x3::Get_Z_Rotation -- approximates the rotation about the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE float Matrix3x3::Get_Z_Rotation(void) const -{ - Vector3 v = (*this) * Vector3(1.0,0.0,0.0); - return WWMath::Atan2(v[1],v[0]); -} - -WWINLINE Vector3 Matrix3x3::Get_X_Vector(void) const -{ - return Vector3(Row[0][0], Row[1][0], Row[2][0]); -} - -WWINLINE Vector3 Matrix3x3::Get_Y_Vector(void) const -{ - return Vector3(Row[0][1], Row[1][1], Row[2][1]); -} - -WWINLINE Vector3 Matrix3x3::Get_Z_Vector(void) const -{ - return Vector3(Row[0][2], Row[1][2], Row[2][2]); -} - -WWINLINE void Matrix3x3::Get_X_Vector(Vector3 * set) const -{ - set->Set(Row[0][0], Row[1][0], Row[2][0]); -} - -WWINLINE void Matrix3x3::Get_Y_Vector(Vector3 * set) const -{ - set->Set(Row[0][1], Row[1][1], Row[2][1]); -} - -WWINLINE void Matrix3x3::Get_Z_Vector(Vector3 * set) const -{ - set->Set(Row[0][2], Row[1][2], Row[2][2]); -} - -WWINLINE Matrix3x3 operator - (const Matrix3x3 & a) -{ - return Matrix3x3(-a.Row[0], -a.Row[1], -a.Row[2]); -} - -WWINLINE Matrix3x3 operator * (const Matrix3x3 & a, float d) -{ - return Matrix3x3(a.Row[0] * d, a.Row[1] * d, a.Row[2] * d); -} - -WWINLINE Matrix3x3 operator * (float d, const Matrix3x3 & a) -{ - return a*d; -} - -WWINLINE Matrix3x3 operator / (const Matrix3x3 & a, float d) -{ - float ood = 1.0f / d; - return Matrix3x3(a.Row[0] * ood, a.Row[1] * ood, a.Row[2] * ood); -} - -/* -** matrix addition -*/ -WWINLINE Matrix3x3 operator + (const Matrix3x3 & a, const Matrix3x3 & b) -{ - return Matrix3x3( - a.Row[0] + b.Row[0], - a.Row[1] + b.Row[1], - a.Row[2] + b.Row[2] - ); -} - -WWINLINE void Matrix3x3::Add(const Matrix3x3 & a, const Matrix3x3 & b,Matrix3x3 * c) -{ - WWASSERT(c); - Vector3::Add(a.Row[0],b.Row[0],&(c->Row[0])); - Vector3::Add(a.Row[1],b.Row[1],&(c->Row[1])); - Vector3::Add(a.Row[2],b.Row[2],&(c->Row[2])); -} - -/* -** matrix subtraction -*/ -WWINLINE Matrix3x3 operator - (const Matrix3x3 & a, const Matrix3x3 & b) -{ - return Matrix3x3( - a.Row[0] - b.Row[0], - a.Row[1] - b.Row[1], - a.Row[2] - b.Row[2] - ); -} - -WWINLINE void Matrix3x3::Subtract(const Matrix3x3 & a, const Matrix3x3 & b,Matrix3x3 * c) -{ - WWASSERT(c); - Vector3::Subtract(a.Row[0],b.Row[0],&(c->Row[0])); - Vector3::Subtract(a.Row[1],b.Row[1],&(c->Row[1])); - Vector3::Subtract(a.Row[2],b.Row[2],&(c->Row[2])); -} - -/* -** matrix multiplication -*/ -WWINLINE Matrix3x3 operator * (const Matrix3x3 & a, const Matrix3x3 & b) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - return Matrix3x3( - Vector3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2) ), - Vector3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2) ), - Vector3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2) ) - ); - - #undef ROWCOL -} - - -/* -** Multiply a Matrix3x3 by a Vector3. Yeilds a Vector3 result -*/ -WWINLINE Vector3 operator * (const Matrix3x3 & a, const Vector3 & v) -{ - return Vector3( - a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2], - a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2], - a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] - ); -} - - -WWINLINE int operator == (const Matrix3x3 & a, const Matrix3x3 & b) -{ - return ((a [0] == b [0]) && (a [1] == b [1]) && (a [2] == b [2])); -} - - -WWINLINE int operator != (const Matrix3x3 & a, const Matrix3x3 & b) -{ - return (!(a == b)); -} - - -/*********************************************************************************************** - * Matrix3x3::Rotate_X -- Post-mutiplies an x rotation onto the current matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3x3::Rotate_X(float theta) -{ - Rotate_X(sinf(theta),cosf(theta)); -} - -WWINLINE void Matrix3x3::Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][1]; tmp2 = Row[0][2]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[0][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[1][2]; - Row[1][1] = (float)( c*tmp1 + s*tmp2); - Row[1][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][1]; tmp2 = Row[2][2]; - Row[2][1] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * Matrix3x3::Rotate_Y -- Post-multiplies the matrix with a rotation about Y * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3x3::Rotate_Y(float theta) -{ - Rotate_Y(sinf(theta),cosf(theta)); -} - -WWINLINE void Matrix3x3::Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][2]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[0][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][2]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][2]; - Row[2][0] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * Matrix3x3::Rotate_Z -- Post-multiplies the matrix with a rotation about Z * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3x3::Rotate_Z(float theta) -{ - Rotate_Z(sinf(theta),cosf(theta)); -} - -WWINLINE void Matrix3x3::Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][1]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[0][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][1]; - Row[1][0] = (float)( c*tmp1 + s*tmp2); - Row[1][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][1]; - Row[2][0] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * Create_X_Rotation_Matrix3 -- creates a matrix3 which is a rotation about X * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3 Create_X_Rotation_Matrix3(float s,float c) -{ - Matrix3x3 mat; - - mat[0][0] = 1.0f; - mat[0][1] = 0.0f; - mat[0][2] = 0.0f; - - mat[1][0] = 0.0f; - mat[1][1] = c; - mat[1][2] = -s; - - mat[2][0] = 0.0f; - mat[2][1] = s; - mat[2][2] = c; - - return mat; -} - -WWINLINE Matrix3x3 Create_X_Rotation_Matrix3(float rad) -{ - return Create_X_Rotation_Matrix3(sinf(rad),cosf(rad)); -} - -/*********************************************************************************************** - * Create_Y_Rotation_Matrix3 -- Creates a Matrix3x3 which is a rotation about Y * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3 Create_Y_Rotation_Matrix3(float s,float c) -{ - Matrix3x3 mat; - - mat[0][0] = c; - mat[0][1] = 0.0f; - mat[0][2] = s; - - mat[1][0] = 0.0f; - mat[1][1] = 1.0f; - mat[1][2] = 0.0f; - - mat[2][0] = -s; - mat[2][1] = 0.0f; - mat[2][2] = c; - - return mat; -} - -WWINLINE Matrix3x3 Create_Y_Rotation_Matrix3(float rad) -{ - return Create_Y_Rotation_Matrix3(sinf(rad),cosf(rad)); -} - -/*********************************************************************************************** - * Create_Z_Rotation_Matrix3 -- Creates a matrix3 which is a rotation about Z * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3x3 Create_Z_Rotation_Matrix3(float s,float c) -{ - Matrix3x3 mat; - - mat[0][0] = c; - mat[0][1] = -s; - mat[0][2] = 0.0f; - - mat[1][0] = s; - mat[1][1] = c; - mat[1][2] = 0.0f; - - mat[2][0] = 0.0f; - mat[2][1] = 0.0f; - mat[2][2] = 1.0f; - - return mat; -} - -WWINLINE Matrix3x3 Create_Z_Rotation_Matrix3(float rad) -{ - return Create_Z_Rotation_Matrix3(sinf(rad),cosf(rad)); -} - -WWINLINE void Matrix3x3::Rotate_Vector(const Matrix3x3 & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z); -} - -WWINLINE void Matrix3x3::Transpose_Rotate_Vector(const Matrix3x3 & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ - } - out->X = (A[0][0] * v->X + A[1][0] * v->Y + A[2][0] * v->Z); - out->Y = (A[0][1] * v->X + A[1][1] * v->Y + A[2][1] * v->Z); - out->Z = (A[0][2] * v->X + A[1][2] * v->Y + A[2][2] * v->Z); -} - -WWINLINE void Matrix3x3::Rotate_AABox_Extent(const Vector3 & extent,Vector3 * set_extent) -{ - // push each extent out to the projections of the original extents - for (int i=0; i<3; i++) { - - // start the center out at the translation portion of the matrix - // and the extent at zero - (*set_extent)[i] = 0.0f; - - for (int j=0; j<3; j++) { - (*set_extent)[i] += WWMath::Fabs(Row[i][j] * extent[j]); - } - } -} - -#endif /*Matrix3_H*/ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3d.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3d.cpp deleted file mode 100644 index ec9b42c8da..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3d.cpp +++ /dev/null @@ -1,1242 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/matrix3d.cpp 41 5/09/01 2:38p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : MATRIX3D.CPP * - * * - * Org Programmer : Greg Hjelstrom * - * * - * Programmer : Kenny Mitchell * - * * - * Start Date : 02/24/97 * - * * - * Last Update : June 6, 2002 [KM] * - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * Matrix3D::Set -- Init a matrix3D from a matrix3 and a position * - * Matrix3D::Set -- Init a matrix3D from a quaternion and a position * - * Matrix3D::Get_X_Rotation -- approximates the rotation about the X axis * - * Matrix3D::Get_Y_Rotation -- approximates the rotation about the Y axis * - * Matrix3D::Get_Z_Rotation -- approximates the rotation about the Z axis * - * Matrix3D::Multiply -- matrix multiplication without temporaries. * - * Matrix3D::Inverse_Rotate_Vector -- rotates a vector by the inverse of the 3x3 sub-matrix * - * Matrix3D::Transform_Min_Max_AABox -- compute transformed axis-aligned box * - * Matrix3D::Transform_Center_Extent_AABox -- compute transformed axis-aligned box * - * Matrix3D::Get_Inverse -- calculate the inverse of this matrix * - * Matrix3D::Get_Orthogonal_Inverse -- Returns the inverse of the matrix * - * Matrix3D::Re_Orthogonalize -- makes this matrix orthogonal. * - * Matrix3D::Is_Orthogonal -- checks whether this matrix is orthogonal * - * Lerp - linearly interpolate matrices (orientation is slerped) * - * Matrix3D::Solve_Linear_System -- 3x3 Gauss-Jordan elimination * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "matrix3d.h" - -#include -#include -#include -//#include -#include "vector3.h" -#include "matrix3.h" -#include "matrix4.h" -#include "quat.h" -#include "d3dx8math.h" - -// some static matrices which are sometimes useful -const Matrix3D Matrix3D::Identity -( - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateX90 -( - 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0, - 0.0, 1.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateX180 -( - 1.0, 0.0, 0.0, 0.0, - 0.0, -1.0, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateX270 -( - 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, -1.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateY90 -( - 0.0, 0.0, 1.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - -1.0, 0.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateY180 -( - -1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateY270 -( - 0.0, 0.0, -1.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateZ90 -( - 0.0, -1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateZ180 -( - -1.0, 0.0, 0.0, 0.0, - 0.0, -1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateZ270 -( - 0.0, 1.0, 0.0, 0.0, - -1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix3D from a matrix3 and a position * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Set(const Matrix3x3 & rot,const Vector3 & pos) -{ - Row[0].Set( rot[0][0], rot[0][1], rot[0][2], pos[0]); - Row[1].Set( rot[1][0], rot[1][1], rot[1][2], pos[1]); - Row[2].Set( rot[2][0], rot[2][1], rot[2][2], pos[2]); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix3D from a quaternion and a position * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Set(const Quaternion & rot,const Vector3 & pos) -{ - Set_Rotation(rot); - Set_Translation(pos); -} - - -/*********************************************************************************************** - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/11/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Set_Rotation(const Matrix3x3 & m) -{ - Row[0][0] = m[0][0]; - Row[0][1] = m[0][1]; - Row[0][2] = m[0][2]; - - Row[1][0] = m[1][0]; - Row[1][1] = m[1][1]; - Row[1][2] = m[1][2]; - - Row[2][0] = m[2][0]; - Row[2][1] = m[2][1]; - Row[2][2] = m[2][2]; -} - - -/*********************************************************************************************** - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/11/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Set_Rotation(const Quaternion & q) -{ - Row[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - Row[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - Row[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - Row[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - Row[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - Row[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - Row[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - Row[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - Row[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); -} - - -/*********************************************************************************************** - * Matrix3D::Get_X_Rotation -- approximates the rotation about the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -float Matrix3D::Get_X_Rotation(void) const -{ - return WWMath::Atan2(Row[2][1], Row[1][1]); -} - - -/*********************************************************************************************** - * Matrix3D::Get_Y_Rotation -- approximates the rotation about the Y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -float Matrix3D::Get_Y_Rotation(void) const -{ - return WWMath::Atan2(Row[0][2], Row[2][2]); -} - - -/*********************************************************************************************** - * Matrix3D::Get_Z_Rotation -- approximates the rotation about the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -float Matrix3D::Get_Z_Rotation(void) const -{ - return WWMath::Atan2(Row[1][0], Row[0][0]); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Vector -- Uses the 3x3 sub-matrix to rotate a vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -Vector3 Matrix3D::Rotate_Vector(const Vector3 &vect) const -{ - return Vector3( - (Row[0][0]*vect[0] + Row[0][1]*vect[1] + Row[0][2]*vect[2]), - (Row[1][0]*vect[0] + Row[1][1]*vect[1] + Row[1][2]*vect[2]), - (Row[2][0]*vect[0] + Row[2][1]*vect[1] + Row[2][2]*vect[2]) - ); -} - - -/*********************************************************************************************** - * Matrix3D::Inverse_Rotate_Vector -- rotates a vector by the inverse of the 3x3 sub-matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/98 GTH : Created. * - *=============================================================================================*/ -Vector3 Matrix3D::Inverse_Rotate_Vector(const Vector3 &vect) const -{ - return Vector3( - (Row[0][0]*vect[0] + Row[1][0]*vect[1] + Row[2][0]*vect[2]), - (Row[0][1]*vect[0] + Row[1][1]*vect[1] + Row[2][1]*vect[2]), - (Row[0][2]*vect[0] + Row[1][2]*vect[1] + Row[2][2]*vect[2]) - ); -} - -/*********************************************************************************************** - * M3DC::Look_At -- Creates a "look at" transformation. * - * * - * Builds a transformation matrix which positions the origin at p, * - * points the negative z-axis towards a target t, and rolls about the z-axis * - * by the angle specified by roll. * - * * - * This can be useful for creating a camera matrix, just invert * - * the matrix after initializing it with this function... * - * * - * INPUT: * - * p - position of the coordinate system * - * t - target of the coordinate system * - * roll - roll angle (in radians) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This function is written assuming the convention that the "ground" is the X-Y plane and * - * Z is altitude. * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Look_At(const Vector3 &p,const Vector3 &t,float roll) -{ - float dx,dy,dz; //vector from p to t - float len1,len2; - float sinp,cosp; //sine and cosine of the pitch ("up-down" tilt about x) - float siny,cosy; //sine and cosine of the yaw ("left-right"tilt about z) - - dx = (t[0] - p[0]); - dy = (t[1] - p[1]); - dz = (t[2] - p[2]); - - len1 = (float)WWMath::Sqrt(dx*dx + dy*dy + dz*dz); - len2 = (float)WWMath::Sqrt(dx*dx + dy*dy); - - if (len1 != 0.0f) { - sinp = dz/len1; - cosp = len2/len1; - } else { - sinp = 0.0f; - cosp = 1.0f; - } - - if (len2 != 0.0f) { - siny = dy/len2; - cosy = dx/len2; - } else { - siny = 0.0f; - cosy = 1.0f; - } - - // init the matrix with position p and -z pointing down +x and +y up - Row[0].X = 0.0f; Row[0].Y = 0.0f; Row[0].Z = -1.0f; - Row[1].X = -1.0f; Row[1].Y = 0.0f; Row[1].Z = 0.0f; - Row[2].X = 0.0f; Row[2].Y = 1.0f; Row[2].Z = 0.0f; - - Row[0].W = p.X; - Row[1].W = p.Y; - Row[2].W = p.Z; - - // Yaw rotation to make the matrix look at the projection of the target - // into the x-y plane - Rotate_Y(siny,cosy); - - // rotate about local x axis to pitch up to the targets position - Rotate_X(sinp,cosp); - - // roll about the local z axis (negate since we look down -z) - Rotate_Z(-roll); -} - -// Create a matrix given a position and a direction (x axis will point in direction) -// Make sure you pass in UNITIZED direction!!! -void Matrix3D::buildTransformMatrix( const Vector3 &pos, const Vector3 &dir ) -{ - float sinp, cosp; // sine and cosine of the pitch ("up-down" tilt about y) - float siny, cosy; // sine and cosine of the yaw ("left-right"tilt about z) - - float len2 = (float)sqrt( (dir.X * dir.X) + (dir.Y * dir.Y) ); - - sinp = dir.Z; - cosp = len2; - - if( len2 != 0.0f ) - { - siny = dir.Y / len2; - cosy = dir.X / len2; - } - else - { - siny = 0.0f; - cosy = 1.0f; - } - - Make_Identity(); - Translate( pos ); - - // Yaw rotation to projection of target in x-y plane - Rotate_Z( siny, cosy ); - - // Pitch rotation - Rotate_Y( -sinp, cosp ); -} - -/*********************************************************************************************** - * M3DC::Obj_Look_At -- Commando Object "look at" transformation. * - * * - * Builds a transformation matrix which positions the origin at p, * - * points the positive X axis towards a target t, and rolls about the X axis * - * by the angle specified by roll. * - * * - * The object convention used by Commando and G is Forward = +X, Left = +Y, Up = +Z. The * - * world is basically the x-y plane with z as altitude and +x is the default "forward". * - * * - * INPUT: * - * p - position of the coordinate system * - * t - target of the coordinate system * - * roll - roll angle (in radians) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Obj_Look_At(const Vector3 &p,const Vector3 &t,float roll) -{ - float dx,dy,dz; //vector from p to t - float len1,len2; - float sinp,cosp; //sine and cosine of the pitch ("up-down" tilt about y) - float siny,cosy; //sine and cosine of the yaw ("left-right"tilt about z) - - dx = (t[0] - p[0]); - dy = (t[1] - p[1]); - dz = (t[2] - p[2]); - - len1 = (float)sqrt(dx*dx + dy*dy + dz*dz); - len2 = (float)sqrt(dx*dx + dy*dy); - - if (len1 != 0.0f) { - sinp = dz/len1; - cosp = len2/len1; - } else { - sinp = 0.0f; - cosp = 1.0f; - } - - if (len2 != 0.0f) { - siny = dy/len2; - cosy = dx/len2; - } else { - siny = 0.0f; - cosy = 1.0f; - } - - Make_Identity(); - Translate(p); - - // Yaw rotation to projection of target in x-y plane - Rotate_Z(siny,cosy); - - // Pitch rotation - Rotate_Y(-sinp,cosp); - - // Roll rotation - Rotate_X(roll); -} - - -/*********************************************************************************************** - * Matrix3D::Get_Inverse -- calculate the inverse of this matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/7/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Get_Inverse(Matrix3D & inv) const -{ - // TODO: Implement the general purpose inverse function here (once we need it :-) - //Get_Orthogonal_Inverse(inv); - - Matrix4x4 mat4(*this); - Matrix4x4 mat4Inv; - - float det; - D3DXMatrixInverse((D3DXMATRIX *)&mat4Inv, &det, (D3DXMATRIX*)&mat4); - - inv.Row[0][0]=mat4Inv[0][0]; - inv.Row[0][1]=mat4Inv[0][1]; - inv.Row[0][2]=mat4Inv[0][2]; - inv.Row[0][3]=mat4Inv[0][3]; - - inv.Row[1][0]=mat4Inv[1][0]; - inv.Row[1][1]=mat4Inv[1][1]; - inv.Row[1][2]=mat4Inv[1][2]; - inv.Row[1][3]=mat4Inv[1][3]; - - inv.Row[2][0]=mat4Inv[2][0]; - inv.Row[2][1]=mat4Inv[2][1]; - inv.Row[2][2]=mat4Inv[2][2]; - inv.Row[2][3]=mat4Inv[2][3]; -} - -/*********************************************************************************************** - * Matrix3D::Get_Orthogonal_Inverse -- Returns the inverse of the matrix * - * * - * NOTE!!! This only works if the matrix is really ORTHOGONAL!!! * - * * - *********************************************************************************************** - * Inverting an orthogonal Matrix3D * - * * - * M is the original transform, * - * R is rotation submatrix, * - * T is translation vector in M. * - * * - * To build MINV * - * * - * R' = transpose of R (inverse of orthogonal 3x3 matrix is transpose) * - * T' = -R'T * - * * - * Build MINV with R'and T' * - * MINV is the inverse of M * - * * - *********************************************************************************************** - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Get_Orthogonal_Inverse(Matrix3D & inv) const -{ - // Transposing the rotation submatrix - inv.Row[0][0] = Row[0][0]; - inv.Row[0][1] = Row[1][0]; - inv.Row[0][2] = Row[2][0]; - - inv.Row[1][0] = Row[0][1]; - inv.Row[1][1] = Row[1][1]; - inv.Row[1][2] = Row[2][1]; - - inv.Row[2][0] = Row[0][2]; - inv.Row[2][1] = Row[1][2]; - inv.Row[2][2] = Row[2][2]; - - // Now, calculate translation portion of matrix: - // T' = -R'T - Vector3 trans = Get_Translation(); - trans = inv.Rotate_Vector(trans); - trans = -trans; - - inv.Row[0][3] = trans[0]; - inv.Row[1][3] = trans[1]; - inv.Row[2][3] = trans[2]; -} - -/*********************************************************************************************** - * Copy_3x3_Matrix(float *matrix) -- Copies a 3x3 (float[9]) matrix into this matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/16/98 EHC : Created. * - *=============================================================================================*/ -void Matrix3D::Copy_3x3_Matrix(float matrix[3][3]) -{ - Row[0][0] = matrix[0][0]; - Row[0][1] = matrix[0][1]; - Row[0][2] = matrix[0][2]; - Row[0][3] = 0; - Row[1][0] = matrix[1][0]; - Row[1][1] = matrix[1][1]; - Row[1][2] = matrix[1][2]; - Row[1][3] = 0; - Row[2][0] = matrix[2][0]; - Row[2][1] = matrix[2][1]; - Row[2][2] = matrix[2][2]; - Row[2][3] = 0; -} - - - -/*********************************************************************************************** - * Matrix3D::Multiply -- matrix multiplication without temporaries. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/22/98 GTH : Created. * - *=============================================================================================*/ -//void print_matrix(const Matrix3D & m); - -void Matrix3D::Multiply(const Matrix3D & A,const Matrix3D & B,Matrix3D * set_res) -{ - assert(set_res != NULL); - - Matrix3D tmp; - Matrix3D * Aptr; - - // Check for aliased parameters, copy the 'A' matrix into a temporary if the - // result is going into 'A'. (in this case, this function is no better than - // the overloaded C++ operator...) - if (set_res == &A) { - tmp = A; - Aptr = &tmp; - } else { - Aptr = (Matrix3D *)&A; - } - -#ifdef ALLOW_TEMPORARIES - float tmp1,tmp2,tmp3; - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - (*set_res)[0][0] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][0] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][0] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - (*set_res)[0][1] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][1] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][1] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - (*set_res)[0][2] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][2] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][2] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][3]; - tmp2 = B[1][3]; - tmp3 = B[2][3]; - - (*set_res)[0][3] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3 + (*Aptr)[0][3]; - (*set_res)[1][3] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3 + (*Aptr)[1][3]; - (*set_res)[2][3] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3 + (*Aptr)[2][3]; -#else - set_res->mul(*Aptr, B); -#endif -} - -#if 0 -void Matrix3D::Multiply(const Matrix3D & A,const Matrix3D & B,Matrix3D * set_res) -{ - assert(set_res != NULL); - - float tmp[12]; -// Check for aliased parameters, copy the 'A' matrix into a temporary if the -// result is going into 'A'. (in this case, this function is no better than -// the overloaded C++ operator...) - -/* if (set_res == &A) - { - Matrix3D tmp; - Matrix3D * Aptr; - float tmp1,tmp2,tmp3; - tmp = A; - Aptr = &tmp; - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - (*set_res)[0][0] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][0] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][0] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - (*set_res)[0][1] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][1] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][1] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - (*set_res)[0][2] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][2] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][2] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][3]; - tmp2 = B[1][3]; - tmp3 = B[2][3]; - - (*set_res)[0][3] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3 + (*Aptr)[0][3]; - (*set_res)[1][3] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3 + (*Aptr)[1][3]; - (*set_res)[2][3] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3 + (*Aptr)[2][3]; - - return; - } -*/ - - __asm { - mov ecx,B - fld dword ptr [ecx+32] // B[2][0] - mov edx,A - lea ebx,tmp - mov eax,set_res - cmp eax,edx - jne not_equal - mov eax,ebx -not_equal: - fld dword ptr [ecx+16] // B[1][0] - fld dword ptr [ecx] // B[0][0] - -// tmp1 = B[0][0]; -// tmp2 = B[1][0]; -// tmp3 = B[2][0]; - -// (*set_res)[0][0] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - fld dword ptr [edx+8] // A[0][2] - fmul st(0),st(3) // A[0][2] * B[2][0] - fld dword ptr [edx+4] // A[0][1] - fmul st(0),st(3) // A[0][1] * B[1][0] - fld dword ptr [edx] // A[0][0] - fmul st(0),st(3) // A[0][2] * B[0][0] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax] // res[0][0] - -// (*set_res)[1][0] = A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3; - fld dword ptr [edx+24] // A[1][2] - fmul st(0),st(3) // A[1][2] * B[2][0] - fld dword ptr [edx+20] // A[1][1] - fmul st(0),st(3) // A[1][1] * B[1][0] - fld dword ptr [edx+16] // A[1][0] - fmul st(0),st(3) // A[1][0] * B[0][0] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+16] // res[1][0] - -// (*set_res)[2][0] = A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3; - - fld dword ptr [edx+40] // A[2][2] - fmul st(0),st(3) // A[2][2] * B[2][0] - fld dword ptr [edx+36] // A[2][1] - fmul st(0),st(3) // A[2][1] * B[1][0] - fld dword ptr [edx+32] // A[2][0] - fmul st(0),st(3) // A[2][0] * B[0][0] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+32] // res[2][0] - -// tmp1 = B[0][1]; -// tmp2 = B[1][1]; -// tmp3 = B[2][1]; - fstp st(0) - fstp st(0) - fstp st(0) - fld dword ptr [ecx+36] // B[2][1] - fld dword ptr [ecx+20] // B[1][1] - fld dword ptr [ecx+4] // B[0][1] - -// (*set_res)[0][1] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - fld dword ptr [edx+8] // A[0][2] - fmul st(0),st(3) // A[0][2] * B[2][1] - fld dword ptr [edx+4] // A[0][1] - fmul st(0),st(3) // A[0][1] * B[1][1] - fld dword ptr [edx] // A[0][0] - fmul st(0),st(3) // A[0][2] * B[0][1] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+4] // res[0][1] - -// (*set_res)[1][1] = A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3; - fld dword ptr [edx+24] // A[1][2] - fmul st(0),st(3) // A[1][2] * B[2][1] - fld dword ptr [edx+20] // A[1][1] - fmul st(0),st(3) // A[1][1] * B[1][1] - fld dword ptr [edx+16] // A[1][0] - fmul st(0),st(3) // A[1][0] * B[0][1] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+20] // res[1][1] - -// (*set_res)[2][1] = A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3; - - fld dword ptr [edx+40] // A[2][2] - fmul st(0),st(3) // A[2][2] * B[2][1] - fld dword ptr [edx+36] // A[2][1] - fmul st(0),st(3) // A[2][1] * B[1][1] - fld dword ptr [edx+32] // A[2][0] - fmul st(0),st(3) // A[2][0] * B[0][1] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+36] // res[2][1] - -// tmp1 = B[0][2]; -// tmp2 = B[1][2]; -// tmp3 = B[2][2]; - fstp st(0) - fstp st(0) - fstp st(0) - fld dword ptr [ecx+40] // B[2][2] - fld dword ptr [ecx+24] // B[1][2] - fld dword ptr [ecx+8] // B[0][2] - -// (*set_res)[0][2] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - fld dword ptr [edx+8] // A[0][2] - fmul st(0),st(3) // A[0][2] * B[2][2] - fld dword ptr [edx+4] // A[0][1] - fmul st(0),st(3) // A[0][1] * B[1][2] - fld dword ptr [edx] // A[0][0] - fmul st(0),st(3) // A[0][2] * B[0][2] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+8] // res[0][2] - -// (*set_res)[1][2] = A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3; - fld dword ptr [edx+24] // A[1][2] - fmul st(0),st(3) // A[1][2] * B[2][2] - fld dword ptr [edx+20] // A[1][1] - fmul st(0),st(3) // A[1][1] * B[1][2] - fld dword ptr [edx+16] // A[1][0] - fmul st(0),st(3) // A[1][0] * B[0][2] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+24] // res[1][2] - -// (*set_res)[2][2] = A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3; - - fld dword ptr [edx+40] // A[2][2] - fmul st(0),st(3) // A[2][2] * B[2][2] - fld dword ptr [edx+36] // A[2][1] - fmul st(0),st(3) // A[2][1] * B[1][2] - fld dword ptr [edx+32] // A[2][0] - fmul st(0),st(3) // A[2][0] * B[0][2] - faddp st(1),st(0) - faddp st(1),st(0) - fstp dword ptr [eax+40] // res[2][2] - -// ------------------------------- -// tmp1 = B[0][3]; -// tmp2 = B[1][3]; -// tmp3 = B[2][3]; - fstp st(0) - fstp st(0) - fstp st(0) - fld dword ptr [ecx+44] // B[2][3] - fld dword ptr [ecx+28] // B[1][3] - fld dword ptr [ecx+12] // B[0][3] - -// (*set_res)[0][3] = A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3 + A[0][3]; - fld dword ptr [edx+8] // A[0][2] - fmul st(0),st(3) // A[0][2] * B[2][3] - fld dword ptr [edx+4] // A[0][1] - fmul st(0),st(3) // A[0][1] * B[1][3] - fld dword ptr [edx] // A[0][0] - fmul st(0),st(3) // A[0][2] * B[0][3] - faddp st(1),st(0) - faddp st(1),st(0) - fadd dword ptr [edx+12] // + A[0][3] - fstp dword ptr [eax+12] // res[0][3] - -// (*set_res)[1][3] = A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3 + A[1][3]; - fld dword ptr [edx+24] // A[1][2] - fmul st(0),st(3) // A[1][2] * B[2][3] - fld dword ptr [edx+20] // A[1][1] - fmul st(0),st(3) // A[1][1] * B[1][3] - fld dword ptr [edx+16] // A[1][0] - fmul st(0),st(3) // A[1][0] * B[0][3] - faddp st(1),st(0) - faddp st(1),st(0) - fadd dword ptr [edx+28] // + A[1][3] - fstp dword ptr [eax+28] // res[1][3] - -// (*set_res)[2][3] = A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3 + A[2][3]; - - fld dword ptr [edx+40] // A[2][2] - fmul st(0),st(3) // A[2][2] * B[2][3] - fld dword ptr [edx+36] // A[2][1] - fmul st(0),st(3) // A[2][1] * B[1][3] - fld dword ptr [edx+32] // A[2][0] - fmul st(0),st(3) // A[2][0] * B[0][3] - faddp st(1),st(0) - faddp st(1),st(0) - fadd dword ptr [edx+44] // + A[2][3] - fstp dword ptr [eax+44] // res[2][3] - fstp st(0) - fstp st(0) - fstp st(0) - - cmp eax,ebx - jne not_equal2 - mov ecx,12 // copy 12 dwords - mov esi,eax // set source to tmp - mov edi,set_res // set destination to set_res - rep movsd // copy -not_equal2: - - } -/* - WWDEBUG_SAY(("{%2.2f, %2.2f, %2.2f, %2.2f}, {%2.2f, %2.2f, %2.2f, %2.2f}, {%2.2f, %2.2f, %2.2f, %2.2f}\n" - ,res[0][0],res[0][1],res[0][2],res[0][3] - ,res[1][0],res[1][1],res[1][2],res[1][3] - ,res[2][0],res[2][1],res[2][2],res[2][3])); - WWDEBUG_SAY(("{%2.2f, %2.2f, %2.2f, %2.2f}, {%2.2f, %2.2f, %2.2f, %2.2f}, {%2.2f, %2.2f, %2.2f, %2.2f}\n" - ,res2[0][0],res2[0][1],res2[0][2],res2[0][3] - ,res2[1][0],res2[1][1],res2[1][2],res2[1][3] - ,res2[2][0],res2[2][1],res2[2][2],res2[2][3])); -// res[2][3]=res2[2][3]; -// res=res2; -*/ -/* for (int y=0;y<3;++y) { - for (int x=0;x<4;++x) { - if (fabs(res2[y][x]-res[y][x])>0.001f) { - WWDEBUG_SAY(("x: %d, y: %d, %f != %f\n",x,y,res2[y][x],res[y][x])); - __asm nop - } - } - } -*/ -/* WWASSERT(res2[0][0]==res[0][0]); - WWASSERT(res2[0][1]==res[0][1]); - WWASSERT(res2[0][2]==res[0][2]); - WWASSERT(res2[0][3]==res[0][3]); - WWASSERT(res2[1][0]==res[1][0]); - WWASSERT(res2[1][1]==res[1][1]); - WWASSERT(res2[1][2]==res[1][2]); - WWASSERT(res2[1][3]==res[1][3]); - WWASSERT(res2[2][0]==res[2][0]); - WWASSERT(res2[2][1]==res[2][1]); - WWASSERT(res2[2][2]==res[2][2]); - WWASSERT(res2[2][3]==res[2][3]); -*/ -} -#endif - -/*********************************************************************************************** - * Matrix3D::Transform_Min_Max_AABox -- compute transformed axis-aligned box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/17/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Transform_Min_Max_AABox -( - const Vector3 & min, - const Vector3 & max, - Vector3 * set_min, - Vector3 * set_max -) const -{ - WWASSERT(set_min != &min); - WWASSERT(set_max != &max); - - float tmp0,tmp1; - - // init the min and max to the translation of the transform - set_min->X = set_max->X = Row[0][3]; - set_min->Y = set_max->Y = Row[1][3]; - set_min->Z = set_max->Z = Row[2][3]; - - // now push them both out by the projections of the original intervals - for (int i=0; i<3; i++) { - - for (int j=0; j<3; j++) { - - tmp0 = Row[i][j] * min[j]; - tmp1 = Row[i][j] * max[j]; - - if (tmp0 < tmp1) { - - (*set_min)[i] += tmp0; - (*set_max)[i] += tmp1; - - } else { - - (*set_min)[i] += tmp1; - (*set_max)[i] += tmp0; - - } - } - } -} - - -/*********************************************************************************************** - * Matrix3D::Transform_Center_Extent_AABox -- compute transformed axis-aligned box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/17/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Transform_Center_Extent_AABox -( - const Vector3 & center, - const Vector3 & extent, - Vector3 * set_center, - Vector3 * set_extent -) const -{ - WWASSERT(set_center != ¢er); - WWASSERT(set_extent != &extent); - - // push each extent out to the projections of the original extents - for (int i=0; i<3; i++) { - - // start the center out at the translation portion of the matrix - // and the extent at zero - (*set_center)[i] = Row[i][3]; - (*set_extent)[i] = 0.0f; - - for (int j=0; j<3; j++) { - - (*set_center)[i] += Row[i][j] * center[j]; - (*set_extent)[i] += WWMath::Fabs(Row[i][j] * extent[j]); - - } - } -} - - -/*********************************************************************************************** - * Matrix3D::Is_Orthogonal -- checks whether this matrix is orthogonal * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/16/98 GTH : Created. * - *=============================================================================================*/ -int Matrix3D::Is_Orthogonal(void) const -{ - Vector3 x(Row[0].X,Row[0].Y,Row[0].Z); - Vector3 y(Row[1].X,Row[1].Y,Row[1].Z); - Vector3 z(Row[2].X,Row[2].Y,Row[2].Z); - - if (Vector3::Dot_Product(x,y) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(y,z) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(z,x) > WWMATH_EPSILON) return 0; - - if (WWMath::Fabs(x.Length2() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(y.Length2() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(z.Length2() - 1.0f) > WWMATH_EPSILON) return 0; - - return 1; -} - -/*********************************************************************************************** - * Matrix3D::Re_Orthogonalize -- makes this matrix orthogonal. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This function is rather expensive, should only be used if you *know* numerical error is * - * killing you. * - * * - * HISTORY: * - * 9/16/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Re_Orthogonalize(void) -{ - Vector3 x(Row[0][0],Row[0][1],Row[0][2]); - Vector3 y(Row[1][0],Row[1][1],Row[1][2]); - Vector3 z; - - Vector3::Cross_Product(x,y,&z); - Vector3::Cross_Product(z,x,&y); - - float len = x.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - x *= 1.0f/len; - } - - len = y.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - y *= 1.0f/len; - } - - len = z.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - z *= 1.0f/len; - } - - Row[0][0] = x.X; - Row[0][1] = x.Y; - Row[0][2] = x.Z; - - Row[1][0] = y.X; - Row[1][1] = y.Y; - Row[1][2] = y.Z; - - Row[2][0] = z.X; - Row[2][1] = z.Y; - Row[2][2] = z.Z; -} - - -/*********************************************************************************************** - * Lerp - linearly interpolate matrices (orientation is slerped) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/05/1998 NH : Created. * - *=============================================================================================*/ -void Matrix3D::Lerp(const Matrix3D &A, const Matrix3D &B, float factor, Matrix3D& result) -{ - assert(factor >= 0.0f); - assert(factor <= 1.0f); - - // Lerp position -#ifdef ALLOW_TEMPORARIES - Vector3 pos = Vector3::Lerp(A.Get_Translation(), B.Get_Translation(), factor); -#else - Vector3 pos; - Vector3::Lerp(A.Get_Translation(), B.Get_Translation(), factor, &pos); -#endif - Quaternion rot; - Slerp(rot,Build_Quaternion(A), Build_Quaternion(B), factor); - result.Set(rot, pos); -} - - -/*********************************************************************************************** - * Matrix3D::Solve_Linear_System -- 3x3 Gauss-Jordan elimination * - * * - * The result of this function will be that the 3x3 sub-matrix is inverted and the * - * final column will contain the result. False is returned if the system cannot be solved. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/18/2001 gth : Created. * - *=============================================================================================*/ -bool Matrix3D::Solve_Linear_System(Matrix3D & system) -{ - /* - ** Gauss-Jordan Elimination - ** We repeatedly replace rows in the matrix with a linear combination of itself and - ** another row in the system in order to reduce the matrix to the identity matrix. - ** TODO: optimize away all unnecessary math operations! - */ - if (system[0][0] == 0.0f) return false; - system[0] *= 1.0f / system[0][0]; // (0,0) now equals 1.0 (row,col) - system[1] -= system[1][0] * system[0]; // (1,0) now equals 0.0 - system[2] -= system[2][0] * system[0]; // (2,0) now equals 0.0 - - if (system[1][1] == 0.0f) return false; - system[1] *= 1.0f / system[1][1]; // (1,1) now equals 1.0 - system[2] -= system[2][1] * system[1]; // (2,1) now equals 0.0 - - if (system[2][2] == 0.0f) return false; - system[2] *= 1.0f / system[2][2]; // (2,2) now equals 1.0, and we already have one answer - - system[1] -= system[1][2] * system[2]; // (1,2) now equals 0.0, and we have another answer - system[0] -= system[0][2] * system[2]; // (0,2) now equals 0.0 - - system[0] -= system[0][1] * system[1]; // (0,1) now equals 0.0, and we are done! - - return true; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3d.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3d.h deleted file mode 100644 index 591363d5b7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix3d.h +++ /dev/null @@ -1,1818 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/matrix3d.h 55 5/11/01 7:11p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : MATRIX3D.H * - * * - * Org Programmer : Greg Hjelstrom * - * * - * Programmer : Kenny Mitchell * - * * - * Start Date : 06/02/97 * - * * - * Last Update : June 6, 2002 [KM] * - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix3D::Matrix3D -- Constructors for Matrix3D * - * Matrix3D::Set -- init a Matrix3D from an arrray of 12 floats * - * Matrix3D::Set -- Init a Matrix3D from 12 individual floats * - * Matrix3D::Set -- Init a matrix from 3 axis vectors and a position * - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * Matrix3D::Set -- Init a matrix to be a pure translation * - * Matrix3D::Make_Identity -- Initializes the matrix to be the identity matrix * - * Matrix3D::Translate -- Post-Multiplies by a Translation Matrix * - * Matrix3D::Translate -- Post-Multiplies the matrix by a translation matrix * - * M3DC::Translate_X -- Post-Multiplies the matrix by a translation matrix with X only * - * M3DC::Translate_Y -- Post-Multiplies the matrix by a translation matrix with Y only * - * M3DC::Translate_Z -- Post-Multiplies the matrix by a translation matrix with Z only * - * Matrix3D::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * Matrix3D::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * Matrix3D::Rotate_Y -- Post-multiplies the matrix by a rotation about the Y axis * - * Matrix3D::Rotate_Y -- Post-Multiplies the matrix by a rotation about Y * - * Matrix3D::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * Matrix3D::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * Matrix3D::Scale -- Scales Matrix !!! WARNING DO NOT USE, INV FUNCTION WILL FAIL * - * Matrix3D::Scale -- Scales Matrix !!! WARNING DO NOT USE, INV FUNCTION WILL FAIL * - * Matrix3D::Scale -- Scales Matrix !!! WARNING DO NOT USE, INV FUNCTION WILL FAIL * - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by rotation about X * - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by rotation about Y * - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by rotation about Z * - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by rotation about X * - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by rotation about Y * - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by rotation about Z * - * operator * -- Matrix multiplication * - * operator * -- Matrix - vector multiplication * - * operator == -- Matrix equality operator * - * operator != -- Matrix inequality operator * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#define NO_ALLOW_TEMPORARIES - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MATRIX3D_H -#define MATRIX3D_H - -#ifdef _UNIX -#include "osdep.h" -#endif - -#include "always.h" -#include -#include "vector2.h" -#include "vector3.h" -#include "vector4.h" -#ifdef _UNIX -#include "osdep.h" -#endif - - -class Matrix3x3; -class Matrix4x4; -class Quaternion; - -/******************************************************************************* - - Matrix3D - - Three important notes: - - I use *column-vectors* - - I use a *right-handed* coordinate system - - These matrices are *orthogonal* - - 3D Transformation matrices. This class is really a 4x4 homogeneous - matrix where the last row is assumed to always be 0 0 0 1. However, - since I don't store the last row, you cant do some things that you can - do with a real 4x4 homogeneous matrix. - - I use column-vectors so normally transformations are post-multiplied - and camera transformations should be pre-multiplied. The methods of - this class called Translate, Rotate_X, etc. all perform post-multiplication - with the current matix. These methods (Translate, Rotate_X, etc) also - have been hand-coded to only perform the necessary arithmetic. The - * operator can be used for general purpose matrix multiplication or to - transform a vector by a matrix. - - Some operations in this class assume that the matrix is orthogonal. - -*********************************************************************************/ - -class Matrix3D -{ -public: - - // Constructors - WWINLINE Matrix3D(void) {} - - WWINLINE explicit Matrix3D(bool init) { if (init) Make_Identity(); } - - WWINLINE explicit Matrix3D(float m[12]); - - WWINLINE explicit Matrix3D( - float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34 - ); - - WWINLINE explicit Matrix3D( - const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos // position - ); - - WWINLINE explicit Matrix3D( - const Vector3 &axis, - float angle - ); - - WWINLINE explicit Matrix3D( - const Vector3 &axis, - float sine, - float cosine - ); - - WWINLINE explicit Matrix3D( - const Matrix3x3 & rotation, - const Vector3 & position - ); - - WWINLINE explicit Matrix3D( - const Quaternion & rotation, - const Vector3 & position - ); - - // Creates identity rotation w. given position. - WWINLINE explicit Matrix3D(const Vector3 & position); - - // Copy constructor - WWINLINE Matrix3D(const Matrix3D & m); - - // Assignment operator - WWINLINE Matrix3D & operator = (const Matrix3D & m); - - // Init functions - WWINLINE void Set(float m[12]); - - WWINLINE void Set( - float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34 - ); - - WWINLINE void Set( - const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos // position - ); - - WWINLINE void Set(const Vector3 & axis,float angle); - - WWINLINE void Set(const Vector3 & axis,float sine,float cosine); - - void Set(const Matrix3x3 & rotation,const Vector3 & position); - - void Set(const Quaternion & rotation,const Vector3 & position); - - // Creates identity rotation w. given position. - WWINLINE void Set(const Vector3 & position); - - // access functions: - WWINLINE Vector4 & operator [] (int i) { return Row[i]; } - WWINLINE const Vector4 & operator [] (int i) const { return Row[i]; } - - WWINLINE Vector3 Get_Translation(void) const { return Vector3(Row[0][3],Row[1][3],Row[2][3]); } - WWINLINE void Get_Translation(Vector3 * set) const { set->X = Row[0][3]; set->Y = Row[1][3]; set->Z = Row[2][3]; } - WWINLINE void Set_Translation(const Vector3 & t) { Row[0][3] = t[0]; Row[1][3] = t[1];Row[2][3] = t[2]; } - - void Set_Rotation(const Matrix3x3 & m); - void Set_Rotation(const Quaternion & q); - - WWINLINE float Get_X_Translation(void) const { return Row[0][3]; }; - WWINLINE float Get_Y_Translation(void) const { return Row[1][3]; }; - WWINLINE float Get_Z_Translation(void) const { return Row[2][3]; }; - - WWINLINE void Set_X_Translation(float x) { Row[0][3] = x; }; - WWINLINE void Set_Y_Translation(float y) { Row[1][3] = y; }; - WWINLINE void Set_Z_Translation(float z) { Row[2][3] = z; }; - - WWINLINE void Adjust_Translation(const Vector3 & t) { Row[0][3] += t[0]; Row[1][3] += t[1]; Row[2][3] += t[2]; }; - WWINLINE void Adjust_X_Translation(float x) { Row[0][3] += x; }; - WWINLINE void Adjust_Y_Translation(float y) { Row[1][3] += y; }; - WWINLINE void Adjust_Z_Translation(float z) { Row[2][3] += z; }; - - // These functions will give you the approximate amount that the - // matrix has been rotated about a given axis. These functions - // cannot be used to re-build a matrx. Use the EulerAnglesClass - // to convert a matrix into a set of three Euler angles. - float Get_X_Rotation(void) const; - float Get_Y_Rotation(void) const; - float Get_Z_Rotation(void) const; - - // Each of the transformation methods performs an - // "optimized" post-multiplication with the current matrix. - // All angles are assumed to be radians. - WWINLINE void Make_Identity(void); - void Translate(float x,float y,float z); - void Translate(const Vector3 &t); - void Translate_X(float x); - void Translate_Y(float y); - void Translate_Z(float z); - void Rotate_X(float theta); - void Rotate_Y(float theta); - void Rotate_Z(float theta); - void Rotate_X(float s,float c); - void Rotate_Y(float s,float c); - void Rotate_Z(float s,float c); - - // !! - // !! Use Scale methods with Extreme Caution - // !! The Matrix Inverse function, only works - // !! with Orthogonal Matrices, for optimization purposes - // !! - WWINLINE void Scale(float scale); // uniform scale all 3 axis - WWINLINE void Scale(float x, float y, float z); // separate input for each axis - WWINLINE void Scale(Vector3 &scale); // scale each axis - - - // Each of these performs an "optimized" pre-multiplication with the - // current matrix. All angles are assumed to be radians. The "In_Place" - // versions do not affect the translation part of the matrix, - WWINLINE void Pre_Rotate_X(float theta); - WWINLINE void Pre_Rotate_Y(float theta); - WWINLINE void Pre_Rotate_Z(float theta); - WWINLINE void Pre_Rotate_X(float s,float c); - WWINLINE void Pre_Rotate_Y(float s,float c); - WWINLINE void Pre_Rotate_Z(float s,float c); - WWINLINE void In_Place_Pre_Rotate_X(float theta); - WWINLINE void In_Place_Pre_Rotate_Y(float theta); - WWINLINE void In_Place_Pre_Rotate_Z(float theta); - WWINLINE void In_Place_Pre_Rotate_X(float s,float c); - WWINLINE void In_Place_Pre_Rotate_Y(float s,float c); - WWINLINE void In_Place_Pre_Rotate_Z(float s,float c); - - // Points the negative Z axis at the target t. Assumes that - // the "world" uses x-y as the ground and z as altitude. - // Used for pointing cameras at targets. - void Look_At(const Vector3 &p,const Vector3 &t,float roll); - - // Previous look_at function follows the camera coordinate convention. - // This one follows the object convention used in Commando and G. I - // special cased this convention since it is used so much by us rather - // than supporting every one of the 24(?) possible conventions... - void Obj_Look_At(const Vector3 &p,const Vector3 &t,float roll); - - // Create a matrix given a position and a direction (x axis will point in direction) - void buildTransformMatrix( const Vector3 &pos, const Vector3 &dir ); - - // use the 3x3 sub-matrix only (ignore translation) - Vector3 Rotate_Vector(const Vector3 &vect) const; - Vector3 Inverse_Rotate_Vector(const Vector3 &vect) const; - - // these get the a vector representing the direction an axis is pointing - WWINLINE Vector3 Get_X_Vector() const { return Vector3(Row[0][0], Row[1][0], Row[2][0]); } - WWINLINE Vector3 Get_Y_Vector() const { return Vector3(Row[0][1], Row[1][1], Row[2][1]); } - WWINLINE Vector3 Get_Z_Vector() const { return Vector3(Row[0][2], Row[1][2], Row[2][2]); } - WWINLINE void Get_X_Vector(Vector3 * set_x) const { set_x->Set(Row[0][0], Row[1][0], Row[2][0]); } - WWINLINE void Get_Y_Vector(Vector3 * set_y) const { set_y->Set(Row[0][1], Row[1][1], Row[2][1]); } - WWINLINE void Get_Z_Vector(Vector3 * set_z) const { set_z->Set(Row[0][2], Row[1][2], Row[2][2]); } - - // Get the inverse of the matrix. - // TODO: currently the "intended-to-be" general inverse function just calls - // the special case Orthogonal inverse functions. Also, when we implement - // general case, check where we were using Get_Inverse since usually it should - // be changed to Get_Orthogonal_Inverse... - void Get_Inverse(Matrix3D & set_inverse) const; - void Get_Orthogonal_Inverse(Matrix3D & set_inverse) const; - - // used for importing SurRender matrices - void Copy_3x3_Matrix(float matrix[3][3]); - - // Optimized Axis-Aligned Box transforms. One for each of the common forms of - // axis aligned box: min,max vectors and center,extent vectors. - void Transform_Min_Max_AABox(const Vector3 & min,const Vector3 & max,Vector3 * set_min,Vector3 * set_max) const; - void Transform_Center_Extent_AABox(const Vector3 & center,const Vector3 & extent,Vector3 * set_center,Vector3 * set_extent) const; - - // matrix multiplication without temporaries - static void Multiply(const Matrix3D &A,const Matrix3D &B,Matrix3D * set_result); - static WWINLINE void Transform_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - static WWINLINE void Rotate_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - - // transform a vector by the inverse of this matrix (note: assumes the matrix - // is orthogonal; if you've manually scaled or sheared the matrix this function - // will not give correct results) - static WWINLINE void Inverse_Transform_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - static WWINLINE void Inverse_Rotate_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - - // Solve a linear system of 3 equations and 3 unknowns. The result of this function is - // that the 3x3 portion of the matrix is inverted and the final column is your answer... - static bool Solve_Linear_System(Matrix3D & system); - - // Check whether a matrix is orthogonal or FORCE it to be :-) - int Is_Orthogonal(void) const; - void Re_Orthogonalize(void); - - static void Lerp(const Matrix3D &A, const Matrix3D &B, float factor, Matrix3D& result); - -#ifdef ALLOW_TEMPORARIES - // nothing -#else - - // does "this = that * this" - void preMul(const Matrix3D& that); - - // does "this = this * that" - void postMul(const Matrix3D& that); - - // does "this = a * b" - void mul(const Matrix3D& a, const Matrix3D& b); - - void mulVector3(const Vector3& in, Vector3& out) const; - void mulVector3(Vector3& inout) const { mulVector3(inout, inout); } - -#endif - - void mulVector3Array(const Vector3* in, Vector3* out, int count) const; - void mulVector3Array(Vector3* inout, int count) const; - - // some static matrices which are sometimes useful - static const Matrix3D Identity; - static const Matrix3D RotateX90; - static const Matrix3D RotateX180; - static const Matrix3D RotateX270; - static const Matrix3D RotateY90; - static const Matrix3D RotateY180; - static const Matrix3D RotateY270; - static const Matrix3D RotateZ90; - static const Matrix3D RotateZ180; - static const Matrix3D RotateZ270; - -protected: - - Vector4 Row[3]; - -#ifdef ALLOW_TEMPORARIES - WWINLINE friend Vector3 operator * (const Matrix3D &A,const Vector3 &a); -#endif -}; - - - -/* --------------------------------------------------------------- - Vector Transformation, Matrix concatenation ---------------------------------------------------------------- */ -#ifdef ALLOW_TEMPORARIES -Vector3 operator * (const Matrix3D &A,const Vector3 &v); -Matrix3D operator * (const Matrix3D &A,const Matrix3D &B); -#endif - -/* --------------------------------------------------------------- - Equality and inequality operators ---------------------------------------------------------------- */ -bool operator == (const Matrix3D &A, const Matrix3D &B); -bool operator != (const Matrix3D &A, const Matrix3D &B); - - -/*********************************************************************************************** - * M3DC::Matrix3D -- Constructors for Matrix3D * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3D::Matrix3D(float m[12]) -{ - Row[0].Set(m[0],m[1],m[2],m[3]); - Row[1].Set(m[4],m[5],m[6],m[7]); - Row[2].Set(m[8],m[9],m[10],m[11]); -} - -WWINLINE Matrix3D::Matrix3D -( - float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34 -) -{ - Row[0].Set(m11,m12,m13,m14); - Row[1].Set(m21,m22,m23,m24); - Row[2].Set(m31,m32,m33,m34); -} - -WWINLINE Matrix3D::Matrix3D -( - const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos // position -) -{ - Set(x,y,z,pos); -} - -WWINLINE Matrix3D::Matrix3D(const Vector3 & axis,float angle) -{ - Set(axis,angle); -} - -WWINLINE Matrix3D::Matrix3D(const Vector3 & axis,float sine,float cosine) -{ - Set(axis,sine,cosine); -} - -WWINLINE Matrix3D::Matrix3D(const Matrix3x3 & rot,const Vector3 & pos) -{ - Set(rot,pos); -} - -WWINLINE Matrix3D::Matrix3D(const Quaternion & rot,const Vector3 & pos) -{ - Set(rot,pos); -} - -WWINLINE Matrix3D::Matrix3D(const Vector3 & position) -{ - Set(position); -} - -// Copy Constructor -WWINLINE Matrix3D::Matrix3D(const Matrix3D & m) -{ - Row[0] = m.Row[0]; - Row[1] = m.Row[1]; - Row[2] = m.Row[2]; -} - -// Assignment operator -WWINLINE Matrix3D & Matrix3D::operator = (const Matrix3D & m) -{ - Row[0] = m.Row[0]; - Row[1] = m.Row[1]; - Row[2] = m.Row[2]; - return *this; -} - - -/*********************************************************************************************** - * Matrix3D::Set -- init a Matrix3D from an arrray of 12 floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Set(float m[12]) -{ - Row[0].Set(m[0],m[1],m[2],m[3]); - Row[1].Set(m[4],m[5],m[6],m[7]); - Row[2].Set(m[8],m[9],m[10],m[11]); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a Matrix3D from 12 individual floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Set( float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34) -{ - Row[0].Set(m11,m12,m13,m14); - Row[1].Set(m21,m22,m23,m24); - Row[2].Set(m31,m32,m33,m34); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix from 3 axis vectors and a position * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Set( const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos) // position -{ - Row[0].Set(x[0],y[0],z[0],pos[0]); - Row[1].Set(x[1],y[1],z[1],pos[1]); - Row[2].Set(x[2],y[2],z[2],pos[2]); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Set(const Vector3 & axis,float angle) -{ - float c = cosf(angle); - float s = sinf(angle); - - Set(axis,s,c); -} - -/*********************************************************************************************** - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Set(const Vector3 & axis,float s,float c) -{ - assert(WWMath::Fabs(axis.Length2() - 1.0f) < 0.001f); - - Row[0].Set( - (float)(axis[0]*axis[0] + c*(1.0f - axis[0]*axis[0])), - (float)(axis[0]*axis[1]*(1.0f - c) - axis[2]*s), - (float)(axis[2]*axis[0]*(1.0f - c) + axis[1]*s), - 0.0f - ); - - Row[1].Set( - (float)(axis[0]*axis[1]*(1.0f - c) + axis[2]*s), - (float)(axis[1]*axis[1] + c*(1.0f - axis[1]*axis[1])), - (float)(axis[1]*axis[2]*(1.0f - c) - axis[0]*s), - 0.0f - ); - - Row[2].Set( - (float)(axis[2]*axis[0]*(1.0f - c) - axis[1]*s), - (float)(axis[1]*axis[2]*(1.0f - c) + axis[0]*s), - (float)(axis[2]*axis[2] + c*(1 - axis[2]*axis[2])), - 0.0f - ); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix to be a pure translation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Set(const Vector3 & position) -{ - Row[0].Set(1.0f,0.0f,0.0f,position[0]); - Row[1].Set(0.0f,1.0f,0.0f,position[1]); - Row[2].Set(0.0f,0.0f,1.0f,position[2]); -} - - -/*********************************************************************************************** - * M3DC::Make_Identity -- Initializes the matrix to be the identity matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Make_Identity(void) -{ - Row[0].Set(1.0f,0.0f,0.0f,0.0f); - Row[1].Set(0.0f,1.0f,0.0f,0.0f); - Row[2].Set(0.0f,0.0f,1.0f,0.0f); -} - - -/*********************************************************************************************** - * M3DC::Translate -- Post-Multiplies by a Translation Matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Translate(float x,float y,float z) -{ - Row[0][3] += (float)(Row[0][0]*x + Row[0][1]*y + Row[0][2]*z); - Row[1][3] += (float)(Row[1][0]*x + Row[1][1]*y + Row[1][2]*z); - Row[2][3] += (float)(Row[2][0]*x + Row[2][1]*y + Row[2][2]*z); -} - - -/*********************************************************************************************** - * M3DC::Translate -- Post-Multiplies the matrix by a translation matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Translate(const Vector3 &t) -{ - Row[0][3] += Row[0][0]*t[0] + Row[0][1]*t[1] + Row[0][2]*t[2]; - Row[1][3] += Row[1][0]*t[0] + Row[1][1]*t[1] + Row[1][2]*t[2]; - Row[2][3] += Row[2][0]*t[0] + Row[2][1]*t[1] + Row[2][2]*t[2]; -} - - -/*********************************************************************************************** - * M3DC::Translate_X -- Post-Multiplies the matrix by a translation matrix with X only * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/06/1998 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Translate_X(float x) -{ - Row[0][3] += (float)(Row[0][0]*x); - Row[1][3] += (float)(Row[1][0]*x); - Row[2][3] += (float)(Row[2][0]*x); -} - - -/*********************************************************************************************** - * M3DC::Translate_Y -- Post-Multiplies the matrix by a translation matrix with Y only * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/06/1998 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Translate_Y(float y) -{ - Row[0][3] += (float)(Row[0][1]*y); - Row[1][3] += (float)(Row[1][1]*y); - Row[2][3] += (float)(Row[2][1]*y); -} - - -/*********************************************************************************************** - * M3DC::Translate_Z -- Post-Multiplies the matrix by a translation matrix with Z only * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/06/1998 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Translate_Z(float z) -{ - Row[0][3] += (float)(Row[0][2]*z); - Row[1][3] += (float)(Row[1][2]*z); - Row[2][3] += (float)(Row[2][2]*z); -} - - -/*********************************************************************************************** - * M3DC::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Rotate_X(float theta) -{ - float tmp1,tmp2; - float s,c; - - s = sinf(theta); - c = cosf(theta); - - tmp1 = Row[0][1]; tmp2 = Row[0][2]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[0][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[1][2]; - Row[1][1] = (float)( c*tmp1 + s*tmp2); - Row[1][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][1]; tmp2 = Row[2][2]; - Row[2][1] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); - -} - - -/*********************************************************************************************** - * M3DC::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][1]; tmp2 = Row[0][2]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[0][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[1][2]; - Row[1][1] = (float)( c*tmp1 + s*tmp2); - Row[1][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][1]; tmp2 = Row[2][2]; - Row[2][1] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Y -- Post-multiplies the matrix by a rotation about the Y axis * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Rotate_Y(float theta) -{ - float tmp1,tmp2; - float s,c; - - s = sinf(theta); - c = cosf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[0][2]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[0][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][2]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][2]; - Row[2][0] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Y -- Post-Multiplies the matrix by a rotation about Y * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][2]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[0][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][2]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][2]; - Row[2][0] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Rotate_Z(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[0][1]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[0][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][1]; - Row[1][0] = (float)( c*tmp1 + s*tmp2); - Row[1][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][1]; - Row[2][0] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][1]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[0][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][1]; - Row[1][0] = (float)( c*tmp1 + s*tmp2); - Row[1][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][1]; - Row[2][0] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * Matrix3D::Scale -- Scales each Axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/07/2000 jga : Created. * - *=============================================================================================*/ -// !! -// !! Use Scale methods with Extreme Caution -// !! The Matrix Inverse function, only works -// !! with Orthogonal Matrices, for optimization purposes -// !! -WWINLINE void Matrix3D::Scale(float scale) -{ // uniform scale all 3 axis - // X - Row[0][0] *= scale; - Row[1][0] *= scale; - Row[2][0] *= scale; - // Y - Row[0][1] *= scale; - Row[1][1] *= scale; - Row[2][1] *= scale; - // Z - Row[0][2] *= scale; - Row[1][2] *= scale; - Row[2][2] *= scale; -} -/*********************************************************************************************** - * Matrix3D::Scale -- Scales each Axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/07/2000 jga : Created. * - *=============================================================================================*/ -// !! -// !! Use Scale methods with Extreme Caution -// !! The Matrix Inverse function, only works -// !! with Orthogonal Matrices, for optimization purposes -// !! -WWINLINE void Matrix3D::Scale(float x, float y, float z) -{ // separate input for each axis - // X - Row[0][0] *= x; - Row[1][0] *= x; - Row[2][0] *= x; - // Y - Row[0][1] *= y; - Row[1][1] *= y; - Row[2][1] *= y; - // Z - Row[0][2] *= z; - Row[1][2] *= z; - Row[2][2] *= z; -} -/*********************************************************************************************** - * Matrix3D::Scale -- Scales each Axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 03/07/2000 jga : Created. * - *=============================================================================================*/ -// !! -// !! Use Scale methods with Extreme Caution -// !! The Matrix Inverse function, only works -// !! with Orthogonal Matrices, for optimization purposes -// !! -WWINLINE void Matrix3D::Scale(Vector3 &scale) -{ // scale each axis - Scale(scale.X, scale.Y, scale.Z); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Pre_Rotate_X(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][3]; tmp2 = Row[2][3]; - Row[1][3] = (float)(c*tmp1 - s*tmp2); - Row[2][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Pre_Rotate_Y(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[2][3]; - Row[0][3] = (float)( c*tmp1 + s*tmp2); - Row[2][3] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Pre_Rotate_Z(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[1][3]; - Row[0][3] = (float)(c*tmp1 - s*tmp2); - Row[1][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Pre_Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][3]; tmp2 = Row[2][3]; - Row[1][3] = (float)(c*tmp1 - s*tmp2); - Row[2][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Pre_Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[2][3]; - Row[0][3] = (float)( c*tmp1 + s*tmp2); - Row[2][3] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::Pre_Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[1][3]; - Row[0][3] = (float)(c*tmp1 - s*tmp2); - Row[1][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by a rotation about X * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::In_Place_Pre_Rotate_X(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by a rotation about Y * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::In_Place_Pre_Rotate_Y(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by a rotation about Z * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::In_Place_Pre_Rotate_Z(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by a rotation about X * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::In_Place_Pre_Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by a rotation about Y * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::In_Place_Pre_Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by a rotation about Z * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix3D::In_Place_Pre_Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); -} - -#ifdef ALLOW_TEMPORARIES -/*********************************************************************************************** - * operator * -- Matrix multiplication * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix3D operator * (const Matrix3D &A,const Matrix3D &B) -{ - Matrix3D C; - float tmp1,tmp2,tmp3; - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - C[0][0] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3); - C[1][0] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3); - C[2][0] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3); - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - C[0][1] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3); - C[1][1] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3); - C[2][1] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3); - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - C[0][2] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3); - C[1][2] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3); - C[2][2] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3); - - tmp1 = B[0][3]; - tmp2 = B[1][3]; - tmp3 = B[2][3]; - - C[0][3] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3 + A[0][3]); - C[1][3] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3 + A[1][3]); - C[2][3] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3 + A[2][3]); - - return C; -} - -#else - -WWINLINE float submul(const Vector4& row, float tmp1, float tmp2, float tmp3) -{ - return row.X * tmp1 + row.Y * tmp2 + row.Z * tmp3; -} - -// does "this = that * this" -WWINLINE void Matrix3D::preMul(const Matrix3D& that) -{ - assert(this != &that); - - // yes, this is ok. see the comments for 'mul' - this->mul(that, *this); -} - -// does "this = this * that" -WWINLINE void Matrix3D::postMul(const Matrix3D& that) -{ - assert(this != &that); - -#define AVOID_TEMP_IN_POSTMUL -#ifdef AVOID_TEMP_IN_POSTMUL - float tmpX, tmpY, tmpZ, tmpW; - - tmpX = submul(this->Row[0], that.Row[0].X, that.Row[1].X, that.Row[2].X); - tmpY = submul(this->Row[0], that.Row[0].Y, that.Row[1].Y, that.Row[2].Y); - tmpZ = submul(this->Row[0], that.Row[0].Z, that.Row[1].Z, that.Row[2].Z); - tmpW = submul(this->Row[0], that.Row[0].W, that.Row[1].W, that.Row[2].W); - - this->Row[0].X = tmpX; - this->Row[0].Y = tmpY; - this->Row[0].Z = tmpZ; - this->Row[0].W += tmpW; - - tmpX = submul(this->Row[1], that.Row[0].X, that.Row[1].X, that.Row[2].X); - tmpY = submul(this->Row[1], that.Row[0].Y, that.Row[1].Y, that.Row[2].Y); - tmpZ = submul(this->Row[1], that.Row[0].Z, that.Row[1].Z, that.Row[2].Z); - tmpW = submul(this->Row[1], that.Row[0].W, that.Row[1].W, that.Row[2].W); - - this->Row[1].X = tmpX; - this->Row[1].Y = tmpY; - this->Row[1].Z = tmpZ; - this->Row[1].W += tmpW; - - tmpX = submul(this->Row[2], that.Row[0].X, that.Row[1].X, that.Row[2].X); - tmpY = submul(this->Row[2], that.Row[0].Y, that.Row[1].Y, that.Row[2].Y); - tmpZ = submul(this->Row[2], that.Row[0].Z, that.Row[1].Z, that.Row[2].Z); - tmpW = submul(this->Row[2], that.Row[0].W, that.Row[1].W, that.Row[2].W); - - this->Row[2].X = tmpX; - this->Row[2].Y = tmpY; - this->Row[2].Z = tmpZ; - this->Row[2].W += tmpW; -#else - Matrix3D tmp = *this; - this->mul(tmp, that); -#endif -} - -// does "this = A * B" -WWINLINE void Matrix3D::mul(const Matrix3D& A, const Matrix3D& B) -{ - assert(this != &A); - //assert(this != &B); - // nope, this is actually ok. (srj) - //assert(this != &B); - - float tmp1,tmp2,tmp3; - - tmp1 = B.Row[0].X; - tmp2 = B.Row[1].X; - tmp3 = B.Row[2].X; - - this->Row[0].X = submul(A.Row[0], tmp1, tmp2, tmp3); - this->Row[1].X = submul(A.Row[1], tmp1, tmp2, tmp3); - this->Row[2].X = submul(A.Row[2], tmp1, tmp2, tmp3); - - tmp1 = B.Row[0].Y; - tmp2 = B.Row[1].Y; - tmp3 = B.Row[2].Y; - - this->Row[0].Y = submul(A.Row[0], tmp1, tmp2, tmp3); - this->Row[1].Y = submul(A.Row[1], tmp1, tmp2, tmp3); - this->Row[2].Y = submul(A.Row[2], tmp1, tmp2, tmp3); - - tmp1 = B.Row[0].Z; - tmp2 = B.Row[1].Z; - tmp3 = B.Row[2].Z; - - this->Row[0].Z = submul(A.Row[0], tmp1, tmp2, tmp3); - this->Row[1].Z = submul(A.Row[1], tmp1, tmp2, tmp3); - this->Row[2].Z = submul(A.Row[2], tmp1, tmp2, tmp3); - - tmp1 = B.Row[0].W; - tmp2 = B.Row[1].W; - tmp3 = B.Row[2].W; - - this->Row[0].W = submul(A.Row[0], tmp1, tmp2, tmp3) + A.Row[0].W; - this->Row[1].W = submul(A.Row[1], tmp1, tmp2, tmp3) + A.Row[1].W; - this->Row[2].W = submul(A.Row[2], tmp1, tmp2, tmp3) + A.Row[2].W; -} - -#endif - -#ifdef ALLOW_TEMPORARIES -/*********************************************************************************************** - * operator * -- Matrix - vector multiplication * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Vector3 operator * (const Matrix3D &A,const Vector3 &a) -{ -#if 0 - return Vector3 - ( - (A[0][0]*a[0] + A[0][1]*a[1] + A[0][2]*a[2] + A[0][3]), - (A[1][0]*a[0] + A[1][1]*a[1] + A[1][2]*a[2] + A[1][3]), - (A[2][0]*a[0] + A[2][1]*a[1] + A[2][2]*a[2] + A[2][3]) - ); -#else - return Vector3 - ( - (A.Row[0].X*a.X + A.Row[0].Y*a.Y + A.Row[0].Z*a.Z + A.Row[0].W), - (A.Row[1].X*a.X + A.Row[1].Y*a.Y + A.Row[1].Z*a.Z + A.Row[1].W), - (A.Row[2].X*a.X + A.Row[2].Y*a.Y + A.Row[2].Z*a.Z + A.Row[2].W) - ); -#endif -} - -#else - -WWINLINE void Matrix3D::mulVector3(const Vector3& in, Vector3& out) const -{ - // note, it's ok for in==out here. - float x = (Row[0].X * in.X + Row[0].Y * in.Y + Row[0].Z * in.Z + Row[0].W); - float y = (Row[1].X * in.X + Row[1].Y * in.Y + Row[1].Z * in.Z + Row[1].W); - float z = (Row[2].X * in.X + Row[2].Y * in.Y + Row[2].Z * in.Z + Row[2].W); - out.Set(x, y, z); -} - -#endif - -WWINLINE void Matrix3D::mulVector3Array(const Vector3* in, Vector3* out, int count) const -{ - assert(in != out); -#ifdef ALLOW_TEMPORARIES - for (int i=0; iX = (Row[0].X * in->X + Row[0].Y * in->Y + Row[0].Z * in->Z + Row[0].W); - out->Y = (Row[1].X * in->X + Row[1].Y * in->Y + Row[1].Z * in->Z + Row[1].W); - out->Z = (Row[2].X * in->X + Row[2].Y * in->Y + Row[2].Z * in->Z + Row[2].W); - ++in; - ++out; - } -#endif -} - -WWINLINE void Matrix3D::mulVector3Array(Vector3* inout, int count) const -{ -#ifdef ALLOW_TEMPORARIES - for (int i=0; iX + Row[0].Y * inout->Y + Row[0].Z * inout->Z + Row[0].W); - float y = (Row[1].X * inout->X + Row[1].Y * inout->Y + Row[1].Z * inout->Z + Row[1].W); - float z = (Row[2].X * inout->X + Row[2].Y * inout->Y + Row[2].Z * inout->Z + Row[2].W); - inout->Set(x, y, z); - ++inout; - } -#endif -} - -/*********************************************************************************************** - * operator == -- Matrix equality operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/29/1998 NH : Created. * - *=============================================================================================*/ -WWINLINE bool operator == (const Matrix3D &A, const Matrix3D &B) -{ - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 4; j++) { - if (A[i][j] != B[i][j]) return false; - } - } - return true; -} - - -/*********************************************************************************************** - * operator != -- Matrix inequality operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/29/1998 NH : Created. * - *=============================================================================================*/ -WWINLINE bool operator != (const Matrix3D &A, const Matrix3D &B) -{ - return !(A == B); -} - - -WWINLINE void Matrix3D::Transform_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z + A[0][3]); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z + A[1][3]); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z + A[2][3]); -} - -WWINLINE void Matrix3D::Rotate_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z); -} - -WWINLINE void Matrix3D::Inverse_Transform_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - Vector3 diff(v->X - A[0][3], v->Y - A[1][3], v->Z - A[2][3]); - Matrix3D::Inverse_Rotate_Vector(A, diff, out); -} - -WWINLINE void Matrix3D::Inverse_Rotate_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ - } - out->X = (A[0][0] * v->X + A[1][0] * v->Y + A[2][0] * v->Z); - out->Y = (A[0][1] * v->X + A[1][1] * v->Y + A[2][1] * v->Z); - out->Z = (A[0][2] * v->X + A[1][2] * v->Y + A[2][2] * v->Z); -} - -class DynamicMatrix3D : public W3DMPO -{ - W3DMPO_GLUE(DynamicMatrix3D) -public: - Matrix3D Mat; -}; -#endif /* MATRIX3D_H */ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix4.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix4.cpp deleted file mode 100644 index 72fdf245fe..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix4.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/matrix4.cpp $* - * * - * Org Author:: Greg_h * - * * - * Author : Kenny_m * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 6 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix4x4::Multiply -- Multiply two Matrix4x4's together * - * Matrix4x4::Multiply -- Multiply a Matrix3D * Matrix4x4 * - * Matrix4x4::Multiply -- Multiply a Matrix4x4 * Matrix3D * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "matrix4.h" -#include - -/*********************************************************************************************** - * Matrix4x4::Multiply -- Multiply two Matrix4x4's together * - * * - * INPUT: * - * a - first operand * - * b - second operand * - * res - pointer to matrix to store the result in (must not point to a or b) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/13/99 gth : Created. * - *=============================================================================================*/ -void Matrix4x4::Multiply(const Matrix4x4 &a,const Matrix4x4 &b,Matrix4x4 * res) -{ - assert(res != &a); - assert(res != &b); - - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - (*res)[0][3] = ROWCOL(0,3); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - (*res)[1][3] = ROWCOL(1,3); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - (*res)[2][3] = ROWCOL(2,3); - - (*res)[3][0] = ROWCOL(3,0); - (*res)[3][1] = ROWCOL(3,1); - (*res)[3][2] = ROWCOL(3,2); - (*res)[3][3] = ROWCOL(3,3); - - #undef ROWCOL -} - - -/*********************************************************************************************** - * Matrix4x4::Multiply -- Multiply a Matrix3D * Matrix4x4 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/13/99 gth : Created. * - *=============================================================================================*/ -void Matrix4x4::Multiply(const Matrix3D &a,const Matrix4x4 &b,Matrix4x4 * res) -{ - assert(res != &b); - - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - (*res)[0][3] = ROWCOL(0,3); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - (*res)[1][3] = ROWCOL(1,3); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - (*res)[2][3] = ROWCOL(2,3); - - (*res)[3][0] = b[3][0]; // last row of a is 0,0,0,1 - (*res)[3][1] = b[3][1]; // this leaves the last row of b unchanged - (*res)[3][2] = b[3][2]; - (*res)[3][3] = b[3][3]; - - #undef ROWCOL -} - - -/*********************************************************************************************** - * Matrix4x4::Multiply -- Multiply a Matrix4x4 * Matrix3D * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix4x4::Multiply(const Matrix4x4 & a,const Matrix3D & b,Matrix4x4 * res) -{ - assert(res != &a); - - // ROWCOL multiplies a row of 'a' by one of the first three columns of 'b' (4th entry in b is zero) - // ROWCOL4 multiplies a row of 'a' by the fourth column of 'b' (4th entry in b is one) - - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - #define ROWCOL4(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - (*res)[0][3] = ROWCOL4(0,3); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - (*res)[1][3] = ROWCOL4(1,3); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - (*res)[2][3] = ROWCOL4(2,3); - - (*res)[3][0] = ROWCOL(3,0); - (*res)[3][1] = ROWCOL(3,1); - (*res)[3][2] = ROWCOL(3,2); - (*res)[3][3] = ROWCOL4(3,3); - - #undef ROWCOL - #undef ROWCOL4 -} - -int operator == (const Matrix4x4 & a, const Matrix4x4 & b) -{ - unsigned* m1=(unsigned*)&a; - unsigned* m2=(unsigned*)&b; - unsigned res=0; - for (int i=0;i<4;++i) { - res|=*m1++^*m2++; - res|=*m1++^*m2++; - res|=*m1++^*m2++; - res|=*m1++^*m2++; - } - return !res; -} - -int operator != (const Matrix4x4 & a, const Matrix4x4 & b) -{ - return (!(a == b)); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix4.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix4.h deleted file mode 100644 index b062816479..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/matrix4.h +++ /dev/null @@ -1,848 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/matrix4.h 20 10/04/01 10:33a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * File Name : MATRIX4.H * - * * - * Org Programmer : Greg Hjelstrom * - * * - * Author : Kenny Mitchell * - * * - * Start Date : 06/02/97 * - * * - * Last Update : June 6, 2002 [KM] * - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix4x4::Matrix4x4 -- Constructor, optionally initialize to Identitiy matrix * - * Matrix4x4::Matrix4x4 -- Copy Constructor * - * Matrix4x4::Matrix4x4 -- Convert a Matrix3D (fake 4x4) to a Matrix4x4 * - * Matrix4x4::Matrix4x4 -- Constructor * - * Matrix4x4::Make_Identity -- Initializes the matrix to Identity * - * Matrix4x4::Init -- Initializes from the contents of the give Matrix3D * - * Matrix4x4::Init -- Initializes the rows from the given Vector4s * - * Matrix4x4::Init -- Initializes the rows from the given 16 floats * - * Matrix4x4::Init_Ortho -- Initialize to an orthographic projection matrix * - * Matrix4x4::Init_Perspective -- Initialize to a perspective projection matrix * - * Matrix4x4::Init_Perspective -- Initialize to a perspective projection matrix * - * Matrix4x4::Transpose -- Returns transpose of the matrix * - * Matrix4x4::Inverse -- returns the inverse of the matrix * - * Matrix4x4::operator = -- assignment operator * - * Matrix4x4::operator += -- "plus equals" operator * - * Matrix4x4::operator -= -- "minus equals" operator * - * Matrix4x4::operator *= -- "times equals" operator * - * Matrix4x4::operator /= -- "divide equals" operator * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef MATRIX4_H -#define MATRIX4_H - -#include "always.h" -#include "vector4.h" -#include "matrix3d.h" -#include "matrix3.h" - - -class Matrix4x4 -{ -public: - - /* - ** Constructors - */ - Matrix4x4(void) {}; - Matrix4x4(const Matrix4x4 & m); - - WWINLINE explicit Matrix4x4(bool identity); - WWINLINE explicit Matrix4x4(const Matrix3D & m); - WWINLINE explicit Matrix4x4(const Matrix3x3 & m); - WWINLINE explicit Matrix4x4(const Vector4 & v0, const Vector4 & v1, const Vector4 & v2, const Vector4 & v3); - WWINLINE explicit Matrix4x4( float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34, - float m41,float m42,float m43,float m44 ); - - WWINLINE void Make_Identity(void); - WWINLINE void Init(const Matrix3D & m); - WWINLINE void Init(const Matrix3x3 & m); - WWINLINE void Init(const Vector4 & v0, const Vector4 & v1, const Vector4 & v2, const Vector4 & v3); - WWINLINE void Init( float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34, - float m41,float m42,float m43,float m44 ); - - /* - ** Projection matrices. The znear and zfar parameters are positive values indicating the - ** distance from the camera to the z clipping planes. See implementations for more info. - */ - WWINLINE void Init_Ortho(float left,float right,float bottom,float top,float znear,float zfar); - WWINLINE void Init_Perspective(float hfov,float vfov,float znear,float zfar); - WWINLINE void Init_Perspective(float left,float right,float bottom,float top,float znear,float zfar); - - /* - ** Access operators - */ - WWINLINE Vector4 & operator [] (int i) { return Row[i]; } - WWINLINE const Vector4 & operator [] (int i) const { return Row[i]; } - - /* - ** Transpose and Inverse - */ - WWINLINE Matrix4x4 Transpose(void) const; - WWINLINE Matrix4x4 Inverse(void) const; - - /* - ** Assignment operators - */ - WWINLINE Matrix4x4 & operator = (const Matrix4x4 & m); - WWINLINE Matrix4x4 & operator += (const Matrix4x4 & m); - WWINLINE Matrix4x4 & operator -= (const Matrix4x4 & m); - WWINLINE Matrix4x4 & operator *= (float d); - WWINLINE Matrix4x4 & operator /= (float d); - - /* - ** Negation - */ - WWINLINE friend Matrix4x4 operator - (const Matrix4x4& a); - - /* - ** Scalar multiplication and division - */ - WWINLINE friend Matrix4x4 operator * (const Matrix4x4& a,float d); - WWINLINE friend Matrix4x4 operator * (float d,const Matrix4x4& a); - WWINLINE friend Matrix4x4 operator / (const Matrix4x4& a,float d); - - /* - ** matrix addition - */ - WWINLINE friend Matrix4x4 operator + (const Matrix4x4& a, const Matrix4x4& b); - WWINLINE friend Matrix4x4 Add(const Matrix4x4& a); - - /* - ** matrix subtraction - */ - WWINLINE friend Matrix4x4 operator - (const Matrix4x4 & a, const Matrix4x4 & b); - WWINLINE friend Matrix4x4 Subtract(const Matrix4x4 & a, const Matrix4x4 & b); - - /* - ** matrix multiplication - */ - WWINLINE friend Matrix4x4 operator * (const Matrix4x4 & a, const Matrix4x4 & b); - WWINLINE friend Matrix4x4 Multiply(const Matrix4x4 & a, const Matrix4x4 & b); - WWINLINE friend Matrix4x4 operator * (const Matrix4x4 & a, const Matrix3D & b); - WWINLINE friend Matrix4x4 operator * (const Matrix3D & a, const Matrix4x4 & b); - - /* - ** Comparison operators - */ - friend int operator == (const Matrix4x4 & a, const Matrix4x4 & b); - friend int operator != (const Matrix4x4 & a, const Matrix4x4 & b); - - /* - ** Swap two matrices in place - */ - WWINLINE friend void Swap(Matrix4x4 & a,Matrix4x4 & b); - - /* - ** Linear Transforms - */ - WWINLINE friend Vector4 operator * (const Matrix4x4 & a, const Vector4 & v); - WWINLINE friend Vector4 operator * (const Matrix4x4 & a, const Vector3 & v); - - /* - ** Matrix multiplication without temporaries... - */ - static void Multiply(const Matrix4x4 &A,const Matrix4x4 &B,Matrix4x4 * set_result); - static void Multiply(const Matrix3D &A,const Matrix4x4 &B,Matrix4x4 * set_result); - static void Multiply(const Matrix4x4 &A,const Matrix3D &B,Matrix4x4 * set_result); - - static WWINLINE void Transform_Vector(const Matrix4x4 & tm,const Vector3 & in,Vector3 * out); - static WWINLINE void Transform_Vector(const Matrix4x4 & tm,const Vector3 & in,Vector4 * out); - static WWINLINE void Transform_Vector(const Matrix4x4 & tm,const Vector4 & in,Vector4 * out); - -protected: - - Vector4 Row[4]; - -}; - - -/*********************************************************************************************** - * Matrix4x4::Matrix4x4 -- Constructor, optionally initialize to Identitiy matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4::Matrix4x4(bool identity) -{ - if (identity) { - Make_Identity(); - } -} - -/*********************************************************************************************** - * Matrix4x4::Matrix4x4 -- Copy Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4::Matrix4x4(const Matrix4x4 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; Row[3] = m.Row[3]; -} - -/*********************************************************************************************** - * Matrix4x4::Matrix4x4 -- Convert a Matrix3D (fake 4x4) to a Matrix4x4 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4::Matrix4x4(const Matrix3D & m) -{ - Init(m); -} - -/*********************************************************************************************** - * Matrix4x4::Matrix4x4 -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4::Matrix4x4(const Vector4 & r0, const Vector4 & r1, const Vector4 & r2, const Vector4 & r3) -{ - Init(r0,r1,r2,r3); -} - -/*********************************************************************************************** - * Matrix4x4::Matrix4x4 -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/06/2001 NH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4::Matrix4x4(float m11,float m12,float m13,float m14, float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34, float m41,float m42,float m43,float m44 ) -{ - Init(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44); -} - -/*********************************************************************************************** - * Matrix4x4::Make_Identity -- Initializes the matrix to Identity * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Make_Identity(void) -{ - Row[0].Set(1.0,0.0,0.0,0.0); - Row[1].Set(0.0,1.0,0.0,0.0); - Row[2].Set(0.0,0.0,1.0,0.0); - Row[3].Set(0.0,0.0,0.0,1.0); -} - - -/*********************************************************************************************** - * Matrix4x4::Init -- Initializes from the contents of the give Matrix3D * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Init(const Matrix3D & m) -{ - Row[0] = m[0]; Row[1] = m[1]; Row[2] = m[2]; Row[3] = Vector4(0.0,0.0,0.0,1.0); -} - - -/*********************************************************************************************** - * Matrix4x4::Init -- Initializes the rows from the given Vector4s * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Init(const Vector4 & r0, const Vector4 & r1, const Vector4 & r2, const Vector4 & r3) -{ - Row[0] = r0; Row[1] = r1; Row[2] = r2; Row[3] = r3; -} - - -/*********************************************************************************************** - * Matrix4x4::Init -- Initializes the rows from the given 16 floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/6/01 NH : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Init(float m11,float m12,float m13,float m14, float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34, float m41,float m42,float m43,float m44) -{ - Row[0].Set(m11,m12,m13,m14); - Row[1].Set(m21,m22,m23,m24); - Row[2].Set(m31,m32,m33,m34); - Row[3].Set(m41,m42,m43,m44); -} - - -/*********************************************************************************************** - * Matrix4x4::Init_Ortho -- Initialize to an orthographic projection matrix * - * * - * You can find the formulas for this in the appendix of the OpenGL programming guide. Also * - * this happens to be the same convention used by Surrender. * - * * - * The result of this projection will be that points inside the volume will have all coords * - * between -1 and +1. A point at znear will project to z=-1. A point at zfar will project * - * to z=+1... * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Note that the znear and zfar parameters are positive distances to the clipping planes * - * even though in the camera coordinate system, the clipping planes are at negative z * - * coordinates. This holds for all of the projection initializations and is consistent * - * with OpenGL's convention. * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Init_Ortho -( - float left, - float right, - float bottom, - float top, - float znear, - float zfar -) -{ - assert(znear >= 0.0f); - assert(zfar > znear); - - Make_Identity(); - Row[0][0] = 2.0f / (right - left); - Row[0][3] = -(right + left) / (right - left); - Row[1][1] = 2.0f / (top - bottom); - Row[1][3] = -(top + bottom) / (top - bottom); - Row[2][2] = -2.0f / (zfar - znear); - Row[2][3] = -(zfar + znear) / (zfar - znear); -} - - -/*********************************************************************************************** - * Matrix4x4::Init_Perspective -- Initialize to a perspective projection matrix * - * * - * You can find the formulas for this matrix in the appendix of the OpenGL programming guide. * - * Also, this happens to be the same convention used by Surrender. * - * * - * The result of this projection will be that points inside the volume will have all coords * - * between -1 and +1. A point at znear will project to z=-1. A point at zfar will project * - * to z=+1... * - * * - * INPUT: * - * hfov - horizontal field of view (in radians) * - * vfov - vertical field of view (in radians) * - * znear - distance to near z clipping plane (positive) * - * zfar - distance to the far z clipping plane (positive) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Note that the znear and zfar parameters are positive distances to the clipping planes * - * even though in the camera coordinate system, the clipping planes are at negative z * - * coordinates. This holds for all of the projection initializations and is consistent * - * with OpenGL's convention. * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Init_Perspective(float hfov,float vfov,float znear,float zfar) -{ - assert(znear > 0.0f); - assert(zfar > znear); - - Make_Identity(); - Row[0][0] = static_cast(1.0 / tan(hfov*0.5)); - Row[1][1] = static_cast(1.0 / tan(vfov*0.5)); - Row[2][2] = -(zfar + znear) / (zfar - znear); - Row[2][3] = static_cast(-(2.0*zfar*znear) / (zfar - znear)); - Row[3][2] = -1.0f; - Row[3][3] = 0.0f; -} - - -/*********************************************************************************************** - * Matrix4x4::Init_Perspective -- Initialize to a perspective projection matrix * - * * - * You can find the formulas for this matrix in the appendix of the OpenGL programming guide. * - * Also, this happens to be the same convention used by Surrender. * - * * - * The result of this projection will be that points inside the volume will have all coords * - * between -1 and +1. A point at znear will project to z=-1. A point at zfar will project * - * to z=+1... * - * * - * INPUT: * - * * - * left - min x coordinate of near clip plane * - * right - max x coordinate of near clip plane * - * bottom - min y coordinate of near clip plane * - * top - max y coordinate of near clip plane * - * znear - distance to near Z clipping plane * - * zfar - distance to far Z clipping plane * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Note that the znear and zfar parameters are positive distances to the clipping planes * - * even though in the camera coordinate system, the clipping planes are at negative z * - * coordinates. This holds for all of the projection initializations and is consistent * - * with OpenGL's convention. * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Matrix4x4::Init_Perspective -( - float left, - float right, - float bottom, - float top, - float znear, - float zfar -) -{ - assert(znear > 0.0f); - assert(zfar > 0.0f); - - Make_Identity(); - Row[0][0] = static_cast(2.0*znear / (right - left)); - Row[0][2] = (right + left) / (right - left); - Row[1][1] = static_cast(2.0*znear / (top - bottom)); - Row[1][2] = (top + bottom) / (top - bottom); - Row[2][2] = -(zfar + znear) / (zfar - znear); - Row[2][3] = static_cast(-(2.0*zfar*znear) / (zfar - znear)); - Row[3][2] = -1.0f; - Row[3][3] = 0.0f; -} - -/*********************************************************************************************** - * Matrix4x4::Transpose -- Returns transpose of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4 Matrix4x4::Transpose() const -{ - return Matrix4x4( - Vector4(Row[0][0], Row[1][0], Row[2][0], Row[3][0]), - Vector4(Row[0][1], Row[1][1], Row[2][1], Row[3][1]), - Vector4(Row[0][2], Row[1][2], Row[2][2], Row[3][2]), - Vector4(Row[0][3], Row[1][3], Row[2][3], Row[3][3]) - ); -} - -/*********************************************************************************************** - * Matrix4x4::Inverse -- returns the inverse of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4 Matrix4x4::Inverse() const // Gauss-Jordan elimination with partial pivoting -{ - WWASSERT_PRINT(0,"Matrix4x4::Inverse does not work, re-implement!"); - - Matrix4x4 a(*this); // As a evolves from original mat into identity - Matrix4x4 b(true); // b evolves from identity into inverse(a) - int i, j, i1; - - // Loop over cols of a from left to right, eliminating above and below diagonal - for (j=0; j<4; j++) { - - // Find largest pivot in column j among rows j..3 - i1 = j; - for (i=j+1; i<4; i++) { - if (WWMath::Fabs(a[i][j]) > WWMath::Fabs(a[i1][j])) { - i1 = i; - } - } - - // Swap rows i1 and j in a and b to put pivot on diagonal - Swap(a.Row[i1], a.Row[j]); - Swap(b.Row[i1], b.Row[j]); - - // Scale row j to have a unit diagonal - if (a[j][j]==0.) { - //ALGEBRA_ERROR("Matrix4x4::inverse: singular matrix; can't invert\n"); - } - b.Row[j] /= a.Row[j][j]; - a.Row[j] /= a.Row[j][j]; - - // Eliminate off-diagonal elems in col j of a, doing identical ops to b - for (i=0; i<4; i++) { - if (i != j) { - b.Row[i] -= a[i][j] * b.Row[j]; - a.Row[i] -= a[i][j] * a.Row[j]; - } - } - } - return b; -} - -/*********************************************************************************************** - * Matrix4x4::operator = -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4 & Matrix4x4::operator = (const Matrix4x4 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; Row[3] = m.Row[3]; - return *this; -} - -/*********************************************************************************************** - * Matrix4x4::operator += -- "plus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4& Matrix4x4::operator += (const Matrix4x4 & m) -{ - Row[0] += m.Row[0]; Row[1] += m.Row[1]; Row[2] += m.Row[2]; Row[3] += m.Row[3]; - return *this; -} - -/*********************************************************************************************** - * Matrix4x4::operator-= -- "minus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4& Matrix4x4::operator -= (const Matrix4x4 & m) -{ - Row[0] -= m.Row[0]; Row[1] -= m.Row[1]; Row[2] -= m.Row[2]; Row[3] -= m.Row[3]; - return *this; -} - -/*********************************************************************************************** - * Matrix4x4::operator *= -- "times equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4& Matrix4x4::operator *= (float d) -{ - Row[0] *= d; Row[1] *= d; Row[2] *= d; Row[3] *= d; - return *this; -} - -/*********************************************************************************************** - * Matrix4x4::operator /= -- "divide equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Matrix4x4& Matrix4x4::operator /= (float d) -{ - float ood = d; - Row[0] *= ood; Row[1] *= ood; Row[2] *= ood; Row[3] *= ood; - return *this; -} - -WWINLINE Matrix4x4 operator - (const Matrix4x4 & a) -{ - return Matrix4x4(-a.Row[0], -a.Row[1], -a.Row[2], -a.Row[3]); -} - -WWINLINE Matrix4x4 operator * (const Matrix4x4 & a, float d) -{ - return Matrix4x4(a.Row[0] * d, a.Row[1] * d, a.Row[2] * d, a.Row[3] * d); -} - -WWINLINE Matrix4x4 operator * (float d, const Matrix4x4 & a) -{ - return a*d; -} - -WWINLINE Matrix4x4 operator / (const Matrix4x4 & a, float d) -{ - float ood = 1.0f / d; - return Matrix4x4(a.Row[0] * ood, a.Row[1] * ood, a.Row[2] * ood, a.Row[3] * ood); -} - -/* -** matrix addition -*/ -WWINLINE Matrix4x4 operator + (const Matrix4x4 & a, const Matrix4x4 & b) -{ - return Matrix4x4( - a.Row[0] + b.Row[0], - a.Row[1] + b.Row[1], - a.Row[2] + b.Row[2], - a.Row[3] + b.Row[3] - ); -} - -WWINLINE Matrix4x4 Add(const Matrix4x4 & a, const Matrix4x4 & b) -{ return a+b; } - -/* -** matrix subtraction -*/ -WWINLINE Matrix4x4 operator - (const Matrix4x4 & a, const Matrix4x4 & b) -{ - return Matrix4x4( - a.Row[0] - b.Row[0], - a.Row[1] - b.Row[1], - a.Row[2] - b.Row[2], - a.Row[3] - b.Row[3] - ); -} - -WWINLINE Matrix4x4 Subtract(const Matrix4x4 & a, const Matrix4x4 & b) -{ return a-b; } - -/* -** matrix multiplication -*/ -WWINLINE Matrix4x4 operator * (const Matrix4x4 & a, const Matrix4x4 & b) -{ - #define ROWCOL(i, j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - - return Matrix4x4( - Vector4(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2), ROWCOL(0,3)), - Vector4(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2), ROWCOL(1,3)), - Vector4(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2), ROWCOL(2,3)), - Vector4(ROWCOL(3,0), ROWCOL(3,1), ROWCOL(3,2), ROWCOL(3,3)) - ); - - #undef ROWCOL -} - -WWINLINE Matrix4x4 Multiply(const Matrix4x4 & a, const Matrix4x4 & b) -{ return a*b; } - -WWINLINE Matrix4x4 operator * (const Matrix4x4 & a, const Matrix3D & b) -{ - // This function hand coded to handle the last row of b as 0,0,0,1 - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - #define ROWCOL_LAST(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3] - return Matrix4x4( - Vector4(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2), ROWCOL_LAST(0,3)), - Vector4(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2), ROWCOL_LAST(1,3)), - Vector4(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2), ROWCOL_LAST(2,3)), - Vector4(ROWCOL(3,0), ROWCOL(3,1), ROWCOL(3,2), ROWCOL_LAST(3,3)) - ); - #undef ROWCOL - #undef ROWCOL_LAST -} - -WWINLINE Matrix4x4 operator * (const Matrix3D & a, const Matrix4x4 & b) -{ - // This function hand coded to handle the last row of a as 0,0,0,1 - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - return Matrix4x4( - Vector4(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2), ROWCOL(0,3)), - Vector4(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2), ROWCOL(1,3)), - Vector4(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2), ROWCOL(2,3)), - Vector4(b[3][0], b[3][1], b[3][2], b[3][3]) - ); - #undef ROWCOL -} - -/* -** Multiply a Matrix4x4 by a Vector3 (assumes w=1.0!!!). Yeilds a Vector4 result -*/ -WWINLINE Vector4 operator * (const Matrix4x4 & a, const Vector3 & v) { - return Vector4( - a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2] + a[0][3] * 1.0f, - a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2] + a[1][3] * 1.0f, - a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] + a[2][3] * 1.0f, - a[3][0] * v[0] + a[3][1] * v[1] + a[3][2] * v[2] + a[3][3] * 1.0f - ); -} - -/* -** Multiply a Matrix4x4 by a Vector4 -*/ -WWINLINE Vector4 operator * (const Matrix4x4 & a, const Vector4 & v) { - return Vector4( - a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2] + a[0][3] * v[3], - a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2] + a[1][3] * v[3], - a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] + a[2][3] * v[3], - a[3][0] * v[0] + a[3][1] * v[1] + a[3][2] * v[2] + a[3][3] * v[3] - ); -} - -/* -** Multiply a Matrix4x4 by a Vector4 -*/ -WWINLINE void Matrix4x4::Transform_Vector(const Matrix4x4 & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z + A[0][3]); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z + A[1][3]); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z + A[2][3]); -} - - -WWINLINE void Matrix4x4::Transform_Vector(const Matrix4x4 & A,const Vector3 & in,Vector4 * out) -{ - out->X = (A[0][0] * in.X + A[0][1] * in.Y + A[0][2] * in.Z + A[0][3]); - out->Y = (A[1][0] * in.X + A[1][1] * in.Y + A[1][2] * in.Z + A[1][3]); - out->Z = (A[2][0] * in.X + A[2][1] * in.Y + A[2][2] * in.Z + A[2][3]); - out->W = 1.0f; -} - -WWINLINE void Matrix4x4::Transform_Vector(const Matrix4x4 & A,const Vector4 & in,Vector4 * out) -{ - Vector4 tmp; - Vector4 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector4 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z + A[0][3] * v->W); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z + A[1][3] * v->W); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z + A[2][3] * v->W); - out->W = (A[3][0] * v->X + A[3][1] * v->Y + A[3][2] * v->Z + A[3][3] * v->W); -} - - -#endif /*MATRIX4_H*/ \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/obbox.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/obbox.cpp deleted file mode 100644 index e65a49e6fb..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/obbox.cpp +++ /dev/null @@ -1,791 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/obbox.cpp $* - * * - * Org Author:: Greg_h * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 24 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * OBBoxClass::OBBoxClass -- Constructor that computes the box for a set of point * - * OBBoxClass::Init_From_Box_Points -- Create an OBBox from 8 corners of a box * - * OBBoxClass::Init_Random -- initalize a random oriented box * - * Oriented_Boxes_Intersect_On_Axis -- test if two boxes intersect on given axis * - * Oriented_Boxes_Intersect -- test if two oriented boxes intersect * - * Oriented_Boxes_Collide_On_Axis -- test if two boxes collide on the given axis * - * Oriented_Boxes_Collide -- test if two oriented boxes collide * - * Oriented_Box_Intersects_Tri_On_Axis -- tests if the box and tri intersect on the axis * - * Oriented_Box_Intersects_Tri -- tests if the given box and tri intersect * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "obbox.h" -#include "matrix3.h" -#include "vector3.h" -#include "aabox.h" -#include "tri.h" -#include "plane.h" -#include "quat.h" -#include -//#include - - -/*********************************************************************************************** - * OBBoxClass::OBBoxClass -- Constructor that computes the box for a set of points * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/4/98 GTH : Created. * - *=============================================================================================*/ -OBBoxClass::OBBoxClass(const Vector3 * /*points*/, int /*n*/) -{ - // TODO: IMPLEMENT THIS!!! - assert(0); - -#if 0 - int i; - - // compute mean and covariances of points - float xsum = 0.0f, ysum = 0.0f, zsum = 0.0f;; - float xxsum = 0.0f, xysum = 0.0f, xzsum = 0.0f; - float yysum = 0.0f, yzsum = 0.0f, zzsum = 0.0f; - - for (i = 0; i < n; i++) - { - xsum += points[i].X; - ysum += points[i].Y; - zsum += points[i].Z; - - xxsum += points[i].X * points[i].X; - xysum += points[i].X * points[i].Y; - xzsum += points[i].X * points[i].Z; - - yysum += points[i].Y * points[i].Y; - yzsum += points[i].Y * points[i].Z; - zzsum += points[i].Z * points[i].Z; - } - - float xmean = xsum/n; - float ymean = ysum/n; - float zmean = zsum/n; - float xxcov = xxsum/n - xmean*xmean; - float xycov = xysum/n - xmean*ymean; - float xzcov = xzsum/n - xmean*zmean; - float yycov = yysum/n - ymean*ymean; - float yzcov = yzsum/n - ymean*zmean; - float zzcov = zzsum/n - zmean*zmean; - - // compute eigenvectors for covariance matrix, - // these will be the axes. - mgcEigen eig(3); - eig.Matrix(0,0) = xxcov; - eig.Matrix(0,1) = xycov; - eig.Matrix(0,2) = xzcov; - eig.Matrix(1,0) = xycov; - eig.Matrix(1,1) = yycov; - eig.Matrix(1,2) = yzcov; - eig.Matrix(2,0) = xzcov; - eig.Matrix(2,1) = yzcov; - eig.Matrix(2,2) = zzcov; - - eig.EigenStuff3(); - Point3 U = - { - eig.Eigenvector(0,0), - eig.Eigenvector(1,0), - eig.Eigenvector(2,0) - }; - Point3 V = - { - eig.Eigenvector(0,1), - eig.Eigenvector(1,1), - eig.Eigenvector(2,1) - }; - Point3 W = - { - eig.Eigenvector(0,2), - eig.Eigenvector(1,2), - eig.Eigenvector(2,2) - }; - - // box center is the mean of the distribution - box.center.x = xmean; - box.center.y = ymean; - box.center.z = zmean; - - - // Box axes are the eigenvectors of the covariance matrix with - // adjusted lengths to enclose the points. If U, V, and W are the - // eigenvectors, C is the center of the box, and X is a point in - // the input list, then X = C + a*U + b*V + c*W. The box extent is - // determined by max|a|, max|b|, and max|c|. The box axes are then - // defined to be (max|a|)*U and (max|b|)*V. Note that since U and V - // are unit length and orthogonal, a = Dot(U,X-C), b = Dot(V,X-C), - // and c = Dot(W,X-C). - float amax = 0.0f, bmax = 0.0f, cmax = 0.0f; - for (i = 0; i < n; i++) - { - float dx = pt[i].x - box.center.x; - float dy = pt[i].y - box.center.y; - float dz = pt[i].z - box.center.z; - float absdot = float(WWMath::Fabs(U.x*dx+U.y*dy+U.z*dz)); - if ( absdot > amax ) - amax = absdot; - absdot = float(WWMath::Fabs(V.x*dx+V.y*dy+V.z*dz)); - if ( absdot > bmax ) - bmax = absdot; - absdot = float(WWMath::Fabs(W.x*dx+W.y*dy+W.z*dz)); - if ( absdot > cmax ) - cmax = absdot; - } - - box.axis[0].x = amax*U.x; - box.axis[0].y = amax*U.y; - box.axis[0].z = amax*U.z; - box.axis[1].x = bmax*V.x; - box.axis[1].y = bmax*V.y; - box.axis[1].z = bmax*V.z; - box.axis[2].x = cmax*W.x; - box.axis[2].y = cmax*W.y; - box.axis[2].z = cmax*W.z; - -#endif -} - -/*********************************************************************************************** - * OBBoxClass::Init_From_Box_Points -- Create an OBBox from 8 corners of a box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -void OBBoxClass::Init_From_Box_Points(Vector3 * points,int num) -{ - int i,j; - - /* - ** This function assumes that you pass in 8 points which are the - ** corners of a rectangular solid. Bad things will happen if - ** this assumption is not true!!!! - */ - assert(num == 8); - - /* - ** Just pick the first point as the preliminary center. Compute - ** vectors from this point to each of the other points - */ - Vector3 dp[8]; - for (i=1;i Extent.X) Extent.X = xprj; - - float yprj = float(WWMath::Fabs(axis1.X * dx + axis1.Y * dy + axis1.Z * dz)); - if (yprj > Extent.Y) Extent.Y = yprj; - - float zprj = float(WWMath::Fabs(axis2.X * dx + axis2.Y * dy + axis2.Z * dz)); - if (zprj > Extent.Z) Extent.Z = zprj; - } -} - - -/*********************************************************************************************** - * OBBoxClass::Init_Random -- initalize a random oriented box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/21/98 GTH : Created. * - *=============================================================================================*/ -void OBBoxClass::Init_Random(float min_extent,float max_extent) -{ - Center.Set(0,0,0); - - Extent.X = min_extent + WWMath::Random_Float() * (max_extent - min_extent); - Extent.Y = min_extent + WWMath::Random_Float() * (max_extent - min_extent); - Extent.Z = min_extent + WWMath::Random_Float() * (max_extent - min_extent); - - Quaternion orient; - orient.X = WWMath::Random_Float(); - orient.Y = WWMath::Random_Float(); - orient.Z = WWMath::Random_Float(); - orient.W = WWMath::Random_Float(); - orient.Normalize(); - - Basis = Build_Matrix3(orient); -} - - - - -/*********************************************************************************************** - * Oriented_Boxes_Intersect_On_Axis -- test if two boxes intersect on given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/99 GTH : Created. * - *=============================================================================================*/ -bool Oriented_Boxes_Intersect_On_Axis -( - const OBBoxClass & box0, - const OBBoxClass & box1, - const Vector3 & axis -) -{ - float ra,rb,rsum; - - if (axis.Length2() < WWMATH_EPSILON) return true; - - ra = box0.Project_To_Axis(axis); - rb = box1.Project_To_Axis(axis); - rsum = WWMath::Fabs(ra) + WWMath::Fabs(rb); - - // project the center distance onto the line: - Vector3 C = box1.Center - box0.Center; - float cdist = Vector3::Dot_Product(axis,C); - - if ((cdist > rsum) || (cdist < -rsum)) { - return false; - } - return true; -} - - -/*********************************************************************************************** - * Oriented_Boxes_Intersect -- test if two oriented boxes intersect * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/99 GTH : Created. * - *=============================================================================================*/ -bool Oriented_Boxes_Intersect -( - const OBBoxClass & box0, - const OBBoxClass & box1 -) -{ - Vector3 axis; - Vector3 A[3],B[3]; - - // vectors for the axis directions of the two boxes in world space - A[0].Set(box0.Basis[0][0],box0.Basis[1][0],box0.Basis[2][0]); - A[1].Set(box0.Basis[0][1],box0.Basis[1][1],box0.Basis[2][1]); - A[2].Set(box0.Basis[0][2],box0.Basis[1][2],box0.Basis[2][2]); - - B[0].Set(box1.Basis[0][0],box1.Basis[1][0],box1.Basis[2][0]); - B[1].Set(box1.Basis[0][1],box1.Basis[1][1],box1.Basis[2][1]); - B[2].Set(box1.Basis[0][2],box1.Basis[1][2],box1.Basis[2][2]); - - ///////////////////////////////////////////////////////////////////////// - // Projecting the two boxes onto Box0's X axis. If their intervals - // on this line do not intersect, the boxes are not intersecting. - // Each of the tests in this function work in a similar way. - ///////////////////////////////////////////////////////////////////////// - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,A[0])) return false; - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,A[1])) return false; - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,A[2])) return false; - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,B[0])) return false; - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,B[1])) return false; - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,B[2])) return false; - - ///////////////////////////////////////////////////////////////////////// - // None of the aligned axes turned out to be separating axes. Now - // we check all combinations of cross products of the two boxes axes. - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A[0],B[0],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[0],B[1],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[0],B[2],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[1],B[0],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[1],B[1],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[1],B[2],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[2],B[0],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[2],B[1],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - Vector3::Cross_Product(A[2],B[2],&axis); - if (!Oriented_Boxes_Intersect_On_Axis(box0,box1,axis)) return false; - - // None of the above tests separated the two boxes, so they are intersecting - return true; -} - - - - - -/*********************************************************************************************** - * Oriented_Boxes_Collide_On_Axis -- test if two boxes collide on the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/99 GTH : Created. * - *=============================================================================================*/ -bool Oriented_Boxes_Collide_On_Axis -( - const OBBoxClass & box0, - const Vector3 & v0, - const OBBoxClass & box1, - const Vector3 & v1, - const Vector3 & axis, - float dt -) -{ - float ra,rb,rsum; - - if (axis.Length2() < WWMATH_EPSILON) return true; - - ra = box0.Project_To_Axis(axis); - rb = box1.Project_To_Axis(axis); - rsum = WWMath::Fabs(ra) + WWMath::Fabs(rb); - - // project the center distance onto the line: - Vector3 C = box1.Center - box0.Center; - Vector3 V = v1 - v0; - - float cdist = Vector3::Dot_Product(axis,C); - float vdist = cdist + dt * Vector3::Dot_Product(axis,V); - - if ((cdist > rsum && vdist > rsum) || (cdist < -rsum && vdist < -rsum)) { - return false; - } - return true; -} - - -/*********************************************************************************************** - * Oriented_Boxes_Collide -- test if two oriented boxes collide * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/99 GTH : Created. * - *=============================================================================================*/ -bool Oriented_Boxes_Collide -( - const OBBoxClass & box0, - const Vector3 & v0, - const OBBoxClass & box1, - const Vector3 & v1, - float dt -) -{ - bool intersect = true; - - // variables for holding the separating axis and the projected distances - Vector3 SepAxis; - - // vectors for the axis directions of the two boxes in world space - Vector3 A0(box0.Basis[0][0],box0.Basis[1][0],box0.Basis[2][0]); - Vector3 A1(box0.Basis[0][1],box0.Basis[1][1],box0.Basis[2][1]); - Vector3 A2(box0.Basis[0][2],box0.Basis[1][2],box0.Basis[2][2]); - - Vector3 B0(box1.Basis[0][0],box1.Basis[1][0],box1.Basis[2][0]); - Vector3 B1(box1.Basis[0][1],box1.Basis[1][1],box1.Basis[2][1]); - Vector3 B2(box1.Basis[0][2],box1.Basis[1][2],box1.Basis[2][2]); - - - ///////////////////////////////////////////////////////////////////////// - // L = A0 - // - // Projecting the two boxes onto Box0's X axis. If their intervals - // on this line do not intersect, the boxes are not intersecting! - // Each of the tests in this function work in a similar way. - ///////////////////////////////////////////////////////////////////////// - SepAxis = A0; - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A1 - // Separating Axis is Box0's Y axis - ///////////////////////////////////////////////////////////////////////// - SepAxis = A1; - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A2 - // Separating Axis is Box0's Z axis - ///////////////////////////////////////////////////////////////////////// - SepAxis = A2; - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = B0 - // Separating Axis is Box1's X axis - ///////////////////////////////////////////////////////////////////////// - SepAxis = B0; - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = B1 - // Separating Axis is Box1's Y axis - ///////////////////////////////////////////////////////////////////////// - SepAxis = B1; - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = B2 - // Separating Axis is Box1's Z axis - ///////////////////////////////////////////////////////////////////////// - SepAxis = B2; - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // None of the aligned axes turned out to be separating axes. Now - // we check all combinations of cross products of the two boxes axes. - ///////////////////////////////////////////////////////////////////////// - - ///////////////////////////////////////////////////////////////////////// - // L = A0xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A0,B0,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A0xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A0,B1,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A0xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A0,B2,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A1xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A1,B0,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A1xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A1,B1,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A1xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A1,B2,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A2xB0 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A2,B0,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A2xB1 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A2,B1,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - - ///////////////////////////////////////////////////////////////////////// - // L = A2xB2 - ///////////////////////////////////////////////////////////////////////// - Vector3::Cross_Product(A2,B2,&SepAxis); - - if (!Oriented_Boxes_Collide_On_Axis(box0,v0,box1,v1,SepAxis,dt)) { - intersect = false; - goto exit; - } - -exit: - - return intersect; -} - - - -/*********************************************************************************************** - * Oriented_Box_Intersects_Tri_On_Axis -- tests if the box and tri intersect on the axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/99 GTH : Created. * - *=============================================================================================*/ -bool Oriented_Box_Intersects_Tri_On_Axis(const OBBoxClass & box,const TriClass & tri,Vector3 & axis) -{ - float leb; // leading edge of box (farthest point from center) - float lep; // leading edge of poly (closest point to center) - float dist; // distance from box center to v0 - float tmp; - - if (axis.Length2() < WWMATH_EPSILON) return true; - - Vector3 D = *(tri.V[0]) - box.Center; - Vector3 r1 = *(tri.V[1]) - *(tri.V[0]); - Vector3 r2 = *(tri.V[2]) - *(tri.V[0]); - - // I want the axis to point from box.center to tri.v0 - dist = Vector3::Dot_Product(D,axis); - if (dist < 0) { - dist = -dist; - axis = -axis; - } - - // compute leading edge of the box - leb = box.Project_To_Axis(axis); - - // compute the leading edge of the triangle - lep = 0; - tmp = Vector3::Dot_Product(r1,axis); if (tmp < lep) lep = tmp; - tmp = Vector3::Dot_Product(r2,axis); if (tmp < lep) lep = tmp; - lep += dist; - - if (lep >= leb) { - return false; - } else { - return true; - } -} - - -/*********************************************************************************************** - * Oriented_Box_Intersects_Tri -- tests if the given box and tri intersect * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/99 GTH : Created. * - *=============================================================================================*/ -bool Oriented_Box_Intersects_Tri(const OBBoxClass & box,const TriClass & tri) -{ - Vector3 axis; - - // vectors for the axis directions of the two boxes in world space - Vector3 A[3]; - Vector3 E[3]; - Vector3 normal = *tri.N; - A[0].Set(box.Basis[0][0],box.Basis[1][0],box.Basis[2][0]); - A[1].Set(box.Basis[0][1],box.Basis[1][1],box.Basis[2][1]); - A[2].Set(box.Basis[0][2],box.Basis[1][2],box.Basis[2][2]); - E[0] = *(tri.V[1]) - *(tri.V[0]); - E[1] = *(tri.V[2]) - *(tri.V[1]); - E[2] = *(tri.V[0]) - *(tri.V[2]); - - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,normal)) return false; - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,A[0])) return false; - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,A[1])) return false; - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,A[2])) return false; - - Vector3::Cross_Product(A[0],E[0],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[0],E[1],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[0],E[2],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[1],E[0],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[1],E[1],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[1],E[2],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[2],E[0],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[2],E[1],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - Vector3::Cross_Product(A[2],E[2],&axis); - if (!Oriented_Box_Intersects_Tri_On_Axis(box,tri,axis)) return false; - - return true; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/obbox.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/obbox.h deleted file mode 100644 index 8706032598..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/obbox.h +++ /dev/null @@ -1,271 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwmath * - * * - * $Archive:: /Commando/Code/wwmath/obbox.h $* - * * - * Org Author:: Greg_h * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 24 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * OBBoxClass::Transform -- transform an oriented box * - * OBBoxClass::Project_To_Axis -- compute projection onto the given axis * - * OBBoxClass::Compute_Point -- computes position of a parametricly defined point * - * OBBoxClass::Compute_Axis_Aligned_Extent -- computes extent of an AABox enclosing this box * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef OBBOX_H -#define OBBOX_H - -#include "always.h" -#include "vector3.h" -#include "matrix3.h" -#include "matrix3d.h" -#include "wwmath.h" -#include "castres.h" - -class TriClass; -class AABoxClass; -class PlaneClass; - - -/* -** OBBoxClass -** -** Oriented-Bounding-Box Class. -** This is a collision box in world space. -** Center - position of the center of the box -** Extents - size of the box -** Basis - rotation matrix defining the orientation of the box -** -** To find the world space coordinates of the "+x,+y,+z" corner of -** the bounding box you could use this equation: -** Vector3 corner = Center + Basis * Extent; -*/ -class OBBoxClass -{ -public: - - OBBoxClass(void) { } - - OBBoxClass(const OBBoxClass & that) : - Basis(that.Basis), - Center(that.Center), - Extent(that.Extent) - { } - - OBBoxClass(const Vector3 & center,const Vector3 & extent) : - Basis(1), - Center(center), - Extent(extent) - { } - - OBBoxClass(const Vector3 & center,const Vector3 & extent,const Matrix3x3 & basis) : - Basis(basis), - Center(center), - Extent(extent) - { } - - OBBoxClass(const Vector3 * points, int num_points); - - bool operator== (const OBBoxClass &src); - bool operator!= (const OBBoxClass &src); - - void Init_From_Box_Points(Vector3 * points,int num_points); - void Init_Random(float min_extent = 0.5f,float max_extent = 1.0f); - float Project_To_Axis(const Vector3 & axis) const; - float Volume(void) const { return 2.0*Extent.X * 2.0*Extent.Y * 2.0*Extent.Z; } - void Compute_Point(float params[3],Vector3 * set_point) const; - void Compute_Axis_Aligned_Extent(Vector3 * set_extent) const; - - Matrix3x3 Basis; - Vector3 Center; - Vector3 Extent; - - static void Transform(const Matrix3D & tm,const OBBoxClass & in,OBBoxClass * out); -}; - -// Test functions: slow, easy to understand version of box intersection code :) -bool Oriented_Boxes_Intersect(const OBBoxClass & box0,const OBBoxClass & box1); -bool Oriented_Boxes_Collide(const OBBoxClass & box0,const Vector3 & v0,const OBBoxClass & box1,const Vector3 & v1,float dt); -bool Oriented_Box_Intersects_Tri(const OBBoxClass & box,const TriClass & tri); - - -/*********************************************************************************************** - * OBBoxClass::Project_To_Axis -- compute projection onto the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline float OBBoxClass::Project_To_Axis(const Vector3 & axis) const -{ - float x = Extent[0] * Vector3::Dot_Product(axis,Vector3(Basis[0][0],Basis[1][0],Basis[2][0])); - float y = Extent[1] * Vector3::Dot_Product(axis,Vector3(Basis[0][1],Basis[1][1],Basis[2][1])); - float z = Extent[2] * Vector3::Dot_Product(axis,Vector3(Basis[0][2],Basis[1][2],Basis[2][2])); - - // projection is the sum of the absolute values of the projections of the three extents - return (WWMath::Fabs(x) + WWMath::Fabs(y) + WWMath::Fabs(z)); -} - - -/*********************************************************************************************** - * OBBoxClass::Transform -- transform an oriented box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void OBBoxClass::Transform -( - const Matrix3D & tm, - const OBBoxClass & in, - OBBoxClass * out -) -{ - WWASSERT(out); - WWASSERT(out!=&in); - - out->Extent = in.Extent; - Matrix3D::Transform_Vector(tm,in.Center,&(out->Center)); - Matrix3x3::Multiply(tm,in.Basis,&(out->Basis)); -} - - -/*********************************************************************************************** - * OBBoxClass::Compute_Point -- computes position of a parametricly defined point * - * * - * set_point = Center + params[0]*A0 + params[1]*A1 + params[2]*A2 * - * * - * INPUT: * - * params - parametric description of a point in the box. -1 < params[i] < 1 * - * set_point - pointer to a Vector3 to set. * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/2/99 GTH : Created. * - *=============================================================================================*/ -inline void OBBoxClass::Compute_Point(float params[3],Vector3 * set_point) const -{ - Vector3 point = Extent; - point.X *= params[0]; - point.Y *= params[1]; - point.Z *= params[2]; - - Matrix3x3::Rotate_Vector(Basis,point,set_point); - Vector3::Add(Center,*set_point,set_point); -} - - -/*********************************************************************************************** - * OBBoxClass::Compute_Axis_Aligned_Extent -- computes extent of an AABox enclosing this box * - * * - * INPUT: * - * set_extent - pointer to a Vector3 to put the result into * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/15/99 gth : Created. * - *=============================================================================================*/ -inline void OBBoxClass::Compute_Axis_Aligned_Extent(Vector3 * set_extent) const -{ - WWASSERT(set_extent != NULL); - - // x extent is the box projected onto the x axis - set_extent->X = WWMath::Fabs(Extent[0] * Basis[0][0]) + - WWMath::Fabs(Extent[1] * Basis[0][1]) + - WWMath::Fabs(Extent[2] * Basis[0][2]); - - set_extent->Y = WWMath::Fabs(Extent[0] * Basis[1][0]) + - WWMath::Fabs(Extent[1] * Basis[1][1]) + - WWMath::Fabs(Extent[2] * Basis[1][2]); - - set_extent->Z = WWMath::Fabs(Extent[0] * Basis[2][0]) + - WWMath::Fabs(Extent[1] * Basis[2][1]) + - WWMath::Fabs(Extent[2] * Basis[2][2]); -} - - -/*********************************************************************************************** - * OBBoxClass::operator== -- Comparison operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/21/00 PDS : Created. * - *=============================================================================================*/ -inline bool OBBoxClass::operator== (const OBBoxClass &src) -{ - return (Center == src.Center) && (Extent == src.Extent) && (Basis == src.Basis); -} - - -/*********************************************************************************************** - * OBBoxClass::operator!= -- Comparison operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/21/00 PDS : Created. * - *=============================================================================================*/ -inline bool OBBoxClass::operator!= (const OBBoxClass &src) -{ - return (Center != src.Center) || (Extent != src.Extent) && (Basis == src.Basis); -} - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/ode.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/ode.cpp deleted file mode 100644 index 0926eba4e0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/ode.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/ODE.CPP 8 7/02/99 10:32a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /Commando/Code/wwmath/ODE.CPP $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 6/25/99 6:23p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Euler_Integrate -- uses Eulers method to integrate a system of ODE's * - * Midpoint_Integrate -- midpoint method (Runge-Kutta 2) for integration * - * Runge_Kutta_Integrate -- Runge Kutta 4 method * - * Runge_Kutta5_Integrate -- 5th order Runge-Kutta * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "ode.h" -#include - -static StateVectorClass Y0; -static StateVectorClass Y1; -static StateVectorClass _WorkVector0; -static StateVectorClass _WorkVector1; -static StateVectorClass _WorkVector2; -static StateVectorClass _WorkVector3; -static StateVectorClass _WorkVector4; -static StateVectorClass _WorkVector5; -static StateVectorClass _WorkVector6; -static StateVectorClass _WorkVector7; - -/*********************************************************************************************** - * Euler_Solve -- uses Eulers method to integrate a system of ODE's * - * * - * INPUT: * - * odesys - pointer to the ODE system to integrate * - * dt - size of the timestep * - * * - * OUTPUT: * - * state vector in odesys will be updated for the next timestep * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - * 6/25/99 GTH : Updated to the new integrator system * - *=============================================================================================*/ -void IntegrationSystem::Euler_Integrate(ODESystemClass * sys, float dt) -{ - WWASSERT(sys != NULL); - - /* - ** Get the current state - */ - Y0.Reset(); - sys->Get_State(Y0); - Y1.Resize(Y0.Count()); - - /* - ** make aliases to the work-vectors we need - */ - StateVectorClass & dydt = _WorkVector0; - dydt.Resize(Y0.Count()); - - /* - ** Euler method, just evaluate the derivative, multiply - ** by the time-step and add to the current state vector. - */ - sys->Compute_Derivatives(0,NULL,&dydt); - - Y1.Resize(Y0.Count()); - for (int i = 0; i < Y0.Count(); i++) { - Y1[i] = Y0[i] + dydt[i] * dt; - } - - sys->Set_State(Y1); -} - -/*********************************************************************************************** - * Midpoint_Integrate -- midpoint method (Runge-Kutta 2) * - * * - * INPUT: * - * sys - pointer to the ODE system to integrate * - * dt - size of the timestep * - * * - * OUTPUT: * - * state vector in odesys will be updated for the next timestep * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - * 6/25/99 GTH : Updated to the new integrator system * - *=============================================================================================*/ -void IntegrationSystem::Midpoint_Integrate(ODESystemClass * sys,float dt) -{ - int i; - - /* - ** Get the current state - */ - Y0.Reset(); - sys->Get_State(Y0); - Y1.Resize(Y0.Count()); - - /* - ** make aliases to the work-vectors we need - */ - StateVectorClass & dydt = _WorkVector0; - StateVectorClass & ymid = _WorkVector1; - dydt.Resize(Y0.Count()); - ymid.Resize(Y0.Count()); - - /* - ** MidPoint method, first evaluate the derivitives of the - ** state vector just like the Euler method. - */ - sys->Compute_Derivatives(0.0f,NULL,&dydt); - - /* - ** Compute the midpoint between the Euler solution and - ** the input values. - */ - for (i=0; iCompute_Derivatives(dt/2.0f,&ymid,&dydt); - - /* - ** Use these derivatives to compute the solution. - */ - for (i=0; iSet_State(Y1); -} - - -/*********************************************************************************************** - * Runge_Kutta_Integrate -- Runge Kutta 4 method * - * * - * INPUT: * - * odesys - pointer to the ODE system to integrate * - * dt - size of the timestep * - * * - * OUTPUT: * - * state vector in odesys will be updated for the next timestep * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -void IntegrationSystem::Runge_Kutta_Integrate(ODESystemClass * sys,float dt) -{ - int i; - float dt2 = dt / 2.0f; - float dt6 = dt / 6.0f; - - /* - ** Get the current state - */ - Y0.Reset(); - sys->Get_State(Y0); - Y1.Resize(Y0.Count()); - - /* - ** make aliases to the work-vectors we need - */ - StateVectorClass & dydt = _WorkVector0; - StateVectorClass & dym = _WorkVector1; - StateVectorClass & dyt = _WorkVector2; - StateVectorClass & yt = _WorkVector3; - dydt.Resize(Y0.Count()); - dym.Resize(Y0.Count()); - dyt.Resize(Y0.Count()); - yt.Resize(Y0.Count()); - - /* - ** First Step - */ - sys->Compute_Derivatives(0.0f,NULL,&dydt); - for (i=0; iCompute_Derivatives(dt2, &yt, &dyt); - for (i=0; iCompute_Derivatives(dt2, &yt, &dym); - for (i=0; iCompute_Derivatives(dt, &yt, &dyt); - for (i=0; iSet_State(Y1); -} - -/*********************************************************************************************** - * Runge_Kutta5_Integrate -- 5th order Runge-Kutta * - * * - * INPUT: * - * odesys - pointer to the ODE system to integrate * - * dt - size of the timestep * - * * - * OUTPUT: * - * state vector in odesys will be updated for the next timestep * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - * 6/25/99 GTH : Converted to the new Integrator system * - *=============================================================================================*/ -void IntegrationSystem::Runge_Kutta5_Integrate(ODESystemClass * odesys,float dt) -{ - int i; - int veclen; - static const float a2 = 0.2f; - static const float a3 = 0.3f; - static const float a4 = 0.6f; - static const float a5 = 1.0f; - static const float a6 = 0.875f; - static const float b21 = 0.2f; - static const float b31 = 3.0f/40.0f; - static const float b32 = 9.0f/40.0f; - static const float b41 = 0.3f; - static const float b42 = -0.9f; - static const float b43 = 1.2f; - static const float b51 = -11.0f /54.0f; - static const float b52 = 2.5f; - static const float b53 = -70.0f/27.0f; - static const float b54 = 35.0f/27.0f; - static const float b61 = 1631.0f/55296.0f; - static const float b62 = 175.0f/512.0f; - static const float b63 = 575.0f/13824.0f; - static const float b64 = 44275.0f/110592.0f; - static const float b65 = 253.0f/4096.0f; - static const float c1 = 37.0f/378.0f; - static const float c3 = 250.0f/621.0f; - static const float c4 = 125.0f/594.0f; - static const float c6 = 512.0f/1771.0f; - static const float dc5 = -277.0f/14336.0f; - static const float dc1 = c1 - 2825.0f/27648.0f; - static const float dc3 = c3 - 18575.0f/48384.0f; - static const float dc4 = c4 - 13525.0f/55296.0f; - static const float dc6 = c6 - 0.25f; - - /* - ** Get the current state - */ - Y0.Reset(); - odesys->Get_State(Y0); - veclen = Y0.Count(); - Y1.Resize(veclen); - - /* - ** make aliases to the work-vectors we need - */ - StateVectorClass & dydt = _WorkVector0; - StateVectorClass & ak2 = _WorkVector1; - StateVectorClass & ak3 = _WorkVector2; - StateVectorClass & ak4 = _WorkVector3; - StateVectorClass & ak5 = _WorkVector4; - StateVectorClass & ak6 = _WorkVector5; - StateVectorClass & ytmp = _WorkVector6; - StateVectorClass & yerr = _WorkVector7; - - dydt.Resize(veclen); - ak2.Resize(veclen); - ak3.Resize(veclen); - ak4.Resize(veclen); - ak5.Resize(veclen); - ak6.Resize(veclen); - ytmp.Resize(veclen); - yerr.Resize(veclen); - - // First step - odesys->Compute_Derivatives(0.0f,NULL,&dydt); - for (i=0;iCompute_Derivatives(a2*dt, &ytmp, &ak2); - for (i=0; iCompute_Derivatives(a3*dt, &ytmp, &ak3); - for (i=0; iCompute_Derivatives(a4*dt, &ytmp, &ak4); - for (i=0; iCompute_Derivatives(a5*dt, &ytmp, &ak5); - for (i=0; iCompute_Derivatives(a6*dt, &ytmp, &ak6); - for (i=0; iSet_State(Y1); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/ode.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/ode.h deleted file mode 100644 index ffaf630028..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/ode.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /G/wwmath/ode.h 9 9/21/99 5:54p Neal_k $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando * - * * - * $Archive:: /G/wwmath/ode.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 9/21/99 5:54p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef ODE_H -#define ODE_H - -#include "always.h" -#include "Vector.H" -#include "wwdebug.h" - - -/* -** StateVectorClass -** The state vector for a system of ordinary differential equations will be -** stored in this form. It is a dynamically resizeable array so that we don't -** have to hard-code a maximum size. If needed, in the final product, we could -** do a slight optimization which makes this a normal fixed size array that -** we've determined is "big enough". -*/ -class StateVectorClass : public DynamicVectorClass -{ -public: - void Reset(void) { ActiveCount = 0; } - void Resize(int size) { if (size > VectorMax) { DynamicVectorClass::Resize(size); } } -}; - - -/* -** ODESystemClass -** If a system of Ordinary Differential Equations (ODE's) are put behind an interface -** of this type, they can be integrated using the Integrators defined in this module. -*/ -class ODESystemClass -{ - -public: - - /* - ** Get_Current_State - ** This function should fill the given state vector with the - ** current state of this object. Each state variable should be - ** inserted into the vector using its 'Add' interface. - */ - virtual void Get_State(StateVectorClass & set_state) = 0; - - /* - ** Set_Current_State - ** This function should read its state from this state vector starting from the - ** given index. The return value should be the index that the next object should - ** read from (i.e. increment the index past your state) - */ - virtual int Set_State(const StateVectorClass & new_state,int start_index = 0) = 0; - - /* - ** Compute_Derivatives - ** The various ODE solvers will use this interface to ask the ODESystemClass to - ** compute the derivatives of their state. In some cases, the integrator will - ** pass in a new state vector (test_state) to be used when computing the derivatives. - ** NULL will be passed if they want the derivatives for the initial state. - ** This function works similarly to the Set_State function in that it passes you - ** the index to start reading from and you pass it back the index to continue from. - */ - virtual int Compute_Derivatives(float t,StateVectorClass * test_state,StateVectorClass * dydt,int start_index = 0) = 0; - -}; - - -/* -** IntegrationSystem -** -** The Euler_Solve is the simplest but most inaccurate. It requires only -** a single computation of the derivatives per timestep. -** -** The Midpoint_Solve function will evaluate the derivatives at two points -** -** The Runge_Kutta_Solve requires four evaluations of the derivatives. -** This is the fourth order Runge-Kutta method... -** -** Runge_Kutta5_Solve is an implementation of fifth order Runge- -** Kutta. It requires six evaluations of the derivatives. -*/ - -class IntegrationSystem -{ -public: - - static void Euler_Integrate(ODESystemClass * sys,float dt); - static void Midpoint_Integrate(ODESystemClass * sys,float dt); - static void Runge_Kutta_Integrate(ODESystemClass * sys,float dt); - static void Runge_Kutta5_Integrate(ODESystemClass * odesys,float dt); - -}; - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/plane.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/plane.h deleted file mode 100644 index f607a68541..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/plane.h +++ /dev/null @@ -1,250 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/plane.h 16 5/05/01 5:48p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : PLANE.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 03/17/97 * - * * - * Last Update : March 17, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef PLANE_H -#define PLANE_H - -#include "always.h" -#include "vector3.h" -#include "sphere.h" - -/* -** PlaneClass -** -** 3D-planes. This class uses the Normal+Distance description of a plane. -** The relationship for all points (p) on the plane is given by: -** -** N.X * p.X + N.Y * p.Y + N.Z * p.Z = D -** -** BEWARE, if you are used to the Ax + By + Cz + D = 0 description, the -** sign of the D value is inverted. -*/ - -class PlaneClass -{ -public: - - enum { FRONT = 0, BACK, ON }; - - Vector3 N; // Normal of the plane - float D; // Distance along the normal from the origin - - PlaneClass(void) : N(0.0f,0.0f,1.0f), D(0.0f) { } - - /* - ** Plane initialization: - ** a,b,c,d - explicitly set the four coefficients (note the sign of d!) - ** normal,dist - explicitly set the normal and distance - ** normal,point - compute plane with normal, containing point - ** p1,p2,p3 - compute plane containing three points - */ - PlaneClass(float nx,float ny,float nz,float dist); - PlaneClass(const Vector3 & normal,float dist); - PlaneClass(const Vector3 & normal,const Vector3 & point); - PlaneClass(const Vector3 & point1,const Vector3 & point2,const Vector3 & point3); - - inline void Set(float a,float b,float c,float d); - inline void Set(const Vector3 & normal,float dist); - inline void Set(const Vector3 & normal,const Vector3 & point); - inline void Set(const Vector3 & point1,const Vector3 & point2,const Vector3 & point3); - - bool Compute_Intersection(const Vector3 & p0,const Vector3 & p1,float * set_t) const; - bool In_Front(const Vector3 & point) const; - bool In_Front(const SphereClass & sphere) const; - bool In_Front_Or_Intersecting(const SphereClass & sphere) const; - - static void Intersect_Planes(const PlaneClass & a, const PlaneClass & b, Vector3 *line_dir, Vector3 *line_point); -}; - -inline PlaneClass::PlaneClass(float nx,float ny,float nz,float dist) -{ - Set(nx,ny,nz,dist); -} - -inline PlaneClass::PlaneClass(const Vector3 & normal,float dist) -{ - Set(normal,dist); -} - -inline PlaneClass::PlaneClass(const Vector3 & normal,const Vector3 & point) -{ - Set(normal,point); -} - -inline PlaneClass::PlaneClass(const Vector3 & point1, const Vector3 & point2, const Vector3 & point3) -{ - Set(point1,point2,point3); -} - -inline void PlaneClass::Set(float a,float b,float c,float d) -{ - N.X = a; - N.Y = b; - N.Z = c; - D = d; -} - -inline void PlaneClass::Set(const Vector3 & normal,float dist) -{ - N = normal; - D = dist; -} - -inline void PlaneClass::Set(const Vector3 & normal,const Vector3 & point) -{ - N = normal; - D = Vector3::Dot_Product(normal , point); -} - - -inline void PlaneClass::Set(const Vector3 & point1, const Vector3 & point2, const Vector3 & point3) -{ -#ifdef ALLOW_TEMPORARIES - N = Vector3::Cross_Product((point2 - point1), (point3 - point1)); -#else - Vector3::Cross_Product((point2 - point1), (point3 - point1), &N); -#endif - if (N != Vector3(0.0f, 0.0f, 0.0f)) { - // Points are not colinear. Normalize N and calculate D. - N.Normalize(); - D = Vector3::Dot_Product(N, point1); - } else { - // They are colinear - return default plane (constructors can't fail). - N = Vector3(0.0f, 0.0f, 1.0f); - D = 0.0f; - } -} - -inline bool PlaneClass::Compute_Intersection(const Vector3 & p0,const Vector3 & p1,float * set_t) const -{ - float num,den; - den = Vector3::Dot_Product(N,p1-p0); - - /* - ** If the denominator is zero, the ray is parallel to the plane - */ - if (den == 0.0f) { - return false; - } - - num = -(Vector3::Dot_Product(N,p0) - D); - - *set_t = num/den; - - /* - ** If t is not between 0 and 1, the line containing the segment intersects - ** the plane but the segment does not - */ - if ((*set_t < 0.0f) || (*set_t > 1.0f)) { - return false; - } - - return true; -} - -inline bool PlaneClass::In_Front(const Vector3 & point) const -{ - float dist = Vector3::Dot_Product(point,N); - return (dist > D); -} - -// This function returns true if the sphere is in front of the plane. -inline bool PlaneClass::In_Front(const SphereClass & sphere) const -{ - float dist = Vector3::Dot_Product(sphere.Center,N); - return ((dist - D) >= sphere.Radius); -} - -// This function will return 1 if any part of the sphere is in front of the plane. -// (i.e. if the sphere is entirely in front of the plane or if it intersects the plane). -inline bool PlaneClass::In_Front_Or_Intersecting(const SphereClass & sphere) const -{ - float dist = Vector3::Dot_Product(sphere.Center , N); - return ((D - dist) < sphere.Radius); -} - -inline void PlaneClass::Intersect_Planes(const PlaneClass & a, const PlaneClass & b, Vector3 *line_dir, Vector3 *line_point) -{ - // Method used is from "plane-to-plane intersection", Graphics Gems III, pp. 233-235. - - // Find line of intersection. First find direction vector of line: - Vector3::Cross_Product(a.N, b.N, line_dir); - - // Now find point on line. How we do it depends on what the largest coordinate of the - // direction vector is. - Vector3 abs_dir = *line_dir; - abs_dir.Update_Max(-abs_dir); - if (abs_dir.X > abs_dir.Y) { - if (abs_dir.X > abs_dir.Z) { - // X largest - float ool = 1.0f / line_dir->X; - line_point->Y = (b.N.Z * a.D - a.N.Z * b.D) * ool; - line_point->Z = (a.N.Y * b.D - b.N.Y * a.D) * ool; - line_point->X = 0.0f; - } else { - // Z largest - float ool = 1.0f / line_dir->Z; - line_point->X = (b.N.Y * a.D - a.N.Y * b.D) * ool; - line_point->Y = (a.N.X * b.D - b.N.X * a.D) * ool; - line_point->Z = 0.0f; - } - } else { - if (abs_dir.Y > abs_dir.Z) { - // Y largest - float ool = 1.0f / line_dir->Y; - line_point->Z = (b.N.X * a.D - a.N.X * b.D) * ool; - line_point->X = (a.N.Z * b.D - b.N.Z * a.D) * ool; - line_point->Y = 0.0f; - } else { - // Z largest - float ool = 1.0f / line_dir->Z; - line_point->X = (b.N.Y * a.D - a.N.Y * b.D) * ool; - line_point->Y = (a.N.X * b.D - b.N.X * a.D) * ool; - line_point->Z = 0.0f; - } - } - - // Normalize direction vector (we do it here because we needed the non-normalized version to - // find the point). - line_dir->Normalize(); -} - -#endif /*PLANE_H*/ diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/pot.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/pot.cpp deleted file mode 100644 index ea20b93374..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/pot.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /G/ww3d/POT.CPP $* - * * - * $Author:: Naty_h $* - * * - * $Modtime:: 12/23/98 7:58a $* - * * - * $Revision:: 3 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * Find_POT -- finds closest inclusive power of 2 to a value * - * Find_POT_Log2 -- finds log2 of closest inclusive power of 2 to a value* - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "pot.h" - -/************************************************************************** - * Find_POT -- finds closest inclusive power of 2 to a value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/1997 PWG : Created. * - *========================================================================*/ -int Find_POT(int val) -{ - // clear out the recorded position and the recorded count - int recpos = 0; - int reccnt = 0; - - // walk through the value shifting off bits and record the - // position of the highest bit, and whether we have found - // more than one bit. - for (int lp = 0; val; lp++) { - if (val & 1) { - recpos = lp; - reccnt++; - } - val >>= 1; - } - // if we have not found more than one bit then the number - // was the power of two so return it. - if (reccnt < 2) { - return( 1 << recpos); - } - // if we found more than one bit, then the number needs to - // be rounded up to the next highest power of 2. - return( 1 << (recpos + 1)); -} - - -/************************************************************************** - * Find_POT_Log2 -- finds log2 of closest inclusive power of 2 to a value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/23/1998 NH : Created. * - *========================================================================*/ -unsigned int Find_POT_Log2(unsigned int val) -{ - // clear out the recorded position and the recorded count - int recpos = 0; - int reccnt = 0; - - // walk through the value shifting off bits and record the - // position of the highest bit, and whether we have found - // more than one bit. - for (int lp = 0; val; lp++) { - if (val & 1) { - recpos = lp; - reccnt++; - } - val >>= 1; - } - // if we have not found more than one bit then the number - // was the power of two so return it. - if (reccnt < 2) { - return recpos; - } - // if we found more than one bit, then the number needs to - // be rounded up to the next highest power of 2. - return recpos + 1; -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/pot.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/pot.h deleted file mode 100644 index 8b8cff5e90..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/pot.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /G/ww3d/POT.H $* - * * - * $Author:: Naty_h $* - * * - * $Modtime:: 12/23/98 7:51a $* - * * - * $Revision:: 4 $* - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __POT_H__ -#define __POT_H__ -int Find_POT(int val); -unsigned int Find_POT_Log2(unsigned int val); -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/quat.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/quat.cpp deleted file mode 100644 index 691b24ed2a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/quat.cpp +++ /dev/null @@ -1,895 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/quat.cpp 38 8/28/01 10:26a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : QUAT.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 28, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Quaternion::Quaternion -- constructor * - * Quaternion::Set -- Set the quaternion * - * Quaternion::operator= -- Assignment operator * - * Quaternion::Make_Closest -- Use nearest representation to the given quaternion. * - * Trackball -- Computes a "trackball" quaternion given 2D mouse coordinates * - * Axis_To_Quat -- Creates a quaternion given an axis and angle of rotation * - * Slerp -- Spherical Linear interpolation! * - * Build_Quaternion -- Creates a quaternion from a Matrix * - * Build_Matrix -- Creates a Matrix from a Quaternion * - * Normalize -- normalizes a quaternion * - * Quaternion::Quaternion -- constructor * - * Slerp_Setup -- Get ready to call "Cached_Slerp" * - * Cached_Slerp -- Quaternion slerping, optimized with cached values * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "quat.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "wwmath.h" - -#include -#include -#include -#include - -#define SLERP_EPSILON 0.001 - -static int _nxt[3] = { 1 , 2 , 0 }; - - -// ------------------------------------------------------------ -// local functions -// ------------------------------------------------------------ -static float project_to_sphere(float,float,float); - - -/*********************************************************************************************** - * Quaternion::Quaternion -- constructor * - * * - * constructs a quaternion from the given axis and angle of rotation (in RADIANS of course) * - * * - * INPUT: * - * axis - axis of the rotation * - * angle - rotation angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/10/97 GTH : Created. * - *=============================================================================================*/ -Quaternion::Quaternion(const Vector3 & axis,float angle) -{ - float s = WWMath::Sin(angle/2); - float c = WWMath::Cos(angle/2); - X = s * axis.X; - Y = s * axis.Y; - Z = s * axis.Z; - W = c; -} - - -/*********************************************************************************************** - * Quaternion::Normalize -- Normalize to a unit quaternion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -void Quaternion::Normalize() -{ - float len2=X * X + Y * Y + Z * Z + W * W; - if (0.0f == len2) { - return; - } else { - float inv_mag = WWMath::Inv_Sqrt(len2); - - X *= inv_mag; - Y *= inv_mag; - Z *= inv_mag; - W *= inv_mag; - } -} - -/*********************************************************************************************** - * Q::Make_Closest -- Use nearest representation to the given quaternion. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion & Quaternion::Make_Closest(const Quaternion & qto) -{ - float cos_t = qto.X * X + qto.Y * Y + qto.Z * Z + qto.W * W; - - // if we are on opposite hemisphere from qto, negate ourselves - if (cos_t < 0.0) { - X = -X; - Y = -Y; - Z = -Z; - W = -W; - } - - return *this; -} - -/*********************************************************************************************** - * Trackball -- Computes a "trackball" quaternion given 2D mouse coordinates * - * * - * INPUT: * - * x0,y0 - x1,y1 - "normalized" mouse coordinates for the mouse movement * - * sphsize - size of the trackball sphere * - * * - * OUTPUT: * - * a quaternion representing the rotation of a trackball * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Trackball(float x0, float y0, float x1, float y1, float sphsize) -{ - Vector3 a; - Vector3 p1; - Vector3 p2; - Vector3 d; - - float phi,t; - - if ((x0 == x1) && (y0 == y1)) { - return Quaternion(0.0f, 0.0f, 0.0f, 1.0f); // Zero rotation - } - - - // Compute z coordinates for projection of p1 and p2 to - // deformed sphere - p1[0] = x0; - p1[1] = y0; - p1[2] = project_to_sphere(sphsize, x0, y0); - - p2[0] = x1; - p2[1] = y1; - p2[2] = project_to_sphere(sphsize, x1, y1); - - - // Find their cross product - Vector3::Cross_Product(p2,p1,&a); - - // Compute how much to rotate - d = p1 - p2; - t = d.Length() / (2.0f * sphsize); - - // Avoid problems with out of control values - if (t > 1.0f) t = 1.0f; - if (t < -1.0f) t = -1.0f; - phi = 2.0f * WWMath::Asin(t); - - return Axis_To_Quat(a, phi); -} - - -/*********************************************************************************************** - * Axis_To_Quat -- Creates a quaternion given an axis and angle of rotation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Axis_To_Quat(const Vector3 &a, float phi) -{ - Quaternion q; - Vector3 tmp = a; - - tmp.Normalize(); - q[0] = tmp[0]; - q[1] = tmp[1]; - q[2] = tmp[2]; - - q.Scale(WWMath::Sin(phi / 2.0f)); - q[3] = WWMath::Cos(phi / 2.0f); - - return q; -} - -/*********************************************************************************************** - * Slerp -- Spherical Linear interpolation! * - * * - * INPUT: * - * p - start quaternion * - * q - end quaternion * - * alpha - interpolating parameter * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ - -#if 0 -#pragma warning (disable : 4725) - -#define ARC_TABLE_SIZE_MASK 1023 -#define SIN_TABLE_SIZE_MASK 1023 - -void __cdecl Fast_Slerp(Quaternion& res, const Quaternion & p,const Quaternion & q,float alpha) -{ - float float_epsilon2=WWMATH_EPSILON * WWMATH_EPSILON; - float HalfOfArcTableSize=float(ARC_TABLE_SIZE/2); - float HalfOfSinTableSize=float(SIN_TABLE_SIZE/2); - const unsigned ARC_TABLE_SIZE_PER_2=ARC_TABLE_SIZE/2; - - float beta; // complementary interploation parameter - float theta; // angle between p and q - - __asm { - mov esi, p - mov edi, q - fld1 // we'll need 1.0 and 0.0 later - -// ---------------------------------------------------------------------------- -// cos theta = dot product of p and q -// cos_t = p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W; -// if q is on opposite hemisphere from A, use -B instead -// if (cos_t < 0.0) { -// cos_t = -cos_t; -// qflip = true; -// } -// else { -// qflip = false; -// } -// ---------------------------------------------------------------------------- - - fld dword ptr [esi] // p.X - fmul dword ptr [edi] // p.X*q.X - fld dword ptr [esi+08h] // p.Y - fmul dword ptr [edi+08h] // p.Y*q.Y - fld dword ptr [esi+04h] // p.Z - fmul dword ptr [edi+04h] // p.Z*q.Z - fld dword ptr [edi+0ch] // p.W - fmul dword ptr [esi+0ch] // p.W*q.W - faddp st(2), st(0) // y+=w - faddp st(2), st(0) // x+=z - faddp st(1),st(0) // x+z + y+w - fst beta - fabs - mov ebx,beta - and ebx,0x80000000 - -// ---------------------------------------------------------------------------- -// if q is very close to p, just linearly interpolate -// between the two. -// if (1.0 - cos_t < WWMATH_EPSILON * WWMATH_EPSILON) { -// beta = 1.0 - alpha; -// } -// ---------------------------------------------------------------------------- - - fld st(0) // duplicate st(0), which contains cos_t - fsubr st(0),st(2) // st(2) contains 1.0 - fcomp float_epsilon2 - fnstsw ax - test ah, 01h - je normal_slerp - - fld alpha - fsubr st(0),st(1) // st(1) contains 1.0 - fstp beta - jmp done_slerp - -normal_slerp: -// ---------------------------------------------------------------------------- -// normal slerp! -// else { -// theta = WWMath::Acos(cos_t); -// sin_t = WWMath::Sin(theta); -// oo_sin_t = 1.0 / sin_t; -// beta = WWMath::Sin(theta - alpha*theta) * oo_sin_t; -// alpha = WWMath::Sin(alpha*theta) * oo_sin_t; -// } -// if (qflip) { -// alpha = -alpha; -// } -// ---------------------------------------------------------------------------- - - fld HalfOfSinTableSize - fld HalfOfArcTableSize - fmul st(0),st(2) // cos_t * (ARC_TABLE_SIZE/2) - fistp theta // convert to integer - mov eax,theta - add eax,ARC_TABLE_SIZE_PER_2 - jns no_neg - xor eax,eax - jmp contin -no_neg: - cmp eax,ARC_TABLE_SIZE - jl contin // Note: Use Setcc/Movcc here!!! - mov eax,ARC_TABLE_SIZE_MASK -contin: - fld dword ptr[_FastAcosTable+eax*4] - fst theta - - fmul st(0),st(1) // theta * (sin_table_size/2) - fadd st(0),st(1) // theta * (sin_table_size/2) + (sin_table_size/2) - fistp beta // conver to integer - mov ecx,SIN_TABLE_SIZE_MASK - mov eax,beta - and eax,ecx // & SIN_TABLE_SIZE_MASK - fld dword ptr[_FastInvSinTable+eax*4] // 1.0f/sin(theta) - - fld theta - fmul alpha // theta*alpha - fld st(0) // duplicate stack head as we need theta*alpha later - fsubr theta // theta-theta*alpha - - fmul st(0),st(3) // (theta-theta*alpha)*HalfOfSinTableSize - fadd st(0),st(3) // (theta-theta*alpha)*HalfOfSinTableSize+HalfOfSinTableSize - fistp beta // convert to integer - mov eax,beta - and eax,ecx // & SIN_TABLE_SIZE_MASK - fld dword ptr[_FastSinTable+eax*4] // sin(theta-theta*alpha) - - fmul st(0),st(2) // sin(theta-theta*alpha) * oo_sin_t - fstp beta - - fmul st(0),st(2) // (theta*alpha)*HalfOfSinTableSize - fadd st(0),st(2) // (theta*alpha)*HalfOfSinTableSize+HalfOfSinTableSize - fistp theta // convert to integer - mov eax,theta - and eax,ecx // & SIN_TABLE_SIZE_MASK - fld dword ptr[_FastSinTable+eax*4] // sin(theta*alpha) - - fmul st(0),st(1) // oo_sin_t - fstp alpha - fstp st(0) // pop oo_sin_t - fstp st(0) // pop HalfOfSinTableSize -done_slerp: - test ebx, ebx - je no_negative - fld alpha - fchs - fstp alpha - -no_negative: -// ---------------------------------------------------------------------------- -// res.X = beta*p.X + alpha*q.X; -// res.Y = beta*p.Y + alpha*q.Y; -// res.Z = beta*p.Z + alpha*q.Z; -// res.W = beta*p.W + alpha*q.W; -// ---------------------------------------------------------------------------- - - fstp st(0) // pop cos_t - fstp st(0) // pop 1.0 - - fld alpha - fld dword ptr [edi+4] // q.Y - fmul st(0),st(1) // alpha*q.Y - fld dword ptr [edi+8] // q.Z - fmul st(0),st(2) // alpha*q.Z - fld dword ptr [edi+12] // q.W - fmul st(0),st(3) // alpha*q.W - fld dword ptr [edi] // q.X - fmulp st(4),st // alpha*q.X - - fld beta - fld dword ptr [esi+4] // p.Y - fmul st(0),st(1) // beta*p.Y - fld dword ptr [esi+8] // p.Z - fmul st(0),st(2) // beta*p.Z - fld dword ptr [esi] // p.X - fmul st(0),st(3) // beta*p.X - fxch st(3) // move beta to top of stack - fmul dword ptr [esi+12] // beta*p.W - - faddp st(4),st // w - faddp st(4),st // z - faddp st(4),st // y - faddp st(4),st // x - - mov ecx, res - fstp [ecx+12] // w - fstp [ecx+8] // z - fstp [ecx+4] // y - fstp [ecx] // x - } -} -#else -void __cdecl Fast_Slerp(Quaternion& res, const Quaternion & p,const Quaternion & q,float alpha) -{ - float beta; // complementary interploation parameter - float theta; // angle between p and q - float cos_t; // sine, cosine of theta - float oo_sin_t; - int qflip; // use flip of q? - - // cos theta = dot product of p and q - cos_t = p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W; - - // if q is on opposite hemisphere from A, use -B instead - if (cos_t < 0.0f) { - cos_t = -cos_t; - qflip = true; - } else { - qflip = false; - } - - if (1.0f - cos_t < WWMATH_EPSILON * WWMATH_EPSILON) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0f - alpha; - - } else { - - theta = WWMath::Fast_Acos(cos_t); - float sin_t = WWMath::Fast_Sin(theta); - oo_sin_t = 1.0f / sin_t; - beta = WWMath::Fast_Sin(theta - alpha*theta) * oo_sin_t; - alpha = WWMath::Fast_Sin(alpha*theta) * oo_sin_t; - } - - if (qflip) { - alpha = -alpha; - } - - res.X = beta*p.X + alpha*q.X; - res.Y = beta*p.Y + alpha*q.Y; - res.Z = beta*p.Z + alpha*q.Z; - res.W = beta*p.W + alpha*q.W; -} - -#endif // MSC_VER - -void Slerp(Quaternion& res, const Quaternion & p,const Quaternion & q,float alpha) -{ - float beta; // complementary interploation parameter - float theta; // angle between p and q - //float sin_t - float cos_t; // sine, cosine of theta - float oo_sin_t; - int qflip; // use flip of q? - - // cos theta = dot product of p and q - cos_t = p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W; - - // if q is on opposite hemisphere from A, use -B instead - if (cos_t < 0.0f) { - cos_t = -cos_t; - qflip = true; - } else { - qflip = false; - } - - if (1.0f - cos_t < WWMATH_EPSILON * WWMATH_EPSILON) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0f - alpha; - - } else { - - // normal slerp! - theta = WWMath::Acos(cos_t); - float sin_t = WWMath::Sin(theta); - oo_sin_t = 1.0f / sin_t; - beta = WWMath::Sin(theta - alpha*theta) * oo_sin_t; - alpha = WWMath::Sin(alpha*theta) * oo_sin_t; - } - - if (qflip) { - alpha = -alpha; - } - - res.X = beta*p.X + alpha*q.X; - res.Y = beta*p.Y + alpha*q.Y; - res.Z = beta*p.Z + alpha*q.Z; - res.W = beta*p.W + alpha*q.W; -} - -/*********************************************************************************************** - * Slerp_Setup -- Get ready to call "Cached_Slerp" * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/27/98 GTH : Created. * - *=============================================================================================*/ -void Slerp_Setup(const Quaternion & p,const Quaternion & q,SlerpInfoStruct * slerpinfo) -{ - float cos_t; - - assert(slerpinfo != NULL); - - // cos theta = dot product of p and q - cos_t = p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W; - - // if q is on opposite hemisphere from A, use -B instead - if (cos_t < 0.0f) { - cos_t = -cos_t; - slerpinfo->Flip = true; - } else { - slerpinfo->Flip = false; - } - - if (1.0f - cos_t < SLERP_EPSILON) { - - slerpinfo->Linear = true; - slerpinfo->Theta = 0.0f; - slerpinfo->SinT = 0.0f; - - } else { - - slerpinfo->Linear = false; - slerpinfo->Theta = WWMath::Acos(cos_t); - slerpinfo->SinT = WWMath::Sin(slerpinfo->Theta); - - } -} - -/*********************************************************************************************** - * Cached_Slerp -- Quaternion slerping, optimized with cached values * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/27/98 GTH : Created. * - *=============================================================================================*/ -Quaternion Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo) -{ - float beta; // complementary interploation parameter - float oo_sin_t; - - if (slerpinfo->Linear) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0f - alpha; - - } else { - - // normal slerp! - oo_sin_t = 1.0f / slerpinfo->Theta; - beta = WWMath::Sin(slerpinfo->Theta - alpha*slerpinfo->Theta) * oo_sin_t; - alpha = WWMath::Sin(alpha*slerpinfo->Theta) * oo_sin_t; - } - - if (slerpinfo->Flip) { - alpha = -alpha; - } - - Quaternion res; - res.X = beta*p.X + alpha*q.X; - res.Y = beta*p.Y + alpha*q.Y; - res.Z = beta*p.Z + alpha*q.Z; - res.W = beta*p.W + alpha*q.W; - - return res; -} - -void Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo,Quaternion * set_q) -{ - float beta; // complementary interploation parameter - float oo_sin_t; - - if (slerpinfo->Linear) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0f - alpha; - - } else { - - // normal slerp! - oo_sin_t = 1.0f / slerpinfo->Theta; - beta = WWMath::Sin(slerpinfo->Theta - alpha*slerpinfo->Theta) * oo_sin_t; - alpha = WWMath::Sin(alpha*slerpinfo->Theta) * oo_sin_t; - } - - if (slerpinfo->Flip) { - alpha = -alpha; - } - - set_q->X = beta*p.X + alpha*q.X; - set_q->Y = beta*p.Y + alpha*q.Y; - set_q->Z = beta*p.Z + alpha*q.Z; - set_q->W = beta*p.W + alpha*q.W; -} - -/*********************************************************************************************** - * Build_Quaternion -- Creates a quaternion from a Matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Matrix MUST NOT have scaling! * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Build_Quaternion(const Matrix3D & mat) -{ - float tr,s; - int i,j,k; - Quaternion q; - - // sum the diagonal of the rotation matrix - tr = mat[0][0] + mat[1][1] + mat[2][2]; - - if (tr > 0.0f) { - - s = sqrt(tr + 1.0); - q[3] = s * 0.5; - s = 0.5 / s; - - q[0] = (mat[2][1] - mat[1][2]) * s; - q[1] = (mat[0][2] - mat[2][0]) * s; - q[2] = (mat[1][0] - mat[0][1]) * s; - - } else { - - i=0; - if (mat[1][1] > mat[0][0]) i = 1; - if (mat[2][2] > mat[i][i]) i = 2; - j = _nxt[i]; - k = _nxt[j]; - - s = sqrt((mat[i][i] - (mat[j][j] + mat[k][k])) + 1.0); - - q[i] = s * 0.5; - if (s != 0.0) { - s = 0.5 / s; - } - - q[3] = ( mat[k][j] - mat[j][k] ) * s; - q[j] = ( mat[j][i] + mat[i][j] ) * s; - q[k] = ( mat[k][i] + mat[i][k] ) * s; - - } - - return q; -} - -Quaternion Build_Quaternion(const Matrix3x3 & mat) -{ - float tr,s; - int i,j,k; - Quaternion q; - - // sum the diagonal of the rotation matrix - tr = mat[0][0] + mat[1][1] + mat[2][2]; - - if (tr > 0.0) { - - s = sqrt(tr + 1.0); - q[3] = s * 0.5; - s = 0.5 / s; - - q[0] = (mat[2][1] - mat[1][2]) * s; - q[1] = (mat[0][2] - mat[2][0]) * s; - q[2] = (mat[1][0] - mat[0][1]) * s; - - } else { - - i = 0; - if (mat[1][1] > mat[0][0]) i = 1; - if (mat[2][2] > mat[i][i]) i = 2; - - j = _nxt[i]; - k = _nxt[j]; - - s = sqrt( (mat[i][i] - (mat[j][j]+mat[k][k])) + 1.0); - - q[i] = s * 0.5; - - if (s != 0.0) { - s = 0.5/s; - } - - q[3] = ( mat[k][j] - mat[j][k] ) * s; - q[j] = ( mat[j][i] + mat[i][j] ) * s; - q[k] = ( mat[k][i] + mat[i][k] ) * s; - } - - return q; -} - -Quaternion Build_Quaternion(const Matrix4x4 & mat) -{ - float tr,s; - int i,j,k; - Quaternion q; - - // sum the diagonal of the rotation matrix - tr = mat[0][0] + mat[1][1] + mat[2][2]; - - if (tr > 0.0) { - - s = sqrt(tr + 1.0); - q[3] = s * 0.5; - s = 0.5 / s; - - q[0] = (mat[2][1] - mat[1][2]) * s; - q[1] = (mat[0][2] - mat[2][0]) * s; - q[2] = (mat[1][0] - mat[0][1]) * s; - - } else { - - i = 0; - if (mat[1][1] > mat[0][0]) i = 1; - if (mat[2][2] > mat[i][i]) i = 2; - - j = _nxt[i]; - k = _nxt[j]; - - s = sqrt( (mat[i][i] - (mat[j][j]+mat[k][k])) + 1.0); - - q[i] = s * 0.5; - if (s != 0.0) { - s = 0.5/s; - } - q[3] = ( mat[k][j] - mat[j][k] ) * s; - q[j] = ( mat[j][i] + mat[i][j] ) * s; - q[k] = ( mat[k][i] + mat[i][k] ) * s; - } - - return q; -} - - -/*********************************************************************************************** - * Build_Matrix -- Creates a Matrix from a Quaternion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Matrix3x3 Build_Matrix3(const Quaternion & q) -{ - Matrix3x3 m; - - m[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - m[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - m[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - m[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - m[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - m[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - m[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - m[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - m[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); - - return m; -} - -Matrix4x4 Build_Matrix4(const Quaternion & q) -{ - Matrix4x4 m; - - // initialize the rotation sub-matrix - m[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - m[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - m[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - m[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - m[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - m[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - m[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - m[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - m[2][2] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); - - // no translation - m[0][3] = m[1][3] = m[2][3] = 0.0f; - - // last row - m[3][0] = m[3][1] = m[3][2] = 0.0f; - m[3][3] = 1.0f; - return m; -} - -void Quaternion::Rotate_X(float theta) -{ - // TODO: optimize this - *this = (*this) * Quaternion(Vector3(1,0,0),theta); -} - -void Quaternion::Rotate_Y(float theta) -{ - // TODO: optimize this - *this = (*this) * Quaternion(Vector3(0,1,0),theta); -} - -void Quaternion::Rotate_Z(float theta) -{ - // TODO: optimize this - *this = (*this) * Quaternion(Vector3(0,0,1),theta); -} - -float project_to_sphere(float r, float x, float y) -{ - const float SQRT2 = 1.41421356f; - float t, z; - float d = WWMath::Sqrt(x * x + y * y); - - if (d < r * (SQRT2/(2.0f))) // inside sphere - z = WWMath::Sqrt(r * r - d * d); - else { // on hyperbola - t = r / SQRT2; - z = t * t / d; - } - - return z; -} - - -void Quaternion::Randomize(void) -{ - X = ((float) (rand() & 0xFFFF)) / 65536.0f; - Y = ((float) (rand() & 0xFFFF)) / 65536.0f; - Z = ((float) (rand() & 0xFFFF)) / 65536.0f; - W = ((float) (rand() & 0xFFFF)) / 65536.0f; - - Normalize(); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/quat.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/quat.h deleted file mode 100644 index 620cd6f853..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/quat.h +++ /dev/null @@ -1,317 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/quat.h 29 5/11/01 7:11p Jani_p $ */ -/*************************************************************************** - *** Confidential - Westwood Studios *** - *************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : QUAT.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef QUAT_H -#define QUAT_H - -#include "always.h" -#include "wwmath.h" -#include "matrix3.h" -#include "vector3.h" -#include "matrix3d.h" - - -class Quaternion -{ -private: - -public: - - // X,Y,Z are the imaginary parts of the quaterion - // W is the real part - float X; - float Y; - float Z; - float W; - -public: - - WWINLINE Quaternion(void) {}; - WWINLINE explicit Quaternion(bool init) { if (init) { X = 0.0f; Y = 0.0f; Z = 0.0f; W = 1.0f; } } - WWINLINE explicit Quaternion(float a, float b, float c, float d) { X=a; Y=b; Z=c; W=d; } - WWINLINE explicit Quaternion(const Vector3 & axis,float angle); - WWINLINE Quaternion & operator=(const Quaternion & source); - - WWINLINE void Set(float a = 0.0, float b = 0.0, float c = 0.0, float d = 1.0) { X = a; Y = b; Z = c; W = d; } - WWINLINE void Make_Identity(void) { Set(); }; - WWINLINE void Scale(float s) { X = (float)(s*X); Y = (float)(s*Y); Z = (float)(s*Z); W = (float)(s*W); } - - // Array access - WWINLINE float & operator [](int i) { return (&X)[i]; } - WWINLINE const float & operator [](int i) const { return (&X)[i]; } - - // Unary operators. - // Remember that q and -q represent the same 3D rotation. - WWINLINE Quaternion operator-() const { return(Quaternion(-X,-Y,-Z,-W)); } - WWINLINE Quaternion operator+() const { return *this; } - - // Every 3D rotation can be expressed by two different quaternions, This - // function makes the current quaternion convert itself to the representation - // which is closer on the 4D unit-hypersphere to the given quaternion. - Quaternion & Make_Closest(const Quaternion & qto); - - // Square of the magnitude of the quaternion - WWINLINE float Length2(void) const { return (X*X + Y*Y + Z*Z + W*W); } - - // Magnitude of the quaternion - WWINLINE float Length(void) const { return WWMath::Sqrt(Length2()); } - - // Make the quaternion unit length - void Normalize(void); - - // post-concatenate rotations about the coordinate axes - void Rotate_X(float theta); - void Rotate_Y(float theta); - void Rotate_Z(float theta); - - // initialize this quaternion randomly (creates a random *unit* quaternion) - void Randomize(void); - - // transform (rotate) a vector with this quaternion - WWINLINE Vector3 Rotate_Vector(const Vector3 & v) const; - WWINLINE void Rotate_Vector(const Vector3 & v,Vector3 * set_result) const; - - // verify that none of the members of this quaternion are invalid floats - bool Is_Valid(void) const; -}; - -// Inverse of the quaternion (1/q) -WWINLINE Quaternion Inverse(const Quaternion & a) -{ - return Quaternion(-a[0],-a[1],-a[2],a[3]); -} - -// Conjugate of the quaternion -WWINLINE Quaternion Conjugate(const Quaternion & a) -{ - return Quaternion(-a[0],-a[1],-a[2],a[3]); -} - -// Add two quaternions -WWINLINE Quaternion operator + (const Quaternion & a,const Quaternion & b) -{ - return Quaternion(a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]); -} - -// Subract two quaternions -WWINLINE Quaternion operator - (const Quaternion & a,const Quaternion & b) -{ - return Quaternion(a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]); -} - -// Multiply a quaternion by a scalar: -WWINLINE Quaternion operator * (float scl, const Quaternion & a) -{ - return Quaternion(scl*a[0], scl*a[1], scl*a[2], scl*a[3]); -} - -// Multiply a quaternion by a scalar -WWINLINE Quaternion operator * (const Quaternion & a, float scl) -{ - return scl*a; -} - -// Multiply two quaternions -WWINLINE Quaternion operator * (const Quaternion & a,const Quaternion & b) -{ - return Quaternion - ( - a.W*b.X + b.W*a.X + (a.Y*b.Z - b.Y*a.Z), - a.W*b.Y + b.W*a.Y - (a.X*b.Z - b.X*a.Z), - a.W*b.Z + b.W*a.Z + (a.X*b.Y - b.X*a.Y), - a.W * b.W - (a.X * b.X + a.Y * b.Y + a.Z * b.Z) - ); -} - -// Divide two quaternions -WWINLINE Quaternion operator / (const Quaternion & a,const Quaternion & b) -{ - return a * Inverse(b); -} - -// Normalized version of the quaternion -WWINLINE Quaternion Normalize(const Quaternion & a) -{ - float mag = a.Length(); - if (0.0f == mag) { - return a; - } else { - float oomag = 1.0f / mag; - return Quaternion(a[0] * oomag, a[1] * oomag, a[2] * oomag, a[3] * oomag); - } -} - -// This function computes a quaternion based on an axis -// (defined by the given Vector a) and an angle about -// which to rotate. The angle is expressed in radians. -Quaternion Axis_To_Quat(const Vector3 &a, float angle); - -// Pass the x and y coordinates of the last and current position -// of the mouse, scaled so they are from -1.0 to 1.0 -// The quaternion is the computed as the rotation of a trackball -// between the two points projected onto a sphere. This can -// be used to implement an intuitive viewing control system. -Quaternion Trackball(float x0, float y0, float x1, float y1, float sphsize); - -// Spherical Linear interpolation of quaternions -//Quaternion Slerp(const Quaternion & a,const Quaternion & b,float t); -void __cdecl Slerp(Quaternion& result, const Quaternion & a,const Quaternion & b,float t); -// Fast slerp is innaccurate but multiple times faster -void __cdecl Fast_Slerp(Quaternion& result, const Quaternion & a,const Quaternion & b,float t); - -// Convert a rotation matrix into a quaternion -Quaternion Build_Quaternion(const Matrix3x3 & matrix); -Quaternion Build_Quaternion(const Matrix3D & matrix); -Quaternion Build_Quaternion(const Matrix4x4 & matrix); - -// Convert a quaternion into a rotation matrix -Matrix3x3 Build_Matrix3(const Quaternion & quat); -Matrix3D &Build_Matrix3D(const Quaternion & q, Matrix3D &out); -WWINLINE Matrix3D &Build_Matrix3D(const Quaternion & q, Matrix3D &out) -{ - out[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - out[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - out[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - out[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - out[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - out[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - out[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - out[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - out[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); - - // no translation - out[0][3] = out[1][3] = out[2][3] = 0.0f; - - return out; -} - -Matrix4x4 Build_Matrix4(const Quaternion & quat); - - -// Some values can be cached if you are performing multiple slerps -// between the same two quaternions... -struct SlerpInfoStruct -{ - float SinT; - float Theta; - bool Flip; - bool Linear; -}; - -// Cached slerp implementation -void Slerp_Setup(const Quaternion & p,const Quaternion & q,SlerpInfoStruct * slerpinfo); -void Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo,Quaternion * set_q); -Quaternion Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo); - -WWINLINE Vector3 Quaternion::Rotate_Vector(const Vector3 & v) const -{ - float x = W*v.X + (Y*v.Z - v.Y*Z); - float y = W*v.Y - (X*v.Z - v.X*Z); - float z = W*v.Z + (X*v.Y - v.X*Y); - float w = -(X*v.X + Y*v.Y + Z*v.Z); - - return Vector3 - ( - w*(-X) + W*x + (y*(-Z) - (-Y)*z), - w*(-Y) + W*y - (x*(-Z) - (-X)*z), - w*(-Z) + W*z + (x*(-Y) - (-X)*y) - ); -} - -WWINLINE void Quaternion::Rotate_Vector(const Vector3 & v,Vector3 * result) const -{ - assert(result != NULL); - - float x = W*v.X + (Y*v.Z - v.Y*Z); - float y = W*v.Y - (X*v.Z - v.X*Z); - float z = W*v.Z + (X*v.Y - v.X*Y); - float w = -(X*v.X + Y*v.Y + Z*v.Z); - - result->X = w*(-X) + W*x + (y*(-Z) - (-Y)*z); - result->Y = w*(-Y) + W*y - (x*(-Z) - (-X)*z); - result->Z = w*(-Z) + W*z + (x*(-Y) - (-X)*y); -} - -WWINLINE bool Quaternion::Is_Valid(void) const -{ - return ( WWMath::Is_Valid_Float(X) && - WWMath::Is_Valid_Float(Y) && - WWMath::Is_Valid_Float(Z) && - WWMath::Is_Valid_Float(W) ); -} - -WWINLINE bool Equal_Within_Epsilon(const Quaternion &a, const Quaternion &b, float epsilon) -{ - return( (WWMath::Fabs(a.X - b.X) < epsilon) && - (WWMath::Fabs(a.Y - b.Y) < epsilon) && - (WWMath::Fabs(a.Z - b.Z) < epsilon) && - (WWMath::Fabs(a.W - b.W) < epsilon) ); -} - -/*********************************************************************************************** - * Quaternion::operator= -- Assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Quaternion & Quaternion::operator = (const Quaternion & source) -{ - X = source[0]; - Y = source[1]; - Z = source[2]; - W = source[3]; - - return *this; -} - - -#endif /* QUAT_H */ - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/rect.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/rect.h deleted file mode 100644 index 116a253c25..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/rect.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/rect.h $* - * * - * Author:: Byon Garrabrant * - * * - * $Modtime:: 4/16/01 10:01a $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef RECT_H -#define RECT_H - -#include "vector2.h" - -class RectClass -{ -public: - float Left; - float Top; - float Right; - float Bottom; - - // Constructors - RectClass( void ) {}; - RectClass( const RectClass & r ) { Left = r.Left; Top = r.Top; Right = r.Right; Bottom = r.Bottom; } - RectClass( float left, float top, float right, float bottom ) { Left = left; Top = top; Right = right; Bottom = bottom; } - RectClass( const Vector2 & top_left, const Vector2 & bottom_right ) { Left = top_left.X; Top = top_left.Y; Right = bottom_right.X; Bottom = bottom_right.Y; } - - // Assignment - RectClass & operator = (const RectClass & r) { Left = r.Left; Top = r.Top; Right = r.Right; Bottom = r.Bottom; return *this; } - void Set(float left, float top, float right, float bottom) { Left = left; Top = top; Right = right; Bottom = bottom; } - void Set( const Vector2 & top_left, const Vector2 & bottom_right ) { Left = top_left.X; Top = top_left.Y; Right = bottom_right.X; Bottom = bottom_right.Y; } - void Set(const RectClass & r) { Left = r.Left; Top = r.Top; Right = r.Right; Bottom = r.Bottom; } - - // Access - float Width(void) const { return Right - Left; } - float Height(void) const { return Bottom - Top; } - Vector2 Center( void ) const { return Vector2( (Left + Right)/2, (Top + Bottom)/2 ); } - Vector2 Extent( void ) const { return Vector2( (Right - Left)/2, (Bottom - Top)/2 ); } - Vector2 Upper_Left( void ) const { return Vector2( Left, Top ); } - Vector2 Lower_Right( void ) const { return Vector2( Right, Bottom ); } - Vector2 Upper_Right( void ) const { return Vector2( Right, Top ); } - Vector2 Lower_Left( void ) const { return Vector2( Left, Bottom ); } - - // Scaling - RectClass & operator *= (float k) { return Scale( k ); } - RectClass & operator /= (float k) { return Scale( 1/k ); } - RectClass & Scale_Relative_Center( float k ) { Vector2 center = Center(); *this-=center; Left*=k; Top*=k; Right*=k; Bottom*=k; *this+=center; return *this; } - RectClass & Scale( float k ) { Left*=k; Top*=k; Right*=k; Bottom*=k; return *this; } - RectClass & Scale( const Vector2 &k ) { Left*=k.X; Top*=k.Y; Right*=k.X; Bottom*=k.Y; return *this; } - RectClass & Inverse_Scale( const Vector2 &k ) { Left/=k.X; Top/=k.Y; Right/=k.X; Bottom/=k.Y; return *this; } - - // Offset - RectClass & operator += ( const Vector2 & o ) { Left+=o.X; Top+=o.Y; Right+=o.X; Bottom+=o.Y; return *this; } - RectClass & operator -= ( const Vector2 & o ) { Left-=o.X; Top-=o.Y; Right-=o.X; Bottom-=o.Y; return *this; } - - // Inflate - void Inflate( const Vector2 & o ) { Left-=o.X; Top-=o.Y; Right+=o.X; Bottom+=o.Y; } - - // Union - RectClass & operator += ( const RectClass & r ) { Left=MIN(Left,r.Left); Top=MIN(Top,r.Top); Right=MAX(Right,r.Right); Bottom=MAX(Bottom,r.Bottom); return *this; } - - // Equality - bool operator == ( const RectClass &rval ) const { return (rval.Left == Left) && (rval.Right == Right) && (rval.Top == Top) && (rval.Bottom == Bottom); } - bool operator != ( const RectClass &rval ) const { return (rval.Left != Left) || (rval.Right != Right) || (rval.Top != Top) || (rval.Bottom != Bottom); } - - // Containment - bool Contains ( const Vector2 &pos ) const { return (pos.X >= Left) && (pos.X <= Right) && (pos.Y >= Top) && (pos.Y <= Bottom); } - - // Misc - void Snap_To_Units( const Vector2 & u ) { Left = (int)(Left / u.X + 0.5f) * u.X; Right = (int)(Right / u.X + 0.5f) * u.X; Top = (int)(Top / u.Y + 0.5f) * u.Y; Bottom = (int)(Bottom / u.Y + 0.5f) * u.Y; } - -}; - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/sphere.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/sphere.h deleted file mode 100644 index bb19d36fed..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/sphere.h +++ /dev/null @@ -1,552 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwmath * - * * - * $Archive:: /Commando/Code/WWMath/sphere.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 3/29/01 10:37a $* - * * - * $Revision:: 18 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * SphereClass::SphereClass -- constructor * - * SphereClass::Init -- assign a new center and radius to this sphere * - * SphereClass::Re_Center -- move the center, update radius to enclose old sphere * - * SphereClass::Add_Sphere -- expands 'this' sphere to enclose the given sphere * - * SphereClass::Transform -- transforms this sphere * - * SphereClass::Volume -- returns the volume of this sphere * - * SphereClass::operator+= -- 'Add' a sphere to this one * - * SphereClass::operator *= -- transform this sphere by the given radius * - * Spheres_Intersect -- test whether two spheres intersect * - * Add_Spheres -- Add two spheres together, creating sphere which encloses both * - * operator + -- Add two spheres together, creating a sphere which encloses both * - * Transform Sphere -- transform a sphere * - * Transform_Sphere -- transform a sphere * - * operator * -- Transform a sphere * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SPHERE_H -#define SPHERE_H - -#include "always.h" -#include "vector3.h" -#include "matrix3d.h" - - -///////////////////////////////////////////////////////////////////// -// SphereClass -// -// Center - center of the sphere. -// Radius - radius of the sphere -// -///////////////////////////////////////////////////////////////////// -class SphereClass -{ -public: - inline SphereClass(void) { }; - inline SphereClass(const Vector3 & center,float radius) { Init(center,radius); } - inline SphereClass(const Matrix3D& mtx,const Vector3 & center,float radius) { Init(mtx,center,radius); } - inline SphereClass(const Vector3 & center,const SphereClass & s0); - inline SphereClass(const Vector3 *Position, const int VertCount); - - inline void Init(const Vector3 & pos,float radius); - inline void Init(const Matrix3D& mtx,const Vector3 & pos,float radius); - inline void Re_Center(const Vector3 & center); - inline void Add_Sphere(const SphereClass & s); - inline void Transform(const Matrix3D & tm); - inline float Volume(void) const; - - inline SphereClass & operator += (const SphereClass & s); - inline SphereClass & operator *= (const Matrix3D & m); - - Vector3 Center; - float Radius; -}; - - -/*********************************************************************************************** - * SphereClass::SphereClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass::SphereClass(const Vector3 & center,const SphereClass & s0) -{ - float dist = (s0.Center - center).Length(); - Center = center; - Radius = s0.Radius + dist; -} - -inline SphereClass::SphereClass(const Vector3 *Position,const int VertCount) -{ - int i; - double dx,dy,dz; - - // bounding sphere - // Using the algorithm described in Graphics Gems I page 301. - // This algorithm supposedly generates a bounding sphere within - // 5% of the optimal one but is much faster and simpler to implement. - Vector3 xmin(Position[0].X,Position[0].Y,Position[0].Z); - Vector3 xmax(Position[0].X,Position[0].Y,Position[0].Z); - Vector3 ymin(Position[0].X,Position[0].Y,Position[0].Z); - Vector3 ymax(Position[0].X,Position[0].Y,Position[0].Z); - Vector3 zmin(Position[0].X,Position[0].Y,Position[0].Z); - Vector3 zmax(Position[0].X,Position[0].Y,Position[0].Z); - - - // FIRST PASS: - // finding the 6 minima and maxima points - for (i=1; i xmax.X) { - xmax.X = Position[i].X; xmax.Y = Position[i].Y; xmax.Z = Position[i].Z; - } - if (Position[i].Y < ymin.Y) { - ymin.X = Position[i].X; ymin.Y = Position[i].Y; ymin.Z = Position[i].Z; - } - if (Position[i].Y > ymax.Y) { - ymax.X = Position[i].X; ymax.Y = Position[i].Y; ymax.Z = Position[i].Z; - } - if (Position[i].Z < zmin.Z) { - zmin.X = Position[i].X; zmin.Y = Position[i].Y; zmin.Z = Position[i].Z; - } - if (Position[i].Z > zmax.Z) { - zmax.X = Position[i].X; zmax.Y = Position[i].Y; zmax.Z = Position[i].Z; - } - } - - // xspan = distance between the 2 points xmin and xmax squared. - // same goes for yspan and zspan. - dx = xmax.X - xmin.X; - dy = xmax.Y - xmin.Y; - dz = xmax.Z - xmin.Z; - double xspan = dx*dx + dy*dy + dz*dz; - - dx = ymax.X - ymin.X; - dy = ymax.Y - ymin.Y; - dz = ymax.Z - ymin.Z; - double yspan = dx*dx + dy*dy + dz*dz; - - dx = zmax.X - zmin.X; - dy = zmax.Y - zmin.Y; - dz = zmax.Z - zmin.Z; - double zspan = dx*dx + dy*dy + dz*dz; - - - // Set points dia1 and dia2 to the maximally separated pair - // This will be the diameter of the initial sphere - Vector3 dia1 = xmin; - Vector3 dia2 = xmax; - double maxspan = xspan; - - if (yspan > maxspan) { - maxspan = yspan; - dia1 = ymin; - dia2 = ymax; - } - if (zspan > maxspan) { - maxspan = zspan; - dia1 = zmin; - dia2 = zmax; - } - - - // Compute initial center and radius and radius squared - Vector3 center; - center.X = (dia1.X + dia2.X) / 2.0f; - center.Y = (dia1.Y + dia2.Y) / 2.0f; - center.Z = (dia1.Z + dia2.Z) / 2.0f; - - dx = dia2.X - center.X; - dy = dia2.Y - center.Y; - dz = dia2.Z - center.Z; - - double radsqr = dx*dx + dy*dy + dz*dz; - double radius = sqrt(radsqr); - - - // SECOND PASS: - // Increment current sphere if any points fall outside of it. - for (i=0; i radsqr) { - - // this point was outside the old sphere, compute a new - // center point and radius which contains this point - double testrad = sqrt(testrad2); - - // adjust center and radius - radius = (radius + testrad) / 2.0; - radsqr = radius * radius; - - double oldtonew = testrad - radius; - center.X = (radius * center.X + oldtonew * Position[i].X) / testrad; - center.Y = (radius * center.Y + oldtonew * Position[i].Y) / testrad; - center.Z = (radius * center.Z + oldtonew * Position[i].Z) / testrad; - } - } - - Center = center; - Radius = radius; -} - - -/*********************************************************************************************** - * SphereClass::Init -- assign a new center and radius to this sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline void SphereClass::Init(const Vector3 & pos,float radius) -{ - Center = pos; - Radius = radius; -} - -/*********************************************************************************************** - * SphereClass::Init -- assign a new center and radius to this sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline void SphereClass::Init(const Matrix3D& mtx, const Vector3 & pos,float radius) -{ -#ifdef ALLOW_TEMPORARIES - Center = mtx * pos; -#else - mtx.mulVector3(pos, Center); -#endif - Radius = radius; -} - - -/*********************************************************************************************** - * SphereClass::Re_Center -- move the center, update radius to enclose old sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline void SphereClass::Re_Center(const Vector3 & center) -{ - float dist = (Center - center).Length(); - Center = center; - Radius += dist; -} - - -/*********************************************************************************************** - * SphereClass::Add_Sphere -- expands 'this' sphere to enclose the given sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline void SphereClass::Add_Sphere(const SphereClass & s) -{ - if (s.Radius == 0.0f) return; - - float dist = (s.Center - Center).Length(); - if (dist == 0.0f) { - Radius = (Radius > s.Radius) ? Radius : s.Radius; - return; - } - - float rnew = (dist + Radius + s.Radius) / 2.0f; - - // If rnew is smaller than either of the two sphere radii (it can't be - // smaller than both of them), this means that the smaller sphere is - // completely inside the larger, and the result of adding the two is - // simply the larger sphere. If rnew isn't less than either of them, it is - // the new radius - calculate the new center. - if (rnew < Radius) { - // The existing sphere is the result - do nothing. - } else { - if (rnew < s.Radius) { - // The new sphere is the result: - Init(s.Center, s.Radius); - } else { - // Neither sphere is completely inside the other, so rnew is the new - // radius - calculate the new center - float lerp = (rnew - Radius) / dist; - Vector3 center = (s.Center - Center) * lerp + Center; - Init(center, rnew); - } - } -} - -/*********************************************************************************************** - * SphereClass::Transform -- transforms this sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/12/99 GTH : Created. * - *=============================================================================================*/ -inline void SphereClass::Transform(const Matrix3D & tm) -{ - // warning, assumes Orthogonal matrix -#ifdef ALLOW_TEMPORARIES - Center = tm * Center; -#else - tm.mulVector3(Center, Center); -#endif -} - - -/*********************************************************************************************** - * SphereClass::Volume -- returns the volume of this sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/22/99 GTH : Created. * - *=============================================================================================*/ -inline float SphereClass::Volume(void) const -{ - return (4.0 / 3.0) * WWMATH_PI * (Radius * Radius * Radius); -} - -/*********************************************************************************************** - * SphereClass::operator+= -- 'Add' a sphere to this one * - * * - * Expands 'this' sphere to also enclose the given sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass & SphereClass::operator += (const SphereClass & s) -{ - Add_Sphere(s); - return *this; -} - - -/*********************************************************************************************** - * SphereClass::operator *= -- transform this sphere by the given radius * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass & SphereClass::operator *= (const Matrix3D & m) -{ - Init(m, Center, Radius); - return *this; -} - - -/*********************************************************************************************** - * Spheres_Intersect -- test whether two spheres intersect * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline bool Spheres_Intersect(const SphereClass & s0,const SphereClass & s1) -{ - Vector3 delta = s0.Center - s1.Center; - float dist2 = Vector3::Dot_Product(delta, delta); - - if (dist2 < (s0.Radius + s1.Radius) * (s0.Radius + s1.Radius)) { - return true; - } else { - return false; - } -} - - -/*********************************************************************************************** - * Add_Spheres -- Add two spheres together, creating sphere which encloses both * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass Add_Spheres(const SphereClass & s0, const SphereClass & s1) -{ - if (s0.Radius == 0.0f) { - return s1; - } else { - SphereClass result(s0); - result.Add_Sphere(s1); - return result; - } -} - - -/*********************************************************************************************** - * operator + -- Add two spheres together, creating a sphere which encloses both * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass operator + (const SphereClass & s0,const SphereClass & s1) -{ - return Add_Spheres(s0,s1); -} - - -/*********************************************************************************************** - * Transform Sphere -- transform a sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass Transform_Sphere(const Matrix3D & m, const SphereClass & s) -{ - // Warning, assumes Orthogonal matrix - return SphereClass(m,s.Center,s.Radius); -} - - -/*********************************************************************************************** - * Transform_Sphere -- transform a sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline void Transform_Sphere(const Matrix3D & m, const SphereClass & s,SphereClass & res) -{ - // warning, assumes Orthogonal matrix -#ifdef ALLOW_TEMPORARIES - res.Center = m*s.Center; -#else - m.mulVector3(s.Center, res.Center); -#endif - res.Radius = s.Radius; -} - - -/*********************************************************************************************** - * operator * -- Transform a sphere * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/12/98 GTH : Created. * - *=============================================================================================*/ -inline SphereClass operator * (const Matrix3D & m, const SphereClass & s) -{ - return Transform_Sphere(m,s); -} - - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/tcbspline.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/tcbspline.cpp deleted file mode 100644 index 85ad2bd083..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/tcbspline.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/tcbspline.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "tcbspline.h" -#include "wwdebug.h" -#include "persistfactory.h" -#include "wwmathids.h" -#include "wwhack.h" - - -/* -** Force-Link this module because the linker can't detect that we actually need it... -*/ -DECLARE_FORCE_LINK(tcbspline); - -/* -** Save-Load stuff -*/ -SimplePersistFactoryClass _TCBSpline3DFactory; - -enum -{ - // ID's used by TCBSpline3D - TCB3D_CHUNK_HERMITE3D = 0x02071009, - TCB3D_CHUNK_PARAMS, -}; - - -/* -** TCBSpline3DClass Implemenation -*/ - -int TCBSpline3DClass::Add_Key(const Vector3 & point,float t) -{ - int index; - index = HermiteSpline3DClass::Add_Key(point,t); - - TCBClass params; - params.Tension = 0.0f; - params.Continuity = 0.0f; - params.Bias = 0.0f; - Params.Insert(index,params); - return index; -} - -void TCBSpline3DClass::Remove_Key(int i) -{ - HermiteSpline3DClass::Remove_Key(i); - Params.Delete(i); -} - -void TCBSpline3DClass::Clear_Keys(void) -{ - HermiteSpline3DClass::Clear_Keys(); - Params.Clear(); -} - -void TCBSpline3DClass::Set_TCB_Params(int i,float tension,float continuity,float bias) -{ - WWASSERT(i >= 0); - WWASSERT(i < Params.Count()); - Params[i].Tension = tension; - Params[i].Continuity = continuity; - Params[i].Bias = bias; - TangentsDirty = true; -} - -void TCBSpline3DClass::Get_TCB_Params(int i,float *tension,float *continuity,float *bias) -{ - if (tension) *tension = Params[i].Tension; - if (continuity) *continuity = Params[i].Continuity; - if (bias) *bias = Params[i].Bias; -} - -void TCBSpline3DClass::Update_Tangents(void) -{ - if (Keys.Count() < 2) { - for (int i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /VSS_Sync/wwmath/tcbspline.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef TCBSPLINE_H -#define TCBSPLINE_H - -#include "hermitespline.h" - -/* -** TCBSpline3DClass -** Tension-Continuity-Bias splines. Otherwise known as Kochanek-Bartels cubic splines -*/ -class TCBSpline3DClass : public HermiteSpline3DClass -{ -public: - - virtual int Add_Key(const Vector3 & point,float t); - virtual void Remove_Key(int i); - virtual void Clear_Keys(void); - - virtual void Set_TCB_Params(int i,float tension,float continuity,float bias); - virtual void Get_TCB_Params(int i,float *tension,float *continuity,float *bias); - - void Update_Tangents(void); - - // save-load support - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); - -protected: - - class TCBClass - { - public: - float Tension; - float Continuity; - float Bias; - bool operator == (const TCBClass & that) { return ((Tension == that.Tension) && (Continuity == that.Continuity) && (Bias == that.Bias)); } - bool operator != (const TCBClass & that) { return !TCBClass::operator == (that); } - }; - - DynamicVectorClass Params; -}; - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/tri.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/tri.cpp deleted file mode 100644 index f450b9187d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/tri.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/WWMath/tri.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/03/01 3:41p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * TriClass::Find_Dominant_Plane -- returns indices of the axes of the dominant plane * - * TriClass::Contains_Point -- performs 2D point-in-triangle test. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "tri.h" -#include "vector2.h" - - -struct FDPRec -{ - int axis1; - int axis2; - int axis3; -}; - -static inline void find_dominant_plane_fast(const TriClass & tri, FDPRec& info) -{ - static const FDPRec dominance[3] = - { - { 1, 2, 0 }, // Dominant is the X axis - { 0, 2, 1 }, // Dominant is the Y axis - { 0, 1, 2 } // Dominant is the Z axis - }; - - /* - ** Find the largest component of the normal - */ - float x = WWMath::Fabs(tri.N->X); - float y = WWMath::Fabs(tri.N->Y); - float z = WWMath::Fabs(tri.N->Z); - - float val = x; - int ni = 0; - - if (y > val) - { - ni = 1; - val = y; - } - - if (z > val) - { - ni = 2; - } - - info = dominance[ni]; -} - -static inline void find_dominant_plane(const TriClass & tri, int * axis1,int * axis2,int * axis3) -{ - /* - ** Find the largest component of the normal - */ - int ni = 0; - float x = WWMath::Fabs(tri.N->X); - float y = WWMath::Fabs(tri.N->Y); - float z = WWMath::Fabs(tri.N->Z); - float val = x; - - if (y > val) { - ni = 1; - val = y; - } - - if (z > val) { - ni = 2; - } - - /* - ** return the indices of the two axes perpendicular - */ - switch (ni) - { - case 0: - // Dominant is the X axis - *axis1 = 1; - *axis2 = 2; - *axis3 = 0; - break; - case 1: - // Dominant is the Y axis - *axis1 = 0; - *axis2 = 2; - *axis3 = 1; - break; - case 2: - // Dominant is the Z axis - *axis1 = 0; - *axis2 = 1; - *axis3 = 2; - break; - } -} - - - -/*********************************************************************************************** - * TriClass::Find_Dominant_Plane -- returns indices of the axes of the dominant plane * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/24/99 GTH : Created. * - *=============================================================================================*/ -void TriClass::Find_Dominant_Plane(int * axis1,int * axis2) const -{ - /* - ** Find the largest component of the normal - */ - int ni = 0; - float x = WWMath::Fabs(N->X); - float y = WWMath::Fabs(N->Y); - float z = WWMath::Fabs(N->Z); - float val = x; - - if (y > val) { - ni = 1; - val = y; - } - - if (z > val) { - ni = 2; - } - - /* - ** return the indices of the two axes perpendicular - */ - switch (ni) - { - case 0: - // Dominant is the X axis - *axis1 = 1; - *axis2 = 2; - break; - case 1: - // Dominant is the Y axis - *axis1 = 0; - *axis2 = 2; - break; - case 2: - // Dominant is the Z axis - *axis1 = 0; - *axis2 = 1; - break; - } -} - - -/*********************************************************************************************** - * TriClass::Contains_Point -- performs 2D point-in-triangle test. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Assumes that the point is in the plane of the triangle... use this after you've intersected * - * a ray with the plane of the triangle. * - * * - * HISTORY: * - * 3/24/99 GTH : Created. * - *=============================================================================================*/ -bool TriClass::Contains_Point(const Vector3 & ipoint) const -{ -#if 0 - /* - ** Perform the test in 2d on the plane which the normal - ** is most perpendicular to. (copied from E.Cosky's intersection code) - */ - int axis1 = 0; - int axis2 = 0; - Find_Dominant_Plane(&axis1,&axis2); - -#if 1 - unsigned char flags; // dummy variable passed into function and not used here - return Point_In_Triangle_2D(*V[0], *V[1], *V[2], ipoint, axis1, axis2, flags); -#else - float u0 = ipoint[axis1] - (*V[0])[axis1]; - float v0 = ipoint[axis2] - (*V[0])[axis2]; - - /* - ** determine the 2d vectors on the dominant plane from the first vertex to the other two - */ - float u1 = (*V[1])[axis1] - (*V[0])[axis1]; - float v1 = (*V[1])[axis2] - (*V[0])[axis2]; - float u2 = (*V[2])[axis1] - (*V[0])[axis1]; - float v2 = (*V[2])[axis2] - (*V[0])[axis2]; - - float alpha, beta; - bool intersect = false; - - // calculate alpha and beta as normalized (0..1) percentages across the 2d projected triangle - // and do bounds checking (sum <= 1) to determine whether or not the triangle intersection occurs. - if (u1 == 0) { - beta = u0 / u2; - if ((beta >= 0) && (beta <= 1)) { - alpha = (v0 - beta * v2) / v1; - intersect = ((alpha >= 0) && ((alpha + beta) <= 1 + WWMATH_EPSILON)); - } - } else { - beta = (v0 * u1 - u0 * v1) / (v2 * u1 - u2 * v1); - if ((beta >= 0) && (beta <= 1)) { - alpha = (u0 - beta * u2) / u1; - intersect = ((alpha >= 0) && ((alpha + beta) <= 1 + WWMATH_EPSILON)); - } - } - - return intersect; -#endif -#endif -/* -** New cross-product based point-containment -*/ -#if 0 - int vi; - int axis3 = 0; - - for (vi=0; vi<3; vi++) { - if ((axis1 != vi) && (axis2 != vi)) axis3 = vi; - } - - Vector3 test_point = ipoint; - test_point[axis3] = 0.0f; - - Vector3 points[3]; - for (vi=0; vi<3; vi++) { - points[vi] = *(V[vi]); - points[vi][axis3] = 0.0f; - } - - bool side[3]; - Vector3 edge; - Vector3 cross; - Vector3 dp; - - for (vi=0; vi<3; vi++) { - edge = points[(vi+1)%3] - points[vi]; - dp = test_point - points[vi]; - - Vector3::Cross_Product(dp,edge,&cross); - side[vi] = (cross[axis3] > 0.0f); - } - - bool my_intersect = ((side[0] == side[1]) && (side[1] == side[2])); - return my_intersect; -#endif - - -/* -** "Optimized" version -*/ -#if 1 -#if 0 - - // srj opto version - /// @todo srj -- profile me to see if this is actually faster - - FDPRec info; - find_dominant_plane_fast(*this, info); - - /* - ** Compute the 2D cross product of edge0 with a vector to the point - */ - - float edge_x, edge_y, dp_x, dp_y, cross; - bool side0, side1, side2; - - edge_x = (*V[1])[info.axis1] - (*V[0])[info.axis1]; - edge_y = (*V[1])[info.axis2] - (*V[0])[info.axis2]; - dp_x = ipoint[info.axis1] - (*V[0])[info.axis1]; - dp_y = ipoint[info.axis2] - (*V[0])[info.axis2]; - cross = edge_x * dp_y - edge_y * dp_x; - side0 = (cross >= 0.0f); - - edge_x = (*V[2])[info.axis1] - (*V[1])[info.axis1]; - edge_y = (*V[2])[info.axis2] - (*V[1])[info.axis2]; - dp_x = ipoint[info.axis1] - (*V[1])[info.axis1]; - dp_y = ipoint[info.axis2] - (*V[1])[info.axis2]; - cross = edge_x * dp_y - edge_y * dp_x; - side1 = (cross >= 0.0f); - - edge_x = (*V[0])[info.axis1] - (*V[2])[info.axis1]; - edge_y = (*V[0])[info.axis2] - (*V[2])[info.axis2]; - dp_x = ipoint[info.axis1] - (*V[2])[info.axis1]; - dp_y = ipoint[info.axis2] - (*V[2])[info.axis2]; - cross = edge_x * dp_y - edge_y * dp_x; - side2 = (cross >= 0.0f); - - bool my_intersect = ((side0 == side1) && (side1 == side2)); - return my_intersect; - -#else - int vi; - int axis1 = 0; - int axis2 = 0; - int axis3 = 0; - - find_dominant_plane(*this,&axis1,&axis2,&axis3); - - bool side[3]; - - /* - ** Compute the 2D cross product of edge0 with a vector to the point - */ - Vector2 edge; - Vector2 dp; - - for (vi=0; vi<3; vi++) { - - int va=vi; - int vb=(vi+1)%3; - - edge.Set((*V[vb])[axis1] - (*V[va])[axis1] , (*V[vb])[axis2] - (*V[va])[axis2]); - dp.Set(ipoint[axis1] - (*V[va])[axis1] , ipoint[axis2] - (*V[va])[axis2]); - float cross = edge.X * dp.Y - edge.Y * dp.X; - side[vi] = (cross >= 0.0f); - } - - bool my_intersect = ((side[0] == side[1]) && (side[1] == side[2])); - return my_intersect; -#endif -#endif - - -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/tri.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/tri.h deleted file mode 100644 index 329f68b463..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/tri.h +++ /dev/null @@ -1,306 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/tri.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 5/04/01 8:35p $* - * * - * $Revision:: 14 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef TRI_H -#define TRI_H - -#include "always.h" -#include "vector4.h" -#include "vector3.h" -#include "vector2.h" -#include - - -/** -** TriClass -** When the math library needs to deal with triangles, this will be the form used. -** The initial reason for this class is for Commando's collision detection code. Initially -** I wrote custom code inside the render object for the terrain to perform collision -** detection. Moving the low-level geometrical collision code into the math library makes it -** more re-useable and independent from changes in the rendering code. -*/ -class TriClass -{ -public: - - const Vector3 * N; - const Vector3 * V[3]; - - void Compute_Normal() - { - assert(N); - assert(V[0]); - assert(V[1]); - assert(V[2]); - - Vector3::Cross_Product(*(V[1])-*(V[0]),*(V[2])-*(V[0]),(Vector3 *)N); - ((Vector3 *)N)->Normalize(); - } - - - bool Contains_Point(const Vector3 & ipoint) const; - void Find_Dominant_Plane(int * axis1,int * axis2) const; -}; - - -/* -** Utility functions: -** Functions which have to do with triangles but not neccessarily with TriClass - usually used -** by TriClass but also available for use elsewhere. -*/ - -// Enums for raycast flags (currently used only for semi-infinite axis-aligned rays) -enum -{ - TRI_RAYCAST_FLAG_NONE = 0x00, - TRI_RAYCAST_FLAG_HIT_EDGE = 0x01, - TRI_RAYCAST_FLAG_START_IN_TRI = 0x02 -}; - -// This function does a pure 2D point-in-triangle test. We pass in 3D points both for the -// triangle and test points, but we also pass in the two axes to use (the third axis is ignored, -// so we are actually testing the projection of the four points onto one of the axis planes). The -// triangle points are not assumed to be in any particular winding order (that is checked for -// internally). It is used internally by TriClass::Contains_Point(), and may be used elsewhere. -// If the ray intersects the camera at an edge we also count it as an intersection. We set a bit -// in 'flags' to true in this case (some users of this function need this extra information and -// it is very cheap to compute). We do not modify 'flags' if no edges are hit, so it must be -// initialized outside this function if its value is to be used. -inline bool Point_In_Triangle_2D(const Vector3 &tri_point0, const Vector3 &tri_point1, - const Vector3 &tri_point2, const Vector3 &test_point, int axis_1, int axis_2, - unsigned char &flags) -{ - // The function is based on checking signs of determinants, or in a more visually intuitive - // sense, checking on which side of a line a point lies. For example, if the points run in - // counter-clockwise order, the interior of the triangle is the intersection of the three - // half-planes to the left of the directed infinite lines along P0 to P1, P1 to P2, P2 to P0. - // Therefore the test point is in the triangle iff it is to the left of all three lines (if - // the points are in clockwise order, we check if it is to the right of the lines). - Vector2 p0p1(tri_point1[axis_1] - tri_point0[axis_1], tri_point1[axis_2] - tri_point0[axis_2]); - Vector2 p1p2(tri_point2[axis_1] - tri_point1[axis_1], tri_point2[axis_2] - tri_point1[axis_2]); - Vector2 p2p0(tri_point0[axis_1] - tri_point2[axis_1], tri_point0[axis_2] - tri_point2[axis_2]); - - // Check which side P2 is relative to P0P1. The sign of this test must equal the sign of all - // three tests between the lines and the test point for the test point to be inside the - // triangle. (this test will also tell us if the three points are colinear - if the triangle - // is degenerate). - Vector2 p0p2(tri_point2[axis_1] - tri_point0[axis_1], tri_point2[axis_2] - tri_point0[axis_2]); - float p0p1p2 = Vector2::Perp_Dot_Product(p0p1, p0p2); - if (p0p1p2 != 0.0f) { - - // The triangle is not degenerate - test three sides - float side_factor = p0p1p2 > 0.0f ? 1.0f : -1.0f; - float factors[3]; - - // Now perform tests - Vector2 p0pT(test_point[axis_1] - tri_point0[axis_1], test_point[axis_2] - tri_point0[axis_2]); - factors[0] = Vector2::Perp_Dot_Product(p0p1, p0pT); - if (factors[0] * side_factor < 0.0f) { - return false; - } - Vector2 p1pT(test_point[axis_1] - tri_point1[axis_1], test_point[axis_2] - tri_point1[axis_2]); - factors[1] = Vector2::Perp_Dot_Product(p1p2, p1pT); - if (factors[1] * side_factor < 0.0f) { - return false; - } - Vector2 p2pT(test_point[axis_1] - tri_point2[axis_1], test_point[axis_2] - tri_point2[axis_2]); - factors[2] = Vector2::Perp_Dot_Product(p2p0, p2pT); - if (factors[2] * side_factor < 0.0f) { - return false; - } - if ((factors[0] == 0.0f) || (factors[1] == 0.0f) || (factors[2] == 0.0f)) flags |= TRI_RAYCAST_FLAG_HIT_EDGE; - return true; - - } else { - - // The triangle is degenerate. This should be a rare case, so it does not matter much if it - // is a little slower than the non-colinear case. - - // Find the two outer points along the triangle's line ('start' and 'end' points) - float p0p1dist2 = p0p1.Length2(); - float p1p2dist2 = p1p2.Length2(); - float p2p0dist2 = p1p2.Length2(); - float max_dist2; - Vector2 pSpE, pSpT; // 'end' point, test point - both in 'start' points' frame - if (p0p1dist2 > p1p2dist2) { - if (p0p1dist2 > p2p0dist2) { - // points 0 and 1 are the 'outer' points. 0 is 'start' and 1 is 'end'. - pSpE = p0p1; - pSpT.Set(test_point[axis_1] - tri_point0[axis_1], test_point[axis_2] - tri_point0[axis_2]); - max_dist2 = p0p1dist2; - } else { - // points 0 and 2 are the 'outer' points. 2 is 'start' and 0 is 'end'. - pSpE = p2p0; - pSpT.Set(test_point[axis_1] - tri_point2[axis_1], test_point[axis_2] - tri_point2[axis_2]); - max_dist2 = p2p0dist2; - } - } else { - if (p1p2dist2 > p2p0dist2) { - // points 1 and 2 are the 'outer' points. 1 is 'start' and 2 is 'end'. - pSpE = p1p2; - pSpT.Set(test_point[axis_1] - tri_point1[axis_1], test_point[axis_2] - tri_point1[axis_2]); - max_dist2 = p1p2dist2; - } else { - // points 0 and 2 are the 'outer' points. 2 is 'start' and 0 is 'end'. - pSpE = p2p0; - pSpT.Set(test_point[axis_1] - tri_point2[axis_1], test_point[axis_2] - tri_point2[axis_2]); - max_dist2 = p2p0dist2; - } - } - - if (max_dist2 != 0.0f) { - // Triangle is line segment, check if test point is colinear with it - if (Vector2::Perp_Dot_Product(pSpE, pSpT)) { - // Not colinear - return false; - } else { - // Colinear - is test point's distance from start and end <= segment length? - Vector2 pEpT = pSpT - pSpE; - if (pSpT.Length2() <= max_dist2 && pEpT.Length2() <= max_dist2) { - flags |= TRI_RAYCAST_FLAG_HIT_EDGE; - return true; - } else { - return false; - } - } - } else { - // All triangle points coincide, check if test point coincides with them - if (pSpT.Length2() == 0.0f) { - flags |= TRI_RAYCAST_FLAG_HIT_EDGE; - return true; - } else { - return false; - } - } - } -} - - -// This function tests a semi-infinite axis-aligned ray vs. a triangle. -// The inputs are blah blah blah -inline bool Cast_Semi_Infinite_Axis_Aligned_Ray_To_Triangle(const Vector3 &tri_point0, - const Vector3 &tri_point1, const Vector3 &tri_point2, const Vector4 &tri_plane, - const Vector3 &ray_start, int axis_r, int axis_1, int axis_2, int direction, - unsigned char & flags) -{ - bool retval = false; - - // First check infinite ray vs. triangle (2D check) - unsigned char flags_2d = TRI_RAYCAST_FLAG_NONE; - if (Point_In_Triangle_2D(tri_point0, tri_point1, tri_point2, ray_start, axis_1, axis_2, flags_2d)) { - - // NOTE: SR plane equations, unlike WWMath's PlaneClass, use the Ax+By+Cz+D = 0 - // representation. It can also be viewed as C0x+C1y+C2z+C3 = dist where dist is the - // signed distance from the plane (and therefore the plane is defined as those points - // where dist = 0). Now that we know that the projection along the ray is inside the - // triangle, determining whether the ray hits the triangle is a matter of determining - // whether the start point is on the triangle plane's "anti-rayward side" (the side - // which the ray points away from). - // To determine this, we will use C[axis_r] (the plane coefficient of the ray axis). - // This coefficient is positive if the positive direction of the ray axis points into - // the planes' positive halfspace and negative if it points into the planes' negative - // halfspace (it is zero if the ray axis is parallel to the triangle plane). If we - // multiply this by 'sign' which is defined to be -1.0 if 'direction' equals 0 and - // 1.0 if 'direction' equals 1, we will get a number which is positive or negative - // depending on which halfspace the ray itself (as opposed to the rays axis) points - // towards. If we further multiply this by dist(start point) - the result of plugging - // the start point into the plane equation - we will get a number which is positive - // if the start point is on the 'rayward side' (ray does not intersect the triangle) - // and is negative if the start point is on the 'anti-rayward side' (ray does - // intersect triangle). In either of these two cases we are done. - // (see below for what happens when the result is zero - more checks need to be made). - static const float sign[2] = {-1.0f, 1.0f }; - float result = tri_plane[axis_r] * sign[direction] * (tri_plane.X * ray_start.X + - tri_plane.Y * ray_start.Y + tri_plane.Z * ray_start.Z + tri_plane.W); - if (result < 0.0f) { - // Intersection! - flags |= (flags_2d & TRI_RAYCAST_FLAG_HIT_EDGE); - retval = true; - } else { - if (result == 0.0f) { - // If the result is 0, this means either the ray is parallel to the triangle - // plane or the start point is embedded in the triangle plane. Note that since - // the start point passed the 2D check, then if the ray is parallel the start - // point must also be embedded in the triangle plane. This leaves us with two - // cases: - // A) The ray is not parallel to the plane - in this case the start point is - // embedded in the triangle. We report an intersection, bitwise OR the edge - // result from the 2D check into the 'edge hit' flag and set the 'start in tri' - // flag. - // B) The ray is parallel to the plane. In this case the result of the 2D test - // tells us that the infinite line intersects the triangle (actually is - // embedded in the triangle along part of its length), but we do not know - // whether the semi-infinite ray also does so. We simplify things by not - // counting such an 'intersection'. There are four reasons behind this: - // 1. It differs from a 'normal' intersection (which has one intersecting - // point) - there are infinitely many intersecting points. - // 2. Moving the plane by an infinitesimally small amount to either side will - // cause the ray to no longer touch the plane. - // 3. This will not affect results for the known uses of this function. - // 4. By doing so we avoid having to code up a bunch of complex tests. - // Therefore in case B) we just report no intersection. We still need to find - // out whether the point is embedded in the triangle (for setting the flag) so - // we do another simple 2D test on the dominant plane. - if (tri_plane[axis_r]) { - // Case A) - flags |= (flags_2d & TRI_RAYCAST_FLAG_HIT_EDGE); - flags |= TRI_RAYCAST_FLAG_START_IN_TRI; - retval = true; - } else { - // Case B) - test if point in tri (we know it is in plane, so we can use - // TriClass function) - TriClass tri; - tri.V[0] = &tri_point0; - tri.V[1] = &tri_point1; - tri.V[2] = &tri_point2; - tri.N = (Vector3*)&tri_plane; - if (tri.Contains_Point(ray_start)) { - flags |= TRI_RAYCAST_FLAG_START_IN_TRI; - } - } - } // if (result == 0.0f) - } // else (result < 0.0f) - } // if Point_In_Triangle_2D() - - return retval; -} - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp deleted file mode 100644 index 550ebcabac..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/wwmath/v3_rnd.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 7/09/99 9:49a $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "v3_rnd.h" -#include "vector2.h" - -const float Vector3Randomizer::OOIntMax = 1.0f / (float)INT_MAX; -const float Vector3Randomizer::OOUIntMax = 1.0f / (float)UINT_MAX; -Random3Class Vector3Randomizer::Randomizer; - -Vector3SolidBoxRandomizer::Vector3SolidBoxRandomizer(const Vector3 & extents) -{ - Extents.X = MAX(extents.X, 0.0f); - Extents.Y = MAX(extents.Y, 0.0f); - Extents.Z = MAX(extents.Z, 0.0f); -} - -void Vector3SolidBoxRandomizer::Get_Vector(Vector3 &vector) -{ - vector.X = Get_Random_Float_Minus1_To_1() * Extents.X; - vector.Y = Get_Random_Float_Minus1_To_1() * Extents.Y; - vector.Z = Get_Random_Float_Minus1_To_1() * Extents.Z; -} - -float Vector3SolidBoxRandomizer::Get_Maximum_Extent(void) -{ - float max = MAX(Extents.X, Extents.Y); - max = MAX(max, Extents.Z); - return max; -} - -void Vector3SolidBoxRandomizer::Scale(float scale) -{ - scale = MAX(scale, 0.0f); - Extents.X *= scale; - Extents.Y *= scale; - Extents.Z *= scale; -} - - -Vector3SolidSphereRandomizer::Vector3SolidSphereRandomizer(float radius) -{ - Radius = MAX(radius, 0.0f); -} - -void Vector3SolidSphereRandomizer::Get_Vector(Vector3 &vector) -{ - // Generate vectors in a cube and discard the ones not in a sphere - float rad_squared = Radius * Radius; - for (;;) { - vector.X = Get_Random_Float_Minus1_To_1() * Radius; - vector.Y = Get_Random_Float_Minus1_To_1() * Radius; - vector.Z = Get_Random_Float_Minus1_To_1() * Radius; - if (vector.Length2() <= rad_squared) break; - } -} - -float Vector3SolidSphereRandomizer::Get_Maximum_Extent(void) -{ - return Radius; -} - -void Vector3SolidSphereRandomizer::Scale(float scale) -{ - scale = MAX(scale, 0.0f); - Radius *= scale; -} - - -Vector3HollowSphereRandomizer::Vector3HollowSphereRandomizer(float radius) -{ - Radius = MAX(radius, 0.0f); -} - -void Vector3HollowSphereRandomizer::Get_Vector(Vector3 &vector) -{ - // Generate vectors in a 2x2x2 origin-centered cube, discard the ones not in a unit-radius - // sphere and scale the result to Radius. - float v_l2; - for (;;) { - vector.X = Get_Random_Float_Minus1_To_1(); - vector.Y = Get_Random_Float_Minus1_To_1(); - vector.Z = Get_Random_Float_Minus1_To_1(); - v_l2 = vector.Length2(); - if (v_l2 <= 1.0f && v_l2 > 0.0f) break; - } - - float scale = Radius * WWMath::Inv_Sqrt(v_l2); - - vector.X *= scale; - vector.Y *= scale; - vector.Z *= scale; -} - -float Vector3HollowSphereRandomizer::Get_Maximum_Extent(void) -{ - return Radius; -} - -void Vector3HollowSphereRandomizer::Scale(float scale) -{ - scale = MAX(scale, 0.0f); - Radius *= scale; -} - - -Vector3SolidCylinderRandomizer::Vector3SolidCylinderRandomizer(float extent, float radius) -{ - Extent = MAX(extent, 0.0f); - Radius = MAX(radius, 0.0f); -} - -void Vector3SolidCylinderRandomizer::Get_Vector(Vector3 &vector) -{ - vector.X = Get_Random_Float_Minus1_To_1() * Extent; - - // Generate 2D vectors in a square and discard the ones not in a circle - Vector2 vec2; - float rad_squared = Radius * Radius; - for (;;) { - vec2.X = Get_Random_Float_Minus1_To_1() * Radius; - vec2.Y = Get_Random_Float_Minus1_To_1() * Radius; - if (vec2.Length2() <= rad_squared) break; - } - - vector.Y = vec2.X; - vector.Z = vec2.Y; -} - -float Vector3SolidCylinderRandomizer::Get_Maximum_Extent(void) -{ - return MAX(Extent, Radius); -} - -void Vector3SolidCylinderRandomizer::Scale(float scale) -{ - scale = MAX(scale, 0.0f); - Extent *= scale; - Radius *= scale; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.h deleted file mode 100644 index aba4fdc157..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/v3_rnd.h +++ /dev/null @@ -1,235 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/wwmath/v3_rnd.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 7/09/99 9:49a $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef V3_RND_H -#define V3_RND_H - -#include "always.h" -#include "vector3.h" -#include "RANDOM.H" -#include - -/* -** Vector3Randomizer is an abstract class for generating random Vector3s. -** Examples: generating vectors in a sphere, cylinder, etc. -** This file contains several concrete derived classes; others may be defined -** in future. -** A possible future extension to this class would be to add a method to -** efficiently get an array of random points. -*/ - -class Vector3Randomizer { - - public: - - enum - { - CLASSID_UNKNOWN = 0xFFFFFFFF, - CLASSID_SOLIDBOX = 0, - CLASSID_SOLIDSPHERE, - CLASSID_HOLLOWSPHERE, - CLASSID_SOLIDCYLINDER, - CLASSID_MAXKNOWN, - CLASSID_LAST = 0x0000FFFF - }; - - virtual ~Vector3Randomizer(void) { } - - // RTTI identifiction - virtual unsigned int Class_ID (void) const = 0; - - // Return a random vector - virtual void Get_Vector(Vector3 &vector) = 0; - - // Get the maximum component possible for generated vectors - virtual float Get_Maximum_Extent(void) = 0; - - // Scale all vectors produced in future - virtual void Scale(float scale) = 0; - - // Clone the randomizer - virtual Vector3Randomizer * Clone(void) const = 0; - - protected: - - // Derived classes should have protected copy CTors so users use the Clone() function - - // Utility functions - float Get_Random_Float_Minus1_To_1() { return Randomizer * OOIntMax; } - float Get_Random_Float_0_To_1() { return ((unsigned int)Randomizer) * OOUIntMax; } - - static const float OOIntMax; - static const float OOUIntMax; - static Random3Class Randomizer; - - private: - - // Derived classes should have a private dummy assignment operator to block usage -}; - - -/* -** Vector3SolidBoxRandomizer is a randomizer for generating points uniformly distributed inside a -** box which is centered on the origin. -*/ -class Vector3SolidBoxRandomizer : public Vector3Randomizer { - - public: - - Vector3SolidBoxRandomizer(const Vector3 & extents); - - virtual unsigned int Class_ID (void) const { return CLASSID_SOLIDBOX; } - virtual const Vector3 & Get_Extents (void) const { return Extents; } - virtual void Get_Vector(Vector3 &vector); - virtual float Get_Maximum_Extent(void); - virtual void Scale(float scale); - virtual Vector3Randomizer * Clone(void) const { return W3DNEW Vector3SolidBoxRandomizer(*this); } - - protected: - - // Derived classes should have protected copy CTors so users use the Clone() function - Vector3SolidBoxRandomizer(const Vector3SolidBoxRandomizer &src) : Extents(src.Extents) { } - - private: - - // Derived classes should have a private dummy assignment operator to block usage - Vector3SolidBoxRandomizer & operator = (const Vector3SolidBoxRandomizer &that) { that; return *this; } - - Vector3 Extents; -}; - - -/* -** Vector3SolidSphereRandomizer is a randomizer for generating points uniformly distributed inside -** a sphere which is centered on the origin. -*/ -class Vector3SolidSphereRandomizer : public Vector3Randomizer { - - public: - - Vector3SolidSphereRandomizer(float radius); - - virtual unsigned int Class_ID (void) const { return CLASSID_SOLIDSPHERE; } - virtual float Get_Radius (void) const { return Radius; } - virtual void Get_Vector(Vector3 &vector); - virtual float Get_Maximum_Extent(void); - virtual void Scale(float scale); - virtual Vector3Randomizer * Clone(void) const { return W3DNEW Vector3SolidSphereRandomizer(*this); } - - protected: - - // Derived classes should have protected copy CTors so users use the Clone() function - Vector3SolidSphereRandomizer(const Vector3SolidSphereRandomizer &src) : Radius(src.Radius) { } - - private: - - // Derived classes should have a private dummy assignment operator to block usage - Vector3SolidSphereRandomizer & operator = (const Vector3SolidSphereRandomizer &that) { that; return *this; } - - float Radius; -}; - - -/* -** Vector3HollowSphereRandomizer is a randomizer for generating points uniformly distributed on the -** surface of a sphere which is centered on the origin. -*/ -class Vector3HollowSphereRandomizer : public Vector3Randomizer { - - public: - - Vector3HollowSphereRandomizer(float radius); - - virtual unsigned int Class_ID (void) const { return CLASSID_HOLLOWSPHERE; } - virtual float Get_Radius (void) const { return Radius; } - virtual void Get_Vector(Vector3 &vector); - virtual float Get_Maximum_Extent(void); - virtual void Scale(float scale); - virtual Vector3Randomizer * Clone(void) const { return W3DNEW Vector3HollowSphereRandomizer(*this); } - - protected: - - // Derived classes should have protected copy CTors so users use the Clone() function - Vector3HollowSphereRandomizer(const Vector3HollowSphereRandomizer &src) : Radius(src.Radius) { } - - private: - - // Derived classes should have a private dummy assignment operator to block usage - Vector3HollowSphereRandomizer & operator = (const Vector3HollowSphereRandomizer &that) { that; return *this; } - - float Radius; -}; - - -/* -** Vector3SolidCylinderRandomizer is a randomizer for generating points uniformly distributed -** inside a cylinder which is centered on the origin (set extent to 0 for a disk). -*/ -class Vector3SolidCylinderRandomizer : public Vector3Randomizer { - - public: - - Vector3SolidCylinderRandomizer(float extent, float radius); - - virtual unsigned int Class_ID (void) const { return CLASSID_SOLIDCYLINDER; } - virtual float Get_Radius (void) const { return Radius; } - virtual float Get_Height (void) const { return Extent; } - virtual void Get_Vector(Vector3 &vector); - virtual float Get_Maximum_Extent(void); - virtual void Scale(float scale); - virtual Vector3Randomizer * Clone(void) const { return W3DNEW Vector3SolidCylinderRandomizer(*this); } - - protected: - - // Derived classes should have protected copy CTors so users use the Clone() function - Vector3SolidCylinderRandomizer(const Vector3SolidCylinderRandomizer &src) : Extent(src.Extent), Radius(src.Radius) { } - - private: - - // Derived classes should have a private dummy assignment operator to block usage - Vector3SolidCylinderRandomizer & operator = (const Vector3SolidCylinderRandomizer &that) { that; return *this; } - - float Extent; - float Radius; -}; - - -#endif - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector2.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/vector2.h deleted file mode 100644 index d324cee3a2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector2.h +++ /dev/null @@ -1,671 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/vector2.h 24 7/06/01 9:43a Byon_g $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Westwood 3D * - * * - * File Name : VECTOR2.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Scalar Division Operator -- Divide a vector by a scalar * - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * Vector Addition Operator -- Add two vectors * - * Vector Subtraction Operator -- Subract two vectors * - * Vector Inner Product Operator -- Compute the inner or dot product * - * Vector Equality Operator -- Detemine if two vectors are identical * - * Equal_Within_Epsilon -- Determine if two vectors are identical within * - * Vector Inequality Operator -- Detemine if two vectors are identical * - * Swap -- swap two Vector2's * - * Vector2::Is_Valid -- Verifies that all components are valid floats * - * Vector2::Update_Min -- sets each component of the vector to the min of this and a. * - * Vector2::Update_Max -- sets each component of the vector to the max of this and a. * - * Vector2::Scale -- multiply components of a vector by independant scaling factors. * - * Vector2::Lerp -- linearly interpolates two Vector2's * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR2_H -#define VECTOR2_H - -#include "always.h" -#include "wwmath.h" -#include - - -/* -** 2-Dimensional Vectors -*/ - -class Vector2 -{ - -public: - - union { - float X; - float U; - }; - - union { - float Y; - float V; - }; - - // Constructors - WWINLINE Vector2(void) {}; - WWINLINE Vector2(const Vector2 & v) { X = v.X; Y = v.Y; } - WWINLINE Vector2(float x, float y) { X = x; Y = y; } - WWINLINE Vector2(const float vector[2]) { X = vector[0]; Y = vector[1]; } - - - // Assignment - WWINLINE Vector2 & operator = (const Vector2 & v) { X = v[0]; Y = v[1]; return *this; } - WWINLINE void Set(float x, float y) { X = x; Y = y; } - WWINLINE void Set(const Vector2 & v) { X = v.X; Y = v.Y; } - - // Array access - WWINLINE float & operator [](int i) { return (&X)[i]; } - WWINLINE const float & operator [](int i) const { return (&X)[i]; } - - // normalize, compute length - WWINLINE void Normalize(void); - WWINLINE float Length(void) const; - WWINLINE float Length2(void) const; - - // unary operators - WWINLINE Vector2 operator-() const { return Vector2(-X,-Y); } - WWINLINE Vector2 operator+() const { return *this; } - - WWINLINE Vector2 & operator += (const Vector2 & v) { X += v.X; Y += v.Y; return *this; } - WWINLINE Vector2 & operator -= (const Vector2 & v) { X -= v.X; Y -= v.Y; return *this; } - WWINLINE Vector2 & operator *= (float k) { X = (float)(X*k); Y=(float)(Y*k); return *this; } - WWINLINE Vector2 & operator /= (float k) { k=1.0f/k; X*=k; Y*=k; return *this; } - - // scalar multiplication, division - WWINLINE friend Vector2 operator * (const Vector2 &a,float k); - WWINLINE friend Vector2 operator * (float k,const Vector2 &a); - WWINLINE friend Vector2 operator / (const Vector2 &a,float k); - - // vector addition,subtraction - WWINLINE friend Vector2 operator + (const Vector2 &a,const Vector2 &b); - WWINLINE friend Vector2 operator - (const Vector2 &a,const Vector2 &b); - - // dot product / inner product - WWINLINE friend float operator * (const Vector2 &a,const Vector2 &b); - static WWINLINE float Dot_Product(const Vector2 &a,const Vector2 &b); - - // dot product between a and perpendicular vector to b - static float Perp_Dot_Product(const Vector2 &a,const Vector2 &b); - - // Equality operators - friend bool operator == (const Vector2 &a,const Vector2 &b); - friend bool operator != (const Vector2 &a,const Vector2 &b); - WWINLINE friend bool Equal_Within_Epsilon(const Vector2 &a,const Vector2 &b,float epsilon); - - // Rotation - WWINLINE void Rotate(float theta); - WWINLINE void Rotate(float s, float c); - WWINLINE bool Rotate_Towards_Vector(Vector2 &target, float max_theta, bool & positive_turn); - WWINLINE bool Rotate_Towards_Vector(Vector2 &target, float max_s, float max_c, bool & positive_turn); - - // verify that none of the members of this vector are invalid floats - WWINLINE bool Is_Valid(void) const; - - // make this vector the min or max of itself and the passed vector - WWINLINE void Update_Min (const Vector2 & a); - WWINLINE void Update_Max (const Vector2 & a); - WWINLINE void Scale (float a, float b); - WWINLINE void Scale (const Vector2 & a); - - static WWINLINE float Distance(const Vector2 &p1, const Vector2 &p2); - static WWINLINE float Quick_Distance(const Vector2 &p1, const Vector2 &p2); - - // interpolate between two Vector2's - static void Lerp(const Vector2 & a,const Vector2 & b,float t,Vector2 * set_result); -}; - - -/************************************************************************** - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector2 operator * (const Vector2 &a,float k) -{ - float a0k(a[0] * k); - float a1k(a[1] * k); - return Vector2(a0k,a1k); -} - -WWINLINE Vector2 operator * (float k, const Vector2 &a) -{ - float a0k(a[0] * k); - float a1k(a[1] * k); - return Vector2(a0k,a1k); -} - -/************************************************************************** - * Scalar Division Operator -- Divide a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE Vector2 operator / (const Vector2 &a,float k) -{ - float ook=1.0f/k; - float a0ook(a[0] * ook); - float a1ook(a[1] * ook); - return Vector2(a0ook,a1ook); -} - -/************************************************************************** - * Vector Addition Operator -- Add two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector2 operator + (const Vector2 &a,const Vector2 &b) -{ - return Vector2( - a.X + b.X, - a.Y + b.Y - ); -} - -/************************************************************************** - * Vector Subtraction Operator -- Subract two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector2 operator - (const Vector2 &a,const Vector2 &b) -{ - return Vector2( - a.X - b.X, - a.Y - b.Y - ); -} - -/************************************************************************** - * Vector Inner Product -- Compute the inner or dot product of two vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float operator * (const Vector2 &a,const Vector2 &b) -{ - return a.X*b.X + a.Y*b.Y; -} - -WWINLINE float Vector2::Dot_Product(const Vector2 &a,const Vector2 &b) -{ - return a*b; -} - -WWINLINE float Vector2::Perp_Dot_Product(const Vector2 &a,const Vector2 &b) -{ - return a.X * -b.Y + a.Y * b.X; -} - -/************************************************************************** - * Vector Equality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator == (const Vector2 &a,const Vector2 &b) -{ - bool a0b0(a[0] == b[0]); - bool a1b1(a[1] == b[1]); - return ( a0b0 & a1b1); -} - -/************************************************************************** - * Vector Inequality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator != (const Vector2 &a,const Vector2 &b) -{ - bool a0b0(a[0] != b[0]); - bool a1b1(a[1] != b[1]); - return ( a0b0 | a1b1); -} - -/************************************************************************** - * Equal_Within_Epsilon -- Determine if two vectors are identical within e* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool Equal_Within_Epsilon(const Vector2 &a,const Vector2 &b,float epsilon) -{ - return( (WWMath::Fabs(a.X - b.X) < epsilon) && (WWMath::Fabs(a.Y - b.Y) < epsilon) ); -} - -/************************************************************************** - * Vector2::Normalize -- Normalizes the vector. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE void Vector2::Normalize() -{ - float len2 = Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - X *= oolen; - Y *= oolen; - } -} - -WWINLINE Vector2 Normalize(const Vector2 & vec) -{ - float len2 = vec.Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - return vec / oolen; - } - return Vector2(0.0f,0.0f); -} - -/************************************************************************** - * Vector2::Length -- Returns the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector2::Length() const -{ - return (float)WWMath::Sqrt(Length2()); -} - -/************************************************************************** - * Vector2::Length -- Returns the square of the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector2::Length2() const -{ - return (X*X + Y*Y); -} - -/************************************************************************** - * Vector2::Rotate -- Rotate vector * - * * - * INPUT: * - * float theta - angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE void Vector2::Rotate(float theta) -{ - Rotate(WWMath::Sin(theta), WWMath::Cos(theta)); -} - -/************************************************************************** - * Vector2::Rotate -- Rotate vector * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE void Vector2::Rotate(float s, float c) -{ - float new_x = X * c + Y * -s; - float new_y = X * s + Y * c; - X = new_x; - Y = new_y; -} - -/************************************************************************** - * Vector2::Rotate -- Rotate towards given vector (stop on reaching it) * - * * - * INPUT: * - * float theta - angle to rotate * - * * - * OUTPUT: * - * bool - true if we have reached the desired vector * - * * - * WARNINGS: * - * This function assumes both vectors are normalized! * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool Vector2::Rotate_Towards_Vector(Vector2 &target, float max_theta, bool & positive_turn) -{ - return Rotate_Towards_Vector(target, WWMath::Sin(max_theta), WWMath::Cos(max_theta), positive_turn); -} - -/************************************************************************** - * Vector2::Rotate -- Rotate towards given vector (stop on reaching it) * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * bool - true if we have reached the desired vector * - * * - * WARNINGS: * - * This function assumes both vectors are normalized! * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool Vector2::Rotate_Towards_Vector(Vector2 &target, float max_s, float max_c, bool & positive_turn) -{ - bool return_value = false; - - positive_turn = Vector2::Perp_Dot_Product(target, *this) > 0.0f; - - if (Vector2::Dot_Product(*this, target) >= max_c) { - Set(target); - return_value = true; - } else { - // Determine turn direction and rotate accordingly. - if (positive_turn) { - Rotate(max_s, max_c); - } else { - Rotate(-max_s, max_c); - } - } - - return return_value; -} - -/*********************************************************************************************** - * Swap -- swap two Vector2's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Swap(Vector2 & a,Vector2 & b) -{ - Vector2 tmp(a); - a = b; - b = tmp; -} - - -/*********************************************************************************************** - * Vector2::Is_Valid -- Verifies that all components are valid floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE bool Vector2::Is_Valid(void) const -{ - return (WWMath::Is_Valid_Float(X) && WWMath::Is_Valid_Float(Y)); -} - - -/*********************************************************************************************** - * Vector2::Update_Min -- Set each component of the vector to the min of this and a. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/12/00 IML : Created. * - *=============================================================================================*/ -WWINLINE void Vector2::Update_Min (const Vector2 & a) -{ - if (a.X < X) X = a.X; - if (a.Y < Y) Y = a.Y; -} - - -/*********************************************************************************************** - * Vector2::Update_Max -- Set each component of the vector to the max of this and a. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/12/00 IML : Created. * - *=============================================================================================*/ -WWINLINE void Vector2::Update_Max (const Vector2 & a) -{ - if (a.X > X) X = a.X; - if (a.Y > Y) Y = a.Y; -} - - -/*********************************************************************************************** - * Vector2::Scale -- multiply components of a vector by independant scaling factors. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/19/2000 IML : Created. * - *=============================================================================================*/ -WWINLINE void Vector2::Scale (float a, float b) -{ - X *= a; - Y *= b; -} - - -/*********************************************************************************************** - * Vector2::Scale -- multiply components of a vector by independant scaling factors. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/19/2000 IML : Created. * - *=============================================================================================*/ -WWINLINE void Vector2::Scale (const Vector2 & a) -{ - X *= a.X; - Y *= a.Y; -} - - -/*********************************************************************************************** - * Quick_Distance -- Fast but inaccurate 2D distance calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE float Quick_Distance(float x1, float y1, float x2, float y2) -{ - // From Graphic Gems I. - float x_diff = x1 - x2; - float y_diff = y1 - y2; - - WWMath::Fabs(x_diff); - WWMath::Fabs(y_diff); - - if (x_diff > y_diff) - { - return ((y_diff / 2) + x_diff); - } - else - { - return ((x_diff / 2) + y_diff); - } -} - -WWINLINE float Vector2::Quick_Distance(const Vector2 &a, const Vector2 &b) -{ - return ::Quick_Distance(a.X, a.Y, b.X, b.Y); -} - - -/*********************************************************************************************** - * Distance -- Accurate distance 2D calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE float Vector2::Distance(const Vector2 &a, const Vector2 &b) -{ - Vector2 temp; - temp = a - b; - - return (temp.Length()); -} - -WWINLINE float Distance(float x1, float y1, float x2, float y2) -{ - float x_diff = x1 - x2; - float y_diff = y1 - y2; - - return (WWMath::Sqrt((x_diff * x_diff) + (y_diff * y_diff))); -} - - -/*********************************************************************************************** - * Vector2::Lerp -- linearly interpolates two Vector2's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/14/2000 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector2::Lerp(const Vector2 & a,const Vector2 & b,float t,Vector2 * set_result) -{ - assert(set_result != NULL); - set_result->X = (a.X + (b.X - a.X)*t); - set_result->Y = (a.Y + (b.Y - a.Y)*t); -} - - -#endif /* VECTOR2_H */ - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector2i.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/vector2i.h deleted file mode 100644 index 2bf67476a7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector2i.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/vector2i.h $* - * * - * Author:: Eric Cosky * - * * - * $Modtime:: 5/10/01 11:37p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR2I_H -#define VECTOR2I_H - -#include "always.h" - -class Vector2i -{ -public: - - int I; - int J; - - WWINLINE Vector2i(void); - WWINLINE Vector2i(int i,int j); - - WWINLINE void Set(int i, int j); - - WWINLINE void Swap(Vector2i & other); - - WWINLINE bool operator== (const Vector2i & v) const; - WWINLINE bool operator!= (const Vector2i& v) const; - WWINLINE const int& operator[] (int n) const; - WWINLINE int& operator[] (int n); -}; - - -WWINLINE Vector2i::Vector2i(void) -{ -} - -WWINLINE Vector2i::Vector2i(int i,int j) -{ - I = i; J = j; -} - -WWINLINE bool Vector2i::operator == (const Vector2i & v) const -{ - return (I == v.I && J == v.J ); -} - -WWINLINE bool Vector2i::operator != (const Vector2i& v) const -{ - return !(I == v.I && J == v.J); -} - -WWINLINE const int& Vector2i::operator[] (int n) const -{ - return ((int*)this)[n]; -} - -WWINLINE int& Vector2i::operator[] (int n) -{ - return ((int*)this)[n]; -} - -WWINLINE void Vector2i::Set(int i, int j) { I = i; J = j; } - -WWINLINE void Vector2i::Swap(Vector2i & other) -{ - // this could use MMX.. - - I ^= other.I; - other.I ^= I; - I ^= other.I; - - J ^= other.J; - other.J ^= J; - J ^= other.J; -} - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector3.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/vector3.h deleted file mode 100644 index 8287842b1d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector3.h +++ /dev/null @@ -1,939 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/vector3.h 40 5/11/01 7:11p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Westwood 3D * - * * - * File Name : VECTOR3.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Scalar Division Operator -- Divide a vector by a scalar * - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * Vector Addition Operator -- Add two vectors * - * Vector Subtraction Operator -- Subract two vectors * - * Vector Inner Product Operator -- Compute the inner or dot product * - * Vector Equality Operator -- Determine if two vectors are identical * - * Vector Inequality Operator -- Determine if two vectors are identical * - * Equal_Within_Epsilon -- Determine if two vectors are identical within * - * Cross_Product -- compute the cross product of two vectors * - * Vector3::Normalize -- Normalizes the vector. * - * Vector3::Length -- Returns the length of the vector * - * Vector3::Length2 -- Returns the square of the length of the vector * - * Vector3::Quick_Length -- returns a quick approximation of the length * - * Swap -- swap two Vector3's * - * Lerp -- linearly interpolate two Vector3's by an interpolation factor. * - * Lerp -- linearly interpolate two Vector3's without return-by-value * - * Vector3::Add -- Add two vector3's without return-by-value * - * Vector3::Subtract -- Subtract two vector3's without return-by-value * - * Vector3::Update_Min -- sets each component of the vector to the min of this and a * - * Vector3::Update_Max -- Sets each component of the vector to the max of this and a * - * Vector3::Scale -- scale this vector by 3 independent scale factors * - * Vector3::Rotate_X -- rotates this vector around the X axis * - * Vector3::Rotate_X -- Rotates this vector around the x axis * - * Vector3::Rotate_Y -- Rotates this vector around the y axis * - * Vector3::Rotate_Y -- Rotates this vector around the Y axis * - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * Vector3::Is_Valid -- Verifies that each component of this vector is a valid float * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR3_H -#define VECTOR3_H - -#include "always.h" -#include "wwmath.h" -#include -#ifdef _UNIX -#include "osdep.h" -#endif - - -/* -** Vector3 - 3-Dimensional Vectors -*/ -class Vector3 -{ - -public: - - - float X; - float Y; - float Z; - - - // Constructors - WWINLINE Vector3(void) {}; - WWINLINE Vector3(const Vector3 & v) { X = v.X; Y = v.Y; Z = v.Z; } - WWINLINE Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } - WWINLINE Vector3(const float vector[3]) { X = vector[0]; Y = vector[1]; Z = vector[2]; } - - // Assignment - WWINLINE Vector3 & operator = (const Vector3 & v) { X = v.X; Y = v.Y; Z = v.Z; return *this; } - WWINLINE void Set(float x, float y, float z) { X = x; Y = y; Z = z; } - WWINLINE void Set(const Vector3 & that) { X = that.X; Y = that.Y; Z = that.Z; } - - // Array access - WWINLINE float & operator [](int i) { return (&X)[i]; } - WWINLINE const float & operator [](int i) const { return (&X)[i]; } - - // normalize, compute length - void Normalize(void); - WWINLINE float Length(void) const; - WWINLINE float Length2(void) const; - float Quick_Length(void) const; - void Scale(const Vector3 & scale); - - // rotation, (warning, modifies this vector!) - WWINLINE void Rotate_X(float angle); - WWINLINE void Rotate_X(float s_angle,float c_angle); - WWINLINE void Rotate_Y(float angle); - WWINLINE void Rotate_Y(float s_angle,float c_angle); - WWINLINE void Rotate_Z(float angle); - WWINLINE void Rotate_Z(float s_angle,float c_angle); - - // unary operators - WWINLINE Vector3 operator-() const { return(Vector3(-X,-Y,-Z)); } - WWINLINE Vector3 operator+() const { return *this; } - - WWINLINE Vector3 & operator += (const Vector3 & v) { X += v.X; Y += v.Y; Z += v.Z; return *this; } - WWINLINE Vector3 & operator -= (const Vector3 & v) { X -= v.X; Y -= v.Y; Z -= v.Z; return *this; } - WWINLINE Vector3 & operator *= (float k) { X = X*k; Y=Y*k; Z=Z*k; return *this; } - WWINLINE Vector3 & operator /= (float k) { float ook=1.0f/k; X=X*ook; Y=Y*ook; Z=Z*ook; return *this; } - - // scalar multiplication, division - WWINLINE friend Vector3 operator * (const Vector3 &a,float k); - WWINLINE friend Vector3 operator * (float k,const Vector3 &a); - WWINLINE friend Vector3 operator / (const Vector3 &a,float k); - - // vector addition,subtraction - WWINLINE friend Vector3 operator + (const Vector3 &a,const Vector3 &b); - WWINLINE friend Vector3 operator - (const Vector3 &a,const Vector3 &b); - - // Equality operators - friend bool operator == (const Vector3 &a,const Vector3 &b); - friend bool operator != (const Vector3 &a,const Vector3 &b); - WWINLINE friend bool Equal_Within_Epsilon(const Vector3 &a,const Vector3 &b,float epsilon); - - // dot product / inner product - WWINLINE friend float operator * (const Vector3 &a,const Vector3 &b); - static WWINLINE float Dot_Product(const Vector3 &a,const Vector3 &b); - - // cross product / outer product -#ifdef ALLOW_TEMPORARIES - static WWINLINE Vector3 Cross_Product(const Vector3 &a,const Vector3 &b); -#endif - static WWINLINE void Cross_Product(const Vector3 &a,const Vector3 &b,Vector3 * result); - static WWINLINE void Normalized_Cross_Product(const Vector3 &a, const Vector3 &b, Vector3 * result); - static WWINLINE float Cross_Product_X(const Vector3 &a,const Vector3 &b); - static WWINLINE float Cross_Product_Y(const Vector3 &a,const Vector3 &b); - static WWINLINE float Cross_Product_Z(const Vector3 &a,const Vector3 &b); - - // add and subtract without return by value - static WWINLINE void Add(const Vector3 & a,const Vector3 & b,Vector3 * c); - static WWINLINE void Subtract(const Vector3 & a,const Vector3 & b,Vector3 * c); - - // Line intersection functions. - static WWINLINE float Find_X_At_Y(float y, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_X_At_Z(float z, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Y_At_X(float x, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Y_At_Z(float z, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Z_At_X(float x, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Z_At_Y(float z, const Vector3 &p1, const Vector3 &p2); - - // make this vector the min or max of itself and the passed vector - WWINLINE void Update_Min(const Vector3 & a); - WWINLINE void Update_Max(const Vector3 & a); - WWINLINE void Cap_Absolute_To(const Vector3 & a); - - // verify that none of the members of this vector are invalid floats - WWINLINE bool Is_Valid(void) const; - - static WWINLINE float Quick_Distance(const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Distance(const Vector3 &p1, const Vector3 &p2); - - // Linearly interpolate two Vector3's - static void Lerp(const Vector3 & a, const Vector3 & b, float alpha,Vector3 * set_result); - -#ifdef ALLOW_TEMPORARIES - static Vector3 Lerp(const Vector3 & a, const Vector3 & b, float alpha); -#endif - - // Color Conversion - WWINLINE unsigned long Convert_To_ABGR( void ) const; - WWINLINE unsigned long Convert_To_ARGB( void ) const; - WWINLINE unsigned long Convert_To_ARGB( float alpha ) const; -}; - - -/************************************************************************** - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector3 operator * (const Vector3 &a,float k) -{ - return Vector3((a.X * k),(a.Y * k),(a.Z * k)); -} - -WWINLINE Vector3 operator * (float k, const Vector3 &a) -{ - return Vector3((a.X * k),(a.Y * k),(a.Z * k)); -} - -/************************************************************************** - * Scalar Division Operator -- Divide a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE Vector3 operator / (const Vector3 &a,float k) -{ - float ook = 1.0f/k; - return Vector3((a.X * ook),(a.Y * ook),(a.Z * ook)); -} - -/************************************************************************** - * Vector Addition Operator -- Add two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector3 operator + (const Vector3 &a,const Vector3 &b) -{ - return Vector3( - a.X+b.X, - a.Y+b.Y, - a.Z+b.Z - ); -} - -/************************************************************************** - * Vector Subtraction Operator -- Subract two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector3 operator - (const Vector3 &a,const Vector3 &b) -{ - return Vector3( - a.X-b.X, - a.Y-b.Y, - a.Z-b.Z - ); -} - -/************************************************************************** - * Vector Inner Product -- Compute the inner or dot product of two vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float operator * (const Vector3 &a,const Vector3 &b) -{ - return a.X*b.X + - a.Y*b.Y + - a.Z*b.Z; -} - -WWINLINE float Vector3::Dot_Product(const Vector3 &a,const Vector3 &b) -{ - return a.X*b.X + - a.Y*b.Y + - a.Z*b.Z; -} - - -/************************************************************************** - * Vector Equality Operator -- Determine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator == (const Vector3 &a,const Vector3 &b) -{ - return ( (a.X == b.X) && (a.Y == b.Y) && (a.Z == b.Z)); -} - -/************************************************************************** - * Vector Inequality Operator -- Determine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator != (const Vector3 &a,const Vector3 &b) -{ - return ( (a.X != b.X) || (a.Y != b.Y) || (a.Z != b.Z)); -} - -/************************************************************************** - * Equal_Within_Epsilon -- Determine if two vectors are identical within e* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool Equal_Within_Epsilon(const Vector3 &a,const Vector3 &b,float epsilon) -{ - return( (WWMath::Fabs(a.X - b.X) < epsilon) && - (WWMath::Fabs(a.Y - b.Y) < epsilon) && - (WWMath::Fabs(a.Z - b.Z) < epsilon) ); -} - - -/************************************************************************** - * Cross_Product -- compute the cross product of two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -#ifdef ALLOW_TEMPORARIES -WWINLINE Vector3 Vector3::Cross_Product(const Vector3 &a,const Vector3 &b) -{ - return Vector3( - (a.Y * b.Z - a.Z * b.Y), - (a.Z * b.X - a.X * b.Z), - (a.X * b.Y - a.Y * b.X) - ); -} -#endif - -WWINLINE void Vector3::Cross_Product(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != &a); - set_result->X = (a.Y * b.Z - a.Z * b.Y); - set_result->Y = (a.Z * b.X - a.X * b.Z); - set_result->Z = (a.X * b.Y - a.Y * b.X); -} - -WWINLINE void Vector3::Normalized_Cross_Product(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != &a); - set_result->X = (a.Y * b.Z - a.Z * b.Y); - set_result->Y = (a.Z * b.X - a.X * b.Z); - set_result->Z = (a.X * b.Y - a.Y * b.X); - set_result->Normalize(); -} - -WWINLINE float Vector3::Cross_Product_X(const Vector3 &a,const Vector3 &b) -{ - return a.Y * b.Z - a.Z * b.Y; -} - -WWINLINE float Vector3::Cross_Product_Y(const Vector3 &a,const Vector3 &b) -{ - return a.Z * b.X - a.X * b.Z; -} - -WWINLINE float Vector3::Cross_Product_Z(const Vector3 &a,const Vector3 &b) -{ - return a.X * b.Y - a.Y * b.X; -} - -/************************************************************************** - * Vector3::Normalize -- Normalizes the vector. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE void Vector3::Normalize() -{ - float len2 = Length2(); - if (len2 != 0.0f) - { - float oolen = WWMath::Inv_Sqrt(len2); - X *= oolen; - Y *= oolen; - Z *= oolen; - } -} - -#ifdef ALLOW_TEMPORARIES -WWINLINE Vector3 Normalize(const Vector3 & vec) -{ - float len2 = vec.Length2(); - if (len2 != 0.0f) - { - float oolen = WWMath::Inv_Sqrt(len2); - return vec * oolen; - } - return vec; -} -#endif - -/************************************************************************** - * Vector3::Length -- Returns the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector3::Length() const -{ - return WWMath::Sqrt(Length2()); -} - -/************************************************************************** - * Vector3::Length2 -- Returns the square of the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector3::Length2() const -{ - return X*X + Y*Y + Z*Z; -} - - -/*********************************************************************************************** - * Vector3::Quick_Length -- returns a quick approximation of the length * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/15/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE float Vector3::Quick_Length(void) const -{ - // this method of approximating the length comes from Graphics Gems 1 and - // supposedly gives an error of +/- 8% - float max = WWMath::Fabs(X); - float mid = WWMath::Fabs(Y); - float min = WWMath::Fabs(Z); - float tmp; - - if (max < mid) { tmp = max; max = mid; mid = tmp; } - if (max < min) { tmp = max; max = min; min = tmp; } - if (mid < min) { tmp = mid; mid = min; min = mid; } - - return max + (11.0f / 32.0f)*mid + (1.0f / 4.0f)*min; -} - - -/*********************************************************************************************** - * Swap -- swap two Vector3's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Swap(Vector3 & a,Vector3 & b) -{ - Vector3 tmp(a); - a = b; - b = tmp; -} - -/*********************************************************************************************** - * Lerp -- linearly interpolate two Vector3's without return-by-value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Lerp(const Vector3 & a, const Vector3 & b, float alpha,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = (a.X + (b.X - a.X)*alpha); - set_result->Y = (a.Y + (b.Y - a.Y)*alpha); - set_result->Z = (a.Z + (b.Z - a.Z)*alpha); -} - - -#ifdef ALLOW_TEMPORARIES -WWINLINE Vector3 Vector3::Lerp(const Vector3 & a, const Vector3 & b, float alpha) -{ - Vector3 set_result; - Vector3::Lerp(a, b, alpha, &set_result); - return set_result; -} -#endif - -/*********************************************************************************************** - * Vector3::Add -- Add two vector3's without return-by-value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Add(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = a.X + b.X; - set_result->Y = a.Y + b.Y; - set_result->Z = a.Z + b.Z; -} - - -/*********************************************************************************************** - * Vector3::Subtract -- Subtract two vector3's without return-by-value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Subtract(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = a.X - b.X; - set_result->Y = a.Y - b.Y; - set_result->Z = a.Z - b.Z; -} - - -/*********************************************************************************************** - * Vector3::Update_Min -- sets each component of the vector to the min of this and a * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Update_Min(const Vector3 & a) -{ - if (a.X < X) X = a.X; - if (a.Y < Y) Y = a.Y; - if (a.Z < Z) Z = a.Z; -} - - -/*********************************************************************************************** - * Vector3::Update_Max -- Sets each component of the vector to the max of this and a * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Update_Max(const Vector3 & a) -{ - if (a.X > X) X = a.X; - if (a.Y > Y) Y = a.Y; - if (a.Z > Z) Z = a.Z; -} - -/*********************************************************************************************** - * Vector3::Cap_To_Absolute_Of -- Sets each component of the vector to no larger than the -ve or +ve of* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/29/99 wst : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Cap_Absolute_To(const Vector3 & a) -{ - if (X > 0) - { - if (a.X < X) X = a.X; - } - else - { - if (-a.X > X) X = -a.X; - } - - if (Y > 0) - { - if (a.Y < Y) Y = a.Y; - } - else - { - if (-a.Y > Y) Y = -a.Y; - } - - if (Z > 0) - { - if (a.Z < Z) Z = a.Z; - } - else - { - if (-a.Z > Z) Z = -a.Z; - } - -} - -/*********************************************************************************************** - * Vector3::Scale -- scale this vector by 3 independent scale factors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Scale(const Vector3 & scale) -{ - X *= scale.X; - Y *= scale.Y; - Z *= scale.Z; -} - - -/*********************************************************************************************** - * Vector3::Rotate_X -- rotates this vector around the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_X(float angle) -{ - Rotate_X(sinf(angle),cosf(angle)); -} - - -/*********************************************************************************************** - * Vector3::Rotate_X -- Rotates this vector around the x axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_X(float s_angle,float c_angle) -{ - float tmp_y = Y; - float tmp_z = Z; - - Y = c_angle * tmp_y - s_angle * tmp_z; - Z = s_angle * tmp_y + c_angle * tmp_z; -} - - -/*********************************************************************************************** - * Vector3::Rotate_Y -- Rotates this vector around the y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Y(float angle) -{ - Rotate_Y(sinf(angle),cosf(angle)); -} - - -/*********************************************************************************************** - * Vector3::Rotate_Y -- Rotates this vector around the Y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Y(float s_angle,float c_angle) -{ - float tmp_x = X; - float tmp_z = Z; - - X = c_angle * tmp_x + s_angle * tmp_z; - Z = -s_angle * tmp_x + c_angle * tmp_z; -} - - -/*********************************************************************************************** - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Z(float angle) -{ - Rotate_Z(sinf(angle),cosf(angle)); -} - - -/*********************************************************************************************** - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Z(float s_angle,float c_angle) -{ - float tmp_x = X; - float tmp_y = Y; - - X = c_angle * tmp_x - s_angle * tmp_y; - Y = s_angle * tmp_x + c_angle * tmp_y; -} - - -/*********************************************************************************************** - * Vector3::Is_Valid -- Verifies that each component of this vector is a valid float * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE bool Vector3::Is_Valid(void) const -{ - return (WWMath::Is_Valid_Float(X) && WWMath::Is_Valid_Float(Y) && WWMath::Is_Valid_Float(Z)); -} - -WWINLINE float Vector3::Find_X_At_Y(float y, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.X + ((y - p1.Y) * ((p2.X - p1.X) / (p2.Y - p1.Y)))); -} -WWINLINE float Vector3::Find_X_At_Z(float z, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.X + ((z - p1.Z) * ((p2.X - p1.X) / (p2.Z - p1.Z)))); -} -WWINLINE float Vector3::Find_Y_At_X(float x, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Y + ((x - p1.X) * ((p2.Y - p1.Y) / (p2.X - p1.X)))); -} -WWINLINE float Vector3::Find_Y_At_Z(float z, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Y + ((z - p1.Z) * ((p2.Y - p1.Y) / (p2.Z - p1.Z)))); -} -WWINLINE float Vector3::Find_Z_At_X(float x, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Z + ((x - p1.X) * ((p2.Z - p1.Z) / (p2.X - p1.X)))); -} -WWINLINE float Vector3::Find_Z_At_Y(float y, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Z + ((y - p1.Y) * ((p2.Z - p1.Z) / (p2.Y - p1.Y)))); -} - -/*********************************************************************************************** - * Vector3::Distance -- Accurate distance calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE float Vector3::Distance(const Vector3 &p1, const Vector3 &p2) -{ - Vector3 temp; - temp = p1 - p2; - return (temp.Length()); -} - -/*********************************************************************************************** - * Vector3::Quick_Distance -- Fast but inaccurate distance calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE float Vector3::Quick_Distance(const Vector3 &p1, const Vector3 &p2) -{ - Vector3 temp; - temp = p1 - p2; - return (temp.Quick_Length()); -} - -/*********************************************************************************************** - * Vector3::Convert_To_ABGR -- Converts to SR packed color . * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE unsigned long Vector3::Convert_To_ABGR( void ) const -{ - return (unsigned(255)<<24) | - (unsigned(Z*255.0f)<<16) | - (unsigned(Y*255.0f)<<8) | - (unsigned(X*255.0f)); -} - -/*********************************************************************************************** - * Vector3::Convert_To_ARGB -- Converts to packed color . * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE unsigned long Vector3::Convert_To_ARGB( void ) const -{ - return (unsigned(255)<<24) | - (unsigned(X*255.0f)<<16) | - (unsigned(Y*255.0f)<<8) | - (unsigned(Z*255.0f)); -} - -WWINLINE unsigned long Vector3::Convert_To_ARGB( float alpha ) const -{ - return (unsigned(alpha * 255)<<24) | - (unsigned(X*255.0f)<<16) | - (unsigned(Y*255.0f)<<8) | - (unsigned(Z*255.0f)); -} - -#endif /* Vector3_H */ - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector4.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/vector4.h deleted file mode 100644 index 146347f8d6..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vector4.h +++ /dev/null @@ -1,412 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/vector4.h 16 5/11/01 7:11p Jani_p $ */ -/*************************************************************************** - *** Confidential - Westwood Studios *** - *************************************************************************** - * * - * Project Name : Westwood 3D * - * * - * File Name : VECTOR4.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : June 2, 1997 [GH] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * Scalar Division Operator -- Divide a vector by a scalar * - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * Vector Addition Operator -- Add two vectors * - * Vector Subtraction Operator -- Subract two vectors * - * Vector Inner Product Operator -- Compute the inner or dot product * - * Vector Equality Operator -- Detemine if two vectors are identical * - * Vector Inequality Operator -- Detemine if two vectors are identical * - * Swap -- swap two Vector4's * - * Vector4::Is_Valid -- Vector4::Is_Valid * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR4_H -#define VECTOR4_H - -#include "always.h" -#include "wwmath.h" -#include - -/* -** Vector4 - 4 dimensional vectors -*/ -class Vector4 -{ - -public: - - float X; - float Y; - float Z; - float W; - - - // Constructors - WWINLINE Vector4(void) {}; - WWINLINE Vector4(const Vector4 & v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; } - WWINLINE Vector4(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } - WWINLINE Vector4(const float vector[4]) { X = vector[0]; Y = vector[1]; Z = vector[2]; W = vector[3]; } - - // Assignment - WWINLINE Vector4 & operator = (const Vector4 & v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; return *this; } - WWINLINE void Set(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } - - // Array access - WWINLINE float & operator [](int i) { return (&X)[i]; } - WWINLINE const float & operator [](int i) const { return (&X)[i]; } - - // normalize, compute length - void Normalize(void); - WWINLINE float Length(void) const; - WWINLINE float Length2(void) const; - - // unary operators - WWINLINE Vector4 operator-() const { return(Vector4(-X,-Y,-Z,-W)); } - WWINLINE Vector4 operator+() const { return *this; } - - WWINLINE Vector4 & operator += (const Vector4 & v) { X += v.X; Y += v.Y; Z += v.Z; W += v.W; return *this; } - WWINLINE Vector4 & operator -= (const Vector4 & v) { X -= v.X; Y -= v.Y; Z -= v.Z; W += v.W; return *this; } - WWINLINE Vector4 & operator *= (float k) { X = X*k; Y=Y*k; Z=Z*k; W=W*k; return *this; } - WWINLINE Vector4 & operator /= (float k) { k=1.0f/k; X = X*k; Y=Y*k; Z=Z*k; W=W*k; return *this; } - - // scalar multiplication, division - WWINLINE friend Vector4 operator * (const Vector4 &a,float k); - WWINLINE friend Vector4 operator * (float k,const Vector4 &a); - WWINLINE friend Vector4 operator / (const Vector4 &a,float k); - - // vector addition,subtraction - WWINLINE friend Vector4 operator + (const Vector4 &a,const Vector4 &b); - WWINLINE friend Vector4 operator - (const Vector4 &a,const Vector4 &b); - - // dot product / inner product - WWINLINE friend float operator * (const Vector4 &a,const Vector4 &b); - static WWINLINE float Dot_Product(const Vector4 &a,const Vector4 &b); - - // Equality operators - friend bool operator == (const Vector4 &a,const Vector4 &b); - friend bool operator != (const Vector4 &a,const Vector4 &b); - - // Linearly interpolate between two Vector4's - static Vector4 Lerp(const Vector4 & a, const Vector4 & b, float alpha); - static void Lerp(const Vector4 & a, const Vector4 & b, float alpha,Vector4 * set_result); - - // verify that none of the members of this vector are invalid floats - WWINLINE bool Is_Valid(void) const; -}; - -/************************************************************************** - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector4 operator * (const Vector4 &a,float k) -{ - return Vector4((a.X * k),(a.Y * k),(a.Z * k),(a.W * k)); -} - -WWINLINE Vector4 operator * (float k, const Vector4 &a) -{ - return a*k; -} - -/************************************************************************** - * Scalar Division Operator -- Divide a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE Vector4 operator / (const Vector4 &a,float k) -{ - float ook=1.0f/k; - return Vector4((a[0] * ook),(a[1] * ook),(a[2] * ook),(a[3] * ook)); -} - -/************************************************************************** - * Vector Addition Operator -- Add two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector4 operator + (const Vector4 &a,const Vector4 &b) -{ - return Vector4( - a[0]+b[0], - a[1]+b[1], - a[2]+b[2], - a[3]+b[3] - ); -} - -/************************************************************************** - * Vector Subtraction Operator -- Subract two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector4 operator - (const Vector4 &a,const Vector4 &b) -{ - return Vector4( - a[0]-b[0], - a[1]-b[1], - a[2]-b[2], - a[3]-b[3] - ); -} - -/************************************************************************** - * Vector Inner Product -- Compute the inner or dot product of two vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float operator * (const Vector4 &a,const Vector4 &b) -{ - return a[0]*b[0] + - a[1]*b[1] + - a[2]*b[2] + - a[3]*b[3]; -} - -WWINLINE float Vector4::Dot_Product(const Vector4 &a,const Vector4 &b) -{ - return a*b; -} - - -/************************************************************************** - * Vector Equality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator == (const Vector4 &a,const Vector4 &b) -{ - return ( (a[0] == b[0]) && (a[1] == b[1]) && (a[2] == b[2]) && (a[3] == b[3])); -} - -/************************************************************************** - * Vector Inequality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator != (const Vector4 &a,const Vector4 &b) -{ - return ( (a[0] != b[0]) || (a[1] != b[1]) || (a[2] != b[2]) || (a[3] != b[3])); -} - -/************************************************************************** - * Vector4::Normalize -- Normalizes the vector. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE void Vector4::Normalize() -{ - float len2 = Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - X *= oolen; - Y *= oolen; - Z *= oolen; - W *= oolen; - } -} - -WWINLINE Vector4 Normalize(const Vector4 & vec) -{ - float len2 = vec.Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - return vec * oolen; - } - return Vector4(0.0f,0.0f,0.0f,0.0f); -} - -/************************************************************************** - * Vector4::Length -- Returns the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector4::Length() const -{ - return WWMath::Sqrt(Length2()); -} - -/************************************************************************** - * Vector4::Length -- Returns the square of the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector4::Length2() const -{ - return X*X + Y*Y + Z*Z + W*W; -} - - -/*********************************************************************************************** - * Swap -- swap two Vector4's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Swap(Vector4 & a,Vector4 & b) -{ - Vector4 tmp(a); - a = b; - b = tmp; -} - -/*********************************************************************************************** - * Lerp -- linearly interpolate two Vector4's by an interpolation factor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: No checking is done to ensure that alpha is between 0 and 1. * - * * - * HISTORY: * - * 01/14/1999 NH : Created. * - *=============================================================================================*/ -WWINLINE Vector4 Lerp(const Vector4 & a, const Vector4 & b, float alpha) -{ - return Vector4( - (a.X + (b.X - a.X)*alpha), - (a.Y + (b.Y - a.Y)*alpha), - (a.Z + (b.Z - a.Z)*alpha), - (a.W + (b.W - a.W)*alpha) - ); -} - -WWINLINE Vector4 Vector4::Lerp(const Vector4 & a, const Vector4 & b, float alpha) -{ - return Vector4( - (a.X + (b.X - a.X)*alpha), - (a.Y + (b.Y - a.Y)*alpha), - (a.Z + (b.Z - a.Z)*alpha), - (a.W + (b.W - a.W)*alpha) - ); -} - -WWINLINE void Vector4::Lerp(const Vector4 & a, const Vector4 & b, float alpha,Vector4 * set_result) -{ - set_result->X = (a.X + (b.X - a.X)*alpha); - set_result->Y = (a.Y + (b.Y - a.Y)*alpha); - set_result->Z = (a.Z + (b.Z - a.Z)*alpha); - set_result->X = (a.W + (b.W - a.W)*alpha); -} - -/*********************************************************************************************** - * Vector4::Is_Valid -- Vector4::Is_Valid * - * * - * verifies that all members of this vector are valid floats * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE bool Vector4::Is_Valid(void) const -{ - return (WWMath::Is_Valid_Float(X) && WWMath::Is_Valid_Float(Y) && WWMath::Is_Valid_Float(Z) && WWMath::Is_Valid_Float(W)); -} - - -#endif /* VECTOR4_H */ - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp deleted file mode 100644 index 40afd6f50f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.cpp +++ /dev/null @@ -1,686 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : LevelEdit * - * * - * $Archive:: /Commando/Code/wwmath/vehiclecurve.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 6/12/01 10:02a $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "vehiclecurve.h" -#include "vector3.h" -#include "matrix3d.h" -#include "persistfactory.h" -#include "wwmathids.h" -#include "wwmemlog.h" - - -////////////////////////////////////////////////////////////////////// -// Save-Load stuff -////////////////////////////////////////////////////////////////////// -SimplePersistFactoryClass _VehicleCurveFactory; - -//////////////////////////////////////////////////////////////// -// Save/Load constants -//////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_PARENT = 0x11071217, - CHUNKID_ARC_INFO, - CHUNKID_VARIABLES -}; - -enum -{ - VARID_IS_DIRTY = 1, - VARID_RADIUS, -}; - - -////////////////////////////////////////////////////////////////////// -// Local prototypes -////////////////////////////////////////////////////////////////////// -bool Find_Tangent (const Vector3 ¢er, float radius, const Vector3 &point, bool clockwise, float *result); -float Get_Angle_Delta (float angle1, float angle2, bool clockwise); -void Find_Turn_Arc (const Matrix3D &transform, float radius, const Vector3 &prev_pt, const Vector3 &curr_pt, const Vector3 &next_pt, Vector3 *arc_center, bool *is_right_turn); -void Find_Tangents (float radius, const Vector3 &prev_pt, const Vector3 &curr_pt, const Vector3 &next_pt, const Vector3 &arc_center, bool is_right_turn, float *point_angle, float *angle_in_delta, float *angle_out_delta); - - -////////////////////////////////////////////////////////////////////// -// -// Find_Tangent -// -////////////////////////////////////////////////////////////////////// -bool -Find_Tangent -( - const Vector3 & center, - float radius, - const Vector3 & point, - bool clockwise, - float * result -) -{ - bool retval = false; - - // - // Calculate the distance from the point to the center of the circle - // - float delta_x = point.X - center.X; - float delta_y = point.Y - center.Y; - float dist = ::sqrt (delta_x * delta_x + delta_y * delta_y); - if (dist >= radius) { - - // - // Determine the offset angle (from the line between the point and center) - // where the 2 tangent points lie. - // - float angle_offset = WWMath::Acos (radius / dist); - float base_angle = WWMath::Atan2 (delta_x, -delta_y); - base_angle = WWMath::Wrap (base_angle, 0, DEG_TO_RADF (360)); - - // - // Determine which tangent angle we would come across first, depending - // on our orientation - // - float angle = 0; - if (clockwise) { - angle = base_angle - angle_offset; - } else { - angle = base_angle + angle_offset; - } - angle = WWMath::Wrap (angle, 0, DEG_TO_RADF (360)); - (*result) = angle; - - retval = true; - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////// -// -// Get_Angle_Delta -// -// Angle deltas need to be wrapped around 360 degrees differently -// depending on the orientation (clockwise/counterclockwise). This -// function takes orientation into consideration when determining -// the delta. -// -////////////////////////////////////////////////////////////////////// -float -Get_Angle_Delta -( - float angle1, - float angle2, - bool clockwise -) -{ - float result = angle1 - angle2; - - if (clockwise) { - if (angle1 < angle2) { - result = angle1 - (angle2 - DEG_TO_RADF (360)); - } - } else { - if (angle1 > angle2) { - result = (angle1 - DEG_TO_RADF (360)) - angle2; - } - } - - return result; -} - - -////////////////////////////////////////////////////////////////////// -// -// Find_Turn_Arc -// -////////////////////////////////////////////////////////////////////// -void -Find_Turn_Arc -( - const Matrix3D & transform, - float radius, - const Vector3 & prev_pt, - const Vector3 & curr_pt, - const Vector3 & next_pt, - Vector3 * arc_center, - bool * is_right_turn -) -{ - // - // The center of the turn arc can lie anywhere on the circle centered - // at the current point and 'radius' meters in radius. - // - // We will assume the optimal center of the turn arc will lie at - // the point halfway between the angles formed by the (prev-curr) and - // (next-curr) vectors. - // - float angle1 = ::WWMath::Atan2 ((prev_pt.Y - curr_pt.Y), prev_pt.X - curr_pt.X); - angle1 = WWMath::Wrap (angle1, 0, DEG_TO_RADF (360)); - - float angle2 = ::WWMath::Atan2 ((next_pt.Y - curr_pt.Y), next_pt.X - curr_pt.X); - angle2 = WWMath::Wrap (angle2, 0, DEG_TO_RADF (360)); - - float avg_angle = (angle1 + angle2) * 0.5F; - - // - // Find the shortest delta between the two angles (either clockwise or - // counterclockwise). - // - float delta1 = WWMath::Fabs (::Get_Angle_Delta (angle1, angle2, true)); - float delta2 = WWMath::Fabs (::Get_Angle_Delta (angle1, angle2, false)); - if (delta1 < delta2) { - avg_angle = angle1 - (delta1 * 0.5F); - } else { - avg_angle = angle1 + (delta2 * 0.5F); - } - - // - // Find the point on the circle at this angle - // - arc_center->X = curr_pt.X + (radius * ::WWMath::Cos (avg_angle)); - arc_center->Y = curr_pt.Y + (radius * ::WWMath::Sin (avg_angle)); - arc_center->Z = curr_pt.Z; - - // - // Will we be making a right turn or a left turn? - // - Vector3 rel_center; - Matrix3D::Inverse_Transform_Vector (transform, *arc_center, &rel_center); - (*is_right_turn) = (rel_center.Y > 0); - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Find_Tangents -// -////////////////////////////////////////////////////////////////////// -void -Find_Tangents -( - float radius, - const Vector3 & prev_pt, - const Vector3 & curr_pt, - const Vector3 & next_pt, - const Vector3 & arc_center, - bool is_right_turn, - float * point_angle, - float * angle_in_delta, - float * angle_out_delta -) -{ - - // - // Find the 'in' and 'out' tangent angles - // - float angle_in = 0; - float angle_out = 0; - bool valid_in = ::Find_Tangent (arc_center, radius, prev_pt, is_right_turn, &angle_in); - bool valid_out = ::Find_Tangent (arc_center, radius, next_pt, !is_right_turn, &angle_out); - - // - // Find the angle where the current position lies on the turn arc - // - (*point_angle) = ::WWMath::Atan2 (curr_pt.X - arc_center.X, -(curr_pt.Y - arc_center.Y)); - (*point_angle) = WWMath::Wrap ((*point_angle), 0, DEG_TO_RADF (360)); - - // - // If the tangent-in is valid, find its delta from the 'point angle. - // - if (valid_in) { - (*angle_in_delta) = ::Get_Angle_Delta (angle_in, (*point_angle), is_right_turn); - } else { - (*angle_in_delta) = 0; - } - - // - // If the tangent-out is valid, find its delta from the 'point angle. - // - if (valid_out) { - (*angle_out_delta) = ::Get_Angle_Delta (angle_out, (*point_angle), !is_right_turn); - } else { - (*angle_out_delta) = 0; - } - - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Update_Arc_List -// -////////////////////////////////////////////////////////////////////// -void -VehicleCurveClass::Update_Arc_List (void) -{ - WWMEMLOG(MEM_PATHFIND); - m_ArcList.Delete_All (); - - // - // Bail out if there is nothing to do - // - int count = Key_Count (); - if (count == 0) { - return ; - } - - // - // Add a record for the starting point of the arc... - // - ArcInfoStruct arc_start; - arc_start.point_in = Keys[0].Point; - arc_start.point_out = Keys[0].Point; - arc_start.center = Keys[0].Point; - arc_start.point_angle = 0; - arc_start.radius = 0; - arc_start.angle_in_delta = 0; - arc_start.angle_out_delta = 0; - m_ArcList.Add (arc_start); - - // - // Loop over each 'interior' point and generate arc information - // for each. - // - for (int index = 1; index < count - 1; index ++) { - - // - // Get information about the previous, next, and current points. - // - Vector3 prev_pt; - Vector3 next_pt; - Vector3 curr_pt; - float time = 0; - Get_Key (index-1, &prev_pt, &time); - Get_Key (index, &curr_pt, &time); - Get_Key (index+1, &next_pt, &time); - - // - // Determine the last known point on the path - // - Vector3 last_path_pt = m_ArcList[index-1].point_out; - - // - // Create a transformation matrix to simulate the vehicle's position and - // orientation at the last point... - // - Vector3 x_vector (curr_pt - last_path_pt); - Vector3 z_vector (0, 0, 1); - x_vector.Normalize (); -#ifdef ALLOW_TEMPORARIES - Vector3 y_vector = Vector3::Cross_Product (x_vector, z_vector); -#else - Vector3 y_vector; - Vector3::Cross_Product (x_vector, z_vector, &y_vector); -#endif - Matrix3D tm (x_vector, y_vector, z_vector, last_path_pt); - - // - // Find where the turn arc should be centered and whether we should - // make a right-turn or a left turn... - // - bool is_right_turn = false; - Vector3 arc_center (0, 0, 0); - ::Find_Turn_Arc ( tm, - m_Radius, - last_path_pt, - curr_pt, - next_pt, - &arc_center, - &is_right_turn); - - // - // Determine where the vehicle should enter and exit the turn - // - float angle_in_delta = 0; - float angle_out_delta = 0; - float point_angle = 0; - ::Find_Tangents ( m_Radius, - last_path_pt, - curr_pt, - next_pt, - arc_center, - is_right_turn, - &point_angle, - &angle_in_delta, - &angle_out_delta); - - // - // Determine at what points these angles intersect the arc - // - Vector3 point_in (0, 0, 0); - point_in.X = arc_center.X + (m_Radius * ::WWMath::Sin (point_angle + angle_in_delta)); - point_in.Y = arc_center.Y + (m_Radius * -::WWMath::Cos (point_angle + angle_in_delta)); - - Vector3 point_out (0, 0, 0); - point_out.X = arc_center.X + (m_Radius * ::WWMath::Sin (point_angle + angle_out_delta)); - point_out.Y = arc_center.Y + (m_Radius * -::WWMath::Cos (point_angle + angle_out_delta)); - - // - // Sanity check to ensure the vehicle doesn't try to go the long way around the - // turn arc... - // - if ( angle_in_delta > DEG_TO_RADF (200) || angle_out_delta > DEG_TO_RADF (200) || - angle_in_delta < -DEG_TO_RADF (200) || angle_out_delta < -DEG_TO_RADF (200) ) - { - // - // Record information about this arc - // - ArcInfoStruct arc_info; - arc_info.center = curr_pt; - arc_info.point_angle = 0; - arc_info.point_in = curr_pt; - arc_info.point_out = curr_pt; - arc_info.radius = 0; - arc_info.angle_in_delta = 0; - arc_info.angle_out_delta = 0; - m_ArcList.Add (arc_info); - - } else { - - // - // Record information about this arc - // - ArcInfoStruct arc_info; - arc_info.center = arc_center; - arc_info.point_angle = point_angle; - arc_info.point_in = point_in; - arc_info.point_out = point_out; - arc_info.radius = m_Radius; - arc_info.angle_in_delta = angle_in_delta; - arc_info.angle_out_delta = angle_out_delta; - m_ArcList.Add (arc_info); - } - } - - // - // Add a record for the starting point of the arc... - // - if (count > 1) { - ArcInfoStruct arc_end; - arc_end.point_in = Keys[count-1].Point; - arc_end.point_out = Keys[count-1].Point; - arc_end.center = Keys[count-1].Point; - arc_end.point_angle = 0; - arc_end.radius = 0; - arc_end.angle_in_delta = 0; - arc_end.angle_out_delta = 0; - m_ArcList.Add (arc_end); - } - - m_IsDirty = false; - return ; -} - - -////////////////////////////////////////////////////////////////////// -// -// Evaluate -// -////////////////////////////////////////////////////////////////////// -void -VehicleCurveClass::Evaluate (float time, Vector3 *set_val) -{ - int count = Keys.Count (); - m_Sharpness = 0; - - if (time < Keys[0].Time) { - *set_val = Keys[0].Point; - m_LastTime = Keys[0].Time; - return; - } - - if (time >= Keys[count - 1].Time) { - *set_val = Keys[count - 1].Point; - m_LastTime = Keys[count - 1].Time; - return; - } - - // - // Update the arc information if any of the keys have changed... - // - if (m_IsDirty) { - Update_Arc_List (); - } - - // - // Determine which segment we are on - // - int index0 = 0; - int index1 = 0; - float seg_time = 0; - Find_Interval (time, &index0, &index1, &seg_time); - - ArcInfoStruct &arc_info0 = m_ArcList[index0]; - ArcInfoStruct &arc_info1 = m_ArcList[index1]; - - // - // Determine the lengths of each segment of this curve. - // The segments are: - // - Exit curve from prev point - // - Straight line from exit of last curve to enter of this curve - // - Enter curve for the current point - // - float arc_length0 = arc_info0.radius * WWMath::Fabs (arc_info0.angle_out_delta); - float arc_length1 = arc_info1.radius * WWMath::Fabs (arc_info1.angle_in_delta); - float other_length = ((arc_info1.point_in - arc_info0.point_out).Length ()) / 2; - float total_length = arc_length0 + arc_length1 + other_length; - - // - // Determine at what times we should switch between parts of the segment - // - float time1 = arc_length0 / total_length; - float time2 = (arc_length0 + other_length) / total_length; - - // - // Determine which part of the segment we are on - // - if (seg_time < time1) { - - // - // We are on the initial curve of the segment, so calculate where - // on the curve we are... - // - //float percent = seg_time / time1; - //float angle = arc_info0.point_angle + (arc_info0.angle_out_delta) * percent; - float angle = arc_info0.point_angle + arc_info0.angle_out_delta; - - set_val->X = arc_info0.center.X + (arc_info0.radius * ::WWMath::Sin (angle)); - set_val->Y = arc_info0.center.Y + (arc_info0.radius * -::WWMath::Cos (angle)); - - m_Sharpness = WWMath::Clamp (WWMath::Fabs (arc_info0.angle_out_delta) / DEG_TO_RADF (15), 0, 1.0F); - m_SharpnessPos.X = set_val->X; - m_SharpnessPos.Y = set_val->Y; - m_SharpnessPos.Z = Keys[index0].Point.Z + (Keys[index1].Point.Z - Keys[index0].Point.Z) * seg_time; - - m_LastTime = Keys[index0].Time + (Keys[index1].Time - Keys[index0].Time) * time1; - - } else if (seg_time < time2) { - - // - // We are on the line between the two curves, so calculate where on - // the line we are - // - float percent = (seg_time - time1) / (time2 - time1); - - if (percent == 0) { - set_val->X = arc_info0.point_out.X; - set_val->Y = arc_info0.point_out.Y; - } else { - set_val->X = arc_info1.point_in.X; - set_val->Y = arc_info1.point_in.Y; - } - - //set_val->X = arc_info0.point_out.X + (arc_info1.point_in.X - arc_info0.point_out.X) * percent; - //set_val->Y = arc_info0.point_out.Y + (arc_info1.point_in.Y - arc_info0.point_out.Y) * percent; - - m_Sharpness = WWMath::Clamp (WWMath::Fabs (arc_info1.angle_out_delta) / DEG_TO_RADF (15), 0, 1.0F); - m_SharpnessPos = arc_info1.point_in; - - m_LastTime = Keys[index0].Time + (Keys[index1].Time - Keys[index0].Time) * time2; - - } else { - - // - // We are on the ending curve of the segment, so calculate where - // on the curve we are... - // - /*float percent = 1.0F - ((seg_time - time2) / (1.0F - time2)); - float angle = arc_info1.point_angle + (arc_info1.angle_in_delta * percent); - - set_val->X = arc_info1.center.X + (arc_info1.radius * ::WWMath::Sin (angle)); - set_val->Y = arc_info1.center.Y + (arc_info1.radius * -::WWMath::Cos (angle)); */ - - float angle = arc_info1.point_angle + (arc_info1.angle_out_delta); - - set_val->X = arc_info1.center.X + (arc_info1.radius * ::WWMath::Sin (angle)); - set_val->Y = arc_info1.center.Y + (arc_info1.radius * -::WWMath::Cos (angle)); - - m_Sharpness = WWMath::Clamp (WWMath::Fabs (arc_info1.angle_out_delta) / DEG_TO_RADF (15), 0, 1.0F); - m_SharpnessPos.X = set_val->X; - m_SharpnessPos.Y = set_val->Y; - m_SharpnessPos.Z = Keys[index0].Point.Z + (Keys[index1].Point.Z - Keys[index0].Point.Z) * seg_time; - - m_LastTime = Keys[index1].Time; - } - - // - // Our Z value is just a linear interpolation - // - set_val->Z = Keys[index0].Point.Z + (Keys[index1].Point.Z - Keys[index0].Point.Z) * seg_time; - return ; -} - -const PersistFactoryClass & VehicleCurveClass::Get_Factory(void) const -{ - return _VehicleCurveFactory; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -//////////////////////////////////////////////////////////////////////////////////////////// -bool -VehicleCurveClass::Save (ChunkSaveClass &csave) -{ - csave.Begin_Chunk (CHUNKID_PARENT); - Curve3DClass::Save (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_VARIABLES); - - // - // Save each variable to its own microchunk - // - WRITE_MICRO_CHUNK (csave, VARID_IS_DIRTY, m_IsDirty); - WRITE_MICRO_CHUNK (csave, VARID_RADIUS, m_Radius); - - csave.End_Chunk (); - - // - // Save each arc info struct to its own chunk - // - for (int index = 0; index < m_ArcList.Count (); index ++) { - ArcInfoStruct &arc_info = m_ArcList[index]; - - csave.Begin_Chunk (CHUNKID_ARC_INFO); - csave.Write (&arc_info, sizeof (arc_info)); - csave.End_Chunk (); - } - - return true; -} - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -//////////////////////////////////////////////////////////////////////////////////////////// -bool -VehicleCurveClass::Load (ChunkLoadClass &cload) -{ - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_PARENT: - Curve3DClass::Load (cload); - break; - - case CHUNKID_ARC_INFO: - { - ArcInfoStruct arc_info; - cload.Read (&arc_info, sizeof (arc_info)); - m_ArcList.Add (arc_info); - } - break; - - case CHUNKID_VARIABLES: - Load_Variables (cload); - break; - } - - cload.Close_Chunk (); - } - - return true; -} - - -/////////////////////////////////////////////////////////////////////// -// -// Load_Variables -// -/////////////////////////////////////////////////////////////////////// -void -VehicleCurveClass::Load_Variables (ChunkLoadClass &cload) -{ - // - // Loop through all the microchunks that define the variables - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_IS_DIRTY, m_IsDirty); - READ_MICRO_CHUNK (cload, VARID_RADIUS, m_Radius); - } - - cload.Close_Micro_Chunk (); - } - - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.h deleted file mode 100644 index b17adc390e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vehiclecurve.h +++ /dev/null @@ -1,210 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : LevelEdit * - * * - * $Archive:: /VSS_Sync/wwmath/vehiclecurve.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 6/13/01 2:18p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __VEHICLE_CURVE_H -#define __VEHICLE_CURVE_H - -#include "curve.h" -#include "Vector.H" - - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// VehicleCurveClass -// -// A vehicle curve represents the path a vehicle would take through a series of points. -// Each point on the curve passes through a turn-arc of the vehicle. The size of this -// arc is determined by the turn radius which is used to initialize the curve. -// -//////////////////////////////////////////////////////////////////////////////////////////// -class VehicleCurveClass : public Curve3DClass -{ -public: - - /////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////////////// - VehicleCurveClass (void) - : m_IsDirty (true), - m_Radius (0), - m_LastTime (0), - m_Sharpness (0), - m_SharpnessPos (0, 0, 0), - Curve3DClass () { } - - VehicleCurveClass (float radius) - : m_IsDirty (true), - m_Radius (radius), - m_LastTime (0), - m_Sharpness (0), - m_SharpnessPos (0, 0, 0), - Curve3DClass () { } - - virtual ~VehicleCurveClass () {} - - - /////////////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////////////// - - // - // Initialization - // - void Initialize_Arc (float radius); - - // - // From Curve3DClass - // - void Evaluate (float time, Vector3 *set_val); - void Set_Key (int i,const Vector3 & point); - int Add_Key (const Vector3 & point,float t); - void Remove_Key (int i); - void Clear_Keys (void); - - // - // Vehicle curve specific - // - float Get_Current_Sharpness (Vector3 *position) const { *position = m_SharpnessPos; return m_Sharpness; } - float Get_Last_Eval_Time (void) const { return m_LastTime; } - - // - // Save-load support - // - virtual const PersistFactoryClass & Get_Factory(void) const; - virtual bool Save(ChunkSaveClass &csave); - virtual bool Load(ChunkLoadClass &cload); - -protected: - - /////////////////////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////////////////////// - void Update_Arc_List (void); - void Load_Variables (ChunkLoadClass &cload); - - - /////////////////////////////////////////////////////////////////////////// - // Protected data types - /////////////////////////////////////////////////////////////////////////// - typedef struct _ArcInfoStruct - { - Vector3 center; - Vector3 point_in; - Vector3 point_out; - float point_angle; - float radius; - float angle_in_delta; - float angle_out_delta; - - _ArcInfoStruct (void) - : center (0, 0, 0), - point_in (0, 0, 0), - point_out (0, 0, 0), - point_angle (0), - radius (0), - angle_in_delta (0), - angle_out_delta (0) { } - - bool operator== (const _ArcInfoStruct &src) { return false; } - bool operator!= (const _ArcInfoStruct &src) { return true; } - - } ArcInfoStruct; - - typedef DynamicVectorClass ARC_LIST; - - /////////////////////////////////////////////////////////////////////////// - // Protected member data - /////////////////////////////////////////////////////////////////////////// - bool m_IsDirty; - float m_Radius; - ARC_LIST m_ArcList; - - float m_LastTime; - float m_Sharpness; - Vector3 m_SharpnessPos; -}; - -/////////////////////////////////////////////////////////////////////////// -// Set_Key -/////////////////////////////////////////////////////////////////////////// -inline void -VehicleCurveClass::Set_Key (int i,const Vector3 & point) -{ - m_IsDirty = true; - Curve3DClass::Set_Key (i, point); - return ; -} - -/////////////////////////////////////////////////////////////////////////// -// Add_Key -/////////////////////////////////////////////////////////////////////////// -inline int -VehicleCurveClass::Add_Key (const Vector3 & point,float t) -{ - m_IsDirty = true; - return Curve3DClass::Add_Key (point, t); -} - -/////////////////////////////////////////////////////////////////////////// -// Remove_Key -/////////////////////////////////////////////////////////////////////////// -inline void -VehicleCurveClass::Remove_Key (int i) -{ - m_IsDirty = true; - Curve3DClass::Remove_Key (i); - return ; -} - -/////////////////////////////////////////////////////////////////////////// -// Clear_Keys -/////////////////////////////////////////////////////////////////////////// -inline void -VehicleCurveClass::Clear_Keys (void) -{ - m_IsDirty = true; - Curve3DClass::Clear_Keys (); - return ; -} - - -#endif //__VEHICLE_CURVE_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/vp.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/vp.cpp deleted file mode 100644 index 2bfc1e141c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/vp.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwmath * - * * - * $Archive:: /Commando/Code/WWMath/vp.cpp $* - * * - * Org Author:: Hector Yee * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 12 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------*/ - -#include "vp.h" -#include "vector2.h" -#include "vector3.h" -#include "vector4.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "wwdebug.h" -#include "cpudetect.h" -#include - -#define SHUFFLE(x, y, z, w) (((x)&3)<< 6|((y)&3)<<4|((z)&3)<< 2|((w)&3)) -#define BROADCAST(XMM, INDEX) __asm shufps XMM,XMM,(((INDEX)&3)<< 6|((INDEX)&3)<<4|((INDEX)&3)<< 2|((INDEX)&3)) - -#define TRANSPOSE(BX, BY, BZ, BW, TV) \ - __asm movaps TV,BZ \ - __asm unpcklps BZ,BW \ - __asm unpckhps TV,BW \ - __asm movaps BW,BX \ - __asm unpcklps BX,BY \ - __asm unpckhps BW,BY \ - __asm movaps BY,BX \ - __asm shufps BX,BZ,SHUFFLE(1, 0, 1, 0) \ - __asm shufps BY,BZ,SHUFFLE(3, 2, 3, 2) \ - __asm movaps BZ,BW \ - __asm shufps BZ,TV,SHUFFLE(1, 0, 1, 0) \ - __asm shufps BW,TV,SHUFFLE(3, 2, 3, 2) - - -void VectorProcessorClass::Prefetch(void* address) -{ -#if defined (__ICL) // Detect Intel compiler - if (CPUDetectClass::_Has_SSE_Instruction_Set()) { - __asm { -// mov edx,address -// mov eax,[edx] -// prefetchT1 address - } - } -#endif -} - -static Vector4 lastrow(0.0f,0.0f,0.0f,1.0f); -void VectorProcessorClass::Transform (Vector3* dst,const Vector3 *src, const Matrix3D& mtx, const int count) -{ - if (count<=0) return; - -#if defined (__ICL) // Detect Intel compiler - if (CPUDetectClass::_Has_SSE_Instruction_Set()) { - - __asm { - mov edx,dst - mov eax,src - mov ebx,mtx - mov edi,count - - movups xmm4,[ebx+0] - movups xmm5,[ebx+16] - movups xmm6,[ebx+32] - movups xmm7,lastrow //[ebx+48] - - TRANSPOSE(xmm4, xmm5, xmm6, xmm7, xmm0); - - shufps xmm4,xmm4,SHUFFLE(2,1,0,0) - shufps xmm5,xmm5,SHUFFLE(2,1,0,0) - shufps xmm6,xmm6,SHUFFLE(2,1,0,0) - shufps xmm7,xmm7,SHUFFLE(2,1,0,0) - - mov esi,edx - _lp: - test edi,edi - jz _ulos - test esi,0xf - jz _aligned - movss xmm0,[eax] - movss xmm1,[eax+4] - movss xmm2,[eax+8] - BROADCAST(xmm0,0) - BROADCAST(xmm1,0) - BROADCAST(xmm2,0) - mulps xmm0,xmm4 - mulps xmm1,xmm5 - mulps xmm2,xmm6 - addps xmm0,xmm1 - addps xmm0,xmm2 - addps xmm0,xmm7 - movss [edx],xmm0 - movhps [edx+4],xmm0 - add eax,12 - add edx,12 - add esi,12 - dec edi - jmp _lp - _aligned: - - mov esi,1 - - mov ecx,edi - and edi,3 - and ecx,~3 - jz _lp - - lea ecx,[ecx+ecx*2] - shl ecx,2 - add eax,ecx - add edx,ecx - neg ecx - - cmp dword ptr [ebx+12],0 - jne _xlatelp - cmp dword ptr [ebx+28],0 - jne _xlatelp - cmp dword ptr [ebx+44],0 - jne _xlatelp - jmp _noxlatelp - - align 16 - - _noxlatelp: - prefetchnta [eax+ecx+48] - prefetchnta [eax+ecx+48+32] - - movss xmm0,[eax+ecx] - BROADCAST(xmm0,0) - movss xmm1,[eax+ecx+4] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+8] - BROADCAST(xmm2,0) - mulps xmm0,xmm4 - mulps xmm1,xmm5 - mulps xmm2,xmm6 - addps xmm0,xmm1 - addps xmm0,xmm2 - - movss xmm1,[eax+ecx+12] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+16] - BROADCAST(xmm2,0) - movss xmm3,[eax+ecx+20] - BROADCAST(xmm3,0) - mulps xmm1,xmm4 - mulps xmm2,xmm5 - mulps xmm3,xmm6 - addps xmm1,xmm2 - addps xmm3,xmm1 - - movss xmm0,xmm3 - shufps xmm0,xmm0,SHUFFLE(0,3,2,1) - - movaps [edx+ecx],xmm0 - - prefetcht0 [edx+ecx+48] - prefetcht0 [edx+ecx+48+32] - - movss xmm0,[eax+ecx+24] - BROADCAST(xmm0,0) - movss xmm1,[eax+ecx+24+4] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+24+8] - BROADCAST(xmm2,0) - mulps xmm0,xmm4 - mulps xmm1,xmm5 - mulps xmm2,xmm6 - addps xmm0,xmm1 - addps xmm0,xmm2 - - shufps xmm3,xmm0,SHUFFLE(2,1,3,2) - movaps [edx+ecx+16],xmm3 - - movss xmm1,[eax+ecx+24+12] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+24+16] - BROADCAST(xmm2,0) - movss xmm3,[eax+ecx+24+20] - BROADCAST(xmm3,0) - mulps xmm1,xmm4 - mulps xmm2,xmm5 - mulps xmm3,xmm6 - addps xmm1,xmm2 - addps xmm1,xmm3 - - shufps xmm0,xmm0,SHUFFLE(2,1,0,3) - movss xmm1,xmm0 - movaps [edx+ecx+32],xmm1 - - add ecx,48 - js _noxlatelp - - jmp _lp - - align 16 - - _xlatelp: - prefetchnta [eax+ecx+48] - prefetchnta [eax+ecx+48+32] - - movss xmm0,[eax+ecx] - BROADCAST(xmm0,0) - movss xmm1,[eax+ecx+4] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+8] - BROADCAST(xmm2,0) - mulps xmm0,xmm4 - mulps xmm1,xmm5 - mulps xmm2,xmm6 - addps xmm0,xmm1 - addps xmm0,xmm2 - addps xmm0,xmm7 - - movss xmm1,[eax+ecx+12] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+16] - BROADCAST(xmm2,0) - movss xmm3,[eax+ecx+20] - BROADCAST(xmm3,0) - mulps xmm1,xmm4 - mulps xmm2,xmm5 - mulps xmm3,xmm6 - addps xmm1,xmm2 - addps xmm3,xmm1 - addps xmm3,xmm7 - - movss xmm0,xmm3 - shufps xmm0,xmm0,SHUFFLE(0,3,2,1) - movaps [edx+ecx],xmm0 - - prefetcht0 [edx+ecx+48] - prefetcht0 [edx+ecx+48+32] - - movss xmm0,[eax+ecx+24] - BROADCAST(xmm0,0) - movss xmm1,[eax+ecx+24+4] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+24+8] - BROADCAST(xmm2,0) - mulps xmm0,xmm4 - mulps xmm1,xmm5 - mulps xmm2,xmm6 - addps xmm0,xmm1 - addps xmm0,xmm2 - addps xmm0,xmm7 - - shufps xmm3,xmm0,SHUFFLE(2,1,3,2) - movaps [edx+ecx+16],xmm3 - - movss xmm1,[eax+ecx+24+12] - BROADCAST(xmm1,0) - movss xmm2,[eax+ecx+24+16] - BROADCAST(xmm2,0) - movss xmm3,[eax+ecx+24+20] - BROADCAST(xmm3,0) - mulps xmm1,xmm4 - mulps xmm2,xmm5 - mulps xmm3,xmm6 - addps xmm1,xmm2 - addps xmm1,xmm3 - addps xmm1,xmm7 - - shufps xmm0,xmm0,SHUFFLE(2,1,0,3) - movss xmm1,xmm0 - - movaps [edx+ecx+32],xmm1 - - add ecx,48 - js _xlatelp - - jmp _lp - _ulos: - } - - } - else -#endif - { - mtx.mulVector3Array(src, dst, count); - } -} - -void VectorProcessorClass::Transform(Vector4* dst,const Vector3 *src, const Matrix4x4& matrix, const int count) -{ - if (count<=0) return; - - int i; - - for (i=0; imax)?max:src[i].X; - - dst[i].Y=(src[i].Ymax)?max:src[i].Y; - - dst[i].Z=(src[i].Zmax)?max:src[i].Z; - - dst[i].W=(src[i].Wmax)?max:src[i].W; - } -} - -void VectorProcessorClass::Clear(Vector3*dst, const int count) -{ - if (count<=0) return; - memset(dst,0,sizeof(Vector3)*count); -} - - -void VectorProcessorClass::Normalize(Vector3 *dst, const int count) -{ - if (count<=0) return; - int i; - - for (i=0; imin?src[i]:min); -} - -void VectorProcessorClass::Power(float *dst, float *src, const float pow, const int count) -{ - for (int i=0; i. -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwmath * - * * - * $Archive:: /Commando/Code/WWMath/vp.h $* - * * - * Org Author:: Hector Yee * - * * - * Author : Kenny Mitchell * - * * - * $Modtime:: 06/26/02 4:04p $* - * * - * $Revision:: 13 $* - * * - * 06/26/02 KM Matrix name change to avoid MAX conflicts * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Transform - transforms a vector array given Matrix3D * - * Copy - Copies data from source to destination * - * CopyIndexed-copies dst[]=src[index[]] * - * Clear - clears array to zero * - * Normalize - normalize the array * - * MinMax - Finds the min and max of the array * - * * - *----------------------------------------------------------------------------------------------* - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTORPROCESSOR_H -#define VECTORPROCESSOR_H - -class Vector2; -class Vector3; -class Vector4; -class Matrix3D; -class Matrix4x4; - -class VectorProcessorClass -{ -public: - static void Transform(Vector3* dst,const Vector3 *src, const Matrix3D& matrix, const int count); - static void Transform(Vector4* dst,const Vector3 *src, const Matrix4x4& matrix, const int count); - static void Copy(unsigned *dst,const unsigned *src, const int count); - static void Copy(Vector2 *dst,const Vector2 *src, const int count); - static void Copy(Vector3 *dst,const Vector3 *src, const int count); - static void Copy(Vector4 *dst,const Vector4 *src, const int count); - static void Copy(Vector4 *dst,const Vector3 *src, const float * srca, const int count); - static void Copy(Vector4 *dst,const Vector3 *src, const float srca, const int count); - static void Copy(Vector4 *dst,const Vector3 &src, const float * srca, const int count); - static void CopyIndexed(unsigned *dst,const unsigned *src, const unsigned int *index, const int count); - static void CopyIndexed(Vector2 *dst,const Vector2 *src, const unsigned int *index, const int count); - static void CopyIndexed(Vector3 *dst,const Vector3 *src, const unsigned int *index, const int count); - static void CopyIndexed(Vector4 *dst,const Vector4 *src, const unsigned int *index, const int count); - static void CopyIndexed(unsigned char* dst, const unsigned char* src, const unsigned int *index, int count); - static void CopyIndexed(float* dst, float* src, const unsigned int *index, int count); - static void Clamp(Vector4 *dst,const Vector4 *src, const float min, const float max, const int count); - static void Clear (Vector3 *dst, const int count); - static void Normalize(Vector3 *dst, const int count); - static void MinMax(Vector3 *src, Vector3 &min, Vector3 &max, const int count); - - static void MulAdd(float * dest,float multiplier,float add,int count); - - static void Prefetch(void* address); - - static void DotProduct(float *dst, const Vector3 &a, const Vector3 *b,const int count); - static void ClampMin(float *dst, float *src, const float min, const int count); - static void Power(float *dst, float *src, const float pow, const int count); -}; - -#endif // VECTORPROCESSOR_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmath.cpp b/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmath.cpp deleted file mode 100644 index e7e5c4fba0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmath.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/wwmath.cpp $* - * * - * Author:: Eric_c * - * * - * $Modtime:: 5/10/01 10:52p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "wwmath.h" -#include "wwhack.h" -#include "lookuptable.h" -#include -#include "wwdebug.h" -#include "wwprofile.h" - -// TODO: convert to use loouptablemanager... -float _FastAcosTable[ARC_TABLE_SIZE]; -float _FastAsinTable[ARC_TABLE_SIZE]; -float _FastSinTable[SIN_TABLE_SIZE]; -float _FastInvSinTable[SIN_TABLE_SIZE]; - -void WWMath::Init(void) -{ - LookupTableMgrClass::Init(); - - int a=0; - for (;a0) { - _FastInvSinTable[a]=1.0f/_FastSinTable[a]; - } else { - _FastInvSinTable[a]=WWMATH_FLOAT_MAX; - } - } -} - -void WWMath::Shutdown(void) -{ - LookupTableMgrClass::Shutdown(); -} - -float WWMath::Random_Float(void) -{ - return ((float)(rand() & 0xFFF)) / (float)(0xFFF); -} - - -/* -** Force link some modules from this library. -*/ -void Do_Force_Links(void) -{ - FORCE_LINK(curve); - FORCE_LINK(hermitespline); - FORCE_LINK(catmullromspline); - FORCE_LINK(cardinalspline); - FORCE_LINK(tcbspline); -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmath.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmath.h deleted file mode 100644 index 0a151a65dc..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmath.h +++ /dev/null @@ -1,658 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/wwmath.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/26/01 2:22p $* - * * - * $Revision:: 64 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WWMATH_H -#define WWMATH_H - -#include "always.h" -#include -#include -#include -#include - -/* -** Some global constants. -*/ -#define WWMATH_EPSILON 0.0001f -#define WWMATH_EPSILON2 WWMATH_EPSILON * WWMATH_EPSILON -#define WWMATH_PI 3.141592654f -#define WWMATH_FLOAT_MAX (FLT_MAX) -#define WWMATH_FLOAT_MIN (FLT_MIN) -#define WWMATH_SQRT2 1.414213562f -#define WWMATH_SQRT3 1.732050808f -#define WWMATH_OOSQRT2 0.707106781f -#define WWMATH_OOSQRT3 0.577350269f - -// (DRM 05/07/01) Temporarily eliminated _fastcall -// on non-Microsoft compatible compilers. Jani -// should be replacing this soon. -#ifndef _MSC_VER -#define __fastcall -#endif // _MSC_VER - -/* -** Macros to convert between degrees and radians -*/ -#ifndef RAD_TO_DEG -#define RAD_TO_DEG(x) (((double)x)*180.0/WWMATH_PI) -#endif - -#ifndef DEG_TO_RAD -#define DEG_TO_RAD(x) (((double)x)*WWMATH_PI/180.0) -#endif - -#ifndef RAD_TO_DEGF -#define RAD_TO_DEGF(x) (((float)x)*180.0f/WWMATH_PI) -#endif - -#ifndef DEG_TO_RADF -#define DEG_TO_RADF(x) (((float)x)*WWMATH_PI/180.0f) -#endif - - -const int ARC_TABLE_SIZE=1024; -const int SIN_TABLE_SIZE=1024; -extern float _FastAcosTable[ARC_TABLE_SIZE]; -extern float _FastAsinTable[ARC_TABLE_SIZE]; -extern float _FastSinTable[SIN_TABLE_SIZE]; -extern float _FastInvSinTable[SIN_TABLE_SIZE]; - -/* -** Some simple math functions which work on the built-in types. -** Include the various other header files in the WWMATH library -** in order to get matrices, quaternions, etc. -*/ -class WWMath -{ -public: - -// Initialization and Shutdown. Other math sub-systems which require initialization and -// shutdown processing will be handled in these functions -static void Init(void); -static void Shutdown(void); - -// These are meant to be a collection of small math utility functions to be optimized at some point. -static WWINLINE float Fabs(float val) -{ - int value=*(int*)&val; - value&=0x7fffffff; - return *(float*)&value; -} - -static WWINLINE int Float_To_Int_Chop(const float& f); -static WWINLINE int Float_To_Int_Floor(const float& f); - -#if defined(_MSC_VER) && defined(_M_IX86) -static WWINLINE float Cos(float val); -static WWINLINE float Sin(float val); -static WWINLINE float Sqrt(float val); -static float __fastcall Inv_Sqrt(float a); // Some 30% faster inverse square root than regular C++ compiled, from Intel's math library -static WWINLINE long Float_To_Long(float f); -#else -static float Cos(float val); -static float Sin(float val); -static float Sqrt(float val); -static float Inv_Sqrt(float a); -static long Float_To_Long(float f); -#endif - - -static WWINLINE float Fast_Sin(float val); -static WWINLINE float Fast_Inv_Sin(float val); -static WWINLINE float Fast_Cos(float val); -static WWINLINE float Fast_Inv_Cos(float val); - -static WWINLINE float Fast_Acos(float val); -static WWINLINE float Acos(float val); -static WWINLINE float Fast_Asin(float val); -static WWINLINE float Asin(float val); - - -static float Atan(float x) { return static_cast(atan(x)); } -static float Atan2(float y,float x) { return static_cast(atan2(y,x)); } -static float Sign(float val); -static float Ceil(float val) { return ceilf(val); } -static float Floor(float val) { return floorf(val); } -static bool Fast_Is_Float_Positive(const float & val); -static bool Is_Power_Of_2(const unsigned int val); - -static float Random_Float(void); -static float Random_Float(float min,float max); -static float Clamp(float val, float min = 0.0f, float max = 1.0f); -static double Clamp(double val, double min = 0.0f, double max = 1.0f); -static int Clamp_Int(int val, int min_val, int max_val); -static float Wrap(float val, float min = 0.0f, float max = 1.0f); -static double Wrap(double val, double min = 0.0f, double max = 1.0f); -static float Min(float a, float b); -static float Max(float a, float b); - -static int Float_As_Int(const float f) { return *((int*)&f); } - -static float Lerp(float a, float b, float lerp ); -static double Lerp(double a, double b, float lerp ); - -static long Float_To_Long(double f); - -static unsigned char Unit_Float_To_Byte(float f) { return (unsigned char)(f*255.0f); } -static float Byte_To_Unit_Float(unsigned char byte) { return ((float)byte) / 255.0f; } - -static bool Is_Valid_Float(float x); -static bool Is_Valid_Double(double x); - -}; - -WWINLINE float WWMath::Sign(float val) -{ - if (val > 0.0f) { - return +1.0f; - } - if (val < 0.0f) { - return -1.0f; - } - return 0.0f; -} - -WWINLINE bool WWMath::Fast_Is_Float_Positive(const float & val) -{ - return !((*(int *)(&val)) & 0x80000000); -} - -WWINLINE bool WWMath::Is_Power_Of_2(const unsigned int val) -{ - return !((val)&val-1); -} - -WWINLINE float WWMath::Random_Float(float min,float max) -{ - return Random_Float() * (max-min) + min; -} - -WWINLINE float WWMath::Clamp(float val, float min /*= 0.0f*/, float max /*= 1.0f*/) -{ - if(val < min) return min; - if(val > max) return max; - return val; -} - -WWINLINE double WWMath::Clamp(double val, double min /*= 0.0f*/, double max /*= 1.0f*/) -{ - if(val < min) return min; - if(val > max) return max; - return val; -} - -WWINLINE int WWMath::Clamp_Int(int val, int min_val, int max_val) -{ - if(val < min_val) return min_val; - if(val > max_val) return max_val; - return val; -} - -WWINLINE float WWMath::Wrap(float val, float min /*= 0.0f*/, float max /*= 1.0f*/) -{ - // Implemented as an if rather than a while, to long loops - if ( val >= max ) val -= (max-min); - if ( val < min ) val += (max-min); - - if ( val < min ) { - val = min; - } - if ( val > max ) { - val = max; - } - return val; -} - -WWINLINE double WWMath::Wrap(double val, double min /*= 0.0f*/, double max /*= 1.0f*/) -{ - // Implemented as an if rather than a while, to long loops - if ( val >= max ) val -= (max-min); - if ( val < min ) val += (max-min); - if ( val < min ) { - val = min; - } - if ( val > max ) { - val = max; - } - return val; -} - -WWINLINE float WWMath::Min(float a, float b) -{ - if (ab) return a; - return b; -} - -WWINLINE float WWMath::Lerp(float a, float b, float lerp ) -{ - return (a + (b - a)*lerp); -} - -WWINLINE double WWMath::Lerp(double a, double b, float lerp ) -{ - return (a + (b - a)*lerp); -} - - -WWINLINE bool WWMath::Is_Valid_Float(float x) -{ - unsigned long * plong = (unsigned long *)(&x); - unsigned long exponent = ((*plong) & 0x7F800000) >> (32-9); - - // if exponent is 0xFF, this is a NAN - if (exponent == 0xFF) { - return false; - } - return true; -} - -WWINLINE bool WWMath::Is_Valid_Double(double x) -{ - unsigned long * plong = (unsigned long *)(&x) + 1; - unsigned long exponent = ((*plong) & 0x7FF00000) >> (32-12); - - // if exponent is 0x7FF, this is a NAN - if (exponent == 0x7FF) { - return false; - } - return true; -} - -// ---------------------------------------------------------------------------- -// Float to long -// ---------------------------------------------------------------------------- - -#if defined(_MSC_VER) && defined(_M_IX86) -WWINLINE long WWMath::Float_To_Long(float f) -{ - long i; - - __asm { - fld [f] - fistp [i] - } - - return i; -} -#else -WWINLINE long WWMath::Float_To_Long(float f) -{ - return (long) f; -} -#endif - -WWINLINE long WWMath::Float_To_Long(double f) -{ -#if defined(_MSC_VER) && defined(_M_IX86) - long retval; - __asm fld qword ptr [f] - __asm fistp dword ptr [retval] - return retval; -#else - return (long) f; -#endif -} - -// ---------------------------------------------------------------------------- -// Cos -// ---------------------------------------------------------------------------- - -#if defined(_MSC_VER) && defined(_M_IX86) -WWINLINE float WWMath::Cos(float val) -{ - float retval; - __asm { - fld [val] - fcos - fstp [retval] - } - return retval; -} -#else -WWINLINE float WWMath::Cos(float val) -{ - return cosf(val); -} -#endif - -// ---------------------------------------------------------------------------- -// Sin -// ---------------------------------------------------------------------------- - -#if defined(_MSC_VER) && defined(_M_IX86) -WWINLINE float WWMath::Sin(float val) -{ - float retval; - __asm { - fld [val] - fsin - fstp [retval] - } - return retval; -} -#else -WWINLINE float WWMath::Sin(float val) -{ - return sinf(val); -} -#endif - -// ---------------------------------------------------------------------------- -// Fast, table based sin -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Fast_Sin(float val) -{ - val*=float(SIN_TABLE_SIZE) / (2.0f * WWMATH_PI); - - int idx0=Float_To_Int_Floor(val); - int idx1=idx0+1; - float frac=val-(float)idx0; - - idx0 = ((unsigned)idx0) & (SIN_TABLE_SIZE-1); - idx1 = ((unsigned)idx1) & (SIN_TABLE_SIZE-1); - - return (1.0f - frac) * _FastSinTable[idx0] + frac * _FastSinTable[idx1]; -} - -// ---------------------------------------------------------------------------- -// Fast, table based 1.0f/sin -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Fast_Inv_Sin(float val) -{ -#if 0 // TODO: more testing, not reliable! - float index = val * float(SIN_TABLE_SIZE) / (2.0f * WWMATH_PI); - - int idx0=Float_To_Int_Floor(index); - int idx1=idx0+1; - float frac=val-(float)idx0; - - idx0 = ((unsigned)idx0) & (SIN_TABLE_SIZE-1); - idx1 = ((unsigned)idx1) & (SIN_TABLE_SIZE-1); - - // The table becomes inaccurate near 0 and 2pi so fall back to doing a divide. - const int BUFFER = 16; - if ((idx0 <= BUFFER) || (idx0 >= SIN_TABLE_SIZE-BUFFER-1)) { - return 1.0f / WWMath::Fast_Sin(val); - } else { - return (1.0f - frac) * _FastInvSinTable[idx0] + frac * _FastInvSinTable[idx1]; - } -#else - return 1.0f / WWMath::Fast_Sin(val); -#endif -} - - -// ---------------------------------------------------------------------------- -// Fast, table based cos -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Fast_Cos(float val) -{ - val+=(WWMATH_PI * 0.5f); - val*=float(SIN_TABLE_SIZE) / (2.0f * WWMATH_PI); - - int idx0=Float_To_Int_Floor(val); - int idx1=idx0+1; - float frac=val-(float)idx0; - - idx0 = ((unsigned)idx0) & (SIN_TABLE_SIZE-1); - idx1 = ((unsigned)idx1) & (SIN_TABLE_SIZE-1); - - return (1.0f - frac) * _FastSinTable[idx0] + frac * _FastSinTable[idx1]; -} - -// ---------------------------------------------------------------------------- -// Fast, table based 1.0f/cos -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Fast_Inv_Cos(float val) -{ -#if 0 // TODO: more testing, not reliable! - float index = val + (WWMATH_PI * 0.5f); - index *= float(SIN_TABLE_SIZE) / (2.0f * WWMATH_PI); - - int idx0=Float_To_Int_Chop(index); - int idx1=idx0+1; - float frac=val-(float)idx0; - - idx0 = ((unsigned)idx0) & (SIN_TABLE_SIZE-1); - idx1 = ((unsigned)idx1) & (SIN_TABLE_SIZE-1); - - // The table becomes inaccurate near 0 and 2pi so fall back to doing a divide. - if ((idx0 <= 2) || (idx0 >= SIN_TABLE_SIZE-3)) { - return 1.0f / WWMath::Fast_Cos(val); - } else { - return (1.0f - frac) * _FastInvSinTable[idx0] + frac * _FastInvSinTable[idx1]; - } -#else - return 1.0f / WWMath::Fast_Cos(val); -#endif -} - -// ---------------------------------------------------------------------------- -// Fast, table based arc cos -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Fast_Acos(float val) -{ - // Near -1 and +1, the table becomes too inaccurate - if (WWMath::Fabs(val) > 0.975f) { - return WWMath::Acos(val); - } - - val*=float(ARC_TABLE_SIZE/2); - - int idx0=Float_To_Int_Floor(val); - int idx1=idx0+1; - float frac=val-(float)idx0; - - idx0+=ARC_TABLE_SIZE/2; - idx1+=ARC_TABLE_SIZE/2; - - // we dont even get close to the edge of the table... - assert((idx0 >= 0) && (idx0 < ARC_TABLE_SIZE)); - assert((idx1 >= 0) && (idx1 < ARC_TABLE_SIZE)); - - // compute and return the interpolated value - return (1.0f - frac) * _FastAcosTable[idx0] + frac * _FastAcosTable[idx1]; -} - -// ---------------------------------------------------------------------------- -// Arc cos -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Acos(float val) -{ - return (float)acos(val); -} - -// ---------------------------------------------------------------------------- -// Fast, table based arc sin -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Fast_Asin(float val) -{ - // Near -1 and +1, the table becomes too inaccurate - if (WWMath::Fabs(val) > 0.975f) { - return WWMath::Asin(val); - } - - val*=float(ARC_TABLE_SIZE/2); - - int idx0=Float_To_Int_Floor(val); - int idx1=idx0+1; - float frac=val-(float)idx0; - - idx0+=ARC_TABLE_SIZE/2; - idx1+=ARC_TABLE_SIZE/2; - - // we dont even get close to the edge of the table... - assert((idx0 >= 0) && (idx0 < ARC_TABLE_SIZE)); - assert((idx1 >= 0) && (idx1 < ARC_TABLE_SIZE)); - - // compute and return the interpolated value - return (1.0f - frac) * _FastAsinTable[idx0] + frac * _FastAsinTable[idx1]; -} - -// ---------------------------------------------------------------------------- -// Arc sin -// ---------------------------------------------------------------------------- - -WWINLINE float WWMath::Asin(float val) -{ - return (float)asin(val); -} - -// ---------------------------------------------------------------------------- -// Sqrt -// ---------------------------------------------------------------------------- - -#if defined(_MSC_VER) && defined(_M_IX86) -WWINLINE float WWMath::Sqrt(float val) -{ - float retval; - __asm { - fld [val] - fsqrt - fstp [retval] - } - return retval; -} -#else -WWINLINE float WWMath::Sqrt(float val) -{ - return (float)sqrt(val); -} -#endif - -WWINLINE int WWMath::Float_To_Int_Chop(const float& f) -{ - int a = *reinterpret_cast(&f); // take bit pattern of float into a register - int sign = (a>>31); // sign = 0xFFFFFFFF if original value is negative, 0 if positive - int mantissa = (a&((1<<23)-1))|(1<<23); // extract mantissa and add the hidden bit - int exponent = ((a&0x7fffffff)>>23)-127; // extract the exponent - int r = ((unsigned int)(mantissa)<<8)>>(31-exponent); // ((1<>24 -- (we know that mantissa > (1<<24)) - return ((r ^ (sign)) - sign ) &~ (exponent>>31); // add original sign. If exponent was negative, make return value 0. -} - -WWINLINE int WWMath::Float_To_Int_Floor (const float& f) -{ - int a = *reinterpret_cast(&f); // take bit pattern of float into a register - int sign = (a>>31); // sign = 0xFFFFFFFF if original value is negative, 0 if positive - a&=0x7fffffff; // we don't need the sign any more - - int exponent = (a>>23)-127; // extract the exponent - int expsign = ~(exponent>>31); // 0xFFFFFFFF if exponent is positive, 0 otherwise - int imask = ( (1<<(31-(exponent))))-1; // mask for true integer values - int mantissa = (a&((1<<23)-1)); // extract mantissa (without the hidden bit) - int r = ((unsigned int)(mantissa|(1<<23))<<8)>>(31-exponent); // ((1<>24 -- (we know that mantissa > (1<<24)) - - r = ((r & expsign) ^ (sign)) + ((!((mantissa<<8)&imask)&(expsign^((a-1)>>31)))&sign); // if (fabs(value)<1.0) value = 0; copy sign; if (value < 0 && value==(int)(value)) value++; - return r; -} - -// ---------------------------------------------------------------------------- -// Inverse square root -// ---------------------------------------------------------------------------- - -#if defined(_MSC_VER) && defined(_M_IX86) -WWINLINE __declspec(naked) float __fastcall WWMath::Inv_Sqrt(float a) -{ - __asm { - mov eax, 0be6eb508h - mov DWORD PTR [esp-12],03fc00000h ; 1.5 on the stack - sub eax, DWORD PTR [esp+4]; a - sub DWORD PTR [esp+4], 800000h ; a/2 a=Y0 - shr eax, 1 ; firs approx in eax=R0 - mov DWORD PTR [esp-8], eax - - fld DWORD PTR [esp-8] ;r - fmul st, st ;r*r - fld DWORD PTR [esp-8] ;r - fxch st(1) - fmul DWORD PTR [esp+4];a ;r*r*y0 - fld DWORD PTR [esp-12];load 1.5 - fld st(0) - fsub st,st(2) ;r1 = 1.5 - y1 - ;x1 = st(3) - ;y1 = st(2) - ;1.5 = st(1) - ;r1 = st(0) - - fld st(1) - fxch st(1) - fmul st(3),st ; y2=y1*r1*... - fmul st(3),st ; y2=y1*r1*r1 - fmulp st(4),st ; x2=x1*r1 - fsub st,st(2) ; r2=1.5-y2 - ;x2=st(3) - ;y2=st(2) - ;1.5=st(1) - ;r2 = st(0) - - fmul st(2),st ;y3=y2*r2*... - fmul st(3),st ;x3=x2*r2 - fmulp st(2),st ;y3=y2*r2*r2 - fxch st(1) - fsubp st(1),st ;r3= 1.5 - y3 - ;x3 = st(1) - ;r3 = st(0) - fmulp st(1), st - ret 4 - } -} -#else -WWINLINE float WWMath::Inv_Sqrt(float val) -{ - return 1.0f / (float)sqrt(val); -} -#endif - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmathids.h b/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmathids.h deleted file mode 100644 index 8217d09fa5..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWMath/wwmathids.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/wwmathids.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 5/04/01 8:42p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef WWMATHIDS_H -#define WWMATHIDS_H - -#include "saveloadids.h" - -/* -** Persist Factory ID's for WWMATH -*/ -enum -{ - WWMATH_CHUNKID_LINEARCURVE1D = CHUNKID_WWMATH_BEGIN, - WWMATH_CHUNKID_HERMITESPLINE1D, - WWMATH_CHUNKID_CATMULLROMSPLINE1D, - WWMATH_CHUNKID_CARDINALSPLINE1D, - WWMATH_CHUNKID_TCBSPLINE1D, - - WWMATH_CHUNKID_LINEARCURVE3D = CHUNKID_WWMATH_BEGIN + 0x100, - WWMATH_CHUNKID_HERMITESPLINE3D, - WWMATH_CHUNKID_CATMULLROMSPLINE3D, - WWMATH_CHUNKID_CARDINALSPLINE3D, - WWMATH_CHUNKID_TCBSPLINE3D, - WWMATH_CHUNKID_VEHICLECURVE -}; - - - -#endif //WWMATHIDS_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt deleted file mode 100644 index b0c9c99e40..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ -# Set source files -set(WWSAVELOAD_SRC - definition.cpp - definition.h - definitionclassids.h - definitionfactory.cpp - definitionfactory.h - definitionfactorymgr.cpp - definitionfactorymgr.h - definitionmgr.cpp - definitionmgr.h - editable.h - parameter.cpp - parameter.h - parameterlist.h - parametertypes.h - persist.h - persistfactory.cpp - persistfactory.h - pointerremap.cpp - pointerremap.h - postloadable.h - saveload.cpp - saveload.h - saveloadids.h - saveloadstatus.cpp - saveloadstatus.h - saveloadstatus.h - saveloadsubsystem.cpp - saveloadsubsystem.h - simpledefinitionfactory.h - simpleparameter.h - twiddler.cpp - twiddler.h - wwsaveload.cpp - wwsaveload.h -) - -# Targets to build. -add_library(g_wwsaveload STATIC) -set_target_properties(g_wwsaveload PROPERTIES OUTPUT_NAME wwsaveload) - -target_sources(g_wwsaveload PRIVATE ${WWSAVELOAD_SRC}) - -target_link_libraries(g_wwsaveload PRIVATE - g_wwcommon -) diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp deleted file mode 100644 index 09ab287fbd..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definition.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/24/01 4:35p $* - * * - * $Revision:: 10 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "definition.h" -#include "chunkio.h" - -////////////////////////////////////////////////////////////////////////////////// -// Constants -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_VARIABLES = 0x00000100, -}; - -enum -{ - VARID_INSTANCEID = 0x01, - XXX_VARID_PARENTID, - VARID_NAME, -}; - - -///////////////////////////////////////////////////////// -// -// Save -// -///////////////////////////////////////////////////////// -bool -DefinitionClass::Save (ChunkSaveClass &csave) -{ - bool retval = true; - - csave.Begin_Chunk (CHUNKID_VARIABLES); - retval &= Save_Variables (csave); - csave.End_Chunk (); - - return retval; -} - - -///////////////////////////////////////////////////////// -// -// Load -// -///////////////////////////////////////////////////////// -bool -DefinitionClass::Load (ChunkLoadClass &cload) -{ - bool retval = true; - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_VARIABLES: - Load_Variables (cload); - break; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionClass::Save_Variables (ChunkSaveClass &csave) -{ - bool retval = true; - - WRITE_MICRO_CHUNK (csave, VARID_INSTANCEID, m_ID); - WRITE_MICRO_CHUNK_WWSTRING (csave, VARID_NAME, m_Name); - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionClass::Load_Variables (ChunkLoadClass &cload) -{ - bool retval = true; - - // - // Loop through all the microchunks that define the variables - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_INSTANCEID, m_ID) - READ_MICRO_CHUNK_WWSTRING (cload, VARID_NAME, m_Name) - } - - cload.Close_Micro_Chunk (); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Set_ID -// -////////////////////////////////////////////////////////////////////////////////// -void -DefinitionClass::Set_ID (uint32 id) -{ - m_ID = id; - - // - // If we are registered with the definition manager, then we need to - // re-link ourselves back into the list - // - if (m_DefinitionMgrLink != -1) { - DefinitionMgrClass::Unregister_Definition (this); - DefinitionMgrClass::Register_Definition (this); - } - - return ; -} - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.h deleted file mode 100644 index e73b8ae986..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definition.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definition.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/24/01 4:57p $* - * * - * $Revision:: 20 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __DEFINITION_H -#define __DEFINITION_H - -#include "always.h" -// SKB Remove because of G conflicts with CLASSID_?? -#include "definitionclassids.h" -#include "definitionmgr.h" -#include "editable.h" -#include "wwstring.h" - -// Forward declarations -class ChunkSaveClass; -class ChunkLoadClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// DefinitionClass -// -////////////////////////////////////////////////////////////////////////////////// -class DefinitionClass : public PersistClass, public EditableClass -{ -public: - - ///////////////////////////////////////////////////////////////////// - // Editable interface requirements - ///////////////////////////////////////////////////////////////////// - DECLARE_EDITABLE(DefinitionClass, EditableClass); - - ///////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ///////////////////////////////////////////////////////////////////// - DefinitionClass (void); - virtual ~DefinitionClass (void); - - ///////////////////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////////////////// - - // Type identification - virtual uint32 Get_Class_ID (void) const = 0; - virtual uint32 Get_ID (void) const; - virtual void Set_ID (uint32 id); - virtual PersistClass * Create (void) const = 0; - - // Display name methods - virtual const char * Get_Name (void) const; - virtual void Set_Name (const char *new_name); - - // Validation methods - virtual bool Is_Valid_Config (StringClass &message); - - // From PersistClass - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - - // User data support - uint32 Get_User_Data (void) const { return m_GenericUserData; } - void Set_User_Data (uint32 data) { m_GenericUserData = data; } - - // Save support - bool Is_Save_Enabled (void) const { return m_SaveEnabled; } - void Enable_Save (bool onoff) { m_SaveEnabled = onoff; } - -protected: - - ///////////////////////////////////////////////////////////////////// - // Protected member data - ///////////////////////////////////////////////////////////////////// - int m_DefinitionMgrLink; - -private: - - ///////////////////////////////////////////////////////////////////// - // Private methods - ///////////////////////////////////////////////////////////////////// - bool Save_Variables (ChunkSaveClass &csave); - bool Load_Variables (ChunkLoadClass &cload); - - ///////////////////////////////////////////////////////////////////// - // Private member data - ///////////////////////////////////////////////////////////////////// - StringClass m_Name; - uint32 m_ID; - uint32 m_GenericUserData; - bool m_SaveEnabled; - - ///////////////////////////////////////////////////////////////////// - // Friends - ///////////////////////////////////////////////////////////////////// - friend class DefinitionMgrClass; -}; - - -///////////////////////////////////////////////////////////////////// -// DefinitionClass -///////////////////////////////////////////////////////////////////// -inline -DefinitionClass::DefinitionClass (void) - : m_ID (0), - m_SaveEnabled (true), - m_DefinitionMgrLink (-1) -{ - return ; -} - -///////////////////////////////////////////////////////////////////// -// DefinitionClass -///////////////////////////////////////////////////////////////////// -inline -DefinitionClass::~DefinitionClass (void) -{ - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// Get_Name -////////////////////////////////////////////////////////////////////////////////// -inline const char * -DefinitionClass::Get_Name (void) const -{ - return m_Name; -} - -////////////////////////////////////////////////////////////////////////////////// -// Set_Name -////////////////////////////////////////////////////////////////////////////////// -inline void -DefinitionClass::Set_Name (const char *new_name) -{ - m_Name = new_name; - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// Get_ID -////////////////////////////////////////////////////////////////////////////////// -inline uint32 -DefinitionClass::Get_ID (void) const -{ - return m_ID; -} - -////////////////////////////////////////////////////////////////////////////////// -// Is_Valid_Config -////////////////////////////////////////////////////////////////////////////////// -inline bool -DefinitionClass::Is_Valid_Config (StringClass &message) -{ - return true; -} - - -#endif //__DEFINITION_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h deleted file mode 100644 index 973f787ea9..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionclassids.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definitionclassids.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/03/00 5:44p $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __DEFINITION_CLASS_ID_H -#define __DEFINITION_CLASS_ID_H - -#include "always.h" -#include "bittype.h" - -////////////////////////////////////////////////////////////////////////////////// -// -// Constants -// -////////////////////////////////////////////////////////////////////////////////// -const int DEF_CLASSID_START = 0x00001000; -const int DEF_CLASSID_RANGE = 0x00001000; -#define NEXT_SUPER_CLASSID(n) DEF_CLASSID_START + (n * DEF_CLASSID_RANGE) - - -////////////////////////////////////////////////////////////////////////////////// -// -// DefinitionClassID -// -// Note: The following enum should contain ALL of the class ids for -// definitions in the entire system (to guarantee they are unique). Each -// super-class is allocated a range of class ids. Use the -// SuperClassID_From_ClassID function to determine which super class -// a particular class id belongs to. -// -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CLASSID_TERRAIN = NEXT_SUPER_CLASSID(0), - CLASSID_TILE = NEXT_SUPER_CLASSID(1), - CLASSID_GAME_OBJECTS = NEXT_SUPER_CLASSID(2), - CLASSID_LIGHT = NEXT_SUPER_CLASSID(3), - CLASSID_SOUND = NEXT_SUPER_CLASSID(4), - CLASSID_WAYPATH = NEXT_SUPER_CLASSID(5), - CLASSID_ZONE = NEXT_SUPER_CLASSID(6), - CLASSID_TRANSITION = NEXT_SUPER_CLASSID(7), - CLASSID_PHYSICS = NEXT_SUPER_CLASSID(8), - CLASSID_EDITOR_OBJECTS = NEXT_SUPER_CLASSID(9), - CLASSID_MUNITIONS = NEXT_SUPER_CLASSID(10), - CLASSID_DUMMY_OBJECTS = NEXT_SUPER_CLASSID(11), - CLASSID_BUILDINGS = NEXT_SUPER_CLASSID(12), - CLASSID_TWIDDLERS = NEXT_SUPER_CLASSID(13), - CLASSID_GLOBAL_SETTINGS = NEXT_SUPER_CLASSID(14), -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// SuperClassID_From_ClassID -// -////////////////////////////////////////////////////////////////////////////////// -inline uint32 -SuperClassID_From_ClassID (uint32 class_id) -{ - // - // Which id-range does it fall under? - // - int delta = class_id - DEF_CLASSID_START; - int num_ranges = delta / DEF_CLASSID_RANGE; - - return DEF_CLASSID_START + (num_ranges * DEF_CLASSID_RANGE); -} - - -#endif //__DEFINITION_CLASS_ID_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp deleted file mode 100644 index 53b477acff..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definitionfactory.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 9/09/99 7:12p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "definitionfactory.h" -#include "definitionfactorymgr.h" - - -///////////////////////////////////////////////////////// -// -// DefinitionFactoryClass -// -///////////////////////////////////////////////////////// -DefinitionFactoryClass::DefinitionFactoryClass (void) - : m_NextFactory (0), - m_PrevFactory (0) -{ - DefinitionFactoryMgrClass::Register_Factory (this); - return ; -} - - -///////////////////////////////////////////////////////// -// -// ~DefinitionFactoryClass -// -///////////////////////////////////////////////////////// -DefinitionFactoryClass::~DefinitionFactoryClass (void) -{ - DefinitionFactoryMgrClass::Unregister_Factory (this); - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h deleted file mode 100644 index 9102a4ace0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactory.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definitionfactory.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 2/22/01 6:18p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __DEFINITION_FACTORY_H -#define __DEFINITION_FACTORY_H - -#include "always.h" -#include "bittype.h" -#include "definitionclassids.h" - -// Forward declarations -class DefinitionClass; - -////////////////////////////////////////////////////////////////////////////////// -// -// DefinitionFactoryClass -// -// Definition factories act as virtual constructors for object definitions. They -// are responsible for creating new definitions for a particular class of objects. -// -////////////////////////////////////////////////////////////////////////////////// -class DefinitionFactoryClass -{ -public: - - ////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////// - DefinitionFactoryClass (void); - virtual ~DefinitionFactoryClass (void); - - ////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////// - virtual DefinitionClass * Create (void) const = 0; - virtual const char * Get_Name (void) const = 0; - virtual uint32 Get_Class_ID (void) const = 0; - virtual bool Is_Displayed (void) const = 0; - -protected: - - ////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////// - DefinitionFactoryClass * m_NextFactory; - DefinitionFactoryClass * m_PrevFactory; - - - ////////////////////////////////////////////////////////////// - // Friends - ////////////////////////////////////////////////////////////// - friend class DefinitionFactoryMgrClass; -}; - - -#endif //__DEFINITION_FACTORY_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp deleted file mode 100644 index 4fd9baa655..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.cpp +++ /dev/null @@ -1,295 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /VSS_Sync/wwsaveload/definitionfactorymgr.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 10/16/00 11:42a $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "definitionfactorymgr.h" -#include "definitionfactory.h" -#include "wwdebug.h" -#include -#ifdef _UNIX -#include "osdep.h" -#endif - -//////////////////////////////////////////////////////////////////////////// -// Static member initialization -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass *DefinitionFactoryMgrClass::_FactoryListHead = 0; - - -//////////////////////////////////////////////////////////////////////////// -// -// Find_Factory -// -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass * -DefinitionFactoryMgrClass::Find_Factory (uint32 class_id) -{ - DefinitionFactoryClass *factory = 0; - - // - // Loop through all the factories and see if we can - // find the one who owns the corresponding class-id. - // - for ( DefinitionFactoryClass *curr_factory = _FactoryListHead; - (factory == 0) && (curr_factory != 0); - curr_factory = curr_factory->m_NextFactory) { - - // - // Is this the factory we were looking for? - // - if (curr_factory->Get_Class_ID () == class_id) { - factory = curr_factory; - } - } - - return factory; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Find_Factory -// -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass * -DefinitionFactoryMgrClass::Find_Factory (const char *name) -{ - DefinitionFactoryClass *factory = 0; - - // - // Loop through all the factories and see if we can - // find the one who owns the corresponding class-id. - // - for ( DefinitionFactoryClass *curr_factory = _FactoryListHead; - (factory == 0) && (curr_factory != 0); - curr_factory = curr_factory->m_NextFactory) { - - // - // Is this the factory we were looking for? - // - if (::stricmp (curr_factory->Get_Name (), name) == 0) { - factory = curr_factory; - } - } - - return factory; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Get_First -// -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass * -DefinitionFactoryMgrClass::Get_First (uint32 superclass_id) -{ - DefinitionFactoryClass *factory = 0; - - // - // Loop through all the factories and see if we can - // find the next one that belongs to the given superclass - // - for ( DefinitionFactoryClass *curr_factory = _FactoryListHead; - (factory == 0) && (curr_factory != 0); - curr_factory = curr_factory->m_NextFactory) { - - // - // Is this the factory we were looking for? - // - if (::SuperClassID_From_ClassID (curr_factory->Get_Class_ID ()) == superclass_id) { - factory = curr_factory; - } - } - - return factory; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Get_Next -// -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass * -DefinitionFactoryMgrClass::Get_Next -( - DefinitionFactoryClass *curr_factory, - uint32 superclass_id -) -{ - DefinitionFactoryClass *factory = 0; - - // - // Loop through all the factories and see if we can - // find the next one that belongs to the given superclass - // - while ((factory == NULL) && ((curr_factory = curr_factory->m_NextFactory) != NULL)) { - - // - // Is this the factory we were looking for? - // - if (::SuperClassID_From_ClassID (curr_factory->Get_Class_ID ()) == superclass_id) { - factory = curr_factory; - } - } - - return factory; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Get_First -// -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass * -DefinitionFactoryMgrClass::Get_First (void) -{ - return _FactoryListHead; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Get_Next -// -//////////////////////////////////////////////////////////////////////////// -DefinitionFactoryClass * -DefinitionFactoryMgrClass::Get_Next (DefinitionFactoryClass *curr_factory) -{ - DefinitionFactoryClass *factory = 0; - - // - // Simply return the next factory in the chain - // - if (curr_factory != NULL) { - factory = curr_factory->m_NextFactory; - } - - return factory; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Register_Factory -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionFactoryMgrClass::Register_Factory (DefinitionFactoryClass *factory) -{ - WWASSERT (factory->m_NextFactory == 0); - WWASSERT (factory->m_PrevFactory == 0); - Link_Factory (factory); - return ; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Unregister_Factory -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionFactoryMgrClass::Unregister_Factory (DefinitionFactoryClass *factory) -{ - WWASSERT (factory != 0); - Unlink_Factory (factory); - return ; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Link_Factory -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionFactoryMgrClass::Link_Factory (DefinitionFactoryClass *factory) -{ - WWASSERT (factory->m_NextFactory == 0); - WWASSERT (factory->m_PrevFactory == 0); - - // Adding this factory in front of the current head of the list - factory->m_NextFactory = _FactoryListHead; - - // If the list wasn't empty, link the next factory back to this factory - if (factory->m_NextFactory != 0) { - factory->m_NextFactory->m_PrevFactory = factory; - } - - // Point the head of the list at this factory now - _FactoryListHead = factory; - return ; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Unlink_Factory -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionFactoryMgrClass::Unlink_Factory (DefinitionFactoryClass *factory) -{ - WWASSERT(factory != 0); - - // Handle the factory's prev pointer: - if (factory->m_PrevFactory == 0) { - - // this factory is the head - WWASSERT (_FactoryListHead == factory); - _FactoryListHead = factory->m_NextFactory; - - } else { - - // link it's prev with it's next - factory->m_PrevFactory->m_NextFactory = factory->m_NextFactory; - - } - - // Handle the factory's next pointer if its not at the end of the list: - if (factory->m_NextFactory != 0) { - - factory->m_NextFactory->m_PrevFactory = factory->m_PrevFactory; - - } - - // factory is now un-linked - factory->m_NextFactory = 0; - factory->m_PrevFactory = 0; - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h deleted file mode 100644 index a9b2bf939e..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionfactorymgr.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definitionfactorymgr.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 7/07/00 11:55a $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __DEFINITION_FACTORY_MGR_H -#define __DEFINITION_FACTORY_MGR_H - -#include "always.h" -#include "bittype.h" -#include "definitionclassids.h" - -class DefinitionFactoryClass; - -////////////////////////////////////////////////////////////////////////////////// -// -// DefinitionFactoryMgrClass -// -////////////////////////////////////////////////////////////////////////////////// -class DefinitionFactoryMgrClass -{ -public: - - ///////////////////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////////////////// - static DefinitionFactoryClass * Find_Factory (uint32 class_id); - static DefinitionFactoryClass * Find_Factory (const char *name); - static void Register_Factory (DefinitionFactoryClass *factory); - static void Unregister_Factory (DefinitionFactoryClass *factory); - - // Class enumeration - static DefinitionFactoryClass * Get_First (uint32 superclass_id); - static DefinitionFactoryClass * Get_Next (DefinitionFactoryClass *current, uint32 superclass_id); - - // Factory enumeration - static DefinitionFactoryClass * Get_First (void); - static DefinitionFactoryClass * Get_Next (DefinitionFactoryClass *current); - -private: - - ///////////////////////////////////////////////////////////////////// - // Private methods - ///////////////////////////////////////////////////////////////////// - static void Link_Factory (DefinitionFactoryClass *factory); - static void Unlink_Factory (DefinitionFactoryClass *factory); - - ///////////////////////////////////////////////////////////////////// - // Static member data - ///////////////////////////////////////////////////////////////////// - static DefinitionFactoryClass * _FactoryListHead; -}; - - -#endif //__DEFINITION_FACTORY_MGR_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp deleted file mode 100644 index 171f9bcdef..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.cpp +++ /dev/null @@ -1,953 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definitionmgr.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 12/10/01 2:37p $* - * * - * $Revision:: 35 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "definitionmgr.h" -#include "definition.h" -#include "definitionfactory.h" -#include "definitionfactorymgr.h" -#include "definitionclassids.h" -#include "chunkio.h" -#include "persistfactory.h" -#include "wwdebug.h" -#include "wwmemlog.h" -#include "twiddler.h" -#include -#include "wwprofile.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Global instance -////////////////////////////////////////////////////////////////////////////////// -DefinitionMgrClass _TheDefinitionMgr; - -////////////////////////////////////////////////////////////////////////////////// -// Constants -////////////////////////////////////////////////////////////////////////////////// -static const int DEFINTION_LIST_GROW_SIZE = 1000; -static const uint32 IDRANGE_PER_CLASS = 10000; - -enum -{ - CHUNKID_VARIABLES = 0x00000100, - CHUNKID_OBJECTS, - CHUNKID_OBJECT -}; - -enum -{ - VARID_NEXTDEFID = 0x01 -}; - -////////////////////////////////////////////////////////////////////////////////// -// Static member initialization -////////////////////////////////////////////////////////////////////////////////// -DefinitionClass ** DefinitionMgrClass::_SortedDefinitionArray = NULL; -int DefinitionMgrClass::_DefinitionCount = 0; -int DefinitionMgrClass::_MaxDefinitionCount = 0; -HashTemplateClass*>* DefinitionMgrClass::DefinitionHash; - -////////////////////////////////////////////////////////////////////////////////// -// -// DefinitionMgrClass -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionMgrClass::DefinitionMgrClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// ~DefinitionMgrClass -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionMgrClass::~DefinitionMgrClass (void) -{ - Free_Definitions (); - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// -// Find_Definition -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionClass * -DefinitionMgrClass::Find_Definition (uint32 id, bool twiddle) -{ - DefinitionClass *definition = NULL; - - int lower_index = 0; - int upper_index = _DefinitionCount - 1; - int index = upper_index / 2; - bool keep_going = (_DefinitionCount > 0); - - // - // Binary search the list until we've found the definition - // - while (keep_going) { - - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - WWASSERT (curr_def != NULL); - - // - // Is this the definition we are looking for? - // - if (curr_def->Get_ID () == id) { - definition = _SortedDefinitionArray[index]; - keep_going = false; - } else if (upper_index <= lower_index + 1) { - - // - // When the window get's too small, our divide by two won't catch - // both entries, so just go ahead and do them both now. - // - keep_going = false; - if (_SortedDefinitionArray[lower_index]->Get_ID () == id) { - definition = _SortedDefinitionArray[lower_index]; - } else if (_SortedDefinitionArray[upper_index]->Get_ID () == id) { - definition = _SortedDefinitionArray[upper_index]; - } - - } else { - - // - // Cut our 'window' in half - // - if (id > curr_def->Get_ID ()) { - lower_index = index; - index += (upper_index - index) / 2; - } else { - upper_index = index; - index -= (index - lower_index) / 2; - } - } - } - - // - // Should we twiddle this definition? (Twiddling refers to our randomizing - // framework for definitions) - // - if ( twiddle && - definition != NULL && - definition->Get_Class_ID () == CLASSID_TWIDDLERS) - { - definition = ((TwiddlerClass *)definition)->Twiddle (); - } - - return definition; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Find_Named_Definition -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionClass * -DefinitionMgrClass::Find_Named_Definition (const char *name, bool twiddle) -{ - DefinitionClass *definition = NULL; - - // - // Loop through all the definitions and see if we can - // find the one with the requested name - // - for (int index = 0; index < _DefinitionCount; index ++) { - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - - // - // Is this the definition we were looking for? - // - if (curr_def != NULL && ::stricmp (curr_def->Get_Name (), name) == 0) { - definition = curr_def; - break; - } - } - - // - // Should we twiddle this definition? (Twiddling refers to our randomizing - // framework for definitions) - // - if ( twiddle && - definition != NULL && - definition->Get_Class_ID () == CLASSID_TWIDDLERS) - { - definition = ((TwiddlerClass *)definition)->Twiddle (); - } - - return definition; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Find_Typed_Definition -// -////////////////////////////////////////////////////////////////////////////////// - -DefinitionClass * -DefinitionMgrClass::Find_Typed_Definition (const char *name, uint32 class_id, bool twiddle) -{ - // - // Sanity check - // - if (DefinitionHash == NULL) { - WWDEBUG_SAY (("DefinitionMgrClass::Find_Typed_Definition () failed due to a NULL DefinitionHash.\n")); - return NULL; - } - - DefinitionClass *definition = NULL; - - // Check the hash table first. The hash table is built as we need the definitions, so if definition is not - // in the table, it will be added there. - - // - // TSS null deref on this sucker 08/03/01 - // - WWASSERT(DefinitionHash != NULL); - - StringClass lower_case_name(name,true); - _strlwr(lower_case_name.Peek_Buffer()); - DynamicVectorClass* defs = DefinitionHash->Get(lower_case_name); - - if (defs) { - for (int i=0;iLength();++i) { - DefinitionClass* curr_def=(*defs)[i]; - WWASSERT(curr_def); - uint32 curr_class_id = curr_def->Get_Class_ID (); - if ( (curr_class_id == class_id) || - (::SuperClassID_From_ClassID (curr_class_id) == class_id) || - (twiddle && (curr_def->Get_Class_ID () == CLASSID_TWIDDLERS))) - { - definition = curr_def; - break; - } - } - } - - // - // Loop through all the definitions and see if we can - // find the one with the requested name - // - if (!definition) { - for (int index = 0; index < _DefinitionCount; index ++) { - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - if (curr_def != NULL) { - - // - // Is this the correct class of definition? - // - uint32 curr_class_id = curr_def->Get_Class_ID (); - if ( (curr_class_id == class_id) || - (::SuperClassID_From_ClassID (curr_class_id) == class_id) || - (twiddle && (curr_def->Get_Class_ID () == CLASSID_TWIDDLERS))) - { - // - // Is this the definition we were looking for? - // - if (::stricmp (curr_def->Get_Name (), name) == 0) { - definition = curr_def; - // Add the definition to the hash table, so that it can be quickly accessed the next time it is needed. - if (!defs) { - defs=W3DNEW DynamicVectorClass; - DefinitionHash->Insert(lower_case_name,defs); - } - defs->Add(definition); - break; - } - } - } - } - } - - // - // Should we twiddle this definition? (Twiddling refers to our randomizing - // framework for definitions) - // - if ( twiddle && - definition != NULL && - definition->Get_Class_ID () == CLASSID_TWIDDLERS) - { - definition = ((TwiddlerClass *)definition)->Twiddle (); - } - - return definition; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// List_Available_Definitions -// -////////////////////////////////////////////////////////////////////////////////// -void -DefinitionMgrClass::List_Available_Definitions (void) -{ - // - // Loop through all the definitions and print the definition name - // - WWDEBUG_SAY(("Available definitions:\n")); - for (int index = 0; index < _DefinitionCount; index ++) { - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - if (curr_def != NULL) { - WWDEBUG_SAY((" >%s<\n", curr_def->Get_Name ())); - } - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// List_Available_Definitions -// -////////////////////////////////////////////////////////////////////////////////// -void -DefinitionMgrClass::List_Available_Definitions (int superclass_id) -{ - // - // Loop through all the definitions and print the definition name - // - WWDEBUG_SAY(("Available superclass definitions for 0x%8X:\n", superclass_id)); - DefinitionClass *definition = NULL; - for ( definition = Get_First (superclass_id, DefinitionMgrClass::ID_SUPERCLASS); - definition != NULL; - definition = Get_Next (definition, superclass_id, DefinitionMgrClass::ID_SUPERCLASS)) - { - WWDEBUG_SAY((" >%s<\n", definition->Get_Name ())); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Get_First -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionClass * -DefinitionMgrClass::Get_First (uint32 id, ID_TYPE type) -{ - DefinitionClass *definition = NULL; - - // - // Loop through all the definitions and find the first - // one that belongs to the requested class - // - for ( int index = 0; - (definition == NULL) && (index < _DefinitionCount); - index ++) - { - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - if (curr_def != NULL) { - - // - // Is this the definition we were looking for? - // - if ( (type == ID_SUPERCLASS) && - (::SuperClassID_From_ClassID (curr_def->Get_Class_ID ()) == id)) { - definition = curr_def; - } else if ( (type == ID_CLASS) && - (curr_def->Get_Class_ID () == id)) { - definition = curr_def; - } - } - } - - return definition; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Get_Next -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionClass * -DefinitionMgrClass::Get_Next -( - DefinitionClass * curr_def, - uint32 id, - ID_TYPE type -) -{ - DefinitionClass *definition = NULL; - - // - // Loop through all the definitions and find the first - // one that belongs to the requested class - // - for ( int index = curr_def->m_DefinitionMgrLink + 1; - (definition == NULL) && (index < _DefinitionCount); - index ++) - { - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - if (curr_def != NULL) { - - // - // Is this the definition we were looking for? - // - if ( (type == ID_SUPERCLASS) && - (::SuperClassID_From_ClassID (curr_def->Get_Class_ID ()) == id)) { - definition = curr_def; - } else if ( (type == ID_CLASS) && - (curr_def->Get_Class_ID () == id)) { - definition = curr_def; - } - } - } - - return definition; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Get_Next -// -//////////////////////////////////////////////////////////////////////////// -DefinitionClass * -DefinitionMgrClass::Get_Next (DefinitionClass *curr_def) -{ - WWASSERT (curr_def != NULL); - DefinitionClass *definition = NULL; - - int index = curr_def->m_DefinitionMgrLink + 1; - if (index < _DefinitionCount) { - definition = _SortedDefinitionArray[index]; - } - - return definition; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Free_Definitions -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionMgrClass::Free_Definitions (void) -{ - // Clear the hash table - if (DefinitionHash) { - HashTemplateIterator*> ite(*DefinitionHash); - for (ite.First();!ite.Is_Done();ite.Next()) { - DynamicVectorClass* defs=ite.Peek_Value(); -// delete ite.Peek_Value(); - delete defs; - } - DefinitionHash->Remove_All(); - delete DefinitionHash; - DefinitionHash=NULL; - } - - // - // Free each of the definition objects - // - for (int index = 0; index < _DefinitionCount; index ++) { - DefinitionClass *definition = _SortedDefinitionArray[index]; - if (definition != NULL) { - delete definition; - } - } - - // - // Free the definition array - // - if (_SortedDefinitionArray != NULL) { - delete [] _SortedDefinitionArray; - } - - _SortedDefinitionArray = NULL; - _MaxDefinitionCount = 0; - _DefinitionCount = 0; - return ; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Prepare_Definition_Array -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionMgrClass::Prepare_Definition_Array (void) -{ - if (_DefinitionCount + 1 > _MaxDefinitionCount) { - - // - // Allocate a new, bigger array - // - int new_size = _MaxDefinitionCount + DEFINTION_LIST_GROW_SIZE; - DefinitionClass **new_array = W3DNEWARRAY DefinitionClass *[new_size]; - - // - // Copy the entries from the old array to the new array - // - ::memcpy (new_array, _SortedDefinitionArray, _DefinitionCount * sizeof (DefinitionClass *)); - - // - // Free the old array and start using the new array - // - if (_SortedDefinitionArray != NULL) { - delete [] _SortedDefinitionArray; - } - _SortedDefinitionArray = new_array; - _MaxDefinitionCount = new_size; - } - if (!DefinitionHash) DefinitionHash=W3DNEW HashTemplateClass*>; - - return ; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Register_Definition -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionMgrClass::Register_Definition (DefinitionClass *definition) -{ - WWASSERT (definition != NULL); - if (definition != NULL && definition->m_DefinitionMgrLink == -1 && definition->Get_ID () != 0) { - // - // Make sure the definition array is large enough - // - Prepare_Definition_Array (); - - // - // Calculate where in the list we should insert this definition - // - uint32 id = definition->Get_ID (); - int lower_index = 0; - int upper_index = _DefinitionCount - 1; - int index = upper_index / 2; - int insert_index = _DefinitionCount; - bool keep_going = (_DefinitionCount > 0); - bool is_valid = true; - - while (keep_going) { - - DefinitionClass *curr_def = _SortedDefinitionArray[index]; - WWASSERT (curr_def != NULL); - - // - // Check to make sure we aren't trying to register a definition - // that has the same ID as a definition that is already in the list. - // - if (curr_def->Get_ID () == id) { - insert_index = index; - keep_going = false; - is_valid = false; - } else { - - // - // Cut our 'window' in half - // - if (id > curr_def->Get_ID ()) { - lower_index = index; - index += (upper_index - index) / 2; - } else { - upper_index = index; - index -= (index - lower_index) / 2; - } - - // - // If we've narrowed down the window to 2 entries, then quick check - // the different possibilities. - // - if (upper_index <= lower_index + 1) { - if (_SortedDefinitionArray[upper_index]->Get_ID () <= id) { - insert_index = upper_index + 1; - } else if (_SortedDefinitionArray[lower_index]->Get_ID () <= id) { - insert_index = upper_index; - } else { - insert_index = lower_index; - } - keep_going = false; - } - } - } - - //WWASSERT (is_valid); - if (is_valid) { - - // - // Re-index all the definitions that got bumped one cell due to this insertion. - // - for (index = _DefinitionCount - 1; index >= insert_index; index --) { - _SortedDefinitionArray[index + 1] = _SortedDefinitionArray[index]; - _SortedDefinitionArray[index + 1]->m_DefinitionMgrLink = index + 1; - } - - // - // Insert this definition into the list - // - definition->m_DefinitionMgrLink = insert_index; - _SortedDefinitionArray[insert_index] = definition; - _DefinitionCount ++; - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////// -// -// Unregister_Definition -// -//////////////////////////////////////////////////////////////////////////// -void -DefinitionMgrClass::Unregister_Definition (DefinitionClass *definition) -{ - WWASSERT (definition != 0); - //WWASSERT (definition->m_DefinitionMgrLink >= 0 && definition->m_DefinitionMgrLink < _DefinitionCount); - - if (definition != NULL && definition->m_DefinitionMgrLink != -1) { - - // - // Re-index the definitions that come after this definition in the list - // - for (int index = definition->m_DefinitionMgrLink; index < _DefinitionCount - 1; index ++) { - _SortedDefinitionArray[index] = _SortedDefinitionArray[index + 1]; - _SortedDefinitionArray[index]->m_DefinitionMgrLink = index; - } - - _SortedDefinitionArray[_DefinitionCount - 1] = NULL; - definition->m_DefinitionMgrLink = -1; - _DefinitionCount --; - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionMgrClass::Save -( - ChunkSaveClass & csave -) -{ - WWMEMLOG(MEM_GAMEDATA); - - bool retval = true; - - // - // Create a chunk to contain the class variables we need to serialize. - // - csave.Begin_Chunk (CHUNKID_VARIABLES); - Save_Variables (csave); - csave.End_Chunk (); - - // - // Have the base class write the objects to their own chunk. - // - csave.Begin_Chunk (CHUNKID_OBJECTS); - retval &= Save_Objects (csave); - csave.End_Chunk (); - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionMgrClass::Load (ChunkLoadClass &cload) -{ - WWMEMLOG(MEM_GAMEDATA); - bool retval = true; - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - // - // If this is the chunk that contains the class variables, then - // loop through and read each microchunk - // - case CHUNKID_VARIABLES: - retval &= Load_Variables (cload); - break; - - // - // Load all the definition objects from this chunk - // - case CHUNKID_OBJECTS: - retval &= Load_Objects (cload); - break; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save_Objects -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionMgrClass::Save_Objects -( - ChunkSaveClass & csave -) -{ - bool retval = true; - - // - // Loop through all the definition objects - // - for (int index = 0; index < _DefinitionCount; index ++) { - DefinitionClass *definition = _SortedDefinitionArray[index]; - if (definition != NULL && definition->Is_Save_Enabled ()) { - - // - // Save this definition object - // - csave.Begin_Chunk (definition->Get_Factory ().Chunk_ID ()); - definition->Get_Factory ().Save (csave, definition); - csave.End_Chunk (); - } - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionMgrClass::Save_Variables (ChunkSaveClass &csave) -{ - bool retval = true; - return retval; -} - -float _alloc_time; -float _load_time; -float _reg_time; - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load_Objects -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionMgrClass::Load_Objects (ChunkLoadClass &cload) -{ - bool retval = true; - - while (cload.Open_Chunk ()) { - - // - // Load this definition from the chunk (if possible) - // - PersistFactoryClass *factory = SaveLoadSystemClass::Find_Persist_Factory (cload.Cur_Chunk_ID ()); - if (factory != NULL) { - - DefinitionClass *definition = (DefinitionClass *)factory->Load (cload); - if (definition != NULL) { - - // - // Add this definition to our array - // - Prepare_Definition_Array (); - _SortedDefinitionArray[_DefinitionCount ++] = definition; - } - } - - cload.Close_Chunk (); - } - - // - // Sort the definitions - // - if (_DefinitionCount > 0) { - ::qsort (_SortedDefinitionArray, _DefinitionCount, sizeof (DefinitionClass *), fnCompareDefinitionsCallback); - } - - // - // Assign a mgr link to each definition - // - for (int index = 0; index < _DefinitionCount; index ++) { - _SortedDefinitionArray[index]->m_DefinitionMgrLink = index; - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -DefinitionMgrClass::Load_Variables (ChunkLoadClass &cload) -{ - bool retval = true; - - // - // Loop through all the microchunks that define the variables - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - case VARID_NEXTDEFID: - break; - } - - cload.Close_Micro_Chunk (); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Get_New_ID -// -///////////////////////////////////////////////////////////////////// -uint32 -DefinitionMgrClass::Get_New_ID (uint32 class_id) -{ - uint32 idrange_start = (class_id - DEF_CLASSID_START) * IDRANGE_PER_CLASS; - uint32 idrange_end = (idrange_start + IDRANGE_PER_CLASS); - - uint32 new_id = idrange_start + 1; - - // - // Try to find the first empty slot in this ID range - // - for (int index = 0; index < _DefinitionCount; index ++) { - DefinitionClass *definition = _SortedDefinitionArray[index]; - if (definition != NULL) { - - // - // Get this definition's ID - // - uint32 curr_id = definition->Get_ID (); - - // - // Is this id in the range we are looking for? - // - if (curr_id >= idrange_start && curr_id < idrange_end) { - - bool is_ok = false; - if (index < _DefinitionCount - 1) { - - // - // Check to see if the next definition in our array leaves a hole in the - // ID range. - // - DefinitionClass *next_definition = _SortedDefinitionArray[index + 1]; - if (next_definition != NULL && next_definition->Get_ID () > (curr_id + 1)) { - is_ok = true; - } - - } else { - is_ok = true; - } - - // - // Return the new ID - // - if (is_ok) { - new_id = curr_id + 1; - break; - } - } - } - } - - return new_id; -} - - -//////////////////////////////////////////////////////////////// -// -// fnCompareDefinitionsCallback -// -//////////////////////////////////////////////////////////////// -int __cdecl -DefinitionMgrClass::fnCompareDefinitionsCallback -( - const void *elem1, - const void *elem2 -) -{ - WWASSERT (elem1 != NULL); - WWASSERT (elem2 != NULL); - DefinitionClass *definition1 = *((DefinitionClass **)elem1); - DefinitionClass *definition2 = *((DefinitionClass **)elem2); - - // - // Sort the definitions based on ID - // - int result = 0; - if (definition1->Get_ID () > definition2->Get_ID ()) { - result = 1; - } else if (definition1->Get_ID () < definition2->Get_ID ()) { - result = -1; - } else { - result = 0; - } - - return result; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h deleted file mode 100644 index 52d1180df8..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/definitionmgr.h +++ /dev/null @@ -1,187 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/definitionmgr.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 8/24/01 5:13p $* - * * - * $Revision:: 24 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef __DEFINITION_MGR_H -#define __DEFINITION_MGR_H - -#include "always.h" -#include "saveload.h" -#include "saveloadsubsystem.h" -#include "saveloadids.h" -#include "wwdebug.h" -#include "wwstring.h" -#include "hashtemplate.h" -#include "Vector.H" - - -// Forward declarations -class DefinitionClass; - -////////////////////////////////////////////////////////////////////////////////// -// Global declarations -////////////////////////////////////////////////////////////////////////////////// -extern class DefinitionMgrClass _TheDefinitionMgr; - -////////////////////////////////////////////////////////////////////////////////// -// -// DefinitionMgrClass -// -////////////////////////////////////////////////////////////////////////////////// -class DefinitionMgrClass : public SaveLoadSubSystemClass -{ -public: - - ///////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ///////////////////////////////////////////////////////////////////// - DefinitionMgrClass (void); - ~DefinitionMgrClass (void); - - ///////////////////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////////////////// - - // From SaveLoadSubSystemClass - virtual uint32 Chunk_ID (void) const; - - // Type identification - static DefinitionClass * Find_Definition (uint32 id, bool twiddle = true); - static DefinitionClass * Find_Named_Definition (const char *name, bool twiddle = true); - static DefinitionClass * Find_Typed_Definition (const char *name, uint32 class_id, bool twiddle = true); - static void List_Available_Definitions (void); - static void List_Available_Definitions (int superclass_id); - static uint32 Get_New_ID (uint32 class_id); - - // Definition registration - static void Register_Definition (DefinitionClass *definition); - static void Unregister_Definition (DefinitionClass *definition); - - // - // Definition enumeration - // - typedef enum - { - ID_CLASS = 1, - ID_SUPERCLASS, - } ID_TYPE; - - static DefinitionClass * Get_First (void); - static DefinitionClass * Get_First (uint32 id, ID_TYPE type = ID_CLASS); - static DefinitionClass * Get_Next (DefinitionClass *curr_def); - static DefinitionClass * Get_Next (DefinitionClass *curr_def, uint32 id, ID_TYPE type = ID_CLASS); - - static void Free_Definitions (void); - -protected: - - ///////////////////////////////////////////////////////////////////// - // Protected methods - ///////////////////////////////////////////////////////////////////// - - // From SaveLoadSubSystemClass - virtual bool Contains_Data (void) const; - virtual bool Save (ChunkSaveClass &csave); - virtual bool Load (ChunkLoadClass &cload); - virtual const char* Name (void) const { return "DefinitionMgrClass"; } - - // Persistence methods - bool Save_Objects (ChunkSaveClass &csave); - bool Load_Objects (ChunkLoadClass &cload); - bool Save_Variables (ChunkSaveClass &csave); - bool Load_Variables (ChunkLoadClass &cload); - -private: - static HashTemplateClass*>* DefinitionHash; - - ///////////////////////////////////////////////////////////////////// - // Private methods - ///////////////////////////////////////////////////////////////////// - static void Prepare_Definition_Array (void); - static int __cdecl fnCompareDefinitionsCallback (const void *elem1, const void *elem2); - - ///////////////////////////////////////////////////////////////////// - // Static member data - ///////////////////////////////////////////////////////////////////// - static DefinitionClass ** _SortedDefinitionArray; - static int _MaxDefinitionCount; - static int _DefinitionCount; - - ///////////////////////////////////////////////////////////////////// - // Friend classes - ///////////////////////////////////////////////////////////////////// - friend class DefinitionClass; -}; - -///////////////////////////////////////////////////////////////////// -// Chunk_ID -///////////////////////////////////////////////////////////////////// -inline uint32 -DefinitionMgrClass::Chunk_ID (void) const -{ - return CHUNKID_SAVELOAD_DEFMGR; -} - -///////////////////////////////////////////////////////////////////// -// Contains_Data -///////////////////////////////////////////////////////////////////// -inline bool -DefinitionMgrClass::Contains_Data (void) const -{ - return true; // TODO: check if we have any definitions... -} - -///////////////////////////////////////////////////////////////////// -// Get_First_Definition -///////////////////////////////////////////////////////////////////// -inline DefinitionClass * -DefinitionMgrClass::Get_First (void) -{ - DefinitionClass *definition = NULL; - if (_DefinitionCount > 0) { - definition = _SortedDefinitionArray[0]; - } - - return definition; -} - - -#endif //__DEFINITION_MGR_H diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/editable.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/editable.h deleted file mode 100644 index b2aade33fe..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/editable.h +++ /dev/null @@ -1,339 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/editable.h $* - * * - * * - * Org Author:: Patrick Smith * - * * - * Author:: Kenny Mitchell * - * * - * $Modtime:: 5/29/02 11:00a $* - * * - * $Revision:: 29 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * 5/27/02 KM Added named filename parameter declaration - * 5/29/02 KM Added specific texture filename parameter support - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef __EDITABLE_H -#define __EDITABLE_H - - -#include "always.h" -#include "persist.h" -#include "parameter.h" -#include "simpleparameter.h" -#include "parameterlist.h" -#include "wwdebug.h" - -////////////////////////////////////////////////////////////////////////////////// -// -// EditableClass -// -////////////////////////////////////////////////////////////////////////////////// -class EditableClass -{ -public: - - ///////////////////////////////////////////////////////////////////// - // Public methods - // - // Note: These methods can be implemented in derived classes - // by the DECLARE_EDITABLE macro. - // - ///////////////////////////////////////////////////////////////////// - virtual int Get_Parameter_Count (void) const; - virtual ParameterClass * Lock_Parameter (int i); - virtual void Unlock_Parameter (int i); -}; - -///////////////////////////////////////////////////////////////////// -// Get_Parameter_Count -///////////////////////////////////////////////////////////////////// -inline int -EditableClass::Get_Parameter_Count (void) const -{ - return 0; -} - -///////////////////////////////////////////////////////////////////// -// Get_Parameter -///////////////////////////////////////////////////////////////////// -inline ParameterClass * -EditableClass::Lock_Parameter (int i) -{ - WWASSERT (0); - return NULL; -} - -///////////////////////////////////////////////////////////////////// -// Set_Parameter -///////////////////////////////////////////////////////////////////// -inline void -EditableClass::Unlock_Parameter (int i) -{ - return ; -} - -//#define PARAM_EDITING_ON -#ifdef PARAM_EDITING_ON - - ////////////////////////////////////////////////////////////////////////////////// - // - // DECLARE_EDITABLE - // - ////////////////////////////////////////////////////////////////////////////////// - #define DECLARE_EDITABLE(_class, _parent) \ - ParameterListClass plist_##_class; \ - virtual int _class::Get_Parameter_Count(void) const \ - { \ - return plist_##_class.Count () + _parent::Get_Parameter_Count (); \ - } \ - virtual ParameterClass *_class::Lock_Parameter(int i) \ - { \ - if (i < _parent::Get_Parameter_Count()) { \ - return _parent::Lock_Parameter (i); \ - } \ - return plist_##_class[i - _parent::Get_Parameter_Count()]; \ - } \ - - ////////////////////////////////////////////////////////////////////////////////// - // - // EDITABLE_PARAM - // - // The following macros are used inside the constructor for an editable - // object to map member data to abstract parameter objects. - // - // Some examples: - // - // To register the player's name (a string): - // EDITABLE_PARAM(GameClass, ParameterClass::TYPE_STRING, Name) - // - // To register the player's name using a more descriptive display string: - // NAMED_EDITABLE_PARAM(GameClass, ParameterClass::TYPE_STRING, Name, "Player Name") - // - // To register a unit's maximum health - // INT_EDITABLE_PARAM(GameClass, MaxHeatlh, 0, 500) - // - // To register a complex variable (such as an enumerated type: - // #ifdef PARAM_EDITING_ON - // EnumParameterClass *param = new EnumParameterClass(GangID); - // param->Set_Name ("Gang"); - // param->Add_Value ("GDI", ID_GDI); - // param->Add_Value ("NOD", ID_NOD); - // param->Add_Value ("Neutral", ID_NEUTRAL); - // GENERIC_EDITABLE_PARAM(param) - // #endif - // - ////////////////////////////////////////////////////////////////////////////////// - - - #define EDITABLE_PARAM(_class, type, data) plist_##_class.Add (&(data), #data, type); - #define NAMED_EDITABLE_PARAM(_class, type, data, name) plist_##_class.Add (&(data), name, type); - - #define INT_EDITABLE_PARAM(_class, data, min, max) { \ - IntParameterClass *param = W3DNEW IntParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - plist_##_class.Add (param); } \ - - #define INT_UNITS_PARAM(_class, data, min, max, unitsname) { \ - IntParameterClass *param = W3DNEW IntParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - param->Set_Units_Name(unitsname); \ - plist_##_class.Add (param); } \ - - #define NAMED_INT_UNITS_PARAM(_class,data,min,max,unitsname,name) { \ - IntParameterClass *param = W3DNEW IntParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - param->Set_Units_Name(unitsname); \ - param->Set_Name(name); \ - plist_##_class.Add (param); } \ - - #define FLOAT_EDITABLE_PARAM(_class, data, min, max) { \ - FloatParameterClass *param = W3DNEW FloatParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - plist_##_class.Add (param); } \ - - #define FLOAT_UNITS_PARAM(_class, data, min, max, unitsname) { \ - FloatParameterClass *param = W3DNEW FloatParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - param->Set_Units_Name(unitsname); \ - plist_##_class.Add (param); } - - #define NAMED_FLOAT_UNITS_PARAM(_class, data, min, max, unitsname,name) { \ - FloatParameterClass *param = W3DNEW FloatParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - param->Set_Units_Name(unitsname); \ - param->Set_Name(name); \ - plist_##_class.Add (param); } - - #define ANGLE_EDITABLE_PARAM(_class, data, min, max) { \ - AngleParameterClass *param = W3DNEW AngleParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - param->Set_Units_Name ("degrees"); \ - plist_##_class.Add (param); } \ - - #define NAMED_ANGLE_EDITABLE_PARAM(_class, data, min, max, name) { \ - AngleParameterClass *param = W3DNEW AngleParameterClass( &data, #data); \ - param->Set_Range (min, max); \ - param->Set_Units_Name ("degrees"); \ - param->Set_Name(name); \ - plist_##_class.Add (param); } \ - - #define GENERIC_EDITABLE_PARAM(_class, param) \ - plist_##_class.Add (param); \ - - #define MODEL_DEF_PARAM(_class, data, name) { \ - ModelDefParameterClass *param = W3DNEW ModelDefParameterClass (&data); \ - param->Set_Name (#data); \ - param->Set_Base_Class (name); \ - GENERIC_EDITABLE_PARAM(_class, param); } - - #define PHYS_DEF_PARAM(_class, data, name) { \ - PhysDefParameterClass *param = W3DNEW PhysDefParameterClass (&data); \ - param->Set_Name (#data); \ - param->Set_Base_Class (name); \ - GENERIC_EDITABLE_PARAM(_class, param); } - - #define SCRIPT_PARAM(_class, name, params) { \ - ScriptParameterClass *param = W3DNEW ScriptParameterClass (&name, ¶ms); \ - param->Set_Name (#name); \ - GENERIC_EDITABLE_PARAM(_class, param); } - - #define SCRIPTLIST_PARAM(_class, name, name_list, param_list) { \ - ScriptListParameterClass *param = W3DNEW ScriptListParameterClass (&name_list, ¶m_list); \ - param->Set_Name (name); \ - GENERIC_EDITABLE_PARAM(_class, param); } - - #define ENUM_PARAM(_class, data, params) { \ - EnumParameterClass *param = W3DNEW EnumParameterClass (&data); \ - param->Set_Name (#data); \ - param->Add_Values params; \ - plist_##_class.Add (param); } \ - - #define FILENAME_PARAM(_class, data, desc, extension) { \ - FilenameParameterClass *param = W3DNEW FilenameParameterClass (&data); \ - param->Set_Name (#data); \ - param->Set_Description (desc); \ - param->Set_Extension (extension); \ - plist_##_class.Add (param); } \ - - #define NAMED_FILENAME_PARAM(_class, data, name, desc, extension) { \ - FilenameParameterClass *param = new FilenameParameterClass (&data); \ - param->Set_Name (name); \ - param->Set_Description (desc); \ - param->Set_Extension (extension); \ - plist_##_class.Add (param); } \ - - #define TEXTURE_FILENAME_PARAM(_class, data, desc, extension) { \ - TextureFilenameParameterClass *param = new TextureFilenameParameterClass (&data); \ - param->Set_Name (#data); \ - param->Set_Description (desc); \ - param->Set_Extension (extension); \ - plist_##_class.Add (param); } \ - - #define NAMED_TEXTURE_FILENAME_PARAM(_class, data, name, desc, extension) { \ - TextureFilenameParameterClass *param = new TextureFilenameParameterClass (&data); \ - param->Set_Name (name); \ - param->Set_Description (desc); \ - param->Set_Extension (extension); \ - plist_##_class.Add (param); } \ - - #define DEFIDLIST_PARAM(_class, data, root_class_id) { \ - DefIDListParameterClass *param = W3DNEW DefIDListParameterClass (&data); \ - param->Set_Name (#data); \ - param->Set_Class_ID (root_class_id); \ - plist_##_class.Add (param); } \ - - #define CLASSID_DEFIDLIST_PARAM(_class, data, root_class_id, class_id, name) { \ - DefIDListParameterClass *param = W3DNEW DefIDListParameterClass (&data); \ - param->Set_Name (name); \ - param->Set_Class_ID (root_class_id); \ - param->Set_Selected_Class_ID (&class_id); \ - plist_##_class.Add (param); } - - #define ZONE_PARAM(_class, data, name) { \ - ZoneParameterClass *param = W3DNEW ZoneParameterClass (&data); \ - param->Set_Name (name); \ - GENERIC_EDITABLE_PARAM(_class, param); } - - #define PARAM_SEPARATOR(_class, name) { \ - SeparatorParameterClass *param = W3DNEW SeparatorParameterClass; \ - param->Set_Name (name); \ - GENERIC_EDITABLE_PARAM(_class, param); } - - #define GENERIC_DEFID_PARAM(_class, data, root_class_id) { \ - GenericDefParameterClass *param = W3DNEW GenericDefParameterClass (&data); \ - param->Set_Class_ID (root_class_id); \ - param->Set_Name (#data); \ - plist_##_class.Add (param); } - - -#else - - #define DECLARE_EDITABLE(_class, _parent) - #define EDITABLE_PARAM(_class, type, data) - #define NAMED_EDITABLE_PARAM(_class, type, data, name) - #define INT_EDITABLE_PARAM(_class, data, min, max) - #define INT_UNITS_PARAM(_class, data, min, max, unitsname) - #define NAMED_INT_UNITS_PARAM(_class,data,min,max,unitsname,name) - #define FLOAT_EDITABLE_PARAM(_class, data, min, max) - #define FLOAT_UNITS_PARAM(_class, data, min, max, unitsname) - #define NAMED_FLOAT_UNITS_PARAM(_class, data, min, max, unitsname,name) - #define ANGLE_EDITABLE_PARAM(_class, data, min, max) - #define NAMED_ANGLE_EDITABLE_PARAM(_class, data, min, max, name) - #define GENERIC_EDITABLE_PARAM(_class, param) - #define MODEL_DEF_PARAM(_class, data, name) - #define PHYS_DEF_PARAM(_class, data, name) - #define SCRIPT_PARAM(_class, name, params) - #define SCRIPTLIST_PARAM(_class, name, name_list, param_list) - #define ENUM_PARAM(_class, data, params) - #define FILENAME_PARAM(_class, data, desc, extension) - #define NAMED_FILENAME_PARAM(_class, data, name, desc, extension) - #define TEXTURE_FILENAME_PARAM(_class, data, desc, extension) - #define NAMED_TEXTURE_FILENAME_PARAM(_class, data, name, desc, extension) - #define DEFIDLIST_PARAM(_class, data, root_class_id) - #define CLASSID_DEFIDLIST_PARAM(_class, data, root_class_id, class_id, name) - #define ZONE_PARAM(_class, data, name) - #define PARAM_SEPARATOR(_class, name) - #define GENERIC_DEFID_PARAM(_class, data, root_class_id) - -#endif //PARAM_EDITING_ON - - -#endif //__EDITABLE_H - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp deleted file mode 100644 index 5473d0e6d3..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.cpp +++ /dev/null @@ -1,2243 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/parameter.cpp $* - * * - * Org Author:: Patrick Smith * - * * - * Author:: Kenny Mitchell * - * * - * $Modtime:: 5/29/02 11:00a $* - * * - * $Revision:: 33 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "parameter.h" -#include "parametertypes.h" -#include "simpleparameter.h" -#include "wwstring.h" -#include "definitionclassids.h" - - -///////////////////////////////////////////////////////////////////// -// -// Construct -// -// This is a virtual constructor that is capable of creating a new -// instance of any type of parameter used in the Editable system. -// -///////////////////////////////////////////////////////////////////// -ParameterClass * -ParameterClass::Construct (Type type, void *data, const char *name) -{ - ParameterClass *new_param = NULL; - switch (type) { - - case TYPE_INT: - new_param = W3DNEW IntParameterClass (data, name); - break; - - case TYPE_FLOAT: - new_param = W3DNEW FloatParameterClass (data, name); - break; - - case TYPE_VECTOR2: - new_param = W3DNEW Vector2ParameterClass (data, name); - break; - - case TYPE_VECTOR3: - new_param = W3DNEW Vector3ParameterClass (data, name); - break; - - case TYPE_RECT: - new_param = W3DNEW RectParameterClass (data, name); - break; - - case TYPE_COLOR: - new_param = W3DNEW ColorParameterClass (data, name); - break; - - case TYPE_MATRIX3D: - new_param = W3DNEW Matrix3DParameterClass (data, name); - break; - - case TYPE_BOOL: - new_param = W3DNEW BoolParameterClass (data, name); - break; - - case TYPE_STRINGSDB_ID: - new_param = W3DNEW StringsDBEntryParameterClass (data, name); - break; - - case TYPE_ANGLE: - new_param = W3DNEW AngleParameterClass (data, name); - break; - - case TYPE_STRING: - new_param = W3DNEW StringParameterClass ((StringClass *)data); - new_param->Set_Name (name); - break; - - case TYPE_FILENAME: - new_param = W3DNEW FilenameParameterClass ((StringClass *)data); - new_param->Set_Name (name); - break; - - case TYPE_TEXTURE_FILENAME: - new_param = new TextureFilenameParameterClass ((StringClass *)data); - new_param->Set_Name (name); - break; - - case TYPE_SOUND_FILENAME: - new_param = W3DNEW SoundFilenameParameterClass ((StringClass *)data); - new_param->Set_Name (name); - break; - - case TYPE_ENUM: - new_param = W3DNEW EnumParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_GENERICDEFINITIONID: - new_param = W3DNEW GenericDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_GAMEOBJDEFINITIONID: - new_param = W3DNEW GameObjDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_WEAPONOBJDEFINITIONID: - new_param = W3DNEW WeaponObjDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_AMMOOBJDEFINITIONID: - new_param = W3DNEW AmmoObjDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_EXPLOSIONDEFINITIONID: - new_param = W3DNEW ExplosionObjDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_SOUNDDEFINITIONID: - new_param = W3DNEW SoundDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_MODELDEFINITIONID: - new_param = W3DNEW ModelDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_PHYSDEFINITIONID: - new_param = W3DNEW PhysDefParameterClass ((int *)data); - new_param->Set_Name (name); - break; - - case TYPE_DEFINITIONIDLIST: - new_param = W3DNEW DefIDListParameterClass ((DynamicVectorClass *)data); - new_param->Set_Name (name); - ((DefIDListParameterClass *)new_param)->Set_Class_ID (CLASSID_GAME_OBJECTS); - break; - - case TYPE_ZONE: - new_param = W3DNEW ZoneParameterClass ((OBBoxClass *)data); - new_param->Set_Name (name); - break; - - case TYPE_FILENAMELIST: - new_param = W3DNEW FilenameListParameterClass ((DynamicVectorClass *)data); - new_param->Set_Name (name); - break; - - case TYPE_SEPARATOR: - new_param = W3DNEW SeparatorParameterClass; - new_param->Set_Name (name); - break; - } - - return new_param; -} - -//*******************************************************************************************// -// -// Start of StringParameterClass -// -//*******************************************************************************************// - -///////////////////////////////////////////////////////////////////// -// -// StringParameterClass -// -///////////////////////////////////////////////////////////////////// -StringParameterClass::StringParameterClass (StringClass *string) - : m_String (string) -{ - return ; -} - -///////////////////////////////////////////////////////////////////// -// -// StringParameterClass -// -///////////////////////////////////////////////////////////////////// -StringParameterClass::StringParameterClass (const StringParameterClass &src) - : m_String (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const StringParameterClass & -StringParameterClass::operator= (const StringParameterClass &src) -{ - m_String = src.m_String; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -StringParameterClass::operator== (const StringParameterClass &src) -{ - bool retval = false; - - if (m_String != NULL && src.m_String != NULL && - (m_String->Compare (*(src.m_String)) == 0)) { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -StringParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = StringParameterClass::operator== ((const StringParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -StringParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_STRING)) { - (*m_String) = ((StringParameterClass &)src).Get_String (); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// Get_String -// -///////////////////////////////////////////////////////////////////// -const char * -StringParameterClass::Get_String (void) const -{ - const char * string = NULL; - if (m_String != NULL) { - string = (*m_String); - } - return string; -} - - -///////////////////////////////////////////////////////////////////// -// -// Set_String -// -///////////////////////////////////////////////////////////////////// -void -StringParameterClass::Set_String (const char * string) -{ - if (m_String != NULL) { - Set_Modified (); - (*m_String) = string; - } - - return ; -} - - -//*******************************************************************************************// -// -// Start of FilenameParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// FilenameParameterClass -// -///////////////////////////////////////////////////////////////////// -FilenameParameterClass::FilenameParameterClass (StringClass *string) - : StringParameterClass (string) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// FilenameParameterClass -// -///////////////////////////////////////////////////////////////////// -FilenameParameterClass::FilenameParameterClass (const FilenameParameterClass &src) - : StringParameterClass (src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const FilenameParameterClass & -FilenameParameterClass::operator= (const FilenameParameterClass &src) -{ - StringParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -FilenameParameterClass::operator== (const FilenameParameterClass &src) -{ - return StringParameterClass::operator== (src); -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -FilenameParameterClass::operator== (const ParameterClass &src) -{ - return StringParameterClass::operator== (src); -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -FilenameParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_FILENAME)) { - Set_String (((FilenameParameterClass &)src).Get_String ()); - } - - StringParameterClass::Copy_Value (src); - return ; -} - -//*******************************************************************************************// -// -// Start of TextureFilenameParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// TextureFilenameParameterClass -// -///////////////////////////////////////////////////////////////////// -TextureFilenameParameterClass::TextureFilenameParameterClass (StringClass *string) -: FilenameParameterClass (string), - Show_Alpha(false), - Show_Texture(false) -{ -} - - -///////////////////////////////////////////////////////////////////// -// -// TextureFilenameParameterClass -// -///////////////////////////////////////////////////////////////////// -TextureFilenameParameterClass::TextureFilenameParameterClass (const TextureFilenameParameterClass &src) -: FilenameParameterClass (src), - Show_Alpha(false), - Show_Texture(false) -{ -} - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void TextureFilenameParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_TEXTURE_FILENAME)) - { - Set_String (((FilenameParameterClass &)src).Get_String ()); - } - - StringParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of SoundFilenameParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// SoundFilenameParameterClass -// -///////////////////////////////////////////////////////////////////// -SoundFilenameParameterClass::SoundFilenameParameterClass (StringClass *string) - : FilenameParameterClass (string) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// SoundFilenameParameterClass -// -///////////////////////////////////////////////////////////////////// -SoundFilenameParameterClass::SoundFilenameParameterClass (const SoundFilenameParameterClass &src) - : FilenameParameterClass (src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const SoundFilenameParameterClass & -SoundFilenameParameterClass::operator= (const SoundFilenameParameterClass &src) -{ - FilenameParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -SoundFilenameParameterClass::operator== (const SoundFilenameParameterClass &src) -{ - return FilenameParameterClass::operator== (src); -} - - - -//*******************************************************************************************// -// -// Start of EnumParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// EnumParameterClass -// -///////////////////////////////////////////////////////////////////// -EnumParameterClass::EnumParameterClass (int *value) - : m_Value (value) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// EnumParameterClass -// -///////////////////////////////////////////////////////////////////// -EnumParameterClass::EnumParameterClass (const EnumParameterClass &src) - : m_Value (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const EnumParameterClass & -EnumParameterClass::operator= (const EnumParameterClass &src) -{ - m_List.Delete_All (); - - m_Value = src.m_Value; - m_List = src.m_List; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -EnumParameterClass::operator== (const EnumParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -EnumParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = EnumParameterClass::operator== ((const EnumParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -EnumParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_ENUM)) { - (*m_Value) = ((EnumParameterClass &)src).Get_Selected_Value (); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// Add_Value -// -///////////////////////////////////////////////////////////////////// -void -EnumParameterClass::Add_Value (const char *display_name, int value) -{ - m_List.Add (ENUM_VALUE(display_name, value)); - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// Add_Value -// -///////////////////////////////////////////////////////////////////// -void __cdecl -EnumParameterClass::Add_Values (const char *first_name, int first_value, ...) -{ - m_List.Add (ENUM_VALUE(first_name, first_value)); - - va_list arg_list; - va_start (arg_list, first_value); - - // - // Add all the params on the stack (until we found - // the terminator) - // - bool more_params = true; - while (more_params) { - - // - // Get the string param - // - const char *name = va_arg (arg_list, const char *); - if (name == NULL) { - more_params = false; - } else { - - // - // Add the string/id pair to the enum list - // - int value = va_arg (arg_list, int); - m_List.Add (ENUM_VALUE(name, value)); - } - } - - va_end (arg_list); - return ; -} - - - -//*******************************************************************************************// -// -// Start of PhysDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// PhysDefParameterClass -// -///////////////////////////////////////////////////////////////////// -PhysDefParameterClass::PhysDefParameterClass (int *id) - : m_Value (id) -{ - return ; -} - -///////////////////////////////////////////////////////////////////// -// -// PhysDefParameterClass -// -///////////////////////////////////////////////////////////////////// -PhysDefParameterClass::PhysDefParameterClass (const PhysDefParameterClass &src) - : m_Value (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const PhysDefParameterClass & -PhysDefParameterClass::operator= (const PhysDefParameterClass &src) -{ - m_Value = src.m_Value; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -PhysDefParameterClass::operator== (const PhysDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -PhysDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = PhysDefParameterClass::operator== ((const PhysDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -PhysDefParameterClass::Copy_Value (const ParameterClass &/*src*/) -{ - // - // We don't allow the value to be copied - // - return ; -} - - -//*******************************************************************************************// -// -// Start of ModelDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// ModelDefParameterClass -// -///////////////////////////////////////////////////////////////////// -ModelDefParameterClass::ModelDefParameterClass (int *id) - : m_Value (id) -{ - return ; -} - -///////////////////////////////////////////////////////////////////// -// -// ModelDefParameterClass -// -///////////////////////////////////////////////////////////////////// -ModelDefParameterClass::ModelDefParameterClass (const ModelDefParameterClass &src) - : m_Value (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const ModelDefParameterClass & -ModelDefParameterClass::operator= (const ModelDefParameterClass &src) -{ - m_Value = src.m_Value; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ModelDefParameterClass::operator== (const ModelDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ModelDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = ModelDefParameterClass::operator== ((const ModelDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -ModelDefParameterClass::Copy_Value (const ParameterClass &/*src*/) -{ - // - // We don't allow the value to be copied - // - return ; -} - - -//*******************************************************************************************// -// -// Start of DefParameterClass -// -//*******************************************************************************************// - -///////////////////////////////////////////////////////////////////// -// -// DefParameterClass -// -///////////////////////////////////////////////////////////////////// -DefParameterClass::DefParameterClass (int *id) - : m_Value (id) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// DefParameterClass -// -///////////////////////////////////////////////////////////////////// -DefParameterClass::DefParameterClass (const DefParameterClass &src) - : m_Value (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const DefParameterClass & -DefParameterClass::operator= (const DefParameterClass &src) -{ - m_Value = src.m_Value; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -DefParameterClass::operator== (const DefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -DefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = DefParameterClass::operator== ((const DefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -DefParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Get_Type () == Get_Type ()) { - (*m_Value) = ((DefParameterClass &)src).Get_Value (); - } - - ParameterClass::Copy_Value (src); - return ; -} - - - -//*******************************************************************************************// -// -// Start of GenericDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// GenericDefParameterClass -// -///////////////////////////////////////////////////////////////////// -GenericDefParameterClass::GenericDefParameterClass (int *id) - : m_ClassID (0), - DefParameterClass (id) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// GenericDefParameterClass -// -///////////////////////////////////////////////////////////////////// -GenericDefParameterClass::GenericDefParameterClass (const GenericDefParameterClass &src) - : m_ClassID (0), - DefParameterClass (src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const GenericDefParameterClass & -GenericDefParameterClass::operator= (const GenericDefParameterClass &src) -{ - DefParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -GenericDefParameterClass::operator== (const GenericDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -GenericDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = GenericDefParameterClass::operator== ((const GenericDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -GenericDefParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_GENERICDEFINITIONID)) { - (*m_Value) = ((GenericDefParameterClass &)src).Get_Value (); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of GameObjDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// GameObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -GameObjDefParameterClass::GameObjDefParameterClass (int *id) - : DefParameterClass (id) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// GameObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -GameObjDefParameterClass::GameObjDefParameterClass (const GameObjDefParameterClass &src) - : DefParameterClass (src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const GameObjDefParameterClass & -GameObjDefParameterClass::operator= (const GameObjDefParameterClass &src) -{ - DefParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -GameObjDefParameterClass::operator== (const GameObjDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -GameObjDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = GameObjDefParameterClass::operator== ((const GameObjDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -GameObjDefParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_GAMEOBJDEFINITIONID)) { - (*m_Value) = ((GameObjDefParameterClass &)src).Get_Value (); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of WeaponObjDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// WeaponObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -WeaponObjDefParameterClass::WeaponObjDefParameterClass (int *id) - : GameObjDefParameterClass (id) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// WeaponObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -WeaponObjDefParameterClass::WeaponObjDefParameterClass (const WeaponObjDefParameterClass &src) - : GameObjDefParameterClass (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const WeaponObjDefParameterClass & -WeaponObjDefParameterClass::operator= (const WeaponObjDefParameterClass &src) -{ - m_Value = src.m_Value; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -WeaponObjDefParameterClass::operator== (const WeaponObjDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -WeaponObjDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = WeaponObjDefParameterClass::operator== ((const WeaponObjDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -WeaponObjDefParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_WEAPONOBJDEFINITIONID)) { - (*m_Value) = ((WeaponObjDefParameterClass &)src).Get_Value (); - } - - GameObjDefParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of AmmoObjDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// AmmoObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -AmmoObjDefParameterClass::AmmoObjDefParameterClass (int *id) - : GameObjDefParameterClass (id) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// AmmoObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -AmmoObjDefParameterClass::AmmoObjDefParameterClass (const AmmoObjDefParameterClass &src) - : GameObjDefParameterClass (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const AmmoObjDefParameterClass & -AmmoObjDefParameterClass::operator= (const AmmoObjDefParameterClass &src) -{ - m_Value = src.m_Value; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -AmmoObjDefParameterClass::operator== (const AmmoObjDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -AmmoObjDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = AmmoObjDefParameterClass::operator== ((const AmmoObjDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -AmmoObjDefParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_AMMOOBJDEFINITIONID)) { - (*m_Value) = ((AmmoObjDefParameterClass &)src).Get_Value (); - } - - GameObjDefParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of ExplosionObjDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// ExplosionObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -ExplosionObjDefParameterClass::ExplosionObjDefParameterClass (int *id) - : GameObjDefParameterClass (id) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// ExplosionObjDefParameterClass -// -///////////////////////////////////////////////////////////////////// -ExplosionObjDefParameterClass::ExplosionObjDefParameterClass (const ExplosionObjDefParameterClass &src) - : GameObjDefParameterClass (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const ExplosionObjDefParameterClass & -ExplosionObjDefParameterClass::operator= (const ExplosionObjDefParameterClass &src) -{ - m_Value = src.m_Value; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ExplosionObjDefParameterClass::operator== (const ExplosionObjDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ExplosionObjDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = ExplosionObjDefParameterClass::operator== ((const ExplosionObjDefParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -ExplosionObjDefParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_AMMOOBJDEFINITIONID)) { - (*m_Value) = ((ExplosionObjDefParameterClass &)src).Get_Value (); - } - - GameObjDefParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of SoundDefParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// SoundDefParameterClass -// -///////////////////////////////////////////////////////////////////// -SoundDefParameterClass::SoundDefParameterClass (int *id) - : DefParameterClass (id) -{ - return ; -} - -///////////////////////////////////////////////////////////////////// -// -// SoundDefParameterClass -// -///////////////////////////////////////////////////////////////////// -SoundDefParameterClass::SoundDefParameterClass (const SoundDefParameterClass &src) - : DefParameterClass (src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const SoundDefParameterClass & -SoundDefParameterClass::operator= (const SoundDefParameterClass &src) -{ - DefParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -SoundDefParameterClass::operator== (const SoundDefParameterClass &src) -{ - bool retval = false; - - if (m_Value != NULL && src.m_Value != NULL && - (*m_Value) == (*src.m_Value)) - { - retval = true; - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -SoundDefParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = SoundDefParameterClass::operator== ((const SoundDefParameterClass &)src); - } - - return retval; -} - - -//*******************************************************************************************// -// -// Start of ScriptParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// ScriptParameterClass -// -///////////////////////////////////////////////////////////////////// -ScriptParameterClass::ScriptParameterClass (StringClass *name, StringClass *params) - : m_ScriptName (name), - m_ScriptParams (params) -{ - return ; -} - -///////////////////////////////////////////////////////////////////// -// -// ScriptParameterClass -// -///////////////////////////////////////////////////////////////////// -ScriptParameterClass::ScriptParameterClass (const ScriptParameterClass &src) - : m_ScriptName (NULL), - m_ScriptParams (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const ScriptParameterClass & -ScriptParameterClass::operator= (const ScriptParameterClass &src) -{ - m_ScriptName = src.m_ScriptName; - m_ScriptParams = src.m_ScriptParams; - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ScriptParameterClass::operator== (const ScriptParameterClass &src) -{ - bool retval = false; - - // - // Data valid? - // - if ( (m_ScriptName != NULL) && (src.m_ScriptName != NULL) && - (m_ScriptParams != NULL) && (src.m_ScriptParams != NULL)) - { - - // - // Simple string compares should workd - // - if ( (m_ScriptName->Compare (*(src.m_ScriptName)) == 0) && - (m_ScriptParams->Compare (*(src.m_ScriptParams)) == 0)) - { - retval = true; - } - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ScriptParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = ScriptParameterClass::operator== ((const ScriptParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -ScriptParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_SCRIPT)) { - (*m_ScriptName) = ((ScriptParameterClass &)src).Get_Script_Name (); - (*m_ScriptParams) = ((ScriptParameterClass &)src).Get_Params (); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of DefIDListParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// DefIDListParameterClass -// -///////////////////////////////////////////////////////////////////// -DefIDListParameterClass::DefIDListParameterClass (DynamicVectorClass *list) - : m_IDList (list), - m_ClassID (0), - m_SelectedClassID (NULL) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// DefIDListParameterClass -// -///////////////////////////////////////////////////////////////////// -DefIDListParameterClass::DefIDListParameterClass (const DefIDListParameterClass &src) - : m_IDList (NULL), - m_ClassID (0), - m_SelectedClassID (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const DefIDListParameterClass & -DefIDListParameterClass::operator= (const DefIDListParameterClass &src) -{ - m_IDList = src.m_IDList; - m_ClassID = src.m_ClassID; - m_SelectedClassID = src.m_SelectedClassID; - - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -DefIDListParameterClass::operator== (const DefIDListParameterClass &src) -{ - bool retval = false; - - // - // Data valid? - // - if ((m_IDList != NULL) && (src.m_IDList != NULL)) - { - // - // Class IDs the same? - // - if (m_ClassID == src.m_ClassID) { - - int count1 = m_IDList->Count (); - int count2 = src.m_IDList->Count (); - - // - // Are the lists the same? - // - retval = (count1 == count2); - for (int index = 0; (index < count1) && retval; index ++) { - int value1 = (*m_IDList)[index]; - int value2 = (*src.m_IDList)[index]; - retval &= (value1 == value2); - } - } - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -DefIDListParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = DefIDListParameterClass::operator== ((const DefIDListParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -DefIDListParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_DEFINITIONIDLIST)) { - DefIDListParameterClass real_src = (DefIDListParameterClass &)src; - - m_ClassID = real_src.m_ClassID; - (*m_IDList) = (*real_src.m_IDList); - - if (m_SelectedClassID != NULL && real_src.m_SelectedClassID != NULL) { - (*m_SelectedClassID) = (*real_src.m_SelectedClassID); - } - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of ZoneParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// ZoneParameterClass -// -///////////////////////////////////////////////////////////////////// -ZoneParameterClass::ZoneParameterClass (OBBoxClass *box) - : m_OBBox (box) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// ZoneParameterClass -// -///////////////////////////////////////////////////////////////////// -ZoneParameterClass::ZoneParameterClass (const ZoneParameterClass &src) - : m_OBBox (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const ZoneParameterClass & -ZoneParameterClass::operator= (const ZoneParameterClass &src) -{ - m_OBBox = src.m_OBBox; - - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ZoneParameterClass::operator== (const ZoneParameterClass &src) -{ - bool retval = false; - - // - // Are the OBBoxes the same? - // - if ((m_OBBox != NULL) && (src.m_OBBox != NULL)) { - retval = (*m_OBBox) == (*src.m_OBBox); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ZoneParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = ZoneParameterClass::operator== ((const ZoneParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -ZoneParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_ZONE)) { - ZoneParameterClass real_src = (ZoneParameterClass &)src; - - (*m_OBBox) = (*real_src.m_OBBox); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of FilenameListParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// FilenameListParameterClass -// -///////////////////////////////////////////////////////////////////// -FilenameListParameterClass::FilenameListParameterClass (DynamicVectorClass *list) - : m_FilenameList (list) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// FilenameListParameterClass -// -///////////////////////////////////////////////////////////////////// -FilenameListParameterClass::FilenameListParameterClass (const FilenameListParameterClass &src) - : m_FilenameList (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const FilenameListParameterClass & -FilenameListParameterClass::operator= (const FilenameListParameterClass &src) -{ - m_FilenameList = src.m_FilenameList; - - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -FilenameListParameterClass::operator== (const FilenameListParameterClass &src) -{ - bool retval = false; - - // - // Data valid? - // - if ((m_FilenameList != NULL) && (src.m_FilenameList != NULL)) - { - int count1 = m_FilenameList->Count (); - int count2 = src.m_FilenameList->Count (); - - // - // Are the lists the same? - // - retval = (count1 == count2); - for (int index = 0; (index < count1) && retval; index ++) { - StringClass &filename1 = (*m_FilenameList)[index]; - StringClass &filename2 = (*src.m_FilenameList)[index]; - retval &= (::stricmp (filename1, filename2) == 0); - } - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -FilenameListParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = FilenameListParameterClass::operator== ((const FilenameListParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -FilenameListParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_FILENAMELIST)) { - FilenameListParameterClass real_src = (FilenameListParameterClass &)src; - (*m_FilenameList) = (*real_src.m_FilenameList); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of ScriptListParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// ScriptListParameterClass -// -///////////////////////////////////////////////////////////////////// -ScriptListParameterClass::ScriptListParameterClass -( - DynamicVectorClass *name_list, - DynamicVectorClass *param_list -) - : m_NameList (name_list), - m_ParamList (param_list) -{ - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// ScriptListParameterClass -// -///////////////////////////////////////////////////////////////////// -ScriptListParameterClass::ScriptListParameterClass (const ScriptListParameterClass &src) - : m_NameList (NULL), - m_ParamList (NULL) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const ScriptListParameterClass & -ScriptListParameterClass::operator= (const ScriptListParameterClass &src) -{ - m_NameList = src.m_NameList; - m_ParamList = src.m_ParamList; - - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ScriptListParameterClass::operator== (const ScriptListParameterClass &src) -{ - bool retval = false; - - // - // Data valid? - // - if ( (m_NameList != NULL) && (src.m_NameList != NULL) && - (m_ParamList != NULL) && (src.m_ParamList != NULL)) - { - retval = Are_Lists_Identical (*m_NameList, *(src.m_NameList)); - retval &= Are_Lists_Identical (*m_ParamList, *(src.m_ParamList)); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Are_Lists_Identical -// -///////////////////////////////////////////////////////////////////// -bool -ScriptListParameterClass::Are_Lists_Identical -( - DynamicVectorClass &list1, - DynamicVectorClass &list2 -) -{ - int count1 = list1.Count (); - int count2 = list2.Count (); - - // - // Do a string compare on every entry - // - bool retval = (count1 == count2); - for (int index = 0; (index < count1) && retval; index ++) { - StringClass &string1 = list1[index]; - StringClass &string2 = list2[index]; - retval &= (::stricmp (string1, string2) == 0); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -ScriptListParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = ScriptListParameterClass::operator== ((const ScriptListParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -ScriptListParameterClass::Copy_Value (const ParameterClass &src) -{ - if (src.Is_Type (ParameterClass::TYPE_SCRIPTLIST)) { - ScriptListParameterClass &real_src = (ScriptListParameterClass &)src; - (*m_NameList) = (*real_src.m_NameList); - (*m_ParamList) = (*real_src.m_ParamList); - } - - ParameterClass::Copy_Value (src); - return ; -} - - -//*******************************************************************************************// -// -// Start of SeparatorParameterClass -// -//*******************************************************************************************// - - -///////////////////////////////////////////////////////////////////// -// -// SeparatorParameterClass -// -///////////////////////////////////////////////////////////////////// -SeparatorParameterClass::SeparatorParameterClass (const SeparatorParameterClass &src) -{ - (*this) = src; - return ; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator= -// -///////////////////////////////////////////////////////////////////// -const SeparatorParameterClass & -SeparatorParameterClass::operator= (const SeparatorParameterClass &src) -{ - ParameterClass::operator= (src); - return *this; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -SeparatorParameterClass::operator== (const SeparatorParameterClass &src) -{ - return true; -} - - -///////////////////////////////////////////////////////////////////// -// -// operator== -// -///////////////////////////////////////////////////////////////////// -bool -SeparatorParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - - if (src.Get_Type () == Get_Type ()) { - retval = SeparatorParameterClass::operator== ((const SeparatorParameterClass &)src); - } - - return retval; -} - - -///////////////////////////////////////////////////////////////////// -// -// Copy_Value -// -///////////////////////////////////////////////////////////////////// -void -SeparatorParameterClass::Copy_Value (const ParameterClass &src) -{ - ParameterClass::Copy_Value (src); - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h deleted file mode 100644 index da9780e6a4..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameter.h +++ /dev/null @@ -1,1161 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/parameter.h $* - * * - * Org Author:: Patrick Smith * - * * - * Author:: Kenny Mitchell * - * * - * $Modtime:: 5/29/02 11:00a $* - * * - * $Revision:: 38 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __PARAMETER_H -#define __PARAMETER_H - -#include "always.h" -#include -#include -#include "parametertypes.h" -#include "Vector.H" -#include "wwstring.h" -#include "bittype.h" -#include "obbox.h" - - -////////////////////////////////////////////////////////////////////////////////// -// Forward declarations -////////////////////////////////////////////////////////////////////////////////// -class DefParameterClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// ParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class ParameterClass -{ -public: - - typedef enum - { - TYPE_INT = 0, - TYPE_FLOAT, - TYPE_STRING, - TYPE_VECTOR3, - TYPE_MATRIX3D, - TYPE_BOOL, - TYPE_TRANSITION, - TYPE_MODELDEFINITIONID, - TYPE_FILENAME, - TYPE_ENUM, - TYPE_GAMEOBJDEFINITIONID, - TYPE_SCRIPT, - TYPE_SOUND_FILENAME, - TYPE_ANGLE, - TYPE_WEAPONOBJDEFINITIONID, - TYPE_AMMOOBJDEFINITIONID, - TYPE_SOUNDDEFINITIONID, - TYPE_COLOR, - TYPE_PHYSDEFINITIONID, - TYPE_EXPLOSIONDEFINITIONID, - TYPE_DEFINITIONIDLIST, - TYPE_ZONE, - TYPE_FILENAMELIST, - TYPE_SEPARATOR, - TYPE_GENERICDEFINITIONID, - TYPE_SCRIPTLIST, - TYPE_VECTOR2, - TYPE_RECT, - TYPE_TEXTURE_FILENAME, - TYPE_STRINGSDB_ID - - } Type; - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - ParameterClass (void); - ParameterClass (const ParameterClass &src); - virtual ~ParameterClass (void); - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const ParameterClass & operator= (const ParameterClass &src); - virtual bool operator== (const ParameterClass &src) = 0; - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // RTTI - virtual DefParameterClass * As_DefParameterClass (void) { return NULL; } - - // Type identification (see paramtypes.h in wwsaveload) - virtual Type Get_Type (void) const = 0; - virtual bool Is_Type (Type type) const { return false; } - - // Modification - virtual bool Is_Modifed (void) const { return IsModified; } - virtual void Set_Modified (bool onoff = true) { IsModified = onoff; } - - // Display name methods - virtual const char * Get_Name (void) const; - virtual void Set_Name (const char *new_name); - - // Units display methods - virtual const char * Get_Units_Name (void) const; - virtual void Set_Units_Name (const char *units_name); - - // Copy methods - virtual void Copy_Value (const ParameterClass &src) { }; - - ////////////////////////////////////////////////////////////////////////////// - // Static methods - ////////////////////////////////////////////////////////////////////////////// - - // Virtual constructor used to create a new instance of any parameter type - static ParameterClass * Construct (ParameterClass::Type type, void *data, const char *param_name); - -private: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - bool IsModified; - const char * m_Name; - StringClass m_UnitsName; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// ParameterClass -////////////////////////////////////////////////////////////////////////////////// -inline -ParameterClass::ParameterClass (void) - : m_Name (NULL), - IsModified (false) -{ - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// ParameterClass -////////////////////////////////////////////////////////////////////////////////// -inline -ParameterClass::ParameterClass (const ParameterClass &src) - : m_Name (NULL), - IsModified (false) -{ - (*this) = src; - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// ~ParameterClass -////////////////////////////////////////////////////////////////////////////////// -inline -ParameterClass::~ParameterClass (void) -{ - Set_Name (NULL); - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// operator= -////////////////////////////////////////////////////////////////////////////////// -inline const ParameterClass & -ParameterClass::operator= (const ParameterClass &src) -{ - IsModified = src.IsModified; - Set_Name (src.m_Name); - return *this; -} - -////////////////////////////////////////////////////////////////////////////////// -// Get_Name -////////////////////////////////////////////////////////////////////////////////// -inline const char * -ParameterClass::Get_Name (void) const -{ - return m_Name; -} - -////////////////////////////////////////////////////////////////////////////////// -// Set_Name -////////////////////////////////////////////////////////////////////////////////// -inline void -ParameterClass::Set_Name (const char *new_name) -{ - if (m_Name != NULL) { - ::free ((void *)m_Name); - m_Name = NULL; - } - - if (new_name != NULL) { - m_Name = ::strdup (new_name); - } - - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// Get_Units_Name -////////////////////////////////////////////////////////////////////////////////// -inline const char * -ParameterClass::Get_Units_Name (void) const -{ - return m_UnitsName; -} - -////////////////////////////////////////////////////////////////////////////////// -// Set_Units_Name -////////////////////////////////////////////////////////////////////////////////// -inline void -ParameterClass::Set_Units_Name (const char *new_name) -{ - m_UnitsName = new_name; - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// -// StringParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class StringParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - StringParameterClass (StringClass *string); - StringParameterClass (const StringParameterClass &src); - virtual ~StringParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const StringParameterClass & operator= (const StringParameterClass &src); - bool operator== (const StringParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_STRING; } - virtual bool Is_Type (Type type) const { return (type == TYPE_STRING) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual const char * Get_String (void) const; - virtual void Set_String (const char *string); - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - StringClass * m_String; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// FilenameParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class FilenameParameterClass : public StringParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - FilenameParameterClass (StringClass *string); - FilenameParameterClass (const FilenameParameterClass &src); - virtual ~FilenameParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const FilenameParameterClass & operator= (const FilenameParameterClass &src); - bool operator== (const FilenameParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_FILENAME; } - virtual bool Is_Type (Type type) const { return (type == TYPE_FILENAME) || StringParameterClass::Is_Type (type); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - - virtual void Set_Extension (const char *extension) { m_Extension = extension; } - virtual const char * Get_Extension (void) const { return m_Extension; } - - virtual void Set_Description (const char *desc) { m_Description = desc; } - virtual const char * Get_Description (void) const { return m_Description; } - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////////////////// - StringClass m_Extension; - StringClass m_Description; -}; - -////////////////////////////////////////////////////////////////////////////////// -// -// TextureFilenameParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class TextureFilenameParameterClass : public FilenameParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - TextureFilenameParameterClass(StringClass *string); - TextureFilenameParameterClass(const TextureFilenameParameterClass& src); - virtual ~TextureFilenameParameterClass() {} - - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_TEXTURE_FILENAME; } - virtual bool Is_Type (Type type) const { return (type == TYPE_TEXTURE_FILENAME) || StringParameterClass::Is_Type (type); } - - void Set_Show_Alpha(bool show) { Show_Alpha=show; } - bool Get_Show_Alpha() const { return Show_Alpha; } - - void Set_Show_Texture(bool show) { Show_Texture=show; } - bool Get_Show_Texture() const { return Show_Texture; } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - bool Show_Alpha; - bool Show_Texture; -}; - - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundFilenameParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class SoundFilenameParameterClass : public FilenameParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - SoundFilenameParameterClass (StringClass *string); - SoundFilenameParameterClass (const SoundFilenameParameterClass &src); - virtual ~SoundFilenameParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const SoundFilenameParameterClass & operator= (const SoundFilenameParameterClass &src); - bool operator== (const SoundFilenameParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_SOUND_FILENAME; } - virtual bool Is_Type (Type type) const { return (type == TYPE_SOUND_FILENAME) || FilenameParameterClass::Is_Type (type); } -}; - -////////////////////////////////////////////////////////////////////////////////// -// -// EnumParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class EnumParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - EnumParameterClass (int *value); - EnumParameterClass (const EnumParameterClass &src); - virtual ~EnumParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const EnumParameterClass & operator= (const EnumParameterClass &src); - bool operator== (const EnumParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_ENUM; } - virtual bool Is_Type (Type type) const { return (type == TYPE_ENUM) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void __cdecl Add_Values (const char *first_name, int first_value, ...); - virtual void Add_Value (const char *display_name, int value); - virtual int Get_Count (void) const { return m_List.Count (); } - virtual const char * Get_Entry_Name (int index) const { return m_List[index].name; } - virtual int Get_Entry_Value (int index) const { return m_List[index].value; } - - virtual void Set_Selected_Value (int value) { (*m_Value) = value; Set_Modified (); } - virtual int Get_Selected_Value (void) const { return (*m_Value); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private data types - ////////////////////////////////////////////////////////////////////////////// - typedef struct _ENUM_VALUE - { - StringClass name; - int value; - - _ENUM_VALUE (const char *_name=NULL, int _value=0) : name (_name), value (_value) {} - bool operator== (const _ENUM_VALUE &) { return false; } - bool operator!= (const _ENUM_VALUE &) { return true; } - } ENUM_VALUE; - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - DynamicVectorClass m_List; - int * m_Value; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// PhysDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class PhysDefParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - PhysDefParameterClass (int *id); - PhysDefParameterClass (const PhysDefParameterClass &src); - virtual ~PhysDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const PhysDefParameterClass & operator= (const PhysDefParameterClass &src); - bool operator== (const PhysDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_PHYSDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_PHYSDEFINITIONID) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void Set_Value (int id) { (*m_Value) = id; Set_Modified (); } - virtual int Get_Value (void) const { return (*m_Value); } - virtual void Set_Base_Class (const char *name) { m_BaseClass = name; } - virtual const char * Get_Base_Class (void) const { return m_BaseClass; } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - int * m_Value; - StringClass m_BaseClass; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// ModelDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class ModelDefParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - ModelDefParameterClass (int *id); - ModelDefParameterClass (const ModelDefParameterClass &src); - virtual ~ModelDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const ModelDefParameterClass & operator= (const ModelDefParameterClass &src); - bool operator== (const ModelDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_MODELDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_MODELDEFINITIONID) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void Set_Value (int id) { (*m_Value) = id; Set_Modified (); } - virtual int Get_Value (void) const { return (*m_Value); } - virtual void Set_Base_Class (const char *name) { m_BaseClass = name; } - virtual const char * Get_Base_Class (void) const { return m_BaseClass; } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - int * m_Value; - StringClass m_BaseClass; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// DefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class DefParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - DefParameterClass (int *id); - DefParameterClass (const DefParameterClass &src); - virtual ~DefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const DefParameterClass & operator= (const DefParameterClass &src); - bool operator== (const DefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // RTTI - virtual DefParameterClass * As_DefParameterClass (void) { return this; } - - // Data manipulation - virtual void Set_Value (int id) { (*m_Value) = id; Set_Modified (); } - virtual int Get_Value (void) const { return (*m_Value); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - int * m_Value; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// GenericDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class GenericDefParameterClass : public DefParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - GenericDefParameterClass (int *id); - GenericDefParameterClass (const GenericDefParameterClass &src); - virtual ~GenericDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const GenericDefParameterClass & operator= (const GenericDefParameterClass &src); - bool operator== (const GenericDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_GENERICDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_GENERICDEFINITIONID) || ParameterClass::Is_Type (type); } - - // Class ID control - virtual void Set_Class_ID (int class_id) { m_ClassID = class_id; Set_Modified (); } - virtual int Get_Class_ID (void) const { return m_ClassID; } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - int m_ClassID; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// GameObjDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class GameObjDefParameterClass : public DefParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - GameObjDefParameterClass (int *id); - GameObjDefParameterClass (const GameObjDefParameterClass &src); - virtual ~GameObjDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const GameObjDefParameterClass & operator= (const GameObjDefParameterClass &src); - bool operator== (const GameObjDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_GAMEOBJDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_GAMEOBJDEFINITIONID) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void Set_Base_Class (const char *name) { m_BaseClass = name; Set_Modified (); } - virtual const char * Get_Base_Class (void) const { return m_BaseClass; } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - StringClass m_BaseClass; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// AmmoObjDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class AmmoObjDefParameterClass : public GameObjDefParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - AmmoObjDefParameterClass (int *id); - AmmoObjDefParameterClass (const AmmoObjDefParameterClass &src); - virtual ~AmmoObjDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const AmmoObjDefParameterClass & operator= (const AmmoObjDefParameterClass &src); - bool operator== (const AmmoObjDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_AMMOOBJDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_AMMOOBJDEFINITIONID) || GameObjDefParameterClass::Is_Type (type); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// WeaponObjDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class WeaponObjDefParameterClass : public GameObjDefParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - WeaponObjDefParameterClass (int *id); - WeaponObjDefParameterClass (const WeaponObjDefParameterClass &src); - virtual ~WeaponObjDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const WeaponObjDefParameterClass & operator= (const WeaponObjDefParameterClass &src); - bool operator== (const WeaponObjDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_WEAPONOBJDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_WEAPONOBJDEFINITIONID) || GameObjDefParameterClass::Is_Type (type); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// ExplosionObjDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class ExplosionObjDefParameterClass : public GameObjDefParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - ExplosionObjDefParameterClass (int *id); - ExplosionObjDefParameterClass (const ExplosionObjDefParameterClass &src); - virtual ~ExplosionObjDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const ExplosionObjDefParameterClass & operator= (const ExplosionObjDefParameterClass &src); - bool operator== (const ExplosionObjDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_EXPLOSIONDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_EXPLOSIONDEFINITIONID) || GameObjDefParameterClass::Is_Type (type); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); -}; - - - -////////////////////////////////////////////////////////////////////////////////// -// -// SoundDefParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class SoundDefParameterClass : public DefParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - SoundDefParameterClass (int *id); - SoundDefParameterClass (const SoundDefParameterClass &src); - virtual ~SoundDefParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const SoundDefParameterClass & operator= (const SoundDefParameterClass &src); - bool operator== (const SoundDefParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_SOUNDDEFINITIONID; } - virtual bool Is_Type (Type type) const { return (type == TYPE_SOUNDDEFINITIONID) || ParameterClass::Is_Type (type); } -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// ScriptParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class ScriptParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - ScriptParameterClass (StringClass *name, StringClass *params); - ScriptParameterClass (const ScriptParameterClass &src); - virtual ~ScriptParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const ScriptParameterClass & operator= (const ScriptParameterClass &src); - bool operator== (const ScriptParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_SCRIPT; } - virtual bool Is_Type (Type type) const { return (type == TYPE_SCRIPT) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void Set_Script_Name (const char *name) { (*m_ScriptName) = name; Set_Modified (); } - virtual const char * Get_Script_Name (void) const { return (*m_ScriptName); } - virtual void Set_Params (const char *params) { (*m_ScriptParams) = params; Set_Modified (); } - virtual const char * Get_Params (void) const { return (*m_ScriptParams); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - StringClass * m_ScriptName; - StringClass * m_ScriptParams; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// DefIDListParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class DefIDListParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - DefIDListParameterClass (DynamicVectorClass *list); - DefIDListParameterClass (const DefIDListParameterClass &src); - virtual ~DefIDListParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const DefIDListParameterClass & operator= (const DefIDListParameterClass &src); - bool operator== (const DefIDListParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_DEFINITIONIDLIST; } - virtual bool Is_Type (Type type) const { return (type == TYPE_DEFINITIONIDLIST) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void Set_Selected_Class_ID (uint32 *id) { m_SelectedClassID = id; } - virtual uint32 * Get_Selected_Class_ID (void) const { return m_SelectedClassID; } - virtual void Set_Class_ID (uint32 id) { m_ClassID = id; } - virtual uint32 Get_Class_ID (void) const { return m_ClassID; } - - virtual DynamicVectorClass &Get_List (void) const { return (*m_IDList); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - DynamicVectorClass * m_IDList; - uint32 m_ClassID; - uint32 * m_SelectedClassID; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// ZoneParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class ZoneParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - ZoneParameterClass (OBBoxClass *box); - ZoneParameterClass (const ZoneParameterClass &src); - virtual ~ZoneParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const ZoneParameterClass & operator= (const ZoneParameterClass &src); - bool operator== (const ZoneParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_ZONE; } - virtual bool Is_Type (Type type) const { return (type == TYPE_ZONE) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual void Set_Zone (const OBBoxClass &box) { (*m_OBBox) = box; Set_Modified (); } - virtual const OBBoxClass & Get_Zone (void) const { return (*m_OBBox); } - - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - OBBoxClass *m_OBBox; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// FilenameListParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class FilenameListParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - FilenameListParameterClass (DynamicVectorClass *list); - FilenameListParameterClass (const FilenameListParameterClass &src); - virtual ~FilenameListParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const FilenameListParameterClass & operator= (const FilenameListParameterClass &src); - bool operator== (const FilenameListParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_FILENAMELIST; } - virtual bool Is_Type (Type type) const { return (type == TYPE_FILENAMELIST) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual DynamicVectorClass &Get_List (void) const { return (*m_FilenameList); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - DynamicVectorClass * m_FilenameList; -}; - - - -////////////////////////////////////////////////////////////////////////////////// -// -// ScriptListParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class ScriptListParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - ScriptListParameterClass (DynamicVectorClass *name_list, DynamicVectorClass *param_list); - ScriptListParameterClass (const ScriptListParameterClass &src); - virtual ~ScriptListParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const ScriptListParameterClass & operator= (const ScriptListParameterClass &src); - bool operator== (const ScriptListParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_SCRIPTLIST; } - virtual bool Is_Type (Type type) const { return (type == TYPE_SCRIPTLIST) || ParameterClass::Is_Type (type); } - - // Data manipulation - virtual DynamicVectorClass &Get_Name_List (void) const { return (*m_NameList); } - virtual DynamicVectorClass &Get_Param_List (void) const { return (*m_ParamList); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); - -protected: - - ////////////////////////////////////////////////////////////////////////////// - // Protected members - ////////////////////////////////////////////////////////////////////////////// - bool Are_Lists_Identical (DynamicVectorClass &list1, DynamicVectorClass &list2); - - ////////////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////////////// - DynamicVectorClass * m_NameList; - DynamicVectorClass * m_ParamList; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// SeparatorParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -class SeparatorParameterClass : public ParameterClass -{ -public: - - ////////////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////////////// - SeparatorParameterClass (void) {} - SeparatorParameterClass (const SeparatorParameterClass &src); - virtual ~SeparatorParameterClass (void) {} - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - const SeparatorParameterClass & operator= (const SeparatorParameterClass &src); - bool operator== (const SeparatorParameterClass &src); - bool operator== (const ParameterClass &src); - - ////////////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////////////// - - // Type identification - virtual Type Get_Type (void) const { return TYPE_SEPARATOR; } - virtual bool Is_Type (Type type) const { return (type == TYPE_SEPARATOR) || ParameterClass::Is_Type (type); } - - // Copy methods - virtual void Copy_Value (const ParameterClass &src); -}; - - -#endif //__PARAMETER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h deleted file mode 100644 index 6bf0250994..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parameterlist.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/parameterlist.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 10/06/99 2:52p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - - - -#ifndef __PARAMETER_LIST_H -#define __PARAMETER_LIST_H - -#include "always.h" -#include "Vector.H" -#include "parameter.h" -#include "wwdebug.h" - -////////////////////////////////////////////////////////////////////////////////// -// -// ParameterListClass -// -////////////////////////////////////////////////////////////////////////////////// -class ParameterListClass : public DynamicVectorClass -{ - using DynamicVectorClass::Vector; - -public: - - ///////////////////////////////////////////////////////////////////// - // Public constructurs/destructors - ///////////////////////////////////////////////////////////////////// - ~ParameterListClass (void); - - ///////////////////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////////////////// - void Add (void *data, const char *param_name, ParameterClass::Type type); - void Add (ParameterClass *parameter); - -protected: - - ///////////////////////////////////////////////////////////////////// - // Protected methods - ///////////////////////////////////////////////////////////////////// - void Free_Parameters (void); - -private: - - ///////////////////////////////////////////////////////////////////// - // Private member data - ///////////////////////////////////////////////////////////////////// - //DynamicVectorClass m_Parameters; -}; - - -///////////////////////////////////////////////////////////////////// -// ~ParameterListClass -///////////////////////////////////////////////////////////////////// -inline -ParameterListClass::~ParameterListClass (void) -{ - Free_Parameters (); - return ; -} - -///////////////////////////////////////////////////////////////////// -// Add -///////////////////////////////////////////////////////////////////// -inline void -ParameterListClass::Add (void *data, const char *param_name, ParameterClass::Type type) -{ - // - // Create a new parameter object - // - ParameterClass *new_param = ParameterClass::Construct (type, data, param_name); - - // - // Add the new paramter object to our list - // - WWASSERT (new_param != NULL); - if (new_param != NULL) { - DynamicVectorClass::Add (new_param); - } - - return ; -} - -///////////////////////////////////////////////////////////////////// -// Add -///////////////////////////////////////////////////////////////////// -inline void -ParameterListClass::Add (ParameterClass *new_param) -{ - // - // Add the new paramter object to our list - // - if (new_param != NULL) { - DynamicVectorClass::Add (new_param); - } - - return ; -} - -///////////////////////////////////////////////////////////////////// -// Free_Parameters -///////////////////////////////////////////////////////////////////// -inline void -ParameterListClass::Free_Parameters (void) -{ - for (int index = 0; index < Count (); index ++) { - ParameterClass *param = Vector[index]; - - // - // Free the parameter object - // - if (param != NULL) { - delete param; - } - } - - Delete_All(); -// m_Parameters.Delete_All (); - return ; -} - - -#endif //__PARAMETER_LIST_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h deleted file mode 100644 index 2a6921bdef..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/parametertypes.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/parametertypes.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 9/10/99 3:38p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - - -#ifndef __PARAMETER_TYPES_H -#define __PARAMETER_TYPES_H - -#include "always.h" - -////////////////////////////////////////////////////////////////////////////////// -// -// ParameterType -// -////////////////////////////////////////////////////////////////////////////////// -/*typedef enum -{ - TYPE_INT = 0, - TYPE_FLOAT, - TYPE_STRING, - TYPE_VECTOR3, - TYPE_MATRIX3D, - TYPE_TRANSITION, - TYPE_PRESETID, - TYPE_MODELFILENAME - -} ParameterType;*/ - - -#endif //__PARAMETER_TYPES_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persist.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persist.h deleted file mode 100644 index f9cefd727c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persist.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/persist.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/04/01 8:42p $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef PERSIST_H -#define PERSIST_H - -#include "always.h" -#include "refcount.h" -#include "postloadable.h" - -class PersistFactoryClass; -class ChunkSaveClass; -class ChunkLoadClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// PersistClass -// -// PersistClass defines the interface for an object to the save load system. -// Each concrete derived type of PersistClass must have an associated -// PersistFactoryClass that basically maps a chunk_id to a constructor, -// a save function, a load function, and a on_post_load function (taken from -// PostLoadableClass ) -// -////////////////////////////////////////////////////////////////////////////////// -class PersistClass : public PostLoadableClass -{ -public: - - virtual const PersistFactoryClass & Get_Factory (void) const = 0; - virtual bool Save (ChunkSaveClass &csave) { return true; } - virtual bool Load (ChunkLoadClass &cload) { return true; } - -}; - - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp deleted file mode 100644 index 36c6725244..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/persistfactory.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 9/09/99 9:50a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "persistfactory.h" -#include "saveload.h" - -PersistFactoryClass::PersistFactoryClass(void) : - NextFactory(NULL) -{ - SaveLoadSystemClass::Register_Persist_Factory(this); -} - -PersistFactoryClass::~PersistFactoryClass(void) -{ - SaveLoadSystemClass::Unregister_Persist_Factory(this); -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h deleted file mode 100644 index d882257905..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/persistfactory.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/persistfactory.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/04/01 8:42p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - - - -#ifndef PERSISTFACTORY_H -#define PERSISTFACTORY_H - -#include "always.h" -#include "bittype.h" -#include "chunkio.h" -#include "wwdebug.h" -#include "saveload.h" -#include "persist.h" - -/* -** PersistFactoryClass -** Create a PersistFactoryClass for each concrete derived PersistClass. These -** factories automatically register with the SaveLoadSystem in their constructors -** and should be accessible through the virtual Get_Factory method of any -** derived PersistClass. -*/ - -class PersistFactoryClass -{ -public: - - PersistFactoryClass(void); - virtual ~PersistFactoryClass(void); - - virtual uint32 Chunk_ID(void) const = 0; - virtual PersistClass * Load(ChunkLoadClass & cload) const = 0; - virtual void Save(ChunkSaveClass & csave,PersistClass * obj) const = 0; - -private: - - PersistFactoryClass * NextFactory; - friend class SaveLoadSystemClass; -}; - - - - -/* -** SimplePersistFactoryClass -** This template automates the creation of a PersistFactory for any type of Persist -** object. Simply instantiate a single static instance of this template with the -** type and chunkid in the .cpp file of your class. -*/ -template class SimplePersistFactoryClass : public PersistFactoryClass -{ -public: - - virtual uint32 Chunk_ID(void) const { return CHUNKID; } - virtual PersistClass * Load(ChunkLoadClass & cload) const; - virtual void Save(ChunkSaveClass & csave,PersistClass * obj) const; - - /* - ** Internal chunk id's - */ - enum - { - SIMPLEFACTORY_CHUNKID_OBJPOINTER = 0x00100100, - SIMPLEFACTORY_CHUNKID_OBJDATA - }; -}; - - -template PersistClass * -SimplePersistFactoryClass::Load(ChunkLoadClass & cload) const -{ - T * new_obj = W3DNEW T; - T * old_obj = NULL; - - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == SIMPLEFACTORY_CHUNKID_OBJPOINTER); - cload.Read(&old_obj,sizeof(T *)); - cload.Close_Chunk(); - - cload.Open_Chunk(); - WWASSERT(cload.Cur_Chunk_ID() == SIMPLEFACTORY_CHUNKID_OBJDATA); - new_obj->Load(cload); - cload.Close_Chunk(); - - SaveLoadSystemClass::Register_Pointer(old_obj,new_obj); - return new_obj; -} - - -template void -SimplePersistFactoryClass::Save(ChunkSaveClass & csave,PersistClass * obj) const -{ - uint32 objptr = (uint32)obj; - csave.Begin_Chunk(SIMPLEFACTORY_CHUNKID_OBJPOINTER); - csave.Write(&objptr,sizeof(uint32)); - csave.End_Chunk(); - - csave.Begin_Chunk(SIMPLEFACTORY_CHUNKID_OBJDATA); - obj->Save(csave); - csave.End_Chunk(); -} - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp deleted file mode 100644 index 952667b8cf..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/pointerremap.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/09/01 11:36a $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "pointerremap.h" -#include "refcount.h" -#include "wwdebug.h" - - -const int POINTER_TABLES_GROWTH_STEP = 4096; - - -PointerRemapClass::PointerRemapClass(void) -{ - PointerPairTable.Set_Growth_Step(POINTER_TABLES_GROWTH_STEP); - PointerRequestTable.Set_Growth_Step(POINTER_TABLES_GROWTH_STEP); - RefCountRequestTable.Set_Growth_Step(POINTER_TABLES_GROWTH_STEP); -} - -PointerRemapClass::~PointerRemapClass(void) -{ -} - -void PointerRemapClass::Reset(void) -{ - PointerPairTable.Delete_All(); - PointerRequestTable.Delete_All(); - RefCountRequestTable.Delete_All(); -} - -void PointerRemapClass::Process(void) -{ - if ( PointerPairTable.Count() > 0 ) { - qsort(&PointerPairTable[0], PointerPairTable.Count(), sizeof(PointerPairTable[0]), ptr_pair_compare_function); - } - - if ( PointerRequestTable.Count() > 0 ) { - WWASSERT( PointerPairTable.Count() > 0 ); - qsort(&PointerRequestTable[0],PointerRequestTable.Count(), sizeof(PointerRequestTable[0]), ptr_request_compare_function); - Process_Request_Table(PointerRequestTable,false); - } - - // remap the ref-counted pointers - if ( RefCountRequestTable.Count() > 0 ) { - WWASSERT( PointerPairTable.Count() > 0 ); - qsort(&RefCountRequestTable[0],RefCountRequestTable.Count(), sizeof(RefCountRequestTable[0]), ptr_request_compare_function); - Process_Request_Table(RefCountRequestTable,true); - } -} - -void PointerRemapClass::Process_Request_Table(DynamicVectorClass & request_table,bool refcount) -{ - // Remap the pointers - int pointer_index = 0; - int pair_index = 0; - - for (pointer_index = 0; pointer_index < request_table.Count(); pointer_index++) { - - void * pointer_to_remap = *(request_table[pointer_index].PointerToRemap); - int pre_search_index = pair_index; - - // Find the pair which contains the pointer we are looking for as its "old" pointer - while ( (pair_index < PointerPairTable.Count()) && - (PointerPairTable[pair_index].OldPointer < pointer_to_remap) ) - { - pair_index++; - } - - if ((pair_index < PointerPairTable.Count()) && (PointerPairTable[pair_index].OldPointer == pointer_to_remap)) { - - // we found the match, plug in the new pointer and add a ref if needed. - *request_table[pointer_index].PointerToRemap = PointerPairTable[pair_index].NewPointer; - - if (refcount) { - RefCountClass * refptr = (RefCountClass *)(*request_table[pointer_index].PointerToRemap); - refptr->Add_Ref(); - } - - } else { - - // Failed to re-map the pointer. - // warn the user, set pointer to NULL, reset index to the pre_search_index. - // If this happens, things could be going very wrong. (find out why its happening!) - pair_index = pre_search_index; - *request_table[pointer_index].PointerToRemap = NULL; -#ifdef WWDEBUG - const char * file = request_table[pointer_index].File; - int line = request_table[pointer_index].Line; - WWDEBUG_SAY(("Warning! Failed to re-map pointer! old_ptr = 0x%X file = %s line = %d\r\n",(unsigned int)pointer_to_remap,file,line)); - WWASSERT( 0 ); -#endif - } - } -} - -void PointerRemapClass::Register_Pointer (void *old_pointer, void *new_pointer) -{ - PointerPairTable.Add(PtrPairStruct(old_pointer,new_pointer)); -} - -#ifdef WWDEBUG -void PointerRemapClass::Request_Pointer_Remap(void **pointer_to_convert,const char * file,int line) -{ - PtrRemapStruct remap; - remap.PointerToRemap = pointer_to_convert; - remap.File = file; - remap.Line = line; - PointerRequestTable.Add(remap); -} - -void PointerRemapClass::Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert,const char * file, int line) -{ - PtrRemapStruct remap; - remap.PointerToRemap = (void**)pointer_to_convert; - remap.File = file; - remap.Line = line; - RefCountRequestTable.Add(remap); -} - -#else - -void PointerRemapClass::Request_Pointer_Remap (void **pointer_to_convert) -{ - PtrRemapStruct remap; - remap.PointerToRemap = pointer_to_convert; - PointerRequestTable.Add(remap); -} - -void PointerRemapClass::Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert) -{ - PtrRemapStruct remap; - remap.PointerToRemap = (void**)pointer_to_convert; - RefCountRequestTable.Add(remap); -} - -#endif - -/* -** sort compare function for pointer pair structures -** sorts by the old pointer value -*/ -int __cdecl PointerRemapClass::ptr_pair_compare_function(void const * ptr1, void const * ptr2) -{ - void * old1 = ((PointerRemapClass::PtrPairStruct const *)ptr1)->OldPointer; - void * old2 = ((PointerRemapClass::PtrPairStruct const *)ptr2)->OldPointer; - - if (old1 == old2) { - return(0); - } - if (old1 < old2) { - return(-1); - } - return(1); -} - -/* -** sort compare function for pointer remap structures -** sorts by the old pointer value -*/ -int __cdecl PointerRemapClass::ptr_request_compare_function(void const * ptr1, void const * ptr2) -{ - PtrRemapStruct * remap1 = (PtrRemapStruct *)ptr1; - PtrRemapStruct * remap2 = (PtrRemapStruct *)ptr2; - - void * old1 = *(remap1->PointerToRemap); - void * old2 = *(remap2->PointerToRemap); - - if (old1 == old2) { - return(0); - } - if (old1 < old2) { - return(-1); - } - return(1); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h deleted file mode 100644 index 94f431898a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/pointerremap.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/pointerremap.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 4/30/01 1:54p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef POINTERREMAP_H -#define POINTERREMAP_H - -#ifdef _UNIX -#include "osdep/osdep.h" -#endif - -#include "always.h" -#include "Vector.H" - -class RefCountClass; - - -class PointerRemapClass -{ - public: - - PointerRemapClass(void); - ~PointerRemapClass(void); - - void Reset(void); - void Process(void); - - void Register_Pointer (void *old_pointer, void *new_pointer); - -#ifdef WWDEBUG - void Request_Pointer_Remap (void **pointer_to_convert,const char * file,int line); - void Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert,const char * file, int line); -#else - void Request_Pointer_Remap (void **pointer_to_convert); - void Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert); -#endif - - private: - - struct PtrPairStruct - { - PtrPairStruct(void) {} - PtrPairStruct(void * oldptr,void * newptr) : OldPointer(oldptr),NewPointer(newptr) {} - bool operator == (const PtrPairStruct & that) { return ((OldPointer == that.OldPointer) && (NewPointer == that.NewPointer)); } - bool operator != (const PtrPairStruct & that) { return !(*this == that); } - - void * OldPointer; - void * NewPointer; - }; - - struct PtrRemapStruct - { - PtrRemapStruct(void) {} - bool operator == (const PtrRemapStruct & that) { return (PointerToRemap == that.PointerToRemap); } - bool operator != (const PtrRemapStruct & that) { return !(*this == that); } - - void ** PointerToRemap; -#ifdef WWDEBUG - const char * File; - int Line; -#endif - }; - - void Process_Request_Table(DynamicVectorClass & request_table,bool refcount); - static int __cdecl ptr_pair_compare_function(void const * ptr1, void const * ptr2); - static int __cdecl ptr_request_compare_function(void const * ptr1, void const * ptr2); - - /* - ** Array of pointers associated with ID values to assist in swizzling. - */ - DynamicVectorClass PointerPairTable; - DynamicVectorClass PointerRequestTable; - DynamicVectorClass RefCountRequestTable; -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h deleted file mode 100644 index 90c3ccbf71..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/postloadable.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/postloadable.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/09/01 11:46a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef POSTLOADABLE_H -#define POSTLOADABLE_H - - -////////////////////////////////////////////////////////////////////////////////// -// -// PostLoadableClass -// -// PostLoadableClass allows a lower level for non-Persist objects to On_Post_Load -// without requiring Get_Factory or other requirements of PersistClass. Objects -// derived from this class can be added to the post-load list in the SaveLoadSystem -// -////////////////////////////////////////////////////////////////////////////////// -class PostLoadableClass -{ -public: - PostLoadableClass(void) : IsPostLoadRegistered(false) { } - virtual ~PostLoadableClass(void) { } - - virtual void On_Post_Load (void) { } - - bool Is_Post_Load_Registered(void) { return IsPostLoadRegistered; } - void Set_Post_Load_Registered(bool onoff) { IsPostLoadRegistered = onoff; } - -private: - - bool IsPostLoadRegistered; -}; - - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp deleted file mode 100644 index 8923fc6ee2..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/saveload.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 12/09/01 6:42p $* - * * - * $Revision:: 19 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "saveload.h" -#include "saveloadsubsystem.h" -#include "persist.h" -#include "persistfactory.h" -#include "chunkio.h" -#include "wwdebug.h" -#include "saveloadstatus.h" -#include "wwhack.h" -#include "wwprofile.h" - -#pragma warning(disable:4201) // warning C4201: nonstandard extension used : nameless struct/union -#include -#include "systimer.h" - - -SaveLoadSubSystemClass * SaveLoadSystemClass::SubSystemListHead = NULL; -PersistFactoryClass * SaveLoadSystemClass::FactoryListHead = NULL; -SList SaveLoadSystemClass::PostLoadList; -PointerRemapClass SaveLoadSystemClass::PointerRemapper; - - - -bool SaveLoadSystemClass::Save (ChunkSaveClass &csave,SaveLoadSubSystemClass & subsystem) -{ - bool ok = true; - - if (subsystem.Contains_Data()) { - csave.Begin_Chunk (subsystem.Chunk_ID ()); - ok &= subsystem.Save (csave); - csave.End_Chunk (); - } - - return ok; -} - -bool SaveLoadSystemClass::Load (ChunkLoadClass &cload,bool auto_post_load) -{ - PointerRemapper.Reset(); - bool ok = true; - - // Load each chunk we encounter and link the manager into the PostLoad list - while (cload.Open_Chunk ()) { - SaveLoadStatus::Inc_Status_Count(); // Count the sub systems loaded - SaveLoadSubSystemClass *sys = Find_Sub_System(cload.Cur_Chunk_ID ()); - if (sys != NULL) { -//WWRELEASE_SAY((" Name: %s\n",sys->Name())); - INIT_SUB_STATUS(sys->Name()); - ok &= sys->Load(cload); - } - cload.Close_Chunk(); - } - - // Process all of the pointer remap requests - PointerRemapper.Process(); - PointerRemapper.Reset(); - - // Call PostLoad on each PersistClass that wanted post-load - if (auto_post_load) { - Post_Load_Processing(NULL); - } - - return ok; -} - -// Nework update macro for post loader. -#define UPDATE_NETWORK \ - if (network_callback) { \ - unsigned long time2 = TIMEGETTIME(); \ - if (time2 - time > 20) { \ - network_callback(); \ - time = time2; \ - } \ - } \ - -bool SaveLoadSystemClass::Post_Load_Processing (void(*network_callback)(void)) -{ - unsigned long time = TIMEGETTIME(); - - // Call PostLoad on each PersistClass that wanted post-load - PostLoadableClass * obj = PostLoadList.Remove_Head(); - while (obj) { - UPDATE_NETWORK; - obj->On_Post_Load(); - obj->Set_Post_Load_Registered(false); - obj = PostLoadList.Remove_Head(); - } - - return true; -} - -void SaveLoadSystemClass::Register_Sub_System (SaveLoadSubSystemClass * sys) -{ - WWASSERT(sys != NULL); - Link_Sub_System(sys); -} - - -void SaveLoadSystemClass::Unregister_Sub_System (SaveLoadSubSystemClass * sys) -{ - WWASSERT(sys != NULL); - Unlink_Sub_System(sys); -} - - -SaveLoadSubSystemClass * SaveLoadSystemClass::Find_Sub_System (uint32 chunk_id) -{ - // TODO: need a d-s that gives fast searching based on chunk_id!! - SaveLoadSubSystemClass * sys; - for ( sys = SubSystemListHead; sys != NULL; sys = sys->NextSubSystem ) { - if ( sys->Chunk_ID() == chunk_id ) { - break; - } - } - return sys; -} - -void SaveLoadSystemClass::Register_Persist_Factory(PersistFactoryClass * factory) -{ - WWASSERT(factory != NULL); - Link_Factory(factory); -} - -void SaveLoadSystemClass::Unregister_Persist_Factory(PersistFactoryClass * factory) -{ - WWASSERT(factory != NULL); - Unlink_Factory(factory); -} - -PersistFactoryClass * SaveLoadSystemClass::Find_Persist_Factory(uint32 chunk_id) -{ - // TODO: need a d-s that gives fast searching based on chunk_id!! - PersistFactoryClass * fact; - for ( fact = FactoryListHead; fact != NULL; fact = fact->NextFactory ) { - if ( fact->Chunk_ID() == chunk_id ) { - break; - } - } - return fact; -} - -bool SaveLoadSystemClass::Is_Post_Load_Callback_Registered(PostLoadableClass * obj) -{ - // obsolete! - bool retval = false; - - SLNode *list_node = NULL; - for ( list_node = PostLoadList.Head(); - retval == false && list_node != NULL; - list_node = list_node->Next()) - { - retval = (list_node->Data() == obj); - } - - return retval; -} - -void SaveLoadSystemClass::Register_Post_Load_Callback(PostLoadableClass * obj) -{ - WWASSERT(obj != NULL); - if (!obj->Is_Post_Load_Registered()) { - obj->Set_Post_Load_Registered(true); - PostLoadList.Add_Head(obj); - } -} - -void SaveLoadSystemClass::Register_Pointer (void *old_pointer, void *new_pointer) -{ - PointerRemapper.Register_Pointer(old_pointer,new_pointer); -} - -#ifdef WWDEBUG - -void SaveLoadSystemClass::Request_Pointer_Remap (void **pointer_to_convert,const char * file,int line) -{ - PointerRemapper.Request_Pointer_Remap(pointer_to_convert,file,line); -} - -void SaveLoadSystemClass::Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert,const char * file,int line) -{ - PointerRemapper.Request_Ref_Counted_Pointer_Remap(pointer_to_convert,file,line); -} - -#else - -void SaveLoadSystemClass::Request_Pointer_Remap (void **pointer_to_convert) -{ - PointerRemapper.Request_Pointer_Remap(pointer_to_convert); -} - -void SaveLoadSystemClass::Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert) -{ - PointerRemapper.Request_Ref_Counted_Pointer_Remap(pointer_to_convert); -} - -#endif - -void SaveLoadSystemClass::Link_Sub_System(SaveLoadSubSystemClass * sys) -{ - WWASSERT(sys != NULL); - if (sys != NULL) { - WWASSERT(sys->NextSubSystem == NULL); // sys should never be registered twice! - sys->NextSubSystem = SubSystemListHead; - SubSystemListHead = sys; - } -} - -void SaveLoadSystemClass::Unlink_Sub_System(SaveLoadSubSystemClass * sys) -{ - WWASSERT(sys != NULL); - SaveLoadSubSystemClass * cursys = SubSystemListHead; - SaveLoadSubSystemClass * prev = NULL; - - while (cursys != sys) { - prev = cursys; - cursys = cursys->NextSubSystem; - } - - if (prev == NULL) { - SubSystemListHead = sys->NextSubSystem; - } else { - prev->NextSubSystem = sys->NextSubSystem; - } - - sys->NextSubSystem = NULL; -} - - -void SaveLoadSystemClass::Link_Factory(PersistFactoryClass * fact) -{ - WWASSERT(fact != NULL); - if (fact != NULL) { - WWASSERT(fact->NextFactory == NULL); // factories should never be registered twice! - fact->NextFactory = FactoryListHead; - FactoryListHead = fact; - } -} - -void SaveLoadSystemClass::Unlink_Factory(PersistFactoryClass * fact) -{ - WWASSERT(fact != NULL); - - PersistFactoryClass * curfact = FactoryListHead; - PersistFactoryClass * prev = NULL; - - while (curfact != fact) { - prev = curfact; - curfact = curfact->NextFactory; - } - - if (prev == NULL) { - FactoryListHead = fact->NextFactory; - } else { - prev->NextFactory = fact->NextFactory; - } - - fact->NextFactory = NULL; -} - -void Force_Link_WWSaveLoad (void) -{ - FORCE_LINK( Twiddler ); - return ; -} \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.h deleted file mode 100644 index df6be42d48..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveload.h +++ /dev/null @@ -1,223 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/saveload.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 9/19/01 4:13p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef SAVELOAD_H -#define SAVELOAD_H - -#include "always.h" -#include "pointerremap.h" -#include "bittype.h" -#include "SLIST.H" - -class RefCountClass; -class SaveLoadSubSystemClass; -class PersistFactoryClass; -class PersistClass; -class PostLoadableClass; -class ChunkSaveClass; -class ChunkLoadClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// WWSaveLoad -// -// The WWSaveLoad library is a framework for saving and loading. The main -// goals that we attempted to achieve in designing this system are: -// -// - Save things in a form that could adapt as our code evolves. We want -// to be able to load files which were created with a previous version of the -// application into the current version. -// - Use the same framework throughout all of our libraries with as small an -// impact on them as possible -// - Automate as much of the implementation of save-load as possible. -// - Make this a generic hunk of code which contains no commando-specific parts -// so that it can be used by other applications. -// - Make this system capable of generating the file formats for our level editor, -// the game's level definition file, and player save files. -// -// To achive this, we developed several core concepts: -// -// - Persistant Objects: Most of the state of the game is contained in the objects -// active at any given time. PersistClass is an abstract interface which will allow -// objects to be used with the save-load system. It was also important to keep the -// overhead caused by inheriting this class to an absolute minimum. -// -// - PersistFactories: We need an automatic "virtual-constructor" or "abstract-factory" -// system for all objects that get saved. This is the PersistFactoryClass and the -// automated SimplePersistFactory template. All objects that "persist" are derived from -// PersistClass and all concrete derived PersistClasses have an associated static -// instance of a PersistFactory which handles their saving and construction upon encountering -// them while loading. In certain cases these PersistFactories can also serve as -// a "shortcut" where we cheat by not actually telling the object to save but simply save -// a small piece of data that allows us to recreate an identical object when we load. This -// is used in WW3D sometimes; we just save a render object name and then ask the WW3D asset -// manager to recreate that model for us. -// -// - SaveLoadSubSystems: The overall file structure will be governed by many sub-systems -// (derived from SaveLoadSubSystemClass). The application in-effect creates file formats -// by simply having the sub-systems that it wants write into a file. In this way you can -// achieve things like saving only static data into one file and dynamic into another, etc. -// All persistant objects that get saved will be told to save by some sub-system. For -// example: in Commando, I have a PhysicsDynamicDataSubSystem which saves all of the -// dynamic physics objects. In saving those objects I use the built-in PersistFactories -// and am therefore completely safe from new object types being added to the system, it will just -// automatically work -// -// - Pointer re-mapping: A pointer remaping system is built into the save-load system. There -// are several things that happen in this system. Each object, as it is saved and loaded, -// registers with the system its old address and its new address. (the old address is saved -// and the new address is available once the object is created). This is automated by the -// SimplePersistFactory for all but classes that use multiple inheritance. During the load -// process a table is built which contains all of these pointer pairs (old address, new address). -// Whenever an object loads a pointer, it gives a "pointer to that pointer" to the save load system. -// Then, after all of the objects have been loaded, the system goes through that list of pointers -// and finds them in the pointer pair table. NOTE: use the macros for re-mapping your -// pointers to enable automatic debugging information when you build with WWDEBUG defined. -// -// - Chunks: The file format will be chunk based since that gives us the flexibility to -// add new data and remove obsolete data without necessarily losing the ability -// to read old files. We will use a "high-granularity" of chunks. In many cases, each -// member variable will be in its own chunk for maximum flexibility. To help soften -// the memory usage for this approach, we developed the concept of "micro-chunks". -// Micro-chunks are just like chunks in that they have an id and a size but -// each of these fields are only a single byte and they are never hierarchical. -// -// - ChunkID's: The chunk ID's used by Subsystems and PersistFactories must be unique -// but all others can be considered local to the object that is saving itself. Unique -// ids for the subsystems and factories are achieved by saveloadids.h defining ranges -// of ids for various libraries and then those libraries maintaining a single header -// file internally which gives unique id's within that range to all of their sub-systems -// and persist factories. Never re-use an id or you will break compatibility with older -// versions of your files... -// -////////////////////////////////////////////////////////////////////////////////// - - -////////////////////////////////////////////////////////////////////////////////// -// -// SaveLoadSystemClass -// -////////////////////////////////////////////////////////////////////////////////// -class SaveLoadSystemClass -{ -public: - - /* - ** Save-Load interface. To create a file, ask each sub-system to save itself. - ** To load a file just open it and pass it to the load method. - */ - static bool Save (ChunkSaveClass &csave, SaveLoadSubSystemClass & subsystem); - static bool Load (ChunkLoadClass &cload,bool auto_post_load = true); - static bool Post_Load_Processing (void(*network_callback)(void)); - /* - ** Look up the persist factory for a given chunk id - */ - static PersistFactoryClass * Find_Persist_Factory(uint32 chunk_id); - - /* - ** Post-Load interface. An object being loaded can ask for a callback after - ** all objects have been loaded and pointers re-mapped. - */ - static void Register_Post_Load_Callback(PostLoadableClass * obj); - - /* - ** Pointer Remapping interface. NOTE: use the macros defined below to - ** get debug info with your pointers when doing a debug build. - */ - static void Register_Pointer (void *old_pointer, void *new_pointer); - -#ifdef WWDEBUG - static void Request_Pointer_Remap (void **pointer_to_convert,const char * file = NULL,int line = 0); - static void Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert,const char * file = NULL,int line = 0); -#else - static void Request_Pointer_Remap (void **pointer_to_convert); - static void Request_Ref_Counted_Pointer_Remap (RefCountClass **pointer_to_convert); -#endif - -protected: - - /* - ** Internal SaveLoadSystem functions - */ - static void Register_Sub_System (SaveLoadSubSystemClass * subsys); - static void Unregister_Sub_System (SaveLoadSubSystemClass * subsys); - static SaveLoadSubSystemClass * Find_Sub_System (uint32 chunk_id); - - static void Register_Persist_Factory(PersistFactoryClass * factory); - static void Unregister_Persist_Factory(PersistFactoryClass * factory); - - static void Link_Sub_System(SaveLoadSubSystemClass * subsys); - static void Unlink_Sub_System(SaveLoadSubSystemClass * subsys); - static void Link_Factory(PersistFactoryClass * factory); - static void Unlink_Factory(PersistFactoryClass * factory); - - static bool Is_Post_Load_Callback_Registered(PostLoadableClass * obj); - - static SaveLoadSubSystemClass * SubSystemListHead; - static PersistFactoryClass * FactoryListHead; - static PointerRemapClass PointerRemapper; - static SList PostLoadList; - - /* - ** these are friends so that they can register themselves at construction time. - */ - friend class SaveLoadSubSystemClass; - friend class PersistFactoryClass; -}; - - -/* -** Use the following macros to automatically enable pointer-remap DEBUG code. Remember that -** in all cases you submit a pointer to the pointer you want re-mapped. -*/ -#ifdef WWDEBUG -#define REQUEST_POINTER_REMAP(pp) SaveLoadSystemClass::Request_Pointer_Remap(pp,__FILE__,__LINE__) -#define REQUEST_REF_COUNTED_POINTER_REMAP(pp) SaveLoadSystemClass::Request_Ref_Counted_Pointer_Remap(pp,__FILE__,__LINE__) -#else -#define REQUEST_POINTER_REMAP(pp) SaveLoadSystemClass::Request_Pointer_Remap(pp) -#define REQUEST_REF_COUNTED_POINTER_REMAP(pp) SaveLoadSystemClass::Request_Ref_Counted_Pointer_Remap(pp) -#endif - - -#endif //SAVELOAD_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h deleted file mode 100644 index f096c4a97a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadids.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/saveloadids.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/04/01 8:42p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SAVELOADIDS_H -#define SAVELOADIDS_H - -////////////////////////////////////////////////////////////////////////////////// -// -// Chunk ID Ranges. -// Here are the ranges to use for SubSystem and PersistFactory chunk id's -// and also the chunk id's used by the save-load system itself. If you are -// creating a new library that is going to take advantage of this system, -// create a new range for it here. -// -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_SAVELOAD_BEGIN = 0x00000100, - CHUNKID_SAVELOAD_DEFMGR, - CHUNKID_TWIDDLER, - CHUNKID_WW3D_BEGIN = 0x00010000, - CHUNKID_WWPHYS_BEGIN = 0x00020000, - CHUNKID_WWAUDIO_BEGIN = 0x00030000, - CHUNKID_COMBAT_BEGIN = 0x00040000, - CHUNKID_COMMANDO_EDITOR_BEGIN = 0x00050000, - CHUNKID_PHYSTEST_BEGIN = 0x00060000, - CHUNKID_COMMANDO_BEGIN = 0x00070000, - CHUNKID_WWMATH_BEGIN = 0x00080000, - CHUNKID_WWTRANSLATEDB_BEGIN = 0x00090000 -}; - - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp deleted file mode 100644 index c12d2c0edf..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadstatus.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "saveloadstatus.h" -#include "mutex.h" - -#define MAX_STATUS_TEXT_ID 2 - -static CriticalSectionClass text_mutex; -static StringClass status_text[MAX_STATUS_TEXT_ID]; - -void SaveLoadStatus::Set_Status_Text(const char* text,int id) -{ - CriticalSectionClass::LockClass m(text_mutex); - WWASSERT(id. -*/ - -#ifndef WWSAVELOADSTATUS_H -#define WWSAVELOADSTATUS_H - -#if defined(_MSC_VER) -#pragma once -#endif - -#include "always.h" -#include "wwstring.h" - -namespace SaveLoadStatus -{ - void Set_Status_Text(const char* text,int id); - - void Reset_Status_Count( void ); - void Inc_Status_Count( void ); - int Get_Status_Count( void ); - void Get_Status_Text(StringClass& text, int id); -}; - -#define INIT_STATUS(t) SaveLoadStatus::Set_Status_Text(t,0) -#define INIT_SUB_STATUS(t) SaveLoadStatus::Set_Status_Text(t,1) - -#endif diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp deleted file mode 100644 index ca8115be5f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/saveloadsubsystem.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 9/09/99 9:50a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "saveloadsubsystem.h" -#include "saveload.h" - - -SaveLoadSubSystemClass::SaveLoadSubSystemClass(void) : - NextSubSystem(NULL) -{ - // All Sub-Systems are automatically registered with the SaveLoadSystem - SaveLoadSystemClass::Register_Sub_System (this); - return ; -} - -SaveLoadSubSystemClass::~SaveLoadSubSystemClass (void) -{ - SaveLoadSystemClass::Unregister_Sub_System (this); - return ; -} diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h deleted file mode 100644 index 500106f74c..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/saveloadsubsystem.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/saveloadsubsystem.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/12/00 4:25p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - -#ifndef SAVELOADSUBSYSTEM_H -#define SAVELOADSUBSYSTEM_H - - -#include "always.h" -#include "bittype.h" -#include "postloadable.h" - -class ChunkLoadClass; -class ChunkSaveClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// SaveLoadSubSystemClass -// -// Each SaveLoadSubSystem will automatically be registered with the SaveLoadSystem -// at construction time. The plan is to have a single static instance of each -// sub-system so that it automatically registers when the global constructors -// are executed. -// -// When an application wants to create a file it does so by asking the -// SaveLoadSystem to save the particular set of SaveLoadSubSystems that contain -// that data. -// -////////////////////////////////////////////////////////////////////////////////// -class SaveLoadSubSystemClass : public PostLoadableClass -{ -public: - - SaveLoadSubSystemClass (void); - virtual ~SaveLoadSubSystemClass (void); - - virtual uint32 Chunk_ID (void) const = 0; - -protected: - - virtual bool Contains_Data(void) const { return true; } - virtual bool Save (ChunkSaveClass &csave) = 0; - virtual bool Load (ChunkLoadClass &cload) = 0; - - virtual const char* Name() const = 0; - -private: - - SaveLoadSubSystemClass * NextSubSystem; // managed by SaveLoadSystem - - friend class SaveLoadSystemClass; -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h deleted file mode 100644 index d3127a163d..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/simpledefinitionfactory.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - - -#ifndef __SIMPLE_DEFINITION_FACTORY_H -#define __SIMPLE_DEFINITION_FACTORY_H - -#include "definitionfactory.h" - -////////////////////////////////////////////////////////////////////////////////// -// -// SimpleDefinitionFactoryClass -// -// Template class to automate the creation of simple definition factories. -// -////////////////////////////////////////////////////////////////////////////////// -template -class SimpleDefinitionFactoryClass : public DefinitionFactoryClass -{ -public: - - ////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////// - SimpleDefinitionFactoryClass (bool is_displayed = true) : - IsDisplayed (is_displayed) {} - - ////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////// - virtual DefinitionClass * Create (void) const; - virtual const char * Get_Name (void) const; - virtual uint32 Get_Class_ID (void) const; - virtual bool Is_Displayed (void) const { return IsDisplayed; } - -protected: - - ////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////// - bool IsDisplayed; -}; - -template -inline DefinitionClass * -SimpleDefinitionFactoryClass::Create (void) const -{ - return W3DNEW T; -} - -template -inline const char * -SimpleDefinitionFactoryClass::Get_Name (void) const -{ - return name; -} - -template -inline uint32 -SimpleDefinitionFactoryClass::Get_Class_ID (void) const -{ - return class_id; -} - -#define DECLARE_DEFINITION_FACTORY(_class, _id, _name) \ -char _class ## Name[] = _name; \ -SimpleDefinitionFactoryClass<_class, _id, _class ## Name> \ - -#endif //__SIMPLE_DEFINITION_FACTORY_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h deleted file mode 100644 index 695e22f859..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/simpleparameter.h +++ /dev/null @@ -1,247 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/simpleparameter.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 7/16/01 11:12a $* - * * - * $Revision:: 17 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - - - - -#ifndef __SIMPLE_PARAMETER_H -#define __SIMPLE_PARAMETER_H - -#include "always.h" -#include "parameter.h" -#include "vector2.h" -#include "vector3.h" -#include "matrix3d.h" -#include "rect.h" -#include - - -////////////////////////////////////////////////////////////////////////////////// -// -// SimpleParameterClass -// -////////////////////////////////////////////////////////////////////////////////// -template -class SimpleParameterClass : public ParameterClass -{ -public: - - /////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////////// - SimpleParameterClass (void *data, const char *name); - - ////////////////////////////////////////////////////////////////////////////// - // Public operators - ////////////////////////////////////////////////////////////////////////////// - bool operator== (const ParameterClass &src); - - /////////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////////// - const T & Get_Value (void) const; - void Set_Value (const T &new_value); - - // From Parameter class - ParameterClass::Type Get_Type (void) const; - void Copy_Value (const ParameterClass &src); - -private: - - /////////////////////////////////////////////////////////////////////// - // Private member data - /////////////////////////////////////////////////////////////////////// - T * m_Data; - T m_Min; - T m_Max; -}; - -////////////////////////////////////////////////////////////////////////////////// -// SimpleParameterClass -////////////////////////////////////////////////////////////////////////////////// -template inline -SimpleParameterClass::SimpleParameterClass (void *data, const char *name) -{ - Set_Name (name); - m_Data = (T *)data; - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// Get_Value -////////////////////////////////////////////////////////////////////////////////// -template inline bool -SimpleParameterClass::operator== (const ParameterClass &src) -{ - bool retval = false; - if (src.Get_Type () == Get_Type ()) { - retval = ((*m_Data) == *(((const SimpleParameterClass &)src).m_Data)); - } - - return retval; -} - -////////////////////////////////////////////////////////////////////////////////// -// Get_Value -////////////////////////////////////////////////////////////////////////////////// -template inline const T & -SimpleParameterClass::Get_Value (void) const -{ - return (*m_Data); -} - -////////////////////////////////////////////////////////////////////////////////// -// Set_Value -////////////////////////////////////////////////////////////////////////////////// -template inline void -SimpleParameterClass::Set_Value (const T &new_value) -{ - (*m_Data) = new_value; - Set_Modified (); - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// Get_Type -////////////////////////////////////////////////////////////////////////////////// -template inline ParameterClass::Type -SimpleParameterClass::Get_Type (void) const -{ - return type; -} - -////////////////////////////////////////////////////////////////////////////////// -// Copy_Value -////////////////////////////////////////////////////////////////////////////////// -template inline void -SimpleParameterClass::Copy_Value (const ParameterClass &src) -{ - if (Get_Type () == src.Get_Type ()) { - (*m_Data) = ((SimpleParameterClass &)src).Get_Value (); - } - - ParameterClass::Copy_Value (src); - return ; -} - -////////////////////////////////////////////////////////////////////////////////// -// -// Simple parameter types -// -////////////////////////////////////////////////////////////////////////////////// -typedef SimpleParameterClass BoolParameterClass; -typedef SimpleParameterClass Vector2ParameterClass; -typedef SimpleParameterClass Vector3ParameterClass; -typedef SimpleParameterClass Matrix3DParameterClass; -typedef SimpleParameterClass RectParameterClass; -typedef SimpleParameterClass ColorParameterClass; -typedef SimpleParameterClass StringsDBEntryParameterClass; - - -////////////////////////////////////////////////////////////////////////////////// -// -// RangedParameterClass -// -// Extends simple paramter types so they can have minimum/maximum values. -// -////////////////////////////////////////////////////////////////////////////////// -template -class RangedParameterClass : public SimpleParameterClass -{ -public: - /////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - /////////////////////////////////////////////////////////////////////// - RangedParameterClass (void *data, const char *name) - : SimpleParameterClass (data, name) { } - - /////////////////////////////////////////////////////////////////////// - // Public methods - /////////////////////////////////////////////////////////////////////// - void Set_Range (const T &min, const T &max) { m_Min = min; m_Max = max; } - const T & Get_Min (void) const { return m_Min; } - const T & Get_Max (void) const { return m_Max; } - -private: - - /////////////////////////////////////////////////////////////////////// - // Private member data - /////////////////////////////////////////////////////////////////////// - T m_Min; - T m_Max; -}; - - -////////////////////////////////////////////////////////////////////////////////// -// IntParameterClass -////////////////////////////////////////////////////////////////////////////////// -class IntParameterClass : public RangedParameterClass -{ -public: - IntParameterClass (void *data, const char *name) - : RangedParameterClass (data, name) - { Set_Range (-1000000000L, 1000000000L); } -}; - -////////////////////////////////////////////////////////////////////////////////// -// FloatParameterClass -////////////////////////////////////////////////////////////////////////////////// -class FloatParameterClass : public RangedParameterClass -{ -public: - FloatParameterClass (void *data, const char *name) - : RangedParameterClass (data, name) - { Set_Range (-100000.0F, 100000.0F); } -}; - -////////////////////////////////////////////////////////////////////////////////// -// AngleParameterClass -////////////////////////////////////////////////////////////////////////////////// -class AngleParameterClass : public RangedParameterClass -{ -public: - AngleParameterClass (void *data, const char *name) - : RangedParameterClass (data, name) - { Set_Range (0.0F, 6.283185307F); } -}; - -#endif //__SIMPLE_PARAMETER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp deleted file mode 100644 index 61dca2345f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/twiddler.cpp $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 12/10/01 12:40p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "twiddler.h" -#include "RANDOM.H" -#include "saveloadids.h" -#include "simpledefinitionfactory.h" -#include "persistfactory.h" -#include "win.h" -#include "wwhack.h" -#include "systimer.h" - - -DECLARE_FORCE_LINK( Twiddler ) - -////////////////////////////////////////////////////////////////////////////////// -// Constants -////////////////////////////////////////////////////////////////////////////////// -enum -{ - CHUNKID_VARIABLES = 0x00000100, - CHUNKID_BASE_CLASS = 0x00000200, -}; - -enum -{ - VARID_DEFINTION_ID = 0x01, - VARID_INDIRECT_CLASSID, -}; - - -////////////////////////////////////////////////////////////////////////////////// -// -// Static factories -// -////////////////////////////////////////////////////////////////////////////////// -DECLARE_DEFINITION_FACTORY(TwiddlerClass, CLASSID_TWIDDLERS, "Twiddler") _TwiddlerFactory; -SimplePersistFactoryClass _TwiddlerPersistFactory; - - -////////////////////////////////////////////////////////////////////////////////// -// -// TwiddlerClass -// -////////////////////////////////////////////////////////////////////////////////// -TwiddlerClass::TwiddlerClass (void) - : m_IndirectClassID (0) - -{ - CLASSID_DEFIDLIST_PARAM (TwiddlerClass, m_DefinitionList, 0, m_IndirectClassID, "Preset List"); - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// ~TwiddlerClass -// -////////////////////////////////////////////////////////////////////////////////// -TwiddlerClass::~TwiddlerClass (void) -{ - return ; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Twiddle -// -////////////////////////////////////////////////////////////////////////////////// -DefinitionClass * -TwiddlerClass::Twiddle (void) const -{ - DefinitionClass *definition = NULL; - - if (m_DefinitionList.Count () > 0) { - - // - // Get a random index into our definition list - // - RandomClass randomizer (TIMEGETTIME ()); - int index = randomizer (0, m_DefinitionList.Count () - 1); - - // - // Lookup the definition this entry represents - // - int def_id = m_DefinitionList[index]; - definition = DefinitionMgrClass::Find_Definition (def_id); - } - - return definition; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Create -// -////////////////////////////////////////////////////////////////////////////////// -PersistClass * -TwiddlerClass::Create (void) const -{ - PersistClass *retval = NULL; - - // - // Pick a random definition - // - DefinitionClass *definition = Twiddle (); - if (definition != NULL) { - - // - // Indirect the creation to the definition we randomly selected - // - retval = definition->Create (); - - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Get_Factory -// -////////////////////////////////////////////////////////////////////////////////// -const PersistFactoryClass & -TwiddlerClass::Get_Factory (void) const -{ - return _TwiddlerPersistFactory; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save -// -////////////////////////////////////////////////////////////////////////////////// -bool -TwiddlerClass::Save (ChunkSaveClass &csave) -{ - bool retval = true; - - csave.Begin_Chunk (CHUNKID_VARIABLES); - retval &= Save_Variables (csave); - csave.End_Chunk (); - - csave.Begin_Chunk (CHUNKID_BASE_CLASS); - retval &= DefinitionClass::Save (csave); - csave.End_Chunk (); - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load -// -////////////////////////////////////////////////////////////////////////////////// -bool -TwiddlerClass::Load (ChunkLoadClass &cload) -{ - bool retval = true; - - while (cload.Open_Chunk ()) { - switch (cload.Cur_Chunk_ID ()) { - - case CHUNKID_VARIABLES: - retval &= Load_Variables (cload); - break; - - case CHUNKID_BASE_CLASS: - retval &= DefinitionClass::Load (cload); - break; - } - - cload.Close_Chunk (); - } - - return retval; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Save_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -TwiddlerClass::Save_Variables (ChunkSaveClass &csave) -{ - WRITE_MICRO_CHUNK (csave, VARID_INDIRECT_CLASSID, m_IndirectClassID) - - for (int index = 0; index < m_DefinitionList.Count (); index ++) { - - // - // Save this definition ID to the chunk - // - int def_id = m_DefinitionList[index]; - WRITE_MICRO_CHUNK (csave, VARID_DEFINTION_ID, def_id) - } - - return true; -} - - -////////////////////////////////////////////////////////////////////////////////// -// -// Load_Variables -// -////////////////////////////////////////////////////////////////////////////////// -bool -TwiddlerClass::Load_Variables (ChunkLoadClass &cload) -{ - // - // Start fresh - // - m_DefinitionList.Delete_All (); - - // - // Loop through all the microchunks that define the variables - // - while (cload.Open_Micro_Chunk ()) { - switch (cload.Cur_Micro_Chunk_ID ()) { - - READ_MICRO_CHUNK (cload, VARID_INDIRECT_CLASSID, m_IndirectClassID) - - case VARID_DEFINTION_ID: - { - // - // Read the definition ID from the chunk and add it - // to our list - // - int def_id = 0; - cload.Read (&def_id, sizeof (def_id)); - m_DefinitionList.Add (def_id); - } - break; - } - - cload.Close_Micro_Chunk (); - } - - return true; -} \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h deleted file mode 100644 index f8d85a2755..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/twiddler.h +++ /dev/null @@ -1,130 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/twiddler.h $* - * * - * Author:: Patrick Smith * - * * - * $Modtime:: 6/27/00 2:34p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __TWIDDLER_H -#define __TWIDDLER_H - -#include "definition.h" -#include "definitionclassids.h" - - -////////////////////////////////////////////////////////////////////////////////// -// -// TwiddlerClass -// -////////////////////////////////////////////////////////////////////////////////// -class TwiddlerClass : public DefinitionClass -{ -public: - - ///////////////////////////////////////////////////////////////////// - // Editable interface requirements - ///////////////////////////////////////////////////////////////////// - DECLARE_EDITABLE(TwiddlerClass, DefinitionClass); - - ///////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ///////////////////////////////////////////////////////////////////// - TwiddlerClass (void); - virtual ~TwiddlerClass (void); - - ///////////////////////////////////////////////////////////////////// - // Public methods - ///////////////////////////////////////////////////////////////////// - - // - // Type identification - // - uint32 Get_Class_ID (void) const { return CLASSID_TWIDDLERS; } - PersistClass * Create (void) const; - - // - // From PersistClass - // - bool Save (ChunkSaveClass &csave); - bool Load (ChunkLoadClass &cload); - const PersistFactoryClass & Get_Factory (void) const; - - // - // Twiddler specific - // - virtual DefinitionClass * Twiddle (void) const; - virtual uint32 Get_Indirect_Class_ID (void) const; - virtual void Set_Indirect_Class_ID (uint32 class_id); - -private: - - ///////////////////////////////////////////////////////////////////// - // Private methods - ///////////////////////////////////////////////////////////////////// - bool Save_Variables (ChunkSaveClass &csave); - bool Load_Variables (ChunkLoadClass &cload); - - ///////////////////////////////////////////////////////////////////// - // Private member data - ///////////////////////////////////////////////////////////////////// - uint32 m_IndirectClassID; - DynamicVectorClass m_DefinitionList; -}; - - -///////////////////////////////////////////////////////////////////// -// Get_Indirect_Class_ID -///////////////////////////////////////////////////////////////////// -inline uint32 -TwiddlerClass::Get_Indirect_Class_ID (void) const -{ - return m_IndirectClassID; -} - - -///////////////////////////////////////////////////////////////////// -// Set_Indirect_Class_ID -///////////////////////////////////////////////////////////////////// -inline void -TwiddlerClass::Set_Indirect_Class_ID (uint32 class_id) -{ - m_IndirectClassID = class_id; - return ; -} - - -#endif //__TWIDDLER_H - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp deleted file mode 100644 index e6c179a80a..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : wwsaveload * - * * - * $Archive:: /Commando/Code/wwsaveload/wwsaveload.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/28/00 9:18a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "wwsaveload.h" -#include "definitionmgr.h" - - -void WWSaveLoad::Init(void) -{ -} - -void WWSaveLoad::Shutdown(void) -{ - _TheDefinitionMgr.Free_Definitions(); -} - - diff --git a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h b/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h deleted file mode 100644 index 0c8a7d69e6..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/WWSaveLoad/wwsaveload.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWSaveLoad * - * * - * $Archive:: /Commando/Code/wwsaveload/wwsaveload.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/28/00 9:20a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WWSAVELOAD_H -#define WWSAVELOAD_H - -/** -** WWSaveLoad -** The Init and Shutdown functions should be called once by the App. -*/ - -class WWSaveLoad -{ -public: - static void Init(void); - static void Shutdown(void); -}; - - -#endif - diff --git a/Generals/Code/Libraries/Source/WWVegas/Wwutil/CMakeLists.txt b/Generals/Code/Libraries/Source/WWVegas/Wwutil/CMakeLists.txt deleted file mode 100644 index 33503abfa7..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/Wwutil/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Set source files -set(WWUTIL_SRC - mathutil.cpp - mathutil.h - miscutil.cpp - miscutil.h -) - -# Targets to build. -add_library(g_wwutil STATIC) -set_target_properties(g_wwutil PROPERTIES OUTPUT_NAME wwutil) - -target_sources(g_wwutil PRIVATE ${WWUTIL_SRC}) - -target_link_libraries(g_wwutil PRIVATE - g_wwcommon -) diff --git a/Generals/Code/Libraries/Source/WWVegas/Wwutil/mathutil.cpp b/Generals/Code/Libraries/Source/WWVegas/Wwutil/mathutil.cpp deleted file mode 100644 index feb5f92900..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/Wwutil/mathutil.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: mathutil.cpp -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: -// -//----------------------------------------------------------------------------- -#include "mathutil.h" // I WANNA BE FIRST! - -#include -#include -#include "wwmath.h" -#include "miscutil.h" -#include "wwdebug.h" - -const double cMathUtil::PI_1 = 3.1415927; -const double cMathUtil::PI_2 = 1.5707963; - -//----------------------------------------------------------------------------- -// -// Returns a unit vector -// -void cMathUtil::Angle_To_Vector(double angle, double & dx, double & dy) -{ - WWASSERT(angle > -WWMATH_EPSILON && angle < 360.0 + WWMATH_EPSILON); - - double angleRadians; - - if (angle >= 0 && angle < 90) { - angleRadians = angle * PI_1 / 180.0; - dx = WWMath::Sin(angleRadians); - dy = WWMath::Cos(angleRadians); - } else if (angle >= 90 && angle < 180) { - angleRadians = (angle - 90) * PI_1 / 180.0; - dx = WWMath::Cos(angleRadians); - dy = -WWMath::Sin(angleRadians); - } else if (angle >= 180 && angle < 270) { - angleRadians = (angle - 180) * PI_1 / 180.0; - dx = -WWMath::Sin(angleRadians); - dy = -WWMath::Cos(angleRadians); - } else { - angleRadians = (angle - 270) * PI_1 / 180.0; - dx = -WWMath::Cos(angleRadians); - dy = WWMath::Sin(angleRadians); - } - - double len; - len = ::sqrt(dx * dx + dy * dy); - WWASSERT(::fabs(len - 1) < 0.0005); - - // - // Correction for Irish nature of windows y coords - // - dy *= -1; -} - -//----------------------------------------------------------------------------- -void cMathUtil::Vector_To_Angle(double dx, double dy, double & angle) -{ - double theta; - - if (dx == 0 && dy == 0) { - theta = 0; - } - - if (dx == 0) { - if (dy <= 0) { - theta = 0; - } else { - theta = PI_1; - } - } else { - theta = WWMath::Atan(-dy / dx); - if (dx < 0) { - theta += PI_1; - } - theta += 3 * PI_2; - if (theta >= 2 * PI_1) { - theta -= 2 * PI_1; - } - theta = 2 * PI_1 - theta; - if (theta == 2 * PI_1) { - theta = 0; - } - } - - angle = theta * 180.0 / PI_1; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Simple_Distance(double x1, double y1, double x2, double y2) -{ - double dx = x2 - x1; - double dy = y2 - y1; - return(::sqrt(dx * dx + dy * dy)); -} - -//----------------------------------------------------------------------------- -int cMathUtil::Round(double arg) -{ - //return (int)(arg + 0.5); - - if (arg > MISCUTIL_EPSILON) { - return (int) (arg + 0.5f); - } else if (arg < -MISCUTIL_EPSILON) { - return (int) (arg - 0.5f); - } else { - return 0; - } -} - -//----------------------------------------------------------------------------- -void cMathUtil::Rotate_Vector(double & vx, double & vy, double angle) -{ - double angle_radians = angle * PI_1 / 180.0; - - double vx1 = vx; - double vy1 = vy; - - vx = vx1 * ::WWMath::Cos(angle_radians) - vy1 * ::WWMath::Sin(angle_radians); - vy = vx1 * ::WWMath::Sin(angle_radians) + vy1 * ::WWMath::Cos(angle_radians); -} - - - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Uniform_Pdf_Double(double lower, double upper) -{ - WWASSERT(upper - lower > -MISCUTIL_EPSILON); - - double x = lower + ::rand() / (double) RAND_MAX * (upper - lower); - - WWASSERT(x - lower > -MISCUTIL_EPSILON && upper - x > -MISCUTIL_EPSILON); - - return x; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Normalized_Uniform_Pdf_Double() -{ - return Get_Uniform_Pdf_Double(0, 1); -} - -//----------------------------------------------------------------------------- -int cMathUtil::Get_Uniform_Pdf_Int(int lower, int upper) -{ - WWASSERT(lower <= upper); - int x = lower + ::rand() % (upper - lower + 1); - - WWASSERT(x >= lower && upper >= x); - - return x; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Hat_Pdf_Double(double lower, double upper) -{ - WWASSERT(upper - lower > -MISCUTIL_EPSILON); - - double x; - - if (::fabs(upper - lower) < MISCUTIL_EPSILON) { - x = lower; - } else { - - double dx = (upper - lower) / 2.0f; - double dy = 1 / dx; - double m = dy / dx; - double c = -m * lower; - - x = Get_Uniform_Pdf_Double(lower, lower + dx); - double y = Get_Uniform_Pdf_Double(0, dy); - - if (y > m * x + c) { - x += dx; - } - } - - WWASSERT(x - lower > -MISCUTIL_EPSILON && upper - x > -MISCUTIL_EPSILON); - - return x; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Normalized_Hat_Pdf_Double() -{ - return Get_Hat_Pdf_Double(0, 1); -} - -//----------------------------------------------------------------------------- -int cMathUtil::Get_Hat_Pdf_Int(int lower, int upper) -{ - return Round(Get_Hat_Pdf_Double(lower, upper)); -} - - - - - - - - - - - diff --git a/Generals/Code/Libraries/Source/WWVegas/Wwutil/mathutil.h b/Generals/Code/Libraries/Source/WWVegas/Wwutil/mathutil.h deleted file mode 100644 index 8d6845352f..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/Wwutil/mathutil.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: mathutil.h -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: static -// -//----------------------------------------------------------------------------- -#if defined(_MSV_VER) -#pragma once -#endif - -#ifndef MATHUTIL_H -#define MATHUTIL_H - -class cMathUtil -{ - public: - static void Angle_To_Vector(double angle, double & dx, double & dy); - static void Vector_To_Angle(double dx, double dy, double & angle); - static double Simple_Distance(double x1, double y1, double x2, double y2); - static int Round(double arg); - static void Rotate_Vector(double & vx, double & vy, double angle); - - // - // Random numbers generated according to simple - // Probability Density Functions - // - static double Get_Uniform_Pdf_Double(double lower, double upper); - static double Get_Normalized_Uniform_Pdf_Double(); - static int Get_Uniform_Pdf_Int(int lower, int upper); - static double Get_Hat_Pdf_Double(double lower, double upper); - static double Get_Normalized_Hat_Pdf_Double(); - static int Get_Hat_Pdf_Int(int lower, int upper); - - static const double PI_1; - static const double PI_2; -}; - -#endif // MATHUTIL_H \ No newline at end of file diff --git a/Generals/Code/Libraries/Source/WWVegas/Wwutil/miscutil.cpp b/Generals/Code/Libraries/Source/WWVegas/Wwutil/miscutil.cpp deleted file mode 100644 index 06e61b56d0..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/Wwutil/miscutil.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: miscutil.cpp -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: -// -//----------------------------------------------------------------------------- -#include "miscutil.h" // I WANNA BE FIRST! - -#include - -#include "RAWFILE.H" -#include "wwdebug.h" -#include "win.h" -#include "mmsys.h" -#include "ffactory.h" - -// -// cMiscUtil statics -// - -//--------------------------------------------------------------------------- -LPCSTR cMiscUtil::Get_Text_Time(void) -{ - // - // Returns a pointer to an internal statically allocated buffer... - // Subsequent time operations will destroy the contents of that buffer. - // Note: BoundsChecker reports 2 memory leaks in ctime here. - // - - time_t time_now = ::time(NULL); - char * time_str = ::ctime(&time_now); - time_str[::strlen(time_str) - 1] = 0; // remove \n - return time_str; -} - -//--------------------------------------------------------------------------- -void cMiscUtil::Seconds_To_Hms(float seconds, int & h, int & m, int & s) -{ - WWASSERT(seconds >= 0); - - h = (int) (seconds / 3600); - seconds -= h * 3600; - m = (int) (seconds / 60); - seconds -= m * 60; - s = (int) seconds; - - WWASSERT(h >= 0); - WWASSERT(m >= 0 && m < 60); - WWASSERT(s >= 0 && s < 60); - - //WWASSERT(fabs((h * 3600 + m * 60 + s) / 60) - mins < WWMATH_EPSILON); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_String_Same(LPCSTR str1, LPCSTR str2) -{ - WWASSERT(str1 != NULL); - WWASSERT(str2 != NULL); - - return(::stricmp(str1, str2) == 0); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_String_Different(LPCSTR str1, LPCSTR str2) -{ - WWASSERT(str1 != NULL); - WWASSERT(str2 != NULL); - - return(::stricmp(str1, str2) != 0); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::File_Exists(LPCSTR filename) -{ -#if 0 - WWASSERT(filename != NULL); - - WIN32_FIND_DATA find_info; - HANDLE file_handle = ::FindFirstFile(filename, &find_info); - - if (file_handle != INVALID_HANDLE_VALUE) { - ::FindClose(file_handle); - return true; - } else { - return false; - } -#else - FileClass * file = _TheFileFactory->Get_File( filename ); - if ( file && file->Is_Available() ) { - return true; - } - _TheFileFactory->Return_File( file ); - return false; -#endif -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::File_Is_Read_Only(LPCSTR filename) -{ - WWASSERT(filename != NULL); - - DWORD attributes = ::GetFileAttributes(filename); - return ((attributes != 0xFFFFFFFF) && (attributes & FILE_ATTRIBUTE_READONLY)); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Alphabetic(char c) -{ - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Numeric(char c) -{ - return (c >= '0' && c <= '9'); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Alphanumeric(char c) -{ - return Is_Alphabetic(c) || Is_Numeric(c); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Whitespace(char c) -{ - return c == ' ' || c == '\t'; -} - -//----------------------------------------------------------------------------- -void cMiscUtil::Trim_Trailing_Whitespace(char * text) -{ - WWASSERT(text != NULL); - - int length = ::strlen(text); - while (length > 0 && Is_Whitespace(text[length - 1])) { - text[--length] = 0; - } -} - -//----------------------------------------------------------------------------- -void cMiscUtil::Get_File_Id_String(LPCSTR filename, StringClass & str) -{ - WWASSERT(filename != NULL); - -// WWDEBUG_SAY(("cMiscUtil::Get_File_Id_String for %s\n", filename)); - - // - // Get size - // - RawFileClass file(filename); - int filesize = file.Size(); - //WWASSERT(filesize > 0); - if (filesize <= 0) - { - WWDEBUG_SAY(("Error: cMiscUtil::Get_File_Id_String for %s: filesize = %d\n", - filename, filesize)); - //W3D_DIE; - } - file.Close(); - - // - // Note... this timedatestamp is not present for all file types... - // - IMAGE_FILE_HEADER header = {0}; - extern bool Get_Image_File_Header(LPCSTR filename, IMAGE_FILE_HEADER *file_header); - /* - bool success; - success = Get_Image_File_Header(filename, &header); - WWASSERT(success); - */ - Get_Image_File_Header(filename, &header); - int time_date_stamp = header.TimeDateStamp; - - char working_filename[500]; - strcpy(working_filename, filename); - ::strupr(working_filename); - - // - // Strip path off filename - // - char * p_start = &working_filename[strlen(working_filename)]; - int num_chars = 1; - while (p_start > working_filename && *(p_start - 1) != '\\') { - p_start--; - num_chars++; - } - ::memmove(working_filename, p_start, num_chars); - - // - // Put all this data into a string - // - str.Format("%s %d %d", working_filename, filesize, time_date_stamp); - - //WWDEBUG_SAY(("File id string: %s\n", str)); -} - -//----------------------------------------------------------------------------- -void cMiscUtil::Remove_File(LPCSTR filename) -{ - WWASSERT(filename != NULL); - - ::DeleteFile(filename); -} - - - - - - - - - - - - - - - - - -/* -#define SIZE_OF_NT_SIGNATURE sizeof(DWORD) -#define PEFHDROFFSET(a) ((LPVOID)((BYTE *)a + \ - ((PIMAGE_DOS_HEADER)a)->e_lfanew + SIZE_OF_NT_SIGNATURE)) -*/ - -/* -int cMiscUtil::Get_Exe_Key(void) -{ - // - // Get exe name - // - char filename[500]; - int succeeded; - succeeded = ::GetModuleFileName(NULL, filename, sizeof(filename)); - ::strupr(filename); - WWASSERT(succeeded); - - // - // Get size - // - RawFileClass file(filename); - int filesize = file.Size(); - WWASSERT(filesize > 0); - file.Close(); - - // - // Strip path off filename - // - char * p_start = &filename[strlen(filename)]; - int num_chars = 1; - while (*(p_start - 1) != '\\') { - p_start--; - num_chars++; - } - ::memmove(filename, p_start, num_chars); - - // - // Pull a time/date stamp out of the exe header - // - PIMAGE_FILE_HEADER p_header = (PIMAGE_FILE_HEADER) PEFHDROFFSET(ProgramInstance); - WWASSERT(p_header != NULL); - int time_date_stamp = p_header->TimeDateStamp; - - // - // Put all this data into a string - // - char id_string[500]; - ::sprintf(id_string, "%s %d %d", filename, filesize, time_date_stamp); - WWDEBUG_SAY(("File id string: %s\n", id_string)); - - // - // return the crc of that string as the key - // - return CRCEngine()(id_string, strlen(id_string)); -} -*/ - -//#include -//#include "verchk.h" - -/* -//----------------------------------------------------------------------------- -int cMiscUtil::Get_Exe_Key(void) -{ - // - // Get exe name - // - char filename[500]; - int succeeded; - succeeded = ::GetModuleFileName(NULL, filename, sizeof(filename)); - ::strupr(filename); - WWASSERT(succeeded); - - StringClass string; - Get_File_Id_String(filename, string); - - // - // return the crc of that string as the key - // - return CRCEngine()(string, strlen(string)); -} -*/ - -//#include "crc.h" diff --git a/Generals/Code/Libraries/Source/WWVegas/Wwutil/miscutil.h b/Generals/Code/Libraries/Source/WWVegas/Wwutil/miscutil.h deleted file mode 100644 index 12d6cba368..0000000000 --- a/Generals/Code/Libraries/Source/WWVegas/Wwutil/miscutil.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: miscutil.h -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: -// -//----------------------------------------------------------------------------- -#if defined(_MSV_VER) -#pragma once -#endif - -#ifndef MISCUTIL_H -#define MISCUTIL_H - -#ifndef ALWAYS_H - #include "always.h" -#endif - -#include "bittype.h" -#include "wwstring.h" - -const float MISCUTIL_EPSILON = 0.0001f; - -class cMiscUtil -{ - public: - static LPCSTR Get_Text_Time(void); - static void Seconds_To_Hms(float seconds, int & h, int & m, int & s); - static bool Is_String_Same(LPCSTR str1, LPCSTR str2); - static bool Is_String_Different(LPCSTR str1, LPCSTR str2); - static void Get_File_Id_String(LPCSTR filename, StringClass & str); - static bool File_Exists(LPCSTR filename); - static bool File_Is_Read_Only(LPCSTR filename); - static bool Is_Alphabetic(char c); - static bool Is_Numeric(char c); - static bool Is_Alphanumeric(char c); - static bool Is_Whitespace(char c); - static void Trim_Trailing_Whitespace(char * text); - static void Remove_File(LPCSTR filename); - - private: -}; - - -#endif // MISCUTIL_H - - - - - - //static int Get_Exe_Key(void); diff --git a/Generals/Code/Libraries/Source/template.cpp b/Generals/Code/Libraries/Source/template.cpp deleted file mode 100644 index cd7bd43cb5..0000000000 --- a/Generals/Code/Libraries/Source/template.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: -// -// Module: -// -// File name: .cpp -// -// Created: -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - - - -//================================================================= -// Function Header -//================================================================= -/** - * Description - */ -//================================================================= - diff --git a/Generals/Code/Libraries/Source/template.h b/Generals/Code/Libraries/Source/template.h deleted file mode 100644 index bfb985c633..0000000000 --- a/Generals/Code/Libraries/Source/template.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: -// -// Module: -// -// File name: .h -// -// Created: -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef $label -#define $label - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// ClassName -//=============================== -/** - * Description - */ -//=============================== - - - - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - - -#endif // $label diff --git a/Generals/Code/Main/WinMain.cpp b/Generals/Code/Main/WinMain.cpp index 94cf3dcf35..c33e023102 100644 --- a/Generals/Code/Main/WinMain.cpp +++ b/Generals/Code/Main/WinMain.cpp @@ -53,6 +53,7 @@ #include "Common/StackDump.h" #include "Common/MessageStream.h" #include "Common/Team.h" +#include "GameClient/ClientInstance.h" #include "GameClient/InGameUI.h" #include "GameClient/GameClient.h" #include "GameLogic/GameLogic.h" ///< @todo for demo, remove @@ -66,7 +67,7 @@ #include "resource.h" #include "trim.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") @@ -83,8 +84,6 @@ const Char *g_strFile = "data\\Generals.str"; const Char *g_csfFile = "data\\%s\\Generals.csf"; const char *gAppPrefix = ""; /// So WB can have a different debug log file name. -static HANDLE GeneralsMutex = NULL; -#define GENERALS_GUID "685EAFF2-3216-4265-B047-251C5F4B82F3" #define DEFAULT_XRESOLUTION 800 #define DEFAULT_YRESOLUTION 600 @@ -744,7 +743,7 @@ void munkeeFunc(void) void checkProtection(void) { -#ifdef _INTERNAL +#ifdef RTS_INTERNAL __try { munkeeFunc(); @@ -887,7 +886,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, return 0; } - #ifdef _DEBUG + #ifdef RTS_DEBUG // Turn on Memory heap tracking int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tmpFlag |= (_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF); @@ -942,23 +941,16 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, #endif - //Create a mutex with a unique name to Generals in order to determine if - //our app is already running. - //WARNING: DO NOT use this number for any other application except Generals. - GeneralsMutex = CreateMutex(NULL, FALSE, GENERALS_GUID); - if (GetLastError() == ERROR_ALREADY_EXISTS) + // TheSuperHackers @refactor The instance mutex now lives in its own class. + + if (!rts::ClientInstance::initialize()) { - HWND ccwindow = FindWindow(GENERALS_GUID, NULL); + HWND ccwindow = FindWindow(rts::ClientInstance::getFirstInstanceName(), NULL); if (ccwindow) { SetForegroundWindow(ccwindow); ShowWindow(ccwindow, SW_RESTORE); } - if (GeneralsMutex != NULL) - { - CloseHandle(GeneralsMutex); - GeneralsMutex = NULL; - } DEBUG_LOG(("Generals is already running...Bail!\n")); delete TheVersion; @@ -967,7 +959,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, DEBUG_SHUTDOWN(); return 0; } - DEBUG_LOG(("Create GeneralsMutex okay.\n")); + DEBUG_LOG(("Create Generals Mutex okay.\n")); #ifdef DO_COPY_PROTECTION if (!CopyProtect::notifyLauncher()) @@ -997,7 +989,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, #ifdef MEMORYPOOL_DEBUG TheMemoryPoolFactory->debugMemoryReport(REPORT_POOLINFO | REPORT_POOL_OVERFLOW | REPORT_SIMPLE_LEAKS, 0, 0); #endif - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) TheMemoryPoolFactory->memoryPoolUsageReport("AAAMemStats"); #endif diff --git a/Generals/Code/Tools/Autorun/ARGS.CPP b/Generals/Code/Tools/Autorun/ARGS.CPP deleted file mode 100644 index bfacd4caec..0000000000 --- a/Generals/Code/Tools/Autorun/ARGS.CPP +++ /dev/null @@ -1,352 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//====================================================================================== -// -// @@@@@ @@ @ @@@@ @@@@ @@@@ @@ @ @@@@ @@@@ @@@@@ @@@@@ @@@@ @@ @ -// @@ @ @@ @ @@ @ @@ @ @@ @ @@@ @ @@ @ @@ @ @@ @ @@ @ @@ @ @@ @ -// @@@@@ @@ @ @@ @@ @@@@@@ @@ @ @ @@@@ @@@@ @@@@@ @@@@@ @@@@@@ @@ -// @@ @ @@ @ @@ @ @@ @ @@ @ @@ @@ @@ @ @@ @ @@ @ @@ @ @@ @ @@ -// @@@@@ @@@@ @@@@ @@@@ @@ @ @@ @ @@@@ @@@@ @@ @ @@@@@ @@ @ @@ -// -// Copyright (c) 1998, 1999 Westwood Studios -- CONFIDENTIAL -// -// ArgC_ArgV.cpp -// -//====================================================================================== - -//----------------------------------------------------------------------------- -// INCLUDES -//----------------------------------------------------------------------------- -#define STRICT -#include -#include -#include -#include -#include - -#include "ARGS.H" - -//----------------------------------------------------------------------------- -// GLOBALS -//----------------------------------------------------------------------------- - -Command_Line_Arguments *Args = NULL; - -//***************************************************************************** -// COMMAND_LINE_ARGUMENTS::COMMAND_LINE_ARGUMENTS -- Constructor. -// -// INPUT: HINSTANCE hInstance -// LPSTR lpszCmdLine -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 09/01/1997 ML/MG : Created. -//============================================================================= - -Command_Line_Arguments::Command_Line_Arguments ( - HINSTANCE current_instance_handle, - LPTSTR windows_command_line_string ) -{ - //-------------------------------------------------------------------------- - // debug checks... - //-------------------------------------------------------------------------- - assert( windows_command_line_string != NULL ); - - //-------------------------------------------------------------------------- - // reset all class data - //-------------------------------------------------------------------------- - memset( ArgV, 0, sizeof( ArgV ) ); - - //-------------------------------------------------------------------------- - // Store the program name in ArgV[ 0 ]. - //-------------------------------------------------------------------------- - GetModuleFileName( current_instance_handle, ArgV[ 0 ], MAX_ARGUMENT_LENGTH ); - - const char * ptr = windows_command_line_string; - bool potentially_forever = true; - - ArgC = 1; - - while( potentially_forever ) { - - //----------------------------------------------------------------------- - // Find the next non-whitespace character in the string. - //----------------------------------------------------------------------- - while ( *ptr == ' ' ) { - ++ ptr; - } - - //----------------------------------------------------------------------- - // If we're at the end of the string, quit. - //----------------------------------------------------------------------- - if ( *ptr == '\0' ) { - break; - } - - //----------------------------------------------------------------------- - // Store a command-line argument. - //----------------------------------------------------------------------- - int i = 0; - - if ( *ptr == '"' ) { - - //-------------------------------------------------------------------- - // Skip the opening quotation mark. - //-------------------------------------------------------------------- - ++ ptr; - - //-------------------------------------------------------------------- - // Collect characters until another quotation mark is encountered. - //-------------------------------------------------------------------- - while ( *ptr != '\0' && *ptr != '"' ) { - if ( i < MAX_ARGUMENT_LENGTH - 1 ) { - ArgV [ ArgC ][ i ] = *ptr; - ++ i; - } - ++ ptr; - } - - //-------------------------------------------------------------------- - // Skip the closing quotation mark. - //-------------------------------------------------------------------- - if ( *ptr == '"' ) { - ++ ptr; - } - - } else { - - //-------------------------------------------------------------------- - // Collect characters until a whitespace character is encountered. - //-------------------------------------------------------------------- - while ( *ptr != '\0' && *ptr != ' ' ) { - if ( i < MAX_ARGUMENT_LENGTH - 1 ) { - ArgV [ ArgC ][ i ] = *ptr; - ++ i; - } - ++ ptr; - } - } - - ArgV [ ArgC ][ i ] = '\0'; - ++ ArgC; - } -} - -//***************************************************************************** -// COMMAND_LINE_ARGUMENTS::COMMAND_LINE_ARGUMENTS -- Constructor. -// -// INPUT: HINSTANCE hInstance -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 09/01/1997 ML/MG : Created. -//============================================================================= - -Command_Line_Arguments::Command_Line_Arguments ( HINSTANCE current_instance_handle ) -{ - - char * windows_command_line_string = GetCommandLine(); - - //-------------------------------------------------------------------------- - // debug checks... - //-------------------------------------------------------------------------- - assert( windows_command_line_string != NULL ); - - //-------------------------------------------------------------------------- - // reset all class data - //-------------------------------------------------------------------------- - memset( ArgV, 0, sizeof( ArgV ) ); - - const char * ptr = windows_command_line_string; - bool potentially_forever = true; - - ArgC = 1; - - while( potentially_forever ) { - - //----------------------------------------------------------------------- - // Find the next non-whitespace character in the string. - //----------------------------------------------------------------------- - while ( *ptr == ' ' ) { - ++ ptr; - } - - //----------------------------------------------------------------------- - // If we're at the end of the string, quit. - //----------------------------------------------------------------------- - if ( *ptr == '\0' ) { - break; - } - - //----------------------------------------------------------------------- - // Store a command-line argument. - //----------------------------------------------------------------------- - int i = 0; - - if ( *ptr == '"' ) { - - //-------------------------------------------------------------------- - // Skip the opening quotation mark. - //-------------------------------------------------------------------- - ++ ptr; - - //-------------------------------------------------------------------- - // Collect characters until another quotation mark is encountered. - //-------------------------------------------------------------------- - while ( *ptr != '\0' && *ptr != '"' ) { - if ( i < MAX_ARGUMENT_LENGTH - 1 ) { - ArgV [ ArgC ][ i ] = *ptr; - ++ i; - } - ++ ptr; - } - - //-------------------------------------------------------------------- - // Skip the closing quotation mark. - //-------------------------------------------------------------------- - if ( *ptr == '"' ) { - ++ ptr; - } - - } else { - - //-------------------------------------------------------------------- - // Collect characters until a whitespace character is encountered. - //-------------------------------------------------------------------- - while ( *ptr != '\0' && *ptr != ' ' ) { - if ( i < MAX_ARGUMENT_LENGTH - 1 ) { - ArgV [ ArgC ][ i ] = *ptr; - ++ i; - } - ++ ptr; - } - } - - ArgV [ ArgC ][ i ] = '\0'; - ++ ArgC; - } -} - -//***************************************************************************** -// COMMAND_LINE_ARGUMENTS::~COMMAND_LINE_ARGUMENTS -- Destructor. -// -// INPUT: HINSTANCE hInstance -// LPSTR lpszCmdLine -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 09/01/1997 ML/MG : Created. -//============================================================================= - -Command_Line_Arguments::~Command_Line_Arguments ( void ) -{ - //-------------------------------------------------------------------------- - // reset all data... - //-------------------------------------------------------------------------- - ArgC = -1; - memset( ArgV, 0, sizeof( ArgV ) ); -} - -//***************************************************************************** -// COMMAND_LINE_ARGUMENTS::GET_ARGC -- Return ArgC. -// -// INPUT: none. -// -// OUTPUT: int ArgC. -// -// WARNINGS: none. -// -// HISTORY: -// 09/01/1997 ML/MG : Created. -//============================================================================= - -int Command_Line_Arguments::Get_argc ( void ) -{ - //-------------------------------------------------------------------------- - // debug checks - make sure we at least have the application name - //-------------------------------------------------------------------------- - assert( ArgC >= 1 ); - - //-------------------------------------------------------------------------- - // return how many string parameters there are in the "argv" list - //-------------------------------------------------------------------------- - return( ArgC ); -} - -//***************************************************************************** -// COMMAND_LINE_ARGUMENTS::GET_ARGV -- Return ArgV. -// -// INPUT: none. -// -// OUTPUT: int ArgV. -// -// WARNINGS: none. -// -// HISTORY: -// 09/01/1997 ML/MG : Created. -//============================================================================= - -const char *Command_Line_Arguments::Get_argv ( int argument_index ) -{ - //-------------------------------------------------------------------------- - // debug checks - make sure we at least have the application name - //-------------------------------------------------------------------------- - assert( argument_index >= 0 ); - assert( argument_index < MAX_COMMAND_LINE_ARGUMENTS ); - assert( argument_index < ArgC ); - assert( ArgC >= 1 ); - - //-------------------------------------------------------------------------- - // return - //-------------------------------------------------------------------------- - return( ArgV[ argument_index ] ); -} - -void Command_Line_Arguments::Set_argv( int argument_index, char *arg ) -{ - if( arg == NULL || *arg == '\0' ) { - return; - } - - //-------------------------------------------------------------------------- - // debug checks - make sure we at least have the application name - //-------------------------------------------------------------------------- - assert( argument_index >= 0 ); - assert( argument_index < MAX_COMMAND_LINE_ARGUMENTS ); - assert( argument_index < ArgC ); - assert( ArgC >= 1 ); - - if (( argument_index >= 0 ) && - ( argument_index < MAX_COMMAND_LINE_ARGUMENTS ) && - ( argument_index < ArgC )) { - - strcpy( ArgV[ argument_index ], arg ); - } -} - - diff --git a/Generals/Code/Tools/Autorun/ARGS.H b/Generals/Code/Tools/Autorun/ARGS.H deleted file mode 100644 index 49e95b102f..0000000000 --- a/Generals/Code/Tools/Autorun/ARGS.H +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//================================================================================================ -// -// @@@@@ @@ @ @@@@ @@@@ @@@@ @@ @ @@@@ @@@@ @@@@@ @@@@@ @@@@ @@ @ -// @@ @ @@ @ @@ @ @@ @ @@ @ @@@ @ @@ @ @@ @ @@ @ @@ @ @@ @ @@ @ -// @@@@@ @@ @ @@ @@ @@@@@@ @@ @ @ @@@@ @@@@ @@@@@ @@@@@ @@@@@@ @@ -// @@ @ @@ @ @@ @ @@ @ @@ @ @@ @@ @@ @ @@ @ @@ @ @@ @ @@ @ @@ -// @@@@@ @@@@ @@@@ @@@@ @@ @ @@ @ @@@@ @@@@ @@ @ @@@@@ @@ @ @@ -// -// Copyright (c) 1998, 1999 Westwood Studios -- CONFIDENTIAL -// -// ArgC_ArgV.h -// -//================================================================================================ - -#ifndef ARGS_H -#define ARGS_H - -//---------------------------------------------------------------------------- -// INCLUDES -//---------------------------------------------------------------------------- -#include -//#include "autorun.h" - -//---------------------------------------------------------------------------- -// DEFINES -//---------------------------------------------------------------------------- -#define MAX_COMMAND_LINE_ARGUMENTS 10 -#define MAX_ARGUMENT_LENGTH 80 - -//---------------------------------------------------------------------------- -// CLASS -//---------------------------------------------------------------------------- -class Command_Line_Arguments -{ - public: - Command_Line_Arguments ( HINSTANCE, LPTSTR ); - Command_Line_Arguments ( LPTSTR ) {}; - Command_Line_Arguments ( HINSTANCE ); - ~Command_Line_Arguments( void ); - - const char * Get_argv( int argument_index ); - int Get_argc(); - void Set_argv( int argument_index, char*arg ); - - private: - int ArgC; - char ArgV[ MAX_COMMAND_LINE_ARGUMENTS ][ MAX_ARGUMENT_LENGTH ]; -}; - -extern Command_Line_Arguments *Args; - -#endif // ARGC_ARGV_H \ No newline at end of file diff --git a/Generals/Code/Tools/Autorun/AUTORUN.RC b/Generals/Code/Tools/Autorun/AUTORUN.RC deleted file mode 100644 index 32b103f665..0000000000 --- a/Generals/Code/Tools/Autorun/AUTORUN.RC +++ /dev/null @@ -1,282 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Japanese resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_JPN) -#ifdef _WIN32 -LANGUAGE LANG_JAPANESE, SUBLANG_DEFAULT -#pragma code_page(932) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_VERSION_STRING "ƒo[ƒWƒ‡ƒ“ %s" - IDS_CANT_FIND_FILE "%s ‚ªŒ©‚‚©‚è‚Ü‚¹‚ñ‚Å‚µ‚½" -END - -#endif // Japanese resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// Korean resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_KOR) -#ifdef _WIN32 -LANGUAGE LANG_KOREAN, SUBLANG_DEFAULT -#pragma code_page(949) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_VERSION_STRING "Korean ©öoAu %s." - IDS_CANT_FIND_FILE "%s (A¡í)¢¬| A¡ÌA¡í ¨ùo ¨ú©ªA¨ö." -END - -#endif // Korean resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// Chinese (Taiwan) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHT) -#ifdef _WIN32 -LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL -#pragma code_page(950) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_VERSION_STRING "Chinese ac¢D? %s!C" - IDS_CANT_FIND_FILE "¡±a?¢G¡Li %s!C" -END - -#endif // Chinese (Taiwan) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_VERSION_STRING "German Version %s." - IDS_CANT_FIND_FILE "Konnte %s nicht finden." -END - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -1 ICON DISCARDABLE "autorun.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Cursor -// - -2 CURSOR DISCARDABLE "arrow.cur" - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -BACKGROUND BITMAP DISCARDABLE "Autorun_BG.bmp" -BUTTON_SEL BITMAP DISCARDABLE "ARButton_Sel.bmp" -BUTTON_REG BITMAP DISCARDABLE "ARButton_Reg.bmp" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "..\\resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -BITMAPDIALOG DIALOG DISCARDABLE 0, 0, 186, 94 -STYLE DS_ABSALIGN | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE | - WS_CAPTION | WS_SYSMENU -FONT 8, "MS Sans Serif" -BEGIN -END - - -///////////////////////////////////////////////////////////////////////////// -// -// WAVE -// - -MOUSEMOVE WAVE DISCARDABLE "mouse.wav" - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VERSIONINFO_1 VERSIONINFO - FILEVERSION 1,0,0,0 - PRODUCTVERSION 1,0,0,0 - FILEFLAGSMASK 0x0L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x0L - FILETYPE 0x0L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - BEGIN - VALUE "CompanyName", "Westwood Studios\0" - VALUE "FileDescription", "Westwood Autorun\0" - VALUE "FileVersion", "1.00\0" - VALUE "InternalName", "Autorun\0" - VALUE "LegalCopyright", "Copyright © Westwood Studios 2001\0" - VALUE "OriginalFilename", "Autorun.exe\0" - VALUE "ProductName", "Command & Conquer Renegade\0" - VALUE "ProductVersion", "1, 0, 0, 0\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_VERSION_STRING "English Version %s." - IDS_CANT_FIND_FILE "Could not find %s." -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// French (France) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA) -#ifdef _WIN32 -LANGUAGE LANG_FRENCH, SUBLANG_FRENCH -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_VERSION_STRING "French Version %s." - IDS_CANT_FIND_FILE "Impossible de trouver %s." -END - -#endif // French (France) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Generals/Code/Tools/Autorun/CDCNTRL.H b/Generals/Code/Tools/Autorun/CDCNTRL.H deleted file mode 100644 index 5b5b530a44..0000000000 --- a/Generals/Code/Tools/Autorun/CDCNTRL.H +++ /dev/null @@ -1,156 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Renegade Setup/Autorun/CDCNTRL.H $* - * * - * $Author:: Maria_l $* - * * - * $Modtime:: 4/20/01 2:07p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - - -#ifndef _CDCNTRL -#define _CDCNTRL - - -//#include "always.h" -//#include -#define STRICT -#include -#include -#include - - - -class CDControlClass { - - public: - CDControlClass(void); - ~CDControlClass(void); - - /* - ** Force the CD tray to open on the specified drive. - */ - void Force_CD_Eject(int drive); - - /* - ** Prevent the user from ejecting the CD in the specified drive. - */ - bool Lock_CD_Tray(int drive); - - /* - ** Allow the user to eject the CD in the specified drive. - */ - bool Unlock_CD_Tray(int drive); - - - private: - /* - ** NT functions. - */ - bool Eject_CD(char drive); - HANDLE Open_Removable_Volume(char drive); - bool Lock_Volume(HANDLE volume); - bool Unlock_Volume(HANDLE volume); - bool Dismount_Volume(HANDLE volume); - bool Prevent_Removal_Of_Volume(HANDLE volume, bool prevent); - bool Auto_Eject_Volume(HANDLE volume); - bool Close_Removable_Volume(HANDLE volume); - bool Lock_CD_Drive(char drive); - bool Unlock_CD_Drive(char drive); - - /* - ** Win9x functions. - */ - HANDLE WINAPI Open_VWin32 (void); - bool WINAPI Close_VWin32 (HANDLE vwin32); - bool WINAPI Unlock_Logical_Volume (HANDLE vwin32, char drive); - bool WINAPI Lock_Logical_Volume (HANDLE vwin32, char drive, char lock_level, short permissions); - bool Lock_Volume_95 (HANDLE vwin32, char drive); - bool Unlock_Volume_95 (HANDLE vwin32, char drive); - bool Auto_Eject_Volume_95 (HANDLE vwin32, char drive); - void Eject_CD_Win95 (char drive); - bool Lock_CD_Drive_95(char drive); - bool Unlock_CD_Drive_95(char drive); - -}; - -extern CDControlClass CDControl; - - -#define LOCK_TIMEOUT 2000 // 2 Seconds -#define LOCK_RETRIES 2 // 2 times - -/* -** Low level structures for Win9x. -** -** DeviceIoControl infrastructure -*/ -#if !defined (VWIN32_DIOC_DOS_IOCTL) -#define VWIN32_DIOC_DOS_IOCTL 1 - -typedef struct _DIOC_REGISTERS { - DWORD reg_EBX; - DWORD reg_EDX; - DWORD reg_ECX; - DWORD reg_EAX; - DWORD reg_EDI; - DWORD reg_ESI; - DWORD reg_Flags; -} DIOC_REGISTERS, *PDIOC_REGISTERS; - -#endif - -/* -** Intel x86 processor status flags -*/ -#define CARRY_FLAG 0x0001 - -/* -** DOS IOCTL function support -*/ - -#pragma pack(1) - -/* -** Parameters for locking/unlocking removable media -*/ -typedef struct _PARAMBLOCK { - BYTE bOperation; - BYTE bNumLocks; -} PARAMBLOCK, *PPARAMBLOCK; - -#pragma pack() - - - -#endif //_CDCNTRL - diff --git a/Generals/Code/Tools/Autorun/CMakeLists.txt b/Generals/Code/Tools/Autorun/CMakeLists.txt index ca4a5f0992..c75ab9f147 100644 --- a/Generals/Code/Tools/Autorun/CMakeLists.txt +++ b/Generals/Code/Tools/Autorun/CMakeLists.txt @@ -1,67 +1,10 @@ -set(AUTORUN_SRC - "ARGS.CPP" - "ARGS.H" - "autorun.cpp" - "autorun.h" - "CallbackHook.h" - "CDCNTRL.CPP" - "CDCNTRL.H" - "DrawButton.cpp" - "DrawButton.h" - "EZGIMEX.cpp" - "GameText.cpp" - "GameText.h" - "GETCD.CPP" - "GetCD.h" - "gimex.h" - "IGR.cpp" - "IGR.h" - "Jsupport.cpp" - "JSUPPORT.H" - "leanAndMeanAutorun.h" - "Locale_API.cpp" - "Locale_API.h" - "locale.cpp" - "locale.h" - "POINT.h" - "RECT.h" - "resource.h" - "TTFont.cpp" - "TTFont.h" - "Utils.cpp" - "Utils.h" - "ViewHTML.cpp" - "ViewHTML.h" - "WinFix.CPP" - "WinFix.H" - "Wnd_file.cpp" - "Wnd_File.h" - "WSYS_File.cpp" - "WSYS_file.h" - "WSYS_FileSystem.cpp" - "WSYS_FileSystem.h" - "WSYS_RAMFile.cpp" - "WSYS_RAMFile.h" - "WSYS_StdFile.cpp" - "WSYS_StdFile.h" - "WSYS_StdFileSystem.cpp" - "WSYS_StdFileSystem.h" -) - macro(setup_autorun appname) add_executable(${appname} WIN32) - target_sources(${appname} PRIVATE ${AUTORUN_SRC}) - target_link_libraries(${appname} PRIVATE + corei_autorun gi_always - core_config - winmm ) - - if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(${appname} PRIVATE AUTORUN.RC) - endif() endmacro() setup_autorun(g_autorun_en) diff --git a/Generals/Code/Tools/Autorun/CallbackHook.h b/Generals/Code/Tools/Autorun/CallbackHook.h deleted file mode 100644 index a97272ed65..0000000000 --- a/Generals/Code/Tools/Autorun/CallbackHook.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: /Renegade Setup/Autorun/CallbackHook.h $ -* -* DESCRIPTION -* -* PROGRAMMER -* Steven Clinard -* $Author: Maria_l $ -* -* VERSION INFO -* $Modtime: 8/14/00 7:52p $ -* $Revision: 2 $ -* -******************************************************************************/ - -#ifndef CALLBACKHOOK_H -#define CALLBACKHOOK_H - -class CallbackHook - { - public: - CallbackHook() - {} - - virtual ~CallbackHook() - {} - - virtual bool DoCallback(void) const - {return false;} - - protected: - CallbackHook(const CallbackHook&); - const CallbackHook& operator=(const CallbackHook&); - }; - - -template class Callback : public CallbackHook - { - public: - Callback(bool (*callback)(T), T userdata) - : mCallback(callback), - mUserData(userdata) - { - } - - virtual ~Callback() - { - } - - virtual bool DoCallback(void) const - { - if (mCallback != NULL) - { - return mCallback(mUserData); - } - - return false; - } - - private: - bool (*mCallback)(T); - T mUserData; - }; - -#endif // CALLBACKHOOK_H diff --git a/Generals/Code/Tools/Autorun/DrawButton.cpp b/Generals/Code/Tools/Autorun/DrawButton.cpp deleted file mode 100644 index abac0db17e..0000000000 --- a/Generals/Code/Tools/Autorun/DrawButton.cpp +++ /dev/null @@ -1,417 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** - ** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - ****************************************************************************** - * * - * Project Name : Autorun * - * * - * File Name : AUTORUN.CPP * - * * - * Programmers: Maria del Mar McCready Legg * - * * - * Start Date : September 5, 1997 * - * * - * Last Update : October 2, 2000 [MML] * - * * - *----------------------------------------------------------------------------* - * Functions: * - * DrawButton::DrawButton * - * DrawButton::Is_Mouse_In_Region * - * DrawButton::Return_Bitmap * - * DrawButton::Return_Area * - * DrawButton::Set_Stretched_Width * - * DrawButton::Set_Stretched_Height * - *----------------------------------------------------------------------------*/ - - -#define STRICT -#include -#include -#include "autorun.h" -#include "DrawButton.h" -#include "Locale_API.h" -#include "Wnd_File.h" - - - -#include "leanAndMeanAutorun.h" - -#ifndef LEAN_AND_MEAN -///////GAMEENGINE HEADERS//////////// -#include "Common/UnicodeString.h" -#include "Common/SubsystemInterface.h" -#include "GameClient/GameText.h" -#endif - - -//***************************************************************************** -// DrawButton::DrawButton -- Constructor for custom "Button" type. -// -// This custom button is drawn by the dialog, and uses the WM_MOUSEMOVE, -// WM_LBUTTONUP, and WM_LBUTTONDOWN to trigger actions. -// -// INPUT: int id -- button id handle -// int x -- x position -// int y -- y position -// int w -- width of button -// int h -- height of button -// char *normal -- name of normal button bitmap -// char *pressed -- name of pressed button bitmap -// char *focus -- name of focus button bitmap -// -// OUTPUT: none. -// -// WARNINGS: No keyboard/mouse/paint handling built in. Do manually. -// -// HISTORY: -// 07/15/1996 MML : Created. -//============================================================================= - -DrawButton::DrawButton ( int id, RECT button_rect, const char *normal, const char *focus, const char *pressed, const char * string, TTFontClass *fontptr ) -{ - Id = id; - - //-------------------------------------------------------------------------- - // Set default rectangle settings. - //-------------------------------------------------------------------------- - rect.left = button_rect.left; - rect.top = button_rect.top; - rect.right = button_rect.left + button_rect.right; - rect.bottom = button_rect.top + button_rect.bottom; - - MyRect.X = button_rect.left; - MyRect.Y = button_rect.top; - MyRect.Width = rect.right - rect.left; - MyRect.Height = rect.bottom - rect.top; - - TextRect.X = button_rect.left; - TextRect.Y = button_rect.top; - TextRect.Width = rect.right - rect.left; - TextRect.Height = rect.bottom - rect.top; - - StretchedWidth = rect.right - rect.left; - StretchedHeight = rect.bottom - rect.top; - - //-------------------------------------------------------------------------- - // Set the string variables. - //-------------------------------------------------------------------------- - memset( String, '\0', MAX_PATH ); -// if ( string != NULL ) { -// wcscpy( String, Locale_GetString( string_num, String )); - - -#ifdef LEAN_AND_MEAN -#else - UnicodeString tempString = TheGameText->fetch(string); - wcscpy(String, tempString.str()); -#endif -// } - - //-------------------------------------------------------------------------- - // Set the font pointer. - //-------------------------------------------------------------------------- - MyFontPtr = NULL; - - if ( fontptr != NULL ) { - MyFontPtr = fontptr; - } - - //-------------------------------------------------------------------------- - // Set Button Backgrounds. - //-------------------------------------------------------------------------- - _tcscpy( NormalBitmap, normal ); - _tcscpy( PressedBitmap, pressed ); - _tcscpy( FocusBitmap, focus ); - - if( NormalBitmap[0] != '\0' ) { - UseBitmaps = true; // determines how to draw button. - } - - //-------------------------------------------------------------------------- - // Start in normal mode. - //-------------------------------------------------------------------------- - ButtonState = NORMAL_STATE; - - Msg( __LINE__, TEXT(__FILE__), TEXT(" rect = [%d,%d,%d,%d]"), rect.left, rect.top, rect.right, rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" MyRect = [%d,%d,%d,%d]"), MyRect.X, MyRect.Y, MyRect.Width, MyRect.Height ); -} - -DrawButton::DrawButton ( int id, RECT button_rect, const char *normal, const char *focus, const char *pressed, const wchar_t *string, TTFontClass *fontptr ) -{ - Id = id; - - //-------------------------------------------------------------------------- - // Set default rectangle settings. - //-------------------------------------------------------------------------- - rect.left = button_rect.left; - rect.top = button_rect.top; - rect.right = button_rect.left + button_rect.right; - rect.bottom = button_rect.top + button_rect.bottom; - - MyRect.X = button_rect.left; - MyRect.Y = button_rect.top; - MyRect.Width = rect.right - rect.left; - MyRect.Height = rect.bottom - rect.top; - - TextRect.X = button_rect.left; - TextRect.Y = button_rect.top; - TextRect.Width = rect.right - rect.left; - TextRect.Height = rect.bottom - rect.top; - - StretchedWidth = rect.right - rect.left; - StretchedHeight = rect.bottom - rect.top; - - //-------------------------------------------------------------------------- - // Set the string variables. - //-------------------------------------------------------------------------- - memset( String, '\0', MAX_PATH ); - if ( string != NULL ) { - wcscpy( String, string ); - } - - //-------------------------------------------------------------------------- - // Set the font pointer. - //-------------------------------------------------------------------------- - MyFontPtr = NULL; - - if ( fontptr != NULL ) { - MyFontPtr = fontptr; - } - - //-------------------------------------------------------------------------- - // Set Button Backgrounds. - //-------------------------------------------------------------------------- - _tcscpy( NormalBitmap, normal ); - _tcscpy( PressedBitmap, pressed ); - _tcscpy( FocusBitmap, focus ); - - if( NormalBitmap[0] != '\0' ) { - UseBitmaps = true; // determines how to draw button. - } - - //-------------------------------------------------------------------------- - // Start in normal mode. - //-------------------------------------------------------------------------- - ButtonState = NORMAL_STATE; - - Msg( __LINE__, TEXT(__FILE__), TEXT(" rect = [%d,%d,%d,%d]"), rect.left, rect.top, rect.right, rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" MyRect = [%d,%d,%d,%d]"), MyRect.X, MyRect.Y, MyRect.Width, MyRect.Height ); -} - -//***************************************************************************** -// DrawButton::Draw_Text -- Check if mouse values are in button area. -// -// INPUT: HDC hDC -- DC to paint to. -// -// OUTPUT: none. -// -// WARNINGS: -// -// HISTORY: -// 01/18/2002 MML : Created. -//============================================================================= - -void DrawButton::Draw_Text ( HDC hDC ) -{ - RECT outline_rect; - Rect rect; - - if( hDC == NULL ) { - return; - } - - Return_Area( &outline_rect ); - Return_Text_Area( &rect ); - - /* - ** This function was combining the pixel color with the background, - ** so it never looked correct. - */ -// SetTextColor( hDC, RGB( 0, 240, 0 )); -// DrawFocusRect( hDC, &dst_rect ); - - if ( Get_State() == DrawButton::PRESSED_STATE ) { - MyFontPtr->Print( - hDC, - String, - rect, - TEXT_PRESSED_COLOR, - TEXT_PRESSED_SHADOW_COLOR, - TPF_BUTTON, - TPF_SHADOW ); - - } else if ( Get_State() == DrawButton::FOCUS_STATE ) { - MyFontPtr->Print( - hDC, - String, - rect, - TEXT_FOCUSED_COLOR, - TEXT_FOCUSED_SHADOW_COLOR, - TPF_BUTTON, - TPF_SHADOW ); - - } else { - MyFontPtr->Print( - hDC, - String, - rect, - TEXT_NORMAL_COLOR, - TEXT_NORMAL_SHADOW_COLOR, - TPF_BUTTON, - TPF_SHADOW ); - } -} - - -//***************************************************************************** -// DrawButton::Is_Mouse_In_Region -- Check if mouse values are in button area. -// -// INPUT: int mouse_x -- mouse x position -// int mouse_y -- mouse y position -// -// OUTPUT: bool -- true of false. -// -// WARNINGS: No keyboard/mouse/paint handling built in. Do manually. -// Note: width is shortened below to accomodate actual bitmap area. -// -// HISTORY: -// 07/15/1996 MML : Created. -//============================================================================= - -bool DrawButton::Is_Mouse_In_Region ( int mouse_x, int mouse_y ) -{ - if ( mouse_x < 0 || mouse_y < 0 ) { - return( false ); - } - - if (( mouse_x >= rect.left ) && - ( mouse_y >= rect.top ) && - ( mouse_x <= rect.left + StretchedWidth ) && - ( mouse_y <= rect.top + StretchedHeight )) { - return ( TRUE ); - } - return ( FALSE ); -} - -//***************************************************************************** -// DrawButton::Return_Bitmap -// -// Return name of correct bitmap based on state of button. -// -// INPUT: none. -// -// OUTPUT: char *bitmap -- name of bitmap file. -// -// WARNINGS: No keyboard/mouse/paint handling built in. Do manually. -// -// HISTORY: -// 07/15/1996 MML : Created. -//============================================================================= - -char *DrawButton::Return_Bitmap ( void ) -{ - if ( ButtonState == PRESSED_STATE ) { - return ( PressedBitmap ); - } else if ( ButtonState == FOCUS_STATE ) { - return ( FocusBitmap ); - } else { - return ( NormalBitmap ); - } -} - -//***************************************************************************** -// DrawButton::Return_Area -- Return x, y and width and height of button. -// -// INPUT: RECT area -- holds the x,y,width,height information. -// -// OUTPUT: none. -// -// WARNINGS: No keyboard/mouse/paint handling built in. Do manually. -// -// HISTORY: -// 07/15/1996 MML : Created. -//============================================================================= - -void DrawButton::Return_Area ( RECT *area ) -{ - area->left = rect.left; - area->top = rect.top; - area->right = rect.left + StretchedWidth; - area->bottom = rect.top + StretchedHeight; -} - -void DrawButton::Return_Area ( Rect *area ) -{ - area->X = MyRect.X; - area->Y = MyRect.Y; - area->Width = MyRect.Width; - area->Height = MyRect.Height; -} - -void DrawButton::Return_Text_Area ( Rect *area ) -{ - area->X = TextRect.X; - area->Y = TextRect.Y; - area->Width = TextRect.Width; - area->Height = TextRect.Height; -} - - -//***************************************************************************** -// DrawButton::Set_Stretched_Width -- Set draw width of button. -// -// INPUT: int value -- destination width size. -// -//OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: 08/12/1996 MML : Created. -//============================================================================= - -int DrawButton::Set_Stretched_Width ( int value ) -{ - int nWidth = StretchedWidth; - - StretchedWidth = value; - return ( nWidth ); -} - -//***************************************************************************** -// DrawButton::Set_Stretched_Height -- Set draw height of button. -// -// INPUT: int value -- destination height size. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: 08/12/1996 MML : Created. -//============================================================================= - -int DrawButton::Set_Stretched_Height ( int value ) -{ - int nHeight = StretchedHeight; - - StretchedHeight = value; - return( nHeight ); -} - - diff --git a/Generals/Code/Tools/Autorun/DrawButton.h b/Generals/Code/Tools/Autorun/DrawButton.h deleted file mode 100644 index 520ce3fdef..0000000000 --- a/Generals/Code/Tools/Autorun/DrawButton.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/************************************************************************ - ** C O N F I D E N T I A L --- W E S T W O O D A S S O C I A T E S ** - ************************************************************************ - * * - * Project Name : DrawButton * - * * - * File Name : DRAWBUTTON.H * - * * - * Programmer : Maria del Mar McCready Legg * - * * - * Start Date : May 10, 1994 * - * * - * Last Update : October 5, 2000 [MML] * - *----------------------------------------------------------------------*/ - -#ifndef DRAWBUTTONS_H -#define DRAWBUTTONS_H - -#include -#include -#include "TTFont.h" - - -//------------------------------------------------------------------------- -// Custom "Button" Class -//------------------------------------------------------------------------- -class DrawButton -{ - public: - - enum BUTTON_STATE { - NORMAL_STATE = 0, - PRESSED_STATE, - FOCUS_STATE - }; - - DrawButton ( int id, RECT button_rect, const char *normal, const char *focus, const char *pressed, const char *string, TTFontClass *fontptr ); - DrawButton ( int id, RECT button_rect, const char *normal, const char *focus, const char *pressed, const wchar_t *string, TTFontClass *fontptr ); - - char *Return_Normal_Bitmap ( void ) { return NormalBitmap; }; - char *Return_Pressed_Bitmap ( void ) { return PressedBitmap; }; - char *Return_Focus_Bitmap ( void ) { return FocusBitmap; }; - char *Return_Bitmap ( void ); - - bool Draw_Bitmaps ( void ) { return( UseBitmaps ); }; - - void Draw_Text ( HDC hDC ); - - BUTTON_STATE Get_State ( void ) { return ButtonState; }; - bool Is_Mouse_In_Region ( int mouse_x, int mouse_y ); - int Return_Id ( void ) { return Id; }; - int Return_X_Pos ( void ) { return rect.left; }; - int Return_Y_Pos ( void ) { return rect.top; }; - int Return_Width ( void ) { return( rect.right - rect.left ); }; - int Return_Height ( void ) { return( rect.bottom - rect.top ); }; - int Return_Stretched_Width ( void ) { return( StretchedWidth ); }; - int Return_Stretched_Height ( void ) { return( StretchedHeight ); }; - void Return_Area ( RECT *area ); - void Return_Area ( Rect *area ); - void Return_Text_Area ( Rect *area ); - TTFontClass *Return_Font_Ptr ( void ) { return( MyFontPtr ); }; - wchar_t *Return_Text ( void ) { return( String ); }; - void Set_State ( BUTTON_STATE state ) { ButtonState = state; }; - int Set_Stretched_Width ( int ); - int Set_Stretched_Height ( int ); - - protected: - - int Id; - Rect MyRect; - Rect TextRect; - RECT rect; - BUTTON_STATE ButtonState; - int StretchedWidth; - int StretchedHeight; - bool UseBitmaps; - TTFontClass *MyFontPtr; - - wchar_t String[ MAX_PATH ]; - char NormalBitmap [ _MAX_FNAME ]; - char PressedBitmap[ _MAX_FNAME ]; - char FocusBitmap [ _MAX_FNAME ]; -}; - - - - - - -#endif diff --git a/Generals/Code/Tools/Autorun/EZGIMEX.cpp b/Generals/Code/Tools/Autorun/EZGIMEX.cpp deleted file mode 100644 index 47ca122310..0000000000 --- a/Generals/Code/Tools/Autorun/EZGIMEX.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* Copyright (C) Electronic Arts Canada Inc. 1994-1998. All rights reserved. */ - -/*------------------------------------------------------------------*/ -/* */ -/* ANSI Standard File and Memory Interface v1.04 */ -/* */ -/* by FrANK G. Barchard, EAC */ -/* */ -/* Code Module - May 24, 1995 */ -/* */ -/*------------------------------------------------------------------*/ -/* */ -/* Module Notes: */ -/* ------------- */ -/* This modules makes an easy basis for new Gimex low level */ -/* functions. You will need to make the following changes: */ -/* */ -/* function what to change */ -/* -------- -------------- */ -/* galloc/free put in your memory manager */ -/* LIBHANDLE.handle handle for your file system */ -/* gopen/gwopen fopen, fseek, ftell (find file size) */ -/* gclose fclose */ -/* gread fread and possibly memcpy */ -/* gwrite fwrite */ -/* gseek fseek */ -/* */ -/* The other routines should not need changing. */ -/* */ -/*------------------------------------------------------------------*/ - -/* And increase stream buffer */ -/* - setvbuf(f, NULL, _IOFBF, FILE_BUFFER_SIZE); -*/ - -#define __NOINLINE__ 1 -#include -#include -#include -#include "gimex.h" -#include "Wnd_File.h" - -/* Memory Functions */ - -int galloccount=0; - -void * GCALL galloc(long size) -{ - ++galloccount; - return(malloc((size_t)size)); -} - -int GCALL gfree(void *memptr) -{ - --galloccount; - free(memptr); - return(1); -} - -/* get motorola memory */ - -unsigned long ggetm(void *src, int bytes) -{ - unsigned char *s = (unsigned char *) src; - unsigned long value; - - value = 0L; - while (bytes--) - { - value = (value<<8) + ((*s++)); - } - return(value); -} - -/* get intel memory */ - -unsigned long ggeti(void *src, int bytes) -{ - unsigned char *s = (unsigned char *) src; - int i = 0; - unsigned long value; - - value = 0L; - while (bytes--) - { - value += ((*s++)) << (i); - i += 8; - } - return(value); -} - -/* put motorolla memory */ - -void gputm(void *dst, unsigned long data, int bytes) -{ - unsigned char *d = (unsigned char *) dst; - unsigned long pval; - - data <<= (4-bytes)*8; - while (bytes) - { - pval = data >> 24; - *d++ = (unsigned char) pval; - data <<= 8; - --bytes; - } -} - -/* put intel memory */ - -void gputi(void *dst, unsigned long data, int bytes) -{ - unsigned char *d = (unsigned char *) dst; - unsigned long pval; - - while (bytes) - { - pval = data; - *d++ = (unsigned char) pval; - data >>= 8; - --bytes; - } -} - -/* File Functions */ - -GSTREAM * GCALL gopen(const char *filename) -{ - FILE *handle; - - Msg( __LINE__, __FILE__, "gopen:: %s.", filename ); - - handle = fopen( filename, "r+b" ); - - Msg( __LINE__, __FILE__, "gopen:: handle = %d", (( handle != NULL )? 1 : 0 )); - - if ( !handle ) { - - handle = fopen( filename, "rb" ); - - Msg( __LINE__, __FILE__, "gopen:: handle = %d", (( handle != NULL )? 1 : 0 )); - } - return((GSTREAM *) handle); -} - -GSTREAM * GCALL gwopen(const char *filename) -{ - FILE *handle; - - handle = fopen(filename,"w+b"); - if (!handle) - handle = fopen(filename,"wb"); - - return((GSTREAM *) handle); -} - -int GCALL gclose(GSTREAM *g) -{ - int ok=1; - if (g) - ok = !fclose((FILE*) g); - return(ok); -} - -int GCALL gread(GSTREAM *g, void *buf, long size) -{ - return(fread(buf, (size_t) 1, (size_t) size, (FILE *) g)); -} - -int GCALL gwrite(GSTREAM *g, void *buf, long size) -{ - return(fwrite(buf, (size_t)1, (size_t)size, (FILE *) g)); -} - -int GCALL gseek(GSTREAM *g, long offset) -{ - return(!fseek((FILE *) g, offset, SEEK_SET)); -} - -long GCALL glen(GSTREAM *g) -{ - long len; - long oldpos = gtell(g); - fseek((FILE *)g, 0, SEEK_END); - len = gtell(g); - fseek((FILE *)g, oldpos, SEEK_SET); - return(len); -} - -long GCALL gtell(GSTREAM *g) -{ - return(ftell((FILE *) g)); -} - diff --git a/Generals/Code/Tools/Autorun/GETCD.CPP b/Generals/Code/Tools/Autorun/GETCD.CPP deleted file mode 100644 index dbc3c41daa..0000000000 --- a/Generals/Code/Tools/Autorun/GETCD.CPP +++ /dev/null @@ -1,414 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** - ***** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***** - **************************************************************************** - * Project Name:: Command & Conquer * - * $Archive:: /Renegade Setup/Autorun/GETCD.CPP $Author:: Steve_t * - * $Modtime:: 1/28/02 10:54a $Revision:: 20 * - *--------------------------------------------------------------------------* - * Functions: * - * GetCDClass::GetCDClass -- default constructor * - * GetCDClass::~GetCDClass -- destructor * - * GetCDClass::GetCDDrive -- returns the logical CD drive * - * CD_Volume_Verification -- Check label of the CDRom. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ - -#include -#include -//#include "always.h" -#include "GetCD.h" -//#include "timer.h" -#include "Wnd_File.h" -//#include "missiondisk.h" -#include "WinFix.H" - -#ifndef ROR_NOT_READY -#define ROR_NOT_READY 21 -#endif - -/********************************************************************** -** This macro serves as a general way to determine the number of elements -** within an array. -*/ -#define ARRAY_SIZE(x) int(sizeof(x)/sizeof(x[0])) -#define size_of(typ,id) sizeof(((typ*)0)->id) - -//----------------------------------------------------------------------------- -// Global Variables -//----------------------------------------------------------------------------- -#if ( MISSION_DISK ) - -static const char * _CD_Volume_Label[] = { - "Renegade Mission", // Yuri's Revenge (mission disk) -}; - -#else - -static const char * _CD_Volume_Label[] = { - "Renegade Game", // Red Alert 2 - "Renegade Data", // Red Alert 2 -}; - -#endif - - -static int _Num_Volumes = ARRAY_SIZE( _CD_Volume_Label ); - -GetCDClass CDList; - - -/**************************************************************************** - * GetCDClass -- default constructor * - * * - * INPUT: * - * none * - * OUTPUT: * - * none * - * WARNINGS: * - * * - * HISTORY: * - * 05/26/1994 SW : Created. * - * 12/04/1995 ST : fixed for Win95 * - *==========================================================================*/ -GetCDClass::GetCDClass( void ) -{ - char path[]={ "a:\\" }; - - CDCount = 0; - CDIndex = 0; - - Msg( __LINE__, __FILE__, "GetCDClass constructor\n" ); - - /*-------------------------------------------------------------------------- - ** Set all CD drive placeholders to empty - */ - for( int j = 0; j < MAX_CD_DRIVES; j++ ) { - CDDrives[j] = NO_CD_DRIVE; - } - - for( char i = 'c'; i <= 'z'; i++ ) { - - path[0] = i; - - if ( GetDriveType( path ) == DRIVE_CDROM ) { - CDDrives[ CDCount++ ] = (int)( i-'a' ); - Msg( __LINE__, __FILE__, "CD drive found - %c:\n", i +'A'-'a' ); - } - } - - /*-------------------------------------------------------------------------- - ** Catch the case when there are NO CD-ROM drives available - */ - if ( CDCount == 0 ) { - for ( char i = 'a'; i <= 'b'; i++ ) { - path[0] = i; - if ( GetDriveType( path ) == DRIVE_CDROM ) { - CDDrives[ CDCount++ ] = (int)( i-'a' ); - } - } - } - if ( CDCount == 0 ) { - Msg( __LINE__, __FILE__, "No CD drives found\n"); - } -} - -/******************************************************************************** - * GetCDClass -- destructor * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: * - * * - * HISTORY: * - * 05/26/1994 SW: Created. * - * 12/4/95 ST: fixed for Win95 * - *==============================================================================*/ -GetCDClass::~GetCDClass(void) -{ -// if(cdDrive_addrp.seg) -// DPMI_real_free(cdDrive_addrp); // free up those conventional buffers -} - -/******************************************************************************** - * GetCDClass -- Get_CD_Drive_For_This_Volume * - * * - * INPUT: char *volume_name * - * * - * OUTPUT: int * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/2000 MML: Created. * - *==============================================================================*/ - -int GetCDClass::Get_CD_Drive_For_This_Volume ( const char *volume_label ) -{ - char volume_name[128] = ""; - int count = 0; - char buffer[128]; - unsigned misc_dword; - unsigned filename_length; - int cd_drive; - - CDIndex = 0; - - while( CDIndex < CDCount ) { - - //--------------------------------------------------------------------- - // NOTE: A=0, B=1, C=2, D=3, etc... - //--------------------------------------------------------------------- - cd_drive = CDDrives[ CDIndex++ ]; - wsprintf( buffer, "%c:\\", 'A' + cd_drive ); - - if ( GetVolumeInformation( - (char const *)buffer, - &volume_name[0], - (unsigned long)sizeof(volume_name)-1, - (unsigned long *)NULL, - (unsigned long *)&filename_length, - (unsigned long *)&misc_dword, - (char *)NULL, - (unsigned long)0 )) { - - //--------------------------------------------------------------------- - // Windows '95 appears to have a volume name limit of 11 characters. - // I cannot find a Win32 call that will return the maximum volume name - // length so the value '11' is hard-coded here and the assumption made - // that all OS's have this length or better. - //--------------------------------------------------------------------- - if( WinVersion.Is_Win95()) { - volume_name[11] = '\0'; - } - - if ( !_stricmp( volume_label, volume_name )) { - return( cd_drive ); - } - - } else { - -#if _DEBUG - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - Msg( __LINE__, __FILE__, (LPTSTR)lpMsgBuf ); - LocalFree( lpMsgBuf ); -#endif - - } - } - return( Get_First_CD_Drive()); -} - -/******************************************************************************** - * GetCDClass -- Get_Volume_Label * - * * - * INPUT: int index * - * * - * OUTPUT: char * * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/31/2000 MML: Created. * Happy Halloween! * * - *==============================================================================*/ - -const char * GetCDClass::Get_Volume_Label ( int index ) -{ - if( index >= 0 && index < _Num_Volumes ) { - return( _CD_Volume_Label[ index ]); - } - return( _CD_Volume_Label[0]); -} - -/******************************************************************************** - * GetCDClass -- Get_Volume_For_This_CD_Drive * - * * - * INPUT: char *volume_name * - * char *path * - * * - * OUTPUT: int * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/31/2000 MML: Created. * Happy Halloween! * * - *==============================================================================*/ - -const char *GetCDClass::Get_Volume_For_This_CD_Drive ( const char *path, char *volume_name ) -{ - char buffer[128]; - unsigned misc_dword; - unsigned filename_length; - static char volume_label[ MAX_PATH ] = ""; // [OYO] add static - - if ( path == NULL || volume_name == NULL ) { - return( NULL ); - } - - memset( volume_name, '\0', sizeof( volume_name )); - wsprintf( buffer, "%c:\\", path[0] ); - - if ( GetVolumeInformation( - (char const *)buffer, - &volume_label[0], - (unsigned long)sizeof(volume_label)-1, - (unsigned long *)NULL, - (unsigned long *)&filename_length, - (unsigned long *)&misc_dword, - (char *)NULL, - (unsigned long)0 )) { - - strcpy( volume_name, volume_label ); - - } else { - - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - Msg( __LINE__, __FILE__, (LPTSTR)lpMsgBuf ); - LocalFree( lpMsgBuf ); - - strcpy( volume_name, _CD_Volume_Label[0] ); - } - - //------------------------------------------------------------------------- - // Windows '95 appears to have a volume name limit of 11 characters. - // I cannot find a Win32 call that will return the maximum volume name - // length so the value '11' is hard-coded here and the assumption made - // that all OS's have this length or better. - //------------------------------------------------------------------------- - bool winversion = WinVersion.Is_Win95(); - - if( winversion ) { - volume_name[11] = '\0'; - } - - return( volume_name ); -} - -/******************************************************************************** - * CD_VOLUME_VERIFICATION -- Check volume label of the CD in the given drive. * - * * - * INPUT: int drive_number * - * char *lable * - * * - * OUTPUT: TRUE/FALSE * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 01/11/99 4:20PM MML : Created * - *==============================================================================*/ - -bool CD_Volume_Verification ( int cd_drive, char *volume_label, char *volume_to_find ) -{ - char volume_name[128] = ""; - int count = 0; - char buffer[128]; - unsigned misc_dword; - unsigned filename_length; - - /*************************************************************************** - ** Get the volume label. If we get a 'not ready' error then retry for the - ** timeout period. - */ - for (;;) { - - //--------------------------------------------------------------------- - // NOTE: A=0, B=1, C=2, D=3, etc... - //--------------------------------------------------------------------- - wsprintf( buffer, "%c:\\", 'A' + cd_drive ); - - if ( GetVolumeInformation( - (char const *)buffer, - &volume_name[0], - (unsigned long)sizeof(volume_name)-1, - (unsigned long *)NULL, - (unsigned long *)&filename_length, - (unsigned long *)&misc_dword, - (char *)NULL, - (unsigned long)0 )) { - - /****************************************************************** - ** Match the volume label to the list of known volume labels. - */ - - //--------------------------------------------------------------------- - // Windows '95 appears to have a volume name limit of 11 characters. - // I cannot find a Win32 call that will return the maximum volume name - // length so the value '11' is hard-coded here and the assumption made - // that all OS's have this length or better. - //--------------------------------------------------------------------- - if( WinVersion.Is_Win95()) { - volume_name[11] = '\0'; - } - - if ( volume_label != NULL ) { - strncpy( volume_label, volume_name, 128 ); - } - - if ( !_stricmp( volume_to_find, volume_name )) { - return TRUE; - } - - if ( !count ) { - count++; - } else { - return FALSE; - } - - } else { - - /********************************************************************* - ** Failed to get the volume label on a known CD drive. If this is a - ** CD changer it may require time to swap the disks so don't return - ** immediately if the error is ROR_NOT_READY - */ - return FALSE; - } - } -} - - - - -/* ==================================================================== */ - diff --git a/Generals/Code/Tools/Autorun/GameText.cpp b/Generals/Code/Tools/Autorun/GameText.cpp deleted file mode 100644 index 2b163b7c32..0000000000 --- a/Generals/Code/Tools/Autorun/GameText.cpp +++ /dev/null @@ -1,1152 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: GameText.cpp -// -// Created: 11/07/01 -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include -#include -#include -#include - -#include - -#include -#include "GameText.h" - -#define DEBUG_LOG(x) {} -#define DEBUG_ASSERTCRASH(x, y) {} - -//#include -//#include -//#include -//#include -//#include -#include "WSYS_file.h" -#include "WSYS_RAMFile.h" - - - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - -#define CSF_ID ( ('C'<<24) | ('S'<<16) | ('F'<<8) | (' ') ) -#define CSF_LABEL ( ('L'<<24) | ('B'<<16) | ('L'<<8) | (' ') ) -#define CSF_STRING ( ('S'<<24) | ('T'<<16) | ('R'<<8) | (' ') ) -#define CSF_STRINGWITHWAVE ( ('S'<<24) | ('T'<<16) | ('R'<<8) | ('W') ) -#define CSF_VERSION 3 - -#define STRING_FILE 0 -#define CSF_FILE 1 -#define MAX_UITEXT_LENGTH (10*1024) -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - -//=============================== -// StringInfo -//=============================== - -struct StringInfo -{ - std::string label; - std::wstring text; - std::string speech; -}; - -struct StringLookUp -{ - std::string *label; - StringInfo *info; -}; - -//=============================== -// CSFHeader -//=============================== - -struct CSFHeader -{ - Int id; - Int version; - Int num_labels; - Int num_strings; - Int skip; - Int langid; - -}; - -//=============================== -// struct NoString -//=============================== - -struct NoString -{ - struct NoString *next; - std::wstring text; -}; - - -//=============================== -// GameTextManager -//=============================== - -class GameTextManager : public GameTextInterface -{ - public: - - GameTextManager(); - virtual ~GameTextManager(); - - virtual void init( void ); ///< Initlaizes the text system - virtual void deinit( void ); ///< De-initlaizes the text system - virtual void update( void ) {}; ///< update text manager - virtual void reset( void ); ///< Resets the text system - - virtual const wchar_t * fetch( const Char *label ); ///< Returns the associated labeled unicode text - protected: - - Int m_textCount; - Int m_maxLabelLen; - Char m_buffer[MAX_UITEXT_LENGTH]; - Char m_buffer2[MAX_UITEXT_LENGTH]; - Char m_buffer3[MAX_UITEXT_LENGTH]; - WideChar m_tbuffer[MAX_UITEXT_LENGTH*2]; - - StringInfo *m_stringInfo; - StringLookUp *m_stringLUT; - Bool m_initialized; - Bool m_jabberWockie; - Bool m_munkee; - NoString *m_noStringList; - Int m_useStringFile; - std::wstring m_failed; - - void stripSpaces ( WideChar *string ); - void removeLeadingAndTrailing ( Char *m_buffer ); - void readToEndOfQuote( File *file, Char *in, Char *out, Char *wavefile, Int maxBufLen ); - void reverseWord ( Char *file, Char *lp ); - void translateCopy( WideChar *outbuf, Char *inbuf ); - Bool getStringCount( Char *filename); - Bool getCSFInfo ( Char *filename ); - Bool parseCSF( Char *filename ); - Bool parseStringFile( char *filename ); - Bool readLine( char *buffer, Int max, File *file ); - Char readChar( File *file ); -}; - -static int _cdecl compareLUT ( const void *, const void*); -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - -GameTextInterface *TheGameText = NULL; - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - -//============================================================================ -// CreateGameTextInterface -//============================================================================ - -GameTextInterface* CreateGameTextInterface( void ) -{ - return new GameTextManager; -} - - -//============================================================================ -// GameTextManager::GameTextManager -//============================================================================ - -GameTextManager::GameTextManager() -: m_textCount(0), - m_maxLabelLen(0), - m_stringInfo(NULL), - m_stringLUT(NULL), - m_initialized(FALSE), - m_jabberWockie(FALSE), - m_munkee(FALSE), - m_noStringList(NULL), - m_useStringFile(TRUE), - m_failed(L"***FATAL*** String Manager failed to initilaized properly") -{ -} - -//============================================================================ -// GameTextManager::~GameTextManager -//============================================================================ - -GameTextManager::~GameTextManager() -{ - deinit(); -} - -//============================================================================ -// GameTextManager::init -//============================================================================ - -extern char szArgvPath[]; - -void GameTextManager::init( void ) -{ - const Char *strFile = "autorun.str"; - const Char *csfFile = "autorun.csf"; - Int format; - - Char realStrFile[_MAX_PATH]; - Char realCsfFile[_MAX_PATH]; - - strncpy(realStrFile, szArgvPath, _MAX_PATH); - strncpy(realCsfFile, szArgvPath, _MAX_PATH); - - strncat(realStrFile, strFile, _MAX_PATH - strlen(realStrFile)); - strncat(realCsfFile, csfFile, _MAX_PATH - strlen(realCsfFile)); - - if ( m_initialized ) - { - return; - } - - m_initialized = TRUE; - - m_maxLabelLen = 0; - m_jabberWockie = FALSE; - m_munkee = FALSE; - - if ( m_useStringFile && getStringCount( realStrFile) ) - { - format = STRING_FILE; - } - else if ( getCSFInfo ( realCsfFile ) ) - { - format = CSF_FILE; - } - else - { - return; - } - - if( (m_textCount == 0) ) - { - return; - } - - //Allocate StringInfo Array - - m_stringInfo = new StringInfo[m_textCount]; - - if( m_stringInfo == NULL ) - { - deinit(); - return; - } - - if ( format == STRING_FILE ) - { - if( parseStringFile( realStrFile ) == FALSE ) - { - deinit(); - return; - } - } - else - { - if ( !parseCSF ( realCsfFile ) ) - { - deinit(); - return; - } - } - - m_stringLUT = new StringLookUp[m_textCount]; - - StringLookUp *lut = m_stringLUT; - StringInfo *info = m_stringInfo; - - for ( Int i = 0; i < m_textCount; i++ ) - { - lut->info = info; - lut->label = &info->label; - lut++; - info++; - } - - qsort( m_stringLUT, m_textCount, sizeof(StringLookUp), compareLUT ); - -} - -//============================================================================ -// GameTextManager::deinit -//============================================================================ - -void GameTextManager::deinit( void ) -{ - - if( m_stringInfo != NULL ) - { - delete [] m_stringInfo; - m_stringInfo = NULL; - } - - if( m_stringLUT != NULL ) - { - delete [] m_stringLUT; - m_stringLUT = NULL; - } - - m_textCount = 0; - - NoString *noString = m_noStringList; - - DEBUG_LOG(("\n*** Missing strings ***\n")); - while ( noString ) - { - DEBUG_LOG(("*** %ls ***\n", noString->text.str())); - NoString *next = noString->next; - delete noString; - noString = next; - } - DEBUG_LOG(("*** End missing strings ***\n\n")); - - m_noStringList = NULL; - - m_initialized = FALSE; -} - -//============================================================================ -// GameTextManager::reset -//============================================================================ - -void GameTextManager::reset( void ) -{ -} - - -//============================================================================ -// GameTextManager::stripSpaces -//============================================================================ - -void GameTextManager::stripSpaces ( WideChar *string ) -{ - WideChar *str, *ptr; - WideChar ch, last = 0; - Int skipall = TRUE; - - str = ptr = string; - - while ( (ch = *ptr++) != 0 ) - { - if ( ch == ' ' ) - { - if ( last == ' ' || skipall ) - { - continue; - } - } - - if ( ch == '\n' || ch == '\t' ) - { - // remove last space - if ( last == ' ' ) - { - str--; - } - - skipall = TRUE; // skip all spaces - last = *str++ = ch; - continue; - } - - last = *str++ = ch; - skipall = FALSE; - } - - if ( last == ' ' ) - { - str--; - } - - *str = 0; -} - -//============================================================================ -// GameTextManager::removeLeadingAndTrailing -//============================================================================ - -void GameTextManager::removeLeadingAndTrailing ( Char *buffer ) -{ - Char *first, *ptr; - Char ch; - - ptr = first = buffer; - - while ( (ch = *first) != 0 && iswspace ( ch )) - { - first++; - } - - while ( (*ptr++ = *first++) != 0 ); - - ptr -= 2;; - - while ( (ptr > buffer) && (ch = *ptr) != 0 && iswspace ( ch ) ) - { - ptr--; - } - - ptr++; - *ptr = 0; -} - -//============================================================================ -// GameTextManager::readToEndOfQuote -//============================================================================ - -void GameTextManager::readToEndOfQuote( File *file, Char *in, Char *out, Char *wavefile, Int maxBufLen ) -{ - Int slash = FALSE; - Int state = 0; - Int line_start = FALSE; - Char ch; - Int ccount = 0; - Int len = 0; - Int done = FALSE; - - while ( maxBufLen ) - { - // get next Char - - if ( in ) - { - if ( (ch = *in++) == 0 ) - { - in = NULL; // have exhausted the input m_buffer - ch = readChar ( file ); - } - } - else - { - ch = readChar ( file ); - } - - if ( ch == EOF ) - { - return ; - } - - if ( ch == '\n' ) - { - line_start = TRUE; - slash = FALSE; - ccount = 0; - ch = ' '; - } - else if ( ch == '\\' && !slash) - { - slash = TRUE; - } - else if ( ch == '\\' && slash) - { - slash = FALSE; - } - else if ( ch == '"' && !slash ) - { - break; // done - } - else - { - slash = FALSE; - } - - if ( iswspace ( ch )) - { - ch = ' '; - } - - *out++ = ch; - maxBufLen--; - } - - *out = 0; - - while ( !done ) - { - // get next Char - - if ( in ) - { - if ( (ch = *in++) == 0 ) - { - in = NULL; // have exhausted the input m_buffer - ch = readChar ( file ); - } - } - else - { - ch = readChar ( file ); - } - - if ( ch == '\n' || ch == EOF ) - { - break; - } - - switch ( state ) - { - - case 0: - if ( iswspace ( ch ) || ch == '=' ) - { - break; - } - - state = 1; - case 1: - if ( ( ch >= 'a' && ch <= 'z') || ( ch >= 'A' && ch <='Z') || (ch >= '0' && ch <= '9') || ch == '_' ) - { - *wavefile++ = ch; - len++; - break; - } - state = 2; - case 2: - break; - } - } - - *wavefile = 0; - - if ( len ) - { - if ( ( ch = *(wavefile-1)) >= '0' && ch <= '9' ) - { - *wavefile++ = 'e'; - *wavefile = 0; - } - } - -} - - -//============================================================================ -// GameTextManager::reverseWord -//============================================================================ - -void GameTextManager::reverseWord ( Char *file, Char *lp ) -{ - Int first = TRUE; - Char f, l; - Int ok = TRUE ; - - while ( ok ) - { - if ( file >= lp ) - { - return; - } - - f = *file; - l = *lp; - - if ( first ) - { - if ( f >= 'A' && f <= 'Z' ) - { - if ( l >= 'a' && l <= 'z' ) - { - f = (f - 'A') + 'a'; - l = (l - 'a') + 'A'; - } - } - - first = FALSE; - } - - *lp-- = f; - *file++ = l; - - } - -} - -//============================================================================ -// GameTextManager::translateCopy -//============================================================================ - -void GameTextManager::translateCopy( WideChar *outbuf, Char *inbuf ) -{ - Bool slash = FALSE; - - if ( m_jabberWockie ) - { - static Char buffer[MAX_UITEXT_LENGTH*2]; - Char *firstLetter = NULL, *lastLetter; - Char *b = buffer; - Int formatWord = FALSE; - Char ch; - - while ( (ch = *inbuf++) != 0 ) - { - if ( ! (( ch >= 'a' && ch <= 'z') || ( ch >= 'A' && ch <= 'Z' ))) - { - if ( firstLetter ) - { - if ( !formatWord ) - { - lastLetter = b-1; - reverseWord ( firstLetter, lastLetter ); - } - firstLetter = NULL; - formatWord = FALSE; - } - *b++ = ch; - if ( ch == '\\' ) - { - *b++ = *inbuf++; - } - if ( ch == '%' ) - { - while ( (ch = *inbuf++) != 0 && !( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) - { - *b++ = ch; - } - *b++ = ch; - } - } - else - { - if ( !firstLetter ) - { - firstLetter = b; - } - - *b++ = ch; - - } - } - - if ( firstLetter ) - { - lastLetter = b-1; - reverseWord ( firstLetter, lastLetter ); - } - - *b++ = 0; - inbuf = buffer; - } - else if( m_munkee ) - { - wcscpy(outbuf, L"Munkee"); - return; - } - - while( *inbuf != '\0' ) - { - if( slash == TRUE ) - { - slash = FALSE; - - switch( *inbuf ) - { - // in case end of string is reached - // should never happen!!! - case '\0': - return; - - case '\\': - *outbuf++ = '\\'; - break; - - case '\'': - *outbuf++ = '\''; - break; - - case '\"': - *outbuf++ = '\"'; - break; - - case '\?': - *outbuf++ = '\?'; - break; - - case 't': - *outbuf++ = '\t'; - break; - - case 'n': - *outbuf++ = '\n'; - break; - - default: - *outbuf++ = *inbuf & 0x00FF; - break; - } - } - else if( *inbuf != '\\' ) - { - *outbuf++ = *inbuf & 0x00FF; - } - else - slash = TRUE; - - inbuf++; - } - *outbuf= 0; -} - -//============================================================================ -// GameTextManager::getStringCount -//============================================================================ - -Bool GameTextManager::getStringCount( char *filename ) -{ - Int ok = TRUE; - - m_textCount = 0; - - RAMFile file; - - if ( !file.open( filename, File::READ | File::TEXT )) - { - return FALSE; - } - - while(ok) - { - if( !readLine( m_buffer, sizeof( m_buffer) -1, &file ) ) - break; - removeLeadingAndTrailing ( m_buffer ); - - if( m_buffer[0] == '"' ) - { - Int len = strlen(m_buffer); - m_buffer[ len ] = '\n'; - m_buffer[ len+1] = 0; - readToEndOfQuote( &file, &m_buffer[1], m_buffer2, m_buffer3, MAX_UITEXT_LENGTH ); - } - else if( !stricmp( m_buffer, "END") ) - { - m_textCount++; - } - } - - m_textCount += 500; - file.close(); - return TRUE; -} - -//============================================================================ -// GameTextManager::getCSFInfo -//============================================================================ - -Bool GameTextManager::getCSFInfo ( Char *filename ) -{ - CSFHeader header; - Int ok = FALSE; - RAMFile file; - - if ( file.open( filename, File::READ | File::BINARY ) ) - { - if ( file.read( &header, sizeof ( header )) == sizeof ( header ) ) - { - if ( header.id == CSF_ID ) - { - m_textCount = header.num_labels; - - ok = TRUE; - } - } - - file.close(); - } - - return ok; -} - -//============================================================================ -// GameTextManager::parseCSF -//============================================================================ - -Bool GameTextManager::parseCSF( Char *filename ) -{ - RAMFile file; - Int id; - Int len; - Int listCount = 0; - Bool ok = FALSE; - CSFHeader header; - - if ( !file.open( filename, File::READ | File::BINARY ) ) - { - return FALSE; - } - - if ( file.read ( &header, sizeof ( CSFHeader)) != sizeof ( CSFHeader) ) - { - return FALSE; - } - - while( file.read ( &id, sizeof (id)) == sizeof ( id) ) - { - Int num; - Int num_strings; - - if ( id != CSF_LABEL ) - { - goto quit; - } - - file.read ( &num_strings, sizeof ( Int )); - - file.read ( &len, sizeof ( Int ) ); - - if ( len ) - { - file.read ( m_buffer, len ); - } - - m_buffer[len] = 0; - - m_stringInfo[listCount].label = m_buffer; - - - if ( len > m_maxLabelLen ) - { - m_maxLabelLen = len; - } - - num = 0; - - while ( num < num_strings ) - { - file.read ( &id, sizeof ( Int ) ); - - if ( id != CSF_STRING && id != CSF_STRINGWITHWAVE ) - { - goto quit; - } - - file.read ( &len, sizeof ( Int ) ); - - if ( len ) - { - file.read ( m_tbuffer, len*sizeof(WideChar) ); - } - - if ( num == 0 ) - { - // only use the first string found - m_tbuffer[len] = 0; - - { - WideChar *ptr; - - ptr = m_tbuffer; - - while ( *ptr ) - { - *ptr = ~*ptr; - ptr++; - } - } - - stripSpaces ( m_tbuffer ); - m_stringInfo[listCount].text = m_tbuffer; - } - - if ( id == CSF_STRINGWITHWAVE ) - { - file.read ( &len, sizeof ( Int ) ); - if ( len ) - { - file.read ( m_buffer, len ); - } - m_buffer[len] = 0; - - if ( num == 0 && len ) - { - // only use the first string found - m_stringInfo[listCount].speech = m_buffer; - } - - } - - num++; - } - - listCount++; - } - - ok = TRUE; - -quit: - - file.close(); - - return ok; -} - - -//============================================================================ -// GameTextManager::parseStringFile -//============================================================================ - -Bool GameTextManager::parseStringFile( char *filename ) -{ - Int listCount = 0; - Int ok = TRUE; - - RAMFile file; - - if ( !file.open( filename, File::READ | File::TEXT ) ) - { - return FALSE; - } - - while( ok ) - { - Int len; - if( !readLine( m_buffer, MAX_UITEXT_LENGTH, &file )) - { - break; - } - - removeLeadingAndTrailing ( m_buffer ); - - if( ( *(unsigned short *)m_buffer == 0x2F2F) || !m_buffer[0]) // 0x2F2F is Hex for // - continue; - - // make sure label is unique - - for ( Int i = 0; i < listCount; i++ ) - { - if ( !stricmp ( m_stringInfo[i].label.c_str(), m_buffer )) - { - DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' multiply defined!", m_buffer )); - } - } - - m_stringInfo[listCount].label = m_buffer; - len = strlen ( m_buffer ); - - - if ( len > m_maxLabelLen ) - { - m_maxLabelLen = len; - } - - Bool readString = FALSE; - while( ok ) - { - if (!readLine ( m_buffer, sizeof(m_buffer)-1, &file )) - { - DEBUG_ASSERTCRASH (FALSE, ("Unexpected end of string file")); - ok = FALSE; - goto quit; - } - - removeLeadingAndTrailing ( m_buffer ); - - if( m_buffer[0] == '"' ) - { - len = strlen(m_buffer); - m_buffer[ len ] = '\n'; - m_buffer[ len+1] = 0; - readToEndOfQuote( &file, &m_buffer[1], m_buffer2, m_buffer3, MAX_UITEXT_LENGTH ); - - - if ( readString ) - { - // only one string per label allows - DEBUG_ASSERTCRASH ( FALSE, ("String label '%s' has more than one string defined!", m_stringInfo[listCount].label.str())); - } - else - { - // Copy string into new home - translateCopy( m_tbuffer, m_buffer2 ); - stripSpaces ( m_tbuffer ); - - m_stringInfo[listCount].text = m_tbuffer ; - m_stringInfo[listCount].speech = m_buffer3; - readString = TRUE; - } - } - else if ( !stricmp ( m_buffer, "END" )) - { - break; - } - } - - listCount++; - } - -quit: - - file.close(); - - return ok; -} - -//============================================================================ -// *GameTextManager::fetch -//============================================================================ - -const wchar_t * GameTextManager::fetch( const Char *label ) -{ - DEBUG_ASSERTCRASH ( m_initialized, ("String Manager has not been m_initialized") ); - - if( m_stringInfo == NULL ) - { - return m_failed.c_str(); - } - - StringLookUp *lookUp; - StringLookUp key; - std::string lb; - lb = label; - key.info = NULL; - key.label = &lb; - - lookUp = (StringLookUp *) bsearch( &key, (void*) m_stringLUT, m_textCount, sizeof(StringLookUp), compareLUT ); - - if( lookUp == NULL ) - { - // See if we already have the missing string - wchar_t tmp[256]; - _snwprintf(tmp, 256, L"MISSING: '%hs'", label); - tmp[255] = 0; - std::wstring missingString = tmp; - - NoString *noString = m_noStringList; - - while ( noString ) - { - if (noString->text == missingString) - return missingString.c_str(); - - noString = noString->next; - } - - //DEBUG_LOG(("*** MISSING:'%s' ***\n", label)); - // Remember file could have been altered at this point. - noString = new NoString; - noString->text = missingString; - noString->next = m_noStringList; - m_noStringList = noString; - return noString->text.c_str(); - } - return lookUp->info->text.c_str(); -} - -//============================================================================ -// GameTextManager::readLine -//============================================================================ - -Bool GameTextManager::readLine( char *buffer, Int max, File *file ) -{ - Int ok = FALSE; - - while ( max && file->read( buffer, 1 ) == 1 ) - { - ok = TRUE; - - if ( *buffer == '\n' ) - { - break; - } - - buffer++; - max--; - } - - *buffer = 0; - - return ok; -} - -//============================================================================ -// GameTextManager::readChar -//============================================================================ - -Char GameTextManager::readChar( File *file ) -{ - Char ch; - - if ( file->read( &ch, 1 ) == 1 ) - { - return ch; - } - - return 0; -} - -//============================================================================ -// GameTextManager::compareLUT -//============================================================================ - -static int __cdecl compareLUT ( const void *i1, const void*i2) -{ - StringLookUp *lut1 = (StringLookUp*) i1; - StringLookUp *lut2 = (StringLookUp*) i2; - - return stricmp( lut1->label->c_str(), lut2->label->c_str()); -} diff --git a/Generals/Code/Tools/Autorun/GameText.h b/Generals/Code/Tools/Autorun/GameText.h deleted file mode 100644 index 2008936b1e..0000000000 --- a/Generals/Code/Tools/Autorun/GameText.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: RTS 3 -// -// File name: GameClient/GameText.h -// -// Created: 11/07/01 -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef __GAMECLIENT_GAMETEXT_H_ -#define __GAMECLIENT_GAMETEXT_H_ - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// GameTextInterface -//=============================== -/** Game text interface object for localised text. - */ -//=============================== - -class GameTextInterface -{ - - public: - - virtual ~GameTextInterface() {}; - - virtual void init( void ) = 0; ///< Initlaizes the text system - virtual const wchar_t * fetch( const char *label ) = 0; ///< Returns the associated labeled unicode text - -}; - - -extern GameTextInterface *TheGameText; -extern GameTextInterface* CreateGameTextInterface( void ); - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - -#endif // __GAMECLIENT_GAMETEXT_H_ diff --git a/Generals/Code/Tools/Autorun/GetCD.h b/Generals/Code/Tools/Autorun/GetCD.h deleted file mode 100644 index 72c3130510..0000000000 --- a/Generals/Code/Tools/Autorun/GetCD.h +++ /dev/null @@ -1,323 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/************************************************************************************************ - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S **** - ************************************************************************************************ - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Renegade Setup/Autorun/GetCD.h $Author:: Denzil_l * - * $Modtime:: 1/08/02 3:38p $Revision:: 20 * - * * - *----------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ - -#pragma once - -#ifndef GETCD_H -#define GETCD_H - - -extern const char * _CD_Volume_Label[]; -extern int _Num_Volumes; - - - -#ifdef NOT_FOR_WIN95 - -/* ==================================================================== */ -/* Defines */ -/* ==================================================================== */ -#define CHLEFT 0 -#define CHRIGHT 1 -#define CHBOTH 2 -#define AUDIO_START_MIN 1 -#define AUDIO_START_SEC 44 - -struct SEGSEL { - unsigned short seg ; - unsigned short sel ; -}; - -extern "C" int DPMI_real_alloc ( UINT , SEGSEL * , USHORT * ) ; -extern "C" int DPMI_real_free ( SEGSEL ) ; -extern "C" void DPMI_real_intr ( int , union REGS * , struct SREGS * ); -extern "C" void DPMI_real_call ( void * funct , union REGS * , struct SREGS * ); - -/* ==================================================================== */ -/* Data structures */ -/* ==================================================================== */ - -//----------------------------------------------------------------------------- -// Audio Track Info request block -//----------------------------------------------------------------------------- -#pragma pack(push, 1) -struct TinfoType { - UBYTE Length; - UBYTE SubCd; - UBYTE Command; - UWORD Status; - UBYTE Rsvd[8]; - UBYTE MDescr; - - UWORD TrnsAdOff; - UWORD TrnsAdSeg; - - UWORD CntTrns; - UWORD StSect; - - UWORD VolIDOff; - UWORD VolIDSeg; - - UBYTE TrInfo; - UBYTE Track; - ULONG Start; - UBYTE TrCtrl; -}; -#pragma pack(pop) - -//----------------------------------------------------------------------------- -// Audio Track Status Control Block -//----------------------------------------------------------------------------- -#pragma pack(push, 1) -struct StatType { - UBYTE Length; - UBYTE SubCd; - UBYTE Command; - UWORD Status; - UBYTE Rsvd[8]; - UBYTE MDescr; - - UWORD TrnsAdOff; - UWORD TrnsAdSeg; - - UWORD CntTrns; - UWORD StSect; - - UWORD VolIDOff; - UWORD VolIDSeg; - - UBYTE StatInfo; - UWORD Stat; - ULONG Start; - ULONG End; -}; -#pragma pack(pop) - -//----------------------------------------------------------------------------- -// Audio Track Volume control block -//----------------------------------------------------------------------------- -#pragma pack(push, 1) -struct VolmType { - UBYTE Length; - UBYTE SubCd; - UBYTE Command; - UWORD Status; - UBYTE Rsvd[8]; - UBYTE MDescr; - - UWORD TrnsAdOff; - UWORD TrnsAdSeg; - - UWORD CntTrns; - UWORD StSect; - - UWORD VolIDOff; - UWORD VolIDSeg; - - UBYTE TrInfo; - UBYTE In0; - UBYTE Vol0; - UBYTE In1; - UBYTE Vol1; - UBYTE In2; - UBYTE Vol2; - UBYTE In3; - UBYTE Vol3; -}; -#pragma pack(pop) - -//----------------------------------------------------------------------------- -// Audio Track Play request block -//----------------------------------------------------------------------------- -#pragma pack(push, 1) -struct PlayType { - UBYTE Length; - UBYTE SubCd; - UBYTE Command; - UWORD Status; - UBYTE Rsvd[8]; - UBYTE AddrMd; - ULONG Start; - ULONG CntSect; -}; -#pragma pack(pop) - - -//----------------------------------------------------------------------------- -// Audio Track Stop request block -//----------------------------------------------------------------------------- -#pragma pack(push, 1) -struct StopType { - UBYTE Length; - UBYTE SubCd; - UBYTE Command; - UWORD Status; - UBYTE Rsvd[8]; -}; -#pragma pack(pop) - -#endif //NOT_FOR_WIN95 - - -/**************************************************************************** - * GetCDClass -- object which will return logical CD drive * - * * - * HISTORY: * - * 06/04/1994 SW : Created. * - *==========================================================================*/ - -#define MAX_CD_DRIVES 26 -#define NO_CD_DRIVE -1 - -class GetCDClass -{ - public: - GetCDClass ( void ); // This is the default constructor - ~GetCDClass ( void ); // This is the destructor - - inline int Get_First_CD_Drive ( void ); - inline int Get_Next_CD_Drive ( void ); - inline int Get_Number_Of_Drives ( void ) { return( CDCount ); }; - inline int Get_Index ( void ) { return( CDIndex ); }; - inline void Reset_Index ( void ) { CDIndex = 0; }; - - int Get_CD_Drive_For_This_Volume ( const char *volume_name ); - const char * Get_Volume_For_This_CD_Drive ( const char *path, char *volume_name ); - const char * Get_Volume_Label ( int index ); - - protected: - - int CDDrives[ MAX_CD_DRIVES ]; //Array containing CD drive letters - int CDCount; //Number of available CD drives - int CDIndex; //Index of current location -}; - -/**************************************************************************** - * GCDC::Get_First_CD_Drive -- return the number of the first CD drive * - * * - * INPUT: none * - * * - * OUTPUT: logical drive number * - * * - * WARNINGS: * - * * - * HISTORY: * - * 05/26/1994 SW : Created. * - * 12/4/95 ST : fixed for Win95 * - *==========================================================================*/ - -inline int GetCDClass::Get_First_CD_Drive(void) -{ - CDIndex = 0; - return (Get_Next_CD_Drive()); -} - -/************************************************************************************ - * GCDC::Get_Next_CD_Drive -- return the logical drive number of the next CD drive * - * * - * INPUT: Nothing * - * * - * OUTPUT: Logical drive number of a cd drive or -1 if none * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 5/21/96 3:50PM ST : Created * - *==================================================================================*/ - -inline int GetCDClass::Get_Next_CD_Drive(void) -{ - if (CDCount){ - if (CDIndex >= CDCount) { - CDIndex = 0; - } - return (CDDrives[CDIndex++]); - } else { - return (-1); - } -} - - -/************************************************************************************ - * RedBookClass -- adds red book functionality * - * * - * this class inherits from GetCDClass and adds red book play functionality * - * * - * * - * HISTORY: * - * 06/04/1994 SW : Created. * - *==================================================================================*/ - -#ifdef NOT_FOR_WIN95 -class RedBookClass : public GetCDClass -{ - public: - - RedBookClass(void); // This is the default constructor - ~RedBookClass(void); // This is the destructor - ULONG RedToHS(ULONG i); - ULONG MSFtoRed(UBYTE m, UBYTE s, UBYTE f); - void FullCDVolume(UBYTE chan); - void PlayTrack(UWORD track); - void Play_CD_MSL(UWORD min_sec, UWORD len); - void PlayMSF(UBYTE startM, UBYTE startS, UBYTE startF, - UBYTE endM, UBYTE endS, UBYTE endF, UBYTE chan); - UWORD CheckCDMusic(void); - void StopCDMusic(void); - - private: - - SEGSEL Tinfo_addrp; - SEGSEL Stat_addrp; - SEGSEL Stop_addrp; - SEGSEL Volm_addrp; - SEGSEL Play_addrp; - - StopType Stop; - PlayType Play; - VolmType Volm; - StatType Stat; - TinfoType Tinfo; -}; - -#endif //NOT_FOR_WIN95 - -/***************************** End of Playcd.h ****************************/ - -extern GetCDClass CDList; - -//----------------------------------------------------------------------------- -// Functions -//----------------------------------------------------------------------------- -bool CD_Volume_Verification ( int cd_drive, char *volume_label, char *volume_to_find ); - - -#endif // PLAYCD_H diff --git a/Generals/Code/Tools/Autorun/IGR.cpp b/Generals/Code/Tools/Autorun/IGR.cpp deleted file mode 100644 index 303480840c..0000000000 --- a/Generals/Code/Tools/Autorun/IGR.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// IGR.cpp - A class used to access the IGR registry settings. -// -// JeffB 7/5/00 -// - -#include -#include -#include -//#include "always.h" -#include "IGR.h" - - -IGROptionsClass *OnlineOptions = NULL; - - -/********************************************************************************************* - * IGROptions::Init -- Class initializer. Reads from the registry * - * * - * INPUT: None * - * * - * OUTPUT: bool; Did we read everything OK? * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/05/00 JeffB: Initial coding * - *===========================================================================================*/ -bool IGROptionsClass::Init( void ) -{ - int size; - int returnValue; - HKEY handle; - char key[128]; - unsigned long type; - - valid = false; - - // Load the options from the registry - size = sizeof( int ); - - // Setup the key - strcpy( key, WOLAPI_REG_KEY_BOTTOM ); - - // Get a handle to the WOLAPI entry - if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_ALL_ACCESS, &handle ) == ERROR_SUCCESS ) { - - // If successful, get the options - IGROptionsType ReadOptions = 0; - - returnValue = RegQueryValueEx(handle, WOLAPI_REG_KEY_OPTIONS, NULL, - (unsigned long *) &type, (unsigned char *) &ReadOptions, (unsigned long *)&size); - - if (returnValue == ERROR_SUCCESS) { - - // If successful, and we got a DWORD, store options and set the valid flage - if (type == REG_DWORD) { - options = ReadOptions; - valid = true; - } - } - - // Clean up - RegCloseKey( handle ); - } - return ( valid ); -} - -/*********************************************************************************************** - * IGROptions::Is_Auto_Login_Allowed -- Set the passed options in the registry * - * * - * INPUT: None * - * * - * OUTPUT: bool; Is the option set * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/05/00 JeffB: Initial coding * - *=============================================================================================*/ -bool IGROptionsClass::Is_Auto_Login_Allowed( void ) -{ - return(( options & IGR_NO_AUTO_LOGIN ) == 0 ); -} - -/*********************************************************************************************** - * IGROptions::Is_Storing_Nicks_Allowed -- Set the passed options in the registry * - * * - * INPUT: None * - * * - * OUTPUT: bool; Is the option set * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/05/00 JeffB: Initial coding * - *=============================================================================================*/ -bool IGROptionsClass::Is_Storing_Nicks_Allowed( void ) -{ - return(( options & IGR_NEVER_STORE_NICKS ) == 0 ); -} - -/*********************************************************************************************** - * IGROptions::Is_Running_Reg_App_Allowed -- Set the passed options in the registry * - * * - * INPUT: None * - * * - * OUTPUT: bool; Is the option set * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/05/00 JeffB: Initial coding * - *=============================================================================================*/ -bool IGROptionsClass::Is_Running_Reg_App_Allowed( void ) -{ - return(( options & IGR_NEVER_RUN_REG_APP ) == 0 ); -} - -/********************************************************************************************* - * IGROptions::Set_Options -- Set the passed options in the registry * - * * - * INPUT: Options to set * - * * - * OUTPUT: bool; Did we set the options successfully * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/05/00 JeffB: Initial coding * - *===========================================================================================*/ -bool IGROptionsClass::Set_Options( IGROptionsType options ) -{ - bool ReturnValue = false; - HKEY handle; - int disp; - char key[ 128 ]; - - // We don't care if it's valid, we'll MAKE it valid. - strcpy( key, WOLAPI_REG_KEY_BOTTOM ); - - // Do they have the WOLAPI key? - if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_ALL_ACCESS, &handle ) != ERROR_SUCCESS ) { - - // If not, make the WOLAPI key - if( RegCreateKeyEx( HKEY_LOCAL_MACHINE, key, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, - NULL, &handle, (unsigned long *)&disp ) != ERROR_SUCCESS ) - return false; - } - - if( RegSetValueEx( handle, WOLAPI_REG_KEY_OPTIONS, 0, REG_DWORD, (unsigned char *)&options, sizeof(int)) - == ERROR_SUCCESS ) { - ReturnValue = true; - } - RegCloseKey( handle ); - - // Reinit the class to make sure we have these settings for later queries. - Init(); - - assert( valid == TRUE ); - - return ReturnValue; -} diff --git a/Generals/Code/Tools/Autorun/IGR.h b/Generals/Code/Tools/Autorun/IGR.h deleted file mode 100644 index 1665e4c07b..0000000000 --- a/Generals/Code/Tools/Autorun/IGR.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// IGR.h - A class used to access the IGR registry settings. -// -// JeffB 7/5/00 -// - -// -// Registry Path -// -#define WOLAPI_REG_KEY_TOP "HKEY_LOCAL_MACHINE" -#define WOLAPI_REG_KEY_WOLAPI "SOFTWARE\\Westwood\\WOLAPI" -#define WOLAPI_REG_KEY_BOTTOM WOLAPI_REG_KEY_WOLAPI "\\" -#define WOLAPI_REG_KEY_OPTIONS "Options" -#define WOLAPI_REG_KEY WOLAPI_REG_KEY_TOP "\\" WOLAPI_REG_KEY_BOTTOM -#define WOLAPI_KEY "WOLAPI" - -// -// Option Bits for Options key -// -#define IGR_NO_AUTO_LOGIN 0x01 -#define IGR_NEVER_STORE_NICKS 0x02 -#define IGR_NEVER_RUN_REG_APP 0x04 -#define IGR_ALL IGR_NO_AUTO_LOGIN | IGR_NEVER_STORE_NICKS | IGR_NEVER_RUN_REG_APP -#define IGR_NONE 0x00 - -typedef unsigned int IGROptionsType; - -class IGROptionsClass -{ - public: - // Constructor - IGROptionsClass( void ) : valid( false ), options( 0 ) {}; - - // Destructor - ~IGROptionsClass( void ) {}; - - // Initialize. Read value(s) from registry - bool Init( void ); - - // Check various options - bool Is_Auto_Login_Allowed( void ); - bool Is_Storing_Nicks_Allowed( void ); - bool Is_Running_Reg_App_Allowed( void ); - - // Set various options - bool Set_Options( IGROptionsType options ); - - private: - - // Private options - IGROptionsType options; - - // Is the data valid? - bool valid; -}; - -extern IGROptionsClass *OnlineOptions; \ No newline at end of file diff --git a/Generals/Code/Tools/Autorun/JSUPPORT.H b/Generals/Code/Tools/Autorun/JSUPPORT.H deleted file mode 100644 index ee14fe67b9..0000000000 --- a/Generals/Code/Tools/Autorun/JSUPPORT.H +++ /dev/null @@ -1,21 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// JSUPPORT.H -// DBCS Support Header -extern int nGetWord( char *,int ); diff --git a/Generals/Code/Tools/Autorun/Jsupport.cpp b/Generals/Code/Tools/Autorun/Jsupport.cpp deleted file mode 100644 index 2dcfb730a0..0000000000 --- a/Generals/Code/Tools/Autorun/Jsupport.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// JSUPPORT.CPP -// DBCS Support Codes - -#include -#include "JSUPPORT.H" - -// ‘O’u‹Ö‘¥•¶Žš -// Can't set these characters on top of line -static BOOL IsDBCSInvalidAtTop(unsigned int c) -{ - static BYTE * dtbl = (BYTE *)"‘‹fhñŒŽABXrtvxzl‚Ÿ‚¡‚£‚¥‚§‚Á‚á‚ã‚å‚ìJKTUƒ@ƒBƒDƒFƒHƒbƒƒƒ…ƒ‡ƒŽƒ•ƒ–E[RSI“jCDFGHnp"; - static BYTE * stbl = (BYTE *)"!%),.:;?]}¡£¤¥Þß"; - - if(c<0x100) - { - if(strchr((char *)stbl,(char)c)) - return TRUE; - } - else - { - BYTE c1,c2,*p; - c1 = (BYTE)(c >> 8); - c2 = (BYTE)(c & 0xff); - p = dtbl; - while(*p) - { - if((*p==c1)&&(*(p+1)==c2)) - return TRUE; - p+=2; - } - } - return FALSE; -} - -// Œã’u‹Ö‘¥•¶Žš -// Can't set these characters on end of line -static BOOL IsDBCSInvalidAtEnd( unsigned int c ) -{ - static BYTE * dtbl = (BYTE *)"egqsuwykimo’"; - static BYTE * stbl = (BYTE *)"¢({["; - - if(c<0x100) - { - if(strchr((char *)stbl,(char)c)) - return TRUE; - } - else - { - BYTE c1,c2,*p; - c1 = (BYTE)(c >> 8); - c2 = (BYTE)(c & 0xff); - p = dtbl; - while(*p) - { - if((*p==c1)&&(*(p+1)==c2)) - return TRUE; - p+=2; - } - } - return FALSE; -} - -int nGetWord( char *string, int fdbcs ) -{ - BOOL bCiae0, bCiat1, bDbcs0, bDbcs1; - BYTE *p = (BYTE *)string; - UINT c0, c1, c; - - //-------------------------------------------------------------------------- - // If no string was passed in, exit. - //-------------------------------------------------------------------------- - if( !p || !( c0 = *p++ )) { -// if(( p == NULL ) || ( *p == '\0' )) { - return 0; - } -// c0 = *p; - - //-------------------------------------------------------------------------- - // If we are NOT a double-byte language, then just parse first word. - //-------------------------------------------------------------------------- - if( !fdbcs ) { - - int n = 0; - - while( *p >' ' ) { - n++; - p++; - } - - if( *p ) { - n++; - } - return n; - } - - //-------------------------------------------------------------------------- - // If we are a double-byte language... - //-------------------------------------------------------------------------- - bDbcs0 = IsDBCSLeadByte( c0 ) && *p; - - if( bDbcs0 ) { - c0 = ( c0 << 8 ) | *p++; - } - - bCiae0 = IsDBCSInvalidAtEnd( c0 ); - - while( c1 = *p ) { - - bDbcs1 = ( IsDBCSLeadByte( c1 ) && ( c = *( p + 1 ))); - if( bDbcs1 ) { - c1 = ( c1<<8 ) | c; - } - - if(( bDbcs0 || bDbcs1 ) && !( bDbcs0 && bDbcs1 )) { // XOR - break; - } - - if( bDbcs1 ) { - - bCiat1 = IsDBCSInvalidAtTop( c1 ); - - if( !( bCiae0 || bCiat1 )) { - break; - } - bCiae0 = IsDBCSInvalidAtEnd( c1 ); - p+=2; - - } else { - - if( c0<=' ' ) { - break; - } - p++; - } - - bDbcs0 = bDbcs1; - c0 = c1; - } - return( p - (BYTE *)string ); -} diff --git a/Generals/Code/Tools/Autorun/Locale_API.cpp b/Generals/Code/Tools/Autorun/Locale_API.cpp deleted file mode 100644 index fce4991cfb..0000000000 --- a/Generals/Code/Tools/Autorun/Locale_API.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/***************************************************************************** -* C O N F I D E N T I A L --- W E S T W O O D A S S O C I A T E S * -****************************************************************************** -* -* FILE -* $Archive: /Renegade Setup/Autorun/Locale_API.cpp $ -* -* DESCRIPTION -* -* PROGRAMMER -* $Author: Maria_l $ -* -* VERSION INFO -* $Modtime: 1/22/02 5:41p $ -* $Revision: 12 $ -* -*****************************************************************************/ - -#include "locale.h" -#include "Locale_API.h" -#include "Utils.h" -#include "Wnd_File.h" -//#include "resources.h" - -#include "GameText.h" - -#define MISSING_STRING_HINTS_MAX (20) - -const wchar_t *localeStringsMissing[ MISSING_STRING_HINTS_MAX ] = -{ - { L"0 MissingInstall" }, - { L"1 MissingExplore" }, - { L"2 MissingPreviews" }, - { L"3 MissingCancel" }, - { L"4 MissingAutoRunTitle" }, - { L"5 MissingNoExplorer" }, - { L"6 MissingWinVersionText" }, - { L"7 MissingWinVersionTitle" }, - { L"8 MissingCantFind" }, - { L"9 MissingUninstall" }, - { L"10 MissingWebsite" }, - { L"11 MissingCheckForUpdates" }, - { L"12 MissingWorldBuilder" }, - { L"13 MissingPlay" }, - { L"14 MissingGameTitle" }, - { L"15 MissingFullGameTitle" }, - { L"16 MissingRegistryKey" }, - { L"17 MissingMainWindow" }, - { L"18 MissingThing" }, - { L"19 UNKNOWN MESSAGE" } -}; - - - - - - - - - -/****************************************************************************/ -/* DEFINES */ -/****************************************************************************/ - -//---------------------------------------------------------------------------- -// NOTE: if USE_MULTI_FILE_FORMAT is "true", then a .lOC file must be in -// the same directory as this file. -//---------------------------------------------------------------------------- -#define USE_MULTI_FILE_FORMAT FALSE - -#define LANGUAGE_IS_DBCS(l) (((l)==IDL_JAPANESE)||((l)==IDL_KOREAN)||((l)==IDL_CHINESE)) // [OYO] -#define CODEPAGE_IS_DBCS(C) ((C==932)||(C==949)||(C==950)) // [OYO] - - -/****************************************************************************/ -/* GLOBAL VARIABLES */ -/****************************************************************************/ -char LanguageFile[ _MAX_PATH ]; -void * LocaleFile = NULL; -int CodePage = GetACP(); -int LanguageID = 0; -int PrimaryLanguage = LANG_NEUTRAL; -int SubLanguage = SUBLANG_DEFAULT; - - -/****************************************************************************/ -/* LOCALE API */ -/****************************************************************************/ -wchar_t * Remove_Quotes_Around_String ( wchar_t *old_string ); - - -//============================================================================= -// These are wrapper functions around the LOCALE_ functions. I made these to -// make using the single vs. multi language files more transparent to the program. -//============================================================================= - -bool Locale_Use_Multi_Language_Files ( void ) -{ -#if( USE_MULTI_FILE_FORMAT ) - return true; -#else - return false; -#endif -} - - -/****************************************************************************/ -/* initialization */ -/****************************************************************************/ - -int Locale_Init ( int language, char *file ) -{ - int result = 0; - - TheGameText = CreateGameTextInterface(); - TheGameText->init(); - -/* - //------------------------------------------------------------------------- - // Check for valid language range. - //------------------------------------------------------------------------- - if( language < 0 || language >= LANG_NUM ) { - language = 0; - } - - //------------------------------------------------------------------------- - // Check for a file passed in. - //------------------------------------------------------------------------- - if( file == NULL || file[0] == '/0' ) { - return 0; - } - strcpy( LanguageFile, file ); - LanguageID = language; - - Msg( __LINE__, __FILE__, "LanguageID = %d", LanguageID ); - Msg( __LINE__, __FILE__, "CodePage = %d.", CodePage ); - Msg( __LINE__, __FILE__, "LanguageFile = %s.", LanguageFile ); - - //------------------------------------------------------------------------- - // Initialize the lx object. - //------------------------------------------------------------------------- - LOCALE_init(); - - #if( USE_MULTI_FILE_FORMAT ) - - //--------------------------------------------------------------------- - // Set bank to use and load the appropriate table. - //--------------------------------------------------------------------- - LOCALE_setbank(0); - result = LOCALE_loadtable( LanguageFile, LanguageID ); - - #else - - //--------------------------------------------------------------------- - // Create a file buffer that holds all the strings in the file. - //--------------------------------------------------------------------- - long filesize; - HRSRC hRsrc; - HGLOBAL hGlobal; - - HMODULE module = GetModuleHandle( NULL ); - - //------------------------------------------------------------------------- - // Find the string file in this program's resources. - //------------------------------------------------------------------------- - switch( CodePage ) { - - // Japanese - case 932: - PrimaryLanguage = LANG_JAPANESE; - SubLanguage = SUBLANG_DEFAULT; - break; - - // Korean - case 949: - PrimaryLanguage = LANG_KOREAN; - SubLanguage = SUBLANG_DEFAULT; - break; - - // Chinese - case 950: - PrimaryLanguage = LANG_CHINESE; - SubLanguage = SUBLANG_DEFAULT; - break; - - // English, French, and German - case 1252: - - switch( LanguageID ) { - - case LANG_GERMAN: - PrimaryLanguage = LANG_GERMAN; - SubLanguage = SUBLANG_GERMAN; - break; - - case LANG_FRENCH: - PrimaryLanguage = LANG_FRENCH; - SubLanguage = SUBLANG_FRENCH; - break; - - case LANG_ENGLISH: - PrimaryLanguage = LANG_ENGLISH; - SubLanguage = SUBLANG_ENGLISH_US; - break; - } - break; - } - - hRsrc = FindResourceEx( module, RT_RCDATA, "STRINGS", MAKELANGID( PrimaryLanguage, SubLanguage )); - if ( hRsrc == NULL ) { - hRsrc = FindResourceEx( module, RT_RCDATA, "STRINGS", MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US )); - } - if ( hRsrc ) { - - //--------------------------------------------------------------------- - // Load the resource, lock the memory, grab a DC. - //--------------------------------------------------------------------- - hGlobal = LoadResource( module, hRsrc ); - filesize = SizeofResource( module, hRsrc ); - - LocaleFile = (void*)malloc( filesize + 1 ); - memset( LocaleFile, '\0', filesize + 1 ); - memcpy( LocaleFile, (const void *)hGlobal, filesize ); - - //--------------------------------------------------------------------- - // Free DS and memory used. - //--------------------------------------------------------------------- - UnlockResource( hGlobal ); - FreeResource( hGlobal ); - } - - if( LocaleFile == NULL ) { - LocaleFile = Load_File( LanguageFile, &filesize ); - } - - if( LocaleFile != NULL ) { - result = 1; - } - - //--------------------------------------------------------------------- - // Set the LanguageID because we may need this later. - //--------------------------------------------------------------------- -// CHAR buffer[ _MAX_PATH ]; - -// Locale_GetString( LANG_NUM, buffer ); -// LanguageID = atoi( buffer ); - - LanguageID = 0; - -#if(_DEBUG) - switch( LanguageID ) { - case 6: - CodePage = 932; - break; - case 9: - CodePage = 949; - break; - case 10: - CodePage = 950; - break; - } -#endif - - #endif -*/ - return result; -} - -/************************************************************************/ -/* restore */ -/************************************************************************/ - -void Locale_Restore ( void ) -{ - if (TheGameText) - { - delete TheGameText; - TheGameText = NULL; - } - - #if( USE_MULTI_FILE_FORMAT ) - LOCALE_freetable(); - LOCALE_restore(); - #else - if( LocaleFile ) { - free( LocaleFile ); - LocaleFile = NULL; - } - #endif -} - -/****************************************************************************/ -/* retreiving strings */ -/****************************************************************************/ - -const char* Locale_GetString( int StringID, char *String ) -{ - static char buffer[ _MAX_PATH ]; - static wchar_t wide_buffer[ _MAX_PATH ]; - - memset( buffer, '\0', _MAX_PATH ); - memset( wide_buffer, '\0', _MAX_PATH ); - - #if( USE_MULTI_FILE_FORMAT ) - wcscpy( wide_buffer, (wchar_t *)LOCALE_getstring( StringID )); - #else - wcscpy( wide_buffer, (wchar_t *)LOCALE_getstr( LocaleFile, StringID )); - #endif - - Remove_Quotes_Around_String( wide_buffer ); - WideCharToMultiByte( CodePage, 0, wide_buffer, _MAX_PATH, buffer, _MAX_PATH, NULL, NULL ); - - if( String != NULL ) { - strncpy( String, buffer, _MAX_PATH ); - } - - return buffer; -} - -const wchar_t* Locale_GetString( const char *id, wchar_t *buffer, int size ) -{ - if (TheGameText) - { - const wchar_t *fetched = TheGameText->fetch(id); - if (buffer) - { - wcsncpy(buffer, fetched, size); - buffer[size-1] = 0; - } - return fetched; - } - return L"No String Manager"; -} - -/* -const wchar_t* Locale_GetString( int StringID, wchar_t *String ) -{ - static wchar_t wide_buffer[ _MAX_PATH ]; - - memset( wide_buffer, '\0', _MAX_PATH ); - - #if( USE_MULTI_FILE_FORMAT ) - wcscpy( wide_buffer, (wchar_t *)LOCALE_getstring( StringID )); - #else - - wchar_t *localeStr = NULL; - - if (TheGameText != NULL) - localeStr = (wchar_t *)TheGameText->fetch( s_stringLabels[StringID] ); - - if (localeStr == NULL) - { - return localeStringsMissing[ min( MISSING_STRING_HINTS_MAX - 1, StringID ) ]; - } - else - { - wcscpy( wide_buffer, localeStr); - } - #endif - - Remove_Quotes_Around_String( wide_buffer ); - - if( String != NULL ) { - wcsncpy( String, wide_buffer, _MAX_PATH ); - } - - return wide_buffer; -} -*/ - -/****************************************************************************/ -/* formating strings */ -/****************************************************************************/ - -wchar_t *Remove_Quotes_Around_String ( wchar_t *old_string ) -{ - wchar_t wide_buffer[ _MAX_PATH ]; - wchar_t *letter = old_string; - int length; - - //---------------------------------------------------------------------- - // If string is not NULL... - //---------------------------------------------------------------------- - if ( *letter == '"' ) { - - letter++; - wcscpy( wide_buffer, letter ); - - length = wcslen( wide_buffer ); - - if ( wide_buffer[ wcslen( wide_buffer )-1 ] == '"' ) { - wide_buffer[ wcslen( wide_buffer )-1 ] = '\0'; - } - wcscpy( old_string, wide_buffer ); - } - - return( old_string ); -} - - - diff --git a/Generals/Code/Tools/Autorun/Locale_API.h b/Generals/Code/Tools/Autorun/Locale_API.h deleted file mode 100644 index 66c252f7e5..0000000000 --- a/Generals/Code/Tools/Autorun/Locale_API.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/************************************************************************************************ -* C O N F I D E N T I A L --- W E S T W O O D A S S O C I A T E S * -************************************************************************************************* -* -* FILE -* $Archive: /Renegade Setup/Autorun/Locale_API.h $ -* -* DESCRIPTION -* -* PROGRAMMER -* $Author: Maria_l $ -* -* VERSION INFO -* $Modtime: 1/15/02 2:16p $ -* $Revision: 5 $ -* -*************************************************************************************************/ - -#pragma once - -#ifndef LOCALE_API_H -#define LOCALE_API_H - -#include - -/****************************************************************************/ -/* GLOBAL VARIABLES */ -/****************************************************************************/ -extern int CodePage; -extern void * LocaleFile; -extern int LanguageID; -extern char LanguageFile[]; -extern int PrimaryLanguage; -extern int SubLanguage; - -/****************************************************************************/ -/* LOCALE API */ -/****************************************************************************/ -int Locale_Init ( int language, char *file ); -void Locale_Restore ( void ); -const wchar_t* Locale_GetString( const char *id, wchar_t *buffer = NULL, int size = _MAX_PATH ); -/* -const char* Locale_GetString ( int StringID, char *String ); -const wchar_t* Locale_GetString ( int StringID, wchar_t *String=NULL ); -*/ -bool Locale_Use_Multi_Language_Files ( void ); -//int Locale_Get_Language_ID ( void ) { return LanguageID; }; - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Autorun/POINT.h b/Generals/Code/Tools/Autorun/POINT.h deleted file mode 100644 index 5c4221013e..0000000000 --- a/Generals/Code/Tools/Autorun/POINT.h +++ /dev/null @@ -1,242 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name: Command & Conquer * - * * - * Archive: /Sun/Point.h * - * * - * Author: Joe_b * - * * - * Modtime: 2/02/98 10:09a * - * * - * Revision: 24 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#pragma once - -#ifndef POINT_H -#define POINT_H - -#include -//#include "always.h" -//#include "cctypes.h" - -//#ifdef __cplusplus -//extern "C"{ -//#endif - -//#pragma pack(1) - -typedef struct Point2DStruct -{ - int X; - int Y; -} Point2DStruct; - -//#pragma pack() - -//#ifdef __cplusplus -//} -//#endif - - - -template class TRect; - -/*********************************************************************************************** -** This class describes a point in 2 dimensional space using arbitrary -** components. The interpretation of which is outside the scope -** of this class. This class is the successor to the old style COORDINATE -** and CELL types but also serves anywhere an X and Y value are treated -** as a logical object (e.g., pixel location). -*/ -template -class TPoint2D { - public: - TPoint2D(void) {} // Default constructor does nothing by design. - TPoint2D(T x, T y) : X(x), Y(y) {} - - // Equality comparison operators. - bool operator == (TPoint2D const & rvalue) const {return(X==rvalue.X && Y==rvalue.Y);} - bool operator != (TPoint2D const & rvalue) const {return(X!=rvalue.X || Y!=rvalue.Y);} - - // Addition and subtraction operators. - TPoint2D const & operator += (TPoint2D const & rvalue) {X += rvalue.X;Y += rvalue.Y;return(*this);} - TPoint2D const & operator -= (TPoint2D const & rvalue) {X -= rvalue.X;Y -= rvalue.Y;return(*this);} - TPoint2D const operator - (TPoint2D const & rvalue) const {return(TPoint2D(T(X - rvalue.X), T(Y - rvalue.Y)));} - TPoint2D const operator + (TPoint2D const & rvalue) const {return(TPoint2D(T(X + rvalue.X), T(Y + rvalue.Y)));} - - // Scalar multiplication and division. - TPoint2D const operator * (T rvalue) const {return(TPoint2D(T(X * rvalue), T(Y * rvalue)));} - TPoint2D const & operator *= (T rvalue) {X *= rvalue; Y *= rvalue;return(*this);} - TPoint2D const operator / (T rvalue) const {if (rvalue == T(0)) return(TPoint2D(0,0));return(TPoint2D(T(X / rvalue), T(Y / rvalue)));} - TPoint2D const & operator /= (T rvalue) {if (rvalue != T(0)) {X /= rvalue;Y /= rvalue;}return(*this);} - - // Dot and cross product. - TPoint2D const operator * (TPoint2D const & rvalue) const {return(TPoint2D(T(X * rvalue.X), T(Y * rvalue.Y)));} - T Dot_Product(TPoint2D const & rvalue) const {return((T(X * rvalue.X + Y * rvalue.Y)));} - TPoint2D const Cross_Product(TPoint2D const & rvalue) const {return(TPoint2D(T(Y - rvalue.Y), T(rvalue.X - X)));} - - // Negation operator -- simple and effective - TPoint2D const operator - (void) const {return(TPoint2D(T(-X), T(-Y)));} - - // Vector support functions. - T Length(void) const {return(T(sqrt(double(X*X + Y*Y))));} - TPoint2D const Normalize(void) const { - double len = sqrt(X*X + Y*Y); - if (len != 0.0) { - return(TPoint2D((T)(X / len), (T)(Y / len))); - } else { - return(*this); - } - } - - // Find distance between points. - T Distance_To(TPoint2D const & point) const {return((*this - point).Length());} - - public: - T X; - T Y; -}; - - -/*********************************************************************************************** -** This typedef provides an uncluttered type name for use by simple integer points. -*/ -class Point2D : public TPoint2D -{ - public: - Point2D(void) {} // Default constructor does nothing by design. - Point2D(int x, int y) : TPoint2D(x, y) {} - Point2D(Point2DStruct const & rvalue) : TPoint2D(rvalue.X, rvalue.Y) {} - Point2D(TPoint2D const & rvalue) : TPoint2D(rvalue) {} - - operator Point2DStruct (void) const {Point2DStruct pt;pt.X = X;pt.Y = Y;return(pt);} - - Point2D const & operator += (Point2D const & rvalue) {X += rvalue.X;Y += rvalue.Y;return(*this);} - Point2D const & operator -= (Point2D const & rvalue) {X -= rvalue.X;Y -= rvalue.Y;return(*this);} - Point2D const operator - (Point2D const & rvalue) const {return(Point2D(int(X - rvalue.X), int(Y - rvalue.Y)));} - Point2D const operator + (Point2D const & rvalue) const {return(Point2D(int(X + rvalue.X), int(Y + rvalue.Y)));} -}; - - -template -T Distance(TPoint2D const & point1, TPoint2D const & point2) -{ - return((point1 - point2).Length()); -} - - -template -TPoint2D const Cross_Product(TPoint2D const & lvalue, TPoint2D const & rvalue) -{ - return(lvalue.Cross_Product(rvalue)); -} - - -/*********************************************************************************************** -** This describes a point in 3 dimensional space using arbitrary -** components. This is the successor to the COORDINATE type for those -** times when height (Z axis) needs to be tracked. -** -** Notice that it is NOT implemented as a virtually derived class. This -** is for efficiency reasons. This class chooses to be smaller and faster at the -** expense of polymorphism. However, since it is publicly derived, inheritance is -** the next best thing. -*/ -template -class TPoint3D : public TPoint2D { - typedef TPoint2D BASECLASS; - - public: - using BASECLASS::X; - using BASECLASS::Y; - - public: - TPoint3D(void) {} // Default constructor does nothing by design. - TPoint3D(T x, T y, T z) : BASECLASS(x, y), Z(z) {} - TPoint3D(BASECLASS const & rvalue, T z /*= 0*/) : BASECLASS(rvalue), Z(z) {} - - // Equality comparison operators. - bool operator == (TPoint3D const & rvalue) const {return(X==rvalue.X && Y==rvalue.Y && Z==rvalue.Z);} - bool operator != (TPoint3D const & rvalue) const {return(X!=rvalue.X || Y!=rvalue.Y || Z!=rvalue.Z);} - - // Addition and subtraction operators. - TPoint3D const & operator += (TPoint3D const & rvalue) {X += rvalue.X;Y += rvalue.Y;Z += rvalue.Z;return(*this);} - TPoint2D const & operator += (TPoint2D const & rvalue) {BASECLASS::operator += (rvalue);return(*this);} - TPoint3D const & operator -= (TPoint3D const & rvalue) {X -= rvalue.X;Y -= rvalue.Y;Z -= rvalue.Z;return(*this);} - TPoint2D const & operator -= (TPoint2D const & rvalue) {BASECLASS::operator -= (rvalue);return(*this);} - TPoint3D const operator - (TPoint3D const & rvalue) const {return(TPoint3D(X - rvalue.X, Y - rvalue.Y, Z - rvalue.Z));} - TPoint3D const operator - (TPoint2D const & rvalue) const {return(TPoint3D(X - rvalue.X, Y - rvalue.Y, Z));} - TPoint3D const operator + (TPoint3D const & rvalue) const {return(TPoint3D(X + rvalue.X, Y + rvalue.Y, Z + rvalue.Z));} - TPoint3D const operator + (TPoint2D const & rvalue) const {return(TPoint3D(X + rvalue.X, Y + rvalue.Y, Z));} - - // Scalar multiplication and division. - TPoint3D const operator * (T rvalue) const {return(TPoint3D(X * rvalue, Y * rvalue, Z * rvalue));} - TPoint3D const & operator *= (T rvalue) {X *= rvalue;Y *= rvalue;Z *= rvalue;return(*this);} - TPoint3D const operator / (T rvalue) const {if (rvalue == T(0)) return(TPoint3D(0,0,0));return(TPoint3D(X / rvalue, Y / rvalue, Z / rvalue));} - TPoint3D const & operator /= (T rvalue) {if (rvalue != T(0)) {X /= rvalue;Y /= rvalue;Z /= rvalue;}return(*this);} - - // Dot and cross product. - TPoint3D const operator * (TPoint3D const & rvalue) const {return(TPoint3D(X * rvalue.X, Y * rvalue.Y, Z * rvalue.Z));} - T Dot_Product(TPoint3D const & rvalue) const {return(T(X * rvalue.X + Y * rvalue.Y + Z * rvalue.Z));} - TPoint3D const Cross_Product(TPoint3D const & rvalue) const {return TPoint3D(Y * rvalue.Z - Z * rvalue.Y, Z * rvalue.X - X * rvalue.Z, X * rvalue.Y - Y * rvalue.X);} - - // Negation operator -- simple and effective - TPoint3D const operator - (void) const {return(TPoint3D(-X, -Y, -Z));} - - // Vector support functions. - T Length(void) const {return(T(sqrt(double(X*X + Y*Y + Z*Z))));} - TPoint3D const Normalize(void) const { - double len = sqrt(X*X + Y*Y + Z*Z); - if (len != 0.0) { - return(TPoint3D((T)(X / len), (T)(Y / len), (T)(Z / len))); - } else { - return(*this); - } - } - - public: - - /* - ** The Z component of this point. - */ - T Z; -}; - - -/*********************************************************************************************** -** This typedef provides a simple uncluttered type name for use by -** integer 3D points. -*/ -typedef TPoint3D Point3D; - -template -TPoint3D const Cross_Product(TPoint3D const & lvalue, TPoint3D const & rvalue) -{ - return(lvalue.Cross_Product(rvalue)); -} - - -#endif diff --git a/Generals/Code/Tools/Autorun/RECT.h b/Generals/Code/Tools/Autorun/RECT.h deleted file mode 100644 index 0ca194c955..0000000000 --- a/Generals/Code/Tools/Autorun/RECT.h +++ /dev/null @@ -1,308 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * Archive : /Sun/RECT.H * - * * - * Author : Joe_b * - * * - * Modtime : 11/21/97 4:40p * - * * - * Revision : 20 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Union -- Combines two rectangles into one larger one. * - * Intersect -- Find the intersection between two rectangles. * - * Intersect -- Simple intersect between two rectangles. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#pragma once - -#ifndef RECT_H -#define RECT_H - -#include -#include "POINT.h" - - -/* -** This class manages a rectangle. Typically, this is used for tracking regions on a surface -** and for clipping operations. This is a lightweight class in that it defines few support -** functions and exposes the member variables for direct access. -*/ -template -class TRect -{ - public: - TRect(void) {} // Default constructor does nothing by design. - TRect(T x, T y, T w, T h) : X(x), Y(y), Width(w), Height(h) {} - TRect(TPoint2D const & point, T w, T h) : X(point.X), Y(point.Y), Width(w), Height(h) {} - - // Equality comparison operators. - bool operator == (TRect const & rvalue) const {return(X==rvalue.X && Y==rvalue.Y && Width==rvalue.Width && Height==rvalue.Height);} - bool operator != (TRect const & rvalue) const {return(X!=rvalue.X || Y!=rvalue.Y || Width!=rvalue.Width || Height!=rvalue.Height);} - - // Addition and subtraction operators. - TRect const & operator += (TPoint2D const & point) {X += point.X;Y += point.Y;return(*this);} - TRect const & operator -= (TPoint2D const & point) {X -= point.X;Y -= point.Y;return(*this);} - TRect const operator + (TPoint2D const & point) {return(TRect(Top_Left() + point, Width, Height));} - TRect const operator - (TPoint2D const & point) {return(TRect(Top_Left() - point, Width, Height));} - - /* - ** Bias this rectangle within another. - */ - TRect const Bias_To(TRect const & rect) const {return(TRect(Top_Left() + rect.Top_Left(), Width, Height));} - - // Assign values - void Set(T x, T y, T w, T h) {X = x; Y = y; Width = w; Height = h;} - - /* - ** Determine if two rectangles overlap. - */ - bool Is_Overlapping(TRect const & rect) const {return(X < rect.X+rect.Width && Y < rect.Y+rect.Height && X+Width > rect.X && Y+Height > rect.Y);} - - /* - ** Determine is rectangle is valid. - */ - bool Is_Valid(void) const {return(Width > 0 && Height > 0);} - __declspec(property(get=Is_Valid)) bool IsValid; - - /* - ** Returns size of rectangle if each discrete location within it is presumed - ** to be of size 1. - */ - int Size(void) const {return(int(Width) * int(Height));} - - /* - ** Fetch points of rectangle (used as a convenience for the programmer). - */ - TPoint2D Top_Left(void) const {return(TPoint2D(X, Y));} - __declspec(property(get=Top_Left)) TPoint2D TopLeft; - - TPoint2D Top_Right(void) const {return(TPoint2D(T(X + Width - 1), Y));} - __declspec(property(get=Top_Right)) TPoint2D TopRight; - - TPoint2D Bottom_Left(void) const {return(TPoint2D(X, T(Y + Height - 1)));} - __declspec(property(get=Bottom_Left)) TPoint2D BottomLeft; - - TPoint2D Bottom_Right(void) const {return(TPoint2D(T(X + Width - 1), T(Y + Height - 1)));} - __declspec(property(get=Bottom_Right)) TPoint2D BottomRight; - - - /* - ** Determine if a point lies within the rectangle. - */ - bool Is_Point_Within(TPoint2D const & point) const {return(point.X >= X && point.X < X+Width && point.Y >= Y && point.Y < Y+Height);} - - public: - - /* - ** Coordinate of upper left corner of rectangle. - */ - T X; - T Y; - - /* - ** Dimensions of rectangle. If the width or height is less than or equal to - ** zero, then the rectangle is in an invalid state. - */ - T Width; - T Height; -}; - - -template -TPoint2D const Bias_To(TPoint2D const & point, TRect const & rect) -{ - return(TPoint2D(T(point.X + rect.X), T(point.Y + rect.Y))); -} - - -/*********************************************************************************************** - * Union -- Combines two rectangles into one larger one. * - * * - * This routine will combine the two specified rectangles such that a larger one is * - * returned that encompasses both rectangles. * - * * - * INPUT: rect1 -- One rectangle to combine. * - * rect2 -- The other rectangle to combine. * - * * - * OUTPUT: Returns with the smallest rectangle that encompasses both specified rectangles. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 06/04/1997 JLB : Created. * - *=============================================================================================*/ -template -TRect const Union(TRect const & rect1, TRect const & rect2) -{ - if (rect1.Is_Valid()) { - if (rect2.Is_Valid()) { - TRect result = rect1; - - if (result.X > rect2.X) { - result.Width += T(result.X-rect2.X); - result.X = rect2.X; - } - if (result.Y > rect2.Y) { - result.Height += T(result.Y-rect2.Y); - result.Y = rect2.Y; - } - if (result.X+result.Width < rect2.X+rect2.Width) { - result.Width = T(((rect2.X+rect2.Width)-result.X)+1); - } - if (result.Y+result.Height < rect2.Y+rect2.Height) { - result.Height = T(((rect2.Y+rect2.Height)-result.Y)+1); - } - return(result); - } - return(rect1); - } - return(rect2); -} - - -/*********************************************************************************************** - * Intersect -- Find the intersection between two rectangles. * - * * - * This routine will take two rectangles and return the intersecting rectangle. It also * - * tracks how much on rectangle was clipped off of the top and left edges and returns * - * these values. It can be handy to use these returned clipping values for blit operations * - * between rectangles. * - * * - * INPUT: bounding_rect -- The rectangle of the bounding box (clipping rectangle). * - * * - * draw_rect -- The rectangle that will be clipped into the bounding rectangle. * - * * - * x,y -- Place to store the clipping offset performed on the draw_rect. * - * If this offset is applied to a subsiquent blit operation from * - * the draw_rect source, it will appear to be properly clipped * - * against the clipping rectangle rather than offset to the * - * clipping rectangle. * - * * - * OUTPUT: Returns with the rectangle that is the intersection of the two rectangles. * - * * - * WARNINGS: The returned rectangle may be clipped into nothingness. Check for Is_Valid * - * to catch this case. * - * * - * HISTORY: * - * 06/04/1997 JLB : Created. * - *=============================================================================================*/ -template -TRect const Intersect(TRect const & bounding_rect, TRect const & draw_rect, T * x, T * y) -{ - TRect bad_rect(0, 0, 0, 0); // Dummy (illegal) draw_rect. - TRect new_draw_rect = draw_rect; // Working draw_rect. - - /* - ** Both draw_rects must be valid or else no intersection can occur. In such - ** a case, return an illegal draw_rect. - */ - if (!bounding_rect.Is_Valid() || !draw_rect.Is_Valid()) return(bad_rect); - - /* - ** The draw_rect spills past the left edge. - */ - if (new_draw_rect.X < bounding_rect.X) { - new_draw_rect.Width -= T(bounding_rect.X - new_draw_rect.X); - new_draw_rect.X = bounding_rect.X; - } - if (new_draw_rect.Width < 1) return(bad_rect); - - /* - ** The draw_rect spills past top edge. - */ - if (new_draw_rect.Y < bounding_rect.Y) { - new_draw_rect.Height -= T(bounding_rect.Y - new_draw_rect.Y); - new_draw_rect.Y = bounding_rect.Y; - } - if (new_draw_rect.Height < 1) return(bad_rect); - - /* - ** The draw_rect spills past the right edge. - */ - if (new_draw_rect.X + new_draw_rect.Width > bounding_rect.X + bounding_rect.Width) { - new_draw_rect.Width -= T((new_draw_rect.X + new_draw_rect.Width) - (bounding_rect.X + bounding_rect.Width)); - } - if (new_draw_rect.Width < 1) return(bad_rect); - - /* - ** The draw_rect spills past the bottom edge. - */ - if (new_draw_rect.Y + new_draw_rect.Height > bounding_rect.Y + bounding_rect.Height) { - new_draw_rect.Height -= T((new_draw_rect.Y + new_draw_rect.Height) - (bounding_rect.Y + bounding_rect.Height)); - } - if (new_draw_rect.Height < 1) return(bad_rect); - - /* - ** Adjust Height relative draw position according to Height new draw_rect - ** union. - */ - if (x != NULL) { - *x -= T(new_draw_rect.X - draw_rect.X); - } - if (y != NULL) { - *y -= T(new_draw_rect.Y - draw_rect.Y); - } - - return(new_draw_rect); -} - - -/*********************************************************************************************** - * Intersect -- Simple intersect between two rectangles. * - * * - * This will return with the rectangle that represents the intersection of the two * - * rectangles specified. * - * * - * INPUT: rect1 -- The first rectangle. * - * * - * rect2 -- The second rectangle. * - * * - * OUTPUT: Returns with the intersecting rectangle between the two rectangles specified. * - * * - * WARNINGS: If there is no valid intersection between the two rectangles, then a rectangle * - * of illegal value is returned. Check for this case by using the Is_Valid() * - * function. * - * * - * HISTORY: * - * 06/04/1997 JLB : Created. * - *=============================================================================================*/ -template -TRect const Intersect(TRect const & rect1, TRect const & rect2) -{ - return(Intersect(rect1, rect2, (T*)NULL, (T*)NULL)); -} - - -/* -** This typedef provides an uncluttered type name for a rectangle that -** is composed of integers. -*/ -typedef TRect Rect; - -const Rect RECT_NONE(0,0,0,0); - -#endif - diff --git a/Generals/Code/Tools/Autorun/TTFont.cpp b/Generals/Code/Tools/Autorun/TTFont.cpp deleted file mode 100644 index 31be82fb6e..0000000000 --- a/Generals/Code/Tools/Autorun/TTFont.cpp +++ /dev/null @@ -1,1475 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/************************************************************************************************ - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - ************************************************************************************************ - * * - * Project Name: Setup * - * * - * Archive: TTFont.cpp * - * * - * Author: Maria del Mar McCready Legg * - * * - * Modtime: 8/24/99 3:44pm * - * * - * Revision: 01 * - * * - *----------------------------------------------------------------------------------------------* - * Functions: * - * TTFontClass::TTFontClass -- Constructor for a font class object. * - * TTFontClass::Char_Pixel_Width -- Fetch the pixel width of the character specified. * - * TTFontClass::Find_Text_VLength -- Finds length of text in pixels * - * TTFontClass::Get_Height -- Fetch the normalized height of the nominal font character. * - * TTFontClass::Get_Width -- Get normalized width of the nominal font character. * - * TTFontClass::Print -- Print text to the surface specified. * - * TTFontClass::Raw_Height -- Fetch the height of the font. * - * TTFontClass::Raw_Width -- Fetch the raw width of a character. * - * TTFontClass::Set_XSpacing -- Set the X spacing override value. * - * TTFontClass::Set_YSpacing -- Set the vertical (Y) spacing override value. * - * TTFontClass::String_Pixel_Width -- Determines the width of the string in pixels. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ - - -#define STRICT -#include -#include -#include -#include -#include -#include "ARGS.H" -#include "autorun.h" -#include "RECT.h" -#include "Wnd_File.h" -#include "TTFont.h" -#include "JSUPPORT.H" // [OYO] -#include "Locale_API.h" - - -#define FONTINFOMAXHEIGHT 4 -#define FONTINFOMAXWIDTH 5 -#define FUDGEDIV 16 - -//------------------------------------------------------------------------- -// Text Fonts. -//------------------------------------------------------------------------- -TTFontClass *TTButtonFontPtr = NULL; -TTFontClass *TTButtonFontPtrSmall = NULL; -TTFontClass *TTTextFontPtr = NULL; -TTFontClass *TTTextFontPtr640 = NULL; -TTFontClass *TTTextFontPtr800 = NULL; -TTFontClass *TTLicenseFontPtr = NULL; - -FontManagerClass * FontManager = NULL; - -//unsigned long TEXT_COLOR = RGB( 247, 171, 11 ); -//unsigned long SHADOW_COLOR = RGB( 40, 8, 8 ); -unsigned long TEXT_COLOR = RGB( 255, 204, 51 ); -unsigned long SHADOW_COLOR = RGB( 40, 8, 8 ); - -unsigned long TEXT_NORMAL_COLOR = RGB( 255, 204, 51 ); -unsigned long TEXT_NORMAL_SHADOW_COLOR = RGB( 40, 8, 8 ); -unsigned long TEXT_FOCUSED_COLOR = RGB( 255, 204, 51 ); -unsigned long TEXT_FOCUSED_SHADOW_COLOR = RGB( 40, 8, 8 ); -unsigned long TEXT_PRESSED_COLOR = RGB( 194, 79, 32 ); -unsigned long TEXT_PRESSED_SHADOW_COLOR = RGB( 70, 55, 49 ); - - -unsigned long BLACK_COLOR = RGB( 0, 0, 0 ); -unsigned long WHITE_COLOR = RGB( 255, 255, 255 ); -unsigned long RED_COLOR = RGB( 255, 0, 0 ); -unsigned long ORANGE_COLOR = RGB( 199, 91, 0 ); -unsigned long YELLOW_COLOR = RGB( 255, 247, 0 ); -unsigned long GREEN_COLOR = RGB( 0, 255, 0 ); -unsigned long BLUE_COLOR = RGB( 0, 0, 255 ); -unsigned long INDIGO_COLOR = RGB( 90, 2, 253 ); -unsigned long VIOLET_COLOR = RGB( 128, 0, 255 ); - - -/************************************************************************************ - * TTFontClass::TTFontClass -- Constructor for a font class object. * - * * - * This constructs a font object as it is based upon the true type windows fonts. * - * * - * INPUT: char *filename -- True Type Windows font file to open. * - * char *facename -- It's face name. * - * int height -- The height requested. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 08/24/1999 MML : Created. * - *==================================================================================*/ -TTFontClass::TTFontClass( - HDC hdc, - char *filename, - char *facename, - int height, - int weight, - BYTE charset, - int width, - int escapement, - int orientation, - BYTE italic, - BYTE underline, - BYTE strikeout, - BYTE outputPrecision, - BYTE clipPrecision, - BYTE quality, - BYTE pitchAndFamily ) -{ - HGDIOBJ old_object; - TEXTMETRIC tm; - char real_facename[MAX_PATH]; - - //-------------------------------------------------------------------------- - // Get or Set a Font filename. - //-------------------------------------------------------------------------- - if (( filename == NULL ) || ( filename[0] == '\0' )) { - strcpy( szFilename, "Arial.ttf" ); - } else { - strcpy( szFilename, filename ); - } - - //-------------------------------------------------------------------------- - // Get or Set a Font facename. - //-------------------------------------------------------------------------- - if (( facename == NULL ) || ( facename[0] == '\0' )) { - strcpy( szFacename, "Arial" ); - } else { - strcpy( szFacename, facename ); - } - real_facename[0] = '\0'; - - Msg( __LINE__, __FILE__, "TTFontClass -- filename=%s, facename=%s, height=%d.", filename, facename, height ); - - //-------------------------------------------------------------------------- - // Make sure the font file is "Registered". Then create the font. - //-------------------------------------------------------------------------- - AddFontResource( szFilename ); - Font = CreateFont( - height, - width, - escapement, - orientation, - weight, - italic, - underline, - strikeout, - charset, - outputPrecision, - clipPrecision, - quality, - pitchAndFamily, - szFacename ); - - if ( hdc && ( Font != NULL )) { - - //---------------------------------------------------------------------- - // The GetTextFace function lets a program determine the face name of - // THE font currently selected in the device context: - //---------------------------------------------------------------------- - old_object = SelectObject( hdc, Font ); - GetTextFace( hdc, ( sizeof( real_facename ) / sizeof( TCHAR )), real_facename ); - - if( _stricmp( real_facename, szFacename ) != 0 ) { - - strcpy( szFilename, "Arial.ttf" ); - strcpy( szFacename, "Arial" ); - - SelectObject( hdc, old_object ); - DeleteObject( Font ); - Font = NULL; - - Font = CreateFont( - height, // height of font - width, // average character width - escapement, // angle of escapement - orientation, // base-line orientation angle - weight, // font weight - italic, // italic attribute option - underline, // underline attribute option - strikeout, // strikeout attribute option - charset, // character set identifier - outputPrecision, // output precision - clipPrecision, // clipping precision - quality, // output quality - pitchAndFamily, // pitch and family - szFacename ); // typeface name - - real_facename[0] = '\0'; - old_object = SelectObject( hdc, Font ); - GetTextFace( hdc, ( sizeof( real_facename ) / sizeof( TCHAR )), real_facename ); - } - } - - //-------------------------------------------------------------------------- - // Save off the height. - //-------------------------------------------------------------------------- - Height = height; - - if ( hdc ) { - - //----------------------------------------------------------------------- - // Get info from the font in BackBuffer's DC. - //----------------------------------------------------------------------- - old_object = SelectObject( hdc, Font ); - GetTextMetrics( hdc, &tm ); - - FontXSpacing = GetTextCharacterExtra( hdc ); - Ascent = tm.tmAscent; - Descent = tm.tmDescent; - InternalLeading = tm.tmInternalLeading; - ExternalLeading = tm.tmExternalLeading; - AveCharWidth = tm.tmAveCharWidth; - MaxCharWidth = tm.tmMaxCharWidth; - Overhang = tm.tmOverhang; - Italic = tm.tmItalic; - Underlined = tm.tmUnderlined; - StruckOut = tm.tmStruckOut; - CharSet = tm.tmCharSet; // [OYO] It is important to support Double Byte Chars - SelectObject( hdc, old_object ); - - } else { - - //----------------------------------------------------------------------- - // Set default values. - //----------------------------------------------------------------------- - Ascent = 0; - Descent = 0; - InternalLeading = 0; - ExternalLeading = 0; - AveCharWidth = 0; - MaxCharWidth = 0; - Overhang = 0; - Italic = 0; - Underlined = 0; - StruckOut = 0; - CharSet = 0; // [OYO] - FontXSpacing = 0; - } -} - - -/*********************************************************************************************** - * TTFontClass::Char_Pixel_Width -- Fetch the pixel width of the character specified. * - * * - * This will return with the pixel width of the character specified. * - * * - * INPUT: c -- The character to determine the pixel width for. * - * * - * OUTPUT: Returns with the pixel width of the character. * - * * - * WARNINGS: The return width is the screen real estate width which may differ from the * - * actual pixels of the character. This difference is controlled by the font * - * X spacing. * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *=============================================================================================*/ - -int TTFontClass::Char_Pixel_Width( HDC hdc, UINT c ) const -{ - HGDIOBJ old_object; - ABC abc; - - abc.abcA = 0; - abc.abcB = 0; - abc.abcC = 0; - - if ( hdc ) { - old_object = SelectObject( hdc, Font ); - GetCharABCWidths( hdc, c, c, &abc ); - SelectObject( hdc, old_object ); - } - return( abc.abcA + abc.abcB + abc.abcC ); -} - -/************************************************************************************************ - * TTFontClass::Char_Pixel_Width -- Fetch the pixel width of the character specified. - * - * This will return with the pixel width of the character specified. - * - * INPUT: HDC hdc -- must be passed in from calling function. - * char const * string -- the pointer to the character in the string. - * int *num_bytes -- return number of bytes this character has: 1 or 2. - * - * OUTPUT: Returns with the pixel width of the character. - * - * WARNINGS: The return width is the screen real estate width which may differ from the - * actual pixels of the character. This difference is controlled by the font - * X spacing. - * - * NOTE: This is function determines if the character is a double-byte or single-byte - * character, then calls the standard Char_Pixel_Width. - * - * HISTORY: - * 05/26/1997 JLB : Created. - *==============================================================================================*/ -// -// [OYO] Supports DBCS ( multi-byte characters ). -// -int TTFontClass::Char_Pixel_Width ( HDC hdc, char const * string, int *num_bytes ) const -{ - char const *letter = string; - int length = 0; - UINT c; - - //-------------------------------------------------------------------------- - // These values must be passed in. - //-------------------------------------------------------------------------- - if ( string == NULL || *string == '\0' || hdc == NULL ) { - return( 0 ); - } - - //-------------------------------------------------------------------------- - // If this value is passed in, the set the default value (1=single). - //-------------------------------------------------------------------------- - if ( num_bytes!= NULL ) { - *num_bytes = 1; - } - - //-------------------------------------------------------------------------- - // Get the pixel width of the character. If it is a double-byte character, - // then num_bytes will come back as '2'. - //-------------------------------------------------------------------------- - if( IsFontDBCS() && IsDBCSLeadByte( *letter )){ - c = Get_Double_Byte_Char( letter, num_bytes ); - length += Char_Pixel_Width( hdc, c ); // pixel length of double-byte character. - } else { - length += Char_Pixel_Width( hdc, *letter ); // pixel length of single-byte character. - } - return( length ); -} - - -/************************************************************************************************ - * TTFontClass::String_Pixel_Width -- Determines the width of the string in pixels. * - * * - * This routine is used to determine how many pixels wide the string will be if it were * - * printed. * - * * - * INPUT: string -- The string to convert into its pixel width. * - * * - * OUTPUT: Returns with the number of pixels the string would span if it were printed. * - * * - * WARNINGS: This routine does not take into account clipping. * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *==============================================================================================*/ - -int TTFontClass::String_Pixel_Width( HDC hdc, char const * string ) const -{ - if ( string == NULL ) { - return(0); - } - - int largest = 0; // Largest recorded width of the string. - int width = 0; - HGDIOBJ old_object; - int length; - SIZE size; - bool make_dc = FALSE; - HDC localDC = hdc; - - size.cx = 0; - - if ( localDC == NULL ) { - return( size.cx ); - } - - if ( localDC ) { - length = strlen( string ); - old_object = SelectObject( localDC, Font ); - GetTextExtentPoint32( localDC, string, length, &size ); - SelectObject( localDC, old_object ); - } - return( size.cx ); -} - -/**************************************************************************** -* -* NAME -* String_Pixel_Bounds(String, Bounds) -* -* DESCRIPTION -* Calculate the bounding box for the specified string. -* -* INPUTS -* String - String to calculate bounds for -* Bounds - Rect to fill with bounds -* -* RESULT -* NONE -* -****************************************************************************/ -// -// [OYO] Supports DBCS ( multi-byte characters ). -// -void TTFontClass::String_Pixel_Bounds( HDC hdc, const char* string, Rect& bounds ) const -{ - int width; - int height; - - bounds.Width = 0; - bounds.Height = 0; - - if ( string == NULL ) { - return; - } - - if ( hdc == NULL ) { - return; - } - - width = 0; - height = Get_Height(); - - while ( *string != 0 ) { - - if (( *string == '\r' ) || ( *string == '\n' )) { - - string++; - height += Get_Height(); - bounds.Width = max( bounds.Width, width ); - width = 0; - - } else if( IsFontDBCS()){ - -#if(0) - //-------------------------------------------------------------------- - // Using one of those _tc functions: - // Get a character, get the width of that character, then - // move the pointer to the next character. - //-------------------------------------------------------------------- - UINT c = Get_Double_Byte_Char( string ); - width += Char_Pixel_Width( hdc, c ); - string = _tcsinc( string ); -#else - //-------------------------------------------------------------------- - // MBCS way: Get a byte. If byte is a "Lead" byte, get the second half, - // combine them into one character, then get the width of that character. - //-------------------------------------------------------------------- - UINT c = *(BYTE*)string++; - if( IsDBCSLeadByte( c )&& *string ) { - c = ( c << 8 ) | *(BYTE *)string++; - } - width += Char_Pixel_Width( hdc, c ); -#endif - - } else { - width += Char_Pixel_Width( hdc, *string++ ); - } - } - - bounds.Width = max( bounds.Width, width ); - bounds.Height = height; -} - -/*********************************************************************************************** - * TTFontClass::Get_Double_Byte_Char -- Get the first character even if DBSC. - * - * INPUT: char * -- string to look at. - * - * OUTPUT: Returns with the normalized width of the character in the font. - * - * WARNINGS: I added this function based on code provided by Ikeda-san. - * - * HISTORY: - * 06/05/2000 MML : Created. - *=============================================================================================*/ -// -// [OYO] Supports DBCS ( multi-byte characters ). -// -UINT TTFontClass::Get_Double_Byte_Char ( const char *string, int *num_bytes ) const -{ - if ( string == NULL || *string == '\0' ) { - return( 0 ); - } - - const char *ptr = string; - UINT c = *(BYTE *)ptr++; - - if ( num_bytes != NULL ) { - *num_bytes = 1; - } - - //-------------------------------------------------------------------------- - // The IsDBCSLeadByte function determines whether a character is a - // lead byte - that is, the first byte of a character in a double-byte - // character set (DBCS). - // - // BOOL IsDBCSLeadByte( BYTE TestChar /* character to test */ ); - // - // TestChar -- Specifies the character to be tested. - // - // Return Values - // If the character is a lead byte, the return value is nonzero. - // If the character is not a lead byte, the return value is zero. - // To get extended error information, call GetLastError. - // Remarks - // Lead bytes are unique to double-byte character sets. - // A lead byte introduces a double-byte character. Lead bytes - // occupy a specific range of byte values. The IsDBCSLeadByte - // function uses the ANSI code page to check lead-byte ranges. - // To specify a different code page, use the IsDBCSLeadByteEx function. - // - // Declared in winnls.h. - //-------------------------------------------------------------------------- - if( IsDBCSLeadByte( c )&& *ptr ) { // [OYO] - c = ( c << 8 ) | *(BYTE *)ptr++; - if ( num_bytes != NULL ) { - *num_bytes = 2; - } - } - return( c ); -} - - -/*********************************************************************************************** - * TTFontClass::Get_Width -- Get normalized width of the nominal font character. * - * * - * This routine is used to fetch the width of the widest character in the font but the * - * width has been biased according to any X spacing override present. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with the normalized width of the widest character in the font. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *=============================================================================================*/ -int TTFontClass::Get_Width( void ) const -{ - return( MaxCharWidth - Overhang ); -} - -/*********************************************************************************************** - * TTFontClass::Get_Height -- Fetch the normalized height of the nominal font character. * - * * - * This will return the height of the font but the returned height will be adjusted by any * - * Y spacing override present. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with the height of the font normalized by any spacing overrides. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *=============================================================================================*/ -int TTFontClass::Get_Height( void ) const -{ - return( Height ); -} - -/*********************************************************************************************** - * TTFontClass::Set_XSpacing -- Set the X spacing override value. * - * * - * Use this routine to control the horizontal spacing override for this font. If the value * - * is negative, the font becomes compressed. If the value is positive, then the font * - * becomes expanded. * - * * - * INPUT: x -- The X spacing override to use for this font. * - * * - * OUTPUT: Returns with the old X spacing override value. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *=============================================================================================*/ -int TTFontClass::Set_XSpacing( HDC hdc, int x ) -{ -// HGDIOBJ old_object; -// int answer = 0; - -// if ( hdc ) { -// old_object = SelectObject( hdc, Font ); -// answer = SetTextCharacterExtra( hdc, x ); -// SelectObject( hdc, old_object ); -// } - FontXSpacing = x; - return( x ); -} - - -/*********************************************************************************************** - * TTFontClass::Set_YSpacing -- Set the vertical (Y) spacing override value. * - * * - * Use this routine to control the "line spacing" of a font. If the Y spacing is negative * - * then the font becomes closer to the line above it. If value is positive, then more * - * space occurs between lines. * - * * - * INPUT: y -- The Y spacing override to use for this font. * - * * - * OUTPUT: Returns with the old Y spacing override value. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *=============================================================================================*/ -int TTFontClass::Set_YSpacing( int y ) -{ - FontYSpacing = y; - return(y); -} - - -/*********************************************************************************************** - * TTFontClass::Print -- Print text to the surface specified. WCHAR Version. * - * * - * This displays text to the surface specified and with the attributes specified. * - * * - * INPUT: string -- The string to display to the surface. * - * surface -- The surface to display the text upon. * - * cliprect -- The clipping rectangle that both clips the text and biases the print * - * location to. * - * point -- The draw position for the upper left corner of the first character. * - * convert -- The pixel convert object that is used to draw the correct colors to * - * the destination surface. * - * remap -- Auxiliary remap table for font colors. * - * * - * OUTPUT: Returns with the point where the next print should begin if it is to smoothly * - * continue where this print operation left off. * - * * - * WARNINGS: There are two separate drawing routines; one for old fonts and one for new fonts. * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - * 06/20/1887 BNA : Modified to handle new fonts. * - *=============================================================================================*/ - -#if(NDEBUG) - -Point2D TTFontClass::Print( - HDC hdc, - wchar_t const * string, - Rect const & cliprect, - COLORREF forecolor, /* = TEXT_COLOR, */ - COLORREF backcolor, /* = TEXT_SHADOW_COLOR, */ - TextFormatType flag, /* = TPF_DEFAULT, */ - TextShadowType shadow ) /* = TPF_FULLSHADOW */ -{ - char buffer[ _MAX_PATH ]; - int length = wcslen( string ); - - memset( buffer, '\0', _MAX_PATH ); - WideCharToMultiByte( CodePage, 0, string, length, buffer, _MAX_PATH, NULL, NULL ); - - return( Print( hdc, buffer, cliprect, forecolor, backcolor, flag, shadow )); -} - -#else - -Point2D TTFontClass::Print( - HDC hdc, - wchar_t const * string, - Rect const & cliprect, - COLORREF forecolor, /* = TEXT_COLOR, */ - COLORREF backcolor, /* = TEXT_SHADOW_COLOR, */ - TextFormatType flag, /* = TPF_DEFAULT, */ - TextShadowType shadow ) /* = TPF_FULLSHADOW */ -{ - Point2D point( cliprect.X, cliprect.Y ); - RECT rect; - HGDIOBJ old_object; - SIZE size; - int length = 0; - int result = 0; - - //-------------------------------------------------------------------------- - // If no string, why continue? - //-------------------------------------------------------------------------- - assert( string != NULL ); - assert( hdc != NULL ); - - if (( string == NULL ) || ( string[0] == '\0' )) { - return( point ); - } - - //-------------------------------------------------------------------------- - // Set up rectangle print regions for the "shadow" and the main color. - //-------------------------------------------------------------------------- - length = wcslen( string ); - rect.left = cliprect.X; - rect.top = cliprect.Y; - rect.right = cliprect.X + cliprect.Width; - rect.bottom = cliprect.Y + cliprect.Height; - - Msg( __LINE__, __FILE__, "TTFontClass::Print -- string = %s.", string ); - Msg( __LINE__, __FILE__, "TTFontClass::Print -- strlen = %d.", length ); - Msg( __LINE__, __FILE__, "TTFontClass::Print -- rect = [%d, %d, %d, %d].", rect.left, rect.top, rect.right, rect.bottom ); -// Msg( __LINE__, __FILE__, "TTFontClass::Print -- rect2 = [%d, %d, %d, %d].", rect.left, rect.top, rect.right, rect.bottom ); - - //-------------------------------------------------------------------------- - // Print the "Shadow" depending on style desired, then the text in the requested color. - //-------------------------------------------------------------------------- - if ( hdc ) { - - assert( Font != NULL ); - - old_object = SelectObject( hdc, Font ); - - SetTextCharacterExtra( hdc, FontXSpacing ); - SetTextAlign( hdc, TA_LEFT | TA_TOP ); - SetBkMode( hdc, TRANSPARENT ); - - SetTextColor( hdc, forecolor ); - -// result = ExtTextOutW( -// hdc, // handle to DC -// rect.left, // x-coordinate of reference point -// rect.top, // y-coordinate of reference point -// ETO_CLIPPED, // text-output options -// &rect, // optional dimensions -// string, // string -// length, // number of characters in string -// NULL // array of spacing values -// ); - -// result = TextOutW( -// hdc, // handle to DC -// rect.left, // x-coordinate of starting position -// rect.top, // y-coordinate of starting position -// string, // character string -// length // number of characters -// ); - - result = DrawTextW( - hdc, - string, - length, - &rect, - flag ); - - GetTextExtentPointW( hdc, string, length, &size ); - SelectObject( hdc, old_object ); - } - point.X += size.cx; - return( point ); -} - -#endif - -/*********************************************************************************************** - * TTFontClass::Print -- Print text to the surface specified. CHAR version. * - * * - * This displays text to the surface specified and with the attributes specified. * - * * - * INPUT: string -- The string to display to the surface. * - * surface -- The surface to display the text upon. * - * cliprect -- The clipping rectangle that both clips the text and biases the print * - * location to. * - * point -- The draw position for the upper left corner of the first character. * - * convert -- The pixel convert object that is used to draw the correct colors to * - * the destination surface. * - * remap -- Auxiliary remap table for font colors. * - * * - * OUTPUT: Returns with the point where the next print should begin if it is to smoothly * - * continue where this print operation left off. * - * * - * WARNINGS: There are two separate drawing routines; one for old fonts and one for new fonts. * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - * 06/20/1887 BNA : Modified to handle new fonts. * - *=============================================================================================*/ - -Point2D TTFontClass::Print( - HDC hdc, - char const * string, - Rect const & cliprect, - COLORREF forecolor, /* = TEXT_COLOR, */ - COLORREF backcolor, /* = TEXT_SHADOW_COLOR, */ - TextFormatType flag, /* = TPF_DEFAULT, */ - TextShadowType shadow ) /* = TPF_FULLSHADOW */ -{ - Point2D point( cliprect.X, cliprect.Y ); - RECT rect, rect2; - HGDIOBJ old_object; - SIZE size; - int length = 0; - int result = 0; - - //-------------------------------------------------------------------------- - // If no string, why continue? - //-------------------------------------------------------------------------- - assert( string != NULL ); - assert( hdc != NULL ); - - if (( string == NULL ) || ( string[0] == '\0' )) { - return( point ); - } - - //-------------------------------------------------------------------------- - // Set up rectangle print regions for the "shadow" and the main color. - //-------------------------------------------------------------------------- - length = strlen( string ); - rect.left = cliprect.X; - rect.top = cliprect.Y; - rect.right = cliprect.X + cliprect.Width; - rect.bottom = cliprect.Y + cliprect.Height; - - // Shadow - rect2.left = rect.left - 1; - rect2.top = rect.top - 1; - rect2.right = rect.right - 1; - rect2.bottom= rect.bottom - 1; - -// Msg( __LINE__, __FILE__, "TTFontClass::Print -- strlen = %d.", length ); -// Msg( __LINE__, __FILE__, "TTFontClass::Print -- rect = [%d, %d, %d, %d].", rect.left, rect.top, rect.right, rect.bottom ); -// Msg( __LINE__, __FILE__, "TTFontClass::Print -- rect2 = [%d, %d, %d, %d].", rect.left, rect.top, rect.right, rect.bottom ); - - //-------------------------------------------------------------------------- - // Print the "Shadow" depending on style desired, then the text in the requested color. - //-------------------------------------------------------------------------- - if ( hdc ) { - - assert( Font != NULL ); - - old_object = SelectObject( hdc, Font ); - - SetTextCharacterExtra( hdc, FontXSpacing ); - SetTextAlign( hdc, TA_LEFT | TA_TOP ); - SetBkMode( hdc, TRANSPARENT ); - SetTextColor( hdc, backcolor ); - - if ( shadow == TPF_SHADOW ) { - - // One left, One up. - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One left. - rect2.left = rect.left - 1; - rect2.top = rect.top; - rect2.right = rect.right - 1; - rect2.bottom = rect.bottom; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One up. - rect2.left = rect.left; - rect2.top = rect.top - 1; - rect2.right = rect.right; - rect2.bottom = rect.bottom - 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - } else if ( shadow == TPF_DOUBLESHADOW ) { - - // One left, One up. - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One left. - rect2.left = rect.left - 1; - rect2.top = rect.top; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One up. - rect2.left = rect.left; - rect2.top = rect.top - 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two left, Two up. - rect2.left = rect.left - 2; - rect2.top = rect.top - 2; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two left. - rect2.left = rect.left - 2; - rect2.top = rect.top; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two up. - rect2.left = rect.left; - rect2.top = rect.top - 2; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - } else if ( shadow == TPF_FULLSHADOW ) { - - // One left, One up. - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One right, One up. - rect2.left = rect.left + 1; - rect2.top = rect.top - 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One left, One down. - rect2.left = rect.left - 1; - rect2.top = rect.top + 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One right, One down. - rect2.left = rect.left + 1; - rect2.top = rect.top + 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One left. - rect2.left = rect.left - 1; - rect2.top = rect.top; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One right. - rect2.left = rect.left + 1; - rect2.top = rect.top; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One up. - rect2.left = rect.left; - rect2.top = rect.top - 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // One down. - rect2.left = rect.left; - rect2.top = rect.top + 1; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two right. - rect2.left = rect.left + 2; - rect2.top = rect.top; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two down. - rect2.left = rect.left; - rect2.top = rect.top + 2; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two right, One up. - rect2.left = rect.left + 2; - rect2.top = rect.top - 2; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Two right, One down. - rect2.left = rect.left + 2; - rect2.top = rect.top + 2; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - - // Three right. - rect2.left = rect.left + 3; - rect2.top = rect.top; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Three down. - rect2.left = rect.left; - rect2.top = rect.top + 3; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Three right, One up. - rect2.left = rect.left + 3; - rect2.top = rect.top - 3; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - - // Three right, One down. - rect2.left = rect.left + 3; - rect2.top = rect.top + 3; - result = DrawText( hdc, string, length, &rect2, flag ); - assert( result != 0 ); - } - - SetTextColor( hdc, forecolor ); - result = DrawText( hdc, string, length, &rect, flag ); - assert( result != 0 ); - - GetTextExtentPoint( hdc, string, length, &size ); - SelectObject( hdc, old_object ); - } - point.X += size.cx; - return( point ); -} - -/*************************************************************************** - * TTFontClass::FIND_TEXT_VLENGTH -- Finds length of text in pixels * - * * - * INPUT: BYTE *string - the strength to find the vertical length of * - * int width - the width of the region to fit it in * - * * - * OUTPUT: int -- the number of pixels it takes up veritcally. * - * * - * HISTORY: * - * 09/27/1994 PWG : Created. * - *=========================================================================*/ -// -// [OYO] Supports DBCS ( multi-byte characters ). -// -int TTFontClass::Find_Text_VLength( HDC hdc, char *str, int width ) -{ - int curlen = 0; - int lastlen = 0; - int lines = Get_Height(); - char *letter = str; - bool make_dc = FALSE; - HDC localDC = hdc; - - if ( *str == '\0' || str == NULL ) { - return( 0 ); - } - - //-------------------------------------------------------------------------- - // If no DC was passed in, then we need to get one. - //-------------------------------------------------------------------------- - if ( localDC == NULL ) { - return( 0 ); - } - - //========================================================================== - // Process languages EXCEPT Double-byte languages. - //========================================================================== - if( !(IS_LANGUAGE_DBCS( LanguageID ))) { - - //----------------------------------------------------------------------- - // Get the pixel length of the string. - //----------------------------------------------------------------------- - curlen = String_Pixel_Width( localDC, str ); - lines = 0; - - //----------------------------------------------------------------------- - // If the string in longer than the width given, calculate the number of - // lines needed in pixels (height of string in pixels ). - //----------------------------------------------------------------------- - if ( curlen > width ) { - - while( curlen > 0 ) { - if ( curlen > width ) { - curlen -= width; - } else { - curlen = 0; - } - lines += Get_Height(); - } - - } else { - lines = Get_Height(); - } - - //----------------------------------------------------------------------- - // Check for any newlines. Add one line per newline. - //----------------------------------------------------------------------- - letter = str; - while ( *letter ) { - if ( *letter == '\n') { - lines += Get_Height(); - } - letter++; - } - - } else { - - //======================================================================= - // Process Double-Byte language text. - //======================================================================= - int i, n, wspc; - UINT c; - int fdbcs = IsFontDBCS(); - - lines = 0; - - //----------------------------------------------------------------------- - // For each word... - //----------------------------------------------------------------------- - while ( n = nGetWord( letter, fdbcs )) { - - //-------------------------------------------------------------------- - // For each character in the word... - //-------------------------------------------------------------------- - for ( c=0, wspc=0, curlen=0, i=0; i < n; i++ ) { - - if ( c ) { - //-------------------------------------------------------------- - // Double-byte character. - //-------------------------------------------------------------- - c = ( c<<8 )|(UINT)(BYTE)letter[i]; - curlen += Char_Pixel_Width( localDC, c ) + wspc; - c = 0; - wspc = 0; - - } else if( fdbcs && IsDBCSLeadByte((BYTE)letter[i])) { - //-------------------------------------------------------------- - // First half of a Double-byte character. - //-------------------------------------------------------------- - c = (UINT)(BYTE)letter[i]; - - } else if((BYTE)letter[i] > ' ' ) { - //-------------------------------------------------------------- - // Single-byte character. - //-------------------------------------------------------------- - curlen += Char_Pixel_Width( localDC, (UINT)(BYTE)letter[i] ) + wspc; - wspc = 0; - - } else if( letter[i] == ' ') { - //-------------------------------------------------------------- - // Space character. - //-------------------------------------------------------------- - wspc += Char_Pixel_Width( localDC, ' ' ); - } - } // end-of-for - - //-------------------------------------------------------------------- - // - //-------------------------------------------------------------------- - if( lastlen + curlen > width ) { - lines += Get_Height(); - lastlen = 0; - } - - //-------------------------------------------------------------------- - // !!! If one block length bigger than available width, - // next line will be overflow. but never endless loop. !!! - //-------------------------------------------------------------------- - lastlen += curlen + wspc; - - //-------------------------------------------------------------------- - // - //-------------------------------------------------------------------- - if( letter[i] == '\n' ) { - lines += Get_Height(); - lastlen = 0; - } - letter += n; - - } // end-of-while - - //----------------------------------------------------------------------- - // Left over, add a line. - //----------------------------------------------------------------------- - if( lastlen ) { - lines += Get_Height(); - } - } - - //-------------------------------------------------------------------------- - // Return the number of lines. - //-------------------------------------------------------------------------- - if ( !lines ) { - lines = Get_Height(); - } - return( lines ); -} - -/*********************************************************************************************** - * FontManagerClass::FontManagerClass -- Constructor for FontManager class. * - * * - * INPUT: none. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/26/1998 MML : Created. * - *=============================================================================================*/ -FontManagerClass::FontManagerClass ( HDC hdc ) -{ - //-------------------------------------------------------------------------- - // Open a DC to the BackBuffer. - //-------------------------------------------------------------------------- - if ( hdc ) { - - char szPath[ MAX_PATH ]; - char szFile[ MAX_PATH ]; - char szFacename[ MAX_PATH ]; - char drive[ _MAX_DRIVE ]; - char dir[ _MAX_DIR ]; - bool b640X480 = false; - RECT rect; // Desktop Window ( used once ). - - strcpy( szFile, "Arial.ttf" ); - strcpy( szFacename, "Arial" ); - - strcpy( szPath, Args->Get_argv(0)); - _splitpath( szPath, drive, dir, NULL, NULL ); - _makepath( szPath, drive, dir, "Setup\\Setup", ".ini" ); - - GetPrivateProfileString( "Fonts", "Font", "Arial.tff", szFile, MAX_PATH, szPath ); - GetPrivateProfileString( "Fonts", "Fontname", "Arial", szFacename, MAX_PATH, szPath ); - - //--------------------------------------------------------------------- - // Use codepage set by Locomoto class. - //--------------------------------------------------------------------- - UINT codepage = CodePage; // GetACP(); - - GetClientRect( GetDesktopWindow(), &rect ); - if( rect.right <= 640 ) { - b640X480 = TRUE; - } - - Msg( __LINE__, __FILE__, "FontManagerClass -- szFile = %s, szFilename = %s.", szFile, szFacename ); - - //--------------------------------------------------------------------- - // Create the True Type Fonts. - // - // Value Weight - // ____________________________ - // FW_DONTCARE 0 - // FW_THIN 100 - // FW_EXTRALIGHT 200 - // FW_ULTRALIGHT 200 - // FW_LIGHT 300 - // FW_NORMAL 400 - // FW_REGULAR 400 - // FW_MEDIUM 500 - // FW_SEMIBOLD 600 - // FW_DEMIBOLD 600 - // FW_BOLD 700 - // FW_EXTRABOLD 800 - // FW_ULTRABOLD 800 - // FW_HEAVY 900 - // FW_BLACK 900 - //--------------------------------------------------------------------- - - switch( LanguageID ) { // [OYO] Add this line if you wish to support another languages - - //================================================================= - // JAPANESE - //================================================================= - case LANG_JAP: // [OYO] Use MS PGothic for Japanese Win9x - - if( codepage == 932 ) { - - strcpy( szFile, "MSGothic.ttc" ); - strcpy( szFacename, "MS PGothic" ); - - TTButtonFontPtr = new TTFontClass( hdc, szFile, szFacename, 20, FW_NORMAL, SHIFTJIS_CHARSET ); - TTButtonFontPtrSmall= new TTFontClass( hdc, szFile, szFacename, 12, FW_NORMAL, SHIFTJIS_CHARSET ); - - TTTextFontPtr = new TTFontClass( hdc, szFile, szFacename, 16, FW_MEDIUM, SHIFTJIS_CHARSET ); - TTTextFontPtr640 = new TTFontClass( hdc, szFile, szFacename, 14, FW_MEDIUM, SHIFTJIS_CHARSET ); - TTTextFontPtr800 = new TTFontClass( hdc, szFile, szFacename, 14, FW_MEDIUM, SHIFTJIS_CHARSET ); - TTLicenseFontPtr = new TTFontClass( hdc, szFile, szFacename, 12, FW_NORMAL, SHIFTJIS_CHARSET ); - } - break; - - //================================================================= - // KOREAN - //================================================================= - case LANG_KOR: // [OYO] Use GulimChe for Korean Win9x - - if ( codepage == 949 ) { - - strcpy( szFile, "Gulim.tff" ); - strcpy( szFacename, "Gulim" ); - - TTButtonFontPtr = new TTFontClass( hdc, szFile, szFacename, 20, FW_NORMAL, HANGEUL_CHARSET ); - TTButtonFontPtrSmall= new TTFontClass( hdc, szFile, szFacename, 20, FW_NORMAL, HANGEUL_CHARSET ); - - TTTextFontPtr = new TTFontClass( hdc, szFile, szFacename, 16, FW_MEDIUM, HANGEUL_CHARSET ); - TTTextFontPtr640 = new TTFontClass( hdc, szFile, szFacename, 14, FW_MEDIUM, HANGEUL_CHARSET ); - TTTextFontPtr800 = new TTFontClass( hdc, szFile, szFacename, 14, FW_MEDIUM, HANGEUL_CHARSET ); - TTLicenseFontPtr = new TTFontClass( hdc, szFile, szFacename, 12, FW_NORMAL, HANGEUL_CHARSET ); - } - break; - - //================================================================= - // CHINESE - //================================================================= - case LANG_CHI: - - if ( codepage == 950 ) { - - strcpy( szFile, "mingliu.ttc" ); - strcpy( szFacename, "mingliu" ); - - TTButtonFontPtr = new TTFontClass( hdc, szFile, szFacename, 20, FW_NORMAL, CHINESEBIG5_CHARSET ); - TTButtonFontPtrSmall= new TTFontClass( hdc, szFile, szFacename, 14, FW_NORMAL, CHINESEBIG5_CHARSET ); - - TTTextFontPtr = new TTFontClass( hdc, szFile, szFacename, 16, FW_MEDIUM, CHINESEBIG5_CHARSET ); - TTTextFontPtr640 = new TTFontClass( hdc, szFile, szFacename, 14, FW_MEDIUM, CHINESEBIG5_CHARSET ); - TTTextFontPtr800 = new TTFontClass( hdc, szFile, szFacename, 14, FW_MEDIUM, CHINESEBIG5_CHARSET ); - TTLicenseFontPtr = new TTFontClass( hdc, szFile, szFacename, 12, FW_NORMAL, CHINESEBIG5_CHARSET ); - } - break; - - //================================================================= - // ENGLISH, FRENCH, GERMAN - //================================================================= - case LANG_GER: - case LANG_FRE: - case LANG_USA: - default: - - TTButtonFontPtr = new TTFontClass( hdc, szFile, szFacename, 22, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - - if( LANG_FRE == LanguageID ) { - TTButtonFontPtrSmall= new TTFontClass( hdc, szFile, szFacename, 20, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } else { - TTButtonFontPtrSmall= new TTFontClass( hdc, szFile, szFacename, 22, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - - TTTextFontPtr = new TTFontClass( hdc, szFile, szFacename, 16, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - TTTextFontPtr640 = new TTFontClass( hdc, szFile, szFacename, 14, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - TTTextFontPtr800 = new TTFontClass( hdc, szFile, szFacename, 14, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - TTLicenseFontPtr = new TTFontClass( hdc, szFile, szFacename, 12, FW_MEDIUM, ANSI_CHARSET, 0, 0, 0, FALSE ); - break; - } - - //---------------------------------------------------------------------- - // If we fell through... - //---------------------------------------------------------------------- - if( TTButtonFontPtr == NULL || TTTextFontPtr == NULL ) { - - strcpy( szFile, "Arial.tff" ); - strcpy( szFacename, "Arial" ); - - if( TTButtonFontPtr == NULL ) { - TTButtonFontPtr = new TTFontClass( hdc, szFile, szFacename, 22, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - if( TTButtonFontPtrSmall == NULL ) { - TTButtonFontPtrSmall= new TTFontClass( hdc, szFile, szFacename, 22, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - if( TTTextFontPtr == NULL ) { - TTTextFontPtr = new TTFontClass( hdc, szFile, szFacename, 16, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - if( TTTextFontPtr640 == NULL ) { - TTTextFontPtr640 = new TTFontClass( hdc, szFile, szFacename, 14, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - if( TTTextFontPtr800 == NULL ) { - TTTextFontPtr800 = new TTFontClass( hdc, szFile, szFacename, 14, FW_SEMIBOLD, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - if( TTLicenseFontPtr == NULL ) { - TTLicenseFontPtr = new TTFontClass( hdc, szFile, szFacename, 12, FW_MEDIUM, ANSI_CHARSET, 0, 0, 0, FALSE ); - } - } - } - assert( TTTextFontPtr != NULL ); - assert( TTTextFontPtr640 != NULL ); - assert( TTTextFontPtr800 != NULL ); - assert( TTButtonFontPtr != NULL ); - assert( TTButtonFontPtrSmall != NULL ); - assert( TTLicenseFontPtr != NULL ); -} - -/*********************************************************************************************** - * FontManagerClass::~FontManagerClass -- Destructor for FontManager class. * - * * - * INPUT: none. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/26/1998 MML : Created. * - *=============================================================================================*/ -FontManagerClass::~FontManagerClass ( void ) -{ - if ( TTButtonFontPtr != NULL ) { - delete TTButtonFontPtr; - TTButtonFontPtr = NULL; - } - if ( TTTextFontPtr != NULL ) { - delete TTTextFontPtr; - TTTextFontPtr = NULL; - } -} - - -/*********************************************************************************************** - * Font_From_TPF -- Convert flags into a font pointer. * - * * - * This routine will examine the specified flags and return with a pointer to the font * - * that the flags represent. * - * * - * INPUT: flags -- The flags to convert into a font pointer. * - * * - * OUTPUT: Returns with a font pointer that matches the flags. * - * * - * WARNINGS: If no match could be found, a default font pointer is returned. * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *=============================================================================================*/ -TTFontClass * Font_From_TPF ( TextPrintType flags ) -{ - TTFontClass *fontptr= NULL; - - switch (flags & 0x000F) { - - case TPF_BUTTON_FONT: - fontptr = TTButtonFontPtr; - break; - - case TPF_TEXT_FONT: - fontptr = TTTextFontPtr; - break; - - default: - fontptr = TTTextFontPtr; - break; - } - return( fontptr ); -} - - -/************************************************************************************************ - * Is_True_Type_Font -- Convert flags into a font pointer. * - * * - * This routine will examine the specified flags and return with a pointer to the font * - * that the flags represent. * - * * - * INPUT: flags -- The flags to convert into a font pointer. * - * * - * OUTPUT: Returns with a font pointer that matches the flags. * - * * - * WARNINGS: If no match could be found, a default font pointer is returned. * - * * - * HISTORY: * - * 05/26/1997 JLB : Created. * - *==============================================================================================*/ - -bool Is_True_Type_Font( TextPrintType flags ) -{ - if (( flags == TPF_BUTTON_FONT ) || ( flags == TPF_TEXT_FONT )) { - return TRUE; - } else { - return FALSE; - } -} - - - diff --git a/Generals/Code/Tools/Autorun/TTFont.h b/Generals/Code/Tools/Autorun/TTFont.h deleted file mode 100644 index 40e493d64b..0000000000 --- a/Generals/Code/Tools/Autorun/TTFont.h +++ /dev/null @@ -1,304 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/************************************************************************************************ - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - ************************************************************************************************ - * * - * Project Name: Setup * - * * - * Archive: ttfont.h * - * * - * Author: Joe_b * - * * - * Modtime: 6/23/97 3:14p * - * * - * Updated: 08/01/2000 [MML] * - * * - * Revision: 22 * - * * - *----------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ -#pragma once - -#ifndef TTFONT_H -#define TTFONT_H - -#include -#include "POINT.h" -#include "RECT.h" - - -/****************************************************************************** -** These are the control flags for Fancy_Text_Print function. -*/ -typedef enum TextPrintType { - - TPF_LASTPOINT = 0x0000, // Use previous font point value. - TPF_TT_10POINT = 0x0001, // True Type Font - 10 point - TPF_TT_12POINT = 0x0002, // True Type Font - 12 point - TPF_TT_14POINT = 0x000A, // True Type Font - 14 point - TPF_TT_16POINT = 0x000B, // True Type Font - 16 point - TPF_TT_18POINT = 0x000C, // True Type Font - 18 point - TPF_TT_20POINT = 0x000D, // True Type Font - 20 point - TPF_TT_22POINT = 0x000E, // True Type Font - 22 point - TPF_TT_24POINT = 0x000F, // True Type Font - 24 point - - TPF_BUTTON_FONT = 0x0010, - TPF_TEXT_FONT = 0x0020, - -} TextPrintType; - -typedef enum TextShadowType { - - TPF_NOSHADOW = 0x0000, - TPF_DROPSHADOW = 0x0001, // Use a simple drop shadow. - TPF_LIGHTSHADOW = 0x0002, - TPF_FULLSHADOW = 0x0004, // Use a full outline shadow. - TPF_DOUBLESHADOW = 0x0008, // Use a simple drop shadow. - TPF_SHADOW = 0x0010, // Print twice, using backcolor. - -} TextShadowType; - -typedef enum TextFormatType { - - TPF_TOP = DT_TOP, // Use with DT_SINGLELINE. Top-justifies text. - TPF_VCENTER = DT_VCENTER, // Use with DT_SINGLELINE. Centers text vertically. - TPF_BOTTOM = DT_BOTTOM, // Use with DT_SINGLELINE. Justifies test to the bottom of the rectangle. - TPF_LEFT = DT_LEFT, // Aligns text to the left. - TPF_CENTER = DT_CENTER, // Centers text horizontally in the rectangle. - TPF_RIGHT = DT_RIGHT, // Right justify text. - TPF_WORDBREAK = DT_WORDBREAK, // Lines are automatically broken between words. - TPF_SINGLE_LINE = DT_SINGLELINE, // All text on one line only. - TPF_NO_PREFIX = DT_NOPREFIX, // Turns off processing of prefix characters. - TPF_PATH_ELLIPSIS = DT_PATH_ELLIPSIS, // For displayed text, replaces characters in the middle of the string with ellipses so that the result fits in the specified rectangle. - -} TextFormatType; - -/****************************************************************************** -** Standard button text print flags. -*/ -//#define TPF_BUTTON (TextFormatType)( DT_VCENTER | DT_CENTER | DT_SINGLELINE ) -//#define TPF_CENTER_FORMAT (TextFormatType)( DT_VCENTER | DT_CENTER | DT_WORDBREAK ) -//#define TPF_CHECKBOX (TextFormatType)( DT_LEFT | DT_VCENTER | DT_WORDBREAK ) -//#define TPF_EDIT (TextFormatType)( DT_LEFT | DT_VCENTER ) -//#define TPF_DEFAULT (TextFormatType)( DT_LEFT | DT_WORDBREAK ) - -#define TPF_BUTTON (TextFormatType)( DT_CENTER | DT_VCENTER | DT_SINGLELINE ) -#define TPF_EDITBOX (TextFormatType)( DT_LEFT | DT_VCENTER | DT_SINGLELINE ) -#define TPF_RADIO (TextFormatType)( DT_LEFT | DT_WORDBREAK ) -#define TPF_CHECKBOX (TextFormatType)( DT_LEFT | DT_WORDBREAK ) -#define TPF_OUTER_SCROLL (TextFormatType)( DT_LEFT | DT_WORDBREAK ) -#define TPF_INNER_SCROLL (TextFormatType)( DT_LEFT | DT_SINGLELINE ) - -#define TPF_LEFT_TEXT (TextFormatType)( DT_LEFT | DT_WORDBREAK ) -#define TPF_CENTER_TEXT (TextFormatType)( DT_CENTER | DT_WORDBREAK ) -#define TPF_RIGHT_TEXT (TextFormatType)( DT_RIGHT | DT_WORDBREAK ) - -#define TPF_LEFT_TOP_ALIGNMENT (TextFormatType)( DT_LEFT | DT_TOP | DT_SINGLELINE ) -#define TPF_LEFT_BOTTOM_ALIGNMENT (TextFormatType)( DT_LEFT | DT_BOTTOM | DT_SINGLELINE ) -#define TPF_LEFT_JUSTIFY (TextFormatType)( DT_LEFT | DT_VCENTER | DT_SINGLELINE ) - -#define TPF_RIGHT_TOP_ALIGNMENT (TextFormatType)( DT_RIGHT | DT_TOP | DT_SINGLELINE ) -#define TPF_RIGHT_BOTTOM_ALIGNMENT (TextFormatType)( DT_RIGHT | DT_BOTTOM | DT_SINGLELINE ) -#define TPF_RIGHT_JUSTIFY (TextFormatType)( DT_RIGHT | DT_VCENTER | DT_SINGLELINE ) - -#define TPF_CENTER_TOP_ALIGNMENT (TextFormatType)( DT_CENTER | DT_TOP | DT_SINGLELINE ) -#define TPF_CENTER_BOTTOM_ALIGNMENT (TextFormatType)( DT_CENTER | DT_BOTTOM | DT_SINGLELINE ) -#define TPF_CENTER_JUSTIFY (TextFormatType)( DT_CENTER | DT_VCENTER | DT_SINGLELINE ) - - - -/****************************************************************************** -** These are the control flags for Fancy_Text_Print function. -*/ -typedef enum SpecialEffectType { - TPF_NONE =0x0000, // No special effects needed. - TPF_CUTOFF_AT_WIDTH =0x0001, // Don't print past the allowed width. - TPF_BURST_MODE =0x0002, // Print text one letter at a time like a typewriter. - TPF_SPECIAL_WRAP =0x0003, // Begin at a specified point but start next line at a point before the starting point. -} SpecialEffectType; - - -/****************************************************************************** -** Global DC. Use it or create your own! -*/ -extern HDC BackBufferDC; - -/****************************************************************************** -** Global Colors for use throughout program. -*/ -extern unsigned long TEXT_COLOR; -extern unsigned long SHADOW_COLOR; -extern unsigned long TEXT_NORMAL_COLOR; -extern unsigned long TEXT_FOCUSED_COLOR; -extern unsigned long TEXT_PRESSED_COLOR; -extern unsigned long TEXT_NORMAL_SHADOW_COLOR; -extern unsigned long TEXT_FOCUSED_SHADOW_COLOR; -extern unsigned long TEXT_PRESSED_SHADOW_COLOR; - -extern unsigned long WHITE_COLOR; -extern unsigned long BLACK_COLOR; -extern unsigned long RED_COLOR; -extern unsigned long ORANGE_COLOR; -extern unsigned long YELLOW_COLOR; -extern unsigned long GREEN_COLOR; -extern unsigned long BLUE_COLOR; -extern unsigned long INDIGO_COLOR; -extern unsigned long VIOLET_COLOR; - - -/****************************************************************************** -** This is a True Type Font class object to create and use True Type fonts. -******************************************************************************/ -// Font Weight - Specifies the weight of the font in the range 0 through 1000. -// For example, 400 is normal and 700 is bold. -// If this value is zero, a default weight is used. -// -// The following values are defined for convenience: -// FW_DONTCARE 0 FW_SEMIBOLD 600 -// FW_THIN 100 FW_DEMIBOLD 600 -// FW_EXTRALIGHT 200 FW_BOLD 700 -// FW_ULTRALIGHT 200 FW_EXTRABOLD 800 -// FW_LIGHT 300 FW_ULTRABOLD 800 -// FW_NORMAL 400 FW_HEAVY 900 -// FW_REGULAR 400 FW_BLACK 900 -// FW_MEDIUM 500 -//----------------------------------------------------------------------------- - -class TTFontClass -{ - public: - - TTFontClass ( - HDC hdc, - char * filename, - char * facename, - int height, - int weight = FW_NORMAL, - BYTE charset = ANSI_CHARSET, - int width = 0, - int escapement = 0, - int orientation = 0, - BYTE italic = FALSE, - BYTE underline = FALSE, - BYTE strikeout = FALSE, - BYTE outputPrecision = OUT_TT_ONLY_PRECIS, - BYTE clipPrecision = CLIP_DEFAULT_PRECIS, - BYTE quality = PROOF_QUALITY, - BYTE pitchAndFamily = FF_DONTCARE ); - - virtual ~TTFontClass(void) - { - if ( Font != NULL ) { - DeleteObject( Font ); - Font = NULL; - } - RemoveFontResource( szFilename ); - }; - - virtual int Char_Pixel_Width ( HDC hdc, UINT c ) const; - virtual int Char_Pixel_Width ( HDC hdc, char const * string, int *num_bytes=NULL ) const; - virtual int String_Pixel_Width ( HDC hdc, char const * string ) const; - virtual void String_Pixel_Bounds ( HDC hdc, const char * string, Rect& bounds ) const; - virtual int Get_Width ( void ) const; - virtual int Get_Height ( void ) const; - virtual int Set_XSpacing ( HDC hdc, int x ); - virtual int Set_YSpacing ( int y ); - virtual int Find_Text_VLength ( HDC hdc, char *str, int width ); - virtual HFONT Get_Font_Ptr ( void ) { return Font; }; - virtual int IsFontDBCS ( void ) const { return ((CharSet==SHIFTJIS_CHARSET)||(CharSet==HANGEUL_CHARSET)||(CharSet==CHINESEBIG5_CHARSET)); }; // [OYO] - virtual UINT Get_Double_Byte_Char ( const char *string, int *num_bytes=NULL ) const; - - virtual Point2D Print( - HDC hdc, - char const * string, - Rect const & cliprect, - COLORREF forecolor = TEXT_COLOR, - COLORREF backcolor = TEXT_NORMAL_SHADOW_COLOR, - TextFormatType flag = TPF_LEFT_TEXT, - TextShadowType shadow = TPF_NOSHADOW ); - - virtual Point2D Print( - HDC hdc, - wchar_t const * string, - Rect const & cliprect, - COLORREF forecolor = TEXT_COLOR, - COLORREF backcolor = TEXT_NORMAL_SHADOW_COLOR, - TextFormatType flag = TPF_LEFT_TEXT, - TextShadowType shadow = TPF_NOSHADOW ); - - private: - - HFONT Font; - long Height; - long Ascent; - long Descent; - long InternalLeading; - long ExternalLeading; - long AveCharWidth; - long MaxCharWidth; - long Overhang; - long Italic; - long Underlined; - long StruckOut; - int CharSet; // [OYO] - int FontXSpacing; // GetTextCharacterExtra; - int FontYSpacing; - char szFacename[ MAX_PATH ]; - char szFilename[ MAX_PATH ]; -}; - - -//------------------------------------------------------------------------- -// Global functions. -//------------------------------------------------------------------------- -TTFontClass * Font_From_TPF ( TextPrintType flags ); // Returns FontPtr based on flags passed in. -bool Is_True_Type_Font ( TextPrintType flags ); // True Type??? - -//------------------------------------------------------------------------- -// This class is a wrapper around all the fonts that we want to be available. -// The constructer will make them, and the destructor will remove them for us. -//------------------------------------------------------------------------- -class FontManagerClass -{ - public: - FontManagerClass ( HDC hdc ); - ~FontManagerClass ( void ); - TTFontClass * Get_Font ( TextPrintType flags ) { return( Font_From_TPF( flags )); }; -}; - - -/****************************************************************************** -** FontManager Class Pointer. -*/ -extern FontManagerClass *FontManager; - -/****************************************************************************** -** Loaded data file pointers. -*/ -extern TTFontClass *TTButtonFontPtr; -extern TTFontClass *TTButtonFontPtrSmall; -extern TTFontClass *TTTextFontPtr; -extern TTFontClass *TTTextFontPtr640; -extern TTFontClass *TTTextFontPtr800; -extern TTFontClass *TTLicenseFontPtr; - - -#endif diff --git a/Generals/Code/Tools/Autorun/Utils.cpp b/Generals/Code/Tools/Autorun/Utils.cpp deleted file mode 100644 index d9a185d9b5..0000000000 --- a/Generals/Code/Tools/Autorun/Utils.cpp +++ /dev/null @@ -1,669 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - **************************************************************************** - * * - * Project Name : Setup * - * * - * File Name : UTILS.C * - * * - * Programmers: Maria del Mar McCready Legg * - * * - * Start Date : December 12, 1992 * - * * - * Last Update : March 16, 1998 [MML] * - * * - *--------------------------------------------------------------------------* - * Functions: * - * * - * Clip_Line_To_Rect -- Clips a line (two points) against a * - * rectangle, using CS algorithm. * - * Compute_Code -- computes line clipping bit code for * - * point & rectangle. * - * Copy_File -- Copies a file from one dir to another. * - * Convert_Hex_To_Version -- Converts a hex num obtained from the * - * Registry, into a string * - * representation of a version * - * number ( XX.XX ). * - * Convert_Version_To_Hex -- Converts a string to an unsigned long. * - * Convert_To_Version_Format -- Converts version string's "," to "."s * - * Dialog_Box -- draws a dialog background box * - * Draw_Box -- Displays a highlighted box. * - * Fatal -- General purpose fatal error handler. * - * Get_Version -- Retrieves a version string from a file. * - * Get_String -- Returns a pointer to the undipped text. * - * Is_File_Available -- Use both FindFirst to check that CD is * - * in drive & if File_Exists() to * - * determine if file is really there. * - * Pad_With_Zeros -- Adds zeros to the beginning of string. * - * String_Width -- Calculate with of the string. * - * Strip_Newlines -- Remove '\r' from string passed in. * - * TextPtr -- Returns a pointer to the undipped text. * - * Path_Name_Valid -- Validate that the path has the correct * - * number of chars between '\' in the * - * path. * - * Path_Get_Next_Directory -- Return the next dir path from string. * - * Path_Add_Back_Slash -- Add a "\\" to the end of the string. * - * Path_Remove_Back_Slash -- Remove a '\\' at the end of the string. * - * Path_Trim_Blanks -- Trim lead/trail white spaces off string * - * Pad_With_Zeros -- Adds zeros to the beginning of string. * - * Remove_Ending_Spaces -- Remove any blank spaces at end of string* - * Remove_Spaces -- Remove spaces from string passed in. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ - -#include -#include "ARGS.H" -#include "assert.h" -#include "Locale_API.h" -#include "resource.h" -#include "Utils.h" -#include "WinFix.H" -#include "Wnd_File.h" -#include -#include -//#include "resources.h" - - - -//---------------------------------------------------------------------------- -// -// Function: Fix_Single_Ampersands() -// -// Purpose: To replace each "&" with "&&" for display in a dialog. -// Some dialogs mistake a single "&" for an accelerator key. -// -// Input: pszString - any NULL terminated string. -// -// Returns: VOID (returns nothing) -// -// Comments: Modifies the characters in pszString. -// -//--------------------------------------------------------------------------- - -void Fix_Single_Ampersands ( LPSTR pszString, bool upper_case ) -{ - char pszTemp[ MAX_PATH ]; // variable to hold the string passed - char pszOld[ MAX_PATH ]; // variable to hold the string passed - char * letter; - int i = 0; - - lstrcpy((LPSTR)pszOld, (LPSTR)pszString ); - letter = pszOld; - memset ( pszTemp, '\0', MAX_PATH ); - - //---------------------------------------------------------------------- - // While our ptr has not passed the end of the string... - //---------------------------------------------------------------------- - while (*letter != '\0') { - - if (*letter == '&') { - - pszTemp[i++] = '&'; - pszTemp[i++] = '&'; - letter++; - - } else { - - if ( upper_case ) { - pszTemp[i++] = (char) toupper( *( letter++ )); - } else { - pszTemp[i++] = *(letter++); - } - } - } - strcpy((LPSTR)pszString, (LPSTR)pszTemp ); -} - -void Fix_Single_Ampersands ( wchar_t *pszString, bool upper_case ) -{ - wchar_t pszTemp[ MAX_PATH ]; // variable to hold the string passed - wchar_t pszOld[ MAX_PATH ]; // variable to hold the string passed - wchar_t *letter; - int i = 0; - - wcscpy( pszOld, pszString ); - letter = pszOld; - memset ( pszTemp, '\0', MAX_PATH ); - - //---------------------------------------------------------------------- - // While our ptr has not passed the end of the string... - //---------------------------------------------------------------------- - while (*letter != '\0') { - - if (*letter == '&') { - - pszTemp[i++] = '&'; - pszTemp[i++] = '&'; - letter++; - - } else { - - if ( upper_case ) { - pszTemp[i++] = (char) toupper( *( letter++ )); - } else { - pszTemp[i++] = *(letter++); - } - } - } - wcscpy( pszString, pszTemp ); -} - -////////////////UnicodeString Fix_Single_Ampersands( UnicodeString string, bool upper_case) -////////////////{ -//////////////// UnicodeString retval; -//////////////// -//////////////// Int i = 0; -//////////////// while (i < string.getLength()) { -//////////////// if (upper_case) { -//////////////// retval.concat(toupper(string.getCharAt(i))); -//////////////// } else { -//////////////// retval.concat(string.getCharAt(i)); -//////////////// } -//////////////// if (string.getCharAt(i) == L'&') { -//////////////// retval.concat(string.getCharAt(i)); -//////////////// } -//////////////// ++i; -//////////////// } -//////////////// -//////////////// return retval; -////////////////} - -//---------------------------------------------------------------------------- -// -// Function: Fix_Double_Ampersands() -// -// Purpose: To replace each "&&" with "&" for display in a dialog. -// Some dialogs mistake a single "&" for an accelerator key. -// -// Input: pszString - any NULL terminated string. -// -// Returns: VOID (returns nothing) -// -// Comments: Modifies the characters in pszString. -// -//--------------------------------------------------------------------------- - -void Fix_Double_Ampersands ( LPSTR pszString, bool upper_case ) -{ - char pszTemp[ MAX_PATH ]; // variable to hold the string passed - char pszOld[ MAX_PATH ]; // variable to hold the string passed - char *letter; - int i = 0; - - lstrcpy( (LPSTR)pszOld, (LPSTR)pszString ); - letter = pszOld; - memset ( pszTemp, '\0', MAX_PATH ); - - //---------------------------------------------------------------------- - // While our ptr has not passed the end of the string... - //---------------------------------------------------------------------- - while (*letter != '\0') { - - if ((*letter == '&') && (*( letter+1 ) == '&')) { - - pszTemp[i++] = '&'; - letter = letter + 2; - - } else { - - if ( upper_case ) { - pszTemp[i++] = (char) toupper( *( letter++ )); - } else { - pszTemp[i++] = *(letter++); - } - } - } - strcpy((LPSTR)pszString, (LPSTR)pszTemp ); -} - - -/****************************************************************************** - * Load_Alloc_Data -- Allocates a buffer and loads the file into it. * - * * - * This is the C++ replacement for the Load_Alloc_Data function. It will * - * allocate the memory big enough to hold the file & read the file into it. * - * * - * INPUT: file -- The file to read. * - * mem -- The memory system to use for allocation. * - * * - * OUTPUT: Returns with a pointer to the allocated and filled memory block. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/17/1994 JLB : Created. * - *============================================================================*/ - -void * Load_Alloc_Data( char *filename, long *filesize ) -{ - int size, bytes_read; - void *ptr = NULL; - StandardFileClass file; - - //------------------------------------------------------------------------- - // Open file in READ ONLY mode. If fails, exit. - //------------------------------------------------------------------------- - file.Open( filename, MODE_READ_ONLY ); - if ( !file.Query_Open()) { - return( NULL ); - } - - //------------------------------------------------------------------------- - // Get filesize and create a buffer. - //------------------------------------------------------------------------- - size = file.Query_Size(); - ptr = (void*)malloc(size + 1); - if ( !ptr ) { - return( NULL ); - } - - //------------------------------------------------------------------------- - // Read data into the buffer, close the file. - //------------------------------------------------------------------------- - memset( ptr, '\0', size + 1 ); - bytes_read = file.Read( ptr, size ); - file.Close(); - - //------------------------------------------------------------------------- - // Check return bytes. It should match the file size. - //------------------------------------------------------------------------- - assert( bytes_read == size ); - if ( bytes_read != size ) { - free(ptr); - return( NULL ); - } - - if ( filesize != NULL ) { - *filesize = (long)size; - } - return( ptr ); -} - -/**************************************************************************** - * MIXFILECLASS::LOAD_FILE -- Returns a buffer loaded with file desired. * - * * - * INPUT: none. * * - * * - * OUTPUT: none. * - * * - * WARNINGS: Searches MixFile first, then local directory. * - * Use free() to release buffer. * * - * * - * HISTORY: * - * 04/13/1998 ML/MG : Created. * - *==========================================================================*/ - -void *Load_File ( char *filename, long *filesize ) -{ - void *ptr = NULL; - - if ( filename == NULL || filename[0] == '\0' ) { - return( NULL ); - } - - //------------------------------------------------------------------------- - // Try loading from local directory. - //------------------------------------------------------------------------- - ptr = Load_Alloc_Data( filename, filesize ); - - return( ptr ); -} - - -/**************************************************************************** - * MAKE_CURRENT_PATH_TO -- Returns a buffer to path desired. * - * * - * INPUT: none. * * - * * - * OUTPUT: none. * - * * - * WARNINGS: * * - * * - * HISTORY: * - * 10/08/2001 MML : Created. * - *==========================================================================*/ - -char *Make_Current_Path_To ( const char *filename, char *path ) -{ - char szPath [ _MAX_PATH ]; - char drive [ _MAX_DRIVE]; - char dir [ _MAX_DIR ]; - - strcpy( szPath, Args->Get_argv(0)); - _splitpath( szPath, drive, dir, NULL, NULL ); - _makepath( szPath, drive, dir, NULL, NULL ); - Path_Add_Back_Slash( szPath ); - strcat( szPath, filename ); - - if( path != NULL ) { - strcpy( path, szPath ); - } - return( path ); -} - -wchar_t *Make_Current_Path_To ( const wchar_t *filename, wchar_t *path ) -{ - wchar_t szPath [ _MAX_PATH ]; - wchar_t drive [ _MAX_DRIVE]; - wchar_t dir [ _MAX_DIR ]; - - wcscpy( szPath, (wchar_t *)Args->Get_argv(0)); - _wsplitpath( szPath, drive, dir, NULL, NULL ); - _wmakepath( szPath, drive, dir, NULL, NULL ); - Path_Add_Back_Slash( szPath ); - wcscat( szPath, filename ); - - if( path != NULL ) { - wcscpy( path, szPath ); - } - return( path ); -} - - -/****************************************************************************** - * Path_Add_Back_Slash -- Add a '\\' to the end of the path. - * - * INPUT: char * path -- Pointer to the string to be modified. - * - * OUTPUT: char * path - * - * WARNINGS: none - * - * HISTORY: - * 08/14/1998 MML : Created. - *============================================================================*/ - -char *Path_Add_Back_Slash ( char *path ) -{ - if ( path != NULL && *path != '\0' ) { - if ( path[ strlen( path )-1 ] != '\\' ) { - strcat( path, "\\" ); - } - } - return( path ); -} - -wchar_t *Path_Add_Back_Slash ( wchar_t *path ) -{ - if ( path != NULL && *path != '\0' ) { - if ( path[ wcslen( path )-1 ] != '\\' ) { - wcscat( path, L"\\" ); - } - } - return( path ); -} - - -/****************************************************************************** - * Path_Remove_Back_Slash -- Remove a '\\' from the end of the path. - * - * INPUT: char * path -- Pointer to the string to be modified. - * - * OUTPUT: char * path - * - * WARNINGS: none - * - * HISTORY: - * 08/14/1998 MML : Created. - *============================================================================*/ - -char *Path_Remove_Back_Slash ( char *path ) -{ - if ( path != NULL && *path != '\0' ) { - if ( path[ strlen( path )-1 ] == '\\' ) { - path[ strlen( path )-1 ] = '\0'; - } - } - return( path ); -} - -wchar_t *Path_Remove_Back_Slash ( wchar_t *path ) -{ - if ( path != NULL && *path != '\0' ) { - if ( path[ wcslen( path )-1 ] == L'\\' ) { - path[ wcslen( path )-1 ] = L'\0'; - } - } - return( path ); -} - -/*--------------------------------------------------------------------------*/ -/* Function: PlugInProductName */ -/* */ -/* Descrip: The function plugs the product name defined in */ -/* SdProductName() into %P found in the static message. */ -/* It will search for the first nMax controls only. */ -/* Misc: */ -/* */ -/*--------------------------------------------------------------------------*/ - -void PlugInProductName ( char *szString, char *szName ) -{ - int nCount, nMsgLength; - char szTextBuf[ MAX_PATH ]; - char szOut[ MAX_PATH ]; - char szProduct[ MAX_PATH ]; - char * temp = NULL; - char * next = NULL; - - if ( szName == NULL || szName[0] == '\0' ) { - return; - } - - //-------------------------------------------------------------------------- - // Find the first appearance of "%P". - //-------------------------------------------------------------------------- - strcpy( szProduct, szName ); - strcpy( szTextBuf, szString ); - nMsgLength = strlen( szTextBuf ); - nCount = 0; - temp = strstr( szTextBuf, "%s" ); - - //------------------------------------------------------------- - // Substitute each "%P" with "%s". nStrReturn is the index - // into the buffer where "%P" was found. - //------------------------------------------------------------- - while ( temp != NULL && nCount < 6) { - next = temp+1; - nCount = nCount + 1; - temp = strstr( next, "%s" ); - } - - //------------------------------------------------------------- - // Only support up to 5 product name per message. - // Do the substitution of the product name and store in szOut. - //------------------------------------------------------------- - switch( nCount ) { - case 1: - sprintf( szOut, szTextBuf, szProduct ); - break; - case 2: - sprintf( szOut, szTextBuf, szProduct, szProduct ); - break; - case 3: - sprintf( szOut, szTextBuf, szProduct, szProduct, szProduct ); - break; - case 4: - sprintf( szOut, szTextBuf, szProduct, szProduct, szProduct, szProduct ); - break; - case 5: - sprintf( szOut, szTextBuf, szProduct, szProduct, szProduct, szProduct, szProduct, szProduct ); - break; - } - - //------------------------------------------------------------- - // Replace szTextBuf with szOut. - //------------------------------------------------------------- - if ( nCount >= 1 ) { - strcpy( szString, szOut ); - } -} - -/*--------------------------------------------------------------------------*/ -/* Function: PlugInProductName */ -/* */ -/* Descrip: The function plugs the product name defined in */ -/* SdProductName() into %P found in the static message. */ -/* It will search for the first nMax controls only. */ -/* Misc: */ -/* */ -/*--------------------------------------------------------------------------*/ - -void PlugInProductName( char *szString, int nName ) -{ -/* - int nCount, nMsgLength; - char szTextBuf[ MAX_PATH ]; - char szOut[ MAX_PATH ]; - char szProduct[ MAX_PATH ]; - char * temp = NULL; - char * next = NULL; - - if ( nName <= STRNONE ) { - nName = STRNONE; - } - - //-------------------------------------------------------------------------- - // Find the first appearance of "%P". - //------------------------------------------------------------- -// LoadString( Main::hInstance, nName, szProduct, MAX_PATH ); - Locale_GetString( nName, szProduct ); - - strcpy( szTextBuf, szString ); - nMsgLength = strlen( szTextBuf ); - nCount = 0; - temp = strstr( szTextBuf, "%s" ); - - //------------------------------------------------------------- - // Substitute each "%P" with "%s". nStrReturn is the index - // into the buffer where "%P" was found. - //------------------------------------------------------------- - while ( temp != NULL && nCount < 6) { - next = temp+1; - nCount = nCount + 1; - temp = strstr( next, "%s" ); - } - - //------------------------------------------------------------- - // Only support up to 5 product name per message. - // Do the substitution of the product name and store in szOut. - //------------------------------------------------------------- - switch( nCount ) { - case 1: - sprintf( szOut, szTextBuf, szProduct ); - break; - case 2: - sprintf( szOut, szTextBuf, szProduct, szProduct ); - break; - case 3: - sprintf( szOut, szTextBuf, szProduct, szProduct, szProduct ); - break; - case 4: - sprintf( szOut, szTextBuf, szProduct, szProduct, szProduct, szProduct ); - break; - case 5: - sprintf( szOut, szTextBuf, szProduct, szProduct, szProduct, szProduct, szProduct, szProduct ); - break; - } - - //------------------------------------------------------------- - // Replace szTextBuf with szOut. - //------------------------------------------------------------- - if ( nCount >= 1 ) { - strcpy( szString, szOut ); - } -*/ -} - -/*--------------------------------------------------------------------------*/ -/* Function: PlugInProductName */ -/* */ -/* Descrip: The function plugs the product name defined in */ -/* SdProductName() into %P found in the static message. */ -/* It will search for the first nMax controls only. */ -/* Misc: */ -/* */ -/*--------------------------------------------------------------------------*/ - -void PlugInProductName ( wchar_t *szString, const wchar_t *szName ) -{ - int nCount, nMsgLength; - wchar_t szTextBuf[ MAX_PATH ]; - wchar_t szOut[ MAX_PATH ]; - wchar_t szProduct[ MAX_PATH ]; - wchar_t *temp = NULL; - wchar_t *next = NULL; - - if ( szName == NULL || szName[0] == '\0' ) { - return; - } - - //-------------------------------------------------------------------------- - // Find the first appearance of "%P". - //-------------------------------------------------------------------------- - wcscpy( szProduct, szName ); - wcscpy( szTextBuf, szString ); - nMsgLength = wcslen( szTextBuf ); - nCount = 0; - temp = wcsstr( szTextBuf, L"%s" ); - - //------------------------------------------------------------- - // Substitute each "%P" with "%s". nStrReturn is the index - // into the buffer where "%P" was found. - //------------------------------------------------------------- - while ( temp != NULL && nCount < 6) { - next = temp+1; - nCount = nCount + 1; - temp = wcsstr( next, L"%s" ); - } - - //------------------------------------------------------------- - // Only support up to 5 product name per message. - // Do the substitution of the product name and store in szOut. - //------------------------------------------------------------- - switch( nCount ) { - case 1: - swprintf( szOut, szTextBuf, szProduct ); - break; - case 2: - swprintf( szOut, szTextBuf, szProduct, szProduct ); - break; - case 3: - swprintf( szOut, szTextBuf, szProduct, szProduct, szProduct ); - break; - case 4: - swprintf( szOut, szTextBuf, szProduct, szProduct, szProduct, szProduct ); - break; - case 5: - swprintf( szOut, szTextBuf, szProduct, szProduct, szProduct, szProduct, szProduct, szProduct ); - break; - } - - //------------------------------------------------------------- - // Replace szTextBuf with szOut. - //------------------------------------------------------------- - if ( nCount >= 1 ) { - wcscpy( szString, szOut ); - } -} - - - - diff --git a/Generals/Code/Tools/Autorun/Utils.h b/Generals/Code/Tools/Autorun/Utils.h deleted file mode 100644 index c349700482..0000000000 --- a/Generals/Code/Tools/Autorun/Utils.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *************************************************************************** - * * - * Project Name : Setup * - * * - * File Name : UTILS.H * - * * - * Programmers: Maria del Mar McCready Legg * - * * - * Start Date : December 20, 1994 * - * * - * Last Update : April 06, 1998 [MML] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#pragma once - -#ifndef UTILS_H -#define UTILS_H - -#include - - -/****************************************************************************** -** Swaps two objects. -*/ -template -void swap( T & left, T & right ) -{ - T temp; - - temp = left; - left = right; - right = temp; -} - - -void Fix_Single_Ampersands ( LPSTR pszString, bool upper_case ); -void Fix_Single_Ampersands ( wchar_t *pszString, bool upper_case ); -//UnicodeString Fix_Single_Ampersands ( UnicodeString string, bool upper_case); -void Fix_Double_Ampersands ( LPSTR string, bool upper_case ); -void * Load_Alloc_Data ( char *filename, long *filesize=0 ); -void * Load_File ( char *filename, long *filesize=0 ); -char * Make_Current_Path_To ( const char *filename, char *path ); -wchar_t * Make_Current_Path_To ( const wchar_t *filename, wchar_t *path ); -char * Path_Add_Back_Slash ( char *path ); -char * Path_Remove_Back_Slash ( char *path ); -wchar_t * Path_Add_Back_Slash ( wchar_t *path ); -wchar_t * Path_Remove_Back_Slash ( wchar_t *path ); -void PlugInProductName ( char *szString, int nName ); -void PlugInProductName ( char *szString, char *szName ); -void PlugInProductName ( wchar_t *szString, const wchar_t *szName ); - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Autorun/ViewHTML.cpp b/Generals/Code/Tools/Autorun/ViewHTML.cpp deleted file mode 100644 index 4ea3f7d755..0000000000 --- a/Generals/Code/Tools/Autorun/ViewHTML.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: /Renegade Setup/Autorun/ViewHTML.cpp $ -* -* DESCRIPTION -* -* PROGRAMMER -* $Author: Maria_l $ -* -* VERSION INFO -* $Modtime: 2/16/01 11:32a $ -* $Revision: 3 $ -* -******************************************************************************/ - -#pragma warning(disable : 4201 4310) -#include - -#include "ViewHTML.h" -//#include "..\win.h" -#include -//#include "debugprint.h" -#include "Wnd_File.h" - - -/****************************************************************************** -* -* NAME -* ViewHTML -* -* DESCRIPTION -* Launch the default browser to view the specified URL -* -* INPUTS -* URL - Website address -* Wait - Wait for user to close browser (default = false) -* Callback - User callback to invoke during wait (default = NULL callback) -* -* RESULT -* Success - True if successful; otherwise false -* -******************************************************************************/ - -bool ViewHTML(const char* url, bool wait, const CallbackHook& callback) - { -// DebugPrint("ViewHTML()\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" )); - Msg( __LINE__, TEXT(__FILE__), TEXT("ViewHTML()" )); - Msg( __LINE__, TEXT(__FILE__), TEXT("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" )); - - //-------------------------------------------------------------------------- - // Just return if no URL specified - //-------------------------------------------------------------------------- - if ((url == NULL) || (strlen(url) == 0)) - { -// DebugPrint("***** No URL specified.\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("***** No URL specified." )); - return false; - } - - //-------------------------------------------------------------------------- - // Create unique temporary HTML filename - //-------------------------------------------------------------------------- - char tempPath[MAX_PATH]; - GetWindowsDirectory(tempPath, MAX_PATH); - - char filename1[MAX_PATH]; - char filename2[MAX_PATH]; - GetTempFileName(tempPath, "WS", 0, filename1); - - strcpy( filename2, filename1 ); - char* extPtr = strrchr(filename2, '.'); - strcpy(extPtr, ".html"); - -// DebugPrint(filename); - Msg( __LINE__, TEXT(__FILE__), TEXT("filename = %s"), filename2 ); - - //-------------------------------------------------------------------------- - // Create file - //-------------------------------------------------------------------------- - HANDLE file = CreateFile( - filename2, - GENERIC_WRITE, - 0, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (file == INVALID_HANDLE_VALUE) - { -// DebugPrint("***** Unable to create temporary HTML file '%s'\n", filename); - Msg( __LINE__, TEXT(__FILE__), TEXT("***** Unable to create temporary HTML file '%s"), filename2 ); - return false; - } - - // Write generic contents - const char* contents = "ViewHTML"; - DWORD written; - WriteFile(file, contents, strlen(contents), &written, NULL); - CloseHandle(file); - - // Find the executable that can launch this file - char exeName[MAX_PATH]; - HINSTANCE hInst = FindExecutable(filename2, NULL, exeName); - - // Delete temporary file - DeleteFile(filename2); - DeleteFile(filename1); - - if ((int)hInst <= 32) - { -// DebugPrint("***** Unable to find executable that will display HTML files.\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("***** Unable to find executable that will display HTML files.")); - return false; - } - - // Launch browser with specified URL - char commandLine[MAX_PATH]; - sprintf(commandLine, "[open] %s", url); - - STARTUPINFO startupInfo; - memset(&startupInfo, 0, sizeof(startupInfo)); - startupInfo.cb = sizeof(startupInfo); - - PROCESS_INFORMATION processInfo; - - BOOL createSuccess = CreateProcess( - exeName, - commandLine, - NULL, - NULL, - FALSE, - 0, - NULL, - NULL, - &startupInfo, - &processInfo); - - if (createSuccess == FALSE) - { -// DebugPrint("\t**** Failed to CreateProcess(%s, %s)\n", exeName, commandLine); - Msg( __LINE__, TEXT(__FILE__), TEXT("\t**** Failed to CreateProcess(%s, %s)"), exeName, commandLine ); - return false; - } - - if (wait == true) - { - WaitForInputIdle(processInfo.hProcess, 5000); - - bool waiting = true; - - while (waiting == true) - { - if (callback.DoCallback() == true) - { - break; - } - - Sleep(100); - - DWORD exitCode; - GetExitCodeProcess(processInfo.hProcess, &exitCode); - - if (exitCode != STILL_ACTIVE) - { - waiting = false; - } - } - } - - return true; - } diff --git a/Generals/Code/Tools/Autorun/ViewHTML.h b/Generals/Code/Tools/Autorun/ViewHTML.h deleted file mode 100644 index ede5b562bd..0000000000 --- a/Generals/Code/Tools/Autorun/ViewHTML.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: /Renegade Setup/Autorun/ViewHTML.h $ -* -* DESCRIPTION -* -* PROGRAMMER -* $Author: Maria_l $ -* -* VERSION INFO -* $Modtime: 8/14/00 7:53p $ -* $Revision: 3 $ -* -******************************************************************************/ - -#ifndef VIEWHTML_H -#define VIEWHTML_H - -#include "CallbackHook.h" - -bool ViewHTML(const char* url, bool wait = false, const CallbackHook& callback = CallbackHook()); - -#endif // VIEWHTML_H diff --git a/Generals/Code/Tools/Autorun/WSYS_File.cpp b/Generals/Code/Tools/Autorun/WSYS_File.cpp deleted file mode 100644 index d3c3200bab..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_File.cpp +++ /dev/null @@ -1,268 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO_ -// -// File name: IO_File.cpp -// -// Created: 4/23/01 -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include -#include -#include -#include - - -#include "WSYS_file.h" - - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - -//================================================================= -// File::File -//================================================================= - -File::File() -: m_open(FALSE), - m_deleteOnClose(FALSE), - m_access(NONE) -{ - - setName(""); - -} - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - - -//================================================================= -// File::~File -//================================================================= - -File::~File() -{ - close(); -} - -//================================================================= -// File::open -//================================================================= -/** - * Any derived open() members must first call File::open. If File::open - * succeeds but the derived class's open failes then make sure to call - * File::close() before returning. - */ -//================================================================= - -Bool File::open( const Char *filename, Int access ) -{ - if( m_open ) - { - return FALSE; - } - - setName( filename ); - - if( (access & ( TEXT | BINARY)) == ( TEXT | BINARY )) - { - // illegal access - return FALSE; - } - - if ( !(access & (READ|APPEND)) ) - { - access |= TRUNCATE; - } - - if ( (access & (READ|WRITE)) == 0 ) - { - access = READ; - } - - if ( (access & (TEXT|BINARY)) == 0 ) - { - access = BINARY; - } - - m_access = access; - m_open = TRUE; - return TRUE; -} - -//================================================================= -// File::close -//================================================================= -/** - * Must call File::close() for each successful File::open() call. - */ -//================================================================= - -void File::close( void ) -{ - if( m_open ) - { - setName( "" ); - m_open = FALSE; - if ( m_deleteOnClose ) - { - delete this; // on special cases File object will delete itself when closing - } - } -} - -//================================================================= -// File::size -//================================================================= -/** - * Default implementation of File::size. Derived classes can optimize - * this member function. - */ -//================================================================= - -Int File::size( void ) -{ - Int pos = seek( 0, CURRENT ); - Int size = seek( 0, END ); - - seek( pos, START ); - - return size < 0 ? 0 : size; -} - -//============================================================================ -// File::position -//============================================================================ - -Int File::position( void ) -{ - return seek(0, CURRENT); -} - -//================================================================= -// File::setName -//================================================================= - -void File::setName( const Char *name ) -{ - strncpy( m_name, name, sizeof( m_name )); - m_name[sizeof(m_name)-1] = 0; - -} - -//================================================================= -// File::getName -//================================================================= - -Bool File::getName( Char *buffer, Int max ) -{ - if( buffer && max > 0 && (strlen( m_name ) < (UnsignedInt) max)) - { - strcpy( buffer, m_name ); - return TRUE; - } - - return FALSE; -} - -//============================================================================ -// File::printf -//============================================================================ - -Bool File::printf ( const Char *format, ...) -{ - Char buffer[10*1024]; - Int len; - - if ( ! (m_access & TEXT ) ) - { - return FALSE; - } - - va_list args; - va_start( args, format ); /* Initialize variable arguments. */ - len = vsprintf( buffer, format, args ); - va_end( args ); - - if ( len >= sizeof(buffer) ) - { - // Big Problem - assert( FALSE ); - return FALSE; - } - - return (write ( buffer, len ) == len); -} - diff --git a/Generals/Code/Tools/Autorun/WSYS_FileSystem.cpp b/Generals/Code/Tools/Autorun/WSYS_FileSystem.cpp deleted file mode 100644 index cd261f60d8..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_FileSystem.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: IO_FileSystem.cpp -// -// Created: 4/23/01 -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include "WSYS_FileSystem.h" - -#include "WSYS_StdFileSystem.h" - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - -//=============================== -// TheFileSystem -//=============================== -/** - * This is the FileSystem's singleton class. All file access - * should be through TheFileSystem, unless code needs to use an explicit - * File or FileSystem derivative. - * - * Using TheFileSystem->open and File exclusively for file access, particularly - * in library or modular code, allows applications to transparently implement - * file access as they see fit. This is particularly important for code that - * needs to be shared between applications, such as games and tools. - */ -//=============================== - -FileSystem *TheFileSystem = NULL; - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - - diff --git a/Generals/Code/Tools/Autorun/WSYS_FileSystem.h b/Generals/Code/Tools/Autorun/WSYS_FileSystem.h deleted file mode 100644 index 6358c9c17d..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_FileSystem.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//----------------------------------------------------------------------------= -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: wsys/FileSystem.h -// -// Created: -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef __WSYS_FILESYSTEM_H -#define __WSYS_FILESYSTEM_H - - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#ifndef __WSYS_FILE_H -#include "WSYS_file.h" -#endif - - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// FileSystem -//=============================== -/** - * FileSystem is an interface class for creating specific FileSystem objects. - * - * A FileSystem object's implemenation decides what derivative of File object needs to be - * created when FileSystem::Open() gets called. - */ -//=============================== - -class FileSystem -{ - protected: - - public: - - virtual ~FileSystem() {}; - virtual File* open( const Char *filename, Int access = 0 ) = NULL ; ///< opens a File interface to the specified file - - -}; - -extern FileSystem* TheFileSystem; - - - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - - -#endif // __WSYS_FILESYSTEM_H diff --git a/Generals/Code/Tools/Autorun/WSYS_RAMFile.cpp b/Generals/Code/Tools/Autorun/WSYS_RAMFile.cpp deleted file mode 100644 index 5a0ffaaee0..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_RAMFile.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: WSYS_RAMFile.cpp -// -// Created: 11/08/01 -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include -#include -#include -#include -#include - -#include "WSYS_FileSystem.h" -#include "WSYS_RAMFile.h" - - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - -//================================================================= -// RAMFile::RAMFile -//================================================================= - -RAMFile::RAMFile() -: m_size(0), - m_data(NULL) -{ - -} - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - - -//================================================================= -// RAMFile::~RAMFile -//================================================================= - -RAMFile::~RAMFile() -{ - delete [] m_data; - - File::close(); - -} - -//================================================================= -// RAMFile::open -//================================================================= -/** - * This function opens a file using the standard C open() call. Access flags - * are mapped to the appropriate open flags. Returns true if file was opened - * successfully. - */ -//================================================================= - -Bool RAMFile::open( const Char *filename, Int access ) -{ - File *file = TheFileSystem->open( filename, access ); - - if ( file == NULL ) - { - return FALSE; - } - - Bool result = open( file ); - - file->close(); - - return result; - - return TRUE; -} - -//============================================================================ -// RAMFile::open -//============================================================================ - -Bool RAMFile::open( File *file ) -{ - if ( file == NULL ) - { - return NULL; - } - - Int access = file->getAccess(); - - if ( !File::open( file->getName(), access )) - { - return FALSE; - } - - // read whole file in to memory - m_size = file->size(); - m_data = new char [ m_size ]; - - if ( m_data == NULL ) - { - return FALSE; - } - - m_size = file->read( m_data, m_size ); - - if ( m_size < 0 ) - { - delete [] m_data; - m_data = NULL; - return FALSE; - } - - m_pos = 0; - - return TRUE; -} - -//================================================================= -// RAMFile::close -//================================================================= -/** - * Closes the current file if it is open. - * Must call RAMFile::close() for each successful RAMFile::open() call. - */ -//================================================================= - -void RAMFile::close( void ) -{ - if ( m_data ) - { - delete [] m_data; - m_data = NULL; - } - - File::close(); -} - -//================================================================= -// RAMFile::read -//================================================================= - -Int RAMFile::read( void *buffer, Int bytes ) -{ - if( m_data == NULL ) - { - return -1; - } - - Int bytesLeft = m_size - m_pos ; - - if ( bytes > bytesLeft ) - { - bytes = bytesLeft; - } - - if ( bytes > 0 ) - { - memcpy ( buffer, &m_data[m_pos], bytes ); - } - else - { - bytes = 0; - } - - m_pos += bytes; - - return bytes; -} - -//================================================================= -// RAMFile::write -//================================================================= - -Int RAMFile::write( void *buffer, Int bytes ) -{ - return -1; -} - -//================================================================= -// RAMFile::seek -//================================================================= - -Int RAMFile::seek( Int pos, seekMode mode) -{ - Int newPos; - - switch( mode ) - { - case START: - newPos = pos; - break; - case CURRENT: - newPos = m_pos + pos; - break; - case END: - newPos = m_size - pos - 1; - break; - default: - // bad seek mode - return -1; - } - - if ( newPos < 0 ) - { - newPos = 0; - } - else if ( newPos > m_size - 1 ) - { - newPos = m_size - 1; - } - - m_pos = newPos; - - return m_pos; - -} - diff --git a/Generals/Code/Tools/Autorun/WSYS_RAMFile.h b/Generals/Code/Tools/Autorun/WSYS_RAMFile.h deleted file mode 100644 index 8b7040e6e9..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_RAMFile.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//----------------------------------------------------------------------------= -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: wsys/RAMFile.h -// -// Created: 11/08/01 -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef __WSYS_RAMFILE_H -#define __WSYS_RAMFILE_H - - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include "WSYS_file.h" - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// RAMFile -//=============================== -/** - * File abstraction for standard C file operators: open, close, lseek, read, write - */ -//=============================== - -class RAMFile : public File -{ - protected: - - Char *m_data; ///< File data in memory - Int m_pos; ///< current read position - Int m_size; ///< size of file in memory - - public: - - RAMFile(); - virtual ~RAMFile(); - - - virtual Bool open( const Char *filename, Int access = 0 ); ///< Open a file for access - virtual void close( void ); ///< Close the file - virtual Int read( void *buffer, Int bytes ); ///< Read the specified number of bytes in to buffer: See File::read - virtual Int write( void *buffer, Int bytes ); ///< Write the specified number of bytes from the buffer: See File::write - virtual Int seek( Int new_pos, seekMode mode = CURRENT ); ///< Set file position: See File::seek - - Bool open( File *file ); ///< Open file for fast RAM access -}; - - - - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - -#endif // __WSYS_RAMFILE_H diff --git a/Generals/Code/Tools/Autorun/WSYS_StdFile.cpp b/Generals/Code/Tools/Autorun/WSYS_StdFile.cpp deleted file mode 100644 index 9be2ae0e5e..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_StdFile.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO_ -// -// File name: IO_StdFile.cpp -// -// Created: 4/23/01 -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include -#include -#include -#include -#include - -#include "WSYS_StdFile.h" - - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - -//================================================================= -// StdFile::StdFile -//================================================================= - -StdFile::StdFile() -: m_handle(-1) -{ - -} - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - - -//================================================================= -// StdFile::~StdFile -//================================================================= - -StdFile::~StdFile() -{ - if( m_handle != -1 ) - { - _close( m_handle ); - m_handle = -1; - } - - File::close(); - -} - -//================================================================= -// StdFile::open -//================================================================= -/** - * This function opens a file using the standard C open() call. Access flags - * are mapped to the appropriate open flags. Returns true if file was opened - * successfully. - */ -//================================================================= - -Bool StdFile::open( const Char *filename, Int access ) -{ - if( !File::open( filename, access) ) - { - return FALSE; - } - - /* here we translate WSYS file access to the std C equivalent */ - - int flags = 0; - - if(m_access & CREATE) flags |= _O_CREAT; - if(m_access & TRUNCATE) flags |= _O_TRUNC; - if(m_access & APPEND) flags |= _O_APPEND; - if(m_access & TEXT) flags |= _O_TEXT; - if(m_access & BINARY) flags |= _O_BINARY; - - if((m_access & READWRITE )== READWRITE ) - { - flags |= _O_RDWR; - } - else if(m_access & WRITE) - { - flags |= _O_WRONLY; - } - else - flags |= _O_RDONLY; - - m_handle = _open( filename, flags , _S_IREAD | _S_IWRITE); - - if( m_handle == -1 ) - { - goto error; - } - - if ( m_access & APPEND ) - { - if ( seek ( 0, END ) < 0 ) - { - goto error; - } - } - - return TRUE; - -error: - - close(); - - return FALSE; -} - -//================================================================= -// StdFile::close -//================================================================= -/** - * Closes the current file if it is open. - * Must call StdFile::close() for each successful StdFile::open() call. - */ -//================================================================= - -void StdFile::close( void ) -{ - File::close(); -} - -//================================================================= -// StdFile::read -//================================================================= - -Int StdFile::read( void *buffer, Int bytes ) -{ - if( !m_open || !buffer ) - { - return -1; - } - - return _read( m_handle, buffer, bytes ); -} - -//================================================================= -// StdFile::write -//================================================================= - -Int StdFile::write( void *buffer, Int bytes ) -{ - - if( !m_open || !buffer ) - { - return -1; - } - - return _write( m_handle, buffer, bytes ); - -} - -//================================================================= -// StdFile::seek -//================================================================= - -Int StdFile::seek( Int pos, seekMode mode) -{ - int lmode; - - switch( mode ) - { - case START: - lmode = SEEK_SET; - break; - case CURRENT: - lmode = SEEK_CUR; - break; - case END: - lmode = SEEK_END; - break; - default: - // bad seek mode - return -1; - } - - return _lseek( m_handle, pos, lmode ); - -} - diff --git a/Generals/Code/Tools/Autorun/WSYS_StdFile.h b/Generals/Code/Tools/Autorun/WSYS_StdFile.h deleted file mode 100644 index b212cae9c9..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_StdFile.h +++ /dev/null @@ -1,97 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//----------------------------------------------------------------------------= -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: wsys/StdFile.h -// -// Created: 4/23/01 -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef __WSYS_STDFILE_H -#define __WSYS_STDFILE_H - - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include "WSYS_file.h" - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// StdFile -//=============================== -/** - * File abstraction for standard C file operators: open, close, lseek, read, write - */ -//=============================== - -class StdFile : public File -{ - protected: - - int m_handle; ///< Std C file handle - - public: - - StdFile(); - virtual ~StdFile(); - - - virtual Bool open( const Char *filename, Int access = 0 ); ///< Open a fioe for access - virtual void close( void ); ///< Close the file - virtual Int read( void *buffer, Int bytes ); ///< Read the specified number of bytes in to buffer: See File::read - virtual Int write( void *buffer, Int bytes ); ///< Write the specified number of bytes from the buffer: See File::write - virtual Int seek( Int new_pos, seekMode mode = CURRENT ); ///< Set file position: See File::seek - -}; - - - - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - -#endif // __WSYS_STDFILE_H diff --git a/Generals/Code/Tools/Autorun/WSYS_StdFileSystem.cpp b/Generals/Code/Tools/Autorun/WSYS_StdFileSystem.cpp deleted file mode 100644 index 47272a5d6f..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_StdFileSystem.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: IO_StdFileSystem.cpp -// -// Created: 4/23/01 -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include "WSYS_StdFileSystem.h" -#include "WSYS_StdFile.h" - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - -//================================================================= -// StdFileSystem::~StdFileSystem -//================================================================= - -StdFileSystem::~StdFileSystem() -{ - -} - -//================================================================= -// StdFileSystem::open -//================================================================= -/** - * This simply creates a StdFile object and calls its open function. - */ -//================================================================= - -File* StdFileSystem::open( const Char *filename, Int access ) -{ - StdFile *file = new StdFile(); - - if( file->open( filename, access )) - { - file->deleteOnClose(); // File object not created by the user so delete it when the user is finished with it - } - else - { - delete file; - file = NULL; - } - - return (File*) file; -} \ No newline at end of file diff --git a/Generals/Code/Tools/Autorun/WSYS_StdFileSystem.h b/Generals/Code/Tools/Autorun/WSYS_StdFileSystem.h deleted file mode 100644 index f1e30ea0aa..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_StdFileSystem.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//----------------------------------------------------------------------------= -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: wsys/StdFileSystem.h -// -// Created: -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef __WSYS_STDFILESYSTEM_H -#define __WSYS_STDFILESYSTEM_H - - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#ifndef __WSYS_FILE_H -#include "WSYS_file.h" -#endif - -#ifndef __WSYS_FILESYSTEM_H -#include "WSYS_FileSystem.h" -#endif - - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// StdFileSystem -//=============================== -/** - * FileSystem that maps directly to StdFile files. - */ -//=============================== - -class StdFileSystem : public FileSystem -{ - - public: - - virtual ~StdFileSystem(); - virtual File* open( const Char *filename, Int access = 0 ); ///< Creates a StdFile object and opens the file with it: See FileSystem::open - - -}; - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - - -#endif // __WSYS_STDFILESYSTEM_H diff --git a/Generals/Code/Tools/Autorun/WSYS_file.h b/Generals/Code/Tools/Autorun/WSYS_file.h deleted file mode 100644 index af93beefe0..0000000000 --- a/Generals/Code/Tools/Autorun/WSYS_file.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//----------------------------------------------------------------------------= -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright(C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: WSYS Library -// -// Module: IO -// -// File name: wsys/File.h -// -// Created: 4/23/01 -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef __WSYS_FILE_H -#define __WSYS_FILE_H - - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - -#include "Lib/BaseType.h" - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -#define IO_MAX_PATH (2*1024) ///< Maximum allowable path legnth - -//=============================== -// File -//=============================== -/** - * File is an interface class for basic file operations. - * - * All code should use the File class and not its derivatives, unless - * absolutely necessary. Also FS::Open should be used to create File objects and open files. - */ -//=============================== - -class File -{ - friend class FileSystem; - - public: - - enum access - { - NONE = 0x00000000, - READ = 0x00000001, ///< Access file for reading - WRITE = 0x00000002, ///< Access file for writing - APPEND = 0x00000004, ///< Seek to end of file on open - CREATE = 0x00000008, ///< Create file if it does not exist - TRUNCATE = 0x00000010, ///< Delete all data in file when opened - TEXT = 0x00000020, ///< Access file as text data - BINARY = 0x00000040, ///< Access file as binary data - READWRITE = (READ | WRITE), - NEW = 0x00000080 ///< Only create file if it does not exist - }; - - enum seekMode - { - START, ///< Seek position is relative to start of file - CURRENT, ///< Seek position is relative to current file position - END ///< Seek position is relative from the end of the file - }; - - protected: - - Char m_name[IO_MAX_PATH+1]; ///< Stores file name - Bool m_open; ///< Has the file been opened - Bool m_deleteOnClose; ///< delete File object on close() - Int m_access; ///< How the file was opened - - - File(); ///< This class can only used as a base class - virtual ~File(); - - public: - - - - virtual Bool open( const Char *filename, Int access = 0 ); ///< Open a file for access - virtual void close( void ); ///< Close the file !!! File object no longer valid after this call !!! - - virtual Int read( void *buffer, Int bytes ) = NULL ; /**< Read the specified number of bytes from the file in to the - * memory pointed at by buffer. Returns the number of bytes read. - * Returns -1 if an error occured. - */ - virtual Int write( void *buffer, Int bytes ) = NULL ; /**< Write the specified number of bytes from the - * memory pointed at by buffer to the file. Returns the number of bytes written. - * Returns -1 if an error occured. - */ - virtual Int seek( Int bytes, seekMode mode = CURRENT ) = NULL; /**< Sets the file position of the next read/write operation. Returns the new file - * position as the number of bytes from the start of the file. - * Returns -1 if an error occured. - * - * seekMode determines how the seek is done: - * - * START : means seek to the specified number of bytes from the start of the file - * CURRENT: means seek the specified the number of bytes from the current file position - * END: means seek the specified number of bytes back from the end of the file - */ - virtual Bool printf ( const Char *format, ...); ///< Prints formated string to text file - virtual Int size( void ); ///< Returns the size of the file - virtual Int position( void ); ///< Returns the current read/write position - - - void setName( const Char *name ); ///< Set the name of the file - Char* getName( void ); ///< Returns a pointer to the name of the file - Bool getName( Char *buffer, Int max ); ///< Copies the name of the file to the buffer - Int getAccess( void ); ///< Returns file's access flags - - void deleteOnClose ( void ); ///< Causes the File object to delete itself when it closes -}; - - - - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - -inline Char* File::getName( void ) { return m_name;}; -inline Int File::getAccess( void ) { return m_access;}; -inline void File::deleteOnClose( void ) { m_deleteOnClose = TRUE;}; - - - -// include FileSystem.h as it will be used alot with File.h -//#include "wsys/FileSystem.h" - - -#endif // __WSYS_FILE_H diff --git a/Generals/Code/Tools/Autorun/WinFix.CPP b/Generals/Code/Tools/Autorun/WinFix.CPP deleted file mode 100644 index b69dbc3b72..0000000000 --- a/Generals/Code/Tools/Autorun/WinFix.CPP +++ /dev/null @@ -1,350 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Renegade Setup/Autorun/WinFix.CPP $* - * * - * $Author:: Maria_l $* - * * - * $Modtime:: 11/15/01 10:44a $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Make_Identifier -- Creates a temporary string identifer. * - * WindowsVersionInfo::WindowsVersionInfo -- Windows Version Info constructor. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#define STRICT -#include -#include -#pragma hdrstop - -//#include -//#include -#include -#include -#include "WinFix.H" -#include "Wnd_File.h" - -/*************************************************************************** -** Windows Version Info global object. -*/ -WindowsVersionInfo WinVersion; - - - -/*********************************************************************************************** - * WindowsVersionInfo::WindowsVersionInfo -- Windows Version Info constructor. * - * * - * This routine will examine the system to determine the OS, version, and patch level of * - * the current OS. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: Don't try and use this class until after WinMain, because it won't be * - * initialized until all the global objects have been constructed. * - * * - * HISTORY: * - * 04/09/98 jdl : Created. * - *=============================================================================================*/ -WindowsVersionInfo::WindowsVersionInfo(void) : - WindowsVersion(0), - MajorVersionNumber(0), - MinorVersionNumber(0), - RunningOSR2(0), - BuildNumber(0), - IsWin9x(false), - IsWin95(false), - IsWin98(false), - IsWin2000(false), - IsWinNT(false), - IsWinXP(false) -{ - OSVERSIONINFO version_info; - - VersionName[0] = '\0'; - AdditionalInfo[0] = '\0'; - - //-------------------------------------------------------------------------- - // Start recording messages. - //-------------------------------------------------------------------------- - Delete_Msg_File(); - Msg( __LINE__, __FILE__, "----------------------------------------------", NULL ); - Msg( __LINE__, __FILE__, "------------------ Setup -----------------", NULL ); - Msg( __LINE__, __FILE__, "----------------------------------------------", NULL ); - - //-------------------------------------------------------------------------- - // Get the version info from the OS. - // - // typedef struct _OSVERSIONINFO{ - // DWORD dwOSVersionInfoSize; - // DWORD dwMajorVersion; - // DWORD dwMinorVersion; - // DWORD dwBuildNumber; - // DWORD dwPlatformId; - // TCHAR szCSDVersion[ 128 ]; - // } OSVERSIONINFO; - // - // typedef struct _OSVERSIONINFOEX { - // DWORD dwOSVersionInfoSize; - // DWORD dwMajorVersion; - // DWORD dwMinorVersion; - // DWORD dwBuildNumber; - // DWORD dwPlatformId; - // TCHAR szCSDVersion[ 128 ]; - // WORD wServicePackMajor; - // WORD wServicePackMinor; - // WORD wSuiteMask; - // BYTE wProductType; - // BYTE wReserved; - // } OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX; - //-------------------------------------------------------------------------- - ZeroMemory( &version_info, sizeof( version_info )); - version_info.dwOSVersionInfoSize = sizeof( version_info ); - - int result = GetVersionEx( &version_info ); - assert( result != 0 ); - - //-------------------------------------------------------------------------- - // Save the major/minor version numbers - //-------------------------------------------------------------------------- - MajorVersionNumber = (int)version_info.dwMajorVersion; - MinorVersionNumber = (int)version_info.dwMinorVersion; - WindowsVersion = ( MajorVersionNumber * 100 ) + MinorVersionNumber; - - //-------------------------------------------------------------------------- - // Save the build number - //-------------------------------------------------------------------------- - BuildNumber = (int)version_info.dwBuildNumber; - - //-------------------------------------------------------------------------- - // Check for Win9x - //-------------------------------------------------------------------------- - if ( version_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { - - IsWin9x = true; - - if ( MajorVersionNumber == 4 && MinorVersionNumber == 0 ) { - IsWin95 = true; - } - if (( MajorVersionNumber > 4 ) || (( MajorVersionNumber == 4 ) && ( MinorVersionNumber > 0 ))) { - IsWin98 = true; - } - - if ( LOWORD( version_info.dwPlatformId ) > 1000 ) { - RunningOSR2 = TRUE; - } - } - - //-------------------------------------------------------------------------- - // Check for WinNT - //-------------------------------------------------------------------------- - if ( version_info.dwPlatformId == VER_PLATFORM_WIN32_NT ) { - - IsWinNT = true; - - if (( MajorVersionNumber >= 5 ) && ( MinorVersionNumber >= 1 )) { - IsWinXP = true; -// if ( version_info.wSuiteMask == VER_SUITE_PERSONAL ) { -// } - } else if (( MajorVersionNumber == 5 ) && ( MinorVersionNumber == 0 )) { - IsWin2000 = true; - } - -// if( bOsVersionInfoEx ) -// { -// if ( osvi.wProductType == VER_NT_WORKSTATION ) -// printf ( "Professional " ); -// -// if ( osvi.wProductType == VER_NT_SERVER ) -// printf ( "Server " ); - -// } else { - - #if( _DEBUG ) - HKEY hKey; - char szProductType[80]; - DWORD dwBufLen; - - RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey ); - RegQueryValueEx( hKey, "ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen); - RegCloseKey( hKey ); - - if ( lstrcmpi( "WINNT", szProductType) == 0 ) - Msg( __LINE__, __FILE__, "WinNT Workstation." ); - if ( lstrcmpi( "SERVERNT", szProductType) == 0 ) - Msg( __LINE__, __FILE__, "WinNT Server." ); - #endif -// } - } - -#ifdef DEV_VERSION - - //-------------------------------------------------------------------------- - // For developmental versions, just use the major & minor version #'s - //-------------------------------------------------------------------------- - sprintf( VersionName, "%x.%x", MajorVersionNumber, MinorVersionNumber ); - -#else - - //-------------------------------------------------------------------------- - // For final versions, trim 0's off the minor version - //-------------------------------------------------------------------------- - unsigned short adjusted_minor; - int i; - - adjusted_minor = MinorVersionNumber; - for (i = 0; i < 4; i++) { - if ((adjusted_minor & 0x000f) != 0) { - break; - } - adjusted_minor >>= 4; - } - sprintf( VersionName, "%x.%x", MajorVersionNumber, adjusted_minor ); - -#endif - - //-------------------------------------------------------------------------- - // Save off the additional version information string - // (used to indicated additional info or patch level, i.e. for NT 4.0 SP3 - // it would contain the string 'Service Pack 3') - //-------------------------------------------------------------------------- - strncpy( AdditionalInfo, version_info.szCSDVersion, sizeof(AdditionalInfo) - 1 ); - AdditionalInfo[sizeof(AdditionalInfo) - 1] = '\x0'; - - //-------------------------------------------------------------------------- - // Send all info found to the debug output file. - //-------------------------------------------------------------------------- -#if ( _DEBUG ) - Msg( __LINE__, __FILE__, "MajorVersionNumber = %d", MajorVersionNumber ); - Msg( __LINE__, __FILE__, "MinorVersionNumber = %d", MinorVersionNumber ); - Msg( __LINE__, __FILE__, "WindowsVersion = %d", WindowsVersion ); - Msg( __LINE__, __FILE__, "BuildNumber = %d", BuildNumber ); - Msg( __LINE__, __FILE__, "IsWin9x = %d", IsWin9x ); - Msg( __LINE__, __FILE__, "IsWin95 = %d", IsWin95 ); - Msg( __LINE__, __FILE__, "IsWin98 = %d", IsWin98 ); - Msg( __LINE__, __FILE__, "IsWin2000 = %d", IsWin2000 ); - Msg( __LINE__, __FILE__, "RunningOSR2 = %d", RunningOSR2 ); - Msg( __LINE__, __FILE__, "IsWinNT = %d", IsWinNT ); - Msg( __LINE__, __FILE__, "AdditionalInfo = %s", AdditionalInfo ); - Msg( __LINE__, __FILE__, "VersionName = %s", VersionName ); -#endif -} - -/*********************************************************************************************** - * WindowsVersionInfo::Version_String -- Get the version number in human readable form * - * * - * INPUT: Nothing * - * * - * OUTPUT: Ptr to string containing version info * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 3/30/99 10:29PM ST : Created * - *=============================================================================================*/ -char *WindowsVersionInfo::Version_String(void) -{ - static char _ver95[] = {"Windows 95 "}; - static char _ver98[] = {"Windows 98 "}; - static char _verNT4[] = {"Windows NT 4 "}; - static char _verNT5[] = {"Windows 2000 "}; - static char _verXP[] = {"Windows XP "}; - static char _unknown[] = {"Unknown "}; - - static char version[256]; - - if (Is_Win95()) { - strcpy (version, _ver95); - } - - if (Is_Win98()) { - strcpy (version, _ver98); - } - - if (Is_WinNT()) { - strcpy (version, _verNT4); - } - - if (Is_WinNT5() || Is_Win_2000()) { - strcpy (version, _verNT5); - } - - if (Is_Win_XP()) { - strcpy (version, _verXP); - } - - strcat (version, AdditionalInfo); - - return (version); -} - -/*************************************************************************** - * WindowsVersionClass::Version_Name -- returns version # as char string * - * * - * INPUT: * - * none. * - * * - * OUTPUT: * - * ptr to name * - * * - * WARNINGS: * - * none. * - * * - * HISTORY: * - * 10/30/1995 BRR : Created. * - *=========================================================================*/ - -char * WindowsVersionInfo::Version_Name(void) -{ - return ( VersionName ); -} - -/**************************************************************************** - * WindowsVersionClass::Meets_Minimum_Version_Requirements * - * * - * INPUT: * - * none. * - * * - * OUTPUT: * - * ptr to name * - * * - * WARNINGS: * - * none. * - * * - * HISTORY: * - * 10/30/1995 BRR : Created. * - *==========================================================================*/ - -bool WindowsVersionInfo::Meets_Minimum_Version_Requirements ( void ) -{ -// return(( !IsWin95 && ( Version() >= 400 ))? true : false ); - return(( Version() >= 400 )? true : false ); -} - - - diff --git a/Generals/Code/Tools/Autorun/WinFix.H b/Generals/Code/Tools/Autorun/WinFix.H deleted file mode 100644 index fc71663a7b..0000000000 --- a/Generals/Code/Tools/Autorun/WinFix.H +++ /dev/null @@ -1,149 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Renegade Setup/Autorun/WinFix.H $* - * * - * $Author:: Maria_l $* - * * - * $Modtime:: 11/07/01 5:57p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * WindowsVersionInfo::Major -- Get the major version of the OS * - * WindowsVersionInfo::Minor -- Get the minor version of the OS * - * WindowsVersionInfo::Build -- Get the build level of the OS * - * WindowsVersionInfo::Info -- Get additional system information * - * WindowsVersionInfo::Is_Win9x -- Determine if we are running on a non-NT system. * - * WindowsVersionInfo::Is_Win95 -- Determine if we are running on a Win95 system. * - * WindowsVersionInfo::Is_Win98 -- Determine if we are running on a Win98 system. * - * WindowsVersionInfo::Is_WinNT -- Determine if we are running on an NT system. * - * WindowsVersionInfo::Is_WinNT5 -- Determine if we are running on an NT 5 system. * - * WindowsVersionInfo::Version -- * - * WindowsVersionInfo::IsOSR2Release -- * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma once - -#ifndef WINFIX_H -#define WINFIX_H - - -/*----------------------------------------------------------------------------- -** Windows Version Information class. This is a global object that is used to -** store information about the specific OS that we are running under. This can -** be used to make special allowances for differences between OS's, such as when -** using the registry, or trying to work around a limitaion of a particular OS -** (their APIs are slightly different...) -**-----------------------------------------------------------------------------*/ -class WindowsVersionInfo -{ - public: - WindowsVersionInfo (void); - ~WindowsVersionInfo (void) {} - - int Major ( void ) const { return( MajorVersionNumber ); } - int Minor ( void ) const { return( MinorVersionNumber ); } - int Build ( void ) const { return( BuildNumber ); } - bool Is_Win9x ( void ) const { return( IsWin9x ); } // Win 9x - bool Is_Win95 ( void ) const { return( IsWin95 ); } // Win 95 - bool Is_Win98 ( void ) const { return( IsWin98 ); } // Win 98 - bool Is_WinNT ( void ) const { return( IsWinNT ); } // Win NT - bool Is_WinNT4 ( void ) const { return( IsWinNT && MajorVersionNumber == 4 ); } // Win NT - bool Is_WinNT5 ( void ) const { return( IsWinNT && MajorVersionNumber == 5 ); } // Win NT - bool Is_Win_2000 ( void ) const { return( IsWin2000 ); } // Win 2000 - bool Is_Win_XP ( void ) const { return( IsWinXP ); } // Win XP - int Version ( void ) const { return( WindowsVersion ); } - int IsOSR2Release ( void ) const { return( RunningOSR2 ); } - const char * Info ( void ) const { return( &AdditionalInfo[0] ); } - char * Version_String ( void ); - char * Version_Name ( void ); - bool Meets_Minimum_Version_Requirements ( void ); - - private: - /*----------------------------------------------------------------------- - ** Major version number; i.e. for 4.10.1721 this would be '4' - */ - int MajorVersionNumber; - - /*----------------------------------------------------------------------- - ** Minor version number; i.e. for 4.10.1721 this would be '10' - */ - int MinorVersionNumber; - - /*----------------------------------------------------------------------- - ** Version number expressed as a DWORD; i.e. for 4.10 this would be '410' - */ - int WindowsVersion; - - /*----------------------------------------------------------------------- - ** Build number; i.e. for 4.10.1721 this would be '1721' - */ - int BuildNumber; - - /*----------------------------------------------------------------------- - ** Is the system running OSR 2 or later release of Windows95. - */ - int RunningOSR2; - - /*----------------------------------------------------------------------- - ** Additional Info; i.e. for NT 4.0 with SP3, this would be - ** the string 'Service Pack 3' - */ - char AdditionalInfo[128]; - - /*----------------------------------------------------------------------- - ** Windows 9x flag; true if running on non-NT system - */ - bool IsWin9x; - bool IsWin95; - bool IsWin98; - - /*----------------------------------------------------------------------- - ** Windows NT flag; true if running on Windows NT system - */ - bool IsWinNT; - - /*----------------------------------------------------------------------- - ** Windows 2000 (Formerly Windows NT 5.0) - ** As you've no doubt heard by now, Windows NT 5.0 has been officially - ** christened "Windows 2000." - */ - bool IsWin2000; - - /*----------------------------------------------------------------------- - ** Windows XP flag; true if running on Windows NT system - */ - bool IsWinXP; - - /*----------------------------------------------------------------------- - ** This array is used for formatting the version # as a string - */ - char VersionName[30]; -}; - -extern WindowsVersionInfo WinVersion; - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Autorun/Wnd_File.h b/Generals/Code/Tools/Autorun/Wnd_File.h deleted file mode 100644 index b8c4ff3666..0000000000 --- a/Generals/Code/Tools/Autorun/Wnd_File.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//**************************************************************************** -// C O N F I D E N T I A L -- W E S T W O O D S T U D I O S -//**************************************************************************** -// -// Project name: Blade Runner CD-ROM Windows 95 -// -// File name: WND_FILE.H -// -// Source code: WND_FILE.CPP -// -// Compatibility: Microsoft Visual C++ 4.0 -// Borland C++ 5.0 -// Watcom C++ 10.6 -// -// Start Date: See comments in version control log -// Last Update: See comments in version control log -// -// Programmer(s): Michael Legg -// Mike Grayford -// James McNeill -// -//**************************************************************************** -#pragma once - -#ifndef WND_FILE_H -#define WND_FILE_H - -//------------------------------------------------------------------------------ -// include files... -//------------------------------------------------------------------------------ - -#include -#include -#include -#include -#include -#include - -#define BOOL int -#define ASSERT(x) assert(x) -#define VERIFY(X) assert(X) - - -//------------------------------------------------------------------------------ -// defines... -//------------------------------------------------------------------------------ - -// -// it's one or the other! -// -#define SUPPORT_STREAMS TRUE // Normally this! -#define SUPPORT_HANDLES FALSE // This is a test! - -#define MODE_READ_ONLY 0 -#define MODE_WRITE_ONLY 1 -#define MODE_READ_AND_WRITE 2 - -#define MODE_WRITE_TRUNCATE MODE_WRITE_ONLY -#define MODE_WRITE_APPEND 3 -#define MODE_WRITE_UPDATE 4 - -#define SEEK_SET 0 -#define SEEK_CUR 1 -#define SEEK_END 2 - -// #define INVALID_FILE_HANDLE -1 -#define INVALID_FILE_HANDLE INVALID_HANDLE_VALUE -#define MAX_PATH_SIZE _MAX_PATH - - -#define STRING_IT(a) #a -#define TOKEN_IT(a) STRING_IT(,##a) -#define MESSAGE(a) message (__FILE__ "(" TOKEN_IT(__LINE__) ") : " a) - -//#pragma MESSAGE("What does it do?") - - - -#ifdef _DEBUG -void __cdecl Msg( int line, const char *file, const char *fmt, ... ); -void __cdecl Msg( int line, const char *filename, const wchar_t *fmt, unsigned int codepage=1252, ... ); -void Delete_Msg_File( void ); -#else -#define Msg -#define Delete_Msg_File() -#endif - - -//------------------------------------------------------------------------------ -// file class definition -//------------------------------------------------------------------------------ - -class StandardFileClass -{ - public: - - // - // public class functions... - // - StandardFileClass(); - ~StandardFileClass(); - bool Open ( const char *file_name, int open_mode ); - bool Close ( void ); - int Read ( void *buffer, unsigned long int bytes_to_read ); - int Write ( void *buffer, unsigned long int bytes_to_write ); - bool Seek ( int distance, int seek_file_position ); - int Tell ( void ); - int Query_Size ( void ); - bool Query_Open ( void ); - char * Query_Name_String ( void ); - int End_Of_File ( void ); - int Flush ( void ); - - #if( SUPPORT_STREAMS ) - FILE *Query_File_Stream_Pointer( void ); - #endif - - private: - - // - // private class functions... - // - void Reset( void ); - // - // private class data... - // - #if( SUPPORT_HANDLES ) - HANDLE File_Handle; - #endif - - #if( SUPPORT_STREAMS ) - //-------------------------------------------------------------------- - // The _stat structure, defined in SYS\STAT.H, includes these fields. - // st_atime Time of last access of file ( time_t ). - // st_ctime Time of creation of file ( time_t ). - // st_dev Drive number of the disk containing the file (same as st_rdev). - // st_rdev Drive number of the disk containing the file (same as st_dev). - // st_mode Bit mask for file-mode information. - // _S_IFDIR bit is set if path specifies a directory; - // _S_IFREG bit is set if path specifies an ordinary file or a device. - // User read/write bits are set according to the file's permission - // mode; user execute bits are set according to the filename extension. - // st_mtime Time of last modification of file. - // st_nlink Always 1 on non-NTFS file systems. - // st_size Size of the file in bytes; a 64-bit integer for _stati64 and _wstati64 - //-------------------------------------------------------------------- - FILE *File_Stream_Ptr; - struct stat File_Statistics; - #endif - - char File_Name[ MAX_PATH_SIZE ]; - bool Currently_Open; -}; - -//------------------------------------------------------------------------------ -// non-class public functions... -//------------------------------------------------------------------------------ - -#if( SUPPORT_HANDLES ) - HANDLE Open_File( char const *file_name, int mode ); - bool Close_File( HANDLE handle ); - int Read_File( HANDLE handle, - void *buffer, - unsigned long int bytes_to_read ); - int Write_File( HANDLE handle, - void const *buffer, - unsigned long int bytes_to_write ); - bool Seek_File( HANDLE handle, - int distance, - int seek_file_location ); - int Tell_File( HANDLE handle ); - int File_Size( HANDLE handle ); - // - // include path in name - // - bool Full_Path_File_Exists( char const *file_name ); - // - // don't include path in name - // - bool HD_File_Exists( char const *file_name ); - bool CD_File_Exists( char const *file_name ); - // bool Find_File( char const *file_name ); -#endif - -#if( SUPPORT_STREAMS ) - // - // include path in name - // - bool Full_Path_File_Exists( char const *file_name ); - // - // don't include path in name - // - bool HD_File_Exists( char const *file_name ); - bool CD_File_Exists( char const *file_name ); - // bool Find_File( char const *file_name ); -#endif - -#endif // WND_FILE_H diff --git a/Generals/Code/Tools/Autorun/Wnd_file.cpp b/Generals/Code/Tools/Autorun/Wnd_file.cpp deleted file mode 100644 index 006fc5c577..0000000000 --- a/Generals/Code/Tools/Autorun/Wnd_file.cpp +++ /dev/null @@ -1,1625 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//***************************************************************************** -// C O N F I D E N T I A L -- W E S T W O O D S T U D I O S -//***************************************************************************** -// -// Project name: Blade Runner CD-ROM Windows 95 -// -// File name: WND_FILE.CPP -// -// Functions: WND_FILE.H -// -// Compatibility: Microsoft Visual C++ 4.0 -// Borland C++ 5.0 -// Watcom C++ 10.6 -// -// Start Date: See comments in version control log -// Last Update: See comments in version control log -// -// Programmer(s): Michael Legg -// Mike Grayford -// -//***************************************************************************** - -//----------------------------------------------------------------------------- -// include files... -//----------------------------------------------------------------------------- -#include "windows.h" -#include -#include -#include "Wnd_File.h" -#include "WinFix.H" -//#include "autorun.h" - - -//----------------------------------------------------------------------------- -// private defines... -//----------------------------------------------------------------------------- -#define DEBUG_FILE "DebugAutorun.txt" - -// TC? This is non-Westwood Library 32-bit file access! -#define MAX_FILES_OPEN_AT_A_TIME 25 // includes .MIX files - -//----------------------------------------------------------------------------- -// private data... -//----------------------------------------------------------------------------- -char HD_Path [ MAX_PATH ] = { '\0' }; -char CD_Path [ MAX_PATH ] = { '\0' }; -char DebugFile [ MAX_PATH ] = { '\0' }; - -// HANDLE Windows_File_Handles[ MAX_FILES_OPEN_AT_A_TIME ]; -// #if( SUPPORT_STREAMS ) -// FILE *Windows_File_Streams[ MAX_FILES_OPEN_AT_A_TIME ]; -// #endif - - -//----------------------------------------------------------------------------- -// non-class private functions in this module... -//----------------------------------------------------------------------------- -// int Get_Internal_File_Handle( void ); -// #if( SUPPORT_STREAMS ) -// FILE *Get_Internal_File_Stream( void ); -// #endif - - -//----------------------------------------------------------------------------- -// public file class functions... -//----------------------------------------------------------------------------- -#if(0) -#ifndef _DEBUG -void __cdecl Msg( int, char *, char *, ... ) { }; // line, file, fmt -void Delete_Msg_File ( void ) { }; -#endif -#endif - - -#ifdef _DEBUG - -/**************************************************************************** - * MSG -- Write Message to Debug file with line and filename. * - * * - * INPUT: int line -- line where message originated. * - * char *filename -- file where message originated. * - * char *fmt -- variable argument list. * - * * - * OUTPUT: none. * - * * - * WARNINGS: none. * - * * - * HISTORY: * - * 08/19/1998 MML : Created. * - *==========================================================================*/ - -void __cdecl Msg( int line, const char *filename, const char *fmt, ... ) -{ - char szBuffer1[ MAX_PATH * 3 ]; - char szBuffer2[ MAX_PATH * 2 ]; - char szFile[ MAX_PATH ]; - va_list va; - DWORD nBytes; - StandardFileClass file; - - //---------------------------------------------------------------------- - // Variable Arguments - //---------------------------------------------------------------------- - va_start( va, fmt ); - - if ( DebugFile[0] == '\0' ) { - return; - } - if ( filename[0] == '\0' ) { - return; - } - - //---------------------------------------------------------------------- - // Make filename. - //---------------------------------------------------------------------- - const char *temp = strrchr( filename, '\\' ); - if ( temp != NULL || temp[0] != '\0' ) { - temp++; - strcpy( szFile, temp ); - } - - //---------------------------------------------------------------------- - // format message with header - //---------------------------------------------------------------------- - memset( szBuffer1, '\0', MAX_PATH * 3 ); - memset( szBuffer2, '\0', MAX_PATH * 2 ); - wvsprintf( szBuffer2, fmt, va ); - wsprintf( szBuffer1, "%4d %14s %s\n", line, szFile, szBuffer2 ); - - //---------------------------------------------------------------------- - // Open debug file and write to it. - //---------------------------------------------------------------------- - file.Open( DebugFile, MODE_WRITE_APPEND ); - if ( file.Query_Open( )) { - - int length = strlen( szBuffer1 ); - nBytes = file.Write( szBuffer1, length ); - if ( nBytes != strlen( szBuffer1 )) { - } - file.Close(); - } - - //---------------------------------------------------------------------- - // To the debugger unless we need to be quiet - //---------------------------------------------------------------------- - OutputDebugString( szBuffer1 ); - -} /* Msg */ - - -/**************************************************************************** - * MSG -- Write Message to Debug file with line and filename. * - * * - * INPUT: int line -- line where message originated. * - * wchar_t *filename -- file where message originated. * - * wchar_t *fmt -- variable argument list. * - * * - * OUTPUT: none. * - * * - * WARNINGS: none. * - * * - * HISTORY: * - * 08/19/1998 MML : Created. * - *==========================================================================*/ - -void __cdecl Msg( int line, const char *filename, const wchar_t *fmt, UINT codepage, ... ) -{ - wchar_t szBuffer1[ MAX_PATH * 3 ]; - wchar_t szBuffer2[ MAX_PATH * 3 ]; - char szBuffer3[ MAX_PATH * 3 ]; - wchar_t szFile[ MAX_PATH ]; - wchar_t szArgs[ MAX_PATH ]; - va_list va; - int length; - DWORD nBytes; - StandardFileClass file; - - //---------------------------------------------------------------------- - // Variable Arguments - //---------------------------------------------------------------------- -// va_start( va, fmt ); - va_start( va, codepage ); - memset( szArgs, '\0', MAX_PATH ); - memset( szFile, '\0', MAX_PATH ); - memset( szBuffer1, '\0', MAX_PATH * 3 ); - memset( szBuffer2, '\0', MAX_PATH * 2 ); - - if ( DebugFile == NULL ) { - return; - } - if ( filename == NULL ) { - return; - } - - //---------------------------------------------------------------------- - // Make filename. - //---------------------------------------------------------------------- - const char *temp = strrchr( filename, '\\' ); - if ( temp != NULL || temp[0] != '\0' ) { - temp++; - length = strlen( temp ); - mbstowcs( szFile, temp, length ); - } - - //---------------------------------------------------------------------- - // format message with header - //---------------------------------------------------------------------- - vswprintf( szBuffer2, fmt, va ); - swprintf( szBuffer1, L"%4d %14s %s\n", line, szFile, szBuffer2 ); - - //---------------------------------------------------------------------- - // Open debug file and write to it. - //---------------------------------------------------------------------- - file.Open( DebugFile, MODE_WRITE_APPEND ); - - if ( file.Query_Open( )) { - - //--------------------------------------------------------------------- - // Identifier Meaning - // 932 Japan - // 949 Korean - // 950 Chinese (Taiwan; Hong Kong SAR, PRC) - // 1252 Windows 3.1 Latin 1 (US, Western Europe) - //--------------------------------------------------------------------- - WideCharToMultiByte( codepage, 0, szBuffer1, -1, szBuffer3, MAX_PATH*3, NULL, NULL ); - - length = strlen( szBuffer3 ); - nBytes = file.Write( szBuffer3, length ); - if ( nBytes != strlen( szBuffer3 )) { - } - file.Close(); - } - - //---------------------------------------------------------------------- - // To the debugger unless we need to be quiet - //---------------------------------------------------------------------- - OutputDebugString( szBuffer3 ); - -} /* Msg */ - - -/*************************************************************************** - * DELETE_MSG_FILE -- Delete the Debug file. * - * * - * INPUT: none. * - * * - * OUTPUT: none. * - * * - * WARNINGS: none. * - * * - * HISTORY: * - * 08/19/1998 MML : Created. * - *=========================================================================*/ - -//---------------------------------------------------------------------- -// Delete_Msg_File -//---------------------------------------------------------------------- - -void Delete_Msg_File ( void ) -{ - DWORD nBytes; - char buff [ 300 ]; - char date [ 50 ]; - char time [ 30 ]; - StandardFileClass file; - - //---------------------------------------------------------------------- - // Make path to debug file. - //---------------------------------------------------------------------- -// strcat( strcpy( DebugFile, ".\\" ), DEBUG_FILE ); - GetWindowsDirectory( DebugFile, MAX_PATH ); - if ( DebugFile[ strlen( DebugFile )-1 ] != '\\' ) { - strcat( DebugFile, "\\" ); - } - strcat( DebugFile, DEBUG_FILE ); - - //-------------------------------------------------------------------------- - // Delete previous file. - //-------------------------------------------------------------------------- - DeleteFile( DebugFile ); - - //-------------------------------------------------------------------------- - // Create/Open new file. - //-------------------------------------------------------------------------- - file.Open( DebugFile, MODE_WRITE_TRUNCATE ); - if ( file.Query_Open( )) { - - wsprintf( buff, "===========================================================\r\n" ); - nBytes = file.Write( buff, strlen( buff )); - - GetDateFormat( LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, date, 50 ); -// GetTimeFormat( LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL, NULL, time, 30 ); - GetTimeFormat( LOCALE_USER_DEFAULT, NULL, NULL, "hh':'mm':'ss tt", time, 30 ); - wsprintf( buff, "SETUP: File: %s Date: %s Time: %s.\r\n", DebugFile, date, time ); - nBytes = file.Write( buff, strlen( buff )); - - wsprintf( buff, "===========================================================\r\n\r\n" ); - nBytes = file.Write( buff, strlen( buff )); - - file.Close(); - } -} - -#endif - - -//------------------------------------------------------------------------------ -// StandardFileClass::StandardFileClass -//------------------------------------------------------------------------------ - -StandardFileClass::StandardFileClass( void ) -{ - // - // reset all internal data - // - Reset(); -} - -//------------------------------------------------------------------------------ -// StandardFileClass::~StandardFileClass -//------------------------------------------------------------------------------ - -StandardFileClass::~StandardFileClass( void ) -{ - // - // make sure this file got shut down before we destruct - // - #if( SUPPORT_HANDLES ) - ASSERT( File_Handle == INVALID_FILE_HANDLE ); - #endif - #if( SUPPORT_STREAMS ) - ASSERT( File_Stream_Ptr == NULL ); - #endif - ASSERT( Currently_Open == FALSE ); - - // - // reset all internal data - // - Reset(); -} - -//------------------------------------------------------------------------------ -// bool StandardFileClass::Open -//------------------------------------------------------------------------------ - -bool StandardFileClass::Open( const char *no_path_file_name, int open_mode ) -{ - int test; - const char *attributes; - char pathed_file_name[ MAX_PATH_SIZE ]; - - // - // debug checks... - // - ASSERT( no_path_file_name != NULL ); - ASSERT( Currently_Open == FALSE ); - ASSERT( strlen( no_path_file_name ) < MAX_PATH ); - ASSERT( open_mode == MODE_READ_ONLY || - open_mode == MODE_WRITE_ONLY || - open_mode == MODE_READ_AND_WRITE || - open_mode == MODE_WRITE_TRUNCATE || - open_mode == MODE_WRITE_APPEND ); - - // - // open the file - // - #if( SUPPORT_HANDLES ) - - ASSERT( File_Handle == INVALID_FILE_HANDLE ); - - // - // try HD open - // - strcpy( pathed_file_name, HD_Path ); - strcat( pathed_file_name, no_path_file_name ); - File_Handle = Open_File( pathed_file_name, open_mode ); - - // - // if not success with HD open, try CD - // - if ( File_Handle == INVALID_FILE_HANDLE ) { - - // - // try CD open - // - strcpy( pathed_file_name, CD_Path ); - strcat( pathed_file_name, no_path_file_name ); - File_Handle = Open_File( pathed_file_name, open_mode ); - } - - // - // not successful HD or CD open? - // - if ( File_Handle == INVALID_FILE_HANDLE ) { - ASSERT( FALSE ); - return( FALSE ); - } - - #endif - - #if( SUPPORT_STREAMS ) - - ASSERT( File_Stream_Ptr == NULL ); - - // - // "r" - open existing file for reading. - // "w" - create new file, or truncate existing one, for output. - // "a" - create new file, or append to if existing, for output. - // "r+" - open existing file for read and write, starting at beginning of file. File must exist. - // "w+" - create new file, or truncate if existing, for read and write. - // "a+" - create new file, or append to existing, for read and write. - // - // add "b" to any string for binary instead of text - // - if ( open_mode == MODE_READ_ONLY ) { - // - // open existing file for input (binary) - // - attributes = "rb"; - } - else if ( open_mode == MODE_WRITE_ONLY || open_mode == MODE_WRITE_TRUNCATE ) { - // - // create new or open/truncate existing file for output (binary) - // - attributes = "wb"; - } - else if ( open_mode == MODE_READ_AND_WRITE ) { - // - // open existing for for read and write, starting at beginning of file - // - attributes = "r+b"; - } - else if ( open_mode == MODE_WRITE_UPDATE ) { - // - // Create a new file for update (reading and writing). If a file by - // that name already exists, it will be overwritten. - // - attributes = "w+b"; - } - else if ( open_mode == MODE_WRITE_APPEND ) { - // - // append to existing file for output (binary) - // - attributes = "a"; - } - else { - ASSERT( FALSE ); - } - - // - // try HD open - // - strcpy( pathed_file_name, HD_Path ); - strcat( pathed_file_name, no_path_file_name ); - File_Stream_Ptr = fopen( pathed_file_name, attributes ); - - // - // if not success with HD open, try CD - // - if ( File_Stream_Ptr == NULL ) { - - // - // try CD open - // - strcpy( pathed_file_name, CD_Path ); - strcat( pathed_file_name, no_path_file_name ); - File_Stream_Ptr = fopen( pathed_file_name, attributes ); - } - - // - // not successful? - // - if ( File_Stream_Ptr == NULL ) { - return( FALSE ); - } - - // - // get file stats - // - test = stat( pathed_file_name, &File_Statistics ); - ASSERT( test == 0 ); - - #endif - - // - // successful, set name and open status - // - strncpy( File_Name, pathed_file_name, MAX_PATH_SIZE-1 ); - Currently_Open = TRUE; - - // - // success! - // - return( TRUE ); -} - -//------------------------------------------------------------------------------ -// bool StandardFileClass::Close -//------------------------------------------------------------------------------ - -bool StandardFileClass::Close( void ) -{ - int status; - - #if( SUPPORT_HANDLES ) - bool success; - #endif - - // - // debug checks... - // - ASSERT( Currently_Open == TRUE ); - - #if( SUPPORT_HANDLES ) - - ASSERT( File_Handle > INVALID_FILE_HANDLE ); - - // - // error? - // - if ( File_Handle == INVALID_FILE_HANDLE || Currently_Open == FALSE ) { - // - // no success - // - ASSERT( FALSE ); - return( FALSE ); - } - - // - // close file - // - // status = Close_File( File_Handle ); - success = Close_File( File_Handle ); - ASSERT( success == TRUE ); - - // - // reset file data - // - File_Handle = INVALID_FILE_HANDLE; - Currently_Open = FALSE; - - // - // error on close? - // - // if ( status == INVALID_FILE_HANDLE ) { - // return( FALSE ); - // } - return( success ); - - #endif - - #if( SUPPORT_STREAMS ) - - ASSERT( File_Stream_Ptr != NULL ); - - // - // error? - // - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - // - // no success - // - ASSERT( FALSE ); - return( FALSE ); - } - - // - // close file - // - status = fclose( File_Stream_Ptr ); - ASSERT( status == 0 ); - - // - // reset file data - // - File_Stream_Ptr = NULL; - Currently_Open = FALSE; - - // - // error on close? - // - if ( status != 0 ) { - return( FALSE ); - } - #endif - - // - // success! - // - return( TRUE ); -} - -//------------------------------------------------------------------------------ -// int StandardFileClass::Read -//------------------------------------------------------------------------------ -int StandardFileClass::Read( void *buffer, unsigned long int bytes_to_read ) -{ - int bytes_read; - int items_read; - - // - // debug checks ( Fails if condition is FALSE ). - // - ASSERT( buffer != NULL ); - ASSERT( bytes_to_read > 0 ); - ASSERT( Currently_Open == TRUE ); - -#if( SUPPORT_HANDLES ) - - ASSERT( File_Handle != INVALID_FILE_HANDLE ); - // - // error? - // - if ( File_Handle == INVALID_FILE_HANDLE || Currently_Open == FALSE ) { - // - // nothing read - // - return( 0 ); - } - - // - // read in the bytes - // - bytes_read = Read_File( File_Handle, buffer, bytes_to_read ); -#endif - -#if( SUPPORT_STREAMS ) - - ASSERT( File_Stream_Ptr != NULL ); - // - // error? - // - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - // - // nothing read - // - return( 0 ); - } - - // - // read in the bytes - // - items_read = fread( buffer, bytes_to_read, 1, File_Stream_Ptr ); -// Msg( __LINE__, __FILE__, "Read --- bytes_to_read = %d, items_read = %d.", bytes_to_read, items_read ); - - // - // &&& we should leave this enabled! - // - // The TRR system causes an error when we load strings into RAM - // IF the strings are kept on disk, then no error occurs! - // - ASSERT( items_read == 1 ); - - bytes_read = items_read * bytes_to_read; -#endif - - // - // return how many bytes we read - // - return( bytes_read ); -} - -//------------------------------------------------------------------------------ -// int StandardFileClass::Write -//------------------------------------------------------------------------------ - -int StandardFileClass::Write( void *buffer, unsigned long int bytes_to_write ) -{ - int items_written; - int bytes_written; - - // - // debug checks - // - ASSERT( buffer != NULL ); - ASSERT( bytes_to_write > 0 ); - ASSERT( Currently_Open == TRUE ); - - if ( buffer == NULL ) { - return( 0 ); - } - if ( bytes_to_write < 1 ) { - return( 0 ); - } - - #if( SUPPORT_HANDLES ) - - ASSERT( File_Handle != INVALID_FILE_HANDLE ); - - // - // error? - // - if ( File_Handle == INVALID_FILE_HANDLE || Currently_Open == FALSE ) { - // - // nothing written - // - return( 0 ); - } - - // - // write out the bytes - // - bytes_written = Write_File( File_Handle, buffer, bytes_to_write ); - ASSERT( bytes_written == bytes_to_write ); - #endif - - #if( SUPPORT_STREAMS ) - - ASSERT( File_Stream_Ptr != NULL ); - // - // error? - // - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - // - // nothing written - // - return( 0 ); - } - - // - // write out the bytes - // - items_written = fwrite( buffer, bytes_to_write, 1, File_Stream_Ptr ); - ASSERT( items_written == 1 ); - bytes_written = items_written * bytes_to_write; - #endif - - // - // return how many bytes we wrote - // - return( bytes_written ); -} - -//------------------------------------------------------------------------------ -// bool StandardFileClass::Seek -//------------------------------------------------------------------------------ - -bool StandardFileClass::Seek( int distance, int seek_file_position ) -{ - // - // debug checks... - // - ASSERT( Currently_Open == TRUE ); - ASSERT( seek_file_position == SEEK_SET || - seek_file_position == SEEK_CUR || - seek_file_position == SEEK_END ); - - #if( SUPPORT_HANDLES ) - - bool success; - - ASSERT( File_Handle != INVALID_FILE_HANDLE ); - // - // error? - // - if ( File_Handle == INVALID_FILE_HANDLE || Currently_Open == FALSE ) { - // - // error - // - return( FALSE ); - } - - // - // do the seek! - // - success = Seek_File( File_Handle, distance, seek_file_position ); - ASSERT( success == TRUE ); - return( success ); - #endif - - #if( SUPPORT_STREAMS ) - - ASSERT( File_Stream_Ptr != NULL ); - - // - // error? - // - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - // - // error - // - return( FALSE ); - } - - // - // do the seek! - // - int result = fseek( File_Stream_Ptr, distance, seek_file_position ); - - ASSERT( result == 0 ); - if ( ! result ) { - return( TRUE ); - } - return( FALSE ); - #endif -} - -//------------------------------------------------------------------------------ -// int StandardFileClass::Tell -//------------------------------------------------------------------------------ -// -// return file position -// -int StandardFileClass::Tell( void ) -{ - int file_pos; - - // - // debug checks... - // - ASSERT( Currently_Open == TRUE ); - - #if( SUPPORT_HANDLES ) - - ASSERT( File_Handle != INVALID_FILE_HANDLE ); - // - // error? - // - if ( File_Handle == INVALID_FILE_HANDLE || Currently_Open == FALSE ) { - // - // error - // - return( -1 ); - } - - // - // do the tell - // - file_pos = Tell_File( File_Handle ); - - ASSERT( file_pos != -1 ); - return( file_pos ); - - #endif - - #if( SUPPORT_STREAMS ) - - ASSERT( File_Stream_Ptr != NULL ); - // - // error? - // - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - // - // error - // - return( -1 ); - } - - // - // do the tell! - // - file_pos = ftell( File_Stream_Ptr ); - - ASSERT( file_pos != -1 ); - return( file_pos ); - - #endif -} - -//------------------------------------------------------------------------------ -// int StandardFileClass::Query_Size -//------------------------------------------------------------------------------ - -int StandardFileClass::Query_Size( void ) -{ - int size; - - // - // debug checks... - // - ASSERT( Currently_Open == TRUE ); - - #if( SUPPORT_HANDLES ) - - ASSERT( File_Handle != INVALID_FILE_HANDLE ); - // - // error? - // - if ( File_Handle == INVALID_FILE_HANDLE || Currently_Open == FALSE ) { - // - // error - // - return( -1 ); - } - - size = File_Size( File_Handle ); - ASSERT( size > -1 ); - #endif - - #if( SUPPORT_STREAMS ) - ASSERT( File_Stream_Ptr != NULL ); - // - // error? - // - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - // - // error - // - return( -1 ); - } - - size = File_Statistics.st_size; - ASSERT( size > -1 ); - #endif - - return( size ); -} - -//------------------------------------------------------------------------------ -// int StandardFileClass::Query_Size -//------------------------------------------------------------------------------ - -bool StandardFileClass::Query_Open( void ) -{ - return( Currently_Open ); -} - -//------------------------------------------------------------------------------ -// char *StandardFileClass::Query_Name_String -//------------------------------------------------------------------------------ - -char *StandardFileClass::Query_Name_String( void ) -{ - return( File_Name ); -} - - -#if( SUPPORT_STREAMS ) - -//------------------------------------------------------------------------------ -// FILE *StandardFileClass::Query_File_Stream_Pointer -//------------------------------------------------------------------------------ - -FILE *StandardFileClass::Query_File_Stream_Pointer( void ) -{ - return( File_Stream_Ptr ); -} - -#endif - -//------------------------------------------------------------------------------ -// private file class functions... -//------------------------------------------------------------------------------ - - -//------------------------------------------------------------------------------ -// void StandardFileClass::Reset -//------------------------------------------------------------------------------ - -void StandardFileClass::Reset( void ) -{ - // - // reset all internal data - // - #if( SUPPORT_HANDLES ) - File_Handle = INVALID_FILE_HANDLE; - #endif - #if( SUPPORT_STREAMS ) - File_Stream_Ptr = NULL; - #endif - Currently_Open = FALSE; - File_Name[ 0 ] = '\0'; -} - - -int StandardFileClass::End_Of_File ( void ) -{ - #if( SUPPORT_HANDLES ) - return( TRUE ); - #endif - - #if( SUPPORT_STREAMS ) - ASSERT( File_Stream_Ptr != NULL ); - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - return( -1 ); - } - return( feof( File_Stream_Ptr )); - #endif -} - -int StandardFileClass::Flush ( void ) -{ - #if( SUPPORT_STREAMS ) - ASSERT( File_Stream_Ptr != NULL ); - if ( File_Stream_Ptr == NULL || Currently_Open == FALSE ) { - return( -1 ); - } - return( fflush( File_Stream_Ptr )); - #endif -} - - -//------------------------------------------------------------------------------ -// non-class public functions from wnd_file.h -//------------------------------------------------------------------------------ - -#if( SUPPORT_HANDLES ) - -//------------------------------------------------------------------------------ -// int Open_File -//------------------------------------------------------------------------------ - -// &&& - if enabled, must handle read and write combined - -HANDLE Open_File( char const *file_name, int mode ) -{ - HANDLE windows_file_handle; - DWORD access; - DWORD creation; - DWORD share; - // int fh; - - // - // debug checks... - // - ASSERT( file_name != NULL ); - // ASSERT( mode == READ || mode == WRITE ); - ASSERT( mode == MODE_READ_ONLY || - mode == MODE_WRITE_ONLY || - mode == MODE_READ_AND_WRITE ); - - // - // get an available file handle - // - // fh = Get_Internal_File_Handle(); - // ASSERT( fh > INVALID_FILE_HANDLE ); - // if ( fh == INVALID_FILE_HANDLE ) { - // return( INVALID_FILE_HANDLE ); - // } - - // - // set the attributes based on read or write for the open - // - // if ( mode == READ ) { - if ( mode == MODE_READ_ONLY ) { - access = GENERIC_READ; - share = FILE_SHARE_READ; - creation = OPEN_EXISTING; - } - // else if ( mode == WRITE ) { - else if ( mode == MODE_WRITE_ONLY ) { - access = GENERIC_WRITE; - share = 0; - creation = CREATE_ALWAYS; - } - else if ( mode == MODE_READ_AND_WRITE ) { - // - // &&& are these correct? - // - access = GENERIC_READ | GENERIC_WRITE; - share = FILE_SHARE_READ | FILE_SHARE_WRITE; - creation = OPEN_EXISTING; - } - else { - // - // error; - // - ASSERT( FALSE ); - } - - // - // 32-bit open file - // - windows_file_handle = CreateFile( file_name, - access, - share, - NULL, - creation, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, - NULL ); - // - // error? - // - // we don't want to assert because we may be looking for a file - // to just see if it is there... - // - // ASSERT( windows_file_handle != INVALID_HANDLE_VALUE ); - // - // error! - // - if ( windows_file_handle == INVALID_HANDLE_VALUE ) { - // #if( _DEBUG ) - // Debug_Printf( "%s: Create file error is %d\r\n", file_name, GetLastError()); - // #endif - return( INVALID_FILE_HANDLE ); - } - - // - // store the windows handle - // - // Windows_File_Handles[ fh ] = windows_file_handle; - // - // return our internal file handle - // - // return( fh ); - - // - // &&& this should be HANDLE, not int - // - // return( windows_file_handle ); - return( windows_file_handle ); -} - -//------------------------------------------------------------------------------ -// int Close_File -//------------------------------------------------------------------------------ - -bool Close_File( HANDLE handle ) -{ - bool success; - - // - // debug checks... - // - // ASSERT( handle > INVALID_FILE_HANDLE ); - // ASSERT( Windows_File_Handles[ handle ] != NULL ); - ASSERT( handle != INVALID_FILE_HANDLE ); - - // - // close the file - // - // success = CloseHandle( Windows_File_Handles[ handle ] ); - // - // &&& - this should be an actual HANDLE - // - success = CloseHandle( (HANDLE) handle ); - ASSERT( success == TRUE ); - - // Debug_Printf( "File %d closed.\r\n", handle ); - - // - // free the entry - // - // Windows_File_Handles[ handle ] = NULL; - - // - // return success or not - // - // if ( success == TRUE ) { - // // - // // return the invalid handle that closed - // // - // return( handle ); - // } - // // - // // error - // // - // return( INVALID_FILE_HANDLE ); - return( success ); -} - -//------------------------------------------------------------------------------ -// int Read_File -//------------------------------------------------------------------------------ - -int Read_File( HANDLE handle, void *buffer, unsigned long int bytes_to_read ) -{ - bool success; - DWORD bytes_actually_read; - - // - // debug checks... - // - ASSERT( handle > INVALID_FILE_HANDLE ); - ASSERT( buffer != NULL ); - // ASSERT( bytes_to_read > 0 ); - // ASSERT( Windows_File_Handles[ handle ] != NULL ); - - // Debug_Printf( "Reading file %d\r\n", handle ); - - // success = ReadFile( Windows_File_Handles[ handle ], - // (void *) buffer, - // (DWORD) bytes_to_read, - // (DWORD *) &bytes_actually_read, - // NULL ); - - // - // &&& use real HANDLE - // - success = ReadFile( (HANDLE) handle, - (void *) buffer, - (DWORD) bytes_to_read, - (DWORD *) &bytes_actually_read, - NULL ); - - ASSERT( success == TRUE ); - - if ( success == FALSE ) { - // - // no bytes read - // - return( 0 ); - } - - return( bytes_actually_read ); -} - -//------------------------------------------------------------------------------ -// int Write_File -//------------------------------------------------------------------------------ - -int Write_File( HANDLE handle, void const *buffer, unsigned long int bytes_to_write ) -{ - bool success; - DWORD bytes_actually_written; - - // - // debug checks... - // - ASSERT( handle != INVALID_FILE_HANDLE ); - ASSERT( buffer != NULL ); - // ASSERT( bytes_to_write > 0 ); - // ASSERT( Windows_File_Handles[ handle ] != NULL ); - - // Debug_Printf( "Writing file %d\r\n", handle ); - - // success = WriteFile( Windows_File_Handles[ handle ], - // buffer, - // (DWORD) bytes_to_write, - // (DWORD *) &bytes_actually_written, - // NULL ); - - // - // &&& make this a real handle - // - success = WriteFile( (HANDLE) handle, - buffer, - (DWORD) bytes_to_write, - (DWORD *) &bytes_actually_written, - NULL ); - - ASSERT( success == TRUE ); - ASSERT( bytes_actually_written == bytes_to_write ); - - if ( success == FALSE ) { - // - // no bytes written - // - return( 0 ); - } - - return( bytes_actually_written ); -} - -//------------------------------------------------------------------------------ -// bool Seek_File -//------------------------------------------------------------------------------ - -bool Seek_File( HANDLE handle, int distance, int seek_file_location ) -{ - DWORD success; - int move_method; - - // - // debug checks... - // - ASSERT( handle != INVALID_FILE_HANDLE ); - // ASSERT( distance >= 0 ); - ASSERT( seek_file_location == SEEK_SET || - seek_file_location == SEEK_CUR || - seek_file_location == SEEK_END ); - // ASSERT( Windows_File_Handles[ handle ] != NULL ); - - // - // set the seek movement method - // - if ( seek_file_location == SEEK_SET ) { - move_method = FILE_BEGIN; - } - else if ( seek_file_location == SEEK_CUR ) { - move_method = FILE_CURRENT; - } - else if ( seek_file_location == SEEK_END ) { - move_method = FILE_END; - } - - // success = SetFilePointer( Windows_File_Handles[ handle ], - // distance, - // NULL, - // move_method ); - - // - // make this a real handle - // - success = SetFilePointer( (HANDLE) handle, - distance, - NULL, - move_method ); - - if ( success == 0xFFFFFFFF ) { - return( FALSE ); - } - return( TRUE ); -} - -//------------------------------------------------------------------------------ -// int Tell_File -//------------------------------------------------------------------------------ - -int Tell_File( HANDLE handle ) -{ - int move_method; - int pos; - - // - // debug checks... - // - ASSERT( handle != INVALID_FILE_HANDLE ); - // ASSERT( Windows_File_Handles[ handle ] != NULL ); - - // - // set the seek movement method - // - move_method = FILE_CURRENT; - - // - // move nowhere - // - pos = SetFilePointer( handle, - 0, // distance to move - NULL, - move_method ); - - if ( pos == 0xFFFFFFFF ) { - return( -1 ); - } - return( pos ); -} - -//------------------------------------------------------------------------------ -// int File_Size -//------------------------------------------------------------------------------ - -int File_Size( HANDLE handle ) -{ - DWORD file_size; - - // - // debug checks... - // - ASSERT( handle != INVALID_FILE_HANDLE ); - // ASSERT( Windows_File_Handles[ handle ] != NULL ); - - file_size = GetFileSize( handle, NULL ); - ASSERT( file_size != 0xFFFFFFFF ); - - // - // error! - // - if ( file_size == 0xFFFFFFFF ) { - return( -1 ); - } - - // - // return size - // - return( (int) file_size ); -} - -//------------------------------------------------------------------------------ -// bool Full_Path_File_Exists -//------------------------------------------------------------------------------ - -bool Full_Path_File_Exists( char const *file_name ) -{ - HANDLE fh; - - // - // debug checks... - // - ASSERT( file_name != NULL ); - - // - // if we can open the file for read, it exists... - // - fh = Open_File( file_name, MODE_READ_ONLY ); - // - // don't assert, because the we might be checking for a file - // that actually does not exist! - // - // ASSERT( fh > INVALID_FILE_HANDLE ); - - // - // close the file and return success if opened - // - if ( fh != INVALID_FILE_HANDLE ) { - Close_File( fh ); - return( TRUE ); - } - - // - // no success if file was not opened - // - return( FALSE ); -} - -//------------------------------------------------------------------------------ -// bool HD_File_Exists -//------------------------------------------------------------------------------ - -bool HD_File_Exists( char const *file_name ) -{ - HANDLE fh; - char full_path[ MAX_PATH_SIZE ]; - - // - // debug checks... - // - ASSERT( file_name != NULL ); - strcpy( full_path, HD_Path ); - strcat( full_path, file_name ); - - // - // if we can open the file for read, it exists... - // - fh = Open_File( full_path, MODE_READ_ONLY ); - // - // don't assert, because the we might be checking for a file - // that actually does not exist! - // - - // - // close the file and return success if opened - // - if ( fh != INVALID_FILE_HANDLE ) { - Close_File( fh ); - return( TRUE ); - } - - // - // no success if file was not opened - // - return( FALSE ); -} - -//------------------------------------------------------------------------------ -// bool CD_File_Exists -//------------------------------------------------------------------------------ - -bool CD_File_Exists( char const *file_name ) -{ - HANDLE fh; - char full_path[ MAX_PATH_SIZE ]; - - // - // debug checks... - // - ASSERT( file_name != NULL ); - strcpy( full_path, CD_Path ); - strcat( full_path, file_name ); - - // - // if we can open the file for read, it exists... - // - fh = Open_File( full_path, MODE_READ_ONLY ); - // - // don't assert, because the we might be checking for a file - // that actually does not exist! - // - - // - // close the file and return success if opened - // - if ( fh != INVALID_FILE_HANDLE ) { - Close_File( fh ); - return( TRUE ); - } - - // - // no success if file was not opened - // - return( FALSE ); -} - -#if( 0 ) -//------------------------------------------------------------------------------ -// bool Find_File -//------------------------------------------------------------------------------ -bool Find_File( char const *file_name ) -{ - return( File_Exists( file_name ) ); -} -#endif - -#if( 0 ) -//------------------------------------------------------------------------------ -// int Get_Internal_File_Handle -//------------------------------------------------------------------------------ -// -// private... -// -int Get_Internal_File_Handle( void ) -{ - static bool _initialized = FALSE; - int i; - - // - // initialize file handle table once! - // - if ( ! _initialized ) { - for ( i = 0; i < MAX_FILES_OPEN_AT_A_TIME; i ++ ) { - Windows_File_Handles[ i ] = NULL; - } - _initialized = TRUE; - } - - // - // look for free slot - // - for ( i = 0; i < MAX_FILES_OPEN_AT_A_TIME; i ++ ) { - if ( Windows_File_Handles[ i ] == NULL ) { - return( i ); - } - } - - // - // no free slot found - // - ASSERT( FALSE ); - return( INVALID_FILE_HANDLE ); -} -#endif - - -#endif // SUPPORT_HANDLES - -#if( SUPPORT_STREAMS ) - -//------------------------------------------------------------------------------ -// bool Full_Path_File_Exists -//------------------------------------------------------------------------------ - -bool Full_Path_File_Exists( char const *file_name ) -{ - FILE *file_stream_ptr; - - file_stream_ptr = fopen( file_name, "rb" ); - if ( file_stream_ptr != NULL ) { - fclose( file_stream_ptr ); - return( TRUE ); - } - return( FALSE ); -} - -//------------------------------------------------------------------------------ -// bool HD_File_Exists -//------------------------------------------------------------------------------ - -bool HD_File_Exists( char const *file_name ) -{ - FILE *file_stream_ptr; - char full_path[ MAX_PATH_SIZE ]; - - // - // debug checks... - // - ASSERT( file_name != NULL ); - - strcpy( full_path, HD_Path ); - strcat( full_path, file_name ); - - file_stream_ptr = fopen( full_path, "rb" ); - if ( file_stream_ptr != NULL ) { - fclose( file_stream_ptr ); - return( TRUE ); - } - return( FALSE ); -} - -//------------------------------------------------------------------------------ -// bool CD_File_Exists -//------------------------------------------------------------------------------ - -bool CD_File_Exists( char const *file_name ) -{ - FILE *file_stream_ptr; - char full_path[ MAX_PATH_SIZE ]; - - // - // debug checks... - // - ASSERT( file_name != NULL ); - - strcpy( full_path, CD_Path ); - strcat( full_path, file_name ); - - file_stream_ptr = fopen( full_path, "rb" ); - if ( file_stream_ptr != NULL ) { - fclose( file_stream_ptr ); - return( TRUE ); - } - return( FALSE ); -} - - -#if( 0 ) -//------------------------------------------------------------------------------ -// bool Find_File -//------------------------------------------------------------------------------ -bool Find_File( char const *file_name ) -{ - return( File_Exists( file_name ) ); -} -#endif - -#endif // SUPPORT_STREAMS - diff --git a/Generals/Code/Tools/Autorun/autorun.cpp b/Generals/Code/Tools/Autorun/autorun.cpp deleted file mode 100644 index c2234b89e5..0000000000 --- a/Generals/Code/Tools/Autorun/autorun.cpp +++ /dev/null @@ -1,5437 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** - ** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - **************************************************************************** - * * - * Project Name : Autorun * - * * - * File Name : AUTORUN.CPP * - * * - * Programmers: Maria del Mar McCready Legg * - * * - * Start Date : September 5, 1997 * - * * - * Last Update : October 15, 2001 [MML] * - * * - *--------------------------------------------------------------------------* - * Functions: * - * WinMain * - * Main::MessageLoop * - * MainWindow::Register * - * MainWindow::MainWindow * - * MainWindow::Window_Proc * - * MainWindow::Is_Product_Registered * - * MainWindow::Run_Explorer * - * MainWindow::Run_Game * - * MainWindow::Run_Setup * - * MainWindow::Run_New_Account * - * MainWindow::Run_Register * - * MainWindow::Run_Auto_Update * - * MainWindow::Run_Uninstall * - * MainWindow::Create_Buttons * - * Wnd_Proc * - * Dialog_Box_Proc * - * Stop_Sound_Playing * - * Options * - * Valid_Environment * - * LoadResourceBitmap * - * CreateDIBPalette * - * LoadResourceButton * - * Cant_Find_MessageBox * - * Error_Message * - * Path_Add_Back_Slash * - * Path_Remove_Back_Slash * - * PlugInProductName * - * Fix_Single_Ampersands * - * Fix_Double_Ampersands * - * LaunchObjectClass::LaunchObjectClass * - * LaunchObjectClass::SetPath * - * LaunchObjectClass::SetArgs * - * LaunchObjectClass::Launch * - *--------------------------------------------------------------------------*/ - - -#define STRICT -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ARGS.H" -#include "autorun.h" -#include "DrawButton.h" -#include "resource.h" -#include "Wnd_File.h" -//#include "visualc.h" -#include "WinFix.H" -#include "CDCNTRL.H" -#include "IGR.h" -#include "ViewHTML.h" - -#include "Utils.h" -#include "Locale_API.h" -//#include "resources.h" -#include "GetCD.h" - -#include "WSYS_FileSystem.h" -#include "WSYS_StdFileSystem.h" - -#include -#include "GameText.h" - -#include "leanAndMeanAutorun.h" - -#ifndef LEAN_AND_MEAN -#include "Common/SubsystemInterface.h" -#include "GameClient/GameText.h" -#include "Common/UnicodeString.h" -#include "Win32Device/Common/Win32LocalFileSystem.h" -#include "Win32Device/Common/Win32BIGFileSystem.h" -#endif - -//----------------------------------------------------------------------------- -// DEFINES -//----------------------------------------------------------------------------- -#define PRETEND_ON_CD_TEST FALSE // should be FALSE -//#define PRETEND_ON_CD_TEST TRUE // should be FALSE - -#define WINDOW_BRUSH FALSE -#define BACKGROUND_BITMAP TRUE -#define USE_MOUSE_MOVES TRUE -#define DISABLE_KEYBOARD FALSE - -#define BUTTON_WIDTH 150 -#define BUTTON_HEIGHT 45 -#define NUM_BUTTONS 10 -#define NUM_ARGUMENTS 10 -#define NUM_SONGS 2 //32 //16 -#define NUM_FLICKER_FRAMES 1 -#define NUM_FLICKER_POSITIONS 15 - -#define MOUSE_WAV "MouseMove" -#define SOUND_FILE1 "SPEECH_FILE1" -#define SOUND_FILE2 "SPEECH_FILE2" - -#define MOH_DEMO_PROGRAM "MOHAADEMO\\SETUP.EXE" -#define SHOW_MOH_DEMO FALSE - -#define BFAVI_FILENAME "Autorun\\BF1942RTR.avi" -#define SC4AVI_FILENAME "Autorun\\SimCity4.avi" -#define HELP_FILENAME "HELP:FILENAME"//"Support\\eahelp.hlp" - -#define SHOW_GAMESPY_BUTTON FALSE -#define GAMESPY_WEBSITE "http://www.gamespyarcade.com/features/launch.asp?svcname=ccrenegade&distID=391" - -#define RESOURCE_FILE "Autorun.loc" -#define SETUP_INI_FILE1 "Setup\\Setup.ini" -#define SETUP_INI_FILE2 "Setup.ini" - -//----------------------------------------------------------------------------- -// These defines need the Product name from Setup.ini to complete. -//----------------------------------------------------------------------------- -#define SETUP_MAIN_WINDOW_NAME "%s Setup" -#define CLASS_NAME "%s Autorun" -#define GAME_MAIN_WINDOW_NAME "%s Game Window" - -//#define GAME_WEBSITE "http://www.westwood.com/" -#define GAME_WEBSITE "http://generals.ea.com" - -#define AUTORUN_MUTEX_OBJECT "01AF9993-3492-11d3-8F6F-0060089C05B1" -//#define GAME_MUTEX_OBJECT "C6D925A3-7A9B-4ca3-866D-8B4D506C3665" -#define GAME_MUTEX_OBJECT "685EAFF2-3216-4265-B047-251C5F4B82F3" -#define PRODUCT_VOLUME_CD1 "Generals1" -#define PRODUCT_VOLUME_CD2 "Generals2" - - -//----------------------------------------------------------------------------- -// Global Variables -//----------------------------------------------------------------------------- -LaunchObjectClass LaunchObject; -MainWindow *GlobalMainWindow = NULL; -int Language = 0; -int LanguageToUse = 0; - -DrawButton *ButtonList [ NUM_BUTTONS ]; -RECT ButtonSizes [ NUM_BUTTONS ]; -char ButtonImages [ NUM_BUTTONS ][ MAX_PATH ]; -CHAR szSongPath [ MAX_PATH ]; -char FocusedButtonImages [ NUM_BUTTONS ][ MAX_PATH ]; -char Arguments [ NUM_ARGUMENTS ][ 30 ]; -char szWavs [ NUM_SONGS][ _MAX_PATH ]; -char szBuffer [ MAX_PATH ]; -char szBuffer1 [ MAX_PATH ]; -char szBuffer2 [ MAX_PATH ]; -char szBuffer3 [ MAX_PATH * 2]; -char szInternetPath [_MAX_PATH]; -char szGamePath [_MAX_PATH]; -char szWorldbuilderPath [_MAX_PATH]; -char szPatchgetPath [_MAX_PATH]; -char szSetupPath [_MAX_PATH]; -char szUninstallPath [_MAX_PATH]; -char szRegisterPath [_MAX_PATH]; -char szButtonWav [_MAX_PATH ]; -char szSpeechWav [_MAX_PATH ]; -char szArgvPath [_MAX_PATH ]; -char drive [_MAX_DRIVE]; -char dir [_MAX_DIR ]; -char szSetupWindow [_MAX_PATH]; -char szGameWindow [_MAX_PATH]; -char szRegistryKey [_MAX_PATH]; -char szClassName [_MAX_PATH]; -char szVolumeName [_MAX_PATH]; - -char szProduct_Name [ _MAX_PATH ]; - - -#ifdef LEAN_AND_MEAN - -wchar_t szWideBuffer [ _MAX_PATH ]; -wchar_t szWideBuffer0 [ _MAX_PATH ]; -wchar_t szWideBuffer2 [ _MAX_PATH ]; -wchar_t szWideBuffer3 [ _MAX_PATH ]; -wchar_t szProductName [ _MAX_PATH ]; -wchar_t szFullProductName [ _MAX_PATH ]; - -/* -enum -{ - IDS_INSTALL, - IDS_EXPLORE_CD, - IDS_PREVIEWS, - IDS_CANCEL, - IDS_AUTORUN_TITLE, - IDS_CANT_FIND_IEXPLORER, - IDS_WINDOWS_VERSION_TEXT, - IDS_WINDOWS_VERSION_TITLE, - IDS_CANT_FIND, - IDS_UNINSTALL, - IDS_WEBSITE, - IDS_CHECKFORUPDATES, - IDS_WORLDBUILDER, - IDS_PLAY, - - IDS_GAME_TITLE, - IDS_FULL_GAME_TITLE, - IDS_REGISTRY_KEY, - IDS_MAIN_WINDOW, - - - IDS_COUNT // keep this last -}; -*/ - -#else - -UnicodeString wideBuffer; -UnicodeString wideBuffer0; -UnicodeString wideBuffer2; -UnicodeString wideBuffer3; -UnicodeString productName; -UnicodeString fullProductName; - -#endif - - - -bool IsEnglish = FALSE; -bool UseSounds = FALSE; -bool b640X480 = FALSE; -bool b800X600 = FALSE; -BOOL OnCDRom = FALSE; -BOOL IAmWindows95 = FALSE; -BOOL InstallProduct = TRUE; -BOOL UninstallAvailable = FALSE; -BOOL IsUserRegistered = FALSE; -BOOL DisplayRegisterButton = FALSE; -BOOL IsWolapiAvailable = FALSE; -BOOL CDLocked = FALSE; -int WindowsVersion = 0; -int NumberArguments = 0; -int SongNumber = 0; -HANDLE AppMutex = NULL; -HANDLE GameAppMutex = NULL; -HANDLE SetupAppMutex = NULL; - - - - -#ifdef LEAN_AND_MEAN - -extern FileSystem *TheFileSystem; - -#else - -extern GameTextInterface *TheGameText; -extern LocalFileSystem *TheLocalFileSystem; -extern ArchiveFileSystem *TheArchiveFileSystem; - -#endif - -// stuff needed to compile. -HWND ApplicationHWnd = NULL; -HINSTANCE ApplicationHInstance; ///< main application instance - -const char *g_strFile = "Autorun.str"; -const char *g_csfFile = "Autorun.csf"; - -const char *gAppPrefix = "ar_"; // prefix to the debug log. - -int FlickerPositions[ NUM_FLICKER_POSITIONS ][2]; - -#if( _DEBUG ) -char szCDDrive[ MAX_PATH ]; -#endif - - -//----------------------------------------------------------------------------- -// Global Function Definitions -//----------------------------------------------------------------------------- -void Cant_Find_MessageBox ( HINSTANCE hInstance, const char *szPath ); -HPALETTE CreateDIBPalette ( LPBITMAPINFO lpbmi, LPINT lpiNumColors ); -void Debug_Date_And_Time_Stamp ( void ); - -void Error_Message ( HINSTANCE hInstance, int title, int string, const char *path ); -void Error_Message ( HINSTANCE hInstance, const char * title, const char * string, const char *path ); - -bool Is_On_CD ( const char * ); -HBITMAP LoadResourceBitmap ( HMODULE hInstance, LPCTSTR lpString, HPALETTE FAR *lphPalette, bool loading_a_button=FALSE ); -HBITMAP LoadResourceButton ( HMODULE hInstance, LPCTSTR lpString, HPALETTE FAR lphPalette ); -BOOL Options ( Command_Line_Arguments *Orgs ); -void Prog_End ( void ); -bool Prompt_For_CD ( HWND window_handle, char *volume_name, const char * message1, const char * message2, int *cd_drive ); -void Reformat_Volume_Name ( const char *volume_name, char *new_volume_name ); -int Show_Message ( HWND window_handle, const char * message_num1, const char * message_num2 ); -int Show_Message ( HWND window_handle, int message_num1 ); -void Stop_Sound_Playing ( void ); -BOOL Valid_Environment ( void ); - -BOOL CALLBACK Dialog_Box_Proc ( HWND window_handle, UINT message, WPARAM w_param, LPARAM l_param ); -LRESULT CALLBACK Wnd_Proc ( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ); - - -//----------------------------------------------------------------------------- -// Main & MainWindow Public Variables -//----------------------------------------------------------------------------- -HINSTANCE Main::hInstance = 0; -HINSTANCE Main::hPrevInstance = 0; -HMODULE Main::hModule = 0; -int Main::nCmdShow = 0; -char MainWindow::szClassName[] = CLASS_NAME; - - -//***************************************************************************** -// WinMain -- Main Program Loop. -// -// INPUT: HINSTANCE hInstance -// HINSTANCE hPrevInstance -// LPTSTR lpszCmdLine -// int nCmdShow -// -// OUTPUT: int. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpszCmdLine, int nCmdShow ) -{ - - int i = 0; - char szPath[ _MAX_PATH ]; - char szIniPath[ _MAX_PATH ]; - - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - Main::hInstance = hInstance; - ApplicationHInstance = hInstance; - Main::hPrevInstance = hPrevInstance; - Main::nCmdShow = nCmdShow; - Main::hModule = GetModuleHandle( NULL ); - - memset( szSetupWindow, '\0', MAX_PATH ); - memset( szGameWindow, '\0', MAX_PATH ); - memset( szProductName, '\0', MAX_PATH ); - memset( szFullProductName, '\0', MAX_PATH ); - memset( szRegistryKey, '\0', MAX_PATH ); - memset( szClassName, '\0', MAX_PATH ); - memset( szVolumeName, '\0', MAX_PATH ); - - Msg( __LINE__, __FILE__, "Entering WinMain." ); - - //------------------------------------------------------------------------- - // Set Cleanup function. - //------------------------------------------------------------------------- - atexit( Prog_End ); - - //------------------------------------------------------------------------- - // Clear Argument Array. - //------------------------------------------------------------------------- - for ( i = 0; i < NUM_ARGUMENTS; i++ ) { - memset( Arguments[i], '\0', sizeof( Arguments[i] )); - } - for ( i = 0; i < NUM_SONGS; i++ ) { - memset( szWavs[i], '\0', sizeof( szWavs[i] )); - } - - //------------------------------------------------------------------------- - // Init Args class. - //------------------------------------------------------------------------- - Args = new Command_Line_Arguments( hInstance, GetCommandLine()); - if ( Args == NULL ) { -// Error_Message( hInstance, IDS_ERROR, IDS_COMMAND_LINE_ERR, NULL ); - Error_Message( hInstance, "Autorun:Error", "Autorun:CommandLineError", NULL ); - return( 0 ); - } - Msg( __LINE__, __FILE__, "Args Created." ); - -#if( PRETEND_ON_CD_TEST ) - strcpy( szCDDrive, "E:\\" ); - Options( Args ); - strcat( szCDDrive, "autorun.exe" ); - Msg( __LINE__, __FILE__, "szCDDrive = %s.", szCDDrive ); - Args->Set_argv( 0, szCDDrive ); -#endif - - //------------------------------------------------------------------------- - // Get the CD volume to check on which CD in the product we are on. - //------------------------------------------------------------------------- - strcpy( szBuffer, Args->Get_argv(0)); - CDList.Get_Volume_For_This_CD_Drive( szBuffer, szVolumeName ); - - Msg( __LINE__, __FILE__, "szVolumeName = %s.", szVolumeName ); - - -#ifdef LEAN_AND_MEAN - - TheFileSystem = new StdFileSystem; - -#else - - // create singletons - TheFileSystem->init(); - TheLocalFileSystem = new Win32LocalFileSystem; - TheArchiveFileSystem = new Win32BIGFileSystem; - TheGameText = CreateGameTextInterface(); - TheGameText->init(); - -#endif - - //========================================================================= - // Make paths to .INI and .LOC files. - //========================================================================= - Make_Current_Path_To( RESOURCE_FILE, szPath ); - Make_Current_Path_To( SETUP_INI_FILE1, szIniPath ); - - handle = FindFirstFile( szIniPath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - - //--------------------------------------------------------------------- - // This might be a secondary CD. - //--------------------------------------------------------------------- - Make_Current_Path_To( SETUP_INI_FILE2, szIniPath ); - } - FindClose( handle ); - - Msg( __LINE__, __FILE__, "Resource file = %s.", szPath ); - Msg( __LINE__, __FILE__, "Setup.ini file = %s.", szIniPath ); - - //-------------------------------------------------------------------------- - // Get the language we are using from the Setup.ini file. - //-------------------------------------------------------------------------- - Language = GetPrivateProfileInt( "Setup", "Language", 0, szIniPath ); - - if( Language == 0 ) { - IsEnglish = true; - } - - Msg( __LINE__, __FILE__, "Language = %d.", Language ); - Msg( __LINE__, __FILE__, "IsEnglish = %d.", IsEnglish ); - - //-------------------------------------------------------------------------- - // Set language to use. - //-------------------------------------------------------------------------- - if( Locale_Use_Multi_Language_Files()) { - - if( IS_LANGUAGE_DBCS( Language ) && !IS_CODEPAGE_DBCS( CodePage )) { - Language = LANG_USA; - } - - /*switch( Language ) { - - case LANG_GER: - LanguageToUse = IDL_GERMAN; - break; - - case LANG_FRE: - LanguageToUse = IDL_FRENCH; - break; - - case LANG_JAP: - LanguageToUse = IDL_JAPANESE; - break; - - case LANG_KOR: - LanguageToUse = IDL_KOREAN; - break; - - case LANG_CHI: - LanguageToUse = IDL_CHINESE; - break; - - case LANG_USA: - default: - LanguageToUse = IDL_ENGLISH; - break; - } - */ - LanguageToUse = Language; - - } - Msg( __LINE__, __FILE__, "LanguageToUse = %d.", LanguageToUse ); - - //------------------------------------------------------------------------- - // Process the Command Line Options. This may change the language id. - //------------------------------------------------------------------------- - if ( !Options( Args )) { - return( 0 ); - } - - //------------------------------------------------------------------------- - // Save off the Current path for use by other stuff. - //------------------------------------------------------------------------- - _tcscpy( szArgvPath, Args->Get_argv(0)); - _tsplitpath( szArgvPath, drive, dir, NULL, NULL ); - _tmakepath ( szArgvPath, drive, dir, NULL, NULL ); - Path_Add_Back_Slash( szArgvPath ); - Msg( __LINE__, TEXT(__FILE__), TEXT("szArgvPath = %s."), szArgvPath ); - - Msg( __LINE__, __FILE__, "About to Init text strings." ); - - //========================================================================= - // Init the strings chosen. - //========================================================================= - - - Locale_Init( LanguageToUse, szPath ); - - /* - if( !Locale_Init( LanguageToUse, szPath )) { - LoadString( Main::hInstance, IDS_CANT_FIND_FILE, szBuffer1, _MAX_PATH ); - MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szPath, _MAX_PATH, szWideBuffer0, _MAX_PATH ); - sprintf( szBuffer2, szBuffer1, szWideBuffer0 ); - MessageBox( NULL, szBuffer2, "Autorun", MB_APPLMODAL | MB_OK ); - return 0; - } - */ - - - //------------------------------------------------------------------------- - // Get some pertinent strings. - //------------------------------------------------------------------------- - Locale_GetString( "Autorun:Title", szProductName ); - Locale_GetString( "Autorun:Command&ConquerGenerals", szFullProductName ); - //Locale_GetString( IDS_GAME_TITLE, szProductName ); - //Locale_GetString( IDS_FULL_GAME_TITLE, szFullProductName ); -// Locale_GetString( IDS_REGISTRY_KEY, szRegistryKey ); -// Locale_GetString( IDS_MAIN_WINDOW, szGameWindow ); - - - //------------------------------------------------------------------------- - // Set other variables used through out. - //------------------------------------------------------------------------- -#ifdef LEAN_AND_MEAN - - //Fix_Single_Ampersands( &szProductName[0], false ); - //Fix_Single_Ampersands( &szFullProductName[0], false ); - Msg( __LINE__, __FILE__, "szProductName = %s.", szProductName ); - WideCharToMultiByte( CodePage, 0, szProductName, _MAX_PATH, szProduct_Name, _MAX_PATH, NULL, NULL ); - -#else - - productName = TheGameText->fetch("Autorun:Generals"); - fullProductName = TheGameText->fetch("Autorun:Command&ConquerGenerals"); - Msg( __LINE__, __FILE__, "Product Name = %ls.", productName.str() ); - Msg( __LINE__, __FILE__, "Full Product Name = %ls.", fullProductName.str() ); - Msg( __LINE__, __FILE__, "szRegistryKey = %s.", szRegistryKey ); - Msg( __LINE__, __FILE__, "szGameWindow = %s.", szGameWindow ); - WideCharToMultiByte( CodePage, 0, productName.str(), productName.getLength()+1, szProduct_Name, _MAX_PATH, NULL, NULL ); - -#endif - - sprintf( szClassName, CLASS_NAME, szProduct_Name ); - MainWindow::Reset_Class_Name( szClassName ); - sprintf( szSetupWindow, SETUP_MAIN_WINDOW_NAME, szProduct_Name ); - - Msg( __LINE__, __FILE__, "szClassName = %s.", szClassName ); - Msg( __LINE__, __FILE__, "szSetupWindow = %s.", szSetupWindow ); - - //========================================================================= - // Create a mutex with a unique name to Autorun in order to determine if - // our app is already running. - // - // Return Values: - // If the function succeeds, the return value is a handle to the mutex object. - // If the named mutex object existed before the function call, the function returns - // a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS. - // Otherwise, the caller created the mutex. - // If the function fails, the return value is NULL. To get extended error - // information, call GetLastError. - // - // WARNING: DO NOT use this number for any other application except Autorun - //========================================================================= - if( WinVersion.Is_Win_XP() || WinVersion.Version() > 500 ) { - strcat( strcpy( szBuffer, "Global\\" ), AUTORUN_MUTEX_OBJECT ); - } else { - strcpy( szBuffer, AUTORUN_MUTEX_OBJECT ); - } - AppMutex = CreateMutex( NULL, FALSE, szBuffer ); - - if ( AppMutex != NULL && ( GetLastError() == ERROR_ALREADY_EXISTS )) { - - Msg( __LINE__, __FILE__, "AppMutex of %s already exists. Exit here.", szBuffer ); - - //--------------------------------------------------------------------- - // Handle is closed in the ProgEnd(). - //--------------------------------------------------------------------- - - //--------------------------------------------------------------------- - // Check if Game/Setup is already running, and is looking for the CDRom. - //--------------------------------------------------------------------- - HWND prev = FindWindow( szClassName, NULL ); - if( prev ){ - //if( IsIconic( prev )){ - //ShowWindow( prev, SW_RESTORE ); - //} - SetForegroundWindow( prev ); - } - return 0; - } - Msg( __LINE__, __FILE__, "AppMutex of %s created.", szBuffer ); - - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // if AppMutex was NULL, let through. Perhaps in future we want to trap it? - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - if ( AppMutex == NULL ) { - } - - //========================================================================= - // Create a mutex with a unique name to Game/Setup in order to - // determine if our app is already running. - // - // Return Values - // If the function succeeds, the return value is a handle to the mutex object. - // If the function fails, the return value is NULL. To get extended error - // information, call GetLastError. - // - // WARNING: DO NOT use this number for any other application except Game/Setup. - //========================================================================= - if( WinVersion.Is_Win_XP() || WinVersion.Version() > 500 ) { - strcat( strcpy( szBuffer, "Global\\" ), GAME_MUTEX_OBJECT ); - } else { - strcpy( szBuffer, GAME_MUTEX_OBJECT ); - } - GameAppMutex = OpenMutex( MUTEX_ALL_ACCESS, FALSE, szBuffer ); - - if ( GameAppMutex != NULL ) { - - Msg( __LINE__, TEXT(__FILE__), TEXT("Mutex Object of game found.")); - Msg( __LINE__, TEXT(__FILE__), TEXT("Looking for Game Window.")); - - HWND ccwindow = FindWindow( szGameWindow, NULL ); - if ( ccwindow ) { - - Msg( __LINE__, TEXT(__FILE__), TEXT("Found Game Window.")); - - if( IsIconic( ccwindow )){ - ShowWindow( ccwindow, SW_RESTORE ); - } - SetForegroundWindow( ccwindow ); - - } else { - - Msg( __LINE__, TEXT(__FILE__), TEXT("Looking for Setup Window.")); - - ccwindow = FindWindow( szSetupWindow, NULL ); - if ( ccwindow ) { - - Msg( __LINE__, TEXT(__FILE__), TEXT("Found Setup Window.")); - - if( IsIconic( ccwindow )){ - ShowWindow( ccwindow, SW_RESTORE ); - } - BOOL result = SetForegroundWindow( ccwindow ); - Msg( __LINE__, TEXT(__FILE__), TEXT("SetForegroundWindow = %d."), result ); - } - } - - //--------------------------------------------------------------------- - // Handle(s) are closed in the ProgEnd(). - //--------------------------------------------------------------------- - - return 0; - } - - //--------------------------------------------------------------------- - // Check if Game/Setup is already running, and is looking for the CDRom. - //--------------------------------------------------------------------- - HWND prev = FindWindow( szClassName, NULL ); - if ( prev == NULL ) { - prev = FindWindow( szGameWindow, NULL ); - if ( prev == NULL ) { - prev = FindWindow( szSetupWindow, NULL ); - } - } - if( prev ){ - if( IsIconic( prev )){ - ShowWindow( prev, SW_RESTORE ); - } - SetForegroundWindow( prev ); - - Msg( __LINE__, __FILE__, "Either same app, game or setup was found. Exit and set window to foreground." ); - return 0; - } - - //========================================================================= - // Select Sounds. - //========================================================================= - memset( szButtonWav, '\0', _MAX_PATH ); - _tcscpy( szButtonWav, _TEXT( MOUSE_WAV )); - -// memset( szSpeechWav, '\0', _MAX_PATH ); -// _tcscpy( szSpeechWav, _TEXT( AUTORUN_WAV )); - - if( LanguageID == LANG_USA ) { - - strcpy( szWavs[0], SOUND_FILE1 ); - strcpy( szWavs[1], SOUND_FILE2 ); - - // Pick a number between 0 and 1. ( NUM_SONGS - 1 ) - // Seed the random-number generator with current time so that - // the numbers will be different every time we run. - - Msg( __LINE__, __FILE__, "szWav[0] = %s.", szWavs[0] ); - Msg( __LINE__, __FILE__, "szWav[1] = %s.", szWavs[1] ); - - srand(( unsigned )time( NULL )); - SongNumber = rand() & 1; -// UseSounds = TRUE; - - Msg( __LINE__, __FILE__, "SongNumber = %d.", SongNumber ); - Msg( __LINE__, __FILE__, "UseSounds = %d.", UseSounds ); - } - - //------------------------------------------------------------------------- - // Get the CD volume to check on which CD in the product we are on. - //------------------------------------------------------------------------- -// strcpy( szBuffer, Args->Get_argv(0)); -// CDList.Get_Volume_For_This_CD_Drive( szBuffer, szVolumeName ); - -// Msg( __LINE__, __FILE__, "szVolumeName = %s.", szVolumeName ); - - //------------------------------------------------------------------------- - // Check if we are on the CD-ROM and in Windows 95. - //------------------------------------------------------------------------- - if ( !Valid_Environment( )) { - return( -1 ); - } - - //========================================================================= - // Lock the CD! - //========================================================================= -// memset( szPath, '\0', _MAX_PATH ); -// szPath[0] = (char)( toupper( szArgvPath[0] )); -// strcat( szPath, ":\\" ); - - //------------------------------------------------------------------------- - // NOTE: Based on A=0, B=1, etc. - //------------------------------------------------------------------------- -//#if(!PRETEND_ON_CD_TEST) - char driveLetter = Args->Get_argv(0)[0]; - Msg( __LINE__, TEXT(__FILE__), TEXT("About to lock on CD: %c:\\ "), toupper( driveLetter )); -// CDLocked = CDControl.Lock_CD_Tray((unsigned)( toupper( szPath[0] ) - 'A' )); - CDLocked = CDControl.Lock_CD_Tray((unsigned)( toupper( driveLetter ) - 'A' )); - Msg( __LINE__, TEXT(__FILE__), TEXT("CDLocked = %d. "), CDLocked ); -//#endif - - //========================================================================= - // Set the buttons images. Use when images are unique for each button. - //========================================================================= - strcpy( ButtonImages[0], BUTTON_REG ); - strcpy( ButtonImages[1], BUTTON_REG ); - strcpy( ButtonImages[2], BUTTON_REG ); - strcpy( ButtonImages[3], BUTTON_REG ); - strcpy( ButtonImages[4], BUTTON_REG ); - strcpy( ButtonImages[5], BUTTON_REG ); - strcpy( ButtonImages[6], BUTTON_REG ); - strcpy( ButtonImages[7], BUTTON_REG ); - strcpy( ButtonImages[8], BUTTON_REG ); - strcpy( ButtonImages[9], BUTTON_REG ); - - strcpy( FocusedButtonImages[0], BUTTON_SEL ); - strcpy( FocusedButtonImages[1], BUTTON_SEL ); - strcpy( FocusedButtonImages[2], BUTTON_SEL ); - strcpy( FocusedButtonImages[3], BUTTON_SEL ); - strcpy( FocusedButtonImages[4], BUTTON_SEL ); - strcpy( FocusedButtonImages[5], BUTTON_SEL ); - strcpy( FocusedButtonImages[6], BUTTON_SEL ); - strcpy( FocusedButtonImages[7], BUTTON_SEL ); - strcpy( FocusedButtonImages[8], BUTTON_SEL ); - strcpy( FocusedButtonImages[9], BUTTON_SEL ); - - //========================================================================= - // A Windows class should be registered with Windows before any windows - // of that type are created. Register here all Windows classes that - // will be used in the program. - //------------------------------------------------------------------------- - // Register the class only AFTER WinMain assigns appropriate values to - // static members of Main and only if no previous instances of the program - // exist (a previous instance would have already performed the registration). - //========================================================================= - if ( !Main::hPrevInstance ) { - MainWindow::Register(); - } - - //------------------------------------------------------------------------- - // Create MainWnd, calls MainWindow Constructor. - //------------------------------------------------------------------------- - MainWindow MainWnd; - - //------------------------------------------------------------------------- - // Begin processing Window Messages. - //------------------------------------------------------------------------- - return( Main::MessageLoop( )); -} - -//***************************************************************************** -// Prog_End -- Close all objects that were created. -// -// INPUT: none. -// -// OUTPUT: int. -// -// WARNINGS: none. -// -// HISTORY: -// 01/22/2001 MML : Created. -//============================================================================= - -void Prog_End ( void ) -{ - //========================================================================== - // UnLock the CD! - //========================================================================== - if( CDLocked ) { - CDControl.Unlock_CD_Tray((unsigned)( toupper( szArgvPath[0] ) - 'A' )); - CDLocked = false; - } - - if( Args != NULL ) { - delete( Args ); - Args = NULL; - Msg( __LINE__, __FILE__, "Args deleted." ); - } - - if ( AppMutex != NULL ) { - CloseHandle( AppMutex ); - AppMutex = NULL; - Msg( __LINE__, __FILE__, "AppMutex deleted." ); - } - - if ( GameAppMutex != NULL) { - CloseHandle( GameAppMutex ); - GameAppMutex = NULL; - } - - if ( FontManager != NULL ) { - delete( FontManager ); - FontManager = NULL; - Msg( __LINE__, __FILE__, "FontManager deleted." ); - } - - if ( OnlineOptions != NULL ) { - delete( OnlineOptions ); - OnlineOptions = NULL; - Msg( __LINE__, __FILE__, "OnlineOptions deleted." ); - } - - //------------------------------------------------------------------------- - // Delete language resource file. - //------------------------------------------------------------------------- - Locale_Restore(); - - Debug_Date_And_Time_Stamp(); -} - - -//***************************************************************************** -// Main::MessageLoop -- Dispatch Message Loop. -// -// INPUT: none. -// -// OUTPUT: int. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -int Main::MessageLoop( void ) -{ - MSG msg; - - while( GetMessage( &msg, NULL, 0, 0 )) { - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } - - //-------------------------------------------------------------------------- - // Stop the sound if still going. - //-------------------------------------------------------------------------- - Stop_Sound_Playing(); - - //========================================================================== - // UnLock the CD! - //========================================================================== -//#if(!PRETEND_ON_CD_TEST) - if( CDLocked ) { - CDControl.Unlock_CD_Tray((unsigned)( toupper( szArgvPath[0] ) - 'A' )); - CDLocked = false; - } -//#endif - - //========================================================================== - // Something to launch? - //========================================================================== - if( LaunchObject.Launch_A_Program()) { - LaunchObject.Launch(); - } - - return( msg.wParam ); -} - - -//***************************************************************************** -// MainWindow::Register -- Register the Main Window. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -void MainWindow::Register( void ) -{ - //-------------------------------------------------------------------------- - // Structure used to register Windows class. - //-------------------------------------------------------------------------- - WNDCLASSEX wndclass; - - //-------------------------------------------------------------------------- - // set up and register window class - //-------------------------------------------------------------------------- - wndclass.cbSize = sizeof(WNDCLASSEX); - wndclass.style = CS_HREDRAW | CS_VREDRAW; - wndclass.lpfnWndProc = Wnd_Proc; - wndclass.cbClsExtra = 0; - - //-------------------------------------------------------------------------- - // Reserve extra bytes for each instance of the window. We will use these - // bytes to store a pointer to the C++ (MainWindow) object corresponding - // to the window. The size of a 'this' pointer depends on the memory model. - //-------------------------------------------------------------------------- - wndclass.cbWndExtra = sizeof( MainWindow * ); - wndclass.hInstance = Main::hInstance; - wndclass.hIcon = LoadIcon( Main::hInstance, MAKEINTRESOURCE(1)); - -// strcpy( szBuffer, "C&C2.ICO" ); -// wndclass.hIcon = (HICON)LoadImage( NULL, szBuffer, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_LOADFROMFILE ); - - wndclass.hCursor = LoadCursor( Main::hInstance, MAKEINTRESOURCE(2) ); - wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); - wndclass.lpszMenuName = szClassName; - wndclass.lpszClassName = szClassName; - wndclass.hIconSm = LoadIcon( Main::hInstance, MAKEINTRESOURCE(1)); - - if ( !RegisterClassEx((const WNDCLASSEX *) &wndclass ) ) { - - #if(_DEBUG) - LPVOID szMessage; - - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - GetLastError(), - MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), - (LPTSTR)&szMessage, - 0, - NULL ); - - _stprintf( szBuffer, TEXT( "%s(%lx)" ), szMessage, GetLastError()); - Msg( __LINE__, TEXT(__FILE__), TEXT("GetLastError: %s"), szBuffer ); - #endif - - exit( FALSE ); - } -} - -//***************************************************************************** -// MainWindow::MainWindow -- Main Window Constructor function. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -MainWindow::MainWindow( void ) -{ - char szTitle[ _MAX_PATH ]; - hWnd = 0; - -#ifdef LEAN_AND_MEAN - - WideCharToMultiByte( CodePage, 0, szFullProductName, _MAX_PATH, szBuffer, _MAX_PATH, NULL, NULL ); - -#else - - WideCharToMultiByte( CodePage, 0, fullProductName.str(), fullProductName.getLength()+1, szBuffer, _MAX_PATH, NULL, NULL ); - -#endif - - memset( szTitle, '\0', _MAX_PATH ); - sprintf( szTitle, CLASS_NAME, szBuffer ); - - //-------------------------------------------------------------------------- - // Create the MainWindow. - // Pass 'this' pointer in lpParam of CreateWindow(). - //-------------------------------------------------------------------------- - hWnd = CreateWindowEx( - 0, - szClassName, - szClassName, - WS_POPUPWINDOW | WS_MINIMIZE | !WS_VISIBLE, - 0, - 0, - 640, - 480, - NULL, - NULL, - Main::hInstance, - (LPTSTR) this ); - - if ( !hWnd ) { - Stop_Sound_Playing(); - exit( FALSE ); - } - - ApplicationHWnd = hWnd; - - //------------------------------------------------------------------------- - // Save the pointer so we can access it globally. - //------------------------------------------------------------------------- - GlobalMainWindow = this; - - //-------------------------------------------------------------------------- - // If you want to see the Background Window, enable these. - //-------------------------------------------------------------------------- -// Show( Main::nCmdShow ); -// Update(); -} - -//***************************************************************************** -// MainWindow::Window_Proc -- Main Window Procedure fnc to process msgs. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -LRESULT MainWindow::Window_Proc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ) -{ - static RECT rect; - static int cxChar, cyChar; - static HBRUSH hBrush = 0; - static POINT point; - int decision; - static int bits_pixel = 0; - - switch( iMessage ) { - - //----------------------------------------------------------------------- - // Create Message. - //----------------------------------------------------------------------- - case WM_CREATE: - #if(0) - hBrush = CreateSolidBrush( GetSysColor( COLOR_WINDOW )); - #endif - GetClientRect( GetDesktopWindow(), &rect ); - SendMessage( hWnd, WM_GO, wParam, lParam ); - break; - - //----------------------------------------------------------------------- - // Go! - //----------------------------------------------------------------------- - case WM_GO: - - decision = DialogBox( Main::hInstance, _TEXT( "BitmapDialog" ), hWnd, Dialog_Box_Proc ); - - if ( Args ) { - delete( Args ); - Args = NULL; - } - Stop_Sound_Playing(); - - MoveWindow( hWnd, 0, 0, 0, 0, TRUE ); - SendMessage( hWnd, WM_DESTROY, wParam, lParam ); - Msg( __LINE__, TEXT(__FILE__), TEXT("---------------------- end of WM_GO ---------------------" )); - break; - - //----------------------------------------------------------------------- - // WM_CTLCOLOR Message. - // wParam Handle to Child Window's device context - // LOWORD( lParam ) Child Window handle - // HIWORD( lParam ) Type of Window: CTLCOLOR_MSGBOX, _EDIT, _LISTBOX, _BTN, _DLG, _SCROLLBAR, _STATIC - //----------------------------------------------------------------------- - #if( WINDOW_BRUSH ) - case WM_CTLCOLOR: - if ( HIWORD( lParam ) == CTLCOLOR_BTN ) { - SetBkColor( (HDC)wParam, GetSysColor( COLOR_WINDOW )); - SetTextColor( (HDC)wParam, GetSysColor( COLOR_WINDOWTEXT )); - UnrealizeObject( hBrush ); // reset the origin of the brush next time used. - point.x = point.y = 0; // create a point. - ClientToScreen( hWnd, &point ); // translate into screen coordinates. - SetBrushOrg( (HDC)wParam, point.x, point.y ); // New Origin to use when next selected. - return ((DWORD) hBrush); - } - break; - - //----------------------------------------------------------------------- - // WM_SYSCOLORCHANGE Message. - //----------------------------------------------------------------------- - case WM_SYSCOLORCHANGE: - DeleteObject( hBrush ); - hBrush = CreateSolidBrush( GetSysColor( COLOR_WINDOW )); - break; - - //----------------------------------------------------------------------- - // WM_SIZE Message. - //----------------------------------------------------------------------- - case WM_SIZE: - rect.left = 24 * cxChar; - rect.top = 2 * cyChar; - rect.right = LOWORD( lParam ); - rect.bottom = HIWORD( lParam ); - break; - #endif - - //----------------------------------------------------------------------- - // WM_COMMAND Message. - // wParam Child Window ID - // LOWORD( lParam ) Child Window handle - // HIWORD( lParam ) Notification Code: BN_CLICKED, BN_PAINT, etc... - //----------------------------------------------------------------------- - case WM_COMMAND: - break; - - //----------------------------------------------------------------------- - // WM_DESTROY Message. - //----------------------------------------------------------------------- - case WM_DESTROY: - #if(WINDOW_BRUSH) - DeleteObject( hBrush ); - #endif - PostQuitMessage( 0 ); - break; - - default: - return DefWindowProc( hWnd, iMessage, wParam, lParam ); - } - return 0; -} - - -//***************************************************************************** -// MainWindow::Is_Product_Registered -- Check the Registration Table information. -// -// INPUT: none. -// -// OUTPUT: BOOL - TRUE if product is already installed, FALSE if not. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -BOOL MainWindow::Is_Product_Registered( void ) -{ - HKEY phKey; - BOOL result = FALSE; - - char key [_MAX_PATH]; - wchar_t szPath [_MAX_PATH]; - - unsigned long Type; - unsigned long Size = _MAX_PATH; - - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - memset( szPath, '\0', sizeof( szPath )); - memset( szGamePath, '\0', sizeof( szGamePath )); - memset( szSetupPath, '\0', sizeof( szSetupPath )); - memset( szRegisterPath, '\0', sizeof( szRegisterPath )); - memset( szInternetPath, '\0', sizeof( szInternetPath )); - memset( szUninstallPath, '\0', sizeof( szUninstallPath )); - memset( FindFileData.cFileName, '\0', sizeof( FindFileData.cFileName )); - memset( FindFileData.cAlternateFileName, '\0', sizeof( FindFileData.cAlternateFileName )); - - InstallProduct = TRUE; - UninstallAvailable = FALSE; - DisplayRegisterButton = FALSE; - IsWolapiAvailable = FALSE; - IsUserRegistered = FALSE; - - //========================================================================== - // Look for keys under the Game's Registry key. - //========================================================================== -// _tcscat( _tcscpy( key, SOFTWARE_EAGAMES_KEY ), szRegistryKey ); - _tcscat( _tcscpy( key, EAGAMES_GENERALS_KEY ), szRegistryKey ); - - //-------------------------------------------------------------------------- - // Try to open the key. - //-------------------------------------------------------------------------- - if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &phKey ) == ERROR_SUCCESS ) { - - //----------------------------------------------------------------------- - // Get Full path\filename of product to execute ("Play"). - //----------------------------------------------------------------------- - Size = _MAX_PATH; - if ( RegQueryValueEx( phKey, INSTALL_PATH_KEY, NULL, &Type, (unsigned char *)szGamePath, &Size ) == ERROR_SUCCESS ) { - _tcscpy(szWorldbuilderPath, szGamePath); - _tcscpy(szPatchgetPath, szGamePath); - _tcscat(szGamePath, LAUNCHER_FILENAME); - _tcscat(szWorldbuilderPath, WORLDBUILDER_FILENAME); - _tcscat(szPatchgetPath, PATCHGET_FILENAME); - handle = FindFirstFile( szGamePath, &FindFileData ); - if ( handle != INVALID_HANDLE_VALUE ) { - InstallProduct = FALSE; - FindClose( handle ); - } - } - Msg( __LINE__, TEXT(__FILE__), TEXT("GamePath = %s."), szGamePath ); - - RegCloseKey( phKey ); - } - - //========================================================================== - // Find Keys under "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" - //========================================================================== - - _tcscpy( key, SHELL_UNINSTALL_KEY ); - Path_Add_Back_Slash( key ); - _tcscat( key, szRegistryKey ); - - //-------------------------------------------------------------------------- - // Query the Uninstall key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall" - //-------------------------------------------------------------------------- - if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_ALL_ACCESS, &phKey ) == ERROR_SUCCESS ) { - - Size = _MAX_PATH; - if ( RegQueryValueEx( phKey, UNINSTALL_STRING_SUBKEY, NULL, &Type, (unsigned char *)szUninstallPath, &Size ) == ERROR_SUCCESS ) { - - //-------------------------------------------------------------------- - // Look for the uninstall program. If found, set flag. - //-------------------------------------------------------------------- - handle = FindFirstFile( szUninstallPath, &FindFileData ); - if ( handle != INVALID_HANDLE_VALUE ) { - UninstallAvailable = TRUE; - FindClose( handle ); - } - } - RegCloseKey( phKey ); - } - - //========================================================================== - // Look for keys under Register. If available, we should show the "Register" - // button. WESTWOOD_REGISTER_KEY "Software\\Westwood\\Register" - //========================================================================== -// _tcscpy( key, WESTWOOD_REGISTER_KEY ); - - //------------------------------------------------------------------------- - // Create IGR Options Object. - //------------------------------------------------------------------------- - IGROptionsClass *OnlineOptions = new IGROptionsClass(); - if ( OnlineOptions ) { - OnlineOptions->Init(); - } - - //-------------------------------------------------------------------------- - // If "Options" is set under WOLAPI, then this is a Game Room Edition and - // registration should NOT be allowed. - //-------------------------------------------------------------------------- - if ( OnlineOptions ) { - DisplayRegisterButton = OnlineOptions->Is_Running_Reg_App_Allowed(); - } - - //-------------------------------------------------------------------------- - // If Registration is allowed... - //-------------------------------------------------------------------------- -/* - if ( DisplayRegisterButton ) { - - DisplayRegisterButton = false; - - if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &phKey ) == ERROR_SUCCESS ) { - - //----------------------------------------------------------------------- - // Get Full path\filename of product to execute ("Register.exe"). - //----------------------------------------------------------------------- - Size = _MAX_PATH; - if ( RegQueryValueEx( phKey, INSTALLPATH_SUBKEY, NULL, &Type, (unsigned char *)szRegisterPath, &Size ) == ERROR_SUCCESS ) { - - //-------------------------------------------------------------------- - // Check if this executable exists. - //-------------------------------------------------------------------- - handle = FindFirstFile( szRegisterPath, &FindFileData ); - if ( handle != INVALID_HANDLE_VALUE ) { - DisplayRegisterButton = TRUE; - FindClose( handle ); - } - } - RegCloseKey( phKey ); - } - } -*/ - //========================================================================== - // Is WOLAPI DLL installed? - //========================================================================== -/* - _tcscpy( key, WESTWOOD_WOLAPI_KEY ); - - if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &phKey ) == ERROR_SUCCESS ) { - - //----------------------------------------------------------------------- - // Get Full path\filename of product to execute ("Register.exe"). - //----------------------------------------------------------------------- - Size = _MAX_PATH; - if ( RegQueryValueEx( phKey, INSTALLPATH_SUBKEY, NULL, &Type, (unsigned char *)szBuffer, &Size ) == ERROR_SUCCESS ) { - - //-------------------------------------------------------------------- - // Check if this executable exists. - //-------------------------------------------------------------------- - handle = FindFirstFile( szBuffer, &FindFileData ); - if ( handle != INVALID_HANDLE_VALUE ) { - IsWolapiAvailable = TRUE; - FindClose( handle ); - } - } - RegCloseKey( phKey ); - } -*/ - - Msg( __LINE__, TEXT(__FILE__), TEXT("---------------- Is_Product_Registered---------------" )); - Msg( __LINE__, TEXT(__FILE__), TEXT(" InstallProduct = %d."), InstallProduct ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" UninstallAvailable = %d."), UninstallAvailable ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" IsUserRegistered = %d."), IsUserRegistered ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" DisplayRegisterButton = %d."), DisplayRegisterButton ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" szGamePath = %s."), szGamePath ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" szSetupPath = %s."), szSetupPath ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" szRegisterPath = %s."), szRegisterPath ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" szInternetPath = %s."), szInternetPath ); - Msg( __LINE__, TEXT(__FILE__), TEXT(" szUninstallPath = %s."), szUninstallPath ); - - return( result ); -} - - -//***************************************************************************** -// MainWindow::Run_Explorer -// -// Get the Current Dir from argv[0]. Open the Explorer Window with -// this dir. The Explorer will open and display everything in this dir. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -BOOL MainWindow::Run_Explorer( const char *szString, HWND hWnd, RECT *rect ) -{ - char szWindowsPath [ _MAX_PATH ]; - char szPath [ _MAX_PATH ]; - char szCurDir [ _MAX_PATH ]; - char drive [ _MAX_DRIVE ]; - char dir [ _MAX_DIR ]; - char lpszComLine [ 127 ]; - - BOOL result = FALSE; - PROCESS_INFORMATION processinfo; - STARTUPINFO startupinfo; - - //-------------------------------------------------------------------------- - // Get current drive/directory from _argv[0]. - //-------------------------------------------------------------------------- - _tcscpy( szPath, szArgvPath ); - _tsplitpath( szPath, drive, dir, NULL, NULL ); - _tmakepath ( szPath, drive, dir, NULL, NULL ); - - //-------------------------------------------------------------------------- - // Get Windows directory and build path to Explorer. Pas in szPath as - // the directory for Explorer to open. - //-------------------------------------------------------------------------- - GetWindowsDirectory( szWindowsPath, _MAX_PATH ); - Path_Add_Back_Slash( szWindowsPath ); - - _tcscat( szWindowsPath, EXPLORER_NAME ); - _tcscat( _tcscat( _tcscpy( lpszComLine, szWindowsPath ), _TEXT( " " )), szPath ); - _tcscpy( szCurDir, szPath ); - - //========================================================================== - // Setup the call - //========================================================================== - memset( &startupinfo, 0, sizeof( STARTUPINFO )); - startupinfo.cb = sizeof( STARTUPINFO ); - - //-------------------------------------------------------------------------- - // Next, start the process - //-------------------------------------------------------------------------- - result = CreateProcess( - szWindowsPath, // address of module name - lpszComLine, // address of command line - NULL, // address of process security attributes - NULL, // address of thread security attributes - FALSE, // new process inherits handles - 0, // creation flags - NULL, // address of new environment block - szCurDir, // address of current directory name - &startupinfo, // address of STARTUPINFO - &processinfo ); // address of PROCESS_INFORMATION - - //-------------------------------------------------------------------------- - // If WinExec returned 0, error occurred. - //-------------------------------------------------------------------------- - if ( !result ) { - - Cant_Find_MessageBox ( Main::hInstance, szPath ); - - #if(BACKGROUND_BITMAP) - //----------------------------------------------------------------------- - // Recreate Buttons based on Registry, then repaint window. - //----------------------------------------------------------------------- - Create_Buttons( hWnd, rect ); - InvalidateRect( hWnd, rect, FALSE ); - #endif - } - return ( result ); -} - -//***************************************************************************** -// MainWindow::Run_Game -- Launch the game based on registry information. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_Game ( HWND hWnd, RECT *rect ) -{ - char dir [_MAX_DIR]; - char ext [_MAX_EXT]; - char drive [_MAX_DRIVE]; - char file [_MAX_FNAME]; - -// unsigned abc = 0; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - //-------------------------------------------------------------------------- - // Check if C&C is already running, and is looking for the CDRom. - // The Autorun keeps asking to "Play" when this happens. - //-------------------------------------------------------------------------- - HWND game_window = FindWindow ( szGameWindow, NULL ); - if ( game_window ){ - ShowWindow( game_window, SW_RESTORE ); - SetForegroundWindow ( game_window ); - return FALSE; - } - - //-------------------------------------------------------------------------- - // Split into parts. - //-------------------------------------------------------------------------- - _tsplitpath( szGamePath, drive, dir, file, ext ); - - //-------------------------------------------------------------------------- - // Launch the game. - //-------------------------------------------------------------------------- - handle = FindFirstFile( szGamePath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - return FALSE; - } - - FindClose( handle ); - - //----------------------------------------------------------------------- - // Stop Sound if sound was playing. - //----------------------------------------------------------------------- - Stop_Sound_Playing(); - - LaunchObject.SetPath( szGamePath ); - LaunchObject.Set_Launch( true ); - return( true ); -} - -//***************************************************************************** -// MainWindow::Run_WorldBuilder -- Launch the map editor based on registry information. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 12/02/2002 BGC : Created. -//============================================================================= - -unsigned int MainWindow::Run_WorldBuilder( HWND hWnd, RECT *rect) -{ - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - //-------------------------------------------------------------------------- - // Launch the game. - //-------------------------------------------------------------------------- - handle = FindFirstFile( szWorldbuilderPath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - return FALSE; - } - - FindClose( handle ); - - //----------------------------------------------------------------------- - // Stop Sound if sound was playing. - //----------------------------------------------------------------------- - Stop_Sound_Playing(); - - LaunchObject.SetPath( szWorldbuilderPath ); - LaunchObject.Set_Launch( true ); - return( true ); -} - -//***************************************************************************** -// MainWindow::Run_PatchGet -- Launch the patch checker based on registry information. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 12/02/2002 BGC : Created. -//============================================================================= - -unsigned int MainWindow::Run_PatchGet( HWND hWnd, RECT *rect) -{ - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - //-------------------------------------------------------------------------- - // Launch the game. - //-------------------------------------------------------------------------- - handle = FindFirstFile( szPatchgetPath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - return FALSE; - } - - FindClose( handle ); - - //----------------------------------------------------------------------- - // Stop Sound if sound was playing. - //----------------------------------------------------------------------- - Stop_Sound_Playing(); - - LaunchObject.SetPath( szPatchgetPath ); - LaunchObject.Set_Launch( true ); - return( true ); -} - -//***************************************************************************** -// MainWindow::Run_Demo -- Launch a demo program if desired. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 01/08/2002 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_Demo ( HWND hWnd, RECT *rect, int cd_drive ) -{ -// unsigned abc = 0; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - //-------------------------------------------------------------------------- - // Make path to demo program. - //-------------------------------------------------------------------------- -// Make_Current_Path_To( MOH_DEMO_PROGRAM, szBuffer ); - wsprintf( szBuffer, "%c:\\", 'A' + cd_drive ); - Path_Add_Back_Slash( szBuffer ); - strcat( szBuffer, MOH_DEMO_PROGRAM ); - - //-------------------------------------------------------------------------- - // Launch the game. - //-------------------------------------------------------------------------- - handle = FindFirstFile( szBuffer, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - Cant_Find_MessageBox( Main::hInstance, szBuffer ); - return FALSE; - } - - FindClose( handle ); - - //----------------------------------------------------------------------- - // Stop Sound if sound was playing. - //----------------------------------------------------------------------- - Stop_Sound_Playing(); - - LaunchObject.SetPath( szBuffer ); - LaunchObject.Set_Launch( true ); - return( true ); -} - -//***************************************************************************** -// MainWindow::Run_OpenFile -- Main Window function to perform Setup tasks. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_OpenFile(int cd_drive, const char *filename, bool wait /* = false */) -{ - char filepath[MAX_PATH]; - MSG msg; - BOOL returnValue; - - SHELLEXECUTEINFO executeInfo; - memset(&executeInfo, 0, sizeof(executeInfo)); - - executeInfo.cbSize = sizeof(executeInfo); - executeInfo.fMask = SEE_MASK_NOCLOSEPROCESS; - executeInfo.hwnd = ApplicationHWnd; - executeInfo.lpVerb = "open"; - executeInfo.lpFile = filename; - executeInfo.nShow = SW_SHOWNORMAL; - - HANDLE hProcess; - - - BOOL ret = ShellExecuteEx(&executeInfo); - - if ((ret == 0) || ((int)(executeInfo.hInstApp) <= 32)) { - Msg(__LINE__, TEXT(__FILE__), TEXT("Couldn't find executable for %s\n"), filepath); - return 0; - } - - hProcess = executeInfo.hProcess; - - if (wait == true) { - WaitForInputIdle(hProcess, 5000); - - bool waiting = true; - bool quit = false; - - while ((waiting == true) && (quit != true)) { - Sleep(0); - - while( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) ) - { - - // get the message - returnValue = GetMessage( &msg, NULL, 0, 0 ); - - // check for quitting - if( returnValue == 0 ) - quit = TRUE; - - // translate and dispatch the message - TranslateMessage( &msg ); - DispatchMessage( &msg ); - - } // end while - - DWORD exitCode; - GetExitCodeProcess(hProcess, &exitCode); - - if (exitCode != STILL_ACTIVE) { - waiting = false; - } - } - } - - return 1; -} - -//***************************************************************************** -// MainWindow::Run_Setup -- Main Window function to perform Setup tasks. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_Setup( HWND hWnd, RECT *rect, int cd_drive ) -{ -// UINT result = 0; - int i = 0; - char params [ 127 ]; - char filepath[ _MAX_PATH ]; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - Msg( __LINE__, TEXT(__FILE__), TEXT("---------------------- Run_Setup --------------------." )); - - //-------------------------------------------------------------------------- - // Clear these buffers for later use. - //-------------------------------------------------------------------------- - memset( params, '\0', 127 ); - - //-------------------------------------------------------------------------- - // Get Drive & Dir from ARGV[0] and create path to SETUP.EXE. - //-------------------------------------------------------------------------- -// strcpy( filepath, szArgvPath ); -// Path_Add_Back_Slash( filepath ); - - wsprintf( filepath, "%c:\\", 'A' + cd_drive ); - Path_Add_Back_Slash( filepath ); - strcat( filepath, SETUP_NAME ); - - //-------------------------------------------------------------------------- - // If we could not find SETUP.EXE, then display error msg and exit. - //-------------------------------------------------------------------------- - handle = FindFirstFile( filepath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - Cant_Find_MessageBox( Main::hInstance, filepath ); - return FALSE; - } - FindClose( handle ); - - //-------------------------------------------------------------------------- - // Create parameters to pass in with the program we are calling. - //-------------------------------------------------------------------------- - memset( params, '\0', sizeof( params )); - if ( NumberArguments ) { - - _tcscpy( params, Arguments[0] ); - i = 1; - while (( i < NUM_ARGUMENTS ) && ( i < NumberArguments )) { - _tcscat( _tcscat( params, _TEXT( " " )), Arguments[i] ); - i++; - } - } - - //-------------------------------------------------------------------------- - // Stop Sound if sound was playing. - //-------------------------------------------------------------------------- - Stop_Sound_Playing(); - - LaunchObject.SetPath( filepath ); - LaunchObject.SetArgs( params ); - LaunchObject.Set_Launch( true ); - return( true ); -} - - -//***************************************************************************** -// MainWindow::Run_New_Account -- Create a new online account. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_New_Account ( HWND hWnd, RECT *rect ) -{ -// UINT result = 0; - int i = 0; - char params [ 127 ]; - char filepath[ _MAX_PATH ]; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - //-------------------------------------------------------------------------- - // Clear these buffers for later use. - //-------------------------------------------------------------------------- - memset( params, '\0', 127 ); - - //-------------------------------------------------------------------------- - // Get Drive & Dir from ARGV[0] and create path to SETUP.EXE. - //-------------------------------------------------------------------------- - _tcscpy( filepath, szArgvPath ); - Path_Add_Back_Slash( filepath ); - _tcscat( filepath, SETUP_NAME ); - - //-------------------------------------------------------------------------- - // If we could not find SETUP.EXE, then display error msg and exit. - //-------------------------------------------------------------------------- - handle = FindFirstFile( filepath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - Cant_Find_MessageBox( Main::hInstance, SETUP_NAME ); - return FALSE; - } - FindClose( handle ); - - //-------------------------------------------------------------------------- - // Create parameters to pass in with the program we are calling. - //-------------------------------------------------------------------------- - memset( params, '\0', sizeof( params )); - if ( NumberArguments ) { - - _tcscpy( params, Arguments[0] ); - i = 1; - while (( i < NUM_ARGUMENTS ) && ( i < NumberArguments )) { - _tcscat( _tcscat( params, _TEXT( " " )), Arguments[i] ); - i++; - } - _tcscat( params, _TEXT( " " )); - } - _tcscat( params, "-o" ); - - //-------------------------------------------------------------------------- - // Stop Sound if sound was playing. - //-------------------------------------------------------------------------- - Stop_Sound_Playing(); - - LaunchObject.SetPath( filepath ); - LaunchObject.SetArgs( params ); - LaunchObject.Set_Launch( true ); - return( true ); -} - - -//***************************************************************************** -// MainWindow::Run_Register_Or_Auto_Update -// -// Either run Register.exe or Game Update Program from the user's harddrive. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 02/24/1999 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_Register ( HWND hWnd, RECT *rect ) -{ - char szArgs[ MAX_PATH ]; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - BOOL result = FALSE; - - //-------------------------------------------------------------------------- - // Register Program is available. Continue... - //-------------------------------------------------------------------------- - if ( DisplayRegisterButton ) { - - //----------------------------------------------------------------------- - // Check again. May have been changed ... - //----------------------------------------------------------------------- - handle = FindFirstFile( szRegisterPath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - return( 0 ); - } - FindClose( handle ); - - //----------------------------------------------------------------------- - // User is already registered, so maybe we should Auto Update! - //----------------------------------------------------------------------- - strcpy( szArgs, _TEXT( " " )); - - LaunchObject.SetPath( szRegisterPath ); - LaunchObject.SetArgs( szArgs ); - LaunchObject.Set_Launch( true ); - result = true; - } - - return( result ); -} - -//***************************************************************************** -// MainWindow::Run_Auto_Update -// -// Either run Register.exe or Game Update Program from the user's harddrive. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 02/24/1999 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_Auto_Update ( HWND hWnd, RECT *rect ) -{ - char szArgs [ MAX_PATH ]; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - BOOL result = FALSE; - - //-------------------------------------------------------------------------- - // Register Program is available. Continue... - //-------------------------------------------------------------------------- - if ( !InstallProduct ) { - - //----------------------------------------------------------------------- - // Check again. May have been changed ... - //----------------------------------------------------------------------- - handle = FindFirstFile( szGamePath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - return( 0 ); - } - FindClose( handle ); - - _tcscpy( szArgs, _TEXT( " GrabPatches" )); - - LaunchObject.SetPath( szGamePath ); - LaunchObject.SetArgs( szArgs ); - LaunchObject.Set_Launch( true ); - result = true; - } - return( result ); -} - - -//***************************************************************************** -// MainWindow::Run_Uninstall -- Main Window function to perform Setup tasks. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -unsigned int MainWindow::Run_Uninstall( HWND hWnd, RECT *rect ) -{ - MSG msg; - UINT result = 0; -// int done = 0; - DWORD dwTimeout = 1500; - DWORD dwRC = WAIT_TIMEOUT; - DWORD lpExitCode; - - STARTUPINFO startupinfo; - PROCESS_INFORMATION processinfo; - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - char szCurDir [_MAX_PATH]; - char file [_MAX_FNAME]; - char ext [_MAX_EXT]; - char szPath [_MAX_PATH]; - - //-------------------------------------------------------------------------- - // Launch the UNINSTALL. - //-------------------------------------------------------------------------- - handle = FindFirstFile( szUninstallPath, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - return( 0 ); - } - - FindClose( handle ); - - _splitpath( szUninstallPath, drive, dir, NULL, NULL ); - _makepath ( szCurDir, drive, dir, NULL, NULL ); - - //======================================================================= - // Setup the call - //======================================================================= - memset( &startupinfo, 0, sizeof( STARTUPINFO )); - startupinfo.cb = sizeof( STARTUPINFO ); - - result = CreateProcess( - szUninstallPath, // address of module name - szUninstallPath, // address of command line - NULL, // address of process security attributes - NULL, // address of thread security attributes - 0, // new process inherits handles - 0, - NULL, // address of new environment block -// _TEXT("."), - szCurDir, - &startupinfo, // address of STARTUPINFO - &processinfo ); // address of PROCESS_INFORMATION - - //-------------------------------------------------------------------------- - // If WinExec returned 0, error occurred. - //-------------------------------------------------------------------------- - if ( !result ) { - - _tsplitpath( szUninstallPath, NULL, NULL, file, ext ); - _tmakepath ( szPath, NULL, NULL, file, ext ); - Cant_Find_MessageBox ( Main::hInstance, szPath ); - -// #if(BACKGROUND_BITMAP) - //----------------------------------------------------------------------- - // Recreate Buttons based on Registry, then repaint window. - //----------------------------------------------------------------------- -// Create_Buttons( hWnd, rect ); -// InvalidateRect( hWnd, rect, FALSE ); -// #endif - - return( result ); - } - - //-------------------------------------------------------------------------- - // Wait for App to shutdown - //-------------------------------------------------------------------------- - while (dwRC == WAIT_TIMEOUT) { - - //----------------------------------------------------------------------- - // Wait for object - //----------------------------------------------------------------------- - dwRC = WaitForSingleObject( processinfo.hProcess, dwTimeout ); - - //----------------------------------------------------------------------- - // Flush the Queue - //----------------------------------------------------------------------- - while (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE )) { - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } - } - - //-------------------------------------------------------------------------- - // If the specified process has not terminated, the termination status - // returned is STILL_ACTIVE. - //-------------------------------------------------------------------------- - GetExitCodeProcess( processinfo.hProcess, &lpExitCode ); - CloseHandle( processinfo.hProcess ); - CloseHandle( processinfo.hThread ); - -#if(BACKGROUND_BITMAP) - - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // MML 5/27/99: This function is dropping through because we launch Uninstll.exe - // which in turn launches Uninst.exe thus ::Run_Install ends before Uninst.exe is done. - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - //-------------------------------------------------------------------------- - // Recreate Buttons based on Registry. - // Repaint calling Window. - //-------------------------------------------------------------------------- - Create_Buttons( hWnd, rect ); - InvalidateRect( hWnd, rect, FALSE ); -#endif - - return( result ); -} - -//***************************************************************************** -// MainWindow::Create_Buttons -- Reset the Buttons. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -void MainWindow::Create_Buttons( HWND hWnd, RECT *dlg_rect ) -{ - int j = 0; - int i = 0; - int x_pos = 0; - int y_pos = 0; - int width = 0; - int height = 0; -// int avg_width = 0; -// int space_between = 5; - int button_index = 0; - - HBITMAP hButtonBitmap = 0; - HPALETTE hpal = 0; - BITMAP button_bm; - char next_button_name[_MAX_PATH]; - char focused_button_name[_MAX_PATH]; - RECT * button_size = ButtonSizes; - - //-------------------------------------------------------------------------- - // Reset all the flags. - //-------------------------------------------------------------------------- - Is_Product_Registered( ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("------------------------ Create_Buttons ------------------------" )); - - //-------------------------------------------------------------------------- - // Get width and height of the button. - //-------------------------------------------------------------------------- - hButtonBitmap = LoadResourceBitmap( Main::hModule, BUTTON_REG, &hpal, TRUE ); - if ( hButtonBitmap ) { - GetObject( hButtonBitmap, sizeof( BITMAP ), (LPTSTR)&button_bm ); - width = button_bm.bmWidth; - height = button_bm.bmHeight; - DeleteObject( hButtonBitmap ); - hButtonBitmap = 0; - } else { - button_bm.bmWidth = width = BUTTON_WIDTH; - button_bm.bmHeight = height = BUTTON_HEIGHT; - } - - //-------------------------------------------------------------------------- - // Initialize the ButtonList. - //-------------------------------------------------------------------------- - if( b640X480 || b800X600 ) { - -// x_pos = 0; -// y_pos = 340; - x_pos = 410; - y_pos = 90; -// width = 123; -// height = 42; - - } else { - x_pos = 540; - y_pos = 117; - } - - for ( i = 0; i < NUM_BUTTONS; i++ ) { - - if ( ButtonList[i] ) { - delete( ButtonList[i] ); - } - ButtonList[i] = NULL; - ButtonSizes[i].left = x_pos; // X position. - ButtonSizes[i].top = y_pos; // Y position. - ButtonSizes[i].right = width; // Button's width. - ButtonSizes[i].bottom = height; // Button's height. -// x_pos -= /*height*/ 16; - y_pos += height + 4; - - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonSizes[%d] = ( %d, %d, %d, %d )"), - i, ButtonSizes[i].left, ButtonSizes[i].top, ButtonSizes[i].right, ButtonSizes[i].bottom ); - } - - //========================================================================== - // Create the "Buttons" - //========================================================================== -// i = NUM_BUTTONS-1; -// j = NUM_BUTTONS-1; - i = 0; - j = 0; - - //-------------------------------------------------------------------------- - // Make any other necessary adjustments here. - //-------------------------------------------------------------------------- - int count = 7; - - if ( !UninstallAvailable ) { - count--; // No uninstall button. - } - if ( InstallProduct ) { - count--; // No Website button. - } -// button_index = NUM_BUTTONS - (( NUM_BUTTONS - count ) / 2 ) - 1; - button_index = 0; - - strcpy( next_button_name, ButtonImages[button_index] ); - strcpy( focused_button_name, FocusedButtonImages[button_index] ); - - button_size = ButtonSizes; - i = j = button_index; -// button_index--; - - Msg( __LINE__, TEXT(__FILE__), TEXT("count = %d."), count ); - Msg( __LINE__, TEXT(__FILE__), TEXT("button_index = %d."), button_index ); - Msg( __LINE__, TEXT(__FILE__), TEXT("next_button_name = %s."), next_button_name ); - Msg( __LINE__, TEXT(__FILE__), TEXT("focused_button_name = %s."), focused_button_name ); - - - //------------------------------------------------------------------------- - // INSTALL or PLAY? - //------------------------------------------------------------------------- - if ( InstallProduct ) { - - //--------------------------------------------------------------------- - // (8) INSTALL button. - //--------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_OK, j, "Install" ); - ButtonList[i++] = new DrawButton( - IDD_OK, - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Install" ), -#else - AsciiString("Autorun:Install"), -#endif - TTButtonFontPtr ); - - } else { - - //--------------------------------------------------------------------- - // (8) PLAY button. - //--------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_OK2, j, "Play" ); - ButtonList[i++] = new DrawButton( - IDD_OK2, - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Play" ), -#else - AsciiString("Autorun:Play"), -#endif - TTButtonFontPtr ); -/* - //--------------------------------------------------------------------- - // (8) WorldBuilder button. - //--------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_OK2, j, "WorldBuilder" ); -// ButtonList[i--] = new DrawButton( - ButtonList[i++] = new DrawButton( - IDD_OK3, -// button_size[j--], - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Worldbuilder" ), -#else - AsciiString("Autorun:Worldbuilder"), -#endif - TTButtonFontPtr ); -*/ - //--------------------------------------------------------------------- - // (8) Check for updates button. - //--------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_OK2, j, "Check For Updates" ); -// ButtonList[i--] = new DrawButton( - ButtonList[i++] = new DrawButton( - IDD_OK4, -// button_size[j--], - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:CheckForUpdates" ), -#else - AsciiString("Autorun:CheckForUpdates"), -#endif - TTButtonFontPtr ); - } - - //------------------------------------------------------------------------- - // (7) EXPLORE CD - //------------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_EXPLORE, j, "Explore" ); -// ButtonList[i--] = new DrawButton ( - ButtonList[i++] = new DrawButton ( - IDD_EXPLORE, -// button_size[j--], - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:ExploreCD" ), -#else - AsciiString("Autorun:ExploreCD"), -#endif - TTButtonFontPtr ); -// strcpy( next_button_name, ButtonImages[button_index] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index--] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index++] ); - - if ( !InstallProduct ) { - //----------------------------------------------------------------------- - // (3) WebSite button. - //----------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_OK, j, "Install" ); -// ButtonList[i--] = new DrawButton( - ButtonList[i++] = new DrawButton( - IDD_INTERNET, -// button_size[j--], - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Website" ), -#else - AsciiString("Autorun:Website"), -#endif - TTButtonFontPtr ); - -// strcpy( next_button_name, ButtonImages[button_index] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index--] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index++] ); - } - - //-------------------------------------------------------------------------- - // (2) UNINSTALL? - //-------------------------------------------------------------------------- - if ( UninstallAvailable && !InstallProduct ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_UNINSTALL, j, "Uninstall" ); -// ButtonList[i--] = new DrawButton( - ButtonList[i++] = new DrawButton( - IDD_UNINSTALL, -// button_size[j--], - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Uninstall" ), -#else - AsciiString("Autorun:Uninstall"), -#endif - TTButtonFontPtr ); - -// strcpy( next_button_name, ButtonImages[button_index] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index--] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index++] ); - } - - //-------------------------------------------------------------------------- - // (1) MOH movie - //-------------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_PREVIEWS, j, "Preview Movies"); - ButtonList[i++] = new DrawButton( - IDD_PREVIEWS, - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Previews" ), -#else - AsciiString("Autorun:Previews"), -#endif - TTButtonFontPtr ); - - //-------------------------------------------------------------------------- - // (1) Help file - //-------------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_HELP, j, "Help file"); - ButtonList[i++] = new DrawButton( - IDD_HELP, - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Help" ), -#else - AsciiString("Autorun:Help"), -#endif - TTButtonFontPtr ); - - //-------------------------------------------------------------------------- - // (1) CANCEL? - //-------------------------------------------------------------------------- - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonList[%d]: Id=%d, ButtonSizes=%d, String=%s."), i, IDD_CANCEL, j, "Cancel" ); -// ButtonList[i--] = new DrawButton( - ButtonList[i++] = new DrawButton( - IDD_CANCEL, -// button_size[j--], - button_size[j++], - BUTTON_REG, - BUTTON_SEL, - BUTTON_SEL, -#ifdef LEAN_AND_MEAN - Locale_GetString( "Autorun:Cancel" ), -#else - AsciiString("Autorun:Cancel"), -#endif - TTButtonFontPtr ); - -// strcpy( next_button_name, ButtonImages[button_index] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index--] ); -// strcpy( focused_button_name, FocusedButtonImages[button_index++] ); - - //------------------------------------------------------------------------- - // Set the top button to have the focus. - //------------------------------------------------------------------------- - if ( ButtonList[0]) { - Msg( __LINE__, TEXT(__FILE__), TEXT("Button with starting Focus = %d"), i ); - ButtonList[0]->Set_State( DrawButton::FOCUS_STATE ); - } - -#if( _DEBUG ) - Msg( __LINE__, TEXT(__FILE__), TEXT("----------------------------------------------------------------------------------")); - for( i=0; iReturn_Id(), - ButtonList[i]->Return_X_Pos(), - ButtonList[i]->Return_Y_Pos(), - ButtonList[i]->Return_Width(), - ButtonList[i]->Return_Height()); - } - } -#endif -} - - -//***************************************************************************** -// WndProc -- Get Main Window's Stored Word. -// -// INPUT: HWND hWnd. -// Window *pWindow -// -// OUTPUT: none. -// -// WARNINGS: none. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -LRESULT CALLBACK Wnd_Proc ( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ) -{ - //-------------------------------------------------------------------------- - // If the GlobalMainWindow Ptr is not initialized, do it when the MW-CREATE - // msg is called. Then we use the GlobalMainWindow's WindowProc to - // process all the individual msgs sent. - //-------------------------------------------------------------------------- - if ( GlobalMainWindow == NULL ) { - if ( iMessage == WM_CREATE ) { - - LPCREATESTRUCT lpcs; - - lpcs = (LPCREATESTRUCT) lParam; - GlobalMainWindow = (MainWindow *) lpcs->lpCreateParams; - - //----------------------------------------------------------------- - // Now let the object perform whatever initialization it needs - // for WM_CREATE in its own WndProc. - //----------------------------------------------------------------- - return GlobalMainWindow->Window_Proc( hWnd, iMessage, wParam, lParam ); - - } else { - return DefWindowProc( hWnd, iMessage, wParam, lParam ); - } - - } else { - return GlobalMainWindow->Window_Proc( hWnd, iMessage, wParam, lParam ); - } -} - -//***************************************************************************** -// DIALOG_BOX_PROC -- Handles dlg messages -// -// INPUT: standard windows dialog command parameters -// -// OUTPUT: unused -// -// WARNINGS: none -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -BOOL CALLBACK Dialog_Box_Proc( HWND window_handle, UINT message, WPARAM w_param, LPARAM l_param ) -{ - int i = 0, j = 0; - int nResult = 0; -// int space_between = 5; - int prevDCStretchMode; - int prevMemDCStretchMode; - int prevButtonDCStretchMode; - int prevLicenseDCStretchMode; - int result = 0; - char buffer1[ 50 ]; -// char buffer2[ 50 ]; - - HDC hDC, memDC, buttonDC, licenseDC; - BITMAP bm, fm, lm; -// LOGPALETTE * plgpl = NULL; - PAINTSTRUCT ps; - static int bits_pixel = 0; - static int idCtl = 0; - static int mouse_x, mouse_y; - - static char szBitmap[_MAX_PATH]; - static char szLicense[ _MAX_PATH ]; - static char szButtonBitmap[_MAX_PATH]; - - static wchar_t szString1[ 500 ]; - static wchar_t szString2[ 500 ]; - static wchar_t szWholeString[ 1000 ]; -// static wchar_t szWSMsg1[ _MAX_PATH ]; - -#ifdef LEAN_AND_MEAN - -#else - static UnicodeString wsMsg1; -#endif - - static wchar_t szWSMsg2[ _MAX_PATH ]; - static wchar_t szWholeWSMsg[ 1000 ]; -// static wchar_t szInstallWarningMsg[ _MAX_PATH ]; - - static HBITMAP hBitmap = 0; - static HBITMAP oldBitmap = 0; -// static HBITMAP oldButtonBitmap = 0; - static HBITMAP oldLicenseBitmap = 0; - static HBITMAP hButtonBitmap = 0; - static HBITMAP hFlicker[NUM_FLICKER_FRAMES]; - static HBITMAP hLicenseBitmap; - - static POINT point; - static HBRUSH hStaticBrush = 0; - static HPALETTE hpal = 0; - static HPALETTE hpalold = 0; - static BOOL FirstTime = TRUE; -// static BOOL Flicker = TRUE; - static BOOL Flicker = FALSE; - static int FlickerIndex = 0; - static BOOL PaintOnlyFlicker = TRUE; - static BOOL PaintBackground = TRUE; - static UINT timer_id = 0; - static RECT rect; // Desktop Window ( used once ). - static RECT tray_rect; // Desktop Window w/o Tray size. - static RECT paint_rect; // Size that needs to be repainted. - static RECT dlg_rect; // Dialog client window size. - static RECT bitmap_rect; // Background bitmap size. - static RECT flicker_rect; // Flicker bitmap size. - static RECT buttons_rect; // Area where buttons are. - static RECT license_rect; // Area where buttons are. - static RECT BackgroundRect[ ( NUM_BUTTONS * 3 ) + 3 ]; // Background areas outside button area. - -#if(USE_MOUSE_MOVES) - static int CurrentButton = 0; - static int LastButton = 0; - static int PrevButton = 0; -#endif - - #if(0) - { - //------------------------------------------------------------------------------- - // Used for debugging -- lining up objects using the mouse coordinates. - //------------------------------------------------------------------------------- - int i = 0; - HDC hdc = GetDC( window_handle ); - char string[10]; - POINT pPoint; - - GetCursorPos( &pPoint ); - ScreenToClient( window_handle, &pPoint ); - sprintf( string, "%d, %d", pPoint.x, pPoint.y ); - TextOut( hdc, 10, 50, string, 8 ); - ReleaseDC( window_handle, hdc ); - } - #endif - - - //----------------------------------------------------------------------------------- - // Process Dialogs messages. - //----------------------------------------------------------------------------------- - switch( message ) { - - case WM_INITDIALOG: - { - //----------------------------------------------------------------------- - // Set dialog's caption. - //----------------------------------------------------------------------- - -#ifdef LEAN_AND_MEAN - - Locale_GetString( "Autorun:Title", szWideBuffer ); - memset( szWideBuffer2, '\0', _MAX_PATH ); - swprintf( szWideBuffer2, szWideBuffer, szProductName ); - swprintf( szWideBuffer2, szWideBuffer, szFullProductName ); - -#else - - wideBuffer = TheGameText->fetch("Autorun:Title"); - wideBuffer2.format(wideBuffer, fullProductName.str()); - WideCharToMultiByte( CodePage, 0, wideBuffer2.str(), wideBuffer2.getLength()+1, szBuffer, _MAX_PATH, NULL, NULL ); - -#endif - - - SetWindowText( window_handle, szBuffer ); - - //----------------------------------------------------------------------- - // Set Icon. - //----------------------------------------------------------------------- - SendMessage( window_handle, WM_SETICON, ICON_SMALL, (long)LoadIcon( Main::hInstance, MAKEINTRESOURCE(1))); - - #if(BACKGROUND_BITMAP) - - //----------------------------------------------------------------------- - // Get the DeskTop's size and this dialogs size (in pixels). - //----------------------------------------------------------------------- - GetClientRect( GetDesktopWindow(), &rect ); - SystemParametersInfo( SPI_GETWORKAREA, 0, &tray_rect, 0 ); - -/// if( rect.right <= 640 ) { -// b640X480 = TRUE; -// } else if( rect.right <= 800 ) { - b800X600 = TRUE; -// } - - //======================================================================= - // Create Fonts. - //======================================================================= - HDC hdc = GetDC( window_handle ); - - FontManager = new FontManagerClass( hdc ); - assert( FontManager != NULL ); - ReleaseDC( window_handle, hdc ); - - //======================================================================= - // Load messages for bottom of screen. - //======================================================================= -// memset( szString1, '\0', MAX_PATH ); -// memset( szString2, '\0', MAX_PATH ); -// memset( szWholeString, '\0', 1000 ); - -// Locale_GetString( EA_LICENSE_MSG1, szString1 ); -// Locale_GetString( EA_LICENSE_MSG2, szString2 ); -// swprintf( szWholeString, L"%s %s", szString1, szString2 ); - -// memset( szWSMsg1, '\0', _MAX_PATH ); - memset( szWSMsg2, '\0', _MAX_PATH ); - memset( szWholeWSMsg, '\0', 1000 ); - -// Locale_GetString( WESTWOOD_COM_MSG, szWSMsg1 ); -// wsMsg1 = TheGameText->fetch("Autorun:WestwoodComMsg"); - -// PlugInProductName( szWSMsg1, (wchar_t *)(fullProductName.str()) ); -// PlugInProductName( (wchar_t *)(wsMsg1.str()), (wchar_t *)(fullProductName.str()) ); -// wsMsg1 = Fix_Single_Ampersands ( wsMsg1, false ); -// swprintf( szWholeWSMsg, L"%s", wsMsg1.str() ); - -// memset( szInstallWarningMsg, '\0', _MAX_PATH ); - -// Locale_GetString( IDS_INSTALL_WARNING_MSG, szWideBuffer ); -// wideBuffer = TheGameText->fetch("Autorun:InstallWarningMsg"); - -// swprintf( szInstallWarningMsg, wideBuffer.str(), fullProductName.str() ); - - //======================================================================= - // Load the correct background & animation bitmap. - //======================================================================= - memset( buffer1, '\0', sizeof( buffer1 )); - - if( b640X480 ) { - - strcpy( szBitmap, _TEXT( "Background2" )); - - if ( LANG_FRE == LanguageID ) { - strcpy( szLicense, _TEXT( "License_FRENCH2" )); - } else if ( LANG_GER == LanguageID ) { - strcpy( szLicense, _TEXT( "License_GERMAN2" )); - } else { - strcpy( szLicense, _TEXT( "License_USA2" )); - } - license_rect.left = 186; - license_rect.top = 414; - - } else if( b800X600 ) { - - strcpy( szBitmap, _TEXT( "Background" )); - - if ( LANG_FRE == LanguageID ) { - strcpy( szLicense, _TEXT( "License_FRENCH2" )); - } else if ( LANG_GER == LanguageID ) { - strcpy( szLicense, _TEXT( "License_GERMAN2" )); - } else { - strcpy( szLicense, _TEXT( "License_USA2" )); - } - license_rect.left = 186; - license_rect.top = 414; - - } else { - - strcpy( szBitmap, _TEXT( "Background" )); - strcpy( buffer1, "FLICKER" ); - - if ( LANG_FRE == LanguageID ) { - strcpy( szLicense, _TEXT( "License_FRENCH" )); - } else if ( LANG_GER == LanguageID ) { - strcpy( szLicense, _TEXT( "License_GERMAN" )); - } else { - strcpy( szLicense, _TEXT( "License_USA" )); - } - license_rect.left = 238; - license_rect.top = 580; - } - - //======================================================================= - // Load flicker bitmap. - //======================================================================= - for( i = 0; i < NUM_FLICKER_FRAMES; i++ ) { - hFlicker[i] = 0; -// sprintf( buffer2, "%s%02d", buffer1, i ); -// hFlicker[i] = LoadResourceBitmap( Main::hModule, buffer2, &hpal ); - hFlicker[i] = LoadResourceBitmap( Main::hModule, buffer1, &hpal ); - } - - //----------------------------------------------------------------------- - // Get the flicker bitmap's dimensions. - //----------------------------------------------------------------------- - result = 712; - - for( i = 0; i < NUM_FLICKER_POSITIONS; i++ ) { - if( i == 8 ) { - FlickerPositions[i][0] = result - 33; - } else if( i == 9 ) { - FlickerPositions[i][0] = result - 35; - } else if ( i > 8 ) { - FlickerPositions[i][0] = result - 28; - } else { - FlickerPositions[i][0] = result - 31; - } - FlickerPositions[i][1] = 560; - result = FlickerPositions[i][0]; - } - - if ( hFlicker[0] ) { - GetObject( hFlicker[0], sizeof( BITMAP ), (LPTSTR)&fm ); - flicker_rect.left = FlickerPositions[0][0]; - flicker_rect.top = FlickerPositions[0][1]; - flicker_rect.right = flicker_rect.left + fm.bmWidth; - flicker_rect.bottom = flicker_rect.top + fm.bmHeight; - } - - //----------------------------------------------------------------------- - // Get the bitmap's dimensions. - //----------------------------------------------------------------------- - hLicenseBitmap = LoadResourceBitmap( Main::hModule, szLicense, &hpal ); - if ( hLicenseBitmap ) { - GetObject( hLicenseBitmap, sizeof( BITMAP ), (LPTSTR)&lm ); - license_rect.right = license_rect.left + lm.bmWidth; - license_rect.bottom = license_rect.top + lm.bmHeight; - } - - //======================================================================= - // Load background bitmap. - //======================================================================= - hBitmap = LoadResourceBitmap( Main::hModule, szBitmap, &hpal ); - if ( hBitmap ) { - GetObject( hBitmap, sizeof( BITMAP ), (LPTSTR)&bm ); - } - - //----------------------------------------------------------------------- - // Set the x, y, width, height of the Dialog and bitmaps dimensions. - //----------------------------------------------------------------------- - bitmap_rect.left = dlg_rect.left = 0; - bitmap_rect.top = dlg_rect.top = 0; - bitmap_rect.right = dlg_rect.right = bm.bmWidth; - bitmap_rect.bottom = dlg_rect.bottom = bm.bmHeight; - - //----------------------------------------------------------------------- - // Set the x, y, width, height of the Dialog and bitmaps dimensions. - //----------------------------------------------------------------------- - dlg_rect.left = 0; - dlg_rect.top = 0; - - if( b640X480 ) { - dlg_rect.right = rect.right; - dlg_rect.bottom = tray_rect.bottom; // desktop smaller than image - } else if( b800X600 ) { - if(true){ - dlg_rect.right = bm.bmWidth + 6; - dlg_rect.bottom = bm.bmHeight + GetSystemMetrics( SM_CYCAPTION ) + 6; // desktop larger than image - } else { - dlg_rect.right = 640;//bm.bmWidth + 6; - dlg_rect.bottom = 480; //bm.bmHeight + GetSystemMetrics( SM_CYCAPTION ) + 6; // desktop larger than image - } - } else { - dlg_rect.right = bm.bmWidth + 6; - dlg_rect.bottom = bm.bmHeight + GetSystemMetrics( SM_CYCAPTION ) + 6; // desktop larger than image - } - - //======================================================================= - // Recreate Buttons based on Registry. - //======================================================================= - GlobalMainWindow->Create_Buttons( window_handle, &dlg_rect ); - - //======================================================================= - // Set Main Rectangle Areas around all the Buttons. - //======================================================================= - - //----------------------------------------------------------------------- - // Who is the first button? - //----------------------------------------------------------------------- - i = 0; - while ( i < NUM_BUTTONS ) { - if ( ButtonList[i] == NULL ) { - i++; - } else { - break; - } - } - - if( i >= NUM_BUTTONS || i < 0 ) { - i = 0; - } - - Msg( __LINE__, TEXT(__FILE__), TEXT("----------------------------- determining button area ---------------------------" )); - - buttons_rect.left = ButtonSizes[i].left; - buttons_rect.top = ButtonSizes[i].top; - buttons_rect.right = ButtonSizes[i].left + ButtonSizes[i].right; - buttons_rect.bottom = ButtonSizes[i].top + ButtonSizes[i].bottom; - -// Msg( __LINE__, TEXT(__FILE__), TEXT("buttons_rect = [%d,%d,%d,%d]"), buttons_rect.left, buttons_rect.top, buttons_rect.right, buttons_rect.bottom ); - - for( j = 0; j < NUM_BUTTONS; j++ ) { - if ( ButtonList[j] != NULL ) { - buttons_rect.left = __min( ButtonSizes[j].left , buttons_rect.left ); - buttons_rect.top = __min( ButtonSizes[j].top , buttons_rect.top ); - buttons_rect.right = __max( ButtonSizes[j].left + ButtonSizes[j].right , buttons_rect.right ); - buttons_rect.bottom = __max( ButtonSizes[j].top + ButtonSizes[j].bottom , buttons_rect.bottom ); - } - } - - Msg( __LINE__, TEXT(__FILE__), TEXT("buttons_rect = [%d,%d,%d,%d]"), buttons_rect.left, buttons_rect.top, buttons_rect.right, buttons_rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT("----------------------------- determining button area ---------------------------" )); - - //======================================================================= - // Center the dialog on the desktop. - //======================================================================= - if ( !b640X480 ) { - MoveWindow( window_handle, - ( rect.right - dlg_rect.right )/2, - ( rect.bottom - dlg_rect.bottom )/2, - dlg_rect.right, - dlg_rect.bottom, TRUE ); - } else { - MoveWindow( window_handle, - 0, 0, - dlg_rect.right, - dlg_rect.bottom, TRUE ); - } - - //----------------------------------------------------------------------- - // Get the new Client area. - //----------------------------------------------------------------------- - GetClientRect( window_handle, &dlg_rect ); - - //======================================================================= - // These are the areas of the Background to paint minus the Button Area. - // This will prevent "flickering". - //======================================================================= - BackgroundRect[0].left = dlg_rect.left; - BackgroundRect[0].top = dlg_rect.top; - BackgroundRect[0].right = dlg_rect.right; - BackgroundRect[0].bottom = buttons_rect.top; - - BackgroundRect[1].left = dlg_rect.left; - BackgroundRect[1].top = buttons_rect.top; - BackgroundRect[1].right = buttons_rect.left; - BackgroundRect[1].bottom = dlg_rect.bottom; - - BackgroundRect[2].left = buttons_rect.left; - BackgroundRect[2].top = buttons_rect.bottom; - BackgroundRect[2].right = buttons_rect.right; - BackgroundRect[2].bottom = dlg_rect.bottom; - - BackgroundRect[3].left = buttons_rect.right; - BackgroundRect[3].top = buttons_rect.top; - BackgroundRect[3].right = dlg_rect.right; - BackgroundRect[3].bottom = dlg_rect.bottom; - - //======================================================================= - // Find Areas that are in between, infront of, and behind each Buttons. - //======================================================================= - i = 0; - j = 4; - - //----------------------------------------------------------------------- - // Who is the first button? - //----------------------------------------------------------------------- - while ( i < NUM_BUTTONS ) { - if ( ButtonList[i] == NULL ) { - i++; - } else { - break; - } - } - - if( i >= NUM_BUTTONS || i < 0 ) { - i = 0; - } - - //----------------------------------------------------------------------- - // For each button... - //----------------------------------------------------------------------- - int index = i; - for( ; index < NUM_BUTTONS; index++ ) { - - //------------------------------------------------------------------- - // Make areas between the buttons. - //------------------------------------------------------------------- - if ( ButtonList[index] != NULL && ButtonList[index+1] != NULL ) { - - // Area between buttons. - BackgroundRect[j].top = ButtonList[index]->Return_Y_Pos() + ButtonList[index]->Return_Height(); - BackgroundRect[j].bottom = ButtonList[index+1]->Return_Y_Pos() - BackgroundRect[j].top; - BackgroundRect[j].left = BackgroundRect[1].right; - BackgroundRect[j].right = BackgroundRect[3].left - BackgroundRect[1].left - 1; - j++; - } - - //------------------------------------------------------------------- - // Now look for areas in front of and behind each button. - //------------------------------------------------------------------- - if ( ButtonList[index] != NULL ) { - - // Area in front of buttons. - BackgroundRect[j].top = ButtonList[index]->Return_Y_Pos(); - BackgroundRect[j].bottom = ButtonList[index]->Return_Height(); - BackgroundRect[j].left = BackgroundRect[1].right; - BackgroundRect[j].right = ButtonList[index]->Return_X_Pos() - BackgroundRect[1].right; - j++; - - // Area behind buttons. - BackgroundRect[j].top = ButtonList[index]->Return_Y_Pos(); - BackgroundRect[j].bottom = ButtonList[index]->Return_Height(); - BackgroundRect[j].left = ButtonList[index]->Return_X_Pos() + ButtonList[index]->Return_Width(); - BackgroundRect[j].right = BackgroundRect[3].left - ( ButtonList[index]->Return_X_Pos() + ButtonList[index]->Return_Width()); - j++; - } - } - - #if(_DEBUG) - Msg( __LINE__, TEXT(__FILE__), TEXT("----------------------------- WM_INITDIALOG ---------------------------" )); - Msg( __LINE__, TEXT(__FILE__), TEXT("DeskTopWindowRect(w/o tray) = [%d,%d,%d,%d]"), tray_rect.left, tray_rect.top, tray_rect.right, tray_rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT("DeskTopWindowRect = [%d,%d,%d,%d]"), rect.left, rect.top, rect.right, rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT("b640X480 = [%d]"), b640X480 ); - Msg( __LINE__, TEXT(__FILE__), TEXT("b800X600 = [%d]"), b800X600 ); - Msg( __LINE__, TEXT(__FILE__), TEXT("ClientRect = [%d,%d,%d,%d]"), dlg_rect.left, dlg_rect.top, dlg_rect.right, dlg_rect.bottom ); - - for( index = 0; index < ( NUM_BUTTONS * 3 ) + 3; index++ ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("BackgroundRect[%d] = [%d,%d,%d,%d]"), index, BackgroundRect[index].top, BackgroundRect[index].bottom, BackgroundRect[index].left, BackgroundRect[index].right ); - } - - Msg( __LINE__, TEXT(__FILE__), TEXT("BitmapRect = [%d,%d,%d,%d]"), bitmap_rect.left, bitmap_rect.top, bitmap_rect.right, bitmap_rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT("FlickerRect = [%d,%d,%d,%d]"), flicker_rect.left, flicker_rect.top, flicker_rect.right, flicker_rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT("ButtonsRect = [%d,%d,%d,%d]"), buttons_rect.left, buttons_rect.top, buttons_rect.right, buttons_rect.bottom ); - Msg( __LINE__, TEXT(__FILE__), TEXT("-----------------------------------------------------------------------" )); - #endif - - #else - - //----------------------------------------------------------------------- - // Create Brush. - //----------------------------------------------------------------------- - hStaticBrush = CreateSolidBrush( RGB( 192, 192, 192 )); - - #endif - - //======================================================================= - // Set dialog's timer! 1000 = 1 second. - //======================================================================= -// timer_id = SetTimer( window_handle, 1000, 250L, NULL ); - timer_id = SetTimer( window_handle, 1000, 500L, NULL ); - } - return( TRUE ); - - //------------------------------------------------------------------------------- - // Try and set a custom cursor. - //------------------------------------------------------------------------------- -// case WM_SETCURSOR: -// SetCursor(LoadCursor( Main::hInstance, MAKEINTRESOURCE(2))); -// break; - - //------------------------------------------------------------------------------- - // Tell Window to Select Palette if we are not the Focused Window. - // This is to avoid getting stuck in a loop of receiving this msg - // when we are focused. - //------------------------------------------------------------------------------- - case WM_PALETTECHANGED: - if (( HWND )w_param != window_handle ) { - SendMessage( window_handle, WM_QUERYNEWPALETTE, w_param, l_param ); - } - break; - - //------------------------------------------------------------------------------- - // Set and Realize our palette, then repaint if necessary. - // Note that SelectPalette here is passed a FALSE. - // This means reset palette as if we are in the foreground. - //------------------------------------------------------------------------------- - case WM_QUERYNEWPALETTE: - hDC = GetDC( window_handle ); - hpalold = SelectPalette( hDC, hpal, FALSE ); - i = RealizePalette( hDC ); - if ( i != 0 ) { - InvalidateRect( window_handle, &dlg_rect, TRUE ); - } - SelectPalette( hDC, hpalold, TRUE ); - RealizePalette( hDC ); - ReleaseDC( window_handle, hDC ); - return i; - - //------------------------------------------------------------------------------- - // Process Timer Messages. - //------------------------------------------------------------------------------- - case WM_TIMER: - { - if ( w_param == 1000 ) { - -// if ( Flicker && hFlicker[FlickerIndex] ) { - if ( Flicker && hFlicker[0] ) { - - FlickerIndex++; -// if ( FlickerIndex >= NUM_FLICKER_FRAMES ) { - if ( FlickerIndex >= NUM_FLICKER_POSITIONS ) { - FlickerIndex = 0; - } - - InvalidateRect( window_handle, &flicker_rect, FALSE ); - flicker_rect.left = FlickerPositions[ FlickerIndex ][0]; - InvalidateRect( window_handle, &flicker_rect, FALSE ); - UpdateWindow( window_handle ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("WM_TIMER: FlickerRect = [%d,%d,%d,%d]"), flicker_rect.left, flicker_rect.right, flicker_rect.top, flicker_rect.bottom ); - } - } - - //----------------------------------------------------------------------- - // If game is running, the mutex will return! Time to exit... - // Note: This number is unique for Tiberian Sun ONLY!!! - //----------------------------------------------------------------------- - if( WinVersion.Is_Win_XP() || WinVersion.Version() > 500 ) { - strcat( strcpy( szBuffer, "Global\\" ), GAME_MUTEX_OBJECT ); - } else { - strcpy( szBuffer, GAME_MUTEX_OBJECT ); - } - GameAppMutex = OpenMutex( MUTEX_ALL_ACCESS, FALSE, szBuffer ); - - if ( GameAppMutex != NULL ) { - - //--------------------------------------------------------- - // Handle(s) are closed in the ProgEnd(). - //--------------------------------------------------------- - - HWND ccwindow = FindWindow( szGameWindow, NULL ); - if ( ccwindow ) { - if( IsIconic( ccwindow )){ - ShowWindow( ccwindow, SW_RESTORE ); - } - SetForegroundWindow( ccwindow ); - - } else { - - ccwindow = FindWindow( szSetupWindow, NULL ); - if ( ccwindow ) { - if( IsIconic( ccwindow )){ - ShowWindow( ccwindow, SW_RESTORE ); - } - SetForegroundWindow( ccwindow ); - } - } - - PostMessage( window_handle, WM_COMMAND, (WPARAM)MAKELONG( IDD_CANCEL, BN_CLICKED ), (LPARAM)GetDlgItem( window_handle, IDD_CANCEL )); - } - } - return ( 0 ); - - //=============================================================================== - // Dialog's main paint routine. - //=============================================================================== - case WM_PAINT: - - //--------------------------------------------------------------------------- - // If there is an area to update, repaint it. - //--------------------------------------------------------------------------- - if ( GetUpdateRect( window_handle, &paint_rect, FALSE )) { - -// Msg( __LINE__, TEXT(__FILE__), TEXT("---------------------- WM_PAINT ---------------------"), i ); -// Msg( __LINE__, TEXT(__FILE__), TEXT("Rectangle to update = [%d,%d,%d,%d]"), paint_rect.left, paint_rect.top, paint_rect.right, paint_rect.bottom ); - - //----------------------------------------------------------------------- - // Get dialog's hDC. - //----------------------------------------------------------------------- - hDC = BeginPaint( window_handle, &ps ); - - #if( BACKGROUND_BITMAP ) - - if ( hBitmap ) { - - //--------------------------------------------------------------- - // Create a compatible DC for the bitmap. - //--------------------------------------------------------------- - memDC = CreateCompatibleDC( hDC ); - buttonDC = CreateCompatibleDC( hDC ); - licenseDC = CreateCompatibleDC( hDC ); - - //--------------------------------------------------------------- - // Set stretching mode for bitmaps. - //--------------------------------------------------------------- - prevDCStretchMode = SetStretchBltMode( hDC, STRETCH_DELETESCANS ); - prevMemDCStretchMode = SetStretchBltMode( memDC, STRETCH_DELETESCANS ); - prevButtonDCStretchMode = SetStretchBltMode( buttonDC,STRETCH_DELETESCANS ); - prevLicenseDCStretchMode = SetStretchBltMode( licenseDC,STRETCH_DELETESCANS ); - - //--------------------------------------------------------------- - // Set the palette in each DC. - //--------------------------------------------------------------- - hpalold = SelectPalette( hDC, hpal, FALSE ); - RealizePalette( hDC ); - SelectPalette( memDC, hpal, FALSE ); - RealizePalette( memDC ); - SelectPalette( buttonDC, hpal, FALSE ); - RealizePalette( buttonDC ); - SelectPalette( licenseDC, hpal, FALSE ); - RealizePalette( licenseDC ); - - //--------------------------------------------------------------- - // If area to update is a button area, this will be drawn farther - // on. This is to prevent "flickering" by drawing the background - // then the button image. - //--------------------------------------------------------------- - for ( i = 0; i < NUM_BUTTONS; i++ ) { - - if ( ButtonList[i] ) { - - ButtonList[i]->Return_Area( &rect ); - - if ( paint_rect.left == rect.left && - paint_rect.top == rect.top && - paint_rect.right == rect.right && - paint_rect.bottom == rect.bottom ) { - - PaintBackground = FALSE; -// Msg( __LINE__, TEXT(__FILE__), TEXT("Rectangle matches a button to update = [%d,%d,%d,%d]"), rect.left, rect.top, rect.right, rect.bottom ); - break; - } - } - } - - //=============================================================== - // Paint the background. - //=============================================================== - if ( PaintBackground ) { - - //----------------------------------------------------------- - // Select & Draw the background bitmap. - //----------------------------------------------------------- - oldBitmap = ( HBITMAP )SelectObject( memDC, hBitmap ); - - //----------------------------------------------------------- - // Updates area around the button area. - //----------------------------------------------------------- - #if(1) - for( int i=0; i < ( NUM_BUTTONS * 3 ) + 3; i++ ) { - - if( BackgroundRect[i].left != 0 || BackgroundRect[i].top != 0 || - BackgroundRect[i].right != 0 || BackgroundRect[i].bottom != 0 ) { - - result = StretchBlt( hDC, - BackgroundRect[i].left, - BackgroundRect[i].top, - BackgroundRect[i].right, - BackgroundRect[i].bottom, - memDC, - BackgroundRect[i].left, - BackgroundRect[i].top, - BackgroundRect[i].right, - BackgroundRect[i].bottom, - SRCCOPY ); - - if( result != 0 ) { -// Msg( __LINE__, TEXT(__FILE__), TEXT("Paint this rect = [%d,%d,%d,%d]"), BackgroundRect[i].left, BackgroundRect[i].top, BackgroundRect[i].right, BackgroundRect[i].bottom ); - } - - #if(0) - HPEN pen = CreatePen( /*PS_DOT*/ PS_SOLID, 1, TEXT_COLOR ); - HGDIOBJ oldpen = SelectObject( hDC, pen ); - SetBkMode( hDC, TRANSPARENT ); - - MoveToEx( hDC, BackgroundRect[i].left+1, BackgroundRect[i].top+1, NULL ); - LineTo( hDC, BackgroundRect[i].right-1, BackgroundRect[i].top+1 ); - LineTo( hDC, BackgroundRect[i].right-1, BackgroundRect[i].bottom-1 ); - LineTo( hDC, BackgroundRect[i].left+1, BackgroundRect[i].bottom-1 ); - LineTo( hDC, BackgroundRect[i].left+1, BackgroundRect[i].top+1 ); - - SelectObject( hDC, oldpen ); - DeleteObject( pen ); - #endif - } - } -/* - //----------------------------------------------------------- - // Select & Draw the background bitmap. - //----------------------------------------------------------- - oldLicenseBitmap = ( HBITMAP )SelectObject( licenseDC, hLicenseBitmap ); - - //----------------------------------------------------------- - // Updates area around the button area. - //----------------------------------------------------------- - result = StretchBlt( hDC, - license_rect.left, - license_rect.top, - license_rect.right, - license_rect.bottom, - licenseDC, - 0, - 0, - license_rect.right, - license_rect.bottom, - SRCCOPY ); -*/ - #else - - //----------------------------------------------------------- - // Blit whole background, in one shot. - //----------------------------------------------------------- - StretchBlt( hDC, dlg_rect.left, dlg_rect.top, dlg_rect.right, dlg_rect.bottom, - memDC, bitmap_rect.left, bitmap_rect.top, bitmap_rect.right, bitmap_rect.bottom, - SRCCOPY ); - #endif - - SelectObject( memDC, oldBitmap ); - SelectObject( licenseDC, oldLicenseBitmap ); - - } else { - PaintBackground = TRUE; - } - - //--------------------------------------------------------------- - // Animation. - //--------------------------------------------------------------- -// if ( Flicker && hFlicker[FlickerIndex] ) { - if ( Flicker && hFlicker[0] ) { - -// oldBitmap = ( HBITMAP )SelectObject( memDC, hFlicker[FlickerIndex] ); - oldBitmap = ( HBITMAP )SelectObject( memDC, hFlicker[0] ); - - StretchBlt( - hDC, - flicker_rect.left, - flicker_rect.top, - flicker_rect.right, - flicker_rect.bottom, - memDC, - 0, - 0, - flicker_rect.right, - flicker_rect.bottom, - SRCCOPY ); - - #if(0) - HPEN pen = CreatePen( /*PS_DOT*/ PS_SOLID, 1, TEXT_COLOR ); - HGDIOBJ oldpen = SelectObject( hDC, pen ); - SetBkMode( hDC, TRANSPARENT ); - - MoveToEx( hDC, flicker_rect.left+1, flicker_rect.top+1, NULL ); - LineTo( hDC, flicker_rect.right-1, flicker_rect.top+1 ); - LineTo( hDC, flicker_rect.right-1, flicker_rect.bottom-1 ); - LineTo( hDC, flicker_rect.left+1, flicker_rect.bottom-1 ); - LineTo( hDC, flicker_rect.left+1, flicker_rect.top+1 ); - - SelectObject( hDC, oldpen ); - DeleteObject( pen ); - #endif - - SelectObject( memDC, oldBitmap ); - -// Msg( __LINE__, TEXT(__FILE__), TEXT(" Drawing Flicker [%d,%d,%d,%d]."), flicker_rect.left, flicker_rect.top, flicker_rect.right, flicker_rect.bottom ); - } - - //--------------------------------------------------------------- - // Draw each button. - //--------------------------------------------------------------- - for ( i = 0; i < NUM_BUTTONS; i++ ) { - - if ( ButtonList[i] ) { - - Rect rect; - - //------------------------------------------------------- - // Uses Bitmaps or DrawText??? - //------------------------------------------------------- - if ( ButtonList[i]->Draw_Bitmaps()) { - - RECT src_rect, dst_rect; - - strcpy( szButtonBitmap, ButtonList[i]->Return_Bitmap( )); - hButtonBitmap = LoadResourceBitmap( Main::hInstance, szButtonBitmap, &hpal, TRUE ); - if ( hButtonBitmap ) { - - GetObject( hButtonBitmap, sizeof( BITMAP ), (LPTSTR)&bm ); - - dst_rect.left = ButtonList[i]->Return_X_Pos(); - dst_rect.top = ButtonList[i]->Return_Y_Pos(); - dst_rect.right = ButtonList[i]->Return_Stretched_Width(); - dst_rect.bottom = ButtonList[i]->Return_Stretched_Height(); - src_rect.left = 0; - src_rect.top = 0; - src_rect.right = bm.bmWidth; - src_rect.bottom = bm.bmHeight; - - //----------------------------------------------- - // Draw the button's bitmap background. - //----------------------------------------------- - oldBitmap = ( HBITMAP ) SelectObject( buttonDC, hButtonBitmap ); - StretchBlt( - hDC, - dst_rect.left, - dst_rect.top, - dst_rect.right, - dst_rect.bottom, - buttonDC, - src_rect.left, - src_rect.top, - src_rect.right, - src_rect.bottom, - SRCCOPY ); - - SelectObject( buttonDC, oldBitmap ); - DeleteObject( hButtonBitmap ); - hButtonBitmap = 0; - } - - } // END OF DRAW BITMAPS - -#if(0) - TTFontClass *fontptr = ButtonList[i]->Return_Font_Ptr(); - if ( fontptr ) { - - RECT outline_rect; - - ButtonList[i]->Return_Area( &outline_rect ); - ButtonList[i]->Return_Text_Area( &rect ); - - /* - ** This function was combining the pixel color with the background, - ** so it never looked correct. - */ -// SetTextColor( hDC, RGB( 0, 240, 0 )); -// DrawFocusRect( hDC, &dst_rect ); - - if ( ButtonList[i]->Get_State() == DrawButton::PRESSED_STATE ) { - fontptr->Print( - hDC, - ButtonList[i]->Return_Text(), - rect, - TEXT_PRESSED_COLOR, - TEXT_PRESSED_SHADOW_COLOR, - TPF_BUTTON, - TPF_SHADOW ); - - } else if ( ButtonList[i]->Get_State() == DrawButton::FOCUS_STATE ) { - fontptr->Print( - hDC, - ButtonList[i]->Return_Text(), - rect, - TEXT_FOCUSED_COLOR, - TEXT_FOCUSED_SHADOW_COLOR, - TPF_BUTTON, - TPF_SHADOW ); - - } else { - fontptr->Print( - hDC, - ButtonList[i]->Return_Text(), - rect, - TEXT_NORMAL_COLOR, - TEXT_NORMAL_SHADOW_COLOR, - TPF_BUTTON, - TPF_SHADOW ); - } - - #if(0) - HPEN pen = CreatePen( /*PS_DOT*/ PS_SOLID, 2, TEXT_COLOR ); - HGDIOBJ oldpen = SelectObject( hDC, pen ); - SetBkMode( hDC, TRANSPARENT ); - - MoveToEx( hDC, // handle to device context - outline_rect.left, // x-coordinate of new current position - outline_rect.top, // y-coordinate of new current position - NULL ); // pointer to old current position - - LineTo( hDC, // device context handle - outline_rect.right, // x-coordinate of line's ending point - outline_rect.top ); // y-coordinate of line's ending point - - LineTo( hDC, // device context handle - outline_rect.right, // x-coordinate of line's ending point - outline_rect.bottom ); // y-coordinate of line's ending point - - LineTo( hDC, // device context handle - outline_rect.left, // x-coordinate of line's ending point - outline_rect.bottom ); // y-coordinate of line's ending point - - LineTo( hDC, // device context handle - outline_rect.left, // x-coordinate of line's ending point - outline_rect.top ); // y-coordinate of line's ending point - - SelectObject( hDC, oldpen ); - DeleteObject( pen ); - #endif - } -#else - ButtonList[i]->Draw_Text( hDC ); -#endif - - - - } // end of if button - - } // For each button... - - //--------------------------------------------------------------- - // Used in debugging -- draw rect around where buttons are. - //--------------------------------------------------------------- - #if(0) - { - HPEN hPen1 = CreatePen( PS_SOLID, 1, RGB( 255, 255, 255 )); - if (hPen1) { - - for ( int i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] ) { - - HGDIOBJ oldpen = SelectObject( hDC, hPen1 ); - - MoveToEx( hDC, - ButtonList[i]->Return_X_Pos()-1, - ButtonList[i]->Return_Y_Pos()-1, NULL ); - LineTo( hDC, - ButtonList[i]->Return_X_Pos() + ButtonList[i]->Return_Width() + 1, - ButtonList[i]->Return_Y_Pos()-1 ); - LineTo( hDC, - ButtonList[i]->Return_X_Pos() + ButtonList[i]->Return_Width() + 1, - ButtonList[i]->Return_Y_Pos() + ButtonList[i]->Return_Height() + 1); - LineTo( hDC, - ButtonList[i]->Return_X_Pos()-1, - ButtonList[i]->Return_Y_Pos() + ButtonList[i]->Return_Height() + 1); - LineTo( hDC, - ButtonList[i]->Return_X_Pos() - 1, - ButtonList[i]->Return_Y_Pos() - 1); - - SelectObject( hDC, oldpen ); - } - } - } - DeleteObject( hPen1 ); - } - #endif - - //--------------------------------------------------------------- - // Restore all default objects to DCs and delete. - //--------------------------------------------------------------- - SetStretchBltMode( hDC, prevDCStretchMode ); - SetStretchBltMode( memDC, prevMemDCStretchMode ); - SetStretchBltMode( buttonDC, prevButtonDCStretchMode ); - SetStretchBltMode( licenseDC, prevLicenseDCStretchMode ); - - SelectPalette( hDC, hpalold, FALSE ); - SelectPalette( memDC, hpalold, FALSE ); - SelectPalette( buttonDC, hpalold, FALSE ); - SelectPalette( licenseDC, hpalold, FALSE ); - - DeleteDC( memDC ); - DeleteDC( buttonDC ); - DeleteDC( licenseDC ); - - } // end of bitmaps - - //=================================================================== - // Draw a solid colored background. - //=================================================================== -// GetClientRect( window_handle, (LPRECT) &dlg_rect ); -// FillRect( hDC, &dlg_rect, (HBRUSH)( COLOR_WINDOW + 1 )); - - //=================================================================== - // Print text at bottom of screen. - //=================================================================== - Rect text_rect; - TTFontClass *fontptr = NULL; - - if ( b640X480 ) { - fontptr = TTTextFontPtr640; - } else if ( b800X600 ) { - fontptr = TTTextFontPtr800; - } else { - fontptr = TTTextFontPtr; - } - - if ( fontptr ) { - - if ( b640X480 || b800X600 ) { - text_rect.X = 10; - text_rect.Y = 240; - text_rect.Width = 140; //498; - text_rect.Height = 100; //26; - } else { - text_rect.X = 20; - text_rect.Y = 340; - text_rect.Width = 180; //498; - text_rect.Height = 120; //26; - } - - #if(0) - RECT one; - - one.left = text_rect.X; - one.top = text_rect.Y; - one.right = text_rect.X + text_rect.Width; - one.bottom = text_rect.Y + text_rect.Height; - - FrameRect( hDC, &one, (HBRUSH)( COLOR_WINDOW + 1 )); -// DrawFocusRect( hDC, &one ); - #endif - - //--------------------------------------------------------------- - // WESTWOOD_COM Message at the top. - //--------------------------------------------------------------- -/* - fontptr->Print( - hDC, - szWholeWSMsg, - text_rect, - TEXT_COLOR, - SHADOW_COLOR, - TPF_CENTER_TEXT, - TPF_SHADOW ); -*/ - } - - //--------------------------------------------------------------- - // EA_COM Message at the bottom. - //--------------------------------------------------------------- - #if(0) // Moved this text to a bitmap. - fontptr = TTLicenseFontPtr; - if( fontptr ) { - - if ( b640X480 || b800X600 ) { - text_rect.X = 220; - text_rect.Y = 400; - text_rect.Width = 300; //460; - text_rect.Height = 48; //26; - } else { - text_rect.X = 250; - text_rect.Y = 574; - text_rect.Width = 420; //460; - text_rect.Height = 60; //26; - } - - #if(0) - RECT one; - - one.left = text_rect.X; - one.top = text_rect.Y; - one.right = text_rect.X + text_rect.Width; - one.bottom = text_rect.Y + text_rect.Height; - - FrameRect( hDC, &one, (HBRUSH)( COLOR_WINDOW + 1 )); -// DrawFocusRect( hDC, &one ); - #endif - - fontptr->Print( - hDC, - szWholeString, - text_rect, - TEXT_COLOR, - SHADOW_COLOR, - TPF_CENTER_TEXT, - TPF_SHADOW ); - } - #endif - - #else - //------------------------------------------------------------------- - // Select the Brush if it was successfully created. - //------------------------------------------------------------------- - if ( hStaticBrush ) { - HBRUSH oldBrush = (HBRUSH) SelectObject( hDC, hStaticBrush ); - GetClientRect( window_handle, (LPRECT) &dlg_rect ); - FillRect( hDC, &dlg_rect, hStaticBrush ); - SelectObject( hDC, oldBrush ); - } - #endif - -// Msg( __LINE__, TEXT(__FILE__), TEXT("--------------------------------------------------------" )); - - EndPaint( window_handle, &ps ); - - //----------------------------------------------------------------------- - // Play DISK.WAV sound on CD. - //----------------------------------------------------------------------- - if ( FirstTime ) { - if( UseSounds ) { - PlaySound( szWavs[ SongNumber ], NULL, SND_ASYNC | SND_RESOURCE ); - } - FirstTime = FALSE; - } - } /* end of if */ - break; - - //------------------------------------------------------------------------------- - // Background needs to be erased. Note we are returning 1 here to "fake" - // Windows into thinking we have already repainted the background with - // our window brush. This prevents "flickering" because of background - // being repainted ( ususally white ) before WM_PAINT is processed. - //------------------------------------------------------------------------------- - #if(BACKGROUND_BITMAP) - case WM_ERASEBKGND: - InvalidateRect( window_handle, &dlg_rect, FALSE ); - return ( 1 ); - #endif - - //------------------------------------------------------------------------------- - // Check which button was pressed. If Explorer button was pressed, - // call it now so we don't have to exit dialog. - //------------------------------------------------------------------------------- - case WM_COMMAND: - { - idCtl = LOWORD( w_param ); - - unsigned int result = TRUE; - bool end_dialog = false; - int cd_drive; - - szBuffer[1] = '\0'; - szBuffer[0] = tolower( szArgvPath[0] ); -// cd_drive = (int)( szBuffer[0] - 'a' + 1 ); - cd_drive = (int)( szBuffer[0] - 'a' ); - - #if(BACKGROUND_BITMAP) - - switch ( idCtl ) { - - //------------------------------------------------------------------- - // IDD_MOHAVI - //------------------------------------------------------------------- - case IDD_PREVIEWS: - { - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_PREVIEWS Selected." )); - // show the previews in succession. each will wait for the previous to finish - // before playing. - unsigned int success; - - char filepath[MAX_PATH]; - _snprintf(filepath, MAX_PATH, "%s%s", szArgvPath, SC4AVI_FILENAME); - - success = GlobalMainWindow->Run_OpenFile(cd_drive, filepath, true); -// if (success != 0) { -// success = GlobalMainWindow->Run_OpenFile(cd_drive, BFAVI_FILENAME, true); -// } -/* - if (success == 0) { - std::wstring wideBuffer = TheGameText->fetch("Autorun:CantRunAVIs"); - std::wstring wideBuffer2 = TheGameText->fetch("Autorun:Error"); - int length = wideBuffer.length(); - WideCharToMultiByte( CodePage, 0, wideBuffer.c_str(), length+1, szBuffer, _MAX_PATH, NULL, NULL ); - length = wideBuffer2.length(); - WideCharToMultiByte( CodePage, 0, wideBuffer2.c_str(), length+1, szBuffer2, _MAX_PATH, NULL, NULL ); - MessageBox( NULL, szBuffer, szBuffer2, MB_APPLMODAL | MB_OK ); - } -*/ - } - break; - - case IDD_HELP: - { - std::wstring wFileName; - wFileName = Locale_GetString(HELP_FILENAME); - - std::string fname; - const wchar_t *tmp = wFileName.c_str(); - char hack[2] = "a"; - while (*tmp) - { - hack[0] = (char)( *tmp & 0xFF ); - fname.append( hack ); - tmp++; - } - - char newdir[MAX_PATH]; - char olddir[MAX_PATH]; - char filepath[MAX_PATH]; - - GetCurrentDirectory(MAX_PATH, olddir); - - _snprintf(newdir, MAX_PATH, "%ssupport", szArgvPath); - SetCurrentDirectory(newdir); - - _snprintf(filepath, MAX_PATH, "%s%s", szArgvPath, fname.c_str()); - - unsigned int success; - success = GlobalMainWindow->Run_OpenFile(cd_drive, filepath, false); - - SetCurrentDirectory(olddir); - -/* - if (success == 0) { - std::wstring wideBuffer = TheGameText->fetch("Autorun:CantRunHelp"); - std::wstring wideBuffer2 = TheGameText->fetch("Autorun:Error"); - int length = wideBuffer.length(); - WideCharToMultiByte( CodePage, 0, wideBuffer.c_str(), length+1, szBuffer, _MAX_PATH, NULL, NULL ); - length = wideBuffer2.length(); - WideCharToMultiByte( CodePage, 0, wideBuffer2.c_str(), length+1, szBuffer2, _MAX_PATH, NULL, NULL ); - MessageBox( NULL, szBuffer, szBuffer2, MB_APPLMODAL | MB_OK ); - } -*/ - } - break; - - //------------------------------------------------------------------- - // IDD_CANCEL - //------------------------------------------------------------------- - case IDD_CANCEL: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_CANCEL Selected." )); - end_dialog = true; - break; - - //------------------------------------------------------------------- - // IDD_OK -- Install - // IDD_OK2 -- Play - //------------------------------------------------------------------- - case IDD_OK: - case IDD_OK2: - case IDD_OK3: - case IDD_OK4: - -// if( !Is_On_CD( PRODUCT_VOLUME_CD1 ) && IsEnglish ) { - if( !Is_On_CD( PRODUCT_VOLUME_CD1 )) { - - //----------------------------------------------------------- - // If false is returned, then CANCEL was pressed. - //----------------------------------------------------------- - char volume_to_match[ MAX_PATH ]; - - Reformat_Volume_Name( PRODUCT_VOLUME_CD1, volume_to_match ); -// result = Prompt_For_CD( window_handle, volume_to_match, IDS_INSERT_CDROM_WITH_VOLUME1, IDS_EXIT_MESSAGE2, &cd_drive ); - result = Prompt_For_CD( window_handle, volume_to_match, "Autorun:InsertCDROMWithVolume1", "Autorun:ExitMessage2", &cd_drive ); - } - - if ( result ) { - if ( idCtl == IDD_OK ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_OK Selected." )); - result = GlobalMainWindow->Run_Setup( window_handle, &dlg_rect, cd_drive ); - } else if ( idCtl == IDD_OK2 ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_OK2 Selected." )); - result = GlobalMainWindow->Run_Game( window_handle, &dlg_rect ); - } else if (idCtl == IDD_OK3 ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_OK3 Selected, running WorldBuilder." )); - result = GlobalMainWindow->Run_WorldBuilder( window_handle, &dlg_rect ); - } else if (idCtl == IDD_OK4 ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_OK4 Selected, running PatchGet." )); - result = GlobalMainWindow->Run_PatchGet( window_handle, &dlg_rect ); - } - } - - if ( result ) { - end_dialog = true; - } - break; - - #if(SHOW_MOH_DEMO) - //------------------------------------------------------------------- - // Launch demo from CD. - //------------------------------------------------------------------- - case IDD_VIEW_DEMO: - - if( !Is_On_CD( PRODUCT_VOLUME_CD2 )) { - - //----------------------------------------------------------- - // If false is returned, then CANCEL was pressed. - //----------------------------------------------------------- - char volume_to_match[ MAX_PATH ]; - - Reformat_Volume_Name( PRODUCT_VOLUME_CD2, volume_to_match ); -// result = Prompt_For_CD( window_handle, volume_to_match, IDS_INSERT_CDROM_WITH_VOLUME2, IDS_EXIT_MESSAGE2, &cd_drive ); - result = Prompt_For_CD( window_handle, volume_to_match, AsciiString("Autorun:InsertCDROMWithVolume2"), AsciiString("Autorun:ExitMessage2"), &cd_drive ); - } - - if ( result ) { - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_VIEW_DEMO Selected." )); - result = GlobalMainWindow->Run_Demo( window_handle, &dlg_rect, cd_drive ); - } - - if ( result ) { - end_dialog = true; - } - - break; - #endif - - #if( SHOW_GAMESPY_BUTTON ) - //------------------------------------------------------------------- - // Launch GameSpy Website. - //------------------------------------------------------------------- - case IDD_GAMESPY: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_GAMESPY Selected." )); - if( ViewHTML( GAMESPY_WEBSITE )) - { - end_dialog = true; - } - else - { - Error_Message( Main::hInstance, AsciiString("Autorun:Generals"), AsciiString("Autorun:CantFindExplorer"), GAME_WEBSITE ); - } - break; - #endif - - //------------------------------------------------------------------- - // Create a new online account. - //------------------------------------------------------------------- - case IDD_NEW_ACCOUNT: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_NEW_ACCOUNT Selected." )); - result = GlobalMainWindow->Run_New_Account( window_handle, &dlg_rect ); - if ( result ) { - end_dialog = true; - } - break; - - //------------------------------------------------------------------- - // IDD_REGISTER - //------------------------------------------------------------------- - case IDD_REGISTER: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_REGISTER Selected." )); - result = GlobalMainWindow->Run_Register( window_handle, &dlg_rect ); - if ( result ) { - end_dialog = true; - } - break; - - //------------------------------------------------------------------- - // IDD_INTERNET - //------------------------------------------------------------------- - case IDD_INTERNET: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_INTERNET Selected." )); - if( ViewHTML( GAME_WEBSITE )) { - end_dialog = true; - } - else - { - Error_Message( Main::hInstance, "Autorun:Generals", "Autorun:CantFindExplorer", GAME_WEBSITE ); - } - break; - - //------------------------------------------------------------------- - // IDD_UPDATE - //------------------------------------------------------------------- - case IDD_UPDATE: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_UPDATE Selected." )); - result = GlobalMainWindow->Run_Auto_Update( window_handle, &dlg_rect ); - if ( result ) { - end_dialog = true; - } - break; - - //------------------------------------------------------------------- - // IDD_EXPLORE - //------------------------------------------------------------------- - case IDD_EXPLORE: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_EXPLORE Selected." )); - GlobalMainWindow->Run_Explorer( "", window_handle, &dlg_rect ); - end_dialog = true; - break; - - //------------------------------------------------------------------- - // IDD_UNINSTALL - //------------------------------------------------------------------- - case IDD_UNINSTALL: - Msg( __LINE__, TEXT(__FILE__), TEXT("IDD_UNINSTALL Selected." )); - result = GlobalMainWindow->Run_Uninstall( window_handle, &dlg_rect ); - - //--------------------------------------------------------------- - // MML 5/27/99: I am exiting here because the we launch - // Uninstll.exe which in turn launches Uninst.exe thus - // ::Run_Install ends before Uninst.exe is done. - //--------------------------------------------------------------- - if ( result ) { - end_dialog = true; - } - break; - - default: - break; - } - - //----------------------------------------------------------------------- - // Exit Autorun. - //----------------------------------------------------------------------- - if( end_dialog ) { - - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] ) { - delete( ButtonList[i] ); - ButtonList[i] = NULL; - } - } - if ( hpal ) { - DeleteObject( hpal ); - } - if ( hBitmap ) { - DeleteObject( hBitmap ); - } - for( i = 0; i < NUM_FLICKER_FRAMES; i++ ) { - DeleteObject( hFlicker[i] ); - hFlicker[i] = 0; - } - Stop_Sound_Playing(); - KillTimer( window_handle, timer_id ); - EndDialog( window_handle, idCtl ); - } - - #else - if ( hStaticBrush ) { - DeleteObject( hStaticBrush ); - hStaticBrush = 0; - } - EndDialog( window_handle, idCtl ); - KillTimer( window_handle, timer_id ); - KillTimer( window_handle, gem_timer_id ); - #endif - - } - break; - - //------------------------------------------------------------------------------- - // This message is the response to the Close Button in upper right corner. - //------------------------------------------------------------------------------- - case WM_SYSCOMMAND: - - if ( w_param == SC_CLOSE ) { - #if(BACKGROUND_BITMAP) - - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] ) { - delete( ButtonList[i] ); - ButtonList[i] = NULL; - } - } - if ( hpal ) { - DeleteObject( hpal ); - } - if ( hBitmap ) { - DeleteObject( hBitmap ); - } - for( i = 0; i < NUM_FLICKER_FRAMES; i++ ) { - DeleteObject( hFlicker[i] ); - hFlicker[i] = 0; - } - - #else - if ( hStaticBrush ) { - DeleteObject( hStaticBrush ); - hStaticBrush = 0; - } - #endif - - //----------------------------------------------------------------------- - // Stop the sound if still going. - //----------------------------------------------------------------------- - Stop_Sound_Playing(); - - //----------------------------------------------------------------------- - // Delete the arguments. - //----------------------------------------------------------------------- - if ( Args ) { - delete( Args ); - Args = NULL; - } - KillTimer( window_handle, timer_id ); - EndDialog( window_handle, w_param ); - } - break; - - //------------------------------------------------------------------------------- - // WM_SYSCOLORCHANGE Message. - // If your applications uses controls in Windows 95/NT, forward the - // WM_SYSCOLORCHANGE message to the controls. - //------------------------------------------------------------------------------- - #if( !BACKGROUND_BITMAP ) - case WM_SYSCOLORCHANGE: - if ( hStaticBrush ) { - DeleteObject( hStaticBrush ); - hStaticBrush = CreateSolidBrush( GetSysColor( COLOR_WINDOW )); - } - break; - #endif - - //------------------------------------------------------------------------------- - // WM_CTLCOLOR Message. - // wParam Handle to Child Window's device context - // LOWORD( lParam ) Child Window handle - // HIWORD( lParam ) Type of Window: CTLCOLOR_MSGBOX, _EDIT, _LISTBOX, _BTN, _DLG, _SCROLLBAR, _STATIC - // - // WM_CTLCOLORMSGBOX - // WM_CTLCOLOREDIT - // WM_CTLCOLORLISTBOX - // WM_CTLCOLORBTN - // WM_CTLCOLORDLG - // WM_CTLCOLORSCROLLBAR - // WM_CTLCOLORSTATIC - // #define WM_CTLCOLOR 0x0019 - // #define GET_WM_CTLCOLOR_HDC (wp, lp, msg) (HDC)(wp) - // #define GET_WM_CTLCOLOR_HWND(wp, lp, msg) (HWND)(lp) - // #define GET_WM_CTLCOLOR_TYPE(wp, lp, msg) (WORD)(msg - WM_CTLCOLORMSGBOX) - // #define GET_WM_CTLCOLOR_MSG (type) (WORD)(WM_CTLCOLORMSGBOX+(type)) - //------------------------------------------------------------------------------- - #if( !BACKGROUND_BITMAP ) - case WM_CTLCOLOR: - if ( HIWORD( l_param ) == CTLCOLOR_STATIC ) { - - SetTextColor(( HDC )w_param, GetSysColor( COLOR_WINDOWTEXT )); - SetBkColor( (HDC)wParam, GetSysColor( COLOR_WINDOW )); -// SetBkColor(( HDC )w_param, RGB( 192, 192, 192 )); - - UnrealizeObject( hStaticBrush ); // reset the origin of the brush next time used. - point.x = point.y = 0; // create a point. - ClientToScreen( window_handle, &point ); // translate into screen coordinates. - SetBrushOrgEx( (HDC)w_param, point.x, point.y, NULL ); // New Origin to use when next selected. - return((LRESULT) hStaticBrush ); - } - #endif - - //=============================================================================== - // Check where Left Mouse button was pressed. - //=============================================================================== - #if(BACKGROUND_BITMAP) - case WM_LBUTTONDOWN: - { - RECT rect; - - //---------------------------------------------------------------------- - // Get mouse coordinates. - //---------------------------------------------------------------------- - mouse_x = LOWORD( l_param ); - mouse_y = HIWORD( l_param ); - - //---------------------------------------------------------------------- - // For each button in the list... - //---------------------------------------------------------------------- - for ( i = 0; i < NUM_BUTTONS; i++ ) { - - //------------------------------------------------------------------- - // If mouse was clicked in one of the "buttons", then change - // that button's state to "pressed". - //------------------------------------------------------------------- - if ( ButtonList[i] && ButtonList[i]->Is_Mouse_In_Region( mouse_x, mouse_y )) { - - if ( ButtonList[i]->Get_State() != DrawButton::PRESSED_STATE ) { - - ButtonList[i]->Return_Area ( &rect ); - ButtonList[i]->Set_State( DrawButton::PRESSED_STATE ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("WM_LBUTTONDOWN -- %s. rect = [%d,%d,%d,%d]."), - ButtonList[i]->Return_Normal_Bitmap(), rect.left, rect.top, rect.right, rect.bottom ); - - UpdateWindow( window_handle ); - } - break; - } - } - } - break; - #endif - - //=============================================================================== - // Check where Left Mouse button was released. - //=============================================================================== - #if(BACKGROUND_BITMAP) - case WM_LBUTTONUP: - { - RECT rect; - int focus_index = 0; - int found_focus = -1; - - //----------------------------------------------------------------------- - // Get mouse coordinates. - //----------------------------------------------------------------------- - mouse_x = LOWORD( l_param ); - mouse_y = HIWORD( l_param ); - - //======================================================================= - // focus_index = previous PRESSED/FOCUSED button. - // found_focus = new PRESSED/FOCUSED button ( if different ). - //======================================================================= - - //----------------------------------------------------------------------- - // First find the button that is either focused or pressed. - //----------------------------------------------------------------------- - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] ) { - - //--------------------------------------------------------------- - // Save index of button with focus. - //--------------------------------------------------------------- - if( ButtonList[i]->Get_State() == DrawButton::FOCUS_STATE || - ButtonList[i]->Get_State() == DrawButton::PRESSED_STATE ) { - focus_index = i; - } - } - } - - //----------------------------------------------------------------------- - // Then find the button that is to be focused or pressed. - //----------------------------------------------------------------------- - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] && ButtonList[i]->Is_Mouse_In_Region( mouse_x, mouse_y )) { - found_focus = i; - } - } - - //----------------------------------------------------------------------- - // If new button is not found... - //----------------------------------------------------------------------- - if ( found_focus == -1 ) { - - //------------------------------------------------------------------- - // Make sure previously focused/pressed button is now is a - // focused state and no action is taken. This occurs when - // mouse is clicked outside of any button areas. - //------------------------------------------------------------------- - if ( ButtonList[focus_index] && ( ButtonList[focus_index]->Get_State() != DrawButton::FOCUS_STATE )) { - - ButtonList[focus_index]->Set_State( DrawButton::FOCUS_STATE ); - ButtonList[focus_index]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("WM_LBUTTONUP -- %s[FOCUS_STATE] = [x=%d, y=%d, w=%d, h=%d]."), - ButtonList[ focus_index ]->Return_Normal_Bitmap(), rect.left, rect.top, rect.right, rect.bottom ); - - UpdateWindow( window_handle ); - } - - } else { - - //------------------------------------------------------------------- - // Buttons are one and the same. - //------------------------------------------------------------------- - if( focus_index == found_focus ) { - - ButtonList[ found_focus ]->Set_State( DrawButton::FOCUS_STATE ); - ButtonList[ found_focus ]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("WM_LBUTTONUP -- %s[FOCUS_STATE] = [x=%d, y=%d, w=%d, h=%d]."), - ButtonList[ found_focus ]->Return_Normal_Bitmap(), rect.left, rect.top, rect.right, rect.bottom ); - - UpdateWindow( window_handle ); - - } else { - - //--------------------------------------------------------------- - // Make previously focused button, Normal... - //--------------------------------------------------------------- - if ( ButtonList[ focus_index ] ) { - - ButtonList[ focus_index ]->Set_State( DrawButton::NORMAL_STATE ); - ButtonList[ focus_index ]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("WM_LBUTTONUP -- %s[NORMAL_STATE] = [x=%d, y=%d, w=%d, h=%d]."), - ButtonList[ focus_index ]->Return_Normal_Bitmap(), - rect.left, rect.top, rect.right, rect.bottom ); - - UpdateWindow( window_handle ); - } - - //--------------------------------------------------------------- - // ...and the new button now has focus. - //--------------------------------------------------------------- - if ( ButtonList[ found_focus ] ) { - - ButtonList[ found_focus ]->Set_State( DrawButton::FOCUS_STATE ); - ButtonList[ found_focus ]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("WM_LBUTTONUP -- %s[FOCUS_STATE] = [x=%d, y=%d, w=%d, h=%d]."), - ButtonList[ found_focus ]->Return_Normal_Bitmap(), rect.left, rect.top, rect.right, rect.bottom ); - - UpdateWindow( window_handle ); - } - } - } - - //----------------------------------------------------------------------- - // Repaint the Window now. - //----------------------------------------------------------------------- - nResult = UpdateWindow( window_handle ); - - //----------------------------------------------------------------------- - // Do the focus button's action. - //----------------------------------------------------------------------- - if ( found_focus >= 0 ) { - if (( ButtonList[found_focus] ) && - ( ButtonList[found_focus]->Get_State() == DrawButton::FOCUS_STATE ) && - ( ButtonList[found_focus]->Is_Mouse_In_Region( mouse_x, mouse_y ))) { - SendMessage( window_handle, WM_COMMAND, ButtonList[found_focus]->Return_Id(), 0L ); - break; - } - } - } - break; - #endif - - //------------------------------------------------------------------------------- - // Check Mouse moves over buttons. - //------------------------------------------------------------------------------- -//#if(DISABLE_KEYBOARD) - #if(BACKGROUND_BITMAP) - case WM_MOUSEMOVE: - { - RECT rect; - int j; - int done = 0; - - //----------------------------------------------------------------------- - // Get mouse coordinates. - //----------------------------------------------------------------------- - mouse_x = LOWORD( l_param ); - mouse_y = HIWORD( l_param ); - - #if(USE_MOUSE_MOVES) - //----------------------------------------------------------------------- - // Reset most current button. - //----------------------------------------------------------------------- - CurrentButton = 0; - #endif - - //----------------------------------------------------------------------- - // For each button in the list... - //----------------------------------------------------------------------- - i = 0; - while( i < NUM_BUTTONS && !done ) { - - //------------------------------------------------------------------- - // For each button, check if mouse is in it's area. - //------------------------------------------------------------------- - if ( ButtonList[i] && ButtonList[i]->Is_Mouse_In_Region( mouse_x, mouse_y )) { - - //--------------------------------------------------------------- - // This is now the current button. - //--------------------------------------------------------------- - CurrentButton = ButtonList[i]->Return_Id(); - - if( CurrentButton != LastButton ) { - - //----------------------------------------------------------- - // Make all other buttons, NORMAL. - //----------------------------------------------------------- - for ( j = 0; j < NUM_BUTTONS; j++ ) { - if ( ButtonList[j] ) { - ButtonList[j]->Set_State( DrawButton::NORMAL_STATE ); -// Msg( __LINE__, TEXT(__FILE__), TEXT("WM_MOUSEMOVE -- %s[NORMAL_STATE]]."), ButtonList[j]->Return_Normal_Bitmap()); - } - } - - if ( w_param & MK_LBUTTON ) { - - //-------------------------------------------------------- - // Left Mouse button is pressed! Make it a pressed button! - //-------------------------------------------------------- - if ( ButtonList[i] && ButtonList[i]->Get_State() != DrawButton::PRESSED_STATE ) { - ButtonList[i]->Set_State( DrawButton::PRESSED_STATE ); -// Msg( __LINE__, TEXT(__FILE__), TEXT("WM_MOUSEMOVE -- %s[PRESSED_STATE]."), ButtonList[i]->Return_Normal_Bitmap()); - } - - } else { - - //-------------------------------------------------------- - // If this button is not already focused, give it the focus. - //-------------------------------------------------------- - if ( ButtonList[i] && ButtonList[i]->Get_State() != DrawButton::FOCUS_STATE ) { - ButtonList[i]->Set_State( DrawButton::FOCUS_STATE ); -// Msg( __LINE__, TEXT(__FILE__), TEXT("WM_MOUSEMOVE -- %s[FOCUS_STATE]."), ButtonList[i]->Return_Normal_Bitmap()); - } - } // end of if - - //----------------------------------------------------------- - // Get the area of the button, and post it for updating. - //----------------------------------------------------------- - for ( j = 0; j < NUM_BUTTONS; j++ ) { - if ( ButtonList[j] ) { - ButtonList[j]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - } - } - - //----------------------------------------------------------- - // Repaint now! - //----------------------------------------------------------- - UpdateWindow( window_handle ); - - done = 1; - } - - } // end of if - i++; - - } // end of for - - - #if( USE_MOUSE_MOVES ) - //----------------------------------------------------------------------- - // If a MouseMove was found to be in one of the buttons, then - // CurrentButton will have a value. - //----------------------------------------------------------------------- - if ( CurrentButton != 0 ) { - - LastButton = CurrentButton; - - //------------------------------------------------------------------- - // If we are still in the same button, don't make a sound! - //------------------------------------------------------------------- - if ( LastButton != PrevButton ) { - PrevButton = LastButton; - PlaySound( szButtonWav, Main::hModule, SND_ASYNC | SND_RESOURCE ); - } - } - #endif - } - break; - - #endif // Background_Bitmap flag -//#endif - - //------------------------------------------------------------------------------- - // Repaint when focus is restored (does partial repaint), and when - // mouse is double clicked on dialog ( full repaint ). - //------------------------------------------------------------------------------- - case WM_LBUTTONDBLCLK: - case WM_SETFOCUS: - InvalidateRect( window_handle, &dlg_rect, TRUE ); -// nResult = UpdateWindow( window_handle ); -// Msg( __LINE__, TEXT(__FILE__), TEXT("WM_LBUTTONDBLCLK -- dlg_rect = [x=%d, y=%d, w=%d, h=%d]."), -// dlg_rect.left, dlg_rect.top, dlg_rect.right, dlg_rect.bottom ); - break; - - #if(BACKGROUND_BITMAP) - //------------------------------------------------------------------------------- - // bit 30 of lParam - Specifies the previous key state. - // The value is 1 if the key is down before the message is sent, - // or it is 0 if the key is up. - //------------------------------------------------------------------------------- - case WM_KEYUP: - { -// int j = 0; - - switch( w_param ) { - - case VK_ESCAPE: - SendMessage( window_handle, WM_SYSCOMMAND, SC_CLOSE, 0L ); - break; - -//#if(DISABLE_KEYBOARD) - case VK_RETURN: - //--------------------------------------------------------------- - // If the Return/Enter key is pressed... find the focused - // button and call its action. - //--------------------------------------------------------------- -// result = ( l_param & 0x40000000 ); - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] && ButtonList[i]->Get_State() == DrawButton::FOCUS_STATE ) { - SendMessage( window_handle, WM_COMMAND, ButtonList[i]->Return_Id(), 0L ); - break; - } - } - break; -//#endif - -//#if(DISABLE_KEYBOARD) - case VK_TAB: - case VK_DOWN: - { - //----------------------------------------------------------- - // Find the button with focus and "tab" to the next button by finding - // the next valid index. If past last button, circle back to the top. - //----------------------------------------------------------- - int focused_button = 0; - int next_button = 0; - - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] && ButtonList[i]->Get_State() == DrawButton::FOCUS_STATE ) { - - focused_button = i; - next_button = i+1; - - if ( next_button >= NUM_BUTTONS ) { - next_button = 0; - } - while (( next_button < NUM_BUTTONS ) && !ButtonList[ next_button ] ) { - next_button++; - } - - if ( next_button >= NUM_BUTTONS ) { - next_button = 0; - while (( next_button < NUM_BUTTONS ) && !ButtonList[ next_button ] ) { - next_button++; - } - } - break; - } - } - - //----------------------------------------------------------- - // Set the previous button to Normal status. - //----------------------------------------------------------- - if ( ButtonList[focused_button] && ( ButtonList[focused_button]->Get_State() != DrawButton::NORMAL_STATE )) { - - ButtonList[focused_button]->Set_State( DrawButton::NORMAL_STATE ); - ButtonList[focused_button]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("VK_DOWN/VK_TAB -- %s = [%s]."), ButtonList[focused_button]->Return_Normal_Bitmap(), "NORMAL_STATE" ); - } - - //----------------------------------------------------------- - // Set the new button to focus status. - //----------------------------------------------------------- - if ( ButtonList[next_button] && ( ButtonList[next_button]->Get_State() != DrawButton::FOCUS_STATE )) { - - ButtonList[next_button]->Set_State( DrawButton::FOCUS_STATE ); - ButtonList[next_button]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - PlaySound( szButtonWav, Main::hModule, SND_ASYNC | SND_RESOURCE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("VK_DOWN/VK_TAB -- %s = [%s]."), ButtonList[next_button]->Return_Normal_Bitmap(), "FOCUS_STATE" ); - } - } - break; - - case VK_UP: - { - //----------------------------------------------------------- - // Find the button with focus and "tab" to the next button by finding - // the next valid index. If past last button, circle back to the top. - //----------------------------------------------------------- - int focused_button = 0; - int next_button = 0; - - for ( i = 0; i < NUM_BUTTONS; i++ ) { - if ( ButtonList[i] && ButtonList[i]->Get_State() == DrawButton::FOCUS_STATE ) { - - focused_button = i; - next_button = i-1; - - if ( next_button < 0 ) { - next_button = NUM_BUTTONS - 1; - } - while (( next_button > 0 ) && !ButtonList[ next_button ] ) { - next_button--; - } - - if ( !ButtonList[ next_button ]) { - next_button = NUM_BUTTONS - 1; - } - while (( next_button >= 0 ) && !ButtonList[ next_button ] ) { - next_button--; - } - break; - } - } - - //----------------------------------------------------------- - // Set the previous button to Normal status. - //----------------------------------------------------------- - if ( ButtonList[focused_button] && ( ButtonList[focused_button]->Get_State() != DrawButton::NORMAL_STATE )) { - - ButtonList[focused_button]->Set_State( DrawButton::NORMAL_STATE ); - ButtonList[focused_button]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("VK_DOWN/VK_TAB -- %s = [%s]."), ButtonList[focused_button]->Return_Normal_Bitmap(), "NORMAL_STATE" ); - } - - //----------------------------------------------------------- - // Set the new button to focus status. - //----------------------------------------------------------- - if ( ButtonList[next_button] && ( ButtonList[next_button]->Get_State() != DrawButton::FOCUS_STATE )) { - - ButtonList[next_button]->Set_State( DrawButton::FOCUS_STATE ); - ButtonList[next_button]->Return_Area ( &rect ); - InvalidateRect( window_handle, &rect, FALSE ); - PlaySound( szButtonWav, Main::hModule, SND_ASYNC | SND_RESOURCE ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("VK_DOWN/VK_TAB -- %s = [%s]."), ButtonList[next_button]->Return_Normal_Bitmap(), "FOCUS_STATE" ); - } - } - break; -//#endif - - } /* end of switch */ - } /* end of case stmt */ - - return ( 0 ); - - #endif - } - return( FALSE ); -} - -//***************************************************************************** -// STOP_SOUND_PLAYING -- Stop the background sound. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: Will stop any sound started by PlaySound. -// -// HISTORY: -// 06/04/1999 MML : Created. -//============================================================================= - -void Stop_Sound_Playing ( void ) -{ - PlaySound( NULL, NULL, SND_ASYNC | SND_FILENAME ); -} - -//***************************************************************************** -// OPTIONS -- Find any user options and set the correct flags -// -// INPUT: int argc = no. of arguments to check -// BYTE *argv[] = ptr to actual command line parameters -// -// OUTPUT: -// -// WARNINGS: -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -BOOL Options( Command_Line_Arguments *Orgs ) -{ - int i; - BOOL result = TRUE; - char buffer[ MAX_ARGUMENT_LENGTH ]; - - //------------------------------------------------------------------------- - // Scan arguments for any options ( / or - followed by a letter) - //------------------------------------------------------------------------- - for ( i = 0; i < Orgs->Get_argc(); i++ ) { - - //--------------------------------------------------------------------- - // Get the next item in the list. - //--------------------------------------------------------------------- - memset( buffer, '\0', sizeof( buffer )); - strcpy( buffer, Orgs->Get_argv(i)); - - Msg( __LINE__, TEXT(__FILE__), TEXT("Options -- Argument[%d] = %s."), i, buffer ); - - //--------------------------------------------------------------------- - // If starts with / or - - //--------------------------------------------------------------------- - if (( buffer[0] == '/' ) || ( buffer[0] == '-' )) { - - switch ( tolower( buffer[1] )) { - - //------------------------------------------------------------- - // Retrieve the game's version info. - //------------------------------------------------------------- - case 'v': - { - char szPath [ MAX_PATH ]; - char szVersion[ MAX_PATH ]; - - Make_Current_Path_To( SETUP_INI_FILE1, szPath ); - GetPrivateProfileString( "Setup", "Version", "1.0", szVersion, sizeof( szVersion ), szPath ); - - LoadString( Main::hInstance, IDS_VERSION_STRING, szBuffer, MAX_PATH ); - -// sprintf( szBuffer3, "V %s", szVersion ); - sprintf( szBuffer3, szBuffer, szVersion ); -// strcpy( szBuffer, szRegistryKey ); - - MessageBox( NULL, szBuffer3, "Autorun", MB_TASKMODAL | MB_OK ); - result = FALSE; - } - break; - - //------------------------------------------------------------- - // Bypass the volume check. - //------------------------------------------------------------- - case 'n': - { - HANDLE handle; - WIN32_FIND_DATA FindFileData; - - memset( szVolumeName, '\0', MAX_PATH ); - - //----------------------------------------------------- - // If we think we are on CD2, then use PRODUCT_VOLUME_CD2. - //----------------------------------------------------- - Make_Current_Path_To( MOH_DEMO_PROGRAM, szBuffer ); - handle = FindFirstFile( szBuffer, &FindFileData ); - if ( handle == INVALID_HANDLE_VALUE ) { - strcpy( szVolumeName, PRODUCT_VOLUME_CD1 ); - } else { - strcpy( szVolumeName, PRODUCT_VOLUME_CD2 ); - FindClose( handle ); - } - - strcpy( Arguments[ NumberArguments++ ], buffer ); - } - break; - - #if( _DEBUG ) - - case 'c': - if( buffer[2] == 'd' ) { - szCDDrive[0] = buffer[3]; - szCDDrive[1] = ':'; - szCDDrive[2] = '\\'; - } - break; - - //------------------------------------------------------------- - // Change languages? - //------------------------------------------------------------- - case 'l': - { - //----------------------------------------------------- - // Identifier Meaning - // 932 Japan - // 936 Chinese (PRC, Singapore) - // 949 Korean - // 1252 Windows 3.1 Latin 1 (US, Western Europe) - //----------------------------------------------------- - char *temp = buffer+2; - int number = atoi( temp ); - - switch( number ) { - - case LANG_GER: - LanguageToUse = LANG_GER; - CodePage = 1252; - break; - - case LANG_FRE: - LanguageToUse = LANG_FRE; - CodePage = 1252; - break; - - case LANG_JAP: - LanguageToUse = LANG_JAP; - CodePage = 932; - break; - - case LANG_KOR: - LanguageToUse = LANG_KOR; - CodePage = 949; - break; - - case LANG_CHI: - LanguageToUse = LANG_CHI; - CodePage = 950; - break; - - case LANG_USA: - default: - LanguageToUse = LANG_USA; - CodePage = 1252; - break; - } - } - break; - - - #endif - - default: - strcpy( Arguments[ NumberArguments++ ], buffer ); - break; - } - } - } - - Msg( __LINE__, TEXT(__FILE__), TEXT("Options -- Language = %d"), Language ); - Msg( __LINE__, TEXT(__FILE__), TEXT("Options -- CodePage = %d"), CodePage ); - -#if(0) - struct lconv *info = localeconv(); - char szDefaultLangID[ MAX_PATH ]; - - GetLocaleInfo( - LOCALE_USER_DEFAULT, // locale identifier - LOCALE_ILANGUAGE, // type of information - szBuffer1, // address of buffer for information - MAX_PATH ); // size of buffer - - Msg( __LINE__, TEXT(__FILE__), TEXT("Options -- GetLocalInfo = %s"), szBuffer1 ); - - sprintf( szDefaultLangID, "%04X", GetUserDefaultLangID()); - Msg( __LINE__, __FILE__, "Options -- GetUserDefaultLangID() = %s", szDefaultLangID ); - - sprintf( szDefaultLangID, "%04X", GetSystemDefaultLangID()); - Msg( __LINE__, __FILE__, "Options -- GetSystemDefaultLangID() = %s", szDefaultLangID ); - Msg( __LINE__, __FILE__, "-------------------------------------------------------------" ); -#endif - - return( result ); -} - -//***************************************************************************** -// Valid_Environment -- Make sure this program is run from CD-ROM disc only -// AND it is a Win95 system. -// -// INPUT: none. -// -// OUTPUT: none. -// -// WARNINGS: returns 0 if ok to continue. -// -// HISTORY: -// 06/04/1996 MML : Created. -//============================================================================= - -BOOL Valid_Environment ( void ) -{ - bool result = 0; - - //-------------------------------------------------------------------------- - // Check Windows Version. - //-------------------------------------------------------------------------- - - int length = 0; - result = WinVersion.Meets_Minimum_Version_Requirements(); - if ( !result ) - { - std::wstring wideBuffer = TheGameText->fetch("GUI:WindowsVersionText"); - std::wstring wideBuffer2 = TheGameText->fetch("GUI:WindowsVersionTitle"); - length = wideBuffer.length(); - WideCharToMultiByte( CodePage, 0, wideBuffer.c_str(), length+1, szBuffer, _MAX_PATH, NULL, NULL ); - length = wideBuffer2.length(); - WideCharToMultiByte( CodePage, 0, wideBuffer2.c_str(), length+1, szBuffer2, _MAX_PATH, NULL, NULL ); - MessageBox( NULL, szBuffer, szBuffer2, MB_APPLMODAL | MB_OK ); - } - - return( result ); -} - -//**************************************************************************** -// LOADRESOURCEBITMAP -- Find & Load the bitmap from the resource. -// -// INPUT: HINSTANCE hInstance -- Program's hInstance. -// LPTSTR lpString -- name of bitmap to find. -// HPALETTE FAR *lphPalette -- we will return palette in this. -// -// OUTPUT: HBITMAP -- handle to the bitmap if found. -// -// WARNINGS: -// -// HISTORY: Found this routine on MS Developmemt CD, July 1996. -// 09/26/1996 MML : Created. -//============================================================================= - -HBITMAP LoadResourceBitmap( HINSTANCE hInstance, LPCTSTR lpString, HPALETTE FAR *lphPalette, bool loading_a_button ) -{ -// HDC hdc; - int iNumColors; - HRSRC hRsrc; - HGLOBAL hGlobal; - HBITMAP hBitmapFinal = NULL; - LPBITMAPINFOHEADER lpbi; - - hBitmapFinal = LoadBitmap( hInstance, lpString ); - - //-------------------------------------------------------------------------- - // Find the Bitmap in this program's resources. - //-------------------------------------------------------------------------- - hRsrc = FindResource( hInstance, lpString, RT_BITMAP ); - if ( hRsrc ) { - - //----------------------------------------------------------------------- - // Load the resource, lock the memory, grab a DC. - //----------------------------------------------------------------------- - hGlobal = LoadResource( hInstance, hRsrc ); - lpbi = (LPBITMAPINFOHEADER) LockResource( hGlobal ); - - if ( loading_a_button ) { - - //-------------------------------------------------------------------------- - // Set number of colors ( 2 to the nth ). - //-------------------------------------------------------------------------- - if ( lpbi->biBitCount <= 8 ) { - iNumColors = ( 1 << lpbi->biBitCount ); - } else { - iNumColors = 0; - } - - } else { - - //-------------------------------------------------------------------- - // Get the palette from the resource. - //-------------------------------------------------------------------- - *lphPalette = CreateDIBPalette((LPBITMAPINFO) lpbi, &iNumColors ); - } - - //----------------------------------------------------------------------- - // Free DS and memory used. - //----------------------------------------------------------------------- - UnlockResource( hGlobal ); - FreeResource( hGlobal ); - } - - return( hBitmapFinal ); -} - -//***************************************************************************** -// CREATEDIBPALETTE -- Creates the palette from the Bitmap found above. -// -// INPUT: LPBITMAPINFO lpbmi -- bitmap info from header. -// LPINT lpiNumColors -- number of colors. -// -// OUTPUT: HPALETTE -- handle to the bitmap if found. -// -// WARNINGS: -// -// HISTORY: Found this routine on MS Developmemt CD, July 1996. -// 09/26/1996 MML : Created. -//============================================================================= -HPALETTE CreateDIBPalette ( LPBITMAPINFO lpbmi, LPINT lpiNumColors ) -{ - LPBITMAPINFOHEADER lpbi; - LPLOGPALETTE lpPal; - HANDLE hLogPal; - HPALETTE hPal = NULL; - int i; - - lpbi = (LPBITMAPINFOHEADER) lpbmi; - - //-------------------------------------------------------------------------- - // Set number of colors ( 2 to the nth ). - //-------------------------------------------------------------------------- - if ( lpbi->biBitCount <= 8 ) { - *lpiNumColors = ( 1 << lpbi->biBitCount ); - } else { - *lpiNumColors = 0; - } - - //-------------------------------------------------------------------------- - // If bitmap has a palette ( bitcount ), lock some memory and create - // a palette from the bitmapinfoheader passed in. - //-------------------------------------------------------------------------- - if ( *lpiNumColors ) { - - hLogPal = GlobalAlloc( GHND, sizeof( LOGPALETTE ) + sizeof( PALETTEENTRY ) * ( *lpiNumColors )); - lpPal = (LPLOGPALETTE) GlobalLock( hLogPal ); - lpPal->palVersion = 0x300; - lpPal->palNumEntries = (WORD)*lpiNumColors; - - for ( i = 0; i < *lpiNumColors; i++ ) { - lpPal->palPalEntry[i].peRed = lpbmi->bmiColors[i].rgbRed; - lpPal->palPalEntry[i].peGreen = lpbmi->bmiColors[i].rgbGreen; - lpPal->palPalEntry[i].peBlue = lpbmi->bmiColors[i].rgbBlue; - lpPal->palPalEntry[i].peFlags = 0; - } - hPal = CreatePalette( lpPal ); - GlobalUnlock( hLogPal ); - GlobalFree( hLogPal ); - -#if(0) - StandardFileClass fileout; - char buff[2]; - - fileout.Open( "test.pal", MODE_WRITE_TRUNCATE ); - for ( i = 0; i < *lpiNumColors; i++ ) { - sprintf( buff, "%d", lpPal->palPalEntry[i].peRed >> 2 ); - fileout.Write(( void *)buff, 2 ); - sprintf( buff, "%d", lpPal->palPalEntry[i].peGreen >> 2 ); - fileout.Write(( void *)buff, 2 ); - sprintf( buff, "%d", lpPal->palPalEntry[i].peBlue >> 2 ); - fileout.Write(( void *)buff, 2 ); - } - fileout.Close(); -#endif - - } - return( hPal ); -} - -//***************************************************************************** -// LOADRESOURCEBUTTON -- Find & Load the bitmap from the resource. -// -// INPUT: HINSTANCE hInstance -- Program's hInstance. -// LPTSTR lpString -- name of bitmap to find. -// HPALETTE FAR *lphPalette -- we will return palette in this. -// -// OUTPUT: HBITMAP -- handle to the bitmap if found. -// -// WARNINGS: -// -// HISTORY: Found this routine on MS Developmemt CD, July 1996. -// 09/26/1996 MML : Created. -//============================================================================= -HBITMAP LoadResourceButton( HINSTANCE hInstance, LPCTSTR lpString, HPALETTE FAR lphPalette ) -{ - HDC hdc; - int iNumColors; - HRSRC hRsrc; - HGLOBAL hGlobal; - HBITMAP hBitmapFinal = NULL; - LPBITMAPINFOHEADER lpbi; - - //-------------------------------------------------------------------------- - // Find the Bitmap in this program's resources. - //-------------------------------------------------------------------------- - hRsrc = FindResource( hInstance, lpString, RT_BITMAP ); - if ( hRsrc ) { - - //----------------------------------------------------------------------- - // Load the resource, lock the memory, grab a DC. - //----------------------------------------------------------------------- - hGlobal = LoadResource( hInstance, hRsrc ); - lpbi = (LPBITMAPINFOHEADER) LockResource( hGlobal ); - hdc = GetDC( NULL ); - - //-------------------------------------------------------------------------- - // Set number of colors ( 2 to the nth ). - //-------------------------------------------------------------------------- - if ( lpbi->biBitCount <= 8 ) { - iNumColors = ( 1 << lpbi->biBitCount ); - } else { - iNumColors = 0; - } - - //----------------------------------------------------------------------- - // Get the palette from the resource. - // Select to the DC and realize it in the System palette. - //----------------------------------------------------------------------- -// *lphPalette = CreateDIBPalette((LPBITMAPINFO) lpbi, &iNumColors ); - if ( lphPalette != NULL ) { - SelectPalette( hdc, lphPalette, FALSE ); - RealizePalette( hdc ); - } - - //----------------------------------------------------------------------- - // Now create the bitmap itself. - //----------------------------------------------------------------------- - hBitmapFinal = CreateDIBitmap( - hdc, - (LPBITMAPINFOHEADER)lpbi, - (LONG)CBM_INIT, - (LPTSTR)lpbi + lpbi->biSize + iNumColors * sizeof( RGBQUAD ), - (LPBITMAPINFO)lpbi, - DIB_RGB_COLORS ); - - //----------------------------------------------------------------------- - // Free DS and memory used. - //----------------------------------------------------------------------- - ReleaseDC( NULL, hdc ); - UnlockResource( hGlobal ); - FreeResource( hGlobal ); - } - return( hBitmapFinal ); -} - -//***************************************************************************** -// Cant_Find_MessageBox -- Find & Load the bitmap from the resource. -// -// INPUT: HINSTANCE hInstance -- Program's hInstance. -// LPTSTR lpString -- name of bitmap to find. -// HPALETTE FAR *lphPalette -- we will return palette in this. -// -// OUTPUT: HBITMAP -- handle to the bitmap if found. -// -// WARNINGS: -// -// HISTORY: Found this routine on MS Developmemt CD, July 1996. -// 09/26/1996 MML : Created. -//============================================================================= - -void Cant_Find_MessageBox ( HINSTANCE hInstance, const char *szPath ) -{ - -#ifdef LEAN_AND_MEAN - - Locale_GetString( "Autorun:AutorunTitle", szWideBuffer ); - swprintf( szWideBuffer2, szWideBuffer, szProductName ); - Locale_GetString( "Autorun:CantFind", szWideBuffer3 ); - -#else - - std::wstring wideBuffer = TheGameText->fetch("Autorun:AutorunTitle"); - std::wstring wideBuffer2.format( wideBuffer.str(), productName.str() ); - std::wstring wideBuffer3 = TheGameText->fetch("Autorun:CantFind"); - - WideCharToMultiByte( CodePage, 0, wideBuffer3.str(), wideBuffer3.getLength()+1, szBuffer3, _MAX_PATH, NULL, NULL ); - WideCharToMultiByte( CodePage, 0, wideBuffer2.str(), wideBuffer2.getLength()+1, szBuffer2, _MAX_PATH, NULL, NULL ); - -#endif - - sprintf( szBuffer1, szBuffer3, szPath ); - - - if ( strlen( szPath ) < 3 ) - { - MessageBox( NULL, "The path specified in Cant_Find_MessageBox was blank", "Autorun", MB_APPLMODAL | MB_OK ); - return; - } - if ( strlen( szBuffer1 ) < 3 && strlen( szBuffer3 ) < 3 ) - { - MessageBox( NULL, "***MISSING MESSAGES***... IDS_AUTORUN_TITLE and IDS_CANT_FIND", "Autorun", MB_APPLMODAL | MB_OK ); - return; - } - if ( strlen( szBuffer1 ) < 3 ) - { - MessageBox( NULL, "***MISSING MESSAGE***... IDS_AUTORUN_TITLE", "Autorun", MB_APPLMODAL | MB_OK ); - return; - } - if ( strlen( szBuffer3 ) < 3 ) - { - MessageBox( NULL, "***MISSING MESSAGE***... IDS_CANT_FIND", "Autorun", MB_APPLMODAL | MB_OK ); - return; - } - - - - - MessageBox( NULL, szBuffer1, szBuffer2, MB_APPLMODAL | MB_OK ); -} - - -/****************************************************************************** - * Error_Message -- - * - * INPUT: - * - * OUTPUT: - * - * WARNINGS: none - * - * HISTORY: - * 08/14/1998 MML : Created. - *============================================================================*/ - -void Error_Message ( HINSTANCE hInstance, const char * title, const char * string, const char *path ) -{ - -#ifndef LEAN_AND_MEAN - - wideBuffer2 = TheGameText->fetch(title); - wideBuffer3 = TheGameText->fetch(string); - - if ( path && ( path[0] != '\0' )) - { - wideBuffer3.format( wideBuffer.str(), path ); - } - else - { - wideBuffer3 = wideBuffer; // insert not provided - } - - WideCharToMultiByte( CodePage, 0, wideBuffer2.str(), wideBuffer2.getLength()+1, szBuffer2, _MAX_PATH, NULL, NULL ); - WideCharToMultiByte( CodePage, 0, wideBuffer3.str(), wideBuffer3.getLength()+1, szBuffer3, _MAX_PATH, NULL, NULL ); - - MessageBox( NULL, szBuffer3, szBuffer2, MB_APPLMODAL | MB_OK ); - -#endif - - MessageBox( NULL, "ERROR_UNDEFINED", "ERROR_UNDEFINED", MB_APPLMODAL | MB_OK ); - - -} - - -/****************************************************************************** -/ Launch Class Object -/******************************************************************************/ - -LaunchObjectClass::LaunchObjectClass ( char *path, char *args ) -{ - memset( szPath, '\0', _MAX_PATH ); - memset( szArgs, '\0', _MAX_PATH ); - - if( path != NULL && path[0] != '\0' ) { - strcpy( szPath, path ); - } - if( args != NULL && args[0] != '\0' ) { - strcpy( szArgs, args ); - } -} - -void LaunchObjectClass::SetPath ( char *path ) -{ - if( path != NULL && path[0] != '\0' ) { - memset( szPath, '\0', _MAX_PATH ); - strcpy( szPath, path ); - } -} - -void LaunchObjectClass::SetArgs ( char *args ) -{ - if( args != NULL && args[0] != '\0' ) { - memset( szArgs, '\0', _MAX_PATH ); - strcpy( szArgs, args ); - } -} - -unsigned int LaunchObjectClass::Launch ( void ) -{ - char filepath [_MAX_PATH]; - char dir [_MAX_DIR]; - char ext [_MAX_EXT]; - char drive [_MAX_DRIVE]; - char file [_MAX_FNAME]; - char lpszComLine [ 127 ]; - - PROCESS_INFORMATION processinfo; - STARTUPINFO startupinfo; - unsigned int abc = 0; - unsigned int result = 0; - - memset( lpszComLine, '\0', 127 ); - - //-------------------------------------------------------------------------- - // Split into parts. - //-------------------------------------------------------------------------- - _splitpath( szPath, drive, dir, file, ext ); - - //-------------------------------------------------------------------------- - // Change current path to the correct dir. - // - // The _chdrive function changes the current working drive to the drive - // specified by drive. The drive parameter uses an integer to specify the - // new working drive (1=A, 2=B, and so forth). This function changes only - // the working drive; _chdir changes the working directory. - //-------------------------------------------------------------------------- - _makepath( filepath, drive, dir, NULL, NULL ); - Path_Remove_Back_Slash( filepath ); - - abc = (unsigned)( toupper( filepath[0] ) - 'A' + 1 ); - if ( !_chdrive( abc )) { - - //---------------------------------------------------------------------- - // Returns a value of 0 if successful. - //---------------------------------------------------------------------- - abc = _chdir( filepath ); - } - -#if (_DEBUG) - - int cde = _getdrive(); - _getcwd( szBuffer, _MAX_PATH ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("Current Working Dir = %d\\%s." ), cde, szBuffer ); -#endif - - //-------------------------------------------------------------------------- - // Try to launch the EXE... - //-------------------------------------------------------------------------- - _stprintf( lpszComLine, _TEXT( "%s %s" ), szPath, szArgs ); - - //========================================================================== - // Setup the call - //========================================================================== - memset( &startupinfo, 0, sizeof( STARTUPINFO )); - startupinfo.cb = sizeof( STARTUPINFO ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("About to launch %s." ), lpszComLine ); - - result = CreateProcess( - szPath, // address of module name - lpszComLine, // address of command line - NULL, // address of process security attributes - NULL, // address of thread security attributes - FALSE, // new process inherits handles - FALSE, - NULL, // address of new environment block - NULL, // address of current directory name - &startupinfo, // address of STARTUPINFO - &processinfo ); // address of PROCESS_INFORMATION - - //-------------------------------------------------------------------------- - // If WinExec returned 0, error occurred. - //-------------------------------------------------------------------------- - if ( !result ) { - - Msg( __LINE__, TEXT(__FILE__), TEXT("Launch of %s failed." ), lpszComLine ); - _makepath ( filepath, NULL, NULL, file, ext ); - Cant_Find_MessageBox ( Main::hInstance, filepath ); - } - Msg( __LINE__, TEXT(__FILE__), TEXT("Launch of %s succeeded." ), lpszComLine ); - - return( result ); -} - -void Debug_Date_And_Time_Stamp ( void ) -{ - //------------------------------------------------------------------------- - // tm_sec - Seconds after minute (0 - 59) - // tm_min - Minutes after hour (0 - 59) - // tm_hour - Hours after midnight (0 - 23) - // tm_mday - Day of month (1 - 31) - // tm_mon - Month (0 - 11; January = 0) - // tm_year - Year (current year minus 1900) - // tm_wday - Day of week (0 - 6; Sunday = 0) - // tm_yday - Day of year (0 - 365; January 1 = 0) - //------------------------------------------------------------------------- - static const char *Month_Strings[ 12 ] = { - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" - }; - - static const char *Week_Day_Strings[ 7 ] = { - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - }; - - char ampm[] = "AM"; - time_t ltime; - struct tm * today; - - /*------------------------------------------------------------------------- - *Convert to time structure and adjust for PM if necessary. - */ - time( <ime ); - today = localtime( <ime ); - if( today->tm_hour > 12 ) { - strcpy( ampm, "PM" ); - today->tm_hour -= 12; - } - if( today->tm_hour == 0 ) { /* Adjust if midnight hour. */ - today->tm_hour = 12; - } - - Msg( __LINE__, __FILE__, "%s, %s %d, %d %d:%d:%d %s", - Week_Day_Strings[ today->tm_wday ], - Month_Strings[ today->tm_mon ], - today->tm_mday, - today->tm_year + 1900, - today->tm_hour, - today->tm_min, - today->tm_sec, - ampm ); - - /*------------------------------------------------------------------------- - * Note how pointer addition is used to skip the first 11 - * characters and printf is used to trim off terminating - * characters. - */ -// Msg( __LINE__, __FILE__, "%s %s\n", asctime( today ), ampm ); -} - - -bool Is_On_CD ( const char *volume_name ) -{ - char volume_to_match[ MAX_PATH ]; - - Reformat_Volume_Name( volume_name, volume_to_match ); - - if( _stricmp( szVolumeName, volume_to_match ) == 0 ) { - return true; - } else { - return false; - } -} - -bool Prompt_For_CD ( HWND window_handle, char *volume_name, const char * message1, const char * message2, int *cd_drive ) -{ - int drive; - - strcpy( szBuffer, Args->Get_argv( 0 )); - drive = toupper( szBuffer[0] ) - 'A'; - memset( szBuffer, '\0', MAX_PATH ); - - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // This is the correct check for a CD Check. - // - // MML: Modified on 10/18/2000 so it would check for all available CD drives. - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - int result = IDRETRY; - - while( result == IDRETRY ) { - - if ( CD_Volume_Verification( drive, szBuffer, volume_name )) { - - result = IDOK; - *cd_drive = drive; - - } else { - - CDList.Reset_Index(); - - while(( result == IDRETRY ) && ( CDList.Get_Index() < CDList.Get_Number_Of_Drives())) { - - drive = CDList.Get_Next_CD_Drive(); - - if ( CD_Volume_Verification( drive, szBuffer, volume_name )) { - result = IDOK; - *cd_drive = drive; - } - } - } - - if ( result == IDRETRY ) { - result = ( Show_Message( window_handle, message1, message2 )); - } - } - - if ( result == IDCANCEL ) { - return( false ); -// return true; - } - - return( true ); -} - - - -int Show_Message ( HWND window_handle, const char * message1, const char * message2 ) -{ - -#ifndef LEAN_AND_MEAN - - UnicodeString string1; - UnicodeString string2; - WCHAR szString3[ MAX_PATH ]; - int result = false; - - string1 = TheGameText->fetch(message1); - string2 = TheGameText->fetch(message2); - - wcscpy( szString3, string1.str() ); - wcscat( szString3, L" " ); - wcscat( szString3, string2.str() ); - - WideCharToMultiByte( CodePage, 0, szString3, _MAX_PATH, szBuffer, _MAX_PATH, NULL, NULL ); - result = MessageBox( window_handle, szBuffer, "Autorun", MB_RETRYCANCEL|MB_APPLMODAL|MB_SETFOREGROUND ); - - return( result ); - -#else - - return ( 0 ); - -#endif - -} - - -void Reformat_Volume_Name ( const char *volume_name, char *new_volume_name ) -{ - char temp_volume_name[ MAX_PATH ]; - - strcpy( temp_volume_name, volume_name ); - - if( WinVersion.Is_Win95()) { - temp_volume_name[11] = '\0'; - } - - if( new_volume_name != NULL ) { - strcpy( new_volume_name, temp_volume_name ); - } -} - - diff --git a/Generals/Code/Tools/Autorun/autorun.h b/Generals/Code/Tools/Autorun/autorun.h deleted file mode 100644 index f249b5f520..0000000000 --- a/Generals/Code/Tools/Autorun/autorun.h +++ /dev/null @@ -1,246 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/************************************************************************************************ -* C O N F I D E N T I A L --- W E S T W O O D A S S O C I A T E S * -************************************************************************************************* -* -* FILE -* $Archive: /Renegade Setup/Autorun/autorun.h $ -* -* DESCRIPTION -* -* PROGRAMMER -* $Author: Maria_l $ -* -* VERSION INFO -* $Modtime: 1/28/02 11:11a $ -* $Revision: 10 $ -* -*************************************************************************************************/ - - -#ifndef AUTORUN_H -#define AUTORUN_H - -#include -#include -#include -#include -#include "TTFont.h" - - -//-------------------------------------------------------------------- -// Externs -//-------------------------------------------------------------------- -extern int Language; - -//-------------------------------------------------------------------- -// Structs that everyone can use. -//-------------------------------------------------------------------- -typedef enum { - LANG_USA, //0 - LANG_UK, //1 - LANG_GER, //2 - LANG_FRE, //3 - LANG_DUT, //4 - LANG_ITA, //5 - LANG_JAP, //6 - LANG_SPA, //7 - LANG_SCA, //8 - LANG_KOR, //9 - LANG_CHI, //10 - LANG_NUM, -} LanguageType; - -#define IS_LANGUAGE_DBCS(l) (((l)==LANG_CHI)||((l)==LANG_JAP)||((l)==LANG_KOR)) // [OYO] -#define IS_CODEPAGE_DBCS(C) ((C==949)||(C==950)||(C==932)) // [OYO] - -//---------------------------------------------------------------------------- -// DEFINES -//---------------------------------------------------------------------------- -#define MAX_COMMAND_LINE_ARGUMENTS 10 -#define MAX_ARGUMENT_LENGTH 80 - -#define MIN(a,b) (((a) < (b)) ? (a) : (b)) -#define MAX(a,b) (((a) > (b)) ? (a) : (b)) - -#define WM_GO (WM_USER)+1 -#define WM_USERSTAT (WM_USER + 100) - -#define EXPLORER_NAME "EXPLORER.EXE" -#define INSTALL_PATH_KEY "InstallPath" -#define INTERNET_PATH_KEY "InternetPath" -#define SETUP_NAME "Setup.exe" -#define UNINSTALL_NAME "Uninst.exe" - -#define SHELL_FOLDERS_KEY "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" -#define SHELL_UNINSTALL_KEY "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" -#define SHELL_APP_PATHS_KEY "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths" -#define PROGRAMS_SUBKEY "Programs" -#define COMMON_PROGRAMS_SUBKEY "Common Programs" -#define SOFTWARE_SUBKEY "Software" -/* -#define WESTWOOD_SUBKEY "Westwood" -#define SOFTWARE_WESTWOOD_KEY "Software\\Westwood\\" -#define WESTWOOD_WOLAPI_KEY "Software\\Westwood\\WOLAPI" -#define WESTWOOD_REGISTER_KEY "Software\\Westwood\\Register" -*/ -#define ELECTRONICARTS_SUBKEY "Electronic Arts" -#define EAGAMES_SUBKEY "EA Games" -#define GENERALS_SUBKEY "Generals" -#define SOFTWARE_EAGAMES_KEY "Software\\Electronic Arts\\EA Games\\" -#define EAGAMES_GENERALS_KEY "Software\\Electronic Arts\\EA Games\\Generals" -#define EAGAMES_ERGC_KEY "Software\\Electronic Arts\\EA Games\\Generals\\ergc" -#define LAUNCHER_FILENAME "Generals.exe" -#define WORLDBUILDER_FILENAME "WorldBuilder.exe" -#define PATCHGET_FILENAME "patchget.dat" - -#define UNINSTALL_STRING_SUBKEY "UninstallString" -#define INSTALLPATH_SUBKEY "InstallPath" -#define VERSION_SUBKEY "Version" -#define LANGUAGE_SUBKEY "Language" -#define MAPPACKVERSION_SUBKEY "MapPackVersion" - -#define DDRAW "DDRAW.DLL" -#define DSOUND "DSOUND.DLL" -#define DDHELP "DDHELP.EXE" - -#define NORMAL "Normal" -#define FOCUSED "Focused" -#define PRESSED "Pressed" -/* -#define BUTTON1NORMAL "Button1Normal" -#define BUTTON2NORMAL "Button2Normal" -#define BUTTON3NORMAL "Button3Normal" -#define BUTTON4NORMAL "Button4Normal" -#define BUTTON5NORMAL "Button5Normal" -#define BUTTON6NORMAL "Button6Normal" -#define BUTTON7NORMAL "Button7Normal" -#define BUTTON8NORMAL "Button8Normal" -#define BUTTON9NORMAL "Button8Normal" -#define BUTTON10NORMAL "Button8Normal" - -#define BUTTON1FOCUSED "Button1Focused" -#define BUTTON2FOCUSED "Button2Focused" -#define BUTTON3FOCUSED "Button3Focused" -#define BUTTON4FOCUSED "Button4Focused" -#define BUTTON5FOCUSED "Button5Focused" -#define BUTTON6FOCUSED "Button6Focused" -#define BUTTON7FOCUSED "Button7Focused" -#define BUTTON8FOCUSED "Button8Focused" -#define BUTTON9FOCUSED "Button8Focused" -#define BUTTON10FOCUSED "Button8Focused" -*/ - -#define BUTTON_REG "BUTTON_REG" -#define BUTTON_SEL "BUTTON_SEL" - -//------------------------------------------------------------------------- -// LaunchObject Class -//------------------------------------------------------------------------- -class LaunchObjectClass -{ - public: - LaunchObjectClass ( char *path=NULL, char *args=NULL ); - - void SetPath ( char *path ); - void SetArgs ( char *args ); - unsigned int Launch ( void ); - bool Launch_A_Program ( void ) { return( LaunchSomething ); }; - void Set_Launch ( bool value ) { LaunchSomething = value; }; - - public: - char szPath[ _MAX_PATH ]; - char szArgs[ _MAX_PATH ]; - bool LaunchSomething; -}; - -extern LaunchObjectClass LaunchObject; - -//------------------------------------------------------------------------- -// Main Class -//------------------------------------------------------------------------- -class Main -{ - public: - static HINSTANCE hInstance; - static HINSTANCE hPrevInstance; - static HMODULE hModule; - static int nCmdShow; - static int MessageLoop( void ); -}; - -//------------------------------------------------------------------------- -// (Base)Window Class -// -// Note that Window_Proc is a "pure virtual" function making this an -// abstract class. -//------------------------------------------------------------------------- -class Window -{ - protected: - HWND hWnd; - - public: - HWND GetHandle( void ) { return hWnd; } - BOOL Show( int nCmdShow ) { return ShowWindow( hWnd, nCmdShow ); } - void Update( void ) { UpdateWindow( hWnd ); } - virtual LRESULT Window_Proc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ) = 0; -}; - -//------------------------------------------------------------------------- -// MainWindow Class -//------------------------------------------------------------------------- -class MainWindow : public Window -{ - protected: - - static char szClassName[ 100 ]; - - public: - - MainWindow( void ); - - static void Register ( void ); - static void Reset_Class_Name ( char *string ) - { - if ( string != NULL && string[0] != '\0' ) { - strcpy( szClassName, string ); - } - }; - - BOOL Is_Product_Registered ( void ); - void Create_Buttons ( HWND hWnd, RECT *dlg_rect ); - unsigned int Run_Auto_Update ( HWND hWnd, RECT *rect ); - unsigned int Run_Demo ( HWND hWnd, RECT *rect, int cd_drive ); - BOOL Run_Explorer ( const char *, HWND hWnd, RECT *rect ); - unsigned int Run_Game ( HWND hWnd, RECT *rect ); - unsigned int Run_WorldBuilder ( HWND hWnd, RECT *rect ); - unsigned int Run_PatchGet ( HWND hWnd, RECT *rect ); - unsigned int Run_New_Account ( HWND hWnd, RECT *rect ); - unsigned int Run_Register ( HWND hWnd, RECT *rect ); - unsigned int Run_Setup ( HWND hWnd, RECT *rect, int cd_drive ); - unsigned int Run_Uninstall ( HWND hWnd, RECT *rect ); - unsigned int Run_OpenFile (int cd_drive, const char *filename, bool wait = false); - LRESULT Window_Proc ( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ); -}; - - -#endif - diff --git a/Generals/Code/Tools/Autorun/gimex.h b/Generals/Code/Tools/Autorun/gimex.h deleted file mode 100644 index e7b9fb246e..0000000000 --- a/Generals/Code/Tools/Autorun/gimex.h +++ /dev/null @@ -1,307 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* Copyright (C) Electronic Arts Canada Inc. 1994-1998. All rights reserved. */ - -/* ABSTRACT -gimex.h - Graphics IMport EXport (GIMEX) v2.26 -@ */ - -#ifndef __GIMEX_H -#define __GIMEX_H 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#define GimexVersion "2.26" - -/****************************************************************************/ -/* Data Types */ -/****************************************************************************/ - -/* ARGB structure used for palettes/pixels */ - -#ifndef _ARGB_T - #define _ARGB_T - #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(PSX) || defined(DC) - - typedef struct - { - unsigned char b,g,r,a; - } ARGB; - - #elif defined(SGI) - - typedef struct - { - unsigned char a,b,g,r; - } ARGB; - - #else /* Mac */ - - typedef struct - { - unsigned char a,r,g,b; - } ARGB; - - #endif -#endif - -/* Info structure describing bitmaps */ - -#define GIMEX_FRAMENAME_SIZE 32 -#define GIMEX_COMMENT_SIZE 256 -#define GIMEX_COLOURTBL_SIZE 256 -#define GIMEX_HOTSPOTTBL_SIZE 256 -#define GIMEX_HOTSPOTTBL_VALUES 2 - -typedef struct -{ - long signature; /* signature of gimex ie 'tga ' (optional) */ - long size; /* size of GINFO structure */ - int version; /* version number of GINFO structure (200) */ - int framenum; /* current frame */ - int width; /* width of bitmap in pixels */ - int height; /* height of bitmap in pixels */ - int bpp; /* bits per pixel (8 or 32) */ - int originalbpp; /* bits per pixel in original image (1 to 32) */ - int startcolour; /* first colour in palette */ - int numcolours; /* number of colours in original indexed palette */ - ARGB colourtbl[GIMEX_COLOURTBL_SIZE]; /* 8 bit palette */ - int subtype; /* internal format sub-type 0-default */ - int packed; /* type of packing on original image. 0 none, 1 run, n other */ - int quality; /* quality of lossy packing 0..100 */ - int framesize; /* size of frame in bytes */ - int alphabits; /* number of bits in alpha channel */ - int redbits; /* number of bits in red channel */ - int greenbits; /* number of bits in green channel */ - int bluebits; /* number of bits in blue channel */ - int centerx; /* center point relative to upper left corner */ - int centery; - int defaultx; /* default coordinate point */ - int defaulty; - int numhotspots; /* number of hot spots defined */ - char framename[GIMEX_FRAMENAME_SIZE]; /* null terminated name of frame/image */ - char comment[GIMEX_COMMENT_SIZE]; /* null terminated multiline user comment */ - int hotspottbl[GIMEX_HOTSPOTTBL_SIZE][GIMEX_HOTSPOTTBL_VALUES];/* up to 256 hot spots, XY pairs relative to upperleft */ - float dpi; /* dots per inch ie 72.0 */ - int reserved[3]; /* reserved for future use - set to zero */ -} GINFO; - -#ifndef _GSTREAM_T -#define _GSTREAM_T GIMEX -typedef void GSTREAM; /* handle used for file functions */ -#endif - -typedef struct -{ - long signature; /* signature of gimex ie 'tga ' (optional) */ - long size; /* size of GINSTANCE structure */ - int frames; /* Number of frames in file */ - int framenum; /* current frame (optional) */ - GSTREAM *gstream; /* stream pointer for file */ - char *gref; /* gimex reference to additional memory used by module (optional) */ -} GINSTANCE; - -/* Info structure describing bitmaps */ - -#define MAXMACTYPES 8 -#define MAXEXTENSIONS 8 - -#define GIMEX_EXTENSION_SIZE 8 -#define GIMEX_AUTHORSTR_SIZE 32 -#define GIMEX_VERSIONSTR_SIZE 8 -#define GIMEX_SHORTTYPESTR_SIZE 8 -#define GIMEX_WORDTYPESTR_SIZE 16 -#define GIMEX_LONGTYPESTR_SIZE 32 - -typedef struct -{ - long signature; /* signature of gimex ie 'tga ' (optional) */ - long size; /* size of GABOUT structure */ - int version; /* version number of GABOUT structure (200) */ - unsigned int canimport :1; /* supports importing */ - unsigned int canexport :1; /* supports exporting */ - unsigned int importpacked :2; /* max import packed field 0..3 */ - unsigned int exportpacked :2; /* max export packed field 0..3 */ - unsigned int import8 :1; /* supports importing 8 bit indexed */ - unsigned int export8 :1; /* supports exporting 8 bit indexed */ - unsigned int import32 :1; /* supports importing 32 bit direct rgb */ - unsigned int export32 :1; /* supports exporting 32 bit direct rgb */ - unsigned int multiframe :1; /* supports multiple frames */ - unsigned int multifile :1; /* format requires additional files or resource fork */ - unsigned int multisize :1; /* supports different size per frame */ - unsigned int framebuffer :1; /* module requires memory to buffer entire frame */ - unsigned int external :1; /* module requires external tool or plugin */ - unsigned int usesfile :1; /* module is file based vs ads/printer/generator */ - unsigned int singlepalette :1; /* limited to a single palette per file */ - unsigned int greyscale :1; /* use maxcolours for number of levels */ - unsigned int startcolour :1; /* supports start colour */ - unsigned int dotsubtype :1; /* subtype based on extension */ - unsigned int resizable :1; /* read will respect ginfo width & height */ - unsigned int pad :11; /* pad bitfield to 32 bit boundary for inter compiler compatibility */ - int maxcolours; /* only use in 8 bit, 0 if module does not care */ - int maxframename; /* maximum characters in ginfo framename */ - int defaultquality; /* default pack quality */ - long mactype[MAXMACTYPES]; /* mac file system types used */ - char extensions[MAXEXTENSIONS][GIMEX_EXTENSION_SIZE]; /* null terminated extensions with '.' */ - char authorstr[GIMEX_AUTHORSTR_SIZE]; /* name of gimex module author */ - char versionstr[GIMEX_VERSIONSTR_SIZE]; /* version number of gimex module ie 1.00 */ - char shorttypestr[GIMEX_SHORTTYPESTR_SIZE]; /* 3 or 4 character type string ie TGA */ - char wordtypestr[GIMEX_WORDTYPESTR_SIZE]; /* single word type string ie Targa */ - char longtypestr[GIMEX_LONGTYPESTR_SIZE]; /* full name of data format ie True Vision Targa */ -} GABOUT; - -/* Bitmap structure (optional) */ - -typedef struct -{ - GINFO *ginfo; - char *image; - int rowbytes; -} GBITMAP; - -#define GMAKEID(a,b,c,d) (((long)(a)<<24)|((long)(b)<<16)|((long)(c)<<8)|(long)(d)) - -#ifndef gmin -#define gmin(a,b) ((a)<(b)?(a):(b)) -#endif - -#ifndef gmax -#define gmax(a,b) ((a)>(b)?(a):(b)) -#endif - -#if !defined(GCALL) -#if defined(_MSC_VER) || defined(__WATCOMC__) -#define GCALL __stdcall -#else -#define GCALL -#endif -#endif - -/* disable unreferenced parameters warnings */ -#if defined(__WATCOMC__) -#pragma warning 202 999999 -#endif -#if defined(_MSC_VER) -#pragma warning(disable : 4100) -#endif - -#if 0 -/****************************************************************************/ -/* Gimex Module Example Prototypes */ -/****************************************************************************/ - -/* Example Information Functions */ - -GABOUT * GCALL aboutbmp(void); -int GCALL isbmp(GSTREAM *g); - -/* Example Import Functions */ - -int GCALL openbmp(GINSTANCE **gx, GSTREAM *g, char *pathname); -GINFO * GCALL infobmp(GINSTANCE *gx, int framenum); -int GCALL readbmp(GINSTANCE *gx, GINFO *ginfo, char *dest, int rowbytes); -int GCALL closebmp(GINSTANCE *gx); - -/* Example Export Functions */ - -int GCALL wopenbmp(GINSTANCE **gx, GSTREAM *g, char *pathname, int numframes); -int GCALL writebmp(GINSTANCE *gx, GINFO *ginfo, char *source, int rowbytes); -int GCALL wclosebmp(GINSTANCE *gx); - -#endif - -/****************************************************************************/ -/* Application Module Prototypes */ -/****************************************************************************/ - -/* File Stream Functions */ - -GSTREAM * GCALL gopen(const char *pathname); -GSTREAM * GCALL gwopen(const char *pathname); -int GCALL gclose(GSTREAM *g); -int GCALL gread(GSTREAM *g, void *buf, long size); -int GCALL gwrite(GSTREAM *g, void *buf, long size); -int GCALL gseek(GSTREAM *g, long offset); -long GCALL glen(GSTREAM *g); -long GCALL gtell(GSTREAM *g); - -/* Memory Functions */ - -void * GCALL galloc(long size); -int GCALL gfree(void *memptr); -void gputm(void *memptr, unsigned long val, int numbytes); -void gputi(void *memptr, unsigned long val, int numbytes); -unsigned long ggetm(void *memptr, int numbytes); -unsigned long ggeti(void *memptr, int numbytes); - -/****************************************************************************/ -/* Watcom Memory Functions */ -/****************************************************************************/ - -#if defined(__WATCOMC__) && !defined(__NOINLINE__) -#pragma aux ggeti = \ - "mov eax,[eax+ecx-4]" \ - "neg ecx" \ - "lea ecx,32[ecx*8]" \ - "shr eax,cl" \ - parm [eax] [ecx] \ - modify [eax ecx] \ - value [eax]; - -#pragma aux ggetm = \ - ".586" \ - "mov eax,[eax]" \ - "bswap eax" \ - "neg ecx" \ - "lea ecx,32[ecx*8]" \ - "shr eax,cl" \ - parm [eax] [ecx] \ - modify [eax ecx] \ - value [eax]; - -unsigned long bswap(unsigned long val); -#pragma aux bswap = "bswap eax" parm [eax] modify [eax] value [eax]; - -#define gputm(putmdest,putmdata,putmbytes) \ - (((int)(putmbytes)==4) ? ((void)(*((unsigned long *) (putmdest)) = bswap((unsigned long)(putmdata)))) \ - : (((int)(putmbytes)==1) ? ((void)(*((unsigned char *) (putmdest)) = (unsigned char)(putmdata))) \ - : (((int)(putmbytes)==2) ? ((void)(*((unsigned short *) (putmdest)) = (unsigned short)(bswap((unsigned long)(putmdata))>>16))) \ - : (((int)(putmbytes)==3) ? ((void)(*((unsigned char *) (putmdest)+2) = (unsigned char)(putmdata)),(void)(*((unsigned short *) (putmdest)) = (unsigned short)(bswap((unsigned long)(putmdata))>>8))) \ - : (void)0)))) - -#define gputi(putidest,putidata,putibytes) \ - (((int)(putibytes)==4) ? ((void)(*((unsigned long *) (putidest)) = ((unsigned long)(putidata)))) \ - : (((int)(putibytes)==1) ? ((void)(*((unsigned char *) (putidest)) = (unsigned char)(putidata))) \ - : (((int)(putibytes)==2) ? ((void)(*((unsigned short *) (putidest)) = (unsigned short)(putidata))) \ - : (((int)(putibytes)==3) ? ((void)(*((unsigned short *) (putidest)) = (unsigned short)(putidata)),(void)(*((unsigned char *) (putidest)+2) = (unsigned char)((unsigned long)(putidata)>>16))) \ - : (void)0)))) - -#endif /* __WATCOMC__ */ - -#ifdef __cplusplus -} -#endif - -#endif /* __GIMEX_H */ -/* END ABSTRACT */ - - - diff --git a/Generals/Code/Tools/Autorun/locale.cpp b/Generals/Code/Tools/Autorun/locale.cpp deleted file mode 100644 index eebeefefe1..0000000000 --- a/Generals/Code/Tools/Autorun/locale.cpp +++ /dev/null @@ -1,864 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* Copyright (C) Electronic Arts Canada Inc. 1998-1999. All rights reserved. */ - -#include -#include -#include "gimex.h" /* for file and memory IO only */ -#include "locale.h" -#include "Wnd_File.h" - -/*************************************************************************/ -/* File Format Structures */ -/*************************************************************************/ - -#define LOCALEFILE_HEADERCHUNKID 0x48434f4c /* 'LOCH' */ -#define LOCALEFILE_INDEXCHUNKID 0x49434f4c /* 'LOCI' */ -#define LOCALEFILE_LANGUAGECHUNKID 0x4c434f4c /* 'LOCL' */ - -typedef struct -{ - unsigned int ChunkID; /* 'LOCH' LOCALEFILE_HEADERCHUNKID */ - unsigned int ChunkSize; /* size of chunk in bytes */ - unsigned int Flags; /* 0=no index chunk present,1=index chunk present */ - unsigned int LanguageCount; /* number of language chunks in this file */ -/* unsigned int LanguageOffset[LanguageCount]; \\ offsets in bytes from start of file to language chunk */ -} LOCALEFILE_HEADERCHUNK; - -/* offset LOCALEFILE_HEADERCHUNK_LANGUAGE_OFFSET bytes from the start of the chunk to the language offset table */ -#define LOCALEFILE_HEADERCHUNK_LANGUAGE_OFFSET sizeof(LOCALEFILE_HEADERCHUNK) - - -typedef struct -{ - unsigned int ChunkID; /* 'LOCI' LOCALEFILE_INDEXCHUNKID */ - unsigned int ChunkSize; /* size of chunk in bytes */ - unsigned int StringCount; /* number of string ids in this chunk (same value in all language chunks) */ - unsigned int pad; /* must be zero */ -/* STRINGID StringID[StringCount]; */ -/* { */ -/* unsigned short ID; \\ id that user gives to look up value */ -/* unsigned short Index; \\ index to look up value in language chunks */ -/* } */ -} LOCALEFILE_INDEXCHUNK; - -/* offset LOCALEFILE_INDEXCHUNK_STRINGID_OFFSET bytes from the start of the chunk to the string id table */ -#define LOCALEFILE_INDEXCHUNK_STRINGID_OFFSET sizeof(LOCALEFILE_INDEXCHUNK) - - -typedef struct -{ - unsigned int ChunkID; /* 'LOCL' LOCALEFILE_LANGUAGECHUNKID */ - unsigned int ChunkSize; /* size of chunk in bytes including this header and all string data */ - unsigned int LanguageID; /* language strings are in for this bank */ - unsigned int StringCount; /* number of strings in this chunk */ -/* unsigned int StringOffset[StringCount]; \\ offsets in bytes from start of chunk to string */ -/* const char* Data[StringCount]; \\ StringCount null terminated strings */ -} LOCALEFILE_LANGUAGECHUNK; - -/* offset LOCALEFILE_LANGUAGECHUNK_STRING_OFFSETbytes from the start of the chunk to the string offset table */ -#define LOCALEFILE_LANGUAGECHUNK_STRING_OFFSET sizeof(LOCALEFILE_LANGUAGECHUNK) - - -/*************************************************************************/ -/* LOCALE_INSTANCE declaration */ -/*************************************************************************/ - -typedef LOCALEFILE_HEADERCHUNK HEADER; -typedef LOCALEFILE_INDEXCHUNK INDEX; -typedef LOCALEFILE_LANGUAGECHUNK BANK; - -typedef struct -{ - int BankIndex; /* current language bank set (0..BANK_COUNT-1) */ - BANK* pBank[LOCALE_BANK_COUNT]; /* array of string banks */ - INDEX* pIndex[LOCALE_BANK_COUNT]; /* array of string indices */ -} LOCALE_INSTANCE; - -static LOCALE_INSTANCE *lx = NULL; - -/*************************************************************************/ -/* initialization/restore */ -/*************************************************************************/ - -/* helper function to make assertions for initialization clearer */ -int LOCALE_isinitialized( void ) -{ - if ( lx == NULL ) { -// TRACE("LOCALE API is not initialized - call LOCALE_init before calling LOCALE functions\n"); - } - return( lx != NULL ); -} - -/* -; -; ABSTRACT -; -; LOCALE_init - Init the localization module -; -; -; SUMMARY -; -; #include "realfont.h" -; -; int LOCALE_init(void) -; -; DESCRIPTION -; -; Initilizes everything needed to use the locale API. Can only be called -; once until LOCALE_restore is called. -; -; Returns non-zero if everything went ok. -; -; SEE ALSO -; -; LOCALE_restore -; -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -int LOCALE_init(void) -{ - int ok = 0; - - /* ensure locale module is NOT already initialized */ - ASSERT(lx == NULL); /* can only call LOCALE_init after a restore or once, cannot double init locale API */ - - /* allocate instance */ - lx = (LOCALE_INSTANCE*)galloc(sizeof(LOCALE_INSTANCE)); - if (lx != NULL) { - memset(lx, 0, sizeof(LOCALE_INSTANCE)); - ok = 1; - } - return ok; -} - -/* -; -; ABSTRACT -; -; LOCALE_restore - Free resources used by the locale module -; -; -; SUMMARY -; -; #include "realfont.h" -; -; void LOCALE_restore(void) -; -; DESCRIPTION -; -; Restores all resources used by the locale API. Can only be called after -; LOCALE_init, and only once. -; -; SEE ALSO -; -; LOCALE_init -; -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -void LOCALE_restore(void) -{ - int i; - - if( lx != NULL ) { - - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - ASSERT(lx != NULL); - - /* free any language tables */ - for (i = 0; i < LOCALE_BANK_COUNT; i++) { - if (lx->pBank[i]) { - LOCALE_setbank(i); - LOCALE_freetable(); - } - } - - /* free instance */ - gfree(lx); - lx = NULL; - } -} - -/*************************************************************************/ -/* attributes */ -/*************************************************************************/ - -/* -; -; ABSTRACT -; -; LOCALE_setbank - Set the current bank -; -; -; SUMMARY -; -; #include "realfont.h" -; -; void LOCALE_setbank(BankIndex) -; int BankIndex; Number between 0 and LOCALE_BANK_COUNT - 1 -; -; DESCRIPTION -; -; Sets the current bank to be active. All functions will now use this -; bank for strings. A bank is slot where a string table is loaded. -; More than one bank can have a table loaded but the locale functions -; only work on one bank at a time, the active bank set by this function. -; -; SEE ALSO -; -; LOCALE_getbank -; -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -void LOCALE_setbank(int BankIndex) -{ - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - lx->BankIndex = BankIndex; -} - -/* -; -; ABSTRACT -; -; LOCALE_getbank - Get the current bank -; -; -; SUMMARY -; -; #include "realfont.h" -; -; int LOCALE_getbank(void) -; -; DESCRIPTION -; -; Returns the bank index of the current bank. -; -; SEE ALSO -; -; LOCALE_setbank -; -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -int LOCALE_getbank(void) -{ - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - return lx->BankIndex; -} - - -/* -; -; ABSTRACT -; -; LOCALE_getbanklanguageid - Get the language id for the current bank -; -; -; SUMMARY -; -; #include "realfont.h" -; -; int LOCALE_getbanklanguageid(void) -; -; DESCRIPTION -; -; Returns the language id of the current bank. This id will match -; the lanugage id in the header file generated by Locomoto -; -; SEE ALSO -; -; LOCALE_loadtable -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -int LOCALE_getbanklanguageid(void) -{ - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - ASSERT(lx->pBank[lx->BankIndex]); /* must load a table into bank before calling this function */ - return (int)(lx->pBank[lx->BankIndex]->LanguageID); -} - -/* -; -; ABSTRACT -; -; LOCALE_getbankstringcount - Get the string count for the current bank -; -; -; SUMMARY -; -; #include "realfont.h" -; -; int LOCALE_getbankstringcount(void) -; -; DESCRIPTION -; -; Returns the number of strings in the current bank. If zero is -; returned then this bank is empty. -; -; SEE ALSO -; -; LOCALE_loadtable -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -int LOCALE_getbankstringcount(void) -{ - int StringCount = 0; - - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - if (lx->pBank[lx->BankIndex]) { - StringCount = lx->pBank[lx->BankIndex]->StringCount; - } - return StringCount; -} - -/*************************************************************************/ -/* operations */ -/*************************************************************************/ - -/* -; -; ABSTRACT -; -; LOCALE_loadtable - Load a string table into the current bank -; -; -; SUMMARY -; -; #include "realfont.h" -; -; int LOCALE_loadtable(pathname, languageid) -; -; const char* pathname; // pathname of .loc file to load -; int languageid; // language id to load (from .h file) -; -; DESCRIPTION -; -; Loads the specified language from the string file into the -; current bank. Returns non zero if the operation was succesful. -; The bank must be free before you can call LOCALE_loadtable. To -; free a bank use the LOCALE_freetable function. To determine -; if the bank is free use the LOCALE_getbankstringcount function. -; -; The languageid value is available in the .h file created by -; locomoto. -; -; Returns non-zero if everthing is ok. -; -; SEE ALSO -; -; LOCALE_freetable, LOCALE_getbankstringcount -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -static int readheader( GSTREAM* g ) -{ - int ok = 0; - - /* read file header */ - LOCALEFILE_HEADERCHUNK header; - int HeaderChunkSize = sizeof(LOCALEFILE_HEADERCHUNK); - -// VERIFY(gread(g, &header, HeaderChunkSize) == HeaderChunkSize); - if( gread(g, &header, HeaderChunkSize) != HeaderChunkSize ) { - return ok; - } - - Msg( __LINE__, __FILE__, "readheader - HeaderChunkSize = %d.", HeaderChunkSize ); - Msg( __LINE__, __FILE__, "readheader - header.LanguageCount = %d.", header.LanguageCount ); - Msg( __LINE__, __FILE__, "readheader - header.Flags = %d.", header.Flags ); - - ASSERT( header.ChunkID == LOCALEFILE_HEADERCHUNKID ); /* ensure that this is a valid .loc file */ - - /* read index chunk if present */ - if ( header.Flags == 1 ) { - - int IndexChunkSize; - int IndexChunkPos = header.ChunkSize; - - /* read index chunk size */ -// VERIFY(gseek(g, IndexChunkPos + 4)); - if( !gseek( g, IndexChunkPos + 4)) { - return ok; - } - - Msg( __LINE__, __FILE__, "readheader - seek to = %d.", IndexChunkPos + 4 ); - -// VERIFY(gread(g, &IndexChunkSize, 4) == 4); - if( gread( g, &IndexChunkSize, 4) != 4 ) { - return ok; - } - - Msg( __LINE__, __FILE__, "readheader - IndexChunkSize = %d.", IndexChunkSize ); - - /* alloc and read index chunk */ - lx->pIndex[lx->BankIndex] = (LOCALEFILE_INDEXCHUNK *)galloc((long)IndexChunkSize ); - if (lx->pIndex[lx->BankIndex]) { - -// VERIFY(gseek(g, IndexChunkPos)); - gseek( g, IndexChunkPos ); - - Msg( __LINE__, __FILE__, "readheader - seek to = %d.", IndexChunkPos ); - -// VERIFY(gread(g, lx->pIndex[lx->BankIndex], IndexChunkSize) == IndexChunkSize); - if ( gread(g, lx->pIndex[lx->BankIndex], IndexChunkSize ) != IndexChunkSize ) { - return ok; - } - Msg( __LINE__, __FILE__, "readheader - IndexChunkSize = %d.", IndexChunkSize ); - - ASSERT( lx->pIndex[lx->BankIndex]->ChunkID == LOCALEFILE_INDEXCHUNKID ); - - ok = 1; - } - } - Msg( __LINE__, __FILE__, "readheader - exiting." ); - - return ok; -} - -static int readstrings( GSTREAM* g, int LanguageID ) -{ - Msg( __LINE__, __FILE__, "readstrings:: g ok? %d.", ((g!= NULL)?1:0)); - - int ok = 0; - - int LanguageChunkOffsetPos = 16 + LanguageID*4; - int LanguageChunkPos = 0; - int LanguageChunkSize = -1; - - /* read offset to language chunk */ -// VERIFY(gseek(g, (int)LanguageChunkOffsetPos)); -// VERIFY(gread(g, &LanguageChunkPos, 4) == 4); - if( !gseek( g, (int)LanguageChunkOffsetPos )) { - return ok; - } - if( gread( g, &LanguageChunkPos, 4 ) != 4 ) { - return ok; - } - - /* read language chunk size */ -// VERIFY(gseek(g, LanguageChunkPos + 4)); -// VERIFY(gread(g, &LanguageChunkSize, 4) == 4); - if( !gseek( g, LanguageChunkPos + 4 )) { - return ok; - } - if( gread( g, &LanguageChunkSize, 4 ) != 4 ) { - return ok; - } - - Msg( __LINE__, __FILE__, "readstrings::LanguageChunkOffsetPos = %d.", LanguageChunkOffsetPos ); - Msg( __LINE__, __FILE__, "readstrings::LanguageChunkPos = %d.", LanguageChunkPos ); - Msg( __LINE__, __FILE__, "readstrings::LanguageChunkSize = %d.", LanguageChunkSize ); - - /* alloc and read language chunk */ - lx->pBank[lx->BankIndex] = (LOCALEFILE_LANGUAGECHUNK *)galloc((long)LanguageChunkSize); - if (lx->pBank[lx->BankIndex]) { - - Msg( __LINE__, __FILE__, "readstrings:: A." ); - -// VERIFY(gseek(g, LanguageChunkPos)); -// VERIFY(gread(g, lx->pBank[lx->BankIndex], LanguageChunkSize) == LanguageChunkSize); - if( !gseek( g, LanguageChunkPos )) { - return ok; - } - if( gread( g, lx->pBank[lx->BankIndex], LanguageChunkSize ) != LanguageChunkSize ) { - return ok; - } - - ASSERT(lx->pBank[lx->BankIndex]->ChunkID == LOCALEFILE_LANGUAGECHUNKID); - ok = 1; - } - return ok; -} - -int LOCALE_loadtable(const char* PathName, int LanguageID) -{ - int ok = 0; - GSTREAM* g; - - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - ASSERT(lx->pBank[lx->BankIndex] == NULL); /* bank must be empty before loading a new table */ - ASSERT(lx->pIndex[lx->BankIndex] == NULL); /* bank must be empty before loading a new table */ - - g = gopen( PathName ); - if( g != NULL ) { - - Msg( __LINE__, __FILE__, "LOCALE_loadtable-- file opened." ); - - if( readheader(g)) { - - Msg( __LINE__, __FILE__, "LOCALE_loadtable-- readstrings." ); - - ok = readstrings( g, LanguageID ); - - Msg( __LINE__, __FILE__, "LOCALE_loadtable-- ok = %d ).", ok ); - } - gclose(g); - } - return ok; -} - -/* -; -; ABSTRACT -; -; LOCALE_purgetable - OBSOLETE -; -; Make all references to LOCALE_freetable -; -; END ABSTRACT -; -*/ - -/* -; -; ABSTRACT -; -; LOCALE_freetable - Free the string table in the current bank -; -; -; SUMMARY -; -; #include "realfont.h" -; -; void LOCALE_freetable(void) -; -; DESCRIPTION -; -; Frees the table loaded in the current bank. There must be a -; table loaded in the current bank. Use LOCALE_getbankstringcount -; to determine if the bank is free or not. -; -; SEE ALSO -; -; LOCALE_loadtable, LOCALE_getbankstringcount -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -void LOCALE_freetable(void) -{ - if( lx != NULL ) { - - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - ASSERT(lx->pBank[lx->BankIndex]); /* table must be loaded before calling this function */ - - /* free string bank */ - gfree(lx->pBank[lx->BankIndex]); - lx->pBank[lx->BankIndex] = NULL; - - /* if the bank has an index loaded, free that as well */ - if (lx->pIndex[lx->BankIndex]) { - gfree(lx->pIndex[lx->BankIndex]); - lx->pIndex[lx->BankIndex] = NULL; - } - } -} - -/* -; -; ABSTRACT -; -; LOCALE_getstring - Return the specified string from the current bank -; -; SUMMARY -; -; #include "realfont.h" -; -; const char* LOCALE_getstring( StringID ) -; int StringID; ID of string to return -; -; DESCRIPTION -; -; Returns the string specified from the current bank. There must -; be a string table loaded into the current bank. Use the String -; ID specified in the header file created by Locomoto. Note that -; the string pointer is a const pointer. Do not modify the string -; or the Locale library may return invalid results. -; -; If the .loc file was created with an index StringID can be any -; valid integer in the range 0..65535. If no index was created -; with the .loc file StringID will be a zero based array index. -; -; String is returned by const for a reason. Bad things will happen -; if you modify it. You have been warned. -; -; SEE ALSO -; -; LOCALE_loadtable, LOCALE_getbankstringcount -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; -; END ABSTRACT -; -*/ - -#include // for bsearch function - -static int compare ( const void* arg1, const void* arg2 ) -{ - const unsigned short* s1 = (const unsigned short*)(arg1); - const unsigned short* s2 = (const unsigned short*)(arg2); - return (*s1) - (*s2); -} - -static int getstringbyindex( unsigned short key, const INDEX* pIndex ) -{ - int index = 0; - unsigned short* result; - unsigned char* base; /* pointer to base of string id table */ - - ASSERT(LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - ASSERT(pIndex != NULL); /* index not loaded - .loc file must have index created (use -i option) */ - - base = ((unsigned char*)pIndex) + LOCALEFILE_INDEXCHUNK_STRINGID_OFFSET; - result = (unsigned short*)bsearch((unsigned char *)&key, base, pIndex->StringCount, 4, compare); - - if (result != NULL) { - /* index is the second unsigned short */ - ++result; - index = *result; - } else { - index = -1; - } - return index; -} - -const char* LOCALE_getstring( int StringID ) -{ - const char* p; /* pointer to string, NULL if string cannot be found */ - - Msg( __LINE__, __FILE__, "Locale_getstring::( %d ).", StringID ); - - ASSERT( LOCALE_isinitialized()); /* must call LOCALE_init before calling this function */ - - /* get string array index from the index if it exists */ - if ( lx->pIndex[ lx->BankIndex ] != NULL ) { - StringID = getstringbyindex((unsigned short)StringID, lx->pIndex[lx->BankIndex]); - } - - Msg( __LINE__, __FILE__, "Locale_getstring::( %d ).", StringID ); - Msg( __LINE__, __FILE__, "Locale_getstring::( lx->BankIndex = %d ).", lx->BankIndex ); - Msg( __LINE__, __FILE__, "Locale_getstring::( lx->pBank[lx->BankIndex]->StringCount = %d ).", lx->pBank[lx->BankIndex]->StringCount ); - - if ((StringID >= 0) && (StringID < (int)(lx->pBank[lx->BankIndex]->StringCount ))) { - - Msg( __LINE__, __FILE__, "Locale_getstring:: A" ); - - unsigned int offset; - - p = (const char*)(lx->pBank[lx->BankIndex]); - - Msg( __LINE__, __FILE__, "Locale_getstring:: B" ); - - offset = *(unsigned int*)(p + LOCALEFILE_LANGUAGECHUNK_STRING_OFFSET + StringID*4); - - Msg( __LINE__, __FILE__, "Locale_getstring:: C" ); - - p += offset; - - Msg( __LINE__, __FILE__, "Locale_getstring:: D" ); - - - } else { - p = NULL; - } - - Msg( __LINE__, __FILE__, L"%s", 1252, (wchar_t *)p ); - - return p; -} - - -/* -; -; ABSTRACT -; -; LOCALE_getstr - return selected string from the specified .loc file -; -; -; SUMMARY -; -; #include "realfont.h" -; -; const char* LOCALE_getstr(stringid) -; -; int stringid; // string id to return -; -; DESCRIPTION -; -; Returns the string identified by stringid from the specified -; .loc file. Use the string ID specified in the header file created -; by Locomoto. Note that the string pointer is a const pointer. Do -; not modify the string or the Locale library may return invalid results. -; -; If your strings are Unicode strings, cast the result to a const USTR *. -; -; If the .loc file was created with an index stringid can be any -; valid integer in the range 0..65535. If no index was created -; with the .loc file stringid will be a zero based array index. -; -; String is returned by const for a reason. Bad things will happen -; if you modify it. You have been warned. -; -; SEE ALSO -; -; EXAMPLE -; -; locale_eg.c -; -; Download the source -; locale_eg.csv (example data) -; -; END ABSTRACT -; -*/ - -int LOCALElanguageid = 0; - -const char* LOCALE_getstr( const void* pLocFile, int StringID ) -{ - const char* p; /* pointer to string, NULL if string cannot be found */ - - HEADER* pHeader; - BANK* pBank; - - ASSERT(pLocFile != NULL); - - pHeader = (LOCALEFILE_HEADERCHUNK*)(pLocFile); - ASSERT(pHeader->ChunkID == LOCALEFILE_HEADERCHUNKID); - ASSERT(pHeader->LanguageCount >= 1); - - if( pHeader->Flags == 1 ) { - - /* file has an index */ - INDEX* pIndex = (INDEX*)((unsigned char*)(pLocFile) + pHeader->ChunkSize); - StringID = getstringbyindex((unsigned short)StringID, pIndex); - } - - /* get pointer to string bank */ - { - int offset = *((int*)(pLocFile) + 4 + LOCALElanguageid); - pBank = (BANK*)((unsigned char*)(pLocFile) + offset); - } - - if ((StringID >= 0) && (StringID < (int)(pBank->StringCount))) { - - unsigned int offset; - - p = (const char*)(pBank); - offset = *(unsigned int*)(p + LOCALEFILE_LANGUAGECHUNK_STRING_OFFSET + StringID*4); - p += offset; - - } else { - p = NULL; - } - - return p; -} - diff --git a/Generals/Code/Tools/Autorun/locale.h b/Generals/Code/Tools/Autorun/locale.h deleted file mode 100644 index 621b4165da..0000000000 --- a/Generals/Code/Tools/Autorun/locale.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* Copyright (C) Electronic Arts Canada Inc. 1998-1999. All rights reserved. */ - -/* ABSTRACT -locale.h - REAL fonts -@ */ - -#ifndef __LOCALE_H -#define __LOCALE_H 1 - -//#ifdef __cplusplus -//extern "C" { -//#endif - - -/****************************************************************************/ -/* LOCALE API */ -/****************************************************************************/ -const char * LOCALE_getstr( const void *localefile, int stringid ); -/* NOTE: this single function replaces the previous LOCALE API */ - -/****************************************************************************/ -/* OBSOLETE LOCALE API */ -/****************************************************************************/ - -/* This API is being retired in favor of the much simplier single LOCALE_getstr function. */ - -#define LOCALE_BANK_COUNT 8 - -/* initialization/restore */ -int LOCALE_init( void ); /* call before calling any other LOCALE functions */ -void LOCALE_restore( void ); /* free all memory/resources allocated by LOCALE */ - -/* attributes */ -void LOCALE_setbank( int bankindex ); /* bankindex >= 0 && bankindex < LOCALE_BANK_COUNT */ -int LOCALE_getbank( void ); /* returns current bank id */ -int LOCALE_getbanklanguageid( void ); /* returns language id of the current bank */ -int LOCALE_getbankstringcount( void ); /* returns the string string count in the current bank */ - -/* operations */ -int LOCALE_loadtable( const char *pathname, int languageid ); /* load table into the current bank */ -void LOCALE_freetable( void ); /* free table in the current bank */ -const char * LOCALE_getstring( int stringid ); /* use values in the .h file created by locomoto */ - -/* maintain backwards compatibility */ -#define LOCALE_purgetable LOCALE_freetable - - -//#ifdef __cplusplus -//} -//#endif - -#endif /* __LOCALE_H */ -/* END ABSTRACT */ - diff --git a/Generals/Code/Tools/Autorun/resource.h b/Generals/Code/Tools/Autorun/resource.h deleted file mode 100644 index 0be22e51f5..0000000000 --- a/Generals/Code/Tools/Autorun/resource.h +++ /dev/null @@ -1,34 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by D:\Projects\Renegade\Autorun\English\AUTORUN.RC -// -#define IDD_OK 100 -#define IDD_OK2 101 -#define IDD_REGISTER 102 -#define IDD_EXPLORE 103 -#define IDD_CANCEL 104 -#define IDD_INTERNET 105 -#define IDD_UNINSTALL 106 -#define IDD_UPDATE 107 -#define IDD_NEW_ACCOUNT 108 -#define IDD_VIEW_DEMO 109 -#define IDD_GAMESPY 110 -#define IDD_OK3 111 -#define IDD_OK4 112 -#define IDD_PREVIEWS 113 -#define IDD_HELP 114 - - -#define IDS_VERSION_STRING 120 -#define IDS_CANT_FIND_FILE 121 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 117 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/Babylon/CMakeLists.txt b/Generals/Code/Tools/Babylon/CMakeLists.txt deleted file mode 100644 index ceebcead1a..0000000000 --- a/Generals/Code/Tools/Babylon/CMakeLists.txt +++ /dev/null @@ -1,66 +0,0 @@ -set(BABYLON_SRC - "bin.cpp" - "bin.h" - "DlgProxy.cpp" - "DlgProxy.h" - "excel8.cpp" - "excel8.h" - "expimp.cpp" - "expimp.h" - "ExportDlg.cpp" - "ExportDlg.h" - "fileops.cpp" - "fileops.h" - "GenerateDlg.cpp" - "GenerateDlg.h" - "iff.cpp" - "iff.h" - "list.cpp" - "list.h" - "loadsave.cpp" - "loadsave.h" - "MatchDlg.cpp" - "MatchDlg.h" - "noxstring.cpp" - "noxstring.h" - "noxstringDlg.cpp" - "noxstringDlg.h" - "olestring.cpp" - "olestring.h" - "ProceedDlg.cpp" - "ProceedDlg.h" - "Report.cpp" - "Report.h" - "resource.h" - "RetranslateDlg.cpp" - "RetranslateDlg.h" - "StdAfx.cpp" - "StdAfx.h" - "transcs.cpp" - "transcs.h" - "TransDB.cpp" - "TransDB.h" - "VerifyDlg.cpp" - "VerifyDlg.h" - "VerifyTextDlg.cpp" - "VerifyTextDlg.h" - "ViewDBsDlg.cpp" - #"VIEWDBSII.cpp" - "VIEWDBSII.h" - "XLStuff.cpp" - "XLStuff.h" -) - -add_executable(g_babylon WIN32) -set_target_properties(g_babylon PROPERTIES OUTPUT_NAME noxstring) - -target_sources(g_babylon PRIVATE ${BABYLON_SRC}) - -target_link_libraries(g_babylon PRIVATE - core_config -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_compile_definitions(g_babylon PRIVATE _AFXDLL) - target_sources(g_babylon PRIVATE noxstring.rc) -endif() diff --git a/Generals/Code/Tools/Babylon/DlgProxy.cpp b/Generals/Code/Tools/Babylon/DlgProxy.cpp deleted file mode 100644 index beb5401589..0000000000 --- a/Generals/Code/Tools/Babylon/DlgProxy.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// DlgProxy.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "DlgProxy.h" -#include "noxstringDlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringDlgAutoProxy - -IMPLEMENT_DYNCREATE(CNoxstringDlgAutoProxy, CCmdTarget) - -CNoxstringDlgAutoProxy::CNoxstringDlgAutoProxy() -{ - EnableAutomation(); - - // To keep the application running as long as an automation - // object is active, the constructor calls AfxOleLockApp. - AfxOleLockApp(); - - // Get access to the dialog through the application's - // main window pointer. Set the proxy's internal pointer - // to point to the dialog, and set the dialog's back pointer to - // this proxy. - ASSERT (AfxGetApp()->m_pMainWnd != NULL); - ASSERT_VALID (AfxGetApp()->m_pMainWnd); - ASSERT_KINDOF(CNoxstringDlg, AfxGetApp()->m_pMainWnd); - m_pDialog = (CNoxstringDlg*) AfxGetApp()->m_pMainWnd; - m_pDialog->m_pAutoProxy = this; -} - -CNoxstringDlgAutoProxy::~CNoxstringDlgAutoProxy() -{ - // To terminate the application when all objects created with - // with automation, the destructor calls AfxOleUnlockApp. - // Among other things, this will destroy the main dialog - if (m_pDialog != NULL) - m_pDialog->m_pAutoProxy = NULL; - AfxOleUnlockApp(); -} - -void CNoxstringDlgAutoProxy::OnFinalRelease() -{ - // When the last reference for an automation object is released - // OnFinalRelease is called. The base class will automatically - // deletes the object. Add additional cleanup required for your - // object before calling the base class. - - CCmdTarget::OnFinalRelease(); -} - -BEGIN_MESSAGE_MAP(CNoxstringDlgAutoProxy, CCmdTarget) - //{{AFX_MSG_MAP(CNoxstringDlgAutoProxy) - // NOTE - the ClassWizard will add and remove mapping macros here. - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -BEGIN_DISPATCH_MAP(CNoxstringDlgAutoProxy, CCmdTarget) - //{{AFX_DISPATCH_MAP(CNoxstringDlgAutoProxy) - // NOTE - the ClassWizard will add and remove mapping macros here. - //}}AFX_DISPATCH_MAP -END_DISPATCH_MAP() - -// Note: we add support for IID_INoxstring to support typesafe binding -// from VBA. This IID must match the GUID that is attached to the -// dispinterface in the .ODL file. - -// {2BF31248-3BA1-11D3-B9DA-006097B90D93} -static const IID IID_INoxstring = -{ 0x2bf31248, 0x3ba1, 0x11d3, { 0xb9, 0xda, 0x0, 0x60, 0x97, 0xb9, 0xd, 0x93 } }; - -BEGIN_INTERFACE_MAP(CNoxstringDlgAutoProxy, CCmdTarget) - INTERFACE_PART(CNoxstringDlgAutoProxy, IID_INoxstring, Dispatch) -END_INTERFACE_MAP() - -// The IMPLEMENT_OLECREATE2 macro is defined in StdAfx.h of this project -// {2BF31246-3BA1-11D3-B9DA-006097B90D93} -IMPLEMENT_OLECREATE2(CNoxstringDlgAutoProxy, "Noxstring.Application", 0x2bf31246, 0x3ba1, 0x11d3, 0xb9, 0xda, 0x0, 0x60, 0x97, 0xb9, 0xd, 0x93) - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringDlgAutoProxy message handlers diff --git a/Generals/Code/Tools/Babylon/DlgProxy.h b/Generals/Code/Tools/Babylon/DlgProxy.h deleted file mode 100644 index 75313d0258..0000000000 --- a/Generals/Code/Tools/Babylon/DlgProxy.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// DlgProxy.h : header file -// - -#if !defined(AFX_DLGPROXY_H__2BF3124F_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_DLGPROXY_H__2BF3124F_3BA1_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -class CNoxstringDlg; - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringDlgAutoProxy command target - -class CNoxstringDlgAutoProxy : public CCmdTarget -{ - DECLARE_DYNCREATE(CNoxstringDlgAutoProxy) - - CNoxstringDlgAutoProxy(); // protected constructor used by dynamic creation - -// Attributes -public: - CNoxstringDlg* m_pDialog; - -// Operations -public: - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CNoxstringDlgAutoProxy) - public: - virtual void OnFinalRelease(); - //}}AFX_VIRTUAL - -// Implementation -protected: - virtual ~CNoxstringDlgAutoProxy(); - - // Generated message map functions - //{{AFX_MSG(CNoxstringDlgAutoProxy) - // NOTE - the ClassWizard will add and remove member functions here. - //}}AFX_MSG - - DECLARE_MESSAGE_MAP() - DECLARE_OLECREATE(CNoxstringDlgAutoProxy) - - // Generated OLE dispatch map functions - //{{AFX_DISPATCH(CNoxstringDlgAutoProxy) - // NOTE - the ClassWizard will add and remove member functions here. - //}}AFX_DISPATCH - DECLARE_DISPATCH_MAP() - DECLARE_INTERFACE_MAP() -}; - -///////////////////////////////////////////////////////////////////////////// - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_DLGPROXY_H__2BF3124F_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/ExportDlg.cpp b/Generals/Code/Tools/Babylon/ExportDlg.cpp deleted file mode 100644 index 0b410f91af..0000000000 --- a/Generals/Code/Tools/Babylon/ExportDlg.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// ExportDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "ExportDlg.h" -#include "direct.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -static int max_index; - -///////////////////////////////////////////////////////////////////////////// -// CExportDlg dialog - - -CExportDlg::CExportDlg(CWnd* pParent /*=NULL*/) - : CDialog(CExportDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(CExportDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void CExportDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CExportDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CExportDlg, CDialog) - //{{AFX_MSG_MAP(CExportDlg) - ON_CBN_SELCHANGE(IDC_COMBOLANG, OnSelchangeCombolang) - ON_CBN_SELENDOK(IDC_COMBOLANG, OnSelendokCombolang) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CExportDlg message handlers - -void CExportDlg::OnOK() -{ - char buffer[100]; - char *ptr; - // TODO: Add extra validation here - CEdit *edit = (CEdit *) GetDlgItem ( IDC_FILENAME ); - CButton *all = (CButton *) GetDlgItem ( IDC_RADIOALL ); - CButton *button; - CButton *sample = (CButton *) GetDlgItem ( IDC_RADIOSAMPLE ); - CButton *dialog = (CButton *) GetDlgItem ( IDC_RADIODIALOG ); - CButton *nondialog = (CButton *) GetDlgItem ( IDC_RADIONONDIALOG ); - CButton *unverified = (CButton *) GetDlgItem ( IDC_RADIOUNVERIFIED ); - CButton *missing = (CButton *) GetDlgItem ( IDC_RADIOMISSING ); - CButton *unsent = (CButton *) GetDlgItem ( IDC_RADIOUNSENT ); - - edit->GetWindowText ( buffer, sizeof ( filename) -1 ); - _getcwd ( filename, sizeof (filename ) -1 ); - strcat ( filename, "\\" ); - if ( ( ptr = strchr ( buffer, '.' ))) - { - *ptr = 0; - } - strcat ( filename, buffer ); - if ( all->GetCheck ()) - { - options.filter = TR_ALL; - } - else if ( dialog->GetCheck ()) - { - options.filter = TR_DIALOG; - } - else if ( nondialog->GetCheck ()) - { - options.filter = TR_NONDIALOG; - } - else if ( sample->GetCheck ()) - { - options.filter = TR_SAMPLE; - } - else if ( unverified->GetCheck ()) - { - options.filter = TR_UNVERIFIED; - } - else if ( missing->GetCheck ()) - { - options.filter = TR_MISSING_DIALOG; - } - else if ( unsent->GetCheck ()) - { - options.filter = TR_UNSENT; - } - else - { - options.filter = TR_CHANGES; - } - - options.include_comments = FALSE; - button = (CButton *) GetDlgItem ( IDC_CHECKTRANS ); - options.include_translations = button->GetCheck (); - - CDialog::OnOK(); -} - -void CExportDlg::OnCancel() -{ - // TODO: Add extra cleanup here - langid = LANGID_UNKNOWN; - CDialog::OnCancel(); -} - -BOOL CExportDlg::OnInitDialog() -{ - int index; - int lang_index; - LANGINFO *info; - CComboBox *combo; - CEdit *edit = (CEdit *) GetDlgItem ( IDC_FILENAME ); - CButton *button = (CButton *) GetDlgItem ( IDC_RADIOCHANGES ); - - - CDialog::OnInitDialog(); - - // TODO: Add extra initialization here - combo = (CComboBox *) GetDlgItem ( IDC_COMBOLANG ); - - combo->SetItemDataPtr ( 0, NULL ); - - options.filter = TR_CHANGES; - options.include_comments = FALSE; - options.include_translations = FALSE; - langid = LANGID_UNKNOWN; - filename[0] = 0; - button->SetCheck ( 1 ); - - - - index = 0; - lang_index = 0; - got_lang = FALSE; - while ( (info = GetLangInfo ( lang_index )) ) - { - if ( TRUE )//info->langid != LANGID_US ) - { - combo->InsertString ( index, info->name ); - combo->SetItemDataPtr ( index, info ); - if ( info->langid == CurrentLanguage ) - { - combo->SetCurSel ( index ); - got_lang = TRUE; - } - index++; - } - - lang_index++; - } - max_index = index; - - if ( !got_lang ) - { - combo->InsertString ( 0, "Select language" ); - combo->SetCurSel ( 0 ); - max_index++; - } - - edit->SetLimitText ( 8 ); - OnSelchangeCombolang (); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CExportDlg::OnSelchangeCombolang() -{ - // TODO: Add your control notification handler code here - LANGINFO *info = NULL; - int index; - CButton *export_button = (CButton *) GetDlgItem ( IDOK ); - CComboBox *combo = (CComboBox *) GetDlgItem ( IDC_COMBOLANG ); - CEdit *edit = (CEdit *) GetDlgItem ( IDC_FILENAME ); - - index = combo->GetCurSel (); - - if ( index >= 0 && index < max_index ) - { - info = (LANGINFO *) combo->GetItemDataPtr ( index ); - } - - if ( info ) - { - char buffer[10]; - edit->EnableWindow ( TRUE ); - sprintf ( buffer, "Generals_%s", info->initials ); - edit->SetWindowText ( buffer ); - export_button->EnableWindow ( TRUE ); - langid = info->langid; - if ( !got_lang ) - { - combo->DeleteString ( 0 ); - max_index--; - got_lang = TRUE; - } - } - else - { - edit->SetWindowText (""); - edit->EnableWindow ( FALSE ); - export_button->EnableWindow ( FALSE ); - langid = LANGID_UNKNOWN; - } - -} - -void CExportDlg::OnSelendokCombolang() -{ - // TODO: Add your control notification handler code here - int i = 0; -} diff --git a/Generals/Code/Tools/Babylon/ExportDlg.h b/Generals/Code/Tools/Babylon/ExportDlg.h deleted file mode 100644 index 34269c519a..0000000000 --- a/Generals/Code/Tools/Babylon/ExportDlg.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_EXPORTDLG_H__DDA81307_4F1A_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_EXPORTDLG_H__DDA81307_4F1A_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// ExportDlg.h : header file -// - -#include "expimp.h" - -///////////////////////////////////////////////////////////////////////////// -// CExportDlg dialog - -class CExportDlg : public CDialog -{ - LangID langid; - char filename[200]; - TROPTIONS options; - int got_lang; - -// Construction -public: - - LangID Language ( void ) { return langid; }; - char* Filename ( void ) { return filename; }; - TROPTIONS* Options ( void ) { return &options; }; - - CExportDlg(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CExportDlg) - enum { IDD = IDD_EXPORT }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CExportDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CExportDlg) - virtual void OnOK(); - virtual void OnCancel(); - virtual BOOL OnInitDialog(); - afx_msg void OnSelchangeCombolang(); - afx_msg void OnSelendokCombolang(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_EXPORTDLG_H__DDA81307_4F1A_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/GenerateDlg.cpp b/Generals/Code/Tools/Babylon/GenerateDlg.cpp deleted file mode 100644 index 9bd34e6040..0000000000 --- a/Generals/Code/Tools/Babylon/GenerateDlg.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// GenerateDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "GenerateDlg.h" -#include "direct.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CGenerateDlg dialog - - -CGenerateDlg::CGenerateDlg(CWnd* pParent /*=NULL*/) - : CDialog(CGenerateDlg::IDD, pParent) -{ - options.format = GN_UNICODE; - options.untranslated = GN_USEIDS; - langids[0] = LANGID_UNKNOWN; - filename[0] = 0; - //{{AFX_DATA_INIT(CGenerateDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void CGenerateDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CGenerateDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CGenerateDlg, CDialog) - //{{AFX_MSG_MAP(CGenerateDlg) - ON_BN_CLICKED(IDC_SELECTALL, OnSelectall) - ON_BN_CLICKED(IDC_INVERT, OnInvert) - ON_EN_CHANGE(IDC_PREFIX, OnChangePrefix) - ON_BN_CLICKED(IDC_NOXSTR, OnNoxstr) - ON_BN_CLICKED(IDC_UNICODE, OnUnicode) - ON_BN_CLICKED(IDC_IDS, OnIds) - ON_BN_CLICKED(IDC_ORIGINAL, OnOriginal) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CGenerateDlg message handlers - -BOOL CGenerateDlg::OnInitDialog() -{ - int index; - LANGINFO *info; - - edit = (CEdit *) GetDlgItem ( IDC_PREFIX ); - unicode = (CButton *) GetDlgItem ( IDC_UNICODE ); - strfile = (CButton *) GetDlgItem ( IDC_NOXSTR ); - useids = (CButton *) GetDlgItem ( IDC_IDS ); - usetext = (CButton *) GetDlgItem ( IDC_ORIGINAL ); - list = (CListBox *) GetDlgItem ( IDC_LANGUAGE ); - filetext = ( CStatic *) GetDlgItem ( IDC_FILENAME ); - - CDialog::OnInitDialog(); - - // TODO: Add extra initialization here - - unicode->SetCheck ( 1 ); - useids->SetCheck ( 1 ); - edit->SetWindowText ( "Generals" ); - edit->SetLimitText ( 5 ); - - OnChangePrefix (); - - - index = 0; - while ( (info = GetLangInfo ( index )) ) - { - list->InsertString ( index, info->name ); - if ( info->langid == CurrentLanguage ) - { - list->SetSel ( index ); - } - - index++; - } - num_langs = index; - - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CGenerateDlg::OnSelectall() -{ - // TODO: Add your control notification handler code here - list->SelItemRange ( TRUE, 0, num_langs-1 ); -} - -void CGenerateDlg::OnInvert() -{ - // TODO: Add your control notification handler code here - int index = 0; - - - while ( index < num_langs ) - { - list->SetSel ( index, !list->GetSel ( index )); - index++; - } - - -} - -void CGenerateDlg::OnChangePrefix() -{ - char buffer[30]; - - edit->GetWindowText ( buffer, 6 ); - - if ( options.format == GN_NOXSTR ) - { - strcat ( buffer, "_{xx}.str" ); - } - else - { - strcat ( buffer, "_{xx}.csf" ); - } - - filetext->SetWindowText ( buffer ); - -} - -void CGenerateDlg::OnNoxstr() -{ - // TODO: Add your control notification handler code here - options.format = GN_NOXSTR; - OnChangePrefix (); - unicode->SetCheck ( 0 ); - - -} - -void CGenerateDlg::OnUnicode() -{ - // TODO: Add your control notification handler code here - options.format = GN_UNICODE; - OnChangePrefix (); - strfile->SetCheck ( 0 ); - -} - -void CGenerateDlg::OnCancel() -{ - // TODO: Add extra cleanup here - - CDialog::OnCancel(); -} - -void CGenerateDlg::OnOK() -{ - char buffer[30]; - int count; - int i; - // TODO: Add extra validation here - - edit->GetWindowText ( buffer, sizeof ( filename) -1 ); - _getcwd ( filename, sizeof (filename ) -1 ); - strcat ( filename, "\\" ); - strcat ( filename, buffer ); - - count = list->GetSelItems ( num_langs, langindices ); - - if ( !count ) - { - AfxMessageBox ( "No languages selected" ); - return; - } - - num_langs = 0; - for ( i = 0; i langid; - } - } - - langids[num_langs] = LANGID_UNKNOWN; - - - CDialog::OnOK(); -} - -void CGenerateDlg::OnIds() -{ - options.untranslated = GN_USEIDS; - usetext->SetCheck ( 0 ); - -} - -void CGenerateDlg::OnOriginal() -{ - options.untranslated = GN_USEORIGINAL; - useids->SetCheck ( 0 ); -} diff --git a/Generals/Code/Tools/Babylon/GenerateDlg.h b/Generals/Code/Tools/Babylon/GenerateDlg.h deleted file mode 100644 index 4531a6c815..0000000000 --- a/Generals/Code/Tools/Babylon/GenerateDlg.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_GENERATEDLG_H__959D0D41_50A5_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_GENERATEDLG_H__959D0D41_50A5_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// GenerateDlg.h : header file -// - -#include "expimp.h" - -///////////////////////////////////////////////////////////////////////////// -// CGenerateDlg dialog - -class CGenerateDlg : public CDialog -{ - char filename[200]; - GNOPTIONS options; - LangID langids[200]; - int langindices[200]; - int num_langs; - CListBox *list; - CEdit *edit; - CStatic *filetext; - CButton *unicode; - CButton *strfile; - CButton *useids; - CButton *usetext; - -// Construction -public: - CGenerateDlg(CWnd* pParent = NULL); // standard constructor - - char* FilePrefix ( void ) { return filename; }; - GNOPTIONS* Options ( void ) { return &options; }; - LangID* Langauges ( void ) { return langids; }; - -// Dialog Data - //{{AFX_DATA(CGenerateDlg) - enum { IDD = IDD_GENERATE }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CGenerateDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CGenerateDlg) - virtual BOOL OnInitDialog(); - afx_msg void OnSelectall(); - afx_msg void OnInvert(); - afx_msg void OnChangePrefix(); - afx_msg void OnNoxstr(); - afx_msg void OnUnicode(); - virtual void OnCancel(); - virtual void OnOK(); - afx_msg void OnIds(); - afx_msg void OnOriginal(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_GENERATEDLG_H__959D0D41_50A5_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/MatchDlg.cpp b/Generals/Code/Tools/Babylon/MatchDlg.cpp deleted file mode 100644 index 4a1d7ddd66..0000000000 --- a/Generals/Code/Tools/Babylon/MatchDlg.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// MatchDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "MatchDlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -NoxText *MatchingNoxText = NULL; -NoxText *MatchOriginalText; -NoxLabel *MatchLabel; - -#define MAX_MATCH 256 -static NoxText *current_match = NULL; - -///////////////////////////////////////////////////////////////////////////// -// CMatchDlg dialog - - -CMatchDlg::CMatchDlg(CWnd* pParent /*=NULL*/) - : CDialog(CMatchDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(CMatchDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void CMatchDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CMatchDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CMatchDlg, CDialog) - //{{AFX_MSG_MAP(CMatchDlg) - ON_BN_CLICKED(IDC_NOMATCH, OnNomatch) - ON_BN_CLICKED(IDC_MATCH, OnMatch) - ON_BN_CLICKED(IDC_SKIP, OnSkip) - ON_CBN_SELCHANGE(IDC_MATCHCOMBO, OnSelchangeMatchcombo) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CMatchDlg message handlers - -void CMatchDlg::OnCancel() -{ - // TODO: Add extra cleanup here - - MatchingNoxText = NULL; - CDialog::OnCancel(); -} - -void CMatchDlg::OnNomatch() -{ - // TODO: Add your control notification handler code here - MatchingNoxText = NULL; - CDialog::OnOK (); -} - -void CMatchDlg::OnMatch() -{ - // TODO: Add your control notification handler code here - if ( (MatchingNoxText = current_match ) ) - { - CButton *check = (CButton *) GetDlgItem ( IDC_CHECKRETRANSLATE ); - - current_match->SetRetranslate ( check->GetCheck ()); - } - CDialog::OnOK (); -} - -BOOL CMatchDlg::OnInitDialog() -{ - NoxText *text; - ListSearch sh; - int index; - CStatic *newtext; - CComboBox *combo; - static char buffer[4*1024]; - - - sprintf ( buffer, "Resolve umatched text from \"%s\" on line %d", MatchLabel->NameSB(), - MatchOriginalText->LineNumber() ); - SetWindowText ( buffer ); - CDialog::OnInitDialog(); - - current_match = NULL; - - newtext = (CStatic *) GetDlgItem ( IDC_NEWTEXT ); - newtext->SetWindowText ( MatchOriginalText->GetSB()); - - combo = (CComboBox *) GetDlgItem ( IDC_MATCHCOMBO ); - CButton *check = (CButton *) GetDlgItem ( IDC_CHECKRETRANSLATE ); - check->SetCheck ( 1 ); - - text = MatchLabel->FirstText ( sh ); - index = 0; - - while ( text ) - { - if ( !text->Matched ()) - { - int result; - - result = combo->InsertString ( index, text->GetSB ()); - result = combo->SetItemDataPtr ( index, text ); - - if ( result == CB_ERR ) - { - result = 0; - } - if ( result == CB_ERRSPACE ) - { - result = 0; - } - index++; - } - - text = MatchLabel->NextText ( sh ); - } - - combo->SetCurSel ( 0 ); - OnSelchangeMatchcombo(); - MatchingNoxText = NULL; - // TODO: Add extra initialization here - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - - -void CMatchDlg::OnSelchangeMatchcombo() -{ - // TODO: Add your control notification handler code here - int index; - CComboBox *combo = (CComboBox *) GetDlgItem ( IDC_MATCHCOMBO ); - - index = combo->GetCurSel (); - - if ( index >= 0 ) - { - CStatic *newtext = (CStatic *) GetDlgItem ( IDC_MATCHTEXT ); - current_match = (NoxText *) combo->GetItemDataPtr ( index ); - newtext->SetWindowText ( current_match->GetSB()); - } - else - { - current_match = NULL; - } -} - -void CMatchDlg::OnSkip() -{ - // TODO: Add your control notification handler code here - EndDialog ( IDSKIP ); -} - - diff --git a/Generals/Code/Tools/Babylon/MatchDlg.h b/Generals/Code/Tools/Babylon/MatchDlg.h deleted file mode 100644 index fa7c19a646..0000000000 --- a/Generals/Code/Tools/Babylon/MatchDlg.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_MATCHDLG_H__FA868061_4EA7_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_MATCHDLG_H__FA868061_4EA7_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// MatchDlg.h : header file -// - -#include "TransDB.h" -#define IDSKIP 100 - -///////////////////////////////////////////////////////////////////////////// -// CMatchDlg dialog - -class CMatchDlg : public CDialog -{ -// Construction -public: - CMatchDlg(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CMatchDlg) - enum { IDD = IDD_MATCH }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CMatchDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CMatchDlg) - virtual void OnCancel(); - afx_msg void OnNomatch(); - afx_msg void OnMatch(); - virtual BOOL OnInitDialog(); - afx_msg void OnSkip(); - afx_msg void OnSelchangeMatchcombo(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -extern NoxText *MatchingNoxText; -extern NoxText *MatchOriginalText; -extern NoxLabel *MatchLabel; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_MATCHDLG_H__FA868061_4EA7_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/ProceedDlg.cpp b/Generals/Code/Tools/Babylon/ProceedDlg.cpp deleted file mode 100644 index be572b825e..0000000000 --- a/Generals/Code/Tools/Babylon/ProceedDlg.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// ProceedDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "ProceedDlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// ProceedDlg dialog - - -ProceedDlg::ProceedDlg(const char *nmessage, CWnd* pParent /*=NULL*/) - : CDialog(ProceedDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(ProceedDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT - message = nmessage; -} - - -void ProceedDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(ProceedDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(ProceedDlg, CDialog) - //{{AFX_MSG_MAP(ProceedDlg) - ON_BN_CLICKED(IDC_YES, OnYes) - ON_BN_CLICKED(IDC_ALWAYS, OnAlways) - ON_BN_CLICKED(IDC_NO, OnNo) - ON_WM_CLOSE() - ON_BN_CLICKED(IDC_BUTTON_NO, OnNo) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// ProceedDlg message handlers - -void ProceedDlg::OnYes() -{ - // TODO: Add your control notification handler code here - EndDialog ( IDYES ); - -} - -void ProceedDlg::OnAlways() -{ - // TODO: Add your control notification handler code here - EndDialog ( IDALWAYS ); - -} - -void ProceedDlg::OnNo() -{ - // TODO: Add your control notification handler code here - EndDialog ( IDNO ); - -} - -void ProceedDlg::OnClose() -{ - // TODO: Add your message handler code here and/or call default - - EndDialog ( IDNO ); - CDialog::OnClose(); -} - -BOOL ProceedDlg::OnInitDialog() -{ - CDialog::OnInitDialog(); - - SetDlgItemText ( IDC_MESSAGE, message ); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} diff --git a/Generals/Code/Tools/Babylon/ProceedDlg.h b/Generals/Code/Tools/Babylon/ProceedDlg.h deleted file mode 100644 index a75bb20c1d..0000000000 --- a/Generals/Code/Tools/Babylon/ProceedDlg.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_PROCEEDDLG_H__35C33E24_5AD8_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_PROCEEDDLG_H__35C33E24_5AD8_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// ProceedDlg.h : header file -// -#define IDALWAYS 101 - -///////////////////////////////////////////////////////////////////////////// -// ProceedDlg dialog - -class ProceedDlg : public CDialog -{ -// Construction - const char *message; -public: - ProceedDlg(const char *message, CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(ProceedDlg) - enum { IDD = IDD_PROCEED }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(ProceedDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(ProceedDlg) - afx_msg void OnYes(); - afx_msg void OnAlways(); - afx_msg void OnNo(); - afx_msg void OnClose(); - virtual BOOL OnInitDialog(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_PROCEEDDLG_H__35C33E24_5AD8_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/Report.cpp b/Generals/Code/Tools/Babylon/Report.cpp deleted file mode 100644 index d3a4a97229..0000000000 --- a/Generals/Code/Tools/Babylon/Report.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Report.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "Report.h" -#include - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CReport dialog - - -CReport::CReport(CWnd* pParent /*=NULL*/) - : CDialog(CReport::IDD, pParent) -{ - - options.translations = TRUE; - options.dialog = TRUE; - options.limit = 0; - langids[0] = LANGID_UNKNOWN; - filename[0] = 0; - //{{AFX_DATA_INIT(CReport) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void CReport::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CReport) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CReport, CDialog) - //{{AFX_MSG_MAP(CReport) - ON_BN_CLICKED(IDC_INVERT, OnInvert) - ON_BN_CLICKED(IDC_SELECTALL, OnSelectall) - ON_BN_CLICKED(IDC_SHOW_DETAILS, OnShowDetails) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CReport message handlers - -BOOL CReport::OnInitDialog() -{ - int index; - LANGINFO *info; - - limit = (CEdit *) GetDlgItem ( IDC_LIMIT ); - trans_status = (CButton *) GetDlgItem ( IDC_TRANSLATION_STATUS ); - dialog_status = (CButton *) GetDlgItem ( IDC_DIALOG_STATUS ); - show_details = (CButton *) GetDlgItem ( IDC_SHOW_DETAILS ); - ifless = (CButton *) GetDlgItem ( IDC_IFLESS ); - list = (CListBox *) GetDlgItem ( IDC_LANGUAGE ); - items = (CStatic *) GetDlgItem ( IDC_ITEMS ); - - CDialog::OnInitDialog(); - - // TODO: Add extra initialization here - - trans_status->SetCheck ( options.translations ); - dialog_status->SetCheck ( options.dialog ); - show_details->SetCheck ( 0 ); - ifless->SetCheck ( 1 ); - limit->EnableWindow ( FALSE ); - ifless->EnableWindow ( FALSE ); - items->EnableWindow ( FALSE ); - limit->SetWindowText ( "100" ); - limit->SetLimitText ( 50 ); - options.limit = 100; - - index = 0; - while ( (info = GetLangInfo ( index )) ) - { - list->InsertString ( index, info->name ); - if ( info->langid == CurrentLanguage ) - { - list->SetSel ( index ); - } - - index++; - } - num_langs = index; - - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CReport::OnSelectall() -{ - // TODO: Add your control notification handler code here - list->SelItemRange ( TRUE, 0, num_langs-1 ); -} - -void CReport::OnInvert() -{ - // TODO: Add your control notification handler code here - int index = 0; - - - while ( index < num_langs ) - { - list->SetSel ( index, !list->GetSel ( index )); - index++; - } - - -} - - - -void CReport::OnShowDetails() -{ - // TODO: Add your control notification handler code here - if ( show_details->GetCheck () == 0 ) - { - ifless->EnableWindow ( FALSE ); - limit->EnableWindow ( FALSE ); - items->EnableWindow ( FALSE ); - } - else - { - ifless->EnableWindow ( TRUE ); - limit->EnableWindow ( TRUE ); - items->EnableWindow ( TRUE ); - } -} - -void CReport::OnOK() -{ - int count; - int i; - char buffer[100]; - - count = list->GetSelItems ( num_langs, langindices ); - - if ( !count ) - { - AfxMessageBox ( "No languages selected" ); - return; - } - -// get the filename - CFileDialog fd ( FALSE , NULL, "*.txt", OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR ); - - if ( fd.DoModal () != IDOK ) - { - return; - } - - strcpy ( filename, fd.GetPathName ()); - - num_langs = 0; - for ( i = 0; i langid; - } - } - - langids[num_langs] = LANGID_UNKNOWN; - - options.dialog = dialog_status->GetCheck (); - options.translations = trans_status->GetCheck (); - limit->GetWindowText( buffer, sizeof(buffer)-1); - options.limit = atoi ( buffer ); - - if ( !show_details->GetCheck () ) - { - options.limit = 0; - } - else if ( !ifless->GetCheck () ) - { - options.limit = INT_MAX; - } - - - CDialog::OnOK(); -} - -void CReport::OnCancel() -{ - // TODO: Add extra cleanup here - - CDialog::OnCancel(); -} diff --git a/Generals/Code/Tools/Babylon/Report.h b/Generals/Code/Tools/Babylon/Report.h deleted file mode 100644 index eb11c1a76f..0000000000 --- a/Generals/Code/Tools/Babylon/Report.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_REPORT_H__47F98BA1_70E3_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_REPORT_H__47F98BA1_70E3_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// Report.h : header file -// - -#include "expimp.h" - -///////////////////////////////////////////////////////////////////////////// -// CReport dialog - -class CReport : public CDialog -{ - char filename[300]; - RPOPTIONS options; - LangID langids[200]; - int langindices[200]; - int num_langs; - CListBox *list; - CEdit *limit; - CButton *dialog_status; - CButton *trans_status; - CButton *show_details; - CButton *ifless; - CStatic *items; - - -// Construction -public: - CReport(CWnd* pParent = NULL); // standard constructor - - char* Filename ( void ) { return filename; }; - RPOPTIONS* Options ( void ) { return &options; }; - LangID* Langauges ( void ) { return langids; }; - -// Dialog Data - //{{AFX_DATA(CReport) - enum { IDD = IDD_CREATE_REPORTS }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CReport) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CReport) - virtual BOOL OnInitDialog(); - afx_msg void OnInvert(); - afx_msg void OnSelectall(); - afx_msg void OnShowDetails(); - virtual void OnOK(); - virtual void OnCancel(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_REPORT_H__47F98BA1_70E3_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/RetranslateDlg.cpp b/Generals/Code/Tools/Babylon/RetranslateDlg.cpp deleted file mode 100644 index 9ec7611740..0000000000 --- a/Generals/Code/Tools/Babylon/RetranslateDlg.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// RetranslateDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "RetranslateDlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// RetranslateDlg dialog - - -RetranslateDlg::RetranslateDlg(CWnd* pParent /*=NULL*/) - : CDialog(RetranslateDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(RetranslateDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void RetranslateDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(RetranslateDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(RetranslateDlg, CDialog) - //{{AFX_MSG_MAP(RetranslateDlg) - ON_WM_CANCELMODE() - ON_BN_CLICKED(IDC_MATCH, OnRetranslate) - ON_BN_CLICKED(IDC_SKIP, OnSkip) - ON_BN_CLICKED(IDC_NOMATCH, OnNoRetranslate) - ON_BN_CLICKED(IDCANCEL, OnSkipAll) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// RetranslateDlg message handlers - -BOOL RetranslateDlg::OnInitDialog() -{ - // TODO: Add extra initialization here - CStatic *text; - static char buffer[4*1024]; - - - CDialog::OnInitDialog(); - - text = (CStatic *) GetDlgItem ( IDC_NEWTEXT ); - text->SetWindowText ( newtext->GetSB()); - - text = (CStatic *) GetDlgItem ( IDC_OLDTEXT ); - text->SetWindowText ( oldtext->GetSB()); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void RetranslateDlg::OnCancelMode() -{ - CDialog::OnCancelMode(); - - // TODO: Add your message handler code here - -} - -void RetranslateDlg::OnRetranslate() -{ - // TODO: Add your control notification handler code here - - - oldtext->SetRetranslate ( TRUE ); - CDialog::OnOK (); -} - -void RetranslateDlg::OnSkip() -{ - // TODO: Add your control notification handler code here - - EndDialog ( IDSKIP ); -} - -void RetranslateDlg::OnNoRetranslate() -{ - // TODO: Add your control notification handler code here - - oldtext->SetRetranslate ( FALSE ); - CDialog::OnOK (); -} - -void RetranslateDlg::OnSkipAll() -{ - // TODO: Add your control notification handler code here - - CDialog::OnCancel (); -} diff --git a/Generals/Code/Tools/Babylon/RetranslateDlg.h b/Generals/Code/Tools/Babylon/RetranslateDlg.h deleted file mode 100644 index 2be8b94cd5..0000000000 --- a/Generals/Code/Tools/Babylon/RetranslateDlg.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_RETRANSLATEDLG_H__19E25401_0ECB_11D4_B9DB_006097B90D93__INCLUDED_) -#define AFX_RETRANSLATEDLG_H__19E25401_0ECB_11D4_B9DB_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// RetranslateDlg.h : header file -// - -#include "TransDB.h" -#define IDSKIP 100 -///////////////////////////////////////////////////////////////////////////// -// RetranslateDlg dialog - -class RetranslateDlg : public CDialog -{ -// Construction -public: - - NoxText *newtext; - NoxText *oldtext; - - RetranslateDlg(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(RetranslateDlg) - enum { IDD = IDD_RETRANSLATE }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(RetranslateDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(RetranslateDlg) - virtual BOOL OnInitDialog(); - afx_msg void OnCancelMode(); - afx_msg void OnRetranslate(); - afx_msg void OnSkip(); - afx_msg void OnNoRetranslate(); - afx_msg void OnSkipAll(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_RETRANSLATEDLG_H__19E25401_0ECB_11D4_B9DB_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/STRCHECK.PL b/Generals/Code/Tools/Babylon/STRCHECK.PL deleted file mode 100644 index 77e20159eb..0000000000 --- a/Generals/Code/Tools/Babylon/STRCHECK.PL +++ /dev/null @@ -1,192 +0,0 @@ -# -# Command & Conquer Generalsâ„¢ -# Copyright 2025 Electronic Arts Inc. -# -# This program 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. -# -# This program 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 this program. If not, see . -# - -sub ShowWarning; -sub ShowError; - -$noxScript = shift || 'C:\Nox\Game\nox.str'; -$outFile = shift; - -open(STR, $noxScript) || die "Can't open Nox string file: $!\n"; - -if ($outFile) -{ - open(STDOUT, ">$outFile") || die "Can't open output file: $!\n"; -} -select((select(STDOUT), $| = 1)[0]); - -$state = 0; -$line = 0; -$strcount = 0; -$strMaxCount = 32; -$lastFileName = ""; -$lastFileNameLine = 0; -$ignoreErrors = 0; -$errCount = 0; -%labels = (); - - -while () -{ - $strline = $_; - $line++; - $strline =~ s/\/\/.*//g; - $strline =~ s/^\s*//g; - $strline =~ s/\s*$//g; - if (! ($strline eq "")) - { - if ($state == 0) - { - if (! ($strline =~ /^[^\"][^ :]*:[^ :]*[^\"]$/)) - { - ShowError($line, $strline, "Expecting 'file:name'\n"); - } - else - { - if (defined ($labels{$strline})) - { - ShowWarning($line, $strline, "Duplicate label at line $labels{$strline}\n"); - } - - $labels{$strline} = $line; - $lastFileName = $strline; - $lastFileNameLine = $line; - $strcount = 0; - $ignoreErrors = 0; - $state = 1; - } - } - - elsif ($state == 1) - { - if (++$strcount >= $strMaxCount) - { - ShowError($line, $strline, "Too many strings ($strcount) - suspected missing END from section $lastFileName on line $lastFileNameLine\n"); - } - elsif ($strline =~ /^END$/i) - { - $state = 0; - } - elsif ($strline =~ /\/n/i) - { - ShowWarning($line, $strline, "'/n'? This should probably be '\\n' instead\n"); - } - elsif ($strline =~ /^\"[^\"]*[^\"]$/) - { - $state = 2; - } - else - { - $strline =~ s/\"\s*={0,1}\s*[a-zA-Z0-9_\.]*[^\"]$/\"/i; - - if (! ($strline =~ /^\".*\"$/)) - { - if ($strline =~ /^[^\"][^ :]*:[^ :]*[^\"]$/) - { - ShowError($line, $strline, "Missing quote - suspected missing END from section $lastFileName on line $lastFileNameLine\n"); - } - else - { - ShowError($line, $strline, "Missing quote\n"); - } - } - } - } - - elsif ($state == 2) - { - $strline =~ s/\"\s*={0,1}\s*[a-zA-Z0-9_\.]*[^\"]$/\"/i; - if (++$strcount >= $strMaxCount) - { - ShowError($line, $strline, "Too many strings ($strcount) - suspected missing END from section $lastFileName on line $lastFileNameLine\n"); - } - elsif ($strline =~ /\/n/i) - { - ShowWarning($line, $strline, "'/n'? This should probably be '\\n' instead\n"); - } - elsif ($strline =~ /^[^\"].*\"$/) - { - $state = 1; - } - elsif (! ($strline =~ /^[^\"].*[^\"]$/)) - { - ShowError($line, $strline, "Extra quote character found at start of line\n"); - } - elsif ($strline =~ /^END$/i) - { - ShowWarning($line, $strline, "Suspiciously placed 'END'. Maybe missing an end-quote from previous section\n"); - } - } - } -} - -if ($state != 0) -{ - ShowError($line, $strline, "Missing END\n"); -} - -print STDOUT "$line lines processed\n"; - -close(STR); - -if ($errCount == 0) -{ - open(RESULT, ">strcheck.err") || die "Can't open output file: $!\n"; - print RESULT "OK"; - close (RESULT); - -} - -exit($errCount); - -sub ShowWarning -{ - my ($errLine, $errString, $errDesc) = @_; - - if (length($errString) > 32) - { - $errString = substr($errString, 0, 32) . "..."; - } - - if ($ignoreErrors == 0) - { - print STDOUT "$noxScript($errLine) : warning: '$errString' : $errDesc"; - } - - $state = 0; - $ignoreErrors = 1; -} - -sub ShowError -{ - my ($errLine, $errString, $errDesc) = @_; - - if (length($errString) > 32) - { - $errString = substr($errString, 0, 32) . "..."; - } - - if ($ignoreErrors == 0) - { - print STDOUT "$noxScript($errLine) : error: '$errString' : $errDesc"; - $errCount++; - } - - $state = 0; - $ignoreErrors = 1; -} diff --git a/Generals/Code/Tools/Babylon/StdAfx.cpp b/Generals/Code/Tools/Babylon/StdAfx.cpp deleted file mode 100644 index 57986e9bc1..0000000000 --- a/Generals/Code/Tools/Babylon/StdAfx.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.cpp : source file that includes just the standard includes -// noxstring.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "StdAfx.h" - - - diff --git a/Generals/Code/Tools/Babylon/StdAfx.h b/Generals/Code/Tools/Babylon/StdAfx.h deleted file mode 100644 index 76bfc93679..0000000000 --- a/Generals/Code/Tools/Babylon/StdAfx.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__2BF31252_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_STDAFX_H__2BF31252_3BA1_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers - -// TheSuperHackers @compile xezon 24/03/2025 Prevent afxwin.h from loading d3d9types.h, colliding with our own DirectX library. -#define _d3d9TYPES_H_ - -#include // MFC core and standard components -#include // MFC extensions -#include // MFC Automation classes -#include // MFC support for Internet Explorer 4 Common Controls -#ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls -#endif // _AFX_NO_AFXCMN_SUPPORT - - -// This macro is the same as IMPLEMENT_OLECREATE, except it passes TRUE -// for the bMultiInstance parameter to the COleObjectFactory constructor. -// We want a separate instance of this application to be launched for -// each automation proxy object requested by automation controllers. -#ifndef IMPLEMENT_OLECREATE2 -#define IMPLEMENT_OLECREATE2(class_name, external_name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ - AFX_DATADEF COleObjectFactory class_name::factory(class_name::guid, \ - RUNTIME_CLASS(class_name), TRUE, _T(external_name)); \ - const AFX_DATADEF GUID class_name::guid = \ - { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; -#endif // IMPLEMENT_OLECREATE2 - -#include "excel8.h" - -extern char AppTitle[]; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. -#endif // !defined(AFX_STDAFX_H__2BF31252_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/TransDB.cpp b/Generals/Code/Tools/Babylon/TransDB.cpp deleted file mode 100644 index 50d835fb1d..0000000000 --- a/Generals/Code/Tools/Babylon/TransDB.cpp +++ /dev/null @@ -1,1905 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// TransDB.cpp -// - -#include "StdAfx.h" -#include "TransDB.h" -#include "noxstringDlg.h" -#include "noxstring.h" -#include "assert.h" -#include "bin.h" -#include "list.h" - -static char buffer[100*1024]; - -static List DataBases; - -static LANGINFO langinfo[] = - { - { LANGID_US, "US", "us", "e"}, - { LANGID_UK, "UK", "uk", "e" }, - { LANGID_GERMAN, "German", "ge", "g" }, - { LANGID_FRENCH, "French", "fr", "f" }, - { LANGID_SPANISH, "Spanish", "sp", "s" }, - { LANGID_ITALIAN, "Italian", "it", "i" }, - { LANGID_JAPANESE, "Japanese", "ja", "j" }, - { LANGID_KOREAN, "Korean", "ko", "k" }, - { LANGID_CHINESE, "Chinese", "ch", "c" }, - { LANGID_JABBER, "Jabberwockie", "jb", "e" }, - { LANGID_UNKNOWN, "Unknown", NULL, NULL } - }; - -LANGINFO *GetLangInfo ( int index ) -{ - - if ( (index >= 0) && (index < (sizeof ( langinfo ) / sizeof (LANGINFO )) -1) ) - { - return &langinfo[index]; - } - - return NULL; -} - -LANGINFO *GetLangInfo ( LangID langid ) -{ - LANGINFO *item; - - item = langinfo; - - while ( item->langid != LANGID_UNKNOWN ) - { - if ( item->langid == langid ) - { - return item; - } - item++; - } - - return NULL; -} - -const char *GetLangName ( LangID langid ) -{ - LANGINFO *item; - - if ( ( item = GetLangInfo ( langid )) ) - { - return item->name; - } - - return "unknown"; -} - -LANGINFO *GetLangInfo ( char *language ) -{ - LANGINFO *item; - - item = langinfo; - - while ( item->langid != LANGID_UNKNOWN ) - { - if ( !stricmp ( language, item->name ) ) - { - return item; - } - item++; - } - - return NULL; -} - -TransDB* FirstTransDB ( void ) -{ - ListNode *first; - - first = DataBases.Next (); - if ( first ) - { - return (TransDB *) first->Item (); - } - return NULL; -} - -TransDB::TransDB ( const char *cname ) -{ - text_bin = new Bin (); - text_id_bin = new BinID (); - label_bin = new Bin (); - obsolete_bin = new Bin (); - strncpy ( name, cname, sizeof ( name ) -1 ); - name[sizeof(name)-1] = 0; - node.SetItem ( this ); - DataBases.AddToTail ( &node ); - next_string_id = -1; - valid = TRUE; - num_obsolete = 0; - checked_for_errors = FALSE; - flags = TRANSDB_OPTION_NONE | TRANSDB_OPTION_DUP_TEXT; -} - -TransDB:: ~TransDB ( ) -{ - Clear (); - node.Remove (); - delete text_bin; - delete text_id_bin; - delete label_bin; - delete obsolete_bin; - -} - -void TransDB::AddLabel ( NoxLabel *label ) -{ - ListNode *node = new ListNode (); - - node->SetItem ( label ); - - label_bin->Add ( label, label->Name() ); - - labels.AddToTail ( node ); - label->SetDB ( this ); - Changed (); - -} - -void TransDB::AddText ( NoxText *text ) -{ - - text_bin->Add ( text, text->Get() ); - if ( text->ID () > 0 ) - { - text_id_bin->Add ( text, text->ID ()); - } - -} - -void TransDB::AddObsolete ( NoxText *text ) -{ - ListNode *node = new ListNode (); - - node->SetItem ( text ); - - obsolete_bin->Add ( text, text->Get() ); - if ( text->ID () > 0 ) - { - text_id_bin->Add ( text, text->ID ()); - } - - num_obsolete++; - text->SetParent ( (DBAttribs *)this ); - text->Changed (); - - obsolete.AddToTail ( node ); - Changed (); - -} - -void TransDB::RemoveLabel ( NoxLabel *label ) -{ - ListNode *node; - - if ( (node = labels.Find ( label )) ) - { - node->Remove (); - label->SetDB ( NULL ); - label_bin->Remove ( label ); - delete node; - Changed (); - } -} - -void TransDB::RemoveText ( NoxText *text ) -{ - text_bin->Remove ( text ); - text_id_bin->Remove ( text ); -} - -void TransDB::RemoveObsolete ( NoxText *text ) -{ - ListNode *node; - - if ( (node = obsolete.Find ( text )) ) - { - node->Remove (); - obsolete_bin->Remove ( text ); - text_id_bin->Remove ( text ); - num_obsolete--; - delete node; - Changed (); - } -} - -int TransDB::NumLabelsChanged ( void ) -{ - NoxLabel *label; - ListSearch sh; - int changed = 0; - - label = FirstLabel ( sh ); - - while ( label ) - { - if ( label->IsChanged ()) - { - changed++; - } - - label = NextLabel ( sh ); - } - - return changed; -} - -int TransDB::NumLabels ( void ) -{ - - return labels.NumItems(); -} - -NoxLabel* TransDB::FirstLabel ( ListSearch& sh ) -{ - ListNode *node; - - if ( ( node = sh.FirstNode ( &labels ))) - { - return (NoxLabel *) node->Item (); - } - - return NULL; -} - -NoxLabel* TransDB::NextLabel ( ListSearch& sh) -{ - ListNode *node; - - if ( ( node = sh.Next ())) - { - return (NoxLabel *) node->Item (); - } - - return NULL; -} - -NoxText* TransDB::FirstObsolete ( ListSearch& sh ) -{ - ListNode *node; - - if ( ( node = sh.FirstNode ( &obsolete ))) - { - return (NoxText *) node->Item (); - } - - return NULL; -} - -NoxText* TransDB::NextObsolete ( ListSearch& sh) -{ - ListNode *node; - - if ( ( node = sh.Next ())) - { - return (NoxText *) node->Item (); - } - - return NULL; -} - -NoxLabel* TransDB::FindLabel ( OLECHAR *name ) -{ - return (NoxLabel *) label_bin->Get ( name ); -} - -NoxText* TransDB::FindText ( OLECHAR *text ) -{ - - return (NoxText *) text_bin->Get ( text ); -} - -NoxText* TransDB::FindSubText ( OLECHAR *pattern, int item ) -{ - NoxLabel *label; - ListSearch sh; - NoxText *text; - ListSearch sh_text; - int plen = wcslen ( pattern ); - - label = FirstLabel ( sh ); - - while ( label ) - { - text = label->FirstText ( sh_text ); - - while ( text ) - { - - if ( !wcsnicmp ( text->Get (), pattern, 15 )) - { - if ( !item ) - { - return text; - } - - item--; - } - - text = label->NextText ( sh_text ); - } - - label = NextLabel ( sh ); - } - - return NULL; - -} - -NoxText* TransDB::FindText ( int id ) -{ - - return (NoxText *) text_id_bin->Get ( id ); -} - -NoxText* TransDB::FindNextText ( void ) -{ - - return (NoxText *) text_bin->GetNext ( ); -} - -NoxText* TransDB::FindObsolete ( OLECHAR *name ) -{ - return (NoxText *) obsolete_bin->Get ( name ); -} - -NoxText* TransDB::FindNextObsolete ( void ) -{ - - return (NoxText *) obsolete_bin->GetNext ( ); - -} - -int TransDB::Clear ( void ) -{ - ListSearch sh; - NoxLabel *label; - NoxText *text; - ListNode *node; - int count = 0; - - text_bin->Clear (); - text_id_bin->Clear (); - label_bin->Clear (); - obsolete_bin->Clear (); - - while ( node = sh.FirstNode ( &labels ) ) - { - node->Remove (); - label = (NoxLabel *) node->Item (); - count++; - delete label; - delete node; - } - - while ( node = sh.FirstNode ( &obsolete ) ) - { - node->Remove (); - text = (NoxText *) node->Item (); - count++; - delete text; - delete node; - } - - num_obsolete = 0; - - if ( next_string_id != -1 ) - { - next_string_id = START_STRING_ID; - } - - if ( count ) - { - Changed (); - } - - valid = TRUE; - - return count; -} - -void TransDB::ClearChanges ( void ) -{ - ListSearch sh; - NoxLabel *label; - - label = FirstLabel ( sh ); - while ( label ) - { - label->ClearChanges (); - label = NextLabel ( sh ); - } - - NoxText *text = FirstObsolete ( sh ); - while ( text ) - { - text->ClearChanges (); - text = NextObsolete ( sh ); - } - - NotChanged (); -} - -void TransDB::ClearProcessed ( void ) -{ - ListSearch sh; - NoxLabel *label; - - label = FirstLabel ( sh ); - while ( label ) - { - label->ClearProcessed (); - label = NextLabel ( sh ); - } - NotProcessed (); -} - -void TransDB::ClearMatched ( void ) -{ - ListSearch sh; - NoxLabel *label; - - label = FirstLabel ( sh ); - while ( label ) - { - label->ClearMatched (); - label = NextLabel ( sh ); - } - NotMatched (); -} - -void TransDB::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes, void (*cb) ( void ) ) -{ - HTREEITEM item; - HTREEITEM ilabels, iobsolete; - ListSearch sh; - NoxLabel *label; - NoxText *txt; - - sprintf ( buffer, "%s%c (%d/%d)",name, ChangedSymbol(), NumLabelsChanged(), NumLabels() ); - item = tc->InsertItem ( buffer, parent ); - ilabels = tc->InsertItem ( "Labels", item ); - - label = FirstLabel ( sh ); - - while ( label ) - { - if ( !changes || label->IsChanged ()) - { - label->AddToTree ( tc, ilabels, changes ); - } - - if ( cb ) - { - cb ( ); - } - - label = NextLabel ( sh ); - } - - if ( num_obsolete ) - { - iobsolete = tc->InsertItem ( "Obsolete Strings", item ); - - txt = FirstObsolete ( sh ); - - while ( txt ) - { - if ( !changes || txt->IsChanged ()) - { - txt->AddToTree ( tc, iobsolete ); - } - - if ( cb ) - { - cb ( ); - } - - txt = NextObsolete ( sh ); - } - } - - -} - -TransDB* TransDB::Next ( void ) -{ - ListNode *next; - - next = node.Next (); - - if ( next ) - { - return (TransDB *) next->Item (); - } - - return NULL; - -} - -void NoxLabel::init ( void ) -{ - db = NULL; - comment = NULL; - line_number = -1; - max_len = 0; - name = NULL; -} - -NoxLabel::NoxLabel ( void ) -{ - init (); - name = new OLEString ( ); - comment = new OLEString ( ); - context = new OLEString ( ); - speaker = new OLEString ( ); - listener = new OLEString ( ); - - -} - -NoxLabel::~NoxLabel ( ) -{ - Clear (); - delete name; - delete comment; - delete context; - delete speaker; - delete listener; -} - -void NoxLabel::Remove ( void ) -{ - if ( db ) - { - db->RemoveLabel ( this ); - } -} - -void NoxLabel::RemoveText ( NoxText *txt ) -{ - ListNode *node; - - if ( (node = text.Find ( txt )) ) - { - node->Remove (); - txt->SetDB ( NULL ); - txt->SetLabel ( NULL ); - txt->SetParent ( NULL ); - delete node; - Changed (); - } -} - -void NoxLabel::AddText ( NoxText *new_text ) -{ - TransDB *db = DB(); - ListNode *node = new ListNode (); - - node->SetItem ( new_text ); - - text.AddToTail ( node ); - Changed (); - new_text->SetDB ( db ); - new_text->SetParent ( (DBAttribs *) this ); - new_text->SetLabel ( this ); -} - -int NoxLabel::Clear ( void ) -{ - ListSearch sh; - NoxText *txt; - ListNode *node; - int count = 0; - - while ( node = sh.FirstNode ( &text ) ) - { - node->Remove (); - txt = (NoxText *) node->Item (); - delete txt; - delete node; - count++; - } - - if ( count ) - { - Changed (); - } - - return count; -} - -NoxLabel* NoxLabel::Clone ( void ) -{ - NoxLabel *clone = new NoxLabel(); - NoxText *txt; - ListSearch sh; - - clone->SetName ( Name()); - clone->SetComment ( Comment ()); - clone->SetListener ( Listener ()); - clone->SetSpeaker ( Speaker ()); - clone->SetMaxLen ( MaxLen ()); - clone->SetContext ( Context ()); - - txt = FirstText ( sh ); - - while ( txt ) - { - clone->AddText ( txt->Clone ()); - - txt = NextText ( sh ); - } - - return clone; -} - -NoxText* NoxLabel::FirstText ( ListSearch& sh ) -{ - ListNode *node; - - if ( ( node = sh.FirstNode ( &text ))) - { - return (NoxText *) node->Item (); - } - - return NULL; -} - -NoxText* NoxLabel::NextText ( ListSearch& sh) -{ - ListNode *node; - - if ( ( node = sh.Next ( ))) - { - return (NoxText *) node->Item (); - } - - return NULL; - -} - -NoxText* NoxLabel::FindText ( OLECHAR *find_text ) -{ - ListSearch sh; - NoxText *txt; - - txt = FirstText ( sh ); - - while ( txt ) - { - if ( !wcscmp ( txt->Get(), find_text )) - { - return txt; - } - txt = NextText ( sh ); - } - - return NULL; -} - - -void NoxLabel::SetDB ( TransDB *new_db ) -{ - NoxText *ntext; - ListSearch sh; - - db = new_db; - SetParent ( (DBAttribs *) new_db ); - - ntext = FirstText ( sh ); - - while ( ntext ) - { - ntext->SetDB ( new_db ); - - ntext = NextText ( sh ); - } - -} - -void NoxLabel::ClearChanges ( void ) -{ - NoxText *ntext; - ListSearch sh; - - ntext = FirstText ( sh ); - - while ( ntext ) - { - ntext->ClearChanges(); - - ntext = NextText ( sh ); - } - - NotChanged(); - -} - -void NoxLabel::ClearProcessed ( void ) -{ - NoxText *ntext; - ListSearch sh; - - ntext = FirstText ( sh ); - - while ( ntext ) - { - ntext->ClearProcessed(); - - ntext = NextText ( sh ); - } - - NotProcessed(); - -} - -void NoxLabel::ClearMatched ( void ) -{ - NoxText *ntext; - ListSearch sh; - - ntext = FirstText ( sh ); - - while ( ntext ) - { - ntext->ClearMatched(); - - ntext = NextText ( sh ); - } - - NotMatched(); - -} - -int NoxLabel::AllMatched ( void ) -{ - NoxText *ntext; - ListSearch sh; - - ntext = FirstText ( sh ); - - while ( ntext ) - { - if ( !ntext->Matched() ) - { - return FALSE; - } - - ntext = NextText ( sh ); - } - - return TRUE; -} - -NoxText::NoxText( void ) -{ - init (); - text = new OLEString ( ); - wavefile = new OLEString ( ); - -} - -int NoxText::IsSent ( void ) -{ - return sent; -} - -void NoxText::Sent ( int val ) -{ - sent = val; -} - -void NoxLabel::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes ) -{ - HTREEITEM litem; - ListSearch sh; - NoxText *txt; - - sprintf ( buffer, "%s%c", NameSB(), ChangedSymbol() ); - - litem = tc->InsertItem ( buffer, parent ); - - txt = FirstText ( sh ); - - while ( txt ) - { - if ( !changes || txt->IsChanged ()) - { - txt->AddToTree ( tc, litem ); - } - - txt = NextText ( sh ); - } - - if ( strcmp ( CommentSB(), "" ) ) - { - sprintf ( buffer, "COMMENT : %s", CommentSB() ); - tc->InsertItem ( buffer, litem ); - } - - if ( strcmp ( ContextSB(), "" ) ) - { - sprintf ( buffer, "CONTEXT : %s", ContextSB() ); - tc->InsertItem ( buffer, litem ); - } - - if ( strcmp ( SpeakerSB(), "" ) ) - { - sprintf ( buffer, "SPEAKER : %s", SpeakerSB() ); - tc->InsertItem ( buffer, litem ); - } - - if ( strcmp ( ListenerSB(), "" ) ) - { - sprintf ( buffer, "LISTENER: %s", ListenerSB() ); - tc->InsertItem ( buffer, litem ); - } - - if ( line_number != -1 ) - { - sprintf ( buffer, "LINE : %d", line_number ); - tc->InsertItem ( buffer, litem ); - } - - if ( max_len ) - { - sprintf ( buffer, "MAX LEN : %d", max_len ); - tc->InsertItem ( buffer, litem ); - } - -} - -void NoxText::init ( void ) -{ - db = NULL; - label = NULL; - line_number = -1; - revision = 1; - text = NULL; - wavefile = NULL; - id = -1; - retranslate = FALSE; - sent = FALSE; - - -} - -NoxText::~NoxText( ) -{ - Clear(); - delete text; - delete wavefile; - -} - -void NoxText::SetDB ( TransDB *new_db ) -{ - Translation *trans; - ListSearch sh; - - if ( db ) - { - db->RemoveText ( this ); - } - - - if ( (db = new_db) ) - { - AssignID (); - db->AddText ( this ); - } - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - trans->SetDB ( new_db ); - - trans = NextTranslation ( sh ); - } - -} - -void NoxText::Remove ( void ) -{ - if ( label ) - { - label->RemoveText ( this ); - } -} - -int NoxText::IsDialog ( void ) -{ - - return strcmp (WaveSB(), "" ); - -} - -int NoxText::DialogIsValid ( const char *path, LangID langid, int check ) -{ - LANGINFO *linfo; - CWaveInfo *winfo; - DBAttribs *attribs; - - linfo = GetLangInfo ( langid ); - - if ( langid == LANGID_US ) - { - winfo = &WaveInfo; - attribs = (DBAttribs *) this; - } - else - { - Translation *trans = GetTranslation ( langid ); - - if ( !trans ) - { - return FALSE; - } - - attribs = (DBAttribs *) trans; - winfo = &trans->WaveInfo; - } - - - if ( winfo->Valid () && check ) - { - WIN32_FIND_DATA info; - HANDLE handle; - - winfo->SetValid ( FALSE ); - winfo->SetMissing ( TRUE ); - - sprintf ( buffer, "%s%s\\%s%s.wav", path, linfo->character, WaveSB(), linfo->character ); - if ( (handle = FindFirstFile ( buffer, &info )) != INVALID_HANDLE_VALUE ) - { - if ( ! (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) - { - if ( winfo->Lo () == info.nFileSizeLow && winfo->Hi() == info.nFileSizeHigh ) - { - winfo->SetValid ( TRUE ); - } - winfo->SetMissing ( FALSE ); - } - - FindClose ( handle ); - } - - } - - return winfo->Valid (); -} - -int NoxText::ValidateDialog ( const char *path, LangID langid ) -{ - WIN32_FIND_DATA info; - HANDLE handle; - CWaveInfo *winfo; - LANGINFO *linfo; - DBAttribs *attribs; - - linfo = GetLangInfo ( langid ); - - if ( langid == LANGID_US ) - { - winfo = &WaveInfo; - attribs = (DBAttribs *) this; - } - else - { - Translation *trans = GetTranslation ( langid ); - - if ( !trans ) - { - return FALSE; - } - - attribs = (DBAttribs *) trans; - winfo = &trans->WaveInfo; - } - - winfo->SetValid ( FALSE ); - winfo->SetMissing ( TRUE ); - - sprintf ( buffer, "%s%s\\%s%s.wav", path, linfo->character , WaveSB(), linfo->character ); - if ( (handle = FindFirstFile ( buffer, &info )) != INVALID_HANDLE_VALUE ) - { - if ( ! (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) - { - winfo->SetLo ( info.nFileSizeLow ); - winfo->SetHi ( info.nFileSizeHigh ); - winfo->SetValid ( TRUE ); - winfo->SetMissing ( FALSE ); - attribs->Changed(); - } - FindClose ( handle ); - } - - return winfo->Valid (); -} - -int NoxText::DialogIsPresent ( const char *path, LangID langid ) -{ - - WIN32_FIND_DATA info; - HANDLE handle; - int present = FALSE; - LANGINFO *linfo = GetLangInfo ( langid ); - - sprintf ( buffer, "%s%s\\%s%s.wav", path, linfo->character , WaveSB(), linfo->character ); - if ( (handle = FindFirstFile ( buffer, &info )) != INVALID_HANDLE_VALUE ) - { - if ( ! (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) - { - present = TRUE; - } - - FindClose ( handle ); - } - - return present; -} - -void NoxText::AddTranslation ( Translation *trans ) -{ - ListNode *node = new ListNode (); - - node->SetItem ( trans ); - - translations.AddToTail ( node ); - Changed (); - trans->SetDB ( DB() ); - trans->SetParent ( (DBAttribs *) this ); - -} - -Translation* NoxText::FirstTranslation ( ListSearch& sh ) -{ - ListNode *node; - - if ( ( node = sh.FirstNode ( &translations ))) - { - return (Translation *) node->Item (); - } - - return NULL; -} - -Translation* NoxText::NextTranslation ( ListSearch& sh) -{ - ListNode *node; - - if ( ( node = sh.Next ( ))) - { - return (Translation *) node->Item (); - } - - return NULL; -} - -Translation* NoxText::GetTranslation ( LangID langid ) -{ - ListSearch sh; - Translation *trans; - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - if ( langid == trans->GetLangID()) - { - break; - } - - trans = NextTranslation ( sh ); - } - - - return trans; -} - -int NoxText::Clear ( void ) -{ - ListSearch sh; - Translation *trans; - ListNode *node; - int count = 0; - - while ( node = sh.FirstNode ( &translations ) ) - { - node->Remove (); - trans = (Translation *) node->Item (); - delete trans; - delete node; - count++; - } - if ( count ) - { - Changed (); - } - - return count; -} - -NoxText* NoxText::Clone ( void ) -{ - NoxText *clone = new NoxText(); - Translation *trans; - ListSearch sh; - - clone->Set ( Get ()); - clone->SetWave ( Wave ()); - clone->SetRevision ( Revision ()); - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - clone->AddTranslation ( trans->Clone ()); - - trans = NextTranslation ( sh ); - } - - return clone; -} - -void NoxText::ClearChanges ( void ) -{ - Translation *trans; - ListSearch sh; - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - trans->ClearChanges(); - - trans = NextTranslation ( sh ); - } - - NotChanged(); - -} - -void NoxText::ClearProcessed ( void ) -{ - Translation *trans; - ListSearch sh; - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - trans->ClearProcessed(); - - trans = NextTranslation ( sh ); - } - - NotProcessed(); - -} - -void NoxText::ClearMatched ( void ) -{ - Translation *trans; - ListSearch sh; - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - trans->ClearMatched(); - - trans = NextTranslation ( sh ); - } - - NotMatched(); - -} - -void NoxText::AssignID ( void ) -{ - if ( id != -1 ) - { - return; // already assigned - } - if ( db ) - { - SetID ( db->NewID ()); - } -} - -void NoxText::Set ( OLECHAR *string ) -{ - if ( db ) - { - db->RemoveText ( this ); - } - - text->Set ( string ); - InvalidateWave ( ); - if ( db ) - { - db->AddText ( this ); - } - - Changed (); -} - -void NoxText::Set ( char *string ) -{ - if ( db ) - { - db->RemoveText ( this ); - } - - text->Set ( string ); - InvalidateWave (); - if ( db ) - { - db->AddText ( this ); - } - - Changed (); -} - -void NoxText::InvalidateAllWaves ( void ) -{ - Translation *trans; - ListSearch sh; - - WaveInfo.SetValid ( FALSE ); - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - trans->WaveInfo.SetValid ( FALSE ); - - trans = NextTranslation ( sh ); - } - -} - -void NoxText::InvalidateWave ( void ) -{ - - WaveInfo.SetValid ( FALSE ); - -} - -void NoxText::InvalidateWave ( LangID langid ) -{ - - WaveInfo.SetValid ( FALSE ); - - if ( langid == LANGID_US ) - { - InvalidateWave (); - } - else - { - Translation *trans = GetTranslation ( langid ); - - if ( trans ) - { - trans->WaveInfo.SetValid ( FALSE ); - } - - } -} - -void NoxText::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes ) -{ - HTREEITEM item; - ListSearch sh; - Translation *trans; - - sprintf ( buffer, "TEXT %c : %s", ChangedSymbol() ,GetSB ()); - item = tc->InsertItem ( buffer, parent ); - - trans = FirstTranslation ( sh ); - - while ( trans ) - { - if ( !changes || trans->IsChanged ()) - { - trans->AddToTree ( tc, item ); - } - - trans = NextTranslation ( sh ); - } - - if ( ID() != -1 ) - { - sprintf ( buffer, "ID : %d", ID ()); - tc->InsertItem ( buffer, item ); - } - - if ( strcmp ( WaveSB(), "" ) ) - { - sprintf ( buffer, "WAVE : %s", WaveSB() ); - tc->InsertItem ( buffer, item ); - } - - if ( line_number != -1 ) - { - sprintf ( buffer, "LINE : %d", line_number ); - tc->InsertItem ( buffer, item ); - } - - sprintf ( buffer, "REV : %d", revision ); - tc->InsertItem ( buffer, item ); - - sprintf ( buffer, "LEN : %d", this->Len() ); - tc->InsertItem ( buffer, item ); - -} - -Translation::Translation ( void ) -{ - text = new OLEString ( ); - comment = new OLEString ( ); - revision = 0; - sent = FALSE; - -} - -Translation::~Translation ( ) -{ - delete text; - delete comment; -} - -int Translation::IsSent ( void ) -{ - return sent; -} - -void Translation::Sent ( int val ) -{ - sent = val; -} - -void Translation::SetDB ( TransDB *new_db ) -{ - db = new_db; -} - -Translation* Translation::Clone ( void ) -{ - Translation *clone = new Translation(); - - clone->Set ( Get ()); - clone->SetComment ( Comment ()); - clone->SetLangID ( GetLangID ()); - clone->SetRevision ( Revision ()); - - return clone; -} - -void Translation::AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes ) -{ - HTREEITEM item; - - sprintf ( buffer, "%s%c : %s", Language(), ChangedSymbol(), GetSB ()); - - item = tc->InsertItem ( buffer, parent ); - - if ( strcmp ( CommentSB(), "" ) ) - { - sprintf ( buffer, "COMMENT: %s", CommentSB() ); - tc->InsertItem ( buffer, item ); - } - - sprintf ( buffer, "REV : %d", revision ); - tc->InsertItem ( buffer, item ); - - sprintf ( buffer, "LEN : %d", Len() ); - tc->InsertItem ( buffer, item ); - -} - -int Translation::TooLong ( int maxlen ) -{ - return maxlen != 0 && text->Len () > maxlen; - -} - -int Translation::ValidateFormat ( NoxText *ntext ) -{ - return SameFormat ( text->Get(), ntext->Get ()); - -} - -int TransDB::Warnings ( CNoxstringDlg *dlg ) -{ - NoxLabel *label; - ListSearch sh_label; - int count = 0; - int warnings = 0; - List dups; - - if ( dlg ) - { - dlg->InitProgress ( NumLabels ()); - dlg->Log (""); - dlg->Log ("Generals.str Warnigs:"); - dlg->Status ( "Creating warnings report...", FALSE ); - } - - text_bin->Clear(); - - label = FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - NoxText *existing_text; - ListSearch sh_text; - - text = label->FirstText ( sh_text ); - - while ( text ) - { - if ( text->Len ( ) == 0 ) - { - if ( dlg ) - { - sprintf ( buffer, "Warning:: text at line %5d is NULL", - text->LineNumber()); - dlg->Log ( buffer ); - } - warnings++; - } - else if ( !DuplicatesAllowed() && ( existing_text = FindText ( text->Get () ))) - { - warnings++; - if ( dlg ) - { - DupNode *dup = new DupNode ( text, existing_text ); - dups.Add ( dup ); - } - } - else - { - text_bin->Add ( text, text->Get() ); - } - - text = label->NextText ( sh_text ); - } - - count++; - if ( dlg ) - { - dlg->SetProgress ( count ); - } - label = NextLabel ( sh_label ); - } - - if ( dlg ) - { - DupNode *dup; - - while ( (dup = (DupNode*)dups.LastNode ())) - { - sprintf ( buffer, "Warning:: text at line %5d is a duplicate of text on line %5d", - dup->Duplicate()->LineNumber(), dup->Original()->LineNumber()); - dlg->Log ( buffer ); - - dup->Remove (); - delete dup; - } - sprintf ( buffer, "Total warnings: %d", warnings ); - dlg->Log ( buffer ); - dlg->Ready(); - } - - return warnings; -} - -int TransDB::Errors ( CNoxstringDlg *dlg ) -{ - NoxLabel *label; - NoxLabel *existing_label; - ListSearch sh_label; - Bin *tbin = new Bin (); - int count = 0; - int errors = 0; - - if ( dlg ) - { - dlg->InitProgress ( NumLabels ()); - dlg->Log (""); - dlg->Log ("Generals.str Errors:"); - dlg->Status ( "Creating error report...", FALSE ); - } - - - - label_bin->Clear(); - - label = FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - NoxText *existing_text; - ListSearch sh_text; - - if ( !MultiTextAllowed () && label->NumStrings () > 1 ) - { - errors++; - if ( dlg ) - { - sprintf ( buffer, "Error : Label \"%s\" at line %d is has more than 1 string defined", - label->NameSB(), label->LineNumber()); - dlg->Log ( buffer ); - } - - } - - if ( ( existing_label = FindLabel ( label->Name () ))) - { - errors++; - if ( dlg ) - { - sprintf ( buffer, "Error : Label \"%s\" at line %d is already defined on line %d", - label->NameSB(), label->LineNumber(), existing_label->LineNumber()); - dlg->Log ( buffer ); - } - } - - label_bin->Add ( label, label->Name()); - - tbin->Clear (); - - text = label->FirstText ( sh_text ); - - while ( text ) - { - if ( ( existing_text = (NoxText *) tbin->Get ( text->Get () ))) - { - errors++; - if ( dlg ) - { - sprintf ( buffer, "Error : Label \"%s\" has duplicate text at line %d", - label->NameSB(), text->LineNumber()); - dlg->Log ( buffer ); - } - } - - tbin->Add ( text, text->Get() ); - - // check string length against max len - - if ( label->MaxLen () ) - { - if ( text->Len () > label->MaxLen ()) - { - errors++; - if ( dlg ) - { - sprintf ( buffer, "Error : The US text at line %d (for label \"%s\") exceeds the max length", - text->LineNumber(), label->NameSB()); - dlg->Log ( buffer ); - } - } - } - - text = label->NextText ( sh_text ); - } - - count++; - if ( dlg ) - { - dlg->SetProgress ( count ); - } - label = NextLabel ( sh_label ); - } - - if ( dlg ) - { - sprintf ( buffer, "Total errors: %d", errors ); - dlg->Log ( buffer ); - - dlg->Ready(); - } - - delete tbin; - last_error_count = errors; - checked_for_errors = TRUE; - return errors; -} - -CWaveInfo::CWaveInfo ( void ) -{ - wave_valid = FALSE; - missing = TRUE; -} - -void TransDB::VerifyDialog( LangID langid, void (*cb) (void) ) -{ - NoxLabel *label; - ListSearch sh_label; - int count = 0; - LANGINFO *linfo = GetLangInfo ( langid ); - - label = FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - ListSearch sh_text; - - text = label->FirstText ( sh_text ); - - while ( text ) - { - if ( text->IsDialog ()) - { - if ( text->DialogIsPresent ( DialogPath, langid )) - { - text->DialogIsValid ( DialogPath, langid ); - } - } - - text = label->NextText ( sh_text ); - } - - if ( cb ) - { - cb(); - } - label = NextLabel ( sh_label ); - } - -} - -void TransDB::InvalidateDialog( LangID langid ) -{ - NoxLabel *label; - ListSearch sh_label; - - label = FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - ListSearch sh_text; - - text = label->FirstText ( sh_text ); - - while ( text ) - { - if ( text->IsDialog ()) - { - text->InvalidateWave ( langid ); - } - - text = label->NextText ( sh_text ); - } - - label = NextLabel ( sh_label ); - } - -} - -int TransDB::ReportDialog( DLGREPORT *report, LangID langid, void (*print) ( const char *), PMASK pmask ) -{ - NoxLabel *label; - ListSearch sh_label; - int count = 0; - DLGREPORT _info; - DLGREPORT *info = &_info; - int skip_verify = FALSE; - LANGINFO *linfo = GetLangInfo ( langid ); - - if ( report ) - { - info = report; - } - - memset ( info, 0, sizeof ( DLGREPORT )); - - - label = FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - ListSearch sh_text; - - text = label->FirstText ( sh_text ); - - while ( text ) - { - if ( text->IsDialog ()) - { - if ( text->DialogIsPresent ( DialogPath, langid)) - { - if ( !text->DialogIsValid ( DialogPath, langid, FALSE ) ) - { - if ( print && pmask & PMASK_UNRESOLVED ) - { - sprintf ( buffer, "%d: audio file \"%s%s.wav\" not verified", text->ID(), text->WaveSB (), linfo->character); - - print ( buffer ); - } - info->unresolved++; - } - else - { - info->resolved++; - } - } - else - { - if ( print && pmask & PMASK_MISSING ) - { - sprintf ( buffer, "%d: audio file \"%s%s.wav\" missing", text->ID(), text->WaveSB (), linfo->character); - - print ( buffer ); - } - info->missing++; - } - - info->numdialog++; - } - - text = label->NextText ( sh_text ); - } - - label = NextLabel ( sh_label ); - } - - return info->missing + info->unresolved + info->errors ; -} - -int TransDB::ReportTranslations( TRNREPORT *report, LangID langid, void (*print) ( const char *buffer), PMASK pmask ) -{ - NoxLabel *label; - ListSearch sh_label; - int count = 0; - int first_error = FALSE; - TRNREPORT _info; - TRNREPORT *info = &_info; - - if ( report ) - { - info = report; - } - - memset ( info, 0, sizeof ( TRNREPORT )); - - label = FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - ListSearch sh_text; - int maxlen = label->MaxLen (); - - text = label->FirstText ( sh_text ); - - while ( text ) - { - int textnum = 0; - Translation *trans; - int too_big = FALSE; - - if ( text->Len ()) - { - info->numstrings++; - if ( langid != LANGID_US ) - { - if ( (trans = text->GetTranslation ( langid ) )) - { - if ( maxlen && trans->Len() > maxlen ) - { - if ( print && pmask & PMASK_TOOLONG ) - { - sprintf ( buffer, "%d: translation is too long by %d characters", text->ID (), trans->Len() - maxlen); - - print ( buffer ); - } - too_big = TRUE; - } - - if ( text->Revision () > trans->Revision ()) - { - if ( print && pmask & PMASK_RETRANSLATE ) - { - sprintf ( buffer, "%d: needs re-translation", text->ID () ); - - print ( buffer ); - } - info->retranslate++; - } - else - { - info->translated++; - if ( !trans->ValidateFormat ( text ) ) - { - if ( print && pmask & PMASK_BADFORMAT ) - { - sprintf ( buffer, "%d: translation has differring formating to original", text->ID () ); - - print ( buffer ); - } - info->bad_format++; - } - } - } - else - { - if ( print && pmask & PMASK_MISSING ) - { - sprintf ( buffer, "%d: not translated", text->ID ()); - - print ( buffer ); - } - info->missing++; - } - } - else - { - // check maxlen - if ( maxlen ) - { - if ( text->Len() > maxlen ) - { - if ( print && pmask & PMASK_TOOLONG ) - { - sprintf ( buffer, "%d: is too long by %d characters", text->ID (), text->Len() - maxlen); - - print ( buffer ); - } - too_big = TRUE; - } - } - } - - } - - if ( too_big ) - { - info->too_big++; - } - text = label->NextText ( sh_text ); - } - - info->numlabels++; - - label = NextLabel ( sh_label ); - } - - info->errors = info->too_big + info->bad_format; - - return info->missing + info->too_big + info->retranslate + info->bad_format; -} diff --git a/Generals/Code/Tools/Babylon/TransDB.h b/Generals/Code/Tools/Babylon/TransDB.h deleted file mode 100644 index 7f15475d59..0000000000 --- a/Generals/Code/Tools/Babylon/TransDB.h +++ /dev/null @@ -1,430 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// ParseStr.h -// -// - -#ifndef __TRANSDB_H -#define __TRANSDB_H - -#include "olestring.h" -#include "list.h" -#include "bin.h" - -class CNoxstringDlg; - -typedef struct -{ - int numdialog; - int missing; - int unresolved; - int resolved; - int errors; - -} DLGREPORT; - -typedef struct -{ - int numlabels; - int numstrings; - int missing; - int retranslate; - int too_big; - int errors; - int bad_format; - int translated; - -} TRNREPORT; - -typedef enum -{ - - PMASK_NONE = 0, - PMASK_MISSING = 0x00000001, - PMASK_UNRESOLVED = 0x00000002, - PMASK_BADFORMAT = 0x00000004, - PMASK_TOOLONG = 0x00000008, - PMASK_RETRANSLATE = 0x00000010, - PMASK_ALL = 0xffffffff -} PMASK; - -typedef enum -{ - LANGID_US, - LANGID_UK, - LANGID_GERMAN, - LANGID_FRENCH, - LANGID_SPANISH, - LANGID_ITALIAN, - LANGID_JAPANESE, - LANGID_JABBER, - LANGID_KOREAN, - LANGID_CHINESE, - LANGID_UNKNOWN -} LangID; - -typedef struct -{ - LangID langid; - const char *name; - const char *initials ; // two character identifier - const char *character; // single character identifier - -} LANGINFO; - -LANGINFO* GetLangInfo ( LangID langid ); -const char* GetLangName ( LangID langid ); -LANGINFO* GetLangInfo ( int index ); -LANGINFO* GetLangInfo ( char *language ); - -class CWaveInfo -{ - int wave_valid; - DWORD wave_size_hi; - DWORD wave_size_lo; - int missing; - - public: - - CWaveInfo ( void ); - int Valid ( void ) { return wave_valid; }; - DWORD Lo ( void ) { return wave_size_lo; }; - DWORD Hi ( void ) { return wave_size_hi; }; - void SetValid( int new_valid ) { wave_valid = new_valid; }; - void SetLo ( DWORD new_lo ) { wave_size_lo = new_lo; }; - void SetHi ( DWORD new_hi ) { wave_size_hi = new_hi; }; - int Missing ( void ) { return missing; }; - void SetMissing ( int val ) { missing = val; }; -}; - -class DBAttribs -{ - DBAttribs *parent; - int changed; - int processed; - void *match; - - - public: - - DBAttribs( void ) { parent = NULL; changed = FALSE; processed = FALSE; match = NULL; }; - - void SetParent ( DBAttribs *new_parent ) { parent = new_parent; }; - int IsChanged ( void ) { return changed; }; - void Changed ( void ) { changed = TRUE; if ( parent ) parent->Changed(); }; - void NotChanged ( void ) { changed = FALSE; }; - char ChangedSymbol ( void ) { return changed ? '*' :' '; }; - int IsProcessed ( void ) { return processed; }; - void Processed ( void ) { processed = TRUE; }; - void NotProcessed ( void ) { processed = FALSE; }; - void* Matched ( void ) { return match; }; - void Match ( void* new_match ) { match = new_match; }; - void NotMatched ( void ) { match = NULL; }; - - -}; - -class TransDB; -class NoxLabel; -class NoxText; - -class Translation : public DBAttribs -{ - TransDB *db; - - OLEString *text; - OLEString *comment; - LangID langid; - int revision; - int sent; - - - public: - - CWaveInfo WaveInfo; - - Translation ( void ); - ~Translation ( ); - - void SetDB ( TransDB *new_db ); - Translation* Clone ( void ); - void SetLangID ( LangID new_id ) { langid = new_id; }; - TransDB* DB ( void ) { return db; }; - void ClearChanges (void) { NotChanged(); }; - void ClearProcessed (void) { NotProcessed(); }; - void ClearMatched (void) { NotMatched(); }; - int Clear ( void ) { return 0;}; - void Set ( OLECHAR *string ) { text->Set ( string ); Changed();}; - void Set ( char *string ) { text->Set ( string ); Changed(); }; - OLECHAR* Get ( void ) { return text->Get (); }; - int Len ( void ) { return text->Len (); }; - char* GetSB ( void ) { return text->GetSB (); }; - void SetComment ( OLECHAR *string ) { comment->Set ( string ); Changed(); }; - void SetComment ( char *string ) { comment->Set ( string ); Changed(); }; - OLECHAR* Comment ( void ) { return comment->Get(); }; - char* CommentSB ( void ) { return comment->GetSB(); }; - int Revision ( void ) { return revision; }; - void SetRevision ( int new_rev ) { revision = new_rev; Changed(); }; - LangID GetLangID ( void ) { return langid; }; - const char* Language ( void ) { return GetLangName ( langid );}; - void AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes = FALSE ); - int TooLong ( int maxlen ); - int ValidateFormat ( NoxText *text ); - int IsSent ( void ); - void Sent ( int val ); -}; - -class NoxText : public DBAttribs -{ - - TransDB *db; - - OLEString *text; - NoxLabel *label; - OLEString *wavefile; - unsigned int line_number; - List translations; - int revision; - int id; - int retranslate; - int sent; - - void init ( void ); - - public: - CWaveInfo WaveInfo; - - NoxText( void ); - ~NoxText( ); - - void AddTranslation ( Translation *trans ); - Translation* FirstTranslation ( ListSearch &sh ); - Translation* NextTranslation ( ListSearch &sh ); - Translation* GetTranslation ( LangID langid ); - void SetDB ( TransDB *new_db ); - void ClearChanges ( void ); - void ClearProcessed ( void ); - void ClearMatched ( void ); - int Clear ( void ); - NoxText* Clone ( void ); - void Remove ( void ); - void AssignID ( void ); - void Set ( OLECHAR *string ); - void Set ( char *string ); - void SetID ( int new_id ) { id = new_id; Changed(); }; - int ID ( void ) { return id; }; - void LockText ( void ) { text->Lock(); }; - TransDB* DB ( void ) { return db; }; - OLECHAR* Get ( void ) { return text->Get (); } ; - int Len ( void ) { return text->Len (); }; - char* GetSB ( void ) { return text->GetSB (); } ; - void SetWave ( OLECHAR *string ) { wavefile->Set ( string ); Changed(); InvalidateAllWaves (); }; - void SetWave ( char *string ) { wavefile->Set ( string ); Changed(); InvalidateAllWaves (); }; - void SetLabel ( NoxLabel *new_label ) { label = new_label; }; - void SetRetranslate ( int flag = TRUE ) { retranslate = flag;}; - int Retranslate ( void ) { return retranslate; }; - OLECHAR* Wave ( void ) { return wavefile->Get (); } ; - char* WaveSB ( void ) { return wavefile->GetSB (); } ; - NoxLabel* Label ( void ) { return label; } ; - int Revision ( void ) { return revision; } ; - void SetRevision ( int new_rev ) { revision = new_rev; Changed(); } ; - void IncRevision ( void ) { revision++; Changed(); }; - void AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes = FALSE ); - int LineNumber ( void ) { return line_number; }; - void SetLineNumber ( int line ) { line_number = line; Changed(); }; - void FormatMetaString ( void ) { text->FormatMetaString (); Changed();}; - int IsDialog ( void ); - int DialogIsPresent ( const char *path, LangID langid = LANGID_US ); - int DialogIsValid ( const char *path, LangID langid = LANGID_US, int check = TRUE ); - int ValidateDialog( const char *path, LangID langid = LANGID_US ); - void InvalidateAllWaves ( void ); - void InvalidateWave ( void ); - void InvalidateWave ( LangID langid ); - int IsSent ( void ); - void Sent ( int val ); - -}; - - -class NoxLabel : public DBAttribs -{ - TransDB *db; - - - OLEString *name; - OLEString *comment; - OLEString *context; - OLEString *speaker; - OLEString *listener; - unsigned int max_len; - unsigned int line_number; - List text; - - void init ( void ); - - public: - - NoxLabel ( void ); - ~NoxLabel ( ); - - int Clear ( void ); - void ClearChanges ( void ); - void ClearProcessed ( void ); - void ClearMatched ( void ); - int AllMatched ( void ); - void Remove ( void ); - void AddText ( NoxText *new_text ); - void RemoveText ( NoxText *new_text ); - NoxText* FirstText ( ListSearch& sh ); - NoxText* NextText ( ListSearch& sh); - NoxText* FindText ( OLECHAR *find_text ); - void SetDB ( TransDB *new_db ); - NoxLabel* Clone ( void ); - int NumStrings ( void ) { return text.NumItems(); }; - void SetMaxLen ( int max ) { max_len = max; Changed(); }; - int MaxLen ( void ) { return max_len; }; - void SetLineNumber( int line ) { line_number = line; Changed(); }; - int LineNumber ( void ) { return line_number; }; - TransDB* DB ( void ) { return db;}; - void LockName ( void ) { name->Lock(); }; - void SetName ( OLECHAR *string ) { name->Set ( string ); Changed(); }; - void SetName ( char *string ) { name->Set ( string ); Changed(); }; - void SetComment ( OLECHAR *string ) { comment->Set ( string ); Changed(); }; - void SetComment ( char *string ) { comment->Set ( string ); Changed(); }; - void SetContext ( OLECHAR *string ) { context->Set ( string ); Changed(); }; - void SetContext ( char *string ) { context->Set ( string ); Changed(); }; - void SetSpeaker ( char *string ) { speaker->Set ( string ); Changed(); }; - void SetSpeaker ( OLECHAR *string ) { speaker->Set ( string ); Changed(); }; - void SetListener ( char *string ) { listener->Set ( string ); Changed(); }; - void SetListener ( OLECHAR *string ) { listener->Set ( string ); Changed(); }; - - OLECHAR* Name ( void ) { return name->Get (); }; - OLECHAR* Comment ( void ) { return comment->Get(); }; - OLECHAR* Context ( void ) { return context->Get(); }; - OLECHAR* Speaker ( void ) { return speaker->Get(); }; - OLECHAR* Listener ( void ) { return listener->Get(); }; - - - char* NameSB ( void ) { return name->GetSB (); }; - char* CommentSB ( void ) { return comment->GetSB(); }; - char* ContextSB ( void ) { return context->GetSB(); }; - char* SpeakerSB ( void ) { return speaker->GetSB(); }; - char* ListenerSB ( void ) { return listener->GetSB(); }; - - void AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes = FALSE ); - -}; - -#define TRANSDB_OPTION_NONE 00000000 -#define TRANSDB_OPTION_DUP_TEXT 00000001 // strings can be dupilcated across labels -#define TRANSDB_OPTION_MULTI_TEXT 00000002 // labels can have more than 1 string - -const int START_STRING_ID = 10000; -class TransDB : public DBAttribs -{ - ListNode node; - List labels; - List obsolete; - Bin *label_bin; - Bin *text_bin; - BinID *text_id_bin; - Bin *obsolete_bin; - char name[100]; - int num_obsolete; - int next_string_id; - int valid; - int checked_for_errors; - int last_error_count; - int flags; - - - public: - - TransDB ( const char *name = "no name" ); - ~TransDB ( ); - - void InvalidateDialog( LangID langid ); - void VerifyDialog( LangID langid, void (*cb) ( void ) = NULL ); - int ReportDialog( DLGREPORT *report, LangID langid, void (*print) ( const char *)= NULL, PMASK pmask= PMASK_ALL ); - int ReportTranslations( TRNREPORT *report, LangID langid, void (*print) ( const char *) = NULL, PMASK pmask = PMASK_ALL ); - void ReportDuplicates ( CNoxstringDlg *dlg = NULL ); - void AddLabel ( NoxLabel *label ); - void AddText ( NoxText *text ); - void AddObsolete ( NoxText *text ); - void RemoveLabel ( NoxLabel *label ); - void RemoveText ( NoxText *text ); - void RemoveObsolete ( NoxText *text ); - int Errors ( CNoxstringDlg *dlg = NULL ); - int HasErrors ( void ) { return checked_for_errors ? last_error_count != 0 : FALSE; }; - int Warnings ( CNoxstringDlg *dlg = NULL ); - int NumLabelsChanged ( void ); - int NumLabels ( void ); - int NumObsolete ( void ) { return num_obsolete; }; - NoxLabel* FirstLabel ( ListSearch& sh ); - NoxLabel* NextLabel ( ListSearch& sh); - NoxText* FirstObsolete ( ListSearch& sh ); - NoxText* NextObsolete ( ListSearch& sh); - NoxLabel* FindLabel ( OLECHAR *name ); - NoxText* FindText ( OLECHAR *text ); - NoxText* FindSubText ( OLECHAR *text, int item = 0 ); - NoxText* FindText ( int id ); - NoxText* FindNextText ( void ); - NoxText* FindObsolete ( OLECHAR *text ); - NoxText* FindNextObsolete ( void ); - int Clear ( void ); - void ClearChanges ( void ); - void ClearProcessed ( void ); - void ClearMatched ( void ); - TransDB* Next ( void ); - void AddToTree ( CTreeCtrl *tc, HTREEITEM parent, int changes = FALSE, void (*cb) ( void ) = NULL ); - char* Name ( void ) { return name;}; - void EnableIDs ( void ) { next_string_id = START_STRING_ID; }; - int NewID ( void ) { if ( next_string_id != -1) return next_string_id++; else return -1; }; - int ID ( void ) { return next_string_id; }; - void SetID ( int new_id ) { next_string_id = new_id; }; - int IsValid ( void ) { return valid; }; - void InValid ( void ) { valid = FALSE; }; - int DuplicatesAllowed ( void ) { return flags & TRANSDB_OPTION_DUP_TEXT;}; - int MultiTextAllowed ( void ) { return flags & TRANSDB_OPTION_MULTI_TEXT;}; - void AllowDupiclates ( int yes = TRUE) { yes ? flags |= TRANSDB_OPTION_DUP_TEXT : flags &= ~(TRANSDB_OPTION_DUP_TEXT ); }; - void AllowMultiText ( int yes = TRUE) { yes ? flags |= TRANSDB_OPTION_MULTI_TEXT : flags &= ~(TRANSDB_OPTION_MULTI_TEXT ); }; -}; - - -class DupNode : public ListNode -{ - NoxText *original; - NoxText *duplicate; - - public: - DupNode ( NoxText *dup, NoxText *orig ) { original = orig; duplicate = dup, SetPriority ( orig->LineNumber ());}; - - NoxText *Duplicate ( void ) { return duplicate; }; - NoxText *Original ( void ) { return original; }; - -}; - - - -extern TransDB* FirstTransDB ( void ); - - - -#endif // __TRANSDB_H \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/VIEWDBSII.cpp b/Generals/Code/Tools/Babylon/VIEWDBSII.cpp deleted file mode 100644 index 3ae87ffdcf..0000000000 --- a/Generals/Code/Tools/Babylon/VIEWDBSII.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// VIEWDBSII.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "VIEWDBSII.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// VIEWDBSII dialog - - -VIEWDBSII::VIEWDBSII(CWnd* pParent /*=NULL*/) - : CDialog(VIEWDBSII::IDD, pParent) -{ - //{{AFX_DATA_INIT(VIEWDBSII) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void VIEWDBSII::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(VIEWDBSII) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(VIEWDBSII, CDialog) - //{{AFX_MSG_MAP(VIEWDBSII) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// VIEWDBSII message handlers diff --git a/Generals/Code/Tools/Babylon/VIEWDBSII.h b/Generals/Code/Tools/Babylon/VIEWDBSII.h deleted file mode 100644 index d8dfbcc3d1..0000000000 --- a/Generals/Code/Tools/Babylon/VIEWDBSII.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_VIEWDBSII_H__AC697EE4_6D37_4F29_ACC7_8B260A33DA2E__INCLUDED_) -#define AFX_VIEWDBSII_H__AC697EE4_6D37_4F29_ACC7_8B260A33DA2E__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// VIEWDBSII.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// VIEWDBSII dialog - -class VIEWDBSII : public CDialog -{ -// Construction -public: - VIEWDBSII(CWnd* pParent = NULL); // standard constructor - - void OnClose(); - BOOL OnInitDialog(); - HTREEITEM create_changes_view ( void ); - HTREEITEM create_full_view ( void ); - -// Dialog Data - //{{AFX_DATA(VIEWDBSII) - enum { IDD = IDD_VIEWDBS }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(VIEWDBSII) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(VIEWDBSII) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -extern int ViewChanges; -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_VIEWDBSII_H__AC697EE4_6D37_4F29_ACC7_8B260A33DA2E__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/VerifyDlg.cpp b/Generals/Code/Tools/Babylon/VerifyDlg.cpp deleted file mode 100644 index 7e7ac8533b..0000000000 --- a/Generals/Code/Tools/Babylon/VerifyDlg.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// VerifyDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "VerifyDlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -#define TIMERID 1000 - -///////////////////////////////////////////////////////////////////////////// -// VerifyDlg dialog - - -VerifyDlg::VerifyDlg( NoxText *ntext, LangID langid, const char *path, CWnd* pParent /*=NULL*/) - : CDialog(VerifyDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(VerifyDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT - - nox_text = ntext; - linfo = GetLangInfo ( langid ); - sprintf ( wavefile, "%s%s\\%s%s.wav", path, linfo->character, ntext->WaveSB(), linfo->character ); -} - - -void VerifyDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(VerifyDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(VerifyDlg, CDialog) - //{{AFX_MSG_MAP(VerifyDlg) - ON_BN_CLICKED(IDC_NOMATCH, OnNomatch) - ON_BN_CLICKED(IDOK, OnMatch) - ON_BN_CLICKED(IDC_STOP, OnStop) - ON_BN_CLICKED(IDC_PLAY, OnPlay) - ON_BN_CLICKED(IDC_PAUSE, OnPause) - ON_WM_TIMER() - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// VerifyDlg message handlers - -BOOL VerifyDlg::OnInitDialog() -{ - //long total; - CDialog::OnInitDialog(); - RECT rect; - - // TODO: Add extra initialization here - - this->GetWindowRect ( &rect ); - rect.top -= 100; - rect.bottom -= 100; - this->MoveWindow ( &rect ); - stop.AutoLoad ( IDC_STOP, this ); - pause.AutoLoad ( IDC_PAUSE, this ); - play.AutoLoad ( IDC_PLAY, this ); - - wave = GetDlgItem ( IDC_WAVENAME ); - text = (CStatic *) GetDlgItem ( IDC_TEXT ); - slider = (CSliderCtrl *) GetDlgItem ( IDC_SLIDER ); - - wave->SetWindowText ( wavefile ); - SetDlgItemText ( IDC_TEXT_TITLE, (nox_text->Label()->NameSB())); - if ( linfo->langid == LANGID_US ) - { - text->SetWindowText ( nox_text->GetSB ()); - } - else - { - Translation *trans = nox_text->GetTranslation ( linfo->langid ); - - if ( trans ) - { - text->SetWindowText ( trans->GetSB ()); - } - else - { - text->SetWindowText ( "No translation!!"); - } - - } - -#if 0 - HDIGDRIVER dig; - HMDIDRIVER mdi; - HDLSDEVICE dls; - - AIL_quick_handles ( &dig, &mdi, &dls ); - stream = AIL_open_stream ( dig, wavefile, 0 ); - if ( stream ) - { - timer = SetTimer( TIMERID, 300, NULL ); - AIL_stream_ms_position ( stream, &total, NULL ); - slider->SetRange ( 0, total ); - } -#endif - - PostMessage ( WM_COMMAND, MAKEWPARAM ( IDC_PLAY, BN_CLICKED )); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void VerifyDlg::OnNomatch() -{ - // TODO: Add your control notification handler code here - CloseAudio (); - this->EndDialog ( IDSKIP ); -} - -void VerifyDlg::OnMatch() -{ - // TODO: Add your control notification handler code here - CloseAudio (); - CDialog::OnOK(); - -} - -void VerifyDlg::OnCancel() -{ - // TODO: Add extra cleanup here - - CloseAudio (); - CDialog::OnCancel(); -} - -void VerifyDlg::OnStop() -{ - // TODO: Add your control notification handler code here - #if 0 - if ( stream ) - { - AIL_pause_stream ( stream, TRUE ); - AIL_set_stream_ms_position ( stream, 0 ); - } - #endif -} - -void VerifyDlg::OnPlay() -{ - // TODO: Add your control notification handler code here - #if 0 - if ( stream ) - { - if ( AIL_stream_status ( stream ) == SMP_STOPPED ) - { - AIL_pause_stream ( stream, FALSE); - } - else - { - AIL_start_stream ( stream ); - } - } - #endif -} - -void VerifyDlg::OnPause() -{ - // TODO: Add your control notification handler code here - #if 0 - if ( stream ) - { - if ( AIL_stream_status ( stream ) == SMP_STOPPED ) - { - AIL_pause_stream ( stream, FALSE); - } - else - { - AIL_pause_stream ( stream, TRUE); - } - } - #endif - -} - -void VerifyDlg::CloseAudio ( void ) -{ - #if 0 - if ( stream ) - { - AIL_close_stream ( stream ); - stream = NULL; - } - #endif -} - -void VerifyDlg::OnTimer(UINT nIDEvent) -{ - // TODO: Add your message handler code here and/or call default - if ( nIDEvent == TIMERID ) - { - #if 0 - if ( stream ) - { - long current; - AIL_stream_ms_position ( stream, NULL, ¤t ); - slider->SetPos ( current ); - } - #endif - } - else - { - CDialog::OnTimer(nIDEvent); - } -} - diff --git a/Generals/Code/Tools/Babylon/VerifyDlg.h b/Generals/Code/Tools/Babylon/VerifyDlg.h deleted file mode 100644 index 9dec509a73..0000000000 --- a/Generals/Code/Tools/Babylon/VerifyDlg.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_VERIFYDLG_H__88E9C121_599B_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_VERIFYDLG_H__88E9C121_599B_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// VerifyDlg.h : header file -// - -#include "TransDB.h" -#define IDSKIP 100 - -///////////////////////////////////////////////////////////////////////////// -// VerifyDlg dialog - -class VerifyDlg : public CDialog -{ - CBitmapButton stop; - CBitmapButton play; - CBitmapButton pause; - CWnd *wave; - CStatic *text; - NoxText *nox_text; - LANGINFO *linfo; - UINT timer; - char wavefile[1024]; - CSliderCtrl *slider; -// Construction -public: - VerifyDlg(NoxText *ntext, LangID langid, const char *path, CWnd* pParent = NULL); // standard constructor - void CloseAudio ( void ); - -// Dialog Data - //{{AFX_DATA(VerifyDlg) - enum { IDD = IDD_MATCHDIALOG }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(VerifyDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(VerifyDlg) - virtual BOOL OnInitDialog(); - afx_msg void OnNomatch(); - afx_msg void OnMatch(); - virtual void OnCancel(); - afx_msg void OnStop(); - afx_msg void OnPlay(); - afx_msg void OnPause(); - afx_msg void OnTimer(UINT nIDEvent); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_VERIFYDLG_H__88E9C121_599B_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/VerifyTextDlg.cpp b/Generals/Code/Tools/Babylon/VerifyTextDlg.cpp deleted file mode 100644 index 65e3d54bdf..0000000000 --- a/Generals/Code/Tools/Babylon/VerifyTextDlg.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// VerifyTextDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "VerifyTextDlg.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CVerifyTextDlg dialog - - -CVerifyTextDlg::CVerifyTextDlg( char *trans, char *orig, CWnd* pParent /*=NULL*/) - : CDialog(CVerifyTextDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(CVerifyTextDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT - - m_trans = trans; - m_orig = orig; -} - - -void CVerifyTextDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CVerifyTextDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CVerifyTextDlg, CDialog) - //{{AFX_MSG_MAP(CVerifyTextDlg) - ON_BN_CLICKED(IDC_NOMATCH, OnNomatch) - ON_BN_CLICKED(IDC_MATCH, OnMatch) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CVerifyTextDlg message handlers - -void CVerifyTextDlg::OnNomatch() -{ - - EndDialog ( IDNO ); - -} - -void CVerifyTextDlg::OnMatch() -{ - - EndDialog ( IDYES ); - -} - -BOOL CVerifyTextDlg::OnInitDialog() -{ - CDialog::OnInitDialog(); - - SetDlgItemText ( IDC_TRANS, m_trans ); - SetDlgItemText ( IDC_ORIG, m_orig ); - - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} diff --git a/Generals/Code/Tools/Babylon/VerifyTextDlg.h b/Generals/Code/Tools/Babylon/VerifyTextDlg.h deleted file mode 100644 index fb18f912b3..0000000000 --- a/Generals/Code/Tools/Babylon/VerifyTextDlg.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if !defined(AFX_VERIFYTEXTDLG_H__39DB1C81_6B90_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_VERIFYTEXTDLG_H__39DB1C81_6B90_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// VerifyTextDlg.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CVerifyTextDlg dialog - -class CVerifyTextDlg : public CDialog -{ -// Construction - char *m_trans; - char *m_orig; -public: - CVerifyTextDlg(char *trans, char *orig, CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CVerifyTextDlg) - enum { IDD = IDD_VERIFYTEXT }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CVerifyTextDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CVerifyTextDlg) - afx_msg void OnNomatch(); - afx_msg void OnMatch(); - virtual BOOL OnInitDialog(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_VERIFYTEXTDLG_H__39DB1C81_6B90_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/ViewDBsDlg.cpp b/Generals/Code/Tools/Babylon/ViewDBsDlg.cpp deleted file mode 100644 index 5297346358..0000000000 --- a/Generals/Code/Tools/Babylon/ViewDBsDlg.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// ViewDBsDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "noxstringDlg.h" -#include "VIEWDBSII.h" -#include "TransDB.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -int ViewChanges = FALSE; - -///////////////////////////////////////////////////////////////////////////// -// CViewDBsDlg dialog - - -VIEWDBSII::VIEWDBSII(CWnd* pParent /*=NULL*/) - : CDialog(VIEWDBSII::IDD, pParent) -{ - //{{AFX_DATA_INIT(CViewDBsDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void VIEWDBSII::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CViewDBsDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(VIEWDBSII, CDialog) - //{{AFX_MSG_MAP(CViewDBsDlg) - ON_WM_CLOSE() - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CViewDBsDlg message handlers - -static int label_count; -static void progress_cb ( void ) -{ - label_count++; - if ( MainDLG ) - { - MainDLG->SetProgress ( label_count ); - } -} - -HTREEITEM VIEWDBSII::create_full_view ( void ) -{ - CTreeCtrl *tc = ( CTreeCtrl *) GetDlgItem ( IDC_TREEVIEW ); - HTREEITEM root; - TransDB *db; - int count = 0; - const char *title = "Building database view..."; - - MainDLG->Log (""); - MainDLG->Status ( title ); - - root = tc->InsertItem ( "DBs" ); - - - db = FirstTransDB ( ); - - while ( db ) - { - count += db->NumLabels (); - count += db->NumObsolete (); - db = db->Next (); - } - - MainDLG->InitProgress ( count ); - - label_count = 0; - - db = FirstTransDB ( ); - - while ( db ) - { - char buffer[100]; - - sprintf ( buffer, "%s%s", title, db->Name()); - MainDLG->Status ( buffer, FALSE ); - db->AddToTree ( tc, root, FALSE, progress_cb ); - db = db->Next (); - } - - MainDLG->Log ("OK", SAME_LINE ); - tc->Expand ( root, TVE_EXPAND ); - return root; -} - -HTREEITEM VIEWDBSII::create_changes_view ( void ) -{ - CTreeCtrl *tc = ( CTreeCtrl *) GetDlgItem ( IDC_TREEVIEW ); - HTREEITEM root; - TransDB *db; - int count = 0; - const char *title = "Building changes view..."; - - MainDLG->Log (""); - MainDLG->Status ( title ); - - - - db = FirstTransDB ( ); - - while ( db ) - { - if ( db->IsChanged ()) - { - count += db->NumLabels (); - count += db->NumObsolete (); - } - db = db->Next (); - } - - if ( MainDLG ) - { - MainDLG->InitProgress ( count ); - } - - if ( count ) - { - root = tc->InsertItem ( "Changes" ); - } - else - { - root = tc->InsertItem ( "No Changes" ); - } - - label_count = 0; - - db = FirstTransDB ( ); - - while ( db ) - { - char buffer[100]; - - if ( db->IsChanged ()) - { - sprintf ( buffer, "%s%s", title, db->Name()); - MainDLG->Status ( buffer, FALSE ); - db->AddToTree ( tc, root, TRUE, progress_cb ); - } - db = db->Next (); - } - - if ( MainDLG ) - { - MainDLG->ProgressComplete ( ); - MainDLG->Log ("OK", SAME_LINE ); - MainDLG->Ready (); - } - - tc->Expand ( root, TVE_EXPAND ); - return root; -} - -BOOL VIEWDBSII::OnInitDialog() -{ - HTREEITEM root; - CDialog::OnInitDialog(); - - // TODO: Add extra initialization here - - if ( !ViewChanges ) - { - root = create_full_view (); - } - else - { - root = create_changes_view (); - } - - - MainDLG->Ready(); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void VIEWDBSII::OnClose() -{ - // TODO: Add your message handler code here and/or call default - - CTreeCtrl *tc = ( CTreeCtrl *) GetDlgItem ( IDC_TREEVIEW ); - HTREEITEM root = tc->GetRootItem (); - tc->Expand ( root, TVE_COLLAPSE ); - tc->DeleteAllItems (); - CDialog::OnClose(); -} - diff --git a/Generals/Code/Tools/Babylon/XLStuff.cpp b/Generals/Code/Tools/Babylon/XLStuff.cpp deleted file mode 100644 index bbfe4a41e9..0000000000 --- a/Generals/Code/Tools/Babylon/XLStuff.cpp +++ /dev/null @@ -1,673 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// XLStuff.cpp -// -// -#include "StdAfx.h" -#include "noxstring.h" -#include "resource.h" -#include -#include "XLStuff.h" -#include -#include - -static const int xlWorkbookNormal = -4143; -static const int xlNoChange = 1; -static const int xlLocalSessionChanges = 2; -static const int xlWBATWorksheet = -4167; -static _Workbook *workbook = NULL; -static _Application *xl = NULL; -static Workbooks *wbs = NULL; -static Range *range = NULL; -static _Worksheet *ws = NULL; -static OLECHAR buffer[100*1024]; - -static VARIANT no, yes, dummy, dummy0, nullstring, empty; -static VARIANT continuous, automatic, medium, thin, none; -static VARIANT yellow, solid; - -static VARIANT GetCell ( int row, int column ) -{ - VARIANT cell; - VARIANT result; - LPDISPATCH dispatch; - OLECHAR cellname[20]; - - V_VT ( &cell ) = VT_EMPTY; - - assert ( column > 0 ); - swprintf ( cellname, L"%c%d", 'A'+column -1 , row ); - V_VT ( &cell ) = VT_BSTR; - V_BSTR ( &cell ) = SysAllocString (cellname); - - V_VT ( &result ) = VT_BOOL; - V_BOOL ( &result ) = FALSE; - - if ( !ws ) - { - goto error; - } - - if ( ! (dispatch = ws->GetRange (cell, cell ))) - { - goto error; - } - - - range->AttachDispatch ( dispatch ); - result = range->GetValue (); - range->ReleaseDispatch ( ); - -error: - - VariantClear ( &cell ); - - return result; -} - - -int PutCell ( int row, int column, const OLECHAR *string, int val ) -{ - VARIANT cell; - VARIANT newValue; - int ok = FALSE; - LPDISPATCH dispatch; - OLECHAR cellname[20]; - - - V_VT ( &newValue ) = VT_EMPTY; - V_VT ( &cell ) = VT_EMPTY; - - assert ( column > 0 ); - swprintf ( cellname, L"%c%d", 'A'+column-1, row ); - V_VT ( &cell ) = VT_BSTR; - V_BSTR ( &cell ) = SysAllocString (cellname); - - if ( !ws ) - { - goto error; - } - - if ( ! (dispatch = ws->GetRange (cell, cell ))) - { - goto error; - } - - range->AttachDispatch ( dispatch ); - - if ( string ) - { - V_VT ( &newValue ) = VT_BSTR; - - if ( string[0] == '\'') - { - buffer[0] = '\\'; - wcscpy ( &buffer[1], string ); - V_BSTR ( &newValue ) = SysAllocString ( buffer ); - } - else - { - V_BSTR ( &newValue ) = SysAllocString ( string ); - } - - } - else - { - V_VT ( &newValue ) = VT_I4; - V_I4 ( &newValue ) = val; - } - - range->SetValue ( newValue ); - range->ReleaseDispatch ( ); - ok = TRUE; - -error: - - - VariantClear ( &cell ); - VariantClear ( &newValue ); - - return ok; -} - -int PutSeparator ( int row ) -{ -// Rows(row).Select -// Selection.Borders(xlDiagonalDown).LineStyle = xlNone -// Selection.Borders(xlDiagonalUp).LineStyle = xlNone -// Selection.Borders(xlEdgeLeft).LineStyle = xlNone -// Selection.Borders(xlEdgeTop).LineStyle = xlNone -// With Selection.Borders(xlEdgeBottom) -// .LineStyle = xlContinuous -// .Weight = xlMedium -// .ColorIndex = xlAutomatic -// End With -// With Selection.Borders(xlEdgeRight) -// .LineStyle = xlContinuous -// .Weight = xlThin -// .ColorIndex = xlAutomatic -// End With - int ok = FALSE; - Border *border = NULL; - Borders *borders = NULL; - LPDISPATCH dispatch; - OLECHAR cellname1[20]; - OLECHAR cellname2[20]; - VARIANT cell1,cell2; - - if ( !ws ) - { - goto error; - } - - assert ( row > 0 ); - swprintf ( cellname1, L"A%d", row ); - swprintf ( cellname2, L"%c%d", 'A'+CELL_LAST-1-1, row ); - V_VT ( &cell1 ) = VT_BSTR; - V_BSTR ( &cell1 ) = SysAllocString (cellname1); - - V_VT ( &cell2 ) = VT_BSTR; - V_BSTR ( &cell2 ) = SysAllocString (cellname2); - - - if ( ! (dispatch = ws->GetRange (cell1, cell2 ))) - { - goto error; - } - - range->AttachDispatch ( dispatch ); - - dispatch = range->GetBorders (); - - - borders = new Borders ( dispatch ); - - if ( !borders ) - { - goto error; - } - - dispatch = borders->GetItem ( xlEdgeBottom ); - - border = new Border ( dispatch ); - - if ( !border ) - { - goto error; - } - - border->SetLineStyle ( continuous ); - border->SetColorIndex ( automatic ); - border->SetWeight ( thin ); - - ok = TRUE; - -error: - - range->ReleaseDispatch ( ); - - if ( borders ) - { - delete borders ; - } - - if ( border ) - { - delete border ; - } - - VariantClear ( &cell1 ); - VariantClear ( &cell2 ); - - return ok; -} - - -int PutSection ( int row, OLECHAR *title ) -{ - - int ok = FALSE; - Range *range = NULL; - Border *border = NULL; - Borders *borders = NULL; - Interior *interior = NULL; - LPDISPATCH dispatch; - OLECHAR cellname1[20]; - OLECHAR cellname2[20]; - VARIANT cell1,cell2; - _Worksheet *ws = NULL; - - if ( !ws ) - { - goto error; - } - - assert ( row > 0 ); - swprintf ( cellname1, L"A%d", row ); - swprintf ( cellname2, L"%c%d", 'A'+CELL_LAST-1-1, row ); - V_VT ( &cell1 ) = VT_BSTR; - V_BSTR ( &cell1 ) = SysAllocString (cellname1); - - V_VT ( &cell2 ) = VT_BSTR; - V_BSTR ( &cell2 ) = SysAllocString (cellname2); - - - if ( ! (dispatch = ws->GetRange (cell1, cell2 ))) - { - goto error; - } - - range->AttachDispatch ( dispatch ); - - dispatch = range->GetBorders (); - - - borders = new Borders ( dispatch ); - - if ( !borders ) - { - goto error; - } - - dispatch = borders->GetItem ( xlEdgeBottom ); - - border = new Border ( dispatch ); - - if ( !border ) - { - goto error; - } - - border->SetLineStyle ( continuous ); - border->SetColorIndex ( automatic ); - border->SetWeight ( thin ); - - delete border; - border = NULL; - - dispatch = borders->GetItem ( xlEdgeTop ); - - border = new Border ( dispatch ); - - if ( !border ) - { - goto error; - } - - border->SetLineStyle ( continuous ); - border->SetColorIndex ( automatic ); - border->SetWeight ( medium ); - - delete border; - border = NULL; - - dispatch = borders->GetItem ( xlEdgeRight ); - - border = new Border ( dispatch ); - - if ( !border ) - { - goto error; - } - - border->SetLineStyle ( none ); - - delete border; - border = NULL; - - dispatch = borders->GetItem ( xlEdgeLeft ); - - border = new Border ( dispatch ); - - if ( !border ) - { - goto error; - } - - border->SetLineStyle ( none ); - - dispatch = range->GetInterior ( ); - - interior = new Interior ( dispatch ); - - if ( !interior ) - { - goto error; - } - - interior->SetColorIndex ( yellow ); - interior->SetPattern ( solid ); - - PutCell ( row, 1, L"Section", 0 ); - PutCell ( row, 2, title, 0 ); - - ok = TRUE; - -error: - - range->ReleaseDispatch ( ); - - if ( borders ) - { - delete borders ; - } - - if ( border ) - { - delete border ; - } - - VariantClear ( &cell1 ); - VariantClear ( &cell2 ); - - return ok; - -} - -int OpenExcel ( void ) -{ - LPDISPATCH dispatch; - - if ( xl ) - { - return TRUE; - } -#if 0 - while ( ExcelRunning ()) - { - if ( AfxMessageBox ( "Excel is running!\n\nClose or kill all instances of Excel and retry\n\nNOTE: Check task tray (CTRL-ALT-DELETE) for instances of Excel", MB_OKCANCEL ) == IDCANCEL ) - { - return FALSE; - } - } -#endif - - xl = new _Application(); - - if ( !xl ) - { - return FALSE; - } - - if ( !xl->CreateDispatch ("Excel.Application")) - { - goto error_access; - } - - dispatch = xl->GetWorkbooks ( ); - - if ( dispatch ) - { - wbs = new Workbooks( dispatch ); - } - - if ( !wbs ) - { - return FALSE; - } - - if ( ! (ws = new _Worksheet ())) - { - return FALSE; - } - - if ( ! (range = new Range ())) - { - return FALSE; - } - - - V_VT ( &no ) = VT_BOOL; - V_VT ( &yes ) = VT_BOOL; - V_VT ( &dummy ) = VT_I4; - V_VT ( &dummy0 ) = VT_I4; - V_VT ( &nullstring ) = VT_BSTR ; - V_VT ( &empty ) = VT_EMPTY; - V_VT ( &continuous ) = VT_I4; - V_VT ( &automatic ) = VT_I4; - V_VT ( &medium ) = VT_I4; - V_VT ( &thin ) = VT_I4; - V_VT ( &none ) = VT_I4; - V_VT ( &solid ) = VT_I4; - V_VT ( &yellow ) = VT_I4; - - V_BOOL ( &no ) = FALSE; - V_BOOL ( &yes ) = TRUE; - V_I4 ( &dummy ) = 1; - V_I4 ( &dummy0 ) = 0; - V_BSTR ( &nullstring ) = SysAllocString ( OLESTR ("") ); - - V_I4 ( &continuous ) = xlContinuous; - V_I4 ( &automatic ) = xlAutomatic; - V_I4 ( &medium ) = xlMedium; - V_I4 ( &thin ) = xlThin; - V_I4 ( &none ) = xlThin; - V_I4 ( &solid ) = xlSolid; - V_I4 ( &yellow ) = 6; - - - return TRUE; - -error_access: - AfxMessageBox ("Could not access Excel!\n\nMake sure Excel is installed on this system."); - return FALSE; -} - - -void CloseExcel ( void ) -{ - CloseWorkBook (); - - if ( range ) - { - delete range; - range = NULL; - } - - if ( ws ) - { - delete ws; - ws = NULL; - } - - if ( wbs ) - { - wbs->Close(); - delete wbs; - wbs = NULL; - } - - if ( xl ) - { - xl->Quit(); - xl->ReleaseDispatch (); - delete xl; - xl = NULL; - } - - VariantClear ( &nullstring ); - -} - -int OpenWorkBook ( const char *filename ) -{ - LPDISPATCH dispatch; - - dispatch = wbs->Open ((LPCTSTR) filename, dummy0, yes, dummy, nullstring, nullstring, yes, dummy, dummy, no, no, dummy, no ); - - if ( dispatch ) - { - workbook = new _Workbook ( dispatch ); - } - - if ( !workbook ) - { - return FALSE; - } - - SelectActiveSheet ( ); - - return TRUE; -} - -int NewWorkBook ( const char *path ) -{ - LPDISPATCH dispatch; - VARIANT temp; - char tfile[200]; - char *p; - WIN32_FIND_DATA finfo; - HANDLE handle; - - V_VT ( &temp ) = VT_I4; - V_I4 ( &temp ) = xlWBATWorksheet; - - if ( path ) - { - strcpy ( tfile, path ); - if ( (p = strchr ( tfile, '.' ))) - { - *p = 0; - } - - strcpy ( p, ".xlt" ); - - if ( (handle = FindFirstFile ( tfile, &finfo)) != INVALID_HANDLE_VALUE ) - { - if ( !(finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) - { - swprintf ( buffer, L"%S", tfile ); - V_VT ( &temp ) = VT_BSTR; - V_BSTR ( &temp ) = SysAllocString ( buffer ); - } - - FindClose ( handle ); - } - } - - dispatch = wbs->Add ( temp ); - - VariantClear ( &temp ); - - if ( dispatch ) - { - workbook = new _Workbook ( dispatch ); - } - - if ( !workbook ) - { - return FALSE; - } - SelectActiveSheet ( ); - return TRUE; -} - -int SaveWorkBook ( const char *filename, int protect ) -{ - VARIANT name, fileformat, rc; - - V_VT ( &name ) = VT_BSTR; - swprintf ( buffer, L"%S", filename ); - V_BSTR ( &name ) = SysAllocString ( buffer ); - - V_VT ( &fileformat ) = VT_I4; - V_I4 ( &fileformat ) = xlWorkbookNormal; - - - V_VT ( &rc ) = VT_I4; - V_I4 ( &rc ) = xlLocalSessionChanges; - - if ( protect ) - { - VARIANT password; - V_VT ( &password ) = VT_BSTR; - V_BSTR ( &password ) = SysAllocString ( L"" ); - - ws->Protect ( password, yes, yes, yes, no ); - VariantClear ( &password ); - } - workbook->SaveAs ( name, fileformat, nullstring, nullstring, no, no, - xlNoChange, rc, no, empty, empty ); - - VariantClear ( &name ); - - return TRUE; - -} - -void CloseWorkBook ( void ) -{ - if ( workbook ) - { - workbook->SetSaved ( TRUE ); - workbook->Close ( no, nullstring, no ); - delete workbook; - workbook = NULL; - } - -} - -void SelectActiveSheet ( void ) -{ - LPDISPATCH dispatch; - - if ( ! (dispatch = xl->GetActiveSheet ())) - { - return; - } - - ws->ReleaseDispatch ( ); - ws->AttachDispatch ( dispatch ); -} - -int GetInt ( int row, int cell ) -{ - long value; - VARIANT var; - _variant_t v; - - var = GetCell ( row, cell ); - - v.Attach ( var ); - - value = v; - - return (int) value; - -} - -int GetString ( int row, int cell, OLECHAR *string ) -{ - VARIANT var; - - string[0] =0; - var = GetCell ( row, cell ); - - if ( V_VT ( &var ) == VT_BSTR ) - { - wcscpy ( string, V_BSTR ( &var )); - - } - VariantClear ( &var ); - - return 1; - -} - diff --git a/Generals/Code/Tools/Babylon/XLStuff.h b/Generals/Code/Tools/Babylon/XLStuff.h deleted file mode 100644 index a0e2266085..0000000000 --- a/Generals/Code/Tools/Babylon/XLStuff.h +++ /dev/null @@ -1,262 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// XLStuff.h -// -// - -#ifndef XLSTUFF_H -#define XLSTUFF_H - -#include "noxstringDlg.h" -typedef enum { - xlAll = -4104, - xlAutomatic = -4105, - xlBoth = 1, - xlCenter = -4108, - xlChecker = 9, - xlCircle = 8, - xlCorner = 2, - xlCrissCross = 16, - xlCross = 4, - xlDiamond = 2, - xlDistributed = -4117, - xlDoubleAccounting = 5, - xlFixedValue = 1, - xlFormats = -4122, - xlGray16 = 17, - xlGray8 = 18, - xlGrid = 15, - xlHigh = -4127, - xlInside = 2, - xlJustify = -4130, - xlLightDown = 13, - xlLightHorizontal = 11, - xlLightUp = 14, - xlLightVertical = 12, - xlLow = -4134, - xlManual = -4135, - xlMinusValues = 3, - xlModule = -4141, - xlNextToAxis = 4, - xlNone = -4142, - xlNotes = -4144, - xlOff = -4146, - xlOn = 1, - xlPercent = 2, - xlPlus = 9, - xlPlusValues = 2, - xlSemiGray75 = 10, - xlShowLabel = 4, - xlShowLabelAndPercent = 5, - xlShowPercent = 3, - xlShowValue = 2, - xlSimple = -4154, - xlSingle = 2, - xlSingleAccounting = 4, - xlSolid = 1, - xlSquare = 1, - xlStar = 5, - xlStError = 4, - xlToolbarButton = 2, - xlTriangle = 3, - xlGray25 = -4124, - xlGray50 = -4125, - xlGray75 = -4126, - xlBottom = -4107, - xlLeft = -4131, - xlRight = -4152, - xlTop = -4160, - xl3DBar = -4099, - xl3DSurface = -4103, - xlBar = 2, - xlColumn = 3, - xlCombination = -4111, - xlCustom = -4114, - xlDefaultAutoFormat = -1, - xlMaximum = 2, - xlMinimum = 4, - xlOpaque = 3, - xlTransparent = 2, - xlBidi = -5000, - xlLatin = -5001, - xlContext = -5002, - xlLTR = -5003, - xlRTL = -5004, - xlVisualCursor = 2, - xlLogicalCursor = 1, - xlSystem = 1, - xlPartial = 3, - xlHindiNumerals = 3, - xlBidiCalendar = 3, - xlGregorian = 2, - xlComplete = 4, - xlScale = 3, - xlClosed = 3, - xlColor1 = 7, - xlColor2 = 8, - xlColor3 = 9, - xlConstants = 2, - xlContents = 2, - xlBelow = 1, - xlCascade = 7, - xlCenterAcrossSelection = 7, - xlChart4 = 2, - xlChartSeries = 17, - xlChartShort = 6, - xlChartTitles = 18, - xlClassic1 = 1, - xlClassic2 = 2, - xlClassic3 = 3, - xl3DEffects1 = 13, - xl3DEffects2 = 14, - xlAbove = 0, - xlAccounting1 = 4, - xlAccounting2 = 5, - xlAccounting3 = 6, - xlAccounting4 = 17, - xlAdd = 2, - xlDebugCodePane = 13, - xlDesktop = 9, - xlDirect = 1, - xlDivide = 5, - xlDoubleClosed = 5, - xlDoubleOpen = 4, - xlDoubleQuote = 1, - xlEntireChart = 20, - xlExcelMenus = 1, - xlExtended = 3, - xlFill = 5, - xlFirst = 0, - xlFloating = 5, - xlFormula = 5, - xlGeneral = 1, - xlGridline = 22, - xlIcons = 1, - xlImmediatePane = 12, - xlInteger = 2, - xlLast = 1, - xlLastCell = 11, - xlList1 = 10, - xlList2 = 11, - xlList3 = 12, - xlLocalFormat1 = 15, - xlLocalFormat2 = 16, - xlLong = 3, - xlLotusHelp = 2, - xlMacrosheetCell = 7, - xlMixed = 2, - xlMultiply = 4, - xlNarrow = 1, - xlNoDocuments = 3, - xlOpen = 2, - xlOutside = 3, - xlReference = 4, - xlSemiautomatic = 2, - xlShort = 1, - xlSingleQuote = 2, - xlStrict = 2, - xlSubtract = 3, - xlTextBox = 16, - xlTiled = 1, - xlTitleBar = 8, - xlToolbar = 1, - xlVisible = 12, - xlWatchPane = 11, - xlWide = 3, - xlWorkbookTab = 6, - xlWorksheet4 = 1, - xlWorksheetCell = 3, - xlWorksheetShort = 5, - xlAllExceptBorders = 6, - xlLeftToRight = 2, - xlTopToBottom = 1, - xlVeryHidden = 2, - xlDrawingObject = 14 -} Constants; - -typedef enum { - xlHairline = 1, - xlMedium = -4138, - xlThick = 4, - xlThin = 2 -} XlBorderWeight; - -typedef enum { - xlContinuous = 1, - xlDash = -4115, - xlDashDot = 4, - xlDashDotDot = 5, - xlDot = -4118, - xlDouble = -4119, - xlSlantDashDot = 13, - xlLineStyleNone = -4142 -} XlLineStyle; - -typedef enum { - xlInsideHorizontal = 12, - xlInsideVertical = 11, - xlDiagonalDown = 5, - xlDiagonalUp = 6, - xlEdgeBottom = 9, - xlEdgeLeft = 7, - xlEdgeRight = 10, - xlEdgeTop = 8 -} XlBordersIndex; - -enum { - CELL_WAVEFILE = 1, - CELL_LABEL, - CELL_SPEAKER, - CELL_LISTENER, - CELL_STRINGID, - CELL_ENGLISH, - CELL_LOCALIZED, - CELL_CONTEXT, - CELL_COMMENT, - CELL_MAXLEN, - CELL_STRLEN, - CELL_LENCHECK, - CELL_REVISION, - CELL_LAST -}; - -#define ROW_COUNT 1 -#define COLUMN_COUNT 2 -#define ROW_LANGUAGE 1 -#define COLUMN_LANGUAGE 1 - - - -int OpenExcel ( void ); -void CloseExcel ( void ); -int NewWorkBook ( const char *path ); -int SaveWorkBook ( const char *filename, int protect = FALSE ); -int OpenWorkBook ( const char *filename ); -void CloseWorkBook ( void ); -int PutCell ( int row, int column, const OLECHAR *string, int val ); -int PutSeparator ( int row ); -int PutSection ( int row, const OLECHAR *title ); -void SelectActiveSheet ( void ); -int GetInt ( int row, int cell ); -int GetString ( int row, int cell, OLECHAR *buffer ); - - - -#endif // XLSTUFF_H \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/bin.cpp b/Generals/Code/Tools/Babylon/bin.cpp deleted file mode 100644 index b09cb47a49..0000000000 --- a/Generals/Code/Tools/Babylon/bin.cpp +++ /dev/null @@ -1,404 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Bin.cpp -// - -#include "StdAfx.h" -#include "bin.h" -#include "assert.h" -#include "list.h" - -Bin::Bin ( int size ) -{ - assert ( size > 0 ); - num_buckets = size; - sh_item = NULL; - - bucket = new List[size]; - -} - -Bin::~Bin ( ) -{ - Clear (); - - delete [] bucket; - -} - - - -void Bin::Clear ( void ) -{ - int count = num_buckets; - sh_item = NULL; - while ( count-- ) - { - List *head = &bucket[count]; - BinItem *item; - - while ( ( item = (BinItem *) head->Next ())) - { - Remove ( item ); - } - } - -} - -void* Bin::Get ( OLECHAR *text1, OLECHAR *text2 ) -{ - BinItem *item; - - if ( ( item = GetBinItem ( text1, text2 )) ) - { - return item->Item(); - } - - return NULL; -} - -void* Bin::GetNext ( void ) -{ - BinItem *item; - - if ( ( item = GetNextBinItem ( )) ) - { - return item->Item(); - } - - return NULL; -} - -void Bin::Add ( void *data, OLECHAR *text1, OLECHAR *text2 ) -{ - BinItem *item; - List *list; - int hash; - - sh_item = NULL; - - hash = calc_hash ( text1 ); - item = new BinItem ( data, hash, text1, text2 ); - - list = &bucket[hash%num_buckets]; - - list->AddToTail ( (ListNode *) item ); - -} - -BinItem* Bin::GetBinItem ( OLECHAR *text1, OLECHAR *text2) -{ - - sh_size1 = sh_size2 = 0; - sh_text1 = text1; - sh_text2 = text2; - - sh_hash = calc_hash ( text1 ); - - if ( sh_text1 ) - { - sh_size1 = wcslen ( sh_text1 ); - } - - if ( sh_text2 ) - { - sh_size2 = wcslen ( sh_text2 ); - } - - sh_item = (BinItem *) &bucket[sh_hash%num_buckets]; - - - return GetNextBinItem (); -} - -BinItem* Bin::GetNextBinItem ( void ) -{ - if ( sh_item ) - { - sh_item = (BinItem *) sh_item->Next (); - } - - while ( sh_item ) - { - if ( sh_item->Same ( sh_hash, sh_text1, sh_size1, sh_text2, sh_size2 )) - { - break; - } - sh_item = (BinItem *) sh_item->Next (); - } - - return sh_item; -} - -BinItem* Bin::GetBinItem ( void *item ) -{ - BinItem *bitem = NULL; - int i; - - - for ( i=0; i< num_buckets; i++) - { - - if ( ( bitem = (BinItem *) bucket[i].Find ( item ))) - { - break; - } - - } - - return bitem; - -} - -void Bin::Remove ( void *item ) -{ - BinItem *bitem; - - if ( ( bitem = GetBinItem ( item ) )) - { - Remove ( bitem ); - } - -} - -void Bin::Remove ( OLECHAR *text1, OLECHAR *text2 ) -{ - BinItem *bitem; - - if ( ( bitem = GetBinItem ( text1, text2 ) )) - { - Remove ( bitem ); - } - -} - -void Bin::Remove ( BinItem *item ) -{ - sh_item = NULL; - item->Remove (); - delete item ; - -} - - -BinItem::BinItem ( void *data, int new_hash, OLECHAR *new_text1, OLECHAR *new_text2 ) -{ - SetItem ( data ); - hash = new_hash; - - if ( (text1 = new_text1) ) - { - text1size = wcslen ( text1 ); - } - else - { - text1size = 0; - } - - if ( (text2 = new_text2) ) - { - text2size = wcslen ( text2 ); - } - else - { - text2size = 0; - } -} - -int BinItem::Same ( int chash, OLECHAR *ctext1, int size1, OLECHAR *ctext2, int size2 ) -{ - if ( hash != chash || text1size != size1 || text2size != size2 ) - { - return FALSE; - } - - if ( wcsicmp ( text1, ctext1 )) - { - return FALSE; - } - - if ( text2 && ctext2 && wcsicmp ( text2, ctext2 )) - { - return FALSE; - } - - return TRUE; - - -} -int Bin::calc_hash ( OLECHAR *text ) -{ - int hash = 0; - - while ( *text ) - { - hash += *text++; - } - - return hash; - -} - -// Bin ID code - -BinID::BinID ( int size ) -{ - assert ( size > 0 ); - num_buckets = size; - - bucket = new List[size]; - -} - -BinID::~BinID ( ) -{ - Clear (); - - delete [] bucket; - -} - - - -void BinID::Clear ( void ) -{ - int count = num_buckets; - - while ( count-- ) - { - List *head = &bucket[count]; - BinIDItem *item; - - while ( ( item = (BinIDItem *) head->Next ())) - { - Remove ( item ); - } - } - -} - -void* BinID::Get ( int id) -{ - BinIDItem *item; - - if ( ( item = GetBinIDItem ( id )) ) - { - return item->Item(); - } - - return NULL; -} - -void BinID::Add ( void *data, int id ) -{ - BinIDItem *item; - List *list; - - - item = new BinIDItem ( data, id ); - - list = &bucket[id%num_buckets]; - - list->AddToTail ( (ListNode *) item ); - -} - -BinIDItem* BinID::GetBinIDItem ( int id ) -{ - BinIDItem *item; - - - item = (BinIDItem *) bucket[id%num_buckets].Next(); - - while ( item ) - { - if ( item->Same ( id )) - { - break; - } - item = (BinIDItem *) item->Next (); - } - - return item ; -} - - -BinIDItem* BinID::GetBinIDItem ( void *item ) -{ - BinIDItem *bitem = NULL; - int i; - - - for ( i=0; i< num_buckets; i++) - { - - if ( ( bitem = (BinIDItem *) bucket[i].Find ( item ))) - { - break; - } - - } - - return bitem; - -} - -void BinID::Remove ( void *item ) -{ - BinIDItem *bitem; - - if ( ( bitem = GetBinIDItem ( item ) )) - { - Remove ( bitem ); - } - -} - -void BinID::Remove ( int id ) -{ - BinIDItem *bitem; - - if ( ( bitem = GetBinIDItem ( id ) )) - { - Remove ( bitem ); - } - -} - -void BinID::Remove ( BinIDItem *item ) -{ - item->Remove (); - delete item ; - -} - - -BinIDItem::BinIDItem ( void *data, int new_id ) -{ - SetItem ( data ); - id = new_id; - -} - -int BinIDItem::Same ( int compare_id ) -{ - return id == compare_id; -} - diff --git a/Generals/Code/Tools/Babylon/bin.h b/Generals/Code/Tools/Babylon/bin.h deleted file mode 100644 index c5b01278f3..0000000000 --- a/Generals/Code/Tools/Babylon/bin.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Bin.h -// - - -#ifndef __BIN_H -#define __BIN_H - -#include "list.h" -#include "olestring.h" - -class BinItem: public ListNode -{ - int hash; - OLECHAR *text1; - int text1size; - OLECHAR *text2; - int text2size; - - public: - BinItem ( void *data, int hash, OLECHAR *text1, OLECHAR *text2 ); - int Same ( int chash, OLECHAR *ctext1, int size1, OLECHAR *ctext2, int size2 ); - -}; - -class Bin -{ - List *bucket; - int num_buckets; - BinItem *sh_item; - int sh_size1,sh_size2; - int sh_hash; - OLECHAR *sh_text1, *sh_text2; - - int calc_hash ( OLECHAR *text ); - - public: - - Bin ( int size = 256 ); - ~Bin (); - - void Clear ( void ); - void* Get ( OLECHAR *text1, OLECHAR *text2 = NULL ); - void* GetNext ( void ); - void Add ( void *item, OLECHAR *text1, OLECHAR *text2 = NULL ); - BinItem* GetBinItem ( OLECHAR *text1, OLECHAR *text2 = NULL ); - BinItem* GetBinItem ( void *item ); - BinItem* GetNextBinItem ( void ); - void Remove ( void *item ); - void Remove ( OLECHAR *text1, OLECHAR *text2 = NULL ); - void Remove ( BinItem *item ); - - -}; - - -class BinIDItem: public ListNode -{ - int id; - - public: - BinIDItem ( void *data, int id ); - int Same ( int id ); - -}; - -class BinID -{ - List *bucket; - int num_buckets; - - public: - - BinID ( int size = 256 ); - ~BinID (); - - void Clear ( void ); - void* Get ( int id ); - void Add ( void *item, int id ); - BinIDItem* GetBinIDItem ( int id ); - BinIDItem* GetBinIDItem ( void *item ); - void Remove ( void *item ); - void Remove ( int id ); - void Remove ( BinIDItem *item ); - - -}; - - -#endif // __BIN_H \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/excel8.cpp b/Generals/Code/Tools/Babylon/excel8.cpp deleted file mode 100644 index 8b08a7e47b..0000000000 --- a/Generals/Code/Tools/Babylon/excel8.cpp +++ /dev/null @@ -1,5455 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Machine generated IDispatch wrapper class(es) created with ClassWizard - -#include "StdAfx.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - - - -///////////////////////////////////////////////////////////////////////////// -// Workbooks properties - -///////////////////////////////////////////////////////////////////////////// -// Workbooks operations - -LPDISPATCH Workbooks::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long Workbooks::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Workbooks::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Workbooks::Add(const VARIANT& Template) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xb5, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Template); - return result; -} - -void Workbooks::Close() -{ - InvokeHelper(0x115, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -long Workbooks::GetCount() -{ - long result; - InvokeHelper(0x76, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Workbooks::GetItem(const VARIANT& Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &Index); - return result; -} - -LPUNKNOWN Workbooks::Get_NewEnum() -{ - LPUNKNOWN result; - InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); - return result; -} - -LPDISPATCH Workbooks::Open(LPCTSTR Filename, const VARIANT& UpdateLinks, const VARIANT& ReadOnly, const VARIANT& Format, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& IgnoreReadOnlyRecommended, const VARIANT& Origin, - const VARIANT& Delimiter, const VARIANT& Editable, const VARIANT& Notify, const VARIANT& Converter, const VARIANT& AddToMru) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x2aa, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - Filename, &UpdateLinks, &ReadOnly, &Format, &Password, &WriteResPassword, &IgnoreReadOnlyRecommended, &Origin, &Delimiter, &Editable, &Notify, &Converter, &AddToMru); - return result; -} - -void Workbooks::OpenText(LPCTSTR Filename, const VARIANT& Origin, const VARIANT& StartRow, const VARIANT& DataType, long TextQualifier, const VARIANT& ConsecutiveDelimiter, const VARIANT& Tab, const VARIANT& Semicolon, const VARIANT& Comma, - const VARIANT& Space, const VARIANT& Other, const VARIANT& OtherChar, const VARIANT& FieldInfo, const VARIANT& TextVisualLayout) -{ - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x2ab, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Filename, &Origin, &StartRow, &DataType, TextQualifier, &ConsecutiveDelimiter, &Tab, &Semicolon, &Comma, &Space, &Other, &OtherChar, &FieldInfo, &TextVisualLayout); -} - -LPDISPATCH Workbooks::Get_Default(const VARIANT& Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &Index); - return result; -} - - -///////////////////////////////////////////////////////////////////////////// -// _Application properties - -///////////////////////////////////////////////////////////////////////////// -// _Application operations - -LPDISPATCH _Application::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Application::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetActiveCell() -{ - LPDISPATCH result; - InvokeHelper(0x131, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetActiveChart() -{ - LPDISPATCH result; - InvokeHelper(0xb7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -CString _Application::GetActivePrinter() -{ - CString result; - InvokeHelper(0x132, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetActivePrinter(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x132, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -LPDISPATCH _Application::GetActiveSheet() -{ - LPDISPATCH result; - InvokeHelper(0x133, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetActiveWindow() -{ - LPDISPATCH result; - InvokeHelper(0x2f7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetActiveWorkbook() -{ - LPDISPATCH result; - InvokeHelper(0x134, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetAddIns() -{ - LPDISPATCH result; - InvokeHelper(0x225, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetAssistant() -{ - LPDISPATCH result; - InvokeHelper(0x59e, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Application::Calculate() -{ - InvokeHelper(0x117, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH _Application::GetCells() -{ - LPDISPATCH result; - InvokeHelper(0xee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetCharts() -{ - LPDISPATCH result; - InvokeHelper(0x79, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetColumns() -{ - LPDISPATCH result; - InvokeHelper(0xf1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetCommandBars() -{ - LPDISPATCH result; - InvokeHelper(0x59f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Application::GetDDEAppReturnCode() -{ - long result; - InvokeHelper(0x14c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::DDEExecute(long Channel, LPCTSTR String) -{ - static BYTE parms[] = - VTS_I4 VTS_BSTR; - InvokeHelper(0x14d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Channel, String); -} - -long _Application::DDEInitiate(LPCTSTR App, LPCTSTR Topic) -{ - long result; - static BYTE parms[] = - VTS_BSTR VTS_BSTR; - InvokeHelper(0x14e, DISPATCH_METHOD, VT_I4, (void*)&result, parms, - App, Topic); - return result; -} - -void _Application::DDEPoke(long Channel, const VARIANT& Item, const VARIANT& Data) -{ - static BYTE parms[] = - VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x14f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Channel, &Item, &Data); -} - -VARIANT _Application::DDERequest(long Channel, LPCTSTR Item) -{ - VARIANT result; - static BYTE parms[] = - VTS_I4 VTS_BSTR; - InvokeHelper(0x150, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - Channel, Item); - return result; -} - -void _Application::DDETerminate(long Channel) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x151, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Channel); -} - -VARIANT _Application::Evaluate(const VARIANT& Name) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x1, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Name); - return result; -} - -VARIANT _Application::_Evaluate(const VARIANT& Name) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xfffffffb, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Name); - return result; -} - -VARIANT _Application::ExecuteExcel4Macro(LPCTSTR String) -{ - VARIANT result; - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x15e, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - String); - return result; -} - -LPDISPATCH _Application::Intersect(LPDISPATCH Arg1, LPDISPATCH Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, const VARIANT& Arg10, - const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, const VARIANT& Arg20, - const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, const VARIANT& Arg30) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_DISPATCH VTS_DISPATCH VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x2fe, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - Arg1, Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30); - return result; -} - -LPDISPATCH _Application::GetNames() -{ - LPDISPATCH result; - InvokeHelper(0x1ba, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetRange(const VARIANT& Cell1, const VARIANT& Cell2) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xc5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &Cell1, &Cell2); - return result; -} - -LPDISPATCH _Application::GetRows() -{ - LPDISPATCH result; - InvokeHelper(0x102, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT _Application::Run(const VARIANT& Macro, const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, - const VARIANT& Arg10, const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, - const VARIANT& Arg20, const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, - const VARIANT& Arg30) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x103, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Macro, &Arg1, &Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30); - return result; -} - -VARIANT _Application::_Run2(const VARIANT& Macro, const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, - const VARIANT& Arg10, const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, - const VARIANT& Arg20, const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, - const VARIANT& Arg30) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x326, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Macro, &Arg1, &Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30); - return result; -} - -LPDISPATCH _Application::GetSelection() -{ - LPDISPATCH result; - InvokeHelper(0x93, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Application::SendKeys(const VARIANT& Keys, const VARIANT& Wait) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x17f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Keys, &Wait); -} - -LPDISPATCH _Application::GetSheets() -{ - LPDISPATCH result; - InvokeHelper(0x1e5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetThisWorkbook() -{ - LPDISPATCH result; - InvokeHelper(0x30a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::Union(LPDISPATCH Arg1, LPDISPATCH Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, const VARIANT& Arg10, const VARIANT& Arg11, - const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, const VARIANT& Arg20, const VARIANT& Arg21, - const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, const VARIANT& Arg30) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_DISPATCH VTS_DISPATCH VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x30b, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - Arg1, Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30); - return result; -} - -LPDISPATCH _Application::GetWindows() -{ - LPDISPATCH result; - InvokeHelper(0x1ae, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetWorkbooks() -{ - LPDISPATCH result; - InvokeHelper(0x23c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetWorksheetFunction() -{ - LPDISPATCH result; - InvokeHelper(0x5a0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetWorksheets() -{ - LPDISPATCH result; - InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetExcel4IntlMacroSheets() -{ - LPDISPATCH result; - InvokeHelper(0x245, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetExcel4MacroSheets() -{ - LPDISPATCH result; - InvokeHelper(0x243, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Application::ActivateMicrosoftApp(long Index) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x447, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Index); -} - -void _Application::AddChartAutoFormat(const VARIANT& Chart, LPCTSTR Name, const VARIANT& Description) -{ - static BYTE parms[] = - VTS_VARIANT VTS_BSTR VTS_VARIANT; - InvokeHelper(0xd8, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Chart, Name, &Description); -} - -void _Application::AddCustomList(const VARIANT& ListArray, const VARIANT& ByRow) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x30c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &ListArray, &ByRow); -} - -BOOL _Application::GetAlertBeforeOverwriting() -{ - BOOL result; - InvokeHelper(0x3a2, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetAlertBeforeOverwriting(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x3a2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -CString _Application::GetAltStartupPath() -{ - CString result; - InvokeHelper(0x139, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetAltStartupPath(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x139, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -BOOL _Application::GetAskToUpdateLinks() -{ - BOOL result; - InvokeHelper(0x3e0, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetAskToUpdateLinks(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x3e0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetEnableAnimations() -{ - BOOL result; - InvokeHelper(0x49c, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetEnableAnimations(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x49c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -LPDISPATCH _Application::GetAutoCorrect() -{ - LPDISPATCH result; - InvokeHelper(0x479, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Application::GetBuild() -{ - long result; - InvokeHelper(0x13a, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetCalculateBeforeSave() -{ - BOOL result; - InvokeHelper(0x13b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetCalculateBeforeSave(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x13b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetCalculation() -{ - long result; - InvokeHelper(0x13c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetCalculation(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x13c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -VARIANT _Application::GetCaller(const VARIANT& Index) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x13d, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index); - return result; -} - -BOOL _Application::GetCanPlaySounds() -{ - BOOL result; - InvokeHelper(0x13e, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetCanRecordSounds() -{ - BOOL result; - InvokeHelper(0x13f, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -CString _Application::GetCaption() -{ - CString result; - InvokeHelper(0x8b, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetCaption(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x8b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -BOOL _Application::GetCellDragAndDrop() -{ - BOOL result; - InvokeHelper(0x140, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetCellDragAndDrop(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x140, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -double _Application::CentimetersToPoints(double Centimeters) -{ - double result; - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x43e, DISPATCH_METHOD, VT_R8, (void*)&result, parms, - Centimeters); - return result; -} - -BOOL _Application::CheckSpelling(LPCTSTR Word, const VARIANT& CustomDictionary, const VARIANT& IgnoreUppercase) -{ - BOOL result; - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1f9, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, - Word, &CustomDictionary, &IgnoreUppercase); - return result; -} - -VARIANT _Application::GetClipboardFormats(const VARIANT& Index) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x141, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index); - return result; -} - -BOOL _Application::GetDisplayClipboardWindow() -{ - BOOL result; - InvokeHelper(0x142, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayClipboardWindow(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x142, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetCommandUnderlines() -{ - long result; - InvokeHelper(0x143, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetCommandUnderlines(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x143, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Application::GetConstrainNumeric() -{ - BOOL result; - InvokeHelper(0x144, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetConstrainNumeric(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x144, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -VARIANT _Application::ConvertFormula(const VARIANT& Formula, long FromReferenceStyle, const VARIANT& ToReferenceStyle, const VARIANT& ToAbsolute, const VARIANT& RelativeTo) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x145, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Formula, FromReferenceStyle, &ToReferenceStyle, &ToAbsolute, &RelativeTo); - return result; -} - -BOOL _Application::GetCopyObjectsWithCells() -{ - BOOL result; - InvokeHelper(0x3df, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetCopyObjectsWithCells(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x3df, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetCursor() -{ - long result; - InvokeHelper(0x489, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetCursor(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x489, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetCustomListCount() -{ - long result; - InvokeHelper(0x313, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -long _Application::GetCutCopyMode() -{ - long result; - InvokeHelper(0x14a, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetCutCopyMode(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x14a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetDataEntryMode() -{ - long result; - InvokeHelper(0x14b, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetDataEntryMode(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x14b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -CString _Application::Get_Default() -{ - CString result; - InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -CString _Application::GetDefaultFilePath() -{ - CString result; - InvokeHelper(0x40e, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetDefaultFilePath(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x40e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -void _Application::DeleteChartAutoFormat(LPCTSTR Name) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0xd9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Name); -} - -void _Application::DeleteCustomList(long ListNum) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x30f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - ListNum); -} - -LPDISPATCH _Application::GetDialogs() -{ - LPDISPATCH result; - InvokeHelper(0x2f9, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetDisplayAlerts() -{ - BOOL result; - InvokeHelper(0x157, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayAlerts(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x157, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetDisplayFormulaBar() -{ - BOOL result; - InvokeHelper(0x158, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayFormulaBar(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x158, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetDisplayFullScreen() -{ - BOOL result; - InvokeHelper(0x425, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayFullScreen(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x425, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetDisplayNoteIndicator() -{ - BOOL result; - InvokeHelper(0x159, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayNoteIndicator(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x159, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetDisplayCommentIndicator() -{ - long result; - InvokeHelper(0x4ac, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayCommentIndicator(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x4ac, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Application::GetDisplayExcel4Menus() -{ - BOOL result; - InvokeHelper(0x39f, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayExcel4Menus(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x39f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetDisplayRecentFiles() -{ - BOOL result; - InvokeHelper(0x39e, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayRecentFiles(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x39e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetDisplayScrollBars() -{ - BOOL result; - InvokeHelper(0x15a, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayScrollBars(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x15a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetDisplayStatusBar() -{ - BOOL result; - InvokeHelper(0x15b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetDisplayStatusBar(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x15b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Application::DoubleClick() -{ - InvokeHelper(0x15d, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL _Application::GetEditDirectlyInCell() -{ - BOOL result; - InvokeHelper(0x3a1, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetEditDirectlyInCell(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x3a1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetEnableAutoComplete() -{ - BOOL result; - InvokeHelper(0x49b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetEnableAutoComplete(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x49b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetEnableCancelKey() -{ - long result; - InvokeHelper(0x448, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetEnableCancelKey(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x448, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Application::GetEnableSound() -{ - BOOL result; - InvokeHelper(0x4ad, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetEnableSound(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4ad, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -VARIANT _Application::GetFileConverters(const VARIANT& Index1, const VARIANT& Index2) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x3a3, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index1, &Index2); - return result; -} - -LPDISPATCH _Application::GetFileSearch() -{ - LPDISPATCH result; - InvokeHelper(0x4b0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetFileFind() -{ - LPDISPATCH result; - InvokeHelper(0x4b1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Application::FindFile() -{ - InvokeHelper(0x42c, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL _Application::GetFixedDecimal() -{ - BOOL result; - InvokeHelper(0x15f, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetFixedDecimal(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x15f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetFixedDecimalPlaces() -{ - long result; - InvokeHelper(0x160, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetFixedDecimalPlaces(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x160, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -VARIANT _Application::GetCustomListContents(long ListNum) -{ - VARIANT result; - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x312, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - ListNum); - return result; -} - -long _Application::GetCustomListNum(const VARIANT& ListArray) -{ - long result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x311, DISPATCH_METHOD, VT_I4, (void*)&result, parms, - &ListArray); - return result; -} - -VARIANT _Application::GetOpenFilename(const VARIANT& FileFilter, const VARIANT& FilterIndex, const VARIANT& Title, const VARIANT& ButtonText, const VARIANT& MultiSelect) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x433, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &FileFilter, &FilterIndex, &Title, &ButtonText, &MultiSelect); - return result; -} - -VARIANT _Application::GetSaveAsFilename(const VARIANT& InitialFilename, const VARIANT& FileFilter, const VARIANT& FilterIndex, const VARIANT& Title, const VARIANT& ButtonText) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x434, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &InitialFilename, &FileFilter, &FilterIndex, &Title, &ButtonText); - return result; -} - -void _Application::Goto(const VARIANT& Reference, const VARIANT& Scroll) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1db, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Reference, &Scroll); -} - -double _Application::GetHeight() -{ - double result; - InvokeHelper(0x7b, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Application::SetHeight(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x7b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -void _Application::Help(const VARIANT& HelpFile, const VARIANT& HelpContextID) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x162, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &HelpFile, &HelpContextID); -} - -BOOL _Application::GetIgnoreRemoteRequests() -{ - BOOL result; - InvokeHelper(0x164, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetIgnoreRemoteRequests(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x164, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -double _Application::InchesToPoints(double Inches) -{ - double result; - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x43f, DISPATCH_METHOD, VT_R8, (void*)&result, parms, - Inches); - return result; -} - -VARIANT _Application::InputBox(LPCTSTR Prompt, const VARIANT& Title, const VARIANT& Default, const VARIANT& Left, const VARIANT& Top, const VARIANT& HelpFile, const VARIANT& HelpContextID, const VARIANT& Type) -{ - VARIANT result; - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x165, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - Prompt, &Title, &Default, &Left, &Top, &HelpFile, &HelpContextID, &Type); - return result; -} - -BOOL _Application::GetInteractive() -{ - BOOL result; - InvokeHelper(0x169, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetInteractive(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x169, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -VARIANT _Application::GetInternational(const VARIANT& Index) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x16a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index); - return result; -} - -BOOL _Application::GetIteration() -{ - BOOL result; - InvokeHelper(0x16b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetIteration(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x16b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -double _Application::GetLeft() -{ - double result; - InvokeHelper(0x7f, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Application::SetLeft(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x7f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -CString _Application::GetLibraryPath() -{ - CString result; - InvokeHelper(0x16e, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::MacroOptions(const VARIANT& Macro, const VARIANT& Description, const VARIANT& HasMenu, const VARIANT& MenuText, const VARIANT& HasShortcutKey, const VARIANT& ShortcutKey, const VARIANT& Category, const VARIANT& StatusBar, - const VARIANT& HelpContextID, const VARIANT& HelpFile) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x46f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Macro, &Description, &HasMenu, &MenuText, &HasShortcutKey, &ShortcutKey, &Category, &StatusBar, &HelpContextID, &HelpFile); -} - -void _Application::MailLogoff() -{ - InvokeHelper(0x3b1, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Application::MailLogon(const VARIANT& Name, const VARIANT& Password, const VARIANT& DownloadNewMail) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x3af, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Name, &Password, &DownloadNewMail); -} - -VARIANT _Application::GetMailSession() -{ - VARIANT result; - InvokeHelper(0x3ae, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -long _Application::GetMailSystem() -{ - long result; - InvokeHelper(0x3cb, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetMathCoprocessorAvailable() -{ - BOOL result; - InvokeHelper(0x16f, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -double _Application::GetMaxChange() -{ - double result; - InvokeHelper(0x170, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Application::SetMaxChange(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x170, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -long _Application::GetMaxIterations() -{ - long result; - InvokeHelper(0x171, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetMaxIterations(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x171, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetMemoryFree() -{ - long result; - InvokeHelper(0x172, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -long _Application::GetMemoryTotal() -{ - long result; - InvokeHelper(0x173, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -long _Application::GetMemoryUsed() -{ - long result; - InvokeHelper(0x174, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetMouseAvailable() -{ - BOOL result; - InvokeHelper(0x175, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetMoveAfterReturn() -{ - BOOL result; - InvokeHelper(0x176, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetMoveAfterReturn(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x176, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Application::GetMoveAfterReturnDirection() -{ - long result; - InvokeHelper(0x478, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetMoveAfterReturnDirection(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x478, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -LPDISPATCH _Application::GetRecentFiles() -{ - LPDISPATCH result; - InvokeHelper(0x4b2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -CString _Application::GetName() -{ - CString result; - InvokeHelper(0x6e, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::NextLetter() -{ - LPDISPATCH result; - InvokeHelper(0x3cc, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -CString _Application::GetNetworkTemplatesPath() -{ - CString result; - InvokeHelper(0x184, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetODBCErrors() -{ - LPDISPATCH result; - InvokeHelper(0x4b3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Application::GetODBCTimeout() -{ - long result; - InvokeHelper(0x4b4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetODBCTimeout(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x4b4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -void _Application::OnKey(LPCTSTR Key, const VARIANT& Procedure) -{ - static BYTE parms[] = - VTS_BSTR VTS_VARIANT; - InvokeHelper(0x272, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Key, &Procedure); -} - -void _Application::OnRepeat(LPCTSTR Text, LPCTSTR Procedure) -{ - static BYTE parms[] = - VTS_BSTR VTS_BSTR; - InvokeHelper(0x301, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Text, Procedure); -} - -void _Application::OnTime(const VARIANT& EarliestTime, LPCTSTR Procedure, const VARIANT& LatestTime, const VARIANT& Schedule) -{ - static BYTE parms[] = - VTS_VARIANT VTS_BSTR VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x270, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &EarliestTime, Procedure, &LatestTime, &Schedule); -} - -void _Application::OnUndo(LPCTSTR Text, LPCTSTR Procedure) -{ - static BYTE parms[] = - VTS_BSTR VTS_BSTR; - InvokeHelper(0x302, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Text, Procedure); -} - -CString _Application::GetOnWindow() -{ - CString result; - InvokeHelper(0x26f, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetOnWindow(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x26f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -CString _Application::GetOperatingSystem() -{ - CString result; - InvokeHelper(0x177, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -CString _Application::GetOrganizationName() -{ - CString result; - InvokeHelper(0x178, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -CString _Application::GetPath() -{ - CString result; - InvokeHelper(0x123, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -CString _Application::GetPathSeparator() -{ - CString result; - InvokeHelper(0x179, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -VARIANT _Application::GetPreviousSelections(const VARIANT& Index) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x17a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index); - return result; -} - -BOOL _Application::GetPivotTableSelection() -{ - BOOL result; - InvokeHelper(0x4b5, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetPivotTableSelection(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4b5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetPromptForSummaryInfo() -{ - BOOL result; - InvokeHelper(0x426, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetPromptForSummaryInfo(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x426, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Application::Quit() -{ - InvokeHelper(0x12e, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Application::RecordMacro(const VARIANT& BasicCode, const VARIANT& XlmCode) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x305, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &BasicCode, &XlmCode); -} - -BOOL _Application::GetRecordRelative() -{ - BOOL result; - InvokeHelper(0x17b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -long _Application::GetReferenceStyle() -{ - long result; - InvokeHelper(0x17c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetReferenceStyle(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x17c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -VARIANT _Application::GetRegisteredFunctions(const VARIANT& Index1, const VARIANT& Index2) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x307, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index1, &Index2); - return result; -} - -BOOL _Application::RegisterXLL(LPCTSTR Filename) -{ - BOOL result; - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x1e, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, - Filename); - return result; -} - -void _Application::Repeat() -{ - InvokeHelper(0x12d, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL _Application::GetRollZoom() -{ - BOOL result; - InvokeHelper(0x4b6, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetRollZoom(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4b6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Application::SaveWorkspace(const VARIANT& Filename) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xd4, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Filename); -} - -BOOL _Application::GetScreenUpdating() -{ - BOOL result; - InvokeHelper(0x17e, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetScreenUpdating(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x17e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Application::SetDefaultChart(const VARIANT& FormatName, const VARIANT& Gallery) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xdb, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &FormatName, &Gallery); -} - -long _Application::GetSheetsInNewWorkbook() -{ - long result; - InvokeHelper(0x3e1, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetSheetsInNewWorkbook(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x3e1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Application::GetShowChartTipNames() -{ - BOOL result; - InvokeHelper(0x4b7, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetShowChartTipNames(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4b7, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Application::GetShowChartTipValues() -{ - BOOL result; - InvokeHelper(0x4b8, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetShowChartTipValues(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4b8, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -CString _Application::GetStandardFont() -{ - CString result; - InvokeHelper(0x39c, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetStandardFont(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x39c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -double _Application::GetStandardFontSize() -{ - double result; - InvokeHelper(0x39d, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Application::SetStandardFontSize(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x39d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -CString _Application::GetStartupPath() -{ - CString result; - InvokeHelper(0x181, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -VARIANT _Application::GetStatusBar() -{ - VARIANT result; - InvokeHelper(0x182, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void _Application::SetStatusBar(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x182, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -CString _Application::GetTemplatesPath() -{ - CString result; - InvokeHelper(0x17d, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetShowToolTips() -{ - BOOL result; - InvokeHelper(0x183, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetShowToolTips(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x183, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -double _Application::GetTop() -{ - double result; - InvokeHelper(0x7e, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Application::SetTop(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x7e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -long _Application::GetDefaultSaveFormat() -{ - long result; - InvokeHelper(0x4b9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetDefaultSaveFormat(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x4b9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -CString _Application::GetTransitionMenuKey() -{ - CString result; - InvokeHelper(0x136, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetTransitionMenuKey(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x136, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -long _Application::GetTransitionMenuKeyAction() -{ - long result; - InvokeHelper(0x137, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetTransitionMenuKeyAction(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x137, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Application::GetTransitionNavigKeys() -{ - BOOL result; - InvokeHelper(0x138, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetTransitionNavigKeys(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x138, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Application::Undo() -{ - InvokeHelper(0x12f, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -double _Application::GetUsableHeight() -{ - double result; - InvokeHelper(0x185, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -double _Application::GetUsableWidth() -{ - double result; - InvokeHelper(0x186, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetUserControl() -{ - BOOL result; - InvokeHelper(0x4ba, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetUserControl(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4ba, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -CString _Application::GetUserName_() -{ - CString result; - InvokeHelper(0x187, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Application::SetUserName(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x187, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -CString _Application::GetValue() -{ - CString result; - InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Application::GetVbe() -{ - LPDISPATCH result; - InvokeHelper(0x4bb, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -CString _Application::GetVersion() -{ - CString result; - InvokeHelper(0x188, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -BOOL _Application::GetVisible() -{ - BOOL result; - InvokeHelper(0x22e, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetVisible(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x22e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Application::Volatile(const VARIANT& Volatile) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x314, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Volatile); -} - -void _Application::Wait(const VARIANT& Time) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x189, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Time); -} - -double _Application::GetWidth() -{ - double result; - InvokeHelper(0x7a, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Application::SetWidth(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x7a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -BOOL _Application::GetWindowsForPens() -{ - BOOL result; - InvokeHelper(0x18b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -long _Application::GetWindowState() -{ - long result; - InvokeHelper(0x18c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetWindowState(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x18c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetUILanguage() -{ - long result; - InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetUILanguage(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetDefaultSheetDirection() -{ - long result; - InvokeHelper(0xe5, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetDefaultSheetDirection(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0xe5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetCursorMovement() -{ - long result; - InvokeHelper(0xe8, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetCursorMovement(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0xe8, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -long _Application::GetControlCharacters() -{ - long result; - InvokeHelper(0xe9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Application::SetControlCharacters(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0xe9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Application::GetEnableEvents() -{ - BOOL result; - InvokeHelper(0x4bc, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Application::SetEnableEvents(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x4bc, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - - -///////////////////////////////////////////////////////////////////////////// -// _Workbook properties - -///////////////////////////////////////////////////////////////////////////// -// _Workbook operations - -LPDISPATCH _Workbook::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Workbook::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetAcceptLabelsInFormulas() -{ - BOOL result; - InvokeHelper(0x5a1, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetAcceptLabelsInFormulas(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5a1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Workbook::Activate() -{ - InvokeHelper(0x130, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH _Workbook::GetActiveChart() -{ - LPDISPATCH result; - InvokeHelper(0xb7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetActiveSheet() -{ - LPDISPATCH result; - InvokeHelper(0x133, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Workbook::GetAutoUpdateFrequency() -{ - long result; - InvokeHelper(0x5a2, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Workbook::SetAutoUpdateFrequency(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x5a2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Workbook::GetAutoUpdateSaveChanges() -{ - BOOL result; - InvokeHelper(0x5a3, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetAutoUpdateSaveChanges(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5a3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Workbook::GetChangeHistoryDuration() -{ - long result; - InvokeHelper(0x5a4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Workbook::SetChangeHistoryDuration(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x5a4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -LPDISPATCH _Workbook::GetBuiltinDocumentProperties() -{ - LPDISPATCH result; - InvokeHelper(0x498, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::ChangeFileAccess(long Mode, const VARIANT& WritePassword, const VARIANT& Notify) -{ - static BYTE parms[] = - VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x3dd, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Mode, &WritePassword, &Notify); -} - -void _Workbook::ChangeLink(LPCTSTR Name, LPCTSTR NewName, long Type) -{ - static BYTE parms[] = - VTS_BSTR VTS_BSTR VTS_I4; - InvokeHelper(0x322, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Name, NewName, Type); -} - -LPDISPATCH _Workbook::GetCharts() -{ - LPDISPATCH result; - InvokeHelper(0x79, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::Close(const VARIANT& SaveChanges, const VARIANT& Filename, const VARIANT& RouteWorkbook) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x115, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &SaveChanges, &Filename, &RouteWorkbook); -} - -CString _Workbook::GetCodeName() -{ - CString result; - InvokeHelper(0x55d, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -CString _Workbook::Get_CodeName() -{ - CString result; - InvokeHelper(0x80010000, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Workbook::Set_CodeName(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x80010000, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -VARIANT _Workbook::GetColors(const VARIANT& Index) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x11e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &Index); - return result; -} - -void _Workbook::SetColors(const VARIANT& Index, const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x11e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &Index, &newValue); -} - -LPDISPATCH _Workbook::GetCommandBars() -{ - LPDISPATCH result; - InvokeHelper(0x59f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Workbook::GetConflictResolution() -{ - long result; - InvokeHelper(0x497, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Workbook::SetConflictResolution(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x497, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -LPDISPATCH _Workbook::GetContainer() -{ - LPDISPATCH result; - InvokeHelper(0x4a6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetCreateBackup() -{ - BOOL result; - InvokeHelper(0x11f, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetCustomDocumentProperties() -{ - LPDISPATCH result; - InvokeHelper(0x499, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetDate1904() -{ - BOOL result; - InvokeHelper(0x193, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetDate1904(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x193, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Workbook::DeleteNumberFormat(LPCTSTR NumberFormat) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x18d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - NumberFormat); -} - -long _Workbook::GetDisplayDrawingObjects() -{ - long result; - InvokeHelper(0x194, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Workbook::SetDisplayDrawingObjects(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x194, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Workbook::ExclusiveAccess() -{ - BOOL result; - InvokeHelper(0x490, DISPATCH_METHOD, VT_BOOL, (void*)&result, NULL); - return result; -} - -long _Workbook::GetFileFormat() -{ - long result; - InvokeHelper(0x120, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Workbook::ForwardMailer() -{ - InvokeHelper(0x3cd, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -CString _Workbook::GetFullName() -{ - CString result; - InvokeHelper(0x121, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetHasPassword() -{ - BOOL result; - InvokeHelper(0x122, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetHasRoutingSlip() -{ - BOOL result; - InvokeHelper(0x3b6, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetHasRoutingSlip(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x3b6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Workbook::GetIsAddin() -{ - BOOL result; - InvokeHelper(0x5a5, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetIsAddin(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5a5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -VARIANT _Workbook::LinkInfo(LPCTSTR Name, long LinkInfo, const VARIANT& Type, const VARIANT& EditionRef) -{ - VARIANT result; - static BYTE parms[] = - VTS_BSTR VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x327, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - Name, LinkInfo, &Type, &EditionRef); - return result; -} - -VARIANT _Workbook::LinkSources(const VARIANT& Type) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x328, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Type); - return result; -} - -LPDISPATCH _Workbook::GetMailer() -{ - LPDISPATCH result; - InvokeHelper(0x3d3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::MergeWorkbook(const VARIANT& Filename) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x5a6, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Filename); -} - -BOOL _Workbook::GetMultiUserEditing() -{ - BOOL result; - InvokeHelper(0x491, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -CString _Workbook::GetName() -{ - CString result; - InvokeHelper(0x6e, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetNames() -{ - LPDISPATCH result; - InvokeHelper(0x1ba, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::NewWindow() -{ - LPDISPATCH result; - InvokeHelper(0x118, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::OpenLinks(LPCTSTR Name, const VARIANT& ReadOnly, const VARIANT& Type) -{ - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x323, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Name, &ReadOnly, &Type); -} - -CString _Workbook::GetPath() -{ - CString result; - InvokeHelper(0x123, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetPersonalViewListSettings() -{ - BOOL result; - InvokeHelper(0x5a7, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetPersonalViewListSettings(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5a7, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Workbook::GetPersonalViewPrintSettings() -{ - BOOL result; - InvokeHelper(0x5a8, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetPersonalViewPrintSettings(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5a8, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -LPDISPATCH _Workbook::PivotCaches() -{ - LPDISPATCH result; - InvokeHelper(0x5a9, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::Post(const VARIANT& DestName) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x48e, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &DestName); -} - -BOOL _Workbook::GetPrecisionAsDisplayed() -{ - BOOL result; - InvokeHelper(0x195, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetPrecisionAsDisplayed(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x195, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Workbook::PrintOut(const VARIANT& From, const VARIANT& To, const VARIANT& Copies, const VARIANT& Preview, const VARIANT& ActivePrinter, const VARIANT& PrintToFile, const VARIANT& Collate) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x389, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &From, &To, &Copies, &Preview, &ActivePrinter, &PrintToFile, &Collate); -} - -void _Workbook::PrintPreview(const VARIANT& EnableChanges) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x119, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &EnableChanges); -} - -void _Workbook::Protect(const VARIANT& Password, const VARIANT& Structure, const VARIANT& Windows) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x11a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Password, &Structure, &Windows); -} - -void _Workbook::ProtectSharing(const VARIANT& Filename, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup, const VARIANT& SharingPassword) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x5aa, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Filename, &Password, &WriteResPassword, &ReadOnlyRecommended, &CreateBackup, &SharingPassword); -} - -BOOL _Workbook::GetProtectStructure() -{ - BOOL result; - InvokeHelper(0x24c, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetProtectWindows() -{ - BOOL result; - InvokeHelper(0x127, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetReadOnly() -{ - BOOL result; - InvokeHelper(0x128, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetReadOnlyRecommended() -{ - BOOL result; - InvokeHelper(0x129, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::RefreshAll() -{ - InvokeHelper(0x5ac, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Workbook::Reply() -{ - InvokeHelper(0x3d1, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Workbook::ReplyAll() -{ - InvokeHelper(0x3d2, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Workbook::RemoveUser(long Index) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x5ad, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Index); -} - -long _Workbook::GetRevisionNumber() -{ - long result; - InvokeHelper(0x494, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Workbook::Route() -{ - InvokeHelper(0x3b2, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL _Workbook::GetRouted() -{ - BOOL result; - InvokeHelper(0x3b7, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetRoutingSlip() -{ - LPDISPATCH result; - InvokeHelper(0x3b5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::RunAutoMacros(long Which) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x27a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Which); -} - -void _Workbook::Save() -{ - InvokeHelper(0x11b, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Workbook::SaveAs(const VARIANT& Filename, const VARIANT& FileFormat, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup, long AccessMode, const VARIANT& ConflictResolution, - const VARIANT& AddToMru, const VARIANT& TextCodepage, const VARIANT& TextVisualLayout) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x11c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Filename, &FileFormat, &Password, &WriteResPassword, &ReadOnlyRecommended, &CreateBackup, AccessMode, &ConflictResolution, &AddToMru, &TextCodepage, &TextVisualLayout); -} - -void _Workbook::SaveCopyAs(const VARIANT& Filename) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xaf, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Filename); -} - -BOOL _Workbook::GetSaved() -{ - BOOL result; - InvokeHelper(0x12a, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetSaved(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x12a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Workbook::GetSaveLinkValues() -{ - BOOL result; - InvokeHelper(0x196, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetSaveLinkValues(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x196, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Workbook::SendMail(const VARIANT& Recipients, const VARIANT& Subject, const VARIANT& ReturnReceipt) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x3b3, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Recipients, &Subject, &ReturnReceipt); -} - -void _Workbook::SendMailer(const VARIANT& FileFormat, long Priority) -{ - static BYTE parms[] = - VTS_VARIANT VTS_I4; - InvokeHelper(0x3d4, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &FileFormat, Priority); -} - -void _Workbook::SetLinkOnData(LPCTSTR Name, const VARIANT& Procedure) -{ - static BYTE parms[] = - VTS_BSTR VTS_VARIANT; - InvokeHelper(0x329, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Name, &Procedure); -} - -LPDISPATCH _Workbook::GetSheets() -{ - LPDISPATCH result; - InvokeHelper(0x1e5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetShowConflictHistory() -{ - BOOL result; - InvokeHelper(0x493, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetShowConflictHistory(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x493, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -LPDISPATCH _Workbook::GetStyles() -{ - LPDISPATCH result; - InvokeHelper(0x1ed, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::Unprotect(const VARIANT& Password) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x11d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Password); -} - -void _Workbook::UnprotectSharing(const VARIANT& SharingPassword) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x5af, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &SharingPassword); -} - -void _Workbook::UpdateFromFile() -{ - InvokeHelper(0x3e3, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Workbook::UpdateLink(const VARIANT& Name, const VARIANT& Type) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x324, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Name, &Type); -} - -BOOL _Workbook::GetUpdateRemoteReferences() -{ - BOOL result; - InvokeHelper(0x19b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetUpdateRemoteReferences(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x19b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -VARIANT _Workbook::GetUserStatus() -{ - VARIANT result; - InvokeHelper(0x495, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetCustomViews() -{ - LPDISPATCH result; - InvokeHelper(0x5b0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetWindows() -{ - LPDISPATCH result; - InvokeHelper(0x1ae, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetWorksheets() -{ - LPDISPATCH result; - InvokeHelper(0x1ee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetWriteReserved() -{ - BOOL result; - InvokeHelper(0x12b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -CString _Workbook::GetWriteReservedBy() -{ - CString result; - InvokeHelper(0x12c, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetExcel4IntlMacroSheets() -{ - LPDISPATCH result; - InvokeHelper(0x245, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Workbook::GetExcel4MacroSheets() -{ - LPDISPATCH result; - InvokeHelper(0x243, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Workbook::GetTemplateRemoveExtData() -{ - BOOL result; - InvokeHelper(0x5b1, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetTemplateRemoveExtData(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5b1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Workbook::HighlightChangesOptions(const VARIANT& When, const VARIANT& Who, const VARIANT& Where) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x5b2, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &When, &Who, &Where); -} - -BOOL _Workbook::GetHighlightChangesOnScreen() -{ - BOOL result; - InvokeHelper(0x5b5, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetHighlightChangesOnScreen(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5b5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Workbook::GetKeepChangeHistory() -{ - BOOL result; - InvokeHelper(0x5b6, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetKeepChangeHistory(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5b6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Workbook::GetListChangesOnNewSheet() -{ - BOOL result; - InvokeHelper(0x5b7, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Workbook::SetListChangesOnNewSheet(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x5b7, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Workbook::PurgeChangeHistoryNow(long Days, const VARIANT& SharingPassword) -{ - static BYTE parms[] = - VTS_I4 VTS_VARIANT; - InvokeHelper(0x5b8, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Days, &SharingPassword); -} - -void _Workbook::AcceptAllChanges(const VARIANT& When, const VARIANT& Who, const VARIANT& Where) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x5ba, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &When, &Who, &Where); -} - -void _Workbook::RejectAllChanges(const VARIANT& When, const VARIANT& Who, const VARIANT& Where) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x5bb, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &When, &Who, &Where); -} - -void _Workbook::ResetColors() -{ - InvokeHelper(0x5bc, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH _Workbook::GetVBProject() -{ - LPDISPATCH result; - InvokeHelper(0x5bd, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Workbook::FollowHyperlink(LPCTSTR Address, const VARIANT& SubAddress, const VARIANT& NewWindow, const VARIANT& AddHistory, const VARIANT& ExtraInfo, const VARIANT& Method, const VARIANT& HeaderInfo) -{ - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x5be, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Address, &SubAddress, &NewWindow, &AddHistory, &ExtraInfo, &Method, &HeaderInfo); -} - -void _Workbook::AddToFavorites() -{ - InvokeHelper(0x5c4, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL _Workbook::GetIsInplace() -{ - BOOL result; - InvokeHelper(0x6f4, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - - -///////////////////////////////////////////////////////////////////////////// -// _Worksheet properties - -///////////////////////////////////////////////////////////////////////////// -// _Worksheet operations - -LPDISPATCH _Worksheet::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Worksheet::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Worksheet::Activate() -{ - InvokeHelper(0x130, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Worksheet::Copy(const VARIANT& Before, const VARIANT& After) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x227, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Before, &After); -} - -void _Worksheet::Delete() -{ - InvokeHelper(0x75, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -CString _Worksheet::GetCodeName() -{ - CString result; - InvokeHelper(0x55d, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -CString _Worksheet::Get_CodeName() -{ - CString result; - InvokeHelper(0x80010000, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Worksheet::Set_CodeName(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x80010000, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -long _Worksheet::GetIndex() -{ - long result; - InvokeHelper(0x1e6, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Worksheet::Move(const VARIANT& Before, const VARIANT& After) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x27d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Before, &After); -} - -CString _Worksheet::GetName() -{ - CString result; - InvokeHelper(0x6e, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetName(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x6e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -LPDISPATCH _Worksheet::GetNext() -{ - LPDISPATCH result; - InvokeHelper(0x1f6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetPageSetup() -{ - LPDISPATCH result; - InvokeHelper(0x3e6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetPrevious() -{ - LPDISPATCH result; - InvokeHelper(0x1f7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Worksheet::PrintOut(const VARIANT& From, const VARIANT& To, const VARIANT& Copies, const VARIANT& Preview, const VARIANT& ActivePrinter, const VARIANT& PrintToFile, const VARIANT& Collate) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x389, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &From, &To, &Copies, &Preview, &ActivePrinter, &PrintToFile, &Collate); -} - -void _Worksheet::PrintPreview(const VARIANT& EnableChanges) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x119, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &EnableChanges); -} - -void _Worksheet::Protect(const VARIANT& Password, const VARIANT& DrawingObjects, const VARIANT& Contents, const VARIANT& Scenarios, const VARIANT& UserInterfaceOnly) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x11a, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Password, &DrawingObjects, &Contents, &Scenarios, &UserInterfaceOnly); -} - -BOOL _Worksheet::GetProtectContents() -{ - BOOL result; - InvokeHelper(0x124, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Worksheet::GetProtectDrawingObjects() -{ - BOOL result; - InvokeHelper(0x125, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Worksheet::GetProtectionMode() -{ - BOOL result; - InvokeHelper(0x487, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -BOOL _Worksheet::GetProtectScenarios() -{ - BOOL result; - InvokeHelper(0x126, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SaveAs(LPCTSTR Filename, const VARIANT& FileFormat, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup, const VARIANT& AddToMru, const VARIANT& TextCodepage, - const VARIANT& TextVisualLayout) -{ - static BYTE parms[] = - VTS_BSTR VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x11c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Filename, &FileFormat, &Password, &WriteResPassword, &ReadOnlyRecommended, &CreateBackup, &AddToMru, &TextCodepage, &TextVisualLayout); -} - -void _Worksheet::Select(const VARIANT& Replace) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xeb, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Replace); -} - -void _Worksheet::Unprotect(const VARIANT& Password) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x11d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Password); -} - -long _Worksheet::GetVisible() -{ - long result; - InvokeHelper(0x22e, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetVisible(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x22e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -LPDISPATCH _Worksheet::GetShapes() -{ - LPDISPATCH result; - InvokeHelper(0x561, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Worksheet::GetTransitionExpEval() -{ - BOOL result; - InvokeHelper(0x191, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetTransitionExpEval(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x191, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Worksheet::GetAutoFilterMode() -{ - BOOL result; - InvokeHelper(0x318, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetAutoFilterMode(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x318, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -void _Worksheet::SetBackgroundPicture(LPCTSTR Filename) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x4a4, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Filename); -} - -void _Worksheet::Calculate() -{ - InvokeHelper(0x117, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL _Worksheet::GetEnableCalculation() -{ - BOOL result; - InvokeHelper(0x590, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetEnableCalculation(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x590, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -LPDISPATCH _Worksheet::GetCells() -{ - LPDISPATCH result; - InvokeHelper(0xee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::ChartObjects(const VARIANT& Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x424, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Index); - return result; -} - -void _Worksheet::CheckSpelling(const VARIANT& CustomDictionary, const VARIANT& IgnoreUppercase, const VARIANT& AlwaysSuggest, const VARIANT& IgnoreInitialAlefHamza, const VARIANT& IgnoreFinalYaa, const VARIANT& SpellScript) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1f9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &CustomDictionary, &IgnoreUppercase, &AlwaysSuggest, &IgnoreInitialAlefHamza, &IgnoreFinalYaa, &SpellScript); -} - -LPDISPATCH _Worksheet::GetCircularReference() -{ - LPDISPATCH result; - InvokeHelper(0x42d, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Worksheet::ClearArrows() -{ - InvokeHelper(0x3ca, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH _Worksheet::GetColumns() -{ - LPDISPATCH result; - InvokeHelper(0xf1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long _Worksheet::GetConsolidationFunction() -{ - long result; - InvokeHelper(0x315, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -VARIANT _Worksheet::GetConsolidationOptions() -{ - VARIANT result; - InvokeHelper(0x316, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -VARIANT _Worksheet::GetConsolidationSources() -{ - VARIANT result; - InvokeHelper(0x317, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -BOOL _Worksheet::GetEnableAutoFilter() -{ - BOOL result; - InvokeHelper(0x484, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetEnableAutoFilter(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x484, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Worksheet::GetEnableSelection() -{ - long result; - InvokeHelper(0x591, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetEnableSelection(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x591, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -BOOL _Worksheet::GetEnableOutlining() -{ - BOOL result; - InvokeHelper(0x485, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetEnableOutlining(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x485, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -BOOL _Worksheet::GetEnablePivotTable() -{ - BOOL result; - InvokeHelper(0x486, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetEnablePivotTable(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x486, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -VARIANT _Worksheet::Evaluate(const VARIANT& Name) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x1, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Name); - return result; -} - -VARIANT _Worksheet::_Evaluate(const VARIANT& Name) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xfffffffb, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Name); - return result; -} - -BOOL _Worksheet::GetFilterMode() -{ - BOOL result; - InvokeHelper(0x320, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::ResetAllPageBreaks() -{ - InvokeHelper(0x592, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH _Worksheet::GetNames() -{ - LPDISPATCH result; - InvokeHelper(0x1ba, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::OLEObjects(const VARIANT& Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x31f, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Index); - return result; -} - -LPDISPATCH _Worksheet::GetOutline() -{ - LPDISPATCH result; - InvokeHelper(0x66, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Worksheet::Paste(const VARIANT& Destination, const VARIANT& Link) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xd3, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Destination, &Link); -} - -void _Worksheet::PasteSpecial(const VARIANT& Format, const VARIANT& Link, const VARIANT& DisplayAsIcon, const VARIANT& IconFileName, const VARIANT& IconIndex, const VARIANT& IconLabel) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x403, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Format, &Link, &DisplayAsIcon, &IconFileName, &IconIndex, &IconLabel); -} - -LPDISPATCH _Worksheet::PivotTables(const VARIANT& Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x2b2, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Index); - return result; -} - -LPDISPATCH _Worksheet::PivotTableWizard(const VARIANT& SourceType, const VARIANT& SourceData, const VARIANT& TableDestination, const VARIANT& TableName, const VARIANT& RowGrand, const VARIANT& ColumnGrand, const VARIANT& SaveData, - const VARIANT& HasAutoFormat, const VARIANT& AutoPage, const VARIANT& Reserved, const VARIANT& BackgroundQuery, const VARIANT& OptimizeCache, const VARIANT& PageFieldOrder, const VARIANT& PageFieldWrapCount, const VARIANT& ReadData, - const VARIANT& Connection) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x2ac, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &SourceType, &SourceData, &TableDestination, &TableName, &RowGrand, &ColumnGrand, &SaveData, &HasAutoFormat, &AutoPage, &Reserved, &BackgroundQuery, &OptimizeCache, &PageFieldOrder, &PageFieldWrapCount, &ReadData, &Connection); - return result; -} - -LPDISPATCH _Worksheet::GetRange(const VARIANT& Cell1, const VARIANT& Cell2) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xc5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &Cell1, &Cell2); - return result; -} - -LPDISPATCH _Worksheet::GetRows() -{ - LPDISPATCH result; - InvokeHelper(0x102, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::Scenarios(const VARIANT& Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x38c, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Index); - return result; -} - -CString _Worksheet::GetScrollArea() -{ - CString result; - InvokeHelper(0x599, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetScrollArea(LPCTSTR lpszNewValue) -{ - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x599, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - lpszNewValue); -} - -void _Worksheet::ShowAllData() -{ - InvokeHelper(0x31a, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Worksheet::ShowDataForm() -{ - InvokeHelper(0x199, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -double _Worksheet::GetStandardHeight() -{ - double result; - InvokeHelper(0x197, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -double _Worksheet::GetStandardWidth() -{ - double result; - InvokeHelper(0x198, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetStandardWidth(double newValue) -{ - static BYTE parms[] = - VTS_R8; - InvokeHelper(0x198, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - newValue); -} - -BOOL _Worksheet::GetTransitionFormEntry() -{ - BOOL result; - InvokeHelper(0x192, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetTransitionFormEntry(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x192, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -long _Worksheet::GetType() -{ - long result; - InvokeHelper(0x6c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetUsedRange() -{ - LPDISPATCH result; - InvokeHelper(0x19c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetHPageBreaks() -{ - LPDISPATCH result; - InvokeHelper(0x58a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetVPageBreaks() -{ - LPDISPATCH result; - InvokeHelper(0x58b, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetQueryTables() -{ - LPDISPATCH result; - InvokeHelper(0x59a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -BOOL _Worksheet::GetDisplayPageBreaks() -{ - BOOL result; - InvokeHelper(0x59b, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); - return result; -} - -void _Worksheet::SetDisplayPageBreaks(BOOL bNewValue) -{ - static BYTE parms[] = - VTS_BOOL; - InvokeHelper(0x59b, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - bNewValue); -} - -LPDISPATCH _Worksheet::GetComments() -{ - LPDISPATCH result; - InvokeHelper(0x23f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH _Worksheet::GetHyperlinks() -{ - LPDISPATCH result; - InvokeHelper(0x571, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void _Worksheet::ClearCircles() -{ - InvokeHelper(0x59c, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void _Worksheet::CircleInvalid() -{ - InvokeHelper(0x59d, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH _Worksheet::GetAutoFilter() -{ - LPDISPATCH result; - InvokeHelper(0x319, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - - -///////////////////////////////////////////////////////////////////////////// -// Range properties - -///////////////////////////////////////////////////////////////////////////// -// Range operations - -LPDISPATCH Range::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long Range::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void Range::Activate() -{ - InvokeHelper(0x130, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -VARIANT Range::GetAddIndent() -{ - VARIANT result; - InvokeHelper(0x427, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetAddIndent(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x427, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -CString Range::GetAddress(const VARIANT& RowAbsolute, const VARIANT& ColumnAbsolute, long ReferenceStyle, const VARIANT& External, const VARIANT& RelativeTo) -{ - CString result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xec, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms, - &RowAbsolute, &ColumnAbsolute, ReferenceStyle, &External, &RelativeTo); - return result; -} - -CString Range::GetAddressLocal(const VARIANT& RowAbsolute, const VARIANT& ColumnAbsolute, long ReferenceStyle, const VARIANT& External, const VARIANT& RelativeTo) -{ - CString result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1b5, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms, - &RowAbsolute, &ColumnAbsolute, ReferenceStyle, &External, &RelativeTo); - return result; -} - -void Range::AdvancedFilter(long Action, const VARIANT& CriteriaRange, const VARIANT& CopyToRange, const VARIANT& Unique) -{ - static BYTE parms[] = - VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x36c, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Action, &CriteriaRange, &CopyToRange, &Unique); -} - -void Range::ApplyNames(const VARIANT& Names, const VARIANT& IgnoreRelativeAbsolute, const VARIANT& UseRowColumnNames, const VARIANT& OmitColumn, const VARIANT& OmitRow, long Order, const VARIANT& AppendLast) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT; - InvokeHelper(0x1b9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Names, &IgnoreRelativeAbsolute, &UseRowColumnNames, &OmitColumn, &OmitRow, Order, &AppendLast); -} - -void Range::ApplyOutlineStyles() -{ - InvokeHelper(0x1c0, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH Range::GetAreas() -{ - LPDISPATCH result; - InvokeHelper(0x238, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -CString Range::AutoComplete(LPCTSTR String) -{ - CString result; - static BYTE parms[] = - VTS_BSTR; - InvokeHelper(0x4a1, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, - String); - return result; -} - -void Range::AutoFill(LPDISPATCH Destination, long Type) -{ - static BYTE parms[] = - VTS_DISPATCH VTS_I4; - InvokeHelper(0x1c1, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Destination, Type); -} - -void Range::AutoFilter(const VARIANT& Field, const VARIANT& Criteria1, long Operator, const VARIANT& Criteria2, const VARIANT& VisibleDropDown) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x319, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Field, &Criteria1, Operator, &Criteria2, &VisibleDropDown); -} - -void Range::AutoFit() -{ - InvokeHelper(0xed, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::AutoFormat(long Format, const VARIANT& Number, const VARIANT& Font, const VARIANT& Alignment, const VARIANT& Border, const VARIANT& Pattern, const VARIANT& Width) -{ - static BYTE parms[] = - VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x72, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Format, &Number, &Font, &Alignment, &Border, &Pattern, &Width); -} - -void Range::AutoOutline() -{ - InvokeHelper(0x40c, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::BorderAround(const VARIANT& LineStyle, long Weight, long ColorIndex, const VARIANT& Color) -{ - static BYTE parms[] = - VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT; - InvokeHelper(0x42b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &LineStyle, Weight, ColorIndex, &Color); -} - -LPDISPATCH Range::GetBorders() -{ - LPDISPATCH result; - InvokeHelper(0x1b3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void Range::Calculate() -{ - InvokeHelper(0x117, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH Range::GetCells() -{ - LPDISPATCH result; - InvokeHelper(0xee, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetCharacters(const VARIANT& Start, const VARIANT& Length) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x25b, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &Start, &Length); - return result; -} - -void Range::CheckSpelling(const VARIANT& CustomDictionary, const VARIANT& IgnoreUppercase, const VARIANT& AlwaysSuggest, const VARIANT& IgnoreInitialAlefHamza, const VARIANT& IgnoreFinalYaa, const VARIANT& SpellScript) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1f9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &CustomDictionary, &IgnoreUppercase, &AlwaysSuggest, &IgnoreInitialAlefHamza, &IgnoreFinalYaa, &SpellScript); -} - -void Range::Clear() -{ - InvokeHelper(0x6f, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::ClearContents() -{ - InvokeHelper(0x71, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::ClearFormats() -{ - InvokeHelper(0x70, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::ClearNotes() -{ - InvokeHelper(0xef, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::ClearOutline() -{ - InvokeHelper(0x40d, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -long Range::GetColumn() -{ - long result; - InvokeHelper(0xf0, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::ColumnDifferences(const VARIANT& Comparison) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x1fe, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Comparison); - return result; -} - -LPDISPATCH Range::GetColumns() -{ - LPDISPATCH result; - InvokeHelper(0xf1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetColumnWidth() -{ - VARIANT result; - InvokeHelper(0xf2, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetColumnWidth(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xf2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::Consolidate(const VARIANT& Sources, const VARIANT& Function, const VARIANT& TopRow, const VARIANT& LeftColumn, const VARIANT& CreateLinks) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1e2, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Sources, &Function, &TopRow, &LeftColumn, &CreateLinks); -} - -void Range::Copy(const VARIANT& Destination) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x227, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Destination); -} - -long Range::CopyFromRecordset(LPUNKNOWN Data, const VARIANT& MaxRows, const VARIANT& MaxColumns) -{ - long result; - static BYTE parms[] = - VTS_UNKNOWN VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x480, DISPATCH_METHOD, VT_I4, (void*)&result, parms, - Data, &MaxRows, &MaxColumns); - return result; -} - -void Range::CopyPicture(long Appearance, long Format) -{ - static BYTE parms[] = - VTS_I4 VTS_I4; - InvokeHelper(0xd5, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Appearance, Format); -} - -long Range::GetCount() -{ - long result; - InvokeHelper(0x76, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void Range::CreateNames(const VARIANT& Top, const VARIANT& Left, const VARIANT& Bottom, const VARIANT& Right) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1c9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Top, &Left, &Bottom, &Right); -} - -void Range::CreatePublisher(const VARIANT& Edition, long Appearance, const VARIANT& ContainsPICT, const VARIANT& ContainsBIFF, const VARIANT& ContainsRTF, const VARIANT& ContainsVALU) -{ - static BYTE parms[] = - VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1ca, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Edition, Appearance, &ContainsPICT, &ContainsBIFF, &ContainsRTF, &ContainsVALU); -} - -LPDISPATCH Range::GetCurrentArray() -{ - LPDISPATCH result; - InvokeHelper(0x1f5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetCurrentRegion() -{ - LPDISPATCH result; - InvokeHelper(0xf3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void Range::Cut(const VARIANT& Destination) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x235, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Destination); -} - -void Range::DataSeries(const VARIANT& Rowcol, long Type, long Date, const VARIANT& Step, const VARIANT& Stop, const VARIANT& Trend) -{ - static BYTE parms[] = - VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1d0, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Rowcol, Type, Date, &Step, &Stop, &Trend); -} - -VARIANT Range::Get_Default(const VARIANT& RowIndex, const VARIANT& ColumnIndex) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &RowIndex, &ColumnIndex); - return result; -} - -void Range::Set_Default(const VARIANT& RowIndex, const VARIANT& ColumnIndex, const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &RowIndex, &ColumnIndex, &newValue); -} - -void Range::Delete(const VARIANT& Shift) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x75, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Shift); -} - -LPDISPATCH Range::GetDependents() -{ - LPDISPATCH result; - InvokeHelper(0x21f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::DialogBox_() -{ - VARIANT result; - InvokeHelper(0xf5, DISPATCH_METHOD, VT_VARIANT, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetDirectDependents() -{ - LPDISPATCH result; - InvokeHelper(0x221, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetDirectPrecedents() -{ - LPDISPATCH result; - InvokeHelper(0x222, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::EditionOptions(long Type, long Option, const VARIANT& Name, const VARIANT& Reference, long Appearance, long ChartSize, const VARIANT& Format) -{ - VARIANT result; - static BYTE parms[] = - VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT; - InvokeHelper(0x46b, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - Type, Option, &Name, &Reference, Appearance, ChartSize, &Format); - return result; -} - -LPDISPATCH Range::GetEnd(long Direction) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x1f4, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - Direction); - return result; -} - -LPDISPATCH Range::GetEntireColumn() -{ - LPDISPATCH result; - InvokeHelper(0xf6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetEntireRow() -{ - LPDISPATCH result; - InvokeHelper(0xf7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void Range::FillDown() -{ - InvokeHelper(0xf8, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::FillLeft() -{ - InvokeHelper(0xf9, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::FillRight() -{ - InvokeHelper(0xfa, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::FillUp() -{ - InvokeHelper(0xfb, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH Range::Find(const VARIANT& What, const VARIANT& After, const VARIANT& LookIn, const VARIANT& LookAt, const VARIANT& SearchOrder, long SearchDirection, const VARIANT& MatchCase, const VARIANT& MatchByte, - const VARIANT& MatchControlCharacters, const VARIANT& MatchDiacritics, const VARIANT& MatchKashida, const VARIANT& MatchAlefHamza) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x18e, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &What, &After, &LookIn, &LookAt, &SearchOrder, SearchDirection, &MatchCase, &MatchByte, &MatchControlCharacters, &MatchDiacritics, &MatchKashida, &MatchAlefHamza); - return result; -} - -LPDISPATCH Range::FindNext(const VARIANT& After) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x18f, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &After); - return result; -} - -LPDISPATCH Range::FindPrevious(const VARIANT& After) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x190, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &After); - return result; -} - -LPDISPATCH Range::GetFont() -{ - LPDISPATCH result; - InvokeHelper(0x92, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetFormula() -{ - VARIANT result; - InvokeHelper(0x105, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetFormula(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x105, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetFormulaArray() -{ - VARIANT result; - InvokeHelper(0x24a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetFormulaArray(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x24a, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -long Range::GetFormulaLabel() -{ - long result; - InvokeHelper(0x564, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void Range::SetFormulaLabel(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x564, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -VARIANT Range::GetFormulaHidden() -{ - VARIANT result; - InvokeHelper(0x106, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetFormulaHidden(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x106, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetFormulaLocal() -{ - VARIANT result; - InvokeHelper(0x107, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetFormulaLocal(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x107, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetFormulaR1C1() -{ - VARIANT result; - InvokeHelper(0x108, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetFormulaR1C1(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x108, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetFormulaR1C1Local() -{ - VARIANT result; - InvokeHelper(0x109, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetFormulaR1C1Local(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x109, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::FunctionWizard() -{ - InvokeHelper(0x23b, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL Range::GoalSeek(const VARIANT& Goal, LPDISPATCH ChangingCell) -{ - BOOL result; - static BYTE parms[] = - VTS_VARIANT VTS_DISPATCH; - InvokeHelper(0x1d8, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, - &Goal, ChangingCell); - return result; -} - -VARIANT Range::Group(const VARIANT& Start, const VARIANT& End, const VARIANT& By, const VARIANT& Periods) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x2e, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Start, &End, &By, &Periods); - return result; -} - -VARIANT Range::GetHasArray() -{ - VARIANT result; - InvokeHelper(0x10a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetHasFormula() -{ - VARIANT result; - InvokeHelper(0x10b, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetHeight() -{ - VARIANT result; - InvokeHelper(0x7b, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetHidden() -{ - VARIANT result; - InvokeHelper(0x10c, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetHidden(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x10c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetHorizontalAlignment() -{ - VARIANT result; - InvokeHelper(0x88, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetHorizontalAlignment(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x88, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetIndentLevel() -{ - VARIANT result; - InvokeHelper(0xc9, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetIndentLevel(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xc9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::InsertIndent(long InsertAmount) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x565, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - InsertAmount); -} - -void Range::Insert(const VARIANT& Shift) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xfc, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Shift); -} - -LPDISPATCH Range::GetInterior() -{ - LPDISPATCH result; - InvokeHelper(0x81, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetItem(const VARIANT& RowIndex, const VARIANT& ColumnIndex) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, parms, - &RowIndex, &ColumnIndex); - return result; -} - -void Range::SetItem(const VARIANT& RowIndex, const VARIANT& ColumnIndex, const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xaa, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &RowIndex, &ColumnIndex, &newValue); -} - -void Range::Justify() -{ - InvokeHelper(0x1ef, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -VARIANT Range::GetLeft() -{ - VARIANT result; - InvokeHelper(0x7f, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -long Range::GetListHeaderRows() -{ - long result; - InvokeHelper(0x4a3, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void Range::ListNames() -{ - InvokeHelper(0xfd, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -long Range::GetLocationInTable() -{ - long result; - InvokeHelper(0x2b3, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetLocked() -{ - VARIANT result; - InvokeHelper(0x10d, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetLocked(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x10d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::Merge(const VARIANT& Across) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x234, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Across); -} - -void Range::UnMerge() -{ - InvokeHelper(0x568, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH Range::GetMergeArea() -{ - LPDISPATCH result; - InvokeHelper(0x569, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetMergeCells() -{ - VARIANT result; - InvokeHelper(0xd0, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetMergeCells(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xd0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetName() -{ - VARIANT result; - InvokeHelper(0x6e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetName(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x6e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::NavigateArrow(const VARIANT& TowardPrecedent, const VARIANT& ArrowNumber, const VARIANT& LinkNumber) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x408, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &TowardPrecedent, &ArrowNumber, &LinkNumber); -} - -LPUNKNOWN Range::Get_NewEnum() -{ - LPUNKNOWN result; - InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetNext() -{ - LPDISPATCH result; - InvokeHelper(0x1f6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -CString Range::NoteText(const VARIANT& Text, const VARIANT& Start, const VARIANT& Length) -{ - CString result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x467, DISPATCH_METHOD, VT_BSTR, (void*)&result, parms, - &Text, &Start, &Length); - return result; -} - -VARIANT Range::GetNumberFormat() -{ - VARIANT result; - InvokeHelper(0xc1, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetNumberFormat(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xc1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetNumberFormatLocal() -{ - VARIANT result; - InvokeHelper(0x449, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetNumberFormatLocal(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x449, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -LPDISPATCH Range::GetOffset(const VARIANT& RowOffset, const VARIANT& ColumnOffset) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xfe, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &RowOffset, &ColumnOffset); - return result; -} - -VARIANT Range::GetOrientation() -{ - VARIANT result; - InvokeHelper(0x86, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetOrientation(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x86, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetOutlineLevel() -{ - VARIANT result; - InvokeHelper(0x10f, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetOutlineLevel(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x10f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -long Range::GetPageBreak() -{ - long result; - InvokeHelper(0xff, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void Range::SetPageBreak(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0xff, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -void Range::Parse(const VARIANT& ParseLine, const VARIANT& Destination) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1dd, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &ParseLine, &Destination); -} - -void Range::PasteSpecial(long Paste, long Operation, const VARIANT& SkipBlanks, const VARIANT& Transpose) -{ - static BYTE parms[] = - VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x403, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Paste, Operation, &SkipBlanks, &Transpose); -} - -LPDISPATCH Range::GetPivotField() -{ - LPDISPATCH result; - InvokeHelper(0x2db, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetPivotItem() -{ - LPDISPATCH result; - InvokeHelper(0x2e4, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetPivotTable() -{ - LPDISPATCH result; - InvokeHelper(0x2cc, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetPrecedents() -{ - LPDISPATCH result; - InvokeHelper(0x220, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetPrefixCharacter() -{ - VARIANT result; - InvokeHelper(0x1f8, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetPrevious() -{ - LPDISPATCH result; - InvokeHelper(0x1f7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void Range::PrintOut(const VARIANT& From, const VARIANT& To, const VARIANT& Copies, const VARIANT& Preview, const VARIANT& ActivePrinter, const VARIANT& PrintToFile, const VARIANT& Collate) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x389, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &From, &To, &Copies, &Preview, &ActivePrinter, &PrintToFile, &Collate); -} - -void Range::PrintPreview(const VARIANT& EnableChanges) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x119, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &EnableChanges); -} - -LPDISPATCH Range::GetQueryTable() -{ - LPDISPATCH result; - InvokeHelper(0x56a, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetRange(const VARIANT& Cell1, const VARIANT& Cell2) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xc5, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &Cell1, &Cell2); - return result; -} - -void Range::RemoveSubtotal() -{ - InvokeHelper(0x373, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -BOOL Range::Replace(const VARIANT& What, const VARIANT& Replacement, const VARIANT& LookAt, const VARIANT& SearchOrder, const VARIANT& MatchCase, const VARIANT& MatchByte, const VARIANT& MatchControlCharacters, const VARIANT& MatchDiacritics, - const VARIANT& MatchKashida, const VARIANT& MatchAlefHamza) -{ - BOOL result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0xe2, DISPATCH_METHOD, VT_BOOL, (void*)&result, parms, - &What, &Replacement, &LookAt, &SearchOrder, &MatchCase, &MatchByte, &MatchControlCharacters, &MatchDiacritics, &MatchKashida, &MatchAlefHamza); - return result; -} - -LPDISPATCH Range::GetResize(const VARIANT& RowSize, const VARIANT& ColumnSize) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x100, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - &RowSize, &ColumnSize); - return result; -} - -long Range::GetRow() -{ - long result; - InvokeHelper(0x101, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::RowDifferences(const VARIANT& Comparison) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x1ff, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Comparison); - return result; -} - -VARIANT Range::GetRowHeight() -{ - VARIANT result; - InvokeHelper(0x110, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetRowHeight(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x110, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -LPDISPATCH Range::GetRows() -{ - LPDISPATCH result; - InvokeHelper(0x102, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::Run(const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, const VARIANT& Arg10, - const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, const VARIANT& Arg20, - const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, const VARIANT& Arg30) -{ - VARIANT result; - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT - VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x103, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, - &Arg1, &Arg2, &Arg3, &Arg4, &Arg5, &Arg6, &Arg7, &Arg8, &Arg9, &Arg10, &Arg11, &Arg12, &Arg13, &Arg14, &Arg15, &Arg16, &Arg17, &Arg18, &Arg19, &Arg20, &Arg21, &Arg22, &Arg23, &Arg24, &Arg25, &Arg26, &Arg27, &Arg28, &Arg29, &Arg30); - return result; -} - -void Range::Select() -{ - InvokeHelper(0xeb, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::Show() -{ - InvokeHelper(0x1f0, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::ShowDependents(const VARIANT& Remove) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x36d, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Remove); -} - -VARIANT Range::GetShowDetail() -{ - VARIANT result; - InvokeHelper(0x249, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetShowDetail(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x249, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::ShowErrors() -{ - InvokeHelper(0x36e, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -void Range::ShowPrecedents(const VARIANT& Remove) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x36f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Remove); -} - -VARIANT Range::GetShrinkToFit() -{ - VARIANT result; - InvokeHelper(0xd1, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetShrinkToFit(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0xd1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::Sort(const VARIANT& Key1, long Order1, const VARIANT& Key2, const VARIANT& Type, long Order2, const VARIANT& Key3, long Order3, long Header, const VARIANT& OrderCustom, const VARIANT& MatchCase, long Orientation, long SortMethod, - const VARIANT& IgnoreControlCharacters, const VARIANT& IgnoreDiacritics, const VARIANT& IgnoreKashida) -{ - static BYTE parms[] = - VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x370, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Key1, Order1, &Key2, &Type, Order2, &Key3, Order3, Header, &OrderCustom, &MatchCase, Orientation, SortMethod, &IgnoreControlCharacters, &IgnoreDiacritics, &IgnoreKashida); -} - -void Range::SortSpecial(long SortMethod, const VARIANT& Key1, long Order1, const VARIANT& Type, const VARIANT& Key2, long Order2, const VARIANT& Key3, long Order3, long Header, const VARIANT& OrderCustom, const VARIANT& MatchCase, long Orientation) -{ - static BYTE parms[] = - VTS_I4 VTS_VARIANT VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4 VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_I4; - InvokeHelper(0x371, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - SortMethod, &Key1, Order1, &Type, &Key2, Order2, &Key3, Order3, Header, &OrderCustom, &MatchCase, Orientation); -} - -LPDISPATCH Range::GetSoundNote() -{ - LPDISPATCH result; - InvokeHelper(0x394, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::SpecialCells(long Type, const VARIANT& Value) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_I4 VTS_VARIANT; - InvokeHelper(0x19a, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - Type, &Value); - return result; -} - -VARIANT Range::GetStyle() -{ - VARIANT result; - InvokeHelper(0x104, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetStyle(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x104, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -void Range::SubscribeTo(LPCTSTR Edition, long Format) -{ - static BYTE parms[] = - VTS_BSTR VTS_I4; - InvokeHelper(0x1e1, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - Edition, Format); -} - -void Range::Subtotal(long GroupBy, long Function, const VARIANT& TotalList, const VARIANT& Replace, const VARIANT& PageBreaks, long SummaryBelowData) -{ - static BYTE parms[] = - VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_I4; - InvokeHelper(0x372, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - GroupBy, Function, &TotalList, &Replace, &PageBreaks, SummaryBelowData); -} - -VARIANT Range::GetSummary() -{ - VARIANT result; - InvokeHelper(0x111, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::Table(const VARIANT& RowInput, const VARIANT& ColumnInput) -{ - static BYTE parms[] = - VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x1f1, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &RowInput, &ColumnInput); -} - -VARIANT Range::GetText() -{ - VARIANT result; - InvokeHelper(0x8a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::TextToColumns(const VARIANT& Destination, long DataType, long TextQualifier, const VARIANT& ConsecutiveDelimiter, const VARIANT& Tab, const VARIANT& Semicolon, const VARIANT& Comma, const VARIANT& Space, const VARIANT& Other, - const VARIANT& OtherChar, const VARIANT& FieldInfo) -{ - static BYTE parms[] = - VTS_VARIANT VTS_I4 VTS_I4 VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT; - InvokeHelper(0x410, DISPATCH_METHOD, VT_EMPTY, NULL, parms, - &Destination, DataType, TextQualifier, &ConsecutiveDelimiter, &Tab, &Semicolon, &Comma, &Space, &Other, &OtherChar, &FieldInfo); -} - -VARIANT Range::GetTop() -{ - VARIANT result; - InvokeHelper(0x7e, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::Ungroup() -{ - InvokeHelper(0xf4, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -VARIANT Range::GetUseStandardHeight() -{ - VARIANT result; - InvokeHelper(0x112, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetUseStandardHeight(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x112, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetUseStandardWidth() -{ - VARIANT result; - InvokeHelper(0x113, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetUseStandardWidth(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x113, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -LPDISPATCH Range::GetValidation() -{ - LPDISPATCH result; - InvokeHelper(0x56b, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetValue() -{ - VARIANT result; - InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetValue(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetValue2() -{ - VARIANT result; - InvokeHelper(0x56c, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetValue2(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x56c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetVerticalAlignment() -{ - VARIANT result; - InvokeHelper(0x89, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetVerticalAlignment(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x89, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Range::GetWidth() -{ - VARIANT result; - InvokeHelper(0x7a, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetWorksheet() -{ - LPDISPATCH result; - InvokeHelper(0x15c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Range::GetWrapText() -{ - VARIANT result; - InvokeHelper(0x114, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Range::SetWrapText(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x114, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -LPDISPATCH Range::AddComment(const VARIANT& Text) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x56d, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, - &Text); - return result; -} - -LPDISPATCH Range::GetComment() -{ - LPDISPATCH result; - InvokeHelper(0x38e, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -void Range::ClearComments() -{ - InvokeHelper(0x56e, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); -} - -LPDISPATCH Range::GetPhonetic() -{ - LPDISPATCH result; - InvokeHelper(0x56f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -LPDISPATCH Range::GetFormatConditions() -{ - LPDISPATCH result; - InvokeHelper(0x570, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long Range::GetReadingOrder() -{ - long result; - InvokeHelper(0x3cf, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -void Range::SetReadingOrder(long nNewValue) -{ - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x3cf, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - nNewValue); -} - -LPDISPATCH Range::GetHyperlinks() -{ - LPDISPATCH result; - InvokeHelper(0x571, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - - -///////////////////////////////////////////////////////////////////////////// -// Border properties - -///////////////////////////////////////////////////////////////////////////// -// Border operations - -LPDISPATCH Border::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long Border::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Border::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Border::GetColor() -{ - VARIANT result; - InvokeHelper(0x63, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Border::SetColor(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x63, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Border::GetColorIndex() -{ - VARIANT result; - InvokeHelper(0x61, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Border::SetColorIndex(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x61, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Border::GetLineStyle() -{ - VARIANT result; - InvokeHelper(0x77, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Border::SetLineStyle(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x77, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Border::GetWeight() -{ - VARIANT result; - InvokeHelper(0x78, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Border::SetWeight(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x78, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - - -///////////////////////////////////////////////////////////////////////////// -// Borders properties - -///////////////////////////////////////////////////////////////////////////// -// Borders operations - -LPDISPATCH Borders::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long Borders::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Borders::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Borders::GetColor() -{ - VARIANT result; - InvokeHelper(0x63, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Borders::SetColor(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x63, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Borders::GetColorIndex() -{ - VARIANT result; - InvokeHelper(0x61, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Borders::SetColorIndex(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x61, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -long Borders::GetCount() -{ - long result; - InvokeHelper(0x76, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Borders::GetItem(long Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_I4; - InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - Index); - return result; -} - -VARIANT Borders::GetLineStyle() -{ - VARIANT result; - InvokeHelper(0x77, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Borders::SetLineStyle(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x77, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -LPUNKNOWN Borders::Get_NewEnum() -{ - LPUNKNOWN result; - InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); - return result; -} - -VARIANT Borders::GetValue() -{ - VARIANT result; - InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Borders::SetValue(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Borders::GetWeight() -{ - VARIANT result; - InvokeHelper(0x78, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Borders::SetWeight(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x78, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -LPDISPATCH Borders::Get_Default(long Index) -{ - LPDISPATCH result; - static BYTE parms[] = - VTS_I4; - InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, - Index); - return result; -} - - -///////////////////////////////////////////////////////////////////////////// -// Interior properties - -///////////////////////////////////////////////////////////////////////////// -// Interior operations - -LPDISPATCH Interior::GetApplication() -{ - LPDISPATCH result; - InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -long Interior::GetCreator() -{ - long result; - InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); - return result; -} - -LPDISPATCH Interior::GetParent() -{ - LPDISPATCH result; - InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); - return result; -} - -VARIANT Interior::GetColor() -{ - VARIANT result; - InvokeHelper(0x63, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Interior::SetColor(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x63, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Interior::GetColorIndex() -{ - VARIANT result; - InvokeHelper(0x61, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Interior::SetColorIndex(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x61, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Interior::GetInvertIfNegative() -{ - VARIANT result; - InvokeHelper(0x84, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Interior::SetInvertIfNegative(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x84, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Interior::GetPattern() -{ - VARIANT result; - InvokeHelper(0x5f, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Interior::SetPattern(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x5f, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Interior::GetPatternColor() -{ - VARIANT result; - InvokeHelper(0x64, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Interior::SetPatternColor(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x64, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} - -VARIANT Interior::GetPatternColorIndex() -{ - VARIANT result; - InvokeHelper(0x62, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&result, NULL); - return result; -} - -void Interior::SetPatternColorIndex(const VARIANT& newValue) -{ - static BYTE parms[] = - VTS_VARIANT; - InvokeHelper(0x62, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, - &newValue); -} diff --git a/Generals/Code/Tools/Babylon/excel8.h b/Generals/Code/Tools/Babylon/excel8.h deleted file mode 100644 index 1a04df750e..0000000000 --- a/Generals/Code/Tools/Babylon/excel8.h +++ /dev/null @@ -1,884 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Machine generated IDispatch wrapper class(es) created with ClassWizard -///////////////////////////////////////////////////////////////////////////// -// Workbooks wrapper class - -class Workbooks : public COleDispatchDriver -{ -public: - Workbooks() {} // Calls COleDispatchDriver default constructor - Workbooks(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - Workbooks(const Workbooks& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - LPDISPATCH Add(const VARIANT& Template); - void Close(); - long GetCount(); - LPDISPATCH GetItem(const VARIANT& Index); - LPUNKNOWN Get_NewEnum(); - LPDISPATCH Open(LPCTSTR Filename, const VARIANT& UpdateLinks, const VARIANT& ReadOnly, const VARIANT& Format, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& IgnoreReadOnlyRecommended, const VARIANT& Origin, - const VARIANT& Delimiter, const VARIANT& Editable, const VARIANT& Notify, const VARIANT& Converter, const VARIANT& AddToMru); - void OpenText(LPCTSTR Filename, const VARIANT& Origin, const VARIANT& StartRow, const VARIANT& DataType, long TextQualifier, const VARIANT& ConsecutiveDelimiter, const VARIANT& Tab, const VARIANT& Semicolon, const VARIANT& Comma, - const VARIANT& Space, const VARIANT& Other, const VARIANT& OtherChar, const VARIANT& FieldInfo, const VARIANT& TextVisualLayout); - LPDISPATCH Get_Default(const VARIANT& Index); -}; -///////////////////////////////////////////////////////////////////////////// -// _Application wrapper class - -class _Application : public COleDispatchDriver -{ -public: - _Application() {} // Calls COleDispatchDriver default constructor - _Application(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - _Application(const _Application& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - LPDISPATCH GetActiveCell(); - LPDISPATCH GetActiveChart(); - CString GetActivePrinter(); - void SetActivePrinter(LPCTSTR lpszNewValue); - LPDISPATCH GetActiveSheet(); - LPDISPATCH GetActiveWindow(); - LPDISPATCH GetActiveWorkbook(); - LPDISPATCH GetAddIns(); - LPDISPATCH GetAssistant(); - void Calculate(); - LPDISPATCH GetCells(); - LPDISPATCH GetCharts(); - LPDISPATCH GetColumns(); - LPDISPATCH GetCommandBars(); - long GetDDEAppReturnCode(); - void DDEExecute(long Channel, LPCTSTR String); - long DDEInitiate(LPCTSTR App, LPCTSTR Topic); - void DDEPoke(long Channel, const VARIANT& Item, const VARIANT& Data); - VARIANT DDERequest(long Channel, LPCTSTR Item); - void DDETerminate(long Channel); - VARIANT Evaluate(const VARIANT& Name); - VARIANT _Evaluate(const VARIANT& Name); - VARIANT ExecuteExcel4Macro(LPCTSTR String); - LPDISPATCH Intersect(LPDISPATCH Arg1, LPDISPATCH Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, const VARIANT& Arg10, - const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, const VARIANT& Arg20, - const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, const VARIANT& Arg30); - LPDISPATCH GetNames(); - LPDISPATCH GetRange(const VARIANT& Cell1, const VARIANT& Cell2); - LPDISPATCH GetRows(); - VARIANT Run(const VARIANT& Macro, const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, - const VARIANT& Arg10, const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, - const VARIANT& Arg20, const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, - const VARIANT& Arg30); - VARIANT _Run2(const VARIANT& Macro, const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, - const VARIANT& Arg10, const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, - const VARIANT& Arg20, const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, - const VARIANT& Arg30); - LPDISPATCH GetSelection(); - void SendKeys(const VARIANT& Keys, const VARIANT& Wait); - LPDISPATCH GetSheets(); - LPDISPATCH GetThisWorkbook(); - LPDISPATCH Union(LPDISPATCH Arg1, LPDISPATCH Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, const VARIANT& Arg10, const VARIANT& Arg11, - const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, const VARIANT& Arg20, const VARIANT& Arg21, - const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, const VARIANT& Arg30); - LPDISPATCH GetWindows(); - LPDISPATCH GetWorkbooks(); - LPDISPATCH GetWorksheetFunction(); - LPDISPATCH GetWorksheets(); - LPDISPATCH GetExcel4IntlMacroSheets(); - LPDISPATCH GetExcel4MacroSheets(); - void ActivateMicrosoftApp(long Index); - void AddChartAutoFormat(const VARIANT& Chart, LPCTSTR Name, const VARIANT& Description); - void AddCustomList(const VARIANT& ListArray, const VARIANT& ByRow); - BOOL GetAlertBeforeOverwriting(); - void SetAlertBeforeOverwriting(BOOL bNewValue); - CString GetAltStartupPath(); - void SetAltStartupPath(LPCTSTR lpszNewValue); - BOOL GetAskToUpdateLinks(); - void SetAskToUpdateLinks(BOOL bNewValue); - BOOL GetEnableAnimations(); - void SetEnableAnimations(BOOL bNewValue); - LPDISPATCH GetAutoCorrect(); - long GetBuild(); - BOOL GetCalculateBeforeSave(); - void SetCalculateBeforeSave(BOOL bNewValue); - long GetCalculation(); - void SetCalculation(long nNewValue); - VARIANT GetCaller(const VARIANT& Index); - BOOL GetCanPlaySounds(); - BOOL GetCanRecordSounds(); - CString GetCaption(); - void SetCaption(LPCTSTR lpszNewValue); - BOOL GetCellDragAndDrop(); - void SetCellDragAndDrop(BOOL bNewValue); - double CentimetersToPoints(double Centimeters); - BOOL CheckSpelling(LPCTSTR Word, const VARIANT& CustomDictionary, const VARIANT& IgnoreUppercase); - VARIANT GetClipboardFormats(const VARIANT& Index); - BOOL GetDisplayClipboardWindow(); - void SetDisplayClipboardWindow(BOOL bNewValue); - long GetCommandUnderlines(); - void SetCommandUnderlines(long nNewValue); - BOOL GetConstrainNumeric(); - void SetConstrainNumeric(BOOL bNewValue); - VARIANT ConvertFormula(const VARIANT& Formula, long FromReferenceStyle, const VARIANT& ToReferenceStyle, const VARIANT& ToAbsolute, const VARIANT& RelativeTo); - BOOL GetCopyObjectsWithCells(); - void SetCopyObjectsWithCells(BOOL bNewValue); - long GetCursor(); - void SetCursor(long nNewValue); - long GetCustomListCount(); - long GetCutCopyMode(); - void SetCutCopyMode(long nNewValue); - long GetDataEntryMode(); - void SetDataEntryMode(long nNewValue); - CString Get_Default(); - CString GetDefaultFilePath(); - void SetDefaultFilePath(LPCTSTR lpszNewValue); - void DeleteChartAutoFormat(LPCTSTR Name); - void DeleteCustomList(long ListNum); - LPDISPATCH GetDialogs(); - BOOL GetDisplayAlerts(); - void SetDisplayAlerts(BOOL bNewValue); - BOOL GetDisplayFormulaBar(); - void SetDisplayFormulaBar(BOOL bNewValue); - BOOL GetDisplayFullScreen(); - void SetDisplayFullScreen(BOOL bNewValue); - BOOL GetDisplayNoteIndicator(); - void SetDisplayNoteIndicator(BOOL bNewValue); - long GetDisplayCommentIndicator(); - void SetDisplayCommentIndicator(long nNewValue); - BOOL GetDisplayExcel4Menus(); - void SetDisplayExcel4Menus(BOOL bNewValue); - BOOL GetDisplayRecentFiles(); - void SetDisplayRecentFiles(BOOL bNewValue); - BOOL GetDisplayScrollBars(); - void SetDisplayScrollBars(BOOL bNewValue); - BOOL GetDisplayStatusBar(); - void SetDisplayStatusBar(BOOL bNewValue); - void DoubleClick(); - BOOL GetEditDirectlyInCell(); - void SetEditDirectlyInCell(BOOL bNewValue); - BOOL GetEnableAutoComplete(); - void SetEnableAutoComplete(BOOL bNewValue); - long GetEnableCancelKey(); - void SetEnableCancelKey(long nNewValue); - BOOL GetEnableSound(); - void SetEnableSound(BOOL bNewValue); - VARIANT GetFileConverters(const VARIANT& Index1, const VARIANT& Index2); - LPDISPATCH GetFileSearch(); - LPDISPATCH GetFileFind(); - void FindFile(); - BOOL GetFixedDecimal(); - void SetFixedDecimal(BOOL bNewValue); - long GetFixedDecimalPlaces(); - void SetFixedDecimalPlaces(long nNewValue); - VARIANT GetCustomListContents(long ListNum); - long GetCustomListNum(const VARIANT& ListArray); - VARIANT GetOpenFilename(const VARIANT& FileFilter, const VARIANT& FilterIndex, const VARIANT& Title, const VARIANT& ButtonText, const VARIANT& MultiSelect); - VARIANT GetSaveAsFilename(const VARIANT& InitialFilename, const VARIANT& FileFilter, const VARIANT& FilterIndex, const VARIANT& Title, const VARIANT& ButtonText); - void Goto(const VARIANT& Reference, const VARIANT& Scroll); - double GetHeight(); - void SetHeight(double newValue); - void Help(const VARIANT& HelpFile, const VARIANT& HelpContextID); - BOOL GetIgnoreRemoteRequests(); - void SetIgnoreRemoteRequests(BOOL bNewValue); - double InchesToPoints(double Inches); - VARIANT InputBox(LPCTSTR Prompt, const VARIANT& Title, const VARIANT& Default, const VARIANT& Left, const VARIANT& Top, const VARIANT& HelpFile, const VARIANT& HelpContextID, const VARIANT& Type); - BOOL GetInteractive(); - void SetInteractive(BOOL bNewValue); - VARIANT GetInternational(const VARIANT& Index); - BOOL GetIteration(); - void SetIteration(BOOL bNewValue); - double GetLeft(); - void SetLeft(double newValue); - CString GetLibraryPath(); - void MacroOptions(const VARIANT& Macro, const VARIANT& Description, const VARIANT& HasMenu, const VARIANT& MenuText, const VARIANT& HasShortcutKey, const VARIANT& ShortcutKey, const VARIANT& Category, const VARIANT& StatusBar, - const VARIANT& HelpContextID, const VARIANT& HelpFile); - void MailLogoff(); - void MailLogon(const VARIANT& Name, const VARIANT& Password, const VARIANT& DownloadNewMail); - VARIANT GetMailSession(); - long GetMailSystem(); - BOOL GetMathCoprocessorAvailable(); - double GetMaxChange(); - void SetMaxChange(double newValue); - long GetMaxIterations(); - void SetMaxIterations(long nNewValue); - long GetMemoryFree(); - long GetMemoryTotal(); - long GetMemoryUsed(); - BOOL GetMouseAvailable(); - BOOL GetMoveAfterReturn(); - void SetMoveAfterReturn(BOOL bNewValue); - long GetMoveAfterReturnDirection(); - void SetMoveAfterReturnDirection(long nNewValue); - LPDISPATCH GetRecentFiles(); - CString GetName(); - LPDISPATCH NextLetter(); - CString GetNetworkTemplatesPath(); - LPDISPATCH GetODBCErrors(); - long GetODBCTimeout(); - void SetODBCTimeout(long nNewValue); - void OnKey(LPCTSTR Key, const VARIANT& Procedure); - void OnRepeat(LPCTSTR Text, LPCTSTR Procedure); - void OnTime(const VARIANT& EarliestTime, LPCTSTR Procedure, const VARIANT& LatestTime, const VARIANT& Schedule); - void OnUndo(LPCTSTR Text, LPCTSTR Procedure); - CString GetOnWindow(); - void SetOnWindow(LPCTSTR lpszNewValue); - CString GetOperatingSystem(); - CString GetOrganizationName(); - CString GetPath(); - CString GetPathSeparator(); - VARIANT GetPreviousSelections(const VARIANT& Index); - BOOL GetPivotTableSelection(); - void SetPivotTableSelection(BOOL bNewValue); - BOOL GetPromptForSummaryInfo(); - void SetPromptForSummaryInfo(BOOL bNewValue); - void Quit(); - void RecordMacro(const VARIANT& BasicCode, const VARIANT& XlmCode); - BOOL GetRecordRelative(); - long GetReferenceStyle(); - void SetReferenceStyle(long nNewValue); - VARIANT GetRegisteredFunctions(const VARIANT& Index1, const VARIANT& Index2); - BOOL RegisterXLL(LPCTSTR Filename); - void Repeat(); - BOOL GetRollZoom(); - void SetRollZoom(BOOL bNewValue); - void SaveWorkspace(const VARIANT& Filename); - BOOL GetScreenUpdating(); - void SetScreenUpdating(BOOL bNewValue); - void SetDefaultChart(const VARIANT& FormatName, const VARIANT& Gallery); - long GetSheetsInNewWorkbook(); - void SetSheetsInNewWorkbook(long nNewValue); - BOOL GetShowChartTipNames(); - void SetShowChartTipNames(BOOL bNewValue); - BOOL GetShowChartTipValues(); - void SetShowChartTipValues(BOOL bNewValue); - CString GetStandardFont(); - void SetStandardFont(LPCTSTR lpszNewValue); - double GetStandardFontSize(); - void SetStandardFontSize(double newValue); - CString GetStartupPath(); - VARIANT GetStatusBar(); - void SetStatusBar(const VARIANT& newValue); - CString GetTemplatesPath(); - BOOL GetShowToolTips(); - void SetShowToolTips(BOOL bNewValue); - double GetTop(); - void SetTop(double newValue); - long GetDefaultSaveFormat(); - void SetDefaultSaveFormat(long nNewValue); - CString GetTransitionMenuKey(); - void SetTransitionMenuKey(LPCTSTR lpszNewValue); - long GetTransitionMenuKeyAction(); - void SetTransitionMenuKeyAction(long nNewValue); - BOOL GetTransitionNavigKeys(); - void SetTransitionNavigKeys(BOOL bNewValue); - void Undo(); - double GetUsableHeight(); - double GetUsableWidth(); - BOOL GetUserControl(); - void SetUserControl(BOOL bNewValue); - CString GetUserName_(); - void SetUserName(LPCTSTR lpszNewValue); - CString GetValue(); - LPDISPATCH GetVbe(); - CString GetVersion(); - BOOL GetVisible(); - void SetVisible(BOOL bNewValue); - void Volatile(const VARIANT& Volatile); - void Wait(const VARIANT& Time); - double GetWidth(); - void SetWidth(double newValue); - BOOL GetWindowsForPens(); - long GetWindowState(); - void SetWindowState(long nNewValue); - long GetUILanguage(); - void SetUILanguage(long nNewValue); - long GetDefaultSheetDirection(); - void SetDefaultSheetDirection(long nNewValue); - long GetCursorMovement(); - void SetCursorMovement(long nNewValue); - long GetControlCharacters(); - void SetControlCharacters(long nNewValue); - BOOL GetEnableEvents(); - void SetEnableEvents(BOOL bNewValue); -}; -///////////////////////////////////////////////////////////////////////////// -// _Workbook wrapper class - -class _Workbook : public COleDispatchDriver -{ -public: - _Workbook() {} // Calls COleDispatchDriver default constructor - _Workbook(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - _Workbook(const _Workbook& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - BOOL GetAcceptLabelsInFormulas(); - void SetAcceptLabelsInFormulas(BOOL bNewValue); - void Activate(); - LPDISPATCH GetActiveChart(); - LPDISPATCH GetActiveSheet(); - long GetAutoUpdateFrequency(); - void SetAutoUpdateFrequency(long nNewValue); - BOOL GetAutoUpdateSaveChanges(); - void SetAutoUpdateSaveChanges(BOOL bNewValue); - long GetChangeHistoryDuration(); - void SetChangeHistoryDuration(long nNewValue); - LPDISPATCH GetBuiltinDocumentProperties(); - void ChangeFileAccess(long Mode, const VARIANT& WritePassword, const VARIANT& Notify); - void ChangeLink(LPCTSTR Name, LPCTSTR NewName, long Type); - LPDISPATCH GetCharts(); - void Close(const VARIANT& SaveChanges, const VARIANT& Filename, const VARIANT& RouteWorkbook); - CString GetCodeName(); - CString Get_CodeName(); - void Set_CodeName(LPCTSTR lpszNewValue); - VARIANT GetColors(const VARIANT& Index); - void SetColors(const VARIANT& Index, const VARIANT& newValue); - LPDISPATCH GetCommandBars(); - long GetConflictResolution(); - void SetConflictResolution(long nNewValue); - LPDISPATCH GetContainer(); - BOOL GetCreateBackup(); - LPDISPATCH GetCustomDocumentProperties(); - BOOL GetDate1904(); - void SetDate1904(BOOL bNewValue); - void DeleteNumberFormat(LPCTSTR NumberFormat); - long GetDisplayDrawingObjects(); - void SetDisplayDrawingObjects(long nNewValue); - BOOL ExclusiveAccess(); - long GetFileFormat(); - void ForwardMailer(); - CString GetFullName(); - BOOL GetHasPassword(); - BOOL GetHasRoutingSlip(); - void SetHasRoutingSlip(BOOL bNewValue); - BOOL GetIsAddin(); - void SetIsAddin(BOOL bNewValue); - VARIANT LinkInfo(LPCTSTR Name, long LinkInfo, const VARIANT& Type, const VARIANT& EditionRef); - VARIANT LinkSources(const VARIANT& Type); - LPDISPATCH GetMailer(); - void MergeWorkbook(const VARIANT& Filename); - BOOL GetMultiUserEditing(); - CString GetName(); - LPDISPATCH GetNames(); - LPDISPATCH NewWindow(); - void OpenLinks(LPCTSTR Name, const VARIANT& ReadOnly, const VARIANT& Type); - CString GetPath(); - BOOL GetPersonalViewListSettings(); - void SetPersonalViewListSettings(BOOL bNewValue); - BOOL GetPersonalViewPrintSettings(); - void SetPersonalViewPrintSettings(BOOL bNewValue); - LPDISPATCH PivotCaches(); - void Post(const VARIANT& DestName); - BOOL GetPrecisionAsDisplayed(); - void SetPrecisionAsDisplayed(BOOL bNewValue); - void PrintOut(const VARIANT& From, const VARIANT& To, const VARIANT& Copies, const VARIANT& Preview, const VARIANT& ActivePrinter, const VARIANT& PrintToFile, const VARIANT& Collate); - void PrintPreview(const VARIANT& EnableChanges); - void Protect(const VARIANT& Password, const VARIANT& Structure, const VARIANT& Windows); - void ProtectSharing(const VARIANT& Filename, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup, const VARIANT& SharingPassword); - BOOL GetProtectStructure(); - BOOL GetProtectWindows(); - BOOL GetReadOnly(); - BOOL GetReadOnlyRecommended(); - void RefreshAll(); - void Reply(); - void ReplyAll(); - void RemoveUser(long Index); - long GetRevisionNumber(); - void Route(); - BOOL GetRouted(); - LPDISPATCH GetRoutingSlip(); - void RunAutoMacros(long Which); - void Save(); - void SaveAs(const VARIANT& Filename, const VARIANT& FileFormat, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup, long AccessMode, const VARIANT& ConflictResolution, - const VARIANT& AddToMru, const VARIANT& TextCodepage, const VARIANT& TextVisualLayout); - void SaveCopyAs(const VARIANT& Filename); - BOOL GetSaved(); - void SetSaved(BOOL bNewValue); - BOOL GetSaveLinkValues(); - void SetSaveLinkValues(BOOL bNewValue); - void SendMail(const VARIANT& Recipients, const VARIANT& Subject, const VARIANT& ReturnReceipt); - void SendMailer(const VARIANT& FileFormat, long Priority); - void SetLinkOnData(LPCTSTR Name, const VARIANT& Procedure); - LPDISPATCH GetSheets(); - BOOL GetShowConflictHistory(); - void SetShowConflictHistory(BOOL bNewValue); - LPDISPATCH GetStyles(); - void Unprotect(const VARIANT& Password); - void UnprotectSharing(const VARIANT& SharingPassword); - void UpdateFromFile(); - void UpdateLink(const VARIANT& Name, const VARIANT& Type); - BOOL GetUpdateRemoteReferences(); - void SetUpdateRemoteReferences(BOOL bNewValue); - VARIANT GetUserStatus(); - LPDISPATCH GetCustomViews(); - LPDISPATCH GetWindows(); - LPDISPATCH GetWorksheets(); - BOOL GetWriteReserved(); - CString GetWriteReservedBy(); - LPDISPATCH GetExcel4IntlMacroSheets(); - LPDISPATCH GetExcel4MacroSheets(); - BOOL GetTemplateRemoveExtData(); - void SetTemplateRemoveExtData(BOOL bNewValue); - void HighlightChangesOptions(const VARIANT& When, const VARIANT& Who, const VARIANT& Where); - BOOL GetHighlightChangesOnScreen(); - void SetHighlightChangesOnScreen(BOOL bNewValue); - BOOL GetKeepChangeHistory(); - void SetKeepChangeHistory(BOOL bNewValue); - BOOL GetListChangesOnNewSheet(); - void SetListChangesOnNewSheet(BOOL bNewValue); - void PurgeChangeHistoryNow(long Days, const VARIANT& SharingPassword); - void AcceptAllChanges(const VARIANT& When, const VARIANT& Who, const VARIANT& Where); - void RejectAllChanges(const VARIANT& When, const VARIANT& Who, const VARIANT& Where); - void ResetColors(); - LPDISPATCH GetVBProject(); - void FollowHyperlink(LPCTSTR Address, const VARIANT& SubAddress, const VARIANT& NewWindow, const VARIANT& AddHistory, const VARIANT& ExtraInfo, const VARIANT& Method, const VARIANT& HeaderInfo); - void AddToFavorites(); - BOOL GetIsInplace(); -}; -///////////////////////////////////////////////////////////////////////////// -// _Worksheet wrapper class - -class _Worksheet : public COleDispatchDriver -{ -public: - _Worksheet() {} // Calls COleDispatchDriver default constructor - _Worksheet(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - _Worksheet(const _Worksheet& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - void Activate(); - void Copy(const VARIANT& Before, const VARIANT& After); - void Delete(); - CString GetCodeName(); - CString Get_CodeName(); - void Set_CodeName(LPCTSTR lpszNewValue); - long GetIndex(); - void Move(const VARIANT& Before, const VARIANT& After); - CString GetName(); - void SetName(LPCTSTR lpszNewValue); - LPDISPATCH GetNext(); - LPDISPATCH GetPageSetup(); - LPDISPATCH GetPrevious(); - void PrintOut(const VARIANT& From, const VARIANT& To, const VARIANT& Copies, const VARIANT& Preview, const VARIANT& ActivePrinter, const VARIANT& PrintToFile, const VARIANT& Collate); - void PrintPreview(const VARIANT& EnableChanges); - void Protect(const VARIANT& Password, const VARIANT& DrawingObjects, const VARIANT& Contents, const VARIANT& Scenarios, const VARIANT& UserInterfaceOnly); - BOOL GetProtectContents(); - BOOL GetProtectDrawingObjects(); - BOOL GetProtectionMode(); - BOOL GetProtectScenarios(); - void SaveAs(LPCTSTR Filename, const VARIANT& FileFormat, const VARIANT& Password, const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup, const VARIANT& AddToMru, const VARIANT& TextCodepage, - const VARIANT& TextVisualLayout); - void Select(const VARIANT& Replace); - void Unprotect(const VARIANT& Password); - long GetVisible(); - void SetVisible(long nNewValue); - LPDISPATCH GetShapes(); - BOOL GetTransitionExpEval(); - void SetTransitionExpEval(BOOL bNewValue); - BOOL GetAutoFilterMode(); - void SetAutoFilterMode(BOOL bNewValue); - void SetBackgroundPicture(LPCTSTR Filename); - void Calculate(); - BOOL GetEnableCalculation(); - void SetEnableCalculation(BOOL bNewValue); - LPDISPATCH GetCells(); - LPDISPATCH ChartObjects(const VARIANT& Index); - void CheckSpelling(const VARIANT& CustomDictionary, const VARIANT& IgnoreUppercase, const VARIANT& AlwaysSuggest, const VARIANT& IgnoreInitialAlefHamza, const VARIANT& IgnoreFinalYaa, const VARIANT& SpellScript); - LPDISPATCH GetCircularReference(); - void ClearArrows(); - LPDISPATCH GetColumns(); - long GetConsolidationFunction(); - VARIANT GetConsolidationOptions(); - VARIANT GetConsolidationSources(); - BOOL GetEnableAutoFilter(); - void SetEnableAutoFilter(BOOL bNewValue); - long GetEnableSelection(); - void SetEnableSelection(long nNewValue); - BOOL GetEnableOutlining(); - void SetEnableOutlining(BOOL bNewValue); - BOOL GetEnablePivotTable(); - void SetEnablePivotTable(BOOL bNewValue); - VARIANT Evaluate(const VARIANT& Name); - VARIANT _Evaluate(const VARIANT& Name); - BOOL GetFilterMode(); - void ResetAllPageBreaks(); - LPDISPATCH GetNames(); - LPDISPATCH OLEObjects(const VARIANT& Index); - LPDISPATCH GetOutline(); - void Paste(const VARIANT& Destination, const VARIANT& Link); - void PasteSpecial(const VARIANT& Format, const VARIANT& Link, const VARIANT& DisplayAsIcon, const VARIANT& IconFileName, const VARIANT& IconIndex, const VARIANT& IconLabel); - LPDISPATCH PivotTables(const VARIANT& Index); - LPDISPATCH PivotTableWizard(const VARIANT& SourceType, const VARIANT& SourceData, const VARIANT& TableDestination, const VARIANT& TableName, const VARIANT& RowGrand, const VARIANT& ColumnGrand, const VARIANT& SaveData, - const VARIANT& HasAutoFormat, const VARIANT& AutoPage, const VARIANT& Reserved, const VARIANT& BackgroundQuery, const VARIANT& OptimizeCache, const VARIANT& PageFieldOrder, const VARIANT& PageFieldWrapCount, const VARIANT& ReadData, - const VARIANT& Connection); - LPDISPATCH GetRange(const VARIANT& Cell1, const VARIANT& Cell2); - LPDISPATCH GetRows(); - LPDISPATCH Scenarios(const VARIANT& Index); - CString GetScrollArea(); - void SetScrollArea(LPCTSTR lpszNewValue); - void ShowAllData(); - void ShowDataForm(); - double GetStandardHeight(); - double GetStandardWidth(); - void SetStandardWidth(double newValue); - BOOL GetTransitionFormEntry(); - void SetTransitionFormEntry(BOOL bNewValue); - long GetType(); - LPDISPATCH GetUsedRange(); - LPDISPATCH GetHPageBreaks(); - LPDISPATCH GetVPageBreaks(); - LPDISPATCH GetQueryTables(); - BOOL GetDisplayPageBreaks(); - void SetDisplayPageBreaks(BOOL bNewValue); - LPDISPATCH GetComments(); - LPDISPATCH GetHyperlinks(); - void ClearCircles(); - void CircleInvalid(); - LPDISPATCH GetAutoFilter(); -}; -///////////////////////////////////////////////////////////////////////////// -// Range wrapper class - -class Range : public COleDispatchDriver -{ -public: - Range() {} // Calls COleDispatchDriver default constructor - Range(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - Range(const Range& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - void Activate(); - VARIANT GetAddIndent(); - void SetAddIndent(const VARIANT& newValue); - CString GetAddress(const VARIANT& RowAbsolute, const VARIANT& ColumnAbsolute, long ReferenceStyle, const VARIANT& External, const VARIANT& RelativeTo); - CString GetAddressLocal(const VARIANT& RowAbsolute, const VARIANT& ColumnAbsolute, long ReferenceStyle, const VARIANT& External, const VARIANT& RelativeTo); - void AdvancedFilter(long Action, const VARIANT& CriteriaRange, const VARIANT& CopyToRange, const VARIANT& Unique); - void ApplyNames(const VARIANT& Names, const VARIANT& IgnoreRelativeAbsolute, const VARIANT& UseRowColumnNames, const VARIANT& OmitColumn, const VARIANT& OmitRow, long Order, const VARIANT& AppendLast); - void ApplyOutlineStyles(); - LPDISPATCH GetAreas(); - CString AutoComplete(LPCTSTR String); - void AutoFill(LPDISPATCH Destination, long Type); - void AutoFilter(const VARIANT& Field, const VARIANT& Criteria1, long Operator, const VARIANT& Criteria2, const VARIANT& VisibleDropDown); - void AutoFit(); - void AutoFormat(long Format, const VARIANT& Number, const VARIANT& Font, const VARIANT& Alignment, const VARIANT& Border, const VARIANT& Pattern, const VARIANT& Width); - void AutoOutline(); - void BorderAround(const VARIANT& LineStyle, long Weight, long ColorIndex, const VARIANT& Color); - LPDISPATCH GetBorders(); - void Calculate(); - LPDISPATCH GetCells(); - LPDISPATCH GetCharacters(const VARIANT& Start, const VARIANT& Length); - void CheckSpelling(const VARIANT& CustomDictionary, const VARIANT& IgnoreUppercase, const VARIANT& AlwaysSuggest, const VARIANT& IgnoreInitialAlefHamza, const VARIANT& IgnoreFinalYaa, const VARIANT& SpellScript); - void Clear(); - void ClearContents(); - void ClearFormats(); - void ClearNotes(); - void ClearOutline(); - long GetColumn(); - LPDISPATCH ColumnDifferences(const VARIANT& Comparison); - LPDISPATCH GetColumns(); - VARIANT GetColumnWidth(); - void SetColumnWidth(const VARIANT& newValue); - void Consolidate(const VARIANT& Sources, const VARIANT& Function, const VARIANT& TopRow, const VARIANT& LeftColumn, const VARIANT& CreateLinks); - void Copy(const VARIANT& Destination); - long CopyFromRecordset(LPUNKNOWN Data, const VARIANT& MaxRows, const VARIANT& MaxColumns); - void CopyPicture(long Appearance, long Format); - long GetCount(); - void CreateNames(const VARIANT& Top, const VARIANT& Left, const VARIANT& Bottom, const VARIANT& Right); - void CreatePublisher(const VARIANT& Edition, long Appearance, const VARIANT& ContainsPICT, const VARIANT& ContainsBIFF, const VARIANT& ContainsRTF, const VARIANT& ContainsVALU); - LPDISPATCH GetCurrentArray(); - LPDISPATCH GetCurrentRegion(); - void Cut(const VARIANT& Destination); - void DataSeries(const VARIANT& Rowcol, long Type, long Date, const VARIANT& Step, const VARIANT& Stop, const VARIANT& Trend); - VARIANT Get_Default(const VARIANT& RowIndex, const VARIANT& ColumnIndex); - void Set_Default(const VARIANT& RowIndex, const VARIANT& ColumnIndex, const VARIANT& newValue); - void Delete(const VARIANT& Shift); - LPDISPATCH GetDependents(); - VARIANT DialogBox_(); - LPDISPATCH GetDirectDependents(); - LPDISPATCH GetDirectPrecedents(); - VARIANT EditionOptions(long Type, long Option, const VARIANT& Name, const VARIANT& Reference, long Appearance, long ChartSize, const VARIANT& Format); - LPDISPATCH GetEnd(long Direction); - LPDISPATCH GetEntireColumn(); - LPDISPATCH GetEntireRow(); - void FillDown(); - void FillLeft(); - void FillRight(); - void FillUp(); - LPDISPATCH Find(const VARIANT& What, const VARIANT& After, const VARIANT& LookIn, const VARIANT& LookAt, const VARIANT& SearchOrder, long SearchDirection, const VARIANT& MatchCase, const VARIANT& MatchByte, - const VARIANT& MatchControlCharacters, const VARIANT& MatchDiacritics, const VARIANT& MatchKashida, const VARIANT& MatchAlefHamza); - LPDISPATCH FindNext(const VARIANT& After); - LPDISPATCH FindPrevious(const VARIANT& After); - LPDISPATCH GetFont(); - VARIANT GetFormula(); - void SetFormula(const VARIANT& newValue); - VARIANT GetFormulaArray(); - void SetFormulaArray(const VARIANT& newValue); - long GetFormulaLabel(); - void SetFormulaLabel(long nNewValue); - VARIANT GetFormulaHidden(); - void SetFormulaHidden(const VARIANT& newValue); - VARIANT GetFormulaLocal(); - void SetFormulaLocal(const VARIANT& newValue); - VARIANT GetFormulaR1C1(); - void SetFormulaR1C1(const VARIANT& newValue); - VARIANT GetFormulaR1C1Local(); - void SetFormulaR1C1Local(const VARIANT& newValue); - void FunctionWizard(); - BOOL GoalSeek(const VARIANT& Goal, LPDISPATCH ChangingCell); - VARIANT Group(const VARIANT& Start, const VARIANT& End, const VARIANT& By, const VARIANT& Periods); - VARIANT GetHasArray(); - VARIANT GetHasFormula(); - VARIANT GetHeight(); - VARIANT GetHidden(); - void SetHidden(const VARIANT& newValue); - VARIANT GetHorizontalAlignment(); - void SetHorizontalAlignment(const VARIANT& newValue); - VARIANT GetIndentLevel(); - void SetIndentLevel(const VARIANT& newValue); - void InsertIndent(long InsertAmount); - void Insert(const VARIANT& Shift); - LPDISPATCH GetInterior(); - VARIANT GetItem(const VARIANT& RowIndex, const VARIANT& ColumnIndex); - void SetItem(const VARIANT& RowIndex, const VARIANT& ColumnIndex, const VARIANT& newValue); - void Justify(); - VARIANT GetLeft(); - long GetListHeaderRows(); - void ListNames(); - long GetLocationInTable(); - VARIANT GetLocked(); - void SetLocked(const VARIANT& newValue); - void Merge(const VARIANT& Across); - void UnMerge(); - LPDISPATCH GetMergeArea(); - VARIANT GetMergeCells(); - void SetMergeCells(const VARIANT& newValue); - VARIANT GetName(); - void SetName(const VARIANT& newValue); - void NavigateArrow(const VARIANT& TowardPrecedent, const VARIANT& ArrowNumber, const VARIANT& LinkNumber); - LPUNKNOWN Get_NewEnum(); - LPDISPATCH GetNext(); - CString NoteText(const VARIANT& Text, const VARIANT& Start, const VARIANT& Length); - VARIANT GetNumberFormat(); - void SetNumberFormat(const VARIANT& newValue); - VARIANT GetNumberFormatLocal(); - void SetNumberFormatLocal(const VARIANT& newValue); - LPDISPATCH GetOffset(const VARIANT& RowOffset, const VARIANT& ColumnOffset); - VARIANT GetOrientation(); - void SetOrientation(const VARIANT& newValue); - VARIANT GetOutlineLevel(); - void SetOutlineLevel(const VARIANT& newValue); - long GetPageBreak(); - void SetPageBreak(long nNewValue); - void Parse(const VARIANT& ParseLine, const VARIANT& Destination); - void PasteSpecial(long Paste, long Operation, const VARIANT& SkipBlanks, const VARIANT& Transpose); - LPDISPATCH GetPivotField(); - LPDISPATCH GetPivotItem(); - LPDISPATCH GetPivotTable(); - LPDISPATCH GetPrecedents(); - VARIANT GetPrefixCharacter(); - LPDISPATCH GetPrevious(); - void PrintOut(const VARIANT& From, const VARIANT& To, const VARIANT& Copies, const VARIANT& Preview, const VARIANT& ActivePrinter, const VARIANT& PrintToFile, const VARIANT& Collate); - void PrintPreview(const VARIANT& EnableChanges); - LPDISPATCH GetQueryTable(); - LPDISPATCH GetRange(const VARIANT& Cell1, const VARIANT& Cell2); - void RemoveSubtotal(); - BOOL Replace(const VARIANT& What, const VARIANT& Replacement, const VARIANT& LookAt, const VARIANT& SearchOrder, const VARIANT& MatchCase, const VARIANT& MatchByte, const VARIANT& MatchControlCharacters, const VARIANT& MatchDiacritics, - const VARIANT& MatchKashida, const VARIANT& MatchAlefHamza); - LPDISPATCH GetResize(const VARIANT& RowSize, const VARIANT& ColumnSize); - long GetRow(); - LPDISPATCH RowDifferences(const VARIANT& Comparison); - VARIANT GetRowHeight(); - void SetRowHeight(const VARIANT& newValue); - LPDISPATCH GetRows(); - VARIANT Run(const VARIANT& Arg1, const VARIANT& Arg2, const VARIANT& Arg3, const VARIANT& Arg4, const VARIANT& Arg5, const VARIANT& Arg6, const VARIANT& Arg7, const VARIANT& Arg8, const VARIANT& Arg9, const VARIANT& Arg10, - const VARIANT& Arg11, const VARIANT& Arg12, const VARIANT& Arg13, const VARIANT& Arg14, const VARIANT& Arg15, const VARIANT& Arg16, const VARIANT& Arg17, const VARIANT& Arg18, const VARIANT& Arg19, const VARIANT& Arg20, - const VARIANT& Arg21, const VARIANT& Arg22, const VARIANT& Arg23, const VARIANT& Arg24, const VARIANT& Arg25, const VARIANT& Arg26, const VARIANT& Arg27, const VARIANT& Arg28, const VARIANT& Arg29, const VARIANT& Arg30); - void Select(); - void Show(); - void ShowDependents(const VARIANT& Remove); - VARIANT GetShowDetail(); - void SetShowDetail(const VARIANT& newValue); - void ShowErrors(); - void ShowPrecedents(const VARIANT& Remove); - VARIANT GetShrinkToFit(); - void SetShrinkToFit(const VARIANT& newValue); - void Sort(const VARIANT& Key1, long Order1, const VARIANT& Key2, const VARIANT& Type, long Order2, const VARIANT& Key3, long Order3, long Header, const VARIANT& OrderCustom, const VARIANT& MatchCase, long Orientation, long SortMethod, - const VARIANT& IgnoreControlCharacters, const VARIANT& IgnoreDiacritics, const VARIANT& IgnoreKashida); - void SortSpecial(long SortMethod, const VARIANT& Key1, long Order1, const VARIANT& Type, const VARIANT& Key2, long Order2, const VARIANT& Key3, long Order3, long Header, const VARIANT& OrderCustom, const VARIANT& MatchCase, long Orientation); - LPDISPATCH GetSoundNote(); - LPDISPATCH SpecialCells(long Type, const VARIANT& Value); - VARIANT GetStyle(); - void SetStyle(const VARIANT& newValue); - void SubscribeTo(LPCTSTR Edition, long Format); - void Subtotal(long GroupBy, long Function, const VARIANT& TotalList, const VARIANT& Replace, const VARIANT& PageBreaks, long SummaryBelowData); - VARIANT GetSummary(); - void Table(const VARIANT& RowInput, const VARIANT& ColumnInput); - VARIANT GetText(); - void TextToColumns(const VARIANT& Destination, long DataType, long TextQualifier, const VARIANT& ConsecutiveDelimiter, const VARIANT& Tab, const VARIANT& Semicolon, const VARIANT& Comma, const VARIANT& Space, const VARIANT& Other, - const VARIANT& OtherChar, const VARIANT& FieldInfo); - VARIANT GetTop(); - void Ungroup(); - VARIANT GetUseStandardHeight(); - void SetUseStandardHeight(const VARIANT& newValue); - VARIANT GetUseStandardWidth(); - void SetUseStandardWidth(const VARIANT& newValue); - LPDISPATCH GetValidation(); - VARIANT GetValue(); - void SetValue(const VARIANT& newValue); - VARIANT GetValue2(); - void SetValue2(const VARIANT& newValue); - VARIANT GetVerticalAlignment(); - void SetVerticalAlignment(const VARIANT& newValue); - VARIANT GetWidth(); - LPDISPATCH GetWorksheet(); - VARIANT GetWrapText(); - void SetWrapText(const VARIANT& newValue); - LPDISPATCH AddComment(const VARIANT& Text); - LPDISPATCH GetComment(); - void ClearComments(); - LPDISPATCH GetPhonetic(); - LPDISPATCH GetFormatConditions(); - long GetReadingOrder(); - void SetReadingOrder(long nNewValue); - LPDISPATCH GetHyperlinks(); -}; -///////////////////////////////////////////////////////////////////////////// -// Border wrapper class - -class Border : public COleDispatchDriver -{ -public: - Border() {} // Calls COleDispatchDriver default constructor - Border(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - Border(const Border& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - VARIANT GetColor(); - void SetColor(const VARIANT& newValue); - VARIANT GetColorIndex(); - void SetColorIndex(const VARIANT& newValue); - VARIANT GetLineStyle(); - void SetLineStyle(const VARIANT& newValue); - VARIANT GetWeight(); - void SetWeight(const VARIANT& newValue); -}; -///////////////////////////////////////////////////////////////////////////// -// Borders wrapper class - -class Borders : public COleDispatchDriver -{ -public: - Borders() {} // Calls COleDispatchDriver default constructor - Borders(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - Borders(const Borders& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - VARIANT GetColor(); - void SetColor(const VARIANT& newValue); - VARIANT GetColorIndex(); - void SetColorIndex(const VARIANT& newValue); - long GetCount(); - LPDISPATCH GetItem(long Index); - VARIANT GetLineStyle(); - void SetLineStyle(const VARIANT& newValue); - LPUNKNOWN Get_NewEnum(); - VARIANT GetValue(); - void SetValue(const VARIANT& newValue); - VARIANT GetWeight(); - void SetWeight(const VARIANT& newValue); - LPDISPATCH Get_Default(long Index); -}; -///////////////////////////////////////////////////////////////////////////// -// Interior wrapper class - -class Interior : public COleDispatchDriver -{ -public: - Interior() {} // Calls COleDispatchDriver default constructor - Interior(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} - Interior(const Interior& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} - -// Attributes -public: - -// Operations -public: - LPDISPATCH GetApplication(); - long GetCreator(); - LPDISPATCH GetParent(); - VARIANT GetColor(); - void SetColor(const VARIANT& newValue); - VARIANT GetColorIndex(); - void SetColorIndex(const VARIANT& newValue); - VARIANT GetInvertIfNegative(); - void SetInvertIfNegative(const VARIANT& newValue); - VARIANT GetPattern(); - void SetPattern(const VARIANT& newValue); - VARIANT GetPatternColor(); - void SetPatternColor(const VARIANT& newValue); - VARIANT GetPatternColorIndex(); - void SetPatternColorIndex(const VARIANT& newValue); -}; diff --git a/Generals/Code/Tools/Babylon/expimp.cpp b/Generals/Code/Tools/Babylon/expimp.cpp deleted file mode 100644 index 83f3b6e128..0000000000 --- a/Generals/Code/Tools/Babylon/expimp.cpp +++ /dev/null @@ -1,1673 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// expimp.cpp -// - -#include "StdAfx.h" -#include "TransDB.h" -#include "XLStuff.h" -#include "noxstringDlg.h" -#include "VerifyTextDlg.h" -#include "noxstring.h" -#include "expimp.h" -#include "direct.h" -#include "fileops.h" -#include "olestring.h" - -static char buffer[100*1024]; -static char buffer2[100*1024]; -static OLECHAR olebuf[100*1024]; -static OLECHAR olebuf2[100*1024]; -static OLECHAR oletrans[100*1024]; - -static CNoxstringDlg *progress_dlg; -static int progress_count; - -static void progress_cb ( void ) -{ - progress_count ++; - - if ( progress_dlg ) - { - progress_dlg->SetProgress ( progress_count ); - } -} - -static FILE *cb_file; - -static void print_to_file ( const char *text ) -{ - - fprintf ( cb_file, "\t\t\tString %s\n", text ); - -} - -static void reverseWord ( OLECHAR *fp, OLECHAR *lp ) -{ - int first = TRUE; - OLECHAR f, l; - - while ( TRUE ) - { - if ( fp >= lp ) - { - return; - } - - f = *fp; - l = *lp; - - if ( first ) - { - if ( f >= 'A' && f <= 'Z' ) - { - if ( l >= 'a' && l <= 'z' ) - { - f = (f - 'A') + 'a'; - l = (l - 'a') + 'A'; - } - } - - first = FALSE; - } - - *lp-- = f; - *fp++ = l; - - } - -} - - -static void translateCopy( OLECHAR *outbuf, OLECHAR *inbuf ) -{ - int slash = FALSE; - - { - static OLECHAR buffer[100*1024]; - OLECHAR *firstLetter = NULL, *lastLetter; - OLECHAR *b = buffer; - int formatWord = FALSE; - OLECHAR ch; - - while ( (ch = *inbuf++)) - { - if ( ! (( ch >= 'a' && ch <= 'z') || ( ch >= 'A' && ch <= 'Z' ))) - { - if ( firstLetter ) - { - if ( !formatWord ) - { - lastLetter = b-1; - reverseWord ( firstLetter, lastLetter ); - } - firstLetter = NULL; - formatWord = FALSE; - } - *b++ = ch; - if ( ch == '\\' ) - { - *b++ = *inbuf++; - } - if ( ch == '%' ) - { - while ( (ch = *inbuf++) && !IsFormatTypeChar ( ch ) && ch != '%') - { - *b++ = ch; - } - *b++ = ch; - } - } - else - { - if ( !firstLetter ) - { - firstLetter = b; - } - - *b++ = ch; - - } - } - - if ( firstLetter ) - { - lastLetter = b-1; - reverseWord ( firstLetter, lastLetter ); - } - - *b++ = 0; - inbuf = buffer; - - } - - - - while( *inbuf != '\0' ) - { - - *outbuf++ = *inbuf++; - } - *outbuf= 0; -} - - -static void writeLabel ( NoxLabel *label, int row ) -{ - PutCell ( row, CELL_LABEL, label->Name (), 0); - wcscpy ( olebuf, label->Comment()); - EncodeFormat ( olebuf ); - PutCell ( row, CELL_COMMENT, olebuf, 0); - wcscpy ( olebuf, label->Context()); - EncodeFormat ( olebuf ); - PutCell ( row, CELL_CONTEXT, olebuf, 0); - wcscpy ( olebuf, label->Speaker()); - EncodeFormat ( olebuf ); - PutCell ( row, CELL_SPEAKER, olebuf, 0); - wcscpy ( olebuf, label->Listener()); - EncodeFormat ( olebuf ); - PutCell ( row, CELL_LISTENER, olebuf , 0); -} - -static void writeText ( NoxText *text, int row ) -{ - NoxLabel *label = text->Label (); - int maxlen = label->MaxLen (); - OLECHAR buffer[100]; - - if ( !maxlen ) - { - maxlen = 10000; - } - - wcscpy ( olebuf, text->Get()); - EncodeFormat ( olebuf ); - PutCell ( row, CELL_ENGLISH, olebuf , 0); - PutCell ( row, CELL_MAXLEN, NULL , maxlen ); - - swprintf ( buffer, L"=LEN(%c%d)",'A' + CELL_LOCALIZED -1, row ); - PutCell ( row, CELL_STRLEN, buffer , 0); - swprintf ( buffer, L"=IF(%c%d>%c%d,\"Too long!\",\" \")", 'A' + CELL_STRLEN -1, row, 'A' + CELL_MAXLEN -1, row ); - PutCell ( row, CELL_LENCHECK ,buffer , 0); - PutCell ( row, CELL_REVISION , 0, text->Revision ()); - PutCell ( row, CELL_STRINGID , 0, text->ID ()); - - writeLabel ( label, row ); -} - -static int export_trans ( TransDB *db, LangID langid, TROPTIONS *options, void (*cb) (void ), int write ) -{ - NoxLabel *label; - NoxText *text; - Translation *trans; - ListSearch sh_label, sh_text; - int count = 0; - int limit = FALSE; - int all = TRUE; - int row; - LANGINFO *linfo; - - linfo = GetLangInfo ( langid ); - - if ( options->filter == TR_SAMPLE ) - { - limit = TRUE; - } - else if ( options->filter == TR_CHANGES ) - { - all = FALSE; - } - - if ( write ) - { - OLECHAR buffer[100]; - - swprintf ( buffer, L"%S", GetLangName ( langid )); - PutCell ( ROW_LANGUAGE, COLUMN_LANGUAGE,buffer,0); - - swprintf ( buffer, L"%S Translation", GetLangName ( langid )); - PutCell ( 2, CELL_LOCALIZED,buffer,0); - } - - row = 3; - label = db->FirstLabel ( sh_label ); - - while ( label ) - { - int label_written = FALSE; - text = label->FirstText ( sh_text ); - - while ( text ) - { - int do_export; - int bad_format = FALSE; - int too_long = FALSE; - - trans = text->GetTranslation ( langid ); - - if ( options->filter == TR_UNSENT ) - { - do_export = !text->IsSent (); - } - else if ( options->filter == TR_NONDIALOG ) - { - do_export = !text->IsDialog (); - } - else if ( options->filter == TR_UNVERIFIED ) - { - do_export = text->IsDialog() && text->DialogIsPresent( DialogPath, langid) && !text->DialogIsValid( DialogPath, langid); - } - else if ( options->filter == TR_MISSING_DIALOG ) - { - do_export = text->IsDialog() && !text->DialogIsPresent( DialogPath, langid); - } - else if ( options->filter == TR_DIALOG ) - { - do_export = text->IsDialog (); - } - else - { - if ( ! (do_export = all) ) - { - if ( !trans ) - { - do_export = TRUE; - } - else - { - if ( text->Revision () > trans->Revision ()) - { - do_export = TRUE; - } - else if ( trans->TooLong ( label->MaxLen ()) ) - { - do_export = TRUE; - too_long = TRUE; - } - else if ( !trans->ValidateFormat ( text ) ) - { - do_export = TRUE; - bad_format = TRUE; - } - } - } - } - - if ( do_export && text->Len () ) - { - count++; - if ( cb ) - { - cb (); - } - - if ( write ) - { - static OLECHAR buffer[100*1024]; - - if ( !label_written ) - { - // write out the lable - //PutSeparator ( row++ ); - //writeLabel ( label, row ); - label_written = TRUE; - } - - // write out text - writeText ( text, row ); - if ( text->IsDialog ()) - { - swprintf ( buffer, L"%s%S.wav", text->Wave (), linfo->character ); - wcsupr ( buffer ); - PutCell ( row, CELL_WAVEFILE , buffer, 0); - } - - { - Translation *trans = text->GetTranslation ( langid ); - - if ( langid == LANGID_JABBER || (trans && ( options->include_translations || too_long || bad_format ))) - { - - if ( langid == LANGID_JABBER ) - { - translateCopy ( olebuf, text->Get() ); - } - else - { - wcscpy ( olebuf, trans->Get()); - } - - EncodeFormat ( olebuf ); - PutCell ( row, CELL_LOCALIZED, olebuf, 0); - if ( bad_format || too_long) - { - wcscpy ( olebuf, L"ERROR: " ); - if ( too_long ) - { - wcscat ( olebuf, L"too long" ); - if ( bad_format ) - { - wcscat ( olebuf, L"and " ); - } - } - - if ( bad_format ) - { - wcscat ( olebuf, L"bad format" ); - } - - PutCell ( row, CELL_COMMENT, olebuf , 0); - } - } - } - row++; - } - } - - text = label->NextText ( sh_text ); - } - - if ( limit && count > 50 ) - { - break; - } - - label = db->NextLabel ( sh_label ); - } - - if ( write ) - { - PutCell ( row, CELL_STRINGID, NULL, -1 ); - PutCell ( ROW_COUNT, COLUMN_COUNT, NULL, count ); - } - - return count; -} - - -int ExportTranslations ( TransDB *db, const char *filename, LangID langid, TROPTIONS *options, CNoxstringDlg *dlg ) -{ - int exports ; - exports = export_trans ( db, langid, options, NULL, FALSE ); - - if ( !exports ) - { - if ( dlg ) - { - AfxMessageBox ( "Nothing to export." ); - dlg->Ready (); - } - - return 0; - } - - if ( (progress_dlg = dlg) ) - { - const char *format; - dlg->InitProgress ( exports ); - - dlg->Log (""); - - switch (options->filter ) - { - case TR_ALL: - format = "Exporting all strings"; - break; - case TR_CHANGES: - format = "Exporting all strings that require %s translation"; - break; - case TR_SAMPLE: - format = "Exporting a sample %s translation file"; - break; - case TR_DIALOG: - format = "Exporting dialog only %s translation file"; - break; - case TR_NONDIALOG: - format = "Exporting non-dialog %s translation file"; - break; - case TR_UNVERIFIED: - format = "Exporting all unverified %s dialog"; - break; - case TR_MISSING_DIALOG: - format = "Exporting all missing %s dialog"; - break; - - - default: - format = "Undefined switch"; - break; - - - } - strcpy ( buffer2, format ); - if ( options->include_comments && options->include_translations ) - { - strcat ( buffer2, " with current %s translations and translator comments" ); - } - else if ( options->include_comments ) - { - strcat ( buffer2, " with %s translator comments" ); - } - else if ( options->include_translations ) - { - strcat ( buffer2, " with current %s translations" ); - } - strcat ( buffer2, "..." ); - sprintf ( buffer, buffer2, GetLangName ( langid ), GetLangName ( langid ) ); - dlg->Status ( buffer ); - } - - _getcwd ( buffer, sizeof ( buffer ) -1 ); - - strcat ( buffer, "\\babylon.xlt" ); - - if ( !FileExists ( buffer ) ) - { - if ( dlg ) - { - dlg->Log ("FAILED", SAME_LINE ); - sprintf ( buffer2, "Template file \"%s\" is missing. Cannot export.", buffer ); - AfxMessageBox ( buffer2 ); - dlg->Log ( buffer2 ); - dlg->Ready(); - } - return -1; - } - - progress_count = 0; - exports = -1; - - if ( NewWorkBook ( buffer ) ) - { - if ( (exports = export_trans ( db, langid, options, progress_cb, TRUE )) != -1 ) - { - if ( SaveWorkBook ( filename, TRUE ) ) - { - if ( dlg ) - { - dlg->Log ("DONE", SAME_LINE ); - } - } - else - { - if ( dlg ) - { - dlg->Log ("FAILED", SAME_LINE ); - sprintf ( buffer2, "Failed to save export!"); - AfxMessageBox ( buffer2 ); - dlg->Log ( buffer2 ); - } - exports = -1; - } - } - CloseWorkBook ( ); - } - else - { - if ( dlg ) - { - dlg->Log ("FAILED", SAME_LINE ); - sprintf ( buffer2, "Failed to create new work book. File \"%s\" may be corrupt", buffer ); - AfxMessageBox ( buffer2 ); - dlg->Log ( buffer2 ); - } - } - - if ( dlg ) - { - dlg->Ready(); - } - - return exports; -} - - -static int import_trans ( TransDB *db, LangID langid, void (*cb) ( void ), CNoxstringDlg *dlg ) -{ - int row = 3; - int id; - int count = 0; - int new_count = 0; - int changes_count = 0; - int missing_count = 0; - int mismatch_count = 0; - int stale_count = 0; - int first_mismatch = TRUE; - int bad_id = FALSE; - int error_count = 0; - int revision; - - while ( (id = GetInt ( row, CELL_STRINGID )) != -1) - { - if ( id == 0 ) - { - goto skip; - } - - NoxText *text; - - if ( (text = db->FindText ( id )) == NULL ) - { - // string is no longer in database - stale_count++; - goto next; - } - - revision = GetInt ( row, CELL_REVISION ); - - if ( text->Revision() > revision ) - { - // old translation - stale_count++; - goto next; - } - - if ( text->Revision() < revision ) - { - if ( dlg ) - { - sprintf ( buffer, "ERROR: expecting revision %d for string ID %d but found revision %d. Possible bad ID!", text->Revision (), id, revision ); - dlg->Log ( buffer ); - } - error_count++; - goto next; - } - - // first see if there is any translation there - GetString ( row, CELL_LOCALIZED, oletrans ); - DecodeFormat ( oletrans ); - - if ( !oletrans[0] ) - { - missing_count++; - goto next; - } - - // verify that the translated engish is the same as the current english - GetString ( row, CELL_ENGLISH, olebuf ); - DecodeFormat ( olebuf ); - - if ( wcscmp ( text->Get(), olebuf ) ) - { - // they are two possible reasons for the text to mismatch - // 1. text was modified but not re-translated - // 2. the IDs are wrong - // - // to check for the first case we search for the label in the xl file - // and make sure it is the same. If not then we have problems - - int nrow = row; - - olebuf2[0] = 0; - while ( nrow > 0 ) - { - GetString ( nrow, CELL_LABEL, olebuf2 ); - if ( olebuf2[0] ) - { - break; - } - nrow--; - } - - - if ( !olebuf2[0] || wcscmp ( text->Label ()->Name(), olebuf2)) - { - sprintf ( buffer, "%S", olebuf ); - CVerifyTextDlg dlg(buffer, text->GetSB()); - - // didnt find label or label doesn't match - // It is possible that the xl was resorted so ask user to do a visual confirmation - - bad_id = dlg.DoModal ()==IDNO; - } - else if ( text->Label()->FindText( olebuf )) - { - // we did find the label but text other than the current ID sourced text matches with the import text - // this means the ID is definitely wrong - bad_id = TRUE; - } - else - { - bad_id = FALSE; - } - - if ( bad_id ) - { - goto done; - } - - } - - // ok import the translation - - Translation *trans; - - if ( ! (trans = text->GetTranslation ( langid ))) - { - new_count++; - - trans = new Translation (); - trans->SetLangID ( langid ); - text->AddTranslation ( trans ); - } - - - if ( trans->Revision () == revision && !wcscmp ( trans->Get (), oletrans )) - { - // already up to date - goto next; - } - - trans->Set ( oletrans ); - trans->WaveInfo.SetValid ( FALSE ); - trans->SetRevision ( revision ); - changes_count++; - - - next: - count++; - - if ( cb ) - { - cb (); - } - - skip: - row++; - } - -done: - - if ( dlg ) - { - sprintf ( buffer, "Total found : %d", count ); - dlg->Log ( buffer ); - - { - sprintf ( buffer, "New : %d", new_count); - dlg->Log ( buffer ); - } - { - sprintf ( buffer, "Updates : %d", (changes_count - new_count)); - dlg->Log ( buffer ); - } - if ( missing_count ) - { - sprintf ( buffer, "Missing : %d", missing_count ); - dlg->Log ( buffer ); - } - if ( stale_count ) - { - sprintf ( buffer, "Unmatched : %d", stale_count); - dlg->Log ( buffer ); - } - - } - - if ( bad_id ) - { - if ( dlg ) - { - sprintf ( buffer, "Aborting import: BAD IDs"); - dlg->Log ( buffer ); - } - - AfxMessageBox ("The imported translation file has bad string IDs! Fix the string IDs and re-import" ); - } - return count; -} - -static int update_sent_trans ( TransDB *db, LangID langid, void (*cb) ( void ), CNoxstringDlg *dlg ) -{ - int row = 3; - int id; - int count = 0; - int new_count = 0; - int matched = 0; - int unmatched = 0; - int changed = 0; - int first_mismatch = TRUE; - int bad_id = FALSE; - int error_count = 0; - int revision; - - while ( (id = GetInt ( row, CELL_STRINGID )) != -1) - { - if ( id == 0 ) - { - goto skip; - } - - NoxText *text; - - if ( (text = db->FindText ( id )) == NULL ) - { - // string is no longer in database - unmatched++; - goto next; - } - - revision = GetInt ( row, CELL_REVISION ); - - if ( text->Revision() > revision ) - { - // old translation - changed++; - goto next; - } - - if ( text->Revision() < revision ) - { - if ( dlg ) - { - sprintf ( buffer, "ERROR: expecting revision %d for string ID %d but found revision %d. Possible bad ID!", text->Revision (), id, revision ); - dlg->Log ( buffer ); - } - error_count++; - goto next; - } - - - // verify that the translated engish is the same as the current english - GetString ( row, CELL_ENGLISH, olebuf ); - DecodeFormat ( olebuf ); - - if ( wcscmp ( text->Get(), olebuf ) ) - { - // they are two possible reasons for the text to mismatch - // 1. text was modified but not re-translated - // 2. the IDs are wrong - // - // to check for the first case we search for the label in the xl file - // and make sure it is the same. If not then we have problems - - int nrow = row; - - olebuf2[0] = 0; - while ( nrow > 0 ) - { - GetString ( nrow, CELL_LABEL, olebuf2 ); - if ( olebuf2[0] ) - { - break; - } - nrow--; - } - - - if ( !olebuf2[0] || wcscmp ( text->Label ()->Name(), olebuf2)) - { - sprintf ( buffer, "%S", olebuf ); - CVerifyTextDlg dlg(buffer, text->GetSB()); - - // didnt find label or label doesn't match - // It is possible that the xl was resorted so ask user to do a visual confirmation - - bad_id = dlg.DoModal ()==IDNO; - } - else if ( text->Label()->FindText( olebuf )) - { - // we did find the label but text other than the current ID sourced text matches with the import text - // this means the ID is definitely wrong - bad_id = TRUE; - } - else - { - bad_id = FALSE; - } - - if ( bad_id ) - { - goto done; - } - - } - else - { - // text is still the same - text->Sent ( TRUE ); - matched++; - - } - - next: - count++; - - if ( cb ) - { - cb (); - } - - skip: - row++; - } - -done: - - if ( dlg ) - { - sprintf ( buffer, "Total found : %d", count ); - dlg->Log ( buffer ); - - { - sprintf ( buffer, "Matched : %d", matched); - dlg->Log ( buffer ); - } - { - sprintf ( buffer, "Unmatched : %d", unmatched); - dlg->Log ( buffer ); - } - - if ( changed ) - { - sprintf ( buffer, "changed : %d", changed); - dlg->Log ( buffer ); - } - - } - - if ( bad_id ) - { - if ( dlg ) - { - sprintf ( buffer, "Aborting import: BAD IDs"); - dlg->Log ( buffer ); - } - - AfxMessageBox ("The imported translation file has bad string IDs! Fix the string IDs and re-import" ); - } - return count; -} - -int ImportTranslations ( TransDB *db, const char *filename, CNoxstringDlg *dlg ) -{ - int imports = -1; - - progress_dlg = dlg; - if ( dlg ) - { - dlg->Log (""); - sprintf ( buffer, "Importing \"%s\"...", filename ); - dlg->Status ( buffer ); - } - - if ( OpenWorkBook ( filename ) ) - { - int num_strings; - LANGINFO *info; - - num_strings = GetInt ( ROW_COUNT, COLUMN_COUNT ); - GetString ( ROW_LANGUAGE, COLUMN_LANGUAGE, olebuf ); - sprintf ( buffer, "%S", olebuf ); - info = GetLangInfo ( buffer ); - - if ( !info ) - { - if ( dlg ) - { - AfxMessageBox ( "Import file is of an unknown language or is not a translation file" ); - dlg->Log ( "FAILED", SAME_LINE ); - dlg->Ready(); - } - CloseWorkBook (); - return -1; - } - - - if ( dlg ) - { - dlg->InitProgress ( num_strings ); - progress_count = 0; - sprintf ( buffer, "...%s", info->name ); - dlg->Log ( buffer, SAME_LINE ); - } - - imports = import_trans ( db, info->langid, progress_cb, dlg ); - - CloseWorkBook ( ); - } - else - { - if ( dlg ) - { - dlg->Log ("FAILED", SAME_LINE ); - sprintf ( buffer2, "Failed to open \"%s\"", buffer ); - AfxMessageBox ( buffer2 ); - dlg->Log ( buffer2 ); - } - } - - if ( dlg ) - { - dlg->Ready(); - } - - return imports; -} - -static int generate_noxstr ( TransDB *db, const char *filename, LangID langid, GNOPTIONS *options ) -{ - int ok = FALSE; - FILE *file; - - if ( ! ( file = fopen ( filename, "wt" ) )) - { - goto error; - } - - fprintf ( file, "// Generated by %s\n", AppTitle ); - fprintf ( file, "// Generated on %s %s\n\n\n", __DATE__, __TIME__ ); - - { - NoxLabel *label; - NoxText *text; - Translation *trans; - ListSearch sh_label, sh_text; - - label = db->FirstLabel ( sh_label ); - - while ( label ) - { - text = label->FirstText ( sh_text ); - - fprintf ( file, "\n\n%s\n", label->NameSB ()); - - while ( text ) - { - const char *string; - - trans = text->GetTranslation ( langid ); - - if ( !trans ) - { - if ( langid == LANGID_US ) - { - string = text->GetSB (); - } - else - { - if ( text->Len ()) - { - if ( options->untranslated == GN_USEIDS ) - { - string = buffer2; - sprintf (buffer2, "%d", text->ID ()); - } - else - { - string = text->GetSB(); - } - } - else - { - string = ""; - } - } - } - else - { - string = trans->GetSB (); - } - - if ( text->Len() == 0 ) - { - string = ""; - } - - fprintf ( file, "\"%s\" %s\n", string, text->WaveSB() ); - text = label->NextText ( sh_text ); - } - - fprintf ( file, "END\n" ); - label = db->NextLabel ( sh_label ); - } - - ok = TRUE; - } -error: - - if ( file ) - { - fclose ( file ); - } - - return ok; -} - -static int writeCSFLabel ( FILE *file, NoxLabel *label ) -{ - int id = CSF_LABEL; - int len = strlen ( label->NameSB() ); - int strings = label->NumStrings (); - - if ( fwrite ( &id, sizeof ( int ), 1, file ) != 1 ) - { - return FALSE; - } - - if ( fwrite ( &strings, sizeof ( int ), 1, file ) != 1 ) - { - return FALSE; - } - - if ( fwrite ( &len, sizeof ( int ), 1, file ) != 1 ) - { - return FALSE; - } - - if ( !len ) - { - return FALSE; - } - - if ( fwrite ( label->NameSB(), len, 1, file ) != 1 ) - { - return FALSE; - } - - return TRUE; -} - -static int writeCSFString ( FILE *file, const OLECHAR *string, char *wave, LANGINFO *linfo ) -{ - int id = CSF_STRING; - int len ; - int wlen = strlen ( wave ); - - if ( wlen ) - { - id = CSF_STRINGWITHWAVE; - } - - wcscpy ( olebuf, string ); - StripSpaces ( olebuf ); - ConvertMetaChars ( olebuf ); - len = wcslen ( olebuf ); - - { - OLECHAR *ptr = olebuf; - - while ( *ptr) - { - *ptr = ~*ptr++; - } - - } - - if ( fwrite ( &id, sizeof ( int ), 1, file ) != 1 ) - { - return FALSE; - } - - if ( fwrite ( &len, sizeof ( int ), 1, file ) != 1 ) - { - return FALSE; - } - - if ( len ) - { - if ( fwrite ( olebuf, len*sizeof(OLECHAR), 1, file ) != 1 ) - { - return FALSE; - } - } - if ( wlen ) - { - wlen++; - if ( fwrite ( &wlen, sizeof ( int ), 1, file ) != 1 ) - { - return FALSE; - } - - if ( fwrite ( wave, wlen-1, 1, file ) != 1 ) - { - return FALSE; - } - if ( fwrite ( linfo->character, 1, 1, file ) != 1 ) - { - return FALSE; - } - } - return TRUE; -} - -static int generate_csf ( TransDB *db, const char *filename, LangID langid, GNOPTIONS *options ) -{ - CSF_HEADER header; - int header_size; - int ok = FALSE; - FILE *file; - LANGINFO *linfo = GetLangInfo ( langid); - - if ( ! ( file = fopen ( filename, "w+b" ) )) - { - goto error; - } - - header.id = CSF_ID; - header.version = CSF_VERSION; - header.skip = 0; - header.num_labels = 0; - header.num_strings = 0; - header.langid = langid; - header_size = sizeof ( header ); - - fseek ( file, header_size, SEEK_SET ); - - { - NoxLabel *label; - NoxText *text; - Translation *trans; - ListSearch sh_label, sh_text; - - label = db->FirstLabel ( sh_label ); - - while ( label ) - { - text = label->FirstText ( sh_text ); - - if ( !writeCSFLabel ( file, label ) ) - { - goto error; - } - header.num_labels++; - - while ( text ) - { - const OLECHAR *string; - - trans = text->GetTranslation ( langid ); - - if ( !trans ) - { - if ( langid == LANGID_US ) - { - string = text->Get (); - } - else - { - if ( text->Len ()) - { - if ( options->untranslated == GN_USEIDS ) - { - string = olebuf2; - swprintf (olebuf2, L"%d", text->ID ()); - } - else - { - string = text->Get(); - } - } - else - { - string = L""; - } - } - } - else - { - string = trans->Get (); - } - - if ( !writeCSFString ( file, string, text->WaveSB (), linfo ) ) - { - goto error; - } - header.num_strings ++; - - text = label->NextText ( sh_text ); - } - - label = db->NextLabel ( sh_label ); - } - - fseek ( file, 0, SEEK_SET ); - if ( fwrite ( &header, header_size, 1, file ) != 1 ) - { - goto error; - } - - fseek ( file, 0, SEEK_END ); - - ok = TRUE; - } - -error: - - if ( file ) - { - fclose ( file ); - } - - - return ok; -} - - -int GenerateGameFiles ( TransDB *db, const char *filepattern, GNOPTIONS *options, LangID *languages, CNoxstringDlg *dlg) -{ - static char filename[2*1024]; - LangID langid; - int count= 0 ; - int num; - - if ( dlg ) - { - LangID *temp = languages; - num = 0; - while ( *temp++ != LANGID_UNKNOWN ) - { - num++; - } - - dlg->Log ( "" ); - dlg->Status ( "Generating game files:" ); - dlg->InitProgress ( num ); - num = 0; - } - while ( (langid = *languages++) != LANGID_UNKNOWN ) - { - LANGINFO *info; - TRNREPORT trnreport; - DLGREPORT dlgreport; - int dlgwarning; - int trnwarning; - int done; - - info = GetLangInfo ( langid ); - - sprintf ( filename, "%s_%s.%s", filepattern, info->initials, options->format == GN_NOXSTR ? "str" : "csf" ); - strlwr ( filename ); - - if ( dlg ) - { - sprintf ( buffer, "Writing: %s - %s...", filename, GetLangName ( langid )); - dlg->Status ( buffer ); - dlgwarning = db->ReportDialog ( &dlgreport, langid ); - trnwarning = db->ReportTranslations ( &trnreport, langid ); - } - - - if ( options->format == GN_NOXSTR ) - { - done = generate_noxstr ( db, filename, langid, options ); - } - else - { - done = generate_csf ( db, filename, langid, options ); - } - - if ( done ) - { - count++; - if ( dlg ) - { - if ( trnwarning || dlgwarning ) - { - dlg->Log ( "WARNING", SAME_LINE ); - - if ( trnwarning ) - { - int missing; - - if ( (missing = trnreport.missing + trnreport.retranslate) ) - { - sprintf ( buffer, "%d translation%s missing", missing, missing > 1 ? "s are" : " is" ); - dlg->Log ( buffer ); - } - - if ( trnreport.too_big ) - { - sprintf ( buffer, "%d string%s too big", trnreport.too_big, trnreport.too_big > 1 ? "s are" : " is" ); - dlg->Log ( buffer ); - } - - if ( trnreport.bad_format ) - { - sprintf ( buffer, "%d translation%s bad format", trnreport.bad_format, trnreport.bad_format > 1 ? "s have a" : " has a" ); - dlg->Log ( buffer ); - } - } - - if ( dlgwarning ) - { - if ( dlgreport.missing ) - { - sprintf ( buffer, "%d dialog%s missing", dlgreport.missing, dlgreport.missing > 1 ? "s are" : " is" ); - dlg->Log ( buffer ); - } - - if ( dlgreport.unresolved ) - { - sprintf ( buffer, "%d dialog%s not verified", dlgreport.unresolved, dlgreport.unresolved> 1 ? "s are" : " is" ); - dlg->Log ( buffer ); - } - } - } - else - { - dlg->Log ( "OK", SAME_LINE ); - } - } - } - else - { - if ( dlg ) - { - dlg->Log ( "FAILED", SAME_LINE ); - } - } - - if ( dlg ) - { - dlg->SetProgress ( ++num ); - } - - } - - if ( dlg ) - { - dlg->Ready (); - } - return count; -} - -void ProcessWaves ( TransDB *db, const char *filename, CNoxstringDlg *dlg ) -{ - int imports = -1; - - progress_dlg = dlg; - - if ( dlg ) - { - dlg->Log (""); - sprintf ( buffer, "Processing wavefile \"%s\"...", filename ); - dlg->Status ( buffer ); - } - - if ( OpenWorkBook ( filename ) ) - { - int row = 1; - int last_row = 1; - int matches = 0; - int unmatched = 0; - FILE *file = NULL; - char *ptr; - - strcpy ( buffer, filename ); - - if ( (ptr = strchr ( buffer, '.' )) ) - { - *ptr = 0; - } - - strcat ( buffer, ".txt" ); - - if ( (file = fopen (buffer, "wt" ))) - { - - while ( row - last_row < 1000 ) - { - NoxText *text; - - GetString ( row, 'J' - 'A' + 1, olebuf ); - - wcslwr ( olebuf ); - - if ( wcsstr ( olebuf, L".wav" ) ) - { - last_row = row; - - fprintf ( file, "%S : ", olebuf ); - GetString ( row, 'K' -'A' + 1, olebuf ); - StripSpaces ( olebuf ); - - if ( (text = db->FindSubText ( olebuf ) )) - { - fprintf ( file, "%6d", text->LineNumber () ); - } - else - { - fprintf ( file, "??????" ); - } - - fprintf ( file, " - \"%S\"\n", olebuf ); - } - - row++; - } - - fclose ( file ); - } - - CloseWorkBook ( ); - } - else - { - if ( dlg ) - { - dlg->Log ("FAILED", SAME_LINE ); - sprintf ( buffer2, "Failed to open \"%s\"", buffer ); - AfxMessageBox ( buffer2 ); - dlg->Log ( buffer2 ); - } - } - - if ( dlg ) - { - dlg->Ready(); - } - -} - - -int GenerateReport ( TransDB *db, const char *filename, RPOPTIONS *options, LangID *languages, CNoxstringDlg *dlg) -{ - LangID langid; - int count= 0 ; - int num; - FILE *file = NULL; - - if ( dlg ) - { - LangID *temp = languages; - num = 0; - while ( *temp++ != LANGID_UNKNOWN ) - { - num++; - } - - dlg->Log ( "" ); - dlg->Status ( "Generating Report:" ); - dlg->InitProgress ( num ); - num = 0; - } - - if ( ! ( file = fopen ( filename, "wt" ))) - { - static char buffer[500]; - - sprintf ( buffer, "Unable to open file \"%s\".\n\nCannot create report!", filename); - AfxMessageBox ( buffer ); - - if ( dlg ) - { - dlg->Log ( "FAILED", SAME_LINE ); - dlg->Ready (); - } - return 0; - } - - cb_file = file; - - { - char date[50]; - char time[50]; - _strtime ( time ); - _strdate ( date ); - fprintf ( file, "Noxstring Report: %s %s\n", date, time); - } - - - - while ( (langid = *languages++) != LANGID_UNKNOWN ) - { - LANGINFO *info; - TRNREPORT tr_report; - DLGREPORT dlg_report; - - info = GetLangInfo ( langid ); - - fprintf ( file, "\n\n%s Status:\n", info->name ); - - - if ( options->translations ) - { - int count; - - count = db->ReportTranslations ( &tr_report, langid ); - - fprintf ( file, "\n\tText Summary: %s\n", info->name ); - fprintf ( file, "\t-------------\n\n"); - - fprintf ( file, "\t\tErrors: %d\n", tr_report.errors); - - if ( langid != LANGID_US ) - { - fprintf ( file, "\t\tNot translated: %d\n", tr_report.missing); - fprintf ( file, "\t\tRetranslation: %d\n", tr_report.retranslate); - fprintf ( file, "\t\tTranslated: %d\n", tr_report.translated ); - } - fprintf ( file, "\t\tTotal text: %d\n", tr_report.numstrings ); - - if ( count && count < options->limit ) - { - fprintf ( file, "\n\tText Details: %s\n", info->name); - fprintf ( file, "\t------------\n\n" ); - db->ReportTranslations ( &tr_report, langid, print_to_file ); - } - - } - - if ( options->dialog ) - { - int count; - - count = db->ReportDialog ( &dlg_report, langid ); - - fprintf ( file, "\n\tDialog Summary: %s\n", info->name ); - fprintf ( file, "\t-------------\n\n"); - - fprintf ( file, "\t\tMissing Audio: %d\n", dlg_report.missing); - fprintf ( file, "\t\tNot verified: %d\n", dlg_report.unresolved); - fprintf ( file, "\t\tVerified: %d\n", dlg_report.resolved); - fprintf ( file, "\t\tTotal dialog: %d\n", dlg_report.numdialog ); - - if ( count && count < options->limit ) - { - fprintf ( file, "\n\tDialog Details: %s\n", info->name ); - fprintf ( file, "\t------------\n\n" ); - db->ReportDialog ( &dlg_report, langid, print_to_file ); - } - } - - if ( dlg ) - { - dlg->SetProgress ( ++num ); - } - - } - - if ( dlg ) - { - dlg->Ready (); - } - - fclose ( file ); - - return count; -} - -int UpdateSentTranslations ( TransDB *db, const char *filename, CNoxstringDlg *dlg ) -{ - int imports = -1; - - progress_dlg = dlg; - if ( dlg ) - { - dlg->Log (""); - sprintf ( buffer, "Importing \"%s\"...", filename ); - dlg->Status ( buffer ); - } - - if ( OpenWorkBook ( filename ) ) - { - int num_strings; - LANGINFO *info; - - num_strings = GetInt ( ROW_COUNT, COLUMN_COUNT ); - GetString ( ROW_LANGUAGE, COLUMN_LANGUAGE, olebuf ); - sprintf ( buffer, "%S", olebuf ); - info = GetLangInfo ( buffer ); - - if ( !info ) - { - if ( dlg ) - { - AfxMessageBox ( "Import file is of an unknown language or is not a translation file" ); - dlg->Log ( "FAILED", SAME_LINE ); - dlg->Ready(); - } - CloseWorkBook (); - return -1; - } - - - if ( dlg ) - { - dlg->InitProgress ( num_strings ); - progress_count = 0; - sprintf ( buffer, "...%s", info->name ); - dlg->Log ( buffer, SAME_LINE ); - } - - imports = update_sent_trans ( db, info->langid, progress_cb, dlg ); - - CloseWorkBook ( ); - } - else - { - if ( dlg ) - { - dlg->Log ("FAILED", SAME_LINE ); - sprintf ( buffer2, "Failed to open \"%s\"", buffer ); - AfxMessageBox ( buffer2 ); - dlg->Log ( buffer2 ); - } - } - - if ( dlg ) - { - dlg->Ready(); - } - - return imports; -} - diff --git a/Generals/Code/Tools/Babylon/expimp.h b/Generals/Code/Tools/Babylon/expimp.h deleted file mode 100644 index cb652b48b3..0000000000 --- a/Generals/Code/Tools/Babylon/expimp.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// expimp.h -// - -#ifndef __EXPIMP_H -#define __EXPIMP_H - -#include "TransDB.h" -#include "noxstringDlg.h" - -typedef enum -{ - TR_ALL, - TR_CHANGES, - TR_DIALOG, - TR_NONDIALOG, - TR_SAMPLE, - TR_MISSING_DIALOG, - TR_UNVERIFIED, - TR_UNSENT -} TrFilter; - -typedef struct -{ - TrFilter filter; - int include_comments; - int include_translations; - -} TROPTIONS; - -typedef enum -{ - GN_UNICODE, - GN_NOXSTR, -} GnFormat; - -typedef enum -{ - GN_USEIDS, - GN_USEORIGINAL, -} GnUntranslated; - -typedef struct -{ - GnFormat format; // what file format to generate - GnUntranslated untranslated; // what to do with untranslated text - -} GNOPTIONS; - -typedef struct -{ - int translations; - int dialog; - int limit; - -} RPOPTIONS; - - -#define CSF_ID ( ('C'<<24) | ('S'<<16) | ('F'<<8) | (' ') ) -#define CSF_LABEL ( ('L'<<24) | ('B'<<16) | ('L'<<8) | (' ') ) -#define CSF_STRING ( ('S'<<24) | ('T'<<16) | ('R'<<8) | (' ') ) -#define CSF_STRINGWITHWAVE ( ('S'<<24) | ('T'<<16) | ('R'<<8) | ('W') ) -#define CSF_VERSION 3 - -typedef struct -{ - int id; - int version; - int num_labels; - int num_strings; - int skip; - -} CSF_HEADER_V1; - -typedef struct -{ - int id; - int version; - int num_labels; - int num_strings; - int skip; - int langid; - -} CSF_HEADER; - -int ExportTranslations ( TransDB *db, const char *filename, LangID langid, TROPTIONS *options, CNoxstringDlg *dlg = NULL ); -int ImportTranslations ( TransDB *db, const char *filename, CNoxstringDlg *dlg = NULL ); -int UpdateSentTranslations ( TransDB *db, const char *filename, CNoxstringDlg *dlg = NULL ); -int GenerateGameFiles ( TransDB *db, const char *filename, GNOPTIONS *option, LangID *languages, CNoxstringDlg *dlg = NULL ); -int GenerateReport ( TransDB *db, const char *filename, RPOPTIONS *options, LangID *languages, CNoxstringDlg *dlg = NULL ); -void ProcessWaves ( TransDB *db, const char *filename, CNoxstringDlg *dlg ); -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/fileops.cpp b/Generals/Code/Tools/Babylon/fileops.cpp deleted file mode 100644 index da7d57a50f..0000000000 --- a/Generals/Code/Tools/Babylon/fileops.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// fileops.cpp -// - -#include "StdAfx.h" -#include "fileops.h" - - - - -int FileExists ( const char *filename ) -{ - int fa = FileAttribs ( filename ); - - return ! ( (fa == FA_NOFILE) || (fa & FA_DIRECTORY )); -} - - -int FileAttribs ( const char *filename ) -{ - WIN32_FIND_DATA fi; - HANDLE handle; - int fa = FA_NOFILE; - - handle = FindFirstFile ( filename, &fi ); - - if ( handle != INVALID_HANDLE_VALUE ) - { - if ( fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) - { - fa |= FA_DIRECTORY; - } - if ( fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY ) - { - fa |= FA_READONLY; - } - else - { - fa |= FA_WRITEABLE; - } - - FindClose ( handle ); - } - - return fa; -} - -static void make_bk_name ( char *bkname, const char *filename ) -{ - const char *ext; - char *ext1; - - strcpy ( bkname, filename ); - - ext = strchr ( filename, '.' ); - ext1 = strchr ( bkname, '.' ); - - if ( ext ) - { - strcpy ( ext1, "_back_up" ); - strcat ( ext1, ext ); - } - else - { - strcat ( bkname, "_back_up" ); - } - -} - -void MakeBackupFile ( const char *filename ) -{ - char bkname[256]; - - make_bk_name ( bkname, filename ); - - CopyFile ( filename, bkname, FALSE ); - -} - -void RestoreBackupFile ( const char *filename ) -{ - char bkname[256]; - - make_bk_name ( bkname, filename ); - - if ( FileExists ( bkname )) - { - CopyFile ( bkname, filename, FALSE ); - } - -} \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/fileops.h b/Generals/Code/Tools/Babylon/fileops.h deleted file mode 100644 index a7fc9e7a71..0000000000 --- a/Generals/Code/Tools/Babylon/fileops.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// File IO support -// - -#ifndef __FILEOPS_H -#define __FILEOPS_H - -static const int FA_NOFILE = 0; -static const int FA_READONLY = 0x00000001; -static const int FA_DIRECTORY = 0x00000002; -static const int FA_WRITEABLE = 0x00000004; - - -int FileExists ( const char *filename ); -int FileAttribs ( const char *filename ); -void MakeBackupFile ( const char *filename ); -void RestoreBackupFile ( const char *filename ); - - -#endif // __FILEIO_H \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/iff.cpp b/Generals/Code/Tools/Babylon/iff.cpp deleted file mode 100644 index 0498b16180..0000000000 --- a/Generals/Code/Tools/Babylon/iff.cpp +++ /dev/null @@ -1,553 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#include "StdAfx.h" -#include "sys/stat.h" -#include "iff.h" -#include -#include -#include -#include - -#define IFF_RAWREAD(iff,data,size,label) {if ( IFF_rawread ( (iff), (data), (size)) != (size)) goto label;} - - -int IFF_rawread ( IFF_FILE *iff, void *buffer, int bytes ) -{ - if ( ! (iff->flags & mIFF_FILE_LOADED ) ) - { - return _read ( iff->fp, buffer, bytes ); - } - - if ( iff->file_size < (iff->file_pos + bytes) ) - { - bytes = iff->file_size - iff->file_pos; - } - memcpy ( buffer, &iff->mem_file[iff->file_pos], bytes ); - iff->file_pos += bytes; - return bytes; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_seek ( IFF_FILE *iff, int pos, int mode ) -{ - - if ( ! (iff->flags & mIFF_FILE_LOADED )) - { - return lseek ( iff->fp, pos, mode ); - } - - switch ( mode ) - { - case SEEK_CUR: - iff->file_pos += pos; - break; - case SEEK_END: - iff->file_pos = iff->file_size - pos; - break; - case SEEK_SET: - iff->file_pos = pos; - break; - } - - if ( iff->file_pos < 0 ) - { - iff->file_pos = 0; - } - else - { - if ( iff->file_pos > iff->file_size ) - { - iff->file_pos = iff->file_size; - } - } - - return iff->file_pos; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -IFF_FILE *IFF_Open ( const char *name ) -{ - IFF_FILE *iff = NULL; - - - if ( ! (iff = (IFF_FILE *) malloc ( sizeof (IFF_FILE)))) - { - goto error; - } - - iff->fp = -1; - memset ( iff, 0, sizeof ( IFF_FILE )); - - if ((iff->fp = open ( name, _O_BINARY | _O_RDONLY )) == -1 ) - { - goto error; - } - - - return iff; - -error: - - if (iff) - { - IFF_Close ( iff ); - } - - return NULL; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -IFF_FILE *IFF_Load ( const char *name ) -{ - IFF_FILE *iff = NULL; - - if ( ! (iff = (IFF_FILE *) malloc ( sizeof (IFF_FILE)))) - { - goto error; - } - - memset ( iff, 0, sizeof ( IFF_FILE )); - iff->fp = -1; - - if ((iff->fp = open ( name, _O_BINARY | _O_RDONLY )) == -1 ) - { - goto error; - } - - iff->file_size = lseek ( iff->fp, 0, SEEK_END ); - lseek ( iff->fp, 0, SEEK_SET ); - - if ( !(iff->mem_file = ( char *) malloc ( iff->file_size) ) ) - { - goto error; - } - - DO_READ ( iff->fp, iff->mem_file, iff->file_size, error ); - - iff->flags |= mIFF_FILE_LOADED; - - return iff; - -error: - - if (iff) - { - IFF_Close ( iff ); - } - - return NULL; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -void IFF_Reset ( IFF_FILE *iff ) -{ - IFF_seek ( iff, 0, SEEK_SET ); - iff->pad_form = 0; - iff->pad_chunk = 0; - iff->FormSize = 0; - iff->ChunkSize = 0; - iff->next_byte = 0; - iff->chunk_size_pos = 0; - iff->form_size_pos = 0; - -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -void IFF_goto_form_end ( IFF_FILE *iff ) -{ - - iff->FormSize += iff->pad_form; - iff->pad_form = 0; - if (iff->FormSize) - { - IFF_seek ( iff, iff->FormSize, SEEK_CUR ); - iff->next_byte += iff->FormSize; - iff->FormSize = 0; - iff->ChunkSize = 0; - } - -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -void IFF_goto_chunk_end ( IFF_FILE *iff ) -{ - - iff->ChunkSize += iff->pad_chunk; - iff->pad_chunk = 0; - if (iff->ChunkSize) - { - IFF_seek ( iff, iff->ChunkSize, SEEK_CUR ); - iff->next_byte += iff->ChunkSize; - iff->FormSize -= iff->ChunkSize; - iff->ChunkSize = 0; - } -} - - - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_NextForm ( IFF_FILE *iff ) -{ - IFF_CHUNK chunk; - int form; - - IFF_goto_form_end ( iff ); - - IFF_RAWREAD (iff, &chunk, sizeof( IFF_CHUNK ), error ); - - chunk.Size = BgEn32 (chunk.Size); - chunk.ID = BgEn32 (chunk.ID); - - iff->pad_form = (int) (chunk.Size & 0x0001); - - if (chunk.ID != vIFF_ID_FORM ) - { - goto error; - } - - IFF_RAWREAD (iff, &form, sizeof( int ), error); - - iff->FormID = (int) BgEn32 (form); - - iff->flags |= mIFF_FILE_FORMOPEN; - iff->next_byte += sizeof( int ) + sizeof ( IFF_CHUNK ); - iff->FormSize = (int) chunk.Size - sizeof ( int ); - iff->ChunkSize = 0; - iff->pad_chunk = 0; - - return TRUE; - -error: - - return FALSE; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_NextChunk ( IFF_FILE *iff ) -{ - IFF_CHUNK chunk; - - IFF_goto_chunk_end ( iff ); - - if (iff->FormSize==0) - { - goto error; - } - - IFF_RAWREAD ( iff, &chunk, sizeof( IFF_CHUNK ), error ); - - chunk.Size = BgEn32 (chunk.Size); - chunk.ID = BgEn32 (chunk.ID); - - iff->pad_chunk = (int) (chunk.Size & 0x0001); - - iff->flags |= mIFF_FILE_CHUNKOPEN; - iff->ChunkID = (int) chunk.ID; - iff->ChunkSize = (int) chunk.Size; - iff->next_byte += sizeof ( IFF_CHUNK ); - iff->FormSize -= sizeof ( IFF_CHUNK ); - - return TRUE; - -error: - - return FALSE; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -void IFF_Close ( IFF_FILE *iff ) -{ - if (iff->fp != -1) - { - _close (iff->fp); - } - - if ( iff->mem_file ) - { - free ( iff->mem_file ); - } - - free ( iff ); -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_Read ( IFF_FILE *iff, void *buff, int size ) -{ - int read =0; - - if ( size>iff->ChunkSize ) - { - size = iff->ChunkSize; - } - - read = IFF_rawread ( iff, buff, size); - - if (read==-1) - { - read = 0; - } - - iff->ChunkSize -= read; - iff->FormSize -= read; - iff->next_byte += read; - - - return read; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -IFF_FILE *IFF_New ( const char *name ) -{ - IFF_FILE *iff = NULL; - - - if ( ! (iff = (IFF_FILE *) malloc ( sizeof (IFF_FILE)))) - { - goto error; - } - - memset ( iff, 0, sizeof ( IFF_FILE )); - iff->fp = -1; - - if ((iff->fp = _open ( name, _O_BINARY | _O_RDWR | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE )) == -1 ) - { - goto error; - } - - return iff; - -error: - - if (iff) - { - IFF_Close ( iff ); - } - - return NULL; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_NewForm ( IFF_FILE *iff, int id ) -{ - IFF_CHUNK chunk; - - chunk.ID = BgEn32 (vIFF_ID_FORM); - chunk.Size = BgEn32 (90000); - - iff->FormSize = 0; - iff->ChunkSize = 0; - iff->FormID = id; - - DO_WRITE ( iff->fp, &chunk, sizeof (IFF_CHUNK), error); - - chunk.ID = BgEn32 ( (int) iff->FormID); - DO_WRITE ( iff->fp, &chunk.ID, sizeof (int), error ); - - iff->flags |= mIFF_FILE_FORMOPEN; - iff->form_size_pos = iff->next_byte + sizeof (int); - iff->next_byte += sizeof ( IFF_CHUNK ) + sizeof (int); - - return TRUE; - -error: - - return FALSE; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_NewChunk ( IFF_FILE *iff, int id ) -{ - IFF_CHUNK chunk; - - chunk.Size = BgEn32 (90000); - chunk.ID = BgEn32 ( (int) id); - - - DO_WRITE ( iff->fp, &chunk, sizeof ( IFF_CHUNK ), error ); - - iff->flags |= mIFF_FILE_CHUNKOPEN; - iff->chunk_size_pos = iff->next_byte + sizeof (int); - iff->next_byte += sizeof ( IFF_CHUNK ) ; - iff->FormSize += sizeof ( IFF_CHUNK ) ; - iff->ChunkSize = 0; - iff->ChunkID = id; - - return TRUE; - -error: - - return FALSE; - -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_Write ( IFF_FILE *iff, void *buff, int size ) -{ - int val =0; - - val = _write ( iff->fp, buff, size); - - if (val==-1) - { - val = 0; - } - - iff->ChunkSize += val; - iff->FormSize += val; - iff->next_byte += val; - - - return val; -} - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_CloseForm ( IFF_FILE *iff ) -{ - int fp; - int off; - int size; - int pad = 0; - - if (iff && ((fp = iff->fp) != -1)) - { - - if (iff->FormSize&0x0001) - { - DO_WRITE (fp, &pad, 1, error ); - iff->next_byte++; - } - - off = iff->next_byte - iff->form_size_pos; - - size = BgEn32 ( (int) (iff->FormSize+sizeof ( int ))); - - if (lseek (fp, -off, SEEK_CUR)==iff->form_size_pos) - { - DO_WRITE ( fp, &size, sizeof (int), error ); - lseek ( fp, 0, SEEK_END); - return TRUE; - } - } - -error: - - return FALSE; -} - - -/******************************************************************/ -/* */ -/* */ -/******************************************************************/ - -int IFF_CloseChunk ( IFF_FILE *iff ) -{ - int fp; - int off; - int size; - int pad = 0; - - if (iff && ((fp = iff->fp) != -1 )) - { - - if (iff->ChunkSize&0x0001) - { - DO_WRITE (fp, &pad, 1, error ); - iff->next_byte++; - iff->FormSize++; - } - - off = iff->next_byte - iff->chunk_size_pos; - - size = BgEn32 ((int) iff->ChunkSize); - - if (lseek (fp, -off, SEEK_CUR)==iff->chunk_size_pos) - { - DO_WRITE ( fp, &size, sizeof (int), error ); - lseek ( fp, 0, SEEK_END); - return TRUE; - } - } - -error: - - return TRUE; -} - diff --git a/Generals/Code/Tools/Babylon/iff.h b/Generals/Code/Tools/Babylon/iff.h deleted file mode 100644 index e7d5af4ecb..0000000000 --- a/Generals/Code/Tools/Babylon/iff.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#ifndef __IFF_H -#define __IFF_H - -#define MakeID(a,b,c,d) ( (int) ( ( (int) (a) ) << 24 | ( (int) (b) ) << 16 | \ - ( (int) (c) ) << 8 | ( (int) (d) ) ) ) - - -#define vIFF_ID_FORM MakeID('F','O','R','M') -#define vIFF_ID_CAT MakeID('C','A','T',' ') -#define vIFF_ID_LIST MakeID('L','I','S','T') -#define vIFF_ID_PROP MakeID('P','R','O','P') -#define vIFF_ID_FILLER W_MakeID(' ',' ',' ',' ') - -/* IFF_FILE: - IFF File handling structure -*/ - -/* defines for IFF_FILE->flags */ -#define mIFF_FILE_FORMOPEN (1<<0) /* in a form */ -#define mIFF_FILE_CHUNKOPEN (1<<1) /* in a chunk */ -#define mIFF_FILE_LOADED (1<<2) /* file is in memory */ - - -typedef struct -{ - int ID; /* Chunk ID */ - int Size; /* Chunk size in bytes */ - -} IFF_CHUNK; - -typedef struct { - - /* public fields */ - int FormID; - int ChunkID; - int FormSize; - int ChunkSize; - - /* private fields */ - - int fp; - int flags; - int next_byte; - int chunk_size_pos; - int form_size_pos; - int pad_form; - int pad_chunk; - int file_size; - int file_pos; - char *mem_file; - - -} IFF_FILE; - -IFF_FILE* IFF_Open ( const char * ); -IFF_FILE* IFF_Load ( const char * ); -VOID IFF_Reset ( IFF_FILE * ); -VOID IFF_Close ( IFF_FILE * ); - -VOID IFF_goto_form_end ( IFF_FILE *); -VOID IFF_goto_chunk_end ( IFF_FILE *); - -int IFF_NextForm ( IFF_FILE *); -int IFF_NextChunk ( IFF_FILE *); - -int IFF_Read ( IFF_FILE *, void *, int ); -int IFF_Write ( IFF_FILE *, void *, int ); - -IFF_FILE* IFF_New ( const char * ); -int IFF_NewForm ( IFF_FILE *, int ); -int IFF_NewChunk ( IFF_FILE *, int ); -int IFF_CloseForm ( IFF_FILE * ); -int IFF_CloseChunk ( IFF_FILE * ); - -#define DO_OPEN(P,N,F,E) {if (!((P)=open(N,(F)))) goto E;} -#define DO_READ(P,B,S,E) {if ( read((P),(B),(S))!=(S)) goto E;} -#define DO_WRITE(P,B,S,E) {if ( write((P),(B),(S))!=(S)) goto E;} - -#define IFF_READ(iff,data,size,label) {if ( IFF_Read ( (iff), (data), (size)) != (size)) goto label;} -#define IFF_WRITE(iff,data,size,label) {if ( IFF_Write ( (iff), (data), (size)) != (size)) goto label;} -#define IFF_NEWCHUNK(iff,id,label) { if ( !IFF_NewChunk ( (iff), (id))) goto label; } -#define IFF_NEWFORM(iff,id,label) { if ( !IFF_NewForm ( (iff), (id))) goto label; } - -#define Reverse32(L) ( (( (L)>>24 ) & 0xff) | (((L)>>8) &0xff00) | (((L)<<8)&0xff0000) | (((L)<<24)&0xff000000)) -#define Reverse16(L) ( (( (L)>>8 ) & 0xff) | (((L)<<8)&0xff00) ) - -#define __CPU_BIG_ENDIAN__ 0 - -#if __CPU_BIG_ENDIAN__ - - #define BgEn32(L) (L) - #define BgEn16(L) (L) - - #define LtEn32(L) Reverse32(L) - #define LtEn16(L) Reverse16(L) - -#else - - #define BgEn32(L) Reverse32(L) - #define BgEn16(L) Reverse16(L) - - #define LtEn32(L) (L) - #define LtEn16(L) (L) - -#endif - - -#endif /* __IFF_H */ diff --git a/Generals/Code/Tools/Babylon/list.cpp b/Generals/Code/Tools/Babylon/list.cpp deleted file mode 100644 index b8fdc0bf33..0000000000 --- a/Generals/Code/Tools/Babylon/list.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// list.cpp -// - - -#include "StdAfx.h" -#include -#include "list.h" - -ListNode::ListNode ( void ) -{ - prev = next = this; - pri = NORMAL_PRIORITY; - item = NULL; -} - -void ListNode::Append ( ListNode *new_node ) -{ - assert ( ! new_node->InList()); /* node is already in a list or was not initialized*/ - - new_node->prev = this; - new_node->next = next; - next = new_node; - new_node->next->prev = new_node; - -} - -void ListNode::Prepend ( ListNode *new_node ) -{ - - assert ( !new_node->InList() ); /* node is already in a list or was not initialized*/ - - new_node->prev = prev; - new_node->next = this; - prev = new_node; - new_node->prev->next = new_node; - -} -void ListNode::Link ( ListNode *node) -{ - next = node; - node->prev = next; -} - -void ListNode::Remove ( void ) -{ - prev->next = next; - next->prev = prev; - prev = next = this; /* so we know that the node is not in a list */ -} - -ListNode* ListNode::Next ( void ) -{ - if ( next->IsHead ( ) ) - { - return NULL; - } - - return next; -} - -ListNode* ListNode::Prev ( void ) -{ - if ( prev->IsHead () ) - { - return NULL; - } - - return prev; -} - -ListNode* ListNode::NextLoop ( void ) -{ - ListNode *next_node = next; - - if ( next_node->IsHead ( )) - { - /* skip head node */ - next_node = next_node->next; - if ( next_node->IsHead ( )) - { - return NULL; /* it is an empty list */ - } - } - - return next_node; - -} - -ListNode* ListNode::PrevLoop ( void ) -{ - ListNode *prev_node = prev; - - if ( prev_node->IsHead ( )) - { - /* skip head node */ - prev_node = prev_node->prev; - if ( prev_node->IsHead ( )) - { - return NULL; /* it is an empty list */ - } - } - - return prev_node; -} - -void* ListNode::Item ( void ) -{ - - assert ( !IsHead () ); - - return item; - -} - -void ListNode::SetItem ( void *new_item ) -{ - assert ( !IsHead () ); - item = new_item ; -} - -int ListNode::InList ( void ) -{ - - return prev != this; -} - -int ListNode::IsHead ( void ) -{ - return item == &this->item; -} - -int ListNode::Priority ( void ) -{ - return pri; - -} -void ListNode::SetPriority ( int new_pri ) -{ - - assert ( new_pri <= HIGHEST_PRIORITY ); - assert ( new_pri >= LOWEST_PRIORITY ); - pri = new_pri; - -} - -List::List ( void ) -{ - - SetItem ( &this->item ); - -} - -void List::AddToTail ( ListNode *node ) -{ - assert ( IsHead ()); - Prepend ( node ); -} - -void List::AddToHead ( ListNode *node ) -{ - assert ( IsHead ()); - Append ( node ); -} - -void List::Add ( ListNode *new_node ) -{ - ListNode* node; - int pri; - - assert ( IsHead ()); - assert ( !new_node->InList ()); - - pri = new_node->Priority(); - node = FirstNode ( ); - - while( node ) - { - if (node->Priority() <= pri ) - { - node->Prepend ( new_node ); - return; - } - - node = node->Next (); - } - - Prepend ( new_node ); - -} - -void List::Merge ( List *list ) -{ - ListNode *first, - *last, - *node; - - assert ( IsHead ()); - - first = list->Next(); - last = list->Prev(); - - if ( !first || !last ) - { - return; - } - - node = Prev(); - node->Link ( first ); - last->Link ( this ); - - list->Empty (); - -} - -int List::NumItems ( void ) -{ - int count = 0; - ListNode *node; - - assert ( IsHead ()); - node = FirstNode(); - - while ( node ) - { - count++; - node = node->Next (); - } - - return count; -} - -void* List::Item ( int list_index ) -{ - ListNode *node; - - assert ( IsHead ()); - node = FirstNode(); - - while (list_index && node ) - { - list_index--; - node = node->Next (); - } - if ( node ) - { - return node->Item(); - } - - return NULL; -} - -ListNode* List::FirstNode ( void ) -{ - assert ( IsHead ()); - return Next (); - -} - -ListNode* List::LastNode ( void ) -{ - assert ( IsHead ()); - return Prev (); - -} - -int List::IsEmpty ( void ) -{ - assert ( IsHead ()); - - return !InList(); - -} - -void List::Empty ( void ) -{ - assert ( IsHead ()); - Remove (); -} - - -ListNode* List::Find ( void *item ) -{ - ListNode *node; - - node = FirstNode (); - - while ( node ) - { - if ( node->Item () == item ) - { - return node; - } - - node = node->Next (); - } - return NULL; -} diff --git a/Generals/Code/Tools/Babylon/list.h b/Generals/Code/Tools/Babylon/list.h deleted file mode 100644 index c53f172b2b..0000000000 --- a/Generals/Code/Tools/Babylon/list.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#ifndef __LIST_H -#define __LIST_H - - -const int LOWEST_PRIORITY = (int ) 0x80000000; -const int HIGHEST_PRIORITY = (int) 0x7fffffff; -const int NORMAL_PRIORITY = 0; - -class ListNode -{ - private: - ListNode *next; - ListNode *prev; - int pri; // node's priority - - protected: - void *item; // item - - public: - - ListNode ( void ); - void Append ( ListNode *node ); - void Prepend ( ListNode *node ); - void Link ( ListNode *node); - void Remove ( void ); - ListNode* Next ( void ); - ListNode* Prev ( void ); - ListNode* NextLoop ( void ); - ListNode* PrevLoop ( void ); - void* Item ( void ); - void SetItem ( void *item ); - int InList ( void ); - int IsHead ( void ); - int Priority ( void ); - void SetPriority ( int new_pri ); - - -}; - -class List: public ListNode -{ - - public: - List ( void ); - void AddToTail ( ListNode *node ); - void AddToHead ( ListNode *node ); - void Add ( ListNode *node ); - void Merge ( List *list ); - int NumItems ( void ); - void* Item ( int list_index ); - ListNode* FirstNode ( void ); - ListNode* LastNode ( void ); - int IsEmpty ( void ); - void Empty ( void ); - ListNode* Find ( void *item ); - -}; - -class ListSearch -{ - List *head; - ListNode *node; - - public: - - ListNode* Next ( void ) { if (node) { node = node->Next ();} return node;}; - ListNode* Prev ( void ) { if (node) { node = node->Prev ();} return node;}; - ListNode* FirstNode ( void ) { node = head; return Next (); }; - ListNode* LastNode ( void ) { node = head; return Prev (); }; - ListNode* FirstNode ( List *new_head ) { node = head = new_head; return Next (); }; - ListNode* LastNode ( List *new_head) { node = head = new_head; return Prev (); }; - -}; - - -#endif // __LIST_H diff --git a/Generals/Code/Tools/Babylon/loadsave.cpp b/Generals/Code/Tools/Babylon/loadsave.cpp deleted file mode 100644 index f1275f412a..0000000000 --- a/Generals/Code/Tools/Babylon/loadsave.cpp +++ /dev/null @@ -1,656 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// loadsave.cpp -// - -#include "StdAfx.h" -#include "iff.h" -#include "TransDB.h" -#include "noxstringDlg.h" - -#define FORM_NOXDB MakeID ('N','X','D','B') -#define FORM_LABEL MakeID ('N','L','B','L') -#define FORM_TEXT MakeID ('N','T','X','T') -#define FORM_TRANS MakeID ('N','T','R','N') -#define CHUNK_COMMENT MakeID ('C','M','N','T') -#define CHUNK_CONTEXT MakeID ('C','T','X','T') -#define CHUNK_SPEAKER MakeID ('S','P','K','R') -#define CHUNK_LISTENER MakeID ('L','T','N','R') -#define CHUNK_TEXT MakeID ('T','E','X','T') -#define CHUNK_WAVE MakeID ('W','A','V','E') -#define CHUNK_WAVE_INFO MakeID ('W','V','I','N') -#define CHUNK_INFO MakeID ('I','N','F','O') -#define CHUNK_NAME MakeID ('N','A','M','E') - -#define MAX_BUFFER (100*1024) - -static OLECHAR buffer[MAX_BUFFER]; -typedef struct -{ - int num_labels; - int next_id; - -} DBINFO; - -typedef struct -{ - int max_len; - -} LBINFO; - -typedef struct -{ - int id; - int revision; - -} TXINFO; - -typedef struct -{ - LangID lang; - int revision; - -} TRINFO; - -typedef struct -{ - int valid; - DWORD lo; - DWORD hi; - -} WVINFO; - - -static int writeString ( IFF_FILE *iff, OLECHAR *string, int chunk_id ) -{ - int len = (wcslen ( string ) ); - int bytes = (len+1)*sizeof(OLECHAR); - - if ( len ) - { - IFF_NEWCHUNK ( iff, chunk_id, error ); - IFF_WRITE ( iff, string, bytes, error); - IFF_CloseChunk ( iff ); - - } - - return TRUE; - -error: - - return FALSE; -} - -static int readString ( IFF_FILE *iff, OLECHAR *string ) -{ - - *string = 0; - - IFF_READ ( iff, string, iff->ChunkSize, error); - - return TRUE; - -error: - - return FALSE; -} - -static int writeTransForm ( IFF_FILE *iff, Translation *trans ) -{ - TRINFO trinfo; - WVINFO wvinfo; - - if ( !IFF_NewForm ( iff, FORM_TRANS )) - { - goto error; - } - - trinfo.lang = trans->GetLangID (); - trinfo.revision = trans->Revision (); - - if ( !IFF_NewChunk ( iff, CHUNK_INFO )) - { - goto error; - } - - IFF_Write ( iff, &trinfo, sizeof ( trinfo )); - - IFF_CloseChunk ( iff ); - - writeString ( iff, trans->Get (), CHUNK_TEXT ); - writeString ( iff, trans->Comment (), CHUNK_COMMENT ); - - if ( (wvinfo.valid = trans->WaveInfo.Valid()) ) - { - wvinfo.lo = trans->WaveInfo.Lo (); - wvinfo.hi = trans->WaveInfo.Hi (); - - if ( !IFF_NewChunk ( iff, CHUNK_WAVE_INFO )) - { - goto error; - } - - IFF_Write ( iff, &wvinfo, sizeof ( wvinfo )); - - IFF_CloseChunk ( iff ); - } - - IFF_CloseForm ( iff ); - - return TRUE; -error: - - return FALSE; - -} - -static int writeTextForm ( IFF_FILE *iff, NoxText *text ) -{ - TXINFO txinfo; - WVINFO wvinfo; - - if ( !IFF_NewForm ( iff, FORM_TEXT )) - { - goto error; - } - - txinfo.id = text->ID (); - txinfo.revision = text->Revision (); - - if ( !IFF_NewChunk ( iff, CHUNK_INFO )) - { - goto error; - } - - IFF_Write ( iff, &txinfo, sizeof ( txinfo )); - - IFF_CloseChunk ( iff ); - writeString ( iff, text->Get (), CHUNK_TEXT ); - writeString ( iff, text->Wave (), CHUNK_WAVE ); - - if ( (wvinfo.valid = text->WaveInfo.Valid()) ) - { - wvinfo.lo = text->WaveInfo.Lo (); - wvinfo.hi = text->WaveInfo.Hi (); - - if ( !IFF_NewChunk ( iff, CHUNK_WAVE_INFO )) - { - goto error; - } - - IFF_Write ( iff, &wvinfo, sizeof ( wvinfo )); - - IFF_CloseChunk ( iff ); - } - - IFF_CloseForm ( iff ); - - return TRUE; -error: - - return FALSE; - -} - -int WriteMainDB(TransDB *db, const char *filename, CNoxstringDlg *dlg ) -{ - NoxText *text; - NoxLabel *label; - ListSearch sh_label; - ListSearch sh_text; - int count = 0; - IFF_FILE *iff = NULL; - DBINFO dbinfo; - int ok = FALSE; - - if ( dlg ) - { - dlg->InitProgress ( db->NumLabels ()); - } - - - if ( !( iff = IFF_New ( filename ))) - { - goto error; - } - - if ( !IFF_NewForm ( iff, FORM_NOXDB ) ) - { - goto error; - } - - dbinfo.next_id = db->ID (); - dbinfo.num_labels = db->NumLabels (); - - if ( !IFF_NewChunk ( iff, CHUNK_INFO )) - { - goto error; - } - - IFF_Write ( iff, &dbinfo, sizeof ( dbinfo )); - - IFF_CloseChunk ( iff ); - IFF_CloseForm ( iff ); - - text = db->FirstObsolete ( sh_text ); - - while ( text ) - { - if ( !writeTextForm ( iff, text ) ) - { - goto error; - } - text = db->NextObsolete ( sh_text ); - } - - - - label = db->FirstLabel ( sh_label ); - - while ( label ) - { - LBINFO lbinfo; - - if ( !IFF_NewForm ( iff, FORM_LABEL )) - { - goto error; - } - - lbinfo.max_len = label->MaxLen (); - - if ( !IFF_NewChunk ( iff, CHUNK_INFO )) - { - goto error; - } - - IFF_Write ( iff, &lbinfo, sizeof ( lbinfo )); - - IFF_CloseChunk ( iff ); - - writeString ( iff, label->Name (), CHUNK_NAME ); - writeString ( iff, label->Comment (), CHUNK_COMMENT ); - writeString ( iff, label->Context (), CHUNK_CONTEXT ); - writeString ( iff, label->Speaker (), CHUNK_SPEAKER ); - writeString ( iff, label->Listener (), CHUNK_LISTENER ); - IFF_CloseForm ( iff ); - - text = label->FirstText ( sh_text ); - - while ( text ) - { - Translation *trans; - ListSearch sh_trans; - if ( !writeTextForm ( iff, text ) ) - { - goto error; - } - - trans = text->FirstTranslation ( sh_trans ); - - while ( trans ) - { - if ( !writeTransForm ( iff, trans ) ) - { - goto error; - } - - trans = text->NextTranslation ( sh_trans ); - } - - text = label->NextText ( sh_text ); - } - - count++; - if ( dlg ) - { - dlg->SetProgress ( count ); - } - label = db->NextLabel ( sh_label ); - } - - ok = TRUE; - db->ClearChanges (); - -error: - if ( iff ) - { - IFF_Close ( iff ); - } - - return ok; -} - -int LoadMainDB(TransDB *db, const char *filename, void (*cb) (void) ) -{ - NoxLabel *label = NULL; - NoxText *text = NULL; - Translation *trans = NULL; - int count = 0; - IFF_FILE *iff = NULL; - DBINFO dbinfo; - int ok = FALSE; - - - if ( !(iff = IFF_Load ( filename ) ) ) - { - goto error; - } - - if ( !IFF_NextForm ( iff ) || iff->FormID != FORM_NOXDB ) - { - goto error; - } - - dbinfo.next_id = -1; - dbinfo.num_labels = 0; - - while ( IFF_NextChunk ( iff )) - { - switch (iff->ChunkID ) - { - case CHUNK_INFO: - IFF_READ ( iff, &dbinfo, sizeof ( dbinfo ), error ); - break; - } - } - - db->SetID ( dbinfo.next_id ); - - while ( IFF_NextForm ( iff ) ) - { - switch ( iff->FormID ) - { - case FORM_LABEL: - { - LBINFO lbinfo; - // new label - - if ( text ) - { - if ( label ) - { - label->AddText ( text ); - } - else - { - db->AddObsolete ( text ); - } - - text = NULL; - } - - if ( label ) - { - count++; - db->AddLabel ( label ); - label = NULL; - if ( cb ) - { - cb (); - } - } - - if ( ! (label = new NoxLabel ())) - { - goto error; - } - - while ( IFF_NextChunk ( iff )) - { - switch ( iff->ChunkID ) - { - case CHUNK_INFO: - IFF_READ ( iff, &lbinfo, sizeof (lbinfo), error ); - label->SetMaxLen ( lbinfo.max_len ); - break; - case CHUNK_COMMENT: - readString ( iff, buffer ); - label->SetComment ( buffer ); - break; - case CHUNK_CONTEXT: - readString ( iff, buffer ); - label->SetContext ( buffer ); - break; - case CHUNK_SPEAKER: - readString ( iff, buffer ); - label->SetSpeaker ( buffer ); - break; - case CHUNK_LISTENER: - readString ( iff, buffer ); - label->SetListener ( buffer ); - break; - case CHUNK_NAME: - readString ( iff, buffer ); - label->SetName ( buffer ); - break; - } - } - break; - } - case FORM_TEXT: - { - TXINFO txinfo; - - if ( text ) - { - if ( label ) - { - label->AddText ( text ); - } - else - { - db->AddObsolete ( text ); - } - - text = NULL; - } - - if ( ! (text = new NoxText ())) - { - goto error; - } - - while ( IFF_NextChunk ( iff )) - { - switch ( iff->ChunkID ) - { - case CHUNK_INFO: - IFF_READ ( iff, &txinfo, sizeof (txinfo), error ); - text->SetID ( txinfo.id ); - text->SetRevision ( txinfo.revision ); - break; - case CHUNK_TEXT: - readString ( iff, buffer ); - text->Set ( buffer ); - break; - - case CHUNK_WAVE: - readString ( iff, buffer ); - text->SetWave ( buffer ); - break; - case CHUNK_WAVE_INFO: - { - WVINFO wvinfo; - IFF_READ ( iff, &wvinfo, sizeof (wvinfo), error ); - text->WaveInfo.SetValid ( wvinfo.valid ); - text->WaveInfo.SetLo ( wvinfo.lo ); - text->WaveInfo.SetHi ( wvinfo.hi ); - break; - } - } - - } - break; - } - case FORM_TRANS: - { - TRINFO trinfo; - - if ( ! (trans = new Translation ())) - { - goto error; - } - - while ( IFF_NextChunk ( iff )) - { - switch ( iff->ChunkID ) - { - case CHUNK_INFO: - IFF_READ ( iff, &trinfo, sizeof (trinfo), error ); - trans->SetLangID ( trinfo.lang ); - trans->SetRevision ( trinfo.revision ); - break; - case CHUNK_TEXT: - readString ( iff, buffer ); - trans->Set ( buffer ); - break; - - case CHUNK_COMMENT: - readString ( iff, buffer ); - trans->SetComment ( buffer ); - break; - case CHUNK_WAVE_INFO: - { - WVINFO wvinfo; - IFF_READ ( iff, &wvinfo, sizeof (wvinfo), error ); - trans->WaveInfo.SetValid ( wvinfo.valid ); - trans->WaveInfo.SetLo ( wvinfo.lo ); - trans->WaveInfo.SetHi ( wvinfo.hi ); - } - break; - - } - - } - if ( text ) - { - text->AddTranslation ( trans ); - } - else - { - delete trans; - } - trans = NULL; - - break; - } - } - } - - if ( text ) - { - if ( label ) - { - label->AddText ( text ); - } - else - { - db->AddObsolete ( text ); - } - - text = NULL; - } - - if ( label ) - { - count++; - db->AddLabel ( label ); - label = NULL; - if ( cb ) - { - cb (); - } - } - - ok = TRUE; - -error: - - if ( label ) - { - delete label; - } - - if ( text ) - { - delete text; - } - - if ( trans ) - { - delete trans; - } - - if ( iff ) - { - IFF_Close ( iff ); - } - - db->ClearChanges (); - - if ( !ok ) - { - db->Clear (); - } - - return ok; -} - - -int GetLabelCountDB ( char *filename ) -{ - IFF_FILE *iff = NULL; - DBINFO dbinfo; - int count = 0; - - - if ( !(iff = IFF_Open ( filename ) ) ) - { - goto error; - } - - if ( !IFF_NextForm ( iff ) || iff->FormID != FORM_NOXDB ) - { - goto error; - } - - dbinfo.next_id = -1; - dbinfo.num_labels = 0; - - while ( IFF_NextChunk ( iff )) - { - switch (iff->ChunkID ) - { - case CHUNK_INFO: - IFF_READ ( iff, &dbinfo, sizeof ( dbinfo ), error ); - break; - } - } - - - count = dbinfo.num_labels; - -error: - if ( iff ) - { - IFF_Close ( iff ); - } - return count; -} \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/loadsave.h b/Generals/Code/Tools/Babylon/loadsave.h deleted file mode 100644 index 5c7f14c9fe..0000000000 --- a/Generals/Code/Tools/Babylon/loadsave.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// loadsave.h -// - -#ifndef __LOADSAVE_H -#define __LOADSAVE_H - -int WriteMainDB(TransDB *db, const char *filename, CNoxstringDlg *dlg ); -int LoadMainDB(TransDB *db, const char *filename, void (*cb) (void ) = NULL ); -int GetLabelCountDB ( char *filename ); - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/noxstring.cpp b/Generals/Code/Tools/Babylon/noxstring.cpp deleted file mode 100644 index 1b598cc789..0000000000 --- a/Generals/Code/Tools/Babylon/noxstring.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// noxstring.cpp : Defines the class behaviors for the application. -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "noxstringDlg.h" -#include "XLStuff.h" - -#include -#include -#include - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -char AppTitle[200]; -CNoxstringDlg *MainDLG = NULL; - -static const char *AppName = "Babylon:"; -static int AlreadyRunning( void ); -static HWND FoundWindow = NULL; -///////////////////////////////////////////////////////////////////////////// -// CNoxstringApp - -BEGIN_MESSAGE_MAP(CNoxstringApp, CWinApp) - //{{AFX_MSG_MAP(CNoxstringApp) - //}}AFX_MSG_MAP - ON_COMMAND(ID_HELP, CWinApp::OnHelp) -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringApp construction - -CNoxstringApp::CNoxstringApp() -{ - // TODO: add construction code here, - // Place all significant initialization in InitInstance -} - -///////////////////////////////////////////////////////////////////////////// -// The one and only CNoxstringApp object - -CNoxstringApp theApp; -TransDB *NoxstrDB = NULL; -TransDB *MainDB = NULL; -char NoxstrFilename[_MAX_PATH]; -char MainXLSFilename[_MAX_PATH]; -char DialogPath[_MAX_PATH]; -char RootPath[_MAX_PATH]; -LangID CurrentLanguage = LANGID_US; - - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringApp initialization - -BOOL CNoxstringApp::InitInstance() -{ - // Initialize OLE libraries - if (!AfxOleInit()) - { - AfxMessageBox(IDP_OLE_INIT_FAILED); - return FALSE; - } - - // Standard initialization - // If you are not using these features and wish to reduce the size - // of your final executable, you should remove from the following - // the specific initialization routines you do not need. - -#ifdef _AFXDLL - Enable3dControls(); // Call this when using MFC in a shared DLL -#else - Enable3dControlsStatic(); // Call this when linking to MFC statically -#endif - - // Parse the command line to see if launched as OLE server - if (RunEmbedded() || RunAutomated()) - { - // Register all OLE server (factories) as running. This enables the - // OLE libraries to create objects from other applications. - COleTemplateServer::RegisterAll(); - } - else - { - // When a server application is launched stand-alone, it is a good idea - // to update the system registry in case it has been damaged. - COleObjectFactory::UpdateRegistryAll(); - } - - MainDB = new TransDB ( "Main" ); - NoxstrDB = new TransDB ( "Generals.str" ); - MainDB->EnableIDs (); - - if ( !AfxInitRichEdit( ) ) - { - AfxMessageBox ( "Error initializing Rich Edit" ); - } - - sprintf (AppTitle, "%s Built on %s - %s", AppName, __DATE__, __TIME__ ); - - if ( !_getcwd( RootPath, _MAX_PATH ) ) - { - AfxMessageBox ( "Failed to obtain current working directoy!\n\n Set directoy path to \"c:\\Babylon\"." ); - strcpy ( (char *) RootPath, "c:\\Babylon" ); - } - strlwr ( RootPath ); - - strcpy ( (char *) NoxstrFilename, RootPath ); - strcat ( (char *) NoxstrFilename, "\\Data\\Generals.str" ); - strcpy ( (char *) MainXLSFilename, RootPath ); - strcat ( (char *) MainXLSFilename, "\\Data\\main.db" ); - strcpy ( (char *) DialogPath, RootPath ); - strcat ( (char *) DialogPath, "\\dialog" ); - - if ( AlreadyRunning () ) - { - if ( FoundWindow ) - { - SetForegroundWindow ( FoundWindow ); - } - } - else if ( OpenExcel ( ) ) - { - CNoxstringDlg dlg; - m_pMainWnd = &dlg; - MainDLG = &dlg; - - int nResponse = dlg.DoModal(); - - CloseExcel (); - } - - delete NoxstrDB ; - delete MainDB; - // Since the dialog has been closed, return FALSE so that we exit the - // application, rather than start the application's message pump. - return FALSE; -} - -//DEL void CNoxstringApp::OnDropFiles(HDROP hDropInfo) -//DEL { -//DEL // TODO: Add your message handler code here and/or call default -//DEL -//DEL CWinApp::OnDropFiles(hDropInfo); -//DEL } - -static BOOL CALLBACK EnumAllWindowsProc(HWND hWnd, LPARAM lParam); -static BOOL CALLBACK EnumAllWindowsProcExact(HWND hWnd, LPARAM lParam); -static const char *szSearchTitle; - -static int AlreadyRunning( void ) -{ - BOOL found = FALSE; - - szSearchTitle = AppName; - - EnumWindows((WNDENUMPROC) EnumAllWindowsProcExact, (LPARAM) &found); - - return found; -} - -//-------------------------------------------------------------------------------- - -int ExcelRunning( void ) -{ - BOOL found = FALSE; - - szSearchTitle = "Microsoft Excel"; - - EnumWindows((WNDENUMPROC) EnumAllWindowsProc, (LPARAM) &found); - - return found; -} - -//-------------------------------------------------------------------------------- - -BOOL CALLBACK EnumAllWindowsProc(HWND hWnd, LPARAM lParam) -{ - char szText[256]; - - GetWindowText(hWnd, szText, sizeof(szText)); - - if ( strstr(szText, szSearchTitle)) - { - * (BOOL *) lParam = TRUE; - FoundWindow = hWnd; - return FALSE; - } - - FoundWindow = NULL; - return TRUE; -} - -//-------------------------------------------------------------------------------- - -BOOL CALLBACK EnumAllWindowsProcExact(HWND hWnd, LPARAM lParam) -{ - char szText[256]; - - GetWindowText(hWnd, szText, sizeof(szText)); - - if ( !strncmp (szText, szSearchTitle, strlen ( szSearchTitle))) - { - * (BOOL *) lParam = TRUE; - FoundWindow = hWnd; - return FALSE; - } - - FoundWindow = NULL; - return TRUE; -} - diff --git a/Generals/Code/Tools/Babylon/noxstring.h b/Generals/Code/Tools/Babylon/noxstring.h deleted file mode 100644 index 07a9273a2f..0000000000 --- a/Generals/Code/Tools/Babylon/noxstring.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// noxstring.h : main header file for the NOXSTRING application -// - -#if !defined(AFX_NOXSTRING_H__2BF3124B_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_NOXSTRING_H__2BF3124B_3BA1_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#ifndef __AFXWIN_H__ - #error include 'stdafx.h' before including this file for PCH -#endif - -#include "resource.h" // main symbols -#include "TransDB.h" - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringApp: -// See noxstring.cpp for the implementation of this class -// - -class CNoxstringApp : public CWinApp -{ -public: - CNoxstringApp(); - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CNoxstringApp) - public: - virtual BOOL InitInstance(); - //}}AFX_VIRTUAL - -// Implementation - - //{{AFX_MSG(CNoxstringApp) - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -int ExcelRunning( void ); -extern TransDB *NoxstrDB; -extern TransDB *MainDB; -extern char NoxstrFilename[]; -extern char MainXLSFilename[]; -extern char RootPath[]; -extern char DialogPath[]; -extern LangID CurrentLanguage; - -///////////////////////////////////////////////////////////////////////////// - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_NOXSTRING_H__2BF3124B_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/noxstring.odl b/Generals/Code/Tools/Babylon/noxstring.odl deleted file mode 100644 index baa8a6b574..0000000000 --- a/Generals/Code/Tools/Babylon/noxstring.odl +++ /dev/null @@ -1,42 +0,0 @@ -// noxstring.odl : type library source for noxstring.exe - -// This file will be processed by the MIDL compiler to produce the -// type library (noxstring.tlb). - -[ uuid(2BF31247-3BA1-11D3-B9DA-006097B90D93), version(1.0) ] -library Noxstring -{ - importlib("stdole32.tlb"); - importlib("stdole2.tlb"); - - - // Primary dispatch interface for CNoxstringDoc - - [ uuid(2BF31248-3BA1-11D3-B9DA-006097B90D93) ] - dispinterface INoxstring - { - properties: - // NOTE - ClassWizard will maintain property information here. - // Use extreme caution when editing this section. - //{{AFX_ODL_PROP(CNoxstringDlgAutoProxy) - //}}AFX_ODL_PROP - - methods: - // NOTE - ClassWizard will maintain method information here. - // Use extreme caution when editing this section. - //{{AFX_ODL_METHOD(CNoxstringDlgAutoProxy) - //}}AFX_ODL_METHOD - - }; - - // Class information for CNoxstringDoc - - [ uuid(2BF31246-3BA1-11D3-B9DA-006097B90D93) ] - coclass Noxstring - { - [default] dispinterface INoxstring; - }; - - //{{AFX_APPEND_ODL}} - //}}AFX_APPEND_ODL}} -}; diff --git a/Generals/Code/Tools/Babylon/noxstring.rc b/Generals/Code/Tools/Babylon/noxstring.rc deleted file mode 100644 index b2c1c68447..0000000000 --- a/Generals/Code/Tools/Babylon/noxstring.rc +++ /dev/null @@ -1,566 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -// Generated Help ID header file -#define APSTUDIO_HIDDEN_SYMBOLS -#include "resource.hm" -#undef APSTUDIO_HIDDEN_SYMBOLS - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "#define _AFX_NO_SPLITTER_RESOURCES\r\n" - "#define _AFX_NO_OLE_RESOURCES\r\n" - "#define _AFX_NO_TRACKER_RESOURCES\r\n" - "#define _AFX_NO_PROPERTY_RESOURCES\r\n" - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "#ifdef _WIN32\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#endif //_WIN32\r\n" - "#include ""res\\noxstring.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#include ""afxres.rc"" // Standard components\r\n" - "#endif\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON DISCARDABLE "res\\noxstring.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOGEX 0, 0, 235, 55 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "About Babylon" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - LTEXT "Babylon Version 1.0",IDC_STATIC,40,10,76,8,SS_NOPREFIX - DEFPUSHBUTTON "OK",IDOK,178,7,50,14,WS_GROUP,WS_EX_STATICEDGE - LTEXT "Static",IDC_BUILD,7,37,221,11 - ICON IDR_MAINFRAME,IDM_PIC,13,13,20,20 - PUSHBUTTON "CP",IDC_BUTTON1,119,7,50,14,0,WS_EX_STATICEDGE -END - -IDD_NOXSTRING_DIALOG DIALOGEX 0, 0, 320, 257 -STYLE DS_MODALFRAME | DS_CONTEXTHELP | WS_MINIMIZEBOX | WS_POPUP | - WS_VISIBLE | WS_CAPTION | WS_SYSMENU -EXSTYLE WS_EX_ACCEPTFILES | WS_EX_APPWINDOW -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Ready",IDC_STATUS,"Static",SS_LEFTNOWORDWRAP | - SS_SUNKEN | WS_GROUP,13,186,291,11,0,HIDC_STATUS - CONTROL "Progress1",IDC_PROGRESS1,"msctls_progress32",PBS_SMOOTH | - WS_BORDER,13,174,263,9,0,HIDC_PROGRESS1 - GROUPBOX "",IDC_STATIC,7,7,306,243 - PUSHBUTTON "&Reload",IDC_RELOAD,19,24,48,15 - CONTROL "",IDC_LOG,"RICHEDIT",ES_MULTILINE | ES_AUTOVSCROLL | - ES_AUTOHSCROLL | ES_READONLY | ES_WANTRETURN | ES_NUMBER | - WS_VSCROLL | WS_HSCROLL | WS_TABSTOP,13,75,291,95, - WS_EX_STATICEDGE - PUSHBUTTON "&DBs",IDC_VIEWDBS,19,54,26,15 - GROUPBOX "DataBase",IDC_STATIC,14,15,169,27 - PUSHBUTTON "&Update",IDC_UPDATE,74,24,48,15 - PUSHBUTTON "&Save",IDC_SAVE,129,24,48,15 - GROUPBOX "View",IDC_STATIC,13,45,88,27 - PUSHBUTTON "E&xport",IDC_EXPORT,196,24,48,15 - PUSHBUTTON "&Import",IDC_IMPORT,251,24,48,15 - PUSHBUTTON "&Generate New Game Files",IDC_GENERATE,13,228,291,17,0, - WS_EX_STATICEDGE - PUSHBUTTON "&Warnings",IDC_WARNINGS,221,54,41,15 - PUSHBUTTON "&Changes",IDC_CHANGES,50,54,43,15 - PUSHBUTTON "&Errors",IDC_ERRORS,267,54,32,15 - GROUPBOX "Translations",IDC_STATIC,189,15,115,27 - RTEXT "100% ",IDC_PERCENT,280,174,24,9,SS_CENTERIMAGE | - SS_SUNKEN - GROUPBOX "Generals.Str",IDC_STATIC,215,45,89,27 - PUSHBUTTON "Dialo&g",IDC_DIALOG,212,208,40,15 - PUSHBUTTON "Report",IDC_REPORTS,145,54,49,15 - GROUPBOX "Verify",IDC_STATIC,13,198,291,28 - COMBOBOX IDC_COMBOLANG,75,209,125,88,CBS_DROPDOWNLIST | CBS_SORT | - WS_VSCROLL | WS_TABSTOP - PUSHBUTTON "&Text",IDC_TRANSLATIONS,259,208,40,15 - GROUPBOX "Create",IDC_STATIC,137,45,65,27 - PUSHBUTTON "Reset",IDC_RESET,18,208,44,15,0,WS_EX_CLIENTEDGE - PUSHBUTTON "Sent",IDC_SENT,105,52,24,15 -END - -IDD_VIEWDBS DIALOG DISCARDABLE 0, 0, 361, 173 -STYLE DS_MODALFRAME | DS_3DLOOK | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | - WS_SYSMENU -CAPTION "View Internal Databases" -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "",IDC_STATIC,7,7,347,159 - CONTROL "Tree1",IDC_TREEVIEW,"SysTreeView32",TVS_HASBUTTONS | - TVS_HASLINES | TVS_LINESATROOT | WS_BORDER | WS_TABSTOP, - 13,16,334,143 -END - -IDD_EXPORT DIALOGEX 0, 0, 277, 117 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Export Translations" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - PUSHBUTTON "&Export",IDOK,170,56,94,20,0,WS_EX_STATICEDGE - DEFPUSHBUTTON "&Cancel",IDCANCEL,170,83,94,14,0,WS_EX_STATICEDGE - COMBOBOX IDC_COMBOLANG,175,18,89,92,CBS_DROPDOWN | CBS_SORT | - WS_VSCROLL | WS_TABSTOP - GROUPBOX "",IDC_STATIC,7,7,263,103 - GROUPBOX "Include",IDC_STATIC,14,14,123,22 - CONTROL "Translations",IDC_CHECKTRANS,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,22,23,84,13 - CONTROL "&All strings",IDC_RADIOALL,"Button",BS_AUTORADIOBUTTON, - 24,66,45,10 - CONTROL "C&hanges only",IDC_RADIOCHANGES,"Button", - BS_AUTORADIOBUTTON,24,54,59,10 - GROUPBOX "Export",IDC_STATIC,14,42,124,62 - EDITTEXT IDC_FILENAME,184,35,80,13,ES_AUTOHSCROLL - LTEXT "Filename:",IDC_STATIC,150,37,31,8 - LTEXT "Language:",IDC_STATIC,140,20,35,8 - CONTROL "&Sample",IDC_RADIOSAMPLE,"Button",BS_AUTORADIOBUTTON,85, - 78,39,10 - CONTROL "&Dialog only",IDC_RADIODIALOG,"Button", - BS_AUTORADIOBUTTON,85,66,51,10 - CONTROL "&Non dialog",IDC_RADIONONDIALOG,"Button", - BS_AUTORADIOBUTTON,85,54,50,10 - CONTROL "&Unverified dialog",IDC_RADIOUNVERIFIED,"Button", - BS_AUTORADIOBUTTON,24,90,67,10 - CONTROL "&Missing dialog",IDC_RADIOMISSING,"Button", - BS_AUTORADIOBUTTON,24,78,58,10 - CONTROL "Unsen&t",IDC_RADIOUNSENT,"Button",BS_AUTORADIOBUTTON,93, - 90,39,10 -END - -IDD_GENERATE DIALOGEX 0, 0, 249, 185 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Generate Game Files" -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "Generate Files",IDOK,139,124,97,25,0,WS_EX_STATICEDGE - DEFPUSHBUTTON "Cancel",IDCANCEL,139,154,97,14,0,WS_EX_STATICEDGE - GROUPBOX "",IDC_STATIC,7,7,235,171 - PUSHBUTTON "&Invert",IDC_INVERT,19,149,47,13,0,WS_EX_STATICEDGE - PUSHBUTTON "Select &All",IDC_SELECTALL,78,149,43,13,0, - WS_EX_STATICEDGE - CONTROL "CSF Format",IDC_UNICODE,"Button",BS_AUTORADIOBUTTON | - WS_GROUP,145,25,53,10 - CONTROL """.str"" Format",IDC_NOXSTR,"Button",BS_AUTORADIOBUTTON | - WS_GROUP,145,36,55,10 - GROUPBOX "Languages",IDC_STATIC,13,14,118,153 - EDITTEXT IDC_PREFIX,170,49,52,12,ES_AUTOHSCROLL - GROUPBOX "File Options",IDC_STATIC,139,14,97,67 - LTEXT "Prefix:",IDC_STATIC,146,52,20,8 - CONTROL "Static",IDC_FILENAME,"Static",SS_LEFTNOWORDWRAP | - SS_SUNKEN | WS_GROUP,145,65,85,11 - LISTBOX IDC_LANGUAGE,19,25,102,117,LBS_SORT | LBS_MULTIPLESEL | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP - CONTROL "Show string IDs",IDC_IDS,"Button",BS_AUTORADIOBUTTON | - WS_GROUP,145,95,88,10 - CONTROL "Show orignal text",IDC_ORIGINAL,"Button", - BS_AUTORADIOBUTTON | WS_GROUP,145,105,70,10 - GROUPBOX "For missing translations",IDC_STATIC,139,85,97,34 -END - -IDD_SETTINGS DIALOGEX 0, 0, 270, 157 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Settings" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - DEFPUSHBUTTON "OK",IDOK,194,126,50,14 - PUSHBUTTON "Cancel",IDCANCEL,17,127,50,14 - GROUPBOX "",IDC_STATIC,7,7,256,143 - EDITTEXT IDC_EDIT1,97,25,90,12,ES_AUTOHSCROLL - LTEXT "Static",IDC_STATIC,27,26,59,8 - PUSHBUTTON "File...",IDC_BUTTON1,191,25,50,14,0,WS_EX_STATICEDGE -END - -IDD_MATCHDIALOG DIALOGEX 0, 0, 340, 213 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "Verify Dialog" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - PUSHBUTTON "Matches",IDOK,196,176,131,24,0,WS_EX_STATICEDGE - DEFPUSHBUTTON "Stop Verifying",IDCANCEL,13,175,56,25,0, - WS_EX_STATICEDGE - GROUPBOX "",IDC_WAVENAME,7,7,326,199 - GROUPBOX "Text",IDC_TEXT_TITLE,14,19,313,137 - LTEXT "",IDC_TEXT,19,30,302,121,SS_SUNKEN - CONTROL "Slider1",IDC_SLIDER,"msctls_trackbar32",TBS_BOTH | - TBS_NOTICKS | WS_TABSTOP,14,161,266,11,WS_EX_STATICEDGE - CONTROL "IDB_STOP",IDC_STOP,"Button",BS_OWNERDRAW | BS_BITMAP | - WS_TABSTOP,284,162,11,8 - CONTROL "IDB_PAUSE",IDC_PAUSE,"Button",BS_OWNERDRAW | BS_BITMAP | - WS_TABSTOP,300,162,11,8 - CONTROL "IDB_PLAY",IDC_PLAY,"Button",BS_OWNERDRAW | BS_BITMAP | - WS_TABSTOP,316,162,11,8 - PUSHBUTTON "Does not match",IDC_NOMATCH,81,182,68,18,0, - WS_EX_STATICEDGE -END - -IDD_PROCEED DIALOG DISCARDABLE 0, 0, 250, 118 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "Proceed?" -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "&Yes",IDC_YES,26,90,50,14 - LTEXT "",IDC_MESSAGE,15,18,220,66 - PUSHBUTTON "Yes &Always",IDC_ALWAYS,98,90,50,14 - PUSHBUTTON "&No",IDC_BUTTON_NO,170,90,50,14 -END - -IDD_MATCH DIALOGEX 0, 0, 423, 183 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "Retranslate changed text?" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - DEFPUSHBUTTON "Skip &All",IDCANCEL,13,142,53,28,0,WS_EX_STATICEDGE - GROUPBOX "",IDC_STATIC,7,7,409,169 - GROUPBOX "Unmatched Text",IDC_STATIC,13,19,193,118 - GROUPBOX "Current Match",IDC_STATIC,211,19,193,151 - PUSHBUTTON "&No Match",IDC_NOMATCH,69,142,53,14,0,WS_EX_STATICEDGE - COMBOBOX IDC_MATCHCOMBO,222,152,174,58,CBS_DROPDOWNLIST | - CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP, - WS_EX_STATICEDGE - PUSHBUTTON "&Match",IDC_MATCH,135,156,70,14,0,WS_EX_STATICEDGE - LTEXT "",IDC_NEWTEXT,21,33,174,95,SS_SUNKEN - LTEXT "",IDC_MATCHTEXT,223,33,174,95,SS_SUNKEN - LTEXT "Possible Matches",IDC_STATIC,223,140,159,10 - CONTROL "Re-translate",IDC_CHECKRETRANSLATE,"Button", - BS_AUTOCHECKBOX | BS_LEFTTEXT | WS_TABSTOP,149,143,54,10 - PUSHBUTTON "&Skip",IDC_SKIP,69,158,53,12,0,WS_EX_STATICEDGE -END - -IDD_VERIFYTEXT DIALOGEX 0, 0, 420, 226 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "Translated text mismatch" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - GROUPBOX "",IDC_STATIC,7,7,406,212 - GROUPBOX "Translated Text",IDC_STATIC,13,19,191,193 - GROUPBOX "Database Text",IDC_STATIC,215,19,189,172 - DEFPUSHBUTTON "&Doesn't Match",IDC_NOMATCH,21,191,70,15,0, - WS_EX_STATICEDGE - PUSHBUTTON "&Matches",IDC_MATCH,125,191,70,15,0,WS_EX_STATICEDGE - LTEXT "",IDC_TRANS,21,33,174,151,SS_SUNKEN - LTEXT "",IDC_ORIG,223,33,174,151,SS_SUNKEN - LTEXT "Do the CONTENTS of the above text match? (i.e. apart from gramatical or spelling differences, are they the same?)", - IDC_STATIC,215,194,189,18 -END - -IDD_CREATE_REPORTS DIALOGEX 0, 0, 249, 185 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Create Report" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - PUSHBUTTON "Create &Report",IDOK,139,124,97,25,0,WS_EX_STATICEDGE - DEFPUSHBUTTON "&Cancel",IDCANCEL,139,154,97,14,0,WS_EX_STATICEDGE - GROUPBOX "",IDC_STATIC,7,7,235,171 - PUSHBUTTON "&Invert",IDC_INVERT,19,149,47,13,0,WS_EX_STATICEDGE - PUSHBUTTON "Select &All",IDC_SELECTALL,78,149,43,13,0, - WS_EX_STATICEDGE - GROUPBOX "Languages",IDC_STATIC,13,14,118,153 - LISTBOX IDC_LANGUAGE,20,25,102,117,LBS_SORT | LBS_MULTIPLESEL | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP - GROUPBOX "Report",IDC_STATIC,139,14,97,104 - CONTROL "&Translation status",IDC_TRANSLATION_STATUS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,145,26,87,10 - CONTROL "&Dialog status",IDC_DIALOG_STATUS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,145,36,87,10 - CONTROL "&Show details",IDC_SHOW_DETAILS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,145,46,87,10 - EDITTEXT IDC_LIMIT,167,68,17,12,ES_AUTOHSCROLL | ES_WANTRETURN | - ES_NUMBER - LTEXT "items",IDC_ITEMS,187,70,17,8 - CONTROL "If less than",IDC_IFLESS,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,157,57,50,10 -END - -IDD_CHARSET DIALOG DISCARDABLE 0, 0, 186, 95 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Dialog" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,129,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14 -END - -IDD_RETRANSLATE DIALOGEX 0, 0, 423, 183 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "Resolve Umatched Text" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - DEFPUSHBUTTON "Skip &All changes",IDCANCEL,13,142,73,28,0, - WS_EX_STATICEDGE - GROUPBOX "",-1,7,7,409,169 - GROUPBOX "New text",-1,13,19,193,118 - GROUPBOX "Old Text",-1,211,19,193,118 - PUSHBUTTON "&No need to Retranslate",IDC_NOMATCH,111,149,95,14,0, - WS_EX_STATICEDGE - PUSHBUTTON "Requires &Retranslation",IDC_MATCH,309,146,95,20,0, - WS_EX_STATICEDGE - LTEXT "",IDC_NEWTEXT,21,33,174,95,SS_SUNKEN - LTEXT "",IDC_OLDTEXT,223,33,174,95,SS_SUNKEN - PUSHBUTTON "&Skip",IDC_SKIP,231,149,53,14,0,WS_EX_STATICEDGE -END - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "\0" - VALUE "CompanyName", "\0" - VALUE "FileDescription", "noxstring MFC Application\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "noxstring\0" - VALUE "LegalCopyright", "Copyright (C) 1999\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "noxstring.EXE\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "noxstring Application\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 228 - TOPMARGIN, 7 - BOTTOMMARGIN, 48 - END - - IDD_NOXSTRING_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 313 - TOPMARGIN, 7 - BOTTOMMARGIN, 250 - END - - IDD_VIEWDBS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 354 - TOPMARGIN, 7 - BOTTOMMARGIN, 166 - END - - IDD_EXPORT, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 270 - TOPMARGIN, 7 - BOTTOMMARGIN, 110 - END - - IDD_GENERATE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 242 - TOPMARGIN, 7 - BOTTOMMARGIN, 178 - END - - IDD_SETTINGS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 263 - TOPMARGIN, 7 - BOTTOMMARGIN, 150 - END - - IDD_MATCHDIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 333 - TOPMARGIN, 7 - BOTTOMMARGIN, 206 - END - - IDD_PROCEED, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 243 - TOPMARGIN, 7 - BOTTOMMARGIN, 111 - END - - IDD_MATCH, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 416 - TOPMARGIN, 7 - BOTTOMMARGIN, 176 - END - - IDD_VERIFYTEXT, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 413 - TOPMARGIN, 7 - BOTTOMMARGIN, 219 - END - - IDD_CREATE_REPORTS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 242 - TOPMARGIN, 7 - BOTTOMMARGIN, 178 - END - - IDD_CHARSET, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 179 - TOPMARGIN, 7 - BOTTOMMARGIN, 88 - END - - IDD_RETRANSLATE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 416 - TOPMARGIN, 7 - BOTTOMMARGIN, 176 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_STOPU BITMAP DISCARDABLE "res\\stop.bmp" -IDB_STOPD BITMAP DISCARDABLE "res\\bitmap1.bmp" -IDB_PLAYU BITMAP DISCARDABLE "res\\playu.bmp" -IDB_PLAYD BITMAP DISCARDABLE "res\\playd.bmp" -IDB_PAUSEU BITMAP DISCARDABLE "res\\pause.bmp" -IDB_PAUSED BITMAP DISCARDABLE "res\\paused.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDP_OLE_INIT_FAILED "OLE initialization failed. Make sure that the OLE libraries are the correct version." - IDS_ABOUTBOX "&About Babylon..." -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#define _AFX_NO_SPLITTER_RESOURCES -#define _AFX_NO_OLE_RESOURCES -#define _AFX_NO_TRACKER_RESOURCES -#define _AFX_NO_PROPERTY_RESOURCES - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE 9, 1 -#pragma code_page(1252) -#endif //_WIN32 -#include "res\noxstring.rc2" // non-Microsoft Visual C++ edited resources -#include "afxres.rc" // Standard components -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Generals/Code/Tools/Babylon/noxstring.reg b/Generals/Code/Tools/Babylon/noxstring.reg deleted file mode 100644 index 14b7c03774..0000000000 --- a/Generals/Code/Tools/Babylon/noxstring.reg +++ /dev/null @@ -1,13 +0,0 @@ -REGEDIT -; This .REG file may be used by your SETUP program. -; If a SETUP program is not available, the entries below will be -; registered in your InitInstance automatically with a call to -; CWinApp::RegisterShellFileTypes and COleObjectFactory::UpdateRegistryAll. - - -HKEY_CLASSES_ROOT\Noxstring.Application = Noxstring Application -HKEY_CLASSES_ROOT\Noxstring.Application\CLSID = {2BF31246-3BA1-11D3-B9DA-006097B90D93} - -HKEY_CLASSES_ROOT\CLSID\{2BF31246-3BA1-11D3-B9DA-006097B90D93} = Noxstring Application -HKEY_CLASSES_ROOT\CLSID\{2BF31246-3BA1-11D3-B9DA-006097B90D93}\ProgId = Noxstring.Application -HKEY_CLASSES_ROOT\CLSID\{2BF31246-3BA1-11D3-B9DA-006097B90D93}\LocalServer32 = NOXSTRING.EXE diff --git a/Generals/Code/Tools/Babylon/noxstringDlg.cpp b/Generals/Code/Tools/Babylon/noxstringDlg.cpp deleted file mode 100644 index aedc8c261f..0000000000 --- a/Generals/Code/Tools/Babylon/noxstringDlg.cpp +++ /dev/null @@ -1,2578 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -// noxstringDlg.cpp : implementation file -// - -#include "StdAfx.h" -#include "noxstring.h" -#include "noxstringDlg.h" -#include "VIEWDBSII.h" -#include "VerifyDlg.h" -#include "ExportDlg.h" -#include "Report.h" -#include "MatchDlg.h" -#include "RetranslateDlg.h" -#include "GenerateDlg.h" -#include "DlgProxy.h" -#include "XLStuff.h" -#include "fileops.h" -#include -#include "iff.h" -#include "loadsave.h" -#include "expimp.h" -#include "ProceedDlg.h" -#include "transcs.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -static char buffer[100*1024]; -static char buffer2[100*1024]; -static char buffer3[100*1024]; -static const int INCREMENTS = 100; -static const int MAX_INFO_LEN = 2*1024; -static int found_error; -static int cb_count; -static CNoxstringDlg *mainDlg; - -static void print_to_log ( const char *text ) -{ - if ( !found_error ) - { - mainDlg->Log ("FAILED", SAME_LINE ); - found_error = TRUE; - } - - sprintf ( buffer, "String %s", text); - mainDlg->Log ( buffer ); - - -} - -static void print_to_log_and_update_progress ( const char *text ) -{ - print_to_log ( text ); - cb_count++; - mainDlg->SetProgress ( cb_count ); -} - -static void cb_progress ( void ) -{ - cb_count++; - mainDlg->SetProgress ( cb_count ); - -} - -typedef struct -{ - char comment[MAX_INFO_LEN+1]; - char context[MAX_INFO_LEN+1]; - char speaker[MAX_INFO_LEN+1]; - char listener[MAX_INFO_LEN+1]; - char wave[MAX_INFO_LEN+1]; - int maxlen; - -} INFO; - -static INFO global_info; -static INFO local_info; - -static void init_info ( INFO *info ) -{ - info->comment[0] = 0; - info->context[0] = 0; - info->speaker[0] = 0; - info->listener[0] = 0; - info->wave[0] = 0; - info->maxlen = 0; -} - -static int progress_count; - -static void progress_cb ( void ) -{ - progress_count++; - if ( MainDLG ) - { - MainDLG->SetProgress ( progress_count ); - } -} - - -static void removeLeadingAndTrailing ( char *buffer ) -{ - char *first, *ptr; - char ch; - - ptr = first = buffer; - - while ( (ch = *first) && iswspace ( ch )) - { - first++; - } - - while ( *ptr++ = *first++ ); - - ptr -= 2;; - - while ( (ptr > buffer) && (ch = *ptr) && iswspace ( ch ) ) - { - ptr--; - } - - ptr++; - *ptr = 0; -} - -///////////////////////////////////////////////////////////////////////////// -// CAboutDlg dialog used for App About - -class CAboutDlg : public CDialog -{ -public: - CAboutDlg(); - -// Dialog Data - //{{AFX_DATA(CAboutDlg) - enum { IDD = IDD_ABOUTBOX }; - //}}AFX_DATA - - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAboutDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - //{{AFX_MSG(CAboutDlg) - virtual BOOL OnInitDialog(); - afx_msg void OnButton1(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) -{ - //{{AFX_DATA_INIT(CAboutDlg) - //}}AFX_DATA_INIT -} - -void CAboutDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CAboutDlg) - //}}AFX_DATA_MAP -} - -BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) - //{{AFX_MSG_MAP(CAboutDlg) - ON_BN_CLICKED(IDC_BUTTON1, OnButton1) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringDlg dialog - -IMPLEMENT_DYNAMIC(CNoxstringDlg, CDialog); - -CNoxstringDlg::CNoxstringDlg(CWnd* pParent /*=NULL*/) - : CDialog(CNoxstringDlg::IDD, pParent) -{ - //{{AFX_DATA_INIT(CNoxstringDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT - // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 - m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); - m_pAutoProxy = NULL; -} - -CNoxstringDlg::~CNoxstringDlg() -{ - // If there is an automation proxy for this dialog, set - // its back pointer to this dialog to NULL, so it knows - // the dialog has been deleted. - if (m_pAutoProxy != NULL) - m_pAutoProxy->m_pDialog = NULL; - -} - -void CNoxstringDlg::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CNoxstringDlg) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - -BEGIN_MESSAGE_MAP(CNoxstringDlg, CDialog) - //{{AFX_MSG_MAP(CNoxstringDlg) - ON_WM_SYSCOMMAND() - ON_WM_PAINT() - ON_WM_QUERYDRAGICON() - ON_WM_CLOSE() - ON_WM_DROPFILES() - ON_BN_CLICKED(IDC_VIEWDBS, OnViewdbs) - ON_BN_CLICKED(IDC_RELOAD, OnReload) - ON_BN_CLICKED(IDC_UPDATE, OnUpdate) - ON_BN_CLICKED(IDC_SAVE, OnSave) - ON_BN_CLICKED(IDC_WARNINGS, OnWarnings) - ON_BN_CLICKED(IDC_ERRORS, OnErrors) - ON_BN_CLICKED(IDC_CHANGES, OnChanges) - ON_BN_CLICKED(IDC_EXPORT, OnExport) - ON_BN_CLICKED(IDC_IMPORT, OnImport) - ON_BN_CLICKED(IDC_GENERATE, OnGenerate) - ON_BN_CLICKED(IDC_DIALOG, OnVerifyDialog) - ON_BN_CLICKED(IDC_TRANSLATIONS, OnTranslations) - ON_CBN_SELCHANGE(IDC_COMBOLANG, OnSelchangeCombolang) - ON_BN_CLICKED(IDC_REPORTS, OnReports) - ON_CBN_DBLCLK(IDC_COMBOLANG, OnDblclkCombolang) - ON_BN_CLICKED(IDC_RESET, OnReset) - ON_BN_CLICKED(IDC_SENT, OnSent) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringDlg message handlers - -BOOL CNoxstringDlg::OnInitDialog() -{ - CDialog::OnInitDialog(); - - // Add "About..." menu item to system menu. - - // IDM_ABOUTBOX must be in the system command range. - ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); - ASSERT(IDM_ABOUTBOX < 0xF000); - - CMenu* pSysMenu = GetSystemMenu(FALSE); - if (pSysMenu != NULL) - { - CString strAboutMenu; - strAboutMenu.LoadString(IDS_ABOUTBOX); - if (!strAboutMenu.IsEmpty()) - { - pSysMenu->AppendMenu(MF_SEPARATOR); - pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); - } - } - - // Set the icon for this dialog. The framework does this automatically - // when the application's main window is not a dialog - SetIcon(m_hIcon, TRUE); // Set big icon - SetIcon(m_hIcon, FALSE); // Set small icon - - // TODO: Add extra initialization here - progress = (CProgressCtrl *) GetDlgItem ( IDC_PROGRESS1 ); - percent = (CStatic *) GetDlgItem ( IDC_PERCENT ); - SetWindowText ( AppTitle ); - Log ( AppTitle ); - { - char buffer[100]; - char date[50]; - char time[50]; - _strtime ( time ); - _strdate ( date ); - sprintf ( buffer, "Session Date: %s %s\n", date, time); - Log ( buffer ); - } - - Status ("Initializing dialog"); - operate_always = FALSE; - combo = ( CComboBox *)GetDlgItem ( IDC_COMBOLANG ); - - int index = 0; - int lang_index = 0; - LANGINFO *info; - while ( (info = GetLangInfo ( lang_index )) ) - { - combo->InsertString ( index, info->name ); - combo->SetItemDataPtr ( index, info ); - index++; - lang_index++; - } - max_index = index; - combo->SetCurSel ( 0 ); - - // do any initialization -#if 0 - // initialize audio - if ( !AIL_quick_startup ( TRUE, FALSE, 22050, 16, 2 ) ) - { - sprintf ( buffer, "Falied to init audio.\n\nReason:%s\n", AIL_last_error ()); - AfxMessageBox ( buffer ); - - } - else - { - onexit ( (_onexit_t ) AIL_quick_shutdown ); - } -#endif - - - Ready();; - - PostMessage ( WM_COMMAND, MAKEWPARAM ( IDC_RELOAD, BN_CLICKED )); - - return TRUE; // return TRUE unless you set the focus to a control -} - -void CNoxstringDlg::OnSysCommand(UINT nID, LPARAM lParam) -{ - if ((nID & 0xFFF0) == IDM_ABOUTBOX) - { - CAboutDlg dlgAbout; - dlgAbout.DoModal(); - } - else - { - CDialog::OnSysCommand(nID, lParam); - } -} - -// If you add a minimize button to your dialog, you will need the code below -// to draw the icon. For MFC applications using the document/view model, -// this is automatically done for you by the framework. - -void CNoxstringDlg::OnPaint() -{ - if (IsIconic()) - { - CPaintDC dc(this); // device context for painting - - SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); - - // Center icon in client rectangle - int cxIcon = GetSystemMetrics(SM_CXICON); - int cyIcon = GetSystemMetrics(SM_CYICON); - CRect rect; - GetClientRect(&rect); - int x = (rect.Width() - cxIcon + 1) / 2; - int y = (rect.Height() - cyIcon + 1) / 2; - - // Draw the icon - dc.DrawIcon(x, y, m_hIcon); - } - else - { - CDialog::OnPaint(); - } -} - -// The system calls this to obtain the cursor to display while the user drags -// the minimized window. -HCURSOR CNoxstringDlg::OnQueryDragIcon() -{ - return (HCURSOR) m_hIcon; -} - -// Automation servers should not exit when a user closes the UI -// if a controller still holds on to one of its objects. These -// message handlers make sure that if the proxy is still in use, -// then the UI is hidden but the dialog remains around if it -// is dismissed. - -void CNoxstringDlg::OnClose() -{ - if (CanExit()) - { - if ( !CanProceed ()) - { - return ; - } - - CDialog::OnOK(); - if ( !SaveLog () ) - { - AfxMessageBox ("Failed to save log!\n\nMake sure babylon.log is writable"); - } - } - -} - -//DEL void CNoxstringDlg::OnOK() -//DEL { -//DEL if (CanExit()) -//DEL CDialog::OnOK(); -//DEL } - -//DEL void CNoxstringDlg::OnCancel() -//DEL { -//DEL if (CanExit()) -//DEL CDialog::OnCancel(); -//DEL } - -BOOL CNoxstringDlg::CanExit() -{ - // If the proxy object is still around, then the automation - // controller is still holding on to this application. Leave - // the dialog around, but hide its UI. - if (m_pAutoProxy != NULL) - { - ShowWindow(SW_HIDE); - return FALSE; - } - - return TRUE; -} - -//DEL void CNoxstringDlg::OnBrowse() -//DEL { -//DEL static char szFilter[] = "XL Files (*.XLS)\0*.xls\0\0\0"; -//DEL -//DEL // TODO: Add your control notification handler code here -//DEL CFileDialog *dlg = new CFileDialog ( TRUE, "xls", "*.xls", OFN_FILEMUSTEXIST, szFilter, this ); -//DEL if ( dlg ) -//DEL { -//DEL dlg->DoModal (); -//DEL if ( dlg->GetPathName() != "*.xls" ) -//DEL { -//DEL SelectFile ( LPCTSTR ( dlg->GetPathName() )); -//DEL } -//DEL else -//DEL { -//DEL SelectFile ( NULL ); -//DEL } -//DEL delete dlg; -//DEL } -//DEL } - -//DEL void CNoxstringDlg::OnChangeXlFilename() -//DEL { -//DEL // TODO: If this is a RICHEDIT control, the control will not -//DEL // send this notification unless you override the CDialog::OnInitDialog() -//DEL // function and call CRichEditCtrl().SetEventMask() -//DEL // with the ENM_CHANGE flag ORed into the mask. -//DEL -//DEL // TODO: Add your control notification handler code here -//DEL -//DEL } - -void CNoxstringDlg::OnExport() -{ - if ( CanOperate ()) - { - CExportDlg dlg; - - if ( dlg.DoModal () == IDOK ) - { - ExportTranslations ( MainDB, dlg.Filename (), dlg.Language(), dlg.Options(), this ); - } - } -} - -BOOL CAboutDlg::OnInitDialog() -{ - CDialog::OnInitDialog(); - - // TODO: Add extra initialization here - - char string[200]; - - sprintf ( string, "Built: %s, %s", __DATE__, __TIME__ ); - SetDlgItemText ( IDC_BUILD, string ); - - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CNoxstringDlg::OnDropFiles(HDROP hDropInfo) -{ - // TODO: Add your message handler code here and/or call default -// char buffer[1024]; -// -// if ( DragQueryFile(hDropInfo, 0, buffer, sizeof ( buffer )-1)) -// { -// -// if ( ConvertStrFile ( buffer ) ) -// { -// return; -// } -// -// if ( SelectFile ( buffer ) ) -// { -// OnExport (); -// } -// } -} - - -//DEL int CNoxstringDlg::SelectFile ( const char *buffer ) -//DEL { -//DEL char *p; -//DEL CWnd *wnd = GetDlgItem ( IDC_EXPORT ); -//DEL -//DEL if ( buffer && (p = strchr ( buffer, '.' )) && !stricmp ( p, ".xls")) -//DEL { -//DEL SetDlgItemText ( IDC_XLFILE, buffer ); -//DEL SetDlgItemText ( IDC_STATUS, "File selected: Click 'convert' to start process"); -//DEL wnd->EnableWindow ( TRUE ); -//DEL return TRUE; -//DEL } -//DEL if ( buffer ) -//DEL { -//DEL AfxMessageBox ("Must be an Excel file"); -//DEL } -//DEL wnd->EnableWindow ( FALSE ); -//DEL SetDlgItemText ( IDC_STATUS, "Select excel file..."); -//DEL SetDlgItemText ( IDC_XLFILE, "Browse or drop excel file to be convertered" ); -//DEL -//DEL return FALSE; -//DEL } - -//DEL int CNoxstringDlg::ConvertStrFile ( const char *buffer ) -//DEL { -//DEL char *p; -//DEL char filename[400]; -//DEL -//DEL if ( buffer && (p = strchr ( buffer, '.' )) && !stricmp ( p, ".str")) -//DEL { -//DEL ParseDB db; -//DEL SetDlgItemText ( IDC_XLFILE, buffer ); -//DEL EnableWindow ( FALSE ); -//DEL SetDlgItemText ( IDC_STATUS, "Parsing .str file"); -//DEL -//DEL if ( db.ParseStrFile ( buffer, this ) ) -//DEL { -//DEL SetDlgItemText ( IDC_STATUS, "Creating .xls file"); -//DEL strcpy ( filename, buffer ); -//DEL p = strchr ( filename, '.' ); -//DEL strcpy ( p, ".xls" ); -//DEL -//DEL if ( db.CreateXLFile ( filename, this ) ) -//DEL { -//DEL SetDlgItemText ( IDC_STATUS, "Created .xls file"); -//DEL } -//DEL else -//DEL { -//DEL SetDlgItemText ( IDC_STATUS, "Falied to create .xls file"); -//DEL } -//DEL -//DEL } -//DEL else -//DEL { -//DEL SetDlgItemText ( IDC_STATUS, "Failed to parse .str file"); -//DEL -//DEL } -//DEL -//DEL EnableWindow ( TRUE ); -//DEL return TRUE; -//DEL } -//DEL return FALSE; -//DEL } - -static int bytes_copied; -static int done_copy; -static int start_copy; -static LogFormat cpy_format; - -static DWORD CALLBACK streamin_cb ( DWORD dwCookie, LPBYTE pbBuff, LONG bytes, LONG *transfered ) -{ - char *src = (char *) dwCookie; - int count = 0; - - src += bytes_copied; - - if ( bytes && start_copy ) - { - if ( cpy_format == NEW_LINE ) - { - *pbBuff++ = '\n'; - count++; - bytes--; - } - start_copy = FALSE; - } - - - while ( bytes-- ) - { - if ( !*src ) - { - done_copy = TRUE; - break; - } - *pbBuff++ = *src++; - bytes_copied++; - count++; - } - *transfered = count; - return 0; -} - -static DWORD CALLBACK streamout_cb ( DWORD dwCookie, LPBYTE pbBuff, LONG bytes, LONG *transfered ) -{ - FILE *log = (FILE *) dwCookie; - int count = 0; - - *transfered = fwrite ( pbBuff, 1, bytes, log ); - return *transfered == -1; -} - -void CNoxstringDlg::Log( const char *string, LogFormat format) -{ - CRichEditCtrl *rec; - EDITSTREAM es; - int lines; - int end_pos; - - rec = (CRichEditCtrl*)GetDlgItem ( IDC_LOG ); - - lines = rec->GetLineCount ( ); - end_pos = rec->LineIndex ( lines ); - - rec->SetSel ( end_pos, end_pos ); - - - //rec->SetReadOnly ( FALSE ); - es.dwCookie = (DWORD) string; - es.dwError = 0; - es.pfnCallback = streamin_cb; - bytes_copied = 0; - done_copy = FALSE; - start_copy = TRUE; - cpy_format = format; - - rec->StreamIn ( SF_TEXT | SFF_SELECTION, es ); - //rec->SetReadOnly ( TRUE ); - lines = rec->GetLineCount ( ); - rec->LineScroll ( -lines, 0 ); - rec->LineScroll ( lines - 10, 0 ); -} - - -void CNoxstringDlg::Status( const char *string, int log ) -{ - char buffer[200]; - int max_len; - - if ( log ) - { - Log ( string ); - } - - max_len = sizeof ( buffer ) -1; - - strcpy ( buffer, "Status: "); - max_len -= strlen ( buffer ); - strncat ( buffer, string, max_len ); - - SetDlgItemText ( IDC_STATUS, buffer ); - -} - -int CNoxstringDlg::SaveLog() -{ - FILE *log = NULL; - EDITSTREAM es; - CRichEditCtrl *rec = (CRichEditCtrl *) GetDlgItem ( IDC_LOG ); - int ok = FALSE; - - - if ( ! (log = fopen ("babylon.log", "a+t" ))) - { - goto error; - } - - { - const char *buffer = "\nLOG START ******************\n\n"; - fwrite ( buffer, 1, strlen ( buffer ), log ); - } - - es.dwCookie = (DWORD) log; - es.dwError = 0; - es.pfnCallback = streamout_cb; - bytes_copied = 0; - done_copy = FALSE; - - rec->StreamOut ( SF_TEXT, es ); - if ( es.dwError ) - { - goto error; - } - - { - const char *buffer = "\nQuiting Babylon\n\nLOG END ******************\n\n"; - fwrite ( buffer, 1, strlen ( buffer ), log ); - } - - ok = TRUE; - -error: - - if ( log ) - { - fclose ( log ); - } - - - return ok; -} - -void CNoxstringDlg::OnViewdbs() -{ - // TODO: Add your control notification handler code here - VIEWDBSII dlg; - - ViewChanges = FALSE; - - dlg.DoModal (); - - -} - -static int readToEndOfQuote( FILE *file, char *in, char *out, char *wavefile, int maxBufLen, int in_comment ) -{ - int slash = FALSE; - int state = 0; - int line_start = FALSE; - char ch; - int new_lines = 0; - int ccount = 0; - - while ( maxBufLen ) - { - // get next char - - if ( in ) - { - if ( !(ch = *in++)) - { - in = NULL; // have exhausted the input buffer - ch = getc ( file ); - } - } - else - { - ch = getc ( file ); - } - - if ( ch == EOF ) - { - AfxMessageBox ( "Missing terminating quote"); - return new_lines; - } - - if ( ch == '\n' ) - { - line_start = TRUE; - if ( !in ) - { - new_lines++; - } - slash = FALSE; - ccount = 0; - ch = ' '; - } - else if ( line_start && ( ch == '/' || iswspace ( ch )) ) - { - continue; - } - else if ( ch == '\\' && !slash) - { - slash = TRUE; - } - else if ( ch == '\\' && slash) - { - slash = FALSE; - } - else if ( ch == '"' && !slash ) - { - break; // done - } - else - { - slash = FALSE; - } - - if ( iswspace ( ch )) - { - ch = ' '; - } - else - { - line_start = FALSE; - } - - *out++ = ch; - maxBufLen--; - } - - *out = 0; - - if ( !wavefile ) - { - return new_lines; - } - - int len = 0; - while ( TRUE ) - { - // get next char - - if ( in ) - { - if ( !(ch = *in++)) - { - in = NULL; // have exhausted the input buffer - ch = getc ( file ); - } - } - else - { - ch = getc ( file ); - } - - if ( ch == '\n' || ch == EOF ) - { - if ( !in ) - { - new_lines++; - } - break; - } - - switch ( state ) - { - - case 0: - if ( iswspace ( ch ) || ch == '=' ) - { - break; - } - - state = 1; - case 1: - if ( (( ch >= 'a' && ch <= 'z') || ( ch >= 'A' && ch <='Z') || (ch >= '0' && ch <= '9') || ch == '_') ) - { - *wavefile++ = ch; - len++; - break; - } - state = 2; - case 2: - break; - } - } - - *wavefile = 0; - if ( len ) - { - if ( ( ch = *(wavefile-1)) < '0' || ch > '9' ) - { - // remove last character - *(wavefile-1) = 0; - } - - } - - return new_lines; -} - -enum -{ - START, - TOKEN, - COLON, - ARG -}; - -static int getString ( FILE *file, char *in, char *out ) -{ - int bytes = MAX_INFO_LEN; - int new_lines = 0; - char ch; - char *ptr = out; - - { - - while ( (ch = *in++) && ch != '\n' && bytes ) - { - *ptr++ = ch; - bytes--; - } - } - - *ptr = 0; - - ConvertMetaChars ( out ); - StripSpaces ( out ); - return new_lines; -} - -static char *getToken ( char *buffer, char *token, int bytes ) -{ - char ch; - int state = START; - *token = 0; - - while ( (ch = *buffer) && ch != '\n' && bytes ) - { - switch ( state ) - { - case START: - if ( ch == '/' || iswspace ( ch )) - { - break; - } - state = TOKEN; - case TOKEN: - if ( !iswspace ( ch ) && ch !=':' ) - { - *token++ = ch; - bytes--; - break; - } - *token = 0; - state = COLON; - case COLON: - if ( ch != ':' ) - { - break; - } - state = ARG; - break; - case ARG: - if ( iswspace ( ch ) ) - { - break; - } - return buffer; - } - buffer++; - } - - *token = 0; - return buffer; - -} - -static int parseComment ( FILE *file, char *buffer, INFO *info ) -{ - char token[256]; - int new_lines = 0; - - buffer = getToken ( buffer, token, sizeof (token) -1 ); - - if ( !token ) - { - return new_lines; - } - - if ( !stricmp ( token, "COMMENT" ) ) - { - new_lines += getString ( file, buffer, info->comment ); - } - else if ( !stricmp ( token, "CONTEXT" ) ) - { - new_lines += getString ( file, buffer, info->context ); - } - else if ( !stricmp ( token, "SPEAKER" ) ) - { - new_lines += getString ( file, buffer, info->speaker ); - } - else if ( !stricmp ( token, "LISTENER" ) ) - { - new_lines += getString ( file, buffer, info->listener ); - } - else if ( !stricmp ( token, "MAXLEN" ) ) - { - info->maxlen = atoi ( buffer ); - } - else if ( !stricmp ( token, "WAVE" ) ) - { - new_lines += getString ( file, buffer, info->wave ); - } - - - return new_lines; -} - -static int getLabelCount( char *filename ) -{ - int count = 0; - FILE *fp; - - if ( ! ( fp = fopen ( filename, "rt" ))) - { - return 0; - } - - while(TRUE) - { - if( fscanf( fp, "%s", buffer ) == EOF ) - break; - - if ( !stricmp( buffer, "END" ) ) - { - count++; - } - } - - fclose ( fp ); - - return count; -} - -int CNoxstringDlg::LoadStrFile ( TransDB *db, const char *filename, void (*cb) ( void ) ) -{ - FILE *file = NULL; - NoxLabel *label = NULL; - int status = FALSE; - int line_number = 0; - int label_count = 0; - int text_dup_count = 0; - int label_dup_count = 0; - - init_info ( &global_info ); - - if ( !(file = fopen ( filename, "rt" ) )) - { - goto exit; - } - - while ( fgets ( buffer, sizeof(buffer)-1, file ) ) - { - - line_number++; - removeLeadingAndTrailing ( buffer ); - - if ( !buffer[0] || (buffer[0] == '/' && buffer[1] == '/') ) - { - line_number += parseComment ( file, buffer, &global_info ); - continue; - } - - label = new NoxLabel ( ); - label->SetName ( buffer ); - label->LockName (); - label->SetLineNumber ( line_number ); - db->AddLabel ( label ); - - local_info = global_info; - local_info.wave[0] = 0; // wave file name is only locally set - while( TRUE ) - { - if ( !fgets ( buffer, sizeof(buffer)-1, file )) - { - AfxMessageBox ( "Unexpected end of file" ); - goto exit; - } - - line_number++; - removeLeadingAndTrailing ( buffer ); - - if ( !stricmp ( buffer, "END" ) ) - { - break; - } - - if ( !buffer[0] || (buffer[0] == '/' && buffer[1] == '/') ) - { - line_number += parseComment ( file, buffer, &local_info ); - continue; - } - - if ( buffer[0] == '"' ) - { - int line = line_number; - strcat ( buffer, "\n" ); - line_number += readToEndOfQuote( file, &buffer[1], buffer2, buffer3, sizeof(buffer2)-1, FALSE ); - NoxText *text = new NoxText ( ); - text->Set ( buffer2 ); - text->FormatMetaString (); - text->LockText (); - if ( buffer3[0] ) - { - text->SetWave ( buffer3 ); - } - else - { - text->SetWave ( local_info.wave ); - } - text->SetLineNumber ( line ); - label->AddText ( text ); - - - } - } - - label->SetComment ( local_info.comment ); - label->SetContext ( local_info.context ); - label->SetSpeaker ( local_info.speaker ); - label->SetListener ( local_info.listener ); - label->SetMaxLen ( local_info.maxlen ); - - if ( cb ) - { - cb (); - } - label = NULL; - - } - status = TRUE; - - -exit: - - db->ClearChanges (); - - if ( label ) - { - delete label; - } - - if ( file ) - { - fclose ( file ); - } - - return status; - -} - -int CNoxstringDlg::CanProceed ( void ) -{ - - if ( MainDB->IsChanged ()) - { - -retry: - int result = AfxMessageBox ( "Main database has changed!\n\n Do you wish to save it before proceeding?", MB_YESNOCANCEL ); - - if ( result == IDCANCEL ) - { - return FALSE; - } - else if ( result == IDYES ) - { - if ( !SaveMainDB () ) - { - AfxMessageBox ("Save failed!\n\nCanceling operation"); - return FALSE; - } - } - else - { - int result = AfxMessageBox ( "Are you sure you don't want to save?\n\nAll current changes will be lost", MB_YESNO ); - if ( result == IDNO ) - { - goto retry; - } - } - } - - return TRUE; -} - - -int CNoxstringDlg::CanOperate ( void ) -{ - if ( operate_always ) - { - return TRUE; - } - - if ( NoxstrDB->IsChanged() || NoxstrDB->HasErrors () ) - { - const char *string = "Unknown problem!\n\n\nProceed anyway?"; - - if ( NoxstrDB->HasErrors ()) - { - string = "Generals.str has errors! As a result the translation database is not up to date!\n\nRecommend you fix problems in Nox.str before proceeding.\n\n\n\nDo you wish to continue anyway?"; - } - - if ( NoxstrDB->IsChanged ()) - { - string = "The translation database is not up to date! Generals.str has changed since the last time the database was updated.\n\nRecommend you update the database before proceeding.\n\n\n\nDo you wish to continue anyway?"; - } - - ProceedDlg dlg ( string ); - - int result = dlg.DoModal (); - - if ( result == IDALWAYS ) - { - operate_always = TRUE; - } - - return result != IDNO; - } - - return TRUE; -} - -void CNoxstringDlg::OnReload() -{ - int num_errors; - int num_warnings; - int count = 0; - int str_loaded = FALSE; - int db_loaded = FALSE; - int db_readonly = FALSE; - int db_error = FALSE; - int do_update = FALSE; - int errors; - CWnd *win; - - // TODO: Add your control notification handler code here - - if ( !CanProceed ()) - { - return; - } - NoxstrDB->Clear (); - NoxstrDB->ClearChanges (); - MainDB->Clear (); - MainDB->ClearChanges (); - - count += getLabelCount ( NoxstrFilename ); - count += GetLabelCountDB ( MainXLSFilename ); - progress_count = 0; - - win = GetDlgItem ( IDC_ERRORS ); - win->EnableWindow ( FALSE ); - win = GetDlgItem ( IDC_WARNINGS ); - win->EnableWindow ( FALSE ); - win = GetDlgItem ( IDC_UPDATE ); - win->EnableWindow ( TRUE); - win = GetDlgItem ( IDC_SAVE ); - win->EnableWindow ( TRUE); - win = GetDlgItem ( IDC_IMPORT ); - win->EnableWindow ( TRUE); - win = GetDlgItem ( IDC_EXPORT ); - win->EnableWindow ( TRUE); - - InitProgress ( count ); - Log ("" ); - - if ( FileExists ( NoxstrFilename )) - { - if ( (errors = ValidateStrFile ( NoxstrFilename )) ) - { - if ( errors == -1 ) - { - if ( AfxMessageBox ( "Unable to verify string file!\n\nMake sure \"strcheck.exe\" is in your path and \"strcheck.rst\" is writeable.\n\nDo you wish to continue loading? \n\nWarning: Any errors in the string file could cause inappropiate updates to the database.", MB_YESNO ) == IDYES ) - { - errors = 0; - } - } - else - { - sprintf ( buffer, "\"%s\" has %d formating error%s!\n\nFile will not be loaded.", NoxstrFilename, errors, errors == 1 ? "" : "s" ); - AfxMessageBox ( buffer ); - } - } - if ( !errors ) - { - sprintf ( buffer, "Loading \"%s\"...", NoxstrFilename ); - Status ( buffer ); - - if ( !(str_loaded = LoadStrFile ( NoxstrDB, NoxstrFilename, progress_cb )) ) - { - Log ( "FAILED", SAME_LINE ); - NoxstrDB->Clear (); - NoxstrDB->ClearChanges (); - } - } - else - { - sprintf ( buffer, "Loading \"%s\"...NOT LOADED", NoxstrFilename ); - Log ( buffer ); - } - } - else - { - sprintf ( buffer, "Loading \"%s\"...", NoxstrFilename ); - Status ( buffer ); - Log ( "FILE NOT FOUND", SAME_LINE ); - } - - if ( str_loaded ) - { - sprintf ( buffer, "Validating \"%s\"...", NoxstrFilename ); - Status ( buffer, FALSE ); - - if ( (num_errors = NoxstrDB->Errors ( ))) - { - sprintf ( buffer, "Generals.str has %d error(s):\n\nClick \"Errors\" for a detailed list.\n\nAll errors must be fixed before \"Update\" will be enabled.", num_errors ); - AfxMessageBox ( buffer ); - win = GetDlgItem ( IDC_UPDATE ); - win->EnableWindow ( FALSE); - win = GetDlgItem ( IDC_ERRORS ); - win->EnableWindow ( TRUE ); - } - - if ( (num_warnings = NoxstrDB->Warnings())) - { - win = GetDlgItem ( IDC_WARNINGS ); - win->EnableWindow ( TRUE ); - } - - if ( !num_errors && !num_warnings ) - { - Log ( "OK", SAME_LINE ); - } - else - { - sprintf ( buffer, "%d errors, %d warnings OK", num_errors, num_warnings ); - Log ( buffer, SAME_LINE ); - } - } - - sprintf ( buffer, "Loading \"%s\"...", MainXLSFilename ); - Status ( buffer ); - - if ( FileExists ( MainXLSFilename )) - { - if ( !(db_loaded = LoadMainDB ( MainDB, MainXLSFilename, progress_cb )) ) - { - Log ( "FAILED", SAME_LINE ); - MainDB->Clear (); - MainDB->ClearChanges (); - db_error = TRUE; - win = GetDlgItem ( IDC_UPDATE ); - win->EnableWindow ( FALSE); - win = GetDlgItem ( IDC_SAVE ); - win->EnableWindow ( FALSE); - win = GetDlgItem ( IDC_EXPORT ); - win->EnableWindow ( FALSE); - win = GetDlgItem ( IDC_IMPORT ); - win->EnableWindow ( FALSE); - } - else - { - if ( FileAttribs ( MainXLSFilename ) & FA_READONLY ) - { - AfxMessageBox ( "Database file is readonly!\n\nNo updates will be allowed.\n\nCheckout the database file and reload."); - db_readonly = TRUE; - win = GetDlgItem ( IDC_UPDATE ); - win->EnableWindow ( FALSE); - win = GetDlgItem ( IDC_SAVE ); - win->EnableWindow ( FALSE); - win = GetDlgItem ( IDC_IMPORT ); - win->EnableWindow ( FALSE); - Log ( "READONLY", SAME_LINE ); - } - else - { - Log ( "OK", SAME_LINE ); - } - } - } - else - { - Log ( "FILE NOT FOUND", SAME_LINE ); - } - - if ( str_loaded && !db_error && !num_errors ) - { - if ( UpdateDB ( NoxstrDB, MainDB, FALSE ) ) - { - NoxstrDB->Changed (); - if ( db_loaded ) - { - if ( db_readonly ) - { - sprintf ( buffer, "\"%s\" has changed!\n\nHowever, as the database is READ ONLY you cannot update the changes.", NoxstrFilename); - } - else - { - sprintf ( buffer, "\"%s\" has changed!\n\nRecomended that you update the database with these new changes.\n\nDo you wish to update now?", NoxstrFilename); - } - } - else - { - sprintf ( buffer, "New Database!\n\nRecomended that you update the new database.\n\nDo you wish to update now?", NoxstrFilename); - } - - if ( db_readonly ) - { - do_update = FALSE; - AfxMessageBox ( buffer ); - - } - else - { - do_update = (AfxMessageBox ( buffer, MB_YESNO ) == IDYES); - } - } - } - ProgressComplete (); - Ready (); - - if ( do_update ) - { - OnUpdate (); - } -} - -void CNoxstringDlg::InitProgress(int range) -{ - - if ( (progress_range = range) <= 0 ) - { - progress_range = 1; - } - - progress->SetRange ( 0, INCREMENTS ); - progress_pos = -1; - progress->SetPos ( 0 ); -} - -void CNoxstringDlg::SetProgress(int pos) -{ - char string[20]; - - int new_pos = (pos * 100 ) / progress_range; - - if ( new_pos > 100 ) - { - new_pos = 100; - } - else if ( new_pos < 0 ) - { - new_pos = 0; - } - - if ( new_pos == progress_pos ) - { - return; - } - - progress->SetPos ( new_pos ); - progress_pos = new_pos; - sprintf ( string, "%d%% ", progress_pos ); - percent->SetWindowText ( string ); - -} - -void CNoxstringDlg::ProgressComplete() -{ - progress->SetPos ( 100 ); - percent->SetWindowText ( "100% "); -} - -void CNoxstringDlg::OnUpdate() -{ - // TODO: Add your control notification handler code here - - UpdateDB ( NoxstrDB, MainDB ); - -} - -#define MACRO_UPDATE(field,count) { if ( wcsicmp ( source->##field () , destination->##field ())) \ - { \ - if ( update ) \ - { \ - destination->Set##field ( source->##field () ); \ - } \ - label_modified = TRUE; \ - info.changes++; \ - (count)++; \ - } \ - } - - -int CNoxstringDlg::UpdateLabel( NoxLabel *source, NoxLabel *destination, UPDATEINFO &info, int update, int skip ) -{ - NoxText *stext, *dtext; - ListSearch sh; - TransDB *destDB, *srcDB; - int label_modified = FALSE; - - destination->ClearMatched (); - source->ClearMatched (); - destDB = destination->DB(); - srcDB = source->DB (); - - // first go through and match up as many strings as possible - - stext = source->FirstText ( sh ); - - while ( stext ) - { - - dtext = destDB->FindText ( stext->Get ()); - - // remember FindText() spans labels so keep looking till we find - // one that belongs to the label we are checking - while ( dtext && (dtext->Label () != destination) ) - { - dtext = destDB->FindNextText (); - } - - if ( dtext && dtext->Matched ()) - { - AfxMessageBox ( "Fatal error: substring already matched" ); - return FALSE; - } - - if ( dtext ) - { - // we have a matching string so mark it - dtext->Match ( stext ); - stext->Match ( dtext ); - - } - - stext = source->NextText ( sh ); - } - - - // ask the user to resolve remaing unmatched strings - - { - - stext = source->FirstText ( sh ); - - while ( stext ) - { - if ( destination->AllMatched ()) - { - // no point trying to match anymore - break; - } - - if ( !stext->Matched () ) - { - int result; - NoxText *match = NULL; - - if ( update && !skip ) - { - if ( destination->DB()->MultiTextAllowed()) - { - result = MatchText ( stext, destination, &match ); - } - else - { - ListSearch tsh; - NoxText *oldtext = destination->FirstText ( tsh ); - if ( !oldtext ) - { - break; - } - result = RetranslateText ( stext, oldtext ); - match = oldtext; - } - } - else - { - result = IDSKIP; - } - - if ( result == IDCANCEL || result == IDSKIP) - { - return result; - } - - if ( match ) - { - stext->Match ( match ); - match->Match ( stext ); - } - stext->Processed (); - } - stext = source->NextText ( sh ); - } - } - - - // go through all matched strings and update them accordingly - - dtext = destination->FirstText ( sh ); - - while ( dtext ) - { - - if ( (stext = (NoxText *) dtext->Matched ()) ) - { - // stext is the newer version; - if ( wcscmp ( dtext->Get (), stext->Get ())) - { - if ( update ) - { - dtext->Set ( stext->Get ()); - } - info.modified_strings++; - label_modified = TRUE; - info.changes ++; - } - if ( wcsicmp ( dtext->Wave (), stext->Wave ())) - { - if ( update ) - { - dtext->SetWave ( stext->Wave ()); - } - info.updated_waves++; - label_modified = TRUE; - info.changes ++; - } - if ( dtext->Retranslate ()) - { - if ( update ) - { - dtext->IncRevision (); - } - label_modified = TRUE; - } - dtext->SetRetranslate ( FALSE ); - } - - dtext = destination->NextText ( sh ); - } - - - // any remaining umatched text in the source are new strings - // any remaining umatched text in the destination are now obsolete - - // delete old strings from destination - - dtext = destination->FirstText ( sh ); - - while ( dtext ) - { - NoxText *next = destination->NextText ( sh ); - - if ( !dtext->Matched ()) - { - if ( update ) - { - dtext->Remove (); - destDB->AddObsolete ( dtext ); - } - info.deleted_strings++; - label_modified = TRUE; - info.changes ++; - } - - dtext = next; - } - - // add new strings from source - - stext = source->FirstText ( sh ); - - while ( stext ) - { - - if ( !stext->Matched ()) - { - if ( update ) - { - dtext = stext->Clone (); - destination->AddText ( dtext ); - } - info.new_strings++; - label_modified = TRUE; - info.changes ++; - } - - stext = source->NextText ( sh ); - } - - // finally update label info - MACRO_UPDATE(Comment, info.updated_comments); - MACRO_UPDATE(Context, info.updated_contexts); - MACRO_UPDATE(Speaker, info.updated_speakers); - MACRO_UPDATE(Listener, info.updated_listeners); - - if ( destination->MaxLen () != source->MaxLen ()) - { - if ( update ) - { - destination->SetMaxLen ( source->MaxLen ()); - } - label_modified = TRUE; - info.updated_maxlen++; - info.changes ++; - } - - - if ( label_modified ) - { - if ( update ) - { - source->ClearChanges (); - } - else - { - source->Changed (); - } - - info.modified_labels ++; - } - - return IDOK; - -} - -int CNoxstringDlg::UpdateDB(TransDB *source, TransDB *destination, int update ) -{ - NoxLabel *slabel; - NoxLabel *dlabel; - ListSearch sh; - int count = 0; - int result = IDOK; - UPDATEINFO info; - int changes = FALSE; - int diffs = 0; - int skip_all = FALSE; - - memset ( &info, 0, sizeof ( info )); - if ( update ) - { - sprintf ( buffer, "Updating \"%s\" from \"%s\"...", destination->Name(), source->Name()); - Log(""); - Status ( buffer ); - } - else - { - Status ("Checking for changes...", FALSE ); - } - - source->ClearProcessed (); - destination->ClearProcessed (); - - if ( update ) - { - InitProgress ( source->NumLabels() ); - } - slabel = source->FirstLabel ( sh ); - - while ( slabel ) - { - if ( (dlabel = destination->FindLabel ( slabel->Name ()))) - { - dlabel->Processed (); - - result = UpdateLabel ( slabel, dlabel, info, update, skip_all ); - - if ( result == IDCANCEL ) - { - skip_all = TRUE; - } - - if ( result == IDOK ) - { - if ( update ) - { - slabel->ClearChanges (); - } - } - else - { - info.skipped_labels ++; - info.changes ++; - if ( !update ) - { - slabel->Changed(); - } - } - } - else - { - NoxLabel *clone; - - if ( update ) - { - clone = slabel->Clone (); - destination->AddLabel ( clone ); - clone->Processed (); - slabel->ClearChanges (); - } - else - { - slabel->Changed (); - } - info.new_strings += slabel->NumStrings (); - info.changes += slabel->NumStrings (); - info.new_labels++; - info.changes++; - } - - count++; - if ( update ) - { - SetProgress ( count ); - } - - slabel->Processed (); - slabel = source->NextLabel ( sh ); - } - - // go through all unprocessed labels in the destination database and remove them. - dlabel = destination->FirstLabel ( sh ); - - while ( dlabel ) - { - NoxLabel *next_label = destination->NextLabel ( sh ); - - if ( !dlabel->IsProcessed ()) - { - // this label was not matched so is obsolete - ListSearch sh_text; - NoxText *dtext = dlabel->FirstText ( sh_text); - - while ( dtext ) - { - NoxText *next = dlabel->NextText ( sh_text ); - - if ( update ) - { - dtext->Remove (); - destination->AddObsolete ( dtext ); - } - - info.deleted_strings++; - info.changes ++; - - dtext = next; - } - - if ( update ) - { - dlabel->Remove (); - delete dlabel; - } - - info.deleted_labels++; - } - - dlabel = next_label; - } - - - if ( update ) - { - if ( info.new_labels ) - { - sprintf ( buffer, "Added %d new label%c", info.new_labels, info.new_labels==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.deleted_labels ) - { - sprintf ( buffer, "Deleted %d label%c", info.deleted_labels, info.deleted_labels==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.modified_labels ) - { - sprintf ( buffer, "Modified %d label%c", info.modified_labels, info.modified_labels==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.new_strings ) - { - sprintf ( buffer, "Added %d new string%c", info.new_strings, info.new_strings==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.deleted_strings ) - { - sprintf ( buffer, "Deleted %d string%c", info.deleted_strings, info.deleted_strings==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.modified_strings ) - { - sprintf ( buffer, "Modified %d string%c", info.modified_strings, info.modified_strings==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.skipped_labels ) - { - sprintf ( buffer, "Skipped %d label%c", info.skipped_labels, info.skipped_labels==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.updated_comments ) - { - sprintf ( buffer, "Updated %d comment%c", info.updated_comments, info.updated_comments==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.updated_contexts ) - { - sprintf ( buffer, "Updated %d context%c", info.updated_contexts, info.updated_contexts==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.updated_speakers ) - { - sprintf ( buffer, "Updated %d speaker%c", info.updated_speakers, info.updated_speakers==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.updated_listeners ) - { - sprintf ( buffer, "Updated %d listener%c", info.updated_listeners, info.updated_listeners==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.updated_maxlen ) - { - sprintf ( buffer, "Updated %d max length%c", info.updated_maxlen, info.updated_maxlen==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( info.updated_waves ) - { - sprintf ( buffer, "Updated %d speech file%c", info.updated_waves, info.updated_waves==1?' ':'s' ); - Log ( buffer ); - changes = TRUE; - } - - if ( !changes ) - { - if ( !slabel && !info.skipped_labels) - { - Log ( "No differences found" ); - } - else - { - Log ( "No changes made" ); - } - } - - if ( result == IDCANCEL ) - { - Log ("Update aborted by user!" ); - InitProgress ( 100 ); - } - else - { - if ( !info.skipped_labels ) - { - source->ClearChanges (); - } - } - } // update - - - Ready (); - - return info.changes; -} - -void CNoxstringDlg::OnSave() -{ - - if ( CanOperate ()) - { - SaveMainDB ( ); - } -} - -int CNoxstringDlg::SaveMainDB( ) -{ - TransDB *db = MainDB; - const char *filename = MainXLSFilename; - int attribs; - - if ( !db ) - { - return TRUE; - } - - if ( !db->IsChanged ()) - { - return TRUE; - } - - attribs = FileAttribs ( filename ); - - if ( attribs & FA_READONLY ) - { - char buffer[100]; - sprintf ( buffer, "Cannot save changes!\n\nFile \"%s\" is read only", filename ); - AfxMessageBox ( buffer ); - sprintf ( buffer, "Cannot save to \"%s\". File is read only", filename ); - Log ( buffer ); - Status ("Save failed", FALSE ); - return FALSE; - } - - Log(""); - Status ( "Saving main database..." ); - - if ( attribs != FA_NOFILE ) - { - MakeBackupFile ( filename ); - } - - if ( !WriteMainDB ( db, filename, this ) ) - { - RestoreBackupFile ( filename ); - Log ("FAILED", SAME_LINE ); - Status ("Save failed", FALSE ); - return FALSE; - } - else - { - Log ("OK", SAME_LINE ); - } - - Ready(); - return TRUE; -} - - -void CNoxstringDlg::OnWarnings() -{ - // TODO: Add your control notification handler code here - if ( NoxstrDB ) - { - NoxstrDB->Warnings ( this ); - } - -} - - -void CNoxstringDlg::OnErrors() -{ - // TODO: Add your control notification handler code here - if ( NoxstrDB ) - { - NoxstrDB->Errors ( this ); - } -} - - -int CNoxstringDlg::MatchText ( NoxText *text, NoxLabel *label, NoxText **match ) -{ - CMatchDlg dlg; - int result; - - *match = NULL; - sprintf ( buffer, "Text: %s\n\nLabel:%s\n", text->GetSB (), label->NameSB () ); - - // TODO: Add your control notification handler code here - - MatchOriginalText = text; - MatchLabel = label; - - result = dlg.DoModal (); - - if ( result != IDCANCEL ) - { - *match = MatchingNoxText; - } - - return result; - -} - -int CNoxstringDlg::RetranslateText ( NoxText *newtext, NoxText *oldtext ) -{ - RetranslateDlg dlg; - int result; - - // TODO: Add your control notification handler code here - - dlg.newtext = newtext; - dlg.oldtext = oldtext; - - result = dlg.DoModal ( ); - - return result; - -} -void CNoxstringDlg::OnChanges() -{ - // TODO: Add your control notification handler code here - - VIEWDBSII dlg; - - ViewChanges = TRUE; - - dlg.DoModal (); - - - -} - -void CNoxstringDlg::OnImport() -{ - if ( CanOperate ()) - { - CFileDialog fd ( TRUE , NULL, "*.xls", OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR ); - - if ( fd.DoModal () == IDOK ) - { - if (ImportTranslations ( MainDB, (LPCSTR ) fd.GetPathName (), this ) == -1 ) - { -// ProcessWaves ( NoxstrDB, fd.GetPathName (), this ); - } - } - } -} - -void CNoxstringDlg::OnGenerate() -{ - if ( CanOperate ()) - { - CGenerateDlg dlg; - - if ( dlg.DoModal () == IDOK ) - { - GenerateGameFiles ( MainDB, dlg.FilePrefix(), dlg.Options(), dlg.Langauges(), this ); - } - } -} - -int CNoxstringDlg::ValidateStrFile( const char *filename) -{ - STARTUPINFO StartupInfo = { 0 }; - PROCESS_INFORMATION ProcessInfo; - const char *results = "strcheck.rst"; - int errors = 0; - FILE *file = NULL; - - StartupInfo.cb = sizeof(STARTUPINFO); - StartupInfo.dwFlags = STARTF_USESHOWWINDOW; - StartupInfo.wShowWindow = SW_SHOWMINNOACTIVE; - - Log (""); - sprintf ( buffer, "Verifying \"%s\"...", filename ); - Status ( buffer ); - if ( FileExists ( results )) - { - DeleteFile ( results ); - } - - sprintf ( buffer, "strcheck %s %s", filename, results ); - - if (!CreateProcess( - NULL, - buffer, - NULL, - NULL, - FALSE, - 0, - NULL, - NULL, - &StartupInfo, - &ProcessInfo)) - { - goto error; - } - - - WaitForSingleObject(ProcessInfo.hProcess, INFINITE); - - //this->SetForegroundWindow (); - //this->RedrawWindow (); - - if ( !(file = fopen ( results, "rt" ))) - { - goto error; - } - - while ( fgets ( buffer, sizeof(buffer), file ) ) - { - strlwr ( buffer ); - if ( strstr ( buffer, "error") || strstr ( buffer, "warning" )) - { - errors++; - } - } - - if ( errors ) - { - sprintf ( buffer, "%d ERROR%s", errors, errors == 1 ? "" : "S" ); - Log (buffer, SAME_LINE ); - fseek ( file, 0, SEEK_SET ); - while ( fgets ( buffer, sizeof(buffer), file ) ) - { - sprintf ( buffer2, " strcheck> %s", buffer ); - strlwr ( buffer ); - if ( strstr ( buffer2, "error") || strstr ( buffer, "warning" ) ) - { - int len = strlen ( buffer2 ); - - if ( buffer2[len-1] == '\n' ) - { - buffer2[len-1] = 0; - } - Log ( buffer2 ); - } - } - - - } - else - { - Log ("OK", SAME_LINE ); - } - - -done: - - if ( FileExists ( results )) - { - DeleteFile ( results ); - } - - if (file ) - { - fclose (file ); - } - - return errors; - -error: - Log ( "UNABLE TO VERIFY", SAME_LINE ); - errors = -1; - goto done; -} - -void CNoxstringDlg::OnVerifyDialog() -{ - if ( MainDB && CanOperate () ) - { - VerifyDialog ( MainDB, CurrentLanguage ); - } - -} - -void CNoxstringDlg::VerifyDialog( TransDB *db, LangID langid ) -{ - NoxLabel *label; - ListSearch sh_label; - int count = 0; - DLGREPORT _info; - DLGREPORT *info = &_info; - - Log (""); - - sprintf ( buffer, "Verifying %s dialog...", GetLangName ( langid ) ); - Status ( buffer ); - - InitProgress ( db->NumLabels () ); - cb_count = 0; - mainDlg = this; - db->VerifyDialog ( langid, cb_progress ); - db->ReportDialog ( info, langid); - - if ( info->unresolved ) - { - Status ( "Verification", FALSE); - - InitProgress ( info->unresolved ); - - label = db->FirstLabel ( sh_label ); - - while ( label ) - { - NoxText *text; - ListSearch sh_text; - - text = label->FirstText ( sh_text ); - - while ( text ) - { - if ( text->IsDialog ()) - { - if ( text->DialogIsPresent ( DialogPath, langid )) - { - if ( !text->DialogIsValid ( DialogPath, langid, FALSE ) ) - { - VerifyDlg dlg(text, langid, DialogPath); - int result; - - result = dlg.DoModal (); - - if ( result == IDCANCEL ) - { - goto done; - } - if ( result == IDOK ) - { - text->ValidateDialog ( DialogPath, langid ); - } - - count++; - SetProgress ( count ); - } - } - } - - text = label->NextText ( sh_text ); - } - - label = db->NextLabel ( sh_label ); - } - } - -done: - Ready (); - - Status ( "Collecting stats...", FALSE ); - - count = db->ReportDialog ( info, langid ); - - if ( count < 100 ) - { - InitProgress ( count ); - - cb_count = 0; - found_error = FALSE; - mainDlg = this; - db->ReportDialog ( info, langid, print_to_log_and_update_progress ); - } - - if ( info->numdialog ) - { - if ( info->errors || info->missing || info->unresolved ) - { - if ( !found_error ) - { - Log ( "FAILED", SAME_LINE ); - } - - if ( info->errors ) - { - sprintf ( buffer, "Errors : %d", info->errors ); - Log ( buffer ); - } - - if ( info->missing ) - { - sprintf ( buffer, "Missing dialog : %d", info->missing ); - Log ( buffer ); - } - - if ( info->unresolved ) - { - sprintf ( buffer, "Unverified dialog: %d", info->unresolved ); - Log ( buffer ); - } - - if ( info->resolved ) - { - sprintf ( buffer, "Verified dialog : %d", info->resolved ); - Log ( buffer ); - } - - } - else - { - Log ( "OK", SAME_LINE ); - - if ( info->resolved ) - { - sprintf ( buffer, "Verified dialog : %d", info->resolved ); - Log ( buffer ); - } - } - sprintf ( buffer, "Total dialog : %d", info->numdialog ); - Log ( buffer ); - } - else - { - Log ( "NO DIALOG FOUND", SAME_LINE ); - } - - Ready(); - -} - -void CNoxstringDlg::VerifyTranslations( TransDB *db, LangID langid ) -{ - int count = 0; - TRNREPORT _info; - TRNREPORT *info = &_info; - - Log (""); - sprintf ( buffer, "Verifying %s text...", GetLangName ( langid ) ); - Status ( buffer ); - - count = db->ReportTranslations ( info, langid ); - - if ( count < 100 ) - { - InitProgress ( count); - cb_count = 0; - found_error = FALSE; - mainDlg = this; - db->ReportTranslations ( info, langid, print_to_log_and_update_progress ); - } - - if ( info->numstrings ) - { - if ( info->too_big || info->missing || info->retranslate || info->bad_format ) - { - - if ( info->missing ) - { - sprintf ( buffer, "Missing translations: %d", info->missing ); - Log ( buffer ); - } - - if ( info->too_big ) - { - sprintf ( buffer, "Oversized strings : %d", info->too_big ); - Log ( buffer ); - } - - if ( info->retranslate ) - { - sprintf ( buffer, "Retranslations : %d", info->retranslate); - Log ( buffer ); - } - - if ( info->bad_format ) - { - sprintf ( buffer, "Badly formated translations: %d", info->bad_format); - Log ( buffer ); - } - - if ( langid == LANGID_US ) - { - sprintf ( buffer, "Recommemd editing \"%s\" to fix problems and reload", NoxstrFilename ); - } - else - { - sprintf ( buffer, "Recommemd exporting translations for update and re-import" ); - } - Log ( buffer ); - } - else - { - Log ( "OK", SAME_LINE ); - - } - } - else - { - Log ( "NO TEXT", SAME_LINE ); - } - - Ready(); -} - -void CNoxstringDlg::OnTranslations() -{ - if ( MainDB && CanOperate () ) - { - - VerifyTranslations ( MainDB, CurrentLanguage ); - } - - -} - -void CNoxstringDlg::OnSelchangeCombolang() -{ - LANGINFO *info = NULL; - int index; - - index = combo->GetCurSel (); - - if ( index >= 0 && index < max_index ) - { - info = (LANGINFO *) combo->GetItemDataPtr ( index ); - } - - if ( info ) - { - CurrentLanguage = info->langid; - } - else - { - CurrentLanguage = LANGID_UNKNOWN; - } - -} - -void CNoxstringDlg::OnReports() -{ - // TODO: Add your control notification handler code here - if ( CanOperate ()) - { - CReport dlg; - - if ( dlg.DoModal () == IDOK ) - { - GenerateReport ( MainDB, dlg.Filename(), dlg.Options(), dlg.Langauges(), this ); - } - } - -} - -void CNoxstringDlg::OnDblclkCombolang() -{ - // TODO: Add your control notification handler code here -} - -void CNoxstringDlg::OnReset() -{ - // TODO: Add your control notification handler code here - - if ( CurrentLanguage != LANGID_UNKNOWN ) - { - sprintf ( buffer, "Are you sure you want to invalidate all %s dialog?", GetLangName ( CurrentLanguage )); - if ( AfxMessageBox ( buffer, MB_YESNO) == IDYES ) - { - MainDB->InvalidateDialog ( CurrentLanguage ); - } - } -} - -void CNoxstringDlg::OnSent() -{ - // TODO: Add your control notification handler code here - if ( CanOperate ()) - { - CFileDialog fd ( TRUE , NULL, "*.xls", OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR ); - - if ( fd.DoModal () == IDOK ) - { - UpdateSentTranslations ( MainDB, (LPCSTR ) fd.GetPathName (), this ); - } - } -} - -void CAboutDlg::OnButton1() -{ - // TODO: Add your control notification handler code here - - CreateTranslationTable ( ); -} - diff --git a/Generals/Code/Tools/Babylon/noxstringDlg.h b/Generals/Code/Tools/Babylon/noxstringDlg.h deleted file mode 100644 index 03da2cbc4a..0000000000 --- a/Generals/Code/Tools/Babylon/noxstringDlg.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// noxstringDlg.h : header file -// - -#if !defined(AFX_NOXSTRINGDLG_H__2BF3124D_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) -#define AFX_NOXSTRINGDLG_H__2BF3124D_3BA1_11D3_B9DA_006097B90D93__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "resource.h" -#include "TransDB.h" - -typedef enum -{ - SAME_LINE, - NEW_LINE - -} LogFormat; - - -typedef struct -{ - int new_strings; - int deleted_strings; - int modified_strings; - int new_labels; - int deleted_labels; - int modified_labels; - int skipped_labels; - int updated_comments; - int updated_contexts; - int updated_waves; - int updated_speakers; - int updated_listeners; - int updated_maxlen; - int changes; - - - -} UPDATEINFO; - -class CNoxstringDlgAutoProxy; - -///////////////////////////////////////////////////////////////////////////// -// CNoxstringDlg dialog - -class CNoxstringDlg : public CDialog -{ - DECLARE_DYNAMIC(CNoxstringDlg); - friend class CNoxstringDlgAutoProxy; - CProgressCtrl *progress; - CStatic *percent; - int progress_pos; - int progress_range; - int max_index; - CComboBox *combo; - int operate_always; - - - -// Construction -public: - int ValidateStrFile ( const char *filename ); - int MatchText ( NoxText *text, NoxLabel *label, NoxText **match ); - int RetranslateText ( NoxText *text, NoxText *label ); - void VerifyDialog( TransDB *db, LangID langid); - void VerifyTranslations( TransDB *db, LangID langid ) ; - int CanProceed ( void ); - int CanOperate ( void ); - int SaveMainDB ( void ); - int UpdateLabel ( NoxLabel *source, NoxLabel *destination, UPDATEINFO &info, int update = TRUE, int skip = FALSE); - int UpdateDB ( TransDB *source, TransDB *destination, int update = TRUE); - void ProgressComplete ( void ); - void SetProgress ( int pos ); - void InitProgress ( int range ); - int SaveLog ( void ); - void Status ( const char *string, int log = TRUE); - void Log ( const char *string, LogFormat format = NEW_LINE ); - CNoxstringDlg(CWnd* pParent = NULL); // standard constructor - virtual ~CNoxstringDlg(); - int LoadStrFile ( TransDB *db, const char *fileaname, void (*cb ) (void ) = NULL ); - void Ready ( void ) { Status ( "Ready", FALSE ); ProgressComplete(); }; - -// Dialog Data - //{{AFX_DATA(CNoxstringDlg) - enum { IDD = IDD_NOXSTRING_DIALOG }; - // NOTE: the ClassWizard will add data members here - //}}AFX_DATA - - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CNoxstringDlg) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - CNoxstringDlgAutoProxy* m_pAutoProxy; - HICON m_hIcon; - - BOOL CanExit(); - - // Generated message map functions - //{{AFX_MSG(CNoxstringDlg) - virtual BOOL OnInitDialog(); - afx_msg void OnSysCommand(UINT nID, LPARAM lParam); - afx_msg void OnPaint(); - afx_msg HCURSOR OnQueryDragIcon(); - afx_msg void OnClose(); - afx_msg void OnDropFiles(HDROP hDropInfo); - afx_msg void OnViewdbs(); - afx_msg void OnReload(); - afx_msg void OnUpdate(); - afx_msg void OnSave(); - afx_msg void OnWarnings(); - afx_msg void OnErrors(); - afx_msg void OnChanges(); - afx_msg void OnExport(); - afx_msg void OnImport(); - afx_msg void OnGenerate(); - afx_msg void OnVerifyDialog(); - afx_msg void OnTranslations(); - afx_msg void OnSelchangeCombolang(); - afx_msg void OnReports(); - afx_msg void OnDblclkCombolang(); - afx_msg void OnReset(); - afx_msg void OnSent(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -extern CNoxstringDlg *MainDLG; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_NOXSTRINGDLG_H__2BF3124D_3BA1_11D3_B9DA_006097B90D93__INCLUDED_) diff --git a/Generals/Code/Tools/Babylon/olestring.cpp b/Generals/Code/Tools/Babylon/olestring.cpp deleted file mode 100644 index b9681c5b9e..0000000000 --- a/Generals/Code/Tools/Babylon/olestring.cpp +++ /dev/null @@ -1,424 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// OLEString.cpp -// - - -#include "StdAfx.h" -#include -#include "olestring.h" - -template void StripSpaces ( OLECHAR *string); -template void StripSpaces ( char *string ); -template void StripSpacesFromMetaString ( OLECHAR *string ); -template void StripSpacesFromMetaString ( char *string); -template void ConvertMetaChars ( OLECHAR *string); -template void ConvertMetaChars ( char *string); -template int SameFormat ( char *string1, char *string2 ); -template int SameFormat ( OLECHAR *string1, OLECHAR *string2 ); -template void EncodeFormat ( char *string ); -template void EncodeFormat ( OLECHAR *string ); -template void DecodeFormat ( char *string1 ); -template void DecodeFormat ( OLECHAR *string ); -template int IsFormatTypeChar ( char string1 ); -template int IsFormatTypeChar ( OLECHAR string ); - - - -static const char *format_type = "cCdiouxXeEfgGnpsS"; // printf type as in %.{h|l|i64|L} - -template int IsFormatTypeChar ( text ch ) -{ - const char *ptr = format_type; - - while ( *ptr ) - { - if ( (unsigned int)*ptr++ == (unsigned int) ch ) - { - return TRUE; - } - } - return FALSE; -} - - - -OLEString::OLEString ( void ) -{ - ole = NULL; - sb = NULL; - len = 0; - - Unlock (); - Set (""); - -} - -OLEString::~OLEString ( ) -{ - delete [] ole; - delete [] sb; - ole = NULL; - sb = NULL; - len = 0; - -} - -void OLEString::Set ( OLECHAR *new_ole ) -{ - - if ( !locked ) - { - delete [] ole; - delete [] sb; - ole = NULL; - sb = NULL; - - len = wcslen ( new_ole ); - { - ole = new OLECHAR[len+1]; - wcscpy ( ole, new_ole ); - sb = new char[len+1]; - sprintf ( sb, "%S", ole ); - } - } - -} - -void OLEString::Set ( const char *new_sb ) -{ - - if ( !locked ) - { - delete [] ole; - delete [] sb; - ole = NULL; - sb = NULL; - - len = strlen ( new_sb ); - - { - ole = new OLECHAR[len+1]; - swprintf ( ole, L"%S", new_sb ); - sb = new char[len+1]; - strcpy ( sb, new_sb ); - } - } -} - -void OLEString::StripSpaces ( void ) -{ - if ( locked ) - { - return; - } - - if ( ole ) - { - ::StripSpaces ( ole ); - } - if ( sb ) - { - ::StripSpaces ( sb ); - } -} - - -void OLEString::FormatMetaString ( void ) -{ - char *str, *ptr; - char ch, last = -1; - int skipall = TRUE; - int slash = FALSE; - - if ( !len || locked ) - { - return; - } - - char *string = new char[len*2]; - - str = string; - ptr = sb; - - while ( (ch = *ptr++) ) - { - if ( ch == ' ' ) - { - if ( last == ' ' ) - { - continue; - } - } - - skipall= FALSE; - - if ( ch == '\\' ) - { - char esc; - slash = !slash; - - if ( slash && ((esc = *ptr) == 'n' || esc == 't') ) - { - // remove last space - if ( last != ' ' ) - { - *str++ = ' '; - } - - *str++ = '\\'; - ptr++; - *str++ = esc; - last = *str++ = ' '; - continue; - } - } - else - { - slash = FALSE; - } - - last = *str++ = ch; - } - - if ( last == ' ' ) - { - str--; - } - - *str = 0; - - Set ( string ); - delete [] string; - string = NULL; -} - -template void StripSpaces ( text *string ) -{ - text *str, *ptr; - text ch, last = -1; - int skipall = TRUE; - - str = ptr = string; - - while ( (ch = *ptr++) ) - { - if ( ch == ' ' ) - { - if ( last == ' ' || skipall ) - { - continue; - } - } - - if ( ch == '\n' || ch == '\t' ) - { - // remove last space - if ( last == ' ' ) - { - str--; - } - - skipall = TRUE; // skip all spaces - last = *str++ = ch; - continue; - } - - last = *str++ = ch; - skipall = FALSE; - } - - if ( last == ' ' ) - { - str--; - } - - *str = 0; -} - -template void StripSpacesFromMetaString ( text *string ) -{ - text *str, *ptr; - text ch, last = -1; - int skipall = TRUE; - int slash = FALSE; - - str = ptr = string; - - while ( (ch = *ptr++) ) - { - if ( ch == ' ' ) - { - if ( last == ' ' || skipall ) - { - continue; - } - } - - skipall= FALSE; - - if ( ch == '\\' ) - { - text esc; - slash = !slash; - - if ( slash && (esc = *ptr) == 'n' || esc == 't' ) - { - // remove last space - if ( last == ' ' ) - { - str--; - } - - skipall = TRUE; // skip all spaces - *str++ = '\\'; - ptr++; - last = *str++ = esc; - continue; - } - } - else - { - slash = FALSE; - } - - last = *str++ = ch; - } - - if ( last == ' ' ) - { - str--; - } - - *str = 0; -} - - -template void ConvertMetaChars ( text *string ) -{ - text *ptr; - text ch; - - ptr = string; - - while ( (ch = *string++) ) - { - if ( ch == '\\' ) - { - if ( ch = *string ) - { - switch ( ch ) - { - case 'n': - case 'N': - ch = '\n'; - break; - case 't': - case 'T': - ch = '\t'; - break; - } - string++; - } - } - - *ptr++ = ch; - } - - *ptr = 0; -} - -template int SameFormat ( text *string1, text *string2 ) -{ - - while ( *string1 && *string2 ) - { - - while ( *string1 ) - { - if (*string1 == '%') - { - string1++; - break; - } - - if ( *string1 == '\\' ) - { - string1++; - } - - if ( *string1 ) - { - string1++; - } - } - - while ( *string2 ) - { - if (*string2 == '%') - { - string2++; - break; - } - - if ( *string2 == '\\' ) - { - string2++; - } - if ( *string2) - { - string2++; - } - } - - if ( !*string1 && !*string2) - { - return TRUE; - } - - int found_type = FALSE; - - while ( *string1 && *string2 && !found_type ) - { - found_type = IsFormatTypeChar ( *string1 ); - - if ( *string1 != *string2 ) - { - return FALSE; - } - - string1++; - string2++; - } - - } - return TRUE; -} - -template void EncodeFormat ( text *string ) -{ - -} - -template void DecodeFormat ( text *string ) -{ - -} - diff --git a/Generals/Code/Tools/Babylon/olestring.h b/Generals/Code/Tools/Babylon/olestring.h deleted file mode 100644 index c59afdbff7..0000000000 --- a/Generals/Code/Tools/Babylon/olestring.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// OLEString -// - -#ifndef __OLESTRING_H -#define __OLESTRING_H - -const unsigned int OLESTRING_DEFAULT_SIZE = 256; - -class OLEString -{ - - OLECHAR *ole; - char *sb; - unsigned int len; - int locked; - - public: - - OLEString ( void ) ; - ~OLEString (); - void Set ( OLECHAR *new_ole ); - void Set ( const char *new_sb ); - OLECHAR*Get ( void ) { return ole; }; - int Len ( void ) { return len; }; - char* GetSB ( void ) { return sb; }; - void StripSpaces ( void ); - void FormatMetaString ( void ); - void Lock ( void ) { locked = TRUE; }; - void Unlock ( void ) { locked = FALSE; }; -}; - -template void StripSpaces ( text *string ); -template void ConvertMetaChars ( text *string ); -template void StripSpacesFromMetaString ( text *string ); -template int SameFormat ( text *string1, text *string2 ); -template void EncodeFormat ( text *string ); -template void DecodeFormat ( text *string ); -template int IsFormatTypeChar( text string1 ); - - - -#endif // __OLESTRING_H \ No newline at end of file diff --git a/Generals/Code/Tools/Babylon/resource.h b/Generals/Code/Tools/Babylon/resource.h deleted file mode 100644 index e7e86784af..0000000000 --- a/Generals/Code/Tools/Babylon/resource.h +++ /dev/null @@ -1,103 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by noxstring.rc -// -#define IDM_ABOUTBOX 0x0010 -#define IDM_PIC 0x0010 -#define IDD_ABOUTBOX 100 -#define IDP_OLE_INIT_FAILED 100 -#define IDS_ABOUTBOX 101 -#define IDD_NOXSTRING_DIALOG 102 -#define IDR_MAINFRAME 128 -#define IDD_VIEWDBS 129 -#define IDD_EXPORT 133 -#define IDD_GENERATE 135 -#define IDD_SETTINGS 136 -#define IDD_MATCHDIALOG 137 -#define IDD_PROCEED 145 -#define IDD_MATCH 146 -#define IDD_VERIFYTEXT 147 -#define IDD_CREATE_REPORTS 148 -#define IDD_CHARSET 149 -#define IDD_RETRANSLATE 150 -#define IDC_BUTTON1 1001 -#define IDC_TESTLOG 1001 -#define IDC_RELOAD 1001 -#define IDC_NOMATCH 1001 -#define IDC_INVERT 1001 -#define IDC_MATCH 1002 -#define IDC_ALWAYS 1002 -#define IDC_BUTTON_NO 1003 -#define IDC_PROGRESS1 1004 -#define IDC_BUILD 1005 -#define IDC_STATUS 1006 -#define IDC_LOG 1009 -#define IDC_VIEWDBS 1013 -#define IDC_TREEVIEW 1014 -#define IDC_WARNINGS 1014 -#define IDC_UPDATE 1015 -#define IDC_SAVE 1016 -#define IDC_EXPORT 1017 -#define IDC_IMPORT 1018 -#define IDC_GENERATE 1019 -#define IDC_MATCHCOMBO 1019 -#define IDC_CHANGES 1020 -#define IDC_ERRORS 1021 -#define IDC_NEWTEXT 1021 -#define IDC_MATCHTEXT 1022 -#define IDC_REPORTS 1022 -#define IDC_DIALOG_STATUS 1022 -#define IDC_CHECKRETRANSLATE 1023 -#define IDC_SHOW_DETAILS 1023 -#define IDC_SENT 1023 -#define IDC_SKIP 1024 -#define IDC_COMBOLANG 1026 -#define IDC_CHECKTRANS 1027 -#define IDC_RADIOALL 1028 -#define IDC_RADIOCHANGES 1029 -#define IDC_FILENAME 1031 -#define IDC_RADIOSAMPLE 1032 -#define IDC_RADIODIALOG 1033 -#define IDC_RADIONONDIALOG 1034 -#define IDC_RADIOUNVERIFIED 1035 -#define IDC_SELECTALL 1036 -#define IDC_RADIOMISSING 1036 -#define IDC_UNICODE 1037 -#define IDC_RADIOUNSENT 1037 -#define IDC_NOXSTR 1038 -#define IDC_PREFIX 1039 -#define IDC_LANGUAGE 1040 -#define IDC_PERCENT 1041 -#define IDC_DIALOG 1043 -#define IDC_TRANSLATIONS 1044 -#define IDC_EDIT1 1046 -#define IDC_TEXT 1047 -#define IDC_SLIDER 1048 -#define IDC_STOP 1049 -#define IDC_PAUSE 1050 -#define IDC_PLAY 1051 -#define IDC_WAVENAME 1052 -#define IDC_YES 1054 -#define IDC_MESSAGE 1055 -#define IDC_TEXT_TITLE 1056 -#define IDC_TRANS 1058 -#define IDC_ORIG 1059 -#define IDC_IDS 1060 -#define IDC_ORIGINAL 1061 -#define IDC_TRANSLATION_STATUS 1062 -#define IDC_LIMIT 1065 -#define IDC_IFLESS 1067 -#define IDC_ITEMS 1068 -#define IDC_RESET 1069 -#define IDC_OLDTEXT 1070 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 151 -#define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 1071 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/Babylon/transcs.cpp b/Generals/Code/Tools/Babylon/transcs.cpp deleted file mode 100644 index 8784e13242..0000000000 --- a/Generals/Code/Tools/Babylon/transcs.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// transcs.cpp -// - -#include "StdAfx.h" -#include -#include -#include -#include -#include -#include - -void CreateTranslationTable ( void ) -{ - int i; - FILE *out; - wchar_t wc; - wchar_t mb; - DWORD last_error; - - if ( ! ( out = fopen ( "utable.c", "wt" ))) - { - return; - } - - - fprintf (out, "static unsigned short Utable[0x10000] =\n{" ); - - for ( i = 0; i < 0x10000; i++ ) - { - - if ( ( i %32 ) == 0 ) - { - fprintf ( out, "\n\t/* 0x%04x */\t", i ); - } - - mb = i; - if ( MultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS, (LPCSTR) &mb, 2, &wc, 2 ) == 0 ) - { - wc = 0; - last_error = GetLastError ( ); - } - - fprintf (out, "0x%04x", wc ); - if ( i != 0xffff ) - { - fprintf (out, "," ); - } - } - - fprintf ( out, "\n};\n"); - - fclose ( out ); - -} diff --git a/Generals/Code/Tools/Babylon/transcs.h b/Generals/Code/Tools/Babylon/transcs.h deleted file mode 100644 index 45ee48b4f1..0000000000 --- a/Generals/Code/Tools/Babylon/transcs.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// transcs.h Translate char set -// - -#ifndef _TRANSCS_H -#define _TRANSCS_H - - -void CreateTranslationTable ( void ); - -#endif // _TRANSCS_H diff --git a/Generals/Code/Tools/CMakeLists.txt b/Generals/Code/Tools/CMakeLists.txt index 77983a2ec4..e1d0da9bd4 100644 --- a/Generals/Code/Tools/CMakeLists.txt +++ b/Generals/Code/Tools/CMakeLists.txt @@ -2,27 +2,17 @@ # Build useful tool binaries. if(RTS_BUILD_GENERALS_TOOLS) - add_subdirectory(DebugWindow) add_subdirectory(GUIEdit) add_subdirectory(ImagePacker) add_subdirectory(MapCacheBuilder) add_subdirectory(ParticleEditor) + add_subdirectory(W3DView) add_subdirectory(WorldBuilder) endif() # Build less useful tool/test binaries. if(RTS_BUILD_GENERALS_EXTRAS) add_subdirectory(Autorun) - add_subdirectory(Babylon) - add_subdirectory(buildVersionUpdate) - add_subdirectory(CRCDiff) add_subdirectory(Launcher) - add_subdirectory(mangler) - add_subdirectory(matchbot) add_subdirectory(PATCHGET) - add_subdirectory(textureCompress) - add_subdirectory(timingTest) - add_subdirectory(versionUpdate) - add_subdirectory(wolSetup) - add_subdirectory(WW3D) endif() diff --git a/Generals/Code/Tools/CRCDiff/CMakeLists.txt b/Generals/Code/Tools/CRCDiff/CMakeLists.txt deleted file mode 100644 index 9a6bf21196..0000000000 --- a/Generals/Code/Tools/CRCDiff/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -set(CRCDIFF_SRC - "CRCDiff.cpp" - "debug.cpp" - "debug.h" - "expander.cpp" - "expander.h" - "KVPair.cpp" - "KVPair.h" - "misc.h" -) - -add_executable(g_crcdiff WIN32) -set_target_properties(g_crcdiff PROPERTIES OUTPUT_NAME crcdiff) - -target_sources(g_crcdiff PRIVATE ${CRCDIFF_SRC}) - -target_link_libraries(g_crcdiff PRIVATE - core_config - core_utility - stlport -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(g_crcdiff PRIVATE /subsystem:console) -endif() diff --git a/Generals/Code/Tools/CRCDiff/CRCDiff.cpp b/Generals/Code/Tools/CRCDiff/CRCDiff.cpp deleted file mode 100644 index c6abe4956e..0000000000 --- a/Generals/Code/Tools/CRCDiff/CRCDiff.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "debug.h" -#include "expander.h" -#include "KVPair.h" -#include "misc.h" -#include -#include -#include -#include - -//============================================================================= - -std::string tableRow; - -//============================================================================= - -static void exitWait(void) -{ - system("PAUSE"); -} - -//============================================================================= - -#define LINESIZE 1024 -static bool getNextLine(FILE *fp, char *line, int& frame, int& index) { - if (!fp) - return false; - - char buf[LINESIZE]; - while (fgets(buf, LINESIZE-1, fp) != NULL) - { - int len = strlen(buf); - if (buf[len-1] == '\n') - buf[len-1] = '\0'; - if (sscanf(buf, "%d:%d ", &frame, &index) == 2) - { - strcpy(line, buf); - return true; - } - } - - fclose(fp); - return false; -} - -//============================================================================= - -static std::string readInFile(const char *fname) { - FILE *fp = fopen(fname, "rt"); - if (!fp) - return ""; - - std::string ret; - char buf[LINESIZE]; - while (fgets(buf, LINESIZE-1, fp) != NULL) - { - ret.append(buf); - } - - fclose(fp); - return ret; -} - -//============================================================================= - -static FILE *ofp = NULL; - -void dumpQueued(void); - -static void outputLine(const char *line) -{ - dumpQueued(); - //cout << line << endl; - if (ofp) - { - fputs(line, ofp); - } -} - -//============================================================================= - -static void outputLine(int frame, int index, int linkNum, - const char *class1, const char *line1, - const char *class2, const char *line2, bool same = false) -{ - dumpQueued(); - if (!line1) - line1 = " "; - if (!line2) - line2 = " "; - if (!class1) - class1 = ""; - if (!class2) - class2 = ""; - - Expander e("((", "))"); - e.addExpansion("LEFTCLASS", class1); - e.addExpansion("LEFTLINE", line1); - e.addExpansion("RIGHTCLASS", class2); - e.addExpansion("RIGHTLINE", line2); - if (same) - { - e.addExpansion("NAME", ""); - e.addExpansion("PREV", intToString(linkNum-1)); - e.addExpansion("NEXT", intToString(linkNum)); - } - else - { - e.addExpansion("NAME", intToString(linkNum)); - e.addExpansion("PREV", intToString(linkNum-1)); - e.addExpansion("NEXT", intToString(linkNum+1)); - } - - std::string out; - e.expand(tableRow, out); - const char *buf = out.c_str(); - - //cout << buf << endl; - if (ofp) - { - fputs(buf, ofp); - } -} - -//============================================================================= - -std::list queuedLines; -static void queueLine(int frame, int index, const char *line1) -{ - if (!line1) - line1 = " "; - - Expander e("((", "))"); - e.addExpansion("LEFTCLASS", "leftHistory"); - e.addExpansion("LEFTLINE", line1); - e.addExpansion("RIGHTCLASS", "rightHistory"); - e.addExpansion("RIGHTLINE", line1); - e.addExpansion("NAME", ""); - e.addExpansion("PREV", intToString(0)); - e.addExpansion("NEXT", intToString(1)); - - std::string out; - e.expand(tableRow, out); - - queuedLines.push_back(out); - if (queuedLines.size() > 150) - queuedLines.pop_front(); - - //cout << buf << endl; -} - -void dumpQueued(void) -{ - while (!queuedLines.empty()) - { - std::list::iterator it = queuedLines.begin(); - const char *buf = (*it).c_str(); - //cout << buf << endl; - if (ofp) - { - fputs(buf, ofp); - } - - queuedLines.pop_front(); - } -} - -//============================================================================= - -int main(int argc, char *argv[]) -{ - atexit(exitWait); - const char *inFname[2]; - const char *outFname = "out.html"; - FILE *ifp[2] = {NULL, NULL}; - std::string header, footer; - - if (argc != 7) - { - cout << "Usage: munkeeDiff top.html row.html bottom.html in1.txt in2.txt out.txt" << endl; - header = readInFile("top.html"); - tableRow = readInFile("row.html"); - footer = readInFile("bottom.html"); - inFname[0] = "test1.txt"; - inFname[1] = "test2.txt"; - //return 0; - } - else - { - header = readInFile(argv[1]); - tableRow = readInFile(argv[2]); - footer = readInFile(argv[3]); - inFname[0] = argv[4]; - inFname[1] = argv[5]; - outFname = argv[6]; - } - - ifp[0] = fopen(inFname[0], "rt"); - if (!ifp[0]) - { - cout << "could not open " << inFname[0] << endl; - return 1; - } - ifp[1] = fopen(inFname[1], "rt"); - if (!ifp[1]) - { - fclose(ifp[0]); - cout << "could not open " << inFname[1] << endl; - return 1; - } - - ofp = fopen(outFname, "wt"); - - char lastLine[2][LINESIZE]; - int lastFrame[2] = {-1, -1}; - int lastIndex[2] = {-1, -1}; - bool fileOk[2] = {true, true}; - - outputLine(header.c_str()); - - int linkNum = 1; - int numDiffs = 0; - - bool seenRight = false; - bool seenLeft = false; - - while (fileOk[0] || fileOk[1]) - { - for (int i=0; i<2; ++i) - { - if (fileOk[i] == true && lastFrame[i] < 0) - { - fileOk[i] = getNextLine(ifp[i], lastLine[i], - lastFrame[i], lastIndex[i]); - } - } - - if (fileOk[0] && fileOk[1]) - { - if (lastFrame[0] < lastFrame[1] || - (lastFrame[0]==lastFrame[1] && lastIndex[0] < lastIndex[1])) - { - //if (!seenLeft) - //cout << "Seen left on " << lastFrame[0] << ":" << lastIndex[0] << endl; - //seenLeft = true; - if (seenRight && seenLeft) - { - outputLine(lastFrame[0], lastIndex[0], linkNum++, - "leftOnly", lastLine[0], NULL, NULL); - ++numDiffs; - } - lastFrame[0] = -1; - } - else if (lastFrame[1] < lastFrame[0] || - (lastFrame[1]==lastFrame[0] && lastIndex[1] < lastIndex[0])) - { - //if (!seenRight) - //cout << "Seen right on " << lastFrame[1] << ":" << lastIndex[1] << endl; - //seenRight = true; - if (seenRight && seenLeft) - { - outputLine(lastFrame[1], lastIndex[1], linkNum++, - NULL, NULL, "rightOnly", lastLine[1]); - ++numDiffs; - } - lastFrame[1] = -1; - } - else - { - int res = strcmp(lastLine[0], lastLine[1]); - if (res!=0) - { - if (!seenLeft || !seenRight) - cout << "Seen both on " << lastFrame[0] << ":" << lastIndex[0] << endl; - seenLeft = seenRight = true; - outputLine(lastFrame[0], lastIndex[0], linkNum++, - "leftDiff", lastLine[0], "rightDiff", lastLine[1]); - ++numDiffs; - } - else - { - //if (!seenLeft || !seenRight) - // cout << "Seen both on " << lastFrame[0] << ":" << lastIndex[0] << endl; - //seenLeft = seenRight = true; - static bool printedFirst = false; - if (!printedFirst) - { - outputLine(lastFrame[0], lastIndex[0], linkNum, - "leftSame", lastLine[0], "rightSame", lastLine[1], true); - printedFirst = true; - } - else if (seenLeft && seenRight) - { - outputLine(lastFrame[0], lastIndex[0], linkNum, - "leftSame", lastLine[0], "rightSame", lastLine[1], true); - ++numDiffs; - } - else - queueLine(lastFrame[0], lastIndex[0], lastLine[0]); - //++numDiffs; - } - lastFrame[0] = -1; - lastFrame[1] = -1; - } - } - else if (fileOk[0]) - { - //if (!seenLeft) - //cout << "Seen left on " << lastFrame[0] << ":" << lastIndex[0] << endl; - //seenLeft = true; - if (seenRight && seenLeft) - { - outputLine(lastFrame[0], lastIndex[0], linkNum++, - "leftOnly", lastLine[0], NULL, NULL); - ++numDiffs; - } - lastFrame[0] = -1; - } - else if (fileOk[1]) - { - //if (!seenRight) - //cout << "Seen right on " << lastFrame[1] << ":" << lastIndex[1] << endl; - //seenRight = true; - if (seenRight && seenLeft) - { - outputLine(lastFrame[1], lastIndex[1], linkNum++, - NULL, NULL, "rightOnly", lastLine[1]); - ++numDiffs; - } - lastFrame[1] = -1; - } - - if (numDiffs > 1000) - break; - } - - Expander e("((", "))"); - e.addExpansion("LAST", intToString(linkNum-1)); - e.addExpansion("BOTTOM", intToString(linkNum)); - std::string out; - e.expand(footer, out); - outputLine(out.c_str()); - - if (ofp) - { - fclose(ofp); - } - - return 0; -} diff --git a/Generals/Code/Tools/CRCDiff/KVPair.cpp b/Generals/Code/Tools/CRCDiff/KVPair.cpp deleted file mode 100644 index afddcc6e60..0000000000 --- a/Generals/Code/Tools/CRCDiff/KVPair.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// --------------------------------------------------------------------------- -// File: KVPair.cpp -// Author: Matthew D. Campbell -// Creation Date: 9/4/2002 -// Description: Key/Value Pair class -// --------------------------------------------------------------------------- - -#include "misc.h" -#include "KVPair.h" -#include "debug.h" -#include - -std::string intToString(int val) -{ - std::string s = ""; - bool neg = (val < 0); - if (val < 0) - { - val = -val; - } - if (val == 0) - return "0"; - - char buf[2]; - buf[1] = 0; - while (val) - { - buf[0] = '0' + val%10; - val /= 10; - s.insert(0, buf); - } - if (neg) - s.insert(0, "-"); - return s; -} - -static std::string trim(std::string s, const std::string& delim) -{ - unsigned int i; - i = s.find_first_not_of(delim); - if (i != s.npos) - { - s = s.substr(i); - } - - i = s.find_last_not_of(delim); - if (i>=0 && isecond; -} - -bool KVPairClass::getString( const std::string& key, std::string& val ) const -{ - std::string tmp = getStringVal(key); - if (tmp.empty()) - { - return false; - } - - val = tmp; - return true; -} - -bool KVPairClass::getInt( const std::string& key, int& val ) const -{ - std::string tmp = getStringVal(key); - if (tmp.empty()) - { - return false; - } - - val = atoi(tmp.c_str()); - return true; -} - -bool KVPairClass::getUnsignedInt( const std::string& key, unsigned int& val ) const -{ - std::string tmp = getStringVal(key); - if (tmp.empty()) - { - return false; - } - - val = atoi(tmp.c_str()); - return true; -} - diff --git a/Generals/Code/Tools/CRCDiff/KVPair.h b/Generals/Code/Tools/CRCDiff/KVPair.h deleted file mode 100644 index 9cf56bc45b..0000000000 --- a/Generals/Code/Tools/CRCDiff/KVPair.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// --------------------------------------------------------------------------- -// File: KVPair.h -// Author: Matthew D. Campbell -// Creation Date: 9/4/2002 -// Description: Key/Value Pair class -// --------------------------------------------------------------------------- - -#ifndef __KVPAIR_H__ -#define __KVPAIR_H__ - -#include -#include - -typedef std::map KeyValueMap; - -class KVPairClass -{ -public: - KVPairClass( void ); - KVPairClass( const std::string& in, const std::string& delim ); - void set( const std::string& in, const std::string& delim ); - void readFromFile( const std::string& in, const std::string& delim ); - - std::string getStringVal( const std::string& key ) const; - - bool getString( const std::string& key, std::string& val ) const; - bool getInt( const std::string& key, int& val ) const; - bool getUnsignedInt( const std::string& key, unsigned int& val ) const; - -protected: - KeyValueMap m_map; -}; - -#endif // __KVPAIR_H__ - diff --git a/Generals/Code/Tools/CRCDiff/debug.cpp b/Generals/Code/Tools/CRCDiff/debug.cpp deleted file mode 100644 index f9d3b17a70..0000000000 --- a/Generals/Code/Tools/CRCDiff/debug.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: debug.cpp //////////////////////////////////////////////////////// -// Minmal debug info -// Author: Matthew D. Campbell, Sept 2002 - -#include -#include "debug.h" -#include - -#ifdef DEBUG - -void DebugLog(const char *fmt, ...) -{ - static char buffer[1024]; - va_list va; - va_start( va, fmt ); - vsnprintf(buffer, 1024, fmt, va ); - buffer[1023] = 0; - va_end( va ); - - printf( "%s", buffer ); - OutputDebugString( buffer ); -} - -#endif // DEBUG - diff --git a/Generals/Code/Tools/CRCDiff/debug.h b/Generals/Code/Tools/CRCDiff/debug.h deleted file mode 100644 index b0c11a5f07..0000000000 --- a/Generals/Code/Tools/CRCDiff/debug.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: debug.h ////////////////////////////////////////////////////////////// -// Minimal debug info -// Author: Matthew D. Campbell, Sept 2002 - -#ifndef __DEBUG_H__ -#define __DEBUG_H__ - -#ifdef DEBUG - -#include - -void DebugLog( const char *fmt, ... ); -#define DEBUG_LOG(x) DebugLog x - -#else // DEBUG - -#define DEBUG_LOG(x) {} - -#endif // DEBUG - -#endif // __DEBUG_H__ - diff --git a/Generals/Code/Tools/CRCDiff/expander.cpp b/Generals/Code/Tools/CRCDiff/expander.cpp deleted file mode 100644 index 7d38c0122b..0000000000 --- a/Generals/Code/Tools/CRCDiff/expander.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// --------------------------------------------------------------------------- -// File: expander.cpp -// Author: Matthew D. Campbell -// Creation Date: 9/13/2002 -// Description: Key/value pair template expansion class -// --------------------------------------------------------------------------- - -#include "debug.h" -#include "expander.h" - -Expander::Expander( const std::string& leftMarker, const std::string& rightMarker ) : - m_left(leftMarker), m_right(rightMarker) -{ -} - -void Expander::addExpansion( const std::string& key, const std::string val ) -{ - m_expansions[key] = val; -} - -void Expander::clear( void ) -{ - m_expansions.clear(); -} - -void Expander::expand( const std::string& input, - std::string& output, - bool stripUnknown ) -{ - output = ""; - unsigned int pos = input.find(m_left); - unsigned int lastpos = input.npos; - while (pos != input.npos) - { - // first, tack on the non-expansion part we just skipped over - if (pos > 0) - { - if (lastpos == input.npos) - { - // first time - output.append(input.substr(0, pos)); - //DEBUG_LOG(("First time, output='%s'\n", output.c_str())); - } - else - { - // done this before - std::string sub = input.substr(lastpos, pos-lastpos); - //DEBUG_LOG(("*** lastpos = %d, pos=%d, sub='%s'\n", lastpos, pos, sub.c_str())); - output.append(sub); - //DEBUG_LOG(("output='%s'\n", output.c_str())); - } - } - else - { - //DEBUG_LOG(("pos == 0\n")); - } - - // pos is the first position of a possible expansion - //DEBUG_LOG(("Looking for endpos via '%s' in '%s'\n", m_right.c_str(), input.substr(pos+m_left.length()).c_str())); - unsigned int endpos = input.find(m_right, pos+m_left.length()); - //DEBUG_LOG(("substr is %d-%d of '%s'\n", pos, endpos, input.c_str())); - if (endpos != input.npos) - { - // found a complete token - expand it - std::string sub = input.substr(pos+m_left.length(), endpos-pos-m_left.length()); - //DEBUG_LOG(("found token: '%s'\n", sub.c_str())); - - ExpansionMap::iterator it = m_expansions.find(sub); - if (it == m_expansions.end()) - { - // unknown key - if (stripUnknown) - { - //output.append("<>"); - } - else - { - output.append(input.substr(pos, endpos-pos+m_right.length())); - } - } - else - { - std::string toExpand = it->second; - std::string expanded = ""; - //DEBUG_LOG(("###### expanding '%s'\n", toExpand.c_str())); - expand(toExpand, expanded, stripUnknown); - //DEBUG_LOG(("###### expanded '%s'\n", expanded.c_str())); - output.append(expanded); - } - } - - lastpos = endpos+m_right.length(); - - pos = input.find(m_left, pos+m_left.length()); - } - - if (lastpos != input.npos) - { - // tack on last bit - output.append(input.substr(lastpos)); - } - else if (!output.length() && pos == input.npos && lastpos == input.npos) - { - output = input; - } -} - - diff --git a/Generals/Code/Tools/CRCDiff/expander.h b/Generals/Code/Tools/CRCDiff/expander.h deleted file mode 100644 index b3f2304381..0000000000 --- a/Generals/Code/Tools/CRCDiff/expander.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// --------------------------------------------------------------------------- -// File: expander.h -// Author: Matthew D. Campbell -// Creation Date: 9/13/2002 -// Description: Key/value pair template expansion class -// --------------------------------------------------------------------------- - -#ifndef __EXPANDER_H__ -#define __EXPANDER_H__ - -#include -#include -#include - -typedef std::map ExpansionMap; - -class Expander -{ - public: - Expander( const std::string& leftMarker, const std::string& rightMarker ); - - void addExpansion( const std::string& key, const std::string val ); - void clear( void ); - - void expand( const std::string& input, - std::string& output, - bool stripUnknown = false ); - - protected: - ExpansionMap m_expansions; - std::string m_left; - std::string m_right; -}; - -#endif // __EXPANDER_H__ - diff --git a/Generals/Code/Tools/CRCDiff/misc.h b/Generals/Code/Tools/CRCDiff/misc.h deleted file mode 100644 index a3265519e6..0000000000 --- a/Generals/Code/Tools/CRCDiff/misc.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// --------------------------------------------------------------------------- -// File: misc.h -// Author: Matthew D. Campbell -// Creation Date: 9/12/2002 -// Description: misc utils -// --------------------------------------------------------------------------- - -#ifndef __MISC_H__ -#define __MISC_H__ - -#include - -std::string intToString(int val); - -#endif // __MISC_H__ - diff --git a/Generals/Code/Tools/DebugWindow/CMakeLists.txt b/Generals/Code/Tools/DebugWindow/CMakeLists.txt deleted file mode 100644 index 6ae53af6d3..0000000000 --- a/Generals/Code/Tools/DebugWindow/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -set(DEBUGWINDOW_SRC - "DebugWindow.cpp" - "DebugWindow.h" - "DebugWindowDialog.cpp" - "DebugWindowDialog.h" - "DebugWindowExport.h" - "StdAfx.cpp" - "StdAfx.h" -) - -add_library(g_debugwindow SHARED) -set_target_properties(g_debugwindow PROPERTIES OUTPUT_NAME debugwindow) - -target_sources(g_debugwindow PRIVATE ${DEBUGWINDOW_SRC}) - -target_link_libraries(g_debugwindow PRIVATE - core_config -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_compile_definitions(g_debugwindow PRIVATE _AFXDLL) - target_sources(g_debugwindow PRIVATE - DebugWindow.rc - DebugWindow.def - ) - set_target_properties(g_debugwindow PROPERTIES OUTPUT_NAME DebugWindow) -else() - set_target_properties(g_debugwindow PROPERTIES OUTPUT_NAME debugwindow) -endif() diff --git a/Generals/Code/Tools/DebugWindow/DebugWindow.cpp b/Generals/Code/Tools/DebugWindow/DebugWindow.cpp deleted file mode 100644 index e2f8655b82..0000000000 --- a/Generals/Code/Tools/DebugWindow/DebugWindow.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// DebugWindow.cpp : Defines the initialization routines for the DLL. -// - -#include "StdAfx.h" -#include "DebugWindow.h" -#include "DebugWindowDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -// -// Note! -// -// If this DLL is dynamically linked against the MFC -// DLLs, any functions exported from this DLL which -// call into MFC must have the AFX_MANAGE_STATE macro -// added at the very beginning of the function. -// -// For example: -// -// extern "C" BOOL PASCAL EXPORT ExportedFunction() -// { -// AFX_MANAGE_STATE(AfxGetStaticModuleState()); -// // normal function body here -// } -// -// It is very important that this macro appear in each -// function, prior to any calls into MFC. This means that -// it must appear as the first statement within the -// function, even before any object variable declarations -// as their constructors may generate calls into the MFC -// DLL. -// -// Please see MFC Technical Notes 33 and 58 for additional -// details. -// - -///////////////////////////////////////////////////////////////////////////// -// CDebugWindowApp - -BEGIN_MESSAGE_MAP(CDebugWindowApp, CWinApp) - //{{AFX_MSG_MAP(CDebugWindowApp) - // NOTE - the ClassWizard will add and remove mapping macros here. - // DO NOT EDIT what you see in these blocks of generated code! - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CDebugWindowApp construction - -CDebugWindowApp::CDebugWindowApp() -{ - AfxInitialize(true); - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - m_DialogWindow = NULL; -} - -DebugWindowDialog* CDebugWindowApp::GetDialogWindow(void) -{ - return m_DialogWindow; -} - -void CDebugWindowApp::SetDialogWindow(DebugWindowDialog* pWnd) -{ - m_DialogWindow = pWnd; -} - -CDebugWindowApp::~CDebugWindowApp() -{ -} - - -///////////////////////////////////////////////////////////////////////////// -// The one and only CDebugWindowApp object - -CDebugWindowApp theApp; - -void __declspec(dllexport) CreateDebugDialog(void) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* tmpWnd; - tmpWnd = new DebugWindowDialog; - tmpWnd->Create(DebugWindowDialog::IDD); - tmpWnd->SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER); - tmpWnd->ShowWindow(SW_SHOW); - if (tmpWnd->GetMainWndHWND()) { - SetFocus(tmpWnd->GetMainWndHWND()); - } - - theApp.SetDialogWindow(tmpWnd); -} - -void __declspec(dllexport) DestroyDebugDialog(void) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - DebugWindowDialog* tmpWnd = theApp.GetDialogWindow(); - - if (tmpWnd) { - tmpWnd->DestroyWindow(); - delete tmpWnd; - theApp.SetDialogWindow(NULL); - } - -} - -bool __declspec(dllexport) CanAppContinue(void) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - if (!pDbg) { - return true; - } - - return pDbg->CanProceed(); -} - -void __declspec(dllexport) ForceAppContinue(void) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - if (!pDbg) { - return; - } - - pDbg->ForceContinue(); -} - -bool __declspec(dllexport) RunAppFast(void) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - if (!pDbg) { - return true; - } - - return pDbg->RunAppFast(); -} - -void __declspec(dllexport) AppendMessage(const char* messageToPass) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - - if (pDbg) { - pDbg->AppendMessage(messageToPass); - } -} - -void __declspec(dllexport) SetFrameNumber(int frameNumber) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - - if (pDbg) { - pDbg->SetFrameNumber(frameNumber); - } -} - - -void __declspec(dllexport) AppendMessageAndPause(const char* messageToPass) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - - if (pDbg) { - pDbg->AppendMessage(messageToPass); - pDbg->ForcePause(); - } -} - - -void __declspec(dllexport) AdjustVariable(const char* variable, const char* value) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - - if (pDbg) { - pDbg->AdjustVariable(variable, value); - } -} - -void __declspec(dllexport) AdjustVariableAndPause(const char* variable, const char* value) -{ - AFX_MANAGE_STATE(AfxGetStaticModuleState( )); - - DebugWindowDialog* pDbg; - pDbg = theApp.GetDialogWindow(); - - if (pDbg) { - pDbg->AdjustVariable(variable, value); - pDbg->ForcePause(); - } -} \ No newline at end of file diff --git a/Generals/Code/Tools/DebugWindow/DebugWindow.h b/Generals/Code/Tools/DebugWindow/DebugWindow.h deleted file mode 100644 index 9a45597487..0000000000 --- a/Generals/Code/Tools/DebugWindow/DebugWindow.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// DebugWindow.h : main header file for the DEBUGWINDOW DLL -// - -#if !defined(AFX_DEBUGWINDOW_H__018E1800_6E59_4527_BA0C_8731EBF22953__INCLUDED_) -#define AFX_DEBUGWINDOW_H__018E1800_6E59_4527_BA0C_8731EBF22953__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#ifndef __AFXWIN_H__ - #error include 'stdafx.h' before including this file for PCH -#endif - -#include "Resource.h" // main symbols -#include "DebugWindowExport.h" -///////////////////////////////////////////////////////////////////////////// -// CDebugWindowApp -// See DebugWindow.cpp for the implementation of this class -// - -class DebugWindowDialog; - -class CDebugWindowApp : public CWinApp -{ - public: - CDebugWindowApp(); - ~CDebugWindowApp(); - DebugWindowDialog* GetDialogWindow(void); - void SetDialogWindow(DebugWindowDialog* pWnd); - - protected: - DebugWindowDialog* m_DialogWindow; - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CDebugWindowApp) - //}}AFX_VIRTUAL - - //{{AFX_MSG(CDebugWindowApp) - // NOTE - the ClassWizard will add and remove member functions here. - // DO NOT EDIT what you see in these blocks of generated code ! - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - - -///////////////////////////////////////////////////////////////////////////// - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_DEBUGWINDOW_H__018E1800_6E59_4527_BA0C_8731EBF22953__INCLUDED_) diff --git a/Generals/Code/Tools/DebugWindow/DebugWindowDialog.cpp b/Generals/Code/Tools/DebugWindow/DebugWindowDialog.cpp deleted file mode 100644 index 9383e8d077..0000000000 --- a/Generals/Code/Tools/DebugWindow/DebugWindowDialog.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "StdAfx.h" -#include "DebugWindowDialog.h" - -DebugWindowDialog::DebugWindowDialog(UINT nIDTemplate, CWnd* pParentWnd) : - CDialog(nIDTemplate, pParentWnd) -{ - mStepping = false; - mRunFast = false; - mNumberOfStepsAllowed = -1; - mMainWndHWND = ::FindWindow(NULL, "Command & Conquer: Generals"); -} - -int DebugWindowDialog::OnCreate(LPCREATESTRUCT lpCreateStruct) -{ - return CDialog::OnCreate(lpCreateStruct); -} - -HWND DebugWindowDialog::GetMainWndHWND(void) -{ - return mMainWndHWND; -} - -void DebugWindowDialog::ForcePause(void) -{ - mNumberOfStepsAllowed = 0; - _UpdatePauseButton(); -} - -void DebugWindowDialog::ForceContinue(void) -{ - mNumberOfStepsAllowed = -1; - _UpdatePauseButton(); -} - -void DebugWindowDialog::OnPause() -{ - if (mNumberOfStepsAllowed < 0) { - mNumberOfStepsAllowed = 0; - } else { - mNumberOfStepsAllowed = -1; - } - _UpdatePauseButton(); -} - -void DebugWindowDialog::OnStep() -{ - mStepping = true; - mNumberOfStepsAllowed = 1; - _UpdatePauseButton(); -} - -void DebugWindowDialog::OnRunFast() -{ - CButton *pButton = (CButton*)GetDlgItem(IDC_RUN_FAST); - mRunFast = pButton->GetCheck() == 1; -} - -void DebugWindowDialog::OnStepTen() -{ - mStepping = true; - mNumberOfStepsAllowed = 10; - _UpdatePauseButton(); -} - -void DebugWindowDialog::OnClearWindows() -{ - mMessages.clear(); - mVariables.clear(); - _RebuildMesgString(); - _RebuildVarsString(); -} - -bool DebugWindowDialog::CanProceed(void) -{ - if (mNumberOfStepsAllowed < 0) { - return true; - } else if (mNumberOfStepsAllowed == 0) { - if (mStepping) { - mStepping = false; - _UpdatePauseButton(); - } - return false; - } - - --mNumberOfStepsAllowed; - return true; -} - -bool DebugWindowDialog::RunAppFast(void) -{ - return mRunFast; -} - -void DebugWindowDialog::AppendMessage(const std::string& messageToAppend) -{ - mMessages.push_back(messageToAppend); - _RebuildMesgString(); -} - -void DebugWindowDialog::AdjustVariable(const std::string& varName, const std::string& varValue) -{ - for (VecPairStringIt it = mVariables.begin(); it != mVariables.end(); it++) { - if (it->first == varName) { - it->second = varValue; - _RebuildVarsString(); - return; - } - } - - PairString newPair; - newPair.first = varName; - newPair.second = varValue; - mVariables.push_back(newPair); - - _RebuildVarsString(); -} - -void DebugWindowDialog::SetFrameNumber(int frameNumber) -{ - static int numDigits; - numDigits = frameNumber / 10 + 2; // 1 for 1 additional digit, 1 for \0 - - mFrameNumber.resize(numDigits); - sprintf(&mFrameNumber[0], "%d", frameNumber); - - CWnd *pWnd = GetDlgItem(IDC_FrameNumber); - if (pWnd) { - pWnd->SetWindowText(mFrameNumber.c_str()); - } -} - -void DebugWindowDialog::_RebuildVarsString(void) -{ - int cursorPosBeg, cursorPosEnd; - ((CEdit*)GetDlgItem(IDC_Variables))->GetSel(cursorPosBeg, cursorPosEnd); - mVariablesString = ""; - - for (VecPairStringIt it = mVariables.begin(); it != mVariables.end(); it++) { - mVariablesString += it->first; - mVariablesString += " = "; - mVariablesString += it->second; - mVariablesString += "\r\n"; - } - - - - // Push the new string - mVariablesDisplayString = mVariablesString.c_str(); - GetDlgItem(IDC_Variables)->SetWindowText(mVariablesDisplayString); - ((CEdit*)GetDlgItem(IDC_Variables))->GetSel(cursorPosBeg, cursorPosEnd); -} - -void DebugWindowDialog::_RebuildMesgString(void) -{ - mMessagesString = ""; - - for (VecStringIt it = mMessages.begin(); it != mMessages.end(); it++) { - mMessagesString += (*it); - mMessagesString += "\r\n"; - } - - // Push the new string - mMessagesDisplayString = mMessagesString.c_str(); - GetDlgItem(IDC_Messages)->SetWindowText(mMessagesDisplayString); - ((CEdit*)GetDlgItem(IDC_Messages))->SetSel(mMessagesString.length(), mMessagesString.length(), false); -} - -void DebugWindowDialog::_UpdatePauseButton(void) -{ - // huh huh huhuh he said pButt - CButton* pButt = (CButton*) GetDlgItem(IDC_Pause); - - if (!pButt) { - return; - } - - // The state should of the button should reflect !mNumberOfStepsAllowed - pButt->SetCheck((mNumberOfStepsAllowed ? FALSE : TRUE)); -} - - -void DebugWindowDialog::OnClose() -{ - ShowWindow(SW_MINIMIZE); -} - -void DebugWindowDialog::OnSize(UINT nType, int cx, int cy) -{ - CDialog::OnSize(nType, cx, cy); - if (nType == SIZE_MINIMIZED) { - if (mMainWndHWND) { - ::SetFocus(mMainWndHWND); - } - } -} - - - -BEGIN_MESSAGE_MAP(DebugWindowDialog, CDialog) - ON_WM_CREATE( ) - ON_BN_CLICKED(IDC_Pause, OnPause) - ON_BN_CLICKED(IDC_Step, OnStep) - ON_BN_CLICKED(IDC_RUN_FAST, OnRunFast) - ON_BN_CLICKED(IDC_StepTen, OnStepTen) - ON_BN_CLICKED(IDC_ClearWindows, OnClearWindows) - ON_WM_CLOSE() - ON_WM_SIZE() -END_MESSAGE_MAP() \ No newline at end of file diff --git a/Generals/Code/Tools/DebugWindow/DebugWindowDialog.h b/Generals/Code/Tools/DebugWindow/DebugWindowDialog.h deleted file mode 100644 index a3040d0481..0000000000 --- a/Generals/Code/Tools/DebugWindow/DebugWindowDialog.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#include "Resource.h" -#include // for std::pair -#include // for std::string -#include // for std::vector - -typedef std::pair PairString; -typedef std::vector VecPairString; -typedef std::vector VecString; - -typedef std::vector::iterator VecPairStringIt; -typedef std::vector::iterator VecStringIt; - - -class DebugWindowDialog : public CDialog -{ - public: - enum {IDD = IDD_DebugWindow}; - DebugWindowDialog(UINT nIDTemplate = DebugWindowDialog::IDD, CWnd* pParentWnd = NULL); - - bool CanProceed(void); - bool RunAppFast(void); - void AppendMessage(const std::string& messageToAppend); - void AdjustVariable(const std::string& varName, const std::string& varValue); - void SetFrameNumber(int frameNumber); - HWND GetMainWndHWND(void); - void ForcePause(void); - void ForceContinue(void); - - // This var shouldn't be here, but honsestly... - protected: - HWND mMainWndHWND; - int mNumberOfStepsAllowed; /// -1 means go forever, 0 means stop now, a positive number will be decremented to 0, 1 frame at a time - std::string mVariablesString; - std::string mMessagesString; - CString mVariablesDisplayString; // For double buffering - CString mMessagesDisplayString; // For double buffering - std::string mFrameNumber; - bool mStepping; - bool mRunFast; - - - - VecPairString mVariables; - VecString mMessages; - - void _RebuildVarsString(void); - void _RebuildMesgString(void); - void _UpdatePauseButton(void); - - protected: - afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); - afx_msg void OnSize(UINT nType, int cx, int cy); - afx_msg void OnPause(); - afx_msg void OnStep(); - afx_msg void OnRunFast(); - afx_msg void OnStepTen(); - afx_msg void OnClearWindows(); - afx_msg void OnClose(); - DECLARE_MESSAGE_MAP() - - - -}; \ No newline at end of file diff --git a/Generals/Code/Tools/DebugWindow/DebugWindowExport.h b/Generals/Code/Tools/DebugWindow/DebugWindowExport.h deleted file mode 100644 index 4987cde2a2..0000000000 --- a/Generals/Code/Tools/DebugWindow/DebugWindowExport.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#pragma once - -// Declared extern C to prevent name mangling, which makes life very unhappy -extern "C" { - // Called to create the dialog - void __declspec(dllexport) CreateDebugDialog(void); - - // Called to (not surprisingly) destroy the dialog (and free the resources) - void __declspec(dllexport) DestroyDebugDialog(void); - - // Call this each frame to determine whether to continue or not - bool __declspec(dllexport) CanAppContinue(void); - - // Call this to force the app to continue. (Unpause if necessary.) - void __declspec(dllexport) ForceAppContinue(void); - - // Call this to tell the app to run really fast - bool __declspec(dllexport) RunAppFast(void); - - // Call this to add a message to the script window - void __declspec(dllexport) AppendMessage(const char* messageToPass); - - // Call this to set the frame number of the app - void __declspec(dllexport) SetFrameNumber(int frameNumber); - - // Call this to add a message, and simulate pressing Pause immediately after - void __declspec(dllexport) AppendMessageAndPause(const char* messageToPass); - - // Call this to add or update a variable value - void __declspec(dllexport) AdjustVariable(const char* variable, const char* value); - - // Call this to add or update a variable value, and simulate pressing Pause immediately after - void __declspec(dllexport) AdjustVariableAndPause(const char* variable, const char* value); -} \ No newline at end of file diff --git a/Generals/Code/Tools/DebugWindow/Resource.h b/Generals/Code/Tools/DebugWindow/Resource.h deleted file mode 100644 index 2b70b46605..0000000000 --- a/Generals/Code/Tools/DebugWindow/Resource.h +++ /dev/null @@ -1,26 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by DebugWindow.rc -// -#define IDC_Pause 1000 -#define IDD_DebugWindow 1000 -#define IDC_Step 1001 -#define IDC_StepTen 1002 -#define IDC_Variables 1003 -#define IDC_Messages 1004 -#define IDC_Variables_Text 1005 -#define IDC_Messages_Text 1006 -#define IDC_ClearWindows 1007 -#define IDC_RUN_FAST 1008 -#define IDC_FrameNumber 1010 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 1001 -#define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 1011 -#define _APS_NEXT_SYMED_VALUE 1000 -#endif -#endif diff --git a/Generals/Code/Tools/DebugWindow/StdAfx.cpp b/Generals/Code/Tools/DebugWindow/StdAfx.cpp deleted file mode 100644 index 7e214580f0..0000000000 --- a/Generals/Code/Tools/DebugWindow/StdAfx.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.cpp : source file that includes just the standard includes -// DebugWindow.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "StdAfx.h" - - - diff --git a/Generals/Code/Tools/DebugWindow/StdAfx.h b/Generals/Code/Tools/DebugWindow/StdAfx.h deleted file mode 100644 index 2ed562467b..0000000000 --- a/Generals/Code/Tools/DebugWindow/StdAfx.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__FB15454D_21B4_4F33_A593_C13A58B86008__INCLUDED_) -#define AFX_STDAFX_H__FB15454D_21B4_4F33_A593_C13A58B86008__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers - -// TheSuperHackers @compile xezon 24/03/2025 Prevent afxwin.h from loading d3d9types.h, colliding with our own DirectX library. -#define _d3d9TYPES_H_ - -#include // MFC core and standard components -#include // MFC extensions - -#ifndef _AFX_NO_OLE_SUPPORT -#include // MFC OLE classes -#include // MFC OLE dialog classes -#include // MFC Automation classes -#endif // _AFX_NO_OLE_SUPPORT - - -#ifndef _AFX_NO_DB_SUPPORT -#include // MFC ODBC database classes -#endif // _AFX_NO_DB_SUPPORT - -#ifndef _AFX_NO_DAO_SUPPORT -#include // MFC DAO database classes -#endif // _AFX_NO_DAO_SUPPORT - -#include // MFC support for Internet Explorer 4 Common Controls -#ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls -#endif // _AFX_NO_AFXCMN_SUPPORT - -// I don't care that debug symbols are longer than 255, I won't read them anyways. -#pragma warning (disable : 4786) - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__FB15454D_21B4_4F33_A593_C13A58B86008__INCLUDED_) diff --git a/Generals/Code/Tools/GUIEdit/Include/GUIEditDisplay.h b/Generals/Code/Tools/GUIEdit/Include/GUIEditDisplay.h index 56ced30d04..9d2966ac5b 100644 --- a/Generals/Code/Tools/GUIEdit/Include/GUIEditDisplay.h +++ b/Generals/Code/Tools/GUIEdit/Include/GUIEditDisplay.h @@ -117,11 +117,11 @@ class GUIEditDisplay : public Display virtual void preloadTextureAssets( AsciiString texture ) {} virtual void toggleLetterBox(void) {} virtual void enableLetterBox(Bool enable) {} -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void dumpModelAssets(const char *path) {} #endif virtual void doSmartAssetPurgeAndPreload(const char* usageFileName) {} -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void dumpAssetUsage(const char* mapname) {} #endif diff --git a/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp b/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp index 6cae5235c5..d6d9e25ec0 100644 --- a/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp @@ -600,9 +600,8 @@ static LRESULT CALLBACK listboxPropertiesCallback( HWND hWndDialog, if(newColumns > 1) { - char *percentages = new char[60]; - char *token; - GetDlgItemText(hWndDialog,EDIT_COLUMN_PERCENT,percentages,200); + Char percentages[200]; + GetDlgItemText(hWndDialog,EDIT_COLUMN_PERCENT,percentages,sizeof(percentages)); if(strlen(percentages) == 0) { MessageBox(NULL,"You have specified a column amount greater then 1, please enter the same about of percentages","whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); @@ -612,7 +611,7 @@ static LRESULT CALLBACK listboxPropertiesCallback( HWND hWndDialog, Int *newPercentages = new Int[newColumns]; Int i = 0; Int total = 0; - token = strtok( percentages, "," ); + Char *token = strtok( percentages, "," ); while( token != NULL ) { newPercentages[i] = atoi(token); @@ -621,23 +620,26 @@ static LRESULT CALLBACK listboxPropertiesCallback( HWND hWndDialog, i++; if(i > newColumns && token) { - Char *whoopsMsg = new char[250]; + Char whoopsMsg[250]; sprintf(whoopsMsg,"You have Specified %d columns but I have read in more then that for the percentages, please double check your data", newColumns); MessageBox(NULL, whoopsMsg,"Whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); + delete[] newPercentages; return 0; } else if( i < newColumns && !token ) { - Char *whoopsMsg = new char[250]; + Char whoopsMsg[250]; sprintf(whoopsMsg,"You have Specified %d columns but I have read in only %d for the percentages, please double check your data", newColumns, i ); MessageBox(NULL, whoopsMsg,"Whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); + delete[] newPercentages; return 0; } else if((total > 100 ) || (total < 100 && !token )) { - Char *whoopsMsg = new char[250]; - sprintf(whoopsMsg,"Please Double check to make sure your percentages add up to 100.", newColumns, i - 1); + Char whoopsMsg[250]; + sprintf(whoopsMsg,"Please Double check to make sure your percentages add up to 100."); MessageBox(NULL, whoopsMsg,"Whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); + delete[] newPercentages; return 0; } } @@ -941,8 +943,8 @@ HWND InitListboxPropertiesDialog( GameWindow *window ) SetDlgItemInt( dialog, EDIT_NUM_COLUMNS, listData->columns, FALSE ); if(listData->columns > 1) { - char *percentages = new char[60]; - char *tempStr = new char[60]; + Char percentages[200]; + Char tempStr[33]; sprintf(percentages,"%d",listData->columnWidthPercentage[0]); for(Int i = 1; i < listData->columns; i++ ) { diff --git a/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp b/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp index a9c3981816..7b4e2c8cfb 100644 --- a/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/GUIEdit.cpp @@ -488,6 +488,10 @@ void GUIEdit::init( void ) // add status bar to the bottom createStatusBar(); + // create the name key generator + TheNameKeyGenerator = new NameKeyGenerator; + TheNameKeyGenerator->init(); + // create file system TheFileSystem = new FileSystem; TheLocalFileSystem = new Win32LocalFileSystem; @@ -522,10 +526,6 @@ void GUIEdit::init( void ) TheWritableGlobalData = new GlobalData; TheWritableGlobalData->init(); - // create the name key generator - TheNameKeyGenerator = new NameKeyGenerator; - TheNameKeyGenerator->init(); - // create the message stream TheMessageStream = new MessageStream; TheMessageStream->init(); diff --git a/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp b/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp index 444bfa67ef..ef558cf7fa 100644 --- a/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp +++ b/Generals/Code/Tools/GUIEdit/Source/LayoutScheme.cpp @@ -2349,32 +2349,43 @@ Bool LayoutScheme::loadScheme( char *filename ) // write header Int version; - fscanf( fp, "Window Layout Scheme: Version '%d'\n", &version ); - if( version != SCHEME_VERSION ) + if (fscanf( fp, "Window Layout Scheme: Version '%d'\n", &version ) == 1) { + if( version != SCHEME_VERSION ) + { - DEBUG_LOG(( "loadScheme: Old layout file version '%d'\n", version )); - MessageBox( TheEditor->getWindowHandle(), - "Old layout version, cannot open.", "Old File", MB_OK ); - return FALSE; - - } // end if + DEBUG_LOG(( "loadScheme: Old layout file version '%d'\n", version )); + MessageBox( TheEditor->getWindowHandle(), + "Old layout version, cannot open.", "Old File", MB_OK ); + return FALSE; + } // end if + } // default text colors - fscanf( fp, "Enabled Text: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_enabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); - fscanf( fp, "Enabled Text Border: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_enabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); - - fscanf( fp, "Disabled Text: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_disabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); - fscanf( fp, "Disabled Text Border: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_disabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); - - fscanf( fp, "Hilite Text: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_hiliteText.color = GameMakeColor( colorR, colorG, colorB, colorA ); - fscanf( fp, "Hilite Text Border: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_hiliteText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + if (fscanf( fp, "Enabled Text: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_enabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Enabled Text Border: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_enabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Disabled Text: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_disabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Disabled Text Border: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_disabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Hilite Text: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_hiliteText.color = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Hilite Text Border: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_hiliteText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + } // default font char fontBuffer[ 256 ]; @@ -2399,34 +2410,36 @@ Bool LayoutScheme::loadScheme( char *filename ) c = fgetc( fp ); // the end quite itself // read the size and bold data elements - fscanf( fp, " Size: %d Bold: %d\n", &size, &bold ); - - // set the font - m_font = TheFontLibrary->getFont( AsciiString(fontBuffer), size, bold ); + if(fscanf( fp, " Size: %i Bold: %i\n", &size, &bold ) == 2) + { + // set the font + m_font = TheFontLibrary->getFont( AsciiString(fontBuffer), size, bold ); + } // all the data for all the states Int numStates, state; char imageBuffer[ 128 ]; - fscanf( fp, "Number of states: %d\n", &numStates ); - for( Int i = 0; i < numStates; i++ ) + if (fscanf( fp, "Number of states: %i\n", &numStates ) == 1) { + for( Int i = 0; i < numStates; i++ ) + { - // read all the data - fscanf( fp, "%d: Image: %s Color: (%d,%d,%d,%d) Border: (%d,%d,%d,%d)\n", - &state, imageBuffer, &colorR, &colorG, &colorB, &colorA, - &bColorR, &bColorG, &bColorB, &bColorA ); - - // sanity - assert( state == i ); - - // store the info - storeImageAndColor( (StateIdentifier)state, - TheMappedImageCollection->findImageByName( AsciiString( imageBuffer ) ), - GameMakeColor( colorR, colorG, colorB, colorA ), - GameMakeColor( bColorR, bColorG, bColorB, bColorA ) ); - - } // end for i - + // read all the data + if( fscanf( fp, "%d: Image: %s Color: (%hhu,%hhu,%hhu,%hhu) Border: (%hhu,%hhu,%hhu,%hhu)\n", + &state, imageBuffer, &colorR, &colorG, &colorB, &colorA, + &bColorR, &bColorG, &bColorB, &bColorA ) == 10) + { + // sanity + assert( state == i ); + + // store the info + storeImageAndColor( (StateIdentifier)state, + TheMappedImageCollection->findImageByName( AsciiString( imageBuffer ) ), + GameMakeColor( colorR, colorG, colorB, colorA ), + GameMakeColor( bColorR, bColorG, bColorB, bColorA ) ); + } + } // end for i + } // close the file fclose( fp ); diff --git a/Generals/Code/Tools/ImagePacker/CMakeLists.txt b/Generals/Code/Tools/ImagePacker/CMakeLists.txt index a1fb500469..34df3e1395 100644 --- a/Generals/Code/Tools/ImagePacker/CMakeLists.txt +++ b/Generals/Code/Tools/ImagePacker/CMakeLists.txt @@ -1,43 +1,9 @@ -set(IMAGEPACKER_SRC - "Include/ImageDirectory.h" - "Include/ImageInfo.h" - "Include/ImagePacker.h" - "Include/TexturePage.h" - "Include/WindowProc.h" - "Include/WinMain.h" - "Source/ImageInfo.cpp" - "Source/ImagePacker.cpp" - "Source/TexturePage.cpp" - "Source/WinMain.cpp" - "Source/Window Procedures/DirectorySelect.cpp" - "Source/Window Procedures/ImageErrorProc.cpp" - "Source/Window Procedures/ImagePackerProc.cpp" - "Source/Window Procedures/PageErrorProc.cpp" - "Source/Window Procedures/PreviewProc.cpp" -) - add_executable(g_imagepacker WIN32) set_target_properties(g_imagepacker PROPERTIES OUTPUT_NAME imagepacker) -target_sources(g_imagepacker PRIVATE ${IMAGEPACKER_SRC}) - -target_include_directories(g_imagepacker PRIVATE - Include - Resource -) - target_link_libraries(g_imagepacker PRIVATE - benchmark - comctl32 - dbghelplib + corei_imagepacker g_gameengine g_gameenginedevice gi_always - imm32 - vfw32 - winmm ) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(g_imagepacker PRIVATE Resource/ImagePacker.rc) -endif() diff --git a/Generals/Code/Tools/ImagePacker/Include/ImageDirectory.h b/Generals/Code/Tools/ImagePacker/Include/ImageDirectory.h deleted file mode 100644 index fd8e4fef89..0000000000 --- a/Generals/Code/Tools/ImagePacker/Include/ImageDirectory.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImageDirectory.h ///////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImageDirectory.h -// -// Created: Colin Day, August 2001 -// -// Desc: Image directory description for directories containing -// image files to pack -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __IMAGEDIRECTORY_H_ -#define __IMAGEDIRECTORY_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////// - -// FORWARD REFERENCES ///////////////////////////////////////////////////////// - -// TYPE DEFINES /////////////////////////////////////////////////////////////// - -// ImageDirectory ------------------------------------------------------------- -/** Directory to contain art files */ -//----------------------------------------------------------------------------- -class ImageDirectory -{ - -public: - - ImageDirectory(); - ~ImageDirectory(); - - char *m_path; ///< path for directory - UnsignedInt m_imageCount; ///< images to consider in this directory - ImageDirectory *m_next; - ImageDirectory *m_prev; - -}; - -/////////////////////////////////////////////////////////////////////////////// -// INLINING /////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -inline ImageDirectory::~ImageDirectory( void ) { delete m_path; } -inline ImageDirectory::ImageDirectory( void ) -{ - m_path = NULL; - m_next = NULL; - m_prev = NULL; - m_imageCount = 0; -} - -// EXTERNALS ////////////////////////////////////////////////////////////////// - -#endif // __IMAGEDIRECTORY_H_ - diff --git a/Generals/Code/Tools/ImagePacker/Include/ImageInfo.h b/Generals/Code/Tools/ImagePacker/Include/ImageInfo.h deleted file mode 100644 index d9047eb97c..0000000000 --- a/Generals/Code/Tools/ImagePacker/Include/ImageInfo.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImageInfo.h ////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImageInfo.h -// -// Created: Colin Day, August 2001 -// -// Desc: Image descriptor for the image packer -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __IMAGEINFO_H_ -#define __IMAGEINFO_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "Lib/BaseType.h" - -/////////////////////////////////////////////////////////////////////////////// -// FORWARD REFERENCES ///////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -class TexturePage; - -// TYPE DEFINES /////////////////////////////////////////////////////////////// - -// ImageInfo ------------------------------------------------------------------ -/** Image file information */ -//----------------------------------------------------------------------------- -class ImageInfo -{ - -public: - - enum - { - UNPACKED = 0x00000001, ///< this image has not yet been packed - PACKED = 0x00000002, ///< this image has been packed and is done - TOOBIG = 0x00000004, ///< this image was too big to process - ROTATED90C = 0x00000008, ///< image is fitted after 90 clockwise rotation - CANTPROCESS = 0x00000010, ///< can't be processed - INVALIDCOLORDEPTH = 0x00000020, ///< unsupported source image format - }; - - enum - { - FIT_XGUTTER = 0x00000001, ///< x gutter is present in fit region - FIT_YGUTTER = 0x00000002, ///< y gutter is present in fit region - FIT_XBORDER_RIGHT = 0x00000004, ///< x border of 1 pixel on right side of region - FIT_XBORDER_LEFT = 0x00000008, ///< x border of 1 pixel on left side of region - FIT_YBORDER_TOP = 0x00000010, ///< y border of 1 pixel on top of region - FIT_YBORDER_BOTTOM = 0x00000020, ///< y border of 1 pixel on bottom of image - }; - -public: - - ImageInfo(); - ~ImageInfo(); - - char *m_path; ///< path to file - char *m_filenameOnly; ///< filename with extension only (no path information) - char *m_filenameOnlyNoExt; ///< filename without extension and no path info - Int m_colorDepth; ///< bits per pixel - UnsignedInt m_area; ///< width and height area - ICoord2D m_size; ///< width and height of image - UnsignedInt m_status; ///< status bits for image - - TexturePage *m_page; ///< pointer to page this image is now packed on - ImageInfo *m_nextPageImage; ///< next image on texture page - ImageInfo *m_prevPageImage; ///< previous image on texture page - IRegion2D m_pagePos; /** once placed on a texture page this has the - coords of the image on the page, it does not include - any padding from stretching borders and gutters */ - - UnsignedInt m_fitBits; /**< bit flags of the region used to fit this image on - a page and therefore to create m_pagePos */ - ICoord2D m_gutterUsed; ///< the gutter size actually used in this image fit - -}; - -// INLINING /////////////////////////////////////////////////////////////////// - -// EXTERNALS ////////////////////////////////////////////////////////////////// - -#endif // __IMAGEINFO_H_ - diff --git a/Generals/Code/Tools/ImagePacker/Include/ImagePacker.h b/Generals/Code/Tools/ImagePacker/Include/ImagePacker.h deleted file mode 100644 index 926c3e2835..0000000000 --- a/Generals/Code/Tools/ImagePacker/Include/ImagePacker.h +++ /dev/null @@ -1,217 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImagePacker.h //////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImagePacker.h -// -// Created: Colin Day, August 2001 -// -// Desc: Image packer tool -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __IMAGEPACKER_H_ -#define __IMAGEPACKER_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "Lib/BaseType.h" -#include "WWLib/TARGA.H" -#include "ImageDirectory.h" -#include "ImageInfo.h" -#include "TexturePage.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// TYPE DEFINES /////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -#define MAX_OUTPUT_FILE_LEN 128 -#define DEFAULT_TARGET_SIZE 512 - -// ImagePacker ---------------------------------------------------------------- -// Class interface for running the image packer */ -//----------------------------------------------------------------------------- -class ImagePacker -{ - -public: - - enum - { - GAP_METHOD_EXTEND_RGB = 0x00000001, ///< extend RGB (no alpha) of image on all sides - GAP_METHOD_GUTTER = 0x00000002, ///< put transparent gutter on right and bottom side of image - }; - -public: - - ImagePacker( void ); - virtual ~ImagePacker( void ); - - Bool init( void ); ///< initialize the system - Bool process( void ); ///< run the process - Bool getSettingsFromDialog( HWND dialog ); ///< get the options for exection - - void setWindowHandle( HWND hWnd ); ///< set window handle for 'dialog' app - HWND getWindowHandle( void ); ///< get window handle for 'dialog' app - - ICoord2D *getTargetSize( void ); ///< get target size - Int getTargetWidth( void ); ///< get target width - Int getTargetHeight( void ); ///< bet target height - - void statusMessage( const char *message ); ///< set a status message - - UnsignedInt getImageCount( void ); ///< get image count - ImageInfo *getImage( Int index ); ///< get image - TexturePage *getFirstTexturePage( void ); ///< get first texture page - - UnsignedInt getPageCount( void ); ///< get the count of texutre pages - - void setTargetPreviewPage( Int page ); ///< set the target preview page to view - Int getTargetPreviewPage( void ); ///< get the target preview page to view - - void setGutter( UnsignedInt size ); ///< set gutter size in pixels - UnsignedInt getGutter( void ); ///< get gutter size in pixels - void setGapMethod( UnsignedInt methodBit ); ///< set gap method option - void clearGapMethod( UnsignedInt methodBit ); ///< clear gap method option - UnsignedInt getGapMethod( void ); ///< get gap method option - - void setOutputAlpha( Bool outputAlpha ); ///< set output alpha option - Bool getOutputAlpha( void ); ///< get output alpha option - - void setPreviewWindow( HWND window ); ///< assign preview window handle - HWND getPreviewWindow( void ); ///< get the preview window handle - - void setUseTexturePreview( Bool use ); ///< use the real image data in preview - Bool getUseTexturePreview( void ); ///< get texture preview option - - void setINICreate( Bool create ); ///< set create INI file option - Bool createINIFile( void ); ///< get create INI option - - char *getOutputFile( void ); ///< get output filename - char *getOutputDirectory( void ); ///< get output directory - - void setCompressTextures( Bool compress ); ///< set compress textures option - Bool getCompressTextures( void ); ///< get compress textures option - -protected: - - void setTargetSize( Int width, Int height ); ///< set the size of the output target image - Bool checkOutputDirectory( void ); ///< verify output directory is OK - - void resetImageDirectoryList( void ); ///< clear the image directory list - void resetImageList( void ); ///< clear the image list - void resetPageList( void ); ///< clear the texture page list - void addDirectory( char *path, Bool subDirs ); ///< add directory to directory list - void addImagesInDirectory( char *dir ); ///< add all images from the specified directory - void addImage( char *path ); ///< add image to image list - Bool validateImages( void ); ///< validate that the loaded images can all be processed - Bool packImages( void ); ///< do the packing - void writeFinalTextures( void ); ///< write the packed textures - - Bool generateINIFile( void ); ///< generate the INI file for this image set - - TexturePage *createNewTexturePage( void ); ///< create a new texture page - - void sortImageList( void ); ///< sort the image list - - HWND m_hWnd; ///< window handle for app - ICoord2D m_targetSize; ///< the target size - Bool m_useSubFolders; ///< use subfolders option - char m_outputFile[ MAX_OUTPUT_FILE_LEN ]; ///< output filename - char m_outputDirectory[ _MAX_PATH ]; ///< destination for texture files - - ImageDirectory *m_dirList; ///< the directory list - UnsignedInt m_dirCount; ///< length of dirList - UnsignedInt m_imagesInDirs; ///< number of images in all directories - ImageInfo **m_imageList; ///< the image list - UnsignedInt m_imageCount; ///< length of imageList - char m_statusBuffer[ 1024 ]; ///< for printing status messages - TexturePage *m_pageTail; ///< end of the texture page list - TexturePage *m_pageList; ///< the final images generated from the packer - UnsignedInt m_pageCount; ///< length of page list - UnsignedInt m_gapMethod; ///< gap method option bits - UnsignedInt m_gutterSize; ///< gutter gaps between images in pixels - Bool m_outputAlpha; ///< final image files will have an alpha channel - Bool m_createINI; ///< create the INI file from compressed image data - - Int m_targetPreviewPage; ///< preview page we're looking at - HWND m_hWndPreview; ///< the preview window - Bool m_showTextureInPreview; ///< show actual texture in preview window - - Targa *m_targa; ///< targa for loading file headers - Bool m_compressTextures; ///< compress the final textures - -}; - -/////////////////////////////////////////////////////////////////////////////// -// INLINING /////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -inline void ImagePacker::setTargetSize( Int width, Int height ) { m_targetSize.x = width; m_targetSize.y = height; } -inline ICoord2D *ImagePacker::getTargetSize( void ) { return &m_targetSize; } -inline Int ImagePacker::getTargetWidth( void ) { return m_targetSize.x; } -inline Int ImagePacker::getTargetHeight( void ) { return m_targetSize.y; } -inline void ImagePacker::setWindowHandle( HWND hWnd ) { m_hWnd = hWnd; } -inline HWND ImagePacker::getWindowHandle( void ) { return m_hWnd; } -inline UnsignedInt ImagePacker::getImageCount( void ) { return m_imageCount; } -inline ImageInfo *ImagePacker::getImage( Int index ) { return m_imageList[ index ]; } -inline void ImagePacker::setTargetPreviewPage( Int page ) { m_targetPreviewPage = page; } -inline Int ImagePacker::getTargetPreviewPage( void ) { return m_targetPreviewPage; } -inline UnsignedInt ImagePacker::getPageCount( void ) { return m_pageCount; } -inline void ImagePacker::setPreviewWindow( HWND window ) { m_hWndPreview = window; } -inline HWND ImagePacker::getPreviewWindow( void ) { return m_hWndPreview; } -inline void ImagePacker::setGutter( UnsignedInt size ) { m_gutterSize = size; } -inline UnsignedInt ImagePacker::getGutter( void ) { return m_gutterSize; } -inline void ImagePacker::setOutputAlpha( Bool outputAlpha ) { m_outputAlpha = outputAlpha; } -inline Bool ImagePacker::getOutputAlpha( void ) { return m_outputAlpha; } -inline TexturePage *ImagePacker::getFirstTexturePage( void ) { return m_pageList; } -inline void ImagePacker::setUseTexturePreview( Bool use ) { m_showTextureInPreview = use; } -inline Bool ImagePacker::getUseTexturePreview( void ) { return m_showTextureInPreview; } -inline void ImagePacker::setINICreate( Bool create ) { m_createINI = create; }; -inline Bool ImagePacker::createINIFile( void ) { return m_createINI; } -inline char *ImagePacker::getOutputFile( void ) { return m_outputFile; } -inline char *ImagePacker::getOutputDirectory( void ) { return m_outputDirectory; } -inline void ImagePacker::setCompressTextures( Bool compress ) { m_compressTextures = compress; } -inline Bool ImagePacker::getCompressTextures( void ) { return m_compressTextures; } -inline void ImagePacker::setGapMethod( UnsignedInt methodBit ) { BitSet( m_gapMethod, methodBit ); } -inline void ImagePacker::clearGapMethod( UnsignedInt methodBit ) { BitClear( m_gapMethod, methodBit ); } -inline UnsignedInt ImagePacker::getGapMethod( void ) { return m_gapMethod; } - -/////////////////////////////////////////////////////////////////////////////// -// EXTERNALS ////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -extern ImagePacker *TheImagePacker; - -#endif // __IMAGEPACKER_H_ - diff --git a/Generals/Code/Tools/ImagePacker/Include/TexturePage.h b/Generals/Code/Tools/ImagePacker/Include/TexturePage.h deleted file mode 100644 index 538c84454e..0000000000 --- a/Generals/Code/Tools/ImagePacker/Include/TexturePage.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: TexturePage.h //////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: TexturePage.h -// -// Created: Colin Day, August 2001 -// -// Desc: This class represents a texture that contains packed -// images. -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __TEXTUREPAGE_H_ -#define __TEXTUREPAGE_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include - -/////////////////////////////////////////////////////////////////////////////// -// USER INCLUDES ////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -#include "WWLib/TARGA.H" -#include "Lib/BaseType.h" -#include "ImageInfo.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// TYPE DEFINES /////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// TexturePage ---------------------------------------------------------------- -/** A texture page continaing multiple source images */ -//----------------------------------------------------------------------------- -class TexturePage -{ - -public: - - enum - { - FREE = 0, ///< open pixel in the cavas - USED = 1, ///< used pixel in the canvas - }; - - enum - { - READY = 0x00000001, ///< texture page here and OK - PAGE_ERROR = 0x00000002, ///< error on page somewhere - CANT_ALLOCATE_PACKED_IMAGE = 0x00000004, ///< couldn't generate final image - CANT_ADD_IMAGE_DATA = 0x00000008, ///< couldn't add image data to page - NO_TEXTURE_DATA = 0x00000010, ///< there was no image data to write - ERROR_DURING_SAVE = 0x00000020, ///< couldn't save final file - }; - - TexturePage( Int width, Int height ); - ~TexturePage( void ); - - Bool addImage( ImageInfo *image ); ///< try to add image to this page - - void setID( Int id ); ///< set page id - Int getID( void ); ///< get page id - - Bool generateTexture( void ); ///< generate the final packed texture - Bool writeFile( char *baseFilename ); ///< write generated texture to file - - ImageInfo *getFirstImage( void ); ///< get the first image in the list - - Int getWidth( void ); ///< get width of texture page - Int getHeight( void ); ///< get height of texture page - - // get rgb from final generated texture (putting this in for quick preview) - void getPixel( Int x, Int y, Byte *r, Byte *g, Byte *b, Byte *a = NULL ); - - TexturePage *m_next; - TexturePage *m_prev; - - UnsignedInt m_status; ///< status bits - -protected: - - Bool spotUsed( Int x, Int y ); ///< is this spot used - Bool lineUsed( Int sx, Int sy, Int ex, Int ey ); ///< is any spot on the line used - - /// build a region to try to fit given the position, size, and border options - UnsignedInt buildFitRegion( IRegion2D *region, - Int startX, Int startY, - Int imageWidth, Int imageHeight, - Int *xGutter, Int *yGutter, - Bool allSidesBorder ); - - void markRegionUsed( IRegion2D *region ); ///< mark this region as used - - /// add the actual image data of 'image' to the destination buffer - Bool addImageData( Byte *destBuffer, - Int destWidth, - Int destHeight, - Int destBPP, - ImageInfo *image ); - - /// extend edges of image outward into border if present - void extendImageEdges( Byte *destBuffer, - Int destWidth, - Int destHeight, - Int destBPP, - ImageInfo *image, - Bool extendAlpha ); - - /// if the pixel at abolve/below row is open, extend pixel at src to its location - void extendToRowIfOpen( char *src, - Int buffWidth, - Int buffBPP, - Bool extendAlpha, - Int imageHeight, - UnsignedInt fitBits, - Int srcX, Int srcY ); - - - Int m_id; ///< texture page ID - ICoord2D m_size; ///< dimensions of texture page - UnsignedByte *m_canvas; ///< as big as the texture page, a used spot is non zero - - ImageInfo *m_imageList; ///< list of images packed on this page - - Byte *m_packedImage; ///< final generated image data - Targa *m_targa; ///< final packed image all in a nice little targa file - -}; - -/////////////////////////////////////////////////////////////////////////////// -// INLINING /////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -inline void TexturePage::setID( Int id ) { m_id = id; } -inline Int TexturePage::getID( void ) { return m_id; } -inline ImageInfo *TexturePage::getFirstImage( void ) { return m_imageList; } -inline Int TexturePage::getWidth( void ) { return m_size.x; } -inline Int TexturePage::getHeight( void ) { return m_size.y; } - -// EXTERNALS ////////////////////////////////////////////////////////////////// - -#endif // __TEXTUREPAGE_H_ - diff --git a/Generals/Code/Tools/ImagePacker/Include/WinMain.h b/Generals/Code/Tools/ImagePacker/Include/WinMain.h deleted file mode 100644 index a0638f3bf5..0000000000 --- a/Generals/Code/Tools/ImagePacker/Include/WinMain.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: WinMain.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: WinMain.h -// -// Created: Colin Day, August 2001 -// -// Desc: Header for main app -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __WINMAIN_H_ -#define __WINMAIN_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// - -// FORWARD REFERENCES ///////////////////////////////////////////////////////// - -// TYPE DEFINES /////////////////////////////////////////////////////////////// - -// INLINING /////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// EXTERNALS ////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -extern HINSTANCE ApplicationHInstance; - -#endif // __WINMAIN_H_ - diff --git a/Generals/Code/Tools/ImagePacker/Include/WindowProc.h b/Generals/Code/Tools/ImagePacker/Include/WindowProc.h deleted file mode 100644 index a2990dd04b..0000000000 --- a/Generals/Code/Tools/ImagePacker/Include/WindowProc.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: WindowProc.h ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: WindowProc.h -// -// Created: Colin Day, August 2001 -// -// Desc: Dialog procedure header for image packer utility -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __WINDOWPROC_H_ -#define __WINDOWPROC_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////// - -// FORWARD REFERENCES ///////////////////////////////////////////////////////// - -// TYPE DEFINES /////////////////////////////////////////////////////////////// - -// INLINING /////////////////////////////////////////////////////////////////// - -// EXTERNALS ////////////////////////////////////////////////////////////////// -extern BOOL CALLBACK ImagePackerProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ); - -extern HWND MakePreviewDisplay( void ); -extern void UpdatePreviewWindow( void ); -extern LRESULT CALLBACK PreviewProc( HWND hWnd, UINT message, - WPARAM wParam, LPARAM lParam ); - -extern BOOL CALLBACK ImageErrorProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ); - -extern BOOL CALLBACK PageErrorProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ); - -extern BOOL CALLBACK DirectorySelectProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ); - -#endif // __WINDOWPROC_H_ - diff --git a/Generals/Code/Tools/ImagePacker/Resource/Resource.h b/Generals/Code/Tools/ImagePacker/Resource/Resource.h deleted file mode 100644 index 33a759f88b..0000000000 --- a/Generals/Code/Tools/ImagePacker/Resource/Resource.h +++ /dev/null @@ -1,55 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by ImagePacker.rc -// -#define IDD_DIALOG1 101 -#define IMAGE_PACKER_DIALOG 101 -#define IMAGE_ERRORS 102 -#define PAGE_ERRORS 103 -#define DIRECTORY_SELECT_DIALOG 104 -#define BUTTON_START 1000 -#define BUTTON_EXIT 1001 -#define LIST_FOLDERS 1002 -#define RADIO_128X128 1003 -#define RADIO_256X256 1004 -#define RADIO_512X512 1005 -#define RADIO_TARGET_OTHER 1006 -#define EDIT_WIDTH 1007 -#define EDIT_HEIGHT 1008 -#define BUTTON_ADD_FOLDER 1009 -#define BUTTON_REMOVE_FOLDER 1010 -#define EDIT_FILENAME 1011 -#define CHECK_USE_SUB_FOLDERS 1012 -#define STATIC_X 1013 -#define STATIC_STATUS 1014 -#define BUTTON_PREVIEW 1016 -#define BUTTON_PREVIOUS 1017 -#define BUTTON_NEXT 1018 -#define LIST_IMAGES 1018 -#define EDIT_GUTTER 1019 -#define CHECK_ALPHA 1020 -#define CHECK_BITMAP_PREVIEW 1021 -#define CHECK_GDF 1022 -#define CHECK_INI 1022 -#define BUTTON_PROCEED 1023 -#define BUTTON_CANCEL 1024 -#define LIST_PAGES 1025 -#define BUTTON_ADD 1027 -#define LIST_DIR 1028 -#define STATIC_CURRENT_DIR 1031 -#define COMBO_DRIVE 1032 -#define CHECK_COMPRESS 1033 -#define CHECK_GAP_EXTEND_RGB 1037 -#define CHECK_GAP_GUTTER 1038 -#define STATIC_GAP_INFO 1039 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 105 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1040 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/ImagePacker/Source/ImageInfo.cpp b/Generals/Code/Tools/ImagePacker/Source/ImageInfo.cpp deleted file mode 100644 index 8d418e32b1..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/ImageInfo.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImageInfo.cpp //////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImageInfo.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Image information struct for images to pack into -// the texture pages -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "ImageInfo.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// ImageInfo::ImageInfo ======================================================= -/** */ -//============================================================================= -ImageInfo::ImageInfo( void ) -{ - - m_area = 0; - m_colorDepth = 0; - m_size.x = 0; - m_size.y = 0; - m_path = NULL; - m_filenameOnly = NULL; - m_filenameOnlyNoExt = NULL; - m_status = UNPACKED; - - m_page = NULL; - m_nextPageImage = NULL; - m_prevPageImage = NULL; - m_pagePos.lo.x = 0; - m_pagePos.lo.y = 0; - m_pagePos.hi.x = 0; - m_pagePos.hi.y = 0; - m_fitBits = 0; - m_gutterUsed.x = 0; - m_gutterUsed.y = 0; - -} // end ImageInfo - -// ImageInfo::~ImageInfo ====================================================== -/** */ -//============================================================================= -ImageInfo::~ImageInfo( void ) -{ - - // delete path name - if( m_path ) - delete [] m_path; - - if( m_filenameOnly ) - delete [] m_filenameOnly; - - if( m_filenameOnlyNoExt ) - delete [] m_filenameOnlyNoExt; - -} // end ~ImageInfo diff --git a/Generals/Code/Tools/ImagePacker/Source/ImagePacker.cpp b/Generals/Code/Tools/ImagePacker/Source/ImagePacker.cpp deleted file mode 100644 index 56b4d0cbad..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/ImagePacker.cpp +++ /dev/null @@ -1,1249 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImagePacker.cpp ////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImagePacker.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Entry point for the image packer. This program takes -// separate image files and combines them into a single -// image as close as possible so that we can conserve texture -// memory -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "Common/Debug.h" -#include "WWLib/TARGA.H" -#include "Resource.h" -#include "ImagePacker.h" -#include "WinMain.h" -#include "WindowProc.h" - -// DEFINES //////////////////////////////////////////////////////////////////// -const char *gAppPrefix = "ip_"; // So IP can have a different debug log file name if we need it. - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE DATA /////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -ImagePacker *TheImagePacker = NULL; - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// ImagePacker::createNewTexturePage ========================================== -/** Create a new texture page and add to the list */ -//============================================================================= -TexturePage *ImagePacker::createNewTexturePage( void ) -{ - TexturePage *page; - - // allocate new page - page = new TexturePage( getTargetWidth(), getTargetHeight() ); - if( page == NULL ) - { - - DEBUG_ASSERTCRASH( page, ("Unable to allocate new texture page.\n") ); - return NULL; - - } // end if - - // link page to list - page->m_prev = NULL; - page->m_next = m_pageList; - if( m_pageList ) - m_pageList->m_prev = page; - m_pageList = page; - - // add the tail pointer if this is the first page - if( m_pageTail == NULL ) - m_pageTail = page; - - // we got a new page now - m_pageCount++; - - // set page id as the current page count - page->setID( m_pageCount ); - - return page; - -} // end createNewTexturePage - -// ImagePacker::validateImages ================================================ -/** Check all the images in the image list, if any of them cannot be - * processed we will flag them as so. If we have some images that can't - * be processed, we will warn the user of these images and ask them - * whether or not to proceed. - * - * Returns TRUE to proceed - * Returns FALSE to cancel build - */ -//============================================================================= -Bool ImagePacker::validateImages( void ) -{ - UnsignedInt i; - ImageInfo *image; - Bool errors = FALSE; - Bool proceed = TRUE; - - // loop through all images - for( i = 0; i < m_imageCount; i++ ) - { - - // get this image - image = m_imageList[ i ]; - - // sanity - if( image == NULL ) - { - - DEBUG_ASSERTCRASH( image, ("Image in imagelist is NULL") ); - continue; // should never happen - - } // end if - - // - // if this image is too big to fit in the target page size as a whole - // then there is nothing we can do about it - // - if( image->m_size.x > getTargetWidth() || - image->m_size.y > getTargetHeight() ) - { - - errors = TRUE; - BitSet( image->m_status, ImageInfo::TOOBIG ); - BitSet( image->m_status, ImageInfo::CANTPROCESS ); - - } // end if - - // - // if this image is not the right format we can't process it, at - // present we only understand 32 and 24 bit images - // - if( image->m_colorDepth != 32 && image->m_colorDepth != 24 ) - { - - errors = TRUE; - BitSet( image->m_status, ImageInfo::INVALIDCOLORDEPTH ); - BitSet( image->m_status, ImageInfo::CANTPROCESS ); - - } // end if - - } // end for i - - // - // if we have errors, build a list and show them to the user - // - if( errors == TRUE ) - { - - proceed = DialogBox( ApplicationHInstance, - (LPCTSTR)IMAGE_ERRORS, - TheImagePacker->getWindowHandle(), - (DLGPROC)ImageErrorProc ); - - } // end if - - return proceed; - -} // end validateImages - -// ImagePacker::packImages ==================================================== -/** Pack all the images in the image list, starting from the top and - * working from there */ -//============================================================================= -Bool ImagePacker::packImages( void ) -{ - UnsignedInt i; - TexturePage *page = NULL; - ImageInfo *image = NULL; - - // - // first sanity check all images loaded, if there are images that cannot - // be processed the user will be given a list of these and asked wether - // or not to proceed - // - Bool proceed; - proceed = validateImages(); - if( proceed == FALSE ) - { - - statusMessage( "Build Cancelled By User." ); - return FALSE; - - } // end if - - // loop through all images - for( i = 0; i < m_imageCount; i++ ) - { - - // update status - sprintf( m_statusBuffer, "Fitting Image %d of %d.", i, m_imageCount ); - statusMessage( m_statusBuffer ); - - // get this image out of the list - image = m_imageList[ i ]; - - // ignore images that we cannot process - if( BitIsSet( image->m_status, ImageInfo::CANTPROCESS) ) - continue; - - // try to put image on each page - for( page = m_pageTail; page; page = page->m_prev ) - { - - if( page->addImage( image ) == TRUE ) - break; // page added, stop trying to add into pages - - } // end for page - - // if image was not able to go on any existing page create a new page for it - if( page == NULL ) - { - - page = createNewTexturePage(); - if( page == NULL ) - return FALSE; - - // try to add the image to this page - if( page->addImage( image ) == FALSE ) - { - char buffer[ _MAX_PATH ]; - - sprintf( buffer, "Unable to add image '%s' to a brand new page!\n", image->m_path ); - DEBUG_ASSERTCRASH( 0, (buffer) ); - MessageBox( NULL, buffer, "Internal Error", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - } // end if - - } // end for i - - return TRUE; // success - -} // end packImages - -// ImagePacker::writeFinalTextures ============================================ -/** Generate and write the final textures to the output directory - * of the packed images along with a definition file for which images - * are where on the page */ -//============================================================================= -void ImagePacker::writeFinalTextures( void ) -{ - TexturePage *page; - Bool errors = FALSE; - char buffer[ 128 ]; - - // - // go through each page, let's start from the end of the list since - // that's where we packed first, but it doesn't matter - // - for( page = m_pageTail; page; page = page->m_prev ) - { - - // update status message - sprintf( buffer, "Generating texture #%d of %d.", - page->getID(), m_pageCount ); - statusMessage( buffer ); - - // generate the final texture for this page - if( page->generateTexture() == FALSE ) - { - - errors = TRUE; - continue; // could not generate this page, but try to continue - - } // end if - - // - // write this page out to a file using the filename given by - // the user and the texture page ID to keep it unique - // - if( page->writeFile( m_outputFile ) == FALSE ) - { - - errors = TRUE; - continue; // could not write page, but try to go on - - } // end if - - } // end for page - - // check for any errors and notify the user - if( errors == TRUE ) - { - - DialogBox( ApplicationHInstance, - (LPCTSTR)PAGE_ERRORS, - TheImagePacker->getWindowHandle(), - (DLGPROC)PageErrorProc ); - - } // end if - -} // end writeFinalTextures - -// sortImageCompare =========================================================== -/** Compare function for qsort - * -1 item1 less than item2 - * 0 item1 identical to item2 - * 1 item1 greater than item2 - */ -//============================================================================= -static Int sortImageCompare( const void *aa, const void *bb ) -{ - const ImageInfo **a = (const ImageInfo **)aa; - const ImageInfo **b = (const ImageInfo **)bb; - - if( (*a)->m_area < (*b)->m_area ) - return 1; - else if( (*a)->m_area > (*b)->m_area ) - return -1; - else - return 0; - -} // end sortImageCompare - -// ImagePacker::sortImageList ================================================= -/** Sort the image list */ -//============================================================================= -void ImagePacker::sortImageList( void ) -{ - - // sort all images so that largest area ones are first - qsort( (void *)m_imageList, m_imageCount, sizeof( ImageInfo *), sortImageCompare ); - -} // end sortImageList - -// ImagePacker::addImagesInDirectory ========================================== -/** Add all the images in the specified directory */ -//============================================================================= -void ImagePacker::addImagesInDirectory( char *dir ) -{ - - // sanity - if( dir == NULL ) - return; - - char currDir[ _MAX_PATH ]; - char filePath[ _MAX_PATH ]; - WIN32_FIND_DATA item; // search item - HANDLE hFile; // handle for search resources - Int len; - - // save the current directory - GetCurrentDirectory( _MAX_PATH, currDir ); - - // change into the directory - SetCurrentDirectory( dir ); - - // go through each item in the output directory - hFile = FindFirstFile( "*", &item); - if( hFile != INVALID_HANDLE_VALUE ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - { - - len = strlen( item.cFileName ); - if( len > 4 && - item.cFileName[ len - 4 ] == '.' && - (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') && - (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') && - (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') ) - { - - sprintf( filePath, "%s%s", dir, item.cFileName ); - addImage( filePath ); - - } // end if - - } // end if - - // find the rest of the files - while( FindNextFile( hFile, &item ) != 0 ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - { - - len = strlen( item.cFileName ); - if( len > 4 && - item.cFileName[ len - 4 ] == '.' && - (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') && - (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') && - (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') ) - { - - sprintf( filePath, "%s%s", dir, item.cFileName ); - addImage( filePath ); - - } // end if - - } // end if - - } // end while - - // close search - FindClose( hFile ); - - } //end if, items found - - // restore our current directory - SetCurrentDirectory( currDir ); - -} // end addImagesInDirectory - -// ImagePacker::checkOutputDirectory ========================================== -/** Verify that there are no files in the output directory ... if there - * are give the user the option to delete them, cancel the operation, - * or proceed with possibly overwriting any files there - * - * Returns TRUE to proceed with the process, FALSE if the user wants - * to cancel the process - */ -//============================================================================= -Bool ImagePacker::checkOutputDirectory( void ) -{ - WIN32_FIND_DATA item; // search item - HANDLE hFile; // handle for search resources - Int fileCount = 0; - char currDir[ _MAX_PATH ]; - - // get the working directory - GetCurrentDirectory( _MAX_PATH, currDir ); - - // create the output directory if it does not exist - CreateDirectory( m_outputDirectory, NULL ); - - // change into the output directory - SetCurrentDirectory( m_outputDirectory ); - - // go through each item in the output directory - hFile = FindFirstFile( "*", &item); - if( hFile != INVALID_HANDLE_VALUE ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - fileCount++; - - // find the rest of the files - while( FindNextFile( hFile, &item ) != 0 ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - fileCount++; - - } // end while - - // close search - FindClose( hFile ); - - } //end if, items found - - // switch back to the current directory - SetCurrentDirectory( currDir ); - - if( fileCount != 0 ) - { - char buffer[ 256 ]; - Int response; - - sprintf( buffer, "The output directory (%s) must be empty before proceeding. Delete '%d' files and continue with build process?", - m_outputDirectory, fileCount ); - response = MessageBox( NULL, buffer, - "Delete files to continue?", - MB_YESNO | MB_ICONWARNING ); - - // if they said no, do not delete the files and abort the pack process - if( response == IDNO ) - return FALSE; - - // - // they said yes, delete all the files in the output directory - // - - // change into the output directory - SetCurrentDirectory( m_outputDirectory ); - - // go through each item in the output directory - hFile = FindFirstFile( "*", &item); - if( hFile != INVALID_HANDLE_VALUE ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - DeleteFile( item.cFileName ); - - // find the rest of the files - while( FindNextFile( hFile, &item ) != 0 ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - DeleteFile( item.cFileName ); - - } // end while - - // close search - FindClose( hFile ); - - } //end if, items found - - // switch back to the current directory - SetCurrentDirectory( currDir ); - - } // end if - - return TRUE; // proceed - -} // end checkOutputDirectory - -// ImagePacker::resetPageList ================================================= -/** Clear the page list */ -//============================================================================= -void ImagePacker::resetPageList( void ) -{ - TexturePage *next; - - while( m_pageList ) - { - - next = m_pageList->m_next; - delete m_pageList; - m_pageList = next; - - } // end while - - m_pageTail = NULL; - m_pageCount = 0; - m_targetPreviewPage = 1; - -} // end resetPageList - -// ImagePacker::resetImageDirectoryList ======================================= -/** Clear the image directory list */ -//============================================================================= -void ImagePacker::resetImageDirectoryList( void ) -{ - ImageDirectory *next; - - while( m_dirList ) - { - - next = m_dirList->m_next; - delete m_dirList; - m_dirList = next; - - } // end while - - m_dirCount = 0; - m_imagesInDirs = 0; - -} // end resetImageDirectoryList - -// ImagePacker::resetImageList ================================================ -/** Clear the image list */ -//============================================================================= -void ImagePacker::resetImageList( void ) -{ - - if( m_imageList ) - delete [] m_imageList; - m_imageList = NULL; - m_imageCount = 0; - -} // end resetImageList - -// ImagePacker::addDirectory ================================================== -/** Add the directory to the directory list, do not add it if it is already - * in the directory list. We want to have that sanity check so that - * we can be assured that each image being added to the image list from - * each directory will be unique and we therefore don't have to do - * any further checking for duplicates */ -//============================================================================= -void ImagePacker::addDirectory( char *path, Bool subDirs ) -{ - char currDir[ _MAX_PATH ]; - WIN32_FIND_DATA item; // search item - HANDLE hFile; // handle for search resources - - // santiy - if( path == NULL ) - return; - - // check to see if path is already in list - ImageDirectory *dir; - for( dir = m_dirList; dir; dir = dir->m_next ) - if( stricmp( dir->m_path, path ) == 0 ) - return; // already in list - - // save our current directory - GetCurrentDirectory( _MAX_PATH, currDir ); - - // set our directory to this one - if( SetCurrentDirectory( path ) == 0 ) - return; // directory does not exist - - // image is not in list, make a new entry and link to the list - dir = new ImageDirectory; - if( dir == NULL ) - { - - MessageBox( NULL, "Unable to allocate image directory", "Error", - MB_OK | MB_ICONERROR ); - return; - - } // end if - - // allocate space for the path - Int len = strlen( path ); - dir->m_path = new char[ len + 1 ]; - strcpy( dir->m_path, path ); - if( dir->m_path == NULL ) - { - - MessageBox( NULL, "Unable to allocate path for directory", "Error", - MB_OK | MB_ICONERROR ); - delete dir; - return; - - } // end if - - // tie to list - dir->m_prev = NULL; - dir->m_next = m_dirList; - if( m_dirList ) - m_dirList->m_prev = dir; - m_dirList = dir; - - // increase our directory count - m_dirCount++; - - // update status - sprintf( m_statusBuffer, "Folder Added: %d.", m_dirCount ); - statusMessage( m_statusBuffer ); - - // count how many image files are in this directory - hFile = FindFirstFile( "*", &item); - if( hFile != INVALID_HANDLE_VALUE ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - { - - len = strlen( item.cFileName ); - if( len > 4 && - item.cFileName[ len - 4 ] == '.' && - (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') && - (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') && - (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') ) - dir->m_imageCount++; - - } // end if - - // find the rest of the files - while( FindNextFile( hFile, &item ) != 0 ) - { - - // if this is a file count it - if( !(item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - { - - len = strlen( item.cFileName ); - if( len > 4 && - item.cFileName[ len - 4 ] == '.' && - (item.cFileName[ len - 3 ] == 't' || item.cFileName[ len - 3 ] == 'T') && - (item.cFileName[ len - 2 ] == 'g' || item.cFileName[ len - 2 ] == 'G') && - (item.cFileName[ len - 1 ] == 'a' || item.cFileName[ len - 1 ] == 'A') ) - dir->m_imageCount++; - - } // end if - - } // end while - - // close search - FindClose( hFile ); - - } //end if, items found - - // add the image count of this directory to the total image count - m_imagesInDirs += dir->m_imageCount; - - // if we are adding subdirectories add them all - if( subDirs ) - { - char subDir[ _MAX_PATH ]; - - // go through each item in the output directory - hFile = FindFirstFile( "*", &item); - if( hFile != INVALID_HANDLE_VALUE ) - { - - // if this is a file count it - if( (item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - { - - sprintf( subDir, "%s%s\\", path, item.cFileName ); - addDirectory( subDir, subDirs ); - - } // end if - - // find the rest of the files - while( FindNextFile( hFile, &item ) != 0 ) - { - - // if this is a file count it - if( (item.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - strcmp( item.cFileName, "." ) && - strcmp( item.cFileName, ".." ) ) - { - - sprintf( subDir, "%s%s\\", path, item.cFileName ); - addDirectory( subDir, subDirs ); - - } // end if - - } // end while - - // close search - FindClose( hFile ); - - } //end if, items found - - } // end if - - // restore our current directory - SetCurrentDirectory( currDir ); - -} // end addDirectory - -// ImagePacker::addImage ====================================================== -/** Add the image to the image list */ -//============================================================================= -void ImagePacker::addImage( char *path ) -{ - - // sanity - if( path == NULL ) - return; - - // allocate a new entry - ImageInfo *info = new ImageInfo; - if( info == NULL ) - { - - MessageBox( NULL, "Unable to allocate image info", "Error", - MB_OK | MB_ICONERROR ); - return; - - } // end if - - // allocate space for the path - Int len = strlen( path ); - info->m_path = new char[ len + 1 ]; - strcpy( info->m_path, path ); - if( info->m_path == NULL ) - { - - MessageBox( NULL, "Unable to allcoate image path info", "Error", - MB_OK | MB_ICONERROR ); - delete info; - return; - - } // end if - - // load just the header information from the targa - m_targa->Load( info->m_path, 0, TRUE ); - - // get the data we need out of the targa header - info->m_colorDepth = m_targa->Header.PixelDepth; - info->m_size.x = m_targa->Header.Width; - info->m_size.y = m_targa->Header.Height; - info->m_area = info->m_size.x * info->m_size.y; - - // save the filename only without path - Int i; - char *c; - for( i = len - 1; i >= 0; i-- ) - { - - if( path[ i ] == '\\' ) - { - c = &path[ i + 1 ]; - break; - } - - } // end for i - - Int nameLen = strlen( c ); - info->m_filenameOnly = new char[ nameLen + 1 ]; - strcpy( info->m_filenameOnly, c ); - - info->m_filenameOnlyNoExt = new char[ nameLen - 4 + 1 ]; - strncpy( info->m_filenameOnlyNoExt, c, nameLen - 4 ); - info->m_filenameOnlyNoExt[ nameLen - 4 ] = '\0'; - - // assign to array - m_imageList[ m_imageCount++ ] = info; - - // update status - sprintf( m_statusBuffer, "Loading Image %d of %d.", - m_imageCount, m_imagesInDirs ); - statusMessage( m_statusBuffer ); - -} // end addImage - -// ImagePacker::generateINIFile =============================================== -/** Generate the INI image file definition for the final packed images */ -//============================================================================= -Bool ImagePacker::generateINIFile( void ) -{ - FILE *fp; - char filename[ _MAX_PATH ]; - - // construct filename we'll use - sprintf( filename, "%s%s.INI", m_outputDirectory, m_outputFile ); - - // open the file - fp = fopen( filename, "w" ); - if( fp == NULL ) - { - char buffer[ _MAX_PATH + 64 ]; - - sprintf( buffer, "Cannot open INI file '%s' for writing.", filename ); - MessageBox( NULL, buffer, "Error Opening File", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - // print header for file - fprintf( fp, "; ------------------------------------------------------------\n" ); - fprintf( fp, "; Do NOT edit by hand, ImagePacker.exe auto generated INI file\n" ); - fprintf( fp, "; ------------------------------------------------------------\n\n" ); - - // - // loop through all the pages so that we write image definitions that - // are on the same page close together in the file, note we're - // going backwards through the page list because page 1 is at the - // tail and I want them to print out in number order, but it - // doesn't really matter - // - TexturePage *page; - ImageInfo *image; - for( page = m_pageTail; page; page = page->m_prev ) - { - - // ignore texture pages that generated errors - if( BitIsSet( page->m_status, TexturePage::PAGE_ERROR ) ) - continue; - - // go through each image on this page - for( image = page->getFirstImage(); - image; - image = image->m_nextPageImage ) - { - - // - // write the item definition, note when we output the texture coords - // we add on to the right and bottom to include that pixel in the - // texture calculations ... need to do this since we are using a zero - // based region for the "filled regions" in the image packer - // - fprintf( fp, "MappedImage %s\n", image->m_filenameOnlyNoExt ); - fprintf( fp, " Texture = %s_%03d.tga\n", m_outputFile, page->getID() ); - fprintf( fp, " TextureWidth = %d\n", page->getWidth() ); - fprintf( fp, " TextureHeight = %d\n", page->getHeight() ); - fprintf( fp, " Coords = Left:%d Top:%d Right:%d Bottom:%d\n", - image->m_pagePos.lo.x, image->m_pagePos.lo.y, - image->m_pagePos.hi.x + 1, image->m_pagePos.hi.y + 1 ); - fprintf( fp, " Status = %s\n", - BitIsSet( image->m_status, ImageInfo::ROTATED90C ) ? - "ROTATED_90_CLOCKWISE" : "NONE" ); - fprintf( fp, "End\n\n" ); - - } // end for image - - } // end for page - - // close the file - fclose( fp ); - - return TRUE; // success - -} // end generateINIFile - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// ImagePacker::getSettingsFromDialog ========================================= -/** Given the current state of the option dialog passed in, get all the - * settings we need for the image packer from the GUI and validate them */ -//============================================================================= -Bool ImagePacker::getSettingsFromDialog( HWND dialog ) -{ - Int i; - - // sanity - if( dialog == NULL ) - return FALSE; - - // if we are using a user target image size, it must be a power of 2 - if( IsDlgButtonChecked( dialog, RADIO_TARGET_OTHER ) ) - { - UnsignedInt size, val; - Int bitCount = 0; - - size = GetDlgItemInt( dialog, EDIT_WIDTH, NULL, FALSE ); - for( val = size; val; val >>= 1 ) - if( BitIsSet( val, 0x1 ) ) - bitCount++; - - // - // if bit count was not 1, this is not a power of 2 ... it also - // guards us from entering a size of zero :) - // - if( bitCount != 1 ) - { - - MessageBox( NULL, "The target image size must be a power of 2.", - "Must Be Power Of 2", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - // set the size for the image packer - setTargetSize( size, size ); - - } // end if - else if( IsDlgButtonChecked( dialog, RADIO_128X128 ) ) - setTargetSize( 128, 128 ); - else if( IsDlgButtonChecked( dialog, RADIO_256X256 ) ) - setTargetSize( 256, 256 ); - else if( IsDlgButtonChecked( dialog, RADIO_512X512 ) ) - setTargetSize( 512, 512 ); - else - { - - MessageBox( NULL, "Internal Error. Target Size Unknown.", - "Error", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end else - - // get alpha option - Bool outputAlpha = FALSE; - if( IsDlgButtonChecked( dialog, CHECK_ALPHA ) == BST_CHECKED ) - outputAlpha = TRUE; - TheImagePacker->setOutputAlpha( outputAlpha ); - - // get create INI option - Bool createINI = FALSE; - if( IsDlgButtonChecked( dialog, CHECK_INI ) == BST_CHECKED ) - createINI = TRUE; - TheImagePacker->setINICreate( createINI ); - - // get preview with image option - Bool useBitmap = FALSE; - if( IsDlgButtonChecked( dialog, CHECK_BITMAP_PREVIEW ) == BST_CHECKED ) - useBitmap = TRUE; - TheImagePacker->setUseTexturePreview( useBitmap ); - - // get option to compress final textures - Bool compress = FALSE; - if( IsDlgButtonChecked( dialog, CHECK_COMPRESS ) == BST_CHECKED ) - compress = TRUE; - TheImagePacker->setCompressTextures( compress ); - - // get options for the gap options - TheImagePacker->clearGapMethod( ImagePacker::GAP_METHOD_EXTEND_RGB ); - if( IsDlgButtonChecked( dialog, CHECK_GAP_EXTEND_RGB ) == BST_CHECKED ) - TheImagePacker->setGapMethod( ImagePacker::GAP_METHOD_EXTEND_RGB ); - TheImagePacker->clearGapMethod( ImagePacker::GAP_METHOD_GUTTER ); - if( IsDlgButtonChecked( dialog, CHECK_GAP_GUTTER ) == BST_CHECKED ) - TheImagePacker->setGapMethod( ImagePacker::GAP_METHOD_GUTTER ); - - // get gutter size whether we are using that option or not - Int gutter = GetDlgItemInt( dialog, EDIT_GUTTER, NULL, FALSE ); - if( gutter < 0 ) - gutter = 0; - setGutter( gutter ); - - // save the filename to output - GetDlgItemText( dialog, EDIT_FILENAME, m_outputFile, MAX_OUTPUT_FILE_LEN - 1 ); - - // check for illegal characters in the output name - Int len = strlen( m_outputFile ); - for( i = 0; i < len; i++ ) - { - const char *illegal = "/\\:*?<>|"; - Int illegalLen = strlen( illegal ); - - for( Int j = 0; j < illegalLen; j++ ) - { - - if( m_outputFile[ i ] == illegal[ j ] ) - { - char buffer[ 256 ]; - - sprintf( buffer, "Output filename '%s' contains one or more of the following illegal characters:\n\n%s", - m_outputFile, illegal ); - MessageBox( NULL, buffer, "Illegal Filename", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - } // end for j - - } // end for i - - // get the work on sub-folders option - m_useSubFolders = IsDlgButtonChecked( dialog, CHECK_USE_SUB_FOLDERS ); - - // clear our list of image directories - resetImageDirectoryList(); - - // set a status message - statusMessage( "Gathering Directory Information, Please Wait ..." ); - - // add all the image directories specified in the folder listbox - Int count = SendDlgItemMessage( dialog, LIST_FOLDERS, LB_GETCOUNT, 0, 0 ); - char buffer[ _MAX_PATH ]; - for( i = 0; i < count; i++ ) - { - - // get text from the listbox - SendDlgItemMessage( dialog, LIST_FOLDERS, - LB_GETTEXT, i, (LPARAM)buffer ); - - // add the directory - addDirectory( buffer, m_useSubFolders ); - - } // end for i - - // all done - return TRUE; - -} // end getSettingsFromDialog - -// ImagePacker::ImagePacker =================================================== -/** */ -//============================================================================= -ImagePacker::ImagePacker( void ) -{ - - m_hWnd = NULL; - m_targetSize.x = DEFAULT_TARGET_SIZE; - m_targetSize.y = DEFAULT_TARGET_SIZE; - m_useSubFolders = TRUE; - strcpy( m_outputFile, "" ); - strcpy( m_outputDirectory, "" ); - m_dirList = NULL; - m_dirCount = 0; - m_imagesInDirs = 0; - m_imageList = NULL; - m_imageCount = 0; - strcpy( m_statusBuffer, "" ); - m_pageList = NULL; - m_pageTail = NULL; - m_pageCount = 0; - m_gapMethod = GAP_METHOD_EXTEND_RGB; - m_gutterSize = 1; - m_outputAlpha = TRUE; - m_createINI = TRUE; - - m_targetPreviewPage = 1; - m_hWndPreview = NULL; - m_showTextureInPreview = FALSE; - - m_targa = NULL; - m_compressTextures = FALSE; - -} // end ImagePacker - -// ImagePacker::~ImagePacker ================================================== -/** */ -//============================================================================= -ImagePacker::~ImagePacker( void ) -{ - - // delete our lists - resetImageDirectoryList(); - resetImageList(); - resetPageList(); - - // delete our targa header loader - if( m_targa ) - delete m_targa; - -} // end ~ImagePacker - -// ImagePacker::init ========================================================== -/** Initialize the image packer system */ -//============================================================================= -Bool ImagePacker::init( void ) -{ - - // allocate a targa to read the headers for the images - m_targa = new Targa; - if( m_targa == NULL ) - { - - DEBUG_ASSERTCRASH( m_targa, ("Unable to allocate targa header during init\n") ); - MessageBox( NULL, "ImagePacker can't init, unable to create targa", - "Internal Error", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - return TRUE; - -} // end init - -// ImagePacker::statusMessage ================================================= -/** Status message for the program */ -//============================================================================= -void ImagePacker::statusMessage( const char *message ) -{ - - SetDlgItemText( getWindowHandle(), STATIC_STATUS, message ); - -} // end statusMessage - -// ImagePacker::process ======================================================= -/** Run the packing process */ -//============================================================================= -Bool ImagePacker::process( void ) -{ - - // build the output directory based on the base name of the output images - char currDir[ _MAX_PATH ]; - GetCurrentDirectory( _MAX_PATH, currDir ); - sprintf( m_outputDirectory, "%s\\ImagePackerOutput\\", currDir ); - CreateDirectory( m_outputDirectory, NULL ); - - // subdir of output directory based on output image name - strcat( m_outputDirectory, m_outputFile ); - strcat( m_outputDirectory, "\\" ); - - // - // check for existing images in the output directory ... if we have - // some then ask the user if they want to delete them or proceed with - // a possible overwrite - // - if( checkOutputDirectory() == FALSE ) - { - - statusMessage( "Build Process Cancelled." ); - return FALSE; - - } // end if - - // reset the contents of our image list and existing textures - resetImageList(); - resetPageList(); - - // set a status message - statusMessage( "Gathering Image Information, Please Wait ..." ); - - // allocate an array to hold all the images - m_imageList = new ImageInfo *[ m_imagesInDirs ]; - - // load our image list with all the art files from the specified directories - ImageDirectory *dir; - for( dir = m_dirList; dir; dir = dir->m_next ) - addImagesInDirectory( dir->m_path ); - - // sort the images with the largest biggest images at the top of the list - sortImageList(); - - // pack all images - if( packImages() ) - { - - // generate the actual final textures and write them out to the file - writeFinalTextures(); - - // generate the INI definition file if requested - if( createINIFile() == TRUE ) - generateINIFile(); - - // update preview window - UpdatePreviewWindow(); - - // all done - sprintf( m_statusBuffer, "Image Packing Complete: '%d' Texture Pages Generated from '%d' Images in '%d' Folder(s)", - m_pageCount, m_imageCount, m_dirCount ); - statusMessage( m_statusBuffer ); - - } // end if - - return TRUE; - -} // end process - diff --git a/Generals/Code/Tools/ImagePacker/Source/TexturePage.cpp b/Generals/Code/Tools/ImagePacker/Source/TexturePage.cpp deleted file mode 100644 index d73090fa37..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/TexturePage.cpp +++ /dev/null @@ -1,1352 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: TexturePage.cpp ////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: TexturePage.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: This class represents a texture that contains packed -// images. -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "Common/Debug.h" -#include "TexturePage.h" -#include "ImagePacker.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// TexturePage::extendToRowIfOpen ============================================= -/** If the pixel at location 'row' is "open", then extend the pixel - * at 'src' to that location - * - * NOTE this assumes 'src' and 'row' are pointers into the same - * buffer and the bits per pixel (buffBPP) are treated as the - * same for both */ -//============================================================================= -void TexturePage::extendToRowIfOpen( char *src, - Int buffWidth, - Int buffBPP, - Bool extendAlpha, - Int imageHeight, - UnsignedInt fitBits, - Int srcX, Int srcY ) -{ - char otherAlpha; - char otherColor[ 3 ]; - char *row = NULL; - - // sanity - if( src == NULL ) - return; - - // - // try to extend pixel up and down a row as well, we try to extend - // up if we're in the top half of the image down if we're - // in the bottom half of the image. Note we're not - // allowed to extend outside the image region if we don't have - // a border to extend into - // - if( srcY < imageHeight / 2 && - (srcY != 0 || BitIsSet( fitBits, ImageInfo::FIT_YBORDER_TOP )) ) - { - - // try to extend pixel "up" if that pixel is "open" - row = src + (buffWidth * buffBPP); - - - } // end if - else if( srcY >= imageHeight / 2 && - (srcY != imageHeight - 1 || - BitIsSet( fitBits, ImageInfo::FIT_YBORDER_BOTTOM )) ) - { - - // try to extend pixel "down" if that pixel is "open" - row = src - (buffWidth * buffBPP); - - } // end else - - // - // if a 'row' is available, try to extend the current pixel - // into that location if it's open - // - if( row ) - { - - // read the pixel at 'row' - if( buffBPP == 4 ) - { - - otherAlpha = row[ 0 ]; - otherColor[ 0 ] = row[ 1 ]; - otherColor[ 1 ] = row[ 2 ]; - otherColor[ 2 ] = row[ 3 ]; - - } // end if - else - { - - otherColor[ 0 ] = row[ 0 ]; - otherColor[ 1 ] = row[ 1 ]; - otherColor[ 2 ] = row[ 2 ]; - - } // end else - - // - // see if this pixel is "open", again we prefer to check the - // alpha channel if present, otherwise we say black is "open" - // - Bool otherOpen = FALSE; - if( buffBPP == 4 ) - { - - if( otherAlpha == 0 ) - otherOpen = TRUE; - - } // end if - else - { - - if( otherColor[ 0 ] == 0 && - otherColor[ 1 ] == 0 && - otherColor[ 2 ] == 0 ) - otherOpen = TRUE; - - } // end else - - // copy pixel data from 'src' to 'row' if 'row' is "open" - if( otherOpen == TRUE ) - { - char alpha; - char color[ 3 ]; - - // read the pixel data at 'src' - if( buffBPP == 4 ) - { - - alpha = src[ 0 ]; - color[ 0 ] = src[ 1 ]; - color[ 1 ] = src[ 2 ]; - color[ 2 ] = src[ 3 ]; - - } // end if - else - { - - color[ 0 ] = src[ 0 ]; - color[ 1 ] = src[ 1 ]; - color[ 2 ] = src[ 2 ]; - - } // end else - - // copy the pixel to 'row' - if( buffBPP == 4 ) - { - - if( extendAlpha ) - row[ 0 ] = alpha; - row[ 1 ] = color[ 0 ]; - row[ 2 ] = color[ 1 ]; - row[ 3 ] = color[ 2 ]; - - } // end if - else - { - - row[ 0 ] = color[ 0 ]; - row[ 1 ] = color[ 1 ]; - row[ 2 ] = color[ 2 ]; - - } // end else - - } // end if, other spot is open, copy it - - } // end if, row - -} // end extendToRowIfOpen - -// TexturePage::extendImageEdges ============================================== -/** We want to extend the image data in destBuffer at the location region - * of image->m_pagePos in "outward" directions, effectively bleeding - * the edges outward. - * - * Note we will not extend outward from the image region UNLESS we - * have a border present on that side (described in the image->m_fitBits - * for the region image->m_pagePos). - */ -//============================================================================= -void TexturePage::extendImageEdges( Byte *destBuffer, - Int destWidth, - Int destHeight, - Int destBPP, - ImageInfo *image, - Bool extendAlpha ) -{ - - // sanity - if( destBuffer == NULL || image == NULL ) - return; - - // - // get the extents that we will loop through on the destination surface, - // those extents are the size of the image, but we have to take into - // account whether or not the destination image was rotated or not - // - Int imageWidth, imageHeight; - if( BitIsSet( image->m_status, ImageInfo::ROTATED90C ) ) - { - - imageWidth = image->m_size.y; - imageHeight = image->m_size.x; - - } // end if - else - { - - imageWidth = image->m_size.x; - imageHeight = image->m_size.y; - - } // end else - - Int x, y; - char *ptr; - char color[ 3 ]; - char alpha; - Bool prevPixel, currPixel; - for( y = 0; y < imageHeight; y++ ) - { - - // compute beginning of destination row - ptr = destBuffer + - ((destHeight - 1 - (image->m_pagePos.lo.y + y)) * destWidth * destBPP ) + - (image->m_pagePos.lo.x * destBPP); - - prevPixel = FALSE; - for( x = 0; x < imageWidth; x++ ) - { - - // read the pixel - if( destBPP == 4 ) - { - - alpha = ptr[ 0 ]; - color[ 0 ] = ptr[ 1 ]; - color[ 1 ] = ptr[ 2 ]; - color[ 2 ] = ptr[ 3 ]; - - } // end if - else - { - - color[ 0 ] = ptr[ 0 ]; - color[ 1 ] = ptr[ 1 ]; - color[ 2 ] = ptr[ 2 ]; - - } // end else - - // - // see wheter or not we have data at this pixel, if we have alpha - // we will use just the mask comparison, if not we will compare the - // colors with black (0,0,0) being an "empty" pixel - // - currPixel = FALSE; - if( destBPP == 4 ) - { - - if( alpha != 0 ) - currPixel = TRUE; - - } // end if - else - { - - if( color[ 0 ] != 0 && - color[ 1 ] != 0 && - color[ 2 ] != 0 ) - currPixel = TRUE; - - } // end else - - // - // if we're at the right edge we will extend this pixel off the - // image to the right border if present, we dont' have to worry about - // the top and bottom edges because they are attempted to be - // extended into when we detect an edge change moving across x - // - if( currPixel == TRUE && x == imageWidth - 1 && - BitIsSet( image->m_fitBits, ImageInfo::FIT_XBORDER_RIGHT ) ) - { - - // - // we are at the right side of the image, we have a pixel here, - // AND we have a border to extend that pixel into - // - if( destBPP == 4 ) - { - - if( extendAlpha ) - *(ptr + 4) = alpha; - *(ptr + 5) = color[ 0 ]; - *(ptr + 6) = color[ 1 ]; - *(ptr + 7) = color[ 2 ]; - - } // end if - else - { - - *(ptr + 3) = color[ 0 ]; - *(ptr + 4) = color[ 1 ]; - *(ptr + 5) = color[ 2 ]; - - } // end else - - } // end if - - // - // if we have a pixel here, attempt to extend it to the above - // or below row if that spot is empty - // - if( currPixel == TRUE ) - extendToRowIfOpen( ptr, destWidth, destBPP, extendAlpha, - imageHeight, image->m_fitBits, x, y ); - - // - // if we've crossed from empty<->filled either extend that pixel - // left or right - // - if( prevPixel == FALSE && currPixel == TRUE ) - { - - // - // we've crossed from empty to filled, copy the color of current - // pixel to the position of previous pixel. Note this is not allowed - // when we're at the left edge and we DON'T have a border to copy into - // - if( x != 0 || BitIsSet( image->m_fitBits, ImageInfo::FIT_XBORDER_LEFT ) ) - { - - // extend our current pixel to the previous location - if( destBPP == 4 && extendAlpha ) - *(ptr - 4) = alpha; - *(ptr - 3) = color[ 0 ]; - *(ptr - 2) = color[ 1 ]; - *(ptr - 1) = color[ 2 ]; - - } // end if - - } // end if - else if( prevPixel == TRUE && currPixel == FALSE ) - { - - // - // we've crossed from filled to empty, copy the color of previous - // pixel to the current pixel position. - // - - // - // this assert should never happen because if x were 0, we are on the - // first column in this image, and the prevPixel should be FALSE since - // previous would be "off" the image which is by definition "open" - // - DEBUG_ASSERTCRASH( x != 0, ("Coming from off image and detecting right edge!") ); - - // extend the previous pixel to this location - if( destBPP == 4 ) - { - - if( extendAlpha ) - ptr[ 0 ] = *(ptr - 4); - ptr[ 1 ] = *(ptr - 3); - ptr[ 2 ] = *(ptr - 2); - ptr[ 3 ] = *(ptr - 1); - - } // end if - else - { - - ptr[ 0 ] = *(ptr - 3); - ptr[ 1 ] = *(ptr - 2); - ptr[ 2 ] = *(ptr - 1); - - } // end else - - } // end else if - - // - // one more time now for a special case in the corners of the extended - // image. since this algorithm goes across extending pixels left, right - // up, and down we must check to see if we have a pixel when our - // source location is in the 4 corners of the image ... if so we will - // extend that pixel DIAGONALLY out to make a complete extended rectangle - // - if( currPixel == TRUE ) - { - char *dst = NULL; - - // top left corner - if( x == 0 && y == 0 && - BitIsSet( image->m_fitBits, ImageInfo::FIT_XBORDER_LEFT ) && - BitIsSet( image->m_fitBits, ImageInfo::FIT_YBORDER_TOP ) ) - dst = (ptr + (destWidth * destBPP)) - destBPP; - - // top right corner - else if( x == imageWidth - 1 && y == 0 && - BitIsSet( image->m_fitBits, ImageInfo::FIT_XBORDER_RIGHT ) && - BitIsSet( image->m_fitBits, ImageInfo::FIT_YBORDER_TOP ) ) - dst = (ptr + (destWidth * destBPP)) + destBPP; - - // bottom right corner - else if( x == imageWidth - 1 && y == imageHeight - 1 && - BitIsSet( image->m_fitBits, ImageInfo::FIT_XBORDER_RIGHT ) && - BitIsSet( image->m_fitBits, ImageInfo::FIT_YBORDER_BOTTOM ) ) - dst = (ptr - (destWidth * destBPP)) + destBPP; - - // bottom left corner - else if( x == 0 && y == imageHeight - 1 && - BitIsSet( image->m_fitBits, ImageInfo::FIT_XBORDER_LEFT ) && - BitIsSet( image->m_fitBits, ImageInfo::FIT_YBORDER_BOTTOM ) ) - dst = (ptr - (destWidth * destBPP)) - destBPP; - - // copy the pixel at 'ptr' to 'dst' for the diagonal extend - if( dst ) - { - - if( destBPP == 4 ) - { - - if( extendAlpha ) - dst[ 0 ] = alpha; - dst[ 1 ] = color[ 0 ]; - dst[ 2 ] = color[ 1 ]; - dst[ 3 ] = color[ 2 ]; - - } // end if - else - { - - dst[ 0 ] = color[ 0 ]; - dst[ 1 ] = color[ 1 ]; - dst[ 2 ] = color[ 2 ]; - - } // end else - - } // end if dst - - } // end if - - // move to the next pixel - ptr += destBPP; - - // - // the state of our current pixel (on/off) becomes the state of the - // previous pixel now - // - prevPixel = currPixel; - - } // end for x - - } // end for y - -} // end extendImageEdges - -// TexturePage::addImageData ================================================== -/** Add the actual image data from 'image' to the destination buffer - * at the coordinates specified in the 'image' ... this puts the - * actual packed image data on the final texture page - * - * NOTE that we have created our texture page regions with the - * assumption that we were packing images with an upper left - * corner at (0,0), but the targa files have the origin in the - * lower left corner ... thus the translation here to shift source - * images into the right positions - */ -//============================================================================= -Bool TexturePage::addImageData( Byte *destBuffer, - Int destWidth, - Int destHeight, - Int destBPP, - ImageInfo *image ) -{ - - // sanity - if( destBuffer == NULL || image == NULL ) - return FALSE; - - // load the real image data for the source - Targa source; - if( source.Load( image->m_path, TGAF_IMAGE, FALSE ) != 0 ) - { - char buffer[ _MAX_PATH + 32 ]; - - sprintf( buffer, "Error loading source file '%s'\n", image->m_path ); - DEBUG_ASSERTCRASH( 0, (buffer) ); - MessageBox( NULL, buffer, "Cannot Load Source File", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - // get the source image buffer - char *sourceBuffer = source.GetImage(); - DEBUG_ASSERTCRASH( sourceBuffer, ("No Source buffer for source image\n") ); - - // get the source bytes per pixel - Int sourceBPP = TGA_BytesPerPixel( source.Header.PixelDepth ); - - // - // the loaded targas are all laid out flat with no encoding, copy - // all the rows in the source to the destination buffer at the coords - // specified in the images' page location - // - char *src, *dest; - Int count; - Int x, y; - - if( BitIsSet( image->m_status, ImageInfo::ROTATED90C ) == FALSE ) - { - - // - // normal copy, image was not rotated - // - - // do all rows - for( y = 0; y < image->m_size.y; y++ ) - { - - // compute source location - src = sourceBuffer + ( (image->m_size.y - 1 - y) * image->m_size.x * sourceBPP); - - // compute destination location - dest = destBuffer + - ((destHeight - 1 - (image->m_pagePos.lo.y + y)) * destWidth * destBPP ) + - (image->m_pagePos.lo.x * destBPP); - - // copy a row from source to destination - count = image->m_pagePos.hi.x - image->m_pagePos.lo.x + 1; - for( x = 0; x < count; x++ ) - { - - // check the target and source formats - if( destBPP == 4 ) - { - - // copy the rgb - dest[ 3 ] = src[ 0 ]; - dest[ 2 ] = src[ 1 ]; - dest[ 1 ] = src[ 2 ]; - - // copy the alpha if present in the source - if( sourceBPP == 4 ) - dest[ 0 ] = src[ 3 ]; - else - dest[ 0 ] = (char)0xFF; // solid alpha - - } // end if - else - { - - // copy the rgb - dest[ 2 ] = src[ 0 ]; - dest[ 1 ] = src[ 1 ]; - dest[ 0 ] = src[ 2 ]; - - } // end else - - // skip past all these pixels - dest += destBPP; - src += sourceBPP; - - } // end for x - - } // end for y - - } // end if, not rotated - else - { - - // - // image was rotated, perform a 90 degrees rotation clockwise when we - // copy over the image data - // - for( y = 0; y < image->m_size.y; y++ ) - { - - - // compute beginning of source row to copy from - src = sourceBuffer + ((image->m_size.y - 1 - y) * image->m_size.x * sourceBPP); - - // for each pixel in source put it in dest rotated - for( x = 0; x < image->m_size.x; x++ ) - { - - // compute destination location - dest = destBuffer + - ( ( (destHeight - 1) - (image->m_pagePos.lo.y + x) ) * destWidth * destBPP ) + - ((image->m_pagePos.lo.x + (image->m_size.y - 1 - y)) * destBPP); - - // copy this pixel, checking target and source formats - if( destBPP == 4 ) - { - - // copy the rgb - dest[ 3 ] = src[ 0 ]; - dest[ 2 ] = src[ 1 ]; - dest[ 1 ] = src[ 2 ]; - - // copy the alpha if present in the source - if( sourceBPP == 4 ) - dest[ 0 ] = src[ 3 ]; - else - dest[ 0 ] = (char)0xFF; // solid alpha - - } // end if - else - { - - // copy the rgb - dest[ 2 ] = src[ 0 ]; - dest[ 1 ] = src[ 1 ]; - dest[ 0 ] = src[ 2 ]; - - } // end else - - // skip past all these pixels - dest += destBPP; - src += sourceBPP; - - } // end for x - - } // end for y - - } // end else - - // - // if we have the option to extend the RGB edges on we now need to process - // the image we just copied into the texture page and "bleed" the edges outward - // and if a border is present, into the border - // - if( BitIsSet( TheImagePacker->getGapMethod(), - ImagePacker::GAP_METHOD_EXTEND_RGB ) ) - extendImageEdges( destBuffer, - destWidth, - destHeight, - destBPP, - image, - FALSE ); - - return TRUE; // all done - -} // end addImageData - -// TexturePage::spotUsed ====================================================== -/** Is this spot in the texture page open? */ -//============================================================================= -Bool TexturePage::spotUsed( Int x, Int y ) -{ - - return m_canvas[ y * m_size.y + x ]; - -} // end spotUsed - -// TexturePage::lineUsed ====================================================== -/** Is there ANY spot in the line specified that is used */ -//============================================================================= -Bool TexturePage::lineUsed( Int sx, Int sy, Int ex, Int ey ) -{ - Int x, y; - UnsignedByte *ptr; - - for( y = sy; y <= ey; y++ ) - { - - // compute start of row - ptr = m_canvas + (y * m_size.y + sx); - - // scan the row - for( x = sx; x <= ex; x++, ptr++ ) - if( *ptr == USED ) - return USED; - - } // end for y - - return FALSE; // it's open! - -} // end lineUsed - -// TexturePage::markRegionUsed ================================================ -/** Mark this region as used */ -//============================================================================= -void TexturePage::markRegionUsed( IRegion2D *region ) -{ - UnsignedByte *ptr; - Int y; - Int count; - - // loop through y - for( y = region->lo.y; y <= region->hi.y; y++ ) - { - - // compute start of row - ptr = m_canvas + (y * m_size.y + region->lo.x); - - // fill this row - count = (region->hi.x - region->lo.x) + 1; - memset( ptr, USED, count ); - - } // end for - -} // end markRegionUsed - -// TexturePage::buildFitRegion ================================================ -/** Build an image region to try to fit into the page based on the location - * given, with the image size, the gutter sizes, and the all sides border - * size - * - * Note that x and y Gutter sizes can be changed as a result of this - * method - * - * Returns a set of "fit bits" that describe what the components - * have been included in the region constructed - */ -//============================================================================= -UnsignedInt TexturePage::buildFitRegion( IRegion2D *region, - Int startX, Int startY, - Int imageWidth, Int imageHeight, - Int *xGutter, Int *yGutter, - Bool allSidesBorder ) -{ - - // sanity - if( region == NULL || xGutter == NULL || yGutter == NULL ) - return 0; - - // - // create border size, if we have an 'allSidesBorder' then we need to - // add two pixels to width and height - // - Int xBorder = 0, yBorder = 0; - if( allSidesBorder ) - { - - xBorder = 2; - yBorder = 2; - - } // end if - - // - // when the image size exactly matches the target size of the texture - // page the region will not include any gutter or border sizes cause - // we can fit the image exactly as it is on the page - // - if( imageWidth == m_size.x ) - { - - *xGutter = 0; - xBorder = 0; - - } // end if - if( imageHeight == m_size.y ) - { - - *yGutter = 0; - yBorder = 0; - - } // end if - - // - // when an image is 1 pixel smaller than the destination texture - // page we can eliminate some borders used to stretch the RGB values - // at the edges because we will be hitting one side of the texture - // anyway. We will say these borders that are only on one side - // will be on the right and bottom (as described in the fit bits - // returned below) - // - if( imageWidth == m_size.x - 1 ) - xBorder = 1; - if( imageHeight == m_size.y - 1 ) - yBorder = 1; - - // build the region - region->lo.x = startX; - region->lo.y = startY; - region->hi.x = startX + imageWidth - 1 + *xGutter + xBorder; // -1 for zero based - region->hi.y = startY + imageHeight - 1 + *yGutter + yBorder; // -1 for zero based - - // - // build a set of region bit flags that tell what this region ACTUALLY - // used in its construction. Note that when we stripped off only ONE - // pixel off one dimension when talking about borders, we say that the - // border that we added was either on the right side of the image, - // or on the bottom of the image - // - UnsignedInt fitBits = 0; - if( *xGutter != 0 ) - BitSet( fitBits, ImageInfo::FIT_XGUTTER ); - if( *yGutter != 0 ) - BitSet( fitBits, ImageInfo::FIT_YGUTTER ); - if( xBorder >= 1 ) - BitSet( fitBits, ImageInfo::FIT_XBORDER_RIGHT ); - if( xBorder == 2 ) - BitSet( fitBits, ImageInfo::FIT_XBORDER_LEFT ); - if( yBorder >= 1 ) - BitSet( fitBits, ImageInfo::FIT_YBORDER_BOTTOM ); - if( yBorder == 2 ) - BitSet( fitBits, ImageInfo::FIT_YBORDER_TOP ); - - return fitBits; - -} // end buildFitRegion - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// TexturePage::TexturePage =================================================== -/** */ -//============================================================================ -TexturePage::TexturePage( Int width, Int height ) -{ - Int canvasSize; - - m_id = -1; - m_next = NULL; - m_prev = NULL; - m_size.x = width; - m_size.y = height; - m_packedImage = NULL; - m_targa = NULL; - - // create a "canvas" to represent used and unused areas - canvasSize = m_size.x * m_size.y; - m_canvas = new UnsignedByte[ canvasSize ]; - DEBUG_ASSERTCRASH( m_canvas, ("Cannot allocate canvas for texture page\n") ); - memset( m_canvas, FREE, sizeof( UnsignedByte ) * canvasSize ); - -} // end TexturePage - -// TexturePage::~TexturePage ================================================== -/** */ -//============================================================================= -TexturePage::~TexturePage( void ) -{ - - // delete the canvas - if( m_canvas ) - delete [] m_canvas; - - // delete targa if present, this will NOT delete a user assigned image buffer - if( m_targa ) - delete m_targa; - - // delete the final image buffer if present - if( m_packedImage ) - delete [] m_packedImage; - -} // end ~TexturePage - -// TexturePage::addImage ====================================================== -/** If this image will fit on this page, add it */ -//============================================================================= -Bool TexturePage::addImage( ImageInfo *image ) -{ - IRegion2D region; - - // santiy - if( image == NULL ) - { - - DEBUG_ASSERTCRASH( image, ("TexturePage::addImage: NULL image!\n") ); - return TRUE; // say it was added - - } // end if - - // get our options for fitting - Bool useGutter, useRGBExtend; - useGutter = BitIsSet( TheImagePacker->getGapMethod(), - ImagePacker::GAP_METHOD_GUTTER ); - useRGBExtend = BitIsSet( TheImagePacker->getGapMethod(), - ImagePacker::GAP_METHOD_EXTEND_RGB ); - - // - // try to fit this image in this page ... we have two tries, once - // normally, and once with the image rotated 90 degrees clockwise - // - Int triesLeft = 2; - Bool tryRotate = FALSE; - while( triesLeft ) - { - - // try the rotated image the second time around - if( triesLeft == 1 ) - tryRotate = TRUE; - - // we've now 'used up' a try - triesLeft--; - - // find a free upper left corner to put the image in - Int x, y; - Int xGutter = 0, yGutter = 0; - Int imageWidth, imageHeight; - UnsignedInt fitBits = 0; - for( y = 0; y < m_size.y; y++ ) - { - - for( x = 0; x < m_size.x; x++ ) - { - - // get the gutter size - if( useGutter ) - { - - xGutter = TheImagePacker->getGutter(); - yGutter = TheImagePacker->getGutter(); - - } // end if - else - { - - xGutter = 0; - yGutter = 0; - - } // end else - - // - // compute the region of the image at this location, the region that will - // be used will take up the image region AND the gutter. UNLESS the - // image is as big as the texture page, in that case there is no reason - // to use a gutter size. Also note that if we're trying to fit - // a rotated image this time we have to swap the coords - // around a little bit - // - if( tryRotate == FALSE ) - { - - // normal, non-rotated image - imageWidth = image->m_size.x; - imageHeight = image->m_size.y; - - } // end if - else - { - - // - // build region for rotation 90 degrees clockwise - // - // 1------------2 - // | | - // 3------------4 - // - // becomes - // - // 3--1 - // | | - // | | - // | | - // | | - // | | - // 4--2 - // - - imageWidth = image->m_size.y; - imageHeight = image->m_size.x; - - } // end else - - // build the region - fitBits = buildFitRegion( ®ion, x, y, - imageWidth, imageHeight, - &xGutter, &yGutter, - useRGBExtend ); - - // - // if the image region plus the gutter goes off the image page, BUT - // the image itself stays on the page, adjust the gutter to only - // be as big as from the end of the image to the end of the page, - // this technically doesn't fill the requirements of making a gutter - // around every image, but it's OK since that space will be - // designated as filled, and at that will be filled with - // transparent alpha - nothingness! - // - if( region.hi.x >= m_size.x ) - { - - // - // attempt to shrink x gutter if image can still fit with a - // smaller gutter to the right - // - if( region.hi.x - xGutter < m_size.x ) - xGutter = m_size.x - imageWidth; - - // rebuild region with new gutter size - fitBits = buildFitRegion( ®ion, x, y, - imageWidth, imageHeight, - &xGutter, &yGutter, - useRGBExtend ); - - - } // end if - if( region.hi.y >= m_size.y ) - { - - // - // attempt to shrink y gutter if image can still fit with - // a smaller gutter below - // - if( region.hi.y - yGutter < m_size.y ) - yGutter = m_size.y - imageHeight; - - // rebuild region with new gutter size - fitBits = buildFitRegion( ®ion, x, y, - imageWidth, imageHeight, - &xGutter, &yGutter, - useRGBExtend ); - - } // end if - - // reject this location if the hi region goes off the texture page - if( region.hi.y >= m_size.y ) - { - - y = m_size.y; // skip to end, this isn't gonna work - continue; - - } // end if - if( region.hi.x >= m_size.x ) - { - - x = m_size.x; // skip to end of row to try next row - continue; - - } // end if - - // - // reject this location if any of the corners are in used spots, - // note since we're trying to fit things by "sliding" them - // horizontally ... we cut out more checks if we see if the horizontal - // bounds are full at the right side first ... if they are we - // move our "anchor" point to try to fit again to after that - // point (saving the checking of between the current upper - // left anchor point and the right side point that is used anyway - // - - // upper right and lower right - if( spotUsed( region.hi.x, region.lo.y ) || // upper right - spotUsed( region.hi.x, region.hi.y ) ) // lower right - { - - x = region.hi.x; // next anchor spot will be to the right of here - continue; - - } // end if - - // upper left and lower left - if( spotUsed( region.lo.x, region.lo.y ) || // upper left - spotUsed( region.lo.x, region.hi.y ) ) // lower left - continue; - - // - // reject this location if we cross any used locations between - // the 4 corners - // - if( lineUsed( region.lo.x, region.lo.y, - region.hi.x, region.lo.y ) || // top side - lineUsed( region.hi.x, region.lo.y, - region.hi.x, region.hi.y ) || // right side - lineUsed( region.lo.x, region.hi.y, - region.hi.x, region.hi.y ) || // bottom side - lineUsed( region.lo.x, region.lo.y, - region.lo.x, region.hi.y ) ) // left side - continue; - - // - // we passed all tests, take up this spot - // - markRegionUsed( ®ion ); // marks region AND gutter used - BitClear( image->m_status, ImageInfo::TOOBIG ); - BitClear( image->m_status, ImageInfo::UNPACKED ); - BitSet( image->m_status, ImageInfo::PACKED ); - image->m_page = this; - - // - // store the properties of the region that was used to fit this - // image - // - image->m_fitBits = fitBits; - - // store the gutter sizes used in fitting this image - image->m_gutterUsed.x = xGutter; - image->m_gutterUsed.y = yGutter; - - // - // if we packed this image rotated, set a flag telling us we - // need to swap the size dimension in the image structure - // when copying the image data - // - if( tryRotate == TRUE ) - BitSet( image->m_status, ImageInfo::ROTATED90C ); - - // - // save the page position of this image, but do not include - // the gutter or padding borders which is incorporated into the region, - // we're interested in just the bounding rectangle of the image itself - // on the texture page - // - image->m_pagePos = region; - if( BitIsSet( fitBits, ImageInfo::FIT_XBORDER_LEFT ) ) - image->m_pagePos.lo.x++; - if( BitIsSet( fitBits, ImageInfo::FIT_YBORDER_TOP ) ) - image->m_pagePos.lo.y++; - if( BitIsSet( fitBits, ImageInfo::FIT_XBORDER_RIGHT ) ) - image->m_pagePos.hi.x--; - if( BitIsSet( fitBits, ImageInfo::FIT_YBORDER_BOTTOM ) ) - image->m_pagePos.hi.y--; - if( BitIsSet( fitBits, ImageInfo::FIT_XGUTTER ) ) - image->m_pagePos.hi.x -= xGutter; - if( BitIsSet( fitBits, ImageInfo::FIT_YGUTTER ) ) - image->m_pagePos.hi.y -= yGutter; - - // link this image to the texture page - image->m_prevPageImage = NULL; - image->m_nextPageImage = m_imageList; - if( m_imageList ) - m_imageList->m_prevPageImage = image; - m_imageList = image; - - return TRUE; // success - - } // end for x - - } // end for y - - } // end while, triesLeft - - // no space - return FALSE; - -} // end addImage - -// TexturePage::generateTexture =============================================== -/** Generate the final packed texture given all the images that have - * already been assigned to this page */ -//============================================================================= -Bool TexturePage::generateTexture( void ) -{ - - // sanity - if( m_imageList == NULL ) - return FALSE; - - // sanity - DEBUG_ASSERTCRASH( m_packedImage == NULL, ("The packed image list must be NULL before generating texture\n") ); - DEBUG_ASSERTCRASH( m_targa == NULL, ("The targa must be NULL before generating a new texture\n") ); - - // allocate targa to help us generate the final texture - m_targa = new Targa; - if( m_targa == NULL ) - { - char buffer[ 128 ]; - - sprintf( buffer, "Unable to allocate new targa to generate texture\n" ); - DEBUG_ASSERTCRASH( m_targa, (buffer) ); - MessageBox( NULL, buffer, "Internal Error", MB_OK | MB_ICONERROR ); - return FALSE; - - } // end if - - Bool outputAlpha = TheImagePacker->getOutputAlpha(); - Int depth, bpp; - - // - // if we're outputting an alpha channel we will use 32 bit color depth, - // if we're not we will use 24 bit - // - if( outputAlpha ) - depth = 32; - else - depth = 24; - - // how many bytes per pixel for the targa file format - bpp = TGA_BytesPerPixel( depth ); - - // allocate a buffer for our final image - Int bufferSize = m_size.x * m_size.y * bpp; - m_packedImage = new Byte[ bufferSize ]; - if( m_packedImage == NULL ) - { - char buffer[ 128 ]; - - sprintf( buffer, "Unable to allocate final packed image buffer\n" ); - DEBUG_ASSERTCRASH( m_packedImage, (buffer) ); - MessageBox( NULL, buffer, "Internal Error", MB_OK | MB_ICONERROR ); - BitSet( m_status, PAGE_ERROR ); - BitSet( m_status, CANT_ALLOCATE_PACKED_IMAGE ); - return FALSE; - - } // end if - - // zero the packed image to all zero - memset( m_packedImage, 0, sizeof( Byte ) * bufferSize ); - - // setup the targa header - m_targa->Header.ImageType = TGA_TRUECOLOR; - m_targa->Header.Width = m_size.x; - m_targa->Header.Height = m_size.y; - m_targa->Header.PixelDepth = depth; - - // add all the images to the final packed buffer - ImageInfo *image; - for( image = m_imageList; image; image = image->m_nextPageImage ) - { - - if( addImageData( m_packedImage, m_size.x, m_size.y, - bpp, image ) == FALSE ) - { - - BitSet( m_status, PAGE_ERROR ); - BitSet( m_status, CANT_ADD_IMAGE_DATA ); - return FALSE; - - } // end if - - } // end for image - - // set this data into the targa structure - m_targa->SetImage( m_packedImage ); - - return TRUE; // success - -} // end generateTexture - -// TexturePage::writeFile ===================================================== -/** Write the texture data that has already been generated to a file - * starting with the baseName passed in with the texture id of - * this texture page appended to the end of it */ -//============================================================================= -Bool TexturePage::writeFile( char *baseFilename ) -{ - - // sanity - if( baseFilename == NULL || m_targa == NULL ) - { - - BitSet( m_status, PAGE_ERROR ); - BitSet( m_status, NO_TEXTURE_DATA ); - return FALSE; - - } // end if - - // construct filename - char filePath[ _MAX_PATH ]; - sprintf( filePath, "%s%s_%03d.tga", TheImagePacker->getOutputDirectory(), - baseFilename, getID() ); - - // write the file - Bool error = FALSE; - long flags = TGAF_IMAGE; - if( TheImagePacker->getCompressTextures() == TRUE ) - BitSet( flags, TGAF_COMPRESS ); - error = m_targa->Save( filePath, flags , FALSE ); - - if( error != 0 ) - { - - // there was an error, set a status bit - BitSet( m_status, PAGE_ERROR ); - BitSet( m_status, ERROR_DURING_SAVE ); - - } // end if - - // return success or not - return !error; - -} // end writeFile - -// TexturePage::getPixel ====================================================== -/** Get the RGB pixel stored at location (x,y) (where (0,0) is the upper - * left corner of the image ... even though the internal targa - * isn't stored that way */ -//============================================================================= -void TexturePage::getPixel( Int x, Int y, Byte *r, Byte *g, Byte *b, Byte *a ) -{ - - // do nothing if we have no image data - if( m_packedImage == NULL ) - return; - - // how many bytes per pixel for the targa file format - Int depth = m_targa->Header.PixelDepth; - Int bpp = TGA_BytesPerPixel( depth ); - - // compute location into buffer - Byte *buf; - buf = m_packedImage + ((m_size.y - 1 - y) * m_size.x * bpp) + (x * bpp); - - // read the pixel data - if( bpp == 4 ) - { - - if( a ) - *a = buf[ 0 ]; - - *r = buf[ 1 ]; - *g = buf[ 2 ]; - *b = buf[ 3 ]; - - } // end if - else - { - - if( a ) - *a = (char)0xff; // no data, just return solid alpha - - *r = buf[ 0 ]; - *g = buf[ 1 ]; - *b = buf[ 2 ]; - - } // end else - -} // end getPixel diff --git a/Generals/Code/Tools/ImagePacker/Source/WinMain.cpp b/Generals/Code/Tools/ImagePacker/Source/WinMain.cpp deleted file mode 100644 index ee1b497283..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/WinMain.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: WinMain.cpp ////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: WinMain.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Application entry point for the image packer tool -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "Lib/BaseType.h" -#include "Common/GameMemory.h" -#include "Common/Debug.h" -#include "ImagePacker.h" -#include "Resource.h" -#include "WindowProc.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC DATA //////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -HINSTANCE ApplicationHInstance = NULL; ///< our application instance - -/// just to satisfy the game libraries we link to -HWND ApplicationHWnd = NULL; - -const Char *g_strFile = "data\\Generals.str"; -const Char *g_csfFile = "data\\%s\\Generals.csf"; - - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// WinMain ==================================================================== -/** Application entry point */ -//============================================================================= -Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPSTR lpCmdLine, Int nCmdShow ) -{ - - // start the log - DEBUG_INIT(DEBUG_FLAGS_DEFAULT); - initMemoryManager(); - - // save application instance - ApplicationHInstance = hInstance; - - // allocate a new image packer system - TheImagePacker = new ImagePacker; - if( TheImagePacker == NULL ) - return 0; - - // initialize the system - if( TheImagePacker->init() == FALSE ) - { - - delete TheImagePacker; - TheImagePacker = NULL; - return 0; - - } // end if - - // load the dialog box - DialogBox( hInstance, (LPCTSTR)IMAGE_PACKER_DIALOG, - NULL, (DLGPROC)ImagePackerProc ); - - // delete the image packer - delete TheImagePacker; - TheImagePacker = NULL; - - // close the log - shutdownMemoryManager(); - DEBUG_SHUTDOWN(); - - // all done - return 0; - -} // end WinMain diff --git a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/DirectorySelect.cpp b/Generals/Code/Tools/ImagePacker/Source/Window Procedures/DirectorySelect.cpp deleted file mode 100644 index 8ec48182ce..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/DirectorySelect.cpp +++ /dev/null @@ -1,387 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: DirectorySelect.cpp ////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: DirectorySelect.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Directory selection dialog -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "ImagePacker.h" -#include "Resource.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE DATA /////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -static char startDir[ _MAX_PATH ]; - - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// selectDrive ================================================================ -/** Based on the drive of the current working directory, select the - * drive item in the COMBO_DRIVE combo box matching the current - * drive letter */ -//============================================================================= -static void selectDrive( HWND dialog ) -{ - char currDir[ _MAX_PATH ]; - char drive; - - // get current directory - GetCurrentDirectory( _MAX_PATH, currDir ); - - // drive letter is the first character - drive = currDir[ 0 ]; - - // construct string to match in the combo - char string[ 32 ]; - sprintf( string, "[-%c-]", drive ); - - // select the string in the combo - Int index; - index = SendDlgItemMessage( dialog, COMBO_DRIVE, - CB_FINDSTRINGEXACT, -1, (LPARAM)string ); - if( index != CB_ERR ) - SendDlgItemMessage( dialog, COMBO_DRIVE, CB_SETCURSEL, index, 0 ); - -} // end selectDrive - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// DirectorySelectProc ======================================================== -/** Directory selection dialog */ -//============================================================================= -BOOL CALLBACK DirectorySelectProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ) -{ - static char buffer[ _MAX_PATH ]; - - switch( message ) - { - - // ------------------------------------------------------------------------ - case WM_INITDIALOG: - { - - // save our current directory as we start up - GetCurrentDirectory( _MAX_PATH, startDir ); - - // set the extents for the horizontal scroll bar in the listbox - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_SETHORIZONTALEXTENT, 1280, 0 ); - - // load the listbox with directory items - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_DIR, - DDL_DIRECTORY | DDL_EXCLUSIVE, - (LPARAM)"*.*" ); - - // set the current directory in the top label - GetCurrentDirectory( _MAX_PATH, buffer ); - if( buffer[ strlen( buffer ) - 1 ] != '\\' ) - strcat( buffer, "\\" ); - SetDlgItemText( hWndDialog, STATIC_CURRENT_DIR, buffer ); - - // load the drive box - SendDlgItemMessage( hWndDialog, COMBO_DRIVE, - CB_DIR, - DDL_DRIVES | DDL_EXCLUSIVE, - (LPARAM)"*.*" ); - - // select the right drive in the drive combo box - selectDrive( hWndDialog ); - - return TRUE; - - } // end init - - // ------------------------------------------------------------------------ - case WM_COMMAND: - { - Int notifyCode = HIWORD( wParam ); - Int controlID = LOWORD( wParam ); -// HWND hWndControl = (HWND)lParam; - - switch( controlID ) - { - - // -------------------------------------------------------------------- - case BUTTON_ADD: - { - Int count; - char text[ _MAX_PATH ]; - char toAdd[ _MAX_PATH ]; - - // get number of items in listbox - count = SendDlgItemMessage( hWndDialog, LIST_DIR, LB_GETCOUNT, 0, 0 ); - - // for each selected item add that directory - for( Int i = 0; i < count; i++ ) - { - - // is this item selected - if( SendDlgItemMessage( hWndDialog, LIST_DIR, LB_GETSEL, i, 0 ) > 0 ) - { - - // get the text - SendDlgItemMessage( hWndDialog, LIST_DIR, LB_GETTEXT, - i, (LPARAM)text ); - - // remove the brackets on the text - Int j, len = strlen( text ); - for( j = 0; j < len - 1; j++ ) - text[ j ] = text[ j + 1 ]; - text[ len - 2 ] = '\0'; - - // ignore the ".." directory - if( strcmp( text, ".." ) == 0 ) - continue; - - // - // construct directory to add, make sure we have a '\' on the - // end cause we assume that in the image file name code - // - sprintf( toAdd, "%s%s\\", buffer, text ); - - // do not add directory if it's already in the listbox - if( SendDlgItemMessage( TheImagePacker->getWindowHandle(), - LIST_FOLDERS, - LB_FINDSTRINGEXACT, -1, (LPARAM)toAdd ) != LB_ERR ) - { - char message[ _MAX_PATH + 32 ]; - - sprintf( message, "Ignoring folder '%s', already in list.", toAdd ); - MessageBox( NULL, message, "Folder Already In List", - MB_OK | MB_ICONINFORMATION ); - continue; - - } // end if - - // add path to the listbox - SendDlgItemMessage( TheImagePacker->getWindowHandle(), - LIST_FOLDERS, - LB_INSERTSTRING, -1, (LPARAM)toAdd ); - - } // end if - - } // end if - - SetCurrentDirectory( startDir ); - EndDialog( hWndDialog, TRUE ); - break; - - } // end proceed - - // -------------------------------------------------------------------- - case BUTTON_CANCEL: - { - - SetCurrentDirectory( startDir ); - EndDialog( hWndDialog, FALSE ); - break; - - } // end cancel - - // -------------------------------------------------------------------- - case COMBO_DRIVE: - { - - if( notifyCode == CBN_SELCHANGE ) - { - Int selected; - - // get selected index - selected = SendDlgItemMessage( hWndDialog, COMBO_DRIVE, - CB_GETCURSEL, 0, 0 ); - if( selected != CB_ERR ) - { - char string[ 32 ]; - - SendDlgItemMessage( hWndDialog, COMBO_DRIVE, - CB_GETLBTEXT, selected, (LPARAM)string ); - - // - // construct a drive letter and colon from the combo - // box strign [-x-] - // - string[ 0 ] = string[ 2 ]; // the drive letter in the form of "[-x-]" - string[ 1 ] = ':'; - string[ 2 ] = '\0'; - - // switch to that drive - SetCurrentDirectory( string ); - - // construct new direcotry name and update status text - GetCurrentDirectory( _MAX_PATH, buffer ); - if( buffer[ strlen( buffer ) - 1 ] != '\\' ) - strcat( buffer, "\\" ); - SetDlgItemText( hWndDialog, STATIC_CURRENT_DIR, buffer ); - EnableWindow( GetDlgItem( hWndDialog, BUTTON_ADD ), FALSE ); - - // reset the content of the listbox and reload - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_RESETCONTENT, 0, 0 ); - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_DIR, - DDL_DIRECTORY | DDL_EXCLUSIVE, - (LPARAM)"*.*" ); - - - } // end if - - } // end if - - break; - - } // end drive - - // -------------------------------------------------------------------- - case LIST_DIR: - { - - if( notifyCode == LBN_SELCHANGE ) - { - Int selCount; - Bool enable; - - // get selected count - selCount = SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_GETSELCOUNT, 0, 0 ); - - // if we have selected items, enable the add button - if( selCount > 0 ) - { - - // - // if the selected item is only the ".." directory we won't - // enable it, we know that _IF_ ".." is present it is at the - // top zero index position - // - enable = TRUE; - Int index = 0; - if( selCount == 1 && - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_GETSEL, index, 0 ) > 0 ) - { - char text[ _MAX_PATH ]; - - SendDlgItemMessage( hWndDialog, LIST_DIR, LB_GETTEXT, - index, (LPARAM)text ); - if( strcmp( text, "[..]" ) == 0 ) - enable = FALSE; - - } // end if - - } // end if - else - enable = FALSE; - - // do the enable - EnableWindow( GetDlgItem( hWndDialog, BUTTON_ADD ), enable ); - - } // end if - if( notifyCode == LBN_DBLCLK ) - { - Int selected; - char text[ _MAX_PATH ]; - - // get currently selected item - selected = SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_GETCURSEL, 0, 0 ); - - // get text of selected item - SendDlgItemMessage( hWndDialog, LIST_DIR, LB_GETTEXT, - selected, (LPARAM)text ); - - // strip the backets off the directory listing - Int len = strlen( text ); - for( Int i = 0; i < len - 1; i++ ) - text[ i ] = text[ i + 1 ]; - text[ len - 2 ] = '\0'; - - // go into that directory - SetCurrentDirectory( text ); - - // construct new direcotry name and update status text - GetCurrentDirectory( _MAX_PATH, buffer ); - if( buffer[ strlen( buffer ) - 1 ] != '\\' ) - strcat( buffer, "\\" ); - SetDlgItemText( hWndDialog, STATIC_CURRENT_DIR, buffer ); - EnableWindow( GetDlgItem( hWndDialog, BUTTON_ADD ), FALSE ); - - // reset the content of the listbox and reload - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_RESETCONTENT, 0, 0 ); - SendDlgItemMessage( hWndDialog, LIST_DIR, - LB_DIR, - DDL_DIRECTORY | DDL_EXCLUSIVE, - (LPARAM)"*.*" ); - - } // end if - - break; - - } // end list command - - } // end switch - - break; - - } // end command - - } // end switch message - - return 0; - -} // end DirectorySelectProc - - - diff --git a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/ImageErrorProc.cpp b/Generals/Code/Tools/ImagePacker/Source/Window Procedures/ImageErrorProc.cpp deleted file mode 100644 index e23c5ca15a..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/ImageErrorProc.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImageErrorProc.cpp /////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImageErrorProc.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Window procedure for the error dialog -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "ImagePacker.h" -#include "Resource.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// ImageErrorProc ============================================================= -/** Dialog proc for the error window */ -//============================================================================= -BOOL CALLBACK ImageErrorProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ) -{ - - switch( message ) - { - - // ------------------------------------------------------------------------ - case WM_INITDIALOG: - { - - // - // load the listbox with images that could not be processed - // and the reasons for it - // - - // sanity - if( TheImagePacker == NULL ) - return TRUE; - - // go through all images - Int i, count; - HWND list = GetDlgItem( hWndDialog, LIST_IMAGES ); - char buffer[ _MAX_PATH + 256 ]; - char reason[ 32 ]; - ImageInfo *image; - - count = TheImagePacker->getImageCount(); - for( i = 0; i < count; i++ ) - { - - // get image - image = TheImagePacker->getImage( i ); - - // sanity - if( image == NULL ) - continue; - - // if image can't be processed find out why - if( BitIsSet( image->m_status, ImageInfo::CANTPROCESS ) ) - { - - if( BitIsSet( image->m_status, ImageInfo::TOOBIG ) ) - sprintf( reason, "Too Big" ); - else if( BitIsSet( image->m_status, ImageInfo::INVALIDCOLORDEPTH ) ) - sprintf( reason, "Unsupported Color Depth" ); - else - sprintf( reason, "Unknown Reason" ); - - sprintf( buffer, "%s: (%dx%dx%d) %s", - reason, image->m_size.x, image->m_size.y, image->m_colorDepth, - image->m_path ); - - SendMessage( list, LB_INSERTSTRING, -1, (LPARAM)buffer ); - - } // end if - - } // end for i - - // set the extents for the horizontal scroll bar in the listbox - SendMessage( list, LB_SETHORIZONTALEXTENT, 1280, 0 ); - - return TRUE; - - } // end init - - // ------------------------------------------------------------------------ - case WM_COMMAND: - { - Int controlID = LOWORD( wParam ); -// Int notifyCode = HIWORD( wParam ); -// HWND hWndControl = (HWND)lParam; - - switch( controlID ) - { - - // -------------------------------------------------------------------- - case BUTTON_PROCEED: - { - - EndDialog( hWndDialog, TRUE ); - break; - - } // end proceed - - // -------------------------------------------------------------------- - case BUTTON_CANCEL: - { - - EndDialog( hWndDialog, FALSE ); - break; - - } // end cancel - - } // end switch - - break; - - } // end command - - } // end switch message - - return 0; - -} // end ImageErrorProc - - diff --git a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/ImagePackerProc.cpp b/Generals/Code/Tools/ImagePacker/Source/Window Procedures/ImagePackerProc.cpp deleted file mode 100644 index ed5a5463bc..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/ImagePackerProc.cpp +++ /dev/null @@ -1,407 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: ImagePackerProc.cpp ////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: ImagePackerProc.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Window procedure for the image packer app -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "ImagePacker.h" -#include "Resource.h" -#include "WindowProc.h" -#include "WinMain.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// ImagePackerProc ============================================================ -/** Dialog procedure for the program flow */ -//============================================================================= -BOOL CALLBACK ImagePackerProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ) -{ - - switch( message ) - { - - // ------------------------------------------------------------------------ - case WM_INITDIALOG: - { - - // we must have our program interface to continue - if( TheImagePacker == NULL ) - { - - MessageBox( NULL, "Internal Error, 'TheImagePacker' not initialized", - "Internal Error", MB_OK ); - EndDialog( hWndDialog, FALSE ); - - } // end if - - // save our window handlw - TheImagePacker->setWindowHandle( hWndDialog ); - - // get size of the screen - Int x, y; - x = GetSystemMetrics( SM_CXFULLSCREEN ); - y = GetSystemMetrics( SM_CYFULLSCREEN ); - - // get size of our dialog - RECT rect; - ICoord2D size; - GetWindowRect( hWndDialog, &rect ); - size.x = rect.right - rect.left; - size.y = rect.bottom - rect.top; - - // center dialog on screen - MoveWindow( hWndDialog, - (x / 2) - (size.x / 2), - (y / 2) - (size.y / 2), - size.x, - size.y, - TRUE ); - - // setup the status message - TheImagePacker->statusMessage( "Select options and click 'Start'." ); - - // set gutter size - SetDlgItemInt( hWndDialog, EDIT_GUTTER, TheImagePacker->getGutter(), FALSE ); - - // set alpha check - if( TheImagePacker->getOutputAlpha() ) - CheckDlgButton( hWndDialog, CHECK_ALPHA, BST_CHECKED ); - - // set the check for preview using the actual texture - if( TheImagePacker->getUseTexturePreview() ) - CheckDlgButton( hWndDialog, CHECK_BITMAP_PREVIEW, BST_CHECKED ); - - // set the check for creating INI definition - if( TheImagePacker->createINIFile() ) - CheckDlgButton( hWndDialog, CHECK_INI, BST_CHECKED ); - - // check the resursive checkbox by default - CheckDlgButton( hWndDialog, CHECK_USE_SUB_FOLDERS, BST_CHECKED ); - - // check the default image size radio button - CheckDlgButton( hWndDialog, RADIO_512X512, BST_CHECKED ); - - // fill out a default target filename - SetDlgItemText( hWndDialog, EDIT_FILENAME, "NewImage" ); - - // limit the size if the filename edit box - SendDlgItemMessage( hWndDialog, EDIT_FILENAME, - EM_LIMITTEXT, MAX_OUTPUT_FILE_LEN, 0 ); - - // set options for compressed textures - if( TheImagePacker->getCompressTextures() ) - CheckDlgButton( hWndDialog, CHECK_COMPRESS, BST_CHECKED ); - - // set option checks for gap method - UnsignedInt gapOptions = TheImagePacker->getGapMethod(); - if( BitIsSet( gapOptions, ImagePacker::GAP_METHOD_EXTEND_RGB ) ) - CheckDlgButton( hWndDialog, CHECK_GAP_EXTEND_RGB, BST_CHECKED ); - if( BitIsSet( gapOptions, ImagePacker::GAP_METHOD_GUTTER ) ) - CheckDlgButton( hWndDialog, CHECK_GAP_GUTTER, BST_CHECKED ); - - return TRUE; - - } // end init dialog - - // ------------------------------------------------------------------------ - case WM_COMMAND: - { - Int notifyCode = HIWORD( wParam ); - Int controlID = LOWORD( wParam ); -// HWND hWndControl = (HWND)lParam; - - switch( controlID ) - { - - // -------------------------------------------------------------------- - case BUTTON_PREVIOUS: - { - Int page = TheImagePacker->getTargetPreviewPage(); - - // target preview page back one - if( page > 1 ) - { - - page--; - TheImagePacker->setTargetPreviewPage( page ); - UpdatePreviewWindow(); - - } // end if - - break; - - } // end previous - - // -------------------------------------------------------------------- - case BUTTON_NEXT: - { - UnsignedInt page = TheImagePacker->getTargetPreviewPage(); - - if( page < TheImagePacker->getPageCount() ) - { - - page++; - TheImagePacker->setTargetPreviewPage( page ); - UpdatePreviewWindow(); - - } // end if - - break; - - } // end next - - // -------------------------------------------------------------------- - case CHECK_BITMAP_PREVIEW: - { - Bool useBitmap; - - if( IsDlgButtonChecked( hWndDialog, controlID ) == BST_CHECKED ) - useBitmap = TRUE; - else - useBitmap = FALSE; - - TheImagePacker->setUseTexturePreview( useBitmap ); - UpdatePreviewWindow(); - - break; - - } // end preview using image - - // -------------------------------------------------------------------- - case CHECK_GAP_GUTTER: - { - Bool enable = FALSE; - - if( IsDlgButtonChecked( hWndDialog, controlID ) == BST_CHECKED ) - enable = TRUE; - - EnableWindow( GetDlgItem( hWndDialog, STATIC_GAP_INFO ), enable ); - EnableWindow( GetDlgItem( hWndDialog, EDIT_GUTTER ), enable ); - - break; - - } // end transparent gutter - - // -------------------------------------------------------------------- - case BUTTON_PREVIEW: - { - HWND preview = TheImagePacker->getPreviewWindow(); - - if( preview ) - { - - // delete test display window - DestroyWindow( preview ); - TheImagePacker->setPreviewWindow( NULL ); - SetDlgItemText( hWndDialog, BUTTON_PREVIEW, "Open Preview" ); - - } // end if - else - { - HWND preview = MakePreviewDisplay(); - - if( preview ) - { - - TheImagePacker->setPreviewWindow( preview ); - UpdatePreviewWindow(); - SetDlgItemText( hWndDialog, BUTTON_PREVIEW, "Close Preview" ); - - } // end if - - } // end else - - break; - - } // end test - - // -------------------------------------------------------------------- - case BUTTON_ADD_FOLDER: - { - - // bring up the add directory dialog - DialogBox( ApplicationHInstance, - (LPCTSTR)DIRECTORY_SELECT_DIALOG, - TheImagePacker->getWindowHandle(), - (DLGPROC)DirectorySelectProc ); - break; - - } // end add folder - - // -------------------------------------------------------------------- - case BUTTON_REMOVE_FOLDER: - { - HWND folderList; - - // get the directory listbox - folderList = GetDlgItem( hWndDialog, LIST_FOLDERS ); - if( folderList == NULL ) - break;; - - // get the selected item in the folder listbox - Int selCount; - selCount = SendMessage( folderList, LB_GETSELCOUNT, 0, 0 ); - if( selCount == 0 ) - { - - MessageBox( NULL, "You must first select a folder to remove it", - "Select Folder First", MB_OK | MB_ICONINFORMATION ); - break; - - } // end if - - // - // start at the end of the listbox, delete any items that - // are selected - // - Int itemCount = SendMessage( folderList, LB_GETCOUNT, 0, 0 ); - for( Int i = itemCount - 1; i >= 0; i-- ) - if( SendMessage( folderList, LB_GETSEL, i, 0 ) > 0 ) - SendMessage( folderList, LB_DELETESTRING, i, 0 ); - - break; - - } // end remove folder - - // -------------------------------------------------------------------- - case RADIO_128X128: - case RADIO_256X256: - case RADIO_512X512: - case RADIO_TARGET_OTHER: - { - Bool enable; - - // - // if this is the other button, enable the first edit box for - // user size, if not, disable that section of the UI - // - enable = IsDlgButtonChecked( hWndDialog, RADIO_TARGET_OTHER ); - EnableWindow( GetDlgItem( hWndDialog, EDIT_WIDTH ), enable ); - EnableWindow( GetDlgItem( hWndDialog, STATIC_X ), enable ); - - break; - - } // end target image size radio buttons - - // -------------------------------------------------------------------- - case EDIT_WIDTH: - { - - switch( notifyCode ) - { - - // ---------------------------------------------------------------- - case EN_UPDATE: - { - char buffer[ 32 ]; - - // - // the text of the width has changed, since our requirements - // are that the image must be square automatically update - // the height box as well - // - GetDlgItemText( hWndDialog, EDIT_WIDTH, buffer, 32 ); - SetDlgItemText( hWndDialog, EDIT_HEIGHT, buffer ); - - break; - - } // end update - - } // end switch - - break; - - } // end user defined width - - // -------------------------------------------------------------------- - case BUTTON_START: - { - Bool success; - - // get all the options from the dialog into the image packer - success = TheImagePacker->getSettingsFromDialog( hWndDialog ); - - // run the packer if nothing went wrong - if( success ) - TheImagePacker->process(); - - break; - - } // end execute - - // -------------------------------------------------------------------- - case BUTTON_EXIT: - { - - // quit the program - EndDialog( hWndDialog, TRUE ); - break; - - } // end exit - - } // end switch - - return 0; - - } // end command - - } // end switch - - return 0; - -} // end ImagePackerProc - - diff --git a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/PageErrorProc.cpp b/Generals/Code/Tools/ImagePacker/Source/Window Procedures/PageErrorProc.cpp deleted file mode 100644 index 3c226556f0..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/PageErrorProc.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: PageErrorProc.cpp //////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: PageErrorProc.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Window procedure for the error dialog for texture pages -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "ImagePacker.h" -#include "Resource.h" - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// PageErrorProc ============================================================== -/** Dialog proc for the error window */ -//============================================================================= -BOOL CALLBACK PageErrorProc( HWND hWndDialog, UINT message, - WPARAM wParam, LPARAM lParam ) -{ - - switch( message ) - { - - // ------------------------------------------------------------------------ - case WM_INITDIALOG: - { - - // - // load the listbox with pages that could not be processed - // and the reasons for it - // - - // sanity - if( TheImagePacker == NULL ) - return TRUE; - - // go through all pages - TexturePage *page; - HWND list = GetDlgItem( hWndDialog, LIST_PAGES ); - char buffer[ _MAX_PATH + 256 ]; - char reason[ 32 ]; - - for( page = TheImagePacker->getFirstTexturePage(); - page; - page = page->m_next ) - { - - // if image can't be processed find out why - if( BitIsSet( page->m_status, TexturePage::PAGE_ERROR ) ) - { - - if( BitIsSet( page->m_status, TexturePage::CANT_ALLOCATE_PACKED_IMAGE ) ) - sprintf( reason, "Can't allocate image memory" ); - else if( BitIsSet( page->m_status, TexturePage::CANT_ADD_IMAGE_DATA ) ) - sprintf( reason, "Can't add image(s) data" ); - else if( BitIsSet( page->m_status, TexturePage::NO_TEXTURE_DATA ) ) - sprintf( reason, "No texture data to write" ); - else if( BitIsSet( page->m_status, TexturePage::ERROR_DURING_SAVE ) ) - sprintf( reason, "Error writing texture file" ); - else - sprintf( reason, "Unknown Reason" ); - - sprintf( buffer, "%s: (%dx%d) %s%d", - reason, page->getWidth(), page->getHeight(), - TheImagePacker->getOutputFile(), page->getID() ); - - SendMessage( list, LB_INSERTSTRING, -1, (LPARAM)buffer ); - - } // end if - - } // end for i - - // set the extents for the horizontal scroll bar in the listbox - SendMessage( list, LB_SETHORIZONTALEXTENT, 1280, 0 ); - - return TRUE; - - } // end init - - // ------------------------------------------------------------------------ - case WM_COMMAND: - { - Int controlID = LOWORD( wParam ); -// Int notifyCode = HIWORD( wParam ); -// HWND hWndControl = (HWND)lParam; - - switch( controlID ) - { - - // -------------------------------------------------------------------- - case IDOK: - { - - EndDialog( hWndDialog, TRUE ); - break; - - } // end proceed - - } // end switch - - break; - - } // end command - - } // end switch message - - return 0; - -} // end PageErrorProc - - diff --git a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/PreviewProc.cpp b/Generals/Code/Tools/ImagePacker/Source/Window Procedures/PreviewProc.cpp deleted file mode 100644 index 169649bd54..0000000000 --- a/Generals/Code/Tools/ImagePacker/Source/Window Procedures/PreviewProc.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: PreviewProc.cpp ////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: PreviewProc.cpp -// -// Created: Colin Day, August 2001 -// -// Desc: Window procedure for the preview window -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "ImagePacker.h" -#include "WinMain.h" - -/////////////////////////////////////////////////////////////////////////////// -// DEFINES //////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -#define PREVIEW_STYLE WS_CAPTION - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -// PUBLIC DATA //////////////////////////////////////////////////////////////// - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// PreviewProc ================================================================ -/** */ -//============================================================================= -LRESULT CALLBACK PreviewProc( HWND hWnd, UINT message, - WPARAM wParam, LPARAM lParam ) -{ - - switch( message ) - { - - case WM_PAINT: - { - PAINTSTRUCT ps; - HDC hdc; - HBRUSH whiteBrush = (HBRUSH)GetStockObject( WHITE_BRUSH ); - - hdc = BeginPaint(hWnd, &ps); - - SelectObject( hdc, GetStockObject( WHITE_PEN ) ); - - // find the target texture page - TexturePage *page; - for( page = TheImagePacker->getFirstTexturePage(); - page; - page = page->m_next ) - { - - // if this is not the target page, ignore it - if( page->getID() != TheImagePacker->getTargetPreviewPage() ) - continue; - - // draw image based on the generated texture or silhouette - if( TheImagePacker->getUseTexturePreview() ) - { - Int x, y; - Byte r, g, b; - HPEN prevPen, pen; - - for( y = 0; y < page->getHeight(); y++ ) - { - - for( x = 0; x < page->getWidth(); x++ ) - { - - // get the color here - page->getPixel( x, y, &r, &g, &b ); - - // create a new pen of the right color - pen = CreatePen( 1, 1, RGB( r, g, b, ) ); - - // select pen into hdc - prevPen = (HPEN)SelectObject( hdc, pen ); - - // draw ... what is the Win32 put pixel function??? - MoveToEx( hdc, x, y, NULL ); - LineTo( hdc, x + 1, y ); - - // put the old pen back - SelectObject( hdc, prevPen ); - - // delete the created pen - DeleteObject( pen ); - - } // end for x - - } // end for y - - } // end if - else - { - - // go through all the images on this page - ImageInfo *image; - for( image = page->getFirstImage(); - image; - image = image->m_nextPageImage ) - { - RECT rect; - - rect.left = image->m_pagePos.lo.x; - rect.top = image->m_pagePos.lo.y; - rect.right = image->m_pagePos.hi.x + 1; // FillRect not inclusive - rect.bottom = image->m_pagePos.hi.y + 1; // FillRect not inclusive - FillRect( hdc, &rect, whiteBrush ); - - } // end for image - - } // end else - - } // end for page - - EndPaint( hWnd, &ps ); - break; - - } // end paint - - } // end switch - - return DefWindowProc( hWnd, message, wParam, lParam ); - -} // end PreviewProc - -// MakePreviewDisplay ========================================================= -/** */ -//============================================================================= -HWND MakePreviewDisplay( void ) -{ - WNDCLASSEX wcex; - const char *className = "PreviewDisplay"; - HWND hWnd; - - wcex.cbSize = sizeof( WNDCLASSEX ); - - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = (WNDPROC)PreviewProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = ApplicationHInstance; - wcex.hIcon = NULL; - wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); - wcex.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH ); - wcex.lpszMenuName = NULL; - wcex.lpszClassName = className; - wcex.hIconSm = NULL; - - RegisterClassEx( &wcex ); - - // create app window and keep handle - hWnd = CreateWindowEx( 0, // extended style - className, // window class name - "Preview", // window name - PREVIEW_STYLE, // window styles - 30, // x position - 30, // y position - TheImagePacker->getTargetWidth(), - TheImagePacker->getTargetHeight(), - NULL, // parent - NULL, // menu - ApplicationHInstance, // instance - NULL ); // creation data - - if( hWnd == NULL ) - return NULL; - - // display the window - ShowWindow( hWnd, SW_SHOW ); - - return hWnd; - -} // end MakePreviewDisplay - -// UpdatePreviewWindow ======================================================== -/** Update the preview window, if present */ -//============================================================================= -void UpdatePreviewWindow( void ) -{ - HWND preview; - - // sanity - if( TheImagePacker == NULL ) - return; - - // get preview window - preview = TheImagePacker->getPreviewWindow(); - - // if window not here don't bother - if( preview == NULL ) - return; - - // make the title - char title[ 256 ]; - - // construct title - sprintf( title, "Page #%d of %d", - TheImagePacker->getTargetPreviewPage(), - TheImagePacker->getPageCount() ); - SetWindowText( preview, title ); - - // adjust the window rect so the client area is the target packed size - RECT clientRect; - POINT p; - - p.x = 0; - p.y = 0; - ClientToScreen( preview, &p ); - clientRect.left = p.x; - clientRect.right = clientRect.left + TheImagePacker->getTargetWidth(); - clientRect.top = p.y; - clientRect.bottom = clientRect.top + TheImagePacker->getTargetHeight(); - AdjustWindowRect( &clientRect, PREVIEW_STYLE, FALSE ); - MoveWindow( preview, - clientRect.left, - clientRect.top, - clientRect.right - clientRect.left, - clientRect.bottom - clientRect.top, - TRUE ); - - // invalidate the client area for redraw - InvalidateRect( preview, NULL, TRUE ); - -} // end UpdatePreviewWindow diff --git a/Generals/Code/Tools/Launcher/BFISH.CPP b/Generals/Code/Tools/Launcher/BFISH.CPP deleted file mode 100644 index 7094af6fb3..0000000000 --- a/Generals/Code/Tools/Launcher/BFISH.CPP +++ /dev/null @@ -1,597 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Blowfish Component * - * * - * $Archive:: /Sun/Blowfish/bfish.cpp $* - * * - * $Author:: Joe_b $* - * * - * $Modtime:: 12/02/97 9:35p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * BlowfishEngine::Decrypt -- Decrypts data using blowfish algorithm. * - * BlowfishEngine::Encrypt -- Encrypt an arbitrary block of data. * - * BlowfishEngine::Process_Block -- Process a block of data using Blowfish algorithm. * - * BlowfishEngine::Sub_Key_Encrypt -- Encrypts a block for use in S-Box processing. * - * BlowfishEngine::Submit_Key -- Submit a key that will allow data processing. * - * BlowfishEngine::~BlowfishEngine -- Destructor for the Blowfish engine. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#pragma warning(disable : 4514) -#include "BFISH.H" -#include -#include - - -/* -** Byte order controlled long integer. This integer is constructed -** so that character 0 (C0) is the most significant byte of the -** integer. This is biased toward big endian architecture, but that -** just happens to be how the Blowfish algorithm was designed. -*/ -typedef union { - unsigned long Long; - struct { - unsigned char C3; - unsigned char C2; - unsigned char C1; - unsigned char C0; - } Char; -} Int; - - -/*********************************************************************************************** - * BlowfishEngine::~BlowfishEngine -- Destructor for the Blowfish engine. * - * * - * This destructor will clear out the s-box tables so that even if the memory for the * - * class remains, it will contain no compromising data. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/08/1996 JLB : Created. * - *=============================================================================================*/ -BlowfishEngine::~BlowfishEngine(void) -{ - if (IsKeyed) { - Submit_Key(NULL, 0); - } -} - - -/*********************************************************************************************** - * BlowfishEngine::Submit_Key -- Submit a key that will allow data processing. * - * * - * This routine must be called before any data can be encrypted or decrypted. This routine * - * need only be called when the key is to be changed or set for the first time. Once the * - * key has been set, the engine may be used to encrypt, decrypt, or both operations * - * indefinitely. The key must be 56 bytes or less in length. This is necessary because * - * any keys longer than that will not correctly affect the encryption process. * - * * - * If the key pointer is NULL, then the S-Box tables are reset to identity. This will * - * mask the previous key setting. Use this method to clear the engine after processing in * - * order to gain a measure of security. * - * * - * INPUT: key -- Pointer to the key data block. * - * * - * length -- The length of the submitted key. * - * * - * OUTPUT: none * - * * - * WARNINGS: This is a time consuming process. * - * * - * HISTORY: * - * 04/14/1996 JLB : Created. * - *=============================================================================================*/ -void BlowfishEngine::Submit_Key(void const * key, int length) -{ - assert(length <= MAX_KEY_LENGTH); - - /* - ** Initialize the permutation and S-Box tables to a known - ** constant value. - */ - memcpy(P_Encrypt, P_Init, sizeof(P_Init)); - memcpy(P_Decrypt, P_Init, sizeof(P_Init)); - memcpy(bf_S, S_Init, sizeof(S_Init)); - - /* - ** Validate parameters. - */ - if (key == 0 || length == 0) { - IsKeyed = false; - return; - } - - /* - ** Combine the key with the permutation table. Wrap the key - ** as many times as necessary to ensure that the entire - ** permutation table has been modified. The key is lifted - ** into a long by using endian independent means. - */ - int j = 0; - unsigned char const * key_ptr = (unsigned char const *)key; - unsigned long * p_ptr = &P_Encrypt[0]; - for (int index = 0; index < ROUNDS+2; index++) { - unsigned long data = 0; - - data = (data << CHAR_BIT) | key_ptr[j++ % length]; - data = (data << CHAR_BIT) | key_ptr[j++ % length]; - data = (data << CHAR_BIT) | key_ptr[j++ % length]; - data = (data << CHAR_BIT) | key_ptr[j++ % length]; - - *p_ptr++ ^= data; - } - - /* - ** The permutation table must be scrambled by means of the key. This - ** is how the key is factored into the encryption -- by merely altering - ** the permutation (and S-Box) tables. Because this transformation alters - ** the table data WHILE it is using the table data, the tables are - ** thoroughly obfuscated by this process. - */ - unsigned long left = 0x00000000L; - unsigned long right = 0x00000000L; - unsigned long * p_en = &P_Encrypt[0]; // Encryption table. - unsigned long * p_de = &P_Decrypt[ROUNDS+1]; // Decryption table. - for (int p_index = 0; p_index < ROUNDS+2; p_index += 2) { - Sub_Key_Encrypt(left, right); - - *p_en++ = left; - *p_en++ = right; - - *p_de-- = left; - *p_de-- = right; - } - - /* - ** Perform a similar transmutation to the S-Box tables. Also notice that the - ** working 64 bit number is carried into this process from the previous - ** operation. - */ - for (int sbox_index = 0; sbox_index < 4; sbox_index++) { - for (int ss_index = 0; ss_index < UCHAR_MAX+1; ss_index += 2) { - Sub_Key_Encrypt(left, right); - bf_S[sbox_index][ss_index] = left; - bf_S[sbox_index][ss_index + 1] = right; - } - } - - IsKeyed = true; -} - - -/*********************************************************************************************** - * BlowfishEngine::Encrypt -- Encrypt an arbitrary block of data. * - * * - * Use this routine to encrypt an arbitrary block of data. The block must be an even * - * multiple of 8 bytes. Any bytes left over will not be encrypted. The 8 byte requirement * - * is necessary because the underlying algorithm processes blocks in 8 byte chunks. * - * Partial blocks are unrecoverable and useless. * - * * - * INPUT: plaintext-- Pointer to the data block to be encrypted. * - * * - * length -- The length of the data block. * - * * - * cyphertext- Pointer to the output buffer that will hold the encrypted data. * - * * - * OUTPUT: Returns with the actual number of bytes encrypted. * - * * - * WARNINGS: You must submit the key before calling this routine. This will only encrypt * - * the plaintext in 8 byte increments. Modulo bytes left over are not processed. * - * * - * HISTORY: * - * 04/14/1996 JLB : Created. * - *=============================================================================================*/ -int BlowfishEngine::Encrypt(void const * plaintext, int length, void * cyphertext) -{ - if (plaintext == 0 || length == 0) { - return(0); - } - if (cyphertext == 0) cyphertext = (void *)plaintext; - - if (IsKeyed) { - - /* - ** Validate parameters. - */ - int blocks = length / BYTES_PER_BLOCK; - - /* - ** Process the buffer in 64 bit chunks. - */ - for (int index = 0; index < blocks; index++) { - Process_Block(plaintext, cyphertext, P_Encrypt); - plaintext = ((char *)plaintext) + BYTES_PER_BLOCK; - cyphertext = ((char *)cyphertext) + BYTES_PER_BLOCK; - } - int encrypted = blocks * BYTES_PER_BLOCK; - - /* - ** Copy over any trailing left over appendix bytes. - */ - if (encrypted < length) { - memmove(cyphertext, plaintext, length - encrypted); - } - - return(encrypted); - } - - /* - ** Non-keyed processing merely copies the data. - */ - if (plaintext != cyphertext) { - memmove(cyphertext, plaintext, length); - } - return(length); -} - - -/*********************************************************************************************** - * BlowfishEngine::Decrypt -- Decrypt an arbitrary block of data. * - * * - * Use this routine to decrypt an arbitrary block of data. The block must be an even * - * multiple of 8 bytes. Any bytes left over will not be decrypted. The 8 byte requirement * - * is necessary because the underlying algorithm processes blocks in 8 byte chunks. * - * Partial blocks are unrecoverable and useless. * - * * - * INPUT: cyphertext- Pointer to the data block to be decrypted. * - * * - * length -- The length of the data block. * - * * - * plaintext-- Pointer to the output buffer that will hold the decrypted data. * - * * - * OUTPUT: Returns with the actual number of bytes decrypted. * - * * - * WARNINGS: You must submit the key before calling this routine. This will only decrypt * - * the cyphertext in 8 byte increments. Modulo bytes left over are not processed. * - * * - * HISTORY: * - * 04/14/1996 JLB : Created. * - *=============================================================================================*/ -int BlowfishEngine::Decrypt(void const * cyphertext, int length, void * plaintext) -{ - if (cyphertext == 0 || length == 0) { - return(0); - } - if (plaintext == 0) plaintext = (void *)cyphertext; - - if (IsKeyed) { - - /* - ** Validate parameters. - */ - int blocks = length / BYTES_PER_BLOCK; - - /* - ** Process the buffer in 64 bit chunks. - */ - for (int index = 0; index < blocks; index++) { - Process_Block(cyphertext, plaintext, P_Decrypt); - cyphertext = ((char *)cyphertext) + BYTES_PER_BLOCK; - plaintext = ((char *)plaintext) + BYTES_PER_BLOCK; - } - int encrypted = blocks * BYTES_PER_BLOCK; - - /* - ** Copy over any trailing left over appendix bytes. - */ - if (encrypted < length) { - memmove(plaintext, cyphertext, length - encrypted); - } - - return(encrypted); - } - - /* - ** Non-keyed processing merely copies the data. - */ - if (plaintext != cyphertext) { - memmove(plaintext, cyphertext, length); - } - return(length); -} - - -/*********************************************************************************************** - * BlowfishEngine::Process_Block -- Process a block of data using Blowfish algorithm. * - * * - * This is the main processing routine for encryption and decryption. The algorithm * - * consists of a 16 round Feistal network and uses mathematics from different algebraic * - * groups (strengthens against differential cryptanalysis). The large S-Boxes and the * - * rounds strengthen it against linear cryptanalysis. * - * * - * INPUT: plaintext -- Pointer to the source text (it actually might be a pointer to * - * the cyphertext if this is called as a decryption process). * - * * - * cyphertext -- Pointer to the output buffer that will hold the processed block. * - * * - * ptable -- Pointer to the permutation table. This algorithm will encrypt * - * and decrypt using the same S-Box tables. The encryption control * - * is handled by the permutation table. * - * * - * OUTPUT: none * - * * - * WARNINGS: The source and destination buffers must be 8 bytes long. * - * * - * HISTORY: * - * 04/19/1996 JLB : Created. * - *=============================================================================================*/ -void BlowfishEngine::Process_Block(void const * plaintext, void * cyphertext, unsigned long const * ptable) -{ - /* - ** Input the left and right halves of the source block such that - ** the byte order is constant regardless of the endian - ** persuasion of the current processor. The blowfish algorithm is - ** biased toward "big endian" architecture and some optimizations - ** could be done for big endian processors in that case. - */ - unsigned char const * source = (unsigned char const *)plaintext; - Int left; - left.Char.C0 = *source++; - left.Char.C1 = *source++; - left.Char.C2 = *source++; - left.Char.C3 = *source++; - - Int right; - right.Char.C0 = *source++; - right.Char.C1 = *source++; - right.Char.C2 = *source++; - right.Char.C3 = *source; - - /* - ** Perform all Feistal rounds on the block. This is the encryption/decryption - ** process. Since there is an exchange that occurs after each round, two - ** rounds are combined in this loop to avoid unnecessary exchanging. - */ - for (int index = 0; index < ROUNDS/2; index++) { - left.Long ^= *ptable++; - right.Long ^= ((( bf_S[0][left.Char.C0] + bf_S[1][left.Char.C1]) ^ bf_S[2][left.Char.C2]) + bf_S[3][left.Char.C3]); - right.Long ^= *ptable++; - left.Long ^= ((( bf_S[0][right.Char.C0] + bf_S[1][right.Char.C1]) ^ bf_S[2][right.Char.C2]) + bf_S[3][right.Char.C3]); - } - - /* - ** The final two longs in the permutation table are processed into the block. - ** The left and right halves are still reversed as a side effect of the last - ** round. - */ - left.Long ^= *ptable++; - right.Long ^= *ptable; - - /* - ** The final block data is output in endian architecture - ** independent format. Notice that the blocks are output as - ** right first and left second. This is to counteract the final - ** superfluous exchange that occurs as a side effect of the - ** encryption rounds. - */ - unsigned char * out = (unsigned char *)cyphertext; - *out++ = right.Char.C0; - *out++ = right.Char.C1; - *out++ = right.Char.C2; - *out++ = right.Char.C3; - - *out++ = left.Char.C0; - *out++ = left.Char.C1; - *out++ = left.Char.C2; - *out = left.Char.C3; -} - - -/*********************************************************************************************** - * BlowfishEngine::Sub_Key_Encrypt -- Encrypts a block for use in S-Box processing. * - * * - * This is the same as the normal process block function but it doesn't have the endian * - * fixup logic. Since this routine is only called for S-Box table generation and it is * - * known that the S-Box initial data is already in local machine endian format, the * - * byte order fixups are not needed. This also has a tendency to speed up S-Box generation * - * as well. * - * * - * INPUT: left -- The left half of the data block. * - * * - * right -- The right half of the data block. * - * * - * OUTPUT: none, but the processed block is stored back into the left and right half * - * integers. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 04/19/1996 JLB : Created. * - *=============================================================================================*/ -void BlowfishEngine::Sub_Key_Encrypt(unsigned long & left, unsigned long & right) -{ - Int l; - l.Long = left; - - Int r; - r.Long = right; - - for (int index = 0; index < ROUNDS; index += 2) { - l.Long ^= P_Encrypt[index]; - r.Long ^= ((( bf_S[0][l.Char.C0] + bf_S[1][l.Char.C1]) ^ bf_S[2][l.Char.C2]) + bf_S[3][l.Char.C3]); - r.Long ^= P_Encrypt[index+1]; - l.Long ^= ((( bf_S[0][r.Char.C0] + bf_S[1][r.Char.C1]) ^ bf_S[2][r.Char.C2]) + bf_S[3][r.Char.C3]); - } - left = r.Long ^ P_Encrypt[ROUNDS+1]; - right = l.Long ^ P_Encrypt[ROUNDS]; -} - - -/* -** These tables have the bytes stored in machine endian format. Because of this, -** a special block cypher routine is needed when the sub-keys are generated. -** This is kludgier than it otherwise should be. However, storing these -** integers in machine independent format would be even more painful. -*/ - -unsigned long const BlowfishEngine::P_Init[BlowfishEngine::ROUNDS+2] = { - 0x243F6A88U,0x85A308D3U,0x13198A2EU,0x03707344U,0xA4093822U,0x299F31D0U,0x082EFA98U,0xEC4E6C89U, - 0x452821E6U,0x38D01377U,0xBE5466CFU,0x34E90C6CU,0xC0AC29B7U,0xC97C50DDU,0x3F84D5B5U,0xB5470917U, - 0x9216D5D9U,0x8979FB1BU -}; - -unsigned long const BlowfishEngine::S_Init[4][UCHAR_MAX+1] = { - { - 0xD1310BA6U,0x98DFB5ACU,0x2FFD72DBU,0xD01ADFB7U,0xB8E1AFEDU,0x6A267E96U,0xBA7C9045U,0xF12C7F99U, - 0x24A19947U,0xB3916CF7U,0x0801F2E2U,0x858EFC16U,0x636920D8U,0x71574E69U,0xA458FEA3U,0xF4933D7EU, - 0x0D95748FU,0x728EB658U,0x718BCD58U,0x82154AEEU,0x7B54A41DU,0xC25A59B5U,0x9C30D539U,0x2AF26013U, - 0xC5D1B023U,0x286085F0U,0xCA417918U,0xB8DB38EFU,0x8E79DCB0U,0x603A180EU,0x6C9E0E8BU,0xB01E8A3EU, - 0xD71577C1U,0xBD314B27U,0x78AF2FDAU,0x55605C60U,0xE65525F3U,0xAA55AB94U,0x57489862U,0x63E81440U, - 0x55CA396AU,0x2AAB10B6U,0xB4CC5C34U,0x1141E8CEU,0xA15486AFU,0x7C72E993U,0xB3EE1411U,0x636FBC2AU, - 0x2BA9C55DU,0x741831F6U,0xCE5C3E16U,0x9B87931EU,0xAFD6BA33U,0x6C24CF5CU,0x7A325381U,0x28958677U, - 0x3B8F4898U,0x6B4BB9AFU,0xC4BFE81BU,0x66282193U,0x61D809CCU,0xFB21A991U,0x487CAC60U,0x5DEC8032U, - 0xEF845D5DU,0xE98575B1U,0xDC262302U,0xEB651B88U,0x23893E81U,0xD396ACC5U,0x0F6D6FF3U,0x83F44239U, - 0x2E0B4482U,0xA4842004U,0x69C8F04AU,0x9E1F9B5EU,0x21C66842U,0xF6E96C9AU,0x670C9C61U,0xABD388F0U, - 0x6A51A0D2U,0xD8542F68U,0x960FA728U,0xAB5133A3U,0x6EEF0B6CU,0x137A3BE4U,0xBA3BF050U,0x7EFB2A98U, - 0xA1F1651DU,0x39AF0176U,0x66CA593EU,0x82430E88U,0x8CEE8619U,0x456F9FB4U,0x7D84A5C3U,0x3B8B5EBEU, - 0xE06F75D8U,0x85C12073U,0x401A449FU,0x56C16AA6U,0x4ED3AA62U,0x363F7706U,0x1BFEDF72U,0x429B023DU, - 0x37D0D724U,0xD00A1248U,0xDB0FEAD3U,0x49F1C09BU,0x075372C9U,0x80991B7BU,0x25D479D8U,0xF6E8DEF7U, - 0xE3FE501AU,0xB6794C3BU,0x976CE0BDU,0x04C006BAU,0xC1A94FB6U,0x409F60C4U,0x5E5C9EC2U,0x196A2463U, - 0x68FB6FAFU,0x3E6C53B5U,0x1339B2EBU,0x3B52EC6FU,0x6DFC511FU,0x9B30952CU,0xCC814544U,0xAF5EBD09U, - 0xBEE3D004U,0xDE334AFDU,0x660F2807U,0x192E4BB3U,0xC0CBA857U,0x45C8740FU,0xD20B5F39U,0xB9D3FBDBU, - 0x5579C0BDU,0x1A60320AU,0xD6A100C6U,0x402C7279U,0x679F25FEU,0xFB1FA3CCU,0x8EA5E9F8U,0xDB3222F8U, - 0x3C7516DFU,0xFD616B15U,0x2F501EC8U,0xAD0552ABU,0x323DB5FAU,0xFD238760U,0x53317B48U,0x3E00DF82U, - 0x9E5C57BBU,0xCA6F8CA0U,0x1A87562EU,0xDF1769DBU,0xD542A8F6U,0x287EFFC3U,0xAC6732C6U,0x8C4F5573U, - 0x695B27B0U,0xBBCA58C8U,0xE1FFA35DU,0xB8F011A0U,0x10FA3D98U,0xFD2183B8U,0x4AFCB56CU,0x2DD1D35BU, - 0x9A53E479U,0xB6F84565U,0xD28E49BCU,0x4BFB9790U,0xE1DDF2DAU,0xA4CB7E33U,0x62FB1341U,0xCEE4C6E8U, - 0xEF20CADAU,0x36774C01U,0xD07E9EFEU,0x2BF11FB4U,0x95DBDA4DU,0xAE909198U,0xEAAD8E71U,0x6B93D5A0U, - 0xD08ED1D0U,0xAFC725E0U,0x8E3C5B2FU,0x8E7594B7U,0x8FF6E2FBU,0xF2122B64U,0x8888B812U,0x900DF01CU, - 0x4FAD5EA0U,0x688FC31CU,0xD1CFF191U,0xB3A8C1ADU,0x2F2F2218U,0xBE0E1777U,0xEA752DFEU,0x8B021FA1U, - 0xE5A0CC0FU,0xB56F74E8U,0x18ACF3D6U,0xCE89E299U,0xB4A84FE0U,0xFD13E0B7U,0x7CC43B81U,0xD2ADA8D9U, - 0x165FA266U,0x80957705U,0x93CC7314U,0x211A1477U,0xE6AD2065U,0x77B5FA86U,0xC75442F5U,0xFB9D35CFU, - 0xEBCDAF0CU,0x7B3E89A0U,0xD6411BD3U,0xAE1E7E49U,0x00250E2DU,0x2071B35EU,0x226800BBU,0x57B8E0AFU, - 0x2464369BU,0xF009B91EU,0x5563911DU,0x59DFA6AAU,0x78C14389U,0xD95A537FU,0x207D5BA2U,0x02E5B9C5U, - 0x83260376U,0x6295CFA9U,0x11C81968U,0x4E734A41U,0xB3472DCAU,0x7B14A94AU,0x1B510052U,0x9A532915U, - 0xD60F573FU,0xBC9BC6E4U,0x2B60A476U,0x81E67400U,0x08BA6FB5U,0x571BE91FU,0xF296EC6BU,0x2A0DD915U, - 0xB6636521U,0xE7B9F9B6U,0xFF34052EU,0xC5855664U,0x53B02D5DU,0xA99F8FA1U,0x08BA4799U,0x6E85076AU, - },{ - 0x4B7A70E9U,0xB5B32944U,0xDB75092EU,0xC4192623U,0xAD6EA6B0U,0x49A7DF7DU,0x9CEE60B8U,0x8FEDB266U, - 0xECAA8C71U,0x699A17FFU,0x5664526CU,0xC2B19EE1U,0x193602A5U,0x75094C29U,0xA0591340U,0xE4183A3EU, - 0x3F54989AU,0x5B429D65U,0x6B8FE4D6U,0x99F73FD6U,0xA1D29C07U,0xEFE830F5U,0x4D2D38E6U,0xF0255DC1U, - 0x4CDD2086U,0x8470EB26U,0x6382E9C6U,0x021ECC5EU,0x09686B3FU,0x3EBAEFC9U,0x3C971814U,0x6B6A70A1U, - 0x687F3584U,0x52A0E286U,0xB79C5305U,0xAA500737U,0x3E07841CU,0x7FDEAE5CU,0x8E7D44ECU,0x5716F2B8U, - 0xB03ADA37U,0xF0500C0DU,0xF01C1F04U,0x0200B3FFU,0xAE0CF51AU,0x3CB574B2U,0x25837A58U,0xDC0921BDU, - 0xD19113F9U,0x7CA92FF6U,0x94324773U,0x22F54701U,0x3AE5E581U,0x37C2DADCU,0xC8B57634U,0x9AF3DDA7U, - 0xA9446146U,0x0FD0030EU,0xECC8C73EU,0xA4751E41U,0xE238CD99U,0x3BEA0E2FU,0x3280BBA1U,0x183EB331U, - 0x4E548B38U,0x4F6DB908U,0x6F420D03U,0xF60A04BFU,0x2CB81290U,0x24977C79U,0x5679B072U,0xBCAF89AFU, - 0xDE9A771FU,0xD9930810U,0xB38BAE12U,0xDCCF3F2EU,0x5512721FU,0x2E6B7124U,0x501ADDE6U,0x9F84CD87U, - 0x7A584718U,0x7408DA17U,0xBC9F9ABCU,0xE94B7D8CU,0xEC7AEC3AU,0xDB851DFAU,0x63094366U,0xC464C3D2U, - 0xEF1C1847U,0x3215D908U,0xDD433B37U,0x24C2BA16U,0x12A14D43U,0x2A65C451U,0x50940002U,0x133AE4DDU, - 0x71DFF89EU,0x10314E55U,0x81AC77D6U,0x5F11199BU,0x043556F1U,0xD7A3C76BU,0x3C11183BU,0x5924A509U, - 0xF28FE6EDU,0x97F1FBFAU,0x9EBABF2CU,0x1E153C6EU,0x86E34570U,0xEAE96FB1U,0x860E5E0AU,0x5A3E2AB3U, - 0x771FE71CU,0x4E3D06FAU,0x2965DCB9U,0x99E71D0FU,0x803E89D6U,0x5266C825U,0x2E4CC978U,0x9C10B36AU, - 0xC6150EBAU,0x94E2EA78U,0xA5FC3C53U,0x1E0A2DF4U,0xF2F74EA7U,0x361D2B3DU,0x1939260FU,0x19C27960U, - 0x5223A708U,0xF71312B6U,0xEBADFE6EU,0xEAC31F66U,0xE3BC4595U,0xA67BC883U,0xB17F37D1U,0x018CFF28U, - 0xC332DDEFU,0xBE6C5AA5U,0x65582185U,0x68AB9802U,0xEECEA50FU,0xDB2F953BU,0x2AEF7DADU,0x5B6E2F84U, - 0x1521B628U,0x29076170U,0xECDD4775U,0x619F1510U,0x13CCA830U,0xEB61BD96U,0x0334FE1EU,0xAA0363CFU, - 0xB5735C90U,0x4C70A239U,0xD59E9E0BU,0xCBAADE14U,0xEECC86BCU,0x60622CA7U,0x9CAB5CABU,0xB2F3846EU, - 0x648B1EAFU,0x19BDF0CAU,0xA02369B9U,0x655ABB50U,0x40685A32U,0x3C2AB4B3U,0x319EE9D5U,0xC021B8F7U, - 0x9B540B19U,0x875FA099U,0x95F7997EU,0x623D7DA8U,0xF837889AU,0x97E32D77U,0x11ED935FU,0x16681281U, - 0x0E358829U,0xC7E61FD6U,0x96DEDFA1U,0x7858BA99U,0x57F584A5U,0x1B227263U,0x9B83C3FFU,0x1AC24696U, - 0xCDB30AEBU,0x532E3054U,0x8FD948E4U,0x6DBC3128U,0x58EBF2EFU,0x34C6FFEAU,0xFE28ED61U,0xEE7C3C73U, - 0x5D4A14D9U,0xE864B7E3U,0x42105D14U,0x203E13E0U,0x45EEE2B6U,0xA3AAABEAU,0xDB6C4F15U,0xFACB4FD0U, - 0xC742F442U,0xEF6ABBB5U,0x654F3B1DU,0x41CD2105U,0xD81E799EU,0x86854DC7U,0xE44B476AU,0x3D816250U, - 0xCF62A1F2U,0x5B8D2646U,0xFC8883A0U,0xC1C7B6A3U,0x7F1524C3U,0x69CB7492U,0x47848A0BU,0x5692B285U, - 0x095BBF00U,0xAD19489DU,0x1462B174U,0x23820E00U,0x58428D2AU,0x0C55F5EAU,0x1DADF43EU,0x233F7061U, - 0x3372F092U,0x8D937E41U,0xD65FECF1U,0x6C223BDBU,0x7CDE3759U,0xCBEE7460U,0x4085F2A7U,0xCE77326EU, - 0xA6078084U,0x19F8509EU,0xE8EFD855U,0x61D99735U,0xA969A7AAU,0xC50C06C2U,0x5A04ABFCU,0x800BCADCU, - 0x9E447A2EU,0xC3453484U,0xFDD56705U,0x0E1E9EC9U,0xDB73DBD3U,0x105588CDU,0x675FDA79U,0xE3674340U, - 0xC5C43465U,0x713E38D8U,0x3D28F89EU,0xF16DFF20U,0x153E21E7U,0x8FB03D4AU,0xE6E39F2BU,0xDB83ADF7U, - },{ - 0xE93D5A68U,0x948140F7U,0xF64C261CU,0x94692934U,0x411520F7U,0x7602D4F7U,0xBCF46B2EU,0xD4A20068U, - 0xD4082471U,0x3320F46AU,0x43B7D4B7U,0x500061AFU,0x1E39F62EU,0x97244546U,0x14214F74U,0xBF8B8840U, - 0x4D95FC1DU,0x96B591AFU,0x70F4DDD3U,0x66A02F45U,0xBFBC09ECU,0x03BD9785U,0x7FAC6DD0U,0x31CB8504U, - 0x96EB27B3U,0x55FD3941U,0xDA2547E6U,0xABCA0A9AU,0x28507825U,0x530429F4U,0x0A2C86DAU,0xE9B66DFBU, - 0x68DC1462U,0xD7486900U,0x680EC0A4U,0x27A18DEEU,0x4F3FFEA2U,0xE887AD8CU,0xB58CE006U,0x7AF4D6B6U, - 0xAACE1E7CU,0xD3375FECU,0xCE78A399U,0x406B2A42U,0x20FE9E35U,0xD9F385B9U,0xEE39D7ABU,0x3B124E8BU, - 0x1DC9FAF7U,0x4B6D1856U,0x26A36631U,0xEAE397B2U,0x3A6EFA74U,0xDD5B4332U,0x6841E7F7U,0xCA7820FBU, - 0xFB0AF54EU,0xD8FEB397U,0x454056ACU,0xBA489527U,0x55533A3AU,0x20838D87U,0xFE6BA9B7U,0xD096954BU, - 0x55A867BCU,0xA1159A58U,0xCCA92963U,0x99E1DB33U,0xA62A4A56U,0x3F3125F9U,0x5EF47E1CU,0x9029317CU, - 0xFDF8E802U,0x04272F70U,0x80BB155CU,0x05282CE3U,0x95C11548U,0xE4C66D22U,0x48C1133FU,0xC70F86DCU, - 0x07F9C9EEU,0x41041F0FU,0x404779A4U,0x5D886E17U,0x325F51EBU,0xD59BC0D1U,0xF2BCC18FU,0x41113564U, - 0x257B7834U,0x602A9C60U,0xDFF8E8A3U,0x1F636C1BU,0x0E12B4C2U,0x02E1329EU,0xAF664FD1U,0xCAD18115U, - 0x6B2395E0U,0x333E92E1U,0x3B240B62U,0xEEBEB922U,0x85B2A20EU,0xE6BA0D99U,0xDE720C8CU,0x2DA2F728U, - 0xD0127845U,0x95B794FDU,0x647D0862U,0xE7CCF5F0U,0x5449A36FU,0x877D48FAU,0xC39DFD27U,0xF33E8D1EU, - 0x0A476341U,0x992EFF74U,0x3A6F6EABU,0xF4F8FD37U,0xA812DC60U,0xA1EBDDF8U,0x991BE14CU,0xDB6E6B0DU, - 0xC67B5510U,0x6D672C37U,0x2765D43BU,0xDCD0E804U,0xF1290DC7U,0xCC00FFA3U,0xB5390F92U,0x690FED0BU, - 0x667B9FFBU,0xCEDB7D9CU,0xA091CF0BU,0xD9155EA3U,0xBB132F88U,0x515BAD24U,0x7B9479BFU,0x763BD6EBU, - 0x37392EB3U,0xCC115979U,0x8026E297U,0xF42E312DU,0x6842ADA7U,0xC66A2B3BU,0x12754CCCU,0x782EF11CU, - 0x6A124237U,0xB79251E7U,0x06A1BBE6U,0x4BFB6350U,0x1A6B1018U,0x11CAEDFAU,0x3D25BDD8U,0xE2E1C3C9U, - 0x44421659U,0x0A121386U,0xD90CEC6EU,0xD5ABEA2AU,0x64AF674EU,0xDA86A85FU,0xBEBFE988U,0x64E4C3FEU, - 0x9DBC8057U,0xF0F7C086U,0x60787BF8U,0x6003604DU,0xD1FD8346U,0xF6381FB0U,0x7745AE04U,0xD736FCCCU, - 0x83426B33U,0xF01EAB71U,0xB0804187U,0x3C005E5FU,0x77A057BEU,0xBDE8AE24U,0x55464299U,0xBF582E61U, - 0x4E58F48FU,0xF2DDFDA2U,0xF474EF38U,0x8789BDC2U,0x5366F9C3U,0xC8B38E74U,0xB475F255U,0x46FCD9B9U, - 0x7AEB2661U,0x8B1DDF84U,0x846A0E79U,0x915F95E2U,0x466E598EU,0x20B45770U,0x8CD55591U,0xC902DE4CU, - 0xB90BACE1U,0xBB8205D0U,0x11A86248U,0x7574A99EU,0xB77F19B6U,0xE0A9DC09U,0x662D09A1U,0xC4324633U, - 0xE85A1F02U,0x09F0BE8CU,0x4A99A025U,0x1D6EFE10U,0x1AB93D1DU,0x0BA5A4DFU,0xA186F20FU,0x2868F169U, - 0xDCB7DA83U,0x573906FEU,0xA1E2CE9BU,0x4FCD7F52U,0x50115E01U,0xA70683FAU,0xA002B5C4U,0x0DE6D027U, - 0x9AF88C27U,0x773F8641U,0xC3604C06U,0x61A806B5U,0xF0177A28U,0xC0F586E0U,0x006058AAU,0x30DC7D62U, - 0x11E69ED7U,0x2338EA63U,0x53C2DD94U,0xC2C21634U,0xBBCBEE56U,0x90BCB6DEU,0xEBFC7DA1U,0xCE591D76U, - 0x6F05E409U,0x4B7C0188U,0x39720A3DU,0x7C927C24U,0x86E3725FU,0x724D9DB9U,0x1AC15BB4U,0xD39EB8FCU, - 0xED545578U,0x08FCA5B5U,0xD83D7CD3U,0x4DAD0FC4U,0x1E50EF5EU,0xB161E6F8U,0xA28514D9U,0x6C51133CU, - 0x6FD5C7E7U,0x56E14EC4U,0x362ABFCEU,0xDDC6C837U,0xD79A3234U,0x92638212U,0x670EFA8EU,0x406000E0U, - },{ - 0x3A39CE37U,0xD3FAF5CFU,0xABC27737U,0x5AC52D1BU,0x5CB0679EU,0x4FA33742U,0xD3822740U,0x99BC9BBEU, - 0xD5118E9DU,0xBF0F7315U,0xD62D1C7EU,0xC700C47BU,0xB78C1B6BU,0x21A19045U,0xB26EB1BEU,0x6A366EB4U, - 0x5748AB2FU,0xBC946E79U,0xC6A376D2U,0x6549C2C8U,0x530FF8EEU,0x468DDE7DU,0xD5730A1DU,0x4CD04DC6U, - 0x2939BBDBU,0xA9BA4650U,0xAC9526E8U,0xBE5EE304U,0xA1FAD5F0U,0x6A2D519AU,0x63EF8CE2U,0x9A86EE22U, - 0xC089C2B8U,0x43242EF6U,0xA51E03AAU,0x9CF2D0A4U,0x83C061BAU,0x9BE96A4DU,0x8FE51550U,0xBA645BD6U, - 0x2826A2F9U,0xA73A3AE1U,0x4BA99586U,0xEF5562E9U,0xC72FEFD3U,0xF752F7DAU,0x3F046F69U,0x77FA0A59U, - 0x80E4A915U,0x87B08601U,0x9B09E6ADU,0x3B3EE593U,0xE990FD5AU,0x9E34D797U,0x2CF0B7D9U,0x022B8B51U, - 0x96D5AC3AU,0x017DA67DU,0xD1CF3ED6U,0x7C7D2D28U,0x1F9F25CFU,0xADF2B89BU,0x5AD6B472U,0x5A88F54CU, - 0xE029AC71U,0xE019A5E6U,0x47B0ACFDU,0xED93FA9BU,0xE8D3C48DU,0x283B57CCU,0xF8D56629U,0x79132E28U, - 0x785F0191U,0xED756055U,0xF7960E44U,0xE3D35E8CU,0x15056DD4U,0x88F46DBAU,0x03A16125U,0x0564F0BDU, - 0xC3EB9E15U,0x3C9057A2U,0x97271AECU,0xA93A072AU,0x1B3F6D9BU,0x1E6321F5U,0xF59C66FBU,0x26DCF319U, - 0x7533D928U,0xB155FDF5U,0x03563482U,0x8ABA3CBBU,0x28517711U,0xC20AD9F8U,0xABCC5167U,0xCCAD925FU, - 0x4DE81751U,0x3830DC8EU,0x379D5862U,0x9320F991U,0xEA7A90C2U,0xFB3E7BCEU,0x5121CE64U,0x774FBE32U, - 0xA8B6E37EU,0xC3293D46U,0x48DE5369U,0x6413E680U,0xA2AE0810U,0xDD6DB224U,0x69852DFDU,0x09072166U, - 0xB39A460AU,0x6445C0DDU,0x586CDECFU,0x1C20C8AEU,0x5BBEF7DDU,0x1B588D40U,0xCCD2017FU,0x6BB4E3BBU, - 0xDDA26A7EU,0x3A59FF45U,0x3E350A44U,0xBCB4CDD5U,0x72EACEA8U,0xFA6484BBU,0x8D6612AEU,0xBF3C6F47U, - 0xD29BE463U,0x542F5D9EU,0xAEC2771BU,0xF64E6370U,0x740E0D8DU,0xE75B1357U,0xF8721671U,0xAF537D5DU, - 0x4040CB08U,0x4EB4E2CCU,0x34D2466AU,0x0115AF84U,0xE1B00428U,0x95983A1DU,0x06B89FB4U,0xCE6EA048U, - 0x6F3F3B82U,0x3520AB82U,0x011A1D4BU,0x277227F8U,0x611560B1U,0xE7933FDCU,0xBB3A792BU,0x344525BDU, - 0xA08839E1U,0x51CE794BU,0x2F32C9B7U,0xA01FBAC9U,0xE01CC87EU,0xBCC7D1F6U,0xCF0111C3U,0xA1E8AAC7U, - 0x1A908749U,0xD44FBD9AU,0xD0DADECBU,0xD50ADA38U,0x0339C32AU,0xC6913667U,0x8DF9317CU,0xE0B12B4FU, - 0xF79E59B7U,0x43F5BB3AU,0xF2D519FFU,0x27D9459CU,0xBF97222CU,0x15E6FC2AU,0x0F91FC71U,0x9B941525U, - 0xFAE59361U,0xCEB69CEBU,0xC2A86459U,0x12BAA8D1U,0xB6C1075EU,0xE3056A0CU,0x10D25065U,0xCB03A442U, - 0xE0EC6E0EU,0x1698DB3BU,0x4C98A0BEU,0x3278E964U,0x9F1F9532U,0xE0D392DFU,0xD3A0342BU,0x8971F21EU, - 0x1B0A7441U,0x4BA3348CU,0xC5BE7120U,0xC37632D8U,0xDF359F8DU,0x9B992F2EU,0xE60B6F47U,0x0FE3F11DU, - 0xE54CDA54U,0x1EDAD891U,0xCE6279CFU,0xCD3E7E6FU,0x1618B166U,0xFD2C1D05U,0x848FD2C5U,0xF6FB2299U, - 0xF523F357U,0xA6327623U,0x93A83531U,0x56CCCD02U,0xACF08162U,0x5A75EBB5U,0x6E163697U,0x88D273CCU, - 0xDE966292U,0x81B949D0U,0x4C50901BU,0x71C65614U,0xE6C6C7BDU,0x327A140AU,0x45E1D006U,0xC3F27B9AU, - 0xC9AA53FDU,0x62A80F00U,0xBB25BFE2U,0x35BDD2F6U,0x71126905U,0xB2040222U,0xB6CBCF7CU,0xCD769C2BU, - 0x53113EC0U,0x1640E3D3U,0x38ABBD60U,0x2547ADF0U,0xBA38209CU,0xF746CE76U,0x77AFA1C5U,0x20756060U, - 0x85CBFE4EU,0x8AE88DD8U,0x7AAAF9B0U,0x4CF9AA7EU,0x1948C25CU,0x02FB8A8CU,0x01C36AE4U,0xD6EBE1F9U, - 0x90D4F869U,0xA65CDEA0U,0x3F09252DU,0xC208E69FU,0xB74E6132U,0xCE77E25BU,0x578FDFE3U,0x3AC372E6U - } -}; - diff --git a/Generals/Code/Tools/Launcher/BFISH.H b/Generals/Code/Tools/Launcher/BFISH.H deleted file mode 100644 index b163349a0d..0000000000 --- a/Generals/Code/Tools/Launcher/BFISH.H +++ /dev/null @@ -1,105 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Blowfish Component * - * * - * $Archive:: /Sun/Blowfish/bfish.h $* - * * - * $Author:: Joe_b $* - * * - * $Modtime:: 12/02/97 9:35p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef BFISH_H -#define BFISH_H - -#include - - -/* -** This engine will process data blocks by encryption and decryption. -** The "Blowfish" algorithm is in the public domain. It uses -** a Feistal network (similar to IDEA). It has no known -** weaknesses, but is still relatively new. Blowfish is particularly strong -** against brute force attacks. It is also quite strong against linear and -** differential cryptanalysis. Unlike public key encription, it is very -** fast at encryption, as far as cryptography goes. Its weakness is that -** it takes a relatively long time to set up with a new key (1/100th of -** a second on a P6-200). The time to set up a key is equivalent to -** encrypting 4240 bytes. -*/ -class BlowfishEngine { - public: - BlowfishEngine(void) : IsKeyed(false) {} - ~BlowfishEngine(void); - - void Submit_Key(void const * key, int length); - - int Encrypt(void const * plaintext, int length, void * cyphertext); - int Decrypt(void const * cyphertext, int length, void * plaintext); - - /* - ** This is the maximum key length supported. - */ - enum {MAX_KEY_LENGTH=56, - BYTES_PER_BLOCK=8 // The number of bytes in each cypher block (don't change). - }; - - private: - bool IsKeyed; - - void Sub_Key_Encrypt(unsigned long & left, unsigned long & right); - - void Process_Block(void const * plaintext, void * cyphertext, unsigned long const * ptable); - void Initialize_Tables(void); - - enum { - ROUNDS = 16 // Feistal round count (16 is standard). - }; - - /* - ** Initialization data for sub keys. The initial values are constant and - ** filled with a number generated from pi. Thus they are not random but - ** they don't hold a weak pattern either. - */ - static unsigned long const P_Init[ROUNDS+2]; - static unsigned long const S_Init[4][UCHAR_MAX+1]; - - /* - ** Permutation tables for encryption and decryption. - */ - unsigned long P_Encrypt[ROUNDS+2]; - unsigned long P_Decrypt[ROUNDS+2]; - - /* - ** S-Box tables (four). - */ - unsigned long bf_S[4][UCHAR_MAX+1]; -}; - -#endif - diff --git a/Generals/Code/Tools/Launcher/CMakeLists.txt b/Generals/Code/Tools/Launcher/CMakeLists.txt index 3233ca7dd0..9ba02b8c74 100644 --- a/Generals/Code/Tools/Launcher/CMakeLists.txt +++ b/Generals/Code/Tools/Launcher/CMakeLists.txt @@ -1,75 +1,9 @@ add_subdirectory(DatGen) -set(LAUNCHER_SRC - "BFISH.CPP" - "BFISH.H" - "configfile.cpp" - "configfile.h" - "dialog.cpp" - "dialog.h" - "dictionary.h" - "filed.h" - "findpatch.cpp" - "findpatch.h" - "loadbmp.cpp" - "loadbmp.h" - "main.cpp" - "monod.cpp" - "monod.h" - "odevice.h" - "patch.cpp" - "patch.h" - "process.cpp" - "process.h" - "Protect.cpp" - "Protect.h" - "resource.h" - "streamer.cpp" - "streamer.h" - "wdebug.cpp" - "wdebug.h" - "winblows.cpp" - "winblows.h" - "wstring.cpp" - "wstring.h" - "wstypes.h" - "Toolkit/Debug/DebugPrint.cpp" - "Toolkit/Debug/DebugPrint.h" - "Toolkit/Storage/File.cpp" - "Toolkit/Storage/File.h" - "Toolkit/Storage/Rights.h" - "Toolkit/Storage/Stream.h" - "Toolkit/Support/RefCounted.h" - "Toolkit/Support/RefPtr.h" - "Toolkit/Support/StringConvert.cpp" - "Toolkit/Support/StringConvert.h" - "Toolkit/Support/UString.cpp" - "Toolkit/Support/UString.h" - "Toolkit/Support/UTypes.h" - "Toolkit/Support/Visualc.h" -) - add_executable(g_launcher WIN32) set_target_properties(g_launcher PROPERTIES OUTPUT_NAME launcher) -target_sources(g_launcher PRIVATE ${LAUNCHER_SRC}) - -target_include_directories(g_launcher PRIVATE - Toolkit -) - -target_compile_definitions(g_launcher PRIVATE - USE_NOTEPAD - $<$:USE_GAMEDIR_FROM_LCF> -) - target_link_libraries(g_launcher PRIVATE - comctl32 - core_config - core_utility - safedisc + corei_launcher + gi_always ) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(g_launcher PRIVATE launcher1.rc) -endif() diff --git a/Generals/Code/Tools/Launcher/DatGen/CMakeLists.txt b/Generals/Code/Tools/Launcher/DatGen/CMakeLists.txt index 4fddbc11f4..6abeb7f077 100644 --- a/Generals/Code/Tools/Launcher/DatGen/CMakeLists.txt +++ b/Generals/Code/Tools/Launcher/DatGen/CMakeLists.txt @@ -1,22 +1,7 @@ -set(DATGEN_SRC - "DatGen.cpp" - "../BFISH.CPP" - "../BFISH.H" - "../Toolkit/Debug/DebugPrint.cpp" - "../Toolkit/Debug/DebugPrint.h" -) - add_executable(g_datgen WIN32) set_target_properties(g_datgen PROPERTIES OUTPUT_NAME datgen) -target_include_directories(g_datgen PRIVATE - ../ - ../Toolkit -) - target_link_libraries(g_datgen PRIVATE - core_config - safedisc + corei_datgen + gi_always ) - -target_sources(g_datgen PRIVATE ${DATGEN_SRC}) diff --git a/Generals/Code/Tools/Launcher/DatGen/DatGen.cpp b/Generals/Code/Tools/Launcher/DatGen/DatGen.cpp deleted file mode 100644 index 1e12d7bafd..0000000000 --- a/Generals/Code/Tools/Launcher/DatGen/DatGen.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// DatGen.cpp : Defines the entry point for the application. -// - -#include -#include -#include -#include -#include "BFISH.H" -#include "SafeDisk/CdaPfn.h" -#include - -void __cdecl doIt(void); - -CDAPFN_DECLARE_GLOBAL(doIt, CDAPFN_OVERHEAD_L5, CDAPFN_CONSTRAINT_NONE); - -static void doIt(void) -{ - // Generate passkey - char passKey[128]; - passKey[0] = '\0'; - unsigned char installPath[MAX_PATH] = ""; - - // Get game information - HKEY hKey; - bool usesHKeycurrentUser = false; - LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Generals", 0, KEY_READ, &hKey); - if (result != ERROR_SUCCESS) - { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Generals", 0, KEY_READ, &hKey); - usesHKeycurrentUser = true; - } - assert((result == ERROR_SUCCESS) && "Failed to open game registry key"); - - if (result != ERROR_SUCCESS) - { - return; - } - - // Retrieve install path - DWORD type; - DWORD sizeOfBuffer = sizeof(installPath); - result = RegQueryValueEx(hKey, "InstallPath", NULL, &type, installPath, &sizeOfBuffer); - - assert((result == ERROR_SUCCESS) && "Failed to obtain game install path!"); - assert((strlen((const char*)installPath) > 0) && "Game install path invalid!"); - DebugPrint("Game install path: %s\n", installPath); - - // Retrieve Hard drive S/N - char drive[8]; - _splitpath((const char*)installPath, drive, NULL, NULL, NULL); - strcat(drive, "\\"); - - DWORD volumeSerialNumber = 0; - DWORD maxComponentLength; - DWORD fileSystemFlags; - BOOL volInfoSuccess = GetVolumeInformation((const char*)drive, NULL, 0, - &volumeSerialNumber, &maxComponentLength, &fileSystemFlags, NULL, 0); - - if (volInfoSuccess == FALSE) - { - PrintWin32Error("***** GetVolumeInformation() Failed!"); - } - - DebugPrint("Drive Serial Number: %lx\n", volumeSerialNumber); - - // Add hard drive serial number portion - char volumeSN[16]; - sprintf(volumeSN, "%lx-", volumeSerialNumber); - strcat(passKey, volumeSN); - - // Retrieve game serial # - unsigned char gameSerialNumber[64]; - gameSerialNumber[0] = '\0'; - sizeOfBuffer = sizeof(gameSerialNumber); - if (usesHKeycurrentUser) - { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Generals\\ergc", 0, KEY_READ, &hKey); - } - else - { - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Generals\\ergc", 0, KEY_READ, &hKey); - } - assert((result == ERROR_SUCCESS) && "Failed to open game serial registry key"); - - if (result == ERROR_SUCCESS) - { - result = RegQueryValueEx(hKey, "", NULL, &type, gameSerialNumber, &sizeOfBuffer); - assert((result == ERROR_SUCCESS) && "Failed to obtain game serial number!"); - assert((strlen((const char*)gameSerialNumber) > 0) && "Game serial number invalid!"); - } - - DebugPrint("Game serial number: %s\n", gameSerialNumber); - - RegCloseKey(hKey); - - // Add game serial number portion - strcat(passKey, (char*)gameSerialNumber); - - // Obtain windows product ID - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion", 0, KEY_READ, &hKey); - assert((result == ERROR_SUCCESS) && "Failed to open windows registry key!"); - - if (result == ERROR_SUCCESS) - { - // Retrieve Windows Product ID - unsigned char winProductID[64]; - winProductID[0] = '\0'; - - DWORD type; - DWORD sizeOfBuffer = sizeof(winProductID); - result = RegQueryValueEx(hKey, "ProductID", NULL, &type, winProductID, &sizeOfBuffer); - - assert((result == ERROR_SUCCESS) && "Failed to obtain windows product ID!"); - assert((strlen((const char*)winProductID) > 0) && "Invalid windows product ID"); - - DebugPrint("Windows Product ID: %s\n", winProductID); - - RegCloseKey(hKey); - - // Add windows product ID portion - strcat(passKey, "-"); - strcat(passKey, (char*)winProductID); - } - - DebugPrint("Retrieved PassKey: %s\n", passKey); - - const char *plainText = "Play the \"Command & Conquer: Generals\" Multiplayer Test."; - int textLen = strlen(plainText); - char cypherText[128]; - - DebugPrint("Retrieved PassKey: %s\n", passKey); - - // Decrypt protected data into the memory mapped file - BlowfishEngine blowfish; - int len = strlen(passKey); - if (len > BlowfishEngine::MAX_KEY_LENGTH) - len = BlowfishEngine::MAX_KEY_LENGTH; - blowfish.Submit_Key(passKey, len); - - blowfish.Encrypt(plainText, textLen, cypherText); - cypherText[textLen] = 0; - DebugPrint("Encrypted data: %s\n", cypherText); - - DebugPrint("Install dir = '%s'\n", installPath); - - char *lastBackslash = strrchr((char *)installPath, '\\'); - if (lastBackslash) - *lastBackslash = 0; // strip of \\game.exe from install path - - strcat((char *)installPath, "\\Generals.dat"); - - DebugPrint("DAT file = '%s'\n", installPath); - - FILE *fp = fopen((char *)installPath, "wb"); - if (fp) - { - fwrite(cypherText, textLen, 1, fp); - fclose(fp); - } - - CDAPFN_ENDMARK(doIt); -} - -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR lpCmdLine, - int nCmdShow) -{ - doIt(); - - return 0; -} - - - diff --git a/Generals/Code/Tools/Launcher/Protect.cpp b/Generals/Code/Tools/Launcher/Protect.cpp deleted file mode 100644 index 9a618fc598..0000000000 --- a/Generals/Code/Tools/Launcher/Protect.cpp +++ /dev/null @@ -1,336 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: /APILauncher/Protect.cpp $ -* -* DESCRIPTION -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: Mcampbell $ -* -* VERSION INFO -* $Modtime: 6/21/01 5:09p $ -* $Revision: 6 $ -* -******************************************************************************/ - -#include "Protect.h" - -#ifdef COPY_PROTECT - -#include "BFISH.H" -#include -#include -#include -#include -#include -#include -#include -#include - -#include "SafeDisk/CdaPfn.h" - -// This GUID should be unique for each product. (CHANGE IT WHEN DOING THE -// NEXT PRODUCT) Note that the game will need to agree on this GUID also, so -// the game will have to be modified also. -const char* const LAUNCHER_GUID = - "150C6462-4E49-4ccf-B073-57579569D994"; // Generals Multiplayer Test Launcher GUID -const char* const protectGUID = - "6096561D-8A70-48ed-9FF8-18552419E50D"; // Generals Multiplayer Test Protect GUID - -/* -const char* const LAUNCHER_GUID = - "FB327081-64F2-43d8-9B72-503C3B765134"; // Generals Launcher GUID -const char* const protectGUID = - "7BEB9006-CC19-4aca-913A-C870A88DE01A"; // Generals Protect GUID -*/ - -HANDLE mLauncherMutex = NULL; -HANDLE mMappedFile = NULL; - -void InitializeProtect(void) -{ - ShutdownProtect(); - - DebugPrint("Initializing protection\n"); - - mLauncherMutex = NULL; - mMappedFile = NULL; - - // Secure launcher mutex - mLauncherMutex = CreateMutex(NULL, FALSE, LAUNCHER_GUID); - - if ((mLauncherMutex == NULL) || (mLauncherMutex && (GetLastError() == ERROR_ALREADY_EXISTS))) - { - DebugPrint("***** Failed to create launcher mutex\n"); - return; - } - - // Create memory mapped file to mirror protected file - File file("Generals.dat", Rights_ReadOnly); - - if (!file.IsAvailable()) - { - DebugPrint("***** Unable to find Generals.dat\n"); - return; - } - - UInt32 fileSize = file.GetLength(); - - SECURITY_ATTRIBUTES security; - security.nLength = sizeof(security); - security.lpSecurityDescriptor = NULL; - security.bInheritHandle = TRUE; - - mMappedFile = CreateFileMapping(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, fileSize, NULL); - - if ((mMappedFile == NULL) || (mMappedFile && (GetLastError() == ERROR_ALREADY_EXISTS))) - { - PrintWin32Error("***** CreateFileMapping() Failed!"); - CloseHandle(mMappedFile); - mMappedFile = NULL; - return; - } -} - -CDAPFN_DECLARE_GLOBAL(SendProtectMessage, CDAPFN_OVERHEAD_L5, CDAPFN_CONSTRAINT_NONE); - -void SendProtectMessage(HANDLE process, DWORD threadID) -{ - // Decrypt protected file contents to mapping file - File file("Generals.dat", Rights_ReadOnly); - - if (!file.IsAvailable()) - { - DebugPrint("***** Unable to find Generals.dat\n"); - return; - } - - // Map file to programs address space - LPVOID mapAddress = MapViewOfFileEx(mMappedFile, FILE_MAP_ALL_ACCESS, 0, 0, 0, NULL); - - if (mapAddress == NULL) - { - PrintWin32Error("***** MapViewOfFileEx() Failed!"); - return; - } - - void* buffer = NULL; - UInt32 bufferSize = 0; - file.Load(buffer, bufferSize); - - if (buffer && (bufferSize > 0)) - { - DebugPrint("Generating PassKey\n"); - - // Generate passkey - char passKey[128]; - passKey[0] = '\0'; - - // Get game information - HKEY hKey; - bool usesHKeycurrentUser = false; - LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Generals", 0, KEY_READ, &hKey); - if (result != ERROR_SUCCESS) - { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Generals", 0, KEY_READ, &hKey); - usesHKeycurrentUser = true; - } - assert((result == ERROR_SUCCESS) && "Failed to open game registry key"); - - if (result == ERROR_SUCCESS) - { - // Retrieve install path - unsigned char installPath[MAX_PATH]; - DWORD type; - DWORD sizeOfBuffer = sizeof(installPath); - result = RegQueryValueEx(hKey, "InstallPath", NULL, &type, installPath, &sizeOfBuffer); - - assert((result == ERROR_SUCCESS) && "Failed to obtain game install path!"); - assert((strlen((const char*)installPath) > 0) && "Game install path invalid!"); - DebugPrint("Game install path: %s\n", installPath); - - // Retrieve Hard drive S/N - char drive[8]; - _splitpath((const char*)installPath, drive, NULL, NULL, NULL); - strcat(drive, "\\"); - - DWORD volumeSerialNumber = 0; - DWORD maxComponentLength; - DWORD fileSystemFlags; - BOOL volInfoSuccess = GetVolumeInformation((const char*)drive, NULL, 0, - &volumeSerialNumber, &maxComponentLength, &fileSystemFlags, NULL, 0); - - if (volInfoSuccess == FALSE) - { - PrintWin32Error("***** GetVolumeInformation() Failed!"); - } - - DebugPrint("Drive Serial Number: %lx\n", volumeSerialNumber); - - // Add hard drive serial number portion - char volumeSN[16]; - sprintf(volumeSN, "%lx-", volumeSerialNumber); - strcat(passKey, volumeSN); - - // Retrieve game serial # - unsigned char gameSerialNumber[64]; - gameSerialNumber[0] = '\0'; - sizeOfBuffer = sizeof(gameSerialNumber); - if (usesHKeycurrentUser) - { - result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Electronic Arts\\EA Games\\Generals\\ergc", 0, KEY_READ, &hKey); - } - else - { - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Electronic Arts\\EA Games\\Generals\\ergc", 0, KEY_READ, &hKey); - } - assert((result == ERROR_SUCCESS) && "Failed to open game serial registry key"); - - if (result == ERROR_SUCCESS) - { - result = RegQueryValueEx(hKey, "", NULL, &type, gameSerialNumber, &sizeOfBuffer); - assert((result == ERROR_SUCCESS) && "Failed to obtain game serial number!"); - assert((strlen((const char*)gameSerialNumber) > 0) && "Game serial number invalid!"); - } - - DebugPrint("Game serial number: %s\n", gameSerialNumber); - - RegCloseKey(hKey); - - // Add game serial number portion - strcat(passKey, (char*)gameSerialNumber); - } - - // Obtain windows product ID - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion", 0, KEY_READ, &hKey); - assert((result == ERROR_SUCCESS) && "Failed to open windows registry key!"); - - if (result == ERROR_SUCCESS) - { - // Retrieve Windows Product ID - unsigned char winProductID[64]; - winProductID[0] = '\0'; - - DWORD type; - DWORD sizeOfBuffer = sizeof(winProductID); - result = RegQueryValueEx(hKey, "ProductID", NULL, &type, winProductID, &sizeOfBuffer); - - assert((result == ERROR_SUCCESS) && "Failed to obtain windows product ID!"); - assert((strlen((const char*)winProductID) > 0) && "Invalid windows product ID"); - - DebugPrint("Windows Product ID: %s\n", winProductID); - - RegCloseKey(hKey); - - // Add windows product ID portion - strcat(passKey, "-"); - strcat(passKey, (char*)winProductID); - } - - DebugPrint("Retrieved PassKey: %s\n", passKey); - - // Decrypt protected data into the memory mapped file - BlowfishEngine blowfish; - int len = strlen(passKey); - if (len > BlowfishEngine::MAX_KEY_LENGTH) - len = BlowfishEngine::MAX_KEY_LENGTH; - blowfish.Submit_Key(passKey, len); - blowfish.Decrypt(buffer, bufferSize, mapAddress); - - DebugPrint("Decrypted data: %s\n", mapAddress); - - free(buffer); - } - - UnmapViewOfFile(mapAddress); - - //--------------------------------------------------------------------------- - // Send protection message - //--------------------------------------------------------------------------- - DebugPrint("Sending protect message\n"); - - DebugPrint("Creating running notification event.\n"); - HANDLE event = CreateEvent(NULL, FALSE, FALSE, protectGUID); - - if ((event == NULL) || (event && (GetLastError() == ERROR_ALREADY_EXISTS))) - { - PrintWin32Error("***** CreateEvent() Failed!"); - return; - } - - DebugPrint("Waiting for game (timeout in %.02f seconds)...\n", ((float)((5 * 60) * 1000) * 0.001)); - -#ifdef _DEBUG - unsigned long start = timeGetTime(); -#endif - - HANDLE handles[2]; - handles[0] = event; - handles[1] = process; - DWORD waitResult = WaitForMultipleObjects(2, &handles[0], FALSE, ((5 * 60) * 1000)); - -#ifdef _DEBUG - unsigned long stop = timeGetTime(); -#endif - - DebugPrint("WaitResult = %ld (WAIT_OBJECT_0 = %ld)\n", waitResult, WAIT_OBJECT_0); - - if (waitResult == WAIT_OBJECT_0) - { - if (mMappedFile != NULL) - { - DebugPrint("Sending game the beef. (%lx)\n", mMappedFile); - BOOL sent = PostThreadMessage(threadID, 0xBEEF, 0, (LPARAM)mMappedFile); - assert(sent == TRUE); - } - } - else - { - DebugPrint("***** Timeout!\n"); - } - -#ifdef _DEBUG - DebugPrint("Waited %.02f seconds\n", ((float)(stop - start) * 0.001)); -#endif - - CloseHandle(event); - CDAPFN_ENDMARK(SendProtectMessage); -} - - -void ShutdownProtect(void) -{ - if (mMappedFile) - { - CloseHandle(mMappedFile); - mMappedFile = NULL; - } - - if (mLauncherMutex) - { - CloseHandle(mLauncherMutex); - mLauncherMutex = NULL; - } -} - -#endif // COPY_PROTECT diff --git a/Generals/Code/Tools/Launcher/Protect.h b/Generals/Code/Tools/Launcher/Protect.h deleted file mode 100644 index 16dc200b07..0000000000 --- a/Generals/Code/Tools/Launcher/Protect.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: /APILauncher/Protect.h $ -* -* DESCRIPTION -* Copy protection -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: Mcampbell $ -* -* VERSION INFO -* $Modtime: 6/18/01 8:24p $ -* $Revision: 4 $ -* -******************************************************************************/ - -#ifndef __PROTECT_H__ -#define __PROTECT_H__ - -#ifdef COPY_PROTECT - -#include - -//#define OLDWAY - -#ifdef OLDWAY -template class RefPtr; -class UString; - - -class Protect - { - public: - Protect(); - ~Protect(); - - void SendMappedFileHandle(HANDLE process, DWORD threadID) const; - - private: - // Prevent copy & assignment - Protect(const Protect&); - const Protect& operator=(const Protect&); - - // Retrieve machine unique key - RefPtr GetPassKey(void) const; - - HANDLE mLauncherMutex; - HANDLE mMappedFile; - }; - -#else - -#ifdef __cplusplus -extern "C" { -#endif - -void __cdecl InitializeProtect(void); -void __cdecl ShutdownProtect(void); -void __cdecl SendProtectMessage(HANDLE process, DWORD threadID); - -#ifdef __cplusplus -}; -#endif - -#endif - -#endif // COPY_PROTECT - -#endif // PROTECT_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp b/Generals/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp deleted file mode 100644 index b38ac57d28..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Debug printing mechanism -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifdef _DEBUG - -#include "DebugPrint.h" -#include -#include -#include -#include - -char debugLogName[_MAX_PATH]; - -/****************************************************************************** -* -* NAME -* DebugPrint(String, ArgList...) -* -* DESCRIPTION -* Ouput debug print messages to the debugger and log file. -* -* INPUTS -* String - String to output. -* ArgList - Argument list -* -* RESULT -* NONE -* -******************************************************************************/ - -void __cdecl DebugPrint(const char* string, ...) - { - static char _buffer[1024]; - static char _filename[512] = ""; - - if (string != NULL) - { - // Format string - va_list va; - va_start(va, string); - vsprintf(&_buffer[0], string, va); - va_end(va); - - // Open log file - HANDLE file = INVALID_HANDLE_VALUE; - - if (strlen(_filename) == 0) - { - char path[_MAX_PATH]; - char drive[_MAX_DRIVE]; - char dir[_MAX_DIR]; - - GetModuleFileName(GetModuleHandle(NULL), &path[0], sizeof(path)); - _splitpath(path, drive, dir, NULL, NULL); - _makepath(_filename, drive, dir, debugLogName, "txt"); - - OutputDebugString("Creating "); - OutputDebugString(_filename); - OutputDebugString("\n"); - - file = CreateFile(_filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); - } - else - { - file = CreateFile(_filename, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); - } - - // Send string to debugger - OutputDebugString(_buffer); - - // Insert carriage return after newlines - int i = 0; - - while (_buffer[i] != '\0') - { - if (_buffer[i] == '\n') - { - int end = strlen(_buffer); - assert((end + 1) <= sizeof(_buffer)); - - while (end >= i) - { - _buffer[end + 1] = _buffer[end]; - end--; - } - - _buffer[i] = '\r'; - i++; - } - - i++; - } - - // Send string to log file - assert(file != INVALID_HANDLE_VALUE); - - if (file != INVALID_HANDLE_VALUE) - { - SetFilePointer(file, 0, NULL, FILE_END); - - DWORD written; - WriteFile(file, &_buffer[0], strlen(_buffer), &written, NULL); - - CloseHandle(file); - } - } - } - - -/****************************************************************************** -* -* NAME -* PrintWin32Error -* -* DESCRIPTION -* Display Win32 error message (Error retrieved from GetLastError()) -* -* INPUTS -* Message string -* -* RESULT -* NONE -* -******************************************************************************/ - -void __cdecl PrintWin32Error(const char* string, ...) - { - static char _buffer[1024]; - - if (string != NULL) - { - // Format string - va_list va; - va_start(va, string); - vsprintf(&_buffer[0], string, va); - va_end(va); - - LPVOID lpMsgBuf; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); - - DebugPrint("***** Win32 Error: %s\n", _buffer); - DebugPrint(" Reason: %s\n", (char*)lpMsgBuf); - - LocalFree(lpMsgBuf); - } - } - -#endif // _DEBUG diff --git a/Generals/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.h b/Generals/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.h deleted file mode 100644 index 4b3fd413c9..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Debug/DebugPrint.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Debug printing mechanism -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifndef _DEBUGPRINT_H_ -#define _DEBUGPRINT_H_ - -#ifdef _DEBUG - -#ifdef __cplusplus -extern "C" -{ -#endif - -//! Ouput debug print messages to the debugger and log file. -void __cdecl DebugPrint(const char* string, ...); -void __cdecl PrintWin32Error(const char* string, ...); - -extern char debugLogName[]; - - -#ifdef __cplusplus -} -#endif - -#else // _DEBUG - -#define DebugPrint -#define PrintWin32Error - -#endif // _DEBUG - -#endif // _DEBUGPRINT_H_ diff --git a/Generals/Code/Tools/Launcher/Toolkit/Storage/File.cpp b/Generals/Code/Tools/Launcher/Toolkit/Storage/File.cpp deleted file mode 100644 index 554ed19200..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Storage/File.cpp +++ /dev/null @@ -1,1109 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* File functionality for WIN32 -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#include "File.h" -#include -#include - -// This should be whatever the file system uses for invalid files -const HANDLE File::INVALID_HANDLE = INVALID_HANDLE_VALUE; - -/****************************************************************************** -* -* NAME -* File -* -* DESCRIPTION -* Default constructor -* -* INPUTS -* NONE -* -* RETURN -* NONE -* -******************************************************************************/ - -File::File() - : mRights(Rights_ReadOnly), - mHandle(INVALID_HANDLE) - { - } - - -/****************************************************************************** -* -* NAME -* File -* -* DESCRIPTION -* Create a file instance with the specified name and access rights. -* -* INPUTS -* Name - Name of file -* Rights - Access rights -* -* RETURN -* NONE -* -******************************************************************************/ - -File::File(const Char* name, ERights rights) - : mRights(rights), - mHandle(INVALID_HANDLE) - { - SetName(name); - } - - -/****************************************************************************** -* -* NAME -* File -* -* DESCRIPTION -* Create a file instance with the specified name and access rights. -* -* INPUTS -* Name - Name of file -* Rights - Access rights -* -* RETURN -* NONE -* -******************************************************************************/ - -File::File(const UString& name, ERights rights) - : mName(name), - mRights(rights), - mHandle(INVALID_HANDLE) - { - } - - -/****************************************************************************** -* -* NAME -* ~File -* -* DESCRIPTION -* Destroy a file representation. -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -File::~File() - { - // Close any open file. - Close(); - } - - -/****************************************************************************** -* -* NAME -* GetName -* -* DESCRIPTION -* Retrieve name of file -* -* INPUTS -* NONE -* -* RETURN -* Name - Name of file. -* -******************************************************************************/ - -const UString& File::GetName(void) const - { - return mName; - } - - -/****************************************************************************** -* -* NAME -* SetName -* -* DESCRIPTION -* Associate a filename to the file class. Any operations will be performed -* on the associated file with the specified name. -* -* INPUTS -* Filename - Name of file to associate. -* -* RESULT -* NONE -* -******************************************************************************/ - -void File::SetName(const UString& name) - { - mName = name; - } - - -/****************************************************************************** -* -* NAME -* GetRights -* -* DESCRIPTION -* Retrieve file access rights -* -* INPUTS -* NONE -* -* RETURN -* Rights - Current access rights for file -* -******************************************************************************/ - -ERights File::GetRights(void) const - { - return mRights; - } - - -/****************************************************************************** -* -* NAME -* SetRights -* -* DESCRIPTION -* Set file access rights -* -* INPUTS -* Rights - New rights -* -* RESULT -* NONE -* -******************************************************************************/ - -void File::SetRights(ERights rights) - { - mRights = rights; - } - - -/****************************************************************************** -* -* NAME -* IsAvailable -* -* DESCRIPTION -* Checks if the associated file is available for access. If the force -* flag is true then the file is check for availabilty until it is found -* or the proceedure is aborted via OnError(). -* -* INPUTS -* Force - Force file availability flag. -* -* RESULT -* Success - Success/Failure condition flag. -* -******************************************************************************/ - -bool File::IsAvailable(bool force) - { - // If the filename is invalid then the file is not available. - if (mName.Length() == 0) - { - return false; - } - - // If the file is open then it must be available. - if (IsOpen()) - { - return true; - } - - // If this is a forced open then go through the standard file open - // procedure so that the abort/retry logic gets called. - if (force == true) - { - Open(GetRights()); - Close(); - return true; - } - - char name[MAX_PATH]; - mName.ConvertToANSI(name, sizeof(name)); - - // Attempt to open the file - mHandle = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - // If the open failed then the file is not available. - if (mHandle == INVALID_HANDLE) - { - return false; - } - - // Close the file. - CloseHandle(mHandle); - mHandle = INVALID_HANDLE; - - return true; - } - - -/****************************************************************************** -* -* NAME -* IsOpen -* -* DESCRIPTION -* Check if the file is open. -* -* INPUTS -* NONE -* -* RETURN -* Opened - File is opened if true; otherwise false -* -******************************************************************************/ - -bool File::IsOpen(void) const - { - return ((mHandle != INVALID_HANDLE) ? true : false); - } - - -/****************************************************************************** -* -* NAME -* Open -* -* DESCRIPTION -* Opens the file associated with this file class. -* -* INPUTS -* Rights - Access rights for the file to open. -* -* RESULT -* Success - Success/Failure condition flag. -* -******************************************************************************/ - -File::EFileError File::Open(ERights rights) - { - // Close any currently opened file - Close(); - - // If the filename is invalid then there is no way to open the file. - if (mName.Length() == 0) - { - OnFileError(FileError_FNF, false); - return FileError_FNF; - } - - mRights = rights; - - char name[MAX_PATH]; - mName.ConvertToANSI(name, sizeof(name)); - - // Continue attempting open until successful or aborted. - for (;;) - { - switch (rights) - { - // Read only access - case Rights_ReadOnly: - mHandle = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - break; - - // Write only access - case Rights_WriteOnly: - mHandle = CreateFile(name, GENERIC_WRITE, 0, - NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - break; - - // Read and Write access - case Rights_ReadWrite: - mHandle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, - NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - break; - - // Unknown rights access violation - default: - OnFileError(FileError_Access, false); - return FileError_Access; - break; - } - - // Check for open failure - if (mHandle == INVALID_HANDLE) - { - PrintWin32Error("File::Open(%S)", mName.Get()); - - if (GetLastError() == ERROR_FILE_NOT_FOUND) - { - if (OnFileError(FileError_FNF, true) == false) - { - return FileError_FNF; - } - else - { - continue; - } - } - else - { - OnFileError(FileError_Open, false); - return FileError_Open; - } - } - - break; - } - - return FileError_None; - } - - -/****************************************************************************** -* -* NAME -* Open -* -* DESCRIPTION -* Associate a file then open that file. -* -* INPUTS -* Filename - Name of file to open. -* Rights - Access rights to file. -* -* RESULT -* Success - Success/Failure condition flag. -* -******************************************************************************/ - -File::EFileError File::Open(const UString& name, ERights rights) - { - // Associate the file then attempt to open it. - SetName(name); - return Open(rights); - } - - -/****************************************************************************** -* -* NAME -* Close -* -* DESCRIPTION -* Close access to the file. -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -void File::Close(void) - { - if (IsOpen()) - { - CloseHandle(mHandle); - mHandle = INVALID_HANDLE; - } - } - - -/****************************************************************************** -* -* NAME -* Create -* -* DESCRIPTION -* Creates a file on the local file system with a filename previously -* associated with a call to SetName(). -* -* INPUTS -* NONE -* -* RESULT -* Success - Success/Failure condition flag. -* -******************************************************************************/ - -File::EFileError File::Create(void) - { - // Close any previous handle - Close(); - - // Open the file for writing - EFileError error = Open(Rights_WriteOnly); - - if (error == FileError_None) - { - Close(); - } - - return error; - } - - -/****************************************************************************** -* -* NAME -* Delete -* -* DESCRIPTION -* Deletes the file on the local file system with the name previously -* associated by calling SetName(). -* -* INPUTS -* NONE -* -* RESULT -* Success - Success/Failure condition flag. -* -******************************************************************************/ - -File::EFileError File::Delete(void) - { - // Make sure the file is closed. - Close(); - - // The file must be available before it can be deleted. - if (IsAvailable() == false) - { - return FileError_FNF; - } - else - { - // Delete the file. Pass error conditions to OnError() - char name[MAX_PATH]; - mName.ConvertToANSI(name, sizeof(name)); - - if (!DeleteFile(name)) - { - OnFileError(FileError_Fault, false); - return FileError_Fault; - } - } - - return FileError_None; - } - - -/****************************************************************************** -* -* NAME -* Load -* -* DESCRIPTION -* The entire contents of the file is loaded into the specified buffer. -* -* INPUTS -* outBuffer - Buffer with file contents. -* -* RESULT -* -******************************************************************************/ - -File::EFileError File::Load(void*& outBuffer, UInt32& outSize) - { - outBuffer = NULL; - outSize = 0; - - // Enforce access control - if (mRights == Rights_WriteOnly) - { - OnFileError(FileError_Access, false); - return FileError_Access; - } - - EFileError result = FileError_None; - - // Open the file here if it isn't already. - bool openedHere = false; - - if (IsOpen() == false) - { - result = Open(GetRights()); - - if (result != FileError_None) - { - return result; - } - - // The file was opened here. - openedHere = true; - } - - // Get the size of the file - UInt32 size = GetFileSize(mHandle, NULL); - - if (size == 0xFFFFFFFF) - { - PrintWin32Error("File::Load(%S) - GetFileSize", mName.Get()); - result = FileError_Fault; - OnFileError(result, false); - } - - if (result == FileError_None) - { - // Allocate buffer to hold file contents - outBuffer = malloc(size); - outSize = size; - - // If allocation succeded then load file data. - if (outBuffer != NULL) - { - // Fill the buffer with the file contents - while (size > 0) - { - unsigned long bytesRead = 0; - - // Read in some bytes. - if (ReadFile(mHandle, outBuffer, size, &bytesRead, NULL) == 0) - { - result = FileError_Read; - - if (OnFileError(result, true) == false) - { - break; - } - - result = FileError_None; - } - - size -= bytesRead; - - if (bytesRead == 0) - { - break; - } - } - } - else - { - result = FileError_Nomem; - OnFileError(result, false); - } - } - - // Close the file if we opened it here. - if (openedHere == true) - { - Close(); - } - - return result; - } - - -/****************************************************************************** -* -* NAME -* Save -* -* DESCRIPTION -* Save data to the file. -* -* INPUTS -* Buffer - Pointer to data to write. -* Size - Number of bytes to write. -* -* RESULT -* -******************************************************************************/ - -File::EFileError File::Save(const void* buffer, UInt32 size) - { - // Enforce access control - if (mRights == Rights_ReadOnly) - { - OnFileError(FileError_Access, false); - return FileError_Access; - } - - EFileError result = FileError_None; - - // Open the file if it isn't already. - bool openedHere = false; - - if (IsOpen() == false) - { - result = Open(GetRights()); - - if (result == FileError_None) - { - openedHere = true; - } - } - - if (result == FileError_None) - { - SetMarker(0, EStreamFrom::FromStart); - - // Write the data to the file. - unsigned long bytesWritten = 0; - - if (WriteFile(mHandle, buffer, size, &bytesWritten, NULL) == 0) - { - result = FileError_Write; - OnFileError(result, false); - } - else - { - SetEndOfFile(mHandle); - } - } - - // If we opened the file here then we must close it here. - if (openedHere == true) - { - Close(); - } - - // Return the number of actual butes written. - return result; - } - - -/****************************************************************************** -* -* NAME -* OnFileError(Error, CanRetry) -* -* DESCRIPTION -* -* INPUTS -* Error - Error condition code. -* CanRetry - Retry allowed flag. If this is false then retrys are not -* permitted for this failure condition. -* -* RESULT -* Retry - Retry flag. -* -******************************************************************************/ -#pragma warning(disable:4100) - -bool File::OnFileError(EFileError error, bool) - { - #ifdef _DEBUG - const char* _errorNames[] = - { - "FileError_None", - "FileError_FNF", - "FileError_Access", - "FileError_Open", - "FileError_Read", - "FileError_Write", - "FileError_Seek", - "FileError_Nomem", - "FileError_Fault", - }; - - DebugPrint("File::OnFileError(%S) - %s\n", mName.Get(), _errorNames[error]); - #endif - - return false; - } - - -/****************************************************************************** -* -* NAME -* GetLength -* -* DESCRIPTION -* Get the size of the file and return it to the caller. -* -* INPUTS -* NONE -* -* RESULT -* Length of the file in bytes. -* -******************************************************************************/ - -UInt32 File::GetLength(void) - { - // If the file is not open then it must be opened first. - bool openedHere = false; - - if (IsOpen() == false) - { - if (Open(GetRights()) != FileError_None) - { - return 0xFFFFFFFF; - } - - openedHere = true; - } - - UInt32 length = GetFileSize(mHandle, NULL); - - if (length == 0xFFFFFFFF) - { - OnFileError(FileError_Fault, false); - } - - // If the file was opened here then we need to close it. - if (openedHere == true) - { - Close(); - } - - return length; - } - - -/****************************************************************************** -* -* NAME -* SetLength -* -* DESCRIPTION -* Set the length of the streamable file. -* -* INPUTS -* Length - Length of stream in bytes -* -* RESULT -* NONE -* -******************************************************************************/ - -void File::SetLength(UInt32 length) - { - // Get the current file position - UInt32 position = SetFilePointer(mHandle, 0, NULL, FILE_CURRENT); - - // Extend the file size by positioning the Win32 file pointer to the - // specified location then setting the end of file. - SetFilePointer(mHandle, length, NULL, FILE_BEGIN); - SetEndOfFile(mHandle); - - // Restore file position - SetFilePointer(mHandle, position, NULL, FILE_BEGIN); - } - - -/****************************************************************************** -* -* NAME -* GetMarker -* -* DESCRIPTION -* Returns the current position in the file stream. -* -* INPUTS -* NONE -* -* RESULT -* Current position in file -* -******************************************************************************/ - -UInt32 File::GetMarker(void) - { - return SetFilePointer(mHandle, 0, NULL, FILE_CURRENT); - } - - -/****************************************************************************** -* -* NAME -* SetMarker -* -* DESCRIPTION -* Position the marker within the file stream. -* -* INPUTS -* Offset - Offset to adjust marker by -* From - -* -* RESULT -* NONE -* -******************************************************************************/ - -void File::SetMarker(Int32 offset, EStreamFrom from) - { - // The file must be open before we can seek into it. - if (IsOpen() == false) - { - OnFileError(FileError_Seek, false); - } - else - { - unsigned long dir; - - switch (from) - { - default: - case Stream::FromStart: - dir = FILE_BEGIN; - break; - - case Stream::FromMarker: - dir = FILE_CURRENT; - break; - - case Stream::FromEnd: - dir = FILE_END; - break; - } - - offset = SetFilePointer(mHandle, offset, NULL, dir); - - if (offset == 0xFFFFFFFF) - { - OnFileError(FileError_Seek, false); - } - } - } - - -/****************************************************************************** -* -* NAME -* AtEnd -* -* DESCRIPTION -* Test if at the end of stream. -* -* INPUTS -* NONE -* -* RESULT -* End - True if at end; otherwise False. -* -******************************************************************************/ - -bool File::AtEnd(void) - { - return (GetMarker() >= GetLength()); - } - - -/****************************************************************************** -* -* NAME -* GetBytes -* -* DESCRIPTION -* Retrieve an arbitrary number of bytes from the file stream. -* -* INPUTS -* Buffer - Pointer to buffer to receive data -* Bytes - Number of bytes to read -* -* RESULT -* Read - Number of bytes actually read. -* -******************************************************************************/ - -UInt32 File::GetBytes(void* ptr, UInt32 bytes) - { - // Parameter check; Null pointers are bad! - assert(ptr != NULL); - - // Enforce rights control - if (GetRights() == Rights_WriteOnly) - { - OnFileError(FileError_Access, false); - return 0; - } - - // Open the file if it isn't already - if (IsOpen() == false) - { - if (Open(GetRights()) != FileError_None) - { - return 0; - } - } - - // Zero total bytes read count - UInt32 totalRead = 0; - UInt32 bytesToRead = bytes; - - while (bytesToRead > 0) - { - unsigned long read; - - if (ReadFile(mHandle, ptr, bytesToRead, &read, NULL) == 0) - { - if (OnFileError(FileError_Read, true) == false) - { - return 0; - } - } - - // End of file condition? - if (read == 0) - { - break; - } - - // Adjust counts - bytesToRead -= read; - totalRead += read; - } - - return totalRead; - } - - -/****************************************************************************** -* -* NAME -* PutBytes(Buffer, Bytes) -* -* DESCRIPTION -* Write an arbitrary number of bytes to the stream -* -* INPUTS -* Buffer - Pointer to buffer containing data to write -* Bytes - Number of bytes to transfer -* -* RESULT -* Actual number of bytes written -* -******************************************************************************/ - -UInt32 File::PutBytes(const void* ptr, UInt32 bytes) - { - // Parameter check; Null pointers are bad! - assert(ptr != NULL); - - // Enforce access control - if (GetRights() == Rights_ReadOnly) - { - OnFileError(FileError_Access, false); - return 0; - } - - // The file must already be open. - if (IsOpen() == false) - { - if (Open(GetRights()) != FileError_None) - { - return 0; - } - } - - // Zero total bytes written count - UInt32 totalWritten = 0; - UInt32 bytesToWrite = bytes; - - while (bytesToWrite > 0) - { - unsigned long written; - - if (WriteFile(mHandle, ptr, bytes, &written, NULL) == 0) - { - if (OnFileError(FileError_Write, true) == false) - { - return 0; - } - } - - bytesToWrite -= written; - totalWritten += written; - } - - return totalWritten; - } - - -/****************************************************************************** -* -* NAME -* PeekBytes(Buffer, Bytes) -* -* DESCRIPTION -* Retrieve bytes from the stream without moving the position marker. -* -* INPUTS -* Buffer - Pointer to buffer to receive data -* Bytes - Number of bytes to retrieve -* -* RESULT -* Actual number of bytes transfered -* -******************************************************************************/ - -UInt32 File::PeekBytes(void* ptr, UInt32 bytes) - { - // Parameter check; NULL pointers are bad! - assert(ptr != NULL); - - // Get current position - UInt32 pos = GetMarker(); - - // Get bytes - UInt32 bytesPeeked = GetBytes(ptr, bytes); - - // Restore previous position - SetMarker(pos, Stream::FromStart); - - return bytesPeeked; - } - - -/****************************************************************************** -* -* NAME -* -* DESCRIPTION -* -* INPUTS -* -* RESULT -* -******************************************************************************/ - -void File::Flush(void) - { - } diff --git a/Generals/Code/Tools/Launcher/Toolkit/Storage/File.h b/Generals/Code/Tools/Launcher/Toolkit/Storage/File.h deleted file mode 100644 index 3f84c529fd..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Storage/File.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* File definitions (Windows) -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -****************************************************************************/ - -#ifndef FILE_H -#define FILE_H - -#include -#include "Stream.h" -#include "Rights.h" -#include -#include - -class File : public Stream - { - public: - // File Error conditions - typedef enum - { - FileError_None = 0, - FileError_FNF, - FileError_Access, - FileError_Open, - FileError_Read, - FileError_Write, - FileError_Seek, - FileError_Nomem, - FileError_Fault, - } EFileError; - - //! Default constructor - Create an unassociated File - File(); - - //! Name constructor - Create a File with an associated name - File(const Char* name, ERights rights = Rights_ReadOnly); - File(const UString& name, ERights rights = Rights_ReadOnly); - - //! Destructor - virtual ~File(); - - //! Retrieve name of file - const UString& GetName(void) const; - - //! Associate a name to the file - virtual void SetName(const UString& name); - - //! Retrieve file access rights - virtual ERights GetRights(void) const; - - //! Set file access rights - virtual void SetRights(ERights rights); - - //! Check if the file is available - virtual bool IsAvailable(bool force = false); - - //! Check if te file is open - virtual bool IsOpen(void) const; - - //! Open the file for access. - virtual EFileError Open(ERights rights); - - //! Open the file with the associated name for access - virtual EFileError Open(const UString& name, ERights rights); - - //! Close the file - virtual void Close(void); - - //! Create a new file - virtual EFileError Create(void); - - //! Delete an existing file - virtual EFileError Delete(void); - - //! Load the file into memory - virtual EFileError Load(void*& outBuffer, UInt32& outSize); - - //! Write file data - virtual EFileError Save(const void* buffer, UInt32 size); - - //! Error handling hook - virtual bool OnFileError(EFileError error, bool canRetry); - - //----------------------------------------------------------------------- - // STREAM INTERFACE - //----------------------------------------------------------------------- - - //! Get the length of the file - virtual UInt32 GetLength(void); - - //! Set the length of the file - virtual void SetLength(UInt32 length); - - //! Get file position marker - virtual UInt32 GetMarker(void); - - //! Set file position marker - virtual void SetMarker(Int32 offset, EStreamFrom from); - - //! End of file test - virtual bool AtEnd(void); - - //! Read bytes from the file - virtual UInt32 GetBytes(void* ptr, UInt32 bytes); - - //! Write bytes to the file - virtual UInt32 PutBytes(const void* ptr, UInt32 bytes); - - //! Read bytes from the file without marker adjustment - virtual UInt32 PeekBytes(void* ptr, UInt32 bytes); - - //! Flush the stream - virtual void Flush(void); - - private: - UString mName; - ERights mRights; - HANDLE mHandle; - static const HANDLE INVALID_HANDLE; - }; - -#endif // FILE_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Storage/Rights.h b/Generals/Code/Tools/Launcher/Toolkit/Storage/Rights.h deleted file mode 100644 index 2970a55a49..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Storage/Rights.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Access privilege definitions. -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -****************************************************************************/ - -#ifndef RIGHTS_H -#define RIGHTS_H - -// Access rights -typedef enum - { - Rights_ReadOnly = 0, - Rights_WriteOnly, - Rights_ReadWrite, - } ERights; - -#endif // RIGHTS_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Storage/Stream.h b/Generals/Code/Tools/Launcher/Toolkit/Storage/Stream.h deleted file mode 100644 index f1175a4f56..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Storage/Stream.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Base class for data streaming functionality -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -****************************************************************************/ - -#ifndef STREAM_H -#define STREAM_H - -#include - -class Stream - { - public: - // Stream marker positioning - typedef enum - { - FromStart = 0, - FromMarker, - FromEnd, - } EStreamFrom; - - //! Get the length of the stream - virtual UInt32 GetLength(void) = 0; - - //! Set the length of the stream - virtual void SetLength(UInt32 length) = 0; - - //! Get current position of stream marker - virtual UInt32 GetMarker(void) = 0; - - //! Set position of stream marker - virtual void SetMarker(Int32 offset, EStreamFrom from) = 0; - - //! End of stream test - virtual bool AtEnd(void) = 0; - - //! Retrieve a sequence of bytes. - virtual UInt32 GetBytes(void* ptr, UInt32 bytes) = 0; - - //! Write a sequence of bytes - virtual UInt32 PutBytes(const void* ptr, UInt32 bytes) = 0; - - //! Retrieve a sequence of bytes without advancing marker. - virtual UInt32 PeekBytes(void* ptr, UInt32 bytes) = 0; - - //! Flush the stream - virtual void Flush(void) = 0; - }; - -#endif // STREAM_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/RefCounted.h b/Generals/Code/Tools/Launcher/Toolkit/Support/RefCounted.h deleted file mode 100644 index 8f7a8f4935..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/RefCounted.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Base class for reference counted classes. -* Use with the reference counting smart pointer RefPtr -* -* Release() is virtual. This helps support cached object and singletons -* -* PROGRAMMER -* Steven Clinard -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifndef REFCOUNTED_H -#define REFCOUNTED_H - -#include - -class RefCounted - { - protected: - RefCounted() - : mRefCount(0) - {} - - RefCounted(const RefCounted&) - : mRefCount(0) - {} - - inline const RefCounted& operator=(const RefCounted&) - {} - - virtual ~RefCounted() - {assert(mRefCount == 0);} - - // Should not be allowed by default - inline virtual bool operator==(const RefCounted&) const - {return false;} - - inline bool operator!=(const RefCounted&) const - {return false;} - - // Add reference - inline void AddReference(void) - {++mRefCount;} - - // Release reference - inline virtual void Release(void) - {if (--mRefCount == 0) delete this;} - - inline int ReferenceCount(void) const - {return mRefCount;} - - private: - friend class RefPtrBase; - - unsigned int mRefCount; - }; - -#endif // REFCOUNTED_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/RefPtr.h b/Generals/Code/Tools/Launcher/Toolkit/Support/RefPtr.h deleted file mode 100644 index 00b51e7351..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/RefPtr.h +++ /dev/null @@ -1,361 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* RefPtr<> and RefPtrConst<> are const-friendly, polymorphic reference -* counting smart pointers. -* -* The pointed-to class must be derived from RefCount. -* -* RefPtr replaces X* -* RefPtrConst replaces const X* -* -* Dynamic_Cast replaces dynamic_cast and dynamic_cast -* Reinterpret_Cast replaces reinterpret_cast and reinterpret_cast -* Const_Cast replaces const_cast and const_cast -* -* IsValid() replaces (x != NULL) -* -* Member function Attach() or assigning RefPtr() will NULL a pointer. -* -* Generally, RefPtr<> and RefPtrConst<> behave like their raw pointer -* counterparts, except of course they are reference counted and will delete -* the pointed-to object when the last reference is lost. The major -* syntatical differences are the use of RefPtrConst<> to represent a pointer -* to a constant object (I found it impossible to represent this within rc_ptr) -* and the use of the upper-case cast functions (it is not possible to overload -* these built-in functions). -* -* An explicit goal of this class is to completely avoid the "new" and "delete" -* operators in client code. The constructors for these pointers are private; -* they are friends of the pointed-to class. This forces the use of Factory -* Method functions (or similar) in the pointed-to class. Pointed-to classes -* should make the constructor protected or private to disallow clients from -* creating an instance with "new". If this is done, it becomes very difficult -* for the client to accidentally leak objects and/or misuse the pointed-to -* class or the reference counting pointers. -* -* PROGRAMMER -* Steven Clinard -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifndef REFPTR_H -#define REFPTR_H - -#include "Visualc.h" -#include "RefCounted.h" -#include -#include - -template class RefPtr; -template class RefPtrConst; - -class RefPtrBase - { - public: - inline bool operator==(const RefPtrBase& rhs) const - {return (mRefObject == rhs.mRefObject);} - - inline bool operator!=(const RefPtrBase& rhs) const - {return !operator==(rhs);} - - inline bool IsValid(void) const - {return (mRefObject != NULL);} - - inline void Detach(void) - { - if (IsValid()) - { - mRefObject->Release(); - mRefObject = NULL; - } - } - - protected: - RefPtrBase() - : mRefObject(NULL) - {} - - RefPtrBase(RefCounted* object) - : mRefObject(object) - { - assert((mRefObject == NULL) || (mRefObject->mRefCount == 0)); - - if (IsValid()) - { - mRefObject->AddReference(); - } - } - - RefPtrBase(const RefPtrBase& object) - : mRefObject(object.mRefObject) - { - assert(false); // why is this being called? - - if (IsValid()) - { - mRefObject->AddReference(); - } - } - - virtual ~RefPtrBase() - {Detach();} - - const RefPtrBase& operator=(const RefPtrBase&); - - inline RefCounted* const GetRefObject(void) - {return mRefObject;} - - inline const RefCounted* const GetRefObject(void) const - {return mRefObject;} - - inline void Attach(RefCounted* object) - { - // If objects are different - if (object != mRefObject) - { - // Add reference to new object - if (object != NULL) - { - object->AddReference(); - } - - // Release reference to old object - Detach(); - - // Assign new object - mRefObject = object; - } - } - - private: - RefCounted* mRefObject; - - template - friend RefPtr Dynamic_Cast(RefPtrBase&); - - template - friend RefPtr Reinterpret_Cast(RefPtrBase&); - }; - - -template class RefPtr - : public RefPtrBase - { - public: - RefPtr() - : RefPtrBase() - {} - - template - RefPtr(const RefPtr& derived) - : RefPtrBase() - { - Attach(const_cast(derived.ReferencedObject())); - } - - RefPtr(const RefPtr& object) - : RefPtrBase() - { - Attach(const_cast(object.ReferencedObject())); - } - - virtual ~RefPtr() - {} - - template - inline const RefPtr& operator=(const RefPtr& derived) - { - Attach(const_cast(derived.ReferencedObject())); - return *this; - } - - inline const RefPtr& operator=(const RefPtr& object) - { - Attach(const_cast(object.ReferencedObject())); - return *this; - } - - inline Type& operator*() const - { - assert(IsValid()); - return *const_cast(ReferencedObject()); - } - - inline Type* const operator->() const - { - assert(IsValid()); - return const_cast(ReferencedObject()); - } - - // These are public mostly because I can't seem to declare rc_ptr as a friend - inline Type* const ReferencedObject(void) - {return reinterpret_cast(GetRefObject());} - - inline const Type* const ReferencedObject(void) const - {return reinterpret_cast(GetRefObject());} - - RefPtr(Type* object) - : RefPtrBase() - { - Attach(object); - } - - inline const RefPtr& operator=(Type* object) - { - Attach(object); - return *this; - } - - private: - friend RefPtr Dynamic_Cast(RefPtrBase&); - friend RefPtr Reinterpret_Cast(RefPtrBase&); - friend RefPtr Const_Cast(RefPtrConst&); - }; - - -template class RefPtrConst - : public RefPtrBase - { - public: - RefPtrConst() - : RefPtrConst() - {} - - template - RefPtrConst(const RefPtr& derived) - : RefPtrBase() - { - Attach(derived.ReferencedObject()); - } - - RefPtrConst(const RefPtr& object) - : RefPtrBase() - { - Attach(const_cast(object.ReferencedObject())); - } - - template - RefPtrConst(const RefPtrConst& derived) - : RefPtrBase() - { - Attach(derived.ReferencedObject()); - } - - RefPtrConst(const RefPtrConst& object) - : RefPtrBase() - { - Attach(object.ReferencedObject()); - } - - template - inline const RefPtrConst& operator=(const RefPtr& derived) - { - Attach(derived.ReferencedObject()); - return *this; - } - - inline const RefPtrConst& operator=(const RefPtr& object) - { - Attach(object.ReferencedObject()); - return *this; - } - - template - inline const RefPtrConst& operator=(const RefPtrConst& derived) - { - Attach(derived.ReferencedObject()); - return *this; - } - - inline const RefPtrConst& operator=(const RefPtrConst& object) - { - Attach(object.ReferencedObject()); - return *this; - } - - virtual ~RefPtrConst() - {} - - inline const Type& operator*() const - { - assert(IsValid()); - return *ReferencedObject(); - } - - inline const Type* const operator->() const - { - assert(IsValid()); - return ReferencedObject(); - } - - // This is public mostly because I can't seem to declare rc_ptr as a friend - inline const Type* const ReferencedObject() const - {return reinterpret_cast(GetRefObject());} - - RefPtrConst(const Type* object) - : RefPtrBase() - { - Attach(object); - } - - const RefPtrConst& operator=(const Type* object) - { - Attach(object); - } - }; - - -template -RefPtr Dynamic_Cast(RefPtrBase& base) - { - RefPtr derived; - derived.Attach(base.GetRefObject()); - return derived; - } - - -template -RefPtr Reinterpret_Cast(RefPtrBase& rhs) - { - RefPtr object; - object.Attach(rhs.GetRefObject()); - return object; - } - - -template -RefPtr Const_Cast(RefPtrConst& rhs) - { - RefPtr object; - object.Attach(rhs.ReferencedObject()); - return object; - } - -#endif // RC_PTR_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/StringConvert.cpp b/Generals/Code/Tools/Launcher/Toolkit/Support/StringConvert.cpp deleted file mode 100644 index e4a0d62303..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/StringConvert.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Perform ANSI <-> Unicode string conversions -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#include "StringConvert.h" -#include "UString.h" -#include -#include -#include - -/****************************************************************************** -* -* NAME -* UStringToANSI -* -* DESCRIPTION -* Convert UString to an ANSI string -* -* INPUTS -* String - String to convert -* Buffer - Pointer to buffer to receive conversion. -* BufferLength - Length of buffer -* -* RESULT -* ANSI - Pointer to ANSI string -* -******************************************************************************/ - -Char* UStringToANSI(const UString& string, Char* buffer, UInt bufferLength) - { - return UnicodeToANSI(string.Get(), buffer, bufferLength); - } - - -/****************************************************************************** -* -* NAME -* UnicodeToANSI -* -* DESCRIPTION -* Convert Unicode string to an ANSI string -* -* INPUTS -* String - Unicode string to convert -* Buffer - Pointer to buffer to receive conversion. -* BufferLength - Length of buffer -* -* RESULT -* ANSI - Pointer to ANSI string -* -******************************************************************************/ - -Char* UnicodeToANSI(const WChar* string, Char* buffer, UInt bufferLength) - { - if ((string == NULL) || (buffer == NULL)) - { - return NULL; - } - - #ifdef _DEBUG - int result = - #endif - WideCharToMultiByte(CP_ACP, 0, string, -1, buffer, bufferLength, - NULL, NULL); - - #ifdef _DEBUG - if (result == 0) - { - PrintWin32Error("ConvertToANSI() Failed"); - assert(false); - } - #endif - - return buffer; - } diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/StringConvert.h b/Generals/Code/Tools/Launcher/Toolkit/Support/StringConvert.h deleted file mode 100644 index 64bb0c8da5..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/StringConvert.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* ANSI <-> Unicode string conversions -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifndef STRINGCONVERT_H -#define STRINGCONVERT_H - -#include "UTypes.h" - -class UString; - -Char* UStringToANSI(const UString& string, Char* buffer, UInt bufferLength); -Char* UnicodeToANSI(const WChar* string, Char* buffer, UInt bufferLength); - -#endif // STRINGCONVERT_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/UString.cpp b/Generals/Code/Tools/Launcher/Toolkit/Support/UString.cpp deleted file mode 100644 index 0bb2afb29b..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/UString.cpp +++ /dev/null @@ -1,1335 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* String management class (Unicode) -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#include "Visualc.h" -#include "UString.h" -#include "StringConvert.h" -#include -#include -#include - -// Convert character to lowercase -template T CharToLower(const T ch) - { - if ((ch >= (T)'A') && (ch <= (T)'Z')) - { - return (ch + 32); - } - - return ch; - } - -// Convert character to uppercase -template T CharToUpper(const T ch) - { - if ((ch >= (T)'a') && (ch <= (T)'z')) - { - return (ch - 32); - } - - return ch; - } - - -// Check if character is one of the specified characters -templatebool IsCharacter(WChar ch, const T* oneOf) - { - assert(oneOf != NULL); - - int length = 0; - - while (oneOf[length] != 0) - { - length++; - } - - for (int index = 0; index < length; index++) - { - if (ch == (WChar)oneOf[index]) - { - return true; - } - } - - return false; - } - - -// Strip all left side characters that are trim chars -template bool StripLeft(WChar* string, const T* trimChars) - { - // Strip leading trim characters from the string. - WChar* start = string; - - while ((*start != 0) && IsCharacter(*start, trimChars)) - { - start++; - } - - if (start != string) - { - wcscpy(string, start); - } - - return true; - } - - -// Strip all right side characters that are trim chars -template bool StripRight(WChar* string, const T* trimChars) - { - int length = wcslen(string) - 1; - int index = length; - - while (index >= 0) - { - if (!IsCharacter(string[index], trimChars)) - { - break; - } - - string[index] = 0; - index--; - } - - return (index != length); - } - - -/****************************************************************************** -* -* NAME -* UString::UString - Default constructor -* -* DESCRIPTION -* Create a new empty UString. -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -UString::UString() - : mData(NULL), - mCapacity(0) - { - } - - -/****************************************************************************** -* -* NAME -* UString::UString - Capacity contructor -* -* DESCRIPTION -* Create a new empty UString with the specified capacity. -* -* INPUTS -* Capacity - Number of characters to allocated to string. -* -* RESULT -* NONE -* -******************************************************************************/ - -UString::UString(UInt capacity) - : mData(NULL), - mCapacity(0) - { - AllocString(capacity); - } - - -/****************************************************************************** -* -* NAME -* UString::UString - ANSI string literal constructor -* -* DESCRIPTION -* Create a new UString from an ANSI string literal -* -* INPUTS -* String - Pointer to a NULL terminated ANSI string -* -* RESULT -* NONE -* -******************************************************************************/ - -UString::UString(const Char* s) - : mData(NULL), - mCapacity(0) - { - Copy(s); - } - - -/****************************************************************************** -* -* NAME -* UString::UString - UNICODE string literal constructor -* -* DESCRIPTION -* Create a new UString from a UNICODE string literal -* -* INPUTS -* String - Pointer to a NULL terminated UNICODE string -* -* RESULT -* NONE -* -******************************************************************************/ - -UString::UString(const WChar* ws) - : mData(NULL), - mCapacity(0) - { - Copy(ws); - } - - -/****************************************************************************** -* -* NAME -* UString::UString - Copy constructor -* -* DESCRIPTION -* Create a new UString from another UString -* -* INPUTS -* String - Reference to UString to copy -* -* RESULT -* NONE -* -******************************************************************************/ - -UString::UString(const UString& s) - : mData(NULL), - mCapacity(0) - { - Copy(s); - } - - -/****************************************************************************** -* -* NAME -* UString::~UString - Destructor -* -* DESCRIPTION -* Destroy the object -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -UString::~UString() - { - if (mData != NULL) - { - delete mData; - } - } - - -/****************************************************************************** -* -* NAME -* UString::Length -* -* DESCRIPTION -* Retrieve the length of the string in characters. -* -* INPUTS -* NONE -* -* RESULT -* Length - Length of string -* -******************************************************************************/ - -UInt UString::Length(void) const - { - if (mData == NULL) - { - return 0; - } - - return wcslen(mData); - } - - -/****************************************************************************** -* -* NAME -* UString::Copy - ANSI string literal -* -* DESCRIPTION -* Copy ANSI string literal. -* -* INPUTS -* String - Pointer to ANSI string literal -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Copy(const Char* s) - { - assert(s != NULL); - UInt length = strlen(s); - - if (length == 0) - { - return; - } - - if (Capacity() < length) - { - AllocString(length); - } - - // Copy and convert ansi string to unicode - assert(Capacity() >= length); - WChar* wsPtr = mData; - const Char* sPtr = s; - - while (length-- > 0) - { - *wsPtr++ = (WChar)*sPtr++; - } - - *wsPtr = 0; - } - - -/****************************************************************************** -* -* NAME -* UString::Copy - Unicode string literal -* -* DESCRIPTION -* Copy a Unicode string literal -* -* INPUTS -* String - Pointer to UNICODE string literal -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Copy(const WChar* ws) - { - assert(ws != NULL); - UInt length = wcslen(ws); - - if (length == 0) - { - return; - } - - if (Capacity() < length) - { - AllocString(length); - } - - assert(Capacity() >= length); - wcscpy(mData, ws); - } - - -/****************************************************************************** -* -* NAME -* UString::Copy -* -* DESCRIPTION -* Copy string -* -* INPUTS -* String - Reference to UString -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Copy(const UString& s) - { - Copy(s.Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::Concat - ANSI string literal -* -* DESCRIPTION -* Concatenate an ANSI string literal to this string -* -* INPUTS -* String - Pointer to ANSI string literal -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Concat(const Char* s) - { - // Parameter check - assert(s != NULL); - - UInt length = Length(); - UInt additional = strlen(s); - UInt totalLength = (length + additional); - - // Resize the string if the combined size is to small - if (Capacity() < totalLength) - { - Resize(totalLength); - } - - // Concatenate and convert ansi string to unicode - WChar* wsPtr = &mData[length]; - const Char* sPtr = s; - - while (additional-- > 0) - { - *wsPtr++ = (WChar)*sPtr++; - } - - *wsPtr = 0; - } - - -/****************************************************************************** -* -* NAME -* UString::Concat - Unicode string literal -* -* DESCRIPTION -* Concatenate a Unicode string literal to this string -* -* INPUTS -* String - Pointer to UNICODE string literal -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Concat(const WChar* ws) - { - assert(ws != NULL); - UInt length = (Length() + wcslen(ws)); - - if (Capacity() < length) - { - Resize(length); - } - - wcscat(mData, ws); - } - - -/****************************************************************************** -* -* NAME -* UString::Concat -* -* DESCRIPTION -* Concatenate string -* -* INPUTS -* String - Reference to UString -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Concat(const UString& s) - { - Concat(s.Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::Compare - ANSI string literal -* -* DESCRIPTION -* Compare strings, returning a value representing their relationship. -* -* INPUTS -* String - String to compare against -* -* RESULT -* Relationship - < 0 String less than this. -* = 0 Strings identical -* > 0 String greater than this. -* -******************************************************************************/ - -Int UString::Compare(const Char* s) const - { - // If comparing string is NULL and this string is NULL then strings are equal, - // otherwise comparing string is less than this string. - if (s == NULL) - { - if (Get() == NULL) - { - return 0; - } - - return -1; - } - - // If this string is NULL then comparing string is greater - if (Get() == NULL) - { - return 1; - } - - // Compare each character - const WChar* ws = Get(); - Int index = 0; - - for (;;) - { - // Difference between characters - Int diff = ((WChar)s[index] - ws[index]); - - // If the difference is not zero then the characters differ - if (diff != 0) - { - return diff; - } - - // If the end of either string has been reached then terminate loop - if ((ws[index] == L'\0') || (s[index] == '\0')) - { - break; - } - - // Advance to next character - index++; - } - - return 0; - } - - -/****************************************************************************** -* -* NAME -* UString::Compare - Unicode string literal -* -* DESCRIPTION -* Compare strings, returning a value representing their relationship. -* -* INPUTS -* String - String to compare against -* -* RESULT -* Relationship - < 0 String less than this. -* = 0 Strings identical -* > 0 String greater than this. -* -******************************************************************************/ - -Int UString::Compare(const WChar* ws) const - { - return wcscmp(ws, Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::Compare -* -* DESCRIPTION -* Compare strings, returning a value representing their relationship. -* -* INPUTS -* String - String to compare against -* -* RESULT -* Relationship - < 0 String less than this. -* = 0 Strings identical -* > 0 String greater than this. -* -******************************************************************************/ - -Int UString::Compare(const UString& s) const - { - return Compare(s.Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::CompareNoCase - ANSI string literal -* -* DESCRIPTION -* Compare strings (case insensitive), returning a value representing their -* relationship. -* -* INPUTS -* String - String to compare against -* -* RESULT -* Relationship - < 0 String less than this. -* = 0 Strings identical -* > 0 String greater than this. -* -******************************************************************************/ - -Int UString::CompareNoCase(const Char* s) const - { - // If comparing string is NULL and this string is NULL then strings are - // equal, otherwise comparing string is less than this string. - if (s == NULL) - { - if (Get() == NULL) - { - return 0; - } - - return -1; - } - - // If this string is NULL then comparing string is greater. - if (Get() == NULL) - { - return 1; - } - - // Compare each character - const WChar* ws = Get(); - Int index = 0; - - for (;;) - { - // Convert to lowercase for compare - WChar sc = (WChar)CharToLower(s[index]); - WChar wc = CharToLower(ws[index]); - - // Difference between characters. - Int diff = (sc - wc); - - // If the difference is not zero then the characters differ. - if (diff != 0) - { - return diff; - } - - // If the end of either string has been reached then terminate loop. - if ((ws[index] == L'\0') || (s[index] == '\0')) - { - break; - } - - // Advance to next character - index++; - } - - return 0; - } - - -/****************************************************************************** -* -* NAME -* UString::CompareNoCase - Unicode string literal -* -* DESCRIPTION -* Compare strings (case insensitive), returning a value representing their -* relationship. -* -* INPUTS -* String - String to compare against -* -* RESULT -* Relationship - < 0 String less than this. -* = 0 Strings identical -* > 0 String greater than this. -* -******************************************************************************/ - -Int UString::CompareNoCase(const WChar* ws) const - { - return wcsicmp(ws, Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::CompareNoCase -* -* DESCRIPTION -* Compare strings (case insensitive), returning a value representing their -* relationship. -* -* INPUTS -* String - String to compare against -* -* RESULT -* Relationship - < 0 String less than this. -* = 0 Strings identical -* > 0 String greater than this. -* -******************************************************************************/ - -Int UString::CompareNoCase(const UString& s) const - { - return CompareNoCase(s.Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::Find - ANSI character -* -* DESCRIPTION -* Find the first occurance of character -* -* INPUTS -* Char - ANSI character to search for -* -* RESULT -* Position - Position of character (-1 if not found) -* -******************************************************************************/ - -Int UString::Find(Char c) const - { - return Find((WChar)c); - } - - -/****************************************************************************** -* -* NAME -* UString::Find - Unicode character -* -* DESCRIPTION -* Find the first occurance of character -* -* INPUTS -* Char - Unicode character to search for. -* -* RESULT -* Position - Position of character (-1 if not found) -* -******************************************************************************/ - -Int UString::Find(WChar c) const - { - const WChar* ptr = wcschr(Get(), c); - - // Not found? - if (ptr == NULL) - { - return -1; - } - - return ((ptr - mData) / sizeof(WChar)); - } - - -/****************************************************************************** -* -* NAME -* UString::FindLast - ANSI character -* -* DESCRIPTION -* Find the last occurance of a character -* -* INPUTS -* Char - ANSI character -* -* RESULT -* Position - Position of character (-1 if not found) -* -******************************************************************************/ - -Int UString::FindLast(Char c) const - { - return FindLast((WChar)c); - } - - -/****************************************************************************** -* -* NAME -* UString::FindLast - Unicode character -* -* DESCRIPTION -* Find the last occurance of a character -* -* INPUTS -* Char - Unicode character -* -* RESULT -* Position - Position of character (-1 if not found) -* -******************************************************************************/ - -Int UString::FindLast(WChar c) const - { - assert(mData != NULL); - WChar* ptr = wcsrchr(mData, (WChar)c); - - // Not found? - if (ptr == NULL) - { - return -1; - } - - return ((ptr - mData) / sizeof(WChar)); - } - - -/****************************************************************************** -* -* NAME -* UString::SubString - ANSI string literal -* -* DESCRIPTION -* Find a substring -* -* INPUTS -* SubString - Substring to search for. -* -* RESULT -* -* -******************************************************************************/ - -UString UString::SubString(const Char* s) - { - assert(false); - assert(s != NULL); - return UString(""); - } - - -UString UString::SubString(const WChar* ws) - { - assert(false); - assert(ws != NULL); - return UString(""); - } - - -UString UString::SubString(const UString& s) - { - assert(false); - return SubString(s.mData); - } - - -/****************************************************************************** -* -* NAME -* UString::Left -* -* DESCRIPTION -* Extract left part of the string. -* -* INPUTS -* Count - Number of characters to extract -* -* RESULT -* Left - Extracted left part of the string -* -******************************************************************************/ - -UString UString::Left(UInt count) - { - assert(false); - - // If the count is zero then return an empty string. - if ((Length() == 0) || (count == 0)) - { - return UString(""); - } - - return UString(""); - } - - -/****************************************************************************** -* -* NAME -* UString::Middle -* -* DESCRIPTION -* Extract middle part of the string. -* -* INPUTS -* First - Position of first character -* Count - Number of characters to extract -* -* RESULT -* Middle - Extracted middle part of the string -* -******************************************************************************/ - -UString UString::Middle(UInt first, UInt count) - { - assert(false); - - // If the first character position is greater than the length of the string - // or the count is zero then return an empty string. - if ((Length() < first) || (count == 0)) - { - return UString(""); - } - - return UString(""); - } - - -/****************************************************************************** -* -* NAME -* UString::Right -* -* DESCRIPTION -* Extract right part of the string. -* -* INPUTS -* Count - Number of characters to extract -* -* RESULT -* Right - Extracted right part of the string -* -******************************************************************************/ - -UString UString::Right(UInt count) - { - UInt length = Length(); - - // If the count is zero then return an empty string. - if ((length == 0) || (count == 0)) - { - return UString(""); - } - - const WChar* ptr = Get(); - UInt pos = (length - count); - - return UString(ptr[pos]); - } - - -/****************************************************************************** -* -* NAME -* UString::ToUpper -* -* DESCRIPTION -* Convert string to uppercase -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::ToUpper(void) - { - if (mData != NULL) - { - wcsupr(mData); - } - } - - -/****************************************************************************** -* -* NAME -* UString::ToLower -* -* DESCRIPTION -* Convert string to lowercase -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::ToLower(void) - { - if (mData != NULL) - { - wcslwr(mData); - } - } - - -/****************************************************************************** -* -* NAME -* UString::Reverse -* -* DESCRIPTION -* Reverse characters of string -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::Reverse(void) - { - if (mData != NULL) - { - wcsrev(mData); - } - } - - -/****************************************************************************** -* -* NAME -* UString::Trim -* -* DESCRIPTION -* Remove leading and trailing characters from string. -* -* INPUTS -* TrimChars - Characters to trim -* -* RESULT -* Removed - True if any characters removed -* -******************************************************************************/ - -bool UString::Trim(const Char* trimChars) - { - bool leftRemoved = TrimLeft(trimChars); - bool rightRemoved = TrimRight(trimChars); - return (leftRemoved || rightRemoved); - } - - -bool UString::Trim(const WChar* trimChars) - { - bool leftRemoved = TrimLeft(trimChars); - bool rightRemoved = TrimRight(trimChars); - return (leftRemoved || rightRemoved); - } - - -bool UString::Trim(const UString& trimChars) - { - bool leftRemoved = TrimLeft(trimChars); - bool rightRemoved = TrimRight(trimChars); - return (leftRemoved || rightRemoved); - } - - -/****************************************************************************** -* -* NAME -* UString::TrimLeft -* -* DESCRIPTION -* Remove characters from left side of string -* -* INPUTS -* TrimChars - Characters to trim -* -* RESULT -* Removed - True if any characters removed -* -******************************************************************************/ - -bool UString::TrimLeft(const Char* trimChars) - { - if ((trimChars == NULL) || (strlen(trimChars) == 0)) - { - return false; - } - - return StripLeft(mData, trimChars); - } - - -bool UString::TrimLeft(const WChar* trimChars) - { - if ((trimChars == NULL) || (wcslen(trimChars) == 0)) - { - return false; - } - - return StripLeft(mData, trimChars); - } - - -bool UString::TrimLeft(const UString& trimChars) - { - return TrimLeft(trimChars.Get()); - } - - -/****************************************************************************** -* -* NAME -* UString::TrimRight -* -* DESCRIPTION -* Remove characters from right side of string -* -* INPUTS -* TrimChars - Characters to trim -* -* RESULT -* Removed - True if any characters removed -* -******************************************************************************/ - -bool UString::TrimRight(const Char* trimChars) - { - if ((trimChars == NULL) || (strlen(trimChars) == 0)) - { - return false; - } - - return StripRight(mData, trimChars); - } - - -bool UString::TrimRight(const WChar* trimChars) - { - if ((trimChars == NULL) || (wcslen(trimChars) == 0)) - { - return false; - } - - return StripRight(mData, trimChars); - } - - -bool UString::TrimRight(const UString& trimChars) - { - return TrimRight(trimChars.mData); - } - - -/****************************************************************************** -* -* NAME -* UString::ConvertToANSI -* -* DESCRIPTION -* Convert the string to ANSI string -* -* INPUTS -* Buffer - Buffer to convert into -* Length - Maximum length of buffer -* -* RESULT -* NONE -* -******************************************************************************/ - -void UString::ConvertToANSI(Char* buffer, UInt bufferLength) const - { - UStringToANSI(*this, buffer, bufferLength); - } - - -/****************************************************************************** -* -* NAME -* UString::Size -* -* DESCRIPTION -* Retrieve the size of the string in bytes -* -* INPUTS -* NONE -* -* RESULT -* Size - Size of string in bytes -* -******************************************************************************/ - -UInt UString::Size(void) const - { - if (mData == NULL) - { - return 0; - } - - return ((Length() + 1) * sizeof(WChar)); - } - - -/****************************************************************************** -* -* NAME -* UString::Capacity -* -* DESCRIPTION -* Retrieve the capacity (maximum number of characters) of the string. -* -* INPUTS -* NONE -* -* RESULT -* Capacity - Maximum number of characters that string can hold. -* -******************************************************************************/ - -UInt UString::Capacity(void) const - { - return mCapacity; - } - - -/****************************************************************************** -* -* NAME -* UString::Resize -* -* DESCRIPTION -* Resize the string capacity. -* -* INPUTS -* NewSize - Size to resize string to. -* -* RESULT -* Success - True if successful; otherwise false -* -******************************************************************************/ - -bool UString::Resize(UInt size) - { - // Allocate new storage - assert(size > 0); - WChar* data = new WChar[size + 1]; - assert(data != NULL); - - if (data == NULL) - { - return false; - } - - // Copy existing string into new storage buffer - if (mData != NULL) - { - UInt minSize = __min(Capacity(), size); - wcsncpy(data, mData, minSize); - data[minSize] = 0; - delete mData; - } - - // Set new storage - mData = data; - mCapacity = size; - - return true; - } - - -/****************************************************************************** -* -* NAME -* UString::AllocString -* -* DESCRIPTION -* Allocate string storage -* -* INPUTS -* Size - Number of characters -* -* RESULT -* Success - True if allocate successful; otherwise false -* -******************************************************************************/ - -bool UString::AllocString(UInt size) - { - WChar* data = new WChar[size + 1]; - assert(data != NULL); - - if (data == NULL) - { - return false; - } - - data[0] = 0; - - if (mData != NULL) - { - delete mData; - } - - mData = data; - mCapacity = size; - - return true; - } diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/UString.h b/Generals/Code/Tools/Launcher/Toolkit/Support/UString.h deleted file mode 100644 index cd1c8e90cf..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/UString.h +++ /dev/null @@ -1,239 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* String management class (Unicode) -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifndef USTRING_H -#define USTRING_H - -#include "UTypes.h" -#include "RefCounted.h" - -class UString - : public RefCounted - { - public: - // Constructors - UString(); - UString(UInt capacity); - UString(const Char* s); - UString(const WChar* ws); - UString(const UString& s); - virtual ~UString(); - - //! Get the length of the string - UInt Length(void) const; - - //! Copy string - void Copy(const Char* s); - void Copy(const WChar* ws); - void Copy(const UString& s); - - //! Concatenate string - void Concat(const Char* s); - void Concat(const WChar* ws); - void Concat(const UString& s); - - //! Compare strings - Int Compare(const Char* s) const; - Int Compare(const WChar* s) const; - Int Compare(const UString& s) const; - - //! Compare strings not case-sensitive - Int CompareNoCase(const Char* s) const; - Int CompareNoCase(const WChar* ws) const; - Int CompareNoCase(const UString& s) const; - - //! Find the first occurance of character - Int Find(Char c) const; - Int Find(WChar wc) const; - - //! Find the last occurance of a character - Int FindLast(Char c) const; - Int FindLast(WChar c) const; - - //! Find a substring - UString SubString(const Char* s); - UString SubString(const WChar* ws); - UString SubString(const UString& s); - - //! Extract left part of the string - UString Left(UInt count); - - //! Extract middle part of the string. - UString Middle(UInt first, UInt count); - - //! Extract right part of the string. - UString Right(UInt count); - - //! Convert string to uppercase - void ToUpper(void); - - //! Convert string to lowercase - void ToLower(void); - - //! Reverse characters of string - void Reverse(void); - - //! Remove leading and trailing characters from string. - // Returns true if any characters removed - bool Trim(const Char* trimChars); - bool Trim(const WChar* trimChars); - bool Trim(const UString& trimChars); - - //! Remove characters from left side of string - // Returns true if any characters removed - bool TrimLeft(const Char* trimChars); - bool TrimLeft(const WChar* trimChars); - bool TrimLeft(const UString& trimChars); - - //! Remove characters from right side of string - // Returns true if any characters removed - bool TrimRight(const Char* trimChars); - bool TrimRight(const WChar* trimChars); - bool TrimRight(const UString& trimChars); - - // Convert string to ANSI - void ConvertToANSI(Char* buffer, UInt bufferLength) const; - - //! Get the size (in bytes) of the string. - UInt Size(void) const; - - //! Get the maximum number of characters this string can hold. - UInt Capacity(void) const; - - //! Resize the string - bool Resize(UInt size); - - const WChar* Get(void) const - {return (mData != NULL) ? mData : L"";} - - //! Assignment operator - UString operator=(const Char* s) - {Copy(s); return *this;}; - - UString operator=(const WChar* ws) - {Copy(ws); return *this;}; - - UString operator=(const UString& s) - {Copy(s); return *this;}; - - //! Addition operator (concatenate) - UString operator+(const Char* s) - {UString ns(*this); ns += s; return ns;} - - UString operator+(const WChar* ws) - {UString ns(*this); ns += ws; return ns;} - - UString operator+(const UString& s) - {UString ns(*this); ns += s; return ns;} - - UString operator+=(const Char* s) - {Concat(s); return *this;} - - UString operator+=(const WChar* ws) - {Concat(ws); return *this;} - - UString operator+=(const UString& s) - {Concat(s); return *this;} - - //! Equal operator (case sensitive compare) - bool operator==(const Char* s) - {return (Compare(s) == 0);} - - bool operator==(const WChar* ws) - {return (Compare(ws) == 0);} - - bool operator==(const UString& s) - {return (Compare(s) == 0);} - - bool operator!=(const Char* s) - {return (Compare(s) != 0);} - - bool operator!=(const WChar* ws) - {return (Compare(ws) != 0);} - - bool operator!=(const UString& s) - {return (Compare(s) != 0);} - - //! Less than operator (case sensitive compare) - bool operator<(const Char* s) - {return (Compare(s) == -1);} - - bool operator<(const WChar* ws) - {return (Compare(ws) == -1);} - - bool operator<(const UString& s) - {return (Compare(s) == -1);} - - bool operator<=(const Char* s) - {return (Compare(s) <= 0);} - - bool operator<=(const WChar* ws) - {return (Compare(ws) <= 0);} - - bool operator<=(const UString& s) - {return (Compare(s) <= 0);} - - //! Greater than operator (case sensitive compare) - bool operator>(const Char* s) - {return (Compare(s) == 1);} - - bool operator>(const WChar* ws) - {return (Compare(ws) == 1);} - - bool operator>(const UString& s) - {return (Compare(s) == 1);} - - bool operator>=(const Char* s) - {return (Compare(s) >= 0);} - - bool operator>=(const WChar* ws) - {return (Compare(ws) >= 0);} - - bool operator>=(const UString& s) - {return (Compare(s) >= 0);} - - // Conversion operator - operator const WChar*() const - {return Get();} - - private: - bool AllocString(UInt size); - - WChar* mData; - UInt mCapacity; - }; - -#endif // USTRING_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/UTypes.h b/Generals/Code/Tools/Launcher/Toolkit/Support/UTypes.h deleted file mode 100644 index d634007195..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/UTypes.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Generic user type definitions -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ - -#ifndef UTYPES_H -#define UTYPES_H - -//! Signed integer value -typedef int Int; - -//! Unsigned integer value -typedef unsigned int UInt; - -//! Signed 8bit value (-127 - 128) -typedef char Int8; - -//! Unsigned 8bit value (0 - 255) -typedef unsigned char UInt8; - -//! Signed 16bit value (-32767 - 32768) -typedef short Int16; - -//! Unsigned 16bit value (0 - 65535) -typedef unsigned short UInt16; - -//! Signed 32bit value -typedef long Int32; - -//! Unsigned 32bit value -typedef unsigned long UInt32; - -//! Signed character (ASCII) -typedef char Char; - -//! Unsigned character (ANSI) -typedef unsigned char UChar; - -//! Wide character (Unicode) -#if defined(_MSC_VER) && _MSC_VER < 1300 -typedef unsigned short WChar; -#else -typedef wchar_t WChar; -#endif - -//! 32bit floating point value -typedef float Float32; - -//! 64bit floating point value -typedef double Float64; - -//! Floating point value -typedef Float32 Float; - -//! TriState -typedef enum {OFF = false, ON = true, PENDING = -1} TriState; - -//! Empty pointer -#ifndef NULL -#define NULL (0L) -#endif - -#endif // UTYPES_H diff --git a/Generals/Code/Tools/Launcher/Toolkit/Support/Visualc.h b/Generals/Code/Tools/Launcher/Toolkit/Support/Visualc.h deleted file mode 100644 index c42086790e..0000000000 --- a/Generals/Code/Tools/Launcher/Toolkit/Support/Visualc.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************** -* -* FILE -* $Archive: $ -* -* DESCRIPTION -* Disable specific warnings generated by Microsoft Visual C++ 6.0 -* -* PROGRAMMER -* Denzil E. Long, Jr. -* $Author: $ -* -* VERSION INFO -* $Modtime: $ -* $Revision: $ -* -******************************************************************************/ -#pragma once - -#ifndef _VISUALC_H_ -#define _VISUALC_H_ - -#if defined(_MSC_VER) - -// "unreferenced inline function has been removed" -// Inline functions are used in headers and this warning will appear everywhere -// without explicitly being disabled. -#pragma warning(disable:4514) - -// "conversion from 'double' to 'float', possible loss of data" -// This occurs during non-constant floating point arithmetic. Since all floating -// point math is silently upcasted to doubles, it should silently downcast -// back to 'float' when complete -- hence this warning should not be displayed. -#pragma warning(disable:4244) - -// "overflow in floating-point constant arithmetic" -// This warning occurs even when there is no overflow. It occurs when a double -// is downcasted to a float during constant arithmetic (this is not worthy of -// a warning message). -#pragma warning(disable:4056) - -// "argument trunation from const double to float" -// This warning is of little use since the compiler uses doubles whenever -// possible, therfore this warning will appear frequently. It is similar to -// warning 4244 and is similarly irrelevant. -#pragma warning(disable:4305) - -// "'this' used in base member initializer list" -// Using "this" in a base member initializer is valid -- no need for this warning. -#pragma warning(disable:4355) - -// "typedef-name used as a synonym for class-name" -// This is by design and should not be a warning. -#pragma warning(disable:4097) - -// "function not inlined" -// This warning is typically useless. The inline keyword only serves as a -// suggestion to the compiler and it may or may not inline a function on a -// case by case basis. No need to be told of this. -#pragma warning(disable:4710) - -// "function selected for automatic inline expansion" -// There is no need to announce this with a warning message. -#pragma warning(disable:4711) - -// "identifier was truncated to 'number' characters in the debug information" -// The debugger cannot debug code with symbols longer than 255 characters. -// In the debugger, you cannot view, evaluate, update, or watch the truncated symbols. -#pragma warning(disable:4786) - -#endif // _MSC_VER -#endif // _VISUALC_H_ diff --git a/Generals/Code/Tools/Launcher/configfile.cpp b/Generals/Code/Tools/Launcher/configfile.cpp deleted file mode 100644 index 45c3062ca0..0000000000 --- a/Generals/Code/Tools/Launcher/configfile.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : configfile.cpp -Author : Neal Kettler -Start Date : June 9, 1997 -Last Update : June 17, 1997 - - -This class will read in a config file and store the key value pairs for -later access. This is a fairly simple class, the config file is assumed -to be of the form: - -#comment -key = value - -The value can then be retrieved as a string or an integer. The key on -the left is used for retrieval and it must be specified in uppercase -for the 'get' functions. E.g. getString("KEY",valWstring); -\***************************************************************************/ - -#include -#include -#include - -#include "configfile.h" - -static uint32 Wstring_Hash(Wstring &string); -static char *Eat_Spaces(char *string); - -ConfigFile::ConfigFile() : dictionary(Wstring_Hash) -{ } - -ConfigFile::~ConfigFile() -{ } - -// Read and parse the config file. The key value pairs will be stored -// for later access by the getString/getInt functions. -bit8 ConfigFile::readFile(FILE *in) -{ - char string[256]; - Wstring key; - Wstring value; - char *cptr; - - memset(string,0,256); - while (fgets(string,256,in)) - { - cptr=Eat_Spaces(string); - if ((*cptr==0)||(*cptr=='#')) // '#' signals a comment - continue; - if (strchr(cptr,'=')==NULL) // All config entries must have a '=' - continue; - key=cptr; - key.truncate('='); - key.removeSpaces(); // No spaces allowed in the key - key.toUpper(); // make key all caps - cptr=Eat_Spaces(strchr(cptr,'=')+1); // Jump to after the '=' - value=cptr; - value.truncate('\r'); - value.truncate('\n'); - dictionary.add(key,value); - } - return(TRUE); -} - -// Get a config entry as a string -bit8 ConfigFile::getString(Wstring &key,Wstring &value) -{ - return(dictionary.getValue(key,value)); -} - -// Get a config entry as a string -bit8 ConfigFile::getString(const char *key,Wstring &value) -{ - Wstring sKey; - sKey.set(key); - return(getString(sKey,value)); -} - -// Get a config entry as an integer -bit8 ConfigFile::getInt(Wstring &key,sint32 &value) -{ - Wstring svalue; - bit8 retval=dictionary.getValue(key,svalue); - if (retval==FALSE) - return(FALSE); - value=atol(svalue.get()); - return(TRUE); -} - -// Get a config entry as an integer -bit8 ConfigFile::getInt(const char *key,sint32 &value) -{ - Wstring sKey; - sKey.set(key); - return(getInt(sKey,value)); -} - - - -// Get a config entry as an integer -bit8 ConfigFile::getInt(Wstring &key,sint16 &value) -{ - Wstring svalue; - bit8 retval=dictionary.getValue(key,svalue); - if (retval==FALSE) - return(FALSE); - value=atoi(svalue.get()); - return(TRUE); -} - -// Get a config entry as an integer -bit8 ConfigFile::getInt(const char *key,sint16 &value) -{ - Wstring sKey; - sKey.set(key); - return(getInt(sKey,value)); -} - - - -/************* Static functions below **************/ - -// Given a Wstring, return a 32 bit integer that has a good numeric -// distributation for the purposes of indexing into a hash table. -static uint32 Wstring_Hash(Wstring &string) -{ - uint32 retval=0; - retval=string.length(); - for (uint32 i=0; i>24); // ROL 8 - } - return(retval); -} - -static char *Eat_Spaces(char *string) -{ - char *retval=string; - while (isspace(*retval)) - retval++; - return(retval); -} diff --git a/Generals/Code/Tools/Launcher/configfile.h b/Generals/Code/Tools/Launcher/configfile.h deleted file mode 100644 index d23f71b78f..0000000000 --- a/Generals/Code/Tools/Launcher/configfile.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : configfile.h -Author : Neal Kettler -Start Date : June 9, 1997 -Last Update : June 17, 1997 -\***************************************************************************/ - -#ifndef CONFIGFILE_HEADER -#define CONFIGFILE_HEADER - -#include "dictionary.h" -#include "wstring.h" - -class ConfigFile -{ - public: - ConfigFile(); - ~ConfigFile(); - bit8 readFile(IN FILE *config); - bit8 getString(IN Wstring &key,OUT Wstring &value); - bit8 getString(IN const char *key,OUT Wstring &value); - - bit8 getInt(IN Wstring &key,OUT sint32 &value); - bit8 getInt(IN const char *key,OUT sint32 &value); - - bit8 getInt(IN Wstring &key,OUT sint16 &value); - bit8 getInt(IN const char *key,OUT sint16 &value); - - private: - Dictionary dictionary; // stores the mappings from keys - // to value strings -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/dialog.cpp b/Generals/Code/Tools/Launcher/dialog.cpp deleted file mode 100644 index 5c6f6a7f48..0000000000 --- a/Generals/Code/Tools/Launcher/dialog.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Create the dialog used during the patching process. -// -#include"winblows.h" -#include"resource.h" -#include"loadbmp.h" -#include - -HWND PatchDialog; -BOOL CALLBACK Patch_Window_Proc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam); - -HWND Create_Patch_Dialog(void) -{ - PatchDialog=CreateDialog(Global_instance, MAKEINTRESOURCE(IDD_PATCHPROGRESS), - NULL, (DLGPROC)Patch_Window_Proc); - - ShowWindow(PatchDialog, SW_NORMAL); - SetForegroundWindow(PatchDialog); - return(PatchDialog); -} - -BOOL CALLBACK Patch_Window_Proc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) -{ - - static LoadBmp bmpLoader; - - switch(iMsg) { - case WM_INITDIALOG: - // progress bar - SendMessage(GetDlgItem(hwnd,IDC_PROGRESS2),PBM_SETRANGE, - 0,MAKELPARAM(0,100)); - SendMessage(GetDlgItem(hwnd,IDC_PROGRESS2),PBM_SETPOS,0,0); - SendMessage(GetDlgItem(hwnd,IDC_PROGRESS2),PBM_SETSTEP,10,0); - - bmpLoader.init("launcher.bmp",GetDlgItem(hwnd,IDC_SPLASH)); - return(TRUE); // True means windows handles focus issues - break; - case WM_PAINT: - bmpLoader.drawBmp(); - break; - case WM_COMMAND: - /* May want to add cancel later - switch(wParam) { - case IDCANCEL: - { - // do some stuff - return(TRUE); - } - default: - break; - } - default: - *************/ - break; - case WM_CLOSE: - DestroyWindow(hwnd); - PostQuitMessage(0); - exit(0); - break; - } - return(FALSE); -} \ No newline at end of file diff --git a/Generals/Code/Tools/Launcher/dialog.h b/Generals/Code/Tools/Launcher/dialog.h deleted file mode 100644 index 008bcd24f6..0000000000 --- a/Generals/Code/Tools/Launcher/dialog.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef DIALOG_HEADER -#define DIALOG_HEADER - -#include"winblows.h" -#include -HWND Create_Patch_Dialog(void); - -extern HWND PatchDialog; - -#endif diff --git a/Generals/Code/Tools/Launcher/dictionary.h b/Generals/Code/Tools/Launcher/dictionary.h deleted file mode 100644 index b42e875e20..0000000000 --- a/Generals/Code/Tools/Launcher/dictionary.h +++ /dev/null @@ -1,586 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : dictionary.h -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 - -This template file implements a hash dictionary. A hash dictionary is -used to quickly match a value with a key. This works well for very -large sets of data. A table is constructed that has some power of two -number of pointers in it. Any value to be put in the table has a hashing -function applied to the key. That key/value pair is then put in the -linked list at the slot the hashing function specifies. If everything -is working well, this is much faster than a linked list, but only if -your hashing function is good. -\****************************************************************************/ - -#ifndef DICTIONARY_HEADER -#define DICTIONARY_HEADER - -#include -#include -#include -#include - -#include "wstypes.h" -#include "wdebug.h" - -// Every entry in the hash dictionary must be an instance of the DNode -// template. 'K' and 'V' denote Key and Value. -template -class DNode -{ - public: - K key; - V value; - DNode *hashNext; -}; - -template -class Dictionary -{ - public: - Dictionary(uint32 (* hashFn)(K &key)); - ~Dictionary(); - - void clear(void); - bit8 add(IN K &key,IN V &value); - bit8 getValue(IN K &key, OUT V &value); - void print(IN FILE *out) const; - uint32 getSize(void) const; - uint32 getEntries(void) const; - bit8 contains(IN K &key); - bit8 updateValue(IN K &key,IN V &value); - bit8 remove(IN K &key,OUT V &value); - bit8 remove(IN K &key); - bit8 removeAny(OUT K &key,OUT V &value); - bit8 iterate(INOUT int &index,INOUT int &offset, OUT V &value) const; - - private: - void shrink(void); // halve the number of slots - void expand(void); // double the number of slots - - - DNode **table; // This stores the lists at each slot - - uint32 entries; // number of entries - uint32 size; // size of table - uint32 tableBits; // table is 2^tableBits big - uint32 log2Size; // Junk variable - bit8 keepSize; // If true don't shrink or expand - - uint32 (* hashFunc)(K &key); // User provided hash function - uint32 keyHash(IN K &key); // This will reduce to correct range - - - // See initilizer list of constructor for values - const double SHRINK_THRESHOLD; // When table is this % full shrink it - const double EXPAND_THRESHOLD; // When table is this % full grow it - const int MIN_TABLE_SIZE; // must be a power of 2 -}; - - -//Create the empty hash dictionary -template -Dictionary::Dictionary(uint32 (* hashFn)(K &key)) : - SHRINK_THRESHOLD(0.20), // When table is only 20% full shrink it - EXPAND_THRESHOLD(0.80), // When table is 80% full grow it - MIN_TABLE_SIZE(32) // must be a power of 2 -{ - log2Size=MIN_TABLE_SIZE; - size=MIN_TABLE_SIZE; - assert(size>=4); - tableBits=0; - while(log2Size) { tableBits++; log2Size>>=1; } - tableBits--; - size=1< **)new DNode* [size]; - assert(table!=NULL); - - memset((void *)table,0,size*sizeof(void *)); - hashFunc=hashFn; -} - -//Free all the memory... -template -Dictionary::~Dictionary() -{ - clear(); // Remove the entries - delete[](table); // And the table as well -} - -// Remove all the entries and free the memory -template -void Dictionary::clear() -{ - DNode *temp,*del; - uint32 i; - //free all the data - for (i=0; ihashNext; - delete(del); - } - table[i]=NULL; - } - entries=0; - - while ((getSize()>(uint32)MIN_TABLE_SIZE)&&(keepSize==FALSE)) - shrink(); -} - -template -uint32 Dictionary::keyHash(IN K &key) -{ - uint32 retval=hashFunc(key); - retval &= ((1< -void Dictionary::print(IN FILE *out) const -{ - DNode *temp; - uint32 i; - - fprintf(out,"--------------------\n"); - for (i=0; ihashNext; - } - fprintf(out,"\n"); - } - fprintf(out,"--------------------\n"); -} - - -// -// Iterate through all the records. Index is for the table, offset specifies the -// element in the linked list. Set both to 0 and continue calling till false -// is returned. -template -bit8 Dictionary::iterate(INOUT int &index,INOUT int &offset, - OUT V &value) const -{ - DNode *temp; - - // index out of range - if ((index<0)||(index >= getSize())) - return(FALSE); - - temp=table[index]; - while ((temp==NULL)&&((++index) < getSize())) - { - temp=table[index]; - offset=0; - } - - if (temp==NULL) // no more slots with data - return(FALSE); - - uint32 i=0; - while ((temp!=NULL) && (i < offset)) - { - temp=temp->hashNext; - i++; - } - - if (temp==NULL) // should never happen - return(FALSE); - - value=temp->value; - if (temp->hashNext==NULL) - { - index++; - offset=0; - } - else - offset++; - - return(TRUE); -} - - - -// Return the current size of the hash table -template -uint32 Dictionary::getSize(void) const -{ return(size); } - - -// Return the current number of entries in the table -template -uint32 Dictionary::getEntries(void) const -{ return(entries); } - - -// Does the Dictionary contain the key? -template -bit8 Dictionary::contains(IN K &key) -{ - int offset; - DNode *node; - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - { return(FALSE); } // can't find it - - while(node!=NULL) - { - if ((node->key)==key) - { return(TRUE); } - node=node->hashNext; - } - return(FALSE); -} - - -// Try and update the value of an already existing object -template -bit8 Dictionary::updateValue(IN K &key,IN V &value) -{ - sint32 retval; - - retval=remove(key); - if (retval==FALSE) - return(FALSE); - - add(key,value); - return(TRUE); -} - - -// Add to the dictionary (if key exists, value is updated with the new V) -template -bit8 Dictionary::add(IN K &key,IN V &value) -{ - int offset; - DNode *node,*item,*temp; - float percent; - - item=(DNode *)new DNode; - assert(item!=NULL); - - #ifdef KEY_MEM_OPS - memcpy(&(item->key),&key,sizeof(K)); - #else - item->key=key; - #endif - - #ifdef VALUE_MEM_OPS - memcpy(&(item->value),&value,sizeof(V)); - #else - item->value=value; - #endif - - item->hashNext=NULL; - - //If key already exists, it will be overwritten - remove(key); - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - { table[offset]=item; } - else - { - temp=table[offset]; - table[offset]=item; - item->hashNext=temp; - } - - entries++; - percent=(float)entries; - percent/=(float)getSize(); - if (percent>= EXPAND_THRESHOLD ) expand(); - - return(TRUE); -} - -// Remove an item from the dictionary -template -bit8 Dictionary::remove(IN K &key,OUT V &value) -{ - int offset; - DNode *node,*last,*temp; - float percent; - - if (entries==0) - return(FALSE); - - percent=(float)(entries-1); - percent/=(float)getSize(); - - offset=keyHash(key); - node=table[offset]; - - last=node; - if (node==NULL) return(FALSE); - - //special case table points to thing to delete - - #ifdef KEY_MEM_OPS - if (0==memcmp(&(node->key),&key,sizeof(K))) - #else - if ((node->key)==key) - #endif - { - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - temp=table[offset]->hashNext; - delete(table[offset]); - table[offset]=temp; - entries--; - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); - } - node=node->hashNext; - - //Now the case if the thing to delete is not the first - while (node!=NULL) - { - #ifdef KEY_MEM_OPS - if (0==memcmp(&(node->key),&key,sizeof(K))) - #else - if (node->key==key) - #endif - { - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - last->hashNext=node->hashNext; - entries--; - delete(node); - break; - } - last=node; - node=node->hashNext; - } - - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); -} - - -template -bit8 Dictionary::remove(IN K &key) -{ - V temp; - return(remove(key,temp)); -} - - -// Remove some random K/V pair that's in the Dictionary -template -bit8 Dictionary::removeAny(OUT K &key,OUT V &value) -{ - int offset; - DNode *node,*last,*temp; - float percent; - - if (entries==0) - return(FALSE); - - percent=(entries-1); - percent/=(float)getSize(); - - int i; - offset=-1; - for (i=0; i<(int)getSize(); i++) - if (table[i]!=NULL) - { - offset=i; - break; - } - - if (offset==-1) // Nothing there - return(FALSE); - - node=table[offset]; - last=node; - - #ifdef KEY_MEM_OPS - memcpy(&key,&(node->key),sizeof(K)); - #else - key=node->key; - #endif - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - - temp=table[offset]->hashNext; - delete(table[offset]); - table[offset]=temp; - entries--; - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); -} - -template -bit8 Dictionary::getValue(IN K &key,OUT V &value) -{ - int offset; - DNode *node; - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) return(FALSE); - - #ifdef KEY_MEM_OPS - while ((node!=NULL)&&(memcmp(&(node->key),&key,sizeof(K)))) - #else - while ((node!=NULL)&&( ! ((node->key)==key)) ) // odd syntax so you don't - #endif // have to do oper != - { node=node->hashNext; } - - if (node==NULL) - { return(FALSE); } - - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=(node->value); - #endif - return(TRUE); -} - - -//A note about Shrink and Expand: They are never necessary, they are -//only here to improve performance of the hash table by reducing -//the length of the linked list at each table entry. - -// Shrink the hash table by a factor of 2 (and relocate entries) -template -void Dictionary::shrink(void) -{ - int i; - int oldsize; - uint32 offset; - DNode **oldtable,*temp,*first,*next; - - if ((size<=(uint32)MIN_TABLE_SIZE)||(keepSize==TRUE)) - return; - - //fprintf(stderr,"Shrinking....\n"); - - oldtable=table; - oldsize=size; - size/=2; - tableBits--; - - table=(DNode **)new DNode*[size]; - assert(table!=NULL); - memset((void *)table,0,size*sizeof(void *)); - - for (i=0; ikey); - first=table[offset]; - table[offset]=temp; - next=temp->hashNext; - temp->hashNext=first; - temp=next; - } - } - delete[](oldtable); -} - - -template -void Dictionary::expand(void) -{ - int i; - int oldsize; - uint32 offset; - DNode **oldtable,*temp,*first,*next; - - if (keepSize==TRUE) - return; - - //fprintf(stderr,"Expanding...\n"); - - oldtable=table; - oldsize=size; - size*=2; - tableBits++; - - table=(DNode **)new DNode* [size]; - assert(table!=NULL); - memset((void *)table,0,size*sizeof(void *)); - - for (i=0; ikey); - first=table[offset]; - table[offset]=temp; - next=temp->hashNext; - temp->hashNext=first; - temp=next; - } - } - delete[](oldtable); -} - -#endif diff --git a/Generals/Code/Tools/Launcher/filed.h b/Generals/Code/Tools/Launcher/filed.h deleted file mode 100644 index ca3fa9e3dc..0000000000 --- a/Generals/Code/Tools/Launcher/filed.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef FILED_HEADER -#define FILED_HEADER - -#include "odevice.h" - -class FileD : public OutputDevice -{ - public: - FileD(char *filename, bool outputDebug) : m_outputDebug(outputDebug) - { - out=fopen(filename,"w"); - if (out==NULL) - out=fopen("FileDev.out","w"); - } - - virtual ~FileD() - { fclose(out); } - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - fprintf(out,"%s",string); - if (m_outputDebug) - { - OutputDebugString(string); - } - delete[](string); - fflush(out); - return(len); - } - - FILE *out; - bool m_outputDebug; -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/findpatch.cpp b/Generals/Code/Tools/Launcher/findpatch.cpp deleted file mode 100644 index ad1b90c9f2..0000000000 --- a/Generals/Code/Tools/Launcher/findpatch.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "findpatch.h" - -// -// Locate a patch file -// If a patch can be found then TRUE is returned and the name is filled in, -// otherwise FALSE is returned. -// -// Patch Types: -// - *.rtp = RTPatch file that can be applied right now -// - *.exe = Executable that should be put in the RunOnce registry entry & reboot -// - *.exn = Executable that should be run right now -// - *.web = Link to a web page that will have the patch -// - else = File is ignored, possibly a resource file for one of the other types -// -int Find_Patch(OUT char *filename,int maxlen, ConfigFile &config) -{ - WIN32_FIND_DATA findData; - char string[128]; - HANDLE hFile; - const char *extensions[]={"web","exe","exn","rtp",NULL}; - int i; - int skuIndex=0; - Wstring key; - Wstring path; - Wstring sku; - char gamePath[MAX_PATH] = ""; - bit8 ok; - - - while(1) - { - // - // Loop through the apps we're responsible for - // - skuIndex++; - ok=Get_App_Dir(gamePath,MAX_PATH,config,skuIndex); - if (ok==FALSE) - break; - - i=0; - while(extensions[i++]) - { - _chdir(gamePath); // goto the directory with the game - - // should probably get the registry entry for the wchat install path - sprintf(string,"patches\\*.%s",extensions[i]); - hFile=FindFirstFile(string,&findData); - if (hFile!=INVALID_HANDLE_VALUE) - { - _getcwd(filename,MAX_PATH); - strcat(filename,"\\patches\\"); - strcat(filename,findData.cFileName); - FindClose(hFile); - return(skuIndex); - } - sprintf(string,"download\\*.%s",extensions[i]); - hFile=FindFirstFile(string,&findData); - if (hFile!=INVALID_HANDLE_VALUE) - { - _getcwd(filename,MAX_PATH); - strcat(filename,"\\download\\"); - strcat(filename,findData.cFileName); - FindClose(hFile); - return(skuIndex); - } - } - } - return(FALSE); -} - - -// -// Get the directory for the N'th application in the config file -// -// Returns FALSE if not in the config file or invalid for some reason. -// -bit8 Get_App_Dir(OUT char *filename,int maxlen, ConfigFile &config,int index) -{ - char string[128]; - Wstring key; - Wstring path; - Wstring sku; - int temp; - char gamePath[MAX_PATH]; - - - sprintf(string,"SKU%d",index); - - // Can't find this product - if (config.getString(string,key)==FALSE) - return(FALSE); - - - DBGMSG("KEY = "<. -*/ - -#ifndef FINDPATCH_HEADER -#define FINDPATCH_HEADER - -#include -#include -#include -#include -#include "wstypes.h" -#include "configfile.h" - -int Find_Patch(OUT char *file,int maxlen, ConfigFile &config); -bit8 Get_App_Dir(OUT char *file,int maxlen, ConfigFile &config, int index); -void Delete_Patches(ConfigFile &config); - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Launcher/loadbmp.cpp b/Generals/Code/Tools/Launcher/loadbmp.cpp deleted file mode 100644 index d3747f59ef..0000000000 --- a/Generals/Code/Tools/Launcher/loadbmp.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include"loadbmp.h" - - -LoadBmp::LoadBmp() -{ - BitmapHandle_=NULL; - PalHandle_=NULL; -} - -LoadBmp::~LoadBmp() -{ - // free resources - DeleteObject(BitmapHandle_); - DeleteObject(PalHandle_); -} - -// -// Load a specified bitmap for later display on a window -// -bit8 LoadBmp::init(const char *filename,HWND hwnd) -{ - int i; - HANDLE hBitmapFile; - DWORD dwRead; - BITMAPFILEHEADER bitmapHeader; - BITMAPINFOHEADER bitmapInfoHeader; - LPLOGPALETTE lpLogPalette; - char *palData; - HGLOBAL hmem2; - LPVOID lpvBits; - HDC hdc; - HPALETTE select; - UINT realize; - RECT rect; - - - // Set the member for future reference - WindowHandle_=hwnd; - - // Retrieve a handle identifying the file. - hBitmapFile = CreateFile( - filename, - GENERIC_READ, - FILE_SHARE_READ, - (LPSECURITY_ATTRIBUTES) NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_READONLY, - (HANDLE) NULL); - - if (hBitmapFile==NULL) - return(FALSE); - - // Retrieve the BITMAPFILEHEADER structure. - ReadFile(hBitmapFile, &bitmapHeader, sizeof(BITMAPFILEHEADER), &dwRead, - (LPOVERLAPPED)NULL); - - - // Retrieve the BITMAPFILEHEADER structure. - ReadFile(hBitmapFile, &bitmapInfoHeader, sizeof(BITMAPINFOHEADER), - &dwRead, (LPOVERLAPPED)NULL); - - - // Allocate memory for the BITMAPINFO structure. - HGLOBAL infoHeaderMem = GlobalAlloc(GHND, sizeof(BITMAPINFOHEADER) + - ((1<bmiHeader.biSize = bitmapInfoHeader.biSize; - lpHeaderMem->bmiHeader.biWidth = bitmapInfoHeader.biWidth; - lpHeaderMem->bmiHeader.biHeight = bitmapInfoHeader.biHeight; - lpHeaderMem->bmiHeader.biPlanes = bitmapInfoHeader.biPlanes; - lpHeaderMem->bmiHeader.biBitCount = bitmapInfoHeader.biBitCount; - lpHeaderMem->bmiHeader.biCompression = bitmapInfoHeader.biCompression; - lpHeaderMem->bmiHeader.biSizeImage = bitmapInfoHeader.biSizeImage; - lpHeaderMem->bmiHeader.biXPelsPerMeter = bitmapInfoHeader.biXPelsPerMeter; - lpHeaderMem->bmiHeader.biYPelsPerMeter = bitmapInfoHeader.biYPelsPerMeter; - lpHeaderMem->bmiHeader.biClrUsed = bitmapInfoHeader.biClrUsed; - lpHeaderMem->bmiHeader.biClrImportant = bitmapInfoHeader.biClrImportant; - - - // Retrieve the color table. - // 1 << bitmapInfoHeader.biBitCount == 2 ^ bitmapInfoHeader.biBitCount - ReadFile(hBitmapFile, lpHeaderMem->bmiColors, - ((1<palVersion=0x300; - lpLogPalette->palNumEntries=256; - - palData=(char *)lpHeaderMem->bmiColors; - - for (i=0; i<256; i++) - { - lpLogPalette->palPalEntry[i].peRed=*palData++; - lpLogPalette->palPalEntry[i].peGreen=*palData++; - lpLogPalette->palPalEntry[i].peBlue=*palData++; - lpLogPalette->palPalEntry[i].peFlags=*palData++; - } - PalHandle_=CreatePalette(lpLogPalette); - delete(lpLogPalette); - - - // Allocate memory for the required number of bytes. - hmem2 = GlobalAlloc(GHND, (bitmapHeader.bfSize - bitmapHeader.bfOffBits)); - - lpvBits = GlobalLock(hmem2); - - // Retrieve the bitmap data. - ReadFile(hBitmapFile, lpvBits, (bitmapHeader.bfSize - bitmapHeader.bfOffBits), - &dwRead, (LPOVERLAPPED) NULL); - - - // Create a bitmap from the data stored in the .BMP file. - hdc=GetDC(hwnd); - select=SelectPalette(hdc,PalHandle_,0); - if (select==NULL) - return(FALSE); - realize=RealizePalette(hdc); - if (realize==GDI_ERROR) - return(FALSE); - BitmapHandle_=CreateDIBitmap(hdc, &bitmapInfoHeader, CBM_INIT, lpvBits, lpHeaderMem, DIB_RGB_COLORS); - ReleaseDC(hwnd,hdc); - - - if (BitmapHandle_==NULL) - return(FALSE); - - // Unlock the global memory objects and close the .BMP file. - GlobalUnlock(infoHeaderMem); - GlobalUnlock(hmem2); - CloseHandle(hBitmapFile); - - if (BitmapHandle_==NULL) - return(FALSE); - - // Inform windows the window needs to be repainted - GetClientRect(hwnd, &rect); - InvalidateRect(hwnd, &rect, TRUE); - UpdateWindow(hwnd); - - return(TRUE); -} - - -bit8 LoadBmp::drawBmp(void) -{ - // Paint the window (and draw the bitmap). - - PAINTSTRUCT ps; - HDC hdc; - char string[128]; - - if (BitmapHandle_ == NULL) // NAK - new - return(FALSE); - - InvalidateRect(WindowHandle_,NULL,FALSE); // keep windows from screwing up the - // redrawing (as much). - hdc=BeginPaint(WindowHandle_,&ps); - - //Do palette stuff - HPALETTE select=SelectPalette(ps.hdc,PalHandle_,0); - if (select==NULL) - { - sprintf(string,"Select Pal Fail: %d",GetLastError()); - MessageBox(NULL,string,"OK",MB_OK); - } - UINT realize=RealizePalette(ps.hdc); - if (realize==GDI_ERROR) - { - sprintf(string,"Realize Pal Fail: %d",GetLastError()); - MessageBox(NULL,string,"OK",MB_OK); - } - - HDC hdcMem = CreateCompatibleDC(ps.hdc); - SelectObject(hdcMem, BitmapHandle_); - BITMAP bm; - GetObject(BitmapHandle_, sizeof(BITMAP), (LPSTR) &bm); - - /// for non-stretching version - ///////BitBlt(ps.hdc, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY); - - RECT clientRect; - GetClientRect(WindowHandle_,&clientRect); - SetStretchBltMode(ps.hdc,COLORONCOLOR); - StretchBlt(ps.hdc,0,0,clientRect.right,clientRect.bottom,hdcMem,0,0,bm.bmWidth, - bm.bmHeight,SRCCOPY); - - - DeleteDC(hdcMem); - EndPaint(WindowHandle_,&ps); - return(TRUE); -} diff --git a/Generals/Code/Tools/Launcher/loadbmp.h b/Generals/Code/Tools/Launcher/loadbmp.h deleted file mode 100644 index 3d6f699503..0000000000 --- a/Generals/Code/Tools/Launcher/loadbmp.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef LOADBMP_HEADER -#define LOADBMP_HEADER - -#include -#include -#include "wstypes.h" -#include "winblows.h" - - -// -// Functions and data assocated with a loaded bitmap on a single window. -// -class LoadBmp -{ - public: - LoadBmp(); - ~LoadBmp(); - bit8 init(const char *filename,HWND hwnd); // must call before the drawBmp - bit8 drawBmp(void); // call this from your WM_PAINT message - - private: - HBITMAP BitmapHandle_; - HPALETTE PalHandle_; - HWND WindowHandle_; -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Launcher/main.cpp b/Generals/Code/Tools/Launcher/main.cpp deleted file mode 100644 index 1fbf29721e..0000000000 --- a/Generals/Code/Tools/Launcher/main.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*****************************************************************************\ - C O N F I D E N T I A L --- W E S T W O O D S T U D I O S -******************************************************************************* - File: main.cpp - Programmer: Neal Kettler - - StartDate: Feb 6, 1998 - LastUpdate: Feb 10, 1998 -------------------------------------------------------------------------------- - - Launcher application for games/apps using the chat API. This should be - run by the user and it will start the actual game executable. If a patch - file has been downloaded the patch will be applied before starting the game. - - This does not download patches or do version checks, the game/app is responsible - for that. This just applies patches that are in the correct location for the - game. All patches should be in the "Patches" folder of the app. - - The launcher should have a config file (launcher.cfg) so it knows which apps - should be checked for patches. The file should look like this: - - # comment - # RUN = the game to launch - RUN = . notepad.exe # directory and app name - # RUN2 = the 2nd launcher if using one - RUN2 = . wordpad.exe - # FLAG = time in seconds of when to stop using 2nd launcher - FLAG = 996778113 - # - # Sku's to check for patches - # - SKU1 = 1100 SOFTWARE\Westwood\WOnline # skus and registry keys - SKU2 = 1234 SOFTWARE\Westwood\FakeGame - -\*****************************************************************************/ -#include "dialog.h" -#include "patch.h" -#include "findpatch.h" -#include "process.h" - -#include "wdebug.h" -#include "monod.h" -#include "filed.h" -#include "configfile.h" -#include - -#ifdef COPY_PROTECT -#include "Protect.h" -#endif -#include - -#define UPDATE_RETVAL 123456789 // if a program returns this it means it wants to check for patches - -void CreatePrimaryWin(const char *prefix); -void myChdir(char *path); - -void RunGame(char *thePath, ConfigFile &config, Process &proc) -{ - char patchFile[MAX_PATH]; - bool launchgame = true; - - // MDC 8/23/2001 Wait 3 seconds for the installer to release the mutex - ///Sleep(3000); - - while (true) - { - int skuIndex; - - while ((skuIndex = Find_Patch(patchFile, MAX_PATH, config)) != 0) - { - Apply_Patch(patchFile, config, skuIndex); - launchgame = true; - } - - // launch the game if first pass, or found a patch - if (launchgame) - { - // don't relaunch unless we find a patch (or checking for patches) - launchgame = false; - myChdir(thePath); - -#ifndef COPY_PROTECT - Create_Process(proc); -#else // COPY_PROTECT - - InitializeProtect(); - Create_Process(proc); - SendProtectMessage(proc.hProcess, proc.dwThreadID); - -#endif // COPY_PROTECT - - DWORD exit_code; - Wait_Process(proc, &exit_code); - - if (exit_code == UPDATE_RETVAL) - { - // They just want to check for patches - launchgame = true; - - // Start patchgrabber - Process patchgrab; - strcpy(patchgrab.directory,proc.directory); // same dir as game - strcpy(patchgrab.command,"patchget.dat"); // the program that grabs game patches - strcpy(patchgrab.args,""); - Create_Process(patchgrab); - Wait_Process(patchgrab); // wait for completion - } - -#ifdef COPY_PROTECT - ShutdownProtect(); -#endif - } - else - { - Delete_Patches(config); // delete all patches - break; - } - } -} - -// The other launcher will handle itself. Just fire and forget. -void RunLauncher(char *thePath, Process &proc) -{ - myChdir(thePath); - Create_Process(proc); -} - -// -// Called by WinMain -// -int main(int argc, char *argv[]) -{ - char patchFile[MAX_PATH]; - - char cwd[MAX_PATH]; // save current directory before game start - _getcwd(cwd, MAX_PATH); - - // Goto the folder where launcher is installed - myChdir(argv[0]); - - // extract the program name from argv[0]. Change the extension to - // .lcf (Launcher ConFig). This is the name of our config file. - char configName[MAX_PATH + 3]; - strcpy(configName, argv[0]); - char* extension = configName; - char* tempptr; - - while ((tempptr = strchr(extension + 1, '.'))) - { - extension = tempptr; - } - - if (*extension == '.') - { - *extension = 0; - } - -#ifdef DEBUG - ///MonoD outputDevice; - char debugFile[MAX_PATH + 3]; - strcpy(debugFile, configName); - strcat(debugFile, ".txt"); - strcpy(debugLogName, strrchr(configName, '\\')); - strcat(debugLogName, "Log"); - FileD outputDevice(debugFile, true); - MsgManager::setAllStreams(&outputDevice); - DBGMSG("Launcher initialized"); -#endif - - CreatePrimaryWin("generals"); - - InitCommonControls(); - - strcat(configName, ".lcf"); - - DBGMSG("Config Name: "<= 2) && (strcmp(argv[1], "GrabPatches") == 0)) - { - // Start patchgrabber - Process patchgrab; - - // same dir as game - strcpy(patchgrab.directory, proc.directory); - - // the program that grabs game patches - strcpy(patchgrab.command, "patchget.dat"); - strcpy(patchgrab.args, ""); - - Create_Process(patchgrab); - Wait_Process(patchgrab); - - // Apply any patches I find - int skuIndex; - - while ((skuIndex = Find_Patch(patchFile, MAX_PATH, config)) != 0) - { - Apply_Patch(patchFile, config, skuIndex); - } - - myChdir(cwd); - return 0; - } - - // Look for patch file(s) to apply - bool launchgame = true; - - time_t cutoffTime = 0; - if (hasSecondEXE) - { - Wstring timeStr; - if (config.getString("FLAG", timeStr)!=FALSE) - { - cutoffTime = atoi(timeStr.get()); - } - - if (cutoffTime == 0) - { - // We didn't have the FLAG parameter; somebody's been hacking. No game for you! Bad hacker! - DBGMSG("Saw cutoffTime of 0; real time is " << time(NULL)); - MessageBox(NULL,"File 'launcher.cfg' is corrupt","Error",MB_OK); - exit(-1); - } - - if (time(NULL) > cutoffTime) - { - // The future is now! Just run the game. - RunGame(argv[0], config, proc); - } - else - { - // Its still early in the product's lifetime, so run the 2nd (SafeDisk'd) launcher. - // We don't have to wait around since it'll do the entire talk to game, look for patches, - // etc. deal. - RunLauncher(argv[0], proc2); - } - } - else - { - // We're the second (or only) launcher, so act normally - RunGame(argv[0], config, proc); - } - - myChdir(cwd); - - // Exit normally - return 0; -} - - -// -// Create a primary window -// -void CreatePrimaryWin(const char *prefix) -{ - char name[256]; - sprintf(name, "launcher_%s", prefix); - - DBGMSG("CreatePrimary: "<. -*/ - -#include "monod.h" - -MonoD::MonoD(void) -{ -#ifdef _WIN32 - unsigned long retval; - handle = CreateFile("\\\\.\\MONO", GENERIC_READ|GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - if (handle != INVALID_HANDLE_VALUE) - { - DeviceIoControl(handle, (DWORD)IOCTL_MONO_CLEAR_SCREEN, NULL, 0, NULL, 0, - &retval,0); - } -#endif -} - -MonoD::~MonoD() -{ - #ifdef _WIN32 - CloseHandle(handle); - handle=NULL; - #endif -} - -int MonoD::print(const char *str, int len) -{ - #ifdef _WIN32 - unsigned long retval; - WriteFile(handle, str, len, &retval, NULL); - //DeviceIoControl(handle, (DWORD)IOCTL_MONO_PRINT_RAW, (void *)str, len, NULL, 0, - // &retval,0); - return(len); - #else - for (int i=0; i. -*/ - -#ifndef MONOD_HEADER -#define MONOD_HEADER - - -#include -#include -#include "odevice.h" - -///////////////////////// WIN32 ONLY /////////////////////////////////// - -#ifdef _WIN32 -#include -#include - - -/* -** This is the identifier for the Monochrome Display Driver -*/ -#define FILE_DEVICE_MONO 0x00008000 - -/* -** These are the IOCTL commands supported by the Monochrome Display Driver. -*/ -#define IOCTL_MONO_HELP_SCREEN CTL_CODE(FILE_DEVICE_MONO, 0x800, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_CLEAR_SCREEN CTL_CODE(FILE_DEVICE_MONO, 0x801, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_PRINT_RAW CTL_CODE(FILE_DEVICE_MONO, 0x802, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_CURSOR CTL_CODE(FILE_DEVICE_MONO, 0x803, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SCROLL CTL_CODE(FILE_DEVICE_MONO, 0x804, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_BRING_TO_TOP CTL_CODE(FILE_DEVICE_MONO, 0x805, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_ATTRIBUTE CTL_CODE(FILE_DEVICE_MONO, 0x806, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_PAN CTL_CODE(FILE_DEVICE_MONO, 0x807, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_LOCK CTL_CODE(FILE_DEVICE_MONO, 0x808, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_UNLOCK CTL_CODE(FILE_DEVICE_MONO, 0x809, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_WINDOW CTL_CODE(FILE_DEVICE_MONO, 0x80A, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_RESET_WINDOW CTL_CODE(FILE_DEVICE_MONO, 0x80B, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_FLAG CTL_CODE(FILE_DEVICE_MONO, 0x80C, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_CLEAR_FLAG CTL_CODE(FILE_DEVICE_MONO, 0x80D, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_FILL_ATTRIB CTL_CODE(FILE_DEVICE_MONO, 0x80E, METHOD_BUFFERED, FILE_WRITE_DATA) - -#endif // ifdef _WIN32 - -class MonoD : public OutputDevice -{ - public: - MonoD(); - ~MonoD(); - - virtual int print(const char *str,int len); - - private: - #ifdef _WIN32 - HANDLE handle; - #endif -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/odevice.h b/Generals/Code/Tools/Launcher/odevice.h deleted file mode 100644 index f04bffaec1..0000000000 --- a/Generals/Code/Tools/Launcher/odevice.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef ODEVICE_HEADER -#define ODEVICE_HEADER - -// This virtual base class provides an interface for output devices -// that can be used for the debugging package. -class OutputDevice -{ - public: - OutputDevice() {} - virtual ~OutputDevice() {}; - virtual int print(const char *s,int len)=0; -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/patch.cpp b/Generals/Code/Tools/Launcher/patch.cpp deleted file mode 100644 index c11a60e880..0000000000 --- a/Generals/Code/Tools/Launcher/patch.cpp +++ /dev/null @@ -1,577 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*****************************************************************************\ - C O N F I D E N T I A L --- W E S T W O O D S T U D I O S -******************************************************************************* - File: patch.cpp - Programmer: Neal Kettler - - StartDate: Feb 6, 1998 - LastUpdate: Feb 10, 1998 -------------------------------------------------------------------------------- - -This is where all the code is for applying various types of patches. - -\*****************************************************************************/ - - -#include "patch.h" -#include -#include - - -// -// For the text box showing patch info -// -BOOL CALLBACK Update_Info_Proc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) -{ - - static int unselectText=0; - - switch(iMsg) - { - case WM_INITDIALOG: - { - FILE *in = fopen("launcher.txt","r"); - if (in==NULL) - { - EndDialog(hwnd,-1); - return(1); - } - - char line[270]; - int lastsel=0; - char *cptr=NULL; - while(fgets(line,255,in)) - { - //Get rid of any trailing junk - while(1) - { - if (strlen(line)<1) - break; - cptr=line+(strlen(line))-1; - if ((*cptr=='\r')||(*cptr=='\n')) - *cptr=0; - else - break; - } - // ...and add back the gunk that windows likes - strcat(line,"\r\r\n"); - - SendDlgItemMessage(hwnd, IDC_TEXT, EM_SETSEL, (WPARAM)lastsel, (LPARAM)lastsel ); - SendDlgItemMessage(hwnd, IDC_TEXT, EM_REPLACESEL, 0, (LPARAM)(line) ); - SendDlgItemMessage(hwnd, IDC_TEXT, EM_GETSEL, (WPARAM)NULL, (LPARAM)&lastsel ); - } - unselectText=1; - fclose(in); - - return(1); // 1 means windows handles focus issues - } - break; - - case WM_PAINT: - if (unselectText) - SendDlgItemMessage(hwnd, IDC_TEXT, EM_SETSEL, -1, 0); - unselectText=0; - return(0); - break; - - - case WM_COMMAND: - switch(wParam) { - case IDOK: - { - EndDialog(hwnd,0); - return(1); - } - default: - break; - } - default: - break; - case WM_CLOSE: - EndDialog(hwnd,0); - return(1); - break; - } - return(FALSE); -} - - - - - - - -// Restart the computer for certain types of patches -void Shutdown_Computer_Now(void); - - -__declspec(dllexport) LPVOID CALLBACK PatchCallBack(UINT ID, LPVOID Param); - -typedef LPVOID (CALLBACK* PATCHCALLBACK)(UINT, LPVOID); -typedef UINT (CALLBACK *PATCHFUNC)( LPSTR, PATCHCALLBACK, BOOL); - -// -// Apply any type of patch. Filename in patchfile. Product base registry -// (eg: "SOFTWARE\Westwood\Red Alert") should be in the config file as -// SKUX SKU base reg dir where X = index -// -void Apply_Patch(char *patchfile,ConfigFile &config,int skuIndex) -{ - DBGMSG("PATCHFILE : "<SetRTPErrCode(Id); - - int percent; - - switch( Id ) - { - case 1: - case 2: - // Warning message header/text - DBGMSG("P_MSG: "<<((char *)Param)); - break; - - case 3: - // Error message header - DBGMSG("P_MSG: "<<((char *)Param)); - break; - - case 4: - // Error message header/text - ///////*g_LogFile << (char *)Parm << endl; - char errmsg[256]; - LoadString(NULL,IDS_ERR_PATCH,errmsg,256); - MessageBox(NULL,(char *)Param,errmsg,MB_OK); - { - FILE *out=fopen("patch.err","a"); - time_t timet=time(NULL); - fprintf(out,"\n\nPatch Error: %s\n",ctime(&timet)); - fprintf(out,"%s\n",(char *)Param); - fclose(out); - } - break; - - case 9: - // progress message - break; - - case 0xa: - // help message - break; - - case 0xb: - // patch file comment - break; - - case 0xc: - // copyright message - break; // these just display text - - case 5: - // % completed - // so adjust the progress bar using the global Dialog pointer - /////////g_DlgPtr->SetProgressBar((int)((float)(*(UINT *)Parm)/(float)0x8000*(float)100)); - percent=((*(UINT *)Param)*100)/0x8000; - SendMessage(GetDlgItem(PatchDialog,IDC_PROGRESS2),PBM_SETPOS,percent,0); - break; - - case 6: - // Number of patch files - DBGMSG("6: "<<*((uint32 *)Param)); - fileCount=*((uint32 *)Param); - currFile=0; - break; - - case 7: - //// begin patch - //LoadString(g_AppInstance, IDS_PROCESSING, lpcBuf, 256); - //strcpy(buf,lpcBuf); - //strcat(buf,(char *)Parm); - //g_DlgPtr->SetProgressText(buf); - //*g_LogFile << buf << " : "; - //fileModified = true; - - DBGMSG("7: "<<(char *)Param); - SetWindowText(GetDlgItem(PatchDialog,IDC_FILENAME),(char *)Param); - percent=0; - SendMessage(GetDlgItem(PatchDialog,IDC_PROGRESS2),PBM_SETPOS,percent,0); - - currFile++; - char xofy[64]; - LoadString(NULL,IDS_FILE_X_OF_Y,xofy,64); - sprintf(string,xofy,currFile,fileCount); - SetWindowText(GetDlgItem(PatchDialog,IDC_CAPTION),string); - - break; - - case 8: - //// end patch - //LoadString(g_AppInstance, IDS_PROCCOMPLETE, lpcBuf, 256); - //g_DlgPtr->SetProgressText(lpcBuf); - //*g_LogFile << " complete" << endl; - percent=100; - SendMessage(GetDlgItem(PatchDialog,IDC_PROGRESS2),PBM_SETPOS,percent,0); - DBGMSG("P_DONE"); - break; - - case 0xd: - //// this one shouldn't happen (only occurs if the command line - //// doesn't have a patch file in it, and we insure that it does). - //Abort = TRUE; - //*g_LogFile << "Incorrect (or none) patch file specified in command line." << endl; - break; - - case 0xe: - //// this one shouldn't happen either (same reason) - //Abort = TRUE; - //*g_LogFile << "Incorrect (or none) path specified in command line." << endl; - break; - - case 0xf: - //// Password Dialog - break; - - case 0x10: - //// Invalid Password Alert - break; - - case 0x11: - //// Disk Change Dialog - break; - - case 0x12: - //// Disk Change Alert - break; - - case 0x13: - //// Confirmation Dialog - break; - - case 0x14: - //// Location Dialog - //Abort = TRUE; - //*g_LogFile << "Specified path is incorrect." << endl; - break; - - case 0x16: - //// Searching Call-back - break; - - case 0x15: - //// Idle... - break; - - default: - break; - } - - if(Abort) - return (NULL); - else - return (RetVal); -} diff --git a/Generals/Code/Tools/Launcher/patch.h b/Generals/Code/Tools/Launcher/patch.h deleted file mode 100644 index e50e5bc060..0000000000 --- a/Generals/Code/Tools/Launcher/patch.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef PATCH_HEADER -#define PATCH_HEADER - -#include "winblows.h" -#include "dialog.h" -#include "resource.h" -#include "wdebug.h" -#include "process.h" - -void Apply_Patch(char *patchfile,ConfigFile &config,int skuIndex); - -#endif diff --git a/Generals/Code/Tools/Launcher/process.cpp b/Generals/Code/Tools/Launcher/process.cpp deleted file mode 100644 index 28a24c9ce0..0000000000 --- a/Generals/Code/Tools/Launcher/process.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "process.h" - -Process::Process() -{ - directory[0]=0; - command[0]=0; - args[0]=0; - hProcess=NULL; - hThread=NULL; -} - -// Create a process -bit8 Create_Process(Process &process) -{ - int retval; - STARTUPINFO si; - PROCESS_INFORMATION piProcess; - ZeroMemory(&si,sizeof(si)); - si.cb=sizeof(si); - - char cmdargs[513]; - memset(cmdargs,0,513); - strcpy(cmdargs,process.command); - strcat(cmdargs,process.args); - - DBGMSG("PROCESS CMD="<. -*/ - -#ifndef PROCESS_HEADER -#define PROCESS_HEADER - -#include -#include "wstypes.h" -#include "wdebug.h" -#include "configfile.h" - -class Process -{ - public: - Process(); - - char directory[256]; - char command[256]; - char args[256]; - HANDLE hProcess; - DWORD dwProcessID; - HANDLE hThread; - DWORD dwThreadID; -}; - -bit8 Read_Process_Info(ConfigFile &config,OUT Process &info, IN const char *key = NULL); -bit8 Create_Process(Process &process); -bit8 Wait_Process(Process &process, DWORD *exit_code=NULL); - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/Launcher/resource.h b/Generals/Code/Tools/Launcher/resource.h deleted file mode 100644 index 2edeae213f..0000000000 --- a/Generals/Code/Tools/Launcher/resource.h +++ /dev/null @@ -1,35 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by launcher1.rc -// -#define IDS_SYS_RESTART 1 -#define IDS_SYS_RESTART_TITLE 2 -#define IDS_WEBPATCH 3 -#define IDS_WEBPATCH_TITLE 4 -#define IDS_FILE_X_OF_Y 5 -#define IDS_MUST_RESTART 6 -#define IDS_RUNONCE_ERR 7 -#define IDS_ERROR 8 -#define IDS_ERR_MISSING_FILE 9 -#define IDS_BAD_LIBRARY 10 -#define IDS_ERR_PATCH 11 -#define IDD_DIALOG1 101 -#define IDD_PATCHPROGRESS 101 -#define IDI_GENERALS 102 -#define IDD_CHANGELOG 103 -#define IDC_PROGRESS2 1001 -#define IDC_SPLASH 1004 -#define IDC_FILENAME 1009 -#define IDC_CAPTION 1010 -#define IDC_TEXT 1011 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 104 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1013 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/Launcher/streamer.cpp b/Generals/Code/Tools/Launcher/streamer.cpp deleted file mode 100644 index dcaed7f884..0000000000 --- a/Generals/Code/Tools/Launcher/streamer.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#include "streamer.h" -#ifdef _WIN32 - #include -#endif - -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) -#define STREAMER_UNBUFFERED unbuffered() -#else -#define STREAMER_UNBUFFERED 0 -#endif - -Streamer::Streamer() : streambuf(), Output_Device(NULL), Buf(NULL) -{ -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) - int state=unbuffered(); - unbuffered(0); // 0 = buffered, 1 = unbuffered -#else - static_assert(STREAMER_UNBUFFERED==0, "std::streambuf is assumed to be buffered by default"); -#endif -} - -Streamer::~Streamer() -{ - ///////// calling sync seems to cause crashes here on Win32 - //sync(); - ///////// - if (Buf) - delete[] Buf; -} - -int Streamer::setOutputDevice(OutputDevice *device) -{ - Output_Device=device; - return(0); -} - - -// put n chars from string into buffer -int Streamer::xsputn(const char* buf, int size) //implementation of sputn -{ - if (size<=0) // Nothing to do - return(0); - - const unsigned char *ptr=(const unsigned char *)buf; - for (int i=0; i= epptr()) && (sync()==EOF)) - return(EOF); - else { - sputc(c); - if ((STREAMER_UNBUFFERED && c=='\n' || pptr() >= epptr()) - && sync()==EOF) { - return(EOF); - } - return(c); - } -} - -// This is a write only stream, this should never happen -int Streamer::underflow(void) -{ - return(EOF); -} - -int Streamer::doallocate() -{ - if (Buf==NULL) - { - Buf=new char[(2*STREAMER_BUFSIZ)]; // deleted by destructor - memset(Buf,0,2*STREAMER_BUFSIZ); - - // Buffer -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) - setb( - Buf, // base pointer - Buf+STREAMER_BUFSIZ, // ebuf pointer (end of buffer); - 0); // 0 = manual deletion of buff -#else - pubsetbuf(Buf, 2*STREAMER_BUFSIZ); -#endif - - // Get area - setg( - Buf, // eback - Buf, // gptr - Buf); // egptr - - Buf+=STREAMER_BUFSIZ; - // Put area - setp(Buf,Buf+STREAMER_BUFSIZ); - return(1); - } - else - return(0); -} - - -int Streamer::sync() -{ - if (pptr()<=pbase()) { - return(0); - } - - int wlen=pptr()-pbase(); - - if (Output_Device) - { - Output_Device->print(pbase(),wlen); - } - - if (STREAMER_UNBUFFERED) { - setp(pbase(),pbase()); - } - else { - setp(pbase(),pbase()+STREAMER_BUFSIZ); - } - return(0); -} diff --git a/Generals/Code/Tools/Launcher/streamer.h b/Generals/Code/Tools/Launcher/streamer.h deleted file mode 100644 index 2dc5ee922d..0000000000 --- a/Generals/Code/Tools/Launcher/streamer.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STREAMER_HEADER -#define STREAMER_HEADER - -#include -#include -#include -#include -#include - -#include "odevice.h" - -#ifndef STREAMER_BUFSIZ -// This limits the number of characters that can be sent to a single 'print' -// call. If your debug message is bigger than this, it will get split over -// multiple 'print' calls. That's usually not a problem. - #define STREAMER_BUFSIZ 2048 -#endif - - -// Provide a streambuf interface for a class that can 'print' -class Streamer : public streambuf -{ - public: - Streamer(); - virtual ~Streamer(); - - int setOutputDevice(OutputDevice *output_device); - - protected: - // Virtual methods from streambuf - int xsputn(const char* s, int n); // buffer some characters - int overflow(int = EOF); // flush buffer and make more room - int underflow(void); // Does nothing - int sync(); - - int doallocate(); // allocate a buffer - - - OutputDevice *Output_Device; - char *Buf; -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/wdebug.cpp b/Generals/Code/Tools/Launcher/wdebug.cpp deleted file mode 100644 index 0c5b5f9c09..0000000000 --- a/Generals/Code/Tools/Launcher/wdebug.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include -#include "wdebug.h" -#include "streamer.h" -#include "odevice.h" - - -static MsgManager *msg_manager=NULL; - -static int debug_enabled=0; -static ostream *debug_ostream=NULL; -static Streamer debug_streamer; - -static int info_enabled=0; -static ostream *info_ostream=NULL; -static Streamer info_streamer; - -static int warn_enabled=0; -static ostream *warn_ostream=NULL; -static Streamer warn_streamer; - -static int error_enabled=0; -static ostream *error_ostream=NULL; -static Streamer error_streamer; - - - -int MsgManager::setAllStreams(OutputDevice *device) -{ - if (device==NULL) - return(1); - - - debug_streamer.setOutputDevice(device); - delete(debug_ostream); - debug_ostream=new ostream(&debug_streamer); - - info_streamer.setOutputDevice(device); - delete(info_ostream); - info_ostream=new ostream(&info_streamer); - - warn_streamer.setOutputDevice(device); - delete(warn_ostream); - warn_ostream=new ostream(&warn_streamer); - - error_streamer.setOutputDevice(device); - delete(error_ostream); - error_ostream=new ostream(&error_streamer); - - return(0); -} - - -int MsgManager::setDebugStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - - debug_streamer.setOutputDevice(device); - delete(debug_ostream); - debug_ostream=new ostream(&debug_streamer); - - return(0); -} - -int MsgManager::setInfoStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - - info_streamer.setOutputDevice(device); - delete(info_ostream); - info_ostream=new ostream(&info_streamer); - - return(0); -} - -int MsgManager::setWarnStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - - warn_streamer.setOutputDevice(device); - delete(warn_ostream); - warn_ostream=new ostream(&warn_streamer); - - return(0); -} - -int MsgManager::setErrorStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - - error_streamer.setOutputDevice(device); - delete(error_ostream); - error_ostream=new ostream(&error_streamer); - - return(0); -} - - - -ostream *MsgManager::debugStream(void) -{ - return(debug_ostream); -} - -ostream *MsgManager::infoStream(void) -{ - return(info_ostream); -} - -ostream *MsgManager::warnStream(void) -{ - return(warn_ostream); -} - -ostream *MsgManager::errorStream(void) -{ - return(error_ostream); -} diff --git a/Generals/Code/Tools/Launcher/wdebug.h b/Generals/Code/Tools/Launcher/wdebug.h deleted file mode 100644 index 699f674a62..0000000000 --- a/Generals/Code/Tools/Launcher/wdebug.h +++ /dev/null @@ -1,193 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*****************************************************************************\ -wdebug Neal Kettler - -MT-LEVEL - MT-UnSafe! (UNIX version is safe though) - -The debugging module is pretty good for debugging and it has some message -printing stuff as well. The basic idea is that you write a class that -inherits from OutputDevice (severall are provided) and assign that output -device to a stream. There are seperate streams for debugging, information, -warning, and error messages. Each one can have a seperate output device, -or they can all have the same one. Debugging messages only get compiled -in if your module defines 'DEBUG'. If you don't define debug, then not even -the text of the debugging message gets into the binary. All the other -output streams get printed regardless of whether DEBUG is defined. - -Sample usage: -FileD debug_device("gameres.debug"); // create a file device -MsgManager::setDebugStream(&debug_device); -DBGMSG("This debug message #" << 1 << " you use C++ streams"); - -Note that since these are defines you really don't need to put a semicolon -at the end, and it can be bad in situations like this: - -if (x) - DBGMSG("Stuff is broken"); -else - DBGMSG("Stuff is NOT broken"); - -This won't compile, read the code until you figure it out. Only then -will you be ready to leave grasshopper. - -\*****************************************************************************/ - -#ifndef WDEBUG_HEADER -#define WDEBUG_HEADER - -#include -#include "odevice.h" -#include "streamer.h" -#include - - - -// Print an information message -#define INFMSG(X)\ -{\ - char timebuf[40]; \ - time_t clock=time(NULL); \ - cftime(timebuf,"%D %T",&clock); \ - if (MsgManager::infoStream()) \ - (*(MsgManager::infoStream())) << "INF " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ -} - -// Print a warning message -#define WRNMSG(X)\ -{\ - char timebuf[40]; \ - time_t clock=time(NULL); \ - cftime(timebuf,"%D %T",&clock); \ - if (MsgManager::warnStream()) \ - (*(MsgManager::warnStream())) << "WRN " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ -} - -// Print an error message -#define ERRMSG(X)\ -{\ - char timebuf[40]; \ - time_t clock=time(NULL); \ - strcpy(timebuf,ctime(&clock)); \ - if (MsgManager::errorStream()) \ - (*(MsgManager::errorStream())) << "ERR " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ -} - - -// Just get a stream to the information device, no extra junk -#define INFSTREAM(X)\ -{\ - if (MsgManager::infoStream()) \ - (*(MsgManager::infoStream())) << X;\ -} - -// Just get a stream to the warning device, no extra junk -#define WRNSTREAM(X)\ -{\ - if (MsgManager::warnStream()) \ - (*(MsgManager::warnStream())) << X;\ -} - -// Just get a stream to the error device, no extra junk -#define ERRSTREAM(X)\ -{\ - if (MsgManager::errorStream()) \ - (*(MsgManager::errorStream())) << X;\ -} - -#ifndef DEBUG - -// No debugging, no debug messages. -// Note that anything enclosed in "DBG()" will NOT get executed -// unless DEBUG is defined. -// They are defined to {} for consistency when DEBUG is defined - -#define DBG(X) -#define DBGSTREAM(X) {} -#define PVAR(v) {} -#define DBGMSG(X) {} -#define VERBOSE(X) {} - -#else // DEBUG _is_ defined - -// Execute only if in debugging mode -#define DBG(X) X - -// Print a variable -#define PVAR(v) \ -{ \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << endl; \ -} - - -#define DBGMSG(X)\ -{\ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << endl;\ -} - -// Just get a stream to the debugging device, no extra junk -#define DBGSTREAM(X)\ -{\ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << X;\ -} - -// Verbosely execute a statement -#define VERBOSE(X)\ -{ \ - if (MsgManager::debugStream()) \ - (*(DebugManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << endl; X \ -} - -#endif // DEBUG - - -class MsgManager -{ - protected: - MsgManager(); - - public: - static int setAllStreams(OutputDevice *device); - static int setDebugStream(OutputDevice *device); - static int setInfoStream(OutputDevice *device); - static int setWarnStream(OutputDevice *device); - static int setErrorStream(OutputDevice *device); - - static void enableDebug(int flag); - static void enableInfo(int flag); - static void enableWarn(int flag); - static void enableError(int flag); - - static ostream *debugStream(void); - static ostream *infoStream(void); - static ostream *warnStream(void); - static ostream *errorStream(void); -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/winblows.cpp b/Generals/Code/Tools/Launcher/winblows.cpp deleted file mode 100644 index b5710df8ba..0000000000 --- a/Generals/Code/Tools/Launcher/winblows.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#include - -#include "winblows.h" - - -HINSTANCE Global_instance; -LPSTR Global_commandline; -int Global_commandshow; - - -/* - * WinMain - initialization, message loop - */ -int PASCAL WinMain( HINSTANCE instance, HINSTANCE, char *command_line, int command_show) -{ - //////MSG msg; - - Global_instance = instance; - Global_commandline = command_line; - Global_commandshow = command_show; - - int argc; - char *argv[64]; - - char path_to_exe[512]; - GetModuleFileName(instance,(char *)&path_to_exe,512); - argc=1; - argv[0]=path_to_exe; - - - int command_scan=0; - char command_char; - do - { - /* - ** Scan for non-space character on command line - */ - do - { - command_char = *( command_line+command_scan++ ); - } while ( command_char==' ' ); - - if ( command_char!=0 && command_char != 13 ) - { - argv[argc++]=command_line+command_scan-1; - - /* - ** Scan for space character on command line - */ - do - { - command_char = *( command_line+command_scan++ ); - } while ( command_char!=' ' && command_char != 0 && command_char!=13); - *( command_line+command_scan-1 ) = 0; - } - - } while ( command_char != 0 && command_char != 13 && argc<20 ); - - return(main(argc,argv)); - -} /* WinMain */ - - -int Print_WM(UINT message,char *out) -{ - switch(message) - { - case WM_NULL: - sprintf(out,"WM_NULL"); - break; - case WM_CREATE: - sprintf(out,"WM_CREATE"); - break; - case WM_DESTROY: - sprintf(out,"WM_DESTROY"); - break; - case WM_CANCELMODE: - sprintf(out,"WM_CANCELMODE"); - break; - case WM_ERASEBKGND: - sprintf(out,"WM_ERASEBKGND"); - break; - case WM_GETTEXT: - sprintf(out,"WM_GETTEXT"); - break; - case WM_QUERYOPEN: - sprintf(out,"WM_QUERYOPEN"); - break; - case WM_MOVE: - sprintf(out,"WM_MOVE"); - break; - case WM_SIZE: - sprintf(out,"WM_SIZE"); - break; - case WM_ACTIVATE: - sprintf(out,"WM_ACTIVATE"); - break; - case WM_SETFOCUS: - sprintf(out,"WM_SETFOCUS"); - break; - case WM_KILLFOCUS: - sprintf(out,"WM_KILLFOCUS"); - break; - case WM_ENABLE: - sprintf(out,"WM_ENABLE"); - break; - case WM_SETREDRAW: - sprintf(out,"WM_REDRAW"); - break; - case WM_PAINT: - sprintf(out,"WM_PAINT"); - break; - case WM_CLOSE: - sprintf(out,"WM_CLOSE"); - break; - case WM_QUIT: - sprintf(out,"WM_QUIT"); - break; - case WM_ACTIVATEAPP: - sprintf(out,"WM_ACTIVATEAPP"); - break; - case WM_SETCURSOR: - sprintf(out,"WM_SETCURSOR"); - break; - case WM_KEYDOWN: - sprintf(out,"WM_KEYDOWN"); - break; - case WM_MOUSEMOVE: - sprintf(out,"WM_MOUSEMOVE"); - break; - case WM_WINDOWPOSCHANGING: - sprintf(out,"WM_WINDOWPOSCHANGING"); - break; - case WM_WINDOWPOSCHANGED: - sprintf(out,"WM_WINDOWPOSCHANGED"); - break; - case WM_DISPLAYCHANGE: - sprintf(out,"WM_DISPLAYCHANGE"); - break; - case WM_NCPAINT: - sprintf(out,"WM_NCPAINT"); - break; - case WM_PALETTEISCHANGING: - sprintf(out,"WM_PALETTEISCHANGING"); - break; - case WM_PALETTECHANGED: - sprintf(out,"WM_PALETTECHANGED"); - break; - case WM_NCACTIVATE: - sprintf(out,"WM_NCACTIVATE"); - break; - case WM_NCCALCSIZE: - sprintf(out,"WM_NCCALCSIZE"); - break; - case WM_SYSCOMMAND: - sprintf(out,"WM_SYSCOMMAND"); - break; - default: - sprintf(out,"? UNKNOWN ?"); - return(-1); - } - return(0); -} diff --git a/Generals/Code/Tools/Launcher/winblows.h b/Generals/Code/Tools/Launcher/winblows.h deleted file mode 100644 index 57a6b54dfe..0000000000 --- a/Generals/Code/Tools/Launcher/winblows.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef WINBLOWS_HEADER -#define WINBLOWS_HEADER - -#define WIN32_LEAN_AND_MEAN -#include -#include -#include - -#include"wstypes.h" - - extern HINSTANCE Global_instance; - extern LPSTR Global_commandline; - extern int Global_commandshow; - - extern int main(int argc, char *argv[]); - - int Print_WM(UINT wm,char *out); - -#endif diff --git a/Generals/Code/Tools/Launcher/wstring.cpp b/Generals/Code/Tools/Launcher/wstring.cpp deleted file mode 100644 index 75cb9b9cca..0000000000 --- a/Generals/Code/Tools/Launcher/wstring.cpp +++ /dev/null @@ -1,611 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : string.cpp -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 - -A fairly typical string class. This string class always copies any input -string to it's own memory (for assignment or construction). -\***************************************************************************/ - -#include -#include -#include -#include - -#include "wstring.h" - -Wstring::Wstring():str(NULL) -{ } - -Wstring::Wstring(const char *string):str(NULL) -{ set(string); } - -Wstring::Wstring(const Wstring &other):str(NULL) -{ - if (other.str!=NULL) - { - str=new char[strlen(other.str)+1]; - strcpy(str,other.str); - } -} - -Wstring::~Wstring() -{ clear(); } - -bit8 Wstring::operator==(const char *other) -{ - if ((str==NULL)&&(other==NULL)) - return(TRUE); - if(strcmp(str, other) != 0) - return(FALSE); - else - return(TRUE); -} - -bit8 Wstring::operator==(const Wstring &other) -{ - if((str == NULL) && (other.str == NULL)) - return(TRUE); - - if((str == NULL) || (other.str == NULL)) - return(FALSE); - - if(strcmp(str, other.str) != 0) - return(FALSE); - else - return(TRUE); -} - - -bit8 Wstring::operator!=(const char *other) -{ - if(strcmp(str, other) != 0) - return(TRUE); - else - return(FALSE); -} - - -bit8 Wstring::operator!=(const Wstring &other) -{ - if((str == NULL) && (other.str == NULL)) - return(FALSE); - - if((str == NULL) || (other.str == NULL)) - return(TRUE); - - if(strcmp(str, other.str) != 0) - return(TRUE); - else - return(FALSE); -} - - -Wstring &Wstring::operator=(const char *other) -{ - set(other); - return(*this); -} - - -Wstring &Wstring::operator=(const Wstring &other) -{ - if(*this == other) - return(*this); - - set(other.get()); - return(*this); -} - - -bit8 Wstring::cat(const char *s) -{ - char *oldStr; - uint32 len; - - if (s==NULL) // it's OK to cat nothing - return(TRUE); - - // Save the contents of the string. - oldStr = str; - - // Determine the length of the resultant string. - len = strlen(s) + 1; - if(oldStr) - len += strlen(oldStr); - - // Allocate memory for the new string. - - if(!(str = new char[(len * sizeof(char))])) - { - str = oldStr; - return(FALSE); - } - - // Copy the contents of the old string and concatenate the passed - // string. - if(oldStr) strcpy(str, oldStr); - else str[0] = 0; - - strcat(str, s); - - // delete the old string. - if(oldStr) - delete[](oldStr); - - return(TRUE); -} - - -bit8 Wstring::cat(uint32 size, const char *s) -{ - char *oldStr; - uint32 len; - - // Save the contents of the string. - oldStr = str; - - // Determine the length of the resultant string. - len = size + 1; - if(oldStr) - len += strlen(oldStr); - - // Allocate memory for the new string. - if(!(str = new char[(len * sizeof(char))])) - { - str = oldStr; - return(FALSE); - } - - // Copy the contents of the old string and concatenate the passed - // string. - if(oldStr) - strcpy(str, oldStr); - else - str[0] = 0; - - strncat(str, s, size); - - // delete the old string. - if(oldStr) - delete[](oldStr); - - return(TRUE); -} - -bit8 Wstring::cat(const Wstring &other) -{ - return cat(other.get()); -} - -Wstring &Wstring::operator+=(const char *string) -{ - cat(string); - return(*this); -} - -Wstring &Wstring::operator+=(const Wstring &other) -{ - cat(other.get()); - return(*this); -} - -Wstring Wstring::operator+(const char *string) -{ - Wstring temp = *this; - temp.cat(string); - return(temp); -} - -Wstring Wstring::operator+(const Wstring &s) -{ - Wstring temp = *this; - temp.cat(s); - return(temp); -} - -// -// This function deletes 'count' characters indexed by `pos' from the Wstring. -// If `pos'+'count' is > the length of the array, the last 'count' characters -// of the string are removed. If an error occurs, FALSE is returned. -// Otherwise, TRUE is returned. Note: count has a default value of 1. -// -// -char Wstring::remove(sint32 pos,sint32 count) -{ - char *s; - sint32 len; - - if (!str) - return(FALSE); - - len = (sint32)strlen(str); - - if(pos+count > len) - pos = len - count; - if (pos < 0) - { - count+=pos; // If they remove before 0, ignore up till beginning - pos=0; - } - if (count<=0) - return(FALSE); - - if(!(s = new char[len-count+1])) - { - //ErrorMessage(SET_EM, "Insufficient memory to modify Wstring."); - return(FALSE); - } - - ///////DBGMSG("Wstring::remove POS: "<strlen(str)) - pos=strlen(str); - char *newstr=new char[strlen(str)+strlen(instring)+1]; - memset(newstr,0,strlen(str)+strlen(instring)+1); - strcpy(newstr,str); - // move the old data out of the way - int bytes=strlen(str)+1-pos; - memmove(newstr+pos+strlen(instring),newstr+pos,bytes); - // move the new data into place - memmove(newstr+pos,instring,strlen(instring)); - delete[](str); - str=newstr; - return(TRUE); -} - -// This function inserts the character specified by `k' into the string at the -// position indexed by `pos'. If `pos' is >= the length of the string, it is -// appended to the string. If an error occurs, FALSE is returned. Otherwise, -// TRUE is returned. -bit8 Wstring::insert(char k, uint32 pos) -{ - char *s; - uint32 len; - char c[2]; - - if(!str) - { - c[0] = k; - c[1] = 0; - return(set(c)); - } - - len = (uint32)strlen(str); - - if(pos > len) - pos = len; - - if(!(s = (char *)new char[(len + 2)])) - { - //ErrorMessage(SET_EM, "Insufficient memory to modify Wstring."); - return(FALSE); - } - - c[0] = str[pos]; - str[pos] = 0; - c[1] = 0; - strcpy(s, str); - str[pos] = c[0]; - c[0] = k; - strcat(s, c); - strcat(s, &(str[pos])); - delete[](str); - str = s; - - return(TRUE); -} - - -// This function replaces any occurences of the string pointed to by -// `replaceThis' with the string pointed to by `withThis'. If an error -// occurs, FALSE is returned. Otherwise, TRUE is returned. -bit8 Wstring::replace(const char *replaceThis, const char *withThis) -{ - Wstring dest; - const char *foundStr, *src; - uint32 len; - - src=get(); - while(src && src[0]) - { - foundStr = strstr(src, replaceThis); - if(foundStr) - { - len = (uint32)foundStr - (uint32)src; - if(len) - { - if(!dest.cat(len, src)) - return(FALSE); - } - if(!dest.cat(withThis)) - return(FALSE); - src = foundStr + strlen(replaceThis); - } - else - { - if(!dest.cat(src)) - return(FALSE); - - src=NULL; - } - } - return(set(dest.get())); -} - - -bit8 Wstring::set(const char *s) -{ - uint32 len; - - clear(); - - len = (uint32)strlen(s) + 1; - - if(!(str = new char[len])) - { - //ErrorMessage(SET_EM, "Insufficient memory to set Wstring."); - return(FALSE); - } - strcpy(str, s); - - return(TRUE); -} - - -bit8 Wstring::set(char c, uint32 index) -{ - if(index >= (uint32)strlen(str)) - return FALSE; - - str[index] = c; - - return TRUE; -} - - -char Wstring::set(uint32 size, const char *string) -{ - uint32 len; - - clear(); - len = size + 1; - - if(!(str = new char[len])) - { - //ErrorMessage(SET_EM, "Insufficient memory to set Wstring."); - return(FALSE); - } - - // Copy the bytes in the string, and NULL-terminate it. - strncpy(str, string, size); - str[size] = 0; - - return(TRUE); -} - - -// This function converts all alphabetical characters in the string to lower -// case. -void Wstring::toLower(void) -{ - uint32 i; - - for(i = 0; i < length(); i++) - { - if((str[i] >= 'A') && (str[i] <= 'Z')) - str[i] = tolower(str[i]); - } -} - - -// This function converts all alphabetical characters in the string to upper -// case. -void Wstring::toUpper(void) -{ - uint32 i; - - for(i = 0; i < length(); i++) - { - if((str[i] >= 'a') && (str[i] <= 'z')) - str[i] = toupper(str[i]); - } -} - - -// This function truncates the string so its length will match the specified -// `len'. If an error occurs, FALSE is returned. Otherwise, TRUE is returned. -bit8 Wstring::truncate(uint32 len) -{ - Wstring tmp; - if(!tmp.set(len, get()) || !set(tmp.get())) - return(FALSE); - return(TRUE); -} - -// Truncate the string after the character 'c' (gets rid of 'c' as well) -// Do nothing if 'c' isn't in the string -bit8 Wstring::truncate(char c) -{ - sint32 len; - - if (str==NULL) - return(FALSE); - - char *cptr=strchr(str,c); - if (cptr==NULL) - return(FALSE); - len=(sint32)(cptr-str); - truncate((uint32)len); - return(TRUE); -} - -// Get a token from this string that's seperated by one or more -// chars from the 'delim' string , start at offset & return offset -sint32 Wstring::getToken(int offset,const char *delim,Wstring &out) -{ - int i; - sint32 start; - sint32 stop; - for (i=offset; i<(int)length(); i++) { - if(strchr(delim,str[i])==NULL) - break; - } - if (i>=(int)length()) - return(-1); - start=i; - - for (; i<(int)length(); i++) { - if(strchr(delim,str[i])!=NULL) - break; - } - stop=i-1; - out.set(str+start); - out.truncate((uint32)stop-start+1); - return(stop+1); -} - -// Get the first line of text after offset. Lines are terminated by '\r\n' or '\n' -sint32 Wstring::getLine(int offset, Wstring &out) -{ - int i; - sint32 start; - sint32 stop; - - start=i=offset; - if (start >= (int)length()) - return(-1); - - for (; i<(int)length(); i++) { - if(strchr("\r\n",str[i])!=NULL) - break; - } - stop=i; - if ((str[stop]=='\r')&&(str[stop+1]=='\n')) - stop++; - - out.set(str+start); - out.truncate((uint32)stop-start+1); - return(stop+1); -} diff --git a/Generals/Code/Tools/Launcher/wstring.h b/Generals/Code/Tools/Launcher/wstring.h deleted file mode 100644 index 448085774c..0000000000 --- a/Generals/Code/Tools/Launcher/wstring.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : main.cpp -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 -\****************************************************************************/ - -#ifndef WSTRING_HEADER -#define WSTRING_HEADER - -#include -#include -#include "wstypes.h" - -class Wstring -{ - public: - Wstring(); - Wstring(const Wstring &other); - Wstring(const char *string); - ~Wstring(); - - void clear(void); - - bit8 cat(const char *string); - bit8 cat(uint32 size,const char *string); - bit8 cat(const Wstring &string); - - void cellCopy(OUT char *dest, uint32 len); - char remove(sint32 pos, sint32 count); - bit8 removeChar(char c); - void removeSpaces(void); - const char *get(void) const; - char get(uint32 index) const; - uint32 length(void) const; - bit8 insert(char c, uint32 pos); - bit8 insert(const char *instring, uint32 pos); - bit8 replace(const char *replaceThis,const char *withThis); - char set(const char *str); - char set(uint32 size,const char *str); - bit8 set(char c, uint32 index); - void setSize(sint32 bytes); // create an empty string - void toLower(void); - void toUpper(void); - bit8 truncate(uint32 len); - bit8 truncate(char c); // trunc after char c - sint32 getToken(int offset,const char *delim,Wstring &out); - sint32 getLine(int offset, Wstring &out); - - bit8 operator==(const char *other); - bit8 operator==(const Wstring &other); - bit8 operator!=(const char *other); - bit8 operator!=(const Wstring &other); - - Wstring &operator=(const char *other); - Wstring &operator=(const Wstring &other); - Wstring &operator+=(const char *other); - Wstring &operator+=(const Wstring &other); - Wstring operator+(const char *other); - Wstring operator+(const Wstring &other); - - private: - char *str; // Pointer to allocated string. -}; - -#endif diff --git a/Generals/Code/Tools/Launcher/wstypes.h b/Generals/Code/Tools/Launcher/wstypes.h deleted file mode 100644 index d436801a39..0000000000 --- a/Generals/Code/Tools/Launcher/wstypes.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: -File Name : wtypes.h -Author : Neal Kettler -Start Date : June 3, 1997 -Last Update : June 17, 1997 - -Standard type definitions for the sake of portability and readability. -\***************************************************************************/ - -#ifndef WTYPES_HEADER -#define WTYPES_HEADER - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - -#ifndef MIN -#define MIN(x,y) (((x)<(y))?(x):(y)) -#endif - -#ifndef MAX -#define MAX(x,y) (((x)>(y))?(x):(y)) -#endif - -#ifndef NULL -#define NULL 0 -#endif - -//These are used for readability purposes mostly, when a method takes a -// pointer or reference these help specify what will happen to the data -// that is sent in. -#define IN -#define OUT -#define INOUT - -typedef char bit8; -typedef char sint8; -typedef unsigned char uint8; -typedef signed short int sint16; -typedef unsigned short int uint16; -typedef signed int sint32; -typedef unsigned int uint32; - -#define MAX_BIT8 0x1 -#define MAX_UINT32 0xFFFFFFFF -#define MAX_UINT16 0xFFFF -#define MAX_UINT8 0xFF -#define MAX_SINT32 0x7FFFFFFF -#define MAX_SINT16 0x7FFF -#define MAX_SINT8 0x7F - -#ifdef _WIN32 -#define strncasecmp _strnicmp -#define strcasecmp _stricmp -#endif - -#endif diff --git a/Generals/Code/Tools/MapCacheBuilder/CMakeLists.txt b/Generals/Code/Tools/MapCacheBuilder/CMakeLists.txt index 4bf0c95ca9..f11d0f24c0 100644 --- a/Generals/Code/Tools/MapCacheBuilder/CMakeLists.txt +++ b/Generals/Code/Tools/MapCacheBuilder/CMakeLists.txt @@ -1,30 +1,9 @@ -set(MAPCACHEBUILDER_SRC - "Include/WinMain.h" - "Resource/Resource.h" - "Source/WinMain.cpp" -) - add_executable(g_mapcachebuilder WIN32) set_target_properties(g_mapcachebuilder PROPERTIES OUTPUT_NAME mapcachebuilder) -target_sources(g_mapcachebuilder PRIVATE ${MAPCACHEBUILDER_SRC}) - -target_include_directories(g_mapcachebuilder PRIVATE - Include - Resource -) -# target_link_libraries(g_mapcachebuilder PRIVATE - comctl32 - dbghelplib + corei_mapcachebuilder g_gameengine g_gameenginedevice gi_always - imm32 - vfw32 - winmm ) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(g_mapcachebuilder PRIVATE Resource/MapCacheBuilder.rc) -endif() diff --git a/Generals/Code/Tools/MapCacheBuilder/Include/WinMain.h b/Generals/Code/Tools/MapCacheBuilder/Include/WinMain.h deleted file mode 100644 index a0638f3bf5..0000000000 --- a/Generals/Code/Tools/MapCacheBuilder/Include/WinMain.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: WinMain.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: ImagePacker -// -// File name: WinMain.h -// -// Created: Colin Day, August 2001 -// -// Desc: Header for main app -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __WINMAIN_H_ -#define __WINMAIN_H_ - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// - -// FORWARD REFERENCES ///////////////////////////////////////////////////////// - -// TYPE DEFINES /////////////////////////////////////////////////////////////// - -// INLINING /////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// EXTERNALS ////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -extern HINSTANCE ApplicationHInstance; - -#endif // __WINMAIN_H_ - diff --git a/Generals/Code/Tools/MapCacheBuilder/Resource/Resource.h b/Generals/Code/Tools/MapCacheBuilder/Resource/Resource.h deleted file mode 100644 index 2cadd6831e..0000000000 --- a/Generals/Code/Tools/MapCacheBuilder/Resource/Resource.h +++ /dev/null @@ -1,55 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by MapPackBuilder.rc -// -#define IDD_DIALOG1 101 -#define IMAGE_PACKER_DIALOG 101 -#define IMAGE_ERRORS 102 -#define PAGE_ERRORS 103 -#define DIRECTORY_SELECT_DIALOG 104 -#define BUTTON_START 1000 -#define BUTTON_EXIT 1001 -#define LIST_FOLDERS 1002 -#define RADIO_128X128 1003 -#define RADIO_256X256 1004 -#define RADIO_512X512 1005 -#define RADIO_TARGET_OTHER 1006 -#define EDIT_WIDTH 1007 -#define EDIT_HEIGHT 1008 -#define BUTTON_ADD_FOLDER 1009 -#define BUTTON_REMOVE_FOLDER 1010 -#define EDIT_FILENAME 1011 -#define CHECK_USE_SUB_FOLDERS 1012 -#define STATIC_X 1013 -#define STATIC_STATUS 1014 -#define BUTTON_PREVIEW 1016 -#define BUTTON_PREVIOUS 1017 -#define BUTTON_NEXT 1018 -#define LIST_IMAGES 1018 -#define EDIT_GUTTER 1019 -#define CHECK_ALPHA 1020 -#define CHECK_BITMAP_PREVIEW 1021 -#define CHECK_GDF 1022 -#define CHECK_INI 1022 -#define BUTTON_PROCEED 1023 -#define BUTTON_CANCEL 1024 -#define LIST_PAGES 1025 -#define BUTTON_ADD 1027 -#define LIST_DIR 1028 -#define STATIC_CURRENT_DIR 1031 -#define COMBO_DRIVE 1032 -#define CHECK_COMPRESS 1033 -#define CHECK_GAP_EXTEND_RGB 1037 -#define CHECK_GAP_GUTTER 1038 -#define STATIC_GAP_INFO 1039 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 105 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1040 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/MapCacheBuilder/Source/WinMain.cpp b/Generals/Code/Tools/MapCacheBuilder/Source/WinMain.cpp deleted file mode 100644 index 5681aa0786..0000000000 --- a/Generals/Code/Tools/MapCacheBuilder/Source/WinMain.cpp +++ /dev/null @@ -1,340 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: WinMain.cpp ////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: MapCacheBuilder -// -// File name: WinMain.cpp -// -// Created: Matthew D. Campbell, October 2002 -// -// Desc: Application entry point for the standalone MapCache Builder -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#include -#include -#include - -// USER INCLUDES ////////////////////////////////////////////////////////////// -#include "Lib/BaseType.h" -#include "Common/Debug.h" -#include "Common/GameMemory.h" -#include "Common/GlobalData.h" -#include "Common/NameKeyGenerator.h" -#include "Resource.h" - -#include "Common/ThingFactory.h" -#include "Common/FileSystem.h" -#include "Win32Device/Common/Win32LocalFileSystem.h" -#include "Win32Device/Common/Win32BIGFileSystem.h" -#include "Common/SubsystemInterface.h" -#include "GameClient/MapUtil.h" -#include "W3DDevice/Common/W3DModuleFactory.h" - - -#include "Common/FileSystem.h" -#include "Common/ArchiveFileSystem.h" -#include "Common/LocalFileSystem.h" -#include "Common/Debug.h" -#include "Common/StackDump.h" -#include "Common/GameMemory.h" -#include "Common/Science.h" -#include "Common/ThingFactory.h" -#include "Common/INI.h" -#include "Common/GameAudio.h" -#include "Common/SpecialPower.h" -#include "Common/TerrainTypes.h" -#include "Common/DamageFX.h" -#include "Common/Upgrade.h" -#include "Common/ModuleFactory.h" -#include "Common/PlayerTemplate.h" -#include "Common/MultiplayerSettings.h" - -#include "GameLogic/Armor.h" -#include "GameLogic/CaveSystem.h" -#include "GameLogic/CrateSystem.h" -#include "GameLogic/ObjectCreationList.h" -#include "GameLogic/Weapon.h" -#include "GameLogic/RankInfo.h" -#include "GameLogic/SidesList.h" -#include "GameLogic/ScriptEngine.h" -#include "GameLogic/ScriptActions.h" -#include "GameClient/Anim2D.h" -#include "GameClient/GameText.h" -#include "GameClient/ParticleSys.h" -#include "GameClient/Water.h" -#include "GameClient/TerrainRoads.h" -#include "GameClient/FXList.h" -#include "GameClient/VideoPlayer.h" -#include "GameLogic/Locomotor.h" - -#include "W3DDevice/Common/W3DModuleFactory.h" -#include "W3DDevice/GameClient/W3DParticleSys.h" -#include "MilesAudioDevice/MilesAudioManager.h" - -#include -#include "Win32Device/GameClient/Win32Mouse.h" -#include "Win32Device/Common/Win32LocalFileSystem.h" -#include "Win32Device/Common/Win32BIGFileSystem.h" -#include "trim.h" - - -// DEFINES //////////////////////////////////////////////////////////////////// - -// PRIVATE TYPES ////////////////////////////////////////////////////////////// - -#ifdef _INTERNAL -// for occasional debugging... -//#pragma optimize("", off) -//#pragma message("************************************** WARNING, optimization disabled for debugging purposes") -#endif - -// PRIVATE DATA /////////////////////////////////////////////////////////////// - -static SubsystemInterfaceList _TheSubsystemList; - -template -void initSubsystem(SUBSYSTEM*& sysref, SUBSYSTEM* sys, const char* path1 = NULL, const char* path2 = NULL, const char* dirpath = NULL) -{ - sysref = sys; - _TheSubsystemList.initSubsystem(sys, path1, path2, dirpath, NULL); -} - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC DATA //////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -HINSTANCE ApplicationHInstance = NULL; ///< our application instance - -/// just to satisfy the game libraries we link to -HWND ApplicationHWnd = NULL; - -const char *gAppPrefix = "MC_"; - -// Where are the default string files? -const Char *g_strFile = "data\\Generals.str"; -const Char *g_csfFile = "data\\%s\\Generals.csf"; - -// PRIVATE PROTOTYPES ///////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////// -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -static char *nextParam(char *newSource, const char *seps) -{ - static char *source = NULL; - if (newSource) - { - source = newSource; - } - if (!source) - { - return NULL; - } - - // find first separator - char *first = source;//strpbrk(source, seps); - if (first) - { - // go past initial spaces - char *firstNonSpace = first; - while (*firstNonSpace == ' ') - ++firstNonSpace; - first = firstNonSpace; - - // go past separator - char *firstSep = strpbrk(first, seps); - char firstChar[2] = {0,0}; - if (firstSep == first) - { - firstChar[0] = *first; - while (*first == firstChar[0]) first++; - } - - // find end - char *end; - if (firstChar[0]) - end = strpbrk(first, firstChar); - else - end = strpbrk(first, seps); - - // trim string & save next start pos - if (end) - { - source = end+1; - *end = 0; - - if (!*source) - source = NULL; - } - else - { - source = NULL; - } - - if (first && !*first) - first = NULL; - } - - return first; -} - -/////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -// WinMain ==================================================================== -/** Application entry point */ -//============================================================================= -Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPSTR lpCmdLine, Int nCmdShow ) -{ - - // start the log - DEBUG_INIT(DEBUG_FLAGS_DEFAULT); - initMemoryManager(); - - try - { - - // save application instance - ApplicationHInstance = hInstance; - - - // Set the current directory to the app directory. - char buf[_MAX_PATH]; - GetModuleFileName(NULL, buf, sizeof(buf)); - char *pEnd = buf + strlen(buf); - while (pEnd != buf) { - if (*pEnd == '\\') { - *pEnd = 0; - break; - } - pEnd--; - } - ::SetCurrentDirectory(buf); - - /* - ** Convert WinMain arguments to simple main argc and argv - */ - std::list argvSet; - char *token; - token = nextParam(lpCmdLine, "\" "); - while (token != NULL) { - char * str = strtrim(token); - argvSet.push_back(str); - DEBUG_LOG(("Adding '%s'\n", str)); - token = nextParam(NULL, "\" "); - } - - // not part of the subsystem list, because it should normally never be reset! - TheNameKeyGenerator = new NameKeyGenerator; - TheNameKeyGenerator->init(); - - TheFileSystem = new FileSystem; - - initSubsystem(TheLocalFileSystem, (LocalFileSystem*)new Win32LocalFileSystem); - initSubsystem(TheArchiveFileSystem, (ArchiveFileSystem*)new Win32BIGFileSystem); - INI ini; - initSubsystem(TheWritableGlobalData, new GlobalData(), "Data\\INI\\Default\\GameData.ini", "Data\\INI\\GameData.ini"); - initSubsystem(TheGameText, CreateGameTextInterface()); - initSubsystem(TheScienceStore, new ScienceStore(), "Data\\INI\\Default\\Science.ini", "Data\\INI\\Science.ini"); - initSubsystem(TheMultiplayerSettings, new MultiplayerSettings(), "Data\\INI\\Default\\Multiplayer.ini", "Data\\INI\\Multiplayer.ini"); - initSubsystem(TheTerrainTypes, new TerrainTypeCollection(), "Data\\INI\\Default\\Terrain.ini", "Data\\INI\\Terrain.ini"); - initSubsystem(TheTerrainRoads, new TerrainRoadCollection(), "Data\\INI\\Default\\Roads.ini", "Data\\INI\\Roads.ini"); - initSubsystem(TheScriptEngine, (ScriptEngine*)(new ScriptEngine())); - initSubsystem(TheAudio, (AudioManager*)new MilesAudioManager()); - initSubsystem(TheVideoPlayer, (VideoPlayerInterface*)(new VideoPlayer())); - initSubsystem(TheModuleFactory, (ModuleFactory*)(new W3DModuleFactory())); - initSubsystem(TheSidesList, new SidesList()); - initSubsystem(TheCaveSystem, new CaveSystem()); - initSubsystem(TheRankInfoStore, new RankInfoStore(), NULL, "Data\\INI\\Rank.ini"); - initSubsystem(ThePlayerTemplateStore, new PlayerTemplateStore(), "Data\\INI\\Default\\PlayerTemplate.ini", "Data\\INI\\PlayerTemplate.ini"); - initSubsystem(TheSpecialPowerStore, new SpecialPowerStore(), "Data\\INI\\Default\\SpecialPower.ini", "Data\\INI\\SpecialPower.ini" ); - initSubsystem(TheParticleSystemManager, (ParticleSystemManager*)(new W3DParticleSystemManager())); - initSubsystem(TheFXListStore, new FXListStore(), "Data\\INI\\Default\\FXList.ini", "Data\\INI\\FXList.ini"); - initSubsystem(TheWeaponStore, new WeaponStore(), NULL, "Data\\INI\\Weapon.ini"); - initSubsystem(TheObjectCreationListStore, new ObjectCreationListStore(), "Data\\INI\\Default\\ObjectCreationList.ini", "Data\\INI\\ObjectCreationList.ini"); - initSubsystem(TheLocomotorStore, new LocomotorStore(), NULL, "Data\\INI\\Locomotor.ini"); - initSubsystem(TheDamageFXStore, new DamageFXStore(), NULL, "Data\\INI\\DamageFX.ini"); - initSubsystem(TheArmorStore, new ArmorStore(), NULL, "Data\\INI\\Armor.ini"); - initSubsystem(TheThingFactory, new ThingFactory(), "Data\\INI\\Default\\Object.ini", NULL, "Data\\INI\\Object"); - initSubsystem(TheCrateSystem, new CrateSystem(), "Data\\INI\\Default\\Crate.ini", "Data\\INI\\Crate.ini"); - initSubsystem(TheUpgradeCenter, new UpgradeCenter, "Data\\INI\\Default\\Upgrade.ini", "Data\\INI\\Upgrade.ini"); - initSubsystem(TheAnim2DCollection, new Anim2DCollection ); //Init's itself. - - _TheSubsystemList.postProcessLoadAll(); - - TheWritableGlobalData->m_buildMapCache = TRUE; - - TheMapCache = new MapCache; - - // add in allowed maps - for (std::list::const_iterator cit = argvSet.begin(); cit != argvSet.end(); ++cit) - { - DEBUG_LOG(("Adding shipping map: '%s'\n", cit->c_str())); - TheMapCache->addShippingMap((*cit).c_str()); - } - - TheMapCache->updateCache(); - - delete TheMapCache; - TheMapCache = NULL; - - // load the dialog box - //DialogBox( hInstance, (LPCTSTR)IMAGE_PACKER_DIALOG, - // NULL, (DLGPROC)ImagePackerProc ); - - // delete TheGlobalData - //delete TheGlobalData; - //TheGlobalData = NULL; - - _TheSubsystemList.shutdownAll(); - - delete TheFileSystem; - TheFileSystem = NULL; - - delete TheNameKeyGenerator; - TheNameKeyGenerator = NULL; - - } - catch (...) - { - DEBUG_CRASH(("Munkee munkee!")); - } - - // close the log - shutdownMemoryManager(); - DEBUG_SHUTDOWN(); - - // all done - return 0; - -} // end WinMain diff --git a/Generals/Code/Tools/PATCHGET/CHATAPI.CPP b/Generals/Code/Tools/PATCHGET/CHATAPI.CPP deleted file mode 100644 index 66b828e26a..0000000000 --- a/Generals/Code/Tools/PATCHGET/CHATAPI.CPP +++ /dev/null @@ -1,1801 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// This module takes care of all the Chat API stuff -// - -#include -#include "gamespy/ghttp/ghttp.h" -#include "DownloadManager.h" - -#include "CHATAPI.H" - -//#include "api/wolapi_i.c" // This should only be in one .cpp file -#include -#include -#include -#include -#if defined(_MSC_VER) && _MSC_VER < 1300 -#include -#endif -#include "RESOURCE.H" -#include "WINBLOWS.H" -#include -#include "process.h" -#include "WWDownload/Registry.h" -#include "WWDownload/urlBuilder.h" -#include "debug.h" - -namespace patchget -{ - -enum EVENT_TYPES -{ - NOUPDATE_EVENT=0, // don't need to update - ABORT_EVENT, - NUM_EVENTS // keep last -}; - -HANDLE Events[NUM_EVENTS]; - -char g_UpdateString[256]; // for the filename -char g_DLTimeRem[80]; -char g_DLBytesLeft[80]; -char g_DLBPS[80]; - -int g_Finished=0; - - -HWND g_DownloadWindow; -HWND g_ContactWindow; -HWND g_PrimaryWindow; - -static bool checkingForPatch = false; -static int checksLeft = 0; -static bool cantConnect = false; -static std::list queuedDownloads; - -BOOL CALLBACK downloadDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, - LPARAM lParam ); - -/////////////////////////////////////////////////////////////////////////////////////// - -static void startOnline( void ); - -/////////////////////////////////////////////////////////////////////////////////////// - -QueuedDownload TheDownload; - -class DownloadManagerMunkee : public DownloadManager -{ -public: - DownloadManagerMunkee() { } - virtual HRESULT OnError( int error ); - virtual HRESULT OnEnd(); - virtual HRESULT OnProgressUpdate( int bytesread, int totalsize, int timetaken, int timeleft ); - virtual HRESULT OnStatusUpdate( int status ); - virtual HRESULT downloadFile( std::string server, std::string username, std::string password, std::string file, std::string localfile, std::string regkey, bool tryResume ); -}; - -/////////////////////////////////////////////////////////////////////////////////////// - -HRESULT DownloadManagerMunkee::downloadFile( std::string server, std::string username, std::string password, std::string file, std::string localfile, std::string regkey, bool tryResume ) -{ - /* - if (staticTextFile) - { - UnicodeString fileString; - fileString.translate(file); - GadgetStaticTextSetText(staticTextFile, fileString); - } - */ - return DownloadManager::downloadFile( server, username, password, file, localfile, regkey, tryResume ); -} -HRESULT DownloadManagerMunkee::OnError( int error ) -{ - HRESULT ret = DownloadManager::OnError( error ); - g_Finished = -1; - return ret; -} -HRESULT DownloadManagerMunkee::OnEnd() -{ - HRESULT ret = DownloadManager::OnEnd(); - g_Finished = 1; - return ret; -} -HRESULT DownloadManagerMunkee::OnProgressUpdate( int bytesread, int totalsize, int timetaken, int timeleft ) -{ - HRESULT ret = DownloadManager::OnProgressUpdate( bytesread, totalsize, timetaken, timeleft ); - - SendDlgItemMessage( g_DownloadWindow, IDC_PROGRESS, PBM_SETPOS, (WPARAM)(bytesread * 100) / totalsize, 0 ); - char temp[256]; - - if( timeleft > 0 ) - { - //DBGMSG("Bytes read: "<=0 && i start) - { - int len = end - start; - char* tmp = new char[len+1]; - memcpy(tmp, start, len); - tmp[len] = 0; - - tok = tmp; - delete[] tmp; - - base = end; - - return true; - } - else - { - base = tok = ""; - return false; - } -} - -/////////////////////////////////////////////////////////////////////////////////////// - -static void queuePatch(bool mandatory, std::string downloadURL) -{ - // downloadURL is of the form "ftp://ftp.ea.com:user@pass/pub/munkee/bananna.rtp" - QueuedDownload q; - bool success = true; - - std::string connectionType; - success = success && nextToken(downloadURL, connectionType, ":"); - - std::string server; - success = success && nextToken(downloadURL, server, ":/"); - - std::string user; - success = success && nextToken(downloadURL, user, ":@"); - - std::string pass; - success = success && nextToken(downloadURL, pass, "@/"); - - std::string filePath; - success = success && nextToken(downloadURL, filePath, ""); - - if (!success && !user.empty()) - { - // no user/pass combo - move the file into it's proper place - filePath = user; - user = ""; // LFeenanEA - Credentials removed as per Security requirements - pass = ""; - success = true; - } - - std::string fileStr = filePath; - unsigned int slashPos = filePath.find_last_of('/'); - std::string fileDir = "patches\\"; - std::string fileName = ""; - if (slashPos == filePath.npos) - { - fileName = filePath; - } - else - { - fileName = filePath.substr(slashPos+1); - } - fileDir.append(fileName); - - DEBUG_LOG(("download URL split: %d [%s] [%s] [%s] [%s] [%s] [%s] [%s]\n", - success, connectionType.c_str(), server.c_str(), user.c_str(), pass.c_str(), - filePath.c_str(), fileName.c_str(), fileDir.c_str())); - - if (!success) - return; - - q.file = filePath; - q.localFile = fileDir; - q.password = pass; - q.regKey = ""; - q.server = server; - q.tryResume = true; - q.userName = user; - - std::list::iterator it = queuedDownloads.begin(); - while (it != queuedDownloads.end()) - { - if (it->localFile == q.localFile) - return; // don't add it if it exists already (because we can check multiple times) - ++it; - } - - queuedDownloads.push_back(q); -} - -/////////////////////////////////////////////////////////////////////////////////////// - -static GHTTPBool patchCheckCallback( GHTTPRequest request, GHTTPResult result, char * buffer, GHTTPByteCount bufferLen, void * param ) -{ - --checksLeft; - DEBUG_ASSERTCRASH(checksLeft>=0, ("Too many callbacks")); - - DEBUG_LOG(("Result=%d, buffer=[%s], len=%d\n", result, buffer, bufferLen)); - if (result != GHTTPSuccess) - { - cantConnect = true; - if (!checksLeft) - { - startOnline(); - } - return GHTTPTrue; - } - - std::string message = buffer; - std::string line; - while (nextToken(message, line, "\r\n")) - { - std::string type, req, url; - bool ok = true; - ok = ok && nextToken(line, type, " "); - ok = ok && nextToken(line, req, " "); - ok = ok && nextToken(line, url, " "); - if (ok && type == "patch") - { - DEBUG_LOG(("Saw a patch: %d/[%s]\n", atoi(req.c_str()), url.c_str())); - queuePatch( atoi(req.c_str()), url ); - } - else if (ok && type == "server") - { - } - } - - if (!checksLeft) - { - startOnline(); - } - - return GHTTPTrue; -} - -/////////////////////////////////////////////////////////////////////////////////////// - -static void StartPatchCheck( void ) -{ - checkingForPatch = true; - std::string gameURL, mapURL; - std::string configURL, motdURL; - - FormatURLFromRegistry(gameURL, mapURL, configURL, motdURL); - - std::string proxy; - if (GetStringFromRegistry("", "Proxy", proxy)) - { - if (!proxy.empty()) - { - ghttpSetProxy(proxy.c_str()); - } - } - - // check for a patch first - checksLeft = 2; - cantConnect = false; - ghttpGet(gameURL.c_str(), GHTTPFalse, patchCheckCallback, NULL); - ghttpGet(mapURL.c_str(), GHTTPFalse, patchCheckCallback, NULL); - - DEBUG_LOG(("Started looking for patches at '%s' && '%s'\n", gameURL.c_str(), mapURL.c_str())); -} - -/////////////////////////////////////////////////////////////////////////////////////// - - -BOOL CALLBACK downloadDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) -{ - // HRESULT res; - - int cmd = LOWORD(wParam); - switch( uMsg ) - { - case WM_COMMAND: - if ( cmd == IDC_DLABORT ) - { - - char abort[128]; - char abortdload[256]; - LoadString(Global_instance, TXT_ABORT_DOWNLOAD, abortdload, sizeof(abortdload)); - LoadString(Global_instance, TXT_ABORT, abort, sizeof(abort)); - - if (MessageBox(g_PrimaryWindow,abortdload,abort,MB_YESNO)==IDYES) - { - TheDownloadManager->reset(); - - EndDialog( hwndDlg, g_Finished ); - DestroyWindow(hwndDlg); - } - } - else - { - return FALSE; - } - break; - - case WM_INITDIALOG: - //SetupDownload(); - - SendMessage(hwndDlg, WM_SETICON,(WPARAM)ICON_SMALL, - (LPARAM)LoadIcon(Global_instance, MAKEINTRESOURCE(IDI_ICON1))); - - g_DLTimeRem[0]=0; - g_DLBytesLeft[0]=0; - g_DLBPS[0]=0; - - //SetDlgItemText( hwndDlg, IDC_DOWNLOADTITLE, g_UpdateString); - //SetWindowText(hwndDlg, g_UpdateString); - - SetDlgItemText( hwndDlg, IDC_TIMEREM, g_DLTimeRem); - SetDlgItemText( hwndDlg, IDC_BYTESLEFT, g_DLBytesLeft); - // SetDlgItemText( hwndDlg, IDC_BPS, g_DLBPS ); - - // Work out the full file name - //char fullpath[_MAX_PATH]; - //char localfile[_MAX_PATH]; - //sprintf( fullpath, "%s/%s", g_Update->patchpath,g_Update->patchfile); - //sprintf(localfile,"%s\\%s",g_Update->localpath,g_Update->patchfile); - - // Create the directory - //CreateDirectory((char *)g_Update->localpath, NULL ); - - TheDownloadManager->downloadFile(TheDownload.server, TheDownload.userName, TheDownload.password, - TheDownload.file, TheDownload.localFile, TheDownload.regKey, TheDownload.tryResume); - /* - res=pDownload->DownloadFile((char *)g_Update->server, (char *)g_Update->login, (char *)g_Update->password, - fullpath, localfile, APP_REG_KEY); - - */ - g_DownloadWindow = hwndDlg; - g_Finished = 0; - SetTimer( hwndDlg, 1, 200, NULL ); // was 50 - - break; - - case WM_TIMER: - DEBUG_LOG(("TIMER\n")); - if( g_Finished == 0 ) - { - DEBUG_LOG(("Entering PumpMsgs\n")); - TheDownloadManager->update(); - /* - pDownload->PumpMessages(); - */ - DEBUG_LOG(("Done with PumpMsgs\n")); - if (strlen(g_DLTimeRem)) - SetDlgItemText( hwndDlg, IDC_TIMEREM, g_DLTimeRem ); - if (strlen(g_DLBytesLeft)) - SetDlgItemText( hwndDlg, IDC_BYTESLEFT, g_DLBytesLeft ); - //if (strlen(g_DLBPS)) - // SetDlgItemText( hwndDlg, IDC_BPS, g_DLBPS ); - } - else - { - DEBUG_LOG(("TIMER: Finished\n")); - EndDialog( hwndDlg, g_Finished ); - DestroyWindow( hwndDlg ); - } - break; - - case WM_DESTROY: - KillTimer( hwndDlg, 1 ); - //ClosedownDownload(); - - //DBGMSG("WM_DESTROY"); - break; - - case WM_SETFONT: - return TRUE; - - default: - return FALSE; - } - return TRUE; -} - - - -DWORD dwChatAdvise; -DWORD dwDownloadAdvise; - -//Update *g_Update; - -uint32 g_AppVer=-1; - - -BOOL CALLBACK Download_Dialog_Proc( HWND hwndDlg, UINT uMsg, WPARAM wParam, - LPARAM lParam ); - -BOOL CALLBACK Simple_Dialog_Proc( HWND hwndDlg, UINT uMsg, WPARAM wParam, - LPARAM lParam ); - -HWND CreatePrimaryWin(void); - -char const * Fetch_String(int id); - - -// -// Create a primary window -// -HWND CreatePrimaryWin(void) -{ - HWND hwnd; - WNDCLASS wc; - char name[256]; - - sprintf(name,Fetch_String(TXT_TITLE)); - - //DBGMSG("CreatePrimary: "< 8)) - { - // Launch the process - SHELLEXECUTEINFO info; - memset(&info,0,sizeof(info)); - info.cbSize=sizeof(info); - info.fMask=SEE_MASK_NOCLOSEPROCESS; - info.hwnd=g_PrimaryWindow; - info.lpVerb=NULL; - info.lpFile=regapp; - info.lpParameters=NULL; - info.lpDirectory="."; - info.nShow=SW_SHOW; - ShellExecuteEx(&info); - - // Can't wait infinite or the other process will never create its window - // Only Bill himself knows why this is happening - while(1) // Wait for completion - { - DispatchEvents(); - if (WaitForSingleObject(info.hProcess,500)!=WAIT_TIMEOUT) - break; - } - } - RegCloseKey(rKey); - } - } - // OK, done with that crap go on to the task at hand now.... -*/ - - - // Find the game version - g_AppVer = -1; - if (!GetUnsignedIntFromRegistry("", "Version", g_AppVer)) - { - MessageBox(g_PrimaryWindow,Fetch_String(TXT_INSTALL_PROBLEM),Fetch_String(TXT_ERROR),MB_OK); - exit(0); - } - // OK, have the current game version now - - g_PrimaryWindow=CreatePrimaryWin(); // Create the main window - DispatchEvents(); // process some win messages - - // Popup the "contacting" window - g_ContactWindow=CreateDialog(Global_instance,MAKEINTRESOURCE(IDD_CONNECTING),g_PrimaryWindow,Simple_Dialog_Proc); - ShowWindow(g_ContactWindow,SW_SHOWNORMAL); - SetForegroundWindow(g_ContactWindow); - DispatchEvents(); // process some win messages - - - // Setup the Westwood Online stuff - Startup_Chat(); - - Update_If_Required(); - - Shutdown_Chat(); - - return(0); -} - - -typedef struct SRecord { - int ID; // ID number of the string resource. - int TimeStamp; // 'Time' that this string was last requested. - char String[2048]; // Copy of string resource. - - SRecord(void) : ID(-1), TimeStamp(-1) {} -} SRecord; - - -/*********************************************************************************************** - * Fetch_String -- Fetches a string resource. * - * * - * Fetches a string resource and returns a pointer to its text. * - * * - * INPUT: id -- The ID number of the string resource to fetch. * - * * - * OUTPUT: Returns with a pointer to the actual text of the string resource. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/25/1996 JLB : Created. * - *=============================================================================================*/ -char const * Fetch_String(int id) -{ - static SRecord _buffers[64]; - static int _time = 0; - - /* - ** Determine if the string ID requested is valid. If not then return an empty string pointer. - */ - if (id == -1 || id == TXT_NONE) return(""); - - /* - ** Adjust the 'time stamp' tracking value. This is an artificial value used merely to track - ** the relative age of the strings requested. - */ - _time = _time+1; - - /* - ** Check to see if the requested string has already been fetched into a buffer. If so, then - ** return a pointer to that string (update the time stamp as well). - */ - for (int index = 0; index < ARRAY_SIZE(_buffers); index++) { - if (_buffers[index].ID == id) { - _buffers[index].TimeStamp = _time; - return(_buffers[index].String); - } - } - - /* - ** Find a suitable buffer to hold the string to be fetched. The buffer should either be - ** empty or have the oldest fetched string. - */ - int oldest = -1; - int oldtime = -1; - for (int text = 0; text < ARRAY_SIZE(_buffers); text++) { - if (oldest == -1 || oldtime > _buffers[text].TimeStamp) { - oldest = text; - oldtime = _buffers[text].TimeStamp; - if (oldtime == -1 || _buffers[text].ID == -1) break; - } - } - - /* - ** A suitable buffer has been found so fetch the string resource and then return a pointer - ** to the string. - */ - char * stringptr = _buffers[oldest].String; - _buffers[oldest].ID = id; - _buffers[oldest].TimeStamp = _time; - - - if (LoadString(Global_instance, id, stringptr, sizeof(_buffers[oldest].String)) == 0) { - return(""); - } - - /****** - char resname[32]; - sprintf(resname,"#%d",id); - HMODULE hmod=GetModuleHandle(NULL); - HRSRC hrsrc=FindResourceEx(hmod, RT_STRING, MAKEINTRESOURCE(id), LANGID); - if (hrsrc==0) - { - char message_buffer[256]; - FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &message_buffer[0], 256, NULL ); - - } - HGLOBAL resdata=LoadResource(NULL,hrsrc); - LPVOID vdata=LockResource(resdata); - strcpy(stringptr,(char *)vdata); - *********/ - - stringptr[sizeof(_buffers[oldest].String)-1] = '\0'; - return(stringptr); -} - - - - -void LogMsg(const char *msg) -{ -#ifdef _DEBUG - FILE *out=fopen("register.log","a"); - fprintf(out,"%s\n",msg); - fflush(out); - fclose(out); -#endif -} - - - - -void Startup_Chat(void) -{ - /* - //////CComObject* g_pChatSink; - HRESULT hRes; - g_pChatSink=NULL; - - CoCreateInstance(CLSID_Chat, NULL, CLSCTX_INPROC_SERVER, - IID_IChat, (void**)&pChat); - - - if (pChat==NULL) - { - char error[128]; - char apimissing[256]; - LoadString(Global_instance, TXT_API_MISSING, apimissing, sizeof(apimissing)); - LoadString(Global_instance, TXT_ERROR, error, sizeof(error)); - MessageBox(g_PrimaryWindow,apimissing,error,MB_OK); - exit(-5); - } - - g_pChatSink=new CChatEventSink; - - // Get a connection point from the chat class - IConnectionPoint *pConnectionPoint=NULL; - IConnectionPointContainer *pContainer=NULL; - - dwChatAdvise=0; - hRes=pChat->QueryInterface(IID_IConnectionPointContainer,(void**)&pContainer); - _ASSERTE(SUCCEEDED(hRes)); - hRes=pContainer->FindConnectionPoint(IID_IChatEvent,&pConnectionPoint); - _ASSERTE(SUCCEEDED(hRes)); - hRes=pConnectionPoint->Advise((IChatEvent *)g_pChatSink,&dwChatAdvise); - _ASSERTE(SUCCEEDED(hRes)); - - - pChat->SetAttributeValue("RegPath",APP_REG_KEY); - - // ADD pConnectionPoint->Release(); - */ -} - -void Shutdown_Chat(void) -{ - /* - /////AtlUnadvise(pChat, IID_IChatEvent, dwChatAdvise); - - IConnectionPoint *pConnectionPoint=NULL; - IConnectionPointContainer *pContainer=NULL; - HRESULT hRes; - - hRes=pChat->QueryInterface(IID_IConnectionPointContainer,(void**)&pContainer); - _ASSERTE(SUCCEEDED(hRes)); - hRes=pContainer->FindConnectionPoint(IID_IChatEvent,&pConnectionPoint); - _ASSERTE(SUCCEEDED(hRes)); - pConnectionPoint->Unadvise(dwChatAdvise); - - pChat->Release(); - - /////delete(g_pChatSink); This appears to be bad.... - // ADD g_pChatSink->Release(); - // ADD pConnectionPoint->Release(); - // ADD pContainer->Release(); - */ -} - - - -// -// Download a patch for the registration client if required -// This uses the chat API for ver checking and FTP. -// -void Update_If_Required(void) -{ - int retval; - int i; - // Create the events - for (i=0; iRequestServerList(1000,262364,"register","regpas98",15); - ///pChat->RequestServerList(1000,300,"register","regpas98",15); - - pChat->RequestServerList(g_AppSku,g_AppVer,"register","regpas98",40); - - while(1) - { - pChat->PumpMessages(); - MSG msg; - while(PeekMessage(&msg,NULL,0,0, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - retval=WaitForMultipleObjectsEx(NUM_EVENTS,Events,FALSE,50,FALSE); - if (retval==WAIT_TIMEOUT) - continue; - //DBGMSG("An event was set"); - retval-=WAIT_OBJECT_0; - break; - } - - //DBGMSG("Out of the loop") - - if (retval==ABORT_EVENT) - { - exit(0); - } - else - { - //DBGMSG("NO update required"); - } - - //DBGMSG("Shutting down"); - - // close all the event objects - for (i=0; i(this) ; - } - else - { - *ppv = NULL; - return E_NOINTERFACE; - } - (reinterpret_cast(*ppv))->AddRef() ; - return S_OK ; -} - -/////////////////////////////////////////////////////////// -// -// AddRef -// -ULONG __stdcall -CChatEventSink::AddRef() -{ - return InterlockedIncrement(&m_cRef) ; -} - -/////////////////////////////////////////////////////////// -// -// Release -// -ULONG __stdcall -CChatEventSink::Release() -{ - if (InterlockedDecrement(&m_cRef) == 0) - { - delete this ; - return 0 ; - } - return m_cRef; -} - - - - - -///// DOWNLOAD - -CDownloadEventSink::CDownloadEventSink() -{ - m_cRef=0; // Ref counter -} - -/////////////////////////////////////////////////////////// -// -// Interface IUnknown Methods -// -/////////////////////////////////////////////////////////// -// -// QueryInterface -// -HRESULT __stdcall -CDownloadEventSink::QueryInterface(const IID& iid, void** ppv) -{ - if ((iid == IID_IUnknown) ||(iid == IID_IDownloadEvent)) - { - *ppv = static_cast(this) ; - } - else - { - *ppv = NULL; - return E_NOINTERFACE; - } - (reinterpret_cast(*ppv))->AddRef() ; - return S_OK ; -} - -/////////////////////////////////////////////////////////// -// -// AddRef -// -ULONG __stdcall -CDownloadEventSink::AddRef() -{ - return InterlockedIncrement(&m_cRef) ; -} - -/////////////////////////////////////////////////////////// -// -// Release -// -ULONG __stdcall -CDownloadEventSink::Release() -{ - if (InterlockedDecrement(&m_cRef) == 0) - { - delete this ; - return 0 ; - } - return m_cRef; -} - -*/ - - - - - - -//// FTP Download stuff - - -void SetupDownload( void ) -{ - /* - HRESULT hRes; - - g_pDownloadSink=NULL; - - CoCreateInstance(CLSID_Download, NULL, CLSCTX_INPROC_SERVER, - IID_IDownload, (void**)&pDownload); - _ASSERTE(pDownload); - g_pDownloadSink=new CDownloadEventSink; - - // Get a connection point from the chat class - IConnectionPoint *pConnectionPoint=NULL; - IConnectionPointContainer *pContainer=NULL; - dwDownloadAdvise = 0; - - hRes=pDownload->QueryInterface(IID_IConnectionPointContainer,(void**)&pContainer); - _ASSERTE(SUCCEEDED(hRes)); - hRes=pContainer->FindConnectionPoint(IID_IDownloadEvent,&pConnectionPoint); - _ASSERTE(SUCCEEDED(hRes)); - hRes=pConnectionPoint->Advise((IDownloadEvent *)g_pDownloadSink,&dwDownloadAdvise); - _ASSERTE(SUCCEEDED(hRes)); - */ -} - - - -void ClosedownDownload( void ) -{ -/* - // AtlUnadvise(pDownload, IID_IDownloadEvent, dwDownloadAdvise); - - IConnectionPoint *pConnectionPoint=NULL; - IConnectionPointContainer *pContainer=NULL; - HRESULT hRes; - - hRes=pDownload->QueryInterface(IID_IConnectionPointContainer,(void**)&pContainer); - _ASSERTE(SUCCEEDED(hRes)); - hRes=pContainer->FindConnectionPoint(IID_IDownloadEvent,&pConnectionPoint); - _ASSERTE(SUCCEEDED(hRes)); - pConnectionPoint->Unadvise(dwDownloadAdvise); - - pDownload->Release(); - - //////delete(g_pDownloadSink); This appears to be bad.... -*/ -} - - - -BOOL CALLBACK Download_Dialog_Proc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) -{ -// char fullpath[ 256 ]; -// char localfile[ 256]; -// HRESULT res; - - switch( uMsg ) - { - case WM_COMMAND: - switch( LOWORD( wParam ) ) - { - case IDC_DLABORT: - { - - char abort[128]; - char abortdload[256]; - LoadString(Global_instance, TXT_ABORT_DOWNLOAD, abortdload, sizeof(abortdload)); - LoadString(Global_instance, TXT_ABORT, abort, sizeof(abort)); - - if (MessageBox(g_PrimaryWindow,abortdload,abort,MB_YESNO)==IDYES) - { -/* - pDownload->Abort(); -*/ - EndDialog( hwndDlg, g_Finished ); - DestroyWindow(hwndDlg); - } - } - break; - - default: - return FALSE; - } - break; - - case WM_INITDIALOG: - SetupDownload(); - - SendMessage(hwndDlg, WM_SETICON,(WPARAM)ICON_SMALL, - (LPARAM)LoadIcon(Global_instance, MAKEINTRESOURCE(IDI_ICON1))); - - g_DLTimeRem[0]=0; - g_DLBytesLeft[0]=0; - g_DLBPS[0]=0; - - //SetDlgItemText( hwndDlg, IDC_DOWNLOADTITLE, g_UpdateString); - //SetWindowText(hwndDlg, g_UpdateString); - - SetDlgItemText( hwndDlg, IDC_TIMEREM, g_DLTimeRem); - SetDlgItemText( hwndDlg, IDC_BYTESLEFT, g_DLBytesLeft); - // SetDlgItemText( hwndDlg, IDC_BPS, g_DLBPS ); - -/* - // Work out the full file name - sprintf( fullpath, "%s/%s", g_Update->patchpath,g_Update->patchfile); - sprintf(localfile,"%s\\%s",g_Update->localpath,g_Update->patchfile); - - // Create the directory - CreateDirectory((char *)g_Update->localpath, NULL ); - - res=pDownload->DownloadFile((char *)g_Update->server, (char *)g_Update->login, (char *)g_Update->password, - fullpath, localfile, APP_REG_KEY); - -*/ - g_DownloadWindow = hwndDlg; - g_Finished = 0; - SetTimer( hwndDlg, 1, 200, NULL ); // was 50 - - break; - - case WM_TIMER: - LogMsg("TIMER"); - if( g_Finished == 0 ) - { - LogMsg("Entering PumpMsgs"); -/* - pDownload->PumpMessages(); -*/ - LogMsg("Done with PumpMsgs"); - if (strlen(g_DLTimeRem)) - SetDlgItemText( hwndDlg, IDC_TIMEREM, g_DLTimeRem ); - if (strlen(g_DLBytesLeft)) - SetDlgItemText( hwndDlg, IDC_BYTESLEFT, g_DLBytesLeft ); - //if (strlen(g_DLBPS)) - // SetDlgItemText( hwndDlg, IDC_BPS, g_DLBPS ); - } - else - { - LogMsg("TIMER: Finished"); - EndDialog( hwndDlg, g_Finished ); - DestroyWindow( hwndDlg ); - } - break; - - case WM_DESTROY: - KillTimer( hwndDlg, 1 ); - ClosedownDownload(); - - //DBGMSG("WM_DESTROY"); - break; - - case WM_SETFONT: - return TRUE; - - default: - return FALSE; - } - return TRUE; -} - - - -// Whoeee this is an exciting one... -BOOL CALLBACK Simple_Dialog_Proc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) -{ - switch( uMsg ) - { - case WM_INITDIALOG: - return(TRUE); - break; - case WM_CLOSE: - DestroyWindow(hwnd); - PostQuitMessage(0); - exit(0); - break; - } - return(FALSE); -} - - - - -///////////////////////////////////////////////////////////////////////////// -// CDownloadEventSink -////////////////////////////////////////////////////////////////////////////// - -/* - -STDMETHODIMP CDownloadEventSink::OnEnd(void) -{ - LogMsg("Finished!"); - g_Finished = 1; - return(S_OK); -} - -STDMETHODIMP CDownloadEventSink::OnError(int error) -{ - LogMsg("ERROR"); - g_Finished = -1; - return(S_OK); -} - - -STDMETHODIMP CDownloadEventSink::OnProgressUpdate(int bytesread, int totalsize, - int timetaken, int timeleft) -{ - SendDlgItemMessage( g_DownloadWindow, IDC_PROGRESS, PBM_SETPOS, (WPARAM)(bytesread * 100) / totalsize, 0 ); - char temp[256]; - - if( timeleft > 0 ) - { - //DBGMSG("Bytes read: "<next; - numupdates++; - } - - // Got a list of updates - If an update is required, the user must either - // patch or quit. - - tmp = updates; - - LogMsg("Found an update"); - - // We have a required update - - char upreq[256]; - char title[128]; - - LoadString(Global_instance, TXT_AN_UPGRADE_AVAILABLE, upreq, sizeof(upreq)); - strcat(upreq,"\n"); - LoadString(Global_instance, TXT_DOWNLOAD_NOW, upreq+strlen(upreq), sizeof(upreq)); - LoadString(Global_instance, TXT_UPGRADE_AVAILABLE, title, sizeof(title)); - - if( MessageBox(g_PrimaryWindow,upreq,title, MB_YESNO ) == IDNO ) - { - // If they don't want to patch now, just exit... - //DBGMSG("Must patch to continue, so exit"); - exit(0); - } - - // Do the downloads - while( tmp != NULL ) - { - g_Update = tmp; - - char dloading[256]; - LoadString(Global_instance, TXT_DOWNLOADING_FILE, dloading, sizeof(dloading)); - sprintf( g_UpdateString, dloading, ++i, numupdates ); - - LogMsg("Creating Download dialog box"); - //if( (retval=DialogBox(Global_instance, MAKEINTRESOURCE(IDD_DOWNLOAD_DIALOG), g_PrimaryWindow, - // (DLGPROC)Download_Dialog_Proc)) != 1 ) - - retval=DialogBox(Global_instance, MAKEINTRESOURCE(IDD_DOWNLOAD_DIALOG), g_PrimaryWindow,(DLGPROC)Download_Dialog_Proc); - - if (g_Finished != 1) - { - // Download failed - //DBGMSG("Download failed: "<next; - } - // Quit so the launcher can apply the patches - exit(0); - return(S_OK); // make silly compiler happy -} - - - - - - -STDMETHODIMP CChatEventSink::OnServerError(HRESULT, LPCSTR) -{ - LogMsg("Server Error"); - return(S_OK); -} - -STDMETHODIMP CChatEventSink::OnMessageOfTheDay(HRESULT, LPCSTR) -{ - return(S_OK); -} - - - -STDMETHODIMP CChatEventSink::OnPrivateAction(HRESULT, User *, LPCSTR) -{ - return(S_OK); -} - - -STDMETHODIMP CChatEventSink::OnPublicAction(HRESULT, Channel *, User *, LPCSTR) -{ - return(S_OK); -} - - -STDMETHODIMP CChatEventSink::OnPrivateGameOptions(HRESULT, User *, LPCSTR) -{ - return(S_OK); -} - - -STDMETHODIMP CChatEventSink::OnPublicGameOptions(HRESULT, Channel *, User *, LPCSTR) -{ - return(S_OK); -} - - -STDMETHODIMP CChatEventSink::OnGameStart(HRESULT, Channel *, User *, int) -{ - return(S_OK); -} - - -STDMETHODIMP CChatEventSink::OnUserKick(HRESULT, Channel *, User *, User *) -{ - return(S_OK); -} - - -STDMETHODIMP CChatEventSink::OnUserIP(HRESULT, User *) -{ - return(S_OK); -} - -STDMETHODIMP CChatEventSink::OnSquadInfo(HRESULT, unsigned long, Squad *) -{ - return(S_OK); -} - -*/ - -} // namespace patchget diff --git a/Generals/Code/Tools/PATCHGET/CHATAPI.H b/Generals/Code/Tools/PATCHGET/CHATAPI.H deleted file mode 100644 index dd54a9de25..0000000000 --- a/Generals/Code/Tools/PATCHGET/CHATAPI.H +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef CHATAPI_HEADER -#define CHATAPI_HEADER - -#include "COMINIT.H" -#include -#include -#include -#include -#include -#include - -/********************************************************************** -** This macro serves as a general way to determine the number of elements -** within an array. -*/ -#define ARRAY_SIZE(x) int(sizeof(x)/sizeof(x[0])) -#define size_of(typ,id) sizeof(((typ*)0)->id) - -namespace patchget -{ - -int main(int argc, char *argv[]); - -void Startup_Chat(void); -void Shutdown_Chat(void); -void Update_If_Required(void); - -char const * Fetch_String(int id); - -} // namespace patchget - -#endif diff --git a/Generals/Code/Tools/PATCHGET/CMakeLists.txt b/Generals/Code/Tools/PATCHGET/CMakeLists.txt index 645d5ad246..281b4ec512 100644 --- a/Generals/Code/Tools/PATCHGET/CMakeLists.txt +++ b/Generals/Code/Tools/PATCHGET/CMakeLists.txt @@ -1,45 +1,13 @@ -set(PATCHGET_SRC - "CHATAPI.CPP" - "CHATAPI.H" - "COMINIT.CPP" - "COMINIT.H" - "debug.cpp" - "debug.h" - "DownloadManager.cpp" - "DownloadManager.h" - "PROCESS.CPP" - "PROCESS.H" - "registry.cpp" - "Registry.h" - "RESOURCE.H" - "WINBLOWS.CPP" - "WINBLOWS.H" - "WSTYPES.H" -) - macro(setup_patchgrabber appname) add_executable(${appname} WIN32) - target_sources(${appname} PRIVATE ${PATCHGET_SRC}) + target_link_libraries(${appname} PRIVATE - comctl32 - dbghelplib + corei_patchgrabber g_gameengine g_gameenginedevice g_wwvegas - gamespy::gamespy gi_always - imm32 - vfw32 - winmm ) - - target_compile_definitions(${appname} PRIVATE - $<$:DEBUG_CRASHING> - ) - - if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(${appname} PRIVATE SCRIPT1.RC) - endif() endmacro() setup_patchgrabber(g_patchgrabber_en) diff --git a/Generals/Code/Tools/PATCHGET/COMINIT.CPP b/Generals/Code/Tools/PATCHGET/COMINIT.CPP deleted file mode 100644 index 797ed73fa1..0000000000 --- a/Generals/Code/Tools/PATCHGET/COMINIT.CPP +++ /dev/null @@ -1,50 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// If you link with this it will automatically call the COM initialization stuff -// -#include "COMINIT.H" -#include -#include -#include -#include - -namespace patchget -{ - -ComInit::ComInit() -{ - HRESULT hRes = CoInitialize(NULL); - if (SUCCEEDED(hRes)==FALSE) - { - MessageBox(NULL,"Can't initialize COM?!?!","Error:",MB_OK); - exit(0); - } -} - - -ComInit::~ComInit() -{ - CoUninitialize(); -} - -// Creating this instance will setup all COM stuff & do cleanup on program exit -ComInit Global_COM_Initializer; - -} // namespace patchget diff --git a/Generals/Code/Tools/PATCHGET/COMINIT.H b/Generals/Code/Tools/PATCHGET/COMINIT.H deleted file mode 100644 index f87ef8746a..0000000000 --- a/Generals/Code/Tools/PATCHGET/COMINIT.H +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef COMINIT_HEADER -#define COMINIT_HEADER - -namespace patchget -{ - -// -// Link with this to automatically initialize COM at startup -// - See cominit.cpp for more info -// - -class ComInit -{ - public: - ComInit(); - ~ComInit(); -}; - -} // namespace patchget - -#endif diff --git a/Generals/Code/Tools/PATCHGET/DownloadManager.cpp b/Generals/Code/Tools/PATCHGET/DownloadManager.cpp deleted file mode 100644 index fa6dea64f8..0000000000 --- a/Generals/Code/Tools/PATCHGET/DownloadManager.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: DownloadManager.cpp ////////////////////////////////////////////////////// -// Generals download manager code -// Author: Matthew D. Campbell, July 2002 - -#include "debug.h" -#include "CHATAPI.H" -#include "DownloadManager.h" -#include "RESOURCE.H" - -namespace patchget -{ - -DownloadManager *TheDownloadManager = NULL; - -DownloadManager::DownloadManager() -{ - m_download = new CDownload(this); - m_wasError = m_sawEnd = false; - m_statusString = Fetch_String(FTP_StatusIdle); - - // ----- Initialize Winsock ----- - m_winsockInit = true; - WORD verReq = MAKEWORD(2, 2); - WSADATA wsadata; - - int err = WSAStartup(verReq, &wsadata); - if (err != 0) - { - m_winsockInit = false; - } - else - { - if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) - { - WSACleanup(); - m_winsockInit = false; - } - } - -} - -DownloadManager::~DownloadManager() -{ - delete m_download; - if (m_winsockInit) - { - WSACleanup(); - m_winsockInit = false; - } -} - -void DownloadManager::init( void ) -{ -} - -void DownloadManager::reset( void ) -{ -} - -HRESULT DownloadManager::update( void ) -{ - return m_download->PumpMessages(); -} - -HRESULT DownloadManager::downloadFile( std::string server, std::string username, std::string password, std::string file, std::string localfile, std::string regkey, bool tryResume ) -{ - return m_download->DownloadFile( server.c_str(), username.c_str(), password.c_str(), file.c_str(), localfile.c_str(), regkey.c_str(), tryResume ); -} - -void DownloadManager::queueFileForDownload( std::string server, std::string username, std::string password, std::string file, std::string localfile, std::string regkey, bool tryResume ) -{ - QueuedDownload q; - q.file = file; - q.localFile = localfile; - q.password = password; - q.regKey = regkey; - q.server = server; - q.tryResume = tryResume; - q.userName = username; - - m_queuedDownloads.push_back(q); -} - -HRESULT DownloadManager::downloadNextQueuedFile( void ) -{ - QueuedDownload q; - std::list::iterator it = m_queuedDownloads.begin(); - if (it != m_queuedDownloads.end()) - { - q = *it; - m_queuedDownloads.pop_front(); - m_wasError = m_sawEnd = false; - return downloadFile( q.server, q.userName, q.password, q.file, q.localFile, q.regKey, q.tryResume ); - } - else - { - DEBUG_CRASH(("Starting non-existent download!")); - return S_OK; - } -} - -std::string DownloadManager::getLastLocalFile( void ) -{ - char buf[256] = ""; - m_download->GetLastLocalFile(buf, 256); - return buf; -} - -HRESULT DownloadManager::OnError( int error ) -{ - m_wasError = true; - std::string s = Fetch_String(FTP_UnknownError); - switch (error) - { - case DOWNLOADEVENT_NOSUCHSERVER: - s = Fetch_String(FTP_NoSuchServer); - break; - case DOWNLOADEVENT_COULDNOTCONNECT: - s = Fetch_String(FTP_CouldNotConnect); - break; - case DOWNLOADEVENT_LOGINFAILED: - s = Fetch_String(FTP_LoginFailed); - break; - case DOWNLOADEVENT_NOSUCHFILE: - s = Fetch_String(FTP_NoSuchFile); - break; - case DOWNLOADEVENT_LOCALFILEOPENFAILED: - s = Fetch_String(FTP_LocalFileOpenFailed); - break; - case DOWNLOADEVENT_TCPERROR: - s = Fetch_String(FTP_TCPError); - break; - case DOWNLOADEVENT_DISCONNECTERROR: - s = Fetch_String(FTP_DisconnectError); - break; - } - m_errorString = s; - DEBUG_LOG(("DownloadManager::OnError(): %s(%d)\n", s.c_str(), error)); - return S_OK; -} - -HRESULT DownloadManager::OnEnd() -{ - m_sawEnd = true; - DEBUG_LOG(("DownloadManager::OnEnd()\n")); - return S_OK; -} - -HRESULT DownloadManager::OnQueryResume() -{ - DEBUG_LOG(("DownloadManager::OnQueryResume()\n")); - //return DOWNLOADEVENT_DONOTRESUME; - return DOWNLOADEVENT_RESUME; -} - -HRESULT DownloadManager::OnProgressUpdate( int bytesread, int totalsize, int timetaken, int timeleft ) -{ - DEBUG_LOG(("DownloadManager::OnProgressUpdate(): %d/%d %d/%d\n", bytesread, totalsize, timetaken, timeleft)); - return S_OK; -} - -HRESULT DownloadManager::OnStatusUpdate( int status ) -{ - std::string s = Fetch_String(FTP_StatusNone); - switch (status) - { - case DOWNLOADSTATUS_CONNECTING: - s = Fetch_String(FTP_StatusConnecting); - break; - case DOWNLOADSTATUS_LOGGINGIN: - s = Fetch_String(FTP_StatusLoggingIn); - break; - case DOWNLOADSTATUS_FINDINGFILE: - s = Fetch_String(FTP_StatusFindingFile); - break; - case DOWNLOADSTATUS_QUERYINGRESUME: - s = Fetch_String(FTP_StatusQueryingResume); - break; - case DOWNLOADSTATUS_DOWNLOADING: - s = Fetch_String(FTP_StatusDownloading); - break; - case DOWNLOADSTATUS_DISCONNECTING: - s = Fetch_String(FTP_StatusDisconnecting); - break; - case DOWNLOADSTATUS_FINISHING: - s = Fetch_String(FTP_StatusFinishing); - break; - case DOWNLOADSTATUS_DONE: - s = Fetch_String(FTP_StatusDone); - break; - } - m_statusString = s; - DEBUG_LOG(("DownloadManager::OnStatusUpdate(): %s(%d)\n", s.c_str(), status)); - return S_OK; -} - -} // namespace patchget diff --git a/Generals/Code/Tools/PATCHGET/DownloadManager.h b/Generals/Code/Tools/PATCHGET/DownloadManager.h deleted file mode 100644 index e82cc956a7..0000000000 --- a/Generals/Code/Tools/PATCHGET/DownloadManager.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: DownloadManager.h ////////////////////////////////////////////////////// -// Generals download class definitions -// Author: Matthew D. Campbell, July 2002 - -#pragma once - -#ifndef __DOWNLOADMANAGER_H__ -#define __DOWNLOADMANAGER_H__ - -#include "WWDownload/downloaddefs.h" -#include "WWDownload/Download.h" -#include -#include - -class CDownload; - -namespace patchget -{ - -class QueuedDownload -{ -public: - std::string server; - std::string userName; - std::string password; - std::string file; - std::string localFile; - std::string regKey; - bool tryResume; -}; - -///////////////////////////////////////////////////////////////////////////// -// DownloadManager - -class DownloadManager : public IDownload -{ -public: - DownloadManager(); - virtual ~DownloadManager(); - -public: - void init( void ); - HRESULT update( void ); - void reset( void ); - - virtual HRESULT OnError( int error ); - virtual HRESULT OnEnd(); - virtual HRESULT OnQueryResume(); - virtual HRESULT OnProgressUpdate( int bytesread, int totalsize, int timetaken, int timeleft ); - virtual HRESULT OnStatusUpdate( int status ); - - virtual HRESULT downloadFile( std::string server, std::string username, std::string password, std::string file, std::string localfile, std::string regkey, bool tryResume ); - std::string getLastLocalFile( void ); - - bool isDone( void ) { return m_sawEnd || m_wasError; } - bool isOk( void ) { return m_sawEnd; } - bool wasError( void ) { return m_wasError; } - - std::string getStatusString( void ) { return m_statusString; } - std::string getErrorString( void ) { return m_errorString; } - - void queueFileForDownload( std::string server, std::string username, std::string password, std::string file, std::string localfile, std::string regkey, bool tryResume ); - bool isFileQueuedForDownload( void ) { return !m_queuedDownloads.empty(); } - HRESULT downloadNextQueuedFile( void ); - -private: - bool m_winsockInit; - CDownload *m_download; - bool m_wasError; - bool m_sawEnd; - std::string m_errorString; - std::string m_statusString; - -protected: - std::list m_queuedDownloads; -}; - -extern DownloadManager *TheDownloadManager; - -} // namespace patchget - -#endif // __DOWNLOADMANAGER_H__ diff --git a/Generals/Code/Tools/PATCHGET/PROCESS.CPP b/Generals/Code/Tools/PATCHGET/PROCESS.CPP deleted file mode 100644 index 8a5fbf7ec0..0000000000 --- a/Generals/Code/Tools/PATCHGET/PROCESS.CPP +++ /dev/null @@ -1,106 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "process.h" - -namespace patchget -{ - -Process::Process() -{ - directory[0]=0; - command[0]=0; - args[0]=0; - hProcess=NULL; - hThread=NULL; -} - -// Create a process -bit8 Create_Process(Process &process) -{ - int retval; - STARTUPINFO si; - PROCESS_INFORMATION piProcess; - ZeroMemory(&si,sizeof(si)); - si.cb=sizeof(si); - - char cmdargs[513]; - memset(cmdargs,0,513); - strcpy(cmdargs,process.command); - strcat(cmdargs,process.args); - - retval=CreateProcess(NULL,cmdargs,NULL,NULL,FALSE, 0 ,NULL, NULL/*process.directory*/,&si,&piProcess); - - process.hProcess=piProcess.hProcess; - process.hThread=piProcess.hThread; - return(TRUE); -} - -// -// Wait for a process to complete, and fill in the exit code -// -bit8 Wait_Process(Process &process, DWORD *exit_code) -{ - DWORD retval; - retval=WaitForSingleObject(process.hProcess,INFINITE); - if (exit_code != NULL) - *exit_code=-1; - if (retval==WAIT_OBJECT_0) // process exited - { - if (exit_code != NULL) - GetExitCodeProcess(process.hProcess,exit_code); - return(TRUE); - } - else // can this happen? - return(FALSE); -} - -/******************* -// -// Get the process to run from the config object -// -bit8 Read_Process_Info(ConfigFile &config,OUT Process &info) -{ - - Wstring procinfo; - if (config.getString("RUN",procinfo)==FALSE) - { - DBGMSG("Couldn't read the RUN line"); - return(FALSE); - } - int offset=0; - Wstring dir; - Wstring executable; - Wstring args; - offset=procinfo.getToken(offset," ",dir); - offset=procinfo.getToken(offset," ",executable); - args=procinfo; - args.remove(0,offset); - - /// - /// - DBGMSG("RUN: EXE = "<. -*/ - -// Registry.h -// Simple interface for storing/retreiving registry values -// Author: Matthew D. Campbell, December 2001 - -#pragma once - -#ifndef __REGISTRY_H__ -#define __REGISTRY_H__ - -#include - -namespace patchget -{ - -/** - * Get a string from the registry - */ -bool GetStringFromRegistry(std::string path, std::string key, std::string& val); - -/** - * Get an unsigned int from the registry - */ -bool GetUnsignedIntFromRegistry(std::string path, std::string key, unsigned int& val); - -/** - * Store a string in the registry - returns true on success - */ -bool SetStringInRegistry(std::string path, std::string key, std::string val); - -/** - * Store an unsigned int in the registry - returns true on success - */ -bool SetUnsignedIntInRegistry(std::string path, std::string key, unsigned int val); - -} // namespace patchget - -#endif // __REGISTRY_H__ diff --git a/Generals/Code/Tools/PATCHGET/WINBLOWS.CPP b/Generals/Code/Tools/PATCHGET/WINBLOWS.CPP deleted file mode 100644 index 2978f523b5..0000000000 --- a/Generals/Code/Tools/PATCHGET/WINBLOWS.CPP +++ /dev/null @@ -1,197 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#include - -#include "WINBLOWS.H" -#include "CHATAPI.H" - - -// TheSuperHackers @fix xezon 13/03/2025 Fix debug linker errors by -// adding "patchget" namespaces and these globals here. -// just to satisfy the game libraries we link to -HINSTANCE ApplicationHInstance = NULL; ///< our application instance -HWND ApplicationHWnd = NULL; -const char *g_strFile = "data\\Generals.str"; -const char *g_csfFile = "data\\%s\\Generals.csf"; -const char *gAppPrefix = "patchget_"; // prefix to the debug log. - - -HINSTANCE Global_instance; -LPSTR Global_commandline; -int Global_commandshow; - - -/* - * WinMain - initialization, message loop - */ -int PASCAL WinMain( HINSTANCE instance, HINSTANCE, char *command_line, int command_show) -{ - //////MSG msg; - - Global_instance = instance; - Global_commandline = command_line; - Global_commandshow = command_show; - - int argc; - char *argv[64]; - - char path_to_exe[512]; - GetModuleFileName(instance,(char *)&path_to_exe,512); - argc=1; - argv[0]=path_to_exe; - - - int command_scan=0; - char command_char; - do - { - /* - ** Scan for non-space character on command line - */ - do - { - command_char = *( command_line+command_scan++ ); - } while ( command_char==' ' ); - - if ( command_char!=0 && command_char != 13 ) - { - argv[argc++]=command_line+command_scan-1; - - /* - ** Scan for space character on command line - */ - do - { - command_char = *( command_line+command_scan++ ); - } while ( command_char!=' ' && command_char != 0 && command_char!=13); - *( command_line+command_scan-1 ) = 0; - } - - } while ( command_char != 0 && command_char != 13 && argc<20 ); - - return(patchget::main(argc,argv)); - -} /* WinMain */ - - -int Print_WM(UINT message,char *out) -{ - switch(message) - { - case WM_NULL: - sprintf(out,"WM_NULL"); - break; - case WM_CREATE: - sprintf(out,"WM_CREATE"); - break; - case WM_DESTROY: - sprintf(out,"WM_DESTROY"); - break; - case WM_CANCELMODE: - sprintf(out,"WM_CANCELMODE"); - break; - case WM_ERASEBKGND: - sprintf(out,"WM_ERASEBKGND"); - break; - case WM_GETTEXT: - sprintf(out,"WM_GETTEXT"); - break; - case WM_QUERYOPEN: - sprintf(out,"WM_QUERYOPEN"); - break; - case WM_MOVE: - sprintf(out,"WM_MOVE"); - break; - case WM_SIZE: - sprintf(out,"WM_SIZE"); - break; - case WM_ACTIVATE: - sprintf(out,"WM_ACTIVATE"); - break; - case WM_SETFOCUS: - sprintf(out,"WM_SETFOCUS"); - break; - case WM_KILLFOCUS: - sprintf(out,"WM_KILLFOCUS"); - break; - case WM_ENABLE: - sprintf(out,"WM_ENABLE"); - break; - case WM_SETREDRAW: - sprintf(out,"WM_REDRAW"); - break; - case WM_PAINT: - sprintf(out,"WM_PAINT"); - break; - case WM_CLOSE: - sprintf(out,"WM_CLOSE"); - break; - case WM_QUIT: - sprintf(out,"WM_QUIT"); - break; - case WM_ACTIVATEAPP: - sprintf(out,"WM_ACTIVATEAPP"); - break; - case WM_SETCURSOR: - sprintf(out,"WM_SETCURSOR"); - break; - case WM_KEYDOWN: - sprintf(out,"WM_KEYDOWN"); - break; - case WM_MOUSEMOVE: - sprintf(out,"WM_MOUSEMOVE"); - break; - case WM_WINDOWPOSCHANGING: - sprintf(out,"WM_WINDOWPOSCHANGING"); - break; - case WM_WINDOWPOSCHANGED: - sprintf(out,"WM_WINDOWPOSCHANGED"); - break; - case WM_DISPLAYCHANGE: - sprintf(out,"WM_DISPLAYCHANGE"); - break; - case WM_NCPAINT: - sprintf(out,"WM_NCPAINT"); - break; - case WM_PALETTEISCHANGING: - sprintf(out,"WM_PALETTEISCHANGING"); - break; - case WM_PALETTECHANGED: - sprintf(out,"WM_PALETTECHANGED"); - break; - case WM_NCACTIVATE: - sprintf(out,"WM_NCACTIVATE"); - break; - case WM_NCCALCSIZE: - sprintf(out,"WM_NCCALCSIZE"); - break; - case WM_SYSCOMMAND: - sprintf(out,"WM_SYSCOMMAND"); - break; - default: - sprintf(out,"? UNKNOWN ?"); - return(-1); - } - return(0); -} diff --git a/Generals/Code/Tools/PATCHGET/WINBLOWS.H b/Generals/Code/Tools/PATCHGET/WINBLOWS.H deleted file mode 100644 index d6a842e1b1..0000000000 --- a/Generals/Code/Tools/PATCHGET/WINBLOWS.H +++ /dev/null @@ -1,37 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef WINBLOWS_HEADER -#define WINBLOWS_HEADER - -#define WIN32_LEAN_AND_MEAN -#include -#include -#include - -#include"WSTYPES.H" - - extern HINSTANCE Global_instance; - extern LPSTR Global_commandline; - extern int Global_commandshow; - - extern int main(int argc, char *argv[]); - - int Print_WM(UINT wm,char *out); - -#endif diff --git a/Generals/Code/Tools/PATCHGET/WSTYPES.H b/Generals/Code/Tools/PATCHGET/WSTYPES.H deleted file mode 100644 index 6ab69ba0c0..0000000000 --- a/Generals/Code/Tools/PATCHGET/WSTYPES.H +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: -File Name : wstypes.h -Author : Neal Kettler -Start Date : June 3, 1997 -Last Update : June 17, 1997 - -Standard type definitions for the sake of portability and readability. -\***************************************************************************/ - -#ifndef WTYPES_HEADER -#define WTYPES_HEADER - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - - -//These are used for readability purposes mostly, when a method takes a -// pointer or reference these help specify what will happen to the data -// that is sent in. -#define IN -#define OUT -#define INOUT - -typedef char bit8; - - -typedef char sint8; -typedef unsigned char uint8; -typedef signed short int sint16; -typedef unsigned short int uint16; -typedef signed int sint32; -typedef unsigned int uint32; - - -#define MAX_BIT8 0x1 -#define MAX_UINT32 0xFFFFFFFF -#define MAX_UINT16 0xFFFF -#define MAX_UINT8 0xFF -#define MAX_SINT32 0x7FFFFFFF -#define MAX_SINT16 0x7FFF -#define MAX_SINT8 0x7F - -#ifdef _WIN32 -#define strncasecmp _strnicmp -#define strcasecmp _stricmp -#endif - -#endif diff --git a/Generals/Code/Tools/PATCHGET/debug.h b/Generals/Code/Tools/PATCHGET/debug.h deleted file mode 100644 index fed78bb155..0000000000 --- a/Generals/Code/Tools/PATCHGET/debug.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: debug.h ////////////////////////////////////////////////////////////// -// Minimal debug info -// Author: Matthew D. Campbell, Sept 2002 - -#ifndef __DEBUG_H__ -#define __DEBUG_H__ - -namespace patchget -{ - -#if defined(DEBUG) || defined(DEBUG_LOGGING) - -void DebugLog( const char *fmt, ... ); -#define DEBUG_LOG(x) DebugLog x - -#else // DEBUG - -#define DEBUG_LOG(x) {} - -#endif // DEBUG - - -#ifdef DEBUG_CRASHING - - extern void DebugCrash(const char *format, ...); - - /* - Yeah, it's a sleazy global, since we can't reasonably add - any args to DebugCrash due to the varargs nature of it. - We'll just let it slide in this case... - */ - extern char* TheCurrentIgnoreCrashPtr; - - #define DEBUG_CRASH(m) \ - do { \ - { \ - static char ignoreCrash = 0; \ - if (!ignoreCrash) { \ - TheCurrentIgnoreCrashPtr = &ignoreCrash; \ - DebugCrash m ; \ - TheCurrentIgnoreCrashPtr = NULL; \ - } \ - } \ - } while (0) - - #define DEBUG_ASSERTCRASH(c, m) do { { if (!(c)) DEBUG_CRASH(m); } } while (0) - -#else - - #define DEBUG_CRASH(m) ((void)0) - #define DEBUG_ASSERTCRASH(c, m) ((void)0) - -#endif - -} // namespace patchget - -#endif // __DEBUG_H__ - diff --git a/Generals/Code/Tools/PATCHGET/registry.cpp b/Generals/Code/Tools/PATCHGET/registry.cpp deleted file mode 100644 index 1a60c8c913..0000000000 --- a/Generals/Code/Tools/PATCHGET/registry.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// Registry.cpp -// Simple interface for storing/retreiving registry values -// Author: Matthew D. Campbell, December 2001 - -#include - -#define WIN32_LEAN_AND_MEAN -#include - -#include "Registry.h" - -namespace patchget -{ - -bool getStringFromRegistry(HKEY root, std::string path, std::string key, std::string& val) -{ - HKEY handle; - unsigned char buffer[256]; - unsigned long size = 256; - unsigned long type; - int returnValue; - - if ((returnValue = RegOpenKeyEx( root, path.c_str(), 0, KEY_ALL_ACCESS, &handle )) == ERROR_SUCCESS) - { - returnValue = RegQueryValueEx(handle, key.c_str(), NULL, &type, (unsigned char *) &buffer, &size); - RegCloseKey( handle ); - } - - if (returnValue == ERROR_SUCCESS) - { - val = (char *)buffer; - return true; - } - - return false; -} - -bool getUnsignedIntFromRegistry(HKEY root, std::string path, std::string key, unsigned int& val) -{ - HKEY handle; - unsigned long buffer; - unsigned long size = sizeof(buffer); - unsigned long type; - int returnValue; - - if ((returnValue = RegOpenKeyEx( root, path.c_str(), 0, KEY_ALL_ACCESS, &handle )) == ERROR_SUCCESS) - { - returnValue = RegQueryValueEx(handle, key.c_str(), NULL, &type, (unsigned char *) &buffer, &size); - RegCloseKey( handle ); - } - - if (returnValue == ERROR_SUCCESS) - { - val = buffer; - return true; - } - - return false; -} - -bool setStringInRegistry( HKEY root, std::string path, std::string key, std::string val) -{ - HKEY handle; - unsigned long type; - unsigned long returnValue; - int size; - char lpClass[] = "REG_NONE"; - - if ((returnValue = RegCreateKeyEx( root, path.c_str(), 0, lpClass, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &handle, NULL )) == ERROR_SUCCESS) - { - type = REG_SZ; - size = val.length()+1; - returnValue = RegSetValueEx(handle, key.c_str(), 0, type, (unsigned char *)val.c_str(), size); - RegCloseKey( handle ); - } - - return (returnValue == ERROR_SUCCESS); -} - -bool setUnsignedIntInRegistry( HKEY root, std::string path, std::string key, unsigned int val) -{ - HKEY handle; - unsigned long type; - unsigned long returnValue; - int size; - char lpClass[] = "REG_NONE"; - - if ((returnValue = RegCreateKeyEx( root, path.c_str(), 0, lpClass, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &handle, NULL )) == ERROR_SUCCESS) - { - type = REG_DWORD; - size = 4; - returnValue = RegSetValueEx(handle, key.c_str(), 0, type, (unsigned char *)&val, size); - RegCloseKey( handle ); - } - - return (returnValue == ERROR_SUCCESS); -} - -bool GetStringFromRegistry(std::string path, std::string key, std::string& val) -{ - std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; - - fullPath.append(path); - if (getStringFromRegistry(HKEY_LOCAL_MACHINE, fullPath.c_str(), key.c_str(), val)) - { - return true; - } - - return getStringFromRegistry(HKEY_CURRENT_USER, fullPath.c_str(), key.c_str(), val); -} - -bool GetUnsignedIntFromRegistry(std::string path, std::string key, unsigned int& val) -{ - std::string fullPath = "SOFTWARE\\Electronic Arts\\EA Games\\Generals"; - - fullPath.append(path); - if (getUnsignedIntFromRegistry(HKEY_LOCAL_MACHINE, fullPath.c_str(), key.c_str(), val)) - { - return true; - } - - return getUnsignedIntFromRegistry(HKEY_CURRENT_USER, fullPath.c_str(), key.c_str(), val); -} - -} // namespace patchget diff --git a/Generals/Code/Tools/ParticleEditor/CMakeLists.txt b/Generals/Code/Tools/ParticleEditor/CMakeLists.txt index 49a49e7ce2..bf7005ea58 100644 --- a/Generals/Code/Tools/ParticleEditor/CMakeLists.txt +++ b/Generals/Code/Tools/ParticleEditor/CMakeLists.txt @@ -1,4 +1,3 @@ -# Set source files set(PARTICLEED_SRC "CButtonShowColor.cpp" "CButtonShowColor.h" @@ -27,7 +26,6 @@ set(PARTICLEED_SRC "VelocityTypePanels.h" ) -# Targets to build. add_library(g_particleeditor SHARED) set_target_properties(g_particleeditor PROPERTIES OUTPUT_NAME particleeditor PREFIX "") diff --git a/Generals/Code/Tools/ParticleEditor/ParticleEditor.cpp b/Generals/Code/Tools/ParticleEditor/ParticleEditor.cpp index cf59c1c6b9..8f5d5f9d2e 100644 --- a/Generals/Code/Tools/ParticleEditor/ParticleEditor.cpp +++ b/Generals/Code/Tools/ParticleEditor/ParticleEditor.cpp @@ -23,7 +23,7 @@ #include "ParticleEditor.h" #include "ParticleEditorDialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/Generals/Code/Tools/ParticleEditor/ParticleEditor.rc b/Generals/Code/Tools/ParticleEditor/ParticleEditor.rc index 95c73af067..8010aaa685 100644 --- a/Generals/Code/Tools/ParticleEditor/ParticleEditor.rc +++ b/Generals/Code/Tools/ParticleEditor/ParticleEditor.rc @@ -69,7 +69,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/Generals/Code/Tools/W3DView/CMakeLists.txt b/Generals/Code/Tools/W3DView/CMakeLists.txt new file mode 100644 index 0000000000..80ab604011 --- /dev/null +++ b/Generals/Code/Tools/W3DView/CMakeLists.txt @@ -0,0 +1,26 @@ +add_executable(g_w3dview WIN32) + +target_link_libraries(g_w3dview PRIVATE + core_config + core_utility + core_wwstub # avoid linking GameEngine + corei_w3dview # this interface gets the source files for the tool + d3d8 + d3d8lib + d3dx8 + dbghelplib + imm32 + milesstub + Version + vfw32 + winmm + g_wwaudio + g_wwvegas +) + +if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") + target_compile_definitions(g_w3dview PRIVATE _AFXDLL) + set_target_properties(g_w3dview PROPERTIES OUTPUT_NAME W3DViewV) +else() + set_target_properties(g_w3dview PROPERTIES OUTPUT_NAME w3dviewv) +endif() diff --git a/Generals/Code/Tools/WW3D/max2w3d/AlphaModifier.cpp b/Generals/Code/Tools/WW3D/max2w3d/AlphaModifier.cpp deleted file mode 100644 index e37c720efa..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/AlphaModifier.cpp +++ /dev/null @@ -1,477 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project name : Buccaneer Bay * - * * - * File name : AlphaModifier.cpp * - * * - * Programmer : Mike Lytle * - * * - * Start date : 11/1/1999 * - * * - * Last update : 11/1/1999 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "AlphaModifier.h" - -enum Alpha_Messages -{ - AM_NOTHING, - AM_UPDATE_DATA, - AM_INITIALIZE, - AM_BOX_CHECKED, -}; - -enum Dialog_Controls -{ - DL_EDIT_VALUE, - DL_FIND_CHECK_BOX, -}; - -void AlphaModifierClass::ModifyObject(TimeValue t, ModContext &mc, ObjectState *os, INode *node) -{ - if (!os->obj->IsSubClassOf(triObjectClassID)) - { - return; - } - - - // Get a mesh from input object - TriObject *object = (TriObject*)os->obj; - - Mesh *mesh = &object->mesh; - - assert(mesh); - - int numVert = mesh->getNumVerts(); - int i = 0; - float *vdata = NULL; - - // Get parameters from pblock - float sparam = 0.0f; - Interval valid = LocalValidity(t); - int pass = 1; - - pblock->GetValue(DL_EDIT_VALUE, t, sparam, valid); - - // If needed a control could be put into the dialog box to specify which - // pass to apply the alpha values to. At this time, it was decided to - // not implement this because of the complexity to the artist and the - // performance issues in game. - //pblock->GetValue(DL_EDIT_PASS, t, pass, valid); - - - // Start from 0. - pass -= 1; - assert(pass >= 0); - - // Use a channel for each pass. - vdata = mesh->vertexFloat(ALPHA_VERTEX_CHANNEL + pass); - - if (!vdata) - { - // Turn on the channel for vertex alpha support. - mesh->setVDataSupport(ALPHA_VERTEX_CHANNEL + pass); - vdata = mesh->vertexFloat(ALPHA_VERTEX_CHANNEL + pass); - - assert(vdata); - - for (i = 0; i < numVert; i++) - { - if (mesh->VertSel()[i]) - { - vdata[i] = 0.0f; - } - } - - } - - // Tracks the state of the FIND check box. - int box_checked = 0; - - - if (Message == AM_UPDATE_DATA) - { - // The user has updated the dialog box, so update the data. - assert(vdata); - - pblock->GetValue(DL_FIND_CHECK_BOX, t, box_checked, valid); - if (!box_checked) - { - for (i = 0; i < numVert; i++) - { - if (SelectedVertices[i]) - { - vdata[i] = sparam; - } - } - } - } - - if (Message == AM_BOX_CHECKED) - { - pblock->GetValue(DL_FIND_CHECK_BOX, t, box_checked, valid); - } - - - // The user is trying to find vertices with certain values. - if (box_checked) - { - assert(vdata); - // Find the vertices that have the user entered value. - for (i = 0; i < numVert; i++) - { - if (vdata[i] == sparam) - { - mesh->VertSel().Set(i); - SelectedVertices.Set(i); - } - else - { - mesh->VertSel().Clear(i); - SelectedVertices.Clear(i); - } - - } - - } - - if (Message == AM_INITIALIZE) - { - assert(vdata); - - SelectedVertices = mesh->VertSel(); - - for (i = 0; i < numVert; i++) - { - if (SelectedVertices[i]) - { - // Set the value in the dialog box to the value of the - // first selected vertex. - pblock->SetValue(DL_EDIT_VALUE, t, vdata[i]); - break; - } - } - - } - - - // Always select the vertices that have been saved by the modifier. - // This must be done because the mesh changes each time ModfiyObject is called. - for (i = 0; i < numVert; i++) - { - if (SelectedVertices[i]) - { - mesh->VertSel().Set(i); - } - else - { - mesh->VertSel().Clear(i); - } - - } - - // Display the vertices. - mesh->SetDispFlag(DISP_SELVERTS | DISP_VERTTICKS); - mesh->selLevel = MESH_VERTEX; - object->UpdateValidity(SELECT_CHAN_NUM, object->ChannelValidity (t, SELECT_CHAN_NUM)); - - // Clear messages. - Message = AM_NOTHING; -} - - - - -/*===========================================================================*\ - | NotifyInputChanged is called each time the input object is changed in some way - | We can find out how it was changed by checking partID and message -\*===========================================================================*/ - -void AlphaModifierClass::NotifyInputChanged(Interval changeInt, PartID partID, RefMessage message, ModContext *mc) -{ - if( (partID&PART_TOPO) || (partID&PART_GEOM) || (partID&PART_SELECT) ) - { - NotifyDependents(FOREVER, PART_OBJ, REFMSG_CHANGE); - } -} - - -/*===========================================================================*\ - | Class Descriptor OSM -\*===========================================================================*/ - -class AlphaClassDesc : public ClassDesc2 { - public: - int IsPublic() { return TRUE; } - void * Create( BOOL loading ) { return new AlphaModifierClass; } - const TCHAR * ClassName() { return Get_String(IDS_ALPHA_MODIFIER_CLASS); } - SClass_ID SuperClassID() { return OSM_CLASS_ID; } - Class_ID ClassID() { return ALPHA_MODIFIER_CLASSID; } - const TCHAR* Category() { return _T(""); } - - HINSTANCE HInstance() { return AppInstance; } - - // Hardwired name, used by MAX Script as unique identifier - const TCHAR* InternalName() { return _T("AlphaMod"); } -}; - -static AlphaClassDesc AlphaCD; -ClassDesc* Get_Alpha_Desc() {return &AlphaCD;} - -/*===========================================================================*\ - | Paramblock2 Descriptor -\*===========================================================================*/ -static ParamBlockDesc2 alpha_param_blk -( - //rollout - 0, _T("AlphaModifierParams"), 0, &AlphaCD, P_AUTO_CONSTRUCT + P_AUTO_UI, 0, - IDD_ALPHA_MODIFIER, IDS_PARAMETERS, 0, 0, NULL, - - // params - - DL_EDIT_VALUE, _T("Custom Data Value"), TYPE_FLOAT, P_ANIMATABLE, IDS_ALPHA_MODIFIER_CLASS, - p_default, 0.0f, - p_range, 0.0f, 100.0f, - p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, IDC_ALPHA_EDIT, IDC_ALPHA_SPIN, 1.0f, - end, - - DL_FIND_CHECK_BOX, _T("1 Custom Data Value"), TYPE_BOOL, 0, IDS_ALPHA_MODIFIER_CLASS, - p_default, FALSE, - p_ui, TYPE_SINGLECHEKBOX, IDC_ALPHA_CHECKBOX, - p_enabled, TRUE, - end, - -/* - DL_EDIT_PASS, _T("2 Custom Data Value"), TYPE_INT, P_ANIMATABLE, IDS_ALPHA_MODIFIER_CLASS, - p_default, 1, - p_range, 1, 4, - p_ui, TYPE_SPINNER, EDITTYPE_INT, IDC_ALPHA_EDIT2, IDC_ALPHA_SPIN2, 1.0, - end, -*/ - - end -); - - -/*===========================================================================*\ - | Basic implementation of a dialog handler -\*===========================================================================*/ - -BOOL AlphaModDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - int id = LOWORD(wParam); - int code = HIWORD(wParam); - - switch (msg) - { - case WM_INITDIALOG: - AlphaModifier->Message = AM_INITIALIZE; - break; - case WM_DESTROY: - break; - case WM_COMMAND: - switch (code) - { - case EN_UPDATE: - break; - case EN_SETFOCUS: - break; - case EN_KILLFOCUS: - break; - case EN_CHANGE: - break; - } - if (id == IDC_ALPHA_EDIT) - { - AlphaModifier->Message = AM_UPDATE_DATA; - } - if (id == IDC_ALPHA_CHECKBOX) - { - AlphaModifier->Message = AM_BOX_CHECKED; - } - break; - - case WM_NOTIFY: - if (id == IDC_ALPHA_EDIT) - { - AlphaModifier->Message = AM_UPDATE_DATA; - } - break; - - default: - break; - - - } - return FALSE; -} - - -/*===========================================================================*\ - | Constructor - | Ask the ClassDesc2 to make the AUTO_CONSTRUCT paramblocks and wire them in -\*===========================================================================*/ - -AlphaModifierClass::AlphaModifierClass() -{ - AlphaCD.MakeAutoParamBlocks(this); - assert(pblock); - Message = 0; -} - - -/*===========================================================================*\ - | Invalidate our UI (or the recently changed parameter) -\*===========================================================================*/ - -void AlphaModifierClass::InvalidateUI() -{ - alpha_param_blk.InvalidateUI(pblock->LastNotifyParamID()); -} - - - -/*===========================================================================*\ - | Open and Close dialog UIs - | We ask the ClassDesc2 to handle Beginning and Ending EditParams for us -\*===========================================================================*/ - -void AlphaModifierClass::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev ) -{ - - AlphaCD.BeginEditParams(ip, this, flags, prev); - - alpha_param_blk.SetUserDlgProc(new AlphaModDlgProc(this)); -} - -void AlphaModifierClass::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next ) -{ - AlphaCD.EndEditParams(ip, this, flags, next); -} - - - -/*===========================================================================*\ - | Standard clone -\*===========================================================================*/ - - -RefTargetHandle AlphaModifierClass::Clone(RemapDir& remap) -{ - AlphaModifierClass* newmod = new AlphaModifierClass(); - newmod->ReplaceReference(0,pblock->Clone(remap)); - return(newmod); -} - - - - -/*===========================================================================*\ - | Subanim & References support -\*===========================================================================*/ - -Animatable* AlphaModifierClass::SubAnim(int i) -{ - switch (i) - { - case 0: return pblock; - default: return NULL; - } -} - -TSTR AlphaModifierClass::SubAnimName(int i) -{ - switch (i) - { - case 0: return Get_String(IDS_PARAMETERS); - default: return _T(""); - } -} - -RefTargetHandle AlphaModifierClass::GetReference(int i) -{ - switch (i) - { - case 0: return pblock; - default: - assert(TRUE); - return NULL; - } -} - -void AlphaModifierClass::SetReference(int i, RefTargetHandle rtarg) -{ - switch (i) - { - case 0: pblock = (IParamBlock2*)rtarg; break; - default: - assert(TRUE); - break; - } -} - -RefResult AlphaModifierClass::NotifyRefChanged -( - Interval changeInt, - RefTargetHandle hTarget, - PartID& partID, - RefMessage message -) -{ - switch (message) - { - case REFMSG_CHANGE: - { - alpha_param_blk.InvalidateUI(); - } - break; - } - return REF_SUCCEED; -} - - - - -/*===========================================================================*\ - | The validity of our parameters - | Start at FOREVER, and intersect with the validity of each item -\*===========================================================================*/ - -Interval AlphaModifierClass::GetValidity(TimeValue t) -{ - float f; - Interval valid = FOREVER; - pblock->GetValue(DL_EDIT_VALUE, t, f, valid); - return valid; -} - -Interval AlphaModifierClass::LocalValidity(TimeValue t) -{ - return GetValidity(t); -} - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/AlphaModifier.h b/Generals/Code/Tools/WW3D/max2w3d/AlphaModifier.h deleted file mode 100644 index 732f5f539e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/AlphaModifier.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project name : Buccaneer Bay * - * * - * File name : AlphaModifier.h * - * * - * Programmer : Mike Lytle * - * * - * Start date : 11/1/1999 * - * * - * Last update : 11/1/1999 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef ALPHA_MODIFIER_H -#define ALPHA_MODIFIER_H - - -#include -#include "iparamm2.h" -#include "istdplug.h" -#include "meshadj.h" -#include "modstack.h" -#include "macrorec.h" -#include "resource.h" -#include "dllmain.h" - - -#define ALPHA_MODIFIER_CLASSID Class_ID(0x518970b3, 0x37d73373) - - -extern ClassDesc* Get_Alpha_Desc(); - -#define ALPHA_VERTEX_CHANNEL 10 - -class AlphaModifierClass : public Modifier -{ - public: - - // Global parameter block - IParamBlock2 *pblock; - - - //Constructor/Destructor - AlphaModifierClass(); - ~AlphaModifierClass() {} - void DeleteThis() { delete this;} - - - // Plugin identification - void GetClassName(TSTR& s) { s= TSTR(Get_String(IDS_ALPHA_MODIFIER_CLASS));} - virtual Class_ID ClassID() { return ALPHA_MODIFIER_CLASSID;} - TCHAR *GetObjectName() { return Get_String(IDS_ALPHA_MODIFIER_CLASS);} - - - // Defines the behavior for this modifier - // This is currently setup to be basic geometry - // modification of deformable objects - ChannelMask ChannelsUsed() {return PART_GEOM|PART_TOPO|PART_SELECT|PART_SUBSEL_TYPE;} - ChannelMask ChannelsChanged() {return PART_GEOM|PART_TOPO|PART_SELECT|PART_SUBSEL_TYPE;} - Class_ID InputType() { return triObjectClassID;} - BOOL ChangeTopology() {return FALSE;} - - - // Calculate the local validity from the parameters - Interval LocalValidity(TimeValue t); - Interval GetValidity(TimeValue t); - - - // Object modification and notification of change - void ModifyObject(TimeValue t, ModContext &mc, ObjectState *os, INode *node); - void NotifyInputChanged(Interval changeInt, PartID partID, RefMessage message, ModContext *mc); - - - // Reference support - int NumRefs() { return 1;} - RefTargetHandle GetReference(int i); - void SetReference(int i, RefTargetHandle rtarg); - RefTargetHandle Clone(RemapDir& remap = NoRemap()); - RefResult NotifyRefChanged( Interval changeInt,RefTargetHandle hTarget, PartID& partID, RefMessage message); - - // SubAnim support - int NumSubs() { return 0;} - Animatable* SubAnim(int i); - TSTR SubAnimName(int i); - - // Direct paramblock access - int NumParamBlocks() {return 1;} - IParamBlock2* GetParamBlock(int i) { return pblock;} - IParamBlock2* GetParamBlockByID(BlockID id) {return (pblock->ID() == id) ? pblock : NULL;} - int GetParamBlockIndex(int id) {return id;} - - // Does not use createmouse callbacks - CreateMouseCallBack* GetCreateMouseCallBack() {return NULL;} - - // Load and unload our UI - void BeginEditParams(IObjParam *ip, ULONG flags,Animatable *prev); - void EndEditParams(IObjParam *ip, ULONG flags,Animatable *next); - void InvalidateUI(); - - // Message saved from window messages. - int Message; - - // Selected vertices. - BitArray SelectedVertices; -}; - - -/*===========================================================================*\ - | Dialog Processor -\*===========================================================================*/ - -class AlphaModDlgProc : public ParamMap2UserDlgProc -{ - public: - AlphaModifierClass *AlphaModifier; - - AlphaModDlgProc() {} - AlphaModDlgProc(AlphaModifierClass *alpha_m) {AlphaModifier = alpha_m;} - - BOOL DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); - void DeleteThis() {} - - void SetThing(ReferenceTarget *m) {AlphaModifier = (AlphaModifierClass*)m;} -}; - - -#endif //ALPHA_MODIFIER_H - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/AppData.cpp b/Generals/Code/Tools/WW3D/max2w3d/AppData.cpp deleted file mode 100644 index 2a57dd814c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/AppData.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/AppData.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 9/26/00 4:24p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -/* -** AppData.cpp - Implementation of some Westwood -** extensions to the MAXScript language. -*/ - -#include // Main MAXScript header -#include // MAX* Wrapper objects -#include // MAX String class -#include // def_* functions to create static function headers - -#include "w3dutil.h" // W3DAppData*Struct accessor functions! -#include "w3ddesc.h" - - -/* -** Let MAXScript know we're implementing new built-in functions. -*/ -def_visible_primitive(copy_app_data, "wwCopyAppData"); -def_visible_primitive(set_origin_app_data, "wwSetOriginAppData"); -def_visible_primitive(get_hierarchy_file, "wwGetHierarchyFile"); - - -/* -** -** MAXScript Function: -** wwCopyAppData - Usage: wwCopyAppData to_node from_node -** -** Copies all AppData associated with from_node to to_node. -** This is needed for W3D flags such as Export Geometry -** and Export Transform to get passed on to their -** instances/copies/references. -*/ -Value * copy_app_data_cf (Value **arg_list, int count) -{ - // Verify the number and type of the arguments. - check_arg_count("wwCopyAppData", 2, count); - type_check(arg_list[0], MAXNode, "Target INode"); - type_check(arg_list[1], MAXNode, "Source INode"); - - // Get the INode pointers that were passed in. - INode *dest_node = arg_list[0]->to_node(); - INode *src_node = arg_list[1]->to_node(); - - /* - ** Copy W3DAppData0Struct - */ - W3DAppData0Struct *app_data_0 = GetW3DAppData0(src_node); - if (app_data_0 != NULL) { - - // App Data 0 is now obsolete, not fatal if we don't find one - W3DAppData0Struct *copy_data_0 = new W3DAppData0Struct; - if (copy_data_0 == NULL) - throw RuntimeError("Out of memory."); - - // Copy the app data and give it to the target node. - *copy_data_0 = *app_data_0; - dest_node->AddAppDataChunk(W3DUtilityClassID, UTILITY_CLASS_ID, W3D_APPDATA_0, - sizeof(W3DAppData0Struct), copy_data_0); - } - - /* - ** Copy W3DAppData1Struct - */ - W3DAppData1Struct *app_data_1 = GetW3DAppData1(src_node); - if (app_data_1 == NULL) - throw RuntimeError("Unable to retrieve W3DAppData1Struct from object: ", arg_list[1]); - - W3DAppData1Struct *copy_data_1 = new W3DAppData1Struct; - if (copy_data_1 == NULL) - throw RuntimeError("Out of memory."); - - // Copy the app data and give it to the target node. - *copy_data_1 = *app_data_1; - dest_node->AddAppDataChunk(W3DUtilityClassID, UTILITY_CLASS_ID, W3D_APPDATA_1, - sizeof(W3DAppData1Struct), copy_data_1); - - - /* - ** Copy W3DAppData2Struct - */ - W3DAppData2Struct *app_data_2 = GetW3DAppData2(src_node); - if (app_data_2 == NULL) - throw RuntimeError("Unable to retrieve W3DAppData1Struct from object: ", arg_list[1]); - - W3DAppData2Struct *copy_data_2 = new W3DAppData2Struct; - if (copy_data_2 == NULL) - throw RuntimeError("Out of memory."); - - // Copy the app data and give it to the target node. - *copy_data_2 = *app_data_2; - dest_node->AddAppDataChunk(W3DUtilityClassID, UTILITY_CLASS_ID, W3D_APPDATA_2, - sizeof(W3DAppData2Struct), copy_data_2); - - /* - ** Copy W3DDazzleAppDataStruct if one is present. - */ - W3DDazzleAppDataStruct *dazzle_app_data = GetW3DDazzleAppData(src_node); - if (dazzle_app_data != NULL) { - - W3DDazzleAppDataStruct *copy_dazzle_data = new W3DDazzleAppDataStruct; - if (copy_dazzle_data == NULL) - throw RuntimeError("Out of memory."); - - - // Copy the app data and give it to the target node. - *copy_dazzle_data = *dazzle_app_data; - dest_node->AddAppDataChunk(W3DUtilityClassID, UTILITY_CLASS_ID, W3D_DAZZLE_APPDATA, - sizeof(W3DDazzleAppDataStruct), copy_dazzle_data); - } - - return &ok; -} - - - -/* -** -** MAXScript Function: -** wwSetOriginAppData - Usage: wwSetOriginAppData origin_node -** -** Sets the AppData associated with the given node to values -** appropriate to an origin. (ie. turn off Export Geometry and -** Export Transform) -*/ -Value * set_origin_app_data_cf (Value **arg_list, int count) -{ - // Check the arguments that were passed to this function. - check_arg_count("wwSetOriginAppData", 1, count); - type_check(arg_list[0], MAXNode, "Origin INode"); - - // Get the INode that we were given. - INode *origin = arg_list[0]->to_node(); - - // Get the node's W3DAppData2Struct, and modify it accordingly. - W3DAppData2Struct *data = GetW3DAppData2(origin); - if (data == NULL) - throw RuntimeError("Unable to retrieve W3DAppData0Struct from object: ", arg_list[0]); - - // Turn off Export Geometry and Export Hierarchy. - data->Enable_Export_Geometry(false); - data->Enable_Export_Transform(false); - - return &ok; -} - -/* -** -** MAXScript Function: -** wwGetHierarchyFile - Usage: wwGetHierarchyFile() -** -** Returns the relative pathname of the file that will be loaded -** during W3D export to get the hierarchy tree. If no such file -** will be loaded, the return value is the MAXScript undefined. -** -*/ -Value * get_hierarchy_file_cf (Value **arg_list, int count) -{ - // Check that we weren't passed any arguments. - check_arg_count("wwGetHierarchyFile", 0, count); - - // Retrieve the export options from the scene. - W3dExportOptionsStruct *options = NULL; - AppDataChunk * appdata = MAXScript_interface->GetScenePointer()->GetAppDataChunk(W3D_EXPORTER_CLASS_ID,SCENE_EXPORT_CLASS_ID,0); - if (appdata) - options = (W3dExportOptionsStruct*)(appdata->data); - - // If we didn't get any options, return undefined. - if (!options) - return &undefined; - - // Return the relative path to the htree file if it's available. - // Otherwise, return the absolute path. - one_typed_value_local(String* htree_file); - if (options->RelativeHierarchyFilename[0] != 0) - vl.htree_file = new String(options->RelativeHierarchyFilename); - else if (options->HierarchyFilename[0] != 0) - vl.htree_file = new String(options->HierarchyFilename); - else - { - // Neither filename is available, return undefined. - pop_value_locals(); - return &undefined; - } - return_value(vl.htree_file); -} - - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/CMakeLists.txt b/Generals/Code/Tools/WW3D/max2w3d/CMakeLists.txt deleted file mode 100644 index e8b27aa5e9..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/CMakeLists.txt +++ /dev/null @@ -1,176 +0,0 @@ -set(MAX2W3D_SRC - "aabtreebuilder.cpp" - "aabtreebuilder.h" - "AlphaModifier.cpp" - "AlphaModifier.h" - "animationcompressionsettings.cpp" - "animationcompressionsettings.h" - "AppData.cpp" - "bchannel.cpp" - "bchannel.h" - "boneicon.cpp" - "boneicon.h" - "bpick.cpp" - "bpick.h" - "colboxsave.cpp" - "colboxsave.h" - "dazzlesave.cpp" - "dazzlesave.h" - "dllmain.cpp" - "dllmain.h" - "ExportAll.cpp" - "ExportAllDlg.cpp" - "ExportAllDlg.h" - "exportlog.cpp" - "exportlog.h" - "floaterdialog.cpp" - "floaterdialog.h" - "FormClass.cpp" - "FormClass.h" - "gamemaps.cpp" - "gamemaps.h" - "GameMtl.cpp" - "gamemtl.h" - "GameMtlDlg.cpp" - "GameMtlDlg.h" - "GameMtlForm.cpp" - "GameMtlForm.h" - "GameMtlPassDlg.cpp" - "GameMtlPassDlg.h" - "GameMtlShaderDlg.cpp" - "GameMtlShaderDlg.h" - "GameMtlTextureDlg.cpp" - "GameMtlTextureDlg.h" - "GameMtlVertexMaterialDlg.cpp" - "GameMtlVertexMaterialDlg.h" - "genlodextensiondialog.cpp" - "genlodextensiondialog.h" - "genmtlnamesdialog.cpp" - "genmtlnamesdialog.h" - "gennamesdialog.cpp" - "gennamesdialog.h" - "geometryexportcontext.h" - "geometryexporttask.cpp" - "geometryexporttask.h" - #"gmtldlg.cpp" - "gridsnapmodifier.cpp" - "gridsnapmodifier.h" - "hiersave.cpp" - "hiersave.h" - "hlodsave.cpp" - "hlodsave.h" - "InputDlg.cpp" - "InputDlg.h" - #"LightGlareSave.cpp" - #"LightGlareSave.h" - "logdlg.cpp" - "logdlg.h" - "max2w3d.def" - "maxworldinfo.cpp" - "maxworldinfo.h" - "meshbuild.cpp" - "meshbuild.h" - "meshcon.cpp" - "meshcon.h" - "MeshDeform.cpp" - "MeshDeform.h" - "MeshDeformData.cpp" - "MeshDeformData.h" - "MeshDeformDefs.h" - "MeshDeformPanel.cpp" - "MeshDeformPanel.h" - "MeshDeformSave.cpp" - "MeshDeformSave.h" - "MeshDeformSaveDefs.h" - "MeshDeformSaveSet.cpp" - "MeshDeformSaveSet.h" - "MeshDeformSet.cpp" - "MeshDeformSet.h" - "MeshDeformUndo.cpp" - "MeshDeformUndo.h" - "meshsave.cpp" - "meshsave.h" - "motion.cpp" - "motion.h" - "namedsel.cpp" - "namedsel.h" - "nullsave.cpp" - "nullsave.h" - "PCToPS2Material.cpp" - "presetexportoptionsdialog.cpp" - "presetexportoptionsdialog.h" - "PS2GameMtl.cpp" - "PS2GameMtlShaderDlg.cpp" - "PS2GameMtlShaderDlg.h" - "rcmenu.cpp" - "rcmenu.h" - "resource.h" - "SceneSetup.cpp" - "SceneSetupDlg.cpp" - "SceneSetupDlg.h" - "simpdib.cpp" - "simpdib.h" - "skin.cpp" - "skin.h" - "SkinCopy.cpp" - "skindata.cpp" - "skindata.h" - "SnapPoints.cpp" - "SnapPoints.h" - "TARGA.CPP" - "TARGA.H" - "util.cpp" - "util.h" - "Utility.cpp" - "vchannel.cpp" - "vchannel.h" - "vxl.cpp" - "vxl.h" - "vxldbg.cpp" - "vxldbg.h" - "vxllayer.cpp" - "vxllayer.h" - "w3d_file.h" - "w3d_obsolete.h" - "w3dappdata.cpp" - "w3dappdata.h" - "w3ddesc.cpp" - "w3ddesc.h" - "w3ddlg.cpp" - "w3ddlg.h" - "w3dexp.cpp" - "w3dexp.h" - "w3dmtl.cpp" - "w3dmtl.h" - "w3dutil.cpp" - "w3dutil.h" -) - -add_library(g_max2w3d SHARED) -set_target_properties(g_max2w3d PROPERTIES OUTPUT_NAME max2w3d SUFFIX ".dle") - -target_include_directories(g_max2w3d PRIVATE - "../pluglib" -) - -target_sources(g_max2w3d PRIVATE ${MAX2W3D_SRC}) - -# TODO: What does W3D_MAX4 do? Needs cmake option? -target_compile_definitions(g_max2w3d PRIVATE W3D_MAX4) - -target_link_libraries(g_max2w3d PRIVATE - Comctl32 - # This is only linked to have its basetsd.h used instead of the vs6's basetsd.h - # The headers typedef INT_PTR to different types, but maxsdk expects it - # typedef'ed to int, otherwise throws linker errors. - d3d8lib - g_pluglib - maxsdk - winmm -) - -set_target_properties(g_max2w3d PROPERTIES LINK_FLAGS "/DEF:max2w3d.def") - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(g_max2w3d PRIVATE max2w3d.rc) -endif() diff --git a/Generals/Code/Tools/WW3D/max2w3d/ExportAll.cpp b/Generals/Code/Tools/WW3D/max2w3d/ExportAll.cpp deleted file mode 100644 index be0c0a3513..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/ExportAll.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/ExportAll.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 10/15/99 2:08p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * wwExportTreeSettings -- Returns the directory to export, and recursive flag. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -/* -** ExportAll.cpp - Implements wwExportTreeSettings, which presents the user with a dialog -** to allow them to choose which directory they want to export, and whether they want to -** export all subdirectories as well. These settings are then passed back so that a script -** can go through the directory (and maybe the subdirectories) and export all .max files -** it finds. -*/ - - -#include "ExportAllDlg.h" - -#undef STRICT -#include -#include -#include -#include - - -/* -** Let MAXScript know we're implementing new built-in functions. -*/ -def_visible_primitive(export_tree_settings, "wwExportTreeSettings"); - - -/*********************************************************************************************** - * export_tree_settings_cf - Returns the directory to export, and recursive flag. * - * * - * wwExportTreeSettings - Usage: wwExportTreeSettings #(, ) * - * * - * INPUT: A MaxScript array containing two values: * - * initial_path (string) - the initial export directory * - * recursive (bool) - the initial recursive setting * - * * - * OUTPUT: An array of the same format containing the values the user chose. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/4/1999 AJA : Created. * - *=============================================================================================*/ -Value * export_tree_settings_cf (Value **arg_list, int count) -{ - // We want an array as an argument - check_arg_count("wwExportAll", 1, count); - type_check(arg_list[0], Array, "Parameter array"); - - // Grab the two values out of the array. - // First value is a string whose value is the initial value for the directory. - // Second value is a bool, true for a recursive export. - ExportAllDlg dlg(MAXScript_interface); - Array *args = (Array*)(arg_list[0]); - char *temp = (args->get(1))->to_string(); - int len = strlen(temp); - if (len < MAX_PATH) - strcpy(dlg.m_Directory, temp); - else - { - strncpy(dlg.m_Directory, temp, MAX_PATH-1); - dlg.m_Directory[MAX_PATH-1] = 0; - } - dlg.m_Recursive = (args->get(2))->to_bool(); - - // Show the dialog to let the user change the settings. - if (dlg.DoModal() == IDCANCEL) - return &undefined; - - // Create the array we will return to MaxScript. - one_typed_value_local(Array *result); - vl.result = new Array(2); - vl.result->append(new String(dlg.m_Directory)); - if (dlg.m_Recursive) - vl.result->append(&true_value); - else - vl.result->append(&false_value); - - // Return the new values. - return_value(vl.result); -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/ExportAllDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/ExportAllDlg.cpp deleted file mode 100644 index 5c6d3dbcd4..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/ExportAllDlg.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/ExportAllDlg.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 10/15/99 4:25p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -// ExportAllDlg.cpp : implementation file -// - -#include "ExportAllDlg.h" -#include -#include -#include // SHBrowseForFolder - - -static BOOL CALLBACK _thunk_dialog_proc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - -///////////////////////////////////////////////////////////////////////////// -// ExportAllDlg dialog - - -ExportAllDlg::ExportAllDlg (Interface *max_interface) -{ - m_Directory[0] = '\0'; - m_Recursive = TRUE; - m_hWnd = NULL; - assert(max_interface != NULL); - m_MaxInterface = max_interface; -} - - -///////////////////////////////////////////////////////////////////////////// -// ExportAllDlg Methods - -int ExportAllDlg::DoModal (void) -{ - // Put up the dialog box. - BOOL result = DialogBoxParam(AppInstance, MAKEINTRESOURCE(IDD_EXPORT_ALL), - m_MaxInterface->GetMAXHWnd(), (DLGPROC)_thunk_dialog_proc, - (LPARAM)this); - - // Return IDOK if the user accepted the new settings. - return (result == 1) ? IDOK : IDCANCEL; -} - -///////////////////////////////////////////////////////////////////////////// -// ExportAllDlg DialogProc - -BOOL CALLBACK _thunk_dialog_proc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - static ExportAllDlg *dialog = NULL; - - if (uMsg == WM_INITDIALOG) - { - dialog = (ExportAllDlg*)lParam; - dialog->m_hWnd = hWnd; - } - - if (dialog) - return dialog->DialogProc(hWnd, uMsg, wParam, lParam); - else - return 0; -} - -BOOL CALLBACK ExportAllDlg::DialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - int code = HIWORD(wParam); - - switch (uMsg) - { - - /******************************************************************* - * WM_INITDIALOG - * - * Initialize all of the custom controls for the dialog box - * - *******************************************************************/ - case WM_INITDIALOG: - - OnInitDialog(); - return TRUE; - - - /******************************************************************* - * WM_COMMAND - * - * - *******************************************************************/ - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - - if (OnOK() == FALSE) - return TRUE; - - SetCursor(LoadCursor(NULL, IDC_WAIT)); - EndDialog(m_hWnd, 1); - break; - - case IDCANCEL: - EndDialog(m_hWnd, 0); - break; - - case IDC_BROWSE: - OnBrowse(); - return FALSE; - - } - return TRUE; - - } - - return FALSE; -} - -///////////////////////////////////////////////////////////////////////////// -// ExportAllDlg message handlers - -void ExportAllDlg::OnInitDialog (void) -{ - CenterWindow(m_hWnd, m_MaxInterface->GetMAXHWnd()); - SetCursor(LoadCursor(NULL, IDC_ARROW)); - - // Set the check box state. - CheckDlgButton(m_hWnd, IDC_RECURSIVE, m_Recursive); - - // Set the default directory. - HWND edit = GetDlgItem(m_hWnd, IDC_DIRECTORY); - assert(edit != NULL); - SetWindowText(edit, m_Directory); -} - -void ExportAllDlg::OnBrowse() -{ - char folder_name[MAX_PATH]; - BROWSEINFO bi; - ZeroMemory(&bi, sizeof(bi)); - bi.hwndOwner = m_hWnd; - bi.pszDisplayName = folder_name; - bi.lpszTitle = "Select a folder for export..."; - bi.ulFlags = BIF_RETURNONLYFSDIRS; - - // Browse for a folder. - LPITEMIDLIST il = SHBrowseForFolder(&bi); - if (il) - { - // Get the path of the folder. - if (SHGetPathFromIDList(il, folder_name)) - { - HWND edit = GetDlgItem(m_hWnd, IDC_DIRECTORY); - assert(edit != NULL); - SetWindowText(edit, folder_name); - } - else - MessageBox(m_hWnd, "Error getting pathname with SHGetPathFromIDList()", - "Error", MB_OK | MB_ICONSTOP); - } -} - -BOOL ExportAllDlg::OnOK (void) -{ - // Get the directory chosen by the user. If none is entered, - // freak on the user. - char dir[_MAX_PATH]; - HWND edit = GetDlgItem(m_hWnd, IDC_DIRECTORY); - assert(edit != NULL); - if (GetWindowText(edit, dir, sizeof(dir)) == 0) - { - // The edit box is empty, that's not a valid choice. - MessageBox(m_hWnd, "You must choose a directory to export", - "Invalid Directory", MB_OK); - SetFocus(edit); - return FALSE; - } - - // TODO: Validate the directory as one that actually exists. - - // Store the values from the dialog in our class members. - strcpy(m_Directory, dir); - m_Recursive = (IsDlgButtonChecked(m_hWnd, IDC_RECURSIVE) == BST_CHECKED) ? TRUE : FALSE; - - return TRUE; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/ExportAllDlg.h b/Generals/Code/Tools/WW3D/max2w3d/ExportAllDlg.h deleted file mode 100644 index c4fc8e1c35..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/ExportAllDlg.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/ExportAllDlg.h $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 10/15/99 4:25p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef EXPORTALLDLG_H -#define EXPORTALLDLG_H - -#include "dllmain.h" -#include "resource.h" - - -class Interface; - -///////////////////////////////////////////////////////////////////////////// -// ExportAllDlg dialog - -class ExportAllDlg -{ -public: - - // Construction - ExportAllDlg (Interface *max_interface); - - // Methods - int DoModal (void); - - // DialogProc - BOOL CALLBACK DialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - // Dialog data associated with GUI components. - char m_Directory[_MAX_PATH]; // edit box - BOOL m_Recursive; // check box - - // Dialog data - enum { IDD = IDD_EXPORT_ALL }; - HWND m_hWnd; - Interface *m_MaxInterface; - -protected: - - // Message Handlers - void OnInitDialog (void); - void OnBrowse (void); - BOOL OnOK (void); // TRUE if ok to close dialog -}; - - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/FormClass.cpp b/Generals/Code/Tools/WW3D/max2w3d/FormClass.cpp deleted file mode 100644 index ad1eec293c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/FormClass.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : FormClass * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/FormClass.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/09/98 3:02a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * FormClass::Create_Form -- Loads the dialog template and initializes * - * FormClass::fnFormProc -- windows proc which thunks into the virtual Dialog_Proc * - * FormClass::ExecuteDlgInit -- Initializes controls in the dialog template * - * FormClass::ExecuteDlgInit -- Initializes the controls in the dialog template * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "FormClass.h" -#include "dllmain.h" - -// hard-coded resource id which VC special cases for MFC... >:-) -#define RT_DLGINIT MAKEINTRESOURCE(240) - - -/*********************************************************************************************** - * FormClass::Create_Form -- Loads the dialog template and initializes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/6/98 GTH : Created. * - *=============================================================================================*/ -HWND -FormClass::Create_Form -( - HWND parent_wnd, - UINT template_id -) -{ - // call PreCreateWindow to get prefered extended style - CREATESTRUCT cs = { 0 }; - cs.style = WS_CHILD; - - m_hWnd = ::CreateDialogParam( AppInstance, - MAKEINTRESOURCE (template_id), - parent_wnd, - fnFormProc, - (LPARAM)this); - - assert(m_hWnd); - - // Remove the caption from the dialog (if there was any) - ::SetWindowLong (m_hWnd, - GWL_STYLE, - ::GetWindowLong (m_hWnd, GWL_STYLE) & (~WS_CAPTION)); - - ::GetWindowRect (m_hWnd, &m_FormRect); - - ExecuteDlgInit(MAKEINTRESOURCE(template_id)); - - return m_hWnd; -} - - -/*********************************************************************************************** - * FormClass::fnFormProc -- windows proc which thunks into the virtual Dialog_Proc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/6/98 GTH : Created. * - *=============================================================================================*/ -BOOL WINAPI -FormClass::fnFormProc -( - HWND dlg_wnd, - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - FormClass *pform = (FormClass *)::GetProp (dlg_wnd, "FORMCLASS"); - - if (message == WM_INITDIALOG) { - pform = (FormClass *)lparam; - ::SetProp (dlg_wnd, "FORMCLASS", (HANDLE)pform); - } else if (message == WM_DESTROY) { - ::RemoveProp (dlg_wnd, "FORMCLASS"); - } - - BOOL retval = FALSE; - if (pform) { - retval = pform->Dialog_Proc (dlg_wnd, message, wparam, lparam); - } - - return retval; -} - - -/*********************************************************************************************** - * FormClass::ExecuteDlgInit -- Initializes controls in the dialog template * - * * - * This code was lifted straight out of MFC. It does some "interesting" things like putting * - * strings into combo boxes which are typed in the resource editor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/6/98 GTH : Created. * - *=============================================================================================*/ -BOOL FormClass::ExecuteDlgInit(LPCTSTR lpszResourceName) -{ - // find resource handle - LPVOID lpResource = NULL; - HGLOBAL hResource = NULL; - if (lpszResourceName != NULL) - { - HINSTANCE hInst = AppInstance; - HRSRC hDlgInit = ::FindResource(hInst, lpszResourceName, RT_DLGINIT); - if (hDlgInit != NULL) - { - // load it - hResource = LoadResource(hInst, hDlgInit); - if (hResource == NULL) - return FALSE; - // lock it - lpResource = LockResource(hResource); - assert(lpResource != NULL); - } - } - - // execute it - BOOL bResult = ExecuteDlgInit(lpResource); - - // cleanup - if (lpResource != NULL && hResource != NULL) - { - UnlockResource(hResource); - FreeResource(hResource); - } - return bResult; -} - - -/*********************************************************************************************** - * FormClass::ExecuteDlgInit -- Initializes the controls in the dialog template * - * * - * As the above ExecuteDlgInit function, this was lifted from MFC... * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/6/98 GTH : Created. * - *=============================================================================================*/ -BOOL FormClass::ExecuteDlgInit(LPVOID lpResource) -{ - BOOL bSuccess = TRUE; - if (lpResource != NULL) - { - UNALIGNED WORD* lpnRes = (WORD*)lpResource; - while (bSuccess && *lpnRes != 0) - { - WORD nIDC = *lpnRes++; - WORD nMsg = *lpnRes++; - DWORD dwLen = *((UNALIGNED DWORD*&)lpnRes)++; - - // In Win32 the WM_ messages have changed. They have - // to be translated from the 32-bit values to 16-bit - // values here. - #define WIN16_LB_ADDSTRING 0x0401 - #define WIN16_CB_ADDSTRING 0x0403 - - if (nMsg == WIN16_LB_ADDSTRING) - nMsg = LB_ADDSTRING; - else if (nMsg == WIN16_CB_ADDSTRING) - nMsg = CB_ADDSTRING; - - // check for invalid/unknown message types - assert(nMsg == LB_ADDSTRING || nMsg == CB_ADDSTRING); - - if (nMsg == LB_ADDSTRING || nMsg == CB_ADDSTRING) - { - // List/Combobox returns -1 for error - if (::SendDlgItemMessageA(m_hWnd, nIDC, nMsg, 0, (LONG)lpnRes) == -1) - bSuccess = FALSE; - } - - // skip past data - lpnRes = (WORD*)((LPBYTE)lpnRes + (UINT)dwLen); - } - } - - return bSuccess; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/FormClass.h b/Generals/Code/Tools/WW3D/max2w3d/FormClass.h deleted file mode 100644 index 77de5b10f4..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/FormClass.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : max2w3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/FormClass.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/13/98 9:34a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef __FORMCLASS_H -#define __FORMCLASS_H - -#include - - -class FormClass : public ParamDlg -{ - public: - FormClass (void) - : m_hWnd (NULL) {} - ~FormClass (void) {} - - HWND Create_Form (HWND parent_wnd, UINT template_id); - void Show (bool show_flag = true) { ::ShowWindow (m_hWnd, show_flag ? SW_SHOW : SW_HIDE); } - virtual BOOL Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam) = 0; - HWND Get_Hwnd(void) { return m_hWnd; } - virtual void Invalidate(void) { InvalidateRect(m_hWnd,NULL,0); } - - protected: - - BOOL ExecuteDlgInit(LPVOID lpResource); - BOOL ExecuteDlgInit(LPCTSTR lpszResourceName); - - static BOOL WINAPI fnFormProc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam); - - HWND m_hWnd; - RECT m_FormRect; -}; - -#endif //__FORMCLASS_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtl.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtl.cpp deleted file mode 100644 index 4463cc7b0b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtl.cpp +++ /dev/null @@ -1,3301 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/GameMtl.cpp 52 8/10/01 2:18p Ian_l $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : GAMEMTL.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/26/97 * - * * - * Last Update : 10/26/1999997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMtl::GameMtl -- constructor * - * GameMtl::~GameMtl -- destructor * - * GameMtl::ClassID -- returns the max ClassID of the material plugin * - * GameMtl::SuperClassID -- returns the super class ID * - * GameMtl::GetClassName -- returns the name of this plugin clas * - * GameMtl::NumSubs -- returns the number of sub animations * - * GameMtl::SubAnimName -- returns the name of the i'th sub animation * - * GameMtl::SubAnim -- returns the i'th sub-anim * - * GameMtl::Clone -- clones this material * - * GameMtl::NotifyRefChanged -- NotifyRefChanged handler * - * GameMtl::SetReference -- set the i'th reference * - * GameMtl::GetReference -- returnst the i'th reference * - * GameMtl::NumSubTexmaps -- returns the number of texture maps in this material * - * GameMtl::SetSubTexmap -- set the i'th texture map * - * GameMtl::GetSubTexmap -- returns the i'th texture map * - * GameMtl::CreateParamDlg -- creates the material editor dialog box * - * GameMtl::Notify_Changed -- someone has changed this material * - * GameMtl::Reset -- reset this material to default settings * - * GameMtl::Update -- time has changed * - * GameMtl::Validity -- return the validity of the material at time t * - * GameMtl::Requirements -- what requirements does this material have? * - * GameMtl::Load -- loading from a MAX file * - * GameMtl::Save -- Saving into a MAX file * - * GameMtl::Shade -- evaluate the material for the renderer. * - * GameMtl::ps2_shade -- Emulate the PS2 shader. * - * GameMtl::Compute_PC_Shader_From_PS2_Shader -- Determine if a PC shader can be created. * - * GameMtl::Compute_PS2_Shader_From_PC_Shader -- Change a W3D material to a PS2 W3D material.* - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "gamemtl.h" -#include -#include -#include -#include "GameMtlDlg.h" -#include "dllmain.h" -#include "resource.h" -#include "util.h" -#include "meshsave.h" -#include "gamemaps.h" - - -/***************************************************************** -* -* GameMtl Class Descriptor -* -*****************************************************************/ -Class_ID GameMaterialClassID(GAMEMTL_ID_PARTA, GAMEMTL_ID_PARTB); - -class GameMaterialClassDesc:public ClassDesc { - -public: - int IsPublic() { return 1; } - void * Create(BOOL loading) { return new GameMtl(loading); } - const TCHAR * ClassName() { return Get_String(IDS_GAMEMTL); } - SClass_ID SuperClassID() { return MATERIAL_CLASS_ID; } - Class_ID ClassID() { return GameMaterialClassID; } - const TCHAR* Category() { return _T(""); } -}; - -static GameMaterialClassDesc _GameMaterialCD; - -ClassDesc * Get_Game_Material_Desc() { return &_GameMaterialCD; } - - -/****************************************************************************** -* -* PostLoadCallback for GameMtl -* -******************************************************************************/ -class GameMtlPostLoad : public PostLoadCallback -{ -public: - GameMtl *m; - - GameMtlPostLoad(GameMtl *b) { m=b; IsOld = false;} - void proc(ILoad *iload); - - /* - ** Data from the previous version of GameMtl - */ - bool IsOld; - ULONG Attributes; - Color Diffuse; - Color Specular; - Color AmbientCoeff; - Color DiffuseCoeff; - Color SpecularCoeff; - Color EmissiveCoeff; - float FogCoeff; - int DCTFrames; - int DITFrames; - int SCTFrames; - int SITFrames; - float DCTFrameRate; - float DITFrameRate; - float SCTFrameRate; - float SITFrameRate; - int DCTMappingType; - int DITMappingType; - int SCTMappingType; - int SITMappingType; - float Opacity; - float Translucency; - float Shininess; -}; - - - -/****************************************************************************** -* -* GameMtl -* -* Notes: -* Prior to Nov, 1998 I was storing everything about the material in custom -* chunks. As part of the upgrade to surrender 1.4x, I'm going to use -* a parameter block for each pass (combination of shader and vertex material) -* -******************************************************************************/ -#define MTL_HDR_CHUNK 0x4000 - -/* -** Custom Chunk IDs -*/ -#define GAMEMTL_FLAGS_CHUNK 0x0000 -#define GAMEMTL_GAMEFLAGS_CHUNK 0x0001 // OBSOLETE! -#define GAMEMTL_COLORS_CHUNK 0x0002 // OBSOLETE! - -#define GAMEMTL_TEXTURE_FRAMES_CHUNK 0x0003 -#define GAMEMTL_ENVMAP_FRAMES_CHUNK 0x0004 -#define GAMEMTL_DCT_FRAMES_CHUNK GAMEMTL_TEXTURE_FRAMES_CHUNK -#define GAMEMTL_DIT_FRAMES_CHUNK GAMEMTL_ENVMAP_FRAMES_CHUNK -#define GAMEMTL_SCT_FRAMES_CHUNK 0x0005 -#define GAMEMTL_SIT_FRAMES_CHUNK 0x0006 - -#define GAMEMTL_DCT_FRAME_RATE_CHUNK 0x0010 -#define GAMEMTL_DIT_FRAME_RATE_CHUNK 0x0011 -#define GAMEMTL_SCT_FRAME_RATE_CHUNK 0x0012 -#define GAMEMTL_SIT_FRAME_RATE_CHUNK 0x0013 - -#define GAMEMTL_DCT_MAPPING_CHUNK 0x0020 -#define GAMEMTL_DIT_MAPPING_CHUNK 0x0021 -#define GAMEMTL_SCT_MAPPING_CHUNK 0x0022 -#define GAMEMTL_SIT_MAPPING_CHUNK 0x0023 - -#define GAMEMTL_ATTRIBUTES_CHUNK 0x0030 -#define GAMEMTL_DIFFUSE_COLOR_CHUNK 0x0031 -#define GAMEMTL_SPECULAR_COLOR_CHUNK 0x0032 - -#define GAMEMTL_AMBIENT_COEFF_CHUNK 0x0040 -#define GAMEMTL_DIFFUSE_COEFF_CHUNK 0x0041 -#define GAMEMTL_SPECULAR_COEFF_CHUNK 0x0042 -#define GAMEMTL_EMISSIVE_COEFF_CHUNK 0x0043 - -#define GAMEMTL_OPACITY_CHUNK 0x0050 -#define GAMEMTL_TRANSLUCENCY_CHUNK 0x0051 -#define GAMEMTL_SHININESS_CHUNK 0x0052 -#define GAMEMTL_FOG_CHUNK 0x0053 - -#define GAMEMTL_PASS0_CUR_PAGE 0x0060 -#define GAMEMTL_PASS1_CUR_PAGE 0x0061 -#define GAMEMTL_PASS2_CUR_PAGE 0x0062 -#define GAMEMTL_PASS3_CUR_PAGE 0x0064 - -#define GAMEMTL_PASS0_STAGE0_MAPPER_ARGS 0x0070 -#define GAMEMTL_PASS1_STAGE0_MAPPER_ARGS 0x0071 -#define GAMEMTL_PASS2_STAGE0_MAPPER_ARGS 0x0072 -#define GAMEMTL_PASS3_STAGE0_MAPPER_ARGS 0x0073 - -#define GAMEMTL_SURFACE_TYPE_CHUNK 0x0080 - -#define GAMEMTL_SORT_LEVEL_CHUNK 0x0090 - -#define GAMEMTL_PASS0_STAGE1_MAPPER_ARGS 0x0100 -#define GAMEMTL_PASS1_STAGE1_MAPPER_ARGS 0x0101 -#define GAMEMTL_PASS2_STAGE1_MAPPER_ARGS 0x0102 -#define GAMEMTL_PASS3_STAGE1_MAPPER_ARGS 0x0103 - - -/* -** Main Parameter Block Definition -*/ -static ParamBlockDescID MainParameterBlockDesc[] = -{ - { TYPE_INT, NULL, FALSE, 0 }, // Pass Count -}; - - -/* -** ID numbers for parameter block entries. As of version 4 of the -** parameter block definitions, these enums should be used directly -** in the pblock defs to avoid accidental ID mismatches. -** -** Note: You should DO NOTHING TO CHANGE THE VALUES OF THE ENUM -** (except adding at the end of course). Following these constraints -** will preserve backwards compatibility with all pblock versions. -** -** Since this enum is now just a series of ID numbers, we must -** manually keep the PASS_PARAMBLOCK_LENGTH up to date. Believe it -** or not, but this is less error-prone than the previous way of -** doing things. -** -** (gth) Aug 6, 2000 -** IMPORTANT -PLEASE READ- -** The following enums are basically the index into the array of -** ParamBlockDescID's that we are using. It is critical that this -** enumeration does not skip indexes and that the value for each -** symbol in this list matches the position in the param block -** for that variable. This enumeration is does not define the -** id for the new variable, only its position in the array. -** -** When you add a new variable to the parameter block, you should -** find an id for it higher than any existing id (look through the -** rest of the entries in the parameter block). That id will not -** usually be able to be the same as its array index due to the -** evolution of this structure. The id I'm referring to is the -** number in the 4th element of each of the ParamBlockDescIDs. -** -** If you remove an entry from our array of ParamBlockDescIDs you -** will need to update all of the PB_xxx enumeration below so that -** they match their position in the array again. -*/ - -enum -{ - PB_AMBIENT = 0, - PB_DIFFUSE = 1, - PB_SPECULAR = 2, - PB_EMISSIVE = 3, - PB_SHININESS = 4, - PB_OPACITY = 5, - PB_TRANSLUCENCY = 6, - PB_COPY_SPECULAR_TO_DIFFUSE = 7, - PB_STAGE0_MAPPING_TYPE = 8, - PB_PSX_TRANSLUCENCY = 9, - PB_PSX_LIGHTING = 10, - - PB_DEPTH_COMPARE = 11, - PB_DEPTH_MASK = 12, - PB_COLOR_MASK = 13, // obsolete (ignored) - PB_DEST_BLEND = 14, - PB_FOG_FUNC = 15, // obsolete (ignored) - PB_PRI_GRADIENT = 16, - PB_SEC_GRADIENT = 17, - PB_SRC_BLEND = 18, - PB_DETAIL_COLOR_FUNC = 19, - PB_DETAIL_ALPHA_FUNC = 20, - - PB_STAGE0_TEXTURE_ENABLE = 21, - PB_STAGE0_TEXTURE_PUBLISH = 22, - PB_STAGE0_TEXTURE_RESIZE = 23, // obsolete (ignored) - PB_STAGE0_TEXTURE_NO_MIPMAP = 24, // obsolete (ignored) - PB_STAGE0_TEXTURE_CLAMP_U = 25, - PB_STAGE0_TEXTURE_CLAMP_V = 26, - PB_STAGE0_TEXTURE_HINT = 27, - PB_STAGE0_TEXTURE_DISPLAY = 28, - PB_STAGE0_TEXTURE_FRAME_RATE = 29, - PB_STAGE0_TEXTURE_FRAME_COUNT = 30, - PB_STAGE0_TEXTURE_ANIM_TYPE = 31, - - PB_STAGE1_TEXTURE_ENABLE = 32, - PB_STAGE1_TEXTURE_PUBLISH = 33, - PB_STAGE1_TEXTURE_RESIZE = 34, // obsolete (ignored) - PB_STAGE1_TEXTURE_NO_MIPMAP = 35, // obsolete (ignored) - PB_STAGE1_TEXTURE_CLAMP_U = 36, - PB_STAGE1_TEXTURE_CLAMP_V = 37, - PB_STAGE1_TEXTURE_HINT = 38, - PB_STAGE1_TEXTURE_DISPLAY = 39, - PB_STAGE1_TEXTURE_FRAME_RATE = 40, - PB_STAGE1_TEXTURE_FRAME_COUNT = 41, - PB_STAGE1_TEXTURE_ANIM_TYPE = 42, - - PB_STAGE0_TEXTURE_ALPHA_BITMAP = 43, - PB_STAGE1_TEXTURE_ALPHA_BITMAP = 44, - - PB_ALPHA_TEST = 45, - - PB_SHADER_PRESET = 46, // obsolete (ignored) - - // For the Playstation 2. - PB_PS2_SHADER_PARAM_A = 47, - PB_PS2_SHADER_PARAM_B = 48, - PB_PS2_SHADER_PARAM_C = 49, - PB_PS2_SHADER_PARAM_D = 50, - - // UV Channel selection - PB_STAGE0_MAP_CHANNEL = 51, - PB_STAGE1_MAP_CHANNEL = 52, - - PB_STAGE1_MAPPING_TYPE = 53, // (gth) this can't be 55, it is used as an array index // = 55, // yes, 55 - - // textures can now disable LOD - PB_STAGE0_TEXTURE_NO_LOD = 54, - PB_STAGE1_TEXTURE_NO_LOD = 55, -}; - - -/* -** Per-Pass Parameter Block Definition -*/ - -// Version 0 (old version) -static ParamBlockDescID PassParameterBlockDescVer0[] = -{ - { TYPE_POINT3, NULL, TRUE, 0 }, // Ambient - { TYPE_POINT3, NULL, TRUE, 1 }, // Diffuse - { TYPE_POINT3, NULL, TRUE, 2 }, // Specular - { TYPE_POINT3, NULL, TRUE, 3 }, // Emissive - { TYPE_FLOAT, NULL, TRUE, 4 }, // Shininess - { TYPE_FLOAT, NULL, TRUE, 5 }, // Opacity - { TYPE_FLOAT, NULL, TRUE, 6 }, // Translucency - { TYPE_INT, NULL, FALSE, 7 }, // Mapping Type - { TYPE_INT, NULL, FALSE, 8 }, // PSX Translucency Type - { TYPE_BOOL, NULL, FALSE, 9 }, // PSX Lighting Flag - - { TYPE_INT, NULL, FALSE, 10}, // Depth Compare - { TYPE_INT, NULL, FALSE, 11}, // Depth Mask - { TYPE_INT, NULL, FALSE, 12}, // Color Mask - { TYPE_INT, NULL, FALSE, 13}, // Dest Blend - { TYPE_INT, NULL, FALSE, 14}, // FogFunc - { TYPE_INT, NULL, FALSE, 15}, // PriGradient - { TYPE_INT, NULL, FALSE, 16}, // SecGradient - { TYPE_INT, NULL, FALSE, 17}, // SrcBlend - { TYPE_INT, NULL, FALSE, 18}, // DetailColorFunc - { TYPE_INT, NULL, FALSE, 19}, // DetailAlphaFunc - { TYPE_INT, NULL, FALSE, 20}, // DitherMask - { TYPE_INT, NULL, FALSE, 21}, // Shade Model - - { TYPE_BOOL, NULL, FALSE, 22}, // Stage0 Texture Enable - { TYPE_BOOL, NULL, FALSE, 23}, // Stage0 Texture Publish - { TYPE_BOOL, NULL, FALSE, 24}, // Stage0 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 25}, // Stage0 Frame Rate - { TYPE_INT, NULL, FALSE, 26}, // Stage0 Frame Count - { TYPE_INT, NULL, FALSE, 27}, // Stage0 Animation Type - - { TYPE_BOOL, NULL, FALSE, 28}, // Stage1 Texture Enable - { TYPE_BOOL, NULL, FALSE, 29}, // Stage1 Texture Publish - { TYPE_BOOL, NULL, FALSE, 30}, // Stage1 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 31}, // Stage1 Frame Rate - { TYPE_INT, NULL, FALSE, 32}, // Stage1 Frame Count - { TYPE_INT, NULL, FALSE, 33}, // Stage1 Animation Type - -}; - -// Version 1 -static ParamBlockDescID PassParameterBlockDescVer1[] = -{ - { TYPE_POINT3, NULL, TRUE, 0 }, // Ambient - { TYPE_POINT3, NULL, TRUE, 1 }, // Diffuse - { TYPE_POINT3, NULL, TRUE, 2 }, // Specular - { TYPE_POINT3, NULL, TRUE, 3 }, // Emissive - { TYPE_FLOAT, NULL, TRUE, 4 }, // Shininess - { TYPE_FLOAT, NULL, TRUE, 5 }, // Opacity - { TYPE_FLOAT, NULL, TRUE, 6 }, // Translucency - { TYPE_BOOL, NULL, FALSE, 34}, // Copy specular to diffuse (new to version 1) - { TYPE_INT, NULL, FALSE, 7 }, // Mapping Type - { TYPE_INT, NULL, FALSE, 8 }, // PSX Translucency Type - { TYPE_BOOL, NULL, FALSE, 9 }, // PSX Lighting Flag - - { TYPE_INT, NULL, FALSE, 10}, // Depth Compare - { TYPE_INT, NULL, FALSE, 11}, // Depth Mask - { TYPE_INT, NULL, FALSE, 12}, // Color Mask (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 13}, // Dest Blend - { TYPE_INT, NULL, FALSE, 14}, // FogFunc (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 15}, // PriGradient - { TYPE_INT, NULL, FALSE, 16}, // SecGradient - { TYPE_INT, NULL, FALSE, 17}, // SrcBlend - { TYPE_INT, NULL, FALSE, 18}, // DetailColorFunc - { TYPE_INT, NULL, FALSE, 19}, // DetailAlphaFunc - - { TYPE_BOOL, NULL, FALSE, 22}, // Stage0 Texture Enable - { TYPE_BOOL, NULL, FALSE, 23}, // Stage0 Texture Publish - { TYPE_BOOL, NULL, FALSE, 35}, // Stage0 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 36}, // Stage0 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 37}, // Stage0 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 38}, // Stage0 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 39}, // Stage0 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 24}, // Stage0 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 25}, // Stage0 Frame Rate - { TYPE_INT, NULL, FALSE, 26}, // Stage0 Frame Count - { TYPE_INT, NULL, FALSE, 27}, // Stage0 Animation Type - - { TYPE_BOOL, NULL, FALSE, 28}, // Stage1 Texture Enable - { TYPE_BOOL, NULL, FALSE, 29}, // Stage1 Texture Publish - { TYPE_BOOL, NULL, FALSE, 40}, // Stage1 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 41}, // Stage1 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 42}, // Stage1 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 43}, // Stage1 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 44}, // Stage1 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 30}, // Stage1 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 31}, // Stage1 Frame Rate - { TYPE_INT, NULL, FALSE, 32}, // Stage1 Frame Count - { TYPE_INT, NULL, FALSE, 33}, // Stage1 Animation Type - - { TYPE_BOOL, NULL, FALSE, 45}, // Stage0 Texture Alpha Bitmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 46}, // Stage1 Texture Alpha Bitmap (new to version 1) - - { TYPE_BOOL, NULL, FALSE, 47}, // Alpha Test (new to version 1) - { TYPE_INT, NULL, FALSE, 48}, // Shader preset (new to version 1) (now obsolete and ignored) -}; - -// Version 2 (old version) -static ParamBlockDescID PassParameterBlockDescVer2[] = -{ - { TYPE_POINT3, NULL, TRUE, 0 }, // Ambient - { TYPE_POINT3, NULL, TRUE, 1 }, // Diffuse - { TYPE_POINT3, NULL, TRUE, 2 }, // Specular - { TYPE_POINT3, NULL, TRUE, 3 }, // Emissive - { TYPE_FLOAT, NULL, TRUE, 4 }, // Shininess - { TYPE_FLOAT, NULL, TRUE, 5 }, // Opacity - { TYPE_FLOAT, NULL, TRUE, 6 }, // Translucency - { TYPE_BOOL, NULL, FALSE, 34}, // Copy specular to diffuse (new to version 1) - { TYPE_INT, NULL, FALSE, 7 }, // Mapping Type - { TYPE_INT, NULL, FALSE, 8 }, // PSX Translucency Type - { TYPE_BOOL, NULL, FALSE, 9 }, // PSX Lighting Flag - - { TYPE_INT, NULL, FALSE, 10}, // Depth Compare - { TYPE_INT, NULL, FALSE, 11}, // Depth Mask - { TYPE_INT, NULL, FALSE, 12}, // Color Mask (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 13}, // Dest Blend - { TYPE_INT, NULL, FALSE, 14}, // FogFunc (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 15}, // PriGradient - { TYPE_INT, NULL, FALSE, 16}, // SecGradient - { TYPE_INT, NULL, FALSE, 17}, // SrcBlend - { TYPE_INT, NULL, FALSE, 18}, // DetailColorFunc - { TYPE_INT, NULL, FALSE, 19}, // DetailAlphaFunc - - { TYPE_BOOL, NULL, FALSE, 22}, // Stage0 Texture Enable - { TYPE_BOOL, NULL, FALSE, 23}, // Stage0 Texture Publish - { TYPE_BOOL, NULL, FALSE, 35}, // Stage0 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 36}, // Stage0 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 37}, // Stage0 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 38}, // Stage0 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 39}, // Stage0 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 24}, // Stage0 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 25}, // Stage0 Frame Rate - { TYPE_INT, NULL, FALSE, 26}, // Stage0 Frame Count - { TYPE_INT, NULL, FALSE, 27}, // Stage0 Animation Type - - { TYPE_BOOL, NULL, FALSE, 28}, // Stage1 Texture Enable - { TYPE_BOOL, NULL, FALSE, 29}, // Stage1 Texture Publish - { TYPE_BOOL, NULL, FALSE, 40}, // Stage1 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 41}, // Stage1 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 42}, // Stage1 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 43}, // Stage1 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 44}, // Stage1 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 30}, // Stage1 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 31}, // Stage1 Frame Rate - { TYPE_INT, NULL, FALSE, 32}, // Stage1 Frame Count - { TYPE_INT, NULL, FALSE, 33}, // Stage1 Animation Type - - { TYPE_BOOL, NULL, FALSE, 45}, // Stage0 Texture Alpha Bitmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 46}, // Stage1 Texture Alpha Bitmap (new to version 1) - - { TYPE_BOOL, NULL, FALSE, 47}, // Alpha Test (new to version 1) - { TYPE_INT, NULL, FALSE, 48}, // Shader preset (new to version 1) (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 49}, // PS2 Shader Param A - { TYPE_INT, NULL, FALSE, 50}, // PS2 Shader Param B - { TYPE_INT, NULL, FALSE, 51}, // PS2 Shader Param C - { TYPE_INT, NULL, FALSE, 52}, // PS2 Shader Param D -}; - -// Version 3 (old version) -static ParamBlockDescID PassParameterBlockDescVer3[] = -{ - { TYPE_POINT3, NULL, TRUE, 0 }, // Ambient - { TYPE_POINT3, NULL, TRUE, 1 }, // Diffuse - { TYPE_POINT3, NULL, TRUE, 2 }, // Specular - { TYPE_POINT3, NULL, TRUE, 3 }, // Emissive - { TYPE_FLOAT, NULL, TRUE, 4 }, // Shininess - { TYPE_FLOAT, NULL, TRUE, 5 }, // Opacity - { TYPE_FLOAT, NULL, TRUE, 6 }, // Translucency - { TYPE_BOOL, NULL, FALSE, 34}, // Copy specular to diffuse (new to version 1) - { TYPE_INT, NULL, FALSE, 7 }, // Mapping Type - { TYPE_INT, NULL, FALSE, 8 }, // PSX Translucency Type - { TYPE_BOOL, NULL, FALSE, 9 }, // PSX Lighting Flag - - { TYPE_INT, NULL, FALSE, 10}, // Depth Compare - { TYPE_INT, NULL, FALSE, 11}, // Depth Mask - { TYPE_INT, NULL, FALSE, 12}, // Color Mask (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 13}, // Dest Blend - { TYPE_INT, NULL, FALSE, 14}, // FogFunc (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 15}, // PriGradient - { TYPE_INT, NULL, FALSE, 16}, // SecGradient - { TYPE_INT, NULL, FALSE, 17}, // SrcBlend - { TYPE_INT, NULL, FALSE, 18}, // DetailColorFunc - { TYPE_INT, NULL, FALSE, 19}, // DetailAlphaFunc - - { TYPE_BOOL, NULL, FALSE, 22}, // Stage0 Texture Enable - { TYPE_BOOL, NULL, FALSE, 23}, // Stage0 Texture Publish - { TYPE_BOOL, NULL, FALSE, 35}, // Stage0 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 36}, // Stage0 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 37}, // Stage0 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 38}, // Stage0 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 39}, // Stage0 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 24}, // Stage0 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 25}, // Stage0 Frame Rate - { TYPE_INT, NULL, FALSE, 26}, // Stage0 Frame Count - { TYPE_INT, NULL, FALSE, 27}, // Stage0 Animation Type - - { TYPE_BOOL, NULL, FALSE, 28}, // Stage1 Texture Enable - { TYPE_BOOL, NULL, FALSE, 29}, // Stage1 Texture Publish - { TYPE_BOOL, NULL, FALSE, 40}, // Stage1 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 41}, // Stage1 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 42}, // Stage1 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 43}, // Stage1 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 44}, // Stage1 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 30}, // Stage1 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 31}, // Stage1 Frame Rate - { TYPE_INT, NULL, FALSE, 32}, // Stage1 Frame Count - { TYPE_INT, NULL, FALSE, 33}, // Stage1 Animation Type - - { TYPE_BOOL, NULL, FALSE, 45}, // Stage0 Texture Alpha Bitmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 46}, // Stage1 Texture Alpha Bitmap (new to version 1) - - { TYPE_BOOL, NULL, FALSE, 47}, // Alpha Test (new to version 1) - { TYPE_INT, NULL, FALSE, 48}, // Shader preset (new to version 1) (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 49}, // PS2 Shader Param A - { TYPE_INT, NULL, FALSE, 50}, // PS2 Shader Param B - { TYPE_INT, NULL, FALSE, 51}, // PS2 Shader Param C - { TYPE_INT, NULL, FALSE, 52}, // PS2 Shader Param D - - { TYPE_INT, NULL, FALSE, 53}, // Stage0 UV Channel - { TYPE_INT, NULL, FALSE, 54}, // Stage1 UV Channel -}; - - -// Version 4 (old version) -static ParamBlockDescID PassParameterBlockDescVer4[] = -{ - { TYPE_POINT3, NULL, TRUE, 0 }, // Ambient - { TYPE_POINT3, NULL, TRUE, 1 }, // Diffuse - { TYPE_POINT3, NULL, TRUE, 2 }, // Specular - { TYPE_POINT3, NULL, TRUE, 3 }, // Emissive - { TYPE_FLOAT, NULL, TRUE, 4 }, // Shininess - { TYPE_FLOAT, NULL, TRUE, 5 }, // Opacity - { TYPE_FLOAT, NULL, TRUE, 6 }, // Translucency - { TYPE_BOOL, NULL, FALSE, 34}, // Copy specular to diffuse (new to version 1) - { TYPE_INT, NULL, FALSE, 7 }, // Stage0 Mapping Type - { TYPE_INT, NULL, FALSE, 8 }, // PSX Translucency Type - { TYPE_BOOL, NULL, FALSE, 9 }, // PSX Lighting Flag - - { TYPE_INT, NULL, FALSE, 10}, // Depth Compare - { TYPE_INT, NULL, FALSE, 11}, // Depth Mask - { TYPE_INT, NULL, FALSE, 12}, // Color Mask (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 13}, // Dest Blend - { TYPE_INT, NULL, FALSE, 14}, // FogFunc (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 15}, // PriGradient - { TYPE_INT, NULL, FALSE, 16}, // SecGradient - { TYPE_INT, NULL, FALSE, 17}, // SrcBlend - { TYPE_INT, NULL, FALSE, 18}, // DetailColorFunc - { TYPE_INT, NULL, FALSE, 19}, // DetailAlphaFunc - - { TYPE_BOOL, NULL, FALSE, 22}, // Stage0 Texture Enable - { TYPE_BOOL, NULL, FALSE, 23}, // Stage0 Texture Publish - { TYPE_BOOL, NULL, FALSE, 35}, // Stage0 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 36}, // Stage0 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 37}, // Stage0 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 38}, // Stage0 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 39}, // Stage0 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 24}, // Stage0 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 25}, // Stage0 Frame Rate - { TYPE_INT, NULL, FALSE, 26}, // Stage0 Frame Count - { TYPE_INT, NULL, FALSE, 27}, // Stage0 Animation Type - - { TYPE_BOOL, NULL, FALSE, 28}, // Stage1 Texture Enable - { TYPE_BOOL, NULL, FALSE, 29}, // Stage1 Texture Publish - { TYPE_BOOL, NULL, FALSE, 40}, // Stage1 Texture Resize (new to version 1) - { TYPE_BOOL, NULL, FALSE, 41}, // Stage1 Texture No Mipmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 42}, // Stage1 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 43}, // Stage1 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 44}, // Stage1 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 30}, // Stage1 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 31}, // Stage1 Frame Rate - { TYPE_INT, NULL, FALSE, 32}, // Stage1 Frame Count - { TYPE_INT, NULL, FALSE, 33}, // Stage1 Animation Type - - { TYPE_BOOL, NULL, FALSE, 45}, // Stage0 Texture Alpha Bitmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 46}, // Stage1 Texture Alpha Bitmap (new to version 1) - - { TYPE_BOOL, NULL, FALSE, 47}, // Alpha Test (new to version 1) - { TYPE_INT, NULL, FALSE, 48}, // Shader preset (new to version 1) (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 49}, // PS2 Shader Param A - { TYPE_INT, NULL, FALSE, 50}, // PS2 Shader Param B - { TYPE_INT, NULL, FALSE, 51}, // PS2 Shader Param C - { TYPE_INT, NULL, FALSE, 52}, // PS2 Shader Param D - - { TYPE_INT, NULL, FALSE, 53}, // Stage0 UV Channel - { TYPE_INT, NULL, FALSE, 54}, // Stage1 UV Channel - - { TYPE_INT, NULL, FALSE, 9998}, // foo - { TYPE_INT, NULL, FALSE, 9999}, // bar - - { TYPE_INT, NULL, FALSE, 55}, // Stage1 Mapping Type (new to version 4) -}; - - -// Version 5 (current version) -static ParamBlockDescID PassParameterBlockDescVer5[] = -{ - { TYPE_POINT3, NULL, TRUE, 0 }, // Ambient - { TYPE_POINT3, NULL, TRUE, 1 }, // Diffuse - { TYPE_POINT3, NULL, TRUE, 2 }, // Specular - { TYPE_POINT3, NULL, TRUE, 3 }, // Emissive - { TYPE_FLOAT, NULL, TRUE, 4 }, // Shininess - { TYPE_FLOAT, NULL, TRUE, 5 }, // Opacity - { TYPE_FLOAT, NULL, TRUE, 6 }, // Translucency - { TYPE_BOOL, NULL, FALSE, 34}, // Copy specular to diffuse (new to version 1) - { TYPE_INT, NULL, FALSE, 7 }, // Stage0 Mapping Type - { TYPE_INT, NULL, FALSE, 8 }, // PSX Translucency Type - { TYPE_BOOL, NULL, FALSE, 9 }, // PSX Lighting Flag - - { TYPE_INT, NULL, FALSE, 10}, // Depth Compare - { TYPE_INT, NULL, FALSE, 11}, // Depth Mask - { TYPE_INT, NULL, FALSE, 12}, // Color Mask (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 13}, // Dest Blend - { TYPE_INT, NULL, FALSE, 14}, // FogFunc (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 15}, // PriGradient - { TYPE_INT, NULL, FALSE, 16}, // SecGradient - { TYPE_INT, NULL, FALSE, 17}, // SrcBlend - { TYPE_INT, NULL, FALSE, 18}, // DetailColorFunc - { TYPE_INT, NULL, FALSE, 19}, // DetailAlphaFunc - - { TYPE_BOOL, NULL, FALSE, 22}, // Stage0 Texture Enable - { TYPE_BOOL, NULL, FALSE, 23}, // Stage0 Texture Publish - { TYPE_BOOL, NULL, FALSE, 35}, // Stage0 Texture Resize (new to version 1) OBSOLETE! - { TYPE_BOOL, NULL, FALSE, 36}, // Stage0 Texture No Mipmap (new to version 1) OBSOLETE! - { TYPE_BOOL, NULL, FALSE, 37}, // Stage0 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 38}, // Stage0 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 39}, // Stage0 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 24}, // Stage0 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 25}, // Stage0 Frame Rate - { TYPE_INT, NULL, FALSE, 26}, // Stage0 Frame Count - { TYPE_INT, NULL, FALSE, 27}, // Stage0 Animation Type - - { TYPE_BOOL, NULL, FALSE, 28}, // Stage1 Texture Enable - { TYPE_BOOL, NULL, FALSE, 29}, // Stage1 Texture Publish - { TYPE_BOOL, NULL, FALSE, 40}, // Stage1 Texture Resize (new to version 1) OBSOLETE! - { TYPE_BOOL, NULL, FALSE, 41}, // Stage1 Texture No Mipmap (new to version 1) OBSOLETE! - { TYPE_BOOL, NULL, FALSE, 42}, // Stage1 Texture Clamp U (new to version 1) - { TYPE_BOOL, NULL, FALSE, 43}, // Stage1 Texture Clamp V (new to version 1) - { TYPE_INT, NULL, FALSE, 44}, // Stage1 Texture Hint (new to version 1) - { TYPE_BOOL, NULL, FALSE, 30}, // Stage1 Texture Display (in viewport...) - { TYPE_FLOAT, NULL, FALSE, 31}, // Stage1 Frame Rate - { TYPE_INT, NULL, FALSE, 32}, // Stage1 Frame Count - { TYPE_INT, NULL, FALSE, 33}, // Stage1 Animation Type - - { TYPE_BOOL, NULL, FALSE, 45}, // Stage0 Texture Alpha Bitmap (new to version 1) - { TYPE_BOOL, NULL, FALSE, 46}, // Stage1 Texture Alpha Bitmap (new to version 1) - - { TYPE_BOOL, NULL, FALSE, 47}, // Alpha Test (new to version 1) - { TYPE_INT, NULL, FALSE, 48}, // Shader preset (new to version 1) (now obsolete and ignored) - { TYPE_INT, NULL, FALSE, 49}, // PS2 Shader Param A - { TYPE_INT, NULL, FALSE, 50}, // PS2 Shader Param B - { TYPE_INT, NULL, FALSE, 51}, // PS2 Shader Param C - { TYPE_INT, NULL, FALSE, 52}, // PS2 Shader Param D - - { TYPE_INT, NULL, FALSE, 53}, // Stage0 UV Channel - { TYPE_INT, NULL, FALSE, 54}, // Stage1 UV Channel - - { TYPE_INT, NULL, FALSE, 55 }, // Stage1 Mapping Type (new to version 4) - - { TYPE_BOOL, NULL, FALSE, 56 }, // Stage0 no texture reduction (new to version 5) - { TYPE_BOOL, NULL, FALSE, 57 }, // Stage0 no texture reduction (new to version 5) -}; - -// Array of old pass parameter block versions (for backwards compatibility) -const int NUM_OLDVERSIONS = 5; -static ParamVersionDesc PassParameterBlockVersions[] = { - ParamVersionDesc(PassParameterBlockDescVer0, 34, 0), - ParamVersionDesc(PassParameterBlockDescVer1, 47, 1), - ParamVersionDesc(PassParameterBlockDescVer2, 51, 2), - ParamVersionDesc(PassParameterBlockDescVer3, 53, 3), - ParamVersionDesc(PassParameterBlockDescVer4, 56, 4) -}; - - -// Current pass parameter block version -const int CURRENT_VERSION = 5; -static ParamVersionDesc CurrentPassParameterBlockVersion( - PassParameterBlockDescVer5, - sizeof(PassParameterBlockDescVer5) / sizeof(ParamBlockDescID), - CURRENT_VERSION); - - -const int DISPLACEMENT_INDEX = (W3dMaterialClass::MAX_PASSES * W3dMaterialClass::MAX_STAGES); - -Color scale(const Color& a, const Color& b) -{ - return Color(a.r * b.r, a.g * b.g, a.b * b.b); -} - -/*********************************************************************************************** - * GameMtl::GameMtl -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtl::GameMtl(BOOL loading) -{ - MaterialDialog = NULL; - SurfaceType = SURFACE_TYPE_DEFAULT; - SortLevel = SORT_LEVEL_NONE; - - Ivalid.SetEmpty(); - RollScroll = 0; - Flags = 0; - Flags |= GAMEMTL_PASSCOUNT_ROLLUP_OPEN; - Set_Flag(GAMEMTL_CONVERTED_TO_NOLOD,true); - - DisplacementMap = NULL; - DisplacementAmt = 0.0F; - - Maps = NULL; - MainParameterBlock = NULL; - for (int pass=0; passReplaceReference(REF_MAIN,remap.CloneRef(MainParameterBlock)); - - // Clone the displacment map's settings - mnew->ReplaceReference (REF_TEXTURE + DISPLACEMENT_INDEX, DisplacementMap); - mnew->DisplacementAmt = DisplacementAmt; - - // Maintain the shader type. - mnew->Set_Shader_Type(ShaderType); - - // replace each pass's parameter block and the textures - for (int pass=0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - - IParamBlock * pblock = NULL; - if (PassParameterBlock[pass]) { - pblock = (IParamBlock *)remap.CloneRef(PassParameterBlock[pass]); - } - mnew->ReplaceReference(pass_ref_index(pass), pblock); - mnew->PassParameterBlock[pass] = pblock; - - for (int stage=0; stage < W3dMaterialClass::MAX_STAGES; stage++) { - if (Texture[pass][stage]) { - mnew->ReplaceReference(texture_ref_index(pass,stage),Texture[pass][stage]->Clone()); - } else { - mnew->ReplaceReference(texture_ref_index(pass,stage),NULL); - } - - // Copy mapper arg strings and lengths - if (MapperArgLen[pass][stage] > 0) { - char *temp = new char[MapperArgLen[pass][stage] + 1]; - assert(strlen(MapperArg[pass][stage]) <= MapperArgLen[pass][stage]); - strcpy(temp, MapperArg[pass][stage]); - mnew->MapperArg[pass][stage] = temp; - mnew->MapperArgLen[pass][stage] = MapperArgLen[pass][stage]; - } - } - - } - - mnew->Ivalid = Ivalid; - return mnew; -} - - -/*********************************************************************************************** - * GameMtl::NotifyRefChanged -- NotifyRefChanged handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -RefResult GameMtl::NotifyRefChanged -( - Interval changeInt, - RefTargetHandle hTarget, - PartID & partID, - RefMessage message -) -{ - switch (message) { - case REFMSG_CHANGE: - { - Ivalid.SetEmpty(); // if any refs changed, clear the validity - if (MaterialDialog && (MaterialDialog->TheMtl == this)) { - MaterialDialog->Invalidate(); // if the dialog is up, refresh it - } - break; - } - case REFMSG_GET_PARAM_DIM: - { - GetParamDim *gpd = (GetParamDim*)partID; - gpd->dim = defaultDim; - return REF_STOP; - } - - case REFMSG_GET_PARAM_NAME: - { - GetParamName *gpn = (GetParamName*)partID; - bool pass_parameter = false; - for(int pass = 0; pass < Get_Pass_Count(); pass++) { - if(hTarget == (RefTargetHandle)PassParameterBlock[pass]) pass_parameter = true; - } - - if (pass_parameter) { - switch (gpn->index) - { - case PB_AMBIENT: gpn->name = _T("Ambient"); break; - case PB_DIFFUSE: gpn->name = _T("Diffuse"); break; - case PB_SPECULAR: gpn->name = _T("Specular"); break; - case PB_EMISSIVE: gpn->name = _T("Emissive"); break; - case PB_SHININESS: gpn->name = _T("Shininess"); break; - case PB_OPACITY: gpn->name = _T("Opacity"); break; - case PB_TRANSLUCENCY: gpn->name = _T("Translucency"); break; - default: gpn->name = _T(""); break; - } - } - return REF_STOP; - } - } - return(REF_SUCCEED); -} - - -/*********************************************************************************************** - * GameMtl::SetReference -- set the i'th reference * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtl::SetReference(int i, RefTargetHandle rtarg) -{ - assert(i < REF_COUNT); - - if (i == REF_MAPS) { - Maps = (GameMapsClass *)rtarg; - return; - } - - if (i == REF_MAIN) { - MainParameterBlock = (IParamBlock*)rtarg; - return; - } - - if ((i >= REF_PASS_PARAMETERS) && (i < REF_PASS_PARAMETERS + W3dMaterialClass::MAX_PASSES)) { - PassParameterBlock[i - REF_PASS_PARAMETERS] = (IParamBlock*)rtarg; - return; - } - - if ((i >= REF_TEXTURE) && (i < REF_TEXTURE + 9)) { - if (i == REF_TEXTURE + DISPLACEMENT_INDEX) { - DisplacementMap = (Texmap *)rtarg; - } else { - int offset = i - REF_TEXTURE; - int pass = offset / 2; - int stage = offset % 2; - Texture[pass][stage] = (Texmap *)rtarg; - } - return; - } -} - - -/*********************************************************************************************** - * GameMtl::GetReference -- returnst the i'th reference * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -RefTargetHandle GameMtl::GetReference(int i) -{ - if (i == REF_MAPS) { - return Maps; - } - if (i == REF_MAIN) { - return MainParameterBlock; - } - if ((i >= REF_PASS_PARAMETERS) && (i < REF_PASS_PARAMETERS + W3dMaterialClass::MAX_PASSES)) { - return PassParameterBlock[i - REF_PASS_PARAMETERS]; - } - if ((i >= REF_TEXTURE) && (i < REF_TEXTURE + 9)) { - if (i == REF_TEXTURE + DISPLACEMENT_INDEX) { - return DisplacementMap; - } else { - int offset = i - REF_TEXTURE; - int pass = offset / 2; - int stage = offset % 2; - return Texture[pass][stage]; - } - } - - return NULL; -} - - -/*********************************************************************************************** - * GameMtl::NumSubTexmaps -- returns the number of texture maps in this material * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -int GameMtl::NumSubTexmaps(void) -{ - return (W3dMaterialClass::MAX_PASSES * W3dMaterialClass::MAX_STAGES) + 1; -} - - -/*********************************************************************************************** - * GameMtl::Get_Displacement_Map_Index -- returns the Sub-texmap index for the displacement map. - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/01/99 PDS : Created. * - *=============================================================================================*/ -int GameMtl::Get_Displacement_Map_Index(void) const -{ - return DISPLACEMENT_INDEX; -} - - -/*********************************************************************************************** - * GameMtl::SetSubTexmap -- set the i'th texture map * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtl::SetSubTexmap(int i, Texmap * m) -{ - ReplaceReference(REF_TEXTURE + i, m); - - int pass,stage; - texmap_index_to_pass_stage(i,&pass,&stage); - if (Texture[pass][stage] != NULL) { - UVGen * uvgen = Texture[pass][stage]->GetTheUVGen(); - if (uvgen != NULL) { - uvgen->SetMapChannel(Get_Map_Channel(pass,stage)); - } - } - - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); -} - - -/*********************************************************************************************** - * GameMtl::GetSubTexmap -- returns the i'th texture map * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -Texmap * GameMtl::GetSubTexmap(int i) -{ - if (i == DISPLACEMENT_INDEX) { - return DisplacementMap; - } - - int pass; - int stage; - texmap_index_to_pass_stage(i,&pass,&stage); - return Texture[pass][stage]; -} - - -/*********************************************************************************************** - * GameMtl::CreateParamDlg -- creates the material editor dialog box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -ParamDlg * GameMtl::CreateParamDlg(HWND hwnd_mtl_edit, IMtlParams *imp) -{ - GameMtlDlg *dlg = new GameMtlDlg(hwnd_mtl_edit, imp, this); - SetParamDlg(dlg); - return dlg; -} - - -/*********************************************************************************************** - * GameMtl::Notify_Changed -- someone has changed this material * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtl::Notify_Changed(void) -{ - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); - if (MaterialDialog != NULL) { - MaterialDialog->Update_Display(); - } -} - - -/*********************************************************************************************** - * GameMtl::Reset -- reset this material to default settings * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtl::Reset() -{ - DebugPrint("GameMtl::Reset()\n"); - - ReplaceReference(REF_MAIN,CreateParameterBlock(MainParameterBlockDesc,1,CURRENT_VERSION)); - - for (int pass = 0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - - // Install a parameter block for each pass - IParamBlock * pblock = CreateParameterBlock( PassParameterBlockDescVer5, - sizeof(PassParameterBlockDescVer5)/sizeof(ParamBlockDescID), - CURRENT_VERSION); - - ReplaceReference(pass_ref_index(pass), pblock); - - for (int stage = 0;stage < W3dMaterialClass::MAX_STAGES; stage++) { - ReplaceReference(texture_ref_index(pass,stage), NULL); - - Set_Texture_Enable(pass,stage,false); - Set_Texture_Publish(pass,stage,false); - Set_Texture_Resize(pass,stage,false); - Set_Texture_No_Mipmap(pass,stage,false); - Set_Texture_Clamp_U(pass,stage,false); - Set_Texture_Clamp_V(pass,stage,false); - Set_Texture_No_LOD(pass,stage,false); - Set_Texture_Alpha_Bitmap(pass,stage,false); - Set_Texture_Hint(pass,stage,W3DTEXTURE_HINT_BASE); - Set_Texture_Display(pass,stage,false); - Set_Texture_Frame_Rate(pass,stage,15.0f); - Set_Texture_Frame_Count(pass,stage,1); - Set_Texture_Anim_Type(pass,stage,W3DTEXTURE_ANIM_LOOP); - Set_Map_Channel(pass,stage,1); - - if (MapperArg[pass][stage]) { - delete [] (MapperArg[pass][stage]); - MapperArg[pass][stage] = NULL; - MapperArgLen[pass][stage] = 0; - } - } - - Set_Sort_Level(SORT_LEVEL_NONE); - - Set_Ambient(pass,0,(pass == 0 ? Color(1.0,1.0,1.0) : Color(0,0,0))); - Set_Diffuse(pass,0,(pass == 0 ? Color(1.0,1.0,1.0) : Color(0,0,0))); - Set_Specular(pass,0,Color(0,0,0)); - Set_Emissive(pass,0,Color(0,0,0)); - Set_Shininess(pass,0,0.0f); - Set_Opacity(pass,0,1.0f); - Set_Translucency(pass,0,0.0f); - Set_Copy_Specular_To_Diffuse(pass,false); - Set_Mapping_Type(pass,0,W3DMAPPING_UV); - Set_Mapping_Type(pass,1,W3DMAPPING_UV); - Set_PSX_Translucency(pass,GAMEMTL_PSX_TRANS_NONE); - Set_PSX_Lighting(pass,true); - - Set_Depth_Compare(pass,W3DSHADER_DEPTHCOMPARE_DEFAULT); - Set_Depth_Mask(pass,W3DSHADER_DEPTHMASK_DEFAULT); - Set_Alpha_Test(pass,W3DSHADER_ALPHATEST_DEFAULT); - Set_Dest_Blend(pass,W3DSHADER_DESTBLENDFUNC_DEFAULT); - Set_Pri_Gradient(pass,W3DSHADER_PRIGRADIENT_DEFAULT); - Set_Sec_Gradient(pass,W3DSHADER_SECGRADIENT_DEFAULT); - Set_Src_Blend(pass,W3DSHADER_SRCBLENDFUNC_DEFAULT); - Set_Detail_Color_Func(pass,W3DSHADER_DETAILCOLORFUNC_DEFAULT); - Set_Detail_Alpha_Func(pass,W3DSHADER_DETAILCOLORFUNC_DEFAULT); - - // Playstation 2 default for opaque. - Set_PS2_Shader_Param_A(pass, PSS_SRC); - Set_PS2_Shader_Param_B(pass, PSS_ZERO); - Set_PS2_Shader_Param_C(pass, PSS_ONE); - Set_PS2_Shader_Param_D(pass, PSS_ZERO); - } - - Ivalid.SetEmpty(); - Set_Pass_Count(1); // set default value for the main param block -} - - -/*********************************************************************************************** - * GameMtl::Update -- time has changed * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtl::Update(TimeValue t, Interval &ivalid) -{ - // This function is called by the system prior to rendering - // Its purpose is to let you pre-calculate anything you can to - // speed up the subsequent 'Shade' calls. - Ivalid = FOREVER; - ivalid &= Ivalid; -} - - -/*********************************************************************************************** - * GameMtl::Validity -- return the validity of the material at time t * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -Interval GameMtl::Validity(TimeValue t) -{ - return FOREVER; -} - - -/*********************************************************************************************** - * GameMtl::Requirements -- what requirements does this material have? * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -ULONG GameMtl::Requirements(int subMtlNum) -{ - ULONG req = 0; - - for (int pass = 0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - for (int stage = 0; stage < W3dMaterialClass::MAX_STAGES; stage++) { - if (Texture[pass][stage]) { - req |= Texture[pass][stage]->Requirements(subMtlNum); - } - } - } - - req |= MTLREQ_BGCOL; - req |= MTLREQ_NOATMOS; - - #ifdef WANT_DISPLACEMENT_MAPS - req |= MTLREQ_DISPLACEMAP; - #endif //WANT_DISPLACEMENT_MAPS - - return req; -} - - -/*********************************************************************************************** - * GameMtl::Load -- loading from a MAX file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -IOResult GameMtl::Load(ILoad *iload) -{ - ULONG nb; - int id; - int passindex = 0; - int len = 0; - unsigned char tmp8; - unsigned short tmp16; - char * tmpstring = NULL; - float tmpfloat; - IOResult res; - - GameMtlPostLoad * lc = new GameMtlPostLoad(this); - iload->RegisterPostLoadCallback(lc); - - // Register automatic translation callbacks for the pass parameter blocks - for (int i = 0; i < W3dMaterialClass::MAX_PASSES; i++) { - iload->RegisterPostLoadCallback( - new ParamBlockPLCB(PassParameterBlockVersions, NUM_OLDVERSIONS, - &CurrentPassParameterBlockVersion, this, REF_PASS_PARAMETERS + i) - ); - } - - while (IO_OK==(res=iload->OpenChunk())) { - - switch (id = iload->CurChunkID()) { - - case MTL_HDR_CHUNK: - res = MtlBase::Load(iload); - Ivalid.SetEmpty(); - break; - - case GAMEMTL_FLAGS_CHUNK: - res = iload->Read(&Flags,sizeof(Flags), &nb); - break; - - case GAMEMTL_SURFACE_TYPE_CHUNK: - res = iload->Read(&SurfaceType,sizeof(SurfaceType),&nb); - break; - - case GAMEMTL_SORT_LEVEL_CHUNK: - res = iload->Read(&SortLevel,sizeof(SortLevel),&nb); - break; - - case GAMEMTL_PASS0_CUR_PAGE: - case GAMEMTL_PASS1_CUR_PAGE: - case GAMEMTL_PASS2_CUR_PAGE: - case GAMEMTL_PASS3_CUR_PAGE: - res = iload->Read(&tmp8,sizeof(tmp8),&nb); - CurPage[id - GAMEMTL_PASS0_CUR_PAGE] = tmp8; - break; - - case GAMEMTL_PASS0_STAGE0_MAPPER_ARGS: - case GAMEMTL_PASS1_STAGE0_MAPPER_ARGS: - case GAMEMTL_PASS2_STAGE0_MAPPER_ARGS: - case GAMEMTL_PASS3_STAGE0_MAPPER_ARGS: - len = iload->CurChunkLength(); - passindex = id - GAMEMTL_PASS0_STAGE0_MAPPER_ARGS; - tmpstring = Get_Mapping_Arg_Buffer(passindex, 0, len); - res = iload->Read(tmpstring, len, &nb); - break; - - case GAMEMTL_PASS0_STAGE1_MAPPER_ARGS: - case GAMEMTL_PASS1_STAGE1_MAPPER_ARGS: - case GAMEMTL_PASS2_STAGE1_MAPPER_ARGS: - case GAMEMTL_PASS3_STAGE1_MAPPER_ARGS: - len = iload->CurChunkLength(); - passindex = id - GAMEMTL_PASS0_STAGE1_MAPPER_ARGS; - tmpstring = Get_Mapping_Arg_Buffer(passindex, 1, len); - res = iload->Read(tmpstring, len, &nb); - break; - - /* - ** All chunks below here are for the obsolete material plugin... - */ - case GAMEMTL_GAMEFLAGS_CHUNK: - break; - - case GAMEMTL_ATTRIBUTES_CHUNK: - res = iload->Read(&lc->Attributes,sizeof(lc->Attributes),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_COLORS_CHUNK: - res = iload->Read(&lc->Diffuse,sizeof(lc->Diffuse),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_DCT_FRAMES_CHUNK: - res = iload->Read(&tmp16,sizeof(unsigned short),&nb); - lc->DCTFrames = tmp16; - lc->IsOld = true; - break; - - case GAMEMTL_DCT_FRAME_RATE_CHUNK: - res = iload->Read(&tmpfloat,sizeof(float),&nb); - lc->DCTFrameRate = tmpfloat; - lc->IsOld = true; - break; - - case GAMEMTL_DIT_FRAMES_CHUNK: - res = iload->Read(&tmp16,sizeof(unsigned short),&nb); - lc->DITFrames = tmp16; - lc->IsOld = true; - break; - - case GAMEMTL_DIT_FRAME_RATE_CHUNK: - res = iload->Read(&tmpfloat,sizeof(float),&nb); - lc->DITFrameRate = tmpfloat; - lc->IsOld = true; - break; - - case GAMEMTL_SCT_FRAMES_CHUNK: - res = iload->Read(&tmp16,sizeof(unsigned short),&nb); - lc->SCTFrames = tmp16; - lc->IsOld = true; - break; - - case GAMEMTL_SCT_FRAME_RATE_CHUNK: - res = iload->Read(&tmpfloat,sizeof(float),&nb); - lc->SCTFrameRate = tmpfloat; - lc->IsOld = true; - break; - - case GAMEMTL_SIT_FRAMES_CHUNK: - res = iload->Read(&tmp16,sizeof(unsigned short),&nb); - lc->SITFrames = tmp16; - lc->IsOld = true; - break; - - case GAMEMTL_SIT_FRAME_RATE_CHUNK: - res = iload->Read(&tmpfloat,sizeof(float),&nb); - lc->SITFrameRate = tmpfloat; - lc->IsOld = true; - break; - - case GAMEMTL_DCT_MAPPING_CHUNK: - res = iload->Read(&tmp8,sizeof(unsigned char),&nb); - lc->DCTMappingType = tmp8; - lc->IsOld = true; - break; - - case GAMEMTL_DIT_MAPPING_CHUNK: - res = iload->Read(&tmp8,sizeof(unsigned char),&nb); - lc->DITMappingType = tmp8; - lc->IsOld = true; - break; - - case GAMEMTL_SCT_MAPPING_CHUNK: - res = iload->Read(&tmp8,sizeof(unsigned char),&nb); - lc->SCTMappingType = tmp8; - lc->IsOld = true; - break; - - case GAMEMTL_SIT_MAPPING_CHUNK: - res = iload->Read(&tmp8,sizeof(unsigned char),&nb); - lc->SITMappingType = tmp8; - lc->IsOld = true; - break; - - case GAMEMTL_DIFFUSE_COLOR_CHUNK: - res = iload->Read(&lc->Diffuse,sizeof(lc->Diffuse),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_SPECULAR_COLOR_CHUNK: - res = iload->Read(&lc->Specular,sizeof(lc->Specular),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_AMBIENT_COEFF_CHUNK: - res = iload->Read(&lc->AmbientCoeff,sizeof(lc->AmbientCoeff),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_DIFFUSE_COEFF_CHUNK: - res = iload->Read(&lc->DiffuseCoeff,sizeof(lc->DiffuseCoeff),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_SPECULAR_COEFF_CHUNK: - res = iload->Read(&lc->SpecularCoeff,sizeof(lc->SpecularCoeff),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_EMISSIVE_COEFF_CHUNK: - res = iload->Read(&lc->EmissiveCoeff,sizeof(lc->EmissiveCoeff),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_OPACITY_CHUNK: - res = iload->Read(&lc->Opacity,sizeof(lc->Opacity),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_TRANSLUCENCY_CHUNK: - res = iload->Read(&lc->Translucency,sizeof(lc->Translucency),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_SHININESS_CHUNK: - res = iload->Read(&lc->Shininess,sizeof(lc->Shininess),&nb); - lc->IsOld = true; - break; - - case GAMEMTL_FOG_CHUNK: - res = iload->Read(&lc->FogCoeff,sizeof(lc->FogCoeff),&nb); - lc->IsOld = true; - break; - - default: - break; - } - - iload->CloseChunk(); - if (res!=IO_OK) { - return res; - } - } - - return IO_OK; -} - - -/*********************************************************************************************** - * GameMtl::Save -- Saving into a MAX file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -IOResult GameMtl::Save(ISave *isave) -{ - IOResult res; - ULONG nb; - - /* - ** Save the base class stuff - */ - isave->BeginChunk(MTL_HDR_CHUNK); - res = MtlBase::Save(isave); - if (res!=IO_OK) - return res; - isave->EndChunk(); - - /* - ** Save the flags - */ - isave->BeginChunk(GAMEMTL_FLAGS_CHUNK); - isave->Write(&Flags,sizeof(Flags),&nb); - isave->EndChunk(); - - /* - ** Save the "cur-pages" - */ - uint8 tmp8; - int pass; - for (pass=0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - isave->BeginChunk(GAMEMTL_PASS0_CUR_PAGE + pass); - tmp8 = CurPage[pass]; - isave->Write(&tmp8,sizeof(tmp8),&nb); - isave->EndChunk(); - } - - /* - ** Save any Mapper Args - */ - for (pass=0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - char *buffer = Get_Mapping_Arg_Buffer(pass, 0); - if (buffer) { - isave->BeginChunk(GAMEMTL_PASS0_STAGE0_MAPPER_ARGS + pass); - isave->Write(buffer, strlen(buffer) + 1, &nb); - isave->EndChunk(); - } - buffer = Get_Mapping_Arg_Buffer(pass, 1); - if (buffer) { - isave->BeginChunk(GAMEMTL_PASS0_STAGE1_MAPPER_ARGS + pass); - isave->Write(buffer, strlen(buffer) + 1, &nb); - isave->EndChunk(); - } - } - - /* - ** Save the surface type - */ - isave->BeginChunk(GAMEMTL_SURFACE_TYPE_CHUNK); - isave->Write(&SurfaceType,sizeof(SurfaceType),&nb); - isave->EndChunk(); - - /* - ** Save the sort level - */ - isave->BeginChunk(GAMEMTL_SORT_LEVEL_CHUNK); - isave->Write(&SortLevel,sizeof(SortLevel),&nb); - isave->EndChunk(); - - return IO_OK; -} - - -/*********************************************************************************************** - * GameMtl::Shade -- evaluate the material for the renderer. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This function could use a little work. It doesn't always produce correct results. * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtl::Shade(ShadeContext& sc) -{ - if (ShaderType == STE_PS2_SHADER) { - ps2_shade(sc); - return; - } - - if (gbufID) sc.SetGBufferID(gbufID); - - /* - ** Shadowing, return black - */ - if (sc.mode==SCMODE_SHADOW) { - sc.out.t = Color(0,0,0); - return; - } - - /* - ** Render each pass, initialize dest with the current background - */ - Color back_c; - Color back_t; - - Color dest; - Color src; - float alpha; - - sc.GetBGColor(back_c,back_t, FALSE); - dest = back_c; - - for (int pass=0; pass < Get_Pass_Count(); pass++) { - - /* - ** Computing the Primary and Secondary Gradients - */ - Color ambient = sc.ambientLight; - Color diffuse(0,0,0); - Color specular(0,0,0); - - for(int light_index = 0; light_index < sc.nLights; light_index++) { - - Color light_color; - Point3 light_dir; - float dot_nl; - float diffuse_coef; - - LightDesc * light = sc.Light(light_index); - if(light->Illuminate(sc, sc.Normal(), light_color, light_dir, dot_nl, diffuse_coef)) { - - //ambient += light_color; - if (dot_nl > 0.0f) diffuse += dot_nl * light_color; - - float c = DotProd(light_dir, sc.ReflectVector()); - if(c > 0.f) { - specular += (float)pow(c, Get_Shininess(pass, sc.CurTime())) * light_color; - } - } - } - - ambient = ambient * Get_Ambient(pass,sc.CurTime()); - diffuse = diffuse * Get_Diffuse(pass,sc.CurTime()); - specular = specular * Get_Specular(pass,sc.CurTime()); - - Color pri_gradient = ambient + diffuse + Get_Emissive(pass,sc.CurTime()); - if (pri_gradient.r > 1.0f) pri_gradient.r = 1.0f; - if (pri_gradient.g > 1.0f) pri_gradient.g = 1.0f; - if (pri_gradient.b > 1.0f) pri_gradient.b = 1.0f; - - Color sec_gradient = specular * Get_Specular(pass,sc.CurTime()); - - /* - ** Sampling the Texture(s) - */ - AColor texel(1,1,1,1); - if (Get_Texture_Enable(pass,0) && Texture[pass][0]) { -// if (Get_Mapping_Type(pass) == GAMEMTL_MAPPING_UV) { - texel = Texture[pass][0]->EvalColor(sc); -// } - } - - if (Get_Texture_Enable(pass,1) && Texture[pass][1]) { - AColor detail_texel = Texture[pass][1]->EvalColor(sc); - switch (Get_Detail_Color_Func(pass)) - { - case W3DSHADER_DETAILCOLORFUNC_DISABLE: - break; - case W3DSHADER_DETAILCOLORFUNC_DETAIL: - texel = detail_texel; - break; - case W3DSHADER_DETAILCOLORFUNC_SCALE: - texel.r = detail_texel.r * texel.r; - texel.g = detail_texel.g * texel.g; - texel.b = detail_texel.b * texel.b; - break; - case W3DSHADER_DETAILCOLORFUNC_INVSCALE: - texel.r = texel.r + (1.0f - texel.r) * detail_texel.r; - texel.g = texel.g + (1.0f - texel.g) * detail_texel.g; - texel.b = texel.b + (1.0f - texel.b) * detail_texel.b; - break; - case W3DSHADER_DETAILCOLORFUNC_ADD: - texel.r = detail_texel.r + texel.r; - texel.g = detail_texel.g + texel.g; - texel.b = detail_texel.b + texel.b; - break; - case W3DSHADER_DETAILCOLORFUNC_SUB: - texel.r = texel.r - detail_texel.r; - texel.g = texel.g - detail_texel.g; - texel.b = texel.b - detail_texel.b; - break; - case W3DSHADER_DETAILCOLORFUNC_SUBR: - texel.r = detail_texel.r - texel.r; - texel.g = detail_texel.g - texel.g; - texel.b = detail_texel.b - texel.b; - break; - case W3DSHADER_DETAILCOLORFUNC_BLEND: - texel.r = (texel.a * texel.r) + ((1.0f - texel.a)*detail_texel.r); - texel.g = (texel.a * texel.g) + ((1.0f - texel.a)*detail_texel.g); - texel.b = (texel.a * texel.b) + ((1.0f - texel.a)*detail_texel.b); - break; - case W3DSHADER_DETAILCOLORFUNC_DETAILBLEND: - texel.r = (detail_texel.a * texel.r) + ((1.0f - detail_texel.a)*detail_texel.r); - texel.g = (detail_texel.a * texel.g) + ((1.0f - detail_texel.a)*detail_texel.g); - texel.b = (detail_texel.a * texel.b) + ((1.0f - detail_texel.a)*detail_texel.b); - break; - } - switch (Get_Detail_Alpha_Func(pass)) - { - case W3DSHADER_DETAILALPHAFUNC_DISABLE: - break; - case W3DSHADER_DETAILALPHAFUNC_DETAIL: - texel.a = detail_texel.a; - break; - case W3DSHADER_DETAILALPHAFUNC_SCALE: - texel.a = texel.a * detail_texel.a; - break; - case W3DSHADER_DETAILALPHAFUNC_INVSCALE: - texel.a = texel.a + (1.0f - texel.a) * detail_texel.a; - break; - } - } - - /* - ** Shader parameters define combination... - */ - src.r = texel.r; - src.g = texel.g; - src.b = texel.b; - alpha = texel.a * Get_Opacity(pass,sc.CurTime()); - - switch (Get_Pri_Gradient(pass)) - { - case W3DSHADER_PRIGRADIENT_DISABLE: break; - case W3DSHADER_PRIGRADIENT_MODULATE: src = src * pri_gradient; break; - case W3DSHADER_PRIGRADIENT_ADD: src = src + pri_gradient; break; - } - - switch (Get_Sec_Gradient(pass)) - { - case W3DSHADER_SECGRADIENT_DISABLE: break; - case W3DSHADER_SECGRADIENT_ENABLE: src = src + sec_gradient; break; - } - - if (src.r > 1.0f) src.r = 1.0f; - if (src.g > 1.0f) src.g = 1.0f; - if (src.b > 1.0f) src.b = 1.0f; - - if (src.r < 0.0f) src.r = 0.0f; - if (src.g < 0.0f) src.g = 0.0f; - if (src.b < 0.0f) src.b = 0.0f; - - Color dest_blend; - switch (Get_Dest_Blend(pass)) - { - case W3DSHADER_DESTBLENDFUNC_ZERO: dest_blend = Color(0,0,0); break; - case W3DSHADER_DESTBLENDFUNC_ONE: dest_blend = Color(1,1,1); break; - case W3DSHADER_DESTBLENDFUNC_SRC_COLOR: dest_blend = src; break; - case W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_COLOR: dest_blend = Color(1.0f-src.r,1.0f-src.g, 1.0f-src.b); break; - case W3DSHADER_DESTBLENDFUNC_SRC_ALPHA: dest_blend = Color(alpha,alpha,alpha); break; - case W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA: dest_blend = Color(1.0f-alpha,1.0f-alpha,1.0f-alpha); break; - case W3DSHADER_DESTBLENDFUNC_SRC_COLOR_PREFOG: dest_blend = src; break; - } - - Color src_blend; - switch (Get_Src_Blend(pass)) - { - case W3DSHADER_SRCBLENDFUNC_ZERO: src_blend = Color(0,0,0); break; - case W3DSHADER_SRCBLENDFUNC_ONE: src_blend = Color(1,1,1); break; - case W3DSHADER_SRCBLENDFUNC_SRC_ALPHA: src_blend = Color(alpha,alpha,alpha); break; - case W3DSHADER_SRCBLENDFUNC_ONE_MINUS_SRC_ALPHA: src_blend = Color(1.0f-alpha,1.0f-alpha,1.0f-alpha); break; - } - - src = scale(src_blend,src) + scale(dest_blend,dest); - - /* - ** Dest becomes Src and we repeat! - */ - dest = src; - - } - - sc.out.t = Color(0.0f, 0.0f, 0.0f); - sc.out.c = dest; - -} - - -/*********************************************************************************************** - * GameMtl::ps2_shade -- Emulate the PS2 shader. * - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -void GameMtl::ps2_shade(ShadeContext& sc) -{ - if (gbufID) sc.SetGBufferID(gbufID); - - /* - ** Shadowing, return black - */ - if (sc.mode == SCMODE_SHADOW) { - sc.out.t = Color(0,0,0); - return; - } - - /* - ** Render each pass, initialize dest with the current background - */ - - // Background transparency. ??? - Color back_t; - Color back_c; - - AColor dest; - AColor src(1,1,1,1); - - sc.GetBGColor(back_c, back_t, FALSE); - - dest.r = back_c.r; - dest.g = back_c.g; - dest.b = back_c.b; - dest.a = 0.0f; - - for (int pass=0; pass < Get_Pass_Count(); pass++) { - - // Compute the gradients. - Color ambient = sc.ambientLight; - Color diffuse(0,0,0); - Color specular(0,0,0); - - for (int light_index = 0; light_index < sc.nLights; light_index++) { - - Color light_color; - Point3 light_dir; - float dot_nl; - float diffuse_coef; - - LightDesc * light = sc.Light(light_index); - - assert(light); - if(light->Illuminate(sc, sc.Normal(), light_color, light_dir, dot_nl, diffuse_coef)) { - - if (dot_nl > 0.0f) diffuse += dot_nl * light_color; - - float c = DotProd(light_dir, sc.ReflectVector()); - if (c > 0.f) { - specular += (float)pow(c, Get_Shininess(pass, sc.CurTime())) * light_color; - } - } - } - - ambient = ambient * Get_Ambient(pass,sc.CurTime()); - diffuse = diffuse * Get_Diffuse(pass,sc.CurTime()); - specular = specular * Get_Specular(pass,sc.CurTime()); - - Color gradient = ambient + diffuse + Get_Emissive(pass,sc.CurTime()); - AColor pri_gradient; - pri_gradient.r = gradient.r; - pri_gradient.g = gradient.g; - pri_gradient.b = gradient.b; - pri_gradient.a = 1.0f; - if (pri_gradient.r > 1.0f) pri_gradient.r = 1.0f; - if (pri_gradient.g > 1.0f) pri_gradient.g = 1.0f; - if (pri_gradient.b > 1.0f) pri_gradient.b = 1.0f; - - /* - ** Sampling the Texture(s) - */ - if (Get_Texture_Enable(pass,0) && Texture[pass][0]) { - src = Texture[pass][0]->EvalColor(sc); - } - - - /* - ** Shader parameters define combination... - */ - src.a *= Get_Opacity(pass,sc.CurTime()); - - switch (Get_Pri_Gradient(pass)) - { - case PSS_PRIGRADIENT_MODULATE: - src = src * pri_gradient; - break; - case PSS_PRIGRADIENT_HIGHLIGHT: - src = src * pri_gradient; - src += back_t; // ??? - break; - case PSS_PRIGRADIENT_HIGHLIGHT2: - src = src * pri_gradient; - src += back_t; // ??? - break; - } - - if (src.r > 1.0f) src.r = 1.0f; - if (src.g > 1.0f) src.g = 1.0f; - if (src.b > 1.0f) src.b = 1.0f; - if (src.b > 1.0f) src.a = 1.0f; - - if (src.r < 0.0f) src.r = 0.0f; - if (src.g < 0.0f) src.g = 0.0f; - if (src.b < 0.0f) src.b = 0.0f; - if (src.a < 0.0f) src.a = 0.0f; - - AColor param_a; - AColor param_b; - AColor param_c; - AColor param_d; - int a_value = Get_PS2_Shader_Param_A(pass); - int b_value = Get_PS2_Shader_Param_B(pass); - int c_value = Get_PS2_Shader_Param_C(pass); - int d_value = Get_PS2_Shader_Param_D(pass); - - switch (a_value) - { - case PSS_SRC: - param_a = src; - break; - case PSS_DEST: - param_a = dest; - break; - case PSS_ZERO: - param_a = AColor(0, 0, 0, 0); - break; - } - - switch (b_value) - { - case PSS_SRC: - param_b = src; - break; - case PSS_DEST: - param_b = dest; - break; - case PSS_ZERO: - param_b = AColor(0, 0, 0, 0); - break; - } - - switch (c_value) - { - case PSS_SRC_ALPHA: - param_c = AColor(src.a, src.a, src.a, src.a); - break; - case PSS_DEST_ALPHA: - param_c = back_t; // ??? - break; - case PSS_ONE: - param_c = AColor(1, 1, 1, 1); - break; - } - - switch (d_value) - { - case PSS_SRC: - param_d = src; - break; - case PSS_DEST: - param_d = dest; - break; - case PSS_ZERO: - param_d = AColor(0, 0, 0); - break; - } - - src = scale((param_a - param_b), param_c) + param_d; - - if (src.r > 1.0f) src.r = 1.0f; - if (src.g > 1.0f) src.g = 1.0f; - if (src.b > 1.0f) src.b = 1.0f; - if (src.b > 1.0f) src.a = 1.0f; - - if (src.r < 0.0f) src.r = 0.0f; - if (src.g < 0.0f) src.g = 0.0f; - if (src.b < 0.0f) src.b = 0.0f; - if (src.a < 0.0f) src.a = 0.0f; - - /* - ** Dest becomes Src and we repeat! - */ - dest = src; - } - - sc.out.t = Color(0.0f, 0.0f, 0.0f); - sc.out.c.r = dest.r; - sc.out.c.g = dest.g; - sc.out.c.b = dest.b; - - -} - -// PS2 equation paramaters. -// They are set to primes to avoid multiple equation solutions. -enum Shader_Translation { - ST_ZERO, - ST_ONE, - ST_SRC = 7, - ST_DEST = 31, - ST_SRC_ALPHA = 101, - ST_DEST_ALPHA = 2999, -}; - -/*********************************************************************************************** - * GameMtl::Compute_PC_Shader_From_PS2_Shader -- Determine if a PC shader can be created. * - * * - * * - * * - * * - * HISTORY: * - * 10/13/1999MLL: Created. * - *=============================================================================================*/ -int GameMtl::Compute_PC_Shader_From_PS2_Shader(int pass) -{ - int param_value[4]; - - // These match the PC equation paramaters. - static const int src_blend[4] = { - ST_ZERO, - ST_ONE, - ST_SRC_ALPHA, - 1 - ST_SRC_ALPHA - }; - static const int dest_blend[6] = { - ST_ZERO, - ST_ONE, - ST_SRC, - 1 - ST_SRC, - ST_SRC_ALPHA, - 1 - ST_SRC_ALPHA - }; - - int i = 0; - int j = 0; - int equation_value = 0; - - // Get the PS2 shader values. - param_value[0] = Get_PS2_Shader_Param_A(pass); - param_value[1] = Get_PS2_Shader_Param_B(pass); - param_value[2] = Get_PS2_Shader_Param_D(pass); - param_value[3] = Get_PS2_Shader_Param_C(pass); - - // Convert them to the enumeration. - for (i = 0; i < 3; i++) { - switch(param_value[i]) - { - case PSS_SRC: - param_value[i] = ST_SRC; - break; - case PSS_DEST: - param_value[i] = ST_DEST; - break; - case PSS_ZERO: - param_value[i] = ST_ZERO; - break; - } - } - - // The alpha paramater. - switch(param_value[3]) - { - case PSS_SRC_ALPHA: - param_value[3] = ST_SRC_ALPHA; - break; - case PSS_DEST_ALPHA: - param_value[3] = ST_DEST_ALPHA; - break; - case PSS_ONE: - param_value[3] = ST_ONE; - break; - } - - // Calculate the PS2 shader. - equation_value = ((param_value[0] - param_value[1]) * param_value[3]) + param_value[2]; - - for (i = 0; i < 4; i++) { - for (j = 0; j < 6; j++) { - // Calculate the PC shader. If equal, we have found a conversion. - if (((src_blend[i] * ST_SRC) + (dest_blend[j] * ST_DEST)) == equation_value) { - break; - } - } - - if (j != 6) { - break; - } - } - - if ((j == 6) && (i == 4)) { - // Set the W3D shader to opaque. - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_ZERO); - Set_Src_Blend(pass, W3DSHADER_SRCBLENDFUNC_ONE); - - // No matches. - return (FALSE); - } - - // Set the PC shader to an equivalant of the PS2 shader. - switch (dest_blend[j]) - { - case ST_ZERO: - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_ZERO); - break; - case ST_ONE: - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_ONE); - break; - case ST_SRC: - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_SRC_COLOR); - break; - case (1 - ST_SRC): - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_COLOR); - break; - case ST_SRC_ALPHA: - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_SRC_ALPHA); - break; - case (1 - ST_SRC_ALPHA): - Set_Dest_Blend(pass, W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA); - break; - } - - switch (src_blend[i]) - { - case ST_ZERO: - Set_Src_Blend(pass, W3DSHADER_SRCBLENDFUNC_ZERO); - break; - case ST_ONE: - Set_Src_Blend(pass, W3DSHADER_SRCBLENDFUNC_ONE); - break; - case ST_SRC_ALPHA: - Set_Src_Blend(pass, W3DSHADER_SRCBLENDFUNC_SRC_ALPHA); - break; - case (1 - ST_SRC_ALPHA): - Set_Src_Blend(pass, W3DSHADER_SRCBLENDFUNC_ONE_MINUS_SRC_ALPHA); - break; - } - - // A match was made. - return (TRUE); -} - - -/*********************************************************************************************** - * GameMtl::Compute_PS2_Shader_From_PC_Shader -- Change a W3D material to a PS2 W3D material. * -W3DSHADER_PRIGRADIENT_ * * - * * - * * - * * - * HISTORY: * - * 10/26/1999MLL: Created. * - *=============================================================================================*/ -int GameMtl::Compute_PS2_Shader_From_PC_Shader(int pass) -{ - - // These match the PC equation paramaters. - static const int a_blend[3] = { - ST_ZERO, - ST_SRC, - ST_DEST, - }; - - static const int b_blend[3] = { - ST_ZERO, - ST_SRC, - ST_DEST, - }; - - static const int d_blend[3] = { - ST_ZERO, - ST_SRC, - ST_DEST, - }; - - static const int c_blend[6] = { - ST_ONE, - ST_SRC_ALPHA, - ST_DEST_ALPHA, - }; - - int i = 0; - int j = 0; - int k = 0; - int l = 0; - int equation_value = 0; - int param_value[2]; - - // Get the PC shader values. - param_value[0] = Get_Src_Blend(pass); - param_value[1] = Get_Dest_Blend(pass); - - switch (param_value[0]) - { - case W3DSHADER_SRCBLENDFUNC_ZERO: - param_value[0] = ST_ZERO; - break; - case W3DSHADER_SRCBLENDFUNC_ONE: - param_value[0] = ST_ONE; - break; - case W3DSHADER_SRCBLENDFUNC_SRC_ALPHA: - param_value[0] = ST_SRC_ALPHA; - break; - case W3DSHADER_SRCBLENDFUNC_ONE_MINUS_SRC_ALPHA: - param_value[0] = 1 - ST_SRC_ALPHA; - break; - } - - // Convert them to the enumeration. - switch (param_value[1]) - { - case W3DSHADER_DESTBLENDFUNC_ZERO: - param_value[1] = ST_ZERO; - break; - case W3DSHADER_DESTBLENDFUNC_ONE: - param_value[1] = ST_ONE; - break; - case W3DSHADER_DESTBLENDFUNC_SRC_COLOR: - param_value[1] = ST_SRC; - break; - case W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_COLOR: - param_value[1] = 1 - ST_SRC; - break; - case W3DSHADER_DESTBLENDFUNC_SRC_ALPHA: - param_value[1] = ST_SRC_ALPHA; - break; - case W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA: - param_value[1] = 1 - ST_SRC_ALPHA; - break; - case W3DSHADER_DESTBLENDFUNC_SRC_COLOR_PREFOG: - assert(true); - break; - } - - - // Calculate the PC shader. - equation_value = param_value[0] * ST_SRC + param_value[1] * ST_DEST; - - // Set the shader to be a PS2 Shader. - ShaderType = STE_PS2_SHADER; - - // Find a match for the depth compare test. - switch (Get_Depth_Compare(pass)) - { - case W3DSHADER_DEPTHCOMPARE_PASS_NEVER: - Set_Depth_Compare(pass, PSS_DEPTHCOMPARE_PASS_NEVER); - break; - case W3DSHADER_DEPTHCOMPARE_PASS_LESS: - Set_Depth_Compare(pass, PSS_DEPTHCOMPARE_PASS_LESS); - break; - case W3DSHADER_DEPTHCOMPARE_PASS_LEQUAL: - Set_Depth_Compare(pass, PSS_DEPTHCOMPARE_PASS_LEQUAL); - break; - case W3DSHADER_DEPTHCOMPARE_PASS_ALWAYS: - Set_Depth_Compare(pass, PSS_DEPTHCOMPARE_PASS_ALWAYS); - break; - default: - Set_Depth_Compare(pass, PSS_DEPTHCOMPARE_PASS_LEQUAL); - break; - } - - // Only 1 gradient matches between the PC and PS2. - switch (Get_Pri_Gradient(pass)) - { - case W3DSHADER_PRIGRADIENT_MODULATE: - Set_Pri_Gradient(pass, PSS_PRIGRADIENT_MODULATE); - break; - default: - Set_Pri_Gradient(pass, PSS_PRIGRADIENT_MODULATE); - break; - } - - for (i = 0; i < 3; i++) { - for (j = 0; j < 3; j++) { - for (k = 0; k < 3; k++) { - for (l = 0; l < 3; l++) { - // Calculate the PS2 shader. If equal, we have found a conversion. - if (equation_value == ((a_blend[i] - b_blend[j]) * c_blend[k]) + d_blend[l]) { - goto finished; - } - } - } - } - } - - // Set the PS2 W3D shader to opaque. - Set_PS2_Shader_Param_A(pass, PSS_SRC); - Set_PS2_Shader_Param_B(pass, PSS_ZERO); - Set_PS2_Shader_Param_C(pass, PSS_ONE); - Set_PS2_Shader_Param_D(pass, PSS_ZERO); - Set_Depth_Mask(pass,W3DSHADER_DEPTHMASK_DEFAULT); - - // No matches. - return (FALSE); - -finished: - // Set the PS2 shader to an equivalant of the PC shader. - switch (a_blend[i]) - { - case ST_ZERO: - Set_PS2_Shader_Param_A(pass, PSS_ZERO); - break; - case ST_SRC: - Set_PS2_Shader_Param_A(pass, PSS_SRC); - break; - case ST_DEST: - Set_PS2_Shader_Param_A(pass, PSS_DEST); - break; - } - - switch (b_blend[j]) - { - case ST_ZERO: - Set_PS2_Shader_Param_B(pass, PSS_ZERO); - break; - case ST_SRC: - Set_PS2_Shader_Param_B(pass, PSS_SRC); - break; - case ST_DEST: - Set_PS2_Shader_Param_B(pass, PSS_DEST); - break; - } - - - switch (d_blend[l]) - { - case ST_ZERO: - Set_PS2_Shader_Param_D(pass, PSS_ZERO); - break; - case ST_SRC: - Set_PS2_Shader_Param_D(pass, PSS_SRC); - break; - case ST_DEST: - Set_PS2_Shader_Param_D(pass, PSS_DEST); - break; - } - - switch (c_blend[k]) - { - case ST_ONE: - Set_PS2_Shader_Param_C(pass, PSS_ONE); - break; - case ST_SRC_ALPHA: - Set_PS2_Shader_Param_C(pass, PSS_SRC_ALPHA); - break; - case ST_DEST_ALPHA: - Set_PS2_Shader_Param_C(pass, PSS_DEST_ALPHA); - break; - } - - // A match was made. - return (TRUE); -} - -void GameMtl::Set_Pass_Count(int passcount) -{ - assert(MainParameterBlock); - MainParameterBlock->SetValue(0, TimeValue(0), passcount); -} - -int GameMtl::Get_Pass_Count(void) -{ - assert(MainParameterBlock); - int pcount; - MainParameterBlock->GetValue(0, TimeValue(0), pcount, FOREVER); - return pcount; -} - - -Color GameMtl::Get_Ambient(int pass,TimeValue t) -{ - Color val; - PassParameterBlock[pass]->GetValue(PB_AMBIENT,t,val,FOREVER); - return val; -} -Color GameMtl::Get_Diffuse(int pass,TimeValue t) -{ - Color val; - PassParameterBlock[pass]->GetValue(PB_DIFFUSE,t,val,FOREVER); - return val; -} -Color GameMtl::Get_Specular(int pass,TimeValue t) -{ - Color val; - PassParameterBlock[pass]->GetValue(PB_SPECULAR,t,val,FOREVER); - return val; -} -Color GameMtl::Get_Emissive(int pass,TimeValue t) -{ - Color val; - PassParameterBlock[pass]->GetValue(PB_EMISSIVE,t,val,FOREVER); - return val; -} -float GameMtl::Get_Shininess(int pass,TimeValue t) -{ - float val; - PassParameterBlock[pass]->GetValue(PB_SHININESS,t,val,FOREVER); - return val; -} -float GameMtl::Get_Opacity(int pass,TimeValue t) -{ - float val; - PassParameterBlock[pass]->GetValue(PB_OPACITY,t,val,FOREVER); - return val; -} -float GameMtl::Get_Translucency(int pass,TimeValue t) -{ - float val; - PassParameterBlock[pass]->GetValue(PB_TRANSLUCENCY,t,val,FOREVER); - return val; -} -int GameMtl::Get_Copy_Specular_To_Diffuse(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_COPY_SPECULAR_TO_DIFFUSE,0,val,FOREVER); - return val; -} -int GameMtl::Get_Mapping_Type(int pass, int stage) -{ - int val = -1; - if (stage == 0) - PassParameterBlock[pass]->GetValue(PB_STAGE0_MAPPING_TYPE,0,val,FOREVER); - else if (stage == 1) - PassParameterBlock[pass]->GetValue(PB_STAGE1_MAPPING_TYPE,0,val,FOREVER); - return val; -} -int GameMtl::Get_PSX_Translucency(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PSX_TRANSLUCENCY,0,val,FOREVER); - return val; -} -int GameMtl::Get_PSX_Lighting(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PSX_LIGHTING,0,val,FOREVER); - return val; -} -int GameMtl::Get_Depth_Compare(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_DEPTH_COMPARE,0,val,FOREVER); - return val; -} -int GameMtl::Get_Depth_Mask(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_DEPTH_MASK,0,val,FOREVER); - return val; -} -int GameMtl::Get_Alpha_Test(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_ALPHA_TEST,0,val,FOREVER); - return val; -} -int GameMtl::Get_Dest_Blend(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_DEST_BLEND,0,val,FOREVER); - return val; -} -int GameMtl::Get_Pri_Gradient(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PRI_GRADIENT,0,val,FOREVER); - return val; -} -int GameMtl::Get_Sec_Gradient(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_SEC_GRADIENT,0,val,FOREVER); - return val; -} -int GameMtl::Get_Src_Blend(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_SRC_BLEND,0,val,FOREVER); - return val; -} -int GameMtl::Get_Detail_Color_Func(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_DETAIL_COLOR_FUNC,0,val,FOREVER); - return val; -} -int GameMtl::Get_Detail_Alpha_Func(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_DETAIL_ALPHA_FUNC,0,val,FOREVER); - return val; -} -int GameMtl::Get_Texture_Enable(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_ENABLE,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_ENABLE,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Publish(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_PUBLISH,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_PUBLISH,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Resize(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_RESIZE,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_RESIZE,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_No_Mipmap(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_NO_MIPMAP,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_NO_MIPMAP,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Clamp_U(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_CLAMP_U,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_CLAMP_U,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Clamp_V(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_CLAMP_V,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_CLAMP_V,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_No_LOD(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_NO_LOD,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_NO_LOD,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Alpha_Bitmap(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_ALPHA_BITMAP,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_ALPHA_BITMAP,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Hint(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_HINT,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_HINT,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Display(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_DISPLAY,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_DISPLAY,0,val,FOREVER); - } - return val; -} -float GameMtl::Get_Texture_Frame_Rate(int pass,int stage) -{ - float val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_FRAME_RATE,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_FRAME_RATE,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Frame_Count(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_FRAME_COUNT,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_FRAME_COUNT,0,val,FOREVER); - } - return val; -} -int GameMtl::Get_Texture_Anim_Type(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_TEXTURE_ANIM_TYPE,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_TEXTURE_ANIM_TYPE,0,val,FOREVER); - } - return val; -} -Texmap * GameMtl::Get_Texture(int pass,int stage) -{ - return GetSubTexmap(pass_stage_to_texmap_index(pass,stage)); -} - -int GameMtl::Get_PS2_Shader_Param_A(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PS2_SHADER_PARAM_A,0,val,FOREVER); - return val; -} - -int GameMtl::Get_PS2_Shader_Param_B(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PS2_SHADER_PARAM_B,0,val,FOREVER); - return val; -} - -int GameMtl::Get_PS2_Shader_Param_C(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PS2_SHADER_PARAM_C,0,val,FOREVER); - return val; -} - -int GameMtl::Get_PS2_Shader_Param_D(int pass) -{ - int val; - PassParameterBlock[pass]->GetValue(PB_PS2_SHADER_PARAM_D,0,val,FOREVER); - return val; -} - -int GameMtl::Get_Map_Channel(int pass,int stage) -{ - int val; - if (stage == 0) { - PassParameterBlock[pass]->GetValue(PB_STAGE0_MAP_CHANNEL,0,val,FOREVER); - } else { - PassParameterBlock[pass]->GetValue(PB_STAGE1_MAP_CHANNEL,0,val,FOREVER); - } - return val; -} - - -void GameMtl::Set_Ambient(int pass,TimeValue t,Color val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_AMBIENT, t, val); -} -void GameMtl::Set_Diffuse(int pass,TimeValue t,Color val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_DIFFUSE, t, val); -} -void GameMtl::Set_Specular(int pass,TimeValue t,Color val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_SPECULAR, t, val); -} -void GameMtl::Set_Emissive(int pass,TimeValue t,Color val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_EMISSIVE, t, val); -} -void GameMtl::Set_Shininess(int pass,TimeValue t,float val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_SHININESS, t, val); -} -void GameMtl::Set_Opacity(int pass,TimeValue t,float val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_OPACITY, t, val); -} -void GameMtl::Set_Translucency(int pass,TimeValue t,float val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_TRANSLUCENCY, t, val); -} -void GameMtl::Set_Copy_Specular_To_Diffuse(int pass,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_COPY_SPECULAR_TO_DIFFUSE, 0, val); -} -void GameMtl::Set_Mapping_Type(int pass,int stage,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) - PassParameterBlock[pass]->SetValue(PB_STAGE0_MAPPING_TYPE, 0, val); - else if (stage == 1) - PassParameterBlock[pass]->SetValue(PB_STAGE1_MAPPING_TYPE, 0, val); -} -void GameMtl::Set_PSX_Translucency(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PSX_TRANSLUCENCY, 0, val); -} -void GameMtl::Set_PSX_Lighting(int pass,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PSX_LIGHTING, 0, val); -} -void GameMtl::Set_Depth_Compare(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_DEPTH_COMPARE, 0, val); -} -void GameMtl::Set_Depth_Mask(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_DEPTH_MASK, 0, val); -} -void GameMtl::Set_Alpha_Test(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_ALPHA_TEST, 0, val); -} -void GameMtl::Set_Dest_Blend(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_DEST_BLEND, 0, val); -} -void GameMtl::Set_Pri_Gradient(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PRI_GRADIENT, 0, val); -} -void GameMtl::Set_Sec_Gradient(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_SEC_GRADIENT, 0, val); -} -void GameMtl::Set_Src_Blend(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_SRC_BLEND, 0, val); -} -void GameMtl::Set_Detail_Color_Func(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_DETAIL_COLOR_FUNC, 0, val); -} -void GameMtl::Set_Detail_Alpha_Func(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_DETAIL_ALPHA_FUNC, 0, val); -} -void GameMtl::Set_Texture_Enable(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_ENABLE, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_ENABLE, 0, val); - } -} -void GameMtl::Set_Texture_Publish(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_PUBLISH, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_PUBLISH, 0, val); - } -} -void GameMtl::Set_Texture_Resize(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_RESIZE, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_RESIZE, 0, val); - } -} -void GameMtl::Set_Texture_No_Mipmap(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_NO_MIPMAP, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_NO_MIPMAP, 0, val); - } -} -void GameMtl::Set_Texture_Clamp_U(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_CLAMP_U, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_CLAMP_U, 0, val); - } -} -void GameMtl::Set_Texture_Clamp_V(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_CLAMP_V, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_CLAMP_V, 0, val); - } -} -void GameMtl::Set_Texture_No_LOD(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_NO_LOD, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_NO_LOD, 0, val); - } -} -void GameMtl::Set_Texture_Alpha_Bitmap(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_ALPHA_BITMAP, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_ALPHA_BITMAP, 0, val); - } -} -void GameMtl::Set_Texture_Hint(int pass,int stage,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_HINT, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_HINT, 0, val); - } -} -void GameMtl::Set_Texture_Display(int pass,int stage,bool val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - - // clear all tex display flags - for (int pi = 0; piSetValue(PB_STAGE0_TEXTURE_DISPLAY, 0, false); - PassParameterBlock[pi]->SetValue(PB_STAGE1_TEXTURE_DISPLAY, 0, false); - } - - // set the one we want - if (val == true) { - - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_DISPLAY, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_DISPLAY, 0, val); - } - SetMtlFlag( MTL_TEX_DISPLAY_ENABLED, TRUE ); - SetActiveTexmap(Texture[pass][stage]); - NotifyDependents(FOREVER,PART_ALL,REFMSG_CHANGE); - - } else { - - SetMtlFlag( MTL_TEX_DISPLAY_ENABLED, FALSE ); - SetActiveTexmap(NULL); - NotifyDependents(FOREVER,PART_ALL,REFMSG_CHANGE); - - } - - // tell dialog to refresh... - if (MaterialDialog) { - MaterialDialog->ReloadDialog(); - } - - if (IsMultiMtl()) { - - // Loop through all sub materials of the multi-material. - for (unsigned mi = 0; mi < NumSubMtls(); mi++) { - - // Only change those that are W3D materials. - if (GetSubMtl(mi)->ClassID() == GameMaterialClassID) { - int pass; - - for (pass = 0; pass < ((GameMtl*)(GetSubMtl(mi)))->Get_Pass_Count(); pass++) { - - if (((GameMtl*)(GetSubMtl(mi)))->Get_Texture_Enable(pass, stage)) { - (GetSubMtl(mi))->SetMtlFlag(MTL_TEX_DISPLAY_ENABLED, TRUE); - } - } - } - } - } -} - -void GameMtl::Set_Texture_Frame_Rate(int pass,int stage,float val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_FRAME_RATE, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_FRAME_RATE, 0, val); - } -} -void GameMtl::Set_Texture_Frame_Count(int pass,int stage,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_FRAME_COUNT, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_FRAME_COUNT, 0, val); - } -} -void GameMtl::Set_Texture_Anim_Type(int pass,int stage,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_TEXTURE_ANIM_TYPE, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_TEXTURE_ANIM_TYPE, 0, val); - } -} - -void GameMtl::Set_Texture(int pass,int stage,Texmap * tex) -{ - SetSubTexmap(pass_stage_to_texmap_index(pass,stage),tex); -} - -void GameMtl::Set_PS2_Shader_Param_A(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PS2_SHADER_PARAM_A, 0, val); -} - -void GameMtl::Set_PS2_Shader_Param_B(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PS2_SHADER_PARAM_B, 0, val); -} - -void GameMtl::Set_PS2_Shader_Param_C(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PS2_SHADER_PARAM_C, 0, val); -} - -void GameMtl::Set_PS2_Shader_Param_D(int pass,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - PassParameterBlock[pass]->SetValue(PB_PS2_SHADER_PARAM_D, 0, val); -} - -void GameMtl::Set_Map_Channel(int pass,int stage,int val) -{ - assert((pass >=0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert(PassParameterBlock[pass]); - if (stage == 0) { - PassParameterBlock[pass]->SetValue(PB_STAGE0_MAP_CHANNEL, 0, val); - } else { - PassParameterBlock[pass]->SetValue(PB_STAGE1_MAP_CHANNEL, 0, val); - } - - if (Texture[pass][stage] != NULL) { - UVGen * uvgen = Texture[pass][stage]->GetTheUVGen(); - if (uvgen != NULL) { - uvgen->SetMapChannel(val); - } - } - - NotifyDependents(FOREVER,PART_ALL,REFMSG_CHANGE); -} - - -// This returns the mapping args string buffer for that pass (and stage) after -// assuring that it can contain a string of length 'len' (if len is 0 no -// resizing will be performed).. -char * GameMtl::Get_Mapping_Arg_Buffer(int pass, int stage, unsigned int len) -{ - assert(pass >= 0); - assert(pass < W3dMaterialClass::MAX_PASSES); - assert(stage >= 0); - assert(stage < W3dMaterialClass::MAX_STAGES); - - if (MapperArgLen[pass][stage] < len) { - MapperArgLen[pass][stage] = len + 10; // New length - char *temp = new char[MapperArgLen[pass][stage] + 1]; - if (MapperArg[pass][stage]) { - assert(strlen(MapperArg[pass][stage]) <= MapperArgLen[pass][stage]); - strcpy(temp, MapperArg[pass][stage]); - delete [] (MapperArg[pass][stage]); - MapperArg[pass][stage] = NULL; - } - - MapperArg[pass][stage] = temp; - } - - return MapperArg[pass][stage]; -} - -int GameMtl::pass_stage_to_texmap_index(int pass,int stage) -{ - assert((pass >= 0) && (pass < W3dMaterialClass::MAX_PASSES)); - assert((stage >= 0) && (stage < W3dMaterialClass::MAX_STAGES)); - return pass * W3dMaterialClass::MAX_STAGES + stage; -} - -void GameMtl::texmap_index_to_pass_stage(int index,int * set_pass,int * set_stage) -{ - *set_pass = index / W3dMaterialClass::MAX_STAGES; - *set_stage = index % W3dMaterialClass::MAX_STAGES; -} - -float GameMtl::EvalDisplacement(ShadeContext& sc) -{ - float displacement = 0.0F; - if (DisplacementMap != NULL) { - displacement = DisplacementMap->EvalMono(sc); - displacement = displacement * DisplacementAmt; - } - return displacement; -} - -Interval GameMtl::DisplacementValidity(TimeValue t) -{ - return FOREVER; -} - -void GameMtlPostLoad::proc(ILoad *iload) -{ - if (IsOld) { - - m->Reset(); - m->Set_Pass_Count(1); - m->Set_Ambient(0,0,AmbientCoeff); - m->Set_Diffuse(0,0,Diffuse * DiffuseCoeff); - m->Set_Specular(0,0,Specular * SpecularCoeff); - m->Set_Emissive(0,0,EmissiveCoeff); - m->Set_Opacity(0,0,Opacity); - m->Set_Translucency(0,0,Translucency); - m->Set_Shininess(0,0,Shininess); - m->Set_Mapping_Type(0,0,DCTMappingType); - - Texmap * tex = (*(m->Maps))[ID_DI].Map; - - if ((tex) && (tex->ClassID() == Class_ID(BMTEX_CLASS_ID,0))) { - m->Set_Texture(0,0,tex); - m->Set_Texture_Enable(0,0,true); - m->Set_Texture_Frame_Rate(0,0,DCTFrameRate); - m->Set_Texture_Frame_Count(0,0,DCTFrames); - - if (m->TestMtlFlag(MTL_TEX_DISPLAY_ENABLED)) { - m->Set_Texture_Display(0,0,true); - } - } - - m->ReplaceReference(GameMtl::REF_MAPS,NULL); - } - - // older material formats did not save the map channel and will default to zero, - // we need to change the map channel to one in this case. - for (int pass = 0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - for (int stage = 0; stage < W3dMaterialClass::MAX_STAGES; stage++) { - if ((m->Get_Map_Channel(pass,stage) < 1) || (m->Get_Map_Channel(pass,stage) > 99)) { - m->Set_Map_Channel(pass,stage,1); - } - } - } - - // Now that I've removed the UI for the RESIZE and NO_MIPMAP options in the texture - // pane, we initialize the No_LOD setting to the existing NO_MIPMAP setting - // NOTE: I created a new flag for gamemtl which gets set when this conversion takes - // place for the first time. - if (m->Get_Flag(GAMEMTL_CONVERTED_TO_NOLOD) == false) { - for (int pass = 0; pass < W3dMaterialClass::MAX_PASSES; pass++) { - for (int stage = 0; stage < W3dMaterialClass::MAX_STAGES; stage++) { - bool no_lod = m->Get_Texture_No_Mipmap(pass,stage) != 0; - m->Set_Texture_No_LOD(pass,stage,no_lod); - } - } - m->Set_Flag(GAMEMTL_CONVERTED_TO_NOLOD,true); - } - - delete this; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtlDlg.cpp deleted file mode 100644 index c9dc5c2444..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlDlg.cpp +++ /dev/null @@ -1,685 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlDlg.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 12/07/00 5:52p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include -#include -#include -#include - -#include "GameMtlDlg.h" -#include "gamemtl.h" -#include "GameMtlPassDlg.h" -#include "dllmain.h" -#include "resource.h" -#include "w3d_file.h" - -static BOOL CALLBACK DisplacementMapDlgProc(HWND hwndDlg, UINT msg, WPARAM wPara,LPARAM lParam); -static BOOL CALLBACK SurfaceTypePanelDlgProc(HWND hwndDlg, UINT msg, WPARAM wPara,LPARAM lParam); -static BOOL CALLBACK PassCountPanelDlgProc(HWND hwndDlg, UINT msg, WPARAM wPara,LPARAM lParam); -static BOOL CALLBACK PassCountDialogDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam,LPARAM lParam); - -static int _Pass_Index_To_Flag[] = -{ - GAMEMTL_PASS0_ROLLUP_OPEN, - GAMEMTL_PASS1_ROLLUP_OPEN, - GAMEMTL_PASS2_ROLLUP_OPEN, - GAMEMTL_PASS3_ROLLUP_OPEN, -}; - -/*********************************************************************************************** - * GameMtlDlg::GameMtlDlg -- constructor * - * * - * INPUT: * - * hwMtlEdit - windows handle of the MAX material editor * - * imp - Interface object for MAX materials and textures * - * m - pointer to a GameMtl to be edited * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -GameMtlDlg::GameMtlDlg(HWND hwMtlEdit, IMtlParams *imp, GameMtl *m) -{ - HwndEdit = hwMtlEdit; - HwndPassCount = NULL; - HwndSurfaceType = NULL; - HwndDisplacementMap = NULL; - HpalOld = NULL; - - for (int i=0; iRestorePalette(hdc, HpalOld); - ReleaseDC(HwndPassCount,hdc); - } - - #ifdef WANT_DISPLACEMENT_MAPS - TheMtl->Set_Flag(GAMEMTL_DISPLACEMENT_ROLLUP_OPEN,IParams->IsRollupPanelOpen(HwndDisplacementMap)); - #endif //WANT_DISPLACEMENT_MAPS - - TheMtl->Set_Flag(GAMEMTL_SURFACE_ROLLUP_OPEN,IParams->IsRollupPanelOpen(HwndSurfaceType)); - TheMtl->Set_Flag(GAMEMTL_PASSCOUNT_ROLLUP_OPEN,IParams->IsRollupPanelOpen(HwndPassCount)); - TheMtl->RollScroll = IParams->GetRollupScrollPos(); - - IParams->UnRegisterDlgWnd(HwndSurfaceType); - IParams->DeleteRollupPage(HwndSurfaceType); - HwndSurfaceType = NULL; - - #ifdef WANT_DISPLACEMENT_MAPS - IParams->UnRegisterDlgWnd(HwndDisplacementMap); - IParams->DeleteRollupPage(HwndDisplacementMap); - HwndDisplacementMap = NULL; - #endif //#ifdef WANT_DISPLACEMENT_MAPS - - IParams->UnRegisterDlgWnd(HwndPassCount); - IParams->DeleteRollupPage(HwndPassCount); - HwndPassCount = NULL; - - for (int i=0; iSetParamDlg(NULL); -} - - -/*********************************************************************************************** - * GameMtlDlg::ClassID -- Returns the ClassID of GameMtl * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -Class_ID GameMtlDlg::ClassID() -{ - return GameMaterialClassID; -} - -/*********************************************************************************************** - * GameMtlDlg::SetThing -- Sets the material to be edited * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::SetThing(ReferenceTarget *m) -{ - assert (m); - assert (m->SuperClassID()==MATERIAL_CLASS_ID); - assert ((m->ClassID()==GameMaterialClassID) || (m->ClassID()==PS2GameMaterialClassID)); - assert (TheMtl); - - int pass; - - // destroy our old pass dialogs - for (pass=0; passGet_Pass_Count();pass++) { - delete PassDialog[pass]; - PassDialog[pass] = NULL; - } - - // install the new material - TheMtl->SetParamDlg(NULL); - TheMtl = (GameMtl *)m; - TheMtl->SetParamDlg(this); - - // build a new set of pass dialogs - for (pass=0; passGet_Pass_Count(); pass++) { - PassDialog[pass] = new GameMtlPassDlg(HwndEdit, IParams, TheMtl, pass); - } - - // refresh the contents of the dialogs - ReloadDialog(); -} - -/*********************************************************************************************** - * GameMtlDlg::SetTime -- Sets the time value, updates the material and the dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::SetTime(TimeValue t) -{ - if (t!=CurTime) { - CurTime = t; -// TheMtl->Update(IParams->GetTime(),Valid); - ReloadDialog(); - } -} - -/*********************************************************************************************** - * GameMtlDlg::ReloadDialog -- Updates the values in all of the dialog's controls * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::ReloadDialog() -{ - /* - ** Init the pass count panel - */ - assert(TheMtl && HwndPassCount && HwndSurfaceType); - - /* - ** Init the surface count panel - */ - ::SendMessage (HwndSurfaceType, WM_USER+101, 0, 0L); - - #ifdef WANT_DISPLACEMENT_MAPS - ::SendMessage (HwndDisplacementMap, WM_USER+101, 0, 0L); - #endif //WANT_DISPLACEMENT_MAPS - - /* - ** Init the pass count panel - */ - char a[10]; - sprintf(a, "%d", TheMtl->Get_Pass_Count()); - SetWindowText(GetDlgItem(HwndPassCount, IDC_GAMEMTL_PASSCOUNT_STATIC), a); - - /* - ** Init each pass panel - */ - for(int i = 0; i < TheMtl->Get_Pass_Count(); i++) - { - PassDialog[i]->ReloadDialog(); - } -} - -/*********************************************************************************************** - * GameMtlDlg::ActivateDlg -- Activates and deactivates the dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::ActivateDlg(BOOL onoff) -{ - for(int i = 0; i < TheMtl->Get_Pass_Count(); i++) - { - assert(PassDialog[i]); - PassDialog[i]->ActivateDlg(onoff); - } -} - -/*********************************************************************************************** - * GameMtlDlg::Invalidate -- causes the dialog to be redrawn * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::Invalidate() -{ - InvalidateRect(HwndSurfaceType,NULL,0); - - #ifdef WANT_DISPLACEMENT_MAPS - InvalidateRect(HwndDisplacementMap,NULL,0); - #endif //WANT_DISPLACEMENT_MAPS - - InvalidateRect(HwndPassCount,NULL,0); -} - -BOOL GameMtlDlg::DisplacementMapProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - - case WM_INITDIALOG: - //SetupIntSpinner(hDlg, IDC_AMOUNT_SPIN, IDC_AMOUNT_EDIT, -999, 999, 0); - /* no break */ - - case WM_USER + 101: - { - SetDlgItemInt (hDlg, IDC_AMOUNT_EDIT, TheMtl->Get_Displacement_Amount () * 100, TRUE); - SetupIntSpinner(hDlg, IDC_AMOUNT_SPIN, IDC_AMOUNT_EDIT, -999, 999, TheMtl->Get_Displacement_Amount () * 100); - - Texmap *map = TheMtl->Get_Displacement_Map (); - if (map != NULL) { - SetDlgItemText (hDlg, IDC_TEXTURE_BUTTON, map->GetFullName ()); - } - } - break; - - case CC_SPINNER_CHANGE: - { - ISpinnerControl *control = (ISpinnerControl *)lParam; - TheMtl->Set_Displacement_Amount (((float)control->GetIVal ()) / 100.0F); - } - break; - - case WM_COMMAND: - switch(LOWORD(wParam)) - { - case IDC_TEXTURE_BUTTON: - if(HIWORD(wParam) == BN_CLICKED) - { - PostMessage(HwndEdit, WM_TEXMAP_BUTTON, TheMtl->Get_Displacement_Map_Index (), (LPARAM)TheMtl); - } - } - break; - } - - return FALSE; -} - -BOOL GameMtlDlg::SurfaceTypeProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - - case WM_INITDIALOG: - { - // - // Fill the combobox with the names of the different surface types - // - for (int index = 0; index < SURFACE_TYPE_MAX; index ++) { - ::SendDlgItemMessage ( hDlg, - IDC_SURFACE_TYPE_COMBO, - CB_ADDSTRING, - 0, - (LPARAM)SURFACE_TYPE_STRINGS[index]); - } - - // - // Limit the range of the static sort level spinner to 0 - MAX_SORT_LEVEL. - // - int sort_level = TheMtl->Get_Sort_Level(); - SetupIntSpinner(hDlg, IDC_SORT_LEVEL_SPIN, IDC_SORT_LEVEL, 0, MAX_SORT_LEVEL, sort_level); - - // Check the checkbox if sort_level is not SORT_LEVEL_NONE. - ::SendDlgItemMessage(hDlg, IDC_ENABLE_SORT_LEVEL, BM_SETCHECK, - sort_level == SORT_LEVEL_NONE ? BST_UNCHECKED : BST_CHECKED, 0); - } - - case WM_USER + 101: - { - // - // Select the current surface type - // - ::SendDlgItemMessage ( hDlg, - IDC_SURFACE_TYPE_COMBO, - CB_SETCURSEL, - (WPARAM)TheMtl->Get_Surface_Type (), - - 0L); - - // - // Set the correct sort level - // - int sort_level = TheMtl->Get_Sort_Level(); - ISpinnerControl *spinner = GetISpinner(::GetDlgItem(hDlg, IDC_SORT_LEVEL_SPIN)); - assert(spinner); - spinner->SetValue(sort_level, FALSE); - ::SendDlgItemMessage(hDlg, IDC_ENABLE_SORT_LEVEL, BM_SETCHECK, - sort_level == SORT_LEVEL_NONE ? BST_UNCHECKED : BST_CHECKED, 0); - break; - } - - case WM_COMMAND: - { - switch(LOWORD(wParam)) - { - case IDC_SURFACE_TYPE_COMBO: - if(HIWORD(wParam) == CBN_SELCHANGE) - { - unsigned int type = ::SendDlgItemMessage (hDlg, IDC_SURFACE_TYPE_COMBO, CB_GETCURSEL, 0, 0L); - TheMtl->Set_Surface_Type (type); - } - break; - - case IDC_ENABLE_SORT_LEVEL: - if (HIWORD(wParam) == BN_CLICKED) - { - // If the 'enable' checkbox was unchecked, set the sort level to NONE. - int state = ::IsDlgButtonChecked(hDlg, IDC_ENABLE_SORT_LEVEL); - ISpinnerControl *spinner = GetISpinner(::GetDlgItem(hDlg, IDC_SORT_LEVEL_SPIN)); - assert(spinner); - if (state == BST_UNCHECKED) - { - spinner->SetValue(SORT_LEVEL_NONE, FALSE); - TheMtl->Set_Sort_Level(SORT_LEVEL_NONE); - } - else if (state == BST_CHECKED) - { - // Sort level was enabled, so set it's level to 1 if it was NONE before. - if (spinner->GetIVal() == SORT_LEVEL_NONE) - { - spinner->SetValue(1, FALSE); - TheMtl->Set_Sort_Level(1); - } - } - } - } - break; - } - - case CC_SPINNER_CHANGE: - { - ISpinnerControl *spinner = (ISpinnerControl*)lParam; - switch(LOWORD(wParam)) - { - case IDC_SORT_LEVEL_SPIN: - // Check the 'enabled' checkbox if sort level != SORT_LEVEL_NONE, uncheck it otherwise. - ::SendDlgItemMessage(hDlg, IDC_ENABLE_SORT_LEVEL, BM_SETCHECK, - spinner->GetIVal() == SORT_LEVEL_NONE ? BST_UNCHECKED : BST_CHECKED, 0); - TheMtl->Set_Sort_Level(spinner->GetIVal()); - break; - } - break; - } - } - - return FALSE; -} - - -BOOL GameMtlDlg::PassCountProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - break; - - case WM_COMMAND: - switch(LOWORD(wParam)) - { - case IDC_SETPASSCOUNT: - if(HIWORD(wParam) == BN_CLICKED) - { - Set_Pass_Count_Dialog(); - } - } - break; - } - - return FALSE; -} - -static BOOL CALLBACK DisplacementMapDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam,LPARAM lParam) -{ - GameMtlDlg * theDlg; - if (msg == WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndDisplacementMap = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - theDlg->IsActive = 1; - BOOL res = theDlg->DisplacementMapProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - - return res; -} - -static BOOL CALLBACK SurfaceTypePanelDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam,LPARAM lParam) -{ - GameMtlDlg * theDlg; - if (msg == WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndSurfaceType = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - theDlg->IsActive = 1; - BOOL res = theDlg->SurfaceTypeProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - - return res; -} - -static BOOL CALLBACK PassCountPanelDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam,LPARAM lParam) -{ - GameMtlDlg * theDlg; - if (msg == WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndPassCount = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - theDlg->IsActive = 1; - BOOL res = theDlg->PassCountProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - - return res; -} - -void GameMtlDlg::Set_Pass_Count_Dialog(void) -{ - int res = DialogBoxParam( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_PASS_COUNT_DIALOG), - HwndPassCount, - PassCountDialogDlgProc, - (LPARAM)TheMtl->Get_Pass_Count()); - - if (res>=0) - { - if (res<=0) res = 1; - if (res>4) res = 4; - - char a[10]; - sprintf(a, "%d", res); - - SetWindowText(GetDlgItem(HwndPassCount, IDC_GAMEMTL_PASSCOUNT_STATIC), a); - - if(TheMtl->Get_Pass_Count() != res) - { - for(int i = 0; i < TheMtl->Get_Pass_Count(); i++) - { - delete PassDialog[i]; - PassDialog[i] = NULL; - } - - TheMtl->Set_Pass_Count(res); - - for(i = 0; i < TheMtl->Get_Pass_Count(); i++) - { - PassDialog[i] = new GameMtlPassDlg(HwndEdit, IParams, TheMtl, i); - } - - ReloadDialog(); - } - } -} - -static BOOL CALLBACK PassCountDialogDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam,LPARAM lParam) -{ - switch (msg) - { - case WM_INITDIALOG: - { - ISpinnerControl *spin = SetupIntSpinner( - hwndDlg,IDC_PASSCOUNT_SPIN, IDC_PASSCOUNT_EDIT, - 1,4,(int)lParam); - ReleaseISpinner(spin); - CenterWindow(hwndDlg,GetParent(hwndDlg)); - break; - } - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDOK: - { - ISpinnerControl *spin = GetISpinner(GetDlgItem(hwndDlg,IDC_PASSCOUNT_SPIN)); - EndDialog(hwndDlg,spin->GetIVal()); - ReleaseISpinner(spin); - break; - } - - case IDCANCEL: - EndDialog(hwndDlg,-1); - break; - } - break; - - default: - return FALSE; - } - return TRUE; -} - - -/*********************************************************************************************** - * GameMtlDlg::Build_Dialog -- Adds the dialog to the material editor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::Build_Dialog() -{ - if ((TheMtl->Flags&(GAMEMTL_ROLLUP_FLAGS))==0) { - TheMtl->Set_Flag(GAMEMTL_PASS0_ROLLUP_OPEN,TRUE); - } - - HwndSurfaceType = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_SURFACE_TYPE), - SurfaceTypePanelDlgProc, - Get_String(IDS_SURFACE_TYPE), - (LPARAM)this, - TheMtl->Get_Flag(GAMEMTL_SURFACE_ROLLUP_OPEN) ? 0:APPENDROLL_CLOSED - ); - - #ifdef WANT_DISPLACEMENT_MAPS - HwndDisplacementMap = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_DISPLACEMENT_MAP), - DisplacementMapDlgProc, - Get_String(IDS_DISPLACEMENT_MAP), - (LPARAM)this, - TheMtl->Get_Flag(GAMEMTL_DISPLACEMENT_ROLLUP_OPEN) ? 0:APPENDROLL_CLOSED - ); - #endif //WANT_DISPLACEMENT_MAPS - - HwndPassCount = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_PASS_COUNT), - PassCountPanelDlgProc, - Get_String(IDS_PASS_COUNT), - (LPARAM)this, - TheMtl->Get_Flag(GAMEMTL_PASSCOUNT_ROLLUP_OPEN) ? 0:APPENDROLL_CLOSED - ); - - for (int i=0; iGet_Pass_Count(); i++) { - PassDialog[i] = new GameMtlPassDlg(HwndEdit, IParams, TheMtl, i); - } - - IParams->SetRollupScrollPos(TheMtl->RollScroll); - - ReloadDialog(); -} - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlDlg.h b/Generals/Code/Tools/WW3D/max2w3d/GameMtlDlg.h deleted file mode 100644 index e11efb6ae1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlDlg.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlDlg.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 6/30/99 7:10p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - - -#ifndef GAMEMTLDLG_H -#define GAMEMTLDLG_H - -class GameMtl; -class GameMtlPassDlg; - - -//////////////////////////////////////////////////////////////////////// -// GameMtlDlg -// -// Dialog box interface in the material editor for GameMtl -// This is basically a cannibalized version of the Standard -// Max material's dialog. -// -//////////////////////////////////////////////////////////////////////// -class GameMtlDlg: public ParamDlg -{ - -public: - - //////////////////////////////////////////////////////////////////////// - // Methods - //////////////////////////////////////////////////////////////////////// - GameMtlDlg(HWND hwMtlEdit, IMtlParams *imp, GameMtl *m); - ~GameMtlDlg(); - - // From ParamDlg: - Class_ID ClassID(void); - void SetThing(ReferenceTarget *m); - ReferenceTarget* GetThing(void) { return (ReferenceTarget*)TheMtl; } - void DeleteThis() { delete this; } - void SetTime(TimeValue t); - void ReloadDialog(void); - void ActivateDlg(BOOL onOff); - - void Invalidate(void); - void Update_Display(void) { IParams->MtlChanged(); } - -protected: - - void Build_Dialog(void); - - BOOL DisplacementMapProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); - BOOL SurfaceTypeProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); - BOOL PassCountProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); - void Set_Pass_Count_Dialog(void); - - enum { MAX_PASSES = 4 }; - - //////////////////////////////////////////////////////////////////////// - // Windows handles - //////////////////////////////////////////////////////////////////////// - HWND HwndEdit; // window handle of the materials editor dialog - HWND HwndPassCount; // Rollup pass count panel - HWND HwndSurfaceType; // Rollup surface type panel - HWND HwndDisplacementMap; - HPALETTE HpalOld; - - GameMtlPassDlg * PassDialog[MAX_PASSES]; - - //////////////////////////////////////////////////////////////////////// - // Material dialog interface - //////////////////////////////////////////////////////////////////////// - IMtlParams * IParams; // interface to the material editor - GameMtl * TheMtl; // current mtl being edited. - - //////////////////////////////////////////////////////////////////////// - // Member variables - //////////////////////////////////////////////////////////////////////// - TimeValue CurTime; - int IsActive; - - friend BOOL CALLBACK DisplacementMapDlgProc(HWND, UINT, WPARAM,LPARAM); - friend BOOL CALLBACK SurfaceTypePanelDlgProc(HWND, UINT, WPARAM,LPARAM); - friend BOOL CALLBACK PassCountPanelDlgProc(HWND, UINT, WPARAM,LPARAM); - friend class GameMtl; -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlForm.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtlForm.cpp deleted file mode 100644 index 463f209352..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlForm.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlForm.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/23/98 6:21p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMtlFormClass::GameMtlFormClass -- constructor * - * GameMtlFormClass::SetThing -- Set the material being edited by this form * - * GameMtlFormClass::GetThing -- get the material being edited by this form * - * GameMtlFormClass::DeleteThis -- delete myself * - * GameMtlFormClass::ClassID -- returns the classID of the object being edited * - * GameMtlFormClass::SetTime -- set the current time * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "GameMtlForm.h" -#include "gamemtl.h" - - -/*********************************************************************************************** - * GameMtlFormClass::GameMtlFormClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlFormClass::GameMtlFormClass -( - IMtlParams * imtl_params, - GameMtl * mtl, - int pass -) -{ - IParams = imtl_params; - TheMtl = mtl; - PassIndex = pass; -} - - -/*********************************************************************************************** - * GameMtlFormClass::SetThing -- Set the material being edited by this form * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlFormClass::SetThing(ReferenceTarget * target) -{ - assert (target->SuperClassID()==MATERIAL_CLASS_ID); - assert (target->ClassID()==GameMaterialClassID); - - TheMtl = (GameMtl *)target; -} - - -/*********************************************************************************************** - * GameMtlFormClass::GetThing -- get the material being edited by this form * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -ReferenceTarget * GameMtlFormClass::GetThing(void) -{ - return (ReferenceTarget*)TheMtl; -} - - -/*********************************************************************************************** - * GameMtlFormClass::DeleteThis -- delete myself * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlFormClass::DeleteThis(void) -{ - delete this; -} - - -/*********************************************************************************************** - * GameMtlFormClass::ClassID -- returns the classID of the object being edited * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -Class_ID GameMtlFormClass::ClassID() -{ - return GameMaterialClassID; -} - - -/*********************************************************************************************** - * GameMtlFormClass::SetTime -- set the current time * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlFormClass::SetTime(TimeValue t) -{ - // child dialog classes don't have to support - // the SetTime function. -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlForm.h b/Generals/Code/Tools/WW3D/max2w3d/GameMtlForm.h deleted file mode 100644 index 18884ad75d..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlForm.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlForm.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/13/98 10:26a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#ifndef GAMEMTLFORM_H -#define GAMEMTLFORM_H - -#include "FormClass.h" - -class GameMtl; - -class GameMtlFormClass : public FormClass -{ -public: - GameMtlFormClass(IMtlParams * imtl_params,GameMtl * mtl,int pass); - - void SetThing(ReferenceTarget *m); - ReferenceTarget* GetThing(void); - void DeleteThis(void); - Class_ID ClassID(void); - void SetTime(TimeValue t); - -protected: - - IMtlParams * IParams; // interface to the material editor - GameMtl * TheMtl; // current mtl being edited. - int PassIndex; // material pass that this form edits -}; - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp deleted file mode 100644 index b178f6a2d9..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Bay/Tools/max2w3d/GameMtlPassDlg.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 10/22/99 9:54a $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * PassDlgProc -- dialog proc which thunks into a GameMtlPassDlg * - * GameMtlPassDlg::GameMtlPassDlg -- constructor * - * GameMtlPassDlg::~GameMtlPassDlg -- destructor * - * GameMtlPassDlg::DialogProc -- windows message handler * - * GameMtlPassDlg::Invalidate -- invalidate the dialog * - * GameMtlPassDlg::ReloadDialog -- update the contents of all of the controls * - * GameMtlPassDlg::ClassID -- returns classID of the object being edited * - * GameMtlPassDlg::SetThing -- set the material being edited * - * GameMtlPassDlg::ActivateDlg -- activate or deactivate the dialog * - * GameMtlPassDlg::SetTime -- set the current time * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "GameMtlPassDlg.h" -#include "dllmain.h" -#include "resource.h" -#include "gamemtl.h" -#include "GameMtlDlg.h" -#include "GameMtlShaderDlg.h" -#include "PS2GameMtlShaderDlg.h" -#include "GameMtlTextureDlg.h" -#include "GameMtlVertexMaterialDlg.h" -#include "w3d_file.h" - - -static int _Pass_Index_To_Flag[] = -{ - GAMEMTL_PASS0_ROLLUP_OPEN, - GAMEMTL_PASS1_ROLLUP_OPEN, - GAMEMTL_PASS2_ROLLUP_OPEN, - GAMEMTL_PASS3_ROLLUP_OPEN, -}; - - -/*********************************************************************************************** - * PassDlgProc -- dialog proc which thunks into a GameMtlPassDlg * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -static BOOL CALLBACK PassDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - GameMtlPassDlg *theDlg; - - if (msg==WM_INITDIALOG) { - theDlg = (GameMtlPassDlg*)lParam; - theDlg->HwndPanel = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlPassDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - return theDlg->DialogProc(hwndDlg,msg,wParam,lParam); -} - - -/*********************************************************************************************** - * GameMtlPassDlg::GameMtlPassDlg -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlPassDlg::GameMtlPassDlg(HWND hwMtlEdit, IMtlParams *imp, GameMtl *m,int pass) -{ - HwndEdit = hwMtlEdit; - TheMtl = m; - IParams = imp; - PassIndex = pass; - - char title[200]; - sprintf(title, "Pass %d", pass + 1); - - HwndPanel = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_PASS), - PassDlgProc, - title, - (LPARAM)this, - TheMtl->Get_Flag(_Pass_Index_To_Flag[PassIndex]) ? 0 : APPENDROLL_CLOSED - ); -} - - -/*********************************************************************************************** - * GameMtlPassDlg::~GameMtlPassDlg -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlPassDlg::~GameMtlPassDlg() -{ - TheMtl->Set_Flag(_Pass_Index_To_Flag[PassIndex],IParams->IsRollupPanelOpen(HwndPanel)); - IParams->DeleteRollupPage(HwndPanel); - SetWindowLong(HwndPanel, GWL_USERDATA, NULL); -} - - -/*********************************************************************************************** - * GameMtlPassDlg::DialogProc -- windows message handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -BOOL GameMtlPassDlg::DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - int i=0; - int id = LOWORD(wParam); - int code = HIWORD(wParam); - - switch (message) { - - case WM_INITDIALOG: - { - Page[0] = new GameMtlVertexMaterialDlg(HwndPanel,IParams,TheMtl,PassIndex); - if (TheMtl->Get_Shader_Type() == GameMtl::STE_PC_SHADER) { - Page[1] = new GameMtlShaderDlg(HwndPanel,IParams,TheMtl,PassIndex); - } else { - // The PS2 shader is different. - Page[1] = new PS2GameMtlShaderDlg(HwndPanel,IParams,TheMtl,PassIndex); - } - - Page[2] = new GameMtlTextureDlg(HwndPanel,IParams,TheMtl,PassIndex); - - for (i=0; iGet_Hwnd(); - - // set the tab names - char name[64]; - ::GetWindowText(hwnd,name,sizeof(name)); - TC_ITEM tcitem = { TCIF_TEXT,0,0,name,0 }; - TabCtrl_InsertItem(GetDlgItem(HwndPanel,IDC_GAMEMTL_TAB),i,&tcitem); - } - - // Get the display rectangle of the tab control - RECT rect; - ::GetWindowRect(GetDlgItem(HwndPanel,IDC_GAMEMTL_TAB),&rect); - TabCtrl_AdjustRect(GetDlgItem(HwndPanel,IDC_GAMEMTL_TAB),FALSE, &rect); - - // Convert the display rectangle from screen to client coords - ScreenToClient(HwndPanel,(POINT *)(&rect)); - ScreenToClient(HwndPanel, ((LPPOINT)&rect) + 1); - - for (i=0; iGet_Hwnd(); - - // Loop through all the tabs in the property sheet - // Get a pointer to this tab - SetWindowPos( hwnd, - NULL, - rect.left, rect.top, - rect.right - rect.left, rect.bottom - rect.top, - SWP_NOZORDER); - } - - CurPage = 0; - TabCtrl_SetCurSel(GetDlgItem(HwndPanel,IDC_GAMEMTL_TAB),CurPage); - Page[CurPage]->Show(); - - break; - } - - case WM_PAINT: - { - if (!Valid) { - Valid = TRUE; - ReloadDialog(); - } - return FALSE; - } - - case WM_NOTIFY: - { - NMHDR * header = (NMHDR *)lParam; - - switch(header->code) { - case TCN_SELCHANGE: - { - int sel = TabCtrl_GetCurSel(GetDlgItem(HwndPanel,IDC_GAMEMTL_TAB)); - Page[sel]->Show(); - - for (int i=0; i < PAGE_COUNT; i++) { - if (i != sel) Page[i]->Show(false); - } - CurPage = sel; - TheMtl->Set_Current_Page(PassIndex,CurPage); - } - }; - break; - } - } - return FALSE; -} - - -/*********************************************************************************************** - * GameMtlPassDlg::Invalidate -- invalidate the dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlPassDlg::Invalidate() -{ - Valid = FALSE; - InvalidateRect(HwndPanel,NULL,0); -} - - -/*********************************************************************************************** - * GameMtlPassDlg::ReloadDialog -- update the contents of all of the controls * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlPassDlg::ReloadDialog() -{ - int i; - - DebugPrint("GameMtlPassDlg::ReloadDialog\n"); - Interval v; - TheMtl->Update(IParams->GetTime(),v); - - for (i=0; iReloadDialog(); - } - - CurPage = TheMtl->Get_Current_Page(PassIndex); - TabCtrl_SetCurSel(GetDlgItem(HwndPanel,IDC_GAMEMTL_TAB),CurPage); - Page[CurPage]->Show(); - for (i=0; i < PAGE_COUNT; i++) { - if (i != CurPage) Page[i]->Show(false); - } -} - - -/*********************************************************************************************** - * GameMtlPassDlg::ClassID -- returns classID of the object being edited * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -Class_ID GameMtlPassDlg::ClassID() -{ - return GameMaterialClassID; -} - - -/*********************************************************************************************** - * GameMtlPassDlg::SetThing -- set the material being edited * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlPassDlg::SetThing(ReferenceTarget* target) -{ - // Note, parent will "reload" when our "thing" changes :-) - assert (target->SuperClassID()==MATERIAL_CLASS_ID); - assert (target->ClassID()==GameMaterialClassID); - - TheMtl = (GameMtl *)target; - - for (int i=0; iSetThing(target); - } -} - - -/*********************************************************************************************** - * GameMtlPassDlg::ActivateDlg -- activate or deactivate the dialog * - * * - * some of the custom max controls need to be activated and deactivated * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlPassDlg::ActivateDlg(BOOL onoff) -{ - for (int i=0; iActivateDlg(onoff); - } -} - - -/*********************************************************************************************** - * GameMtlPassDlg::SetTime -- set the current time * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlPassDlg::SetTime(TimeValue t) -{ - // parent dialog class keeps track of the validty and we - // don't have to do anything in this function (it will never - // be called in fact) -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.h b/Generals/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.h deleted file mode 100644 index 5dd8a2aa73..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlPassDlg.h +++ /dev/null @@ -1,97 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlPassDlg.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/17/98 1:32p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - - -#ifndef GAMEMTLPASSDLG_H -#define GAMEMTLPASSDLG_H - -#include - -class GameMtl; -class GameMtlFormClass; - -/* -** The GameMtlPassDlg will contain a Tab Control which switches between -** editing the VertexMaterial parameters, the Shader parameters and the -** Texture parameters. -*/ -class GameMtlPassDlg: public ParamDlg -{ -public: - - GameMtlPassDlg(HWND hwMtlEdit, IMtlParams *imp, GameMtl *m,int pass); - ~GameMtlPassDlg(); - - BOOL DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); - - void Invalidate(); - void UpdateMtlDisplay() { IParams->MtlChanged(); } - - void ReloadDialog(); - Class_ID ClassID(); - void SetThing(ReferenceTarget* target); - ReferenceTarget * GetThing() { return (ReferenceTarget *)TheMtl; } - void DeleteThis() { delete this; } - void SetTime(TimeValue t); - void ActivateDlg(BOOL onOff); - - enum { PAGE_COUNT = 3 }; - - //////////////////////////////////////////////////////////////////////// - // Material dialog interface - //////////////////////////////////////////////////////////////////////// - IMtlParams * IParams; // interface to the material editor - GameMtl * TheMtl; // current mtl being edited. - - //////////////////////////////////////////////////////////////////////// - // Windows handles - //////////////////////////////////////////////////////////////////////// - HWND HwndEdit; // window handle of the materials editor dialog - HWND HwndPanel; // Rollup parameters panel - - //////////////////////////////////////////////////////////////////////// - // Variables - //////////////////////////////////////////////////////////////////////// - int PassIndex; - int CurPage; - BOOL Valid; - - GameMtlFormClass* Page[PAGE_COUNT]; -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp deleted file mode 100644 index c9859f4cff..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.cpp +++ /dev/null @@ -1,397 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlShaderDlg.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 2/26/99 7:23p $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMtlShaderDlg::GameMtlShaderDlg -- constructor * - * GameMtlShaderDlg::~GameMtlShaderDlg -- destructor * - * GameMtlShaderDlg::Dialog_Proc -- windows message handler * - * GameMtlShaderDlg::ReloadDialog -- reload the contents of all of the controls * - * GameMtlShaderDlg::ActivateDlg -- activate/deactivate the dialog * - * GameMtlShaderDlg::Apply_Preset -- apply a preset shader setting * - * GameMtlShaderDlg::Set_Preset -- determine preset shader setting from game material * - * GameMtlShaderDlg::CompareShaderToBlendPreset -- compare preset to game material shader * - * GameMtlShaderDlg::Set_Advanced_Defaults -- set advanced settings to defaults * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "GameMtlShaderDlg.h" -#include "GameMtlDlg.h" -#include "gamemtl.h" -#include "resource.h" - -/* -** Shader Blend Setting Presets -*/ - -// Note: the array has NUM_SHADER_BLEND_PRESETS + 1 entries (due to the 'Custom' entry). - -#define NUM_SHADER_BLEND_PRESETS 8 - -static char * _ShaderBlendSettingPresetNames[NUM_SHADER_BLEND_PRESETS + 1] = -{ - "Opaque", - "Add", - "Multiply", - "Multiply and Add", - "Screen", - "Alpha Blend", - "Alpha Test", - "Alpha Test and Blend", - "------ Custom -----" -}; -struct ShaderBlendSettingPreset -{ - int SrcBlend; - int DestBlend; - bool DepthMask; - bool AlphaTest; -}; -static const ShaderBlendSettingPreset ShaderBlendSettingPresets[NUM_SHADER_BLEND_PRESETS] = { - {W3DSHADER_SRCBLENDFUNC_ONE, W3DSHADER_DESTBLENDFUNC_ZERO, true, false}, // Opaque - {W3DSHADER_SRCBLENDFUNC_ONE, W3DSHADER_DESTBLENDFUNC_ONE, false, false}, // Add - {W3DSHADER_SRCBLENDFUNC_ZERO, W3DSHADER_DESTBLENDFUNC_SRC_COLOR, false, false}, // Multiply - {W3DSHADER_SRCBLENDFUNC_ONE, W3DSHADER_DESTBLENDFUNC_SRC_COLOR, false, false}, // Multiply and Add - {W3DSHADER_SRCBLENDFUNC_ONE, W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_COLOR, false, false}, // Screen - {W3DSHADER_SRCBLENDFUNC_SRC_ALPHA, W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA, false, false}, // Alpha Blend - {W3DSHADER_SRCBLENDFUNC_ONE, W3DSHADER_DESTBLENDFUNC_ZERO, true, true}, // Alpha Test - {W3DSHADER_SRCBLENDFUNC_SRC_ALPHA, W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA, true, true} // Alpha Test and Blend -}; - - -/*********************************************************************************************** - * GameMtlShaderDlg::GameMtlShaderDlg -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlShaderDlg::GameMtlShaderDlg -( - HWND parent, - IMtlParams * imp, - GameMtl * mtl, - int pass -) : - GameMtlFormClass(imp,mtl,pass) -{ - Create_Form(parent,IDD_GAMEMTL_SHADER); -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::~GameMtlShaderDlg -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -GameMtlShaderDlg::~GameMtlShaderDlg() -{ -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::Dialog_Proc -- windows message handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -BOOL GameMtlShaderDlg::Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam) -{ - int cursel; - int i; - int id = LOWORD(wparam); - int code = HIWORD(wparam); - - switch (message) - { - - case WM_INITDIALOG: - for(i = 0; i <= NUM_SHADER_BLEND_PRESETS; i++) { - SendDlgItemMessage(dlg_wnd,IDC_PRESET_COMBO,CB_ADDSTRING,0,(LONG)_ShaderBlendSettingPresetNames[i]); - } - SendDlgItemMessage(dlg_wnd,IDC_PRESET_COMBO,CB_SETCURSEL,0,0); - break; - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(dlg_wnd,message,wparam,lparam); - } - return FALSE; - - case WM_COMMAND: - { - if (code == CBN_SELCHANGE) { - - switch (id) - { - case IDC_DEPTHCOMPARE_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DEPTHCOMPARE_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Depth_Compare(PassIndex,cursel); - break; - case IDC_DESTBLEND_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DESTBLEND_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Dest_Blend(PassIndex,cursel); - TheMtl->Notify_Changed(); - Set_Preset(); - break; - case IDC_PRIGRADIENT_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_PRIGRADIENT_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Pri_Gradient(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_SECGRADIENT_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_SECGRADIENT_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Sec_Gradient(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_SRCBLEND_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_SRCBLEND_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Src_Blend(PassIndex,cursel); - TheMtl->Notify_Changed(); - Set_Preset(); - break; - case IDC_DETAILCOLOR_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DETAILCOLOR_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Detail_Color_Func(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_DETAILALPHA_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DETAILALPHA_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Detail_Alpha_Func(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_PRESET_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_PRESET_COMBO,CB_GETCURSEL,0,0); - Apply_Preset(cursel); - break; - } - - } else { - - switch(id) { - - case IDC_DEPTHMASK_CHECK: - if (SendDlgItemMessage(dlg_wnd,IDC_DEPTHMASK_CHECK,BM_GETCHECK,0,0)) { - TheMtl->Set_Depth_Mask(PassIndex,W3DSHADER_DEPTHMASK_WRITE_ENABLE); - } else { - TheMtl->Set_Depth_Mask(PassIndex,W3DSHADER_DEPTHMASK_WRITE_DISABLE); - } - Set_Preset(); - break; - - case IDC_ALPHATEST_CHECK: - if (SendDlgItemMessage(dlg_wnd,IDC_ALPHATEST_CHECK,BM_GETCHECK,0,0)) { - TheMtl->Set_Alpha_Test(PassIndex,W3DSHADER_ALPHATEST_ENABLE); - } else { - TheMtl->Set_Alpha_Test(PassIndex,W3DSHADER_ALPHATEST_DISABLE); - } - Set_Preset(); - break; - - case IDC_SHADER_DEFAULTS_BUTTON: - Set_Advanced_Defaults(); - break; - } - } - } - } - - return FALSE; -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::ReloadDialog -- reload the contents of all of the controls * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlShaderDlg::ReloadDialog(void) -{ - DebugPrint("GameMtlShaderDlg::ReloadDialog\n"); - SendDlgItemMessage(m_hWnd, IDC_DESTBLEND_COMBO, CB_SETCURSEL, TheMtl->Get_Dest_Blend(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_SRCBLEND_COMBO, CB_SETCURSEL, TheMtl->Get_Src_Blend(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_PRIGRADIENT_COMBO, CB_SETCURSEL, TheMtl->Get_Pri_Gradient(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_SECGRADIENT_COMBO, CB_SETCURSEL, TheMtl->Get_Sec_Gradient(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_DEPTHCOMPARE_COMBO, CB_SETCURSEL, TheMtl->Get_Depth_Compare(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_DETAILCOLOR_COMBO, CB_SETCURSEL, TheMtl->Get_Detail_Color_Func(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_DETAILALPHA_COMBO, CB_SETCURSEL, TheMtl->Get_Detail_Alpha_Func(PassIndex), 0 ); - Set_Preset(); - - SetCheckBox(m_hWnd,IDC_DEPTHMASK_CHECK, TheMtl->Get_Depth_Mask(PassIndex)); - SetCheckBox(m_hWnd,IDC_ALPHATEST_CHECK, TheMtl->Get_Alpha_Test(PassIndex)); -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::ActivateDlg -- activate/deactivate the dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlShaderDlg::ActivateDlg(BOOL onoff) -{ - // shader has no color swatches which need to be activated... -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::Apply_Preset -- apply a preset shader setting * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlShaderDlg::Apply_Preset(int preset_index) -{ - if (preset_index < 0 || preset_index >= NUM_SHADER_BLEND_PRESETS) return; - - const ShaderBlendSettingPreset &preset = ShaderBlendSettingPresets[preset_index]; - - TheMtl->Set_Src_Blend(PassIndex, preset.SrcBlend); - - TheMtl->Set_Dest_Blend(PassIndex, preset.DestBlend); - - int depth_mask = preset.DepthMask ? W3DSHADER_DEPTHMASK_WRITE_ENABLE : W3DSHADER_DEPTHMASK_WRITE_DISABLE; - TheMtl->Set_Depth_Mask(PassIndex, depth_mask); - - int alpha_test = preset.AlphaTest ? W3DSHADER_ALPHATEST_ENABLE : W3DSHADER_ALPHATEST_DISABLE; - TheMtl->Set_Alpha_Test(PassIndex, alpha_test); - - TheMtl->Notify_Changed(); - ReloadDialog(); -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::Set_Preset -- determine preset shader setting from game material * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/26/99 NH : Created. * - *=============================================================================================*/ -void GameMtlShaderDlg::Set_Preset(void) -{ - for (int i = 0; i < NUM_SHADER_BLEND_PRESETS; i++) { - if (CompareShaderToBlendPreset(ShaderBlendSettingPresets[i])) break; - } - SendDlgItemMessage(m_hWnd, IDC_PRESET_COMBO, CB_SETCURSEL, i, 0); -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::CompareShaderToBlendPreset -- compare preset to game material shader * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/26/99 NH : Created. * - *=============================================================================================*/ -bool GameMtlShaderDlg::CompareShaderToBlendPreset(const ShaderBlendSettingPreset &blend_preset) -{ - if (TheMtl->Get_Src_Blend(PassIndex) != blend_preset.SrcBlend) return false; - if (TheMtl->Get_Dest_Blend(PassIndex) != blend_preset.DestBlend) return false; - bool depthmask = TheMtl->Get_Depth_Mask(PassIndex) != W3DSHADER_DEPTHMASK_WRITE_DISABLE; - if (depthmask != blend_preset.DepthMask) return false; - bool alphatest = TheMtl->Get_Alpha_Test(PassIndex) != W3DSHADER_ALPHATEST_DISABLE; - if (alphatest != blend_preset.AlphaTest) return false; - return true; -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::Set_Advanced_Defaults -- set advanced settings to defaults * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/26/99 NH : Created. * - *=============================================================================================*/ -void GameMtlShaderDlg::Set_Advanced_Defaults(void) -{ - TheMtl->Set_Pri_Gradient(PassIndex, W3DSHADER_PRIGRADIENT_DEFAULT); - TheMtl->Set_Sec_Gradient(PassIndex, W3DSHADER_SECGRADIENT_DEFAULT); - TheMtl->Set_Depth_Compare(PassIndex, W3DSHADER_DEPTHCOMPARE_DEFAULT); - TheMtl->Set_Detail_Color_Func(PassIndex, W3DSHADER_DETAILCOLORFUNC_DEFAULT); - TheMtl->Set_Detail_Alpha_Func(PassIndex, W3DSHADER_DETAILALPHAFUNC_DEFAULT); - - TheMtl->Notify_Changed(); - ReloadDialog(); -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.h b/Generals/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.h deleted file mode 100644 index 77b51300c8..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlShaderDlg.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlShaderDlg.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 2/26/99 7:00p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#ifndef GAMEMTLSHADERDLG_H -#define GAMEMTLSHADERDLG_H - -#include -#include "GameMtlForm.h" - - -class GameMtl; -struct ShaderBlendSettingPreset; - -class GameMtlShaderDlg : public GameMtlFormClass -{ - -public: - - GameMtlShaderDlg(HWND parent, IMtlParams * imp, GameMtl * m, int pass); - ~GameMtlShaderDlg(); - - virtual BOOL Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam); - - void ActivateDlg(BOOL onOff); - void ReloadDialog(void); - -private: - - void Apply_Preset(int preset_index); - void Set_Preset(void); - bool CompareShaderToBlendPreset(const ShaderBlendSettingPreset &blend_preset); - void Set_Advanced_Defaults(void); -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp deleted file mode 100644 index f6dd31be76..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.cpp +++ /dev/null @@ -1,667 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlTextureDlg.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/14/00 1:47p $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMtlTextureDlg::GameMtlTextureDlg -- constructor * - * GameMtlTextureDlg::~GameMtlTextureDlg -- destructor * - * GameMtlTextureDlg::Dialog_Proc -- windows message handler * - * GameMtlTextureDlg::ReloadDialog -- reload the contents of all of the controls in this dia * - * GameMtlTextureDlg::ActivateDlg -- activate/deactivate this dialog * - * GameMtlTextureDlg::Enable_Stage -- enable or disable a texture stage * - * GameMtlTextureDlg::Update_Texture_Buttons -- update the texture buttons text * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - - - -#include "GameMtlTextureDlg.h" -#include "gamemtl.h" -#include "dllmain.h" -#include "resource.h" -#include -#include -#include - - -/*********************************************************************************************** - * GameMtlTextureDlg::GameMtlTextureDlg -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlTextureDlg::GameMtlTextureDlg -( - HWND parent, - IMtlParams * imp, - GameMtl * mtl, - int pass -) : - GameMtlFormClass(imp,mtl,pass) -{ - Stage0FramesSpin = NULL; - Stage1FramesSpin = NULL; - Stage0RateSpin = NULL; - Stage1RateSpin = NULL; - - Stage0PublishButton = NULL; - Stage1PublishButton = NULL; - Stage0ClampUButton = NULL; - Stage1ClampUButton = NULL; - Stage0ClampVButton = NULL; - Stage1ClampVButton = NULL; - Stage0NoLODButton = NULL; - Stage1NoLODButton = NULL; - Stage0AlphaBitmapButton = NULL; - Stage1AlphaBitmapButton = NULL; - Stage0DisplayButton = NULL; - Stage1DisplayButton = NULL; - - if (mtl->Get_Shader_Type() == GameMtl::STE_PC_SHADER) { - Create_Form(parent,IDD_GAMEMTL_TEXTURES); - } else { - // Use the PS2 dialog. It is the same but it disables some functions that aren't - // supported yet. - Create_Form(parent,IDD_GAMEMTL_PS2_TEXTURES); - } -} - - -/*********************************************************************************************** - * GameMtlTextureDlg::~GameMtlTextureDlg -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlTextureDlg::~GameMtlTextureDlg() -{ - assert(Stage0FramesSpin && Stage1FramesSpin && Stage0RateSpin && Stage1RateSpin); - ReleaseISpinner(Stage0FramesSpin); - ReleaseISpinner(Stage1FramesSpin); - ReleaseISpinner(Stage0RateSpin); - ReleaseISpinner(Stage1RateSpin); - - ReleaseICustButton(Stage0PublishButton); - ReleaseICustButton(Stage1PublishButton); - ReleaseICustButton(Stage0ClampUButton); - ReleaseICustButton(Stage1ClampUButton); - ReleaseICustButton(Stage0ClampVButton); - ReleaseICustButton(Stage1ClampVButton); - ReleaseICustButton(Stage0NoLODButton); - ReleaseICustButton(Stage1NoLODButton); - ReleaseICustButton(Stage0AlphaBitmapButton); - ReleaseICustButton(Stage1AlphaBitmapButton); - ReleaseICustButton(Stage0DisplayButton); - ReleaseICustButton(Stage1DisplayButton); -} - - -/*********************************************************************************************** - * GameMtlTextureDlg::Dialog_Proc -- windows message handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - * 10/6/1999 MLL: Turned off the display button when the texture is turned off. * - *=============================================================================================*/ -BOOL GameMtlTextureDlg::Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam) -{ - int cursel; - int id = LOWORD(wparam); - int code = HIWORD(wparam); - - switch (message) - { - case WM_INITDIALOG: - { - Stage0FramesSpin = SetupIntSpinner( dlg_wnd, - IDC_STAGE0_FRAMES_SPIN, - IDC_STAGE0_FRAMES_EDIT, - 1,999, - TheMtl->Get_Texture_Frame_Count(PassIndex,0) ); - - Stage0RateSpin = SetupFloatSpinner( dlg_wnd, - IDC_STAGE0_RATE_SPIN, - IDC_STAGE0_RATE_EDIT, - 0.0f,60.0f, - TheMtl->Get_Texture_Frame_Rate(PassIndex,0), - 1.0f ); - - Stage1FramesSpin = SetupIntSpinner( dlg_wnd, - IDC_STAGE1_FRAMES_SPIN, - IDC_STAGE1_FRAMES_EDIT, - 1,999, - TheMtl->Get_Texture_Frame_Count(PassIndex,1) ); - - Stage1RateSpin = SetupFloatSpinner( dlg_wnd, - IDC_STAGE1_RATE_SPIN, - IDC_STAGE1_RATE_EDIT, - 0.0f,60.0f, - TheMtl->Get_Texture_Frame_Rate(PassIndex,1), - 1.0f ); - - Stage0PublishButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE0_PUBLISH_BUTTON)); - Stage0PublishButton->SetType(CBT_CHECK); - Stage0PublishButton->SetHighlightColor(GREEN_WASH); - Stage0PublishButton->SetCheck(TheMtl->Get_Texture_Publish(PassIndex,0)); - Stage0PublishButton->SetText(Get_String(IDS_PUBLISH)); - - Stage1PublishButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE1_PUBLISH_BUTTON)); - Stage1PublishButton->SetType(CBT_CHECK); - Stage1PublishButton->SetHighlightColor(GREEN_WASH); - Stage1PublishButton->SetCheck(TheMtl->Get_Texture_Publish(PassIndex,1)); - Stage1PublishButton->SetText(Get_String(IDS_PUBLISH)); - - Stage0ClampUButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE0_CLAMP_U_BUTTON)); - Stage0ClampUButton->SetType(CBT_CHECK); - Stage0ClampUButton->SetHighlightColor(GREEN_WASH); - Stage0ClampUButton->SetCheck(TheMtl->Get_Texture_Clamp_U(PassIndex,0)); - Stage0ClampUButton->SetText(Get_String(IDS_CLAMP_U)); - - Stage1ClampUButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE1_CLAMP_U_BUTTON)); - Stage1ClampUButton->SetType(CBT_CHECK); - Stage1ClampUButton->SetHighlightColor(GREEN_WASH); - Stage1ClampUButton->SetCheck(TheMtl->Get_Texture_Clamp_U(PassIndex,1)); - Stage1ClampUButton->SetText(Get_String(IDS_CLAMP_U)); - - Stage0ClampVButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE0_CLAMP_V_BUTTON)); - Stage0ClampVButton->SetType(CBT_CHECK); - Stage0ClampVButton->SetHighlightColor(GREEN_WASH); - Stage0ClampVButton->SetCheck(TheMtl->Get_Texture_Clamp_V(PassIndex,0)); - Stage0ClampVButton->SetText(Get_String(IDS_CLAMP_V)); - - Stage1ClampVButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE1_CLAMP_V_BUTTON)); - Stage1ClampVButton->SetType(CBT_CHECK); - Stage1ClampVButton->SetHighlightColor(GREEN_WASH); - Stage1ClampVButton->SetCheck(TheMtl->Get_Texture_Clamp_V(PassIndex,1)); - Stage1ClampVButton->SetText(Get_String(IDS_CLAMP_V)); - - Stage0NoLODButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE0_NOLOD_BUTTON)); - Stage0NoLODButton->SetType(CBT_CHECK); - Stage0NoLODButton->SetHighlightColor(GREEN_WASH); - Stage0NoLODButton->SetCheck(TheMtl->Get_Texture_No_LOD(PassIndex,0)); - Stage0NoLODButton->SetText(Get_String(IDS_NO_LOD)); - - Stage1NoLODButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE1_NOLOD_BUTTON)); - Stage1NoLODButton->SetType(CBT_CHECK); - Stage1NoLODButton->SetHighlightColor(GREEN_WASH); - Stage1NoLODButton->SetCheck(TheMtl->Get_Texture_No_LOD(PassIndex,0)); - Stage1NoLODButton->SetText(Get_String(IDS_NO_LOD)); - - Stage0AlphaBitmapButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE0_ALPHA_BITMAP_BUTTON)); - Stage0AlphaBitmapButton->SetType(CBT_CHECK); - Stage0AlphaBitmapButton->SetHighlightColor(GREEN_WASH); - Stage0AlphaBitmapButton->SetCheck(TheMtl->Get_Texture_Alpha_Bitmap(PassIndex,0)); - Stage0AlphaBitmapButton->SetText(Get_String(IDS_ALPHA_BITMAP)); - - Stage1AlphaBitmapButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE1_ALPHA_BITMAP_BUTTON)); - Stage1AlphaBitmapButton->SetType(CBT_CHECK); - Stage1AlphaBitmapButton->SetHighlightColor(GREEN_WASH); - Stage1AlphaBitmapButton->SetCheck(TheMtl->Get_Texture_Alpha_Bitmap(PassIndex,1)); - Stage1AlphaBitmapButton->SetText(Get_String(IDS_ALPHA_BITMAP)); - - Stage0DisplayButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE0_DISPLAY_BUTTON)); - Stage0DisplayButton->SetType(CBT_CHECK); - Stage0DisplayButton->SetHighlightColor(GREEN_WASH); - Stage0DisplayButton->SetCheck(TheMtl->Get_Texture_Display(PassIndex,0)); - Stage0DisplayButton->SetText(Get_String(IDS_DISPLAY)); - - Stage1DisplayButton = GetICustButton(GetDlgItem(dlg_wnd, IDC_STAGE1_DISPLAY_BUTTON)); - Stage1DisplayButton->SetType(CBT_CHECK); - Stage1DisplayButton->SetHighlightColor(GREEN_WASH); - Stage1DisplayButton->SetCheck(TheMtl->Get_Texture_Display(PassIndex,1)); - Stage1DisplayButton->SetText(Get_String(IDS_DISPLAY)); - break; - } - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(dlg_wnd,message,wparam,lparam); - return FALSE; - } - - case CC_SPINNER_CHANGE: - { - TheMtl->Set_Texture_Frame_Count( PassIndex, 0, - Stage0FramesSpin->GetIVal()); - - TheMtl->Set_Texture_Frame_Rate( PassIndex, 0, - Stage0RateSpin->GetFVal()); - - TheMtl->Set_Texture_Frame_Count( PassIndex, 1, - Stage1FramesSpin->GetIVal()); - - TheMtl->Set_Texture_Frame_Rate( PassIndex, 1, - Stage1RateSpin->GetFVal()); - break; - } - - case CC_SPINNER_BUTTONUP: - { - TheMtl->Notify_Changed(); - break; - } - - case WM_COMMAND: - { - switch (id) - { - case IDC_STAGE0_BUTTON: - { - BitmapInfo bmi; - BitmapTex * texture; - - if (TheManager->SelectFileInput(&bmi, m_hWnd)) { - texture = NewDefaultBitmapTex(); - if (texture) { - - BOOL disp = TheMtl->Get_Texture_Display(PassIndex,0); - if (disp) { - TheMtl->Set_Texture_Display(PassIndex,0,FALSE); - } - - texture->SetMapName((char *)bmi.Name()); - int texmap_index = TheMtl->pass_stage_to_texmap_index(PassIndex,0); - TheMtl->SetSubTexmap(texmap_index,texture); - Update_Texture_Buttons(); - TheMtl->Notify_Changed(); - - if (disp) { - TheMtl->Set_Texture_Display(PassIndex,0,TRUE); - TheMtl->Notify_Changed(); - } - } - } - break; - } - case IDC_STAGE1_BUTTON: - { - BitmapInfo bmi; - BitmapTex * texture; - - if (TheManager->SelectFileInput(&bmi, m_hWnd)) { - texture = NewDefaultBitmapTex(); - if (texture) { - - BOOL disp = TheMtl->Get_Texture_Display(PassIndex,1); - if (disp) { - TheMtl->Set_Texture_Display(PassIndex,1,FALSE); - } - - texture->SetMapName((char *)bmi.Name()); - int texmap_index = TheMtl->pass_stage_to_texmap_index(PassIndex,1); - TheMtl->SetSubTexmap(texmap_index,texture); - Update_Texture_Buttons(); - TheMtl->Notify_Changed(); - - if (disp) { - TheMtl->Set_Texture_Display(PassIndex,1,TRUE); - TheMtl->Notify_Changed(); - } - } - } - break; - } - case IDC_STAGE0_ENABLE: - { - int checkbox = GetCheckBox(dlg_wnd,IDC_STAGE0_ENABLE); - Enable_Stage(0,(checkbox == TRUE ? true : false) ); - - // If the texture stage is turned off, turn off the Display button so that it won't - // show up in the viewport. - if (checkbox == FALSE) { - - TheMtl->Set_Texture_Display(PassIndex, 0, FALSE); - TheMtl->Notify_Changed(); - } - break; - } - case IDC_STAGE1_ENABLE: - { - int checkbox = GetCheckBox(dlg_wnd,IDC_STAGE1_ENABLE); - - Enable_Stage(1,(checkbox == TRUE ? true : false) ); - - // If the texture stage is turned off, turn off the Display button so that it won't - // show up in the viewport. - if (checkbox == FALSE) { - - TheMtl->Set_Texture_Display(PassIndex, 1, FALSE); - TheMtl->Notify_Changed(); - } - break; - } - case IDC_STAGE0_PUBLISH_BUTTON: - { - TheMtl->Set_Texture_Publish(PassIndex,0,(Stage0PublishButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE1_PUBLISH_BUTTON: - { - TheMtl->Set_Texture_Publish(PassIndex,1,(Stage1PublishButton->IsChecked() ? TRUE : FALSE)); - break; - } - - case IDC_STAGE0_CLAMP_U_BUTTON: - { - TheMtl->Set_Texture_Clamp_U(PassIndex,0,(Stage0ClampUButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE1_CLAMP_U_BUTTON: - { - TheMtl->Set_Texture_Clamp_U(PassIndex,1,(Stage1ClampUButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE0_CLAMP_V_BUTTON: - { - TheMtl->Set_Texture_Clamp_V(PassIndex,0,(Stage0ClampVButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE1_CLAMP_V_BUTTON: - { - TheMtl->Set_Texture_Clamp_V(PassIndex,1,(Stage1ClampVButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE0_NOLOD_BUTTON: - { - TheMtl->Set_Texture_No_LOD(PassIndex,0,(Stage0NoLODButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE1_NOLOD_BUTTON: - { - TheMtl->Set_Texture_No_LOD(PassIndex,1,(Stage1NoLODButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE0_ALPHA_BITMAP_BUTTON: - { - TheMtl->Set_Texture_Alpha_Bitmap(PassIndex,0,(Stage0AlphaBitmapButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE1_ALPHA_BITMAP_BUTTON: - { - TheMtl->Set_Texture_Alpha_Bitmap(PassIndex,1,(Stage0AlphaBitmapButton->IsChecked() ? TRUE : FALSE)); - break; - } - case IDC_STAGE0_DISPLAY_BUTTON: - { - TheMtl->Set_Texture_Display(PassIndex,0,(Stage0DisplayButton->IsChecked() ? TRUE : FALSE)); - TheMtl->Notify_Changed(); - break; - } - case IDC_STAGE1_DISPLAY_BUTTON: - { - TheMtl->Set_Texture_Display(PassIndex,1,(Stage1DisplayButton->IsChecked() ? TRUE : FALSE)); - TheMtl->Notify_Changed(); - break; - } - case IDC_STAGE0_ANIM_COMBO: - { - if (code == CBN_SELCHANGE) { - cursel = SendDlgItemMessage(dlg_wnd,IDC_STAGE0_ANIM_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Texture_Anim_Type(PassIndex,0,cursel); - } - break; - } - case IDC_STAGE1_ANIM_COMBO: - { - if (code == CBN_SELCHANGE) { - cursel = SendDlgItemMessage(dlg_wnd,IDC_STAGE1_ANIM_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Texture_Anim_Type(PassIndex,1,cursel); - } - break; - } - case IDC_STAGE0_HINT_COMBO: - { - if (code == CBN_SELCHANGE) { - cursel = SendDlgItemMessage(dlg_wnd,IDC_STAGE0_HINT_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Texture_Hint(PassIndex,0,cursel); - } - break; - } - case IDC_STAGE1_HINT_COMBO: - { - if (code == CBN_SELCHANGE) { - cursel = SendDlgItemMessage(dlg_wnd,IDC_STAGE1_HINT_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Texture_Hint(PassIndex,1,cursel); - } - break; - } - - } - break; - } - } - - return FALSE; -} - - -/*********************************************************************************************** - * GameMtlTextureDlg::ReloadDialog -- reload the contents of all of the controls in this dialo * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlTextureDlg::ReloadDialog(void) -{ - DebugPrint("GameMtlTextureDlg::ReloadDialog\n"); - assert(Stage0FramesSpin && Stage1FramesSpin && Stage0RateSpin && Stage1RateSpin); - Stage0FramesSpin->SetValue(TheMtl->Get_Texture_Frame_Count(PassIndex,0),FALSE); - Stage1FramesSpin->SetValue(TheMtl->Get_Texture_Frame_Count(PassIndex,1),FALSE); - Stage0RateSpin->SetValue(TheMtl->Get_Texture_Frame_Rate(PassIndex,0),FALSE); - Stage1RateSpin->SetValue(TheMtl->Get_Texture_Frame_Rate(PassIndex,1),FALSE); - - SendDlgItemMessage( m_hWnd, - IDC_STAGE0_ANIM_COMBO, - CB_SETCURSEL, - TheMtl->Get_Texture_Anim_Type(PassIndex,0), 0 ); - - SendDlgItemMessage( m_hWnd, - IDC_STAGE1_ANIM_COMBO, - CB_SETCURSEL, - TheMtl->Get_Texture_Anim_Type(PassIndex,1), 0 ); - - SendDlgItemMessage( m_hWnd, - IDC_STAGE0_HINT_COMBO, - CB_SETCURSEL, - TheMtl->Get_Texture_Hint(PassIndex,0), 0 ); - - SendDlgItemMessage( m_hWnd, - IDC_STAGE1_HINT_COMBO, - CB_SETCURSEL, - TheMtl->Get_Texture_Hint(PassIndex,1), 0 ); - - SetCheckBox(m_hWnd,IDC_STAGE0_ENABLE, TheMtl->Get_Texture_Enable(PassIndex,0)); - SetCheckBox(m_hWnd,IDC_STAGE1_ENABLE, TheMtl->Get_Texture_Enable(PassIndex,1)); - - Stage0PublishButton->SetCheck(TheMtl->Get_Texture_Publish(PassIndex,0)); - Stage1PublishButton->SetCheck(TheMtl->Get_Texture_Publish(PassIndex,1)); - Stage0ClampUButton->SetCheck(TheMtl->Get_Texture_Clamp_U(PassIndex,0)); - Stage1ClampUButton->SetCheck(TheMtl->Get_Texture_Clamp_U(PassIndex,1)); - Stage0ClampVButton->SetCheck(TheMtl->Get_Texture_Clamp_V(PassIndex,0)); - Stage1ClampVButton->SetCheck(TheMtl->Get_Texture_Clamp_V(PassIndex,1)); - Stage0NoLODButton->SetCheck(TheMtl->Get_Texture_No_LOD(PassIndex,0)); - Stage1NoLODButton->SetCheck(TheMtl->Get_Texture_No_LOD(PassIndex,1)); - Stage0AlphaBitmapButton->SetCheck(TheMtl->Get_Texture_Alpha_Bitmap(PassIndex,0)); - Stage1AlphaBitmapButton->SetCheck(TheMtl->Get_Texture_Alpha_Bitmap(PassIndex,1)); - Stage0DisplayButton->SetCheck(TheMtl->Get_Texture_Display(PassIndex,0)); - Stage1DisplayButton->SetCheck(TheMtl->Get_Texture_Display(PassIndex,1)); - - Update_Texture_Buttons(); - - Enable_Stage(0,TheMtl->Get_Texture_Enable(PassIndex,0)); - Enable_Stage(1,TheMtl->Get_Texture_Enable(PassIndex,1)); -} - - -/*********************************************************************************************** - * GameMtlTextureDlg::ActivateDlg -- activate/deactivate this dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlTextureDlg::ActivateDlg(BOOL onOff) -{ - // no color swatches to activate. -} - - -/*********************************************************************************************** - * GameMtlTextureDlg::Enable_Stage -- enable or disable a texture stage * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlTextureDlg::Enable_Stage(int stage,BOOL onoff) -{ - assert((stage >= 0) && (stage < W3dMaterialClass::MAX_STAGES)); - TheMtl->Set_Texture_Enable(PassIndex,stage,(onoff == TRUE ? true : false)); - - if (stage == 0) { - - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_BUTTON),onoff); - - // Turn these off if it is a playstation 2 shader. - // These aren't supported yet. - if (TheMtl->Get_Shader_Type() == GameMtl::STE_PC_SHADER) { - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_RATE_SPIN), onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_RATE_EDIT), onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_FRAMES_SPIN), onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_FRAMES_EDIT), onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_ANIM_COMBO), onoff); - } else { - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_RATE_SPIN), FALSE); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_RATE_EDIT), FALSE); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_FRAMES_SPIN), FALSE); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_FRAMES_EDIT), FALSE); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_ANIM_COMBO), FALSE); - } - - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_PUBLISH_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_CLAMP_U_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_CLAMP_V_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_NOLOD_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_ALPHA_BITMAP_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_DISPLAY_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE0_HINT_COMBO),onoff); - - } else { - - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_RATE_SPIN),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_RATE_EDIT),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_FRAMES_SPIN),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_FRAMES_EDIT),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_PUBLISH_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_CLAMP_U_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_CLAMP_V_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_NOLOD_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_ALPHA_BITMAP_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_DISPLAY_BUTTON),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_ANIM_COMBO),onoff); - EnableWindow(GetDlgItem(m_hWnd,IDC_STAGE1_HINT_COMBO),onoff); - - } -} - - -/*********************************************************************************************** - * GameMtlTextureDlg::Update_Texture_Buttons -- update the texture buttons text * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlTextureDlg::Update_Texture_Buttons(void) -{ - Texmap * texmap; - texmap = TheMtl->Get_Texture(PassIndex,0); - TSTR filename; - - if (texmap) { - SplitPathFile(texmap->GetFullName(),NULL,&filename); - SetDlgItemText(m_hWnd, IDC_STAGE0_BUTTON,filename); - } else { - SetDlgItemText(m_hWnd, IDC_STAGE0_BUTTON,Get_String(IDS_NONE)); - } - - texmap = TheMtl->Get_Texture(PassIndex,1); - if (texmap) { - SplitPathFile(texmap->GetFullName(),NULL,&filename); - SetDlgItemText(m_hWnd, IDC_STAGE1_BUTTON,filename); - } else { - SetDlgItemText(m_hWnd, IDC_STAGE1_BUTTON,Get_String(IDS_NONE)); - } -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.h b/Generals/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.h deleted file mode 100644 index 42cea83508..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlTextureDlg.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlTextureDlg.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/14/00 1:47p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - - -#ifndef GAMEMTLTEXTUREDLG_H -#define GAMEMTLTEXTUREDLG_H - -#include -#include "GameMtlForm.h" - -class GameMtl; - -class GameMtlTextureDlg : public GameMtlFormClass -{ - -public: - - GameMtlTextureDlg(HWND parent, IMtlParams * imp, GameMtl * m, int pass); - ~GameMtlTextureDlg(void); - - virtual BOOL Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam); - void ActivateDlg(BOOL onOff); - void ReloadDialog(void); - -private: - - void Enable_Stage(int stage,BOOL onoff); - void Update_Texture_Buttons(void); - - ISpinnerControl * Stage0FramesSpin; - ISpinnerControl * Stage1FramesSpin; - - ISpinnerControl * Stage0RateSpin; - ISpinnerControl * Stage1RateSpin; - - ICustButton * Stage0PublishButton; - ICustButton * Stage1PublishButton; - ICustButton * Stage0ClampUButton; - ICustButton * Stage1ClampUButton; - ICustButton * Stage0ClampVButton; - ICustButton * Stage1ClampVButton; - ICustButton * Stage0NoLODButton; - ICustButton * Stage1NoLODButton; - ICustButton * Stage0AlphaBitmapButton; - ICustButton * Stage1AlphaBitmapButton; - ICustButton * Stage0DisplayButton; - ICustButton * Stage1DisplayButton; -}; - - - - -#endif - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp deleted file mode 100644 index 020173cf2f..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.cpp +++ /dev/null @@ -1,392 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlVertexMaterialDlg.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 7/10/00 3:37p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMtlVertexMaterialDlg::GameMtlVertexMaterialDlg -- constructor * - * GameMtlVertexMaterialDlg::~GameMtlVertexMaterialDlg -- destructor * - * GameMtlVertexMaterialDlg::Dialog_Proc -- windows message handler * - * GameMtlVertexMaterialDlg::ReloadDialog -- reload the contents of the controls * - * GameMtlVertexMaterialDlg::ActivateDlg -- activate / deactivate this dialog * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "GameMtlVertexMaterialDlg.h" -#include "gamemtl.h" -#include "dllmain.h" -#include "resource.h" - - -/*********************************************************************************************** - * GameMtlVertexMaterialDlg::GameMtlVertexMaterialDlg -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -GameMtlVertexMaterialDlg::GameMtlVertexMaterialDlg -( - HWND parent, - IMtlParams * imp, - GameMtl * mtl, - int pass -) : - GameMtlFormClass(imp,mtl,pass) -{ - AmbientSwatch = NULL; - DiffuseSwatch = NULL; - SpecularSwatch = NULL; - EmissiveSwatch = NULL; - - OpacitySpin = NULL; - TranslucencySpin = NULL; - ShininessSpin = NULL; - - for (int i=0; iGet_Ambient(PassIndex,IParams->GetTime()),Get_String(IDS_AMBIENT_COLOR)); - DiffuseSwatch = GetIColorSwatch(GetDlgItem(dlg_wnd, IDC_DIFFUSE_COLOR),TheMtl->Get_Diffuse(PassIndex,IParams->GetTime()),Get_String(IDS_DIFFUSE_COLOR)); - SpecularSwatch = GetIColorSwatch(GetDlgItem(dlg_wnd, IDC_SPECULAR_COLOR),TheMtl->Get_Specular(PassIndex,IParams->GetTime()),Get_String(IDS_SPECULAR_COLOR)); - EmissiveSwatch = GetIColorSwatch(GetDlgItem(dlg_wnd, IDC_EMISSIVE_COLOR),TheMtl->Get_Emissive(PassIndex,IParams->GetTime()),Get_String(IDS_EMISSIVE_COLOR)); - - OpacitySpin = SetupFloatSpinner(dlg_wnd,IDC_OPACITY_SPIN,IDC_OPACITY_EDIT,0.0f,1.0f,TheMtl->Get_Opacity(PassIndex,IParams->GetTime()),0.01f); - TranslucencySpin = SetupFloatSpinner(dlg_wnd,IDC_TRANSLUCENCY_SPIN,IDC_TRANSULCENCY_EDIT,0.0f,1.0f,TheMtl->Get_Translucency(PassIndex,IParams->GetTime()),0.01f); - ShininessSpin = SetupFloatSpinner(dlg_wnd,IDC_SHININESS_SPIN,IDC_SHININESS_EDIT,1.0f,1000.0f,TheMtl->Get_Shininess(PassIndex,IParams->GetTime()),1.0f); - UVChannelSpin[0] = SetupIntSpinner(dlg_wnd,IDC_STAGE0UVCHAN_SPIN,IDC_STAGE0UVCHAN_EDIT,1,99,1); - UVChannelSpin[1] = SetupIntSpinner(dlg_wnd,IDC_STAGE1UVCHAN_SPIN,IDC_STAGE1UVCHAN_EDIT,1,99,1); - break; - } - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(dlg_wnd,message,wparam,lparam); - return FALSE; - } - - case WM_COMMAND: - { - switch (id) - { - case IDC_COPY_SPECULAR_DIFFUSE: - TheMtl->Set_Copy_Specular_To_Diffuse(PassIndex,GetCheckBox(dlg_wnd, IDC_COPY_SPECULAR_DIFFUSE) == TRUE); - break; - - case IDC_MAPPING0_COMBO: - if (code == CBN_SELCHANGE) { - val = SendDlgItemMessage(dlg_wnd,IDC_MAPPING0_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Mapping_Type(PassIndex,0,val); - } - break; - - case IDC_MAPPING1_COMBO: - if (code == CBN_SELCHANGE) { - val = SendDlgItemMessage(dlg_wnd,IDC_MAPPING1_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Mapping_Type(PassIndex,1,val); - } - break; - - case IDC_MAPPING0_ARGS_EDIT: - switch (code) { - case EN_SETFOCUS: - DisableAccelerators(); - break; - case EN_KILLFOCUS: - EnableAccelerators(); - break; - case EN_CHANGE: - int len = GetWindowTextLength(GetDlgItem(dlg_wnd, IDC_MAPPING0_ARGS_EDIT)); - char *buffer = TheMtl->Get_Mapping_Arg_Buffer(PassIndex, 0, len); - GetWindowText(GetDlgItem(dlg_wnd, IDC_MAPPING0_ARGS_EDIT), buffer, len + 1); - break; - } - break; - - case IDC_MAPPING1_ARGS_EDIT: - switch (code) { - case EN_SETFOCUS: - DisableAccelerators(); - break; - case EN_KILLFOCUS: - EnableAccelerators(); - break; - case EN_CHANGE: - int len = GetWindowTextLength(GetDlgItem(dlg_wnd, IDC_MAPPING1_ARGS_EDIT)); - char *buffer = TheMtl->Get_Mapping_Arg_Buffer(PassIndex, 1, len); - GetWindowText(GetDlgItem(dlg_wnd, IDC_MAPPING1_ARGS_EDIT), buffer, len + 1); - break; - } - break; - - case IDC_NO_TRANS: - TheMtl->Set_PSX_Translucency(PassIndex,GAMEMTL_PSX_TRANS_NONE); - break; - - case IDC_100_TRANS: - TheMtl->Set_PSX_Translucency(PassIndex,GAMEMTL_PSX_TRANS_100); - break; - - case IDC_50_TRANS: - TheMtl->Set_PSX_Translucency(PassIndex,GAMEMTL_PSX_TRANS_50); - break; - - case IDC_25_TRANS: - TheMtl->Set_PSX_Translucency(PassIndex,GAMEMTL_PSX_TRANS_25); - break; - - case IDC_MINUS_100_TRANS: - TheMtl->Set_PSX_Translucency(PassIndex,GAMEMTL_PSX_TRANS_MINUS_100); - break; - - case IDC_NO_RT_LIGHTING: - TheMtl->Set_PSX_Lighting(PassIndex,!GetCheckBox(dlg_wnd, IDC_NO_RT_LIGHTING)); - break; - } - break; - } - - case CC_COLOR_CHANGE: - { - // just update all of the colors - TheMtl->Set_Ambient(PassIndex,IParams->GetTime(),AmbientSwatch->GetColor()); - TheMtl->Set_Diffuse(PassIndex,IParams->GetTime(),DiffuseSwatch->GetColor()); - TheMtl->Set_Specular(PassIndex,IParams->GetTime(),SpecularSwatch->GetColor()); - TheMtl->Set_Emissive(PassIndex,IParams->GetTime(),EmissiveSwatch->GetColor()); - TheMtl->Notify_Changed(); - break; - } - - case CC_SPINNER_CHANGE: - { - TheMtl->Set_Shininess(PassIndex,IParams->GetTime(),ShininessSpin->GetFVal()); - TheMtl->Set_Opacity(PassIndex,IParams->GetTime(),OpacitySpin->GetFVal()); - TheMtl->Set_Translucency(PassIndex,IParams->GetTime(),TranslucencySpin->GetFVal()); - for (int i=0; iSet_Map_Channel(PassIndex,i,UVChannelSpin[i]->GetIVal()); - } - break; - } - - case CC_SPINNER_BUTTONUP: - { - TheMtl->Notify_Changed(); - break; - } - - } - return FALSE; -} - - -/*********************************************************************************************** - * GameMtlVertexMaterialDlg::ReloadDialog -- reload the contents of the controls * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlVertexMaterialDlg::ReloadDialog(void) -{ - // Vertex Material Controls - DebugPrint("GameMtlVertexMaterialDlg::ReloadDialog\n"); - assert(AmbientSwatch && DiffuseSwatch && SpecularSwatch && EmissiveSwatch); - assert(ShininessSpin && OpacitySpin && TranslucencySpin); - - AmbientSwatch->InitColor(TheMtl->Get_Ambient(PassIndex,IParams->GetTime())); - DiffuseSwatch->InitColor(TheMtl->Get_Diffuse(PassIndex,IParams->GetTime())); - SpecularSwatch->InitColor(TheMtl->Get_Specular(PassIndex,IParams->GetTime())); - EmissiveSwatch->InitColor(TheMtl->Get_Emissive(PassIndex,IParams->GetTime())); - - ShininessSpin->SetValue(TheMtl->Get_Shininess(PassIndex,IParams->GetTime()),FALSE); - OpacitySpin->SetValue(TheMtl->Get_Opacity(PassIndex,IParams->GetTime()),FALSE); - TranslucencySpin->SetValue(TheMtl->Get_Translucency(PassIndex,IParams->GetTime()),FALSE); - for (int i=0; iSetValue(TheMtl->Get_Map_Channel(PassIndex,i),FALSE); - } - - SetCheckBox(m_hWnd,IDC_COPY_SPECULAR_DIFFUSE, TheMtl->Get_Copy_Specular_To_Diffuse(PassIndex)); - - SendDlgItemMessage( m_hWnd, - IDC_MAPPING0_COMBO, - CB_SETCURSEL, - TheMtl->Get_Mapping_Type(PassIndex, 0), - 0 ); - - SendDlgItemMessage( m_hWnd, - IDC_MAPPING1_COMBO, - CB_SETCURSEL, - TheMtl->Get_Mapping_Type(PassIndex, 1), - 0 ); - - // PSX Controls - SetCheckBox(m_hWnd,IDC_NO_RT_LIGHTING, !TheMtl->Get_PSX_Lighting(PassIndex)); - SetCheckBox(m_hWnd,IDC_NO_TRANS, false); - SetCheckBox(m_hWnd,IDC_100_TRANS, false); - SetCheckBox(m_hWnd,IDC_50_TRANS, false); - SetCheckBox(m_hWnd,IDC_25_TRANS, false); - SetCheckBox(m_hWnd,IDC_MINUS_100_TRANS, false); - - switch (TheMtl->Get_PSX_Translucency(PassIndex)) { - case 0: - SetCheckBox(m_hWnd,IDC_NO_TRANS,true); - break; - case GAMEMTL_PSX_TRANS_100: - SetCheckBox(m_hWnd,IDC_100_TRANS,true); - break; - case GAMEMTL_PSX_TRANS_50: - SetCheckBox(m_hWnd,IDC_50_TRANS,true); - break; - case GAMEMTL_PSX_TRANS_25: - SetCheckBox(m_hWnd,IDC_25_TRANS,true); - break; - case GAMEMTL_PSX_TRANS_MINUS_100: - SetCheckBox(m_hWnd,IDC_MINUS_100_TRANS,true); - break; - } - - // Reload contents of mapper args edit box: - char *buffer = TheMtl->Get_Mapping_Arg_Buffer(PassIndex, 0); - SetWindowText(GetDlgItem(m_hWnd, IDC_MAPPING0_ARGS_EDIT), buffer); - buffer = TheMtl->Get_Mapping_Arg_Buffer(PassIndex, 1); - SetWindowText(GetDlgItem(m_hWnd, IDC_MAPPING1_ARGS_EDIT), buffer); -} - - -/*********************************************************************************************** - * GameMtlVertexMaterialDlg::ActivateDlg -- activate / deactivate this dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/23/98 GTH : Created. * - *=============================================================================================*/ -void GameMtlVertexMaterialDlg::ActivateDlg(BOOL onoff) -{ - if (AmbientSwatch) { - AmbientSwatch->Activate(onoff); - } - if (DiffuseSwatch) { - DiffuseSwatch->Activate(onoff); - } - if (SpecularSwatch) { - SpecularSwatch->Activate(onoff); - } - if (EmissiveSwatch) { - EmissiveSwatch->Activate(onoff); - } -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h b/Generals/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h deleted file mode 100644 index 3c9fefc442..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/GameMtlVertexMaterialDlg.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/GameMtlVertexMaterialDlg.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/30/00 12:08p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#ifndef GAMEMTLVERTEXMATERIALDLG_H -#define GAMEMTLVERTEXMATERIALDLG_H - -#include -#include "GameMtlForm.h" - -class GameMtl; - -class GameMtlVertexMaterialDlg : public GameMtlFormClass -{ - -public: - - GameMtlVertexMaterialDlg(HWND parent, IMtlParams * imp, GameMtl * m, int pass); - ~GameMtlVertexMaterialDlg(); - - virtual BOOL Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam); - - void ActivateDlg(BOOL onoff); - void ReloadDialog(void); - -private: - - enum { MAX_STAGES = 2 }; - - IColorSwatch * AmbientSwatch; - IColorSwatch * DiffuseSwatch; - IColorSwatch * SpecularSwatch; - IColorSwatch * EmissiveSwatch; - - ISpinnerControl * OpacitySpin; - ISpinnerControl * TranslucencySpin; - ISpinnerControl * ShininessSpin; - ISpinnerControl * UVChannelSpin[MAX_STAGES]; -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/InputDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/InputDlg.cpp deleted file mode 100644 index 22cea6d20f..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/InputDlg.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/InputDlg.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 5/08/00 1:58p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -// InputDlg.cpp : implementation file -// - -#include "InputDlg.h" -#include - - -static BOOL CALLBACK _thunk_dialog_proc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - -///////////////////////////////////////////////////////////////////////////// -// InputDlg dialog - - -InputDlg::InputDlg (HWND hWndParent) -: m_hWndParent(hWndParent), - m_hWnd(NULL) -{ - // Set the strings to default values. - SetCaption("Input Value..."); - SetLabel("Please enter a value:"); - SetValue(NULL); -} - - -///////////////////////////////////////////////////////////////////////////// -// InputDlg Methods - -int InputDlg::DoModal (void) -{ - // Put up the dialog box. - BOOL result = DialogBoxParam(AppInstance, MAKEINTRESOURCE(IDD), - m_hWndParent, (DLGPROC)_thunk_dialog_proc, - (LPARAM)this); - - // Return IDOK if the user accepted the new settings. - return (result == 1) ? IDOK : IDCANCEL; -} - -void InputDlg::SetCaption (const char *caption) -{ - if (caption) - { - assert(strlen(caption) < sizeof(m_Caption)); - strcpy(m_Caption, caption); - } - else - m_Caption[0] = '\0'; -} - -void InputDlg::SetLabel (const char *label) -{ - if (label) - { - assert(strlen(label) < sizeof(m_Label)); - strcpy(m_Label, label); - } - else - m_Label[0] = '\0'; -} - -void InputDlg::SetValue (const char *value) -{ - if (value) - { - assert(strlen(value) < sizeof(m_Value)); - strcpy(m_Value, value); - } - else - m_Value[0] = '\0'; -} - - -///////////////////////////////////////////////////////////////////////////// -// InputDlg DialogProc - -BOOL CALLBACK _thunk_dialog_proc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - static InputDlg *dialog = NULL; - - if (uMsg == WM_INITDIALOG) - { - dialog = (InputDlg*)lParam; - dialog->m_hWnd = hWnd; - } - - if (dialog) - return dialog->DialogProc(hWnd, uMsg, wParam, lParam); - else - return 0; -} - -BOOL CALLBACK InputDlg::DialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - int code = HIWORD(wParam); - - switch (uMsg) - { - /******************************************************************* - * WM_INITDIALOG - * - * Initialize all of the custom controls for the dialog box - * - *******************************************************************/ - case WM_INITDIALOG: - - OnInitDialog(wParam, lParam); - return TRUE; - - - /******************************************************************* - * WM_COMMAND - * - * - *******************************************************************/ - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - if (!OnOK()) - return TRUE; - - SetCursor(LoadCursor(NULL, IDC_WAIT)); - EndDialog(m_hWnd, 1); - break; - - case IDCANCEL: - EndDialog(m_hWnd, 0); - break; - } - return TRUE; - } - - return FALSE; -} - -///////////////////////////////////////////////////////////////////////////// -// InputDlg message handlers - -LRESULT InputDlg::OnInitDialog (WPARAM wParam, LPARAM lParam) -{ - // Set the cursor to the normal arrow. - SetCursor(LoadCursor(NULL, IDC_ARROW)); - - // Set the dialog box caption. - SetWindowText(m_hWnd, m_Caption); - - // Set the label text. - HWND hLabel = GetDlgItem(m_hWnd, IDC_LABEL); - assert(hLabel != NULL); - SetWindowText(hLabel, m_Label); - - // Set the default value. - HWND hEdit = GetDlgItem(m_hWnd, IDC_VALUE); - assert(hEdit != NULL); - SetWindowText(hEdit, m_Value); - - // Select all of the text in the edit box. - SendMessage(hEdit, EM_SETSEL, 0, -1); - - return 0; -} - -BOOL InputDlg::OnOK (void) -{ - // Update our copy of what the user typed. - HWND hEdit = GetDlgItem(m_hWnd, IDC_VALUE); - assert(hEdit != NULL); - GetWindowText(hEdit, m_Value, sizeof(m_Value)); - - // The dialog can be dismissed. - return TRUE; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/InputDlg.h b/Generals/Code/Tools/WW3D/max2w3d/InputDlg.h deleted file mode 100644 index bbe02e2106..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/InputDlg.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/InputDlg.h $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 5/08/00 1:36p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#ifndef INPUTDLG_H -#define INPUTDLG_H - -#include "dllmain.h" -#include "resource.h" - - -///////////////////////////////////////////////////////////////////////////// -// InputDlg dialog - a generic input box for MAXScript - -class InputDlg -{ - friend BOOL CALLBACK _thunk_dialog_proc (HWND, UINT, WPARAM, LPARAM); - -public: - - // Construction - InputDlg (HWND hWndParent=NULL); - - // Methods - int DoModal (void); // returns IDOK or IDCANCEL - - void SetCaption (const char *caption); - void SetLabel (const char *label); - void SetValue (const char *value); - - // DialogProc - BOOL CALLBACK DialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - // Dialog data associated with GUI components. - char m_Value[1024]; // edit box - char m_Label[512]; // description label - char m_Caption[128]; // dialog caption - -protected: - - // Dialog data - enum { IDD = IDD_INPUT_DIALOG }; - HWND m_hWnd; - HWND m_hWndParent; - - // Message Handlers - LRESULT OnInitDialog (WPARAM wParam, LPARAM lParam); - BOOL OnOK (void); -}; - - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/LightGlareSave.cpp b/Generals/Code/Tools/WW3D/max2w3d/LightGlareSave.cpp deleted file mode 100644 index 945f44b852..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/LightGlareSave.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/LightGlareSave.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/06/00 11:21a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "LightGlareSave.h" -#include "w3d_file.h" -#include "util.h" -#include "w3dappdata.h" -#include "errclass.h" - - -LightGlareSaveClass::LightGlareSaveClass -( - char * mesh_name, - char * container_name, - INode * inode, - Matrix3 & exportspace, - TimeValue curtime, - Progress_Meter_Class & meter -) -{ - ////////////////////////////////////////////////////////////////////// - // Init the glare info - ////////////////////////////////////////////////////////////////////// - memset(&GlareData,0,sizeof(GlareData)); - - ////////////////////////////////////////////////////////////////////// - // Get the position of the pivot point relative to the given - // export coordinate system. - ////////////////////////////////////////////////////////////////////// - - // Transform the mesh into the desired coordinate system - Matrix3 node_matrix = inode->GetObjectTM(curtime); - Matrix3 offset_matrix = node_matrix * Inverse(exportspace); - - GlareData.Position.X = offset_matrix.GetTrans().x; - GlareData.Position.Y = offset_matrix.GetTrans().y; - GlareData.Position.Z = offset_matrix.GetTrans().z; -} - - - -int LightGlareSaveClass::Write_To_File(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(W3D_CHUNK_LIGHTGLARE); - csave.Begin_Chunk(W3D_CHUNK_LIGHTGLARE_INFO); - csave.Write(&GlareData,sizeof(GlareData)); - csave.End_Chunk(); - csave.End_Chunk(); - return 0; -} - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/LightGlareSave.h b/Generals/Code/Tools/WW3D/max2w3d/LightGlareSave.h deleted file mode 100644 index a1752ca6ce..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/LightGlareSave.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/LightGlareSave.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/05/00 10:27a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef LIGHTGLARESAVE_H -#define LIGHTGLARESAVE_H - -#include -#include "w3d_file.h" -#include "chunkio.h" -#include "PROGRESS.H" - - -/******************************************************************************************* -** -** LightGlareSaveClass - Create a Light Glare definition from a Max mesh. In the initial -** implementation, all I need to save is the point at the pivot of the mesh. -** -*******************************************************************************************/ -class LightGlareSaveClass -{ -public: - - enum { - EX_UNKNOWN = 0, // exception error codes - EX_CANCEL = 1 - }; - - LightGlareSaveClass( char * mesh_name, - char * container_name, - INode * inode, - Matrix3 & exportspace, - TimeValue curtime, - Progress_Meter_Class & meter); - - int Write_To_File(ChunkSaveClass & csave); - -private: - - W3dLightGlareStruct GlareData; - -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeform.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeform.cpp deleted file mode 100644 index 0b30edadd3..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeform.cpp +++ /dev/null @@ -1,1446 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/MeshDeform.cpp 7 5/01/01 8:56p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeform.cpp * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/19/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "MeshDeform.h" -#include "MeshDeformData.h" -#include "MeshDeformPanel.h" -#include "MeshDeformUndo.h" -#include "dllmain.h" -#include "resource.h" -#include "util.h" - -#if defined W3D_MAX4 //defined as in the project (.dsp) -static GenSubObjType _SubObjectTypeVertex(1); -#endif - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformClass Class ID -// -/////////////////////////////////////////////////////////////////////////// -Class_ID _MeshDeformClassID(0x51981f5b, 0x1db2bf3); - - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformClassDesc -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformClassDesc : public ClassDesc -{ - public: - int IsPublic (void) { return 1; } - void * Create (BOOL loading) { return new MeshDeformClass (); } - const TCHAR * ClassName () { return _T("WWDeform"); } - SClass_ID SuperClassID () { return OSM_CLASS_ID; } - Class_ID ClassID () { return _MeshDeformClassID; } - const TCHAR* Category () { return _T("Westwood Modifiers"); } -}; - - -/////////////////////////////////////////////////////////////////////////// -// -// Static class desc instance -// -/////////////////////////////////////////////////////////////////////////// -#if 0 // (gth) MeshDeform is obsolete! making sure nobody uses it... -static MeshDeformClassDesc _MeshDeformCD; -ClassDesc * Get_Mesh_Deform_Desc (void) { return &_MeshDeformCD; } -#else -ClassDesc * Get_Mesh_Deform_Desc (void) { return NULL; } -#endif - - -/////////////////////////////////////////////////////////////////////////// -// -// ChannelsUsed -// -/////////////////////////////////////////////////////////////////////////// -ChannelMask -MeshDeformClass::ChannelsUsed (void) -{ - return GEOM_CHANNEL | SELECT_CHANNEL | SUBSEL_TYPE_CHANNEL | VERTCOLOR_CHANNEL; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// ChannelsChanged -// -/////////////////////////////////////////////////////////////////////////// -ChannelMask -MeshDeformClass::ChannelsChanged (void) -{ - return GEOM_CHANNEL | SELECT_CHANNEL | SUBSEL_TYPE_CHANNEL | VERTCOLOR_CHANNEL; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// ModifyObject -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::ModifyObject -( - TimeValue time, - ModContext & mod_context, - ObjectState * object_state, - INode * /*node*/ -) -{ - assert(object_state->obj->IsSubClassOf(triObjectClassID)); - - - MeshDeformModData *mod_data = NULL; - if (mod_context.localData == NULL) { - mod_data = new MeshDeformModData; - mod_context.localData = mod_data; - } else { - mod_data = static_cast (mod_context.localData); - } - - // Display the verts - TriObject *tri_obj = (TriObject *)object_state->obj; - tri_obj->mesh.SetDispFlag (DISP_SELVERTS | DISP_VERTTICKS); - - // Record the initial state of the mesh - bool lock_sets = false; - if (m_pPanel != NULL) { - lock_sets = (m_pPanel->Are_Sets_Tied () == TRUE); - } - mod_data->Record_Mesh_State (*tri_obj, m_DeformState, lock_sets); - - tri_obj->PointsWereChanged(); - - // Kind of a waste when there's no animation... - tri_obj->UpdateValidity (GEOM_CHAN_NUM, Interval (time, time + 1)); - tri_obj->UpdateValidity (SELECT_CHAN_NUM, Interval (time, time + 1)); - tri_obj->UpdateValidity (SUBSEL_TYPE_CHAN_NUM, Interval (time, time + 1)); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// InputType -// -/////////////////////////////////////////////////////////////////////////// -Class_ID -MeshDeformClass::InputType (void) -{ - return triObjectClassID; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// NotifyRefChanged -// -/////////////////////////////////////////////////////////////////////////// -RefResult -MeshDeformClass::NotifyRefChanged -( - Interval time, - RefTargetHandle htarget, - PartID &part_id, - RefMessage mesage -) -{ - return REF_SUCCEED; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// GetCreateMouseCallBack -// -/////////////////////////////////////////////////////////////////////////// -CreateMouseCallBack * -MeshDeformClass::GetCreateMouseCallBack (void) -{ - return NULL; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// BeginEditParams -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::BeginEditParams -( - IObjParam *max_interface, - ULONG flags, - Animatable *prev -) -{ - m_MaxInterface = max_interface; - Update_Set_Count (); - Set_Max_Deform_Sets (m_MaxSets); - - // Add our rollup to the command panel - m_hRollupWnd = m_MaxInterface->AddRollupPage (AppInstance, - MAKEINTRESOURCE (IDD_MESH_DEFORM_PANEL), - MeshDeformPanelClass::Message_Proc, - "Westwood Mesh Deform", - 0, - 0); - - // - // Update the UI - // - m_pPanel = MeshDeformPanelClass::Get_Object (m_hRollupWnd); - m_pPanel->Set_Deformer (this); - m_pPanel->Set_Max_Sets (m_MaxSets); - m_pPanel->Set_Current_Set (m_CurrentSet); - Set_Current_Set (m_CurrentSet, false); - - // - // Register the desired sub-object selection types. - // - const TCHAR * ptype[] = { "Vertices" }; -#if defined W3D_MAX4 //defined as in the project (.dsp) - max_interface->SetSubObjectLevel(1); -#else - //---This call is obsolete from max4. - max_interface->RegisterSubObjectTypes( ptype, 1); -#endif - - // - // Create the mode handlers - // - m_ModeSelect = new SelectModBoxCMode (this, max_interface); - m_ModeMove = new MoveModBoxCMode (this, max_interface); - m_ModeRotate = new RotateModBoxCMode (this, max_interface); - m_ModeUScale = new UScaleModBoxCMode (this, max_interface); - m_ModeNUScale = new NUScaleModBoxCMode (this, max_interface); - m_ModeSquash = new SquashModBoxCMode (this, max_interface); - - // - // Restore the selection level. - /// - max_interface->SetSubObjectLevel (1); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// EndEditParams -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::EndEditParams -( - IObjParam *max_interface, - ULONG flags, - Animatable *next -) -{ - // Remove our deform rollup - if (m_hRollupWnd != NULL) { - max_interface->DeleteRollupPage (m_hRollupWnd); - m_hRollupWnd = NULL; - } - - // - // Free the mode handlers - // - max_interface->DeleteMode (m_ModeMove); - max_interface->DeleteMode (m_ModeSelect); - max_interface->DeleteMode (m_ModeRotate); - max_interface->DeleteMode (m_ModeNUScale); - max_interface->DeleteMode (m_ModeUScale); - max_interface->DeleteMode (m_ModeSquash); - SAFE_DELETE (m_ModeMove); - SAFE_DELETE (m_ModeSelect); - SAFE_DELETE (m_ModeRotate); - SAFE_DELETE (m_ModeNUScale); - SAFE_DELETE (m_ModeUScale); - SAFE_DELETE (m_ModeSquash); - - // Release our hold on the max interface pointer - m_MaxInterface = NULL; - m_pPanel = NULL; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// ActivateSubobjSel -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::ActivateSubobjSel -( - int level, - XFormModes &modes -) -{ - switch (level) - { - // Vertex manipulation - case 1: - modes = XFormModes (m_ModeMove, m_ModeRotate, m_ModeNUScale, m_ModeUScale, m_ModeSquash, m_ModeSelect); - break; - } - - /* - ** Notify our dependents that the subselection type, - ** and the display have changed - */ - NotifyDependents(FOREVER, PART_SUBSEL_TYPE|PART_DISPLAY, REFMSG_CHANGE); - - /* - ** Notify the pipeline that the selection level has changed. - */ - m_MaxInterface->PipeSelLevelChanged(); - - /* - ** Notify our dependents that the selection channel, - ** display attributes, and subselection type channels have changed - */ - NotifyDependents(FOREVER, VERTCOLOR_CHANNEL|SELECT_CHANNEL|DISP_ATTRIB_CHANNEL|SUBSEL_TYPE_CHANNEL, REFMSG_CHANGE); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// HitTest -// -/////////////////////////////////////////////////////////////////////////// -int -MeshDeformClass::HitTest -( - TimeValue time_value, - INode * node, - int type, - int crossing, - int flags, - IPoint2 * point, - ViewExp * viewport, - ModContext * mod_context -) -{ - // Initialize the HitRegion - HitRegion hit_rgn; - MakeHitRegion (hit_rgn, type, crossing, 4, point); - - Matrix3 transform = node->GetObjectTM (time_value); - Object * obj = node->EvalWorldState(time_value).obj; - TriObject * tri = (TriObject *)obj->ConvertToType(time_value, triObjectClassID); - - // - // Set up the graphics window to do the hit-test - // - GraphicsWindow *graphics_wnd = viewport->getGW (); - graphics_wnd->setHitRegion (&hit_rgn); - graphics_wnd->setTransform (transform); - - int saved_limits = graphics_wnd->getRndLimits (); - graphics_wnd->setRndLimits ((saved_limits | GW_PICK) & ~(GW_ILLUM | GW_BACKCULL)); - graphics_wnd->clearHitCode (); - - // - // Perform the hit test - // - SubObjHitList hitlist; - MeshDeformModData *mod_data = static_cast (mod_context->localData); - Mesh &mesh = tri->mesh;//mod_data->Peek_Mesh (); - int result = mesh.SubObjectHitTest (graphics_wnd, - graphics_wnd->getMaterial (), - &hit_rgn, - flags | SUBHIT_VERTS, - hitlist); - - // - // Record all of the hits - // - for (MeshSubHitRec *hit_record = hitlist.First (); - hit_record != NULL; - hit_record = hit_record->Next ()) { - - // rec->index is the index of vertex which was hit! - viewport->LogHit (node, mod_context, hit_record->dist, hit_record->index, NULL); - } - - // Cleanup - graphics_wnd->setRndLimits (saved_limits); - - // Return the integer result code - return result; -} - -/////////////////////////////////////////////////////////////////////////// -// -// HitTest -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::SelectSubComponent -( - HitRecord * hit_record, - BOOL selected, - BOOL all, - BOOL invert -) -{ - // Loop through all the hit records - for (; hit_record != NULL; hit_record = hit_record->Next ()) { - - // Peek at the vertex selection array for this hit record - MeshDeformModData *mod_data = static_cast (hit_record->modContext->localData); - Mesh *mesh = mod_data->Peek_Mesh (); - BitArray &array = (mesh->vertSel); - - if (all & invert) { - - /* - ** hitRec->hitInfo is the MeshSubHitRec::index that was stored in the - ** HitTest method through LogHit - */ - if (array[hit_record->hitInfo]) { - array.Clear (hit_record->hitInfo); - } else { - array.Set (hit_record->hitInfo, selected); - } - } else { - array.Set (hit_record->hitInfo, selected); - } - - if (!all) break; - } - - m_pPanel->Update_Vertex_Color (); - NotifyDependents (FOREVER, PART_SELECT, REFMSG_CHANGE); - m_bSetDirty = true; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// GetSubObjectTMs -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::GetSubObjectTMs -( - SubObjAxisCallback *cb, - TimeValue t, - INode *node, - ModContext *mc -) -{ - int test = 0; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// HitTest -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::GetSubObjectCenters -( - SubObjAxisCallback * callback, - TimeValue time_val, - INode * node, - ModContext * mod_context -) -{ - // Peek at the vertex selection array for this hit record - MeshDeformModData *mod_data = static_cast (mod_context->localData); - const Point3 *vertex_array = mod_data->Peek_Orig_Vertex_Array (); - Mesh *mesh = mod_data->Peek_Mesh (); - - BitArray sel_array = mesh->vertSel; - Matrix3 transform = node->GetObjectTM (time_val); - Box3 box; - - // Loop through all the selected verticies and create a bounding - // box which we can use to determine the selection center. - for (int index = 0; index < mesh->getNumVerts (); index++ ) { - if (sel_array[index]) { - box += mesh->getVert (index) * transform; - } - } - - // Pass the 'selection' center onto MAX - callback->Center (box.Center (), 0); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// ClearSelection -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::ClearSelection (int selLevel) -{ - ModContextList mod_context_list; - INodeTab nodes; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - for (int i = 0; i < mod_context_list.Count (); i++) { - - MeshDeformModData *mod_data = static_cast (mod_context_list[i]->localData); - - if (mod_data != NULL) { - mod_data->Peek_Mesh ()->vertSel.ClearAll (); - } - } - - /* - ** Get rid of the temporary copies of the INodes. - */ - nodes.DisposeTemporary (); - - /* - ** Tell our dependents that the selection set has changed - */ - NotifyDependents (FOREVER, PART_SELECT, REFMSG_CHANGE); - m_bSetDirty = true; - return ; -} - -static Point3 last_delta; -static Point3 last_scale; -static Matrix3 last_rot; - -/////////////////////////////////////////////////////////////////////////// -// -// Move -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Move -( - TimeValue time_val, - Matrix3 & parent_tm, - Matrix3 & tm_axis, - Point3 & displacement, - BOOL local_origin -) -{ - if (m_pPanel->Is_Edit_Mode ()) { - - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // Get the data we've cached for this modifier context - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - Mesh *mesh = mod_data->Peek_Mesh (); - const Point3 *vertex_array = mod_data->Peek_Orig_Vertex_Array (); - Point3 *opstart_array = mod_data->Peek_Vertex_OPStart_Array (); - - // Loop through all the selected verts - for (int vert = 0; vert < mesh->numVerts; vert ++) { - if (mesh->vertSel[vert]) { - - // Do the 'displacment' in axis-space - Point3 vert_ws = parent_tm * mesh->verts[vert]; - Point3 vert_as = Inverse (tm_axis) * vert_ws; - vert_as += displacement - last_delta; - - // Convert back to obj-space - vert_ws = tm_axis * vert_as; - mesh->verts[vert] = Inverse (parent_tm) * vert_ws; - - // Record the delta - //delta_array[vert] = mesh->verts[vert] - vertex_array[vert]; - } - } - - // - // Record these changes in the current set - // - mod_data->Update_Set (m_CurrentSet, VERT_POSITION); - } - } - - // Remember what our last displacement was because we - // want to perform our calculations relative to the current - // position. - last_delta = displacement; - - // Repaint the view - nodes.DisposeTemporary (); - NotifyDependents (FOREVER, PART_GEOM, REFMSG_CHANGE); - } - - m_OperationName = "Move"; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Move -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Scale -( - TimeValue time_val, - Matrix3 & parent_tm, - Matrix3 & tm_axis, - Point3 & value, - BOOL local_origin -) -{ - Point3 test = value - last_scale; - bool bok = (test.x != 0) && (test.y != 0) && (test.z != 0); - if (m_pPanel->Is_Edit_Mode () && bok) { - - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // Get the data we've cached for this modifier context - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - Mesh *mesh = mod_data->Peek_Mesh (); - const Point3 *vertex_array = mod_data->Peek_Orig_Vertex_Array (); - Point3 *opstart_array = mod_data->Peek_Vertex_OPStart_Array (); - - // Loop through all the selected verts - for (int vert = 0; vert < mesh->numVerts; vert ++) { - if (mesh->vertSel[vert]) { - - // Do the 'scale' in axis-space - Point3 vert_ws = parent_tm * opstart_array[vert];//mesh->verts[vert]; - Point3 vert_as = Inverse (tm_axis) * vert_ws; - vert_as = ScaleMatrix (value) * vert_as; - - // Convert back to obj-space - vert_ws = tm_axis * vert_as; - mesh->verts[vert] = Inverse (parent_tm) * vert_ws; - - // Record the delta - //delta_array[vert] = mesh->verts[vert] - vertex_array[vert]; - } - } - - // - // Record these changes in the current set - // - mod_data->Update_Set (m_CurrentSet, VERT_POSITION); - } - } - - // Remember what our last displacement was because we - // want to perform our calculations relative to the current - // position. - //last_scale = value - Point3 (1,1,1); - //last_delta = displacement; - - // Repaint the view - nodes.DisposeTemporary (); - NotifyDependents (FOREVER, PART_GEOM, REFMSG_CHANGE); - } - - m_OperationName = "Scale"; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Rotate -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Rotate -( - TimeValue time_val, - Matrix3 & parent_tm, - Matrix3 & tm_axis, - Quat & rotation, - BOOL local_origin -) -{ - if (m_pPanel->Is_Edit_Mode ()) { - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - Matrix3 matrix_rot; - rotation.MakeMatrix (matrix_rot); - - Matrix3 rel_rot; - rel_rot = Inverse (last_rot) * matrix_rot; - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // Get the data we've cached for this modifier context - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - Mesh *mesh = mod_data->Peek_Mesh (); - const Point3 *vertex_array = mod_data->Peek_Orig_Vertex_Array (); - Point3 *opstart_array = mod_data->Peek_Vertex_OPStart_Array (); - - // Loop through all the selected verts - for (int vert = 0; vert < mesh->numVerts; vert ++) { - if (mesh->vertSel[vert]) { - - // Do the 'displacment' in axis-space - Point3 vert_ws = parent_tm * mesh->verts[vert]; - Point3 vert_as = Inverse (tm_axis) * vert_ws; - vert_as = (rel_rot * vert_as); - - // Convert back to obj-space - vert_ws = tm_axis * vert_as; - mesh->verts[vert] = Inverse (parent_tm) * vert_ws; - - // Record the delta - //delta_array[vert] = mesh->verts[vert] - vertex_array[vert]; - } - } - - // - // Record these changes in the current set - // - mod_data->Update_Set (m_CurrentSet, VERT_POSITION); - } - } - - // Remember what our last displacement was because we - // want to perform our calculations relative to the current - // position. - //last_delta = displacement; - last_rot = matrix_rot; - - // Repaint the view - nodes.DisposeTemporary (); - NotifyDependents (FOREVER, PART_GEOM, REFMSG_CHANGE); - - // Make sure our current 'set' knows what verts have changed - //Update_Current_Set (); - } - - m_OperationName = "Rotate"; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// TransformStart -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::TransformStart (TimeValue time_val) -{ - if (m_MaxInterface != NULL) { - m_MaxInterface->LockAxisTripods (TRUE); - } - - // Reset our last-delta value - last_delta.x = 0; - last_delta.y = 0; - last_delta.z = 0; - last_rot.IdentityMatrix (); - last_scale.x = 0; - last_scale.y = 0; - last_scale.z = 0; - - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Begin the undo operation - theHold.Begin (); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // Get the data we've cached for this modifier context - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - Mesh *mesh = mod_data->Peek_Mesh (); - Point3 *opstart_array = mod_data->Peek_Vertex_OPStart_Array (); - - // Copy the current state of the mesh - for (int vert = 0; vert < mesh->numVerts; vert ++) { - opstart_array[vert] = mesh->verts[vert]; - } - - // Add the 'position restore' object to the undo stack - theHold.Put (new VertexPositionRestoreClass (mesh, this, mod_data)); - } - } - - // Repaint the view - nodes.DisposeTemporary (); - NotifyDependents (FOREVER, PART_GEOM, REFMSG_CHANGE); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// TransformFinish -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::TransformFinish (TimeValue time_val) -{ - if (m_MaxInterface != NULL) { - m_MaxInterface->LockAxisTripods (FALSE); - } - - // Accept the undo operation - theHold.Accept (m_OperationName); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// TransformCancel -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::TransformCancel (TimeValue time_val) -{ - if (m_MaxInterface != NULL) { - m_MaxInterface->LockAxisTripods (FALSE); - } - - // Cancel the undo operation - theHold.Cancel (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Deform_State -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Set_Deform_State (float state) -{ - if ((m_MaxInterface != NULL) && (state != m_DeformState)) { - m_DeformState = state; - NotifyDependents (FOREVER, PART_GEOM | PART_VERTCOLOR, REFMSG_CHANGE); - m_MaxInterface->RedrawViews (m_MaxInterface->GetTime ()); - if (m_pPanel != NULL) { - m_pPanel->Update_Vertex_Color (); - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Vertex_Color -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Set_Vertex_Color (const Point3 &color, bool button_up) -{ - if (m_MaxInterface != NULL) { - - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - bool save_undo = false; - if ((button_up == false) && (m_VertColorChanging == false)) { - theHold.Begin (); - m_VertColorChanging = true; - save_undo = true; - } - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // Get the data we've cached for this modifier context - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - Mesh *mesh = mod_data->Peek_Mesh (); - - // - // Record the original color in the undo stack - // - if (save_undo) { - theHold.Put (new VertexColorRestoreClass (mesh, this, mod_data)); - } - - // Only do this if the mesh is using vertex coloring - if (mesh->numCVerts >= mesh->numVerts) { - - // - // Loop through all the per-face verts - // - for (int face = 0; face < mesh->numFaces; face ++) { - for (int vert = 0; vert < 3; vert ++) { - - // - // If the vertex is selected, then change its color - // - if (mesh->vertSel[mesh->faces[face].v[vert]]) { - int color_index = mesh->vcFace[face].t[vert]; - mesh->vertCol[color_index] = color; - } - } - } - } - - // - // Record these changes in the current set - // - mod_data->Update_Set (m_CurrentSet, VERT_COLORS); - } - } - - if (button_up && m_VertColorChanging) { - theHold.Accept ("Vertex Color"); - } - - // Repaint the model - nodes.DisposeTemporary (); - NotifyDependents (FOREVER, PART_GEOM | PART_VERTCOLOR, REFMSG_CHANGE); - m_MaxInterface->RedrawViews (m_MaxInterface->GetTime ()); - } - - m_VertColorChanging = !button_up; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Get_Vertex_Color -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Get_Vertex_Color (Point3 &color) -{ - // Assume black - color.x = 0; - color.y = 0; - color.z = 0; - - if (m_MaxInterface != NULL) { - - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // - // Loop through all the modifier contexts - // - int sel_count = 0; - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // - // Get the data we've cached for this modifier context - // - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - Mesh *mesh = mod_data->Peek_Mesh (); - - // Only do this if the mesh is using vertex coloring - if (mesh->numCVerts >= mesh->numVerts) { - - // - // Loop through all the per-face verts - // - for (int face = 0; face < mesh->numFaces; face ++) { - for (int vert = 0; vert < 3; vert ++) { - - // - // If this vert is selected, then add its color to the total - // - if (mesh->vertSel[mesh->faces[face].v[vert]]) { - int color_index = mesh->vcFace[face].t[vert]; - Point3 vert_color = mesh->vertCol[color_index]; - color += vert_color; - sel_count ++; - } - } - } - } - } - } - - // - // Normalize the selected color - // - if (sel_count > 0) { - color = color / sel_count; - } - - nodes.DisposeTemporary (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_UI -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Update_UI (MeshDeformModData *mod_data) -{ - assert (mod_data != NULL); - - if (m_pPanel != NULL) { - Update_Set_Count (); - - m_CurrentSet = mod_data->Get_Current_Set (); - int keyframe = mod_data->Peek_Set (m_CurrentSet).Get_Current_Key_Frame (); - Set_Deform_State ((float(keyframe + 1) + 0.5F) / 10.0F); - - m_pPanel->Update_Vertex_Color (); - m_pPanel->Set_Max_Sets (m_MaxSets); - m_pPanel->Set_Current_Set (m_CurrentSet); - m_pPanel->Set_Current_State (m_DeformState); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Auto_Apply -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Auto_Apply (bool auto_apply) -{ - if (m_MaxInterface != NULL) { - - // Get a list of contexts that we are part of. - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // - // Let the mod context know what it's auto apply state is - // - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - mod_data->Auto_Apply (auto_apply); - } - } - - // Cleanup - nodes.DisposeTemporary (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Max_Deform_Sets -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Set_Max_Deform_Sets (int max) -{ - // - // Make sure the current set doesn't exceed the total sets - // - if (m_CurrentSet >= max) { - Set_Current_Set (max - 1, true); - } - - m_MaxSets = max; - if (m_MaxInterface != NULL) { - - // Get a list of contexts that we are part of. - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // - // Let the mod context know the max sets have changed - // - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - mod_data->Set_Max_Deform_Sets (max); - } - } - - // Cleanup - nodes.DisposeTemporary (); - NotifyDependents (FOREVER, PART_SELECT, REFMSG_CHANGE); - m_MaxInterface->RedrawViews (m_MaxInterface->GetTime ()); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Set_Count -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Update_Set_Count (void) -{ - m_MaxSets = 1; - if (m_MaxInterface != NULL) { - - // Get a list of contexts that we are part of. - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // - // Get the count of sets for this context - // - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if ((mod_data != NULL) && (mod_data->Get_Set_Count () > m_MaxSets)) { - m_MaxSets = mod_data->Get_Set_Count (); - } - } - - // Cleanup - nodes.DisposeTemporary (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Current_Set -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Set_Current_Set -( - int index, - bool update_selection -) -{ - last_delta.x = 0; - last_delta.y = 0; - last_delta.z = 0; - - m_CurrentSet = index; - if (m_MaxInterface != NULL) { - if (update_selection) { - ClearSelection (1); - } - - // Get a list of contexts that we are part of. - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // - // Have the mod context select the verts in its set - // - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - mod_data->Set_Current_Set (m_CurrentSet); - if (update_selection) { - mod_data->Select_Set (m_CurrentSet); - } - m_pPanel->Set_Auto_Apply_Check (mod_data->Is_Auto_Apply ()); - } - } - - // Repaint the model - nodes.DisposeTemporary (); - if (update_selection) { - NotifyDependents (FOREVER, PART_SELECT, REFMSG_CHANGE); - m_MaxInterface->RedrawViews (m_MaxInterface->GetTime ()); - } - - // Update the current 'vertex color' on the UI panel - m_pPanel->Update_Vertex_Color (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Current_Set -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformClass::Update_Current_Set (void) -{ - if (m_MaxInterface != NULL) { - - // Get a list of contexts that we are part of. - INodeTab nodes; - ModContextList mod_context_list; - m_MaxInterface->GetModContexts (mod_context_list, nodes); - - // Loop through all the modifier contexts - for (int index = 0; index < mod_context_list.Count (); index ++) { - - // - // Notify the mod context so it can update its list of verts - // in the current set. - // - MeshDeformModData *mod_data = static_cast (mod_context_list[index]->localData); - if (mod_data != NULL) { - //mod_data->Update_Set (m_CurrentSet); - } - } - - // Cleanup - nodes.DisposeTemporary (); - m_bSetDirty = false; - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// SaveLocalData -// -/////////////////////////////////////////////////////////////////////////// -IOResult -MeshDeformClass::SaveLocalData (ISave *save_obj, LocalModData *mod_context) -{ - assert (mod_context != NULL); - return ((MeshDeformModData *)mod_context)->Save (save_obj); -} - - -/////////////////////////////////////////////////////////////////////////// -// -// LoadLocalData -// -/////////////////////////////////////////////////////////////////////////// -IOResult -MeshDeformClass::LoadLocalData (ILoad *load_obj, LocalModData **mod_context) -{ - assert (mod_context != NULL); - MeshDeformModData *mod_data = new MeshDeformModData; - (*mod_context) = mod_data; - return mod_data->Load (load_obj); -} - - - - - - -#if 0 - -void SkinModifierClass::SelectAll(int selLevel) -{ - int needsdel = 0; - Interval valid = FOREVER; - ModContextList mclist; - INodeTab nodes; - - if (!InterfacePtr) return; - - InterfacePtr->GetModContexts(mclist,nodes); - InterfacePtr->ClearCurNamedSelSet(); - - for (int i = 0; i < mclist.Count(); i++) { - - SkinDataClass * skindata = (SkinDataClass *)mclist[i]->localData; - - if (skindata==NULL) continue; - - ObjectState os = nodes[i]->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - - switch (SubObjSelLevel) { - - case OBJECT_SEL_LEVEL: - assert(0); - return; - - case VERTEX_SEL_LEVEL: -#if 0 // undo/redo - if (theHold.Holding()) { - theHold.Put(new VertexSelRestore(meshData,this)); - } -#endif - tobj->mesh.vertSel.SetAll(); - skindata->VertSel.SetAll(); - break; - } - - if (needsdel) { - tobj->DeleteThis(); - } - } - - /* - ** Get rid of the temporary copies of the INodes. - */ - nodes.DisposeTemporary(); - - /* - ** Tell our dependents that the selection set has changed - */ - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); -} - -void SkinModifierClass::InvertSelection(int selLevel) -{ - int needsdel = 0; - Interval valid = FOREVER; - ModContextList mclist; - INodeTab nodes; - - if (!InterfacePtr) return; - - InterfacePtr->GetModContexts(mclist,nodes); - InterfacePtr->ClearCurNamedSelSet(); - - for (int i = 0; i < mclist.Count(); i++) { - - SkinDataClass * skindata = (SkinDataClass *)mclist[i]->localData; - - if (skindata==NULL) continue; - - ObjectState os = nodes[i]->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - - switch (SubObjSelLevel) { - - case OBJECT_SEL_LEVEL: - assert(0); - return; - - case VERTEX_SEL_LEVEL: -#if 0 // undo/redo - if (theHold.Holding()) { - theHold.Put(new VertexSelRestore(meshData,this)); - } -#endif - for (int j=0; jmesh.vertSel.GetSize(); j++) { - if (tobj->mesh.vertSel[j]) tobj->mesh.vertSel.Clear(j); - else tobj->mesh.vertSel.Set(j); - } - skindata->VertSel = tobj->mesh.vertSel; - break; - } - - if (needsdel) { - tobj->DeleteThis(); - } - } - - /* - ** Get rid of the temporary copies of the INodes. - */ - nodes.DisposeTemporary(); - - /* - ** Tell our dependents that the selection set has changed - */ - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); - -} - -#endif // 0 - - -#if defined W3D_MAX4 //defined as in the project (.dsp) -//////////////////////////////////////////////////////////////////////////////////////// -int MeshDeformClass::NumSubObjTypes() -{ - return 1; -} -//////////////////////////////////////////////////////////////////////////////////////// -ISubObjType *MeshDeformClass::GetSubObjType(int i) -{ - static bool _initialized = false; - if(!_initialized){ - _initialized = true; - _SubObjectTypeVertex.SetName("Vertices"); - } - if(i == -1){ - if(GetSubObjectLevel() > 0){ - return GetSubObjType(GetSubObjectLevel()-1); - } - } - return &_SubObjectTypeVertex; -} -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeform.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeform.h deleted file mode 100644 index 9a2810d7b9..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeform.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/MeshDeform.h 6 4/24/01 6:02p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeform.H * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/19/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef __MESH_DEFORM_H -#define __MESH_DEFORM_H - -#include -#include "Vector.H" - -// Forward declarations -class MeshDeformPanelClass; -class MeshDeformModData; - - -/////////////////////////////////////////////////////////////////////////// -// -// Prototypes -// -/////////////////////////////////////////////////////////////////////////// -ClassDesc *Get_Mesh_Deform_Desc (void); -extern Class_ID _MeshDeformClassID; - - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformClass -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformClass : public OSModifier -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - MeshDeformClass (void) - : m_MaxInterface (NULL), - m_ModeMove (NULL), - m_ModeSelect (NULL), - m_ModeRotate (NULL), - m_ModeUScale (NULL), - m_ModeNUScale (NULL), - m_ModeSquash (NULL), - m_DeformState (1.0F), - m_pPanel (NULL), - m_CurrentSet (0), - m_bSetDirty (true), - m_VertColorChanging (false), - m_MaxSets (0), - m_hRollupWnd (NULL) { SetName ("WW Mesh Deformer"); Set_Max_Deform_Sets (1); } - - virtual ~MeshDeformClass (void) { } -#if defined W3D_MAX4 //defined as in the project (.dsp) - NumSubObjTypes(); - GetSubObjType(); -#endif - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - void Set_Deform_State (float state = 1.0F); - float Get_Deform_State (void) const { return m_DeformState; } - void Set_Vertex_Color (const Point3 &color, bool button_up); - void Get_Vertex_Color (Point3 &color); - void Set_Max_Deform_Sets (int max); - int Get_Max_Deform_Sets (void) const { return m_MaxSets; } - void Set_Current_Set (int index, bool update_selection); - int Get_Current_Set (void) const { return m_CurrentSet; } - void Update_UI (MeshDeformModData *mod_data); - void Auto_Apply (bool auto_apply = true); - - ////////////////////////////////////////////////////////////////////// - // Base class overrides - ////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////// - // From Animatable - ////////////////////////////////////////////////////////////////////// - void DeleteThis (void) { delete this; } - void GetClassName (TSTR& s) { s = TSTR(_T("WWDeform")); } - TCHAR * GetObjectName (void) { return _T("WWDamage"); } - SClass_ID SuperClassID (void) { return OSM_CLASS_ID; } - Class_ID ClassID (void) { return _MeshDeformClassID; } - //RefTargetHandle Clone(RemapDir& remap = NoRemap()); - void BeginEditParams (IObjParam *ip, ULONG flags,Animatable *prev); - void EndEditParams (IObjParam *ip, ULONG flags,Animatable *next); - - ////////////////////////////////////////////////////////////////////// - // From Modifier - ////////////////////////////////////////////////////////////////////// - ChannelMask ChannelsUsed (void); - ChannelMask ChannelsChanged (void); - void ModifyObject (TimeValue t, ModContext &mod_context, ObjectState* os, INode *node); - BOOL DependOnTopology (ModContext &mod_context) { return TRUE; } - int NeedUseSubselButton (void) { return TRUE; } - Class_ID InputType (void); - - ////////////////////////////////////////////////////////////////////// - // From ReferenceMaker - ////////////////////////////////////////////////////////////////////// - RefResult NotifyRefChanged (Interval time, RefTargetHandle htarget, PartID &part_id, RefMessage mesage); - IOResult SaveLocalData (ISave *save_obj, LocalModData *mod_context); - IOResult LoadLocalData (ILoad *load_obj, LocalModData **mod_context); - - ////////////////////////////////////////////////////////////////////// - // From BaseObject - ////////////////////////////////////////////////////////////////////// - CreateMouseCallBack * GetCreateMouseCallBack (void); - void ActivateSubobjSel (int level, XFormModes &modes); - int HitTest (TimeValue time_value, INode * node, int type, int crossing, int flags, IPoint2 *point, ViewExp *viewport, ModContext *mod_context); - void SelectSubComponent (HitRecord *hit_record, BOOL selected, BOOL all, BOOL invert); - - void GetSubObjectCenters (SubObjAxisCallback *cb, TimeValue t, INode *node, ModContext *mc); - void GetSubObjectTMs (SubObjAxisCallback *cb, TimeValue t, INode *node, ModContext *mc); - int SubObjectIndex (HitRecord *hitRec) { return hitRec->hitInfo; } - void ClearSelection (int selLevel); - - // Transformation managment - void Move (TimeValue time_val, Matrix3 &parent_tm, Matrix3 &tm_axis, Point3 &point, BOOL local_origin); - void Rotate (TimeValue time_val, Matrix3 &parent_tm, Matrix3 &tm_axis, Quat &rotation, BOOL local_origin); - void Scale (TimeValue time_val, Matrix3 &parent_tm, Matrix3 &tm_axis, Point3 &value, BOOL local_origin); - - void TransformStart (TimeValue time_val); - void TransformFinish (TimeValue time_val); - void TransformCancel (TimeValue time_val); -#if defined W3D_MAX4 //defined as in the project (.dsp) - ISubObjType * GetSubObjType(int i) ; -#endif - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - void Update_Current_Set (void); - void Update_Set_Count (void); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - IObjParam * m_MaxInterface; - HWND m_hRollupWnd; - MeshDeformPanelClass * m_pPanel; - float m_DeformState; - bool m_VertColorChanging; - - // Mode handlers - SelectModBoxCMode * m_ModeSelect; - MoveModBoxCMode * m_ModeMove; - RotateModBoxCMode * m_ModeRotate; - UScaleModBoxCMode * m_ModeUScale; - NUScaleModBoxCMode * m_ModeNUScale; - SquashModBoxCMode * m_ModeSquash; - - // Set managment - bool m_bSetDirty; - int m_CurrentSet; - int m_MaxSets; - - // Information - CStr m_OperationName; -}; - - -#endif //__MESH_DEFORM_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformData.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformData.cpp deleted file mode 100644 index aae3d910d2..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformData.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformData.cpp * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/26/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "MeshDeformData.h" -#include "util.h" -#include "MeshDeformSaveDefs.h" - - -/////////////////////////////////////////////////////////////////////////// -// -// ~MeshDeformModData -// -/////////////////////////////////////////////////////////////////////////// -MeshDeformModData::~MeshDeformModData (void) -{ - Free_Sets_List (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Record_Mesh_State -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformModData::Record_Mesh_State (TriObject &tri_obj, float state, bool update_all) -{ - // - // Ask each set to update its state - // - - for (int index = 0; index < m_SetsList.Count (); index ++) { - if (index != m_CurrentSet) { - if (update_all) { - m_SetsList[index]->Set_State (state); - } - m_SetsList[index]->Update_Mesh (tri_obj); - } - } - - if (m_CurrentSet < m_SetsList.Count ()) { - m_SetsList[m_CurrentSet]->Set_State (state); - m_SetsList[m_CurrentSet]->Update_Mesh (tri_obj); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Free_Sets_List -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformModData::Free_Sets_List (void) -{ - // - // Delete all the object pointers in the set list - // - for (int index = 0; index < m_SetsList.Count (); index ++) { - MeshDeformSetClass *set = m_SetsList[index]; - SAFE_DELETE (set); - } - - // Remove all the entries from the list - m_SetsList.Delete_All (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Max_Deform_Sets -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformModData::Set_Max_Deform_Sets (int max) -{ - int current_max = m_SetsList.Count (); - if (max > current_max) { - - // - // Add the new sets to the list - // - int sets_to_add = max - current_max; - for (int index = 0; index < sets_to_add; index ++) { - MeshDeformSetClass *set = new MeshDeformSetClass; - m_SetsList.Add (set); - } - - } else if (max < current_max) { - - // - // Remove the obsolete sets from the list - // - int sets_to_remove = current_max - max; - for (int index = 0; index < sets_to_remove; index ++) { - - // Restore the set before we delete it - Restore_Set (max); - - // Delete the set - MeshDeformSetClass *set = m_SetsList[max]; - SAFE_DELETE (set); - m_SetsList.Delete (max); - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Restore_Set -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformModData::Restore_Set (int set_index) -{ - if (set_index == -1) { - - // Restore ALL the set - for (int index = 0; index < m_SetsList.Count (); index ++) { - m_SetsList[index]->Restore_Members (); - } - - } else { - m_SetsList[set_index]->Restore_Members (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Save -// -/////////////////////////////////////////////////////////////////////////// -IOResult -MeshDeformModData::Save (ISave *save_obj) -{ - DWORD bytes = 0L; - save_obj->BeginChunk (DEFORM_CHUNK_INFO); - - // - // Write the set count info to the chunk - // - DeformChunk info = { 0 }; - info.SetCount = m_SetsList.Count (); - IOResult result = save_obj->Write (&info, sizeof (info), &bytes); - - save_obj->EndChunk (); - - // - // Now write a chunk for each set - // - for (int index = 0; (index < m_SetsList.Count ()) && (result == IO_OK); index ++) { - result = m_SetsList[index]->Save (save_obj); - } - - // Return IO_OK on success IO_ERROR on failure - return result; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Load -// -/////////////////////////////////////////////////////////////////////////// -IOResult -MeshDeformModData::Load (ILoad *load_obj) -{ - Free_Sets_List (); - DWORD bytes = 0L; - - // - // Is this the chunk we were expecting? - // - IOResult result = load_obj->OpenChunk (); - if ( (result == IO_OK) && - (load_obj->CurChunkID () == DEFORM_CHUNK_INFO)) { - - DeformChunk info = { 0 }; - result = load_obj->Read (&info, sizeof (info), &bytes); - load_obj->CloseChunk (); - - // - // Read the set information from the chunk - // - for (unsigned int index = 0; (index < info.SetCount) && (result == IO_OK); index ++) { - MeshDeformSetClass *set = new MeshDeformSetClass; - m_SetsList.Add (set); - result = set->Load (load_obj); - } - } - - // Return IO_OK on success IO_ERROR on failure - return result; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformData.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformData.h deleted file mode 100644 index c8cf20e29f..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformData.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformData.h * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/26/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef __MESH_DEFORM_DATA_H -#define __MESH_DEFORM_DATA_H - -#include -#include "Vector.H" -#include "MeshDeformSet.h" - - -/////////////////////////////////////////////////////////////////////////// -// -// Typedefs -// -/////////////////////////////////////////////////////////////////////////// -typedef DynamicVectorClass SETS_LIST; - - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformModData -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformModData : public LocalModData -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - MeshDeformModData (void) - : m_CurrentSet (0) { } - - virtual ~MeshDeformModData (void); - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - virtual LocalModData * Clone (void) { return new MeshDeformModData; } - void Record_Mesh_State (TriObject &tri_obj, float state, bool update_all); - - // Inline accessors - Mesh * Peek_Mesh (void) const { return m_SetsList[m_CurrentSet]->Peek_Mesh (); } - const Point3 * Peek_Orig_Vertex_Array (void) const { return m_SetsList[m_CurrentSet]->Peek_Orig_Vertex_Array (); } - Point3 * Peek_Vertex_OPStart_Array (void) const { return m_SetsList[m_CurrentSet]->Peek_Vertex_OPStart_Array (); } - VertColor * Peek_Vertex_Colors (void) const { return m_SetsList[m_CurrentSet]->Peek_Vertex_Colors (); } - - // Auto apply - bool Is_Auto_Apply (void) const { return m_SetsList[m_CurrentSet]->Does_Set_Auto_Apply (); } - void Auto_Apply (bool auto_apply = true) { m_SetsList[m_CurrentSet]->Auto_Apply (auto_apply); } - - // Data modifiers - void Update_Current_Data (void) { m_SetsList[m_CurrentSet]->Update_Current_Data (); } - void Set_Vertex_Position (int index, const Point3 &value) { m_SetsList[m_CurrentSet]->Set_Vertex_Position (index, value); } - void Set_Vertex_Color (int index, int color_index, const VertColor &value) { m_SetsList[m_CurrentSet]->Set_Vertex_Color (index, color_index, value); } - - // Set managment - void Set_Max_Deform_Sets (int max); - void Set_Current_Set (int set_index) { m_CurrentSet = set_index; } - int Get_Current_Set (void) const { return m_CurrentSet; } - void Select_Set (int set_index) { m_SetsList[set_index]->Select_Members (); } - void Update_Set (int set_index, DEFORM_CHANNELS flags) { m_SetsList[set_index]->Update_Members (flags); } - void Restore_Set (int set_index = -1); - MeshDeformSetClass & Peek_Set (int index) { return *(m_SetsList[index]); } - int Get_Set_Count (void) const { return m_SetsList.Count (); } - - // Persistent storage - IOResult Save (ISave *save_obj); - IOResult Load (ILoad *load_obj); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - void Resize_Vertex_Array (int count, int color_count); - void Copy_Vertex_Array (Mesh &mesh); - void Free_Sets_List (void); - void Util_Restore_Set (int set_index); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - - // Set managment - int m_CurrentSet; - SETS_LIST m_SetsList; -}; - - -#endif //__MESH_DEFORM_DATA_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformDefs.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformDefs.h deleted file mode 100644 index 22e43e3f31..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformDefs.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformDefs.h * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/28/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef __MESH_DEFORM_DEFS_H -#define __MESH_DEFORM_DEFS_H - -#include -#include "Vector.H" - -/////////////////////////////////////////////////////////////////////////// -// -// Constants -// -/////////////////////////////////////////////////////////////////////////// -typedef enum -{ - VERT_POSITION = 1, - VERT_COLORS = 2, - BOTH = VERT_POSITION | VERT_COLORS -} DEFORM_CHANNELS; - - -/////////////////////////////////////////////////////////////////////////// -// -// Structures -// -/////////////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////// -// -// VERT_INFO -// -// Used to represent position or color information for a vertex. -// -/////////////////////////////////////////////////////////////////////////// -typedef struct _VERT_INFO -{ - _VERT_INFO (void) - : index (0), - color_index (0), - value (0,0,0) { } - - _VERT_INFO (int vert_index, const Point3 &point, int vert_color_index = 0) - : index (vert_index), - color_index (vert_color_index), - value (point) { } - - UINT index; - UINT color_index; - Point3 value; - - // Don't care, DynamicVectorClass needs these - bool operator== (const _VERT_INFO &src) { return false; } - bool operator!= (const _VERT_INFO &src) { return true; } -} VERT_INFO; - - -/////////////////////////////////////////////////////////////////////////// -// -// Typedefs -// -/////////////////////////////////////////////////////////////////////////// -typedef DynamicVectorClass DEFORM_LIST; - - -#endif //__MESH_DEFORM_DEFS_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformPanel.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformPanel.cpp deleted file mode 100644 index 462835a396..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformPanel.cpp +++ /dev/null @@ -1,365 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformPanel.cpp * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/22/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "MeshDeformPanel.h" -#include "resource.h" -#include "util.h" -#include "MeshDeform.h" - -/////////////////////////////////////////////////////////////////////////// -// -// Local constants -// -/////////////////////////////////////////////////////////////////////////// -const char * const PANEL_OBJ_PROP = "WWPANELOBJ"; - - -/////////////////////////////////////////////////////////////////////////// -// -// Message_Proc -// -/////////////////////////////////////////////////////////////////////////// -BOOL WINAPI -MeshDeformPanelClass::Message_Proc -( - HWND hwnd, - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - // Lookup the controlling object for this panel - MeshDeformPanelClass *panel_obj = MeshDeformPanelClass::Get_Object (hwnd); - BOOL result = FALSE; - - switch (message) - { - // Create the controlling panel-object - case WM_INITDIALOG: - panel_obj = new MeshDeformPanelClass (hwnd); - SetProp (hwnd, PANEL_OBJ_PROP, (HANDLE)panel_obj); - break; - - case WM_DESTROY: - result = panel_obj->On_Message (message, wparam, lparam); - RemoveProp (hwnd, PANEL_OBJ_PROP); - SAFE_DELETE (panel_obj); - break; - } - - // Pass the message onto the controlling panel-object - if (panel_obj != NULL) { - result = panel_obj->On_Message (message, wparam, lparam); - } - - // Return the TRUE/FALSE result code - return result; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Get_Object -// -/////////////////////////////////////////////////////////////////////////// -MeshDeformPanelClass * -MeshDeformPanelClass::Get_Object (HWND hwnd) -{ - return (MeshDeformPanelClass *)::GetProp (hwnd, PANEL_OBJ_PROP); -} - - -/////////////////////////////////////////////////////////////////////////// -// -// On_Message -// -/////////////////////////////////////////////////////////////////////////// -BOOL -MeshDeformPanelClass::On_Message -( - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - switch (message) - { - case WM_INITDIALOG: - m_pColorSwatch = ::GetIColorSwatch (::GetDlgItem (m_hWnd, IDC_VERTEX_COLOR), RGB (0, 0, 0), "Vertex Color"); - m_pMaxSetsEdit = ::GetICustEdit (::GetDlgItem (m_hWnd, IDC_MAX_SETS_EDIT)); - m_pMaxSetsSpin = ::GetISpinner (::GetDlgItem (m_hWnd, IDC_MAX_SETS_SPIN)); - m_pLockSetsButton = ::GetICustButton (::GetDlgItem (m_hWnd, IDC_LOCK_SETS)); - - // - // Setup the 'max-sets' controls - // - m_pMaxSetsSpin->LinkToEdit (::GetDlgItem (m_hWnd, IDC_MAX_SETS_EDIT), EDITTYPE_INT); - m_pMaxSetsSpin->SetLimits (1, 20); - m_pMaxSetsEdit->SetText (1); - m_pMaxSetsSpin->SetValue (1, FALSE); - ::SetDlgItemInt (m_hWnd, IDC_CURRENT_SET_STATIC, 1, FALSE); - - // - // Setup the edit button - // - m_pLockSetsButton->SetType (CBT_CHECK); - m_pLockSetsButton->SetCheck (FALSE); - m_pLockSetsButton->SetHighlightColor (GREEN_WASH); - //m_pEditButton->SetType (CBT_CHECK); - //m_pEditButton->SetCheck (FALSE); - //m_pEditButton->SetHighlightColor (GREEN_WASH); - - // - // Setup the sliders - // - ::SendDlgItemMessage (m_hWnd, IDC_CURRENT_SET_SLIDER, TBM_SETRANGE, (WPARAM)TRUE, MAKELONG (1, 1)); - ::SendDlgItemMessage (m_hWnd, IDC_CURRENT_SET_SLIDER, TBM_SETPOS, (WPARAM)TRUE, 0L); - ::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_SETRANGE, (WPARAM)FALSE, MAKELONG (0, 10)); - ::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_SETPOS, (WPARAM)FALSE, 9L); - - // - // Ensure the sliders are repainted - // - //::InvalidateRect (::GetDlgItem (m_hWnd, IDC_STATE_SLIDER), NULL, TRUE); - //::InvalidateRect (::GetDlgItem (m_hWnd, IDC_CURRENT_SET_SLIDER), NULL, TRUE); - break; - - case WM_DESTROY: - ::ReleaseIColorSwatch (m_pColorSwatch); - ::ReleaseICustEdit (m_pMaxSetsEdit); - ::ReleaseISpinner (m_pMaxSetsSpin); - //::ReleaseICustButton (m_pEditButton); - m_pColorSwatch = NULL; - m_pMaxSetsEdit = NULL; - m_pMaxSetsSpin = NULL; - //m_pEditButton = NULL; - break; - - case WM_COMMAND: - On_Command (wparam, lparam); - break; - - case CC_COLOR_CHANGE: - { - // Pass the new color onto the mesh deformer - COLORREF color_ref = m_pColorSwatch->GetColor (); - VertColor color; - color.x = GetRValue (color_ref) / 255.0F; - color.y = GetGValue (color_ref) / 255.0F; - color.z = GetBValue (color_ref) / 255.0F; - m_pMeshDeformer->Set_Vertex_Color (color, HIWORD (wparam) != 0); - } - break; - - case WM_CUSTEDIT_ENTER: - case CC_SPINNER_CHANGE: - { - Set_Max_Sets (m_pMaxSetsEdit->GetInt (), true); - } - break; - - case WM_HSCROLL: - if ((HWND)lparam == ::GetDlgItem (m_hWnd, IDC_CURRENT_SET_SLIDER)) { - int pos = ::SendDlgItemMessage (m_hWnd, IDC_CURRENT_SET_SLIDER, TBM_GETPOS, 0, 0L); - Set_Current_Set (pos - 1, true); - } else { - int pos = ::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_GETPOS, 0, 0L); - m_pMeshDeformer->Set_Deform_State (((float)pos) / 10.0F); - - if (pos > 0) { - m_pColorSwatch->Enable (); - } else { - m_pColorSwatch->Disable (); - } - } - - break; - } - - return FALSE; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// On_Command -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformPanelClass::On_Command -( - WPARAM wparam, - LPARAM lparam -) -{ - switch (LOWORD (wparam)) - { - case IDC_MANUALAPPLY: - { - m_pMeshDeformer->Auto_Apply (Get_Auto_Apply_Check ()); - } - break; - - //case IDC_EDIT_BUTTON: - /*if (m_pEditButton->IsChecked ()) { - ::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, 100L); - ::EnableWindow (::GetDlgItem (m_hWnd, IDC_STATE_SLIDER), FALSE); - m_pColorSwatch->Enable (); - m_pMeshDeformer->Set_Deform_State (1.0F); - } else { - ::EnableWindow (::GetDlgItem (m_hWnd, IDC_STATE_SLIDER), TRUE); - m_pColorSwatch->Disable (); - }*/ - //break; - - case IDC_MAX_SETS_EDIT: - break; - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Deformer -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformPanelClass::Set_Deformer (MeshDeformClass *obj) -{ - if (m_pMeshDeformer != obj) { - m_pMeshDeformer = obj; - - // Set the slider position based on the current state of the deformer - float state = m_pMeshDeformer->Get_Deform_State (); - ::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, LPARAM(state * 10.0F)); - - // Now update the current vertex color - Update_Vertex_Color (); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Vertex_Color -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformPanelClass::Update_Vertex_Color (void) -{ - if (m_pMeshDeformer != NULL) { - - // Update the color swatch with data from the deformer - Point3 color; - m_pMeshDeformer->Get_Vertex_Color (color); - m_pColorSwatch->SetColor (RGB (int(color.x * 255.0F), int(color.y * 255.0F), int(color.z * 255.0F)), FALSE); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Max_Sets -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformPanelClass::Set_Max_Sets -( - int max, - bool notify -) -{ - // Update the UI - ::SendDlgItemMessage (m_hWnd, IDC_CURRENT_SET_SLIDER, TBM_SETRANGE, (WPARAM)TRUE, MAKELONG (1, max)); - ::SetDlgItemInt (m_hWnd, IDC_CURRENT_SET_STATIC, max, TRUE); - - if (notify == false) { - m_pMaxSetsSpin->SetValue (max, TRUE); - } else if (m_pMeshDeformer != NULL) { - - // Update the deformer - m_pMeshDeformer->Set_Max_Deform_Sets (max); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Current_Set -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformPanelClass::Set_Current_Set -( - int set, - bool notify -) -{ - // Update the UI - ::SetDlgItemInt (m_hWnd, IDC_CURRENT_SET_STATIC, set + 1, TRUE); - - if (notify == false) { - ::SendDlgItemMessage (m_hWnd, IDC_CURRENT_SET_SLIDER, TBM_SETPOS, (WPARAM)TRUE, set + 1); - } else if (m_pMeshDeformer != NULL) { - - // Update the deformer - m_pMeshDeformer->Set_Current_Set (set, true); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Current_State -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformPanelClass::Set_Current_State (float state) -{ - ::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_SETPOS, (WPARAM)TRUE, LPARAM(state * 10.0F)); - return ; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformPanel.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformPanel.h deleted file mode 100644 index 1408c2c52e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformPanel.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformPanel.H * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/22/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef __MESH_DEFORM_PANEL_H -#define __MESH_DEFORM_PANEL_H - -#include -#include "resource.h" - -// Forward declarations -class MeshDeformClass; - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformPanelClass -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformPanelClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - MeshDeformPanelClass (HWND hwnd) - : m_hWnd (hwnd), - m_pColorSwatch (NULL), - m_pMaxSetsSpin (NULL), - m_pMeshDeformer (NULL), - m_pLockSetsButton (NULL), - m_pMaxSetsEdit (NULL) { } - virtual ~MeshDeformPanelClass (void) { } - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - - // Inline accessors - IColorSwatch * Get_Color_Swatch (void) const { return m_pColorSwatch; } - COLORREF Get_Vertex_Color (void) const { return m_pColorSwatch->GetColor (); } - void Set_Vertex_Color (COLORREF color) { m_pColorSwatch->SetColor (color); } - void Set_Deformer (MeshDeformClass *obj); - BOOL Is_Edit_Mode (void) const { return (::SendDlgItemMessage (m_hWnd, IDC_STATE_SLIDER, TBM_GETPOS, 0, 0L) > 0); } - BOOL Are_Sets_Tied (void) const { return m_pLockSetsButton->IsChecked (); } - int Get_Current_Set (void) const { return ::SendDlgItemMessage (m_hWnd, IDC_CURRENT_SET_SLIDER, TBM_GETPOS, 0, 0L); } - void Set_Current_Set (int set, bool notify = false); - void Set_Max_Sets (int max, bool notify = false); - void Set_Current_State (float state); - void Set_Auto_Apply_Check (bool onoff) { ::SendDlgItemMessage (m_hWnd, IDC_MANUALAPPLY, BM_SETCHECK, (WPARAM)(!onoff), 0L); } - bool Get_Auto_Apply_Check (void) const { return ::SendDlgItemMessage (m_hWnd, IDC_MANUALAPPLY, BM_GETCHECK, 0, 0L) == 0; } - - // Update methods - void Update_Vertex_Color (void); - - ////////////////////////////////////////////////////////////////////// - // Static methods - ////////////////////////////////////////////////////////////////////// - static BOOL WINAPI Message_Proc (HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); - static MeshDeformPanelClass * Get_Object (HWND hwnd); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - BOOL On_Message (UINT message, WPARAM wparam, LPARAM lparam); - void On_Command (WPARAM wparam, LPARAM lparam); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - HWND m_hWnd; - IColorSwatch * m_pColorSwatch; - ICustEdit * m_pMaxSetsEdit; - ISpinnerControl * m_pMaxSetsSpin; - ICustButton * m_pLockSetsButton; - MeshDeformClass * m_pMeshDeformer; -}; - - -#endif //__MESH_DEFORM_PANEL_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSave.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSave.cpp deleted file mode 100644 index f9ff592d57..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSave.cpp +++ /dev/null @@ -1,420 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/MeshDeformSave.cpp 6 11/12/99 11:12a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformSafe.CPP - * * - * Programmer : Patrick Smith * - * * - * Start Date : 05/28/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "MeshDeform.h" -#include "MeshDeformSave.h" -#include "MeshDeformData.h" -#include "MeshDeformSet.h" -#include "MeshDeformSaveSet.h" -#include "util.h" -#include "modstack.h" -#include "meshbuild.h" -#include "meshsave.h" - -/////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveClass::Initialize -( - MeshBuilderClass &builder, - Object * object, - Mesh & mesh, - Matrix3 * transform -) -{ - // Start fresh - Reset (); - - // - // Attempt to gain access to the IDerivedObject this node references - // - int test = object->SuperClassID (); - int test2 = GEN_DERIVOB_CLASS_ID; - if ((object != NULL) && - (object->SuperClassID () == GEN_DERIVOB_CLASS_ID)) { - - // - // Loop through all the modifiers and see if we can find the - // Westwood Damage Mesh modifier. - // - IDerivedObject *derived_object = static_cast (object); - int modifier_count = derived_object->NumModifiers (); - bool found = false; - for (int index = 0; (index < modifier_count) && !found; index ++) { - - // - // If this is the right modifier, then initialize using the - // data it contains. - // - Modifier *modifier = derived_object->GetModifier (index); - if ((modifier != NULL) && (modifier->ClassID () == _MeshDeformClassID)) { - - // - // Attempt to get at the modifier data for this context - // - ModContext *mod_context = derived_object->GetModContext (index); - if ((mod_context != NULL) && (mod_context->localData != NULL)) { - MeshDeformModData *mod_data = static_cast (mod_context->localData); - Initialize (builder, mesh, *mod_data, transform); - } - - // Found it! - found = true; - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Initialize -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveClass::Initialize -( - MeshBuilderClass & builder, - Mesh & mesh, - MeshDeformModData & mod_data, - Matrix3 * transform -) -{ - // - // Loop through all the sets in the modifier - // - for (int index = 0; index < mod_data.Get_Set_Count (); index ++) { - - // - // If this set isn't empty then add its data to our list - // - MeshDeformSetClass &deform_set = mod_data.Peek_Set (index); - if (deform_set.Is_Empty () == false) { - - // - // Add this set to our list - // - MeshDeformSaveSetClass *save_set = new MeshDeformSaveSetClass; - deform_set.Save (builder, mesh, *save_set, transform); - m_DeformSets.Add (save_set); - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Reset -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveClass::Reset (void) -{ - // - // Delete all the damage sets - // - for (int index = 0; index < m_DeformSets.Count (); index ++) { - SAFE_DELETE (m_DeformSets[index]); - } - - m_DeformSets.Delete_All (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Export -// -/////////////////////////////////////////////////////////////////////////// -bool -MeshDeformSaveClass::Export (ChunkSaveClass &chunk_save) -{ - bool retval = true; - - if (m_DeformSets.Count() > 0) { - - retval = chunk_save.Begin_Chunk (W3D_CHUNK_DEFORM); - if (retval) { - - // - // Write the deform header to the file - // - W3dMeshDeform header = { 0 }; - header.SetCount = m_DeformSets.Count (); - header.AlphaPasses = m_AlphaPasses; - retval &= (chunk_save.Write (&header, sizeof (header)) == sizeof (header)); - if (retval) { - - // - // Export all the sets in the deformation - // - retval &= Export_Sets (chunk_save); - } - - retval &= chunk_save.End_Chunk (); - } - } - - // Return the true/false result code - return retval; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Export_Sets -// -/////////////////////////////////////////////////////////////////////////// -bool -MeshDeformSaveClass::Export_Sets (ChunkSaveClass &chunk_save) -{ - bool retval = true; - - // - // Loop through all the sets and write them to the file - // - for (int set_index = 0; (set_index < m_DeformSets.Count ()) && retval; set_index ++) { - retval &= chunk_save.Begin_Chunk (W3D_CHUNK_DEFORM_SET); - if (retval) { - - // - // Write a chunk of information out for this set - // - MeshDeformSaveSetClass *set_save = m_DeformSets[set_index]; - W3dDeformSetInfo set_info = { 0 }; - set_info.KeyframeCount = set_save->Get_Keyframe_Count (); - set_info.flags = set_save->Get_Flags (); - retval &= (chunk_save.Write (&set_info, sizeof (set_info)) == sizeof (set_info)); - if (retval) { - - // - // Export all the keyframes for this chunk - // - retval &= Export_Keyframes (chunk_save, *set_save); - } - - retval &= chunk_save.End_Chunk (); - } - } - - // Return the true/false result code - return retval; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Export_Keyframes -// -/////////////////////////////////////////////////////////////////////////// -bool -MeshDeformSaveClass::Export_Keyframes -( - ChunkSaveClass & chunk_save, - MeshDeformSaveSetClass &set_save -) -{ - bool retval = true; - - // - // Loop through all the keyframes in the set - // - int count = set_save.Get_Keyframe_Count (); - for (int keyframe_index = 0; (keyframe_index < count) && retval; keyframe_index ++) { - - // - // Write a chunk of information out for this keyframe - // - retval &= chunk_save.Begin_Chunk (W3D_CHUNK_DEFORM_KEYFRAME); - if (retval) { - W3dDeformKeyframeInfo keyframe_info = { 0 }; - keyframe_info.DeformPercent = set_save.Get_Deform_State (keyframe_index); - keyframe_info.DataCount = set_save.Get_Deform_Data_Count (keyframe_index); - - retval &= (chunk_save.Write (&keyframe_info, sizeof (keyframe_info)) == sizeof (keyframe_info)); - if (retval) { - - // - // Loop through all the verticies in this keyframe - // - int data_count = set_save.Get_Deform_Data_Count (keyframe_index); - for (int index = 0; (index < data_count) && retval; index ++) { - MeshDeformSaveSetClass::DEFORM_DATA &data = set_save.Get_Deform_Data (keyframe_index, index); - - // - // Write a chunk of information out for this vertex - // - retval &= chunk_save.Begin_Chunk (W3D_CHUNK_DEFORM_DATA); - if (retval) { - W3dDeformData data_struct = { 0 }; - data_struct.VertexIndex = data.vert_index; - data_struct.Position.X = data.position.x; - data_struct.Position.Y = data.position.y; - data_struct.Position.Z = data.position.z; - data_struct.Color.R = data.color.x * 255; - data_struct.Color.G = data.color.y * 255; - data_struct.Color.B = data.color.z * 255; - - // If we are using vertex alpha instead of vertex color, then convert - // the v-color into an alpha setting - data_struct.Color.A = 255; - if (m_AlphaPasses != 0) { - data_struct.Color.A = (data_struct.Color.R + data_struct.Color.G + data_struct.Color.B) / 3.0F; - } - - retval &= (chunk_save.Write (&data_struct, sizeof (data_struct)) == sizeof (data_struct)); - retval &= chunk_save.End_Chunk (); - } - } - } - - retval &= chunk_save.End_Chunk (); - } - } - - // Return the true/false result code - return retval; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Re_Index -// -/////////////////////////////////////////////////////////////////////////// -/*void -MeshDeformSaveClass::Re_Index (MeshBuilderClass &builder) -{ - DynamicVectorClass temp_list; - - // - // Reindex each set of deform data - // - for (int set_index = 0; set_index < m_DeformSets.Count (); set_index ++) { - MeshDeformSaveSetClass *set_save = m_DeformSets[set_index]; - - // - // Loop through all the deform entries in this set - // - for (int keyframe_index = 0; keyframe_index < set_save->Get_Keyframe_Count (); keyframe_index ++) { - temp_list.Delete_All (); - for (int index = 0; index < set_save->Get_Deform_Data_Count (keyframe_index); index ++) { - MeshDeformSaveSetClass::DEFORM_DATA &data = set_save->Get_Deform_Data (keyframe_index, index); - - // - // Now try to find the 'W3D' index of this vertex (its different than the max version). - // - //bool found = false; - for (int vert_index = 0; vert_index < builder.Get_Vertex_Count (); vert_index++) { - MeshBuilderClass::VertClass &vert = builder.Get_Vertex (vert_index); - - // - // Reindex this vertex if its the one we are looking for. - // - if (vert.Id == (int)data.vert_index) { - MeshDeformSaveSetClass::DEFORM_DATA new_data = data; - new_data.vert_index = vert_index; - temp_list.Add (new_data); - //data.vert_index = vert_index; - //found = true; - } - } - } - - set_save->Replace_Deform_Data (keyframe_index, temp_list); - } - } - - return ; -}*/ - - -/////////////////////////////////////////////////////////////////////////// -// -// Does_Deformer_Modify_DCG -// -/////////////////////////////////////////////////////////////////////////// -bool -MeshDeformSaveClass::Does_Deformer_Modify_DCG (void) -{ - bool retval = false; - - // - // Loop through all the sets - // - for (int set_index = 0; (set_index < m_DeformSets.Count ()) && !retval; set_index ++) { - MeshDeformSaveSetClass *set_save = m_DeformSets[set_index]; - if (set_save) { - - // - // Loop through all the keyframes in this set - // - int count = set_save->Get_Keyframe_Count (); - for (int keyframe_index = 0; (keyframe_index < count) && !retval; keyframe_index ++) { - - // - // Loop through all the entries in this keyframe - // - int data_count = set_save->Get_Deform_Data_Count (keyframe_index); - for (int index = 0; (index < data_count) && !retval; index ++) { - MeshDeformSaveSetClass::DEFORM_DATA &data = set_save->Get_Deform_Data (keyframe_index, index); - - // - // If the color is not 'white' then we will - // modify the DCG array. - // - if ((data.color.x != 1) || - (data.color.y != 1) || - (data.color.z != 1)) { - retval = true; - } - } - } - } - } - - // Return the true/false result code - return retval; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSave.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSave.h deleted file mode 100644 index 03e2c50d36..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSave.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/MeshDeformSave.h 4 7/07/99 11:52a Patrick $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformSafe.H - * * - * Programmer : Patrick Smith * - * * - * Start Date : 05/28/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef __MESH_DEFORM_SAVE_H -#define __MESH_DEFORM_SAVE_H - -#include -#include "Vector.H" - -// Forward declarations -class ChunkSaveClass; -class MeshDeformModData; -class MeshDeformSaveSetClass; -class MeshBuilderClass; -class MeshDeformSaveSetClass; - - -/////////////////////////////////////////////////////////////////////////// -// -// Typdefs -// -/////////////////////////////////////////////////////////////////////////// -typedef DynamicVectorClass DEFORM_SAVE_LIST; - - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformSaveClass -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformSaveClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - MeshDeformSaveClass (void) - : m_AlphaPasses (0) { } - ~MeshDeformSaveClass (void) { Reset (); } - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - void Initialize (MeshBuilderClass &builder, Object *object, Mesh &mesh, Matrix3 *transform = NULL); - void Initialize (MeshBuilderClass &builder, Mesh &mesh, MeshDeformModData &mod_data, Matrix3 *transform = NULL); - - //void Re_Index (MeshBuilderClass &builder); - bool Export (ChunkSaveClass &chunk_save); - - void Reset (void); - bool Is_Empty (void) const { return m_DeformSets.Count () == 0; } - - bool Does_Deformer_Modify_DCG (void); - - unsigned int Get_Alpha_Passes (void) const { return m_AlphaPasses; } - void Set_Alpha_Passes (unsigned int pass_mask) { m_AlphaPasses = pass_mask; } - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - bool Export_Sets (ChunkSaveClass &chunk_save); - bool Export_Keyframes (ChunkSaveClass &chunk_save, MeshDeformSaveSetClass &set_save); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - DEFORM_SAVE_LIST m_DeformSets; - unsigned int m_AlphaPasses; -}; - -#endif //__MESH_DEFORM_SAVE_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h deleted file mode 100644 index 1b3b1ccab1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveDefs.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformData.cpp * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 06/07/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef __MESH_DEFORM_SAVE_DEFS_H -#define __MESH_DEFORM_SAVE_DEFS_H - -#include - -/////////////////////////////////////////////////////////////////////////// -// -// Constants -// -/////////////////////////////////////////////////////////////////////////// -typedef enum -{ - DEFORM_CHUNK_INFO = 0x000000001, - DEFORM_CHUNK_SET_INFO, - DEFORM_CHUNK_KEYFRAME_INFO, - DEFORM_CHUNK_POSITION_DATA, - DEFORM_CHUNK_POSITION_VERTS, - DEFORM_CHUNK_COLOR_DATA, - DEFORM_CHUNK_COLOR_VERTS -} DEFORM_CHUNK_IDS; - -/////////////////////////////////////////////////////////////////////////// -// -// Structures -// -/////////////////////////////////////////////////////////////////////////// - -// -// Deform information. Each mesh can have sets of keyframes of -// deform info associated with it. -// -struct DeformChunk -{ - uint32 SetCount; - uint32 reserved[4]; -}; - -// -// Deform set information. Each set is made up of a series -// of keyframes. -// -struct DeformChunkSetInfo -{ - uint32 KeyframeCount; - uint32 flags; - uint32 NumVerticies; - uint32 NumVertexColors; - uint32 reserved[2]; -}; - -#define DEFORM_SET_MANUAL_DEFORM 0x00000001 // set is isn't applied during sphere or point tests. - -// -// Deform keyframe information. Each keyframe is made up of -// a set of per-vert deform data. -// -struct DeformChunkKeyframeInfo -{ - float32 DeformPercent; - uint32 VertexCount; - uint32 ColorCount; - uint32 reserved[2]; -}; - -// -// Deform data. Contains deform information about a vertex -// in the mesh. -// -struct DeformDataChunk -{ - uint32 VertexIndex; - uint32 ColorIndex; - Point3 Value; - uint32 reserved[2]; -}; - - -#endif //__MESH_DEFORM_SAVE_DEFS_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp deleted file mode 100644 index 9992ddb153..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/MeshDeformSaveSet.cpp 2 6/16/99 6:56p Patrick $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformSaveSet.CPP - * * - * Programmer : Patrick Smith * - * * - * Start Date : 05/28/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "MeshDeformSaveSet.h" -#include "util.h" - - -//////////////////////////////////////////////////////////////////////// -// -// Reset -// -//////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveSetClass::Reset (void) -{ - // - // Free all the keyframe pointers in our list - // - for (int index = 0; index < m_DeformData.Count (); index ++) { - SAFE_DELETE (m_DeformData[index]); - } - - m_DeformData.Delete_All (); - m_CurrentKeyFrame = NULL; - return ; -} - - -//////////////////////////////////////////////////////////////////////// -// -// Begin_Keyframe -// -//////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveSetClass::Begin_Keyframe (float state) -{ - // - // Allocate a new keyframe structure - // - m_CurrentKeyFrame = new KEYFRAME; - m_CurrentKeyFrame->state = state; - - // - // Add this new keyframe to the end of our list - // - m_DeformData.Add (m_CurrentKeyFrame); - return ; -} - - -//////////////////////////////////////////////////////////////////////// -// -// End_Keyframe -// -//////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveSetClass::End_Keyframe (void) -{ - m_CurrentKeyFrame = NULL; - return ; -} - - -//////////////////////////////////////////////////////////////////////// -// -// Add_Vert -// -//////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveSetClass::Add_Vert -( - UINT vert_index, - const Point3 & position, - const VertColor & color -) -{ - // State OK? - assert (m_CurrentKeyFrame != NULL); - if (m_CurrentKeyFrame != NULL) { - - // - // Create a structure that will hold the - // vertex information. - // - DEFORM_DATA data; - data.vert_index = vert_index; - data.position = position; - data.color = color; - - // - // Add this vertex information to the keyframe list - // - m_CurrentKeyFrame->deform_list.Add (data); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////// -// -// Replace_Deform_Data -// -//////////////////////////////////////////////////////////////////////// -void -MeshDeformSaveSetClass::Replace_Deform_Data -( - int keyframe_index, - DynamicVectorClass &list -) -{ - KEYFRAME *key_frame = m_DeformData[keyframe_index]; - if (key_frame != NULL) { - - // - // Replace the vertex deformation list for the keyframe - // - key_frame->deform_list.Delete_All (); - key_frame->deform_list = list; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////// -// -// Get_Deform_Count -// -//////////////////////////////////////////////////////////////////////// -/*int -MeshDeformSaveSetClass::Get_Deform_Count (void) const -{ - // - // Count up all the deform entries for all the keyframes - // - int count = 0; - for (int index = 0; index < m_DeformData.Count (); index ++) { - KEYFRAME *key_frame = m_DeformData[index]; - if (key_frame != NULL) { - count += key_frame->deform_list.Count (); - } - } - - return count; -}*/ - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.h deleted file mode 100644 index 59de050ca1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSaveSet.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/MeshDeformSaveSet.h 2 6/16/99 6:56p Patrick $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformSaveSet.H - * * - * Programmer : Patrick Smith * - * * - * Start Date : 05/28/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef __MESH_DEFORM_SAVE_SET_H -#define __MESH_DEFORM_SAVE_SET_H - -#include -#include "Vector.H" - -// Forward declarations -class ChunkSaveClass; - - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformSaveSetClass -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformSaveSetClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public friends - ////////////////////////////////////////////////////////////////////// - friend class MeshDeformSaveClass; - - - protected: - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected data types - ////////////////////////////////////////////////////////////////////// - typedef struct _DEFORM_DATA - { - UINT vert_index; - Point3 position; - VertColor color; - - // Don't care, DynamicVectorClass needs these - bool operator== (const _DEFORM_DATA &src) { return false; } - bool operator!= (const _DEFORM_DATA &src) { return true; } - } DEFORM_DATA; - - ////////////////////////////////////////////////////////////////////// - // Protected data types - ////////////////////////////////////////////////////////////////////// - typedef struct - { - float state; - DynamicVectorClass deform_list; - } KEYFRAME; - - -public: - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - MeshDeformSaveSetClass (void) - : m_Flags (0), - m_CurrentKeyFrame (NULL) { } - ~MeshDeformSaveSetClass (void) { Reset (); } - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - - // Keyframe managment - void Begin_Keyframe (float state); - void End_Keyframe (void); - - // Vertex managment - void Add_Vert (UINT vert_index, const Point3 &position, const VertColor &color); - - // Misc - void Reset (void); - bool Is_Empty (void) const { return m_DeformData.Count () == 0; } - - // Flag support - bool Get_Flag (unsigned int flag) const { return (m_Flags & flag) == flag; } - void Set_Flag (unsigned int flag, bool value) { if (value) (m_Flags |= flag); else (m_Flags &= ~flag); } - unsigned int Get_Flags (void) const { return m_Flags; } - - // Enumeration - float Get_Deform_State (int key_frame) const { return m_DeformData[key_frame]->state; } - int Get_Keyframe_Count (void) const { return m_DeformData.Count (); } - int Get_Deform_Data_Count (int key_frame) const { return m_DeformData[key_frame]->deform_list.Count (); } - DEFORM_DATA & Get_Deform_Data (int key_frame, int index) { return m_DeformData[key_frame]->deform_list[index]; } - void Replace_Deform_Data (int keyframe_index, DynamicVectorClass &list); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - DynamicVectorClass m_DeformData; - KEYFRAME * m_CurrentKeyFrame; - unsigned int m_Flags; -}; - -#endif //__MESH_DEFORM_SAVE_SET_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSet.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSet.cpp deleted file mode 100644 index aa6088ff08..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSet.cpp +++ /dev/null @@ -1,1534 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformSet.cpp * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/26/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "MeshDeformSet.h" -#include "util.h" -#include "MeshDeformSaveSet.h" -#include "meshbuild.h" -#include "MeshDeformSaveDefs.h" -#include "MeshDeformDefs.h" - - -/////////////////////////////////////////////////////////////////////////// -// -// Constants -// -/////////////////////////////////////////////////////////////////////////// -const int MAX_DEFORM_KEY_FRAMES = 10; - - -/////////////////////////////////////////////////////////////////////////// -// -// ~MeshDeformSetClass -// -/////////////////////////////////////////////////////////////////////////// -MeshDeformSetClass::~MeshDeformSetClass (void) -{ - SAFE_DELETE (m_pMesh); - SAFE_DELETE (m_pVertexArray); - SAFE_DELETE (m_pVertexOPStartArray); - SAFE_DELETE (m_pVertexColors); - Free_Key_Frames (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Current_Key_Frame -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Set_Current_Key_Frame (int index) -{ - if (index >= -1 && index < MAX_DEFORM_KEY_FRAMES) { - m_CurrentKeyFrame = index; - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Vertex_Position -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Set_Vertex_Position -( - int index, - const Point3 & value -) -{ - DEFORM_LIST &verticies = m_KeyFrames[m_CurrentKeyFrame]->verticies; - BitArray &affected_verts = m_KeyFrames[m_CurrentKeyFrame]->affected_verts; - - // - // Set the vert's position - // - m_pMesh->verts[index] = value; - verticies.Add (VERT_INFO (index, value)); - - // - // Make sure we remember that this vert is affected - // - affected_verts.Set (index, 1); - m_SetMembers.Set (index, 1); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_Vertex_Color -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Set_Vertex_Color -( - int index, - int color_index, - const VertColor & value -) -{ - DEFORM_LIST &colors = m_KeyFrames[m_CurrentKeyFrame]->colors; - BitArray &affected_colors = m_KeyFrames[m_CurrentKeyFrame]->affected_colors; - - // - // Set the vert's color - // - m_pMesh->vertCol[color_index] = value; - colors.Add (VERT_INFO (index, value, color_index)); - - // - // Make sure we remember that this vert color is affected - // - affected_colors.Set (index, 1); - m_SetMembers.Set (index, 1); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Set_Members -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Update_Set_Members (void) -{ - // - // Examine each keyframe - // - m_SetMembers.ClearAll (); - for (int index = 0; index < m_KeyFrames.Count (); index ++) { - BitArray &affected_verts = m_KeyFrames[index]->affected_verts; - BitArray &affected_colors = m_KeyFrames[index]->affected_colors; - - // - // Mark the verts that are affected by this keyframe - // - for (int vert = 0; vert < m_VertexCount; vert ++) { - if (affected_verts[vert] || affected_colors[vert]) { - m_SetMembers.Set (vert, 1); - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Collapse_Keyframe_Data -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Collapse_Keyframe_Data (int keyframe) -{ - DEFORM_LIST &verticies = m_KeyFrames[keyframe]->verticies; - DEFORM_LIST &colors = m_KeyFrames[keyframe]->colors; - BitArray &affected_verts = m_KeyFrames[keyframe]->affected_verts; - BitArray &affected_colors = m_KeyFrames[keyframe]->affected_colors; - - // - // Collapse the vertex position data - // - for (int index = 0; index < verticies.Count (); index ++) { - VERT_INFO &info = verticies[index]; - - // - // If this vertex is unchanged, then remove it - // from the list. - // - if (m_pVertexArray[index] == info.value) { - verticies.Delete (index); - index --; - } else { - affected_verts.Set (info.index, 1); - m_SetMembers.Set (info.index, 1); - } - } - - - // - // Collapse the vertex color data - // - for (index = 0; index < colors.Count (); index ++) { - VERT_INFO &info = colors[index]; - - // - // If this vertex is unchanged, then remove it - // from the list. - // - if (m_pVertexColors[index] == info.value) { - verticies.Delete (index); - index --; - } else { - affected_colors.Set (info.index, 1); - m_SetMembers.Set (info.index, 1); - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Reset_Key_Frame_Verts -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Reset_Key_Frame_Verts (int keyframe) -{ - DEFORM_LIST &verticies = m_KeyFrames[keyframe]->verticies; - BitArray &affected_verts = m_KeyFrames[keyframe]->affected_verts; - - // - // Reset all data for this keyframe - // - affected_verts.ClearAll (); - verticies.Delete_All (); - - // - // Regenerate the list of set members - // - Update_Set_Members (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Reset_Key_Frame_Colors -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Reset_Key_Frame_Colors (int keyframe) -{ - DEFORM_LIST &colors = m_KeyFrames[keyframe]->colors; - BitArray &affected_colors = m_KeyFrames[keyframe]->affected_colors; - - // - // Reset all data for this keyframe - // - affected_colors.ClearAll (); - colors.Delete_All (); - - // - // Regenerate the list of set members - // - Update_Set_Members (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Current_Data -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Update_Current_Data (void) -{ - DEFORM_LIST &verticies = m_KeyFrames[m_CurrentKeyFrame]->verticies; - DEFORM_LIST &colors = m_KeyFrames[m_CurrentKeyFrame]->colors; - BitArray &affected_verts = m_KeyFrames[m_CurrentKeyFrame]->affected_verts; - BitArray &affected_colors = m_KeyFrames[m_CurrentKeyFrame]->affected_colors; - - // - // Assume we have no modifications for this keyframe - // - affected_verts.ClearAll (); - affected_colors.ClearAll (); - verticies.Delete_All (); - colors.Delete_All (); - - // - // Record the vertex position data - // - for (int index = 0; index < m_VertexCount; index ++) { - - // Is this vertex's position different than the undeformed mesh? - Point3 orig = m_pVertexArray[index]; - Point3 current = m_pMesh->verts[index]; - - //Apply_Position_Changes (index, m_CurrentKeyFrame, orig); - - if ( (orig.x != current.x) || - (orig.y != current.y) || - (orig.z != current.z)) { - - // - // Record this vertex's position in our lists - // - affected_verts.Set (index, 1); - verticies.Add (VERT_INFO (index, m_pMesh->verts[index])); - } - } - - // Only do this if the mesh is using vertex coloring - if (m_pMesh->numCVerts >= m_pMesh->numVerts) { - - // - // Record the vertex color data - // - for (int face = 0; face < m_pMesh->numFaces; face ++) { - for (int vert = 0; vert < 3; vert ++) { - - // - // Has this vertex color changed? - // - int vertex_index = m_pMesh->faces[face].v[vert]; - int color_index = m_pMesh->vcFace[face].t[vert]; - VertColor orig = m_pVertexColors[color_index]; - VertColor current = m_pMesh->vertCol[color_index]; - if ( (orig.x != current.x) || - (orig.y != current.y) || - (orig.z != current.z)) { - affected_colors.Set (vertex_index, 1); - colors.Add (VERT_INFO (vertex_index, m_pMesh->vertCol[color_index], color_index)); - } - } - } - } - - // - // Rebuild the list of verticies this 'set' affects - // - Update_Set_Members (); - - // - // Collapse all unsused data from the remainder of the keyframes - // - for (index = 0; index < m_KeyFrames.Count (); index ++) { - //Collapse_Keyframe_Data (index); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Key_Frame -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Update_Key_Frame (int key_frame) -{ - DEFORM_LIST &verticies = m_KeyFrames[key_frame]->verticies; - DEFORM_LIST &colors = m_KeyFrames[key_frame]->colors; - BitArray &affected_verts = m_KeyFrames[key_frame]->affected_verts; - BitArray &affected_colors = m_KeyFrames[key_frame]->affected_colors; - - if ((key_frame == m_CurrentKeyFrame) || - (verticies.Count () > 0) || - (colors.Count () > 0)) { - - // Clear all entries from this keyframe - verticies.Delete_All (); - colors.Delete_All (); - - // - // Copy the vertex position changes - // - for (int vert = 0; vert < m_pMesh->numVerts; vert ++) { - if (affected_verts[vert]) { - verticies.Add (VERT_INFO (vert, m_pMesh->verts[vert])); - } - } - - // - // Copy the vertex color changes - // - - // Only do this if the mesh is using vertex coloring - if (m_pMesh->numCVerts >= m_pMesh->numVerts) { - for (int face = 0; face < m_pMesh->numFaces; face ++) { - - if (affected_colors[m_pMesh->faces[face].v[0]]) { - int color_index = m_pMesh->vcFace[face].t[0]; - colors.Add (VERT_INFO (m_pMesh->faces[face].v[0], m_pMesh->vertCol[color_index], color_index)); - } - - if (affected_colors[m_pMesh->faces[face].v[1]]) { - int color_index = m_pMesh->vcFace[face].t[1]; - colors.Add (VERT_INFO (m_pMesh->faces[face].v[1], m_pMesh->vertCol[color_index], color_index)); - } - - if (affected_colors[m_pMesh->faces[face].v[2]]) { - int color_index = m_pMesh->vcFace[face].t[2]; - colors.Add (VERT_INFO (m_pMesh->faces[face].v[2], m_pMesh->vertCol[color_index], color_index)); - } - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Init_Key_Frames -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Init_Key_Frames (void) -{ - // - // For now, add all the key frames upfront - // - for (int index = 0; index < MAX_DEFORM_KEY_FRAMES; index ++) { - KEY_FRAME *key_frame = new KEY_FRAME; - m_KeyFrames.Add (key_frame); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Free_Key_Frames -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Free_Key_Frames (void) -{ - // - // Loop through and free all the key frames - // - for (int index = 0; index < m_KeyFrames.Count (); index ++) { - KEY_FRAME *key_frame = m_KeyFrames[index]; - SAFE_DELETE (key_frame); - } - - m_KeyFrames.Delete_All (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Copy_Vertex_Array -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Copy_Vertex_Array (Mesh &mesh) -{ - Resize_Vertex_Array (mesh.numVerts, mesh.numCVerts); - - // - // Copy the vertex positions from the mesh - // - for (int vert = 0; vert < mesh.numVerts; vert ++) { - m_pVertexArray[vert] = mesh.verts[vert]; - } - - // - // Copy the vertex colors from the mesh - // - for (int index = 0; index < mesh.numCVerts; index ++) { - m_pVertexColors[index] = mesh.vertCol[index]; - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Resize_Vertex_Array -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Resize_Vertex_Array (int count, int color_count) -{ - if (count != m_VertexCount) { - - // Allocate a new array of verticies - Point3 *vertex_array = new Point3[count]; - Point3 *opstart_array = new Point3[count]; - - // Delete the old vertex array and remember the new one - SAFE_DELETE (m_pVertexArray); - SAFE_DELETE (m_pVertexOPStartArray); - m_pVertexArray = vertex_array; - m_pVertexOPStartArray = opstart_array; - m_VertexCount = count; - - // - // Reset the bounds of the 'affected verts' per keyframe arrays - // - for (int index = 0; index < m_KeyFrames.Count (); index ++) { - m_KeyFrames[index]->affected_verts.SetSize (count); - m_KeyFrames[index]->affected_colors.SetSize (count); - m_KeyFrames[index]->affected_verts.ClearAll (); - m_KeyFrames[index]->affected_colors.ClearAll (); - - } - - m_SetMembers.SetSize (count); - m_SetMembers.ClearAll (); - } - - if (color_count != m_VertexColorCount) { - - // Recreate the color deltas - Point3 *color_array = new VertColor[color_count]; - for (int index = 0; index < color_count; index ++) { - color_array[index].x = 0; - color_array[index].y = 0; - color_array[index].z = 0; - } - - // Delete the old delta array and remeber the new one - SAFE_DELETE (m_pVertexColors); - m_VertexColorCount = color_count; - m_pVertexColors = color_array; - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Set_State -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Set_State (float state) -{ - m_State = state; - int key_frame = (m_State * MAX_DEFORM_KEY_FRAMES) + 0.5F; - Set_Current_Key_Frame ((key_frame >= 0) ? (key_frame - 1) : -1); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Determine_Interpolation_Indicies -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Determine_Interpolation_Indicies -( - int key_frame, - bool position, - int & from, - int & to, - float & state -) -{ - /*state = m_State; - from = -1; - to = key_frame; - - // - // Determine where we should start interpolation - // - for (int index = 0; index <= key_frame; index ++) { - if (position && m_KeyFrames[index]->verticies.Count () > 0) { - from = index; - } else if (!position && m_KeyFrames[index]->colors.Count () > 0) { - from = index; - } - } - - // - // Determine where we should end interpolation - // - for (index = to; index < MAX_DEFORM_KEY_FRAMES; index ++) { - if (position && m_KeyFrames[index]->verticies.Count () > 0) { - to = index; - break; - } else if (!position && m_KeyFrames[index]->colors.Count () > 0) { - to = index; - break; - } - } - - // - // Determine the state (deformation percent) - // - state = 0; - if (m_State > 0) { - state = 1.0F; - if ((to != from) && (m_CurrentKeyFrame < to)) { - float value = m_CurrentKeyFrame;//key_frame; - state = ((value - ((float)from)) / (float)(to-from)); - } - }*/ - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Apply_Position_Changes -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Apply_Position_Changes -( - UINT vert, - int frame_to_check, - Point3 & position, - Matrix3 *transform -) -{ - // - // Determine where we should start interpolating this vert - // - int from = -1; - for (int key_frame = frame_to_check; (key_frame >= 0) && (from == -1); key_frame --) { - if (m_KeyFrames[key_frame]->affected_verts[vert]) { - from = key_frame; - } - } - - // - // Determine where we should end interpolating this vert - // - int to = -1; - if (frame_to_check >= 0) { - for (key_frame = frame_to_check; (key_frame < m_KeyFrames.Count ()) && (to == -1); key_frame ++) { - if (m_KeyFrames[key_frame]->affected_verts[vert]) { - to = key_frame; - } - } - } - - // - // Determine the deformation percent - // - float state = 0; - if (m_State > 0) { - state = 1.0F; - if ((to != from) && (frame_to_check < to)) { - float value = frame_to_check; - state = ((value - ((float)from)) / (float)(to - from)); - } - } - - if (from != -1) { - - // - // Find the vertex value in the 'from' key frame and set the - // triangle object's vertex to be this value (we will interplate from it). - // - DEFORM_LIST &vert_from = m_KeyFrames[from]->verticies; - for (int index = 0; index < vert_from.Count (); index ++) { - VERT_INFO &info = vert_from[index]; - if (info.index == vert) { - Point3 new_pos = info.value; - - // Transform the new position if necessary - if (transform != NULL) { - new_pos = new_pos * (*transform); - } - - position = new_pos; - } - } - } - - if (to != -1) { - - // - // Find the vertex value in the 'to' key frame and interpolate - // this value from the triangle object's current vertex value. - // - DEFORM_LIST &vert_to = m_KeyFrames[to]->verticies; - for (int index = 0; index < vert_to.Count (); index ++) { - VERT_INFO &info = vert_to[index]; - if (info.index == vert) { - - Point3 new_pos = info.value; - - // Transform the new position if necessary - if (transform != NULL) { - new_pos = new_pos * (*transform); - } - - position += state * (new_pos - position); - //m_pMesh->verts[vert] = position; - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Apply_Color_Changes -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Apply_Color_Changes -( - UINT vert, - int frame_to_check, - Mesh & mesh - //VertColor & color -) -{ - // - // Determine where we should start interpolating this vert - // - int from = -1; - for (int key_frame = frame_to_check; (key_frame >= 0) && (from == -1); key_frame --) { - if (m_KeyFrames[key_frame]->affected_colors[vert]) { - from = key_frame; - } - } - - // - // Determine where we should end interpolating this vert - // - int to = -1; - if (frame_to_check >= 0) { - for (key_frame = frame_to_check; (key_frame < m_KeyFrames.Count ()) && (to == -1); key_frame ++) { - if (m_KeyFrames[key_frame]->affected_colors[vert]) { - to = key_frame; - } - } - } - - // - // Determine the deformation percent - // - float state = 0; - if (m_State > 0) { - state = 1.0F; - if ((to != from) && (frame_to_check < to)) { - float value = frame_to_check; - state = ((value - ((float)from)) / (float)(to - from)); - } - } - - if (from != -1) { - - // - // Find the color value in the 'from' key frame and set the - // triangle object's color to be this value (we will interplate from it). - // - DEFORM_LIST &color_from = m_KeyFrames[from]->colors; - for (int index = 0; index < color_from.Count (); index ++) { - VERT_INFO &info = color_from[index]; - if (info.index == vert) { - //color = info.value; - mesh.vertCol[info.color_index] = info.value; - m_pMesh->vertCol[info.color_index] = info.value; - } - } - } - - if (to != -1) { - - // - // Find the color value in the 'to' key frame and interpolate - // this value from the triangle object's current color value. - // - DEFORM_LIST &color_to = m_KeyFrames[to]->colors; - for (int index = 0; index < color_to.Count (); index ++) { - VERT_INFO &info = color_to[index]; - if (info.index == vert) { - mesh.vertCol[info.color_index] = m_pMesh->vertCol[info.color_index] + state * (info.value - m_pMesh->vertCol[info.color_index]); - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Apply_Color_Changes -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Apply_Color_Changes -( - UINT vert_index, - UINT vert_color_index, - int frame_to_check, - VertColor & color -) -{ - // - // Determine where we should start interpolating this vert - // - int from = -1; - for (int key_frame = frame_to_check; (key_frame >= 0) && (from == -1); key_frame --) { - if (m_KeyFrames[key_frame]->affected_colors[vert_index]) { - from = key_frame; - } - } - - // - // Determine where we should end interpolating this vert - // - int to = -1; - for (key_frame = frame_to_check; (key_frame < m_KeyFrames.Count ()) && (to == -1); key_frame ++) { - if (m_KeyFrames[key_frame]->affected_colors[vert_index]) { - to = key_frame; - } - } - - // - // Determine the deformation percent - // - float state = 0; - if (m_State > 0) { - state = 1.0F; - if ((to != from) && (frame_to_check < to)) { - float value = frame_to_check; - state = ((value - ((float)from)) / (float)(to - from)); - } - } - - if (from != -1) { - - // - // Find the color value in the 'from' key frame and set the - // triangle object's color to be this value (we will interplate from it). - // - DEFORM_LIST &color_from = m_KeyFrames[from]->colors; - for (int index = 0; index < color_from.Count (); index ++) { - VERT_INFO &info = color_from[index]; - if (info.color_index == vert_color_index) { - color = info.value; - break; - } - } - } - - if (to != -1) { - - // - // Find the color value in the 'to' key frame and interpolate - // this value from the triangle object's current color value. - // - DEFORM_LIST &color_to = m_KeyFrames[to]->colors; - for (int index = 0; index < color_to.Count (); index ++) { - VERT_INFO &info = color_to[index]; - if (info.color_index == vert_color_index) { - color += state * (info.value - color); - break; - } - } - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Mesh -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Update_Mesh (TriObject &tri_obj) -{ - Copy_Vertex_Array (tri_obj.mesh); - - // Should we update the mesh or copy it? - if (m_pMesh != NULL) { - - // - // Copy the vertex colors from the triangle object - // - for (int vert_color = 0; vert_color < m_pMesh->numCVerts; vert_color ++) { - m_pMesh->vertCol[vert_color] = tri_obj.mesh.vertCol[vert_color]; - } - - // - // Loop through all the verticies and interpolate their - // positions and colors based on the current 'deformation state'. - // - for (UINT vert = 0; vert < (UINT)m_pMesh->numVerts; vert ++) { - - // Is this vertex affected by any keyframe in the set? - if (m_SetMembers[vert]) { - - // Interpolate any changes to this vert - Apply_Position_Changes (vert, m_CurrentKeyFrame, tri_obj.mesh.verts[vert]); - m_pMesh->verts[vert] = tri_obj.mesh.verts[vert]; - Apply_Color_Changes (vert, m_CurrentKeyFrame, tri_obj.mesh); - } - } - - // - // Copy the vertex colors from the triangle object - // - for (vert_color = 0; vert_color < m_pMesh->numCVerts; vert_color ++) { - m_pMesh->vertCol[vert_color] = tri_obj.mesh.vertCol[vert_color]; - } - - - /*for (int index = 0; index < m_pMesh->numCVerts; index ++) { - m_pMesh->vertCol[index] = tri_obj.mesh.vertCol[index]; - } - - // - for (int key_frame = 0; key_frame < m_KeyFrames.Count (); key_frame ++) { - - // - // Update the verticies - // - - int from = 0; - int to = 0; - float state = 0; - Determine_Interpolation_Indicies (key_frame, true, from, to, state); - DEFORM_LIST &vert_to = m_KeyFrames[to]->verticies; - - if (from <= m_CurrentKeyFrame) { - - if (from >= 0) { - DEFORM_LIST &vert_from = m_KeyFrames[from]->verticies; - for (int index = 0; index < vert_from.Count (); index ++) { - VERT_INFO &info = vert_from[index]; - tri_obj.mesh.verts[info.index] = info.value; - } - } else { - - for (int index = 0; index < vert_to.Count (); index ++) { - VERT_INFO &info = vert_to[index]; - tri_obj.mesh.verts[info.index] = m_pVertexArray[info.index]; - } - } - - for (int index = 0; index < vert_to.Count (); index ++) { - VERT_INFO &info = vert_to[index]; - tri_obj.mesh.verts[info.index] += state * (info.value - tri_obj.mesh.verts[info.index]); - m_pMesh->verts[info.index] = tri_obj.mesh.verts[info.index]; - } - } - - // - // Update the vertex colors - // - Determine_Interpolation_Indicies (key_frame, false, from, to, state); - DEFORM_LIST &color_to = m_KeyFrames[to]->colors; - - if (from <= m_CurrentKeyFrame) { - - if (from >= 0) { - DEFORM_LIST &color_from = m_KeyFrames[from]->colors; - for (int index = 0; index < color_from.Count (); index ++) { - VERT_INFO &info = color_from[index]; - tri_obj.mesh.vertCol[info.index] = info.value; - } - } else { - - for (index = 0; index < color_to.Count (); index ++) { - VERT_INFO &info = color_to[index]; - tri_obj.mesh.vertCol[info.index] = m_pMesh->vertCol[info.index]; - } - } - - for (index = 0; index < color_to.Count (); index ++) { - VERT_INFO &info = color_to[index]; - tri_obj.mesh.vertCol[info.index] = m_pMesh->vertCol[info.index] + state * (info.value - m_pMesh->vertCol[info.index]); - //tri_obj.mesh.vertCol[info.index] += state * (info.value - tri_obj.mesh.vertCol[info.index]); - } - } - } - - for (index = 0; index < m_pMesh->numCVerts; index ++) { - m_pMesh->vertCol[index] = tri_obj.mesh.vertCol[index]; - }*/ - - - - - - /*for (int vert = 0; vert < m_VertexCount; vert ++) { - tri_obj.mesh.verts[vert] += (1.0F * m_pVertexDeltaArray[vert]); - m_pMesh->verts[vert] = tri_obj.mesh.verts[vert]; - } - - - // - // Transform the vertex colors based on the current deform state - // - for (vert = 0; vert < m_VertexColorCount; vert ++) { - tri_obj.mesh.vertCol[vert] += (1.0F * m_pVertexColors[vert]); - }*/ - - // - // Pass the new selection onto the mesh - // - tri_obj.mesh.vertSel = m_pMesh->vertSel; - tri_obj.PointsWereChanged (); - - } else { - - // - // Make a copy of the mesh as it currently exists - // - m_pMesh = new Mesh (tri_obj.mesh); - tri_obj.mesh.DeepCopy (m_pMesh, GEOM_CHANNEL | SELECT_CHANNEL | SUBSEL_TYPE_CHANNEL | VERTCOLOR_CHANNEL); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Update_Members -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Update_Members (DEFORM_CHANNELS flags) -{ - assert (m_CurrentKeyFrame >= 0); - - // - // Add all the selected verts to the set array - // - for (int vert = 0; vert < m_pMesh->numVerts; vert ++) { - if (m_pMesh->vertSel[vert]) { - - // - // Should we add this vertex to the array of deformed verts - // the current keyframe? - // - if (flags & VERT_POSITION) { - m_KeyFrames[m_CurrentKeyFrame]->affected_verts.Set (vert, 1); - } - - // - // Should we add this vertex to the array of deformed vertex colors - // the current keyframe? - // - if (flags & VERT_COLORS) { - - m_KeyFrames[m_CurrentKeyFrame]->affected_colors.Set (vert, 1); - - // - // Map indicies in the vertex color array to the vertex array. - // - /*if (m_pMesh->numCVerts >= m_pMesh->numVerts) { - for (int face = 0; face < m_pMesh->numFaces; face ++) { - - if (m_pMesh->faces[face].v[0] == vert) { - int color_index = m_pMesh->vcFace[face].t[0]; - m_KeyFrames[m_CurrentKeyFrame]->affected_colors.Set (color_index, 1); - } - - if (m_pMesh->faces[face].v[1] == vert) { - int color_index = m_pMesh->vcFace[face].t[1]; - m_KeyFrames[m_CurrentKeyFrame]->affected_colors.Set (color_index, 1); - } - - if (m_pMesh->faces[face].v[2] == vert) { - int color_index = m_pMesh->vcFace[face].t[2]; - m_KeyFrames[m_CurrentKeyFrame]->affected_colors.Set (color_index, 1); - } - } - }*/ - } - - // - // Finally, add this vertex to the list of all - // verticies affected by this set. - // - m_SetMembers.Set (vert, 1); - } - } - - //r (int index = m_CurrentKeyFrame; index < MAX_DEFORM_KEY_FRAMES; index ++) { - Update_Key_Frame (m_CurrentKeyFrame); - // - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Select_Members -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Select_Members (void) -{ - // - // Loop through and select the necessary verts - // - for (int vert = 0; vert < m_pMesh->numVerts; vert ++) { - m_pMesh->vertSel.Set (vert, m_SetMembers[vert]); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Restore_Members -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Restore_Members (void) -{ -/* - // - // Loop through and select the necessary verts - // - for (int vert = 0; vert < m_pMesh->numVerts; vert ++) { - - if (m_SetMembers[vert]) { - - // - // Restore the vertex positions - // - m_pMesh->verts[vert] = m_pVertexArray[vert]; - m_pVertexDeltaArray[vert].x = 0; - m_pVertexDeltaArray[vert].y = 0; - m_pVertexDeltaArray[vert].z = 0; - } - } - - // - // Restore the vertex colors - // - - // Only do this if the mesh is using vertex coloring - if (m_pMesh->numCVerts >= m_pMesh->numVerts) { - for (int face = 0; face < m_pMesh->numFaces; face ++) { - - if (m_SetMembers[m_pMesh->faces[face].v[0]]) { - int color_index = m_pMesh->vcFace[face].t[0]; - m_pVertexColors[color_index].x = 0; - m_pVertexColors[color_index].y = 0; - m_pVertexColors[color_index].z = 0; - } - - if (m_SetMembers[m_pMesh->faces[face].v[1]]) { - int color_index = m_pMesh->vcFace[face].t[1]; - m_pVertexColors[color_index].x = 0; - m_pVertexColors[color_index].y = 0; - m_pVertexColors[color_index].z = 0; - } - - if (m_SetMembers[m_pMesh->faces[face].v[2]]) { - int color_index = m_pMesh->vcFace[face].t[2]; - m_pVertexColors[color_index].x = 0; - m_pVertexColors[color_index].y = 0; - m_pVertexColors[color_index].z = 0; - } - } - } - -*/ - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Is_Empty -// -/////////////////////////////////////////////////////////////////////////// -bool -MeshDeformSetClass::Is_Empty (void) const -{ - bool is_empty = true; - - // - // If any vertex is 'selected' then this set is not empty. - // - for (int vert = 0; (vert < m_VertexCount) && is_empty; vert ++) { - is_empty = (m_SetMembers[vert] == 0); - } - - // Return the true/false result code - return is_empty; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Save -// -/////////////////////////////////////////////////////////////////////////// -void -MeshDeformSetClass::Save -( - MeshBuilderClass & builder, - Mesh & mesh, - MeshDeformSaveSetClass & save_set, - Matrix3 * transform -) -{ - // Start fresh - save_set.Reset (); - save_set.Set_Flag (DEFORM_SET_MANUAL_DEFORM, (m_bAutoApply == false)); - - // - // Determine how much each state change (from 0 - 1) - // is associated with each keyframe. - // - int key_frames = m_KeyFrames.Count (); - float state_inc = 1.0F / ((float)key_frames); - float old_state = m_State; - - // - // Loop through all the keyframes - // - for (int key_frame = 0; key_frame < key_frames; key_frame ++) { - - // - // Loop through all the verticies and see if this keyframe - // modifies any of them - // - bool verts_affected = false; - for (int vert = 0; (vert < m_VertexCount) && !verts_affected; vert ++) { - verts_affected = (m_KeyFrames[key_frame]->affected_verts[vert] == 1); - verts_affected |= (m_KeyFrames[key_frame]->affected_colors[vert] == 1); - } - - // - // If the keyframe modifies any of these verts, then save - // the state of all verts in the set. - // - if (verts_affected) { - m_State = state_inc * (key_frame + 1); - save_set.Begin_Keyframe (m_State); - - // - // Save the absolute state of all the verts and colors - // at this keyframe. - // - - for (int w3d_vert_index = 0; w3d_vert_index < builder.Get_Vertex_Count (); w3d_vert_index ++) { - - const MeshBuilderClass::VertClass &w3d_vert = builder.Get_Vertex(w3d_vert_index); - int max_vert_index = w3d_vert.Id; - - if (m_SetMembers[max_vert_index]) { - - // - // Get the absolute position of this vertex - // - Point3 position = mesh.verts[max_vert_index]; - Apply_Position_Changes (max_vert_index, key_frame, position, transform); - - // - // Get the absolute color of this vertex - // - VertColor color (1, 1, 1); - if (mesh.vertCol != NULL) { - int vert_col_index = w3d_vert.MaxVertColIndex; - color = mesh.vertCol[vert_col_index]; - Apply_Color_Changes (max_vert_index, vert_col_index, key_frame, color); - } - - // - // Save this vertex's deformations - // - save_set.Add_Vert (w3d_vert_index, position, color); - } - } - - save_set.End_Keyframe (); - } - } - - m_State = old_state; - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Save -// -/////////////////////////////////////////////////////////////////////////// -IOResult -MeshDeformSetClass::Save (ISave *save_obj) -{ - int key_frames = m_KeyFrames.Count (); - float state_inc = 1.0F / ((float)key_frames); - - DeformChunkSetInfo set_info = { 0 }; - set_info.KeyframeCount = key_frames; - set_info.flags = 0; - set_info.NumVerticies = m_VertexCount; - set_info.NumVertexColors = m_VertexColorCount; - if (m_bAutoApply == false) { - set_info.flags |= DEFORM_SET_MANUAL_DEFORM; - } - DWORD bytes = 0L; - - // - // Write the set info to the chunk - // - save_obj->BeginChunk (DEFORM_CHUNK_SET_INFO); - IOResult result = save_obj->Write (&set_info, sizeof (set_info), &bytes); - - // - // Now write a chunk for each keyframe - // - for (int index = 0; (index < key_frames) && (result == IO_OK); index ++) { - KEY_FRAME &key_frame = *(m_KeyFrames[index]); - - DeformChunkKeyframeInfo keyframe_info = { 0 }; - keyframe_info.DeformPercent = state_inc * (index + 1); - keyframe_info.VertexCount = key_frame.verticies.Count (); - keyframe_info.ColorCount = key_frame.colors.Count (); - - // - // Write keyframe info to the chunk - // - //save_obj->BeginChunk (DEFORM_CHUNK_KEYFRAME_INFO); - result = save_obj->Write (&keyframe_info, sizeof (keyframe_info), &bytes); - //save_obj->EndChunk (); - - // - // Loop through the verticies and save their position - // - for ( unsigned int pos_index = 0; - (pos_index < keyframe_info.VertexCount) && (result == IO_OK); - pos_index ++) - { - VERT_INFO &deform_data = key_frame.verticies[pos_index]; - - DeformDataChunk data; - data.VertexIndex = deform_data.index; - data.ColorIndex = deform_data.color_index; - data.Value = deform_data.value; - - // - // Write vertex position info to the chunk - // - //save_obj->BeginChunk (DEFORM_CHUNK_POSITION_DATA); - result = save_obj->Write (&data, sizeof (data), &bytes); - //save_obj->EndChunk (); - } - - // - // Loop through the verticies and save their color - // - for ( unsigned int color_index = 0; - (color_index < keyframe_info.ColorCount) && (result == IO_OK); - color_index ++) - { - VERT_INFO &deform_data = key_frame.colors[color_index]; - - DeformDataChunk data; - data.VertexIndex = deform_data.index; - data.ColorIndex = deform_data.color_index; - data.Value = deform_data.value; - - // - // Write vertex color info to the chunk - // - //save_obj->BeginChunk (DEFORM_CHUNK_COLOR_DATA); - result = save_obj->Write (&data, sizeof (data), &bytes); - //save_obj->EndChunk (); - } - - // - // Write the list of affected vertex positions to a chunk - // - /*if (result == IO_OK) { - //save_obj->BeginChunk (DEFORM_CHUNK_POSITION_VERTS); - result = key_frame.affected_verts.Save (save_obj); - //save_obj->EndChunk (); - } - - // - // Write the list of affected vertex colors to a chunk - // - if (result == IO_OK) { - //save_obj->BeginChunk (DEFORM_CHUNK_COLOR_VERTS); - result = key_frame.affected_colors.Save (save_obj); - //save_obj->EndChunk (); - }*/ - } - - save_obj->EndChunk (); - - // Return IO_OK on success IO_ERROR on failure - return result; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Load -// -/////////////////////////////////////////////////////////////////////////// -IOResult -MeshDeformSetClass::Load (ILoad *load_obj) -{ - // Start fresh - Free_Key_Frames (); - Init_Key_Frames (); - DWORD bytes = 0L; - - - // - // Is this the chunk we were expecting? - // - IOResult result = load_obj->OpenChunk (); - if ( (result == IO_OK) && - (load_obj->CurChunkID () == DEFORM_CHUNK_SET_INFO)) { - - // - // Read information about this set from the chunk - // - DeformChunkSetInfo set_info = { 0 }; - result = load_obj->Read (&set_info, sizeof (set_info), &bytes); - m_bAutoApply = !(set_info.flags & DEFORM_SET_MANUAL_DEFORM); - - // - // Resize the internal data to fit the saved state - // - if (result == IO_OK) { - Resize_Vertex_Array (set_info.NumVerticies, set_info.NumVertexColors); - } - - // - // Read keyframe information from the chunk - // - for ( unsigned int index = 0; - (index < set_info.KeyframeCount) && (result == IO_OK); - index ++) - { - KEY_FRAME &key_frame = *(m_KeyFrames[index]); - - DeformChunkKeyframeInfo keyframe_info = { 0 }; - result = load_obj->Read (&keyframe_info, sizeof (keyframe_info), &bytes); - - // - // Read all the vertex positions from the chunk - // - for ( unsigned int pos_index = 0; - (pos_index < keyframe_info.VertexCount) && (result == IO_OK); - pos_index ++) - { - // - // Read vertex position info from the chunk - // - DeformDataChunk data; - result = load_obj->Read (&data, sizeof (data), &bytes); - if (result == IO_OK) { - key_frame.verticies.Add (VERT_INFO (data.VertexIndex, data.Value, data.ColorIndex)); - key_frame.affected_verts.Set (data.VertexIndex, 1); - m_SetMembers.Set (data.VertexIndex, 1); - } - } - - // - // Read all the vertex colors from the chunk - // - for ( unsigned int color_index = 0; - (color_index < keyframe_info.ColorCount) && (result == IO_OK); - color_index ++) - { - // - // Read vertex color info from the chunk - // - DeformDataChunk data; - result = load_obj->Read (&data, sizeof (data), &bytes); - if (result == IO_OK) { - key_frame.colors.Add (VERT_INFO (data.VertexIndex, data.Value, data.ColorIndex)); - key_frame.affected_colors.Set (data.VertexIndex, 1); - m_SetMembers.Set (data.VertexIndex, 1); - } - } - - // - // Read the list of affected vertex positions to a chunk - // - /*if (result == IO_OK) { - result = key_frame.affected_verts.Load (load_obj); - } - - // - // Read the list of affected vertex colors to a chunk - // - if (result == IO_OK) { - result = key_frame.affected_colors.Load (load_obj); - }*/ - } - } - - load_obj->CloseChunk (); - - // Return IO_OK on success IO_ERROR on failure - return result; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSet.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSet.h deleted file mode 100644 index 4b00123f4e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformSet.h +++ /dev/null @@ -1,185 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformSet.h * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 04/26/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef __MESH_DEFORM_SET_H -#define __MESH_DEFORM_SET_H - -#include -#include "Vector.H" -#include "MeshDeformDefs.h" - - -// Forward declarations -class MeshDeformSaveSetClass; -class MeshBuilderClass; - - -/////////////////////////////////////////////////////////////////////////// -// -// MeshDeformSetClass -// -/////////////////////////////////////////////////////////////////////////// -class MeshDeformSetClass -{ - public: - - ////////////////////////////////////////////////////////////////////// - // Public data types - ////////////////////////////////////////////////////////////////////// - - - ////////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////////// - MeshDeformSetClass (void) - : m_pMesh (NULL), - m_pVertexArray (NULL), - m_pVertexOPStartArray (NULL), - m_pVertexColors (NULL), - m_VertexColorCount (0), - m_State (0), - m_CurrentKeyFrame (0), - m_bAutoApply (true), - m_VertexCount (0) { Init_Key_Frames (); } - - virtual ~MeshDeformSetClass (void); - - ////////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////////// - //virtual LocalModData * Clone (void) { return new MeshDeformSetClass; } - void Update_Mesh (TriObject &tri_obj); - void Set_State (float state); - - // Inline accessors - Mesh * Peek_Mesh (void) const { return m_pMesh; } - const Point3 * Peek_Orig_Vertex_Array (void) const { return m_pVertexArray; } - Point3 * Peek_Vertex_OPStart_Array (void) const { return m_pVertexOPStartArray; } - VertColor * Peek_Vertex_Colors (void) const { return m_pVertexColors; } - - // Keyframe managment - void Set_Current_Key_Frame (int index); - int Get_Current_Key_Frame (void) const { return m_CurrentKeyFrame; } - void Update_Key_Frame (int key_frame); - void Update_Current_Data (void); - void Update_Set_Members (void); - void Collapse_Keyframe_Data (int keyframe); - void Reset_Key_Frame_Verts (int keyframe); - void Reset_Key_Frame_Colors (int keyframe); - - // Data managment - void Set_Vertex_Position (int index, const Point3 &value); - void Set_Vertex_Color (int index, int color_index, const VertColor &value); - - // Set managment - void Select_Members (void); - void Update_Members (DEFORM_CHANNELS flags); - void Restore_Members (void); - - // Auto apply - bool Does_Set_Auto_Apply (void) const { return m_bAutoApply; } - void Auto_Apply (bool auto_apply = true) { m_bAutoApply = auto_apply; } - - // Information - bool Is_Empty (void) const; - int Get_Vertex_Count (int keyframe) const { return m_KeyFrames[keyframe]->verticies.Count (); } - int Get_Color_Count (int keyframe) const { return m_KeyFrames[keyframe]->colors.Count (); } - const VERT_INFO & Get_Vertex_Data (int keyframe, int index) const { return m_KeyFrames[keyframe]->verticies[index]; } - const VERT_INFO & Get_Color_Data (int keyframe, int index) const { return m_KeyFrames[keyframe]->colors[index]; } - - // Persistent storage - IOResult Save (ISave *save_obj); - IOResult Load (ILoad *load_obj); - - void Save (MeshBuilderClass &builder, Mesh &mesh, MeshDeformSaveSetClass &save_set, Matrix3 *transform = NULL); - - protected: - - ////////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////////// - void Resize_Vertex_Array (int count, int color_count); - void Copy_Vertex_Array (Mesh &mesh); - - // Keyframe methods - void Init_Key_Frames (void); - void Free_Key_Frames (void); - void Determine_Interpolation_Indicies (int key_frame, bool position, int &from, int &to, float &state); - - // Deformation application methods - void Apply_Position_Changes (UINT vert, int frame_to_check, Point3 &position, Matrix3 *transform = NULL); - void Apply_Color_Changes (UINT vert, int frame_to_check, Mesh &mesh); - void Apply_Color_Changes (UINT vert_index, UINT vert_color_index, int frame_to_check, VertColor &color); - - private: - - ////////////////////////////////////////////////////////////////////// - // Private data types - ////////////////////////////////////////////////////////////////////// - typedef struct - { - DEFORM_LIST verticies; - DEFORM_LIST colors; - BitArray affected_verts; - BitArray affected_colors; - } KEY_FRAME; - - typedef DynamicVectorClass KEY_FRAME_LIST; - - ////////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////////// - Mesh * m_pMesh; - Point3 * m_pVertexArray; - Point3 * m_pVertexOPStartArray; - VertColor * m_pVertexColors; - int m_VertexCount; - int m_VertexColorCount; - int m_CurrentKeyFrame; - float m_State; - bool m_bAutoApply; - - // Array representing which verticies are part of the set - BitArray m_SetMembers; - - // List of key frames - KEY_FRAME_LIST m_KeyFrames; -}; - - -#endif //__MESH_DEFORM_DATA_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformUndo.cpp b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformUndo.cpp deleted file mode 100644 index 2d0de5380c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformUndo.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformUndo.h * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 06/08/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "MeshDeformUndo.h" -#include "util.h" -#include "MeshDeformData.h" -#include "MeshDeformSet.h" -#include "MeshDeform.h" - - -/////////////////////////////////////////////////////////////////////////// -// -// VertexRestoreClass -// -/////////////////////////////////////////////////////////////////////////// -VertexRestoreClass::VertexRestoreClass -( - Mesh * mesh, - MeshDeformClass * modifier, - MeshDeformModData * mod_data -) - : m_pModifier (modifier), - m_pModData (mod_data), - m_pMesh (mesh), - m_SetIndex (0), - m_KeyframeIndex (0) -{ - assert (mesh != NULL); - - // - // Remember the deformer's current settings - // - m_SetIndex = m_pModData->Get_Current_Set (); - m_KeyframeIndex = m_pModData->Peek_Set (m_SetIndex).Get_Current_Key_Frame (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Free_Vertex_Array -// -/////////////////////////////////////////////////////////////////////////// -void -VertexRestoreClass::Free_Vertex_Array (void) -{ - m_VertexList.Delete_All (); - m_RedoVertexList.Delete_All (); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Restore -// -/////////////////////////////////////////////////////////////////////////// -void -VertexRestoreClass::Restore (int is_undo) -{ - assert (m_pMesh != NULL); - assert (m_pModData != NULL); - assert (m_pModifier != NULL); - - // Is this being called as part of an undo operation? - if (is_undo != 0) { - - // - // Ensure the modifier is in the state it was when - // the undo operation was recorded - // - m_pModData->Set_Current_Set (m_SetIndex); - m_pModData->Peek_Set (m_SetIndex).Set_Current_Key_Frame (m_KeyframeIndex); - - // - // Apply the original vertex positions to the mesh - // - Apply_Vertex_Data (m_VertexList); - - // - // Notify the mesh of geometry changes - // - m_pModifier->NotifyDependents (FOREVER, PART_GEOM | PART_VERTCOLOR, REFMSG_CHANGE); - m_pModifier->Update_UI (m_pModData); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Redo -// -/////////////////////////////////////////////////////////////////////////// -void -VertexRestoreClass::Redo (void) -{ - assert (m_pMesh != NULL); - assert (m_pModData != NULL); - assert (m_pModifier != NULL); - - // - // Ensure the modifier is in the state it was when - // the undo operation was recorded - // - m_pModData->Set_Current_Set (m_SetIndex); - m_pModData->Peek_Set (m_SetIndex).Set_Current_Key_Frame (m_KeyframeIndex); - - // - // Apply the original vertex positions to the mesh - // - Apply_Vertex_Data (m_RedoVertexList); - - // - // Notify the mesh of geometry changes - // - m_pModifier->NotifyDependents (FOREVER, PART_GEOM | PART_VERTCOLOR, REFMSG_CHANGE); - m_pModifier->Update_UI (m_pModData); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// EndHold -// -/////////////////////////////////////////////////////////////////////////// -void -VertexRestoreClass::EndHold (void) -{ - // - // Record the position of all the verts we are about to change - // (to support redo). - // - Copy_Vertex_State (m_RedoVertexList); - m_pModifier->ClearAFlag (A_HELD); - return ; -} - - -/***************************************************************************************/ -/* -/* End VertexRestoreClass -/* -/***************************************************************************************/ - -/***************************************************************************************/ -/* -/* Start VertexPositionRestoreClass -/* -/***************************************************************************************/ - - -/////////////////////////////////////////////////////////////////////////// -// -// VertexPositionRestoreClass -// -/////////////////////////////////////////////////////////////////////////// -VertexPositionRestoreClass::VertexPositionRestoreClass -( - Mesh * mesh, - MeshDeformClass * modifier, - MeshDeformModData * mod_data -) - : VertexRestoreClass (mesh, modifier, mod_data) -{ - // - // Make a copy of the vertex positions - // - Copy_Vertex_State (m_VertexList); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Copy_Vertex_State -// -/////////////////////////////////////////////////////////////////////////// -void -VertexPositionRestoreClass::Copy_Vertex_State (DEFORM_LIST &list) -{ - // - // Make a copy of each vertex in the current keyframe - // - list.Delete_All (); - MeshDeformSetClass &set_obj = m_pModData->Peek_Set (m_SetIndex); - int count = set_obj.Get_Vertex_Count (m_KeyframeIndex); - for (int index = 0; index < count; index ++) { - const VERT_INFO &data = set_obj.Get_Vertex_Data (m_KeyframeIndex, index); - list.Add (VERT_INFO (data.index, data.value)); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Apply_Vertex_Data -// -/////////////////////////////////////////////////////////////////////////// -void -VertexPositionRestoreClass::Apply_Vertex_Data (DEFORM_LIST &list) -{ - m_pModData->Peek_Set (m_SetIndex).Reset_Key_Frame_Verts (m_KeyframeIndex); - - // - // Apply each vertex in our list - // - for (int index = 0; index < list.Count (); index ++) { - VERT_INFO &info = list[index]; - m_pModData->Set_Vertex_Position (info.index, info.value); - } - - return ; -} - - - -/***************************************************************************************/ -/* -/* End VertexPositionRestoreClass -/* -/***************************************************************************************/ - -/***************************************************************************************/ -/* -/* Start VertexColorRestoreClass -/* -/***************************************************************************************/ - - -/////////////////////////////////////////////////////////////////////////// -// -// VertexColorRestoreClass -// -/////////////////////////////////////////////////////////////////////////// -VertexColorRestoreClass::VertexColorRestoreClass -( - Mesh * mesh, - MeshDeformClass * modifier, - MeshDeformModData * mod_data -) - : VertexRestoreClass (mesh, modifier, mod_data) -{ - // - // Make a copy of the vertex positions - // - Copy_Vertex_State (m_VertexList); - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Copy_Vertex_State -// -/////////////////////////////////////////////////////////////////////////// -void -VertexColorRestoreClass::Copy_Vertex_State (DEFORM_LIST &list) -{ - // - // Make a copy of each vertex color in the current keyframe - // - list.Delete_All (); - MeshDeformSetClass &set_obj = m_pModData->Peek_Set (m_SetIndex); - int count = set_obj.Get_Color_Count (m_KeyframeIndex); - for (int index = 0; index < count; index ++) { - const VERT_INFO &data = set_obj.Get_Color_Data (m_KeyframeIndex, index); - list.Add (VERT_INFO (data.index, data.value, data.color_index)); - } - - return ; -} - - -/////////////////////////////////////////////////////////////////////////// -// -// Apply_Vertex_Data -// -/////////////////////////////////////////////////////////////////////////// -void -VertexColorRestoreClass::Apply_Vertex_Data (DEFORM_LIST &list) -{ - m_pModData->Peek_Set (m_SetIndex).Reset_Key_Frame_Colors (m_KeyframeIndex); - - // - // Apply each vertex in our list - // - for (int index = 0; index < list.Count (); index ++) { - VERT_INFO &info = list[index]; - m_pModData->Set_Vertex_Color (info.index, info.color_index, info.value); - } - - return ; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformUndo.h b/Generals/Code/Tools/WW3D/max2w3d/MeshDeformUndo.h deleted file mode 100644 index acdf8fe47a..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/MeshDeformUndo.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : MeshDeformUndo.h * - * * - * Programmer : Patrick Smith * - * * - * Start Date : 06/08/99 * - * * - * Last Update : - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef __MESH_DEFORM_UNDO_H -#define __MESH_DEFORM_UNDO_H - -#include -#include "Vector.H" -#include "MeshDeformDefs.h" - -// Forward declarations -class MeshDeformClass; -class MeshDeformModData; - - - -/////////////////////////////////////////////////////////////////////////// -// -// VertexRestoreClass -// -/////////////////////////////////////////////////////////////////////////// -class VertexRestoreClass : public RestoreObj -{ - public: - - ////////////////////////////////////////////////////////////////// - // Public constructors/destructor - ////////////////////////////////////////////////////////////////// - VertexRestoreClass (Mesh *mesh, MeshDeformClass *modifier, MeshDeformModData *mod_data); - virtual ~VertexRestoreClass (void) { Free_Vertex_Array (); }; - - ////////////////////////////////////////////////////////////////// - // RestoreObj overrides - ////////////////////////////////////////////////////////////////// - virtual void Restore (int is_undo); - virtual void Redo (void); - virtual int Size (void) { return (m_VertexList.Count () * sizeof (Point3) * 2) + sizeof (VertexRestoreClass); } - virtual void EndHold (void); - - protected: - - ////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////// - virtual void Copy_Vertex_State (DEFORM_LIST &list) = 0; - virtual void Apply_Vertex_Data (DEFORM_LIST &list) = 0; - void Free_Vertex_Array (void); - - ////////////////////////////////////////////////////////////////// - // Protected member data - ////////////////////////////////////////////////////////////////// - Mesh * m_pMesh; - MeshDeformClass * m_pModifier; - MeshDeformModData * m_pModData; - DEFORM_LIST m_VertexList; - DEFORM_LIST m_RedoVertexList; - int m_SetIndex; - int m_KeyframeIndex; -}; - - -/////////////////////////////////////////////////////////////////////////// -// -// VertexPositionRestoreClass -// -/////////////////////////////////////////////////////////////////////////// -class VertexPositionRestoreClass : public VertexRestoreClass -{ - public: - - ////////////////////////////////////////////////////////////////// - // Public constructors/destructor - ////////////////////////////////////////////////////////////////// - VertexPositionRestoreClass (Mesh *mesh, MeshDeformClass *modifier, MeshDeformModData *mod_data); - virtual ~VertexPositionRestoreClass (void) { }; - - ////////////////////////////////////////////////////////////////// - // RestoreObj overrides - ////////////////////////////////////////////////////////////////// - TSTR Description (void) { return TSTR(_T("Vertex Position")); } - - protected: - - ////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////// - virtual void Copy_Vertex_State (DEFORM_LIST &list); - virtual void Apply_Vertex_Data (DEFORM_LIST &list); -}; - - -/////////////////////////////////////////////////////////////////////////// -// -// VertexColorRestoreClass -// -/////////////////////////////////////////////////////////////////////////// -class VertexColorRestoreClass : public VertexRestoreClass -{ - public: - - ////////////////////////////////////////////////////////////////// - // Public constructors/destructor - ////////////////////////////////////////////////////////////////// - VertexColorRestoreClass (Mesh *mesh, MeshDeformClass *modifier, MeshDeformModData *mod_data); - virtual ~VertexColorRestoreClass (void) { }; - - ////////////////////////////////////////////////////////////////// - // RestoreObj overrides - ////////////////////////////////////////////////////////////////// - TSTR Description (void) { return TSTR(_T("Vertex Color")); } - - protected: - - ////////////////////////////////////////////////////////////////// - // Protected methods - ////////////////////////////////////////////////////////////////// - virtual void Copy_Vertex_State (DEFORM_LIST &list); - virtual void Apply_Vertex_Data (DEFORM_LIST &list); -}; - - -#endif //__MESH_DEFORM_UNDO_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/PCToPS2Material.cpp b/Generals/Code/Tools/WW3D/max2w3d/PCToPS2Material.cpp deleted file mode 100644 index c81fcc3ebc..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/PCToPS2Material.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project name : Buccaneer Bay * - * * - * File name : PCToPS2Material.cpp * - * * - * Programmer : Mike Lytle * - * * - * Start date : 10/22/1999 * - * * - * Last update : 10/27/1999 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * PTPMC::BeginEditParams -- Change all W3D materials in the mesh to be PS2 compatible. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include -#include -#include -#include "dllmain.h" -#include "resource.h" -#include "util.h" -#include "utilapi.h" -#include "nodelist.h" -#include "gamemtl.h" - - -Class_ID PCToPS2MaterialClassID(0x40d11cee, 0x68881657); - -class PCToPS2MaterialClass : public UtilityObj { - - public: - - void BeginEditParams(Interface *ip,IUtil *iu); - void EndEditParams(Interface *ip,IUtil *iu) {} - void DeleteThis() {delete this;} - -}; - - -/*********************************************************************************************** - * PTPMC::BeginEditParams -- Change all W3D materials in the mesh to be PS2 compatible. * - * * - * * - * * - * * - * HISTORY: * - * 10/27/1999MLL: Created. * - *=============================================================================================*/ -void PCToPS2MaterialClass::BeginEditParams(Interface *ip,IUtil *iu) -{ - // This function is called when the utility is chosen. - // Since we don't need any window gadgets, we'll just go through all the materials right away. - INode *root = ip->GetRootNode(); - - INodeListClass *meshlist = NULL; - - // Change all materials associated with the mesh, starting with the root node. - if (root) { - meshlist = new INodeListClass(root, 0); - - if (meshlist) { - int i; - - for (i = 0; i < meshlist->Num_Nodes(); i++) { - - Mtl *nodemtl = ((*meshlist)[i])->GetMtl(); - - if (nodemtl == NULL) { - // No material on this node, go to the next. - continue; - } - - if (!nodemtl->IsMultiMtl()) { - // Only change those that are W3D materials. - if (nodemtl->ClassID() == GameMaterialClassID) { - int pass; - - for (pass = 0; pass < ((GameMtl*)nodemtl)->Get_Pass_Count(); pass++) { - // Change the material for each pass. - ((GameMtl*)nodemtl)->Compute_PS2_Shader_From_PC_Shader(pass); - } - - } - } else { - - // Loop through all sub materials of the multi-material. - for (unsigned mi = 0; mi < nodemtl->NumSubMtls(); mi++) { - - // Only change those that are W3D materials. - if (nodemtl->GetSubMtl(mi)->ClassID() == GameMaterialClassID) { - int pass; - - for (pass = 0; pass < ((GameMtl*)nodemtl->GetSubMtl(mi))->Get_Pass_Count(); pass++) { - // Change the material for each pass. - ((GameMtl*)nodemtl->GetSubMtl(mi))->Compute_PS2_Shader_From_PC_Shader(pass); - } - } else if (nodemtl->GetSubMtl(mi)->ClassID() == PS2GameMaterialClassID) { - } - } - } - } - } - - delete meshlist; - } -} - -class PCToPS2MaterialClassDesc:public ClassDesc { - -public: - int IsPublic() { return 1; } - void * Create(BOOL loading) - { - return ((void*)new PCToPS2MaterialClass); - } - const TCHAR * ClassName() { return Get_String(IDS_PC_TO_PS2_MAT_CONVERTER); } - SClass_ID SuperClassID() { return UTILITY_CLASS_ID; } - Class_ID ClassID() { return PCToPS2MaterialClassID; } - const TCHAR* Category() { return _T(""); } -}; - -static PCToPS2MaterialClassDesc _PCToPS2MaterialCD; - -ClassDesc * Get_PS2_Material_Conversion() { return &_PCToPS2MaterialCD; } diff --git a/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtl.cpp b/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtl.cpp deleted file mode 100644 index e6a89eeafe..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtl.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project name : Buccaneer Bay * - * * - * File name : PS2GameMtl.cpp * - * * - * Programmer : Mike Lytle * - * * - * Start date : 10/12/1999 * - * * - * Last update : 10/12/1999 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "gamemtl.h" -#include -#include -#include -#include "dllmain.h" -#include "resource.h" -#include "util.h" - - - -/***************************************************************** -* -* PS2 GameMtl Class Descriptor -* -*****************************************************************/ -Class_ID PS2GameMaterialClassID(0x2ed62ad7, 0x50571dfd); - -// This adds W3D PS2 choice to the Max material selector. -class PS2GameMaterialClassDesc:public ClassDesc { - -public: - int IsPublic() { return 1; } - void * Create(BOOL loading) - { - GameMtl *mtl = new GameMtl(loading); - mtl->Set_Shader_Type(GameMtl::STE_PS2_SHADER); - return ((void*)mtl); - } - const TCHAR * ClassName() { return Get_String(IDS_PS2_GAMEMTL); } - SClass_ID SuperClassID() { return MATERIAL_CLASS_ID; } - Class_ID ClassID() { return PS2GameMaterialClassID; } - const TCHAR* Category() { return _T(""); } -}; - -static PS2GameMaterialClassDesc _PS2GameMaterialCD; - -ClassDesc * Get_PS2_Game_Material_Desc() { return &_PS2GameMaterialCD; } diff --git a/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp deleted file mode 100644 index b793666297..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.cpp +++ /dev/null @@ -1,371 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project name : Buccaneer Bay * - * * - * File name : PS2GameMtlShaderDlg.cpp * - * * - * Programmer : Mike Lytle * - * * - * Start date : 10/12/1999 * - * * - * Last update : 10/12/1999 * - * * - * Taken from GTH's GameMtlShaderDlg.cpp * - *---------------------------------------------------------------------------------------------* - * Functions: * - * PS2GameMtlShaderDlg -- Constructor. * - * PGMSD::Dialog_Proc -- Respond to user selections. * - * PGMSD::ReloadDialog -- Setup the dialog box. * - * PGMSD::Apply_Preset -- Notify the material of the values for the selected setting. * - * PGMSD::Set_Preset -- Sets the dialog to one of the presets or custom. * - * PGMSD::CompareShaderToBlendPreset -- Determine if the settings conform to one of the prese* - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "PS2GameMtlShaderDlg.h" -#include "GameMtlDlg.h" -#include "gamemtl.h" -#include "resource.h" - - -#define NUM_PS2_SHADER_BLEND_PRESETS 7 - -static char * _PS2ShaderBlendSettingPresetNames[NUM_PS2_SHADER_BLEND_PRESETS + 1] = -{ - "Opaque", - "Additive", - "Source Subtracted", - "Destination Subtracted", - "Alpha Blend", - "Alpha Test", - "Alpha Test and Blend", - "------ Custom -----" -}; - -struct PS2ShaderBlendSettingPreset -{ - int A; - int B; - int C; - int D; - bool DepthMask; - bool AlphaTest; -}; - -// (A - B) * C + D -static const PS2ShaderBlendSettingPreset PS2ShaderBlendSettingPresets[NUM_PS2_SHADER_BLEND_PRESETS] = { - {PSS_SRC, PSS_ZERO, PSS_ONE, PSS_ZERO, true, false}, // Opaque - {PSS_SRC, PSS_ZERO, PSS_ONE, PSS_DEST, false, false}, // Additive - {PSS_DEST, PSS_SRC, PSS_ONE, PSS_ZERO, false, false}, // Src subtracted - {PSS_SRC, PSS_DEST, PSS_ONE, PSS_ZERO, false, false}, // Dest subtracted - {PSS_SRC, PSS_DEST, PSS_SRC_ALPHA, PSS_DEST, false, false}, // Alpha blend - {PSS_SRC, PSS_ZERO, PSS_ONE, PSS_ZERO, true, true}, // Alpha test - {PSS_SRC, PSS_DEST, PSS_SRC_ALPHA, PSS_DEST, true, true}, // Alpha test & blend -}; - - -/*********************************************************************************************** - * PS2GameMtlShaderDlg -- Constructor. * - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -PS2GameMtlShaderDlg::PS2GameMtlShaderDlg -( - HWND parent, - IMtlParams * imp, - GameMtl * mtl, - int pass -) : GameMtlFormClass(imp,mtl,pass) -{ - Create_Form(parent, IDD_GAMEMTL_PS2_SHADER); -} - - -/*********************************************************************************************** - * PGMSD::Dialog_Proc -- Respond to user selections. * - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -BOOL PS2GameMtlShaderDlg::Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam) -{ - int cursel; - int i; - int id = LOWORD(wparam); - int code = HIWORD(wparam); - - switch (message) - { - - case WM_INITDIALOG: - for(i = 0; i <= NUM_PS2_SHADER_BLEND_PRESETS; i++) { - SendDlgItemMessage(dlg_wnd,IDC_PS2_PRESET_COMBO,CB_ADDSTRING,0,(LONG)_PS2ShaderBlendSettingPresetNames[i]); - } - SendDlgItemMessage(dlg_wnd,IDC_PS2_PRESET_COMBO,CB_SETCURSEL,0,0); - break; - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(dlg_wnd,message,wparam,lparam); - } - return FALSE; - - case WM_COMMAND: - { - if (code == CBN_SELCHANGE) { - - switch (id) - { - // Shared by both shaders. - case IDC_DEPTHCOMPARE_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DEPTHCOMPARE_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Depth_Compare(PassIndex,cursel); - break; - case IDC_PRIGRADIENT_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_PRIGRADIENT_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Pri_Gradient(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_SECGRADIENT_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_SECGRADIENT_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Sec_Gradient(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_DETAILCOLOR_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DETAILCOLOR_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Detail_Color_Func(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - case IDC_DETAILALPHA_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_DETAILALPHA_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_Detail_Alpha_Func(PassIndex,cursel); - TheMtl->Notify_Changed(); - break; - - // Playstation 2 specific. - case IDC_PS2_PRESET_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_PS2_PRESET_COMBO,CB_GETCURSEL,0,0); - Apply_Preset(cursel); - break; - case IDC_A_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_A_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_PS2_Shader_Param_A(PassIndex,cursel); - TheMtl->Notify_Changed(); - Set_Preset(); - break; - case IDC_B_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_B_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_PS2_Shader_Param_B(PassIndex,cursel); - TheMtl->Notify_Changed(); - Set_Preset(); - break; - case IDC_C_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_C_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_PS2_Shader_Param_C(PassIndex,cursel); - TheMtl->Notify_Changed(); - Set_Preset(); - break; - case IDC_D_COMBO: - cursel = SendDlgItemMessage(dlg_wnd,IDC_D_COMBO,CB_GETCURSEL,0,0); - TheMtl->Set_PS2_Shader_Param_D(PassIndex,cursel); - TheMtl->Notify_Changed(); - Set_Preset(); - break; - } - - } else { - - switch(id) { - - case IDC_DEPTHMASK_CHECK: - if (SendDlgItemMessage(dlg_wnd,IDC_DEPTHMASK_CHECK,BM_GETCHECK,0,0)) { - TheMtl->Set_Depth_Mask(PassIndex,W3DSHADER_DEPTHMASK_WRITE_ENABLE); - } else { - TheMtl->Set_Depth_Mask(PassIndex,W3DSHADER_DEPTHMASK_WRITE_DISABLE); - } - Set_Preset(); - break; - - case IDC_ALPHATEST_CHECK: - if (SendDlgItemMessage(dlg_wnd,IDC_ALPHATEST_CHECK,BM_GETCHECK,0,0)) { - TheMtl->Set_Alpha_Test(PassIndex,W3DSHADER_ALPHATEST_ENABLE); - } else { - TheMtl->Set_Alpha_Test(PassIndex,W3DSHADER_ALPHATEST_DISABLE); - } - Set_Preset(); - break; - - case IDC_SHADER_DEFAULTS_BUTTON: - Set_Advanced_Defaults(); - break; - } - } - } - } - - return FALSE; -} - -/*********************************************************************************************** - * PGMSD::ReloadDialog -- Setup the dialog box. * - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -void PS2GameMtlShaderDlg::ReloadDialog(void) -{ - DebugPrint("GameMtlShaderDlg::ReloadDialog\n"); - SendDlgItemMessage(m_hWnd, IDC_PRIGRADIENT_COMBO, CB_SETCURSEL, TheMtl->Get_Pri_Gradient(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_SECGRADIENT_COMBO, CB_SETCURSEL, TheMtl->Get_Sec_Gradient(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_DEPTHCOMPARE_COMBO, CB_SETCURSEL, TheMtl->Get_Depth_Compare(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_DETAILCOLOR_COMBO, CB_SETCURSEL, TheMtl->Get_Detail_Color_Func(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_DETAILALPHA_COMBO, CB_SETCURSEL, TheMtl->Get_Detail_Alpha_Func(PassIndex), 0 ); - SendDlgItemMessage(m_hWnd, IDC_A_COMBO, CB_SETCURSEL, TheMtl->Get_PS2_Shader_Param_A(PassIndex), 0); - SendDlgItemMessage(m_hWnd, IDC_B_COMBO, CB_SETCURSEL, TheMtl->Get_PS2_Shader_Param_B(PassIndex), 0); - SendDlgItemMessage(m_hWnd, IDC_C_COMBO, CB_SETCURSEL, TheMtl->Get_PS2_Shader_Param_C(PassIndex), 0); - SendDlgItemMessage(m_hWnd, IDC_D_COMBO, CB_SETCURSEL, TheMtl->Get_PS2_Shader_Param_D(PassIndex), 0); - - Set_Preset(); - - SetCheckBox(m_hWnd,IDC_DEPTHMASK_CHECK, TheMtl->Get_Depth_Mask(PassIndex)); - SetCheckBox(m_hWnd,IDC_ALPHATEST_CHECK, TheMtl->Get_Alpha_Test(PassIndex)); -} - - -/*********************************************************************************************** - * PGMSD::Apply_Preset -- Notify the material of the values for the selected setting. * - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -void PS2GameMtlShaderDlg::Apply_Preset(int preset_index) -{ - if (preset_index < 0 || preset_index >= NUM_PS2_SHADER_BLEND_PRESETS) return; - - const PS2ShaderBlendSettingPreset &preset = PS2ShaderBlendSettingPresets[preset_index]; - - int depth_mask = preset.DepthMask ? W3DSHADER_DEPTHMASK_WRITE_ENABLE : W3DSHADER_DEPTHMASK_WRITE_DISABLE; - TheMtl->Set_Depth_Mask(PassIndex, depth_mask); - - int alpha_test = preset.AlphaTest ? W3DSHADER_ALPHATEST_ENABLE : W3DSHADER_ALPHATEST_DISABLE; - TheMtl->Set_Alpha_Test(PassIndex, alpha_test); - - TheMtl->Set_PS2_Shader_Param_A(PassIndex, preset.A); - TheMtl->Set_PS2_Shader_Param_B(PassIndex, preset.B); - TheMtl->Set_PS2_Shader_Param_C(PassIndex, preset.C); - TheMtl->Set_PS2_Shader_Param_D(PassIndex, preset.D); - - TheMtl->Notify_Changed(); - ReloadDialog(); - - if (TheMtl->Compute_PC_Shader_From_PS2_Shader(PassIndex)) - SetWindowText(GetDlgItem(m_hWnd,IDC_COMPATIBLE), " Compatible"); - else - SetWindowText(GetDlgItem(m_hWnd,IDC_COMPATIBLE), " NOT Compatible"); - -} - -/*********************************************************************************************** - * PGMSD::Set_Preset -- Sets the dialog to one of the presets or custom. * - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -void PS2GameMtlShaderDlg::Set_Preset(void) -{ - for (int i = 0; i < NUM_PS2_SHADER_BLEND_PRESETS; i++) { - if (CompareShaderToBlendPreset(PS2ShaderBlendSettingPresets[i])) break; - } - SendDlgItemMessage(m_hWnd, IDC_PS2_PRESET_COMBO, CB_SETCURSEL, i, 0); - - if (TheMtl->Compute_PC_Shader_From_PS2_Shader(PassIndex)) - SetWindowText(GetDlgItem(m_hWnd,IDC_COMPATIBLE), " Compatible"); - else - SetWindowText(GetDlgItem(m_hWnd,IDC_COMPATIBLE), " NOT Compatible"); -} - -/*********************************************************************************************** - * PGMSD::CompareShaderToBlendPreset -- Determine if the settings conform to one of the presets* - * * - * * - * * - * * - * HISTORY: * - * 10/12/1999MLL: Created. * - *=============================================================================================*/ -bool PS2GameMtlShaderDlg::CompareShaderToBlendPreset(const PS2ShaderBlendSettingPreset &blend_preset) -{ - bool depthmask = TheMtl->Get_Depth_Mask(PassIndex) != W3DSHADER_DEPTHMASK_WRITE_DISABLE; - if (depthmask != blend_preset.DepthMask) return false; - bool alphatest = TheMtl->Get_Alpha_Test(PassIndex) != W3DSHADER_ALPHATEST_DISABLE; - if (alphatest != blend_preset.AlphaTest) return false; - - if (TheMtl->Get_PS2_Shader_Param_A(PassIndex) != blend_preset.A) return false; - if (TheMtl->Get_PS2_Shader_Param_B(PassIndex) != blend_preset.B) return false; - if (TheMtl->Get_PS2_Shader_Param_C(PassIndex) != blend_preset.C) return false; - if (TheMtl->Get_PS2_Shader_Param_D(PassIndex) != blend_preset.D) return false; - - return true; -} - - -/*********************************************************************************************** - * GameMtlShaderDlg::Set_Advanced_Defaults -- set advanced settings to defaults * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/26/99 NH : Created. * - *=============================================================================================*/ -void PS2GameMtlShaderDlg::Set_Advanced_Defaults(void) -{ - TheMtl->Set_Pri_Gradient(PassIndex, PSS_PRIGRADIENT_MODULATE); - TheMtl->Set_Depth_Compare(PassIndex, PSS_DEPTHCOMPARE_PASS_LEQUAL); - TheMtl->Set_Detail_Color_Func(PassIndex, W3DSHADER_DETAILCOLORFUNC_DEFAULT); - TheMtl->Set_Detail_Alpha_Func(PassIndex, W3DSHADER_DETAILALPHAFUNC_DEFAULT); - - TheMtl->Notify_Changed(); - ReloadDialog(); -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h b/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h deleted file mode 100644 index adbe1fa0ee..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/PS2GameMtlShaderDlg.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project name : Buccaneer Bay * - * * - * File name : PS2GameMtlShaderDlg.h * - * * - * Programmer : Mike Lytle * - * * - * Start date : 10/12/1999 * - * * - * Last update : 10/12/1999 * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef PS2GAMEMTLSHADERDLG_H -#define PS2GAMEMTLSHADERDLG_H - -#include -#include "GameMtlForm.h" - -// This class was taken from GTH's GameMtlShaderDlg. - -class GameMtl; -struct PS2ShaderBlendSettingPreset; - -class PS2GameMtlShaderDlg : public GameMtlFormClass -{ - -public: - - PS2GameMtlShaderDlg(HWND parent, IMtlParams * imp, GameMtl * m, int pass); - - virtual BOOL Dialog_Proc (HWND dlg_wnd, UINT message, WPARAM wparam, LPARAM lparam); - - void ReloadDialog(void); - - // Pure virtual that must be defined. - void ActivateDlg(BOOL onOff) {} - -private: - - void Apply_Preset(int preset_index); - void Set_Preset(void); - bool CompareShaderToBlendPreset(const PS2ShaderBlendSettingPreset &blend_preset); - void Set_Advanced_Defaults(void); -}; - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/SceneSetup.cpp b/Generals/Code/Tools/WW3D/max2w3d/SceneSetup.cpp deleted file mode 100644 index bce702d5e9..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/SceneSetup.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/SceneSetup.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 10/15/99 3:33p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * wwSceneSetup -- Allows the user to select how many LOD and damage models to create. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -/* -** SceneSetup.cpp - Implements the "wwSceneSetup" MAXScript function to -** present a nice dialog to the user for getting a number of parameters -** that will governs the number, placement, and type of LOD and Damage -** models created in the scene. -*/ - - -#include "SceneSetupDlg.h" - -#undef STRICT -#include -#include -#include -#include - - -/* -** Let MAXScript know we're implementing new built-in functions. -*/ -def_visible_primitive(scene_setup, "wwSceneSetup"); - - -/*********************************************************************************************** - * scene_setup_cf - MAXScript function wwSceneSetup * - * * - * wwSceneSetup - Usage: wwSceneSetup arg_array * - * * - * INPUT: * - * The contents of the given array is assumed to be as follows: * - * lod_count (int) - the number of LOD models that will be created * - * lod_offset (float) - X offset to move the LODs by * - * lod_clone (int) - 1==copy 2==instance 3==reference * - * damage_count (int) - the number of damage models that will be created * - * damage_offset (float) - Y offset to move the LODs by * - * damage_clone (int) - 1==copy 2==instance 3==reference * - * * - * OUTPUT: * - * The function returns an array of the new values the user selected in the same format as * - * above. - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/27/1999 AJA : Created. * - *=============================================================================================*/ -Value * scene_setup_cf (Value **arg_list, int count) -{ - // We don't want any arguments for this function. - check_arg_count("wwSceneSetup", 1, count); - type_check(arg_list[0], Array, "Parameter array"); - - SceneSetupDlg dlg(MAXScript_interface); - one_typed_value_local(Array* result); - - // Read the initial values out of the array. - Array *args = (Array*)(arg_list[0]); - dlg.m_LodCount = (args->get(1))->to_int(); - dlg.m_LodOffset = (args->get(2))->to_float(); - dlg.m_LodProc = (args->get(3))->to_int(); - dlg.m_DamageCount = (args->get(4))->to_int(); - dlg.m_DamageOffset = (args->get(5))->to_float(); - dlg.m_DamageProc = (args->get(6))->to_int(); - - // Display the dialog - if (dlg.DoModal() == IDCANCEL) - { - pop_value_locals(); - return &undefined; - } - - // Stuff the values the user chose into the array we'll return. - vl.result = new Array(6); - vl.result->append(Integer::intern(dlg.m_LodCount)); - vl.result->append(Float::intern(dlg.m_LodOffset)); - vl.result->append(Integer::intern(dlg.m_LodProc)); - vl.result->append(Integer::intern(dlg.m_DamageCount)); - vl.result->append(Float::intern(dlg.m_DamageOffset)); - vl.result->append(Integer::intern(dlg.m_DamageProc)); - - // Return the array of new values. - return_value(vl.result); -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/SceneSetupDlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/SceneSetupDlg.cpp deleted file mode 100644 index 69c81b7458..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/SceneSetupDlg.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/SceneSetupDlg.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 10/15/99 3:37p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -// SceneSetupDlg.cpp : implementation file -// - -#include "SceneSetupDlg.h" -#include -#include - -static BOOL CALLBACK _thunk_dialog_proc (HWND hWnd, UINT uMsg, WPARAM wAparam, LPARAM lParam); - - - -///////////////////////////////////////////////////////////////////////////// -// SceneSetupDlg dialog - - -SceneSetupDlg::SceneSetupDlg(Interface *max_interface) -{ - m_DamageCount = 0; - m_DamageOffset = -100.0f; - m_LodCount = 0; - m_LodOffset = -100.0f; - m_DamageProc = 3; - m_LodProc = 3; - m_hWnd = NULL; - m_MaxInterface = max_interface; - assert(max_interface != NULL); -} - - -///////////////////////////////////////////////////////////////////////////// -// SceneSetupDlg Protected Methods - -void SceneSetupDlg::SetEditInt (int control_id, int value) -{ - char buf[64]; - sprintf(buf, "%d", value); - HWND edit = GetDlgItem(m_hWnd, control_id); - assert(edit != NULL); - SetWindowText(edit, buf); -} - -void SceneSetupDlg::SetEditFloat (int control_id, float value) -{ - char buf[64]; - sprintf(buf, "%.0f", value); - HWND edit = GetDlgItem(m_hWnd, control_id); - assert(edit != NULL); - SetWindowText(edit, buf); -} - -int SceneSetupDlg::GetEditInt (int control_id) -{ - char buf[64]; - HWND edit = GetDlgItem(m_hWnd, control_id); - assert(edit != NULL); - GetWindowText(edit, buf, sizeof(buf)); - int value = 0; - sscanf(buf, "%d", &value); - return value; -} - -float SceneSetupDlg::GetEditFloat (int control_id) -{ - char buf[64]; - HWND edit = GetDlgItem(m_hWnd, control_id); - assert(edit != NULL); - GetWindowText(edit, buf, sizeof(buf)); - float value = 0; - sscanf(buf, "%f", &value); - return value; -} - -bool SceneSetupDlg::ValidateEditFloat (int control_id) -{ - char buf[64]; - HWND edit = GetDlgItem(m_hWnd, control_id); - assert(edit != NULL); - GetWindowText(edit, buf, sizeof(buf)); - float value = 0; - if (sscanf(buf, "%f", &value) == 1) - return true; - else - return false; -} - -///////////////////////////////////////////////////////////////////////////// -// SceneSetupDlg Public Methods - -int SceneSetupDlg::DoModal (void) -{ - // Put up the dialog box. - BOOL result = DialogBoxParam(AppInstance, MAKEINTRESOURCE(IDD_SCENE_SETUP), - m_MaxInterface->GetMAXHWnd(), (DLGPROC)_thunk_dialog_proc, - (LPARAM)this); - - // Return IDOK if the user accepted the new settings. - return (result == 1) ? IDOK : IDCANCEL; -} - -///////////////////////////////////////////////////////////////////////////// -// SceneSetupDlg DialogProc - -BOOL CALLBACK _thunk_dialog_proc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - static SceneSetupDlg *dialog = NULL; - - if (uMsg == WM_INITDIALOG) - { - dialog = (SceneSetupDlg*)lParam; - dialog->m_hWnd = hWnd; - } - - if (dialog) - return dialog->DialogProc(hWnd, uMsg, wParam, lParam); - else - return 0; -} - -BOOL CALLBACK SceneSetupDlg::DialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - int code = HIWORD(wParam); - - switch (uMsg) - { - - /******************************************************************* - * WM_INITDIALOG - * - * Initialize all of the custom controls for the dialog box - * - *******************************************************************/ - case WM_INITDIALOG: - - OnInitDialog(); - return TRUE; - - - /******************************************************************* - * WM_COMMAND - * - * - *******************************************************************/ - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - - if (OnOK() == FALSE) - return TRUE; - - SetCursor(LoadCursor(NULL, IDC_WAIT)); - EndDialog(m_hWnd, 1); - break; - - case IDCANCEL: - EndDialog(m_hWnd, 0); - break; - - } - return TRUE; - - } - - return FALSE; -} - - -///////////////////////////////////////////////////////////////////////////// -// SceneSetupDlg message handlers - -void SceneSetupDlg::OnInitDialog() -{ - CenterWindow(m_hWnd, m_MaxInterface->GetMAXHWnd()); - SetCursor(LoadCursor(NULL, IDC_ARROW)); - - // Select the appropriate radio buttons. - switch (m_LodProc) - { - case 1: - CheckDlgButton(m_hWnd, IDC_LOD_AS_COPY, BST_CHECKED); - break; - case 2: - CheckDlgButton(m_hWnd, IDC_LOD_AS_INSTANCE, BST_CHECKED); - break; - case 3: - CheckDlgButton(m_hWnd, IDC_LOD_AS_REFERENCE, BST_CHECKED); - break; - } - switch (m_DamageProc) - { - case 1: - CheckDlgButton(m_hWnd, IDC_DAMAGE_AS_COPY, BST_CHECKED); - break; - case 2: - CheckDlgButton(m_hWnd, IDC_DAMAGE_AS_INSTANCE, BST_CHECKED); - break; - case 3: - CheckDlgButton(m_hWnd, IDC_DAMAGE_AS_REFERENCE, BST_CHECKED); - break; - } - - // Set the text for the edit boxes. - SetEditInt(IDC_LOD_COUNT, m_LodCount); - SetEditFloat(IDC_LOD_OFFSET, m_LodOffset); - SetEditInt(IDC_DAMAGE_COUNT, m_DamageCount); - SetEditFloat(IDC_DAMAGE_OFFSET, m_DamageOffset); -} - -BOOL SceneSetupDlg::OnOK() -{ - if (!ValidateEditFloat(IDC_LOD_OFFSET)) - { - MessageBox(m_hWnd, "You must enter a valid number for the LOD Offset.", - "Not a Number", MB_OK); - SetFocus(GetDlgItem(m_hWnd, IDC_LOD_OFFSET)); - return FALSE; - } - if (!ValidateEditFloat(IDC_DAMAGE_OFFSET)) - { - MessageBox(m_hWnd, "You must enter a valid number for the Damage Offset.", - "Not a Number", MB_OK); - SetFocus(GetDlgItem(m_hWnd, IDC_DAMAGE_OFFSET)); - return FALSE; - } - - // Get the clone procedure the user wants to use. - if (IsDlgButtonChecked(m_hWnd, IDC_LOD_AS_COPY)) - m_LodProc = 1; - else if (IsDlgButtonChecked(m_hWnd, IDC_LOD_AS_INSTANCE)) - m_LodProc = 2; - else if (IsDlgButtonChecked(m_hWnd, IDC_LOD_AS_REFERENCE)) - m_LodProc = 3; - if (IsDlgButtonChecked(m_hWnd, IDC_DAMAGE_AS_COPY)) - m_DamageProc = 1; - else if (IsDlgButtonChecked(m_hWnd, IDC_DAMAGE_AS_INSTANCE)) - m_DamageProc = 2; - else if (IsDlgButtonChecked(m_hWnd, IDC_DAMAGE_AS_REFERENCE)) - m_DamageProc = 3; - - // Get the other values the user selected. - m_LodCount = GetEditInt(IDC_LOD_COUNT); - m_LodOffset = GetEditFloat(IDC_LOD_OFFSET); - m_DamageCount = GetEditInt(IDC_DAMAGE_COUNT); - m_DamageOffset = GetEditFloat(IDC_DAMAGE_OFFSET); - - return TRUE; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/SceneSetupDlg.h b/Generals/Code/Tools/WW3D/max2w3d/SceneSetupDlg.h deleted file mode 100644 index c76bb97295..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/SceneSetupDlg.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/SceneSetupDlg.h $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 10/15/99 4:24p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef SCENESETUPDLG_H -#define SCENESETUPDLG_H - -// SceneSetupDlg.h : header file -// - -#include "dllmain.h" -#include "resource.h" - - -class Interface; - -///////////////////////////////////////////////////////////////////////////// -// SceneSetupDlg dialog - -class SceneSetupDlg -{ -public: - - // Construction - SceneSetupDlg(Interface *max_interface); - - // Methods - int DoModal (void); - - // DialogProc - BOOL CALLBACK DialogProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - // Dialog data associated with GUI components. - enum { IDD = IDD_SCENE_SETUP }; - int m_DamageCount; - float m_DamageOffset; - int m_LodCount; - float m_LodOffset; - int m_LodProc; - int m_DamageProc; - - // Dialog Data - HWND m_hWnd; - -protected: - - // Message Handlers - void OnInitDialog (void); - BOOL OnOK (void); // TRUE if ok to close dialog - - // Protected Methods - void SetEditInt (int control_id, int value); - void SetEditFloat (int control_id, float value); - int GetEditInt (int control_id); - float GetEditFloat (int control_id); - bool ValidateEditFloat (int control_id); - - // Protected Data - Interface *m_MaxInterface; -}; - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/SkinCopy.cpp b/Generals/Code/Tools/WW3D/max2w3d/SkinCopy.cpp deleted file mode 100644 index 7603f4bcf0..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/SkinCopy.cpp +++ /dev/null @@ -1,526 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/SkinCopy.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 11/03/99 11:51a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * find_skin_binding -- Find the "WWSkin Binding" modifier on this object. * - * find_skin_wsm -- Finds the node for the WWSkin WSM used by this object. * - * get_skin_wsm_obj -- Gets the SkinWSMObjectClass from a WWSkin WSM node. * - * duplicate_wsm -- Duplicates a WWSkin WSM * - * find_equivalent_node -- Searches a hierarchy for an object equivalent to the given one. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -/* --- Copy the skin info for this object into the target object. --- If we haven't copied the WSM yet, it will be copied. -new_wsm = wwCopySkinInfo source_root target_root new_wsm -*/ - -#include // Main MAXScript header -#include // MAX* Wrapper objects -#include // def_* functions to create static function headers - -#include -#include - -#include "skin.h" -#include "util.h" -#include "w3d_file.h" - - -/* -** Forward declarations -*/ - -Value *find_skin_node_in_tree (INode *root); - -SkinModifierClass *find_skin_binding (INode *skinned_obj); - -INode *find_skin_wsm (INode *skinned_obj); - -SkinWSMObjectClass *get_skin_wsm_obj (INode *wsm_node); - -INode *duplicate_wsm (INode *skinned_obj, INode *tree_root); - -INode *find_equivalent_node (INode *source, INode *tree, bool name_is_valid = false); - -Value *copy_skin_info (INode *source, INode *target, INode *wsm); - -IDerivedObject *setup_wsm_derived_obj (INode *node); - -ModContext *find_skin_mod_context (INode *node); - - -/* -** Let MAXScript know we're implementing a new built-in function. -*/ -def_visible_primitive(find_skin_node, "wwFindSkinNode"); -def_visible_primitive(copy_skin_info, "wwCopySkinInfo"); -def_visible_primitive(dupe_skin_wsm, "wwDuplicateSkinWSM"); - - -/* -** -** MAXScript Function: -** wwFindSkinNode - Usage: wwFindSkinNode tree_root_node -** -** Searches the given hierarchy tree for the node containing -** the WWSkin WSM. Returns the node if found, otherwise it -** returns undefined. -** -** Used by the SceneSetup MAXScript. -*/ -Value *find_skin_node_cf (Value **arg_list, int count) -{ - // Verify the number and type of the arguments. - check_arg_count("wwFindSkinNode", 1, count); - type_check(arg_list[0], MAXNode, "Tree Root INode"); - - // Get the INode that was passed in. - INode *tree_root = arg_list[0]->to_node(); - - // Search the tree for the WWSkin WSM, and return - // the node which references it. - return find_skin_node_in_tree(tree_root); -} - -/* -** -** MAXScript Function: -** wwCopySkinInfo - Usage: wwCopySkinInfo from_node to_node wsm_node to_tree_root -** -** Copies the skin info for the given node to the target node. -** If wsm_node is "undefined" then we will create a new WWSkin WSM -** with the same values as the one being used by from_node. -** If from_node doesn't have a WWSkin binding, the return value -** is "undefined". If the function succeeds, it returns the -** wsm_node (the new WSM if it was created, otherwise the old wsm_node). -** -** Used by the SceneSetup MAXScript. -*/ -Value * copy_skin_info_cf (Value **arg_list, int count) -{ - // Verify the number and type of the arguments. - check_arg_count("wwCopySkinInfo", 4, count); - type_check(arg_list[0], MAXNode, "Source INode"); - type_check(arg_list[1], MAXNode, "Target INode"); - type_check(arg_list[3], MAXNode, "Target Tree Root INode"); - - // Get the INode pointers that were passed in. - INode *src_node = arg_list[0]->to_node(); - INode *dest_node = arg_list[1]->to_node(); - INode *wsm_node = NULL; - INode *tree_root = arg_list[3]->to_node(); - if (arg_list[2] == &undefined) - { - // Duplicate the WSM used by src_node. - wsm_node = duplicate_wsm(find_skin_wsm(src_node), tree_root); - if (wsm_node == NULL) - return &undefined; - } - else - wsm_node = arg_list[2]->to_node(); - - return copy_skin_info(src_node, dest_node, wsm_node); -} - - -/* -** -** MAXScript Function: -** wwDuplicateSkinWSM - Usage: wwDuplicateSkinWSM wwskin_wsm_node tree_root -** -** Duplicates the given WWSkin WSM. tree_root is the root node of a hierarchy -** containing bones similar to the ones used by the given WSM. The hierarchy -** will be searched for equivalent bones (ie. names the same except their -** extension), and those bones will be used by the newly duplicated WSM. -** -** Used by the SceneSetup MAXScript. -*/ -Value * dupe_skin_wsm_cf (Value **arg_list, int count) -{ - // Verify the number and type of the arguments. - check_arg_count("wwDuplicateSkinWSM", 2, count); - type_check(arg_list[0], MAXNode, "WWSkin Object INode"); - type_check(arg_list[1], MAXNode, "Target Tree Root INode"); - - // Get the INode pointers that were passed in. - INode *wsm_node = arg_list[0]->to_node(); - INode *root_node = arg_list[1]->to_node(); - - // Return the duplicated WWSkin WSM. - INode *dupe = duplicate_wsm(wsm_node, root_node); - if (!dupe) - return &undefined; - else - { - // Return the WSM. - one_typed_value_local(Value* wsm_node); - vl.wsm_node = MAXNode::intern(dupe); - return_value(vl.wsm_node); - } -} - - -Value *find_skin_node_in_tree (INode *root) -{ - if (root == NULL) - return &undefined; - - // Is this the node we're looking for? - if (get_skin_wsm_obj(root)) - { - one_typed_value_local(Value* wsm_node); - vl.wsm_node = MAXNode::intern(root); - return_value(vl.wsm_node); - } - - // Search the children of this node. - for (int i = 0; i < root->NumChildren(); i++) - { - Value *retval = find_skin_node_in_tree(root->GetChildNode(i)); - if (retval != &undefined) - return retval; - } - - // Didn't find it anywhere! - return &undefined; -} - - -/*********************************************************************************************** - * find_skin_binding -- Find the "WWSkin Binding" modifier on this object. * - * * - * INPUT: The skinned object. * - * * - * OUTPUT: The skin modifier, or NULL if one doesn't exist. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/19/1999 AJA : Created. * - *=============================================================================================*/ -SkinModifierClass *find_skin_binding (INode *skinned_obj) -{ - // WWSkin Binding ties us to a space warp, so search the node's - // WSM Derived Object for the WWSkin Binding modifier. - IDerivedObject *dobj = skinned_obj->GetWSMDerivedObject(); - if (dobj == NULL) - return NULL; // not bound to a space warp - - // Search for the WWSkin Binding modifier on this derived object. - for (int i = 0; i < dobj->NumModifiers(); i++) - { - Modifier *mod = dobj->GetModifier(i); - if (mod->ClassID() != SKIN_MOD_CLASS_ID) - continue; - - // We found the skin modifier. - return (SkinModifierClass*)mod; - } - - // Skin modifier not found. - return NULL; -} - - -/*********************************************************************************************** - * find_skin_wsm -- Finds the node for the WWSkin WSM used by this object. * - * * - * INPUT: The node of an object with a WWSkin Binding. * - * * - * OUTPUT: The node of the WWSkin WSM referenced by the given object. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/1999 AJA : Created. * - *=============================================================================================*/ -INode *find_skin_wsm (INode *skinned_obj) -{ - // Find the skin modifier on this object. - SkinModifierClass *skin_mod = find_skin_binding(skinned_obj); - if (skin_mod == NULL) - return NULL; - - // Using the skin modifer, find the WSM's INode. - INode *wsm = (INode*)( skin_mod->GetReference(SkinModifierClass::NODE_REF) ); - if (wsm == NULL) - { - char buf[256]; - sprintf(buf, "%s has a WWSkin Binding, but I can't find its WWSkin WSM!", - skinned_obj->GetName()); - throw RuntimeError(buf); - } - - return wsm; -} - - -/*********************************************************************************************** - * get_skin_wsm_obj -- Gets the SkinWSMObjectClass from a WWSkin WSM node. * - * * - * INPUT: The node for the WWSkin WSM's representation in the scene. * - * * - * OUTPUT: The SkinWSMObjectClass. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/1999 AJA : Created. * - *=============================================================================================*/ -SkinWSMObjectClass *get_skin_wsm_obj (INode *wsm_node) -{ - // We need a valid node. - if (!wsm_node) - return NULL; - - // The node must reference an object. - Object *obj = wsm_node->GetObjectRef(); - if (!obj) - return NULL; - - // That BASE object must be a SkinWSMObject - while (obj) - { - // If this is a derived object, burrow deeper, - // otherwise we're at the base object. - if (obj->SuperClassID() == GEN_DERIVOB_CLASS_ID) - obj = ((IDerivedObject*)obj)->GetObjRef(); - else - break; - } - if (obj->ClassID() != SKIN_OBJ_CLASS_ID) - return NULL; - - // Return it. - return (SkinWSMObjectClass*)obj; -} - - -/*********************************************************************************************** - * duplicate_wsm -- Duplicates a WWSkin WSM * - * * - * INPUT: wsm_node - INode of the WWSkin WSM object. * - * tree - The root of a tree containing equivalents of the bones in the WWSkin used * - * by skinned_obj. The bone names must be the same (after being processed by * - * Set_W3D_Name() * - * * - * OUTPUT: The node of the newly duplicated WWSkin WSM. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/1999 AJA : Created. * - * 11/3/1999 AJA : Changed first argument from skinned_obj to wsm_node. * - *=============================================================================================*/ -INode *duplicate_wsm (INode *wsm_node, INode *tree) -{ - SkinWSMObjectClass *wsm_obj = get_skin_wsm_obj(wsm_node); - - if (!wsm_node || !wsm_obj) - return NULL; - - /* - ** Duplicate the WSM. - */ - - SkinWSMObjectClass *new_wsm_obj = - (SkinWSMObjectClass*)CreateInstance(WSM_OBJECT_CLASS_ID, SKIN_OBJ_CLASS_ID); - if (!new_wsm_obj) - return NULL; - - // Create a new node in the scene that points to the new WSM object. - INode *new_wsm_node = MAXScript_interface->CreateObjectNode(new_wsm_obj); - if (!new_wsm_node) - return NULL; - - // Copy the bones from one to the other. - for (int i = 0; i < wsm_obj->Num_Bones(); i++) - { - INode *src_bone = wsm_obj->Get_Bone(i); - INode *dst_bone = find_equivalent_node(src_bone, tree); - if (!src_bone || !dst_bone) - return NULL; - - new_wsm_obj->Add_Bone(dst_bone); - } - - // Return a pointer to the new WSM node. - return new_wsm_node; -} - - -/*********************************************************************************************** - * find_equivalent_node -- Searches a hierarchy for an object equivalent to the given one. * - * * - * INPUT: source - The node to search for an equivalent of. * - * tree - The hierarchy to search in. * - * * - * OUTPUT: The equivalent node, or NULL if none was found. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/19/1999 AJA : Created. * - *=============================================================================================*/ -INode *find_equivalent_node (INode *source, INode *tree, bool name_is_valid) -{ - // We need a valid source and tree. - if (!source || !tree) - return NULL; - - // The name of the source object. We'll only evaluate this once as an easy optimization. - static char src_name[W3D_NAME_LEN]; - if (!name_is_valid) - Set_W3D_Name(src_name, source->GetName()); - - // The name of the current object we're examining. - char chk_name[W3D_NAME_LEN]; - Set_W3D_Name(chk_name, tree->GetName()); - - // Is this the node we're looking for? - if (strcmp(src_name, chk_name) == 0) - return tree; // Yup, sure is. - - // Nope. Check its children. - for (int i = 0; i < tree->NumberOfChildren(); i++) - { - INode *retval = find_equivalent_node(source, tree->GetChildNode(i), true); - if (retval != NULL) - return retval; // we found the node in our children - } - - // No equivalent node was found. - return NULL; -} - - -Value *copy_skin_info (INode *source, INode *target, INode *wsm) -{ - // Get the "WWSkin Binding" modifier on the source object. - SkinModifierClass *source_modifier = find_skin_binding(source); - if (source_modifier == NULL) - return &undefined; - - // Get the WSMDerivedObject we can add our skin binding modifier to. - IDerivedObject *dobj = setup_wsm_derived_obj(target); - - // Create a new skin modifier and copy the source modifier's settings to it. - SkinModifierClass *new_modifier = new SkinModifierClass(wsm, get_skin_wsm_obj(wsm)); - if (new_modifier == NULL) - throw RuntimeError("Out of memory - Unable to allocate a new SkinModifierClass object!"); - new_modifier->SubObjSelLevel = source_modifier->SubObjSelLevel; - - // Dupe the mod context, especially the local mod data hanging off of it. - ModContext *source_context = find_skin_mod_context(source); - ModContext *new_context = new ModContext(source_context->tm, source_context->box, - source_context->localData); - if (new_context == NULL) - throw RuntimeError("Out of memory - Unable to allocate a new ModContext object!"); - - // Add a new "WWSkin Binding" modifier to the target object to associate - // the object with the skin WSM. All of the settings should be correct, - // and the target object becomes a "skinned object". - dobj->AddModifier(new_modifier, new_context); - - // Return the WSM. - one_typed_value_local(Value* wsm_node); - vl.wsm_node = MAXNode::intern(wsm); - return_value(vl.wsm_node); -} - - -IDerivedObject *setup_wsm_derived_obj (INode *node) -{ - // Check if the target object is already bound to a space warp. - IDerivedObject *dobj = node->GetWSMDerivedObject(); - if (dobj != NULL) - { - // It's bound to a space warp. Check if WWSkin is one of the - // space warp bindings. If so, remove it (we don't want to - // be bound to an old skin). - for (int i = 0; i < dobj->NumModifiers(); i++) - { - Modifier *mod = dobj->GetModifier(i); - if (mod->ClassID() != SKIN_MOD_CLASS_ID) - continue; - - // We found the skin modifier, remove it. - dobj->DeleteModifier(i); - break; - } - } - else - { - // This object isn't bound to a space warp. Create a - // WSMDerivedObject for the node to play with. - dobj = CreateWSDerivedObject(node->GetObjectRef()); - if (dobj == NULL) - { - char msg[128]; - sprintf(msg, "Error setting up the WSMDerivedObject for %s", node->GetName()); - throw RuntimeError(msg); - } - node->SetObjectRef(dobj); - } - - return dobj; -} - - -ModContext *find_skin_mod_context (INode *node) -{ - // We need a valid node - if (node == NULL) - return NULL; - - // The node needs to be bound to a space warp (ie. must have - // a WSMDerivedObject). - IDerivedObject *dobj = node->GetWSMDerivedObject(); - if (dobj == NULL) - return NULL; - - // It's bound to a space warp. Find the WWSkin modifier. - for (int i = 0; i < dobj->NumModifiers(); i++) - { - Modifier *mod = dobj->GetModifier(i); - if (mod->ClassID() != SKIN_MOD_CLASS_ID) - continue; - - // We found the skin modifier, return its mod context. - return dobj->GetModContext(i); - } - - // We didn't find a WWSkin binding. - return NULL; -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/SnapPoints.cpp b/Generals/Code/Tools/WW3D/max2w3d/SnapPoints.cpp deleted file mode 100644 index 0f1ea46d4d..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/SnapPoints.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/SnapPoints.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/23/98 11:05a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#include "SnapPoints.h" -#include "chunkio.h" -#include "max.h" -#include "nodelist.h" -#include "w3d_file.h" - - -class PointFilterClass : public INodeFilterClass -{ -public: - PointFilterClass(void) { } - - virtual BOOL Accept_Node(INode * node, TimeValue time) - { - if (node == NULL) return FALSE; - Object * obj = node->EvalWorldState(time).obj; - if (obj == NULL) return FALSE; - - if - ( - obj->ClassID() == Class_ID(POINTHELP_CLASS_ID,0) && - !node->IsHidden() - ) - { - return TRUE; - } else { - return FALSE; - } - } -}; - - -void SnapPointsClass::Export_Points(INode * scene_root,TimeValue time,ChunkSaveClass & csave) -{ - if (scene_root == NULL) return; - - PointFilterClass pointfilter; - INodeListClass pointlist(scene_root,time,&pointfilter); - - if (pointlist.Num_Nodes() > 0) { - - csave.Begin_Chunk(W3D_CHUNK_POINTS); - - for (unsigned int ci=0; ciGetNodeTM(time).GetTrans(); - vect.X = pos.x; - vect.Y = pos.y; - vect.Z = pos.z; - csave.Write(&vect,sizeof(vect)); - - } - - csave.End_Chunk(); - } -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/SnapPoints.h b/Generals/Code/Tools/WW3D/max2w3d/SnapPoints.h deleted file mode 100644 index 6071e1d96f..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/SnapPoints.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/SnapPoints.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 11/19/98 4:36p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef SNAPPOINTS_H -#define SNAPPOINTS_H - -#include "max.h" - -class ChunkSaveClass; -class INode; - -/* -** This class simply contains static functions which will find -** helper points that should be exported with a w3d render object and -** export them in a chunk using the given ChunkSaveClass object. -*/ -class SnapPointsClass -{ -public: - static void Export_Points(INode * scene_root,TimeValue time,ChunkSaveClass & csave); -}; - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/TARGA.CPP b/Generals/Code/Tools/WW3D/max2w3d/TARGA.CPP deleted file mode 100644 index ba77e106d1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/TARGA.CPP +++ /dev/null @@ -1,1397 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/**************************************************************************** -* -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S -* -*---------------------------------------------------------------------------- -* -* FILE -* targa.cpp -* -* DESCRIPTION -* Targa image file class. -* -* PROGRAMMER -* Denzil E. Long, Jr. -* -* DATE -* August 8, 1995 -* -*---------------------------------------------------------------------------- -* -* PUBLIC -* Open - Open Targa image file. -* Close - Close Targa image file. -* Load - Load Targa image file. -* Save - Save a Targa Image File. -* XFlip - X flip the image. -* YFlip - Y flip the image. -* SetImage - Set the image buffer. -* GetImage - Get the current image buffer address. -* SetPalette - Set the palette buffer. -* GetPalette - Retrieve the current palette buffer address. -* GetExtension - Get Extension data. (Targa 2.0 files only) -* -* PRIVATE -* DecodeImage - Decompress Targa image data. -* EncodeImage - Compress the image using targa RLE. -* InvertImage - Invert TrueColor image data. -* -* MODIFICATIONS: -* Converted to work with FileClass, FileFactory (changes are inside -* ifdefs, so can be easily reversed). Naty Hoffman, January 25, 2001 -* -****************************************************************************/ - -#include "TARGA.H" -#ifndef TGA_USES_WWLIB_FILE_CLASSES -#include -#endif -#include -#include -#include -#ifdef TGA_USES_WWLIB_FILE_CLASSES -#include "wwfile.h" -#include "ffactory.h" -#else -#include -#include -#include -#endif - - -/**************************************************************************** -* -* NAME -* Targa::Targa - Initialize a Targa instance. -* -* SYNOPSIS -* Targa() -* -* void Targa(void); -* -* FUNCTION -* Initialize the targa class instance. -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -Targa::Targa(void) - { - mImage = NULL; - mPalette = NULL; - Clear_File(); - mAccess = TGA_READMODE; - mFlags = 0; - memset(&Header, 0, sizeof(TGAHeader)); - memset(&mExtension, 0, sizeof(TGA2Extension)); - } - - -/**************************************************************************** -* -* NAME -* Targa::~Targa - Targa class destructor. -* -* SYNOPSIS -* ~Targa() -* -* void ~Targa(void); -* -* FUNCTION -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -Targa::~Targa(void) -{ - /* Close the file if has been left open. */ - Close(); - - /* Free the palette buffer if we allocated it. */ - if ((mPalette != NULL) && (mFlags & TGAF_PAL)) - free(mPalette); - - /* Free the image buffer if we allocated it. */ - if ((mImage != NULL) && (mFlags & TGAF_IMAGE)) - free(mImage); -} - - -/**************************************************************************** -* -* NAME -* Targa::Open - Open Targa image file. -* -* SYNOPSIS -* Error = Open(Name, Mode) -* -* long Open(char *, long); -* -* FUNCTION -* Open a Targa image file and read in its header. The file stream will -* positioned after the ID field (if there is one). -* -* INPUTS -* Name - Pointer to name of Targa file. -* Mode - Access mode. -* -* RESULT -* Error - Error code, 0 if okay. -* -****************************************************************************/ - -long Targa::Open(const char* name, long mode) -{ - TGA2Footer footer; - long size; - long error = 0; - - /* File already open? */ - if (Is_File_Open() && (mAccess == mode)) { - return (0); - } - - Close(); - - /* Initialize the access mode. */ - mAccess = mode; - mFlags &= ~TGAF_TGA2; - - switch (mode) { - - /* Open targa file for read. */ - case TGA_READMODE: - if (File_Open_Read(name)) { - - /* Check for 2.0 targa file by loading the footer */ - if (File_Seek(-26, SEEK_END) == -1) { - error = TGAERR_READ; - } - - if (!error) { - if (File_Read(&footer, sizeof(TGA2Footer)) != sizeof(TGA2Footer)) { - error = TGAERR_READ; - } else { - /* If this a 2.0 file with an extension? */ - if (strncmp(footer.Signature, TGA2_SIGNATURE, 16) == 0) { - if (footer.Extension != 0) { - mFlags |= TGAF_TGA2; - } - } - } - } - - /* Read in Extension data */ - if (!error && (mFlags & TGAF_TGA2)) { - - if (File_Seek(footer.Extension, SEEK_SET) == -1) { - error = TGAERR_READ; - } - - if (!error) { - if (File_Read(&mExtension, sizeof(TGA2Extension)) != sizeof(TGA2Extension)) { - error = TGAERR_READ; - } - } - } - - /* Read in header. */ - if (!error && (File_Seek(0, SEEK_SET) == -1)) { - error = TGAERR_READ; - } else { - - size = File_Read(&Header, sizeof(TGAHeader)); - if (size != sizeof(TGAHeader)) { - error = TGAERR_READ; - } - } - - /* Skip the ID field */ - if (!error && (Header.IDLength != 0)) { - if (File_Seek(Header.IDLength, SEEK_CUR) == -1) { - error = TGAERR_READ; - } - } - - } else { - error = TGAERR_OPEN; - } - break; - - /* Open targa file for write. */ - case TGA_WRITEMODE: - if (!File_Open_Write(name)) { - error = TGAERR_OPEN; - } else { -// printf("\r"); - } - break; - - /* Open targa file for read/write.*/ - case TGA_RDWRMODE: - if (File_Open_ReadWrite(name)) { - - /* Read in header. */ - size = File_Read(&Header, sizeof(TGAHeader)); - - if (size != sizeof(TGAHeader)) { - error = TGAERR_READ; - } - /* Skip the ID field */ - if (!error && (Header.IDLength != 0)) { - if (File_Seek(Header.IDLength, SEEK_CUR) == -1) { - error = TGAERR_READ; - } - } - - } else { - error = TGAERR_OPEN; - } - break; - } - - /* Close on any error! */ - if (error) { - Close(); - } - - return (error); -} - - -/**************************************************************************** -* -* NAME -* Targa::Close - Close Targa image file. -* -* SYNOPSIS -* Close() -* -* void Close(void); -* -* FUNCTION -* Close the Targa image file and free its handle. -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -void Targa::Close(void) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - if (TGAFile) { - TGAFile->Close(); - _TheFileFactory->Return_File(TGAFile); - TGAFile = NULL; - } -#else - /* Close the file if it is open. */ - if (mFH != -1) { - close(mFH); - mFH = -1; - } -#endif -} - - -/**************************************************************************** -* -* NAME -* Targa::Load - Load Targa Image File into specified buffers. -* -* SYNOPSIS -* Error = Load(Name, Palette, ImageBuffer) -* -* long Load(char *, char *, char *); -* -* FUNCTION -* Open and load the Targa into the specified buffers. If either buffer -* pointer is NULL then that field will not be processed. -* -* INPUTS -* Name - Name of Targa image file to load. -* Palette - Pointer to buffer to load the palette into. -* ImageBuffer - Pointer to buffer to load the image data into. -* -* RESULT -* Error - 0 if successful, or TGAERR_??? error code. -* -****************************************************************************/ - -long Targa::Load(const char* name, char* palette, char* image,bool invert_image) -{ - long size; - long depth; - long error = 0; - - /* Open the Targa */ - if (Open(name, TGA_READMODE) == NULL) { - - /* Process ColorMap (palette) */ - if (Header.ColorMapType == 1) { - - depth = (Header.CMapDepth >> 3); - size = (Header.CMapLength * depth); - - /* Load the palette from the TGA if a palette buffer is provided - * otherwise we will skip it. - */ - if ((palette != NULL) && (Header.CMapLength > 0)) { - - /* Adjust palette to the starting color entry. */ - palette += (Header.CMapStart * depth); - - /* Read in the palette. */ - if (File_Read(palette, size) != size) { - error = TGAERR_READ; - } - - } else { - if (File_Seek(size, SEEK_CUR) == -1) { - error = TGAERR_READ; - } - } - } - - /* Load the image data from the TGA if an image buffer is provided - * otherwise we are done. - */ - if (!error && (image != NULL)) { - - depth = TGA_BytesPerPixel(Header.PixelDepth); - size = ((Header.Width * Header.Height) * depth); - - switch (Header.ImageType) { - case TGA_CMAPPED: - if (File_Read(image, size) != size) { - error = TGAERR_READ; - } - break; - - case TGA_TRUECOLOR: - if (File_Read(image, size) == size) { - if (invert_image) InvertImage(); - } else { - error = TGAERR_READ; - } - break; - - case TGA_MONO: - if (File_Read(image, size) != size) { - error = TGAERR_READ; - } - break; - - case TGA_CMAPPED_ENCODED: - error = DecodeImage(); - break; - - case TGA_TRUECOLOR_ENCODED: - if ((error = DecodeImage()) == NULL) { - if (invert_image) InvertImage(); - } - break; - - default: - error = TGAERR_NOTSUPPORTED; - break; - } - - /* Arrange the image so that the origin position (coordinate 0,0) - * is the upperleft hand corner of the image. - */ - if (!error) { - if ( Header.ImageDescriptor & TGAIDF_XORIGIN ) { - XFlip(); - Header.ImageDescriptor &= ~TGAIDF_XORIGIN; - } - - // Mod (IML) : Locate the origin at the bottom-left corner instead. This - // will make ot consistent with .TGA's that have been generated with our - // existing software. - // if (( Header.ImageDescriptor & TGAIDF_YORIGIN ) == 0){ - if ( Header.ImageDescriptor & TGAIDF_YORIGIN ) { - YFlip(); - // Bug fix (IML) : Clear this flag to indicate to the targa reader - // that the Y-origin is at the bottom of the image. - Header.ImageDescriptor &= ~TGAIDF_YORIGIN; - } - } - } - - /* Close the Targa */ - Close(); - - } else { - error = TGAERR_OPEN; - } - - return (error); -} - - -/**************************************************************************** -* -* NAME -* Targa::Load - Load Targa Image File. (Auto buffer allocation). -* -* SYNOPSIS -* Error = Load(Name, Flags) -* -* long Load(char, long); -* -* FUNCTION -* Open and load the Targa into buffers allocated by this function. -* -* INPUTS -* Name - Name of Targa image file to load. -* Flags - -* -* RESULT -* Error - 0 if successful, or TGAERR_??? error code. -* -****************************************************************************/ - -long Targa::Load(const char* name, long flags, bool invert_image) -{ - long size; - long error = 0; - - /* Open the file to get the header. */ - if (Open(name, TGA_READMODE) == 0) { - - /* Allocate palette memory if requested to and the targa has one. */ - if ((flags & TGAF_PAL) && (Header.ColorMapType == 1)) { - - /* Dispose of any previous palette. */ - if ((mPalette != NULL) && (mFlags & TGAF_PAL)) { - free(mPalette); - mPalette = NULL; - mFlags &= ~TGAF_PAL; - } - - /* Only allocate a palette if the client hasn't assigned one. */ - if ((mPalette == NULL) && !(mFlags & TGAF_PAL)) { - - /* Compute the size of the palette from the targa header. */ - size = (Header.CMapLength * (Header.CMapDepth >> 3)); - - if (size != 0) { - /* Allocate memory for the palette. */ - if ((mPalette = (char *)malloc(size)) != NULL) { - mFlags |= TGAF_PAL; /* We allocated the palette. */ - } else { - error = TGAERR_NOMEM; - } - } - } - } - - /* Allocate image memory if requested to. */ - if (!error && (flags & TGAF_IMAGE)) { - - /* Dispose of any previous image. */ - if ((mImage != NULL) && (mFlags & TGAF_IMAGE)) { - free(mImage); - mImage = NULL; - mFlags &= ~TGAF_IMAGE; - } - - /* Only allocate an image if the client hasn't assigned one. */ - if ((mImage == NULL) && !(mFlags & TGAF_IMAGE)) { - - /* Compute the size of the image data from the targa header. */ - size = ((Header.Width * Header.Height) * TGA_BytesPerPixel(Header.PixelDepth)); - if (size != 0) { - /* Allocate memory for the image. */ - if ((mImage = (char *)malloc(size)) != NULL) { - mFlags |= TGAF_IMAGE; /* We allocated the image. */ - } else { - error = TGAERR_NOMEM; - } - } - } - } - - /* Read in the file contents. */ - if (!error) { - error = Load(name, mPalette, mImage, invert_image); - } - - /* Close the file. */ - Close(); - - } else { - error = TGAERR_OPEN; - } - - return (error); -} - - -/**************************************************************************** -* -* NAME -* Targa::Save - Save a Targa Image File. -* -* SYNOPSIS -* Error = Save(Name, Flags) -* -* long Save(char *, long); -* -* FUNCTION -* -* INPUTS -* Name - Pointer to name of file to save. -* Flags - -* -* RESULT -* Error - 0 if successful, or TGAERR_??? error code. -* -****************************************************************************/ - -long Targa::Save(const char* name, long flags, bool addextension) - { - long size; - long depth; - char *palette; - char *temppal; - char *ptr; - //long i,n; - //char c; - long error = 0; - TGA2Footer footer; - - /* Open the Targa for write. */ - if (Open(name, TGA_WRITEMODE) == NULL) - { - Header.IDLength = 0; - - /* Set the ImageType for compression. */ - if (flags & TGAF_COMPRESS) - { - switch (Header.ImageType) - { - case TGA_CMAPPED: - case TGA_TRUECOLOR: - case TGA_MONO: - Header.ImageType += 8; - break; - - case TGA_CMAPPED_ENCODED: - case TGA_TRUECOLOR_ENCODED: - case TGA_MONO_ENCODED: - break; - - /* Turn off compression for unknown types. */ - default: - flags &= ~TGAF_COMPRESS; - break; - } - } - - /*----------------------------------------------------------------------- - * WRITE THE HEADER DATA SECTION - *---------------------------------------------------------------------*/ - if (File_Write(&Header, sizeof(TGAHeader)) != sizeof(TGAHeader)) - error = TGAERR_WRITE; - - /*----------------------------------------------------------------------- - * WRITE THE COLORMAP (PALETTE) DATA SECTION - *---------------------------------------------------------------------*/ - if (!error && (flags & TGAF_PAL) && (mPalette != NULL) - && (Header.CMapLength > 0)) - { - /* Adjust palette to the starting color entry. */ - depth = (Header.CMapDepth >> 3); - palette = mPalette + (Header.CMapStart * depth); - size = (Header.CMapLength * depth); - - /* Allocate temporary buffer for palette manipulation. */ - if ((temppal = (char *)malloc(size)) != NULL) - { - memcpy(temppal, palette, size); - ptr = temppal; - - #if(0) - /* Swap the byte ordering of the palette entries. */ - for (i = 0; i < Header.CMapLength; i++) - { - c = *ptr; - *ptr = *(ptr + (depth - 1)); - *(ptr + (depth - 1)) = c; - - /* Next entry */ - palette += depth; - } - #endif - - /* Write the palette. */ - if (File_Write(temppal, size) != size) - error = TGAERR_WRITE; - - /* Free temporary palette buffer. */ - free(temppal); - } - else - error = TGAERR_NOMEM; - } - - /*----------------------------------------------------------------------- - * WRITE THE IMAGE DATA SECTION - *---------------------------------------------------------------------*/ - if (!error && (flags & TGAF_IMAGE) && (mImage != NULL)) - { - - bool imageinverted; - - /* Invert truecolor data. */ - if ((Header.ImageType == TGA_TRUECOLOR) || (Header.ImageType == TGA_TRUECOLOR_ENCODED)) { - InvertImage(); - imageinverted = true; - } else { - imageinverted = false; - } - - /* Write the image. */ - if (flags & TGAF_COMPRESS) - EncodeImage(); - else - { - depth = TGA_BytesPerPixel(Header.PixelDepth); - size = (((Header.Width * Header.Height)) * depth); - - if (File_Write(mImage, size) != size) - error = TGAERR_WRITE; - } - - // Bug fix (IML) : If the image was inverted, invert it again to restore it to its prior state. - if (imageinverted) InvertImage(); - } - - /*----------------------------------------------------------------------- - * WRITE THE EXTENSION DATA SECTION - *---------------------------------------------------------------------*/ - - // Mod (IML) Optionally add an extension to the file. - if (addextension) { - if (!error) { - - mExtension.ExtSize = 495; - strncpy(mExtension.SoftID, "Denzil's Targa Code", 41); - mExtension.SoftVer.Number = (1 * 100); - mExtension.SoftVer.Letter = 0; - - /* Save position of extension area. */ - if ((footer.Extension = File_Seek(0, SEEK_CUR)) == -1) - error = TGAERR_WRITE; - - if (!error && (File_Write(&mExtension, sizeof(TGA2Extension)) - != sizeof(TGA2Extension))) - error = TGAERR_WRITE; - } - } else { - footer.Extension = 0; - } - - /*----------------------------------------------------------------------- - * WRITE THE FOOTER DATA SECTION - *---------------------------------------------------------------------*/ - if (!error) - { - footer.Developer = 0; - strncpy(footer.Signature, TGA2_SIGNATURE, 16); - footer.RsvdChar = '.'; - footer.BZST = 0; - - if (File_Write(&footer, sizeof(TGA2Footer)) != sizeof(TGA2Footer)) - error = TGAERR_WRITE; - } - - /* Close targa file. */ - Close(); - } - else - error = TGAERR_OPEN; - - return (error); - } - - -/**************************************************************************** -* -* NAME -* Targa::XFlip - X flip the image. -* -* SYNOPSIS -* XFlip() -* -* void XFlip(); -* -* FUNCTION -* Flip the image in memory on its X axis. (left to right) -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -void Targa::XFlip(void) - { - char *ptr,*ptr1; - long x,y,d; - char v,v1; - char depth; - - /* Pixel depth in bytes. */ - depth = TGA_BytesPerPixel(Header.PixelDepth); - - for (y = 0; y < Header.Height; y++) - { - ptr = (mImage + ((Header.Width * depth) * y)); - ptr1 = (ptr + ((Header.Width * depth) - depth)); - - for (x = 0; x < (Header.Width / 2); x++) - { - for (d = 0; d < depth; d++) - { - v = *(ptr + d); - v1 = *(ptr1 + d); - *(ptr + d) = v1; - *(ptr1 + d) = v; - } - - ptr += depth; - ptr1 -= depth; - } - } - } - - -/**************************************************************************** -* -* NAME -* Targa::YFlip - Y flip the image. -* -* SYNOPSIS -* YFlip() -* -* void YFlip(); -* -* FUNCTION -* Flip the image in memory on its Y axis. (top to bottom) -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -void Targa::YFlip(void) - { - char *ptr,*ptr1; - long x,y; - char v,v1; - char depth; - - /* Pixel depth in bytes. */ - depth = TGA_BytesPerPixel(Header.PixelDepth); - - for (y = 0; y < (Header.Height >> 1); y++) - { - /* Compute address of lines to exchange. */ - ptr = (mImage + ((Header.Width * y) * depth)); - ptr1 = (mImage + ((Header.Width * (Header.Height - 1)) * depth)); - ptr1 -= ((Header.Width * y) * depth); - - /* Exchange all the pixels on this scan line. */ - for (x = 0; x < (Header.Width * depth); x++) - { - v = *ptr; - v1 = *ptr1; - *ptr = v1; - *ptr1 = v; - ptr++; - ptr1++; - } - } - } - - -/**************************************************************************** -* -* NAME -* Targa::SetImage - Set the image buffer. -* -* SYNOPSIS -* OldImage = SetImage(Image) -* -* char *SetImage(char *); -* -* FUNCTION -* Set the image buffer to one provided by the caller. -* -* INPUTS -* Image - Pointer to buffer to use for the image buffer. -* -* RESULT -* OldImage - Previous caller assigned image buffer. -* -****************************************************************************/ - -char *Targa::SetImage(char *buffer) -{ - char *oldbuffer = NULL; - - /* Free any image buffer before assigning another. */ - if ((mImage != NULL) && (mFlags & TGAF_IMAGE)) - { - free(mImage); - mImage = NULL; - mFlags &= ~TGAF_IMAGE; - } - - /* Get the old user buffer. */ - if (mImage != NULL) - oldbuffer = mImage; - - /* Assign the new image buffer. */ - mImage = buffer; - - return (oldbuffer); -} - - -/**************************************************************************** -* -* NAME -* Targa::SetPalette - Set the palette buffer. -* -* SYNOPSIS -* OldPal = SetPalette(Pal) -* -* char *SetPalette(char *); -* -* FUNCTION -* -* INPUTS -* Pal - Pointer to buffer to use for palette. -* -* RESULT -* OldPal - Pointer to previous user palette. -* -****************************************************************************/ - -char *Targa::SetPalette(char *buffer) -{ - char *oldbuffer = NULL; - - /* Free any image buffer before assigning another. */ - if ((mPalette != NULL) && (mFlags & TGAF_PAL)) - { - free(mPalette); - mPalette = NULL; - mFlags &= ~TGAF_PAL; - } - - /* Get the old user buffer. */ - if (mPalette != NULL) - oldbuffer = mPalette; - - /* Assign the new image buffer. */ - mPalette = buffer; - - return (oldbuffer); -} - - -bool Targa::IsCompressed(void) - { - if (Header.ImageType > 8) - return true; - - return false; - } - - -/**************************************************************************** -* -* NAME -* Targa::GetExtension - Get Extension data. (Targa 2.0 files only) -* -* SYNOPSIS -* Ext = GetExtension() -* -* TGA2Extension *GetExtension(void); -* -* FUNCTION -* Retrieve a pointer to the Targa 2.0 extension data area. If the file -* version is 1.0 OR there is no extensio area then a NULL will be returned. -* -* INPUTS -* NONE -* -* RESULT -* Ext - Pointer to Extension data, NULL if not available. -* -****************************************************************************/ - -TGA2Extension *Targa::GetExtension(void) - { - if (mFlags & TGAF_TGA2) - return (&mExtension); - - return (NULL); - } - - -/**************************************************************************** -* -* NAME -* Targa::DecodeImage - Decompress Targa image data. -* -* SYNOPSIS -* Error = DecodeImage() -* -* long DecodeImage(); -* -* FUNCTION -* Decode the RLE compressed image data into the specified buffer from -* the file I/O stream. -* -* INPUTS -* NONE -* -* RESULT -* Error - 0 if successful, or TGAERR_??? error code. -* -****************************************************************************/ - -long Targa::DecodeImage() - { - char *image; - char *color; - unsigned char count; - unsigned char depth; - unsigned long pixel_count; - unsigned long size; - unsigned long c,i; - long error = 0; - - /* Initialize */ - image = mImage; - - /* Compute pixel depth in bytes. */ - depth = TGA_BytesPerPixel(Header.PixelDepth); - - /* Total number of pixels compressed in this image. */ - pixel_count = (Header.Width * Header.Height); - - while ((pixel_count > 0) && !error) - { - /* Read count. */ - if (File_Read(&count, 1) == 1) - { - /* If bit 8 of the count is set then we have a run of pixels, - * otherwise the data is raw pixels. - */ - if (count & 0x80) - { - count &= 0x7F; - count++; - - /* Read in run pixel. */ - if (File_Read(image, depth) == depth) - { - color = image; - image += depth; - - /* Repeat the pixel for the run count in the image buffer. */ - for (c = 1; c < count; c++) - for (i = 0; i < depth; i++) - *image++ = *(color + i); - } - else - error = TGAERR_READ; - } - else - { - count++; - size = (count * depth); - - /* Read in raw pixels. */ - if ((unsigned)File_Read(image, size) == size) - image += size; - else - error = TGAERR_READ; - } - - /* Adjust the pixel count. */ - pixel_count -= count; - } - else - error = TGAERR_READ; - } - - return (error); - } - - -/**************************************************************************** -* -* NAME -* Targa::EncodeImage - Compress the image using targa RLE. -* -* SYNOPSIS -* EncodeImage() -* -* void EncodeImage(void); -* -* FUNCTION -* Encode the image data using the RLE algorithm outlined in the TARGA -* file specification. -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -long Targa::EncodeImage() - { - char *packet; - long packet_index; - char *start; - char *end; - long depth; - long pixels; - long count; - long match; - long i; - long error = 0; - - /* Initialize variables. */ - depth = TGA_BytesPerPixel(Header.PixelDepth); - - /* Allocate packet buffer to hold maximum encoded data run. */ - if ((packet = (char *)malloc(128 * depth)) != NULL) - { - pixels = Header.Width * Header.Height; - start = mImage; - end = start; - count = 0; - packet[0] = 0; - packet_index = 1; - - while ((pixels != 0) && !error) - { - match = 1; - - /* Advance to the next pixel */ - end += depth; - pixels--; - - /* Compare pixels. */ - for (i = 0; i < depth; i++) - { - if (start[i] != end[i]) - { - match = 0; - break; - } - } - - /* Run of pixels */ - if (match == 1) - { - count++; - - /* Continue counting until the maximum has been reached. */ - if (count < 128) - { - if (packet[0] == 0) - continue; - } - else - count--; - } - - /* If there is a count then write out the run. Otherwise, write - * the raw pixel to the packet. - */ - if ((count != 0) && (packet[0] == 0)) - { - /* Run count */ - packet[0] = (count | 0x80); - - /* Run pixel */ - for (i = 0; i < depth; i++) - packet[i + 1] = start[i]; - - /* Write the run packet. */ - if (File_Write(packet, (depth + 1)) != (depth + 1)) - error = TGAERR_WRITE; - - /* Reposition start and reset. */ - start = end; - count = 0; - packet[0] = 0; - } - else - { - if (count == 0) - { - /* Copy the raw pixel to the packet. */ - for (i = 0; i < depth; i++) - packet[packet_index + i] = start[i]; - - /* Increment the raw packet count. */ - packet[0]++; - - /* Reposition start */ - start = end; - packet_index += depth; - } - - /* Write the raw packet if the packet is full or a run has started - * or all the pixels have been processed. - */ - if ((packet[0] == 127) || (count != 0) || (pixels == 0)) - { - i = packet[0]; - packet[0]--; - - if (File_Write(packet, ((i * depth) + 1)) != ((i * depth) + 1)) - error = TGAERR_WRITE; - - packet_index = 1; - packet[0] = 0; - } - } - } - - /* Free the packet buffer. */ - free(packet); - } - else - error = TGAERR_NOMEM; - - return (error); - } - - -/**************************************************************************** -* -* NAME -* Targa::InvertImage - Invert TrueColor image data. -* -* SYNOPSIS -* InvertImage() -* -* void InvertImage(void); -* -* FUNCTION -* -* INPUTS -* NONE -* -* RESULT -* NONE -* -****************************************************************************/ - -void Targa::InvertImage(void) - { - char *buffer; - long depth; - long pixel_count; - long i; - char c; - - /* Initialize */ - buffer = mImage; - - /* Compute the pixel depth in bytes. */ - depth = TGA_BytesPerPixel(Header.PixelDepth); - - /* Total number of pixels in this image. */ - pixel_count = (Header.Width * Header.Height); - - /* 16-bit pixel layout is different that 24-bit and 32-bit. */ - if (depth > 2) - { - while (pixel_count > 0) - { - for (i = 0; i < (depth / 2); i++) - { - c = *(buffer + i); - *(buffer + i) = *(buffer + ((depth - 1) - i)); - *(buffer + ((depth - 1) - i)) = c; - } - - /* Next pixel */ - pixel_count--; - buffer += depth; - } - } - } - - -/* -** These functions are just for ease of ifdef'ing between standard io calls and FileClass. -*/ -void Targa::Clear_File(void) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - TGAFile = NULL; -#else - mFH = -1; -#endif -} -bool Targa::Is_File_Open(void) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - return (TGAFile != NULL); -#else - return (mFH != -1); -#endif -} -bool Targa::File_Open_Read(const char* name) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - TGAFile = _TheFileFactory->Get_File(name); - if (TGAFile && TGAFile->Is_Available()) { - return (TGAFile->Open(FileClass::READ) != 0); - } else { - return false; - } -#else - mFH = open(name, (O_RDONLY|O_BINARY)); - return (mFH != -1); -#endif -} -bool Targa::File_Open_Write(const char* name) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - TGAFile = _TheWritingFileFactory->Get_File(name); - if (TGAFile) { - return (TGAFile->Open(FileClass::WRITE) != 0); - } else { - return false; - } -#else - mFH = open(name, (O_CREAT|O_TRUNC|O_WRONLY|O_BINARY), (S_IREAD|S_IWRITE)); - return (mFH != -1); -#endif -} -bool Targa::File_Open_ReadWrite(const char* name) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - TGAFile = _TheWritingFileFactory->Get_File(name); - if (TGAFile && TGAFile->Is_Available()) { - return (TGAFile->Open(FileClass::READ|FileClass::WRITE) != 0); - } else { - return false; - } -#else - mFH = open(name, (O_RDWR|O_BINARY), (S_IREAD|S_IWRITE)); - return (mFH != -1); -#endif -} -int Targa::File_Seek(int pos, int dir) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - return TGAFile->Seek(pos, dir); -#else - return lseek(mFH, pos, dir); -#endif -} -int Targa::File_Read(void *buffer, int size) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - return TGAFile->Read(buffer, size); -#else - return read(mFH, buffer, size); -#endif -} -int Targa::File_Write(void *buffer, int size) -{ -#ifdef TGA_USES_WWLIB_FILE_CLASSES - return TGAFile->Write(buffer, size); -#else - return write(mFH, buffer, size); -#endif -} - -// ---------------------------------------------------------------------------- -// -// Output targa load error message. -// -// ---------------------------------------------------------------------------- - -long Targa_Error_Handler(long load_err,const char* filename) -{ - switch (load_err) { - case 0: - return 0; - case TGAERR_OPEN: -// WWDEBUG_SAY(("Targa: Failed to open file \"%s\"\n", filename)); - break; - - case TGAERR_READ: -// WWDEBUG_SAY(("Targa: Failed to read file \"%s\"\n", filename)); - break; - - case TGAERR_NOTSUPPORTED: -// WWDEBUG_SAY(("Targa: File \"%s\" is an unsupported Targa type\n", filename)); - break; - - case TGAERR_NOMEM: -// WWDEBUG_SAY(("Targa: Failed to allocate memory for file \"%s\"\n", filename)); - break; - - default: -// WWDEBUG_SAY(("Targa: Unknown error when loading file \"%s\"\n", filename)); - break; - } - return load_err; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/TARGA.H b/Generals/Code/Tools/WW3D/max2w3d/TARGA.H deleted file mode 100644 index c0b1472ed1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/TARGA.H +++ /dev/null @@ -1,320 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef _TARGA_H_ -#define _TARGA_H_ -/**************************************************************************** -* -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S -* -*---------------------------------------------------------------------------- -* -* FILE -* Targa.h -* -* DESCRIPTION -* Targa image file class definitions. -* -* PROGRAMMER -* Denzil E. Long, Jr. -* -* DATE -* July 15, 1998 -* -****************************************************************************/ - -#pragma pack(push, 1) - -// If you wish to display loading error messages call targa functions inside of -// the following macro - for example TARGA_ERROR_HANDLER(targa.Open(filename, TGA_READMODE)); -// The error code is returned back from the handler so it can be used in an expression. -long Targa_Error_Handler(long error_code,const char* filename); -#define TARGA_ERROR_HANDLER(call,filename) Targa_Error_Handler(call,filename) - -/*--------------------------------------------------------------------------- - * STRUCTURES AND RELATED DEFINITIONS - *-------------------------------------------------------------------------*/ - -/* TGAHeader - Targa Image File header. - * - * IDLength - Size of Image ID field - * ColorMapType - Color map type. - * ImageType - Image type code. - * CMapStart - Color map origin. - * CMapLength - Color map length. - * CMapDepth - Depth of color map entries. - * XOffset - X origin of image. - * YOffset - Y origin of image. - * Width - Width of image. - * Height - Height of image. - * PixelDepth - Image pixel size - * ImageDescriptor - Image descriptor byte. - */ -typedef struct _TGAHeader - { - char IDLength; - char ColorMapType; - char ImageType; - short CMapStart; - short CMapLength; - char CMapDepth; - short XOffset; - short YOffset; - short Width; - short Height; - char PixelDepth; - char ImageDescriptor; - } TGAHeader; - -/* ImageType definiton */ -#define TGA_NOIMAGE 0 /* No image data included in file */ -#define TGA_CMAPPED 1 /* Color-mapped image data */ -#define TGA_TRUECOLOR 2 /* Truecolor image data */ -#define TGA_MONO 3 /* Monochrome image data */ -#define TGA_CMAPPED_ENCODED 9 /* Color-mapped image data (Encoded) */ -#define TGA_TRUECOLOR_ENCODED 10 /* Truecolor image data (Encoded) */ -#define TGA_MONO_ENCODED 11 /* Monochrome image data (Encoded) */ - -/* ImageDescriptor definition */ -#define TGAIDF_ATTRIB_BITS (0x0F<<0) /* Number of attribute bits per pixel */ -#define TGAIDF_XORIGIN (1<<4) -#define TGAIDF_YORIGIN (1<<5) - -/* Access modes. */ -#define TGA_READMODE 0 -#define TGA_WRITEMODE 1 -#define TGA_RDWRMODE 2 - -/* Error codes */ -#define TGAERR_OPEN -1 -#define TGAERR_READ -2 -#define TGAERR_WRITE -3 -#define TGAERR_SYNTAX -4 -#define TGAERR_NOMEM -5 -#define TGAERR_NOTSUPPORTED -6 - -/* Flags definitions */ -#define TGAF_IMAGE (1<<0) -#define TGAF_PAL (1<<1) -#define TGAF_COMPRESS (1<<2) -#define TGAF_TGA2 (1<<3) - -/* Macro definitions */ -#define TGA_BytesPerPixel(a) ((a+7) >> 3) - -/*--------------------------------------------------------------------------- - * TARGA 2.0 DEFINITIONS - *-------------------------------------------------------------------------*/ - -#define TGA2_SIGNATURE "TRUEVISION-XFILE" - -/* TGA2Footer - Targa 2.0 footer - * - * Extension - Offset to the Extension area from start of file. - * Developer - Offset to the Developer area from start of file. - * Signature - 16 byte Targa 2.0 signature "TRUEVISION-XFILE" - * RsvdChar - Reserved character, must be ASCII "." (period) - * BZST - Binary Zero String Terminator. - */ -typedef struct _TGA2Footer - { - long Extension; - long Developer; - char Signature[16]; - char RsvdChar; - char BZST; - _TGA2Footer() {} - } TGA2Footer; - -/* TGA2DateStamp - A series of 3 WORD values which define the integer value - * for the date the image was saved. - * - * Month - Month number (1 - 12) - * Day - Day number (1 - 31) - * Year - Year number (4 digit, ie. 1989) - */ -typedef struct _TGA2DateStamp - { - short Month; - short Day; - short Year; - } TGA2DateStamp; - -/* TGA2TimeStamp - A series of 3 WORD values which define the integer value - * for the time the image was saved. - * - * Hour - Hour number, military time (0 - 23) - * Minute - Minute number (0 - 59) - * Second - Second number (0 - 59) - */ -typedef struct _TGA2TimeStamp - { - short Hour; - short Minute; - short Second; - } TGA2TimeStamp; - -/* TGA2SoftVer - Define the version of the software used to generate file. - * - * Number - Version number * 100 - * Letter - Version letter - */ -typedef struct _TGA2SoftVer - { - short Number; - char Letter; - } TGA2SoftVer; - -/* TGA2Ratio - Numerator and denominator which when taken together specify - * a ratio. - * - * Numer - Numerator - * Denom - Denominator (a value of zero indicates no ratio specified) - */ -typedef struct _TGA2Ratio - { - short Numer; - short Denom; - } TGA2Ratio; - -/* TGA2Extension - Extension area, provided for additional file information. - * This data is pointed to by the Extension offset in the - * TGA2Footer. - * - * ExtSize - Extension area size. (495 bytes for 2.0) - * AuthName - Name of the person who created image (NULL terminated ASCII) - * AuthComment - Comments of the author (NULL terminated ASCII) - * DateStamp - Date the file was created. (See TGA2DateStamp) - * TimeStamp - Time the file was created. (See TGA2TimeStamp) - * JobName - Name of job image belongs to (NULL terminated ASCII) - * JobTime - Elapsed time of the job. - * SoftID - ID of software used to create image (NULL terminated ASCII) - * SoftVer - Version number of software used. - * KeyColor - Tranparent color value. - * Aspect - Pixel aspect ratio. - * Gamma - Fractional gamma value. - * ColorCor - Color correction table offset. - * PostStamp - Postage stamp image offset. - * ScanLine - Scan line table offset. - * Attributes - Alpha channel attributes. (Set defines below) - */ -typedef struct _TGA2Extension - { - short ExtSize; - char AuthName[41]; - char AuthComment[324]; - TGA2DateStamp Date; - TGA2TimeStamp Time; - char JobName[41]; - TGA2TimeStamp JobTime; - char SoftID[41]; - TGA2SoftVer SoftVer; - long KeyColor; - TGA2Ratio Aspect; - TGA2Ratio Gamma; - long ColorCor; - long PostStamp; - long ScanLine; - char Attributes; - } TGA2Extension; - -/* Alpha channel attributes (Extension Area) */ -#define EXTA_NOALPHA 0 /* No alpha data included */ -#define EXTA_IGNORE 1 /* Undefined alpha data, can ignore */ -#define EXTA_RETAIN 2 /* Undefined alpha data, should retain */ -#define EXTA_USEFUL 3 /* Useful alpha channel */ -#define EXTA_PREMULT 4 /* Pre-Multiplied alpha data */ - -#pragma pack(pop) - -/* -** This define changes this code from code that works with standard IO calls, -** to code that uses FileClass and FileFactoryClass. -*/ -//#define TGA_USES_WWLIB_FILE_CLASSES - -#ifdef TGA_USES_WWLIB_FILE_CLASSES -class FileClass; -#endif - -/*--------------------------------------------------------------------------- - * CLASS DEFINITION - *-------------------------------------------------------------------------*/ - -class Targa - { - public: - /* Constructor/destructor */ - Targa(void); - ~Targa(); - - /* Function prototypes. */ - long Open(const char* name, long mode); - void Close(void); - - long Load(const char* name, char* palette, char* image,bool invert_image=true); - long Load(const char* name, long flags, bool invert_image=true); - long Save(const char* name, long flags, bool addextension = false); - - void XFlip(void); - void YFlip(void); - - char* SetImage(char* buffer); - char* GetImage(void) const {return (mImage);} - - char* SetPalette(char* buffer); - char* GetPalette(void) const {return (mPalette);} - - bool IsCompressed(void); - - TGA2Extension* GetExtension(void); - - TGAHeader Header; - - protected: -#ifdef TGA_USES_WWLIB_FILE_CLASSES - FileClass *TGAFile; -#else - long mFH; -#endif - long mAccess; - long mFlags; - char* mImage; - char* mPalette; - TGA2Extension mExtension; - - private: - // Utility functions - long DecodeImage(void); - long EncodeImage(void); - void InvertImage(void); - - // These functions are for ease of ifdef'ing between standard io calls - // and FileClass. - void Clear_File(void); - bool Is_File_Open(void); - bool File_Open_Read(const char* name); - bool File_Open_Write(const char* name); - bool File_Open_ReadWrite(const char* name); - int File_Seek(int pos, int dir); - int File_Read(void *buffer, int size); - int File_Write(void *buffer, int size); - }; - -#endif /* _TARGA_H_ */ - diff --git a/Generals/Code/Tools/WW3D/max2w3d/Utility.cpp b/Generals/Code/Tools/WW3D/max2w3d/Utility.cpp deleted file mode 100644 index ca44363eba..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/Utility.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/Utility.cpp $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 5/08/00 11:51a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * wwGetAbsolutePath -- Returns the absolute path based on a relative one. * - * wwInputBox -- Retrive a string from the user in a nice friendly manner. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -/* -** Utility.cpp - Implementation of a some convenient features the WIN32 API provides -** that the MAXScript API doesn't. -*/ - - -#include -#include -#include -#include - -#include "util.h" -#include "InputDlg.h" - - -/* -** Let MAXScript know we're implementing new built-in functions. -*/ -def_visible_primitive(get_absolute_path, "wwGetAbsolutePath"); -def_visible_primitive(input_box, "wwInputBox"); - - -/*********************************************************************************************** - * get_absolute_path_cf -- Returns the absolute path based on a relative one. * - * * - * wwGetAbsolutePath - Usage: wwGetAbsolutePath * - * * - * INPUT: A string containing a relative path, and its context. * - * * - * OUTPUT: The equivalent absolute path. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/4/1999 AJA : Created. * - *=============================================================================================*/ -Value * get_absolute_path_cf (Value **arg_list, int count) -{ - // We want an array as an argument - check_arg_count("wwGetAbsolutePath", 2, count); - type_check(arg_list[0], String, "Relative path"); - type_check(arg_list[1], String, "Context"); - - // Grab the arguments out of the array. - char absolute[MAX_PATH]; - char *relative = arg_list[0]->to_string(); - char *context = arg_list[1]->to_string(); - - // Turn the relative path into an absolute one. - Create_Full_Path(absolute, context, relative); - - // Return the absolute path. - one_typed_value_local(String *abs); - vl.abs = new String(absolute); - return_value(vl.abs); -} - - -/*********************************************************************************************** - * input_box_cf -- Retrive a string from the user in a nice friendly manner. * - * * - * wwInputBox - Usage: wwInputBox [caption:'caption'] [label:'label'] [value:'value'] * - * * - * INPUT: Three optional named arguments. If they are not given values, defaults are used. * - * * - * OUTPUT: Returns the string entered by the user. * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -Value * input_box_cf (Value **arg_list, int count) -{ - // Create the input box (but don't show it yet). - InputDlg input_box(MAXScript_interface->GetMAXHWnd()); - Value *param = NULL; - - // Check the 'caption' parameter. - param = key_arg(caption); - if (param && param != &unsupplied) - input_box.SetCaption(param->to_string()); - - // Check the 'label' parameter. - param = key_arg(label); - if (param && param != &unsupplied) - input_box.SetLabel(param->to_string()); - - // Check the 'value' parameter. - param = key_arg(value); - if (param && param != &unsupplied) - input_box.SetValue(param->to_string()); - - // Show the dialog and let the user enter a value. - if (input_box.DoModal() == IDCANCEL) - return &undefined; - - // Return the value the user entered. - one_typed_value_local(String *val); - vl.val = new String(input_box.m_Value); - return_value(vl.val); -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/aabtreebuilder.cpp b/Generals/Code/Tools/WW3D/max2w3d/aabtreebuilder.cpp deleted file mode 100644 index 52edb974b1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/aabtreebuilder.cpp +++ /dev/null @@ -1,930 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/aabtreebuilder.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/24/00 8:41a $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * AABTreeBuilderClass::AABTreeBuilderClass -- Constructor * - * AABTreeBuilderClass::~AABTreeBuilderClass -- Destructor * - * AABTreeBuilderClass::Reset -- reset the builder, delete all arrays * - * AABTreeBuilderClass::Build_AABTree -- Build an AABTree for the given mesh. * - * AABTreeBuilderClass::Build_Tree -- recursivly builds the culling tree * - * AABTreeBuilderClass::Select_Splitting_Plane -- select a partition for the given polys * - * AABTreeBuilderClass::Compute_Plane_Score -- evaluate the suitability of a partition plane * - * AABTreeBuilderClass::Which_Side -- which side of a plane is the given poly * - * AABTreeBuilderClass::Split_Polys -- partition the polys with a plane * - * AABTreeBuilderClass::Compute_Bounding_Box -- compute bounding boxes for the cull nodes * - * AABTreeBuilderClass::Assign_Index -- assign an array index to each node * - * AABTreeBuilderClass::Node_Count -- Count the nodes in the tree * - * AABTreeBuilderClass::Poly_Count -- returns number of polys * - * AABTreeBuilderClass::Node_Count_Recursive -- internal implementation of Node_Count * - * AABTreeBuilderClass::Submit_Tree -- install nodes into an AABTreeClass * - * AABTreeBuilderClass::Submit_Tree_Recursive -- internal implementation of Submit_Tree * - * AABTreeBuilderClass::Update_Min -- ensure given vector is < min of the poly * - * AABTreeBuilderClass::Update_Max -- ensure given vector is > max of poly * - * AABTreeBuilderClass::Update_Min_Max -- ensure given vector is in min max of poly * - * AABTreeBuilderClass::Export -- Saves this AABTree into a W3D chunk * - * AABTreeBuilderClass::Build_W3D_AABTree_Recursive -- Build array of indices and W3dMeshAAB * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "aabtreebuilder.h" -#include "chunkio.h" -#include "w3d_file.h" -#include -#include -#include - -#define WWASSERT assert // can't use WWASSERT because we use this module in the MAX plugin... -const float COINCIDENCE_EPSILON = 0.001f; - - -/*********************************************************************************************** - * AABTreeBuilderClass::AABTreeBuilderClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -AABTreeBuilderClass::AABTreeBuilderClass(void) : - Root(NULL), - CurPolyIndex(0), - PolyCount(0), - Polys(NULL), - VertCount(0), - Verts(NULL) -{ -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::~AABTreeBuilderClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/19/2000 gth : Created. * - *=============================================================================================*/ -AABTreeBuilderClass::~AABTreeBuilderClass(void) -{ - Reset(); -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Reset -- reset the builder, delete all arrays * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/19/2000 gth : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Reset(void) -{ - if (Root) { - delete Root; Root = NULL; - } - - if (Verts != NULL) { - delete[] Verts; - Verts = NULL; - } - - if (Polys != NULL) { - delete[] Polys; - Polys = NULL; - } -} - -/*********************************************************************************************** - * AABTreeBuilderClass::Build_AABTree -- Build an AABTree for the given mesh. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Build_AABTree(int polycount,Vector3i * polys,int vertcount,Vector3 * verts) -{ - WWASSERT(polycount > 0); - WWASSERT(vertcount > 0); - WWASSERT(polys != NULL); - WWASSERT(verts != NULL); - - /* - ** If we already have allocated data, release it - */ - Reset(); - - /* - ** Copy the mesh data - */ - VertCount = vertcount; - PolyCount = polycount; - Verts = new Vector3[VertCount]; - Polys = new Vector3i[PolyCount]; - - for (int vi=0; viPolyCount = polycount; - node->PolyIndices = polyindices; - return; - } - - /* - ** Try to find a suitable partitioning plane. - */ - SplitChoiceStruct sc; - - sc = Select_Splitting_Plane(polycount,polyindices); - - /* - ** If the algorithm could not separate any polys, just install the polys - ** in this node and terminate. TODO: explore how this happens. - */ - if (sc.FrontCount + sc.BackCount != polycount) { - node->PolyCount = polycount; - node->PolyIndices = polyindices; - return; - } - - /* - ** Decide whether to actually partition this node. If the partitioning - ** will not gain us anything, just install the polys in this node and terminate - ** the tree. - */ -#if 0 - if (sc.Cost == MAX_COST) { - node->PolyCount = polycount; - node->PolyIndices = polyindices; - return; - } -#endif - - /* - ** Ok, split the polys - */ - SplitArraysStruct arrays; - Split_Polys(polycount,polyindices,sc,&arrays); - - /* - ** Free the memory in use by the input tile-list - */ - delete[] polyindices; - - /* - ** Build a front tree if necessary. Remember that the Build function - ** deletes the poly array. - */ - if (arrays.FrontCount) { - WWASSERT(arrays.FrontPolys != NULL); - node->Front = new CullNodeStruct; - Build_Tree(node->Front,arrays.FrontCount,arrays.FrontPolys); - arrays.FrontPolys = NULL; - } - - /* - ** Build a back tree if necessary. Remember that the build function - ** deletes the tile array. - */ - if (arrays.BackCount) { - WWASSERT(arrays.BackPolys != NULL); - - node->Back = new CullNodeStruct; - Build_Tree(node->Back,arrays.BackCount,arrays.BackPolys); - arrays.BackPolys = NULL; - } - -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Select_Splitting_Plane -- select a partition for the given polys * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -AABTreeBuilderClass::SplitChoiceStruct -AABTreeBuilderClass::Select_Splitting_Plane(int polycount,int * polyindices) -{ - WWASSERT(polyindices != NULL); - - const int NUM_TRYS = 50; - - SplitChoiceStruct best_plane_stats; - SplitChoiceStruct considered_plane_stats; - - /* - ** Try putting axis-aligned planes through some random vertices - */ - for (int trys = 0; trys < MIN(NUM_TRYS,polycount); trys++) { - - AAPlaneClass plane; - - /* - ** Select a random poly and vertex index; - */ - int poly_index = polyindices[rand() % polycount]; - int vert_index = rand() % 3; - const Vector3i * polyverts = Polys + poly_index; - const Vector3 * vert = Verts + (*polyverts)[vert_index]; - - /* - ** Select a random plane - */ - switch(rand() % 3) { - case 0: plane.Set(AAPlaneClass::XNORMAL,vert->X); break; - case 1: plane.Set(AAPlaneClass::YNORMAL,vert->Y); break; - case 2: plane.Set(AAPlaneClass::ZNORMAL,vert->Z); break; - }; - - /* - ** Get the score for this plane - */ - considered_plane_stats = Compute_Plane_Score(polycount,polyindices,plane); - - if (considered_plane_stats.Cost < best_plane_stats.Cost) { - best_plane_stats = considered_plane_stats; - } - } - - return best_plane_stats; -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Compute_Plane_Score -- evaluate the suitability of a partition plane * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -AABTreeBuilderClass::SplitChoiceStruct -AABTreeBuilderClass::Compute_Plane_Score(int polycount,int * polyindices,const AAPlaneClass & plane) -{ - /* - ** The score of a splitting plane is based on the following factors: - ** - the volumes of the resulting two children volumes, - ** - the number of polys in each child volume - */ - SplitChoiceStruct sc; - sc.Plane = plane; - - for (int i=0; i COINCIDENCE_EPSILON) { - mask |= POS; - } - if (delta < -COINCIDENCE_EPSILON) { - mask |= NEG; - } - mask |= ON; - } - - /* - ** Now evaluate the status of all of the verts to determine whether the - ** triangle is in front, behind, on or overlapping the plane - */ - - /* - ** If all verts were ON the plane, the triangle is ON the plane - */ - if (mask == ON) { - return ON; - } - - /* - ** If all verts were POS or ON, the triangle is POS (IN_FRONT) - */ - if ((mask & ~(POS | ON)) == 0) { - return POS; - } - - /* - ** If all verts were NEG or ON, the triangle is NEG (BEHIND) - */ - if ((mask & ~(NEG | ON)) == 0) { - return NEG; - } - - /* - ** Otherwise, the triangle spans the plane - */ - return BOTH; -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Split_Polys -- partition the polys with a plane * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Split_Polys -( - int polycount, - int * polyindices, - const SplitChoiceStruct & sc, - SplitArraysStruct * arrays -) -{ - /* - ** Note that this routine arrays of polygons. The caller is then responsible for keeping - ** track of the memory this routine allocates. - */ - if (sc.FrontCount > 0) { - arrays->FrontPolys = new int[sc.FrontCount]; - } - - if (sc.BackCount > 0) { - arrays->BackPolys = new int[sc.BackCount]; - } - - arrays->FrontCount = 0; - arrays->BackCount = 0; - - for (int i=0; iFrontPolys[arrays->FrontCount++] = polyindices[i]; - break; - - case BACK: - arrays->BackPolys[arrays->BackCount++] = polyindices[i]; - break; - } - } - - /* - ** when we are all done, the counts should match. - */ - WWASSERT(arrays->FrontCount == sc.FrontCount); - WWASSERT(arrays->BackCount == sc.BackCount); -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Compute_Bounding_Box -- compute bounding boxes for the cull nodes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Compute_Bounding_Box(CullNodeStruct * node) -{ - /* - ** compute bounding volumes of the children - */ - if (node->Front) { - Compute_Bounding_Box(node->Front); - } - - if (node->Back) { - Compute_Bounding_Box(node->Back); - } - - /* - ** compute bounding volume for the polys in this node - */ - node->Min.Set(100000.0f,100000.0f,100000.0f); - node->Max.Set(-100000.0f,-100000.0f,-100000.0f); - - for (int poly_index = 0; poly_index < node->PolyCount; poly_index++) { - Update_Min_Max(node->PolyIndices[poly_index],node->Min,node->Max ); - } - - /* - ** bound the polys in the front child node - */ - if (node->Front) { - if (node->Front->Min.X < node->Min.X) node->Min.X = node->Front->Min.X; - if (node->Front->Max.X > node->Max.X) node->Max.X = node->Front->Max.X; - - if (node->Front->Min.Y < node->Min.Y) node->Min.Y = node->Front->Min.Y; - if (node->Front->Max.Y > node->Max.Y) node->Max.Y = node->Front->Max.Y; - - if (node->Front->Min.Z < node->Min.Z) node->Min.Z = node->Front->Min.Z; - if (node->Front->Max.Z > node->Max.Z) node->Max.Z = node->Front->Max.Z; - } - - /* - ** bound the polys in the back child node - */ - if (node->Back) { - if (node->Back->Min.X < node->Min.X) node->Min.X = node->Back->Min.X; - if (node->Back->Max.X > node->Max.X) node->Max.X = node->Back->Max.X; - - if (node->Back->Min.Y < node->Min.Y) node->Min.Y = node->Back->Min.Y; - if (node->Back->Max.Y > node->Max.Y) node->Max.Y = node->Back->Max.Y; - - if (node->Back->Min.Z < node->Min.Z) node->Min.Z = node->Back->Min.Z; - if (node->Back->Max.Z > node->Max.Z) node->Max.Z = node->Back->Max.Z; - } - - WWASSERT(node->Min.X != 100000.0f); - WWASSERT(node->Min.Y != 100000.0f); - WWASSERT(node->Min.Z != 100000.0f); - WWASSERT(node->Max.X != -100000.0f); - WWASSERT(node->Max.Y != -100000.0f); - WWASSERT(node->Max.Z != -100000.0f); -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Assign_Index -- assign an array index to each node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -int AABTreeBuilderClass::Assign_Index(CullNodeStruct * node,int index) -{ - /* - ** This function is used to assign a sequential index to - ** each node in the tree. The AABTree stores its nodes in - ** an array so this index is used to determine which slot - ** in the array to put each node into. - */ - WWASSERT(node); - node->Index = index; - index++; - - if (node->Front) { - index = Assign_Index(node->Front,index); - } - - if (node->Back) { - index = Assign_Index(node->Back,index); - } - - return index; -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Node_Count -- Count the nodes in the tree * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -int AABTreeBuilderClass::Node_Count(void) -{ - if (Root) { - return Node_Count_Recursive(Root,0); - } else { - return 0; - } -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Poly_Count -- returns number of polys * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/23/98 GTH : Created. * - *=============================================================================================*/ -int AABTreeBuilderClass::Poly_Count(void) -{ - return PolyCount; -} - -/*********************************************************************************************** - * AABTreeBuilderClass::Node_Count_Recursive -- internal implementation of Node_Count * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/19/98 GTH : Created. * - *=============================================================================================*/ -int AABTreeBuilderClass::Node_Count_Recursive(CullNodeStruct * node,int curcount) -{ - curcount++; - if (node->Front) { - curcount = Node_Count_Recursive(node->Front,curcount); - } - if (node->Back) { - curcount = Node_Count_Recursive(node->Back,curcount); - } - return curcount; -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Update_Min -- ensure given vector is < min of the poly * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/98 GTH : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Update_Min(int poly_index,Vector3 & min) -{ - for (int vert_index = 0; vert_index < 3; vert_index++) { - - const Vector3i * polyverts = Polys + poly_index; - const Vector3 * point = Verts + (*polyverts)[vert_index]; - - if (point->X < min.X) min.X = point->X; - if (point->Y < min.Y) min.Y = point->Y; - if (point->Z < min.Z) min.Z = point->Z; - } -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Update_Max -- ensure given vector is > max of poly * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 6/22/98 GTH : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Update_Max(int poly_index,Vector3 & max) -{ - for (int vert_index = 0; vert_index < 3; vert_index++) { - - const Vector3i * polyverts = Polys + poly_index; - const Vector3 * point = Verts + (*polyverts)[vert_index]; - - if (point->X > max.X) max.X = point->X; - if (point->Y > max.Y) max.Y = point->Y; - if (point->Z > max.Z) max.Z = point->Z; - } -} - - -/*********************************************************************************************** - * AABTreeBuilderClass::Update_Min_Max -- ensure given vector is in min max of poly * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/24/98 BMG : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Update_Min_Max(int poly_index, Vector3 & min, Vector3 & max) -{ - for (int vert_index = 0; vert_index < 3; vert_index++) { - - const Vector3i * polyverts = Polys + poly_index; - const Vector3 * point = Verts + (*polyverts)[vert_index]; - - if (point->X < min.X) min.X = point->X; - if (point->Y < min.Y) min.Y = point->Y; - if (point->Z < min.Z) min.Z = point->Z; - - if (point->X > max.X) max.X = point->X; - if (point->Y > max.Y) max.Y = point->Y; - if (point->Z > max.Z) max.Z = point->Z; - } -} - - - -/*********************************************************************************************** - * AABTreeBuilderClass::Export -- Saves this AABTree into a W3D chunk * - * * - * This function will export the AABTree into a W3D chunk so that it can be loaded by its * - * sister class "AABTreeClass" in the WW3D library. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/22/2000 gth : Created. * - *=============================================================================================*/ -void AABTreeBuilderClass::Export(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(W3D_CHUNK_AABTREE); - - /* - ** Pack the tree into an array of W3dMeshAABTreeNode's and polygon indices - */ - W3dMeshAABTreeNode * nodes = new W3dMeshAABTreeNode[Node_Count()]; - uint32 * poly_indices = new uint32[Poly_Count()]; - - int cur_node = 0; - int cur_poly = 0; - Build_W3D_AABTree_Recursive(Root,nodes,poly_indices,cur_node,cur_poly); - - /* - ** Write out the header - */ - csave.Begin_Chunk(W3D_CHUNK_AABTREE_HEADER); - W3dMeshAABTreeHeader header; - memset(&header,0,sizeof(header)); - header.NodeCount = Node_Count(); - header.PolyCount = Poly_Count(); - csave.Write(&header,sizeof(header)); - csave.End_Chunk(); - - /* - ** Write out the array of polygon indices - */ - csave.Begin_Chunk(W3D_CHUNK_AABTREE_POLYINDICES); - csave.Write(poly_indices,Poly_Count() * sizeof(uint32)); - csave.End_Chunk(); - - /* - ** Write out the array of nodes - */ - csave.Begin_Chunk(W3D_CHUNK_AABTREE_NODES); - for (int ni=0; niIndex]); - newnode->Min.X = node->Min.X; - newnode->Min.Y = node->Min.Y; - newnode->Min.Z = node->Min.Z; - newnode->Max.X = node->Max.X; - newnode->Max.Y = node->Max.Y; - newnode->Max.Z = node->Max.Z; - - /* - ** If this is a non-leaf node, set up the child indices, otherwise set up the polygon indices - */ - if (node->Front != NULL) { - - WWASSERT(node->Back != NULL); // if we have one child, we better have both! - newnode->FrontOrPoly0 = node->Front->Index; - newnode->BackOrPolyCount = node->Back->Index; - - } else { - - newnode->FrontOrPoly0 = cur_poly | 0x80000000; - newnode->BackOrPolyCount = node->PolyCount; - - } - - /* - ** Copy the polygon indices for this node into our array - */ - for (int pcounter = 0; pcounter < node->PolyCount; pcounter++) { - poly_indices[cur_poly++] = node->PolyIndices[pcounter]; - } - - /* - ** Install the children - */ - if (node->Front) { - Build_W3D_AABTree_Recursive(node->Front,w3d_nodes,poly_indices,cur_node,cur_poly); - } - if (node->Back) { - Build_W3D_AABTree_Recursive(node->Back,w3d_nodes,poly_indices,cur_node,cur_poly); - } -} - - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/aabtreebuilder.h b/Generals/Code/Tools/WW3D/max2w3d/aabtreebuilder.h deleted file mode 100644 index 25a843a8ed..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/aabtreebuilder.h +++ /dev/null @@ -1,209 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/aabtreebuilder.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/22/00 2:02p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AABTREEBUILDER_H -#define AABTREEBUILDER_H - -#include "always.h" -#include "vector3.h" -#include "vector3i.h" -#include "aaplane.h" -#include "BITTYPE.H" -#include - -class AABTreeClass; -class ChunkSaveClass; -struct W3dMeshAABTreeNode; - -/* -** AABTreeBuilderClass -** This class serves simply to build AABTreeClasses. It first builds a tree -** which uses an easier to manage data structure (but uses more memory). Then -** the tree is converted into the representation used in the AABTreeClass. -*/ -class AABTreeBuilderClass -{ -public: - - AABTreeBuilderClass(void); - ~AABTreeBuilderClass(void); - - void Build_AABTree(int polycount,Vector3i * polys,int vertcount,Vector3 * verts); - void Export(ChunkSaveClass & csave); - - int Node_Count(void); - int Poly_Count(void); - - enum - { - MIN_POLYS_PER_NODE = 4, - SMALL_VERTEX = -100000, - BIG_VERTEX = 100000 - }; - -private: - - /* - ** This CullNodeStruct is used in building the AABTree. It is much more - ** wasteful in terms of memory footprint and number of allocations than the - ** streamlined version found in the actual AABTreeClass. - */ - struct CullNodeStruct - { - CullNodeStruct(void) : Index(0),Min(0,0,0),Max(0,0,0),Front(NULL),Back(NULL),PolyCount(0),PolyIndices(NULL) {} - ~CullNodeStruct(void) - { - if (Front) { delete Front; } - if (Back) { delete Back; } - if (PolyIndices) { delete[] PolyIndices; } - } - - int Index; - Vector3 Min; - Vector3 Max; - CullNodeStruct * Front; - CullNodeStruct * Back; - int PolyCount; - int * PolyIndices; - }; - - /* - ** SplitChoiceStruct - encapsulates the results of evaluating the suitability of a partition - */ - struct SplitChoiceStruct - { - SplitChoiceStruct(void) : - Cost(FLT_MAX), - FrontCount(0), - BackCount(0), - BMin(BIG_VERTEX,BIG_VERTEX,BIG_VERTEX), - BMax(SMALL_VERTEX,SMALL_VERTEX,SMALL_VERTEX), - FMin(BIG_VERTEX,BIG_VERTEX,BIG_VERTEX), - FMax(SMALL_VERTEX,SMALL_VERTEX,SMALL_VERTEX), - Plane(AAPlaneClass::XNORMAL,0) - { - } - - float Cost; // try to minimize this! - int FrontCount; // number of polys in front of the plane - int BackCount; // number of polys behind the plane - Vector3 BMin; // min of the bounding box of the "back" child - Vector3 BMax; // max of the bounding box of the "back" child - Vector3 FMin; // min of the bounding box of the "front" child - Vector3 FMax; // max of the bounding box of the "front" child - AAPlaneClass Plane; // partitioning plane - }; - - struct SplitArraysStruct - { - SplitArraysStruct(void) : - FrontCount(0), - BackCount(0), - FrontPolys(NULL), - BackPolys(NULL) - { - } - - int FrontCount; - int BackCount; - int * FrontPolys; - int * BackPolys; - }; - - enum OverlapType - { - POS = 0x01, - NEG = 0x02, - ON = 0x04, - BOTH = 0x08, - OUTSIDE = POS, - INSIDE = NEG, - OVERLAPPED = BOTH, - FRONT = POS, - BACK = NEG, - }; - - - /* - ** Internal functions - */ - void Reset(); - void Build_Tree(CullNodeStruct * node,int polycount,int * polyindices); - SplitChoiceStruct Select_Splitting_Plane(int polycount,int * polyindices); - SplitChoiceStruct Compute_Plane_Score(int polycont,int * polyindices,const AAPlaneClass & plane); - void Split_Polys(int polycount,int * polyindices,const SplitChoiceStruct & sc,SplitArraysStruct * arrays); - OverlapType Which_Side(const AAPlaneClass & plane,int poly_index); - void Compute_Bounding_Box(CullNodeStruct * node); - int Assign_Index(CullNodeStruct * node,int index); - int Node_Count_Recursive(CullNodeStruct * node,int curcount); - void Update_Min(int poly_index,Vector3 & set_min); - void Update_Max(int poly_index,Vector3 & set_max); - void Update_Min_Max(int poly_index, Vector3 & set_min, Vector3 & set_max); - - void Build_W3D_AABTree_Recursive(CullNodeStruct * node, - W3dMeshAABTreeNode * w3dnodes, - uint32 * poly_indices, - int & cur_node, - int & cur_poly); - /* - ** Tree - */ - CullNodeStruct * Root; - int CurPolyIndex; - - /* - ** Mesh data - */ - int PolyCount; - Vector3i * Polys; - int VertCount; - Vector3 * Verts; - - friend class AABTreeClass; -}; - - - - -#endif //AABTREEBUILDER_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/animationcompressionsettings.cpp b/Generals/Code/Tools/WW3D/max2w3d/animationcompressionsettings.cpp deleted file mode 100644 index 00d939acfc..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/animationcompressionsettings.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/animationcompressionsettings.cpp $* - * * - * Original Author:: Patrick Smith * - * * - * $Author:: Patrick $* - * * - * $Modtime:: 10/30/00 1:57p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "animationcompressionsettings.h" -#include "dllmain.h" -#include "resource.h" -#include "w3dexp.h" - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// AnimationCompressionSettingsDialogClass -// -//////////////////////////////////////////////////////////////////////////////////////// -AnimationCompressionSettingsDialogClass::AnimationCompressionSettingsDialogClass (Interface *maxinterface, HWND parent_wnd) : - MaxInterface (maxinterface), - Options (NULL), - Wnd (NULL), - ParentWnd (parent_wnd) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// ~AnimationCompressionSettingsDialogClass -// -//////////////////////////////////////////////////////////////////////////////////////// -AnimationCompressionSettingsDialogClass::~AnimationCompressionSettingsDialogClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Do_Modal -// -//////////////////////////////////////////////////////////////////////////////////////// -int -AnimationCompressionSettingsDialogClass::Do_Modal (void) -{ - int retval = ::DialogBoxParam (AppInstance, MAKEINTRESOURCE (IDD_ANIMATION_COMPRESSION), - ParentWnd, Real_Message_Proc, (LPARAM)this); - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Real_Message_Proc -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL CALLBACK -AnimationCompressionSettingsDialogClass::Real_Message_Proc -( - HWND wnd, - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - AnimationCompressionSettingsDialogClass *dialog_obj = NULL; - - // - // Setup the framework we need so that the instance - // can process the messages instead of this static callback. - // - if (message == WM_INITDIALOG) { - dialog_obj = (AnimationCompressionSettingsDialogClass *)lparam; - dialog_obj->Wnd = wnd; - ::SetProp (wnd, "DIALOG_OBJ", (HANDLE)dialog_obj); - } else { - dialog_obj = (AnimationCompressionSettingsDialogClass *)::GetProp (wnd, "DIALOG_OBJ"); - } - - // - // Allow the instance to handle the call - // - BOOL retval = FALSE; - if (dialog_obj != NULL) { - retval = dialog_obj->Message_Proc (message, wparam, lparam); - } - - // - // Cleanup the framework - // - if (message == WM_DESTROY) { - ::RemoveProp (wnd, "DIALOG_OBJ"); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Message_Proc -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL -AnimationCompressionSettingsDialogClass::Message_Proc -( - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - BOOL retval = FALSE; - - switch (message) - { - case WM_INITDIALOG: - { - // - // Center the dialog - // - RECT parent_rect = { 0 }; - RECT rect = { 0 }; - ::GetWindowRect (ParentWnd, &parent_rect); - ::GetWindowRect (Wnd, &rect); - int width = parent_rect.right - parent_rect.left; - int height = parent_rect.bottom - parent_rect.top; - ::SetWindowPos ( Wnd, NULL, - parent_rect.left + (width / 2) - ((rect.right - rect.left) / 2), - parent_rect.top + (height / 2) - ((rect.bottom - rect.top) / 2), - 0, 0, SWP_NOZORDER | SWP_NOSIZE); - - // - // Initialize the dialog controls - // - Initialize_Controls (); - } - break; - - case WM_COMMAND: - { - switch (LOWORD (wparam)) - { - case IDCANCEL: - EndDialog (Wnd, IDCANCEL); - break; - - case IDOK: - Save_Settings (); - EndDialog (Wnd, IDOK); - break; - } - } - break; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Controls -// -//////////////////////////////////////////////////////////////////////////////////////// -void -AnimationCompressionSettingsDialogClass::Initialize_Controls (void) -{ - SetCheckBox (Wnd, IDC_REDUCE_ANIMATION_CHECK, Options->ReduceAnimation); - char string[128] = { 0 }; - - // - // Populate the reduction percent combo box - // - HWND percent_combo = ::GetDlgItem (Wnd, IDC_REDUCE_ANIMATION_COMBO); - for (int index = 1; index < 100; index ++) { - sprintf (string, "%d", index); - ComboBox_AddString (percent_combo, string); - } - - // - // Populate the animation type combo box - // - HWND flavor_combo = ::GetDlgItem (Wnd, IDC_COMPRESS_ANIMATION_FLAVOR_COMBO); - ComboBox_AddString (flavor_combo, "TimeCoded"); - ComboBox_AddString (flavor_combo, "Adaptive Delta"); - - // - // Bounds check the parameters - // - if ((Options->ReduceAnimationPercent < 1) || (Options->ReduceAnimationPercent > 99)) { - Options->ReduceAnimationPercent = 50; - - } - - if ((Options->CompressAnimationFlavor < 0) || (Options->CompressAnimationFlavor >= ANIM_FLAVOR_VALID)) { - Options->CompressAnimationFlavor = 0; - } - - // - // Select the correct entries in the combo boxes - // - ComboBox_SetCurSel (percent_combo, Options->ReduceAnimationPercent - 1); - ComboBox_SetCurSel (flavor_combo, Options->CompressAnimationFlavor); - - // - // Fill in the error fields - // - ::sprintf (string, "%f", Options->CompressAnimationTranslationError); - ::SetDlgItemText (Wnd, IDC_MAX_TRANS_ERROR_EDIT, string); - - ::sprintf (string, "%f", Options->CompressAnimationRotationError); - ::SetDlgItemText (Wnd, IDC_MAX_ROT_ERROR_EDIT, string); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Save_Settings -// -//////////////////////////////////////////////////////////////////////////////////////// -void -AnimationCompressionSettingsDialogClass::Save_Settings (void) -{ - // - // Read the compression type setting - // - int flavor = ComboBox_GetCurSel (::GetDlgItem (Wnd, IDC_COMPRESS_ANIMATION_FLAVOR_COMBO)); - Options->CompressAnimationFlavor = flavor; - - // - // Determine whether or not we want to force reduction - // - Options->ReduceAnimation = (IsDlgButtonChecked (Wnd, IDC_REDUCE_ANIMATION_CHECK) == 1); - - // - // Read the reduction percent setting - // - int reduce_percent = ComboBox_GetCurSel (::GetDlgItem (Wnd, IDC_REDUCE_ANIMATION_COMBO)) + 1; - Options->ReduceAnimationPercent = reduce_percent; - - // - // Read the amount of compression error we'll allow in the translational component - // - char string[128]; - ::GetDlgItemText (Wnd, IDC_MAX_TRANS_ERROR_EDIT, string, sizeof (string)); - float trans_error = ::atof (string); - Options->CompressAnimationTranslationError = trans_error; - - // - // Read the amount of compression error we'll allow in the rotational component - // - ::GetDlgItemText (Wnd, IDC_MAX_ROT_ERROR_EDIT, string, sizeof (string)); - float rot_error = ::atof (string); - Options->CompressAnimationRotationError = rot_error; - return ; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/animationcompressionsettings.h b/Generals/Code/Tools/WW3D/max2w3d/animationcompressionsettings.h deleted file mode 100644 index 5e6ab3ca3c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/animationcompressionsettings.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/animationcompressionsettings.h $* - * * - * Original Author:: Patrick Smith * - * * - * $Author:: Patrick $* - * * - * $Modtime:: 10/30/00 1:57p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef __ANIMATION_COMPRESSION_SETTINGS_H -#define __ANIMATION_COMPRESSION_SETTINGS_H - -#include -#include -#include "w3dutil.h" - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// AnimationCompressionSettingsDialogClass -// -//////////////////////////////////////////////////////////////////////////////////////// -class AnimationCompressionSettingsDialogClass -{ -public: - - ////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////// - AnimationCompressionSettingsDialogClass (Interface *maxinterface, HWND parent_wnd = NULL); - ~AnimationCompressionSettingsDialogClass (void); - - - ////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////// - - void Set_Options (W3dExportOptionsStruct *options) { Options = options; } - int Do_Modal (void); - -private: - - ////////////////////////////////////////////////////////////////// - // Static methods - ////////////////////////////////////////////////////////////////// - static BOOL CALLBACK Real_Message_Proc (HWND wnd, UINT message, WPARAM wparam, LPARAM lparam); - - ////////////////////////////////////////////////////////////////// - // Private methods - ////////////////////////////////////////////////////////////////// - BOOL Message_Proc (UINT message, WPARAM wparam, LPARAM lparam); - void Initialize_Controls (void); - void Save_Settings (void); - - ////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////// - W3dExportOptionsStruct * Options; - Interface * MaxInterface; - HWND Wnd; - HWND ParentWnd; -}; - - -#endif //__ANIMATION_COMPRESSION_SETTINGS_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/bchannel.cpp b/Generals/Code/Tools/WW3D/max2w3d/bchannel.cpp deleted file mode 100644 index 1682caf8b1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/bchannel.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : W3D Tools * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/bchannel.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 5:25p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "bchannel.h" -#include "w3d_file.h" -#include "logdlg.h" -#include "exportlog.h" - - -BitChannelClass::BitChannelClass -( - uint32 id, - int maxframes, - uint32 chntype, - bool default_val -) : - ID(id), - ChannelType(chntype), - MaxFrames(maxframes), - IsEmpty(true), - DefaultVal(default_val), - Data(maxframes), - Begin(0), - End(0) -{ - // start "Begin" at the end of the array, whenever we set a value - // at an index less than "Begin", we push "Begin" back. - Begin = MaxFrames; - End = 0; -} - -BitChannelClass::~BitChannelClass(void) -{ -} - -void BitChannelClass::Set_Bit(int frameidx,bool bit) -{ - assert(frameidx >= 0); - assert(frameidx < MaxFrames); - - Data[frameidx] = bit; - - if (!is_default(bit)) { - IsEmpty = false; - } -} - -void BitChannelClass::Set_Bits(BooleanVectorClass & bits) -{ - for (int i=0; i= 0); - assert(frameidx < MaxFrames); - - return Data[frameidx]; -} - - -bool BitChannelClass::Save(ChunkSaveClass & csave, bool compress) -{ - if (IsEmpty) return true; - - if (compress) { - // Save the Channel Data Compressed - // TIMECODED - if (!csave.Begin_Chunk(W3D_CHUNK_COMPRESSED_BIT_CHANNEL)) { - return false; - } - - uint32 channelsize = sizeof(W3dTimeCodedBitChannelStruct); - uint32 packetsize = sizeof(uint32); - - channelsize += packetsize * MaxFrames; - channelsize -= sizeof(uint32); - - W3dTimeCodedBitChannelStruct * chn = (W3dTimeCodedBitChannelStruct *)malloc(channelsize); - - if (chn == NULL) { - return false; - } - - chn->NumTimeCodes = MaxFrames; - chn->Pivot = ID; - chn->Flags = ChannelType; - chn->DefaultVal = DefaultVal; - - // copy data into the channel struct, in timecoded raw format - - for (uint32 fcount=0; fcount < chn->NumTimeCodes; fcount++) { - - if (Get_Bit(fcount)) { - chn->Data[fcount] = fcount | W3D_TIMECODED_BIT_MASK; - } - else { - chn->Data[fcount] = fcount; - } - } - - // Compress the new structure - - BitChannelClass::compress( chn ); - - float originalchannelsize = channelsize; - - // Update Channel Size - channelsize = sizeof(W3dTimeCodedBitChannelStruct); - channelsize += packetsize * chn->NumTimeCodes; - channelsize -= sizeof(uint32); - - float percent = (((float) channelsize) / originalchannelsize) * 100.0f; - - ExportLog::printf("%.0f", percent); - - - // save - - if (csave.Write(chn,channelsize) != channelsize) { - return false; - } - - if (chn != NULL) { - free(chn); - } - - if (!csave.End_Chunk()) { - return false; - } - - } - else { - // Stock Raw Save - if (!csave.Begin_Chunk(W3D_CHUNK_BIT_CHANNEL)) { - return false; - } - - compute_range(); - - int numbits = End - Begin + 1; - assert(numbits > 0); - int numbytes = (numbits + 7) / 8; - - unsigned int channelsize = sizeof(W3dBitChannelStruct); - channelsize += numbytes - 1; // one byte inside the W3dBitChannelStruct... - - W3dBitChannelStruct * chn = (W3dBitChannelStruct *)malloc(channelsize); - - if (chn == NULL) { - return false; - } - - chn->FirstFrame = Begin; - chn->LastFrame = End; - chn->Flags = ChannelType; - chn->Pivot = ID; - chn->DefaultVal = DefaultVal; - - uint8 * bits = (uint8 *)&(chn->Data[0]); - - for (int fcount=0; fcount < End-Begin+1; fcount++) { - ::Set_Bit(bits,fcount,Get_Bit(Begin + fcount)); - } - - if (csave.Write(chn,channelsize) != channelsize) { - return false; - } - - if (chn != NULL) { - free(chn); - } - - if (!csave.End_Chunk()) { - return false; - } - - } - - return true; -} - - -bool BitChannelClass::is_default(bool bit) -{ - return (bit == DefaultVal); -} - -void BitChannelClass::compute_range(void) -{ - Begin = 0; - while ((Begin < MaxFrames) && (is_default(Get_Bit(Begin)))) { - Begin++; - } - - End = MaxFrames-1; - while ((End >= 0) && (is_default(Get_Bit(End)))) { - End--; - } -} // compute_range - - -// -// find a packet that isn't needed, and return the index -// if all packets are necessary, then return back PACKETS_ALL_USEFUL -// a useless packet is defined, as a packet that can be recreated -// -#define PACKETS_ALL_USEFUL (0xFFFFFFFF) -// -uint32 BitChannelClass::find_useless_packet(W3dTimeCodedBitChannelStruct * c) -{ - - assert( c ); // make sure pointer exists - assert( c->NumTimeCodes ); // make sure some packets exist - - if (c->NumTimeCodes > 2) { - - for(uint32 try_idx = 0; try_idx < (c->NumTimeCodes - 1); try_idx++) { - - if ((c->Data[try_idx] & W3D_TIMECODED_BIT_MASK) == - (c->Data[try_idx+1] & W3D_TIMECODED_BIT_MASK)) { - return(try_idx + 1); - } - - } // for - } - - return( PACKETS_ALL_USEFUL ); - -} // find_useless_packet - - -// -// Remove a packet from a W3dTimeCodedBitChannelStruct -// -void BitChannelClass::remove_packet(W3dTimeCodedBitChannelStruct * c, uint32 packet_idx) -{ - assert( c ); - assert( c->NumTimeCodes > 1 ); - - uint32 packet_size = 1; - uint32 packet_len = packet_size * sizeof(uint32); - - uint32 *src, *dst; - - dst = (uint32 *) &c->Data[ packet_size * packet_idx ]; - src = (uint32 *) &c->Data[ packet_size * (packet_idx + 1) ]; - - uint32 copy_length = (c->NumTimeCodes - (packet_idx + 1)) * packet_len; - - if (copy_length) { - - memcpy(dst, src, copy_length); - - } - - // Decrement Packet Count - c->NumTimeCodes--; - -} // remove_packet - -// -// Take a non-compressed TimeCoded Bit Channel -// and compress the packets -// -void BitChannelClass::compress(W3dTimeCodedBitChannelStruct * c) -{ - while(1) { - - uint32 idx = find_useless_packet( c ); - - if (PACKETS_ALL_USEFUL == idx) break; - - remove_packet( c, idx ); - - } - -} // compress - - - - -// EOF - bchannel.cpp diff --git a/Generals/Code/Tools/WW3D/max2w3d/bchannel.h b/Generals/Code/Tools/WW3D/max2w3d/bchannel.h deleted file mode 100644 index 88225578c4..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/bchannel.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : W3D Tools * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/bchannel.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 5:25p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef BCHANNEL_H -#define BCHANNEL_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef BITTYPE_H -#include "BITTYPE.H" -#endif - -#ifndef CHUNKIO_H -#include "chunkio.h" -#endif - -#ifndef VECTOR_H -#include "Vector.H" -#endif - -#ifndef W3D_FILE_H -#include "w3d_file.h" -#endif - -class LogDataDialogClass; - -class BitChannelClass -{ -public: - - BitChannelClass(uint32 id,int maxframes,uint32 chntype,bool def_val); - ~BitChannelClass(void); - - void Set_Bit(int framenumber,bool bit); - void Set_Bits(BooleanVectorClass & bits); - bool Get_Bit(int frameidx); - bool Is_Empty(void) { return IsEmpty; } - bool Save(ChunkSaveClass & csave, bool compress); - -private: - - uint32 ID; - uint32 ChannelType; - int MaxFrames; - bool IsEmpty; - - bool DefaultVal; - BooleanVectorClass Data; - int Begin; - int End; - - // Test a bit against the "default" bit - bool is_default(bool bit); - - // This function finds the start and end of the "non-default" data - void compute_range(void); - - // compress functions - void remove_packet(W3dTimeCodedBitChannelStruct * c, uint32 packet_idx); - uint32 find_useless_packet(W3dTimeCodedBitChannelStruct * c); - void compress(W3dTimeCodedBitChannelStruct * c); - - -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/boneicon.cpp b/Generals/Code/Tools/WW3D/max2w3d/boneicon.cpp deleted file mode 100644 index 75e34564b8..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/boneicon.cpp +++ /dev/null @@ -1,606 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/boneicon.cpp 6 1/12/98 4:02p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/boneicon.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/09/98 3:09p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "boneicon.h" - -const int NumBoneIconVerts = 184; -const int NumBoneIconFaces = 366; - -/* -** Don't try this at home :-) -*/ -#pragma warning(disable:4305) - -VertexStruct BoneIconVerts[NumBoneIconVerts] = { - - { 0.07, -0.37, 0.23 }, - { 0.07, -0.38, 0.22 }, - { 0.07, -0.37, 0.22 }, - { -0.07, -0.38, 0.22 }, - { -0.07, -0.38, 0.22 }, - { -0.05, -0.31, 0.21 }, - { -0.07, -0.38, 0.22 }, - { -0.07, -0.37, 0.21 }, - { 0.07, -0.38, 0.22 }, - { 0.06, -0.34, 0.18 }, - { 0.07, -0.38, 0.23 }, - { -0.07, -0.38, 0.22 }, - { -0.10, -0.42, 0.19 }, - { -0.04, -0.47, 0.11 }, - { -0.04, -0.51, 0.21 }, - { -0.04, -0.36, 0.12 }, - { 0.05, -0.41, 0.10 }, - { 0.05, -0.51, 0.15 }, - { 0.05, -0.49, 0.26 }, - { 0.11, -0.42, 0.19 }, - { -0.05, -0.45, 0.26 }, - { -0.06, -0.43, 0.25 }, - { -0.04, -0.45, 0.27 }, - { -0.07, -0.40, 0.23 }, - { 0.00, -0.46, 0.27 }, - { 0.04, -0.45, 0.27 }, - { 0.05, -0.44, 0.27 }, - { -0.00, -0.46, 0.27 }, - { 0.06, -0.43, 0.25 }, - { 0.07, -0.39, 0.24 }, - { -0.11, -0.37, 0.28 }, - { -0.05, -0.47, 0.30 }, - { -0.05, -0.38, 0.37 }, - { -0.05, -0.29, 0.32 }, - { 0.04, -0.44, 0.35 }, - { 0.04, -0.33, 0.36 }, - { 0.04, -0.28, 0.26 }, - { 0.10, -0.37, 0.28 }, - { 0.04, -0.30, 0.23 }, - { 0.04, -0.29, 0.24 }, - { 0.01, -0.29, 0.24 }, - { -0.03, -0.30, 0.25 }, - { -0.05, -0.31, 0.22 }, - { -0.04, -0.35, 0.15 }, - { -0.03, -0.35, 0.13 }, - { -0.02, -0.35, 0.13 }, - { 0.04, -0.36, 0.14 }, - { 0.05, -0.34, 0.16 }, - { -0.05, 0.36, -0.16 }, - { -0.05, 0.36, -0.15 }, - { -0.07, 0.41, -0.22 }, - { 0.05, 0.33, -0.22 }, - { 0.06, 0.35, -0.21 }, - { 0.07, 0.41, -0.22 }, - { 0.04, 0.38, -0.14 }, - { 0.07, 0.40, -0.20 }, - { 0.07, 0.41, -0.21 }, - { 0.04, 0.38, -0.13 }, - { 0.01, 0.38, -0.13 }, - { -0.03, 0.38, -0.13 }, - { -0.07, 0.40, -0.21 }, - { -0.04, 0.33, -0.22 }, - { -0.07, 0.41, -0.22 }, - { -0.03, 0.32, -0.24 }, - { -0.02, 0.32, -0.24 }, - { 0.04, 0.33, -0.24 }, - { -0.10, 0.40, -0.27 }, - { -0.04, 0.36, -0.35 }, - { -0.04, 0.31, -0.25 }, - { -0.04, 0.47, -0.34 }, - { 0.05, 0.41, -0.36 }, - { 0.05, 0.32, -0.31 }, - { 0.05, 0.50, -0.28 }, - { 0.11, 0.40, -0.27 }, - { -0.06, 0.46, -0.24 }, - { -0.07, 0.42, -0.23 }, - { -0.05, 0.48, -0.25 }, - { -0.04, 0.48, -0.25 }, - { 0.00, 0.49, -0.26 }, - { 0.04, 0.48, -0.25 }, - { 0.05, 0.48, -0.25 }, - { -0.00, 0.49, -0.26 }, - { 0.07, 0.43, -0.21 }, - { 0.06, 0.46, -0.24 }, - { -0.11, 0.45, -0.18 }, - { -0.05, 0.44, -0.08 }, - { -0.05, 0.54, -0.14 }, - { -0.05, 0.52, -0.25 }, - { 0.04, 0.39, -0.11 }, - { 0.04, 0.50, -0.10 }, - { 0.04, 0.54, -0.20 }, - { 0.10, 0.45, -0.18 }, - { 0.07, 0.37, 0.22 }, - { 0.07, 0.37, 0.22 }, - { 0.07, 0.37, 0.21 }, - { -0.07, 0.37, 0.22 }, - { -0.07, 0.37, 0.22 }, - { -0.05, 0.33, 0.17 }, - { -0.07, 0.37, 0.22 }, - { -0.07, 0.36, 0.22 }, - { 0.07, 0.37, 0.22 }, - { 0.06, 0.31, 0.21 }, - { 0.07, 0.37, 0.22 }, - { -0.07, 0.37, 0.22 }, - { -0.10, 0.37, 0.27 }, - { -0.04, 0.32, 0.36 }, - { -0.04, 0.43, 0.34 }, - { -0.04, 0.27, 0.25 }, - { 0.05, 0.28, 0.31 }, - { 0.05, 0.38, 0.37 }, - { 0.05, 0.46, 0.29 }, - { 0.11, 0.37, 0.27 }, - { -0.05, 0.44, 0.26 }, - { -0.06, 0.43, 0.25 }, - { -0.04, 0.45, 0.26 }, - { -0.07, 0.39, 0.24 }, - { 0.00, 0.46, 0.26 }, - { 0.04, 0.45, 0.26 }, - { 0.05, 0.44, 0.25 }, - { -0.00, 0.46, 0.27 }, - { 0.06, 0.42, 0.25 }, - { 0.07, 0.40, 0.22 }, - { -0.11, 0.42, 0.19 }, - { -0.05, 0.48, 0.26 }, - { -0.05, 0.50, 0.15 }, - { -0.05, 0.41, 0.09 }, - { 0.04, 0.51, 0.21 }, - { 0.04, 0.46, 0.10 }, - { 0.04, 0.35, 0.12 }, - { 0.10, 0.42, 0.19 }, - { 0.04, 0.35, 0.15 }, - { 0.04, 0.35, 0.14 }, - { 0.01, 0.34, 0.13 }, - { -0.03, 0.35, 0.14 }, - { -0.05, 0.33, 0.16 }, - { -0.04, 0.30, 0.23 }, - { -0.03, 0.28, 0.24 }, - { -0.02, 0.28, 0.24 }, - { 0.04, 0.29, 0.25 }, - { 0.05, 0.30, 0.22 }, - { -0.05, -0.34, -0.21 }, - { -0.05, -0.34, -0.22 }, - { -0.07, -0.41, -0.22 }, - { 0.05, -0.37, -0.16 }, - { 0.06, -0.37, -0.17 }, - { 0.07, -0.41, -0.22 }, - { 0.04, -0.33, -0.23 }, - { 0.07, -0.40, -0.22 }, - { 0.07, -0.41, -0.23 }, - { 0.04, -0.32, -0.24 }, - { 0.01, -0.32, -0.24 }, - { -0.03, -0.33, -0.24 }, - { -0.07, -0.40, -0.21 }, - { -0.04, -0.38, -0.15 }, - { -0.07, -0.41, -0.22 }, - { -0.03, -0.38, -0.13 }, - { -0.02, -0.38, -0.13 }, - { 0.04, -0.39, -0.14 }, - { -0.10, -0.45, -0.19 }, - { -0.04, -0.50, -0.11 }, - { -0.04, -0.39, -0.12 }, - { -0.04, -0.54, -0.21 }, - { 0.05, -0.54, -0.15 }, - { 0.05, -0.44, -0.10 }, - { 0.05, -0.52, -0.26 }, - { 0.11, -0.45, -0.19 }, - { -0.06, -0.46, -0.26 }, - { -0.07, -0.43, -0.23 }, - { -0.05, -0.48, -0.26 }, - { -0.04, -0.48, -0.27 }, - { 0.00, -0.49, -0.27 }, - { 0.04, -0.48, -0.27 }, - { 0.05, -0.47, -0.27 }, - { -0.00, -0.49, -0.27 }, - { 0.07, -0.42, -0.24 }, - { 0.06, -0.46, -0.25 }, - { -0.11, -0.40, -0.28 }, - { -0.05, -0.32, -0.32 }, - { -0.05, -0.41, -0.37 }, - { -0.05, -0.50, -0.30 }, - { 0.04, -0.31, -0.26 }, - { 0.04, -0.35, -0.36 }, - { 0.04, -0.47, -0.35 }, - { 0.10, -0.40, -0.28 } -}; - - -FaceStruct BoneIconFaces[NumBoneIconFaces] = { - - { 0, 1, 2 }, - { 3, 4, 5 }, - { 6, 3, 7 }, - { 1, 8, 9 }, - { 1, 0, 10 }, - { 4, 3, 11 }, - { 11, 3, 6 }, - { 11, 4, 11 }, - { 10, 8, 1 }, - { 12, 13, 14 }, - { 12, 15, 13 }, - { 13, 16, 17 }, - { 14, 17, 18 }, - { 17, 14, 13 }, - { 16, 13, 15 }, - { 19, 18, 17 }, - { 19, 17, 16 }, - { 12, 14, 20 }, - { 21, 12, 20 }, - { 14, 22, 20 }, - { 22, 14, 18 }, - { 12, 21, 23 }, - { 24, 18, 25 }, - { 18, 26, 25 }, - { 26, 18, 19 }, - { 18, 24, 27 }, - { 22, 18, 27 }, - { 26, 19, 28 }, - { 19, 29, 28 }, - { 30, 31, 32 }, - { 30, 32, 33 }, - { 32, 34, 35 }, - { 33, 35, 36 }, - { 34, 32, 31 }, - { 35, 33, 32 }, - { 37, 35, 34 }, - { 37, 36, 35 }, - { 31, 30, 21 }, - { 20, 31, 21 }, - { 31, 20, 22 }, - { 30, 23, 21 }, - { 34, 31, 24 }, - { 25, 34, 24 }, - { 34, 25, 37 }, - { 37, 25, 26 }, - { 31, 27, 24 }, - { 27, 31, 22 }, - { 28, 37, 26 }, - { 37, 28, 29 }, - { 38, 36, 37 }, - { 37, 2, 38 }, - { 2, 37, 29 }, - { 0, 2, 29 }, - { 36, 38, 39 }, - { 33, 36, 40 }, - { 40, 36, 39 }, - { 33, 40, 41 }, - { 33, 42, 30 }, - { 42, 33, 41 }, - { 5, 30, 42 }, - { 23, 30, 4 }, - { 30, 5, 4 }, - { 12, 23, 6 }, - { 7, 12, 6 }, - { 12, 7, 15 }, - { 43, 15, 7 }, - { 15, 43, 44 }, - { 16, 15, 45 }, - { 45, 15, 44 }, - { 16, 45, 46 }, - { 47, 16, 46 }, - { 16, 47, 19 }, - { 9, 19, 47 }, - { 9, 19, 9 }, - { 29, 19, 8 }, - { 19, 9, 8 }, - { 29, 10, 0 }, - { 6, 23, 11 }, - { 11, 23, 11 }, - { 11, 23, 4 }, - { 10, 29, 8 }, - { 48, 3, 49 }, - { 49, 3, 5 }, - { 50, 3, 48 }, - { 3, 50, 7 }, - { 51, 1, 9 }, - { 1, 51, 52 }, - { 53, 1, 52 }, - { 1, 53, 2 }, - { 56, 38, 2 }, - { 38, 54, 39 }, - { 38, 56, 55 }, - { 38, 55, 54 }, - { 2, 53, 56 }, - { 57, 39, 54 }, - { 39, 57, 40 }, - { 40, 58, 41 }, - { 57, 58, 40 }, - { 59, 41, 58 }, - { 41, 59, 42 }, - { 42, 59, 5 }, - { 49, 5, 59 }, - { 7, 50, 43 }, - { 43, 50, 60 }, - { 43, 60, 61 }, - { 43, 61, 44 }, - { 60, 50, 62 }, - { 63, 44, 61 }, - { 44, 63, 45 }, - { 45, 63, 64 }, - { 45, 64, 46 }, - { 65, 46, 64 }, - { 46, 65, 47 }, - { 47, 65, 9 }, - { 51, 9, 65 }, - { 66, 67, 68 }, - { 66, 69, 67 }, - { 67, 70, 71 }, - { 69, 72, 70 }, - { 71, 68, 67 }, - { 70, 67, 69 }, - { 73, 70, 72 }, - { 73, 71, 70 }, - { 74, 66, 75 }, - { 66, 74, 69 }, - { 69, 74, 76 }, - { 77, 69, 76 }, - { 69, 77, 72 }, - { 72, 78, 79 }, - { 80, 72, 79 }, - { 72, 80, 73 }, - { 78, 72, 81 }, - { 72, 77, 81 }, - { 82, 73, 83 }, - { 73, 80, 83 }, - { 84, 85, 86 }, - { 84, 86, 87 }, - { 85, 88, 89 }, - { 86, 89, 90 }, - { 89, 86, 85 }, - { 90, 87, 86 }, - { 91, 89, 88 }, - { 91, 90, 89 }, - { 75, 84, 87 }, - { 75, 87, 74 }, - { 87, 76, 74 }, - { 76, 87, 77 }, - { 87, 90, 78 }, - { 90, 79, 78 }, - { 79, 90, 91 }, - { 79, 91, 80 }, - { 81, 87, 78 }, - { 87, 81, 77 }, - { 91, 83, 80 }, - { 83, 91, 82 }, - { 84, 48, 85 }, - { 49, 85, 48 }, - { 48, 84, 50 }, - { 84, 75, 50 }, - { 51, 71, 73 }, - { 73, 52, 51 }, - { 52, 73, 53 }, - { 73, 82, 53 }, - { 56, 82, 91 }, - { 88, 54, 91 }, - { 91, 54, 55 }, - { 91, 55, 56 }, - { 56, 53, 82 }, - { 54, 88, 57 }, - { 88, 85, 58 }, - { 57, 88, 58 }, - { 58, 85, 59 }, - { 49, 59, 85 }, - { 66, 60, 75 }, - { 68, 60, 66 }, - { 68, 61, 60 }, - { 62, 75, 60 }, - { 75, 62, 50 }, - { 61, 68, 63 }, - { 64, 68, 71 }, - { 68, 64, 63 }, - { 64, 71, 65 }, - { 51, 65, 71 }, - { 92, 93, 94 }, - { 95, 96, 97 }, - { 98, 95, 99 }, - { 93, 100, 101 }, - { 93, 92, 102 }, - { 96, 95, 103 }, - { 103, 95, 98 }, - { 103, 96, 103 }, - { 102, 100, 93 }, - { 104, 105, 106 }, - { 104, 107, 105 }, - { 105, 108, 109 }, - { 106, 109, 110 }, - { 109, 106, 105 }, - { 108, 105, 107 }, - { 111, 110, 109 }, - { 111, 109, 108 }, - { 104, 106, 112 }, - { 113, 104, 112 }, - { 106, 114, 112 }, - { 114, 106, 110 }, - { 104, 113, 115 }, - { 116, 110, 117 }, - { 110, 118, 117 }, - { 118, 110, 111 }, - { 110, 116, 119 }, - { 114, 110, 119 }, - { 118, 111, 120 }, - { 111, 121, 120 }, - { 122, 123, 124 }, - { 122, 124, 125 }, - { 124, 126, 127 }, - { 125, 127, 128 }, - { 126, 124, 123 }, - { 127, 125, 124 }, - { 129, 127, 126 }, - { 129, 128, 127 }, - { 123, 122, 113 }, - { 112, 123, 113 }, - { 123, 112, 114 }, - { 122, 115, 113 }, - { 126, 123, 116 }, - { 117, 126, 116 }, - { 126, 117, 129 }, - { 129, 117, 118 }, - { 123, 119, 116 }, - { 119, 123, 114 }, - { 120, 129, 118 }, - { 129, 120, 121 }, - { 130, 128, 129 }, - { 129, 94, 130 }, - { 94, 129, 121 }, - { 92, 94, 121 }, - { 128, 130, 131 }, - { 125, 128, 132 }, - { 132, 128, 131 }, - { 125, 132, 133 }, - { 125, 134, 122 }, - { 134, 125, 133 }, - { 97, 122, 134 }, - { 115, 122, 96 }, - { 122, 97, 96 }, - { 104, 115, 98 }, - { 99, 104, 98 }, - { 104, 99, 107 }, - { 135, 107, 99 }, - { 107, 135, 136 }, - { 108, 107, 137 }, - { 137, 107, 136 }, - { 108, 137, 138 }, - { 139, 108, 138 }, - { 108, 139, 111 }, - { 101, 111, 139 }, - { 101, 111, 101 }, - { 121, 111, 100 }, - { 111, 101, 100 }, - { 121, 102, 92 }, - { 98, 115, 103 }, - { 103, 115, 103 }, - { 103, 115, 96 }, - { 102, 121, 100 }, - { 140, 95, 141 }, - { 141, 95, 97 }, - { 142, 95, 140 }, - { 95, 142, 99 }, - { 143, 93, 101 }, - { 93, 143, 144 }, - { 145, 93, 144 }, - { 93, 145, 94 }, - { 148, 130, 94 }, - { 130, 146, 131 }, - { 130, 148, 147 }, - { 130, 147, 146 }, - { 94, 145, 148 }, - { 149, 131, 146 }, - { 131, 149, 132 }, - { 132, 150, 133 }, - { 149, 150, 132 }, - { 151, 133, 150 }, - { 133, 151, 134 }, - { 134, 151, 97 }, - { 141, 97, 151 }, - { 99, 142, 135 }, - { 135, 142, 152 }, - { 135, 152, 153 }, - { 135, 153, 136 }, - { 152, 142, 154 }, - { 155, 136, 153 }, - { 136, 155, 137 }, - { 137, 155, 156 }, - { 137, 156, 138 }, - { 157, 138, 156 }, - { 138, 157, 139 }, - { 139, 157, 101 }, - { 143, 101, 157 }, - { 158, 159, 160 }, - { 158, 161, 159 }, - { 159, 162, 163 }, - { 161, 164, 162 }, - { 163, 160, 159 }, - { 162, 159, 161 }, - { 165, 162, 164 }, - { 165, 163, 162 }, - { 166, 158, 167 }, - { 158, 166, 161 }, - { 161, 166, 168 }, - { 169, 161, 168 }, - { 161, 169, 164 }, - { 164, 170, 171 }, - { 172, 164, 171 }, - { 164, 172, 165 }, - { 170, 164, 173 }, - { 164, 169, 173 }, - { 174, 165, 175 }, - { 165, 172, 175 }, - { 176, 177, 178 }, - { 176, 178, 179 }, - { 177, 180, 181 }, - { 178, 181, 182 }, - { 181, 178, 177 }, - { 182, 179, 178 }, - { 183, 181, 180 }, - { 183, 182, 181 }, - { 167, 176, 179 }, - { 167, 179, 166 }, - { 179, 168, 166 }, - { 168, 179, 169 }, - { 179, 182, 170 }, - { 182, 171, 170 }, - { 171, 182, 183 }, - { 171, 183, 172 }, - { 173, 179, 170 }, - { 179, 173, 169 }, - { 183, 175, 172 }, - { 175, 183, 174 }, - { 176, 140, 177 }, - { 141, 177, 140 }, - { 140, 176, 142 }, - { 176, 167, 142 }, - { 143, 163, 165 }, - { 165, 144, 143 }, - { 144, 165, 145 }, - { 165, 174, 145 }, - { 148, 174, 183 }, - { 180, 146, 183 }, - { 183, 146, 147 }, - { 183, 147, 148 }, - { 148, 145, 174 }, - { 146, 180, 149 }, - { 180, 177, 150 }, - { 149, 180, 150 }, - { 150, 177, 151 }, - { 141, 151, 177 }, - { 158, 152, 167 }, - { 160, 152, 158 }, - { 160, 153, 152 }, - { 154, 167, 152 }, - { 167, 154, 142 }, - { 153, 160, 155 }, - { 156, 160, 163 }, - { 160, 156, 155 }, - { 156, 163, 157 }, - { 143, 157, 163 } -}; \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/boneicon.h b/Generals/Code/Tools/WW3D/max2w3d/boneicon.h deleted file mode 100644 index 81d8afbb0b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/boneicon.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/boneicon.h 5 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/boneicon.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/21/97 2:06p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef BONEICON_H -#define BONEICON_H - -struct VertexStruct -{ - float X,Y,Z; -}; - -struct FaceStruct -{ - int V0,V1,V2; -}; - -extern const int NumBoneIconVerts; -extern const int NumBoneIconFaces; -extern VertexStruct BoneIconVerts[]; -extern FaceStruct BoneIconFaces[]; - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/bpick.cpp b/Generals/Code/Tools/WW3D/max2w3d/bpick.cpp deleted file mode 100644 index d1ed8630cd..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/bpick.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/bpick.cpp 7 1/04/01 11:12a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/bpick.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/04/01 11:12a $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * BonePickerClass::Filter -- determine whether the passed node is suitable * - * BonePickerClass::HitTest -- MAX HitTest method * - * BonePickerClass::Pick -- MAX Pick method * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "bpick.h" -#include "dllmain.h" -#include "resource.h" - - -/* -** Global instance of a bone picker :-) -*/ -BonePickerClass TheBonePicker; - - -/*********************************************************************************************** - * BonePickerClass::Filter -- determine whether the passed node is suitable * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -BOOL BonePickerClass::Filter(INode *node) -{ - if (BoneList == NULL) { - ObjectState os = node->EvalWorldState(0); - if (os.obj) { - return TRUE; - } - - } else { - for (int i=0; iCount(); i++) { - if ((*BoneList)[i] == node) return TRUE; - } - } - - return FALSE; -} - -/*********************************************************************************************** - * BonePickerClass::HitTest -- MAX HitTest method * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -BOOL BonePickerClass::HitTest(IObjParam *ip,HWND hwnd,ViewExp *vpt,IPoint2 m,int flags) -{ - if (ip->PickNode(hwnd,m,GetFilter())) { - return TRUE; - } else { - return FALSE; - } -} - -/*********************************************************************************************** - * BonePickerClass::Pick -- MAX Pick method * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -BOOL BonePickerClass::Pick(IObjParam *ip,ViewExp *vpt) -{ - INode *node = vpt->GetClosestHit(); - - if (node) { - - /* - ** Tell the "owning" skin modifier about the - ** bone which was picked. - */ - assert(User); - User->User_Picked_Bone(node); - User = NULL; - BoneList = NULL; - } - - return TRUE; -} - -BOOL BonePickerClass::filter(INode * inode) -{ - return Filter(inode); -} - -void BonePickerClass::proc(INodeTab & nodetab) -{ - assert(User != NULL); - User->User_Picked_Bones(nodetab); - User = NULL; - BoneList = NULL; -} - -TCHAR * BonePickerClass::dialogTitle(void) -{ - return Get_String(IDS_PICK_BONE_DIALOG_TITLE); -} - -TCHAR * BonePickerClass::buttonText(void) -{ - return Get_String(IDS_PICK_BONE_BUTTON_TEXT); -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/bpick.h b/Generals/Code/Tools/WW3D/max2w3d/bpick.h deleted file mode 100644 index ca6078c4a8..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/bpick.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/bpick.h 6 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/bpick.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/21/97 2:05p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef BPICK_H -#define BPICK_H - -#include "max.h" -//#include "dllmain.h" -//#include "resource.h" - - -/* -** To use the Bone picking class, you should inherit from this class -** and implement the User_Picked... functions. -*/ -class BonePickerUserClass -{ -public: - virtual void User_Picked_Bone(INode * node) = 0; - virtual void User_Picked_Bones(INodeTab & nodetab) = 0; -}; - - -/* -** BonePickerClass -** Uses Max's interface to let the user pick bones out of the scene -** or by using a dialog box to pick by name. -*/ -class BonePickerClass : public PickNodeCallback, public PickModeCallback, public HitByNameDlgCallback -{ -public: - - BonePickerClass(void) : User(NULL), BoneList(NULL), SinglePick(FALSE) {} - - /* - ** Tell this class who is using it and optionally the list - ** of bones to allow the user to select from. - ** Call this before giving this class to MAX... - */ - void Set_User(BonePickerUserClass * user,int singlepick = FALSE, INodeTab * bonelist = NULL) { User = user; SinglePick = singlepick; BoneList = bonelist; } - - /* - ** From BonePickNodeCallback: - */ - BOOL Filter(INode *node); - - /* - ** From BonePickModeCallback: - */ - BOOL HitTest(IObjParam *ip,HWND hWnd,ViewExp *vpt,IPoint2 m,int flags); - BOOL Pick(IObjParam *ip,ViewExp *vpt); - - void EnterMode(IObjParam *ip) { } - void ExitMode(IObjParam *ip) { } - - PickNodeCallback * GetFilter() {return this;} - BOOL RightClick(IObjParam *ip,ViewExp *vpt) { return TRUE; } - - /* - ** From HitByNameDlgCallback - */ - virtual TCHAR * dialogTitle(void); - virtual TCHAR * buttonText(void); - virtual BOOL singleSelect(void) { return SinglePick; } - virtual BOOL useFilter(void) { return TRUE; } - virtual BOOL useProc(void) { return TRUE; } - virtual BOOL doCustomHilite(void) { return FALSE; } - virtual BOOL filter(INode * inode); - virtual void proc(INodeTab & nodeTab); - -protected: - - /* - ** The bone picker will pass the bones on to the "user" of - ** the class. - */ - BonePickerUserClass * User; - - /* - ** List of bones that the user is being allowed to pick from. - ** If this is NULL, then the user can pick any bone - */ - INodeTab * BoneList; - - /* - ** Flag for whether to allow multiple selection or not - */ - int SinglePick; -}; - -extern BonePickerClass TheBonePicker; - - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/colboxsave.cpp b/Generals/Code/Tools/WW3D/max2w3d/colboxsave.cpp deleted file mode 100644 index 80b2f8ac1b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/colboxsave.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/colboxsave.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 12/06/00 4:06p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "colboxsave.h" -#include "w3d_file.h" -#include "util.h" -#include "w3dappdata.h" -#include "errclass.h" - - -CollisionBoxSaveClass::CollisionBoxSaveClass -( - char * mesh_name, - char * container_name, - INode * inode, - Matrix3 & exportspace, - TimeValue curtime, - Progress_Meter_Class & meter -) -{ - ////////////////////////////////////////////////////////////////////// - // wrestle the mesh out of 3dsMAX - ////////////////////////////////////////////////////////////////////// - Object * obj = inode->EvalWorldState(curtime).obj; - TriObject * tri = (TriObject *)obj->ConvertToType(curtime, triObjectClassID); - Mesh mesh = tri->mesh; - DWORD wirecolor = inode->GetWireColor(); - - if (mesh.getNumVerts() == 0) { - throw ErrorClass("Mesh %s has no vertices!\n",mesh_name); - } - - ////////////////////////////////////////////////////////////////////// - // Generate the AABox or OBBox data. - ////////////////////////////////////////////////////////////////////// - memset(&BoxData,0,sizeof(BoxData)); - - BoxData.Version = W3D_BOX_CURRENT_VERSION; - if ((container_name != NULL) && (strlen(container_name) > 0)) { - strcpy(BoxData.Name,container_name); - strcat(BoxData.Name,"."); - } - strcat(BoxData.Name,mesh_name); - - BoxData.Attributes = 0; - if (Is_Collision_AABox(inode)) { - BoxData.Attributes |= W3D_BOX_ATTRIBUTE_ALIGNED; - } else { - BoxData.Attributes |= W3D_BOX_ATTRIBUTE_ORIENTED; - } - if (Is_Physical_Collision(inode)) { - BoxData.Attributes |= W3D_BOX_ATTRIBTUE_COLLISION_TYPE_PHYSICAL; - } - if (Is_Projectile_Collision(inode)) { - BoxData.Attributes |= W3D_BOX_ATTRIBTUE_COLLISION_TYPE_PROJECTILE; - } - if (Is_Vis_Collision(inode)) { - BoxData.Attributes |= W3D_BOX_ATTRIBTUE_COLLISION_TYPE_VIS; - } - if (Is_Camera_Collision(inode)) { - BoxData.Attributes |= W3D_BOX_ATTRIBTUE_COLLISION_TYPE_CAMERA; - } - if (Is_Vehicle_Collision(inode)) { - BoxData.Attributes |= W3D_BOX_ATTRIBTUE_COLLISION_TYPE_VEHICLE; - } - - BoxData.Color.R = GetRValue(wirecolor); - BoxData.Color.G = GetGValue(wirecolor); - BoxData.Color.B = GetBValue(wirecolor); - - // if this is an axis-aligned box, then use the world coord system - if (Is_Collision_AABox(inode)) { - exportspace.NoRot(); - } - - // Transform the mesh into the desired coordinate system - Matrix3 node_matrix = inode->GetObjectTM(curtime); - Matrix3 offset_matrix = node_matrix * Inverse(exportspace); - int ivert; - - for (ivert = 0; ivert < mesh.getNumVerts (); ++ivert) { - mesh.verts[ivert] = mesh.verts[ivert] * offset_matrix; - } - - // Find the center and extent of the box. - Point3 min_point = mesh.verts[0]; - Point3 max_point = mesh.verts[1]; - - for (ivert=0; ivert < mesh.getNumVerts(); ++ivert) { - if (mesh.verts[ivert].x < min_point.x) min_point.x = mesh.verts[ivert].x; - if (mesh.verts[ivert].y < min_point.y) min_point.y = mesh.verts[ivert].y; - if (mesh.verts[ivert].z < min_point.z) min_point.z = mesh.verts[ivert].z; - - if (mesh.verts[ivert].x > max_point.x) max_point.x = mesh.verts[ivert].x; - if (mesh.verts[ivert].y > max_point.y) max_point.y = mesh.verts[ivert].y; - if (mesh.verts[ivert].z > max_point.z) max_point.z = mesh.verts[ivert].z; - } - - Point3 center = (max_point + min_point) / 2.0f; - Point3 extent = (max_point - min_point) / 2.0f; - - BoxData.Center.X = center.x; - BoxData.Center.Y = center.y; - BoxData.Center.Z = center.z; - - BoxData.Extent.X = extent.x; - BoxData.Extent.Y = extent.y; - BoxData.Extent.Z = extent.z; -} - - - -int CollisionBoxSaveClass::Write_To_File(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(W3D_CHUNK_BOX); - csave.Write(&BoxData,sizeof(BoxData)); - csave.End_Chunk(); - return 0; -} - - - \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/colboxsave.h b/Generals/Code/Tools/WW3D/max2w3d/colboxsave.h deleted file mode 100644 index a9f05c3ebd..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/colboxsave.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/colboxsave.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/16/99 8:37a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef COLBOXSAVE_H -#define COLBOXSAVE_H - -#include -#include "w3d_file.h" -#include "chunkio.h" -#include "PROGRESS.H" - - -/******************************************************************************************* -** -** CollisionBoxSaveClass - Create an AABox or an OBBox from a Max mesh (typically the -** artist should use a 'box' to generate this. In any case, we're just using the bounding -** box). -** -*******************************************************************************************/ -class CollisionBoxSaveClass -{ -public: - - enum { - EX_UNKNOWN = 0, // exception error codes - EX_CANCEL = 1 - }; - - CollisionBoxSaveClass( char * mesh_name, - char * container_name, - INode * inode, - Matrix3 & exportspace, - TimeValue curtime, - Progress_Meter_Class & meter); - - int Write_To_File(ChunkSaveClass & csave); - -private: - - W3dBoxStruct BoxData; // contains same information as the W3dOBBoxStruct - -}; - - - -#endif //COLBOXSAVE_H \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/dazzlesave.cpp b/Generals/Code/Tools/WW3D/max2w3d/dazzlesave.cpp deleted file mode 100644 index 9f95b876a2..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/dazzlesave.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/dazzlesave.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 9/21/00 4:14p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "dazzlesave.h" -#include "w3d_file.h" -#include "util.h" -#include "w3dappdata.h" -#include "errclass.h" - - -DazzleSaveClass::DazzleSaveClass -( - char * mesh_name, - char * container_name, - INode * inode, - Matrix3 & exportspace, - TimeValue curtime, - Progress_Meter_Class & meter -) -{ - assert(mesh_name != NULL); - assert(container_name != NULL); - - /* - ** Set up the render object name - */ - memset(&W3DName,0,sizeof(W3DName)); - if ((container_name != NULL) && (strlen(container_name) > 0)) { - strcpy(W3DName,container_name); - strcat(W3DName,"."); - } - strcat(W3DName,mesh_name); - - /* - ** Dig the dazzle-type out of the appropriate App-Data chunk on - ** the INode. - */ - W3DDazzleAppDataStruct * dazzle_data = W3DDazzleAppDataStruct::Get_App_Data(inode); - strncpy(DazzleType,dazzle_data->DazzleType,sizeof(DazzleType)); -} - - - -int DazzleSaveClass::Write_To_File(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(W3D_CHUNK_DAZZLE); - - csave.Begin_Chunk(W3D_CHUNK_DAZZLE_NAME); - csave.Write(W3DName,strlen(W3DName) + 1); - csave.End_Chunk(); - - csave.Begin_Chunk(W3D_CHUNK_DAZZLE_TYPENAME); - csave.Write(DazzleType,strlen(DazzleType) + 1); - csave.End_Chunk(); - - csave.End_Chunk(); - return 0; -} - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/dazzlesave.h b/Generals/Code/Tools/WW3D/max2w3d/dazzlesave.h deleted file mode 100644 index 943fb89454..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/dazzlesave.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/dazzlesave.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 9/21/00 4:09p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef DAZZLESAVE_H -#define DAZZLESAVE_H - -#include -#include "w3d_file.h" -#include "chunkio.h" -#include "PROGRESS.H" - - -/******************************************************************************************* -** -** DazzleSaveClass - Create a Dazzle definition from an INode. Basically, we just save -** the transform and the dazzle type that the user has selected. -** -*******************************************************************************************/ -class DazzleSaveClass -{ -public: - - enum { - EX_UNKNOWN = 0, // exception error codes - EX_CANCEL = 1 - }; - - DazzleSaveClass( char * mesh_name, - char * container_name, - INode * inode, - Matrix3 & exportspace, - TimeValue curtime, - Progress_Meter_Class & meter); - - int Write_To_File(ChunkSaveClass & csave); - -private: - - char W3DName[128]; - char DazzleType[128]; - -}; - - - - - - - -#endif //DAZZLESAVE_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/dllmain.cpp b/Generals/Code/Tools/WW3D/max2w3d/dllmain.cpp deleted file mode 100644 index e992552b21..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/dllmain.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/dllmain.cpp 8 7/24/01 5:11p Moumine_ballo $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : DLLMAIN.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/09/97 * - * * - * Last Update : June 9, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * DllMain -- Entry point for the dll * - * LibDescription -- Returns description of this library * - * LibNumberClasses -- Returns number of classes in this library * - * LibClassDesc -- Returns a ClassDesc for the specified class * - * LibVersion -- Returns the version number of this library * - * GetString -- Gets a string out of the resources * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include -#include -#include "dllmain.h" -#include "w3ddesc.h" -#include "w3dexp.h" -#include "w3dutil.h" -#include "skin.h" -#include "gamemtl.h" -#include "gamemaps.h" -#include "MeshDeform.h" -#include "AlphaModifier.h" -#include "gridsnapmodifier.h" - -#include "resource.h" - -#define DLLEXPORT __declspec(dllexport) - - -/***************************************************************************** -* Globals -*****************************************************************************/ - -HINSTANCE AppInstance = NULL; -static int ControlsInit = FALSE; -static W3dClassDesc W3d_Export_Class_Descriptor; - - - -/*********************************************************************************************** - * DllMain -- Entry point for the dll * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -BOOL WINAPI DllMain(HINSTANCE hinstDLL,ULONG /*fdwReason*/,LPVOID /*lpvReserved*/) -{ - AppInstance = hinstDLL; - - if ( !ControlsInit ) - { - ControlsInit = TRUE; - InitCustomControls(AppInstance); - InitCommonControls(); - } - - return TRUE; -} - - -/*********************************************************************************************** - * LibDescription -- Returns description of this library * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -DLLEXPORT const TCHAR * LibDescription() -{ - return Get_String(IDS_LIB_DESCRIPTION); -} - -/*********************************************************************************************** - * LibNumberClasses -- Returns number of classes in this library * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -DLLEXPORT int LibNumberClasses() -{ - return 9; //Moumine 7/24/2001 4:38:27 PM was 10. Removed Mesh_Deformation(#6) -} - - -/*********************************************************************************************** - * LibClassDesc -- Returns a ClassDesc for the specified class * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -DLLEXPORT ClassDesc * LibClassDesc(int i) -{ - switch(i) - { - case 0: return & W3d_Export_Class_Descriptor; break; - case 1: return Get_W3D_Utility_Desc(); break; - case 2: return Get_Skin_Obj_Desc(); break; - case 3: return Get_Skin_Mod_Desc(); break; - case 4: return Get_Game_Material_Desc(); break; - case 5: return Get_Game_Maps_Desc(); break; - case 6: return Get_PS2_Game_Material_Desc(); break; - case 7: return Get_PS2_Material_Conversion(); break; - case 8: return Get_Alpha_Desc(); break; - //case 6: return Get_Mesh_Deform_Desc(); break; - //Moumine 7/24/2001 4:33:52 PM Removed #6 and shifted up instead of returning NULL - // NULL causes a crash in "File->Summary info->Plug-in ifo..." - default: return NULL; break; - } -} - - -/*********************************************************************************************** - * LibVersion -- Returns the version number of this library * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -DLLEXPORT ULONG LibVersion() -{ - return VERSION_3DSMAX; -} - - -/*********************************************************************************************** - * Get_String -- Gets a string out of the resources * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -TCHAR * Get_String( int id ) -{ - static TCHAR buf[256]; - if (AppInstance) - return LoadString(AppInstance, id, buf, sizeof(buf)) ? buf : NULL; - return NULL; -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/dllmain.h b/Generals/Code/Tools/WW3D/max2w3d/dllmain.h deleted file mode 100644 index fd94fdefe0..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/dllmain.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/dllmain.h 4 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : DLLMAIN.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/09/97 * - * * - * Last Update : June 9, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef DLLMAIN_H -#define DLLMAIN_H - -#include - -extern HINSTANCE AppInstance; - -#define MAX_STRING_LENGTH 256 -#define MAX_PATH_LENGTH _MAX_PATH - -TCHAR * Get_String(int id); - -#endif /*DLLMAIN_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/exportlog.cpp b/Generals/Code/Tools/WW3D/max2w3d/exportlog.cpp deleted file mode 100644 index 6c90bda55b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/exportlog.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/exportlog.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 3:16p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * ExportLog::Init -- Initialize the export logging system * - * ExportLog::Shutdown -- Shutdown the export logging system * - * ExportLog::printf -- Print a string to the log window * - * ExportLog::rprintf -- Print a string over the last line printed * - * ExportLog::updatebar -- Set the position of the progress bar * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "exportlog.h" -#include "logdlg.h" -#include - - -/* -** Static variables -*/ -LogDataDialogClass * _LogDialog = NULL; - - -/* -** -** ExportLog implementation. Note, this is a class which only contains static functions. -** -*/ - - -/*********************************************************************************************** - * ExportLog::Init -- Initialize the export logging system * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/30/2000 gth : Created. * - *=============================================================================================*/ -void ExportLog::Init(HWND parent) -{ - assert(_LogDialog == NULL); - _LogDialog = new LogDataDialogClass(parent); -} - - -/*********************************************************************************************** - * ExportLog::Shutdown -- Shutdown the export logging system * - * * - * INPUT: * - * wait_for_ok - should we wait for the user to press OK on the dialog? * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/30/2000 gth : Created. * - *=============================================================================================*/ -void ExportLog::Shutdown(bool wait_for_ok) -{ - if (_LogDialog != NULL) { - - if (wait_for_ok) { - _LogDialog->Wait_OK(); - } - - delete _LogDialog; - _LogDialog = NULL; - } -} - - -/*********************************************************************************************** - * ExportLog::printf -- Print a string to the log window * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/30/2000 gth : Created. * - *=============================================================================================*/ -void ExportLog::printf(const char * format, ...) -{ - if (_LogDialog != NULL) { - va_list arguments; - va_start(arguments, format); - _LogDialog->printf(format,arguments); - } -} - - -/*********************************************************************************************** - * ExportLog::rprintf -- Print a string over the last line printed * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/30/2000 gth : Created. * - *=============================================================================================*/ -void ExportLog::rprintf(const char * format, ...) -{ - if (_LogDialog != NULL) { - va_list arguments; - va_start(arguments, format); - _LogDialog->rprintf(format,arguments); - } -} - - -/*********************************************************************************************** - * ExportLog::updatebar -- Set the position of the progress bar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/30/2000 gth : Created. * - *=============================================================================================*/ -void ExportLog::updatebar(float position, float total) -{ - if (_LogDialog != NULL) { - _LogDialog->updatebar(position,total); - } -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/exportlog.h b/Generals/Code/Tools/WW3D/max2w3d/exportlog.h deleted file mode 100644 index 4c9e8797c5..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/exportlog.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/exportlog.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 3:18p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef EXPORTLOG_H -#define EXPORTLOG_H - -#include - -/** -** ExportLog -** This is an interface to the export log dialog. -*/ -class ExportLog -{ -public: - static void Init(HWND parent); - static void Shutdown(bool wait_for_ok); - - static void printf(const char *, ...); - static void rprintf(const char *, ...); - static void updatebar(float position, float total); -}; - - -#endif //EXPORTLOG_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/floaterdialog.cpp b/Generals/Code/Tools/WW3D/max2w3d/floaterdialog.cpp deleted file mode 100644 index dd0518116b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/floaterdialog.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/floaterdialog.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 2:58p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * FloaterDialogClass::FloaterDialogClass -- Constructor * - * FloaterDialogClass::~FloaterDialogClass -- Destructor * - * FloaterDialogClass::Is_Created -- test whether the floater has already been created * - * FloaterDialogClass::Create -- create the window * - * FloaterDialogClass::Dialog_Proc -- Dialog Proc for the floater * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "floaterdialog.h" -#include "dllmain.h" -#include "resource.h" -#include - - -/********************************************************************************************** -** -** FloaterDialogClass Implementation -** -**********************************************************************************************/ - -BOOL CALLBACK _floater_dialog_proc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - if (message == WM_INITDIALOG) { - FloaterDialogClass * floater = (FloaterDialogClass *)lParam; - ::SetProp(hwnd,"FloaterDialogClass",(HANDLE)floater); - } - - FloaterDialogClass * floater = (FloaterDialogClass *)::GetProp(hwnd,"FloaterDialogClass"); - - if (message == WM_DESTROY) { - ::RemoveProp(hwnd,"FloaterDialogClass"); - } - - - if (floater) { - return floater->Dialog_Proc(hwnd,message,wParam,lParam); - } else { - return FALSE; - } -} - - -/*********************************************************************************************** - * FloaterDialogClass::FloaterDialogClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -FloaterDialogClass::FloaterDialogClass(void) : - Hwnd(NULL), - ChildDialogTemplateID(-1), - ChildDialogProc(NULL) -{ -} - - -/*********************************************************************************************** - * FloaterDialogClass::~FloaterDialogClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -FloaterDialogClass::~FloaterDialogClass(void) -{ - if (Hwnd != NULL) { - ::DestroyWindow(Hwnd); - } -} - - -/*********************************************************************************************** - * FloaterDialogClass::Is_Created -- test whether the floater has already been created * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/11/2000 gth : Created. * - *=============================================================================================*/ -bool FloaterDialogClass::Is_Created(void) -{ - return (Hwnd != NULL); -} - - -/*********************************************************************************************** - * FloaterDialogClass::Create -- create the window * - * * - * This function will return automatically if the floater has been created already. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/11/2000 gth : Created. * - *=============================================================================================*/ -void FloaterDialogClass::Create(Interface * ip, int child_dlg_id, DLGPROC child_dlg_proc) -{ - /* - ** Don't create multiple ones - */ - if (Is_Created()) { - return; - } - - /* - ** Copy down the data needed to create the child window later - */ - ChildDialogTemplateID = child_dlg_id; - ChildDialogProc = child_dlg_proc; - - - /* - ** Create the dialog box - */ - Hwnd = CreateDialogParam( - AppInstance, - MAKEINTRESOURCE(IDD_W3DUTILITY_FLOATER_DIALOG), - ::GetCOREInterface()->GetMAXHWnd(), - (DLGPROC) _floater_dialog_proc, - (LPARAM) this - ); - ::GetCOREInterface()->RegisterDlgWnd(Hwnd); -} - - - -/*********************************************************************************************** - * FloaterDialogClass::Dialog_Proc -- Dialog Proc for the floater * - * * - * The only thing we need to do here is to create the child dialog and resize ourselves to * - * contain it. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/11/2000 gth : Created. * - *=============================================================================================*/ -bool FloaterDialogClass::Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM) -{ - switch (message ) { - - case WM_INITDIALOG: - { - HWND childhwnd = CreateDialogParam( - AppInstance, - MAKEINTRESOURCE(ChildDialogTemplateID), - hWnd, - ChildDialogProc, - 0 - ); - if (childhwnd!= NULL) { - RECT rect; - LONG style = ::GetWindowLong(hWnd,GWL_STYLE); - ::GetWindowRect(childhwnd,&rect); - ::AdjustWindowRect(&rect,style,FALSE); - ::SetWindowPos(hWnd,NULL,0,0,rect.right - rect.left,rect.bottom - rect.top,SWP_NOZORDER|SWP_NOMOVE); - ::SetWindowPos(childhwnd,NULL,0,0,0,0,SWP_NOZORDER|SWP_NOSIZE|SWP_SHOWWINDOW); - } - } - return 1; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDCANCEL: - DestroyWindow(Hwnd); - break; - } - return 1; - - case WM_DESTROY: - ::GetCOREInterface()->UnRegisterDlgWnd(Hwnd); - Hwnd = NULL; - break; - } - return 0; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/floaterdialog.h b/Generals/Code/Tools/WW3D/max2w3d/floaterdialog.h deleted file mode 100644 index 6d7a94d883..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/floaterdialog.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/floaterdialog.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/11/00 11:23a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef FLOATERDIALOG_H -#define FLOATERDIALOG_H - -#include - -class Interface; - -/** -** FloaterDialogClass -** This class is designed to be used by modeless dialog boxes. See w3dutil.cpp for an -** example of how to embed an arbitrary dialog template and dialog proc into a floating -** window. -*/ -class FloaterDialogClass -{ -public: - - FloaterDialogClass(void); - ~FloaterDialogClass(); - - bool Is_Created(void); - void Create(Interface * ip, int child_dialog_id, DLGPROC child_dlg_proc); - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - -private: - - HWND Hwnd; - int ChildDialogTemplateID; - DLGPROC ChildDialogProc; - -}; - - - -#endif //FLOATERDIALOG_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/gamemaps.cpp b/Generals/Code/Tools/WW3D/max2w3d/gamemaps.cpp deleted file mode 100644 index de0aed7a34..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gamemaps.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/gamemaps.cpp 5 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : GAMEMAPS.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/26/97 * - * * - * Last Update : June 26, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMapsClass::ClassID -- Returns the ClassID for GameMapsClass * - * GameMapsClass::AssignController -- Assigns a controller to one of the Sub-Anims * - * GameMapsClass::NotifyRefChanged -- Max is notifying GameMapsClass that a reference has cha* - * GameMapsClass::Clone -- Create a clone of the GameMapsClass * - * GameMapsClass::Save -- Saves the GameMapsClass data into a MAX file * - * GameMapsClass::Load -- Loads GameMapsClass data from a MAX file * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "gamemaps.h" - - -/***************************************************************** -* -* Chunk ID's for saving data in the MAX file. -* -*****************************************************************/ -#define GAMEMAPS_ONOFF_CHUNK 0x0000 -#define GAMEMAPS_AMT0_CHUNK 0x0001 -#define GAMEMAPS_AMT1_CHUNK 0x0002 -#define GAMEMAPS_AMT2_CHUNK 0x0003 -#define GAMEMAPS_AMT3_CHUNK 0x0004 -#define GAMEMAPS_AMT4_CHUNK 0x0005 -#define GAMEMAPS_AMT5_CHUNK 0x0006 -#define GAMEMAPS_AMT6_CHUNK 0x0007 -#define GAMEMAPS_AMT7_CHUNK 0x0008 -#define GAMEMAPS_AMT8_CHUNK 0x0009 -#define GAMEMAPS_AMT9_CHUNK 0x000A -#define GAMEMAPS_AMTA_CHUNK 0x000B - - -/***************************************************************** -* -* A PostLoadCallback which does nothing... -* -*****************************************************************/ -class GameMapsPostLoad : public PostLoadCallback -{ -public: - GameMapsClass *tm; - GameMapsPostLoad(GameMapsClass *b) {tm=b;} - void proc(ILoad *iload) { delete this; } -}; - - -/***************************************************************** -* -* GameMapsClass Class Desriptor -* -*****************************************************************/ -static Class_ID _GameMapsClassID(0x36d23f7b, 0x79ce63e1); - -class GameMapsClassDesc : public ClassDesc -{ - public: - int IsPublic() { return 0; } - void * Create(BOOL loading) { return new GameMapsClass(NULL); } - const TCHAR * ClassName() { return _T("GameMaps"); } - SClass_ID SuperClassID() { return REF_MAKER_CLASS_ID; } - Class_ID ClassID() { return _GameMapsClassID; } - const TCHAR* Category() { return _T(""); } -}; - -static GameMapsClassDesc _GameMapsCD; - -ClassDesc * Get_Game_Maps_Desc() { return &_GameMapsCD; } - - -/*********************************************************************************************** - * GameMapsClass::ClassID -- Returns the ClassID for GameMapsClass * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -Class_ID GameMapsClass::ClassID() -{ - return _GameMapsClassID; -} - -/*********************************************************************************************** - * GameMapsClass::AssignController -- Assigns a controller to one of the Sub-Anims * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -BOOL GameMapsClass::AssignController(Animatable *control,int subAnim) -{ - ReplaceReference(SubNumToRefNum(subAnim),(ReferenceTarget *)control); - return TRUE; -} - -/*********************************************************************************************** - * GameMapsClass::NotifyRefChanged -- Max is notifying GameMapsClass that a reference has chan * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -RefResult GameMapsClass::NotifyRefChanged -( - Interval changeInt, - RefTargetHandle hTarget, - PartID & partID, - RefMessage message -) -{ - switch (message) { - case REFMSG_GET_PARAM_DIM: { - GetParamDim *gpd = (GetParamDim*)partID; - break; - } - case REFMSG_GET_PARAM_NAME: { - GetParamName *gpn = (GetParamName*)partID; - return REF_STOP; - } - } - return(REF_SUCCEED); -} - -/*********************************************************************************************** - * GameMapsClass::Clone -- Create a clone of the GameMapsClass * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -RefTargetHandle GameMapsClass::Clone(RemapDir &remap) -{ - GameMapsClass *tm = new GameMapsClass(NULL); - - for (int i=0; iTextureSlot[i].MapOn = TextureSlot[i].MapOn; - tm->TextureSlot[i].Map = NULL; - - if (TextureSlot[i].Map) { - tm->ReplaceReference(i,remap.CloneRef(TextureSlot[i].Map)); - } - } - - return tm; -} - - -/*********************************************************************************************** - * GameMapsClass::Save -- Saves the GameMapsClass data into a MAX file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -IOResult GameMapsClass::Save(ISave * isave) -{ - ULONG nb,f=0; - - isave->BeginChunk(GAMEMAPS_ONOFF_CHUNK); - for (int i=0; iWrite(&f,sizeof(f),&nb); - isave->EndChunk(); - - for (i=0; iBeginChunk(GAMEMAPS_AMT0_CHUNK + i); - isave->Write(&(TextureSlot[i].Amount),sizeof(float),&nb); - isave->EndChunk(); - } - } - return IO_OK; -} - - -/*********************************************************************************************** - * GameMapsClass::Load -- Loads GameMapsClass data from a MAX file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -IOResult GameMapsClass::Load(ILoad * iload) -{ - ULONG nb; - int id; - IOResult res; - - while (IO_OK==(res=iload->OpenChunk())) { - - switch (id = iload->CurChunkID()) { - case GAMEMAPS_ONOFF_CHUNK: - { - ULONG f; - res = iload->Read(&f,sizeof(f), &nb); - for (int i=0; iRead(&(TextureSlot[index].Amount),sizeof(float),&nb); - break; - } - - iload->CloseChunk(); - if (res!=IO_OK) { - return res; - } - } - return IO_OK; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/gamemaps.h b/Generals/Code/Tools/WW3D/max2w3d/gamemaps.h deleted file mode 100644 index 983377e87d..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gamemaps.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/gamemaps.h 7 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : GAMEMAPS.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/26/97 * - * * - * Last Update : June 26, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef GAMEMAPS_H -#define GAMEMAPS_H - -#include -#include "stdmat.h" - - -ClassDesc * Get_Game_Maps_Desc(); - - -/////////////////////////////////////////////////////////////////////////// -// -// TexmapSlotClass -// -/////////////////////////////////////////////////////////////////////////// -class TexmapSlotClass -{ -public: - - BOOL MapOn; - float Amount; - Texmap * Map; - - TexmapSlotClass() : MapOn(FALSE), Amount(1.0f), Map(NULL) {}; - - RGBA Eval(ShadeContext& sc) { return Map->EvalColor(sc); } - float EvalMono(ShadeContext& sc) { return Map->EvalMono(sc); } - Point3 EvalNormalPerturb(ShadeContext &sc) { return Map->EvalNormalPerturb(sc); } - BOOL IsActive() { return (Map && MapOn); } - void Update(TimeValue t, Interval &ivalid) { if (IsActive()) Map->Update(t,ivalid); }; - float GetAmount(TimeValue t) { return Amount; } -}; - - -/////////////////////////////////////////////////////////////////////////// -// -// Texture Maps for In-Game material -// -// This class can contain a collection of all of the maps which -// MAX uses but the GameMtl plugin will only give the user access -// to the ones we can actually use in the game. -// -/////////////////////////////////////////////////////////////////////////// -class GameMapsClass: public ReferenceTarget -{ -public: - - MtlBase * Client; - TexmapSlotClass TextureSlot[NTEXMAPS]; - - GameMapsClass() { Client = NULL; } - GameMapsClass(MtlBase *mb) { Client = mb; } - - void DeleteThis() { delete this; } - void SetClientPtr(MtlBase *mb) { Client = mb; } - TexmapSlotClass & operator[](int i) { return TextureSlot[i]; } - Class_ID ClassID(); - SClass_ID SuperClassID() { return REF_MAKER_CLASS_ID; } - int NumSubs() { return NTEXMAPS; } - Animatable * SubAnim(int i) { return TextureSlot[i].Map; } - TSTR SubAnimName(int i) { return Client->GetSubTexmapTVName(i); } - int NumRefs() { return NTEXMAPS; } - RefTargetHandle GetReference(int i) { return TextureSlot[i].Map; } - void SetReference(int i, RefTargetHandle rtarg) { TextureSlot[i].Map = (Texmap*)rtarg; } - int SubNumToRefNum(int subNum) { return subNum; } - - - BOOL AssignController(Animatable *control,int subAnim); - RefTargetHandle Clone(RemapDir &remap); - RefResult NotifyRefChanged( Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); - - IOResult Save(ISave * isave); - IOResult Load(ILoad * iload); -}; - - -#endif /*GAMEMAPS_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/gamemtl.h b/Generals/Code/Tools/WW3D/max2w3d/gamemtl.h deleted file mode 100644 index 8c96c984e0..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gamemtl.h +++ /dev/null @@ -1,373 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/gamemtl.h 38 8/22/01 7:56a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : GAMEMTL.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/26/97 * - * * - * Last Update : June 26, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef GAMEMTL_H -#define GAMEMTL_H - -#include -#include "w3dmtl.h" -#include "w3d_file.h" - - -// GameMtl flags values -#define GAMEMTL_CONVERTED_TO_NOLOD (1<<0) // this material has been converted to use the NO_LOD flag on textures - -#define GAMEMTL_DISPLACEMENT_ROLLUP_OPEN (1<<25) -#define GAMEMTL_SURFACE_ROLLUP_OPEN (1<<26) -#define GAMEMTL_PASSCOUNT_ROLLUP_OPEN (1<<27) -#define GAMEMTL_PASS0_ROLLUP_OPEN (1<<28) -#define GAMEMTL_PASS1_ROLLUP_OPEN (1<<29) -#define GAMEMTL_PASS2_ROLLUP_OPEN (1<<30) -#define GAMEMTL_PASS3_ROLLUP_OPEN (1<<31) - -#define GAMEMTL_ROLLUP_FLAGS ( GAMEMTL_SURFACE_ROLLUP_OPEN | \ - GAMEMTL_DISPLACEMENT_ROLLUP_OPEN | \ - GAMEMTL_PASSCOUNT_ROLLUP_OPEN | \ - GAMEMTL_PASS0_ROLLUP_OPEN | \ - GAMEMTL_PASS1_ROLLUP_OPEN | \ - GAMEMTL_PASS2_ROLLUP_OPEN | \ - GAMEMTL_PASS3_ROLLUP_OPEN ) - -#define GAMEMTL_ID_PARTA 0x29397211 -#define GAMEMTL_ID_PARTB 0x28c016c2 - -/////////////////////////////////////////////////////////////////////////// -// -// Mapping types -// -/////////////////////////////////////////////////////////////////////////// -#define GAMEMTL_MAPPING_UV 0 -#define GAMEMTL_MAPPING_ENV 1 -#define GAMEMTL_MAPPING_CHEAP_ENV 2 -#define GAMEMTL_MAPPING_SCREEN 3 -#define GAMEMTL_MAPPING_LINEAR_OFFSET 4 -#define GAMEMTL_MAPPING_SILHOUETTE 5 -#define GAMEMTL_MAPPING_SCALE 6 -#define GAMEMTL_MAPPING_GRID 7 -#define GAMEMTL_MAPPING_ROTATE 8 -#define GAMEMTL_MAPPING_SINE_LINEAR_OFFSET 9 -#define GAMEMTL_MAPPING_STEP_LINEAR_OFFSET 10 -#define GAMEMTL_MAPPING_ZIGZAG_LINEAR_OFFSET 11 -#define GAMEMTL_MAPPING_WS_CLASSIC_ENV 12 -#define GAMEMTL_MAPPING_WS_ENVIRONMENT 13 -#define GAMEMTL_MAPPING_GRID_CLASSIC_ENV 14 -#define GAMEMTL_MAPPING_GRID_ENVIRONMENT 15 -#define GAMEMTL_MAPPING_RANDOM 16 -#define GAMEMTL_MAPPING_EDGE 17 -#define GAMEMTL_MAPPING_BUMPENV 18 - - -/////////////////////////////////////////////////////////////////////////// -// -// PSX Translucency Type -// -/////////////////////////////////////////////////////////////////////////// -#define GAMEMTL_PSX_TRANS_NONE 0 -#define GAMEMTL_PSX_TRANS_100 1 -#define GAMEMTL_PSX_TRANS_50 2 -#define GAMEMTL_PSX_TRANS_25 3 -#define GAMEMTL_PSX_TRANS_MINUS_100 4 - -class GameMtlDlg; -class GameMapsClass; - -extern Class_ID GameMaterialClassID; -extern ClassDesc * Get_Game_Material_Desc(); - -// MLL -// For Playstation 2 materials. -extern Class_ID PS2GameMaterialClassID; -extern ClassDesc * Get_PS2_Game_Material_Desc(); - -extern Class_ID PCToPS2MaterialClassID; -extern ClassDesc * Get_PS2_Material_Conversion(); - -/////////////////////////////////////////////////////////////////////////// -// -// Game Material -// This is a plugin-material which attempts to emulate the material -// used in our in-game 3D engine. It has varying degrees of success -// at making Max render things like our game but it gives us the -// ability to have control over all parameters in our material. -// -/////////////////////////////////////////////////////////////////////////// -class GameMtl: public Mtl -{ - -public: - - enum ShaderTypeEnum - { - STE_PC_SHADER, - STE_PS2_SHADER, - }; - - GameMtl(BOOL loading = FALSE); - ~GameMtl(void); - - Class_ID ClassID(); - SClass_ID SuperClassID(); - - // From Animatable - void GetClassName(TSTR& s); - void DeleteThis() { delete this; } - int NumSubs(); - Animatable * SubAnim(int i); - TSTR SubAnimName(int i); - - // References - int NumRefs() { return REF_COUNT; } - RefTargetHandle Clone(RemapDir &remap = NoRemap()); - RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); - void SetReference(int i, RefTargetHandle rtarg); - RefTargetHandle GetReference(int i); - - // From MtlBase and Mtl - void SetAmbient(Color c, TimeValue t) { Set_Ambient(0,t,c); } - void SetDiffuse(Color c, TimeValue t) { Set_Diffuse(0,t,c); } - void SetSpecular(Color c, TimeValue t) { Set_Specular(0,t,c); } - void SetShininess(float v, TimeValue t) { Set_Shininess(0,t,v); } - Color GetAmbient(int mtlNum=0, BOOL backFace=FALSE) { return Get_Ambient(0,0); } - Color GetDiffuse(int mtlNum=0, BOOL backFace=FALSE) { return Get_Diffuse(0,0); } - Color GetSpecular(int mtlNum=0, BOOL backFace=FALSE) { return Get_Specular(0,0); } - float GetXParency(int mtlNum=0, BOOL backFace=FALSE) { return 0.0f; } - float GetShininess(int mtlNum=0, BOOL backFace=FALSE) { return Get_Shininess(0,0); } - float GetShinStr(int mtlNum=0, BOOL backFace=FALSE) { return 1.0f; } - void Reset(void); - void Update(TimeValue t, Interval& validr); - Interval Validity(TimeValue t); - - int NumSubTexmaps(void); - void SetSubTexmap(int i, Texmap * m); - Texmap * GetSubTexmap(int i); - - float EvalDisplacement(ShadeContext& sc); - Interval DisplacementValidity(TimeValue t); - - // Rendering - void Shade(ShadeContext& sc); - ULONG Requirements(int subMtlNum); - //ULONG LocalRequirements(int subMtlNum); - - // Material editor - void SetParamDlg(GameMtlDlg * pd) { MaterialDialog = pd; } - ParamDlg* CreateParamDlg(HWND hwMtlEdit, IMtlParams *imp); - - // IO stuff - IOResult Save(ISave* iSave); - IOResult Load(ILoad* iLoad); - - // Accessors... - void Set_Flag(ULONG f, ULONG val) { if (val) Flags|=f; else Flags &= ~f; } - int Get_Flag(ULONG f) { return ((Flags&f) ? 1 : 0); } - - void Set_Surface_Type(unsigned int type) { SurfaceType = type; } - unsigned int Get_Surface_Type(void) const { return SurfaceType; } - - void Set_Sort_Level(int level) { SortLevel = level; } - int Get_Sort_Level(void) const { return SortLevel; } - - void Set_Pass_Count(int passcount); - int Get_Pass_Count(void); - - IParamBlock * Get_Parameter_Block(int pass); - int Get_Current_Page(int pass) { return CurPage[pass]; } - Color Get_Ambient(int pass,TimeValue t); - Color Get_Diffuse(int pass,TimeValue t); - Color Get_Specular(int pass,TimeValue t); - Color Get_Emissive(int pass,TimeValue t); - float Get_Shininess(int pass,TimeValue t); - float Get_Opacity(int pass,TimeValue t); - float Get_Translucency(int pass,TimeValue t); - int Get_Copy_Specular_To_Diffuse(int pass); - int Get_Mapping_Type(int pass, int stage=0); - int Get_PSX_Translucency(int pass); - int Get_PSX_Lighting(int pass); - - int Get_Depth_Compare(int pass); - int Get_Depth_Mask(int pass); - int Get_Alpha_Test(int pass); - int Get_Dest_Blend(int pass); - int Get_Pri_Gradient(int pass); - int Get_Sec_Gradient(int pass); - int Get_Src_Blend(int pass); - int Get_Detail_Color_Func(int pass); - int Get_Detail_Alpha_Func(int pass); - int Get_PS2_Shader_Param_A(int pass); - int Get_PS2_Shader_Param_B(int pass); - int Get_PS2_Shader_Param_C(int pass); - int Get_PS2_Shader_Param_D(int pass); - - int Get_Texture_Enable(int pass,int stage); - int Get_Texture_Publish(int pass,int stage); - int Get_Texture_Resize(int pass,int stage); // NOTE: obsolete, replaced by Get_Texture_No_LOD - int Get_Texture_No_Mipmap(int pass,int stage); // NOTE: obsolete, replaced by Get_Texture_No_LOD - int Get_Texture_Clamp_U(int pass,int stage); - int Get_Texture_Clamp_V(int pass,int stage); - int Get_Texture_No_LOD(int pass,int stage); - int Get_Texture_Alpha_Bitmap(int pass,int stage); - int Get_Texture_Hint(int pass,int stage); - int Get_Texture_Display(int pass,int stage); - float Get_Texture_Frame_Rate(int pass,int stage); - int Get_Texture_Frame_Count(int pass,int stage); - int Get_Texture_Anim_Type(int pass,int stage); - Texmap * Get_Texture(int pass,int stage); - Texmap * Get_Displacement_Map(void) const { return DisplacementMap; } - float Get_Displacement_Amount(void) const { return DisplacementAmt; } - int Get_Displacement_Map_Index(void) const; - int Get_Map_Channel(int pass,int stage); - - void Set_Current_Page(int pass,int page) { CurPage[pass] = page; } - void Set_Ambient(int pass,TimeValue t,Color color); - void Set_Diffuse(int pass,TimeValue t,Color color); - void Set_Specular(int pass,TimeValue t,Color color); - void Set_Emissive(int pass,TimeValue t,Color color); - void Set_Shininess(int pass,TimeValue t,float val); - void Set_Opacity(int pass,TimeValue t,float val); - void Set_Translucency(int pass,TimeValue t,float val); - void Set_Copy_Specular_To_Diffuse(int pass,bool val); - void Set_Mapping_Type(int pass,int stage,int val); - void Set_PSX_Translucency(int pass,int val); - void Set_PSX_Lighting(int pass,bool val); - - void Set_Depth_Compare(int pass,int val); - void Set_Depth_Mask(int pass,int val); - void Set_Alpha_Test(int pass,int val); - void Set_Dest_Blend(int pass,int val); - void Set_Pri_Gradient(int pass,int val); - void Set_Sec_Gradient(int pass,int val); - void Set_Src_Blend(int pass,int val); - void Set_Detail_Color_Func(int pass,int val); - void Set_Detail_Alpha_Func(int pass,int val); - void Set_PS2_Shader_Param_A(int pass,int val); - void Set_PS2_Shader_Param_B(int pass,int val); - void Set_PS2_Shader_Param_C(int pass,int val); - void Set_PS2_Shader_Param_D(int pass,int val); - - void Set_Texture_Enable(int pass,int stage,bool val); - void Set_Texture_Publish(int pass,int stage,bool val); - void Set_Texture_Resize(int pass,int stage,bool val); // NOTE: obsolete: replaced by Set_Texture_No_LOD - void Set_Texture_No_Mipmap(int pass,int stage,bool val); // NOTE: obsolete: replaced by Set_Texture_No_LOD - void Set_Texture_Clamp_U(int pass,int stage,bool val); - void Set_Texture_Clamp_V(int pass,int stage,bool val); - void Set_Texture_No_LOD(int pass,int stage,bool val); - void Set_Texture_Alpha_Bitmap(int pass,int stage,bool val); - void Set_Texture_Hint(int pass,int stage,int val); - void Set_Texture_Display(int pass,int stage,bool val); - void Set_Texture_Frame_Rate(int pass,int stage,float val); - void Set_Texture_Frame_Count(int pass,int stage,int val); - void Set_Texture_Anim_Type(int pass,int stage,int val); - void Set_Texture(int pass,int stage,Texmap * tex); - void Set_Displacement_Amount(float amount) { DisplacementAmt = amount; Notify_Changed (); } - - void Set_Map_Channel(int pass,int stage,int channel); - - void Notify_Changed(void); - - // This returns the mapping args string buffer for that pass after - // assuring that it is at least of length 'len'. - char * Get_Mapping_Arg_Buffer(int pass, int stage=0, unsigned int len = 0U); - - int pass_stage_to_texmap_index(int pass,int stage); - void texmap_index_to_pass_stage(int index,int * set_pass,int * set_stage); - - // Set and get the type of shader, PC or PS2. - // MLL - int Get_Shader_Type() {return (ShaderType);} - void Set_Shader_Type(int shadertype) {ShaderType = shadertype;} - - // Approximate the PS2 shader on the PC. - int Compute_PC_Shader_From_PS2_Shader(int pass); - int Compute_PS2_Shader_From_PC_Shader(int pass); - - // IML: Get/set substitute material. - Mtl* Substitute_Material() {return (SubstituteMaterial);} - void Set_Substitute_Material (Mtl *m) {SubstituteMaterial = m;} - -private: - - int texture_ref_index(int pass,int stage) { return REF_TEXTURE + pass*W3dMaterialClass::MAX_STAGES + stage; } - int pass_ref_index(int pass) { return REF_PASS_PARAMETERS + pass; } - - void update_viewport_display(); - - // Do the shade functions specific to the Playstation 2. - void ps2_shade(ShadeContext& sc); - - - unsigned int SurfaceType; - int SortLevel; - - Interval Ivalid; // Valid interval - GameMtlDlg * MaterialDialog; // Dialog - ULONG Flags; // Flags - int RollScroll; // Rollup scroll position - int CurPage[W3dMaterialClass::MAX_PASSES]; // which page was last open for each pass - - GameMapsClass * Maps; // ref 0 (obsolete...) - IParamBlock * MainParameterBlock; - IParamBlock * PassParameterBlock[W3dMaterialClass::MAX_PASSES]; - Texmap * Texture[W3dMaterialClass::MAX_PASSES][W3dMaterialClass::MAX_STAGES]; - char * MapperArg[W3dMaterialClass::MAX_PASSES][W3dMaterialClass::MAX_STAGES]; - unsigned int MapperArgLen[W3dMaterialClass::MAX_PASSES][W3dMaterialClass::MAX_STAGES]; - Texmap * DisplacementMap; - float DisplacementAmt; - - // MLL - int ShaderType; - enum - { - REF_MAPS = 0, // obsolete, gamemaps object - REF_MAIN = 1, // main parameter block is ref 1 - REF_PASS_PARAMETERS = 2, // pass parameter blocks are refs 2,3,4,5 - REF_TEXTURE = 6, // textures are refs 6,7,8,9,10,11,12,13,14 (14 is the displacement map) - REF_COUNT = 15 - }; - - Mtl *SubstituteMaterial; // IML: Temporary material used during game to standard material conversion and vice-versa. - - friend class GameMtlDlg; - friend class GameMtlPostLoad; -}; - -Mtl * CreateGameMtl(); - -#endif - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/genlodextensiondialog.cpp b/Generals/Code/Tools/WW3D/max2w3d/genlodextensiondialog.cpp deleted file mode 100644 index 1684038e17..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/genlodextensiondialog.cpp +++ /dev/null @@ -1,208 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/genlodextensiondialog.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/10/00 11:14a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GenLodExtensionDialogClass::GenLodExtensionDialogClass -- Constructor * - * GenLodExtensionDialogClass::~GenLodExtensionDialogClass -- Destructor * - * GenLodExtensionDialogClass::Get_Options -- Presents the dialog, gets user input * - * GenLodExtensionDialogClass::Dialog_Proc -- Windows message handling * - * _gen_lod_ext_dialog_proc -- windows dialog proc * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "genlodextensiondialog.h" -#include "dllmain.h" -#include "resource.h" -#include - - -/********************************************************************************************** -** -** GenLodExtensionDialogClass Implementation -** -**********************************************************************************************/ - - -/*********************************************************************************************** - * GenLodExtensionDialogClass::GenLodExtensionDialogClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -GenLodExtensionDialogClass::GenLodExtensionDialogClass(Interface * maxinterface) : - Hwnd(NULL), - Options(NULL), - MaxInterface(maxinterface), - LodIndexSpin(NULL) -{ -} - - -/*********************************************************************************************** - * GenLodExtensionDialogClass::~GenLodExtensionDialogClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -GenLodExtensionDialogClass::~GenLodExtensionDialogClass(void) -{ - ReleaseISpinner(LodIndexSpin); -} - - -/*********************************************************************************************** - * GenLodExtensionDialogClass::Get_Options -- Presents the dialog, gets user input * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenLodExtensionDialogClass::Get_Options(OptionsStruct * options) -{ - Options = options; - - // Put up the options dialog box. - BOOL result = DialogBoxParam - ( - AppInstance, - MAKEINTRESOURCE (IDD_GENERATE_LOD_EXTENSION_DIALOG), - MaxInterface->GetMAXHWnd(), - (DLGPROC) _gen_lod_ext_dialog_proc, - (LPARAM) this - ); - - if (result == TRUE) { - return true; - } else { - return false; - } -} - - -/*********************************************************************************************** - * GenLodExtensionDialogClass::Dialog_Proc -- Windows message handling * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenLodExtensionDialogClass::Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM) -{ - switch (message ) { - - case WM_INITDIALOG: - - // Setup the LOD spinner control. - LodIndexSpin = SetupIntSpinner - ( - Hwnd, - IDC_LOD_INDEX_SPIN, - IDC_LOD_INDEX_EDIT, - MIN_LOD_INDEX,MAX_LOD_INDEX,INITIAL_LOD_INDEX - ); - - return 1; - - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - Options->LodIndex = LodIndexSpin->GetIVal(); - EndDialog(Hwnd, 1); - break; - - case IDCANCEL: - EndDialog(Hwnd, 0); - break; - } - return 1; - } - return 0; -} - - -/*********************************************************************************************** - * _gen_lod_ext_dialog_proc -- windows dialog proc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -static BOOL CALLBACK _gen_lod_ext_dialog_proc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam) -{ - static GenLodExtensionDialogClass * dialog = NULL; - - if (message == WM_INITDIALOG) { - dialog = (GenLodExtensionDialogClass *)lparam; - dialog->Hwnd = hwnd; - } - - if (dialog) { - return dialog->Dialog_Proc(hwnd, message, wparam, lparam); - } else { - return FALSE; - } -} - - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/genlodextensiondialog.h b/Generals/Code/Tools/WW3D/max2w3d/genlodextensiondialog.h deleted file mode 100644 index a3ef870f59..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/genlodextensiondialog.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/genlodextensiondialog.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/10/00 11:14a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef GENLODEXTENSIONDIALOG_H -#define GENLODEXTENSIONDIALOG_H - -#include - -class Interface; -class ISpinnerControl; - -/********************************************************************************************** -** -** GenLodExtensionDialogClass - Dialog box for the LOD extension naming parameters -** -**********************************************************************************************/ -class GenLodExtensionDialogClass -{ -public: - - GenLodExtensionDialogClass(Interface * maxinterface); - ~GenLodExtensionDialogClass(); - - struct OptionsStruct - { - OptionsStruct(void) : LodIndex(0) - { - } - - // name options - int LodIndex; - }; - - bool Get_Options(OptionsStruct * options); - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - -private: - - enum - { - MIN_LOD_INDEX = 0, - MAX_LOD_INDEX = 99, - INITIAL_LOD_INDEX = 0, - }; - - HWND Hwnd; - - OptionsStruct * Options; - Interface * MaxInterface; - ISpinnerControl * LodIndexSpin; - - friend BOOL CALLBACK _gen_lod_ext_dialog_proc(HWND Hwnd,UINT message,WPARAM wParam,LPARAM lParam); - -}; - - - - -#endif //GENLODEXTENSIONDIALOG_H \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp b/Generals/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp deleted file mode 100644 index 7240376c96..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/genmtlnamesdialog.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/10/00 11:12a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GenMtlNamesDialogClass::GenMtlNamesDialogClass -- Constructor * - * GenMtlNamesDialogClass::~GenMtlNamesDialogClass -- Destructor * - * GenMtlNamesDialogClass::Get_Options -- present the dialog, get user input * - * GenMtlNamesDialogClass::Ok_To_Exit -- verify that the input is valid * - * GenMtlNamesDialogClass::Dialog_Proc -- windows message handling * - * _gen_mtl_names_dialog_proc -- windows dialog proc for GenMtlNamesDialog * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "genmtlnamesdialog.h" -#include "dllmain.h" -#include "resource.h" -#include "w3d_file.h" -#include - -static BOOL CALLBACK _gen_mtl_names_dialog_proc(HWND Hwnd,UINT message,WPARAM wParam,LPARAM lParam); - - -/********************************************************************************************** -** -** GenMtlNamesDialogClass Implementation -** -**********************************************************************************************/ - - -/*********************************************************************************************** - * GenMtlNamesDialogClass::GenMtlNamesDialogClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -GenMtlNamesDialogClass::GenMtlNamesDialogClass(Interface * maxinterface) : - Hwnd(NULL), - Options(NULL), - MaxInterface(maxinterface), - NameIndexSpin(NULL) -{ -} - - -/*********************************************************************************************** - * GenMtlNamesDialogClass::~GenMtlNamesDialogClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -GenMtlNamesDialogClass::~GenMtlNamesDialogClass(void) -{ - ReleaseISpinner(NameIndexSpin); -} - - -/*********************************************************************************************** - * GenMtlNamesDialogClass::Get_Options -- present the dialog, get user input * - * * - * INPUT: * - * options - pointer to structure to hold the user's input * - * * - * OUTPUT: * - * true - user pressed ok and the input is valid * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenMtlNamesDialogClass::Get_Options(OptionsStruct * options) -{ - Options = options; - - // Put up the options dialog box. - BOOL result = DialogBoxParam - ( - AppInstance, - MAKEINTRESOURCE (IDD_GENERATE_MTL_NAMES_DIALOG), - MaxInterface->GetMAXHWnd(), - (DLGPROC) _gen_mtl_names_dialog_proc, - (LPARAM) this - ); - - if (result == TRUE) { - return true; - } else { - return false; - } -} - - -/*********************************************************************************************** - * GenMtlNamesDialogClass::Ok_To_Exit -- verify that the input is valid * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenMtlNamesDialogClass::Ok_To_Exit(void) -{ - // just check that the user entered a name - char buf[W3D_NAME_LEN]; - GetWindowText(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),buf,sizeof(buf)); - - if (strlen(buf) == 0) { - MessageBox(Hwnd,"Please enter a root name to use.\n","Error",MB_OK); - return false; - } else { - return true; - } - - return true; -} - - -/*********************************************************************************************** - * GenMtlNamesDialogClass::Dialog_Proc -- windows message handling * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenMtlNamesDialogClass::Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM) -{ - switch (message ) { - - case WM_INITDIALOG: - - NameIndexSpin = SetupIntSpinner - ( - Hwnd, - IDC_NAME_INDEX_SPIN, - IDC_NAME_INDEX_EDIT, - MIN_NAME_INDEX,MAX_NAME_INDEX,INITIAL_NAME_INDEX - ); - - // limit the edit box characters - SendDlgItemMessage(Hwnd,IDC_BASE_NAME_EDIT,EM_LIMITTEXT,MAX_ROOT_NAME_LEN,0); - - // set initial name to root of the filename - char buf[_MAX_FNAME]; - _splitpath(MaxInterface->GetCurFileName(),NULL,NULL,buf,NULL); - buf[MAX_ROOT_NAME_LEN+1] = 0; - SetWindowText(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),buf); - - // init radio buttons - CheckDlgButton(Hwnd,IDC_AFFECT_ALL_RADIO,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_AFFECT_SELECTED_RADIO,BST_CHECKED); - - return 1; - - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - if (Ok_To_Exit()) { - // general options - Options->OnlyAffectSelected = (IsDlgButtonChecked(Hwnd,IDC_AFFECT_SELECTED_RADIO) == BST_CHECKED); - - // naming options - Options->NameIndex = NameIndexSpin->GetIVal(); - GetWindowText(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),Options->RootName,sizeof(Options->RootName)); - - EndDialog(Hwnd, 1); - } - break; - - case IDCANCEL: - EndDialog(Hwnd, 0); - break; - - } - return 1; - } - return 0; -} - - -/*********************************************************************************************** - * _gen_mtl_names_dialog_proc -- windows dialog proc for GenMtlNamesDialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -static BOOL CALLBACK _gen_mtl_names_dialog_proc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam) -{ - static GenMtlNamesDialogClass * dialog = NULL; - - if (message == WM_INITDIALOG) { - dialog = (GenMtlNamesDialogClass *)lparam; - dialog->Hwnd = hwnd; - } - - if (dialog) { - return dialog->Dialog_Proc(hwnd, message, wparam, lparam); - } else { - return FALSE; - } -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.h b/Generals/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.h deleted file mode 100644 index f53bbb012e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/genmtlnamesdialog.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/genmtlnamesdialog.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/10/00 11:12a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef GENMTLNAMESDIALOG_H -#define GENMTLNAMESDIALOG_H - -#include - -class Interface; -class ISpinnerControl; - -/********************************************************************************************** -** -** GenMtlNamesDialogClass - Dialog box for the material naming parameters -** -**********************************************************************************************/ -class GenMtlNamesDialogClass -{ -public: - - GenMtlNamesDialogClass(Interface * maxinterface); - ~GenMtlNamesDialogClass(); - - enum - { - MAX_MATERIAL_NAME_LEN = 32, - MIN_NAME_INDEX = 0, - MAX_NAME_INDEX = 999, - INITIAL_NAME_INDEX = 0, - MAX_ROOT_NAME_LEN = 28, - }; - - struct OptionsStruct - { - OptionsStruct(void) : OnlyAffectSelected(true), NameIndex(0) - { - memset(RootName,0,sizeof(RootName)); - } - - // overall options - bool OnlyAffectSelected; - - // name options - char RootName[MAX_MATERIAL_NAME_LEN]; - int NameIndex; - }; - - bool Get_Options(OptionsStruct * options); - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - bool Ok_To_Exit(void); - -private: - - HWND Hwnd; - - OptionsStruct * Options; - Interface * MaxInterface; - ISpinnerControl * NameIndexSpin; - - friend BOOL CALLBACK _gen_mtl_names_dialog_proc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam); - -}; - - -#endif //GENMTLNAMESDIALOG_H - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/gennamesdialog.cpp b/Generals/Code/Tools/WW3D/max2w3d/gennamesdialog.cpp deleted file mode 100644 index 5beb4ded9c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gennamesdialog.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/gennamesdialog.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 12/06/00 3:24p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GenNamesDialogClass::GenNamesDialogClass -- Constructor * - * GenNamesDialogClass::~GenNamesDialogClass -- Destructor * - * GenNamesDialogClass::Get_Options -- Get_Options * - * GenNamesDialogClass::Ok_To_Exit -- verifies that the input is valid * - * GenNamesDialogClass::Toggle_Name_Assignment -- toggles the controls related to name assig * - * GenNamesDialogClass::Toggle_Collision_Bits_Assignment -- toggles the controls related to * - * GenNamesDialogClass::Dialog_Proc -- windows dialog proc * - * _gen_names_dialog_proc -- dialog proc that "thunks" to the class's dialog proc * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "gennamesdialog.h" -#include "dllmain.h" -#include "resource.h" - - -static BOOL CALLBACK _gen_names_dialog_proc(HWND Hwnd,UINT message,WPARAM wParam,LPARAM lParam); - - -/********************************************************************************************** -** -** GenNamesDialogClass Implementation -** -**********************************************************************************************/ - - -/*********************************************************************************************** - * GenNamesDialogClass::GenNamesDialogClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -GenNamesDialogClass::GenNamesDialogClass(Interface * maxinterface) : - Hwnd(NULL), - Options(NULL), - MaxInterface(maxinterface), - NameIndexSpin(NULL) -{ -} - - -/*********************************************************************************************** - * GenNamesDialogClass::~GenNamesDialogClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -GenNamesDialogClass::~GenNamesDialogClass(void) -{ - ReleaseISpinner(NameIndexSpin); -} - - -/*********************************************************************************************** - * GenNamesDialogClass::Get_Options -- Get_Options * - * * - * presents the dialog to the user and records his selections into the passed-in options * - * structure. * - * * - * INPUT: * - * options - pointer to a OptionsStruct to store the users input in. * - * * - * OUTPUT: * - * true - user pressed ok and entered valid input * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenNamesDialogClass::Get_Options(OptionsStruct * options) -{ - Options = options; - - // Put up the options dialog box. - BOOL result = DialogBoxParam - ( - AppInstance, - MAKEINTRESOURCE (IDD_GENERATE_NAMES_DIALOG), - MaxInterface->GetMAXHWnd(), - (DLGPROC) _gen_names_dialog_proc, - (LPARAM) this - ); - - if (result == TRUE) { - return true; - } else { - return false; - } -} - - -/*********************************************************************************************** - * GenNamesDialogClass::Ok_To_Exit -- verifies that the input is valid * - * * - * INPUT: * - * * - * OUTPUT: * - * true - dialog contains valid input * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenNamesDialogClass::Ok_To_Exit(void) -{ - if (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_NAMES_CHECK) == BST_CHECKED) { - - // just check that the user entered a name - char buf[W3D_NAME_LEN]; - GetWindowText(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),buf,sizeof(buf)); - - if (strlen(buf) == 0) { - MessageBox(Hwnd,"Please enter a root name to use.\n","Error",MB_OK); - return false; - } else { - return true; - } - } - - return true; -} - - -/*********************************************************************************************** - * GenNamesDialogClass::Toggle_Name_Assignment -- toggles the controls related to name assignm * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -void GenNamesDialogClass::Toggle_Name_Assignment(void) -{ - bool onoff = (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_NAMES_CHECK) == BST_CHECKED); - EnableWindow(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_LOD_INDEX_EDIT),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_LOD_INDEX_SPIN),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_NAME_INDEX_EDIT),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_NAME_INDEX_SPIN),onoff); -} - - -/*********************************************************************************************** - * GenNamesDialogClass::Toggle_Collision_Bits_Assignment -- toggles the controls related to co * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -void GenNamesDialogClass::Toggle_Collision_Bits_Assignment(void) -{ - bool onoff = (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_COLLISION_BITS_CHECK) == BST_CHECKED); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PHYSICAL),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PROJECTILE),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VIS),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_CAMERA),onoff); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VEHICLE),onoff); -} - - -/*********************************************************************************************** - * GenNamesDialogClass::Dialog_Proc -- windows dialog proc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -bool GenNamesDialogClass::Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM) -{ - switch (message ) { - - case WM_INITDIALOG: - - NameIndexSpin = SetupIntSpinner - ( - Hwnd, - IDC_NAME_INDEX_SPIN, - IDC_NAME_INDEX_EDIT, - MIN_NAME_INDEX,MAX_NAME_INDEX,INITIAL_NAME_INDEX - ); - - // limit the base name edit box to 10 characters - SendDlgItemMessage(Hwnd,IDC_BASE_NAME_EDIT,EM_LIMITTEXT,MAX_ROOT_NAME_LEN,0); - - // limit the suffix and prefix edit boxes - SendDlgItemMessage(Hwnd,IDC_PREFIX_EDIT,EM_LIMITTEXT,MAX_PREFIX_LEN,0); - SendDlgItemMessage(Hwnd,IDC_SUFFIX_EDIT,EM_LIMITTEXT,MAX_SUFFIX_LEN,0); - - // set initial name to root of the filename - char buf[_MAX_FNAME]; - _splitpath(MaxInterface->GetCurFileName(),NULL,NULL,buf,NULL); - buf[MAX_ROOT_NAME_LEN+1] = 0; - SetWindowText(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),buf); - - // init radio buttons - CheckDlgButton(Hwnd,IDC_AFFECT_ALL_RADIO,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_AFFECT_SELECTED_RADIO,BST_CHECKED); - - // init the check boxes - CheckDlgButton(Hwnd,IDC_ASSIGN_NAMES_CHECK,BST_CHECKED); - CheckDlgButton(Hwnd,IDC_ASSIGN_PREFIX_CHECK,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_ASSIGN_SUFFIX_CHECK,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_ASSIGN_COLLISION_BITS_CHECK,BST_CHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_PHYSICAL,BST_CHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_PROJECTILE,BST_CHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_VIS,BST_CHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_CAMERA,BST_CHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_VEHICLE,BST_CHECKED); - return 1; - - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - if (Ok_To_Exit()) { - // general options - Options->AssignNames = (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_NAMES_CHECK) == BST_CHECKED); - Options->AssignPrefix = (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_PREFIX_CHECK) == BST_CHECKED); - Options->AssignSuffix = (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_SUFFIX_CHECK) == BST_CHECKED); - Options->AssignCollisionBits = (IsDlgButtonChecked(Hwnd,IDC_ASSIGN_COLLISION_BITS_CHECK) == BST_CHECKED); - Options->OnlyAffectSelected = (IsDlgButtonChecked(Hwnd,IDC_AFFECT_SELECTED_RADIO) == BST_CHECKED); - - // naming options - Options->NameIndex = NameIndexSpin->GetIVal(); - GetWindowText(GetDlgItem(Hwnd,IDC_BASE_NAME_EDIT),Options->RootName,sizeof(Options->RootName)); - GetWindowText(GetDlgItem(Hwnd,IDC_PREFIX_EDIT),Options->PrefixName,sizeof(Options->PrefixName)); - GetWindowText(GetDlgItem(Hwnd,IDC_SUFFIX_EDIT),Options->SuffixName,sizeof(Options->SuffixName)); - - // collision options - Options->PhysicalCollision = (IsDlgButtonChecked(Hwnd,IDC_COLLISION_PHYSICAL) == BST_CHECKED); - Options->ProjectileCollision = (IsDlgButtonChecked(Hwnd,IDC_COLLISION_PROJECTILE) == BST_CHECKED); - Options->VisCollision = (IsDlgButtonChecked(Hwnd,IDC_COLLISION_VIS) == BST_CHECKED); - Options->CameraCollision = (IsDlgButtonChecked(Hwnd,IDC_COLLISION_CAMERA) == BST_CHECKED); - Options->VehicleCollision = (IsDlgButtonChecked(Hwnd,IDC_COLLISION_VEHICLE) == BST_CHECKED); - EndDialog(Hwnd, 1); - } - break; - - case IDCANCEL: - EndDialog(Hwnd, 0); - break; - - case IDC_ASSIGN_NAMES_CHECK: - Toggle_Name_Assignment(); - break; - - case IDC_ASSIGN_PREFIX_CHECK: - EnableWindow(GetDlgItem(Hwnd,IDC_PREFIX_EDIT),(IsDlgButtonChecked(Hwnd,IDC_ASSIGN_SUFFIX_CHECK) == BST_CHECKED)); - break; - - case IDC_ASSIGN_SUFFIX_CHECK: - EnableWindow(GetDlgItem(Hwnd,IDC_SUFFIX_EDIT),(IsDlgButtonChecked(Hwnd,IDC_ASSIGN_SUFFIX_CHECK) == BST_CHECKED)); - break; - - case IDC_ASSIGN_COLLISION_BITS_CHECK: - Toggle_Collision_Bits_Assignment(); - break; - } - return 1; - } - return 0; -} - - -/*********************************************************************************************** - * _gen_names_dialog_proc -- dialog proc that "thunks" to the class's dialog proc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/10/2000 gth : Created. * - *=============================================================================================*/ -static BOOL CALLBACK _gen_names_dialog_proc(HWND hwnd,UINT message,WPARAM wparam,LPARAM lparam) -{ - static GenNamesDialogClass * dialog = NULL; - - if (message == WM_INITDIALOG) { - dialog = (GenNamesDialogClass *)lparam; - dialog->Hwnd = hwnd; - } - - if (dialog) { - return dialog->Dialog_Proc(hwnd, message, wparam, lparam); - } else { - return FALSE; - } -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/gennamesdialog.h b/Generals/Code/Tools/WW3D/max2w3d/gennamesdialog.h deleted file mode 100644 index 6c52343ee5..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gennamesdialog.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/gennamesdialog.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 12/06/00 3:25p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include -#include "w3d_file.h" - - -/********************************************************************************************** -** -** GenNamesDialogClass - Dialog box for the node naming parameters -** -**********************************************************************************************/ -class GenNamesDialogClass -{ -public: - - GenNamesDialogClass(Interface * maxinterface); - ~GenNamesDialogClass(); - - struct OptionsStruct - { - OptionsStruct(void) : OnlyAffectSelected(false), NameIndex(0), AssignCollisionBits(false) - { - memset(RootName,0,sizeof(RootName)); - memset(PrefixName,0,sizeof(PrefixName)); - memset(SuffixName,0,sizeof(SuffixName)); - } - - // overall options - bool AssignNames; - bool AssignPrefix; - bool AssignSuffix; - bool AssignCollisionBits; - bool OnlyAffectSelected; - - // name options - char RootName[W3D_NAME_LEN]; - char PrefixName[W3D_NAME_LEN]; - char SuffixName[W3D_NAME_LEN]; - int NameIndex; - - // collision bit options - bool PhysicalCollision; - bool ProjectileCollision; - bool VisCollision; - bool CameraCollision; - bool VehicleCollision; - }; - - bool Get_Options(OptionsStruct * options); - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - bool Ok_To_Exit(void); - void Toggle_Collision_Bits_Assignment(void); - void Toggle_Name_Assignment(void); - -private: - - enum - { - MIN_NAME_INDEX = 0, - MAX_NAME_INDEX = 999, - INITIAL_NAME_INDEX = 0, - MAX_ROOT_NAME_LEN = 10, - MAX_PREFIX_LEN = 3, - MAX_SUFFIX_LEN = 3, - }; - - HWND Hwnd; - - OptionsStruct * Options; - Interface * MaxInterface; - ISpinnerControl * NameIndexSpin; - - friend BOOL CALLBACK _gen_names_dialog_proc(HWND Hwnd,UINT message,WPARAM wParam,LPARAM lParam); - -}; - diff --git a/Generals/Code/Tools/WW3D/max2w3d/geometryexportcontext.h b/Generals/Code/Tools/WW3D/max2w3d/geometryexportcontext.h deleted file mode 100644 index ce86342bdf..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/geometryexportcontext.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/geometryexportcontext.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/19/00 11:32a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef GEOMETRYEXPORTCONTEXT_H -#define GEOMETRYEXPORTCONTEXT_H - -#include - -class ChunkSaveClass; -class MaxWorldInfoClass; -class HierarchySaveClass; -class INodeListClass; -class Progress_Meter_Class; -struct W3dExportOptionsStruct; - - -/** -** ExportContextClass -** This class encapsulates a bunch of datastructures needed during the geometry export -** process. -** NOTE: The user must plug in a valid ProgressMeter before each export operation. -*/ -class GeometryExportContextClass -{ -public: - GeometryExportContextClass( char * model_name, - ChunkSaveClass & csave, - MaxWorldInfoClass & world_info, - W3dExportOptionsStruct & options, - HierarchySaveClass * htree, - INode * origin, - INodeListClass * origin_list, - TimeValue curtime, - unsigned int *materialColors - ) : - CSave(csave), - WorldInfo(world_info), - Options(options), - CurTime(curtime), - HTree(htree), - OriginList(origin_list), - Origin(origin), - OriginTransform(1), - ProgressMeter(NULL), - materialColors(materialColors), - numMaterialColors(0), - numHouseColors(0), - materialColorTexture(NULL) - { - ModelName = strdup(model_name); - OriginTransform = Origin->GetNodeTM(CurTime); - } - - ~GeometryExportContextClass(void) - { - delete[] ModelName; - } - - char * ModelName; - ChunkSaveClass & CSave; - MaxWorldInfoClass & WorldInfo; - W3dExportOptionsStruct & Options; - TimeValue CurTime; - HierarchySaveClass * HTree; - INodeListClass * OriginList; - - INode * Origin; - Matrix3 OriginTransform; - Progress_Meter_Class * ProgressMeter; - unsigned int * materialColors; ///MW: holds all used material colors. - int numMaterialColors; ///MW: number of used material colors. - int numHouseColors; ///MW: number of used house colors - char * materialColorTexture; //MW: texture to hold material colors -}; - - - -#endif //GEOMETRYEXPORTCONTEXT_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/geometryexporttask.cpp b/Generals/Code/Tools/WW3D/max2w3d/geometryexporttask.cpp deleted file mode 100644 index be3baf4bef..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/geometryexporttask.cpp +++ /dev/null @@ -1,1176 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/geometryexporttask.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/31/00 10:35a $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GeometryExportTaskClass::GeometryExportTaskClass -- Constructor * - * GeometryExportTaskClass::GeometryExportTaskClass -- Copy Constructor * - * GeometryExportTaskClass::~GeometryExportTaskClass -- Destructor * - * GeometryExportTaskClass::Get_Full_Name -- Composes the full name of this robj * - * GeometryExportTaskClass::Create_Task -- virtual constructor for export tasks * - * GeometryExportTaskClass::Optimize_Geometry -- Optimizes the export tasks * - * GeometryExportTaskClass::Generate_Unique_Name -- create a unique name for this object * - * MeshGeometryExportTaskClass::Is_Single_Material -- Tests if this mesh uses a single mater * - * MeshGeometryExportTaskClass::Get_Single_Material -- returns pointer to the material * - * MeshGeometryExportTaskClass::Cache_Single_Material -- updates the cached material pointer * - * MeshGeometryExportTaskClass::Split -- Splits into single material meshes * - * MeshGeometryExportTaskClass::Reduce_To_Single_Material -- deletes polys * - * MeshGeometryExportTaskClass::Can_Combine -- can this mesh combine with anything * - * MeshGeometryExportTaskClass::Can_Combine_With -- can this mesh be combined with the given * - * MeshGeometryExportTaskClass::Combine_Mesh -- Add the given mesh into this mesh * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "geometryexporttask.h" -#include "geometryexportcontext.h" -#include "util.h" -#include "w3dutil.h" -#include "w3dappdata.h" -#include "hiersave.h" -#include "maxworldinfo.h" -#include "meshsave.h" -#include "colboxsave.h" -#include "dazzlesave.h" -#include - - -const int OPTIMIZATION_FACECOUNT_LIMIT = 256; // TODO: what should this number be... -const float OPTIMIZATION_COMBINING_DISTANCE = 20.0f; // TODO: need a smarter method for combining... - - -/** -** MeshGeometryExportTaskClass -** Export task for INodes which are to generate W3D meshes -*/ -class MeshGeometryExportTaskClass : public GeometryExportTaskClass -{ -public: - - MeshGeometryExportTaskClass(INode * node,GeometryExportContextClass & context) : - GeometryExportTaskClass(node,context), - NameDirty(false), - SingleMtl(NULL) - { - /* - ** Copy the export options - */ - ExportOptions = *(W3DAppData2Struct::Get_App_Data(Node)); - - /* - ** Copy the mesh - */ - Object * obj = Node->EvalWorldState(CurTime).obj; - TriObject * tri = (TriObject *)obj->ConvertToType(CurTime, triObjectClassID); - MeshData = tri->mesh; - - /* - ** Store a pointer to the material if this mesh uses only one material (even inside a Multi-Sub) - */ - Update_Cached_Data(); - } - - MeshGeometryExportTaskClass(const MeshGeometryExportTaskClass & that) : - GeometryExportTaskClass(that), - MeshData(that.MeshData), - ExportOptions(that.ExportOptions), - NameDirty(false) - { - } - - virtual ~MeshGeometryExportTaskClass(void) - { - } - - virtual void Export_Geometry(GeometryExportContextClass & context) - { - /* - ** Create the mesh - */ - context.WorldInfo.Set_Current_Task(this); - context.WorldInfo.Set_Export_Transform(ExportSpace); - - MeshSaveClass * mesh = new MeshSaveClass( Name, - ContainerName, - Node, - &MeshData, - ExportSpace, - ExportOptions, - context.HTree, - context.CurTime, - *context.ProgressMeter, - context.materialColors, - context.numMaterialColors, - context.numHouseColors, - context.materialColorTexture, - &context.WorldInfo - ); - - /* - ** Export It - */ - mesh->Write_To_File(context.CSave,!context.Options.DisableExportAABTrees); - delete mesh; - context.ProgressMeter->Add_Increment(); - }; - - /* - ** Naming. During the optimization phase, sometimes new meshes are created and require - ** new unique names. These meshes are flagged and then new names are generated prior - ** to exporting. - */ - bool Is_Name_Dirty(void) { return NameDirty; } - void Set_Name_Dirty(bool onoff) { NameDirty = onoff; } - - /* - ** Vertex Normal smoothing support! - */ - virtual Point3 Get_Shared_Vertex_Normal(const Point3 & pos,int smgroup); - - /* - ** Optimization functions - */ - bool Is_Single_Material(void); - Mtl * Get_Single_Material(void); - void Split(DynamicVectorClass & simple_meshes); - void Reduce_To_Single_Material(int mat_id); - bool Can_Combine(void); - bool Can_Combine_With(MeshGeometryExportTaskClass * other_mesh); - void Combine_Mesh(MeshGeometryExportTaskClass * other_mesh); - -protected: - - virtual int Get_Geometry_Type(void) { return MESH; } - void Update_Cached_Data(void); - - Mesh MeshData; // Copy of the mesh data to be exported. - W3DAppData2Struct ExportOptions; // Copy of the export options in case we want to change them during optimization - bool NameDirty; - - // Cached Data about the Node/Mesh. Updated by calling Update_Cached_Data whenever the mesh changes. - Mtl * SingleMtl; // Pointer to the single material (if the mesh uses only one, even in a multi-mtl) - Point3 BoxCenter; // Center of the bounding box (in object space) - Point3 BoxExtent; // Extent of the bounding box (in object space) - Box3 WorldBounds; // World-space bounding box -}; - - - - - -/** -** CollisionBoxGeometryExportTaskClass -** Export task for INodes which are to generate W3D AABoxes or OBBoxes -*/ -class CollisionBoxGeometryExportTaskClass : public GeometryExportTaskClass -{ -public: - CollisionBoxGeometryExportTaskClass(INode * node,GeometryExportContextClass & context) : - GeometryExportTaskClass(node,context) - { - } - - virtual void Export_Geometry(GeometryExportContextClass & context) - { - /* - ** Create the collision box - */ - CollisionBoxSaveClass * colbox = new CollisionBoxSaveClass( Name, - ContainerName, - Node, - ExportSpace, - context.CurTime, - *context.ProgressMeter); - - /* - ** Export it - */ - colbox->Write_To_File(context.CSave); - delete colbox; - context.ProgressMeter->Add_Increment(); - }; - -protected: - - virtual int Get_Geometry_Type(void) { return COLLISIONBOX; } - -}; - - - - - -/** -** DazzleGeometryExportTaskClass -** Export task for INodes which are to generate W3D Dazzle objects -*/ -class DazzleGeometryExportTaskClass : public GeometryExportTaskClass -{ -public: - DazzleGeometryExportTaskClass(INode * node,GeometryExportContextClass & context) : - GeometryExportTaskClass(node,context) - { - } - - virtual void Export_Geometry(GeometryExportContextClass & context) - { - /* - ** Create the dazzle object - */ - DazzleSaveClass * dazzle = new DazzleSaveClass( Name, - ContainerName, - Node, - ExportSpace, - context.CurTime, - *context.ProgressMeter); - /* - ** Export it. - */ - dazzle->Write_To_File(context.CSave); - delete dazzle; - context.ProgressMeter->Add_Increment(); - }; - -protected: - - virtual int Get_Geometry_Type(void) { return DAZZLE; } - -}; - - - - -/** -** NullGeometryExportTaskClass -** Export task for INodes which are to generate W3D NULL objects. Note that this -** does not do anything in the Export_Geometry call, these only create entries in -** any Hierarhcical model or collection object being exported. -*/ -class NullGeometryExportTaskClass : public GeometryExportTaskClass -{ -public: - NullGeometryExportTaskClass(INode * node,GeometryExportContextClass & context) : - GeometryExportTaskClass(node,context) - { - memset(ContainerName,0,sizeof(ContainerName)); - memset(Name,0,sizeof(Name)); - strcpy(Name,"NULL"); - } - - virtual void Export_Geometry(GeometryExportContextClass & context) - { - context.ProgressMeter->Add_Increment(); - }; - -protected: - - virtual int Get_Geometry_Type(void) { return NULLOBJ; } - -}; - - -/** -** AggregateGeometryExportTaskClass -** Export task for INodes which are to generate W3D Aggregates. These are nodes -** that refer to some external W3D object. This export task doesn't export any -** geometry (similer to the Null export task) and it clears its container name -** because the object to be attached is not a sub-object of the model we are -** currently exporting. -*/ -class AggregateGeometryExportTaskClass : public GeometryExportTaskClass -{ -public: - AggregateGeometryExportTaskClass(INode * node,GeometryExportContextClass & context) : - GeometryExportTaskClass(node,context) - { - memset(ContainerName,0,sizeof(ContainerName)); - } - - virtual void Export_Geometry(GeometryExportContextClass & context) - { - context.ProgressMeter->Add_Increment(); - }; - - virtual bool Is_Aggregate(void) - { - return true; - } - -protected: - - virtual int Get_Geometry_Type(void) { return AGGREGATE; } - -}; - - -/** -** ProxyExportTaskClass -** These are used by the Renegade Level Editor to cause game objects to be -** instantiated at the specified transform. Like aggregates they have to -** be handled specially and therefore have the Is_Proxy member function devoted -** solely to them :-) Hopefully we don't have any more geometry types which -** have to be handled specially or this is going to get messy again. -*/ -class ProxyExportTaskClass : public GeometryExportTaskClass -{ -public: - - ProxyExportTaskClass(INode * node,GeometryExportContextClass & context) : - GeometryExportTaskClass(node,context) - { - /* - ** clear the container name - */ - memset(ContainerName,0,sizeof(ContainerName)); - - /* - ** strip the trailing ~ - */ - char *tilda = ::strchr(Name, '~'); - memset(tilda,0,sizeof(Name) - ((int)tilda - (int)Name)); - - } - - virtual void Export_Geometry(GeometryExportContextClass & context) - { - context.ProgressMeter->Add_Increment(); - }; - - virtual bool Is_Proxy(void) { return true; } - -protected: - - virtual int Get_Geometry_Type(void) { return PROXY; } - -}; - - - - - -/*********************************************************************************************** -** -** Implementations -** -***********************************************************************************************/ - -/*********************************************************************************************** - * GeometryExportTaskClass::GeometryExportTaskClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -GeometryExportTaskClass::GeometryExportTaskClass(INode * node,GeometryExportContextClass & context) : - BoneIndex(0), - ExportSpace(1), - CurTime(context.CurTime), - Node(node) -{ - /* - ** Set up the names - */ - Set_W3D_Name(Name,Node->GetName()); - Append_Lod_Character(Name,Get_Lod_Level(context.Origin),context.OriginList); - Set_W3D_Name(ContainerName,context.ModelName); - - /* - ** Set up the bone index and export coordinate system. - */ - if (context.HTree != NULL) { - if (!Is_Skin(node)) { - context.HTree->Get_Export_Coordinate_System(Node,&BoneIndex,NULL,&ExportSpace); - } else { - BoneIndex = 0; - ExportSpace = context.OriginTransform; - } - } -} - - -/*********************************************************************************************** - * GeometryExportTaskClass::GeometryExportTaskClass -- Copy Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -GeometryExportTaskClass::GeometryExportTaskClass(const GeometryExportTaskClass & that) : - BoneIndex(that.BoneIndex), - ExportSpace(that.ExportSpace), - CurTime(that.CurTime), - Node(that.Node) -{ - Set_W3D_Name(Name,that.Name); - Set_W3D_Name(ContainerName,that.ContainerName); -} - - -/*********************************************************************************************** - * GeometryExportTaskClass::~GeometryExportTaskClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -GeometryExportTaskClass::~GeometryExportTaskClass(void) -{ -} - - -/*********************************************************************************************** - * GeometryExportTaskClass::Get_Full_Name -- Composes the full name of this robj * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/24/2000 gth : Created. * - *=============================================================================================*/ -void GeometryExportTaskClass::Get_Full_Name(char * buffer,int size) -{ - char tmp[128]; - memset(tmp,0,sizeof(tmp)); - if (strlen(ContainerName) > 0) { - strcat(tmp,ContainerName); - strcat(tmp,"."); - } - strcat(tmp,Name); - - strncpy(buffer,tmp,size); -} - - -/*********************************************************************************************** - * GeometryExportTaskClass::Create_Task -- virtual constructor for export tasks * - * * - * Virtual constructor for geometry export tasks. Will create the proper task * - * type depending on the W3D flag settings. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -GeometryExportTaskClass * -GeometryExportTaskClass::Create_Task(INode * node,GeometryExportContextClass & context) -{ - if (!::Is_Geometry(node)) { - return NULL; - } - - // NOTE: we *have* to check Is_Proxy first because it is tied to a naming convention - // rather than an explicit UI setting like the rest of the types. - if (::Is_Proxy(*node)) { - return new ProxyExportTaskClass(node,context); - } - - if (::Is_Normal_Mesh(node) || Is_Camera_Aligned_Mesh(node) || Is_Camera_Oriented_Mesh(node) || Is_Skin(node)) { - return new MeshGeometryExportTaskClass(node,context); - } - - if (::Is_Collision_AABox(node) || Is_Collision_OBBox(node)) { - return new CollisionBoxGeometryExportTaskClass(node,context); - } - - if (::Is_Null_Object(node)) { - return new NullGeometryExportTaskClass(node,context); - } - - if (::Is_Dazzle(node)) { - return new DazzleGeometryExportTaskClass(node,context); - } - - if (::Is_Aggregate(node)) { - return new AggregateGeometryExportTaskClass(node,context); - } - - return NULL; -} - - -/*********************************************************************************************** - * GeometryExportTaskClass::Optimize_Geometry -- Optimizes the export tasks * - * * - * This function will attempt to split meshes so that they use only a single material and * - * then try to combine small meshes that use the same material. Export tasks may be * - * removed and new ones added. * - * * - * INPUT: * - * tasks - dynamic vector of export task pointers. Some tasks may be deleted, some added * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -void GeometryExportTaskClass::Optimize_Geometry -( - DynamicVectorClass & tasks, - GeometryExportContextClass & context -) -{ - int j=0,i=0; - - /* - ** Pass 1: Extract all mesh geometry tasks from the input task array. - ** NOTE: We're not optimizing Skin meshes so we leave them in the task array. - */ - DynamicVectorClass meshes; - while (iGet_Geometry_Type() == GeometryExportTaskClass::MESH) && - (!Is_Skin(tasks[i]->Get_Object_Node())) ) - { - /* - ** Add to the mesh array, remove from the tasks array - */ - meshes.Add((MeshGeometryExportTaskClass *)(tasks[i])); - tasks.Delete(i); - } else { - - /* - ** Leave in the task array and move to the next one. - */ - i++; - } - } - - /* - ** Pass 2: Split all meshes which use more than one material - */ - DynamicVectorClass simple_meshes; - while (meshes.Count() > 0) { - - int cur_index = meshes.Count() - 1; - MeshGeometryExportTaskClass * cur_mesh = meshes[cur_index]; - - /* - ** If this mesh already uses only one material, just transfer it to the simple_meshes array. - ** Otherwise, have it split into new tasks, add them to the simple_meshes array, and delete this task. - */ - if (cur_mesh->Is_Single_Material()) { - simple_meshes.Add(cur_mesh); - } else { - cur_mesh->Split(simple_meshes); - delete cur_mesh; - } - meshes.Delete(cur_index); - } - - /* - ** Pass 3: Combine meshes which satisfy the following - ** - They use the same (single) material - ** - They have fewer than 'x' polygons - ** - They are 'close' to each other - */ - i=0; - while (i < simple_meshes.Count()) { - - if (simple_meshes[i]->Can_Combine()) { - - j=i+1; - while (j < simple_meshes.Count()) { - if (simple_meshes[i]->Can_Combine_With(simple_meshes[j])) { - - /* - ** Add mesh 'j' into mesh 'i', delete its task. - */ - simple_meshes[i]->Combine_Mesh(simple_meshes[j]); - delete simple_meshes[j]; - simple_meshes.Delete(j); - - /* - ** If we've just exceeded the max poly count, move to the next mesh - */ - if (simple_meshes[i]->Can_Combine() == false) { - j = simple_meshes.Count(); - } - - } else { - - /* - ** Otherwise, move to the next mesh - */ - j++; - } - } - } - i++; - } - - - - /* - ** Generate names for each of the meshes that were created - */ - for (i=0; iIs_Name_Dirty()) { - simple_meshes[i]->Generate_Name("MESH",i,context); -// } - } - - /* - ** Finally, transfer all of the optimized tasks into the big task array - */ - for (i=0; iGetMtl(); - - /* - ** Set the SingleMtl pointer if this mesh uses only one material (again, even if its in a Multi-Sub) - */ - if (nodemtl == NULL) { - - SingleMtl = NULL; - - } else if (nodemtl->NumSubMtls() <= 1) { - - SingleMtl = nodemtl; - - } else { - - int mat_index; - int face_index; - int sub_mtl_count = nodemtl->NumSubMtls(); - bool * sub_mtl_flags = new bool[sub_mtl_count]; - - /* - ** Initialize each sub-material flag to false (indicates that the material is un-used) - */ - for (mat_index=0; mat_indexGetSubMtl(mat_index); - mat_count++; - } - } - - if (mat_count > 1) { - SingleMtl = NULL; - } - } - - /* - ** Update the bounding box - */ - Point3 boxmin(0,0,0); - Point3 boxmax(0,0,0); - - if (MeshData.numVerts > 0) { - boxmin = MeshData.verts[1]; - boxmax = MeshData.verts[0]; - for (int i=0; iGetObjectTM(CurTime); -} - - -/*********************************************************************************************** - * MeshGeometryExportTaskClass::Is_Single_Material -- Tests if this mesh uses a single materia * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -bool MeshGeometryExportTaskClass::Is_Single_Material(void) -{ - return ((SingleMtl != NULL) || (Node->GetMtl() == NULL)); -} - - -/*********************************************************************************************** - * MeshGeometryExportTaskClass::Get_Single_Material -- returns pointer to the material * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/23/2000 gth : Created. * - *=============================================================================================*/ -Mtl* MeshGeometryExportTaskClass::Get_Single_Material(void) -{ - return SingleMtl; -} - -/*********************************************************************************************** - * MeshGeometryExportTaskClass::Split -- Splits into single material meshes * - * * - * This function will create new export tasks and add them to the supplied array. Each of * - * these will be single-material meshes. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -void MeshGeometryExportTaskClass::Split(DynamicVectorClass & simple_meshes) -{ - assert(!Is_Single_Material()); - - Mtl * nodemtl = Node->GetMtl(); - - int mat_index; - int face_index; - int sub_mtl_count = nodemtl->NumSubMtls(); - bool * sub_mtl_flags = new bool[sub_mtl_count]; - - /* - ** Initialize each sub-material flag to false (indicates that the material is un-used) - */ - for (mat_index=0; mat_indexReduce_To_Single_Material(mat_index); - new_task->Set_Name_Dirty(true); - simple_meshes.Add(new_task); - - } - } -} - - -/*********************************************************************************************** - * MeshGeometryExportTaskClass::Reduce_To_Single_Material -- deletes polys * - * * - * This function deletes all polys (and subsequent un-used vertices) except for the ones * - * that use the specified material. * - * * - * INPUT: * - * mat_id - only faces using this material id will remain in the mesh. * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/20/2000 gth : Created. * - *=============================================================================================*/ -void MeshGeometryExportTaskClass::Reduce_To_Single_Material(int mat_id) -{ - int sub_mtl_count = Node->GetMtl()->NumSubMtls(); - - BitArray faces_to_delete(MeshData.getNumFaces()); - BitArray verts_to_delete(MeshData.getNumVerts()); - - faces_to_delete.ClearAll(); - verts_to_delete.ClearAll(); - - for (int i=0; i OPTIMIZATION_FACECOUNT_LIMIT) { - return false; - } - if (ExportOptions.Is_Vis_Collision_Enabled()) { - return false; - } - return true; -} - - -/*********************************************************************************************** - * MeshGeometryExportTaskClass::Can_Combine_With -- can this mesh be combined with the given m * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/24/2000 gth : Created. * - *=============================================================================================*/ -bool MeshGeometryExportTaskClass::Can_Combine_With(MeshGeometryExportTaskClass * other_mesh) -{ - /* - ** Does the mesh attach to the same W3D bone that we do? - */ - if (other_mesh->BoneIndex != BoneIndex) { - return false; - } - - /* - ** Does the mesh use the same (single) material that we do? - */ - Mtl * other_mtl = other_mesh->Get_Single_Material(); - if (other_mtl == NULL) { - return false; - } - - Mtl * my_mtl = Get_Single_Material(); - if (my_mtl != other_mtl) { - return false; - } - - /* - ** Are its relevant W3D options the same as ours? - */ - if (ExportOptions.Geometry_Options_Match(other_mesh->ExportOptions)) { - return false; - } - - /* - ** Would our combined polygon count be reasonable - */ - if (MeshData.numFaces + other_mesh->MeshData.numFaces > OPTIMIZATION_FACECOUNT_LIMIT) { - return false; - } - - /* - ** Is the other mesh near me? - */ - Point3 my_center = Node->GetObjectTM(CurTime) * BoxCenter; - Point3 other_center = other_mesh->Node->GetObjectTM(CurTime) * BoxCenter; - float dist = ::FLength(my_center - other_center); - if (dist > OPTIMIZATION_COMBINING_DISTANCE) { - return false; - } - - return true; -} - - -/*********************************************************************************************** - * MeshGeometryExportTaskClass::Combine_Mesh -- Add the given mesh into this mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/24/2000 gth : Created. * - *=============================================================================================*/ -void MeshGeometryExportTaskClass::Combine_Mesh(MeshGeometryExportTaskClass * other_mesh) -{ - /* - ** Compute the transform from other_mesh's coordinate system to ours so that - ** its polygons can be combined with ours (by calling CombineMeshes) - */ - Matrix3 our_tm = Node->GetObjectTM(CurTime); - Matrix3 his_tm = other_mesh->Node->GetObjectTM(CurTime); - Matrix3 tm = Inverse(our_tm) * his_tm; - - /* - ** Store our current material index - */ - int matid = MeshData.faces[0].getMatID(); - if (Node->GetMtl()->NumSubMtls() > 1) { - matid = matid % Node->GetMtl()->NumSubMtls(); - } - - /* - ** Combine the meshes - */ - Mesh new_mesh; - ::CombineMeshes(new_mesh,MeshData,other_mesh->MeshData,&our_tm,&his_tm,0); - MeshData = new_mesh; - - /* - ** Set all material ID's - */ - for (int i=0; iGetObjectTM(CurTime); - Point3 obj_pos = world_pos * Inverse(tm); - - /* - ** Loop through all the faces in this mesh and find out which ones - ** share the same smoothing group as the vertex we are looking for. - */ - for (int face_index = 0; face_index < MeshData.numFaces; face_index ++) { - Face &maxface = MeshData.faces[face_index]; - int face_smgroup = maxface.getSmGroup(); - if ((face_smgroup & smgroup) || (face_smgroup == smgroup)) { - - /* - ** Find out if any of the verticies of this face share the - ** same space as the vertex we are looking for. - */ - bool found = false; - for (int vert_index = 0; (vert_index < 3) && !found; vert_index ++) { - int max_vert_index = maxface.v[vert_index]; - Point3 delta = obj_pos - MeshData.verts[max_vert_index]; - if ((fabs (delta.x) < EPSILON) && - (fabs (delta.y) < EPSILON) && - (fabs (delta.z) < EPSILON)) - { - - /* - ** Compute the normal for this face - */ - Point3 v0 = MeshData.verts[maxface.v[0]]; - Point3 v1 = MeshData.verts[maxface.v[1]]; - Point3 v2 = MeshData.verts[maxface.v[2]]; - Point3 face_normal = (v1-v0)^(v2-v1); - face_normal = ::Normalize(face_normal); - - /* - ** Add this face normal to the sum - */ - normal.x += face_normal.x; - normal.y += face_normal.y; - normal.z += face_normal.z; - - /* - ** Done with this face, look for more - */ - found = true; - } - } - } - } - - /* - ** Transform the "normal" to world space. Note that this vector isn't - ** normalized because we are basically summing the contributions of each - ** face in each mesh which shares this normal. The final normal - ** will be normalized in the MeshBuilderClass. - */ - tm.NoTrans(); - normal = tm.PointTransform(normal); - } - - return normal; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/geometryexporttask.h b/Generals/Code/Tools/WW3D/max2w3d/geometryexporttask.h deleted file mode 100644 index 36114cd7e2..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/geometryexporttask.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/geometryexporttask.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 5:00p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef GEOMETRYEXPORTTASK_H -#define GEOMETRYEXPORTTASK_H - -#include -#include -#include "w3d_file.h" -#include "Vector.H" - - -class GeometryExportContextClass; - - -/** -** GeometryExportTaskClass -** This abstract base class defines the interface for a geometry export task. -** Derived classes will encapsulate the job of exporting meshes, collision -** boxes, dazzles, etc. The factory function Create_Task will create the -** appropriate task for a given INode. -*/ -class GeometryExportTaskClass -{ -public: - - GeometryExportTaskClass(INode * node,GeometryExportContextClass & context); - GeometryExportTaskClass(const GeometryExportTaskClass & that); - virtual ~GeometryExportTaskClass(void); - - virtual void Export_Geometry(GeometryExportContextClass & context) = 0; - - /* - ** Accessors - */ - char * Get_Name(void) { return Name; } - char * Get_Container_Name(void) { return ContainerName; } - void Get_Full_Name(char * buffer,int size); - - int Get_Bone_Index(void) { return BoneIndex; } - INode * Get_Object_Node(void) { return Node; } - Matrix3 Get_Export_Transform(void) { return ExportSpace; } - - void Set_Name(char * name) { strncpy(Name,name,sizeof(Name)); } - void Set_Container_Name(char * name) { strncpy(ContainerName,name,sizeof(ContainerName)); } - /* - ** Unique Name generation. During optimization, new meshes may get created. When this happens, - ** we have to create a unique name for each one. The name will be generated from the original - ** mesh's name, the index passed in, and the LOD level of the original mesh. - */ - void Generate_Name(char * root,int index,GeometryExportContextClass & context); - - - /* - ** Get vertex normal. This function should return the normal of a vertex at the - ** specified x,y,z and smoothing_group if one exists. It is used in the algorithm which - ** smooths the vertex normals on the boundaries of meshes. - */ - virtual Point3 Get_Shared_Vertex_Normal(const Point3 & world_space_point,int smgroup) { return Point3(0,0,0); } - - /* - ** Aggregate Model Detection. An "aggregate" is an external W3D model that we are requesting - ** to be attached to a bone in the model being exported. In order for our LOD system to work - ** properly, some special handling of aggregates is required (they must be added into the model - ** as "additional models" rather than being placed in the normal LOD arrays). This virtual - ** can be used to detect "aggregate" models. - */ - virtual bool Is_Aggregate(void) { return false; } - - /* - ** Proxy Detection. A "proxy" is a reference (by name) to an external game object that should - ** be instantiated at the specified transform. Like the aggregates, these had to unfortunately - ** be handled with special cases and therefore have this virtual function devoted solely to them. - */ - virtual bool Is_Proxy(void) { return false; } - - /* - ** Virtual Constructor - */ - static GeometryExportTaskClass * Create_Task(INode * node,GeometryExportContextClass & context); - - /* - ** Pre-Export Optimization of a set of geometry export tasks. This does things like - ** separating multi-material meshes, combining small meshes which are nearby and use the - ** same material, etc. - */ - static void Optimize_Geometry( DynamicVectorClass & tasks, - GeometryExportContextClass & context ); - -protected: - - /* - ** Internal RTTI - */ - enum - { - MESH = 0, - COLLISIONBOX, - DAZZLE, - NULLOBJ, - AGGREGATE, - PROXY, - }; - virtual int Get_Geometry_Type(void) = 0; - -protected: - - char Name[W3D_NAME_LEN]; - char ContainerName[W3D_NAME_LEN]; - int BoneIndex; - - Matrix3 ExportSpace; - TimeValue CurTime; - INode * Node; -}; - - - -#endif //GEOMETRYEXPORTTASK_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/gmtldlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/gmtldlg.cpp deleted file mode 100644 index e7d393341c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gmtldlg.cpp +++ /dev/null @@ -1,1235 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/gmtldlg.cpp 18 5/27/98 8:34a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : GMTLDLG.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/26/97 * - * * - * Last Update : June 26, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * GameMtlDlg::GameMtlDlg -- constructor * - * GameMtlDlg::~GameMtlDlg -- destructor! * - * GameMtlDlg::ClassID -- Returns the ClassID of GameMtl * - * GameMtlDlg::Invalidate -- causes the dialog to be redrawn * - * GameMtlDlg::ReloadDialog -- Updates the values in all of the dialog's controls * - * GameMtlDlg::SetTime -- Sets the time value, updates the material and the dialog * - * GameMtlDlg::PanelProc -- Windows Message handler * - * PanelDlgProc -- Windows Proc which thunks into GameMtlDlg::PanelProc * - * GameMtlDlg::LoadDialog -- Sets the state of all of the dialog's controls * - * GameMtlDlg::UpdateMtlDisplay -- Informs MAX that the material parameters have changed * - * GameMtlDlg::ActivateDlg -- Activates and deactivates the dialog * - * GameMtlDlg::SetThing -- Sets the material to be edited * - * GameMtlDlg::BuildDialog -- Adds the dialog to the material editor * - * GameMtlDlg::UpdateTexmapDisplay -- Updates the texture map buttons * - * NotesDlgProc -- Dialog Proc which thunks to GameMtlDlg::NotesProc * - * GameMtlDlg::NotesProc -- Dialog Proc for the Notes panel * - * HintsDlgProc -- Dialog proc which thunks to GameMtlDlg::HintsProc * - * GameMtlDlg::HintsProc -- Dialog Proc for the hints panel * - * GameMtlDlg::PsxProc -- Dialog proc for the PSX options panel * - * PsxDlgProc -- Dialog proc which thunks into GameMtlDlg::PsxProc * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include -#include -#include -#include - -#include "gmtldlg.h" -#include "gamemtl.h" -#include "gamemaps.h" -#include "dllmain.h" -#include "resource.h" -#include "w3d_file.h" - - - -static inline float PcToFrac(int pc) -{ - return (float)pc/100.0f; -} - -static inline int FracToPc(float f) -{ - if (f<0.0) return (int)(100.0f*f - .5f); - else return (int) (100.0f*f + .5f); -} - - -/*********************************************************************************************** - * GameMtlDlg::GameMtlDlg -- constructor * - * * - * INPUT: * - * hwMtlEdit - windows handle of the MAX material editor * - * imp - Interface object for MAX materials and textures * - * m - pointer to a GameMtl to be edited * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -GameMtlDlg::GameMtlDlg(HWND hwMtlEdit, IMtlParams *imp, GameMtl *m) -{ - HwndEdit = hwMtlEdit; - HwndPanel = NULL; - HwndHints = NULL; - HwndPsx = NULL; - HwndNotes = NULL; - HpalOld = NULL; - - TheMtl = m; - IParams = imp; - Valid = FALSE; - IsActive = 0; - InstCopy = FALSE; - - DiffuseSwatch = NULL; - SpecularSwatch = NULL; - - AmbientCoeffSwatch = NULL; - DiffuseCoeffSwatch = NULL; - SpecularCoeffSwatch = NULL; - EmissiveCoeffSwatch = NULL; - - DCTFramesSpin = NULL; - DITFramesSpin = NULL; - SCTFramesSpin = NULL; - SITFramesSpin = NULL; - - DCTRateSpin = NULL; - DITRateSpin = NULL; - SCTRateSpin = NULL; - SITRateSpin = NULL; - - OpacitySpin = NULL; - TranslucencySpin = NULL; - ShininessSpin = NULL; - FogSpin = NULL; -} - -/*********************************************************************************************** - * GameMtlDlg::~GameMtlDlg -- destructor! * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -GameMtlDlg::~GameMtlDlg() -{ - if (DiffuseSwatch) { - ReleaseIColorSwatch(DiffuseSwatch); - DiffuseSwatch = NULL; - } - - if (SpecularSwatch) { - ReleaseIColorSwatch(SpecularSwatch); - SpecularSwatch = NULL; - } - - if (AmbientCoeffSwatch) { - ReleaseIColorSwatch(AmbientCoeffSwatch); - AmbientCoeffSwatch = NULL; - } - - if (DiffuseCoeffSwatch) { - ReleaseIColorSwatch(DiffuseCoeffSwatch); - DiffuseCoeffSwatch = NULL; - } - - if (SpecularCoeffSwatch) { - ReleaseIColorSwatch(SpecularCoeffSwatch); - SpecularCoeffSwatch = NULL; - } - - if (EmissiveCoeffSwatch) { - ReleaseIColorSwatch(EmissiveCoeffSwatch); - EmissiveCoeffSwatch = NULL; - } - - if (HwndPanel) { - HDC hdc = GetDC(HwndPanel); - GetGPort()->RestorePalette(hdc, HpalOld); - ReleaseDC(HwndPanel,hdc); - } - - TheMtl->SetFlag(GAMEMTL_ROLLUP1_OPEN,IParams->IsRollupPanelOpen(HwndPanel)); - TheMtl->SetFlag(GAMEMTL_ROLLUP2_OPEN,IParams->IsRollupPanelOpen(HwndPsx)); - TheMtl->SetFlag(GAMEMTL_ROLLUP3_OPEN,IParams->IsRollupPanelOpen(HwndHints)); - TheMtl->SetFlag(GAMEMTL_ROLLUP4_OPEN,IParams->IsRollupPanelOpen(HwndNotes)); - TheMtl->RollScroll = IParams->GetRollupScrollPos(); - TheMtl->SetParamDlg(NULL); - - IParams->UnRegisterDlgWnd(HwndPanel); - IParams->DeleteRollupPage(HwndPanel); - HwndPanel = NULL; - - IParams->UnRegisterDlgWnd(HwndPsx); - IParams->DeleteRollupPage(HwndPsx); - HwndPsx = NULL; - - IParams->UnRegisterDlgWnd(HwndHints); - IParams->DeleteRollupPage(HwndHints); - HwndHints = NULL; - - IParams->UnRegisterDlgWnd(HwndNotes); - IParams->DeleteRollupPage(HwndNotes); - HwndNotes = NULL; -} - - -/*********************************************************************************************** - * GameMtlDlg::ClassID -- Returns the ClassID of GameMtl * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -Class_ID GameMtlDlg::ClassID() -{ - return GameMaterialClassID; -} - -/*********************************************************************************************** - * GameMtlDlg::Invalidate -- causes the dialog to be redrawn * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::Invalidate() -{ - Valid = FALSE; - InvalidateRect(HwndPanel,NULL,0); - InvalidateRect(HwndPsx,NULL,0); - InvalidateRect(HwndHints,NULL,0); - InvalidateRect(HwndNotes,NULL,0); -} - -/*********************************************************************************************** - * GameMtlDlg::ReloadDialog -- Updates the values in all of the dialog's controls * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::ReloadDialog() -{ - Interval v; - TheMtl->Update(IParams->GetTime(),v); - LoadDialog(FALSE); -} - -/*********************************************************************************************** - * GameMtlDlg::SetTime -- Sets the time value, updates the material and the dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::SetTime(TimeValue t) -{ - if (t!=CurTime) { - CurTime = t; - Interval v; - TheMtl->Update(IParams->GetTime(),v); - LoadDialog(TRUE); - } -} - - -/*********************************************************************************************** - * GameMtlDlg::PanelProc -- Windows Message handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -BOOL GameMtlDlg::PanelProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam ) -{ - int id = LOWORD(wParam); - int code = HIWORD(wParam); - int mtype; - - switch (msg) { - - case WM_INITDIALOG: - { - HDC theHDC = GetDC(hwndDlg); - HpalOld = GetGPort()->PlugPalette(theHDC); - ReleaseDC(hwndDlg,theHDC); - - DiffuseSwatch = GetIColorSwatch(GetDlgItem(hwndDlg, IDC_DIFFUSE_COLOR),TheMtl->GetDiffuse(),Get_String(IDS_DIFFUSE_COLOR)); - SpecularSwatch = GetIColorSwatch(GetDlgItem(hwndDlg, IDC_SPECULAR_COLOR),TheMtl->GetSpecular(),Get_String(IDS_SPECULAR_COLOR)); - - AmbientCoeffSwatch = GetIColorSwatch(GetDlgItem(hwndDlg, IDC_AMBIENT_COEFF),TheMtl->GetAmbientCoeff(),Get_String(IDS_AMBIENT_COEFF)); - DiffuseCoeffSwatch = GetIColorSwatch(GetDlgItem(hwndDlg, IDC_DIFFUSE_COEFF),TheMtl->GetDiffuseCoeff(),Get_String(IDS_DIFFUSE_COEFF)); - SpecularCoeffSwatch = GetIColorSwatch(GetDlgItem(hwndDlg, IDC_SPECULAR_COEFF),TheMtl->GetSpecularCoeff(),Get_String(IDS_SPECULAR_COEFF)); - EmissiveCoeffSwatch = GetIColorSwatch(GetDlgItem(hwndDlg, IDC_EMISSIVE_COEFF),TheMtl->GetEmissiveCoeff(),Get_String(IDS_EMISSIVE_COEFF)); - - DCTFramesSpin = SetupIntSpinner(hwndDlg,IDC_DCT_FRAMES_SPIN,IDC_DCT_FRAMES_EDIT,1,999,TheMtl->DCTFrames); - DITFramesSpin = SetupIntSpinner(hwndDlg,IDC_DIT_FRAMES_SPIN,IDC_DIT_FRAMES_EDIT,1,999,TheMtl->DITFrames); - SCTFramesSpin = SetupIntSpinner(hwndDlg,IDC_SCT_FRAMES_SPIN,IDC_SCT_FRAMES_EDIT,1,999,TheMtl->SCTFrames); - SITFramesSpin = SetupIntSpinner(hwndDlg,IDC_SIT_FRAMES_SPIN,IDC_SIT_FRAMES_EDIT,1,999,TheMtl->SITFrames); - - DCTRateSpin = SetupFloatSpinner(hwndDlg,IDC_DCT_RATE_SPIN,IDC_DCT_RATE_EDIT,0.0f,60.0f,TheMtl->DCTFrameRate,5.0f); - DITRateSpin = SetupFloatSpinner(hwndDlg,IDC_DIT_RATE_SPIN,IDC_DIT_RATE_EDIT,0.0f,60.0f,TheMtl->DITFrameRate,5.0f); - SCTRateSpin = SetupFloatSpinner(hwndDlg,IDC_SCT_RATE_SPIN,IDC_SCT_RATE_EDIT,0.0f,60.0f,TheMtl->SCTFrameRate,5.0f); - SITRateSpin = SetupFloatSpinner(hwndDlg,IDC_SIT_RATE_SPIN,IDC_SIT_RATE_EDIT,0.0f,60.0f,TheMtl->SITFrameRate,5.0f); - - OpacitySpin = SetupFloatSpinner(hwndDlg,IDC_OPACITY_SPIN,IDC_OPACITY_EDIT,0.0f,1.0f,TheMtl->GetOpacity(),0.01f); - TranslucencySpin = SetupFloatSpinner(hwndDlg,IDC_TRANSLUCENCY_SPIN,IDC_TRANSULCENCY_EDIT,0.0f,1.0f,TheMtl->GetTranslucency(),0.01f); - ShininessSpin = SetupFloatSpinner(hwndDlg,IDC_SHININESS_SPIN,IDC_SHININESS_EDIT,1.0f,1000.0f,TheMtl->GetShininess(),1.0f); - FogSpin = SetupFloatSpinner(hwndDlg,IDC_FOG_SPIN,IDC_FOG_EDIT,0.0f,1.0f,TheMtl->FogCoeff,0.01f); - - SendDlgItemMessage( hwndDlg, IDC_DCT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_UV_MAPPING)); - SendDlgItemMessage( hwndDlg, IDC_DCT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_ENVIRONMENT_MAPPING) ); - - SendDlgItemMessage( hwndDlg, IDC_DIT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_UV_MAPPING)); - SendDlgItemMessage( hwndDlg, IDC_DIT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_ENVIRONMENT_MAPPING) ); - - SendDlgItemMessage( hwndDlg, IDC_SCT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_UV_MAPPING)); - SendDlgItemMessage( hwndDlg, IDC_SCT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_ENVIRONMENT_MAPPING) ); - - SendDlgItemMessage( hwndDlg, IDC_SIT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_UV_MAPPING)); - SendDlgItemMessage( hwndDlg, IDC_SIT_MAPPING_COMBO, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) Get_String(IDS_ENVIRONMENT_MAPPING) ); - - /* Installing a windproc for texmap buttons which will handle drag-n-drop - HWND hw = GetDlgItem(hwndDlg, texMapID[i]); - WNDPROC oldp = (WNDPROC)GetWindowLong(hw, GWL_WNDPROC); - SetWindowLong( hw, GWL_WNDPROC, (LONG)TexSlotWndProc); - SetWindowLong( hw, GWL_USERDATA, (LONG)oldp); - */ - - return TRUE; - } - break; - - case WM_COMMAND: - { - switch (id) { - - case IDC_DCT_BUTTON: - { - BitmapInfo bmi; - BitmapTex * texture; - - if (TheManager->SelectFileInput(&bmi, HwndEdit)) { - texture = NewDefaultBitmapTex(); - if (texture) { - texture->SetMapName((char *)bmi.Name()); - TheMtl->SetSubTexmap(ID_DI,texture); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - } - } - } - break; - - case IDC_DIT_BUTTON: - { - BitmapInfo bmi; - BitmapTex * texture; - - if (TheManager->SelectFileInput(&bmi, HwndEdit)) { - texture = NewDefaultBitmapTex(); - if (texture) { - texture->SetMapName((char *)bmi.Name()); - TheMtl->SetSubTexmap(ID_SI,texture); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - } - } - } - break; - - case IDC_SCT_BUTTON: - { - BitmapInfo bmi; - BitmapTex * texture; - - if (TheManager->SelectFileInput(&bmi, HwndEdit)) { - texture = NewDefaultBitmapTex(); - if (texture) { - texture->SetMapName((char *)bmi.Name()); - TheMtl->SetSubTexmap(ID_SP,texture); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - } - } - } - break; - - case IDC_SIT_BUTTON: - { - BitmapInfo bmi; - BitmapTex * texture; - - if (TheManager->SelectFileInput(&bmi, HwndEdit)) { - texture = NewDefaultBitmapTex(); - if (texture) { - texture->SetMapName((char *)bmi.Name()); - TheMtl->SetSubTexmap(ID_RL,texture); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - } - } - } - break; - - case IDC_MAPON_DCT: - TheMtl->EnableMap(ID_DI,GetCheckBox(hwndDlg, id)); - if (!GetCheckBox(hwndDlg,id)) TheMtl->SetSubTexmap(ID_DI,NULL); - UpdateTexmapDisplay(ID_DI); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - break; - case IDC_MAPON_DIT: - TheMtl->EnableMap(ID_SI,GetCheckBox(hwndDlg, id)); - if (!GetCheckBox(hwndDlg,id)) TheMtl->SetSubTexmap(ID_SI,NULL); - UpdateTexmapDisplay(ID_SI); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - break; - case IDC_MAPON_SCT: - TheMtl->EnableMap(ID_SP,GetCheckBox(hwndDlg, id)); - if (!GetCheckBox(hwndDlg,id)) TheMtl->SetSubTexmap(ID_SP,NULL); - UpdateTexmapDisplay(ID_SP); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - break; - case IDC_MAPON_SIT: - TheMtl->EnableMap(ID_RL,GetCheckBox(hwndDlg, id)); - if (!GetCheckBox(hwndDlg,id)) TheMtl->SetSubTexmap(ID_RL,NULL); - UpdateTexmapDisplay(ID_RL); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - break; - case IDC_USE_ALPHA_CHECK: - TheMtl->SetAttribute(GAMEMTL_USE_ALPHA,GetCheckBox(hwndDlg,IDC_USE_ALPHA_CHECK)); - UpdateMtlDisplay(); - TheMtl->NotifyChanged(); - break; - case IDC_USE_SORTING_CHECK: - TheMtl->SetAttribute(GAMEMTL_USE_SORTING,GetCheckBox(hwndDlg,IDC_USE_SORTING_CHECK)); - break; - case IDC_DCT_MAPPING_COMBO: - mtype = SendDlgItemMessage(hwndDlg,IDC_DCT_MAPPING_COMBO,CB_GETCURSEL,0,0); - TheMtl->DCTMappingType = mtype; - break; - case IDC_DIT_MAPPING_COMBO: - mtype = SendDlgItemMessage(hwndDlg,IDC_DIT_MAPPING_COMBO,CB_GETCURSEL,0,0); - TheMtl->DITMappingType = mtype; - break; - case IDC_SCT_MAPPING_COMBO: - mtype = SendDlgItemMessage(hwndDlg,IDC_SCT_MAPPING_COMBO,CB_GETCURSEL,0,0); - TheMtl->SCTMappingType = mtype; - break; - case IDC_SIT_MAPPING_COMBO: - mtype = SendDlgItemMessage(hwndDlg,IDC_SIT_MAPPING_COMBO,CB_GETCURSEL,0,0); - TheMtl->SITMappingType = mtype; - break; - case IDC_VIEWPORT_DISPLAY_CHECK: - TheMtl->Set_Viewport_Display_Status(GetCheckBox(hwndDlg,IDC_VIEWPORT_DISPLAY_CHECK)); - TheMtl->NotifyChanged(); - UpdateMtlDisplay(); - break; - } - } - break; - - case CC_COLOR_CHANGE: - { - // just update all of the colors - TheMtl->Diffuse = DiffuseSwatch->GetColor(); - TheMtl->Specular = SpecularSwatch->GetColor(); - TheMtl->AmbientCoeff = AmbientCoeffSwatch->GetColor(); - TheMtl->DiffuseCoeff = DiffuseCoeffSwatch->GetColor(); - TheMtl->SpecularCoeff = SpecularCoeffSwatch->GetColor(); - TheMtl->EmissiveCoeff = EmissiveCoeffSwatch->GetColor(); - - TheMtl->NotifyChanged(); - UpdateMtlDisplay(); - } - break; - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(hwndDlg,msg,wParam,lParam); - } - return FALSE; - - case CC_SPINNER_CHANGE: - { - TheMtl->DCTFrames = DCTFramesSpin->GetIVal(); - TheMtl->DITFrames = DITFramesSpin->GetIVal(); - TheMtl->SCTFrames = SCTFramesSpin->GetIVal(); - TheMtl->SITFrames = SITFramesSpin->GetIVal(); - - TheMtl->DCTFrameRate = DCTRateSpin->GetFVal(); - TheMtl->DITFrameRate = DITRateSpin->GetFVal(); - TheMtl->SCTFrameRate = SCTRateSpin->GetFVal(); - TheMtl->SITFrameRate = SITRateSpin->GetFVal(); - - TheMtl->SetOpacity(OpacitySpin->GetFVal()); - TheMtl->SetTranslucency(TranslucencySpin->GetFVal()); - TheMtl->SetShininess(ShininessSpin->GetFVal()); - TheMtl->FogCoeff = FogSpin->GetFVal(); - - TheMtl->NotifyChanged(); - UpdateMtlDisplay(); - } - break; - - case CC_SPINNER_BUTTONUP: - { - #if 0 - UpdateMtlDisplay(); - #endif - } - break; - - case WM_PAINT: - { - if (!Valid) { - Valid = TRUE; - ReloadDialog(); - } - } - return FALSE; - - case WM_CLOSE: - break; - - case WM_DESTROY: - - TheMtl->DCTFrames = DCTFramesSpin->GetIVal(); - TheMtl->DITFrames = DITFramesSpin->GetIVal(); - TheMtl->SCTFrames = SCTFramesSpin->GetIVal(); - TheMtl->SITFrames = SITFramesSpin->GetIVal(); - - TheMtl->DCTFrameRate = DCTRateSpin->GetFVal(); - TheMtl->DITFrameRate = DITRateSpin->GetFVal(); - TheMtl->SCTFrameRate = SCTRateSpin->GetFVal(); - TheMtl->SITFrameRate = SITRateSpin->GetFVal(); - - TheMtl->SetOpacity(OpacitySpin->GetFVal()); - TheMtl->SetTranslucency(TranslucencySpin->GetFVal()); - TheMtl->SetShininess(ShininessSpin->GetFVal()); - TheMtl->FogCoeff = FogSpin->GetFVal(); - - ReleaseISpinner(DCTFramesSpin); - ReleaseISpinner(DITFramesSpin); - ReleaseISpinner(SCTFramesSpin); - ReleaseISpinner(SITFramesSpin); - ReleaseISpinner(DCTRateSpin); - ReleaseISpinner(DITRateSpin); - ReleaseISpinner(SCTRateSpin); - ReleaseISpinner(SITRateSpin); - ReleaseISpinner(OpacitySpin); - ReleaseISpinner(TranslucencySpin); - ReleaseISpinner(ShininessSpin); - ReleaseISpinner(FogSpin); - - DCTFramesSpin = DITFramesSpin = SCTFramesSpin = SITFramesSpin = NULL; - DCTRateSpin = DITRateSpin = SCTRateSpin = SITRateSpin = NULL; - OpacitySpin = TranslucencySpin = ShininessSpin = FogSpin = NULL; - - break; - - } - - return FALSE; -} - - -/*********************************************************************************************** - * PanelDlgProc -- Windows Proc which thunks into GameMtlDlg::PanelProc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -static BOOL CALLBACK PanelDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - GameMtlDlg *theDlg; - - if (msg==WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndPanel = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - BOOL res; - theDlg->IsActive = 1; - res = theDlg->PanelProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - return res; -} - -/*********************************************************************************************** - * GameMtlDlg::NotesProc -- Dialog Proc for the Notes panel * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -BOOL GameMtlDlg::NotesProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - int id = LOWORD(wParam); - int code = HIWORD(wParam); - - switch (msg) { - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(hwndDlg,msg,wParam,lParam); - return FALSE; - } - - case WM_COMMAND: - { - int i = lParam; - } - break; - - } - return FALSE; -} - - -/*********************************************************************************************** - * NotesDlgProc -- Dialog Proc which thunks to GameMtlDlg::NotesProc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -static BOOL CALLBACK NotesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - GameMtlDlg *theDlg; - - if (msg==WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndNotes = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - BOOL res; - theDlg->IsActive = 1; - res = theDlg->NotesProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - return res; -} - - -/*********************************************************************************************** - * GameMtlDlg::HintsProc -- Dialog Proc for the hints panel * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/98 GTH : Created. * - *=============================================================================================*/ -BOOL GameMtlDlg::HintsProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - int id = LOWORD(wParam); - int code = HIWORD(wParam); - - switch (msg) { - - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(hwndDlg,msg,wParam,lParam); - return FALSE; - } - - case WM_COMMAND: - { - switch(id) - { - case IDC_DIT_OVER_DCT_CHECK: - TheMtl->SetAttribute(GAMEMTL_DIT_OVER_DCT, GetCheckBox(hwndDlg, IDC_DIT_OVER_DCT_CHECK)); - break; - - case IDC_SIT_OVER_SCT_CHECK: - TheMtl->SetAttribute(GAMEMTL_SIT_OVER_SCT, GetCheckBox(hwndDlg, IDC_SIT_OVER_SCT_CHECK)); - break; - - case IDC_DIT_OVER_DIG_CHECK: - TheMtl->SetAttribute(GAMEMTL_DIT_OVER_DIG, GetCheckBox(hwndDlg, IDC_DIT_OVER_DIG_CHECK)); - break; - - case IDC_SIT_OVER_SIG_CHECK: - TheMtl->SetAttribute(GAMEMTL_SIT_OVER_SIG, GetCheckBox(hwndDlg, IDC_SIT_OVER_SIG_CHECK)); - break; - - case IDC_FAST_SPECULAR_AFTER_ALPHA_CHECK: - TheMtl->SetAttribute(GAMEMTL_FAST_SPECULAR_AFTER_ALPHA, GetCheckBox(hwndDlg, IDC_FAST_SPECULAR_AFTER_ALPHA_CHECK)); - break; - } - } - break; - } - return FALSE; -} - - -/*********************************************************************************************** - * HintsDlgProc -- Dialog proc which thunks to GameMtlDlg::HintsProc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/30/98 GTH : Created. * - *=============================================================================================*/ -static BOOL CALLBACK HintsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - GameMtlDlg *theDlg; - - if (msg==WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndHints = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - BOOL res; - theDlg->IsActive = 1; - res = theDlg->HintsProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - return res; -} - - -/*********************************************************************************************** - * GameMtlDlg::PsxProc -- Dialog proc for the PSX options panel * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/31/98 GTH : Created. * - *=============================================================================================*/ -BOOL GameMtlDlg::PsxProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - int id = LOWORD(wParam); - int code = HIWORD(wParam); - - switch (msg) { - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - { - IParams->RollupMouseMessage(hwndDlg,msg,wParam,lParam); - return FALSE; - } - - case WM_COMMAND: - { - switch(id) - { - case IDC_NO_TRANS: - TheMtl->SetMaskedAttribute(GAMEMTL_PSX_TRANS_MASK,0); - break; - - case IDC_100_TRANS: - TheMtl->SetMaskedAttribute(GAMEMTL_PSX_TRANS_MASK,GAMEMTL_PSX_100_TRANS); - break; - - case IDC_50_TRANS: - TheMtl->SetMaskedAttribute(GAMEMTL_PSX_TRANS_MASK,GAMEMTL_PSX_50_TRANS); - break; - - case IDC_25_TRANS: - TheMtl->SetMaskedAttribute(GAMEMTL_PSX_TRANS_MASK,GAMEMTL_PSX_25_TRANS); - break; - - case IDC_MINUS_100_TRANS: - TheMtl->SetMaskedAttribute(GAMEMTL_PSX_TRANS_MASK,GAMEMTL_PSX_MINUS_100_TRANS); - break; - - case IDC_NO_RT_LIGHTING: - TheMtl->SetAttribute(GAMEMTL_PSX_NO_RT_LIGHTING, GetCheckBox(hwndDlg, IDC_NO_RT_LIGHTING)); - break; - } - } - break; - } - return FALSE; -} - - -/*********************************************************************************************** - * PsxDlgProc -- Dialog proc which thunks into GameMtlDlg::PsxProc * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/31/98 GTH : Created. * - *=============================================================================================*/ -static BOOL CALLBACK PsxDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - GameMtlDlg *theDlg; - - if (msg==WM_INITDIALOG) { - theDlg = (GameMtlDlg*)lParam; - theDlg->HwndPsx = hwndDlg; - SetWindowLong(hwndDlg, GWL_USERDATA,lParam); - } else { - if ((theDlg = (GameMtlDlg *)GetWindowLong(hwndDlg, GWL_USERDATA) ) == NULL) { - return FALSE; - } - } - - BOOL res; - theDlg->IsActive = 1; - res = theDlg->PsxProc(hwndDlg,msg,wParam,lParam); - theDlg->IsActive = 0; - return res; -} - - -/*********************************************************************************************** - * GameMtlDlg::LoadDialog -- Sets the state of all of the dialog's controls * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::LoadDialog(BOOL draw) -{ - - /* - ** Set the state of the entire panel based on the current material. - */ - if (TheMtl && HwndPanel) { - - /* - ** Init all of the color swatches - */ - if (DiffuseSwatch) { - DiffuseSwatch->InitColor(TheMtl->GetDiffuse()); - } - if (SpecularSwatch) { - SpecularSwatch->InitColor(TheMtl->GetSpecular()); - } - if (AmbientCoeffSwatch) { - AmbientCoeffSwatch->InitColor(TheMtl->GetAmbientCoeff()); - } - if (DiffuseCoeffSwatch) { - DiffuseCoeffSwatch->InitColor(TheMtl->GetDiffuseCoeff()); - } - if (SpecularCoeffSwatch) { - SpecularCoeffSwatch->InitColor(TheMtl->GetSpecularCoeff()); - } - if (EmissiveCoeffSwatch) { - EmissiveCoeffSwatch->InitColor(TheMtl->GetEmissiveCoeff()); - } - - /* - ** Checkboxes - */ - SetCheckBox(HwndPanel,IDC_USE_ALPHA_CHECK, TheMtl->GetAttribute(GAMEMTL_USE_ALPHA)); - SetCheckBox(HwndPanel,IDC_USE_SORTING_CHECK, TheMtl->GetAttribute(GAMEMTL_USE_SORTING)); - SetCheckBox(HwndPanel,IDC_VIEWPORT_DISPLAY_CHECK,TheMtl->Get_Viewport_Display_Status()); - - /* - ** Texture maps enable checks. - */ - SetCheckBox(HwndPanel,IDC_MAPON_DCT, TheMtl->SubTexmapOn(ID_DI)); - SetCheckBox(HwndPanel,IDC_MAPON_DIT, TheMtl->SubTexmapOn(ID_SI)); - SetCheckBox(HwndPanel,IDC_MAPON_SCT, TheMtl->SubTexmapOn(ID_SP)); - SetCheckBox(HwndPanel,IDC_MAPON_SIT, TheMtl->SubTexmapOn(ID_RL)); - - /* - ** Mapping types - */ - SendDlgItemMessage( HwndPanel, IDC_DCT_MAPPING_COMBO, CB_SETCURSEL, TheMtl->DCTMappingType, 0 ); - SendDlgItemMessage( HwndPanel, IDC_DIT_MAPPING_COMBO, CB_SETCURSEL, TheMtl->DITMappingType, 0 ); - SendDlgItemMessage( HwndPanel, IDC_SCT_MAPPING_COMBO, CB_SETCURSEL, TheMtl->SCTMappingType, 0 ); - SendDlgItemMessage( HwndPanel, IDC_SIT_MAPPING_COMBO, CB_SETCURSEL, TheMtl->SITMappingType, 0 ); - - /* - ** Texture animation parameters - */ - DCTFramesSpin->SetValue(TheMtl->DCTFrames,FALSE); - DITFramesSpin->SetValue(TheMtl->DITFrames,FALSE); - SCTFramesSpin->SetValue(TheMtl->SCTFrames,FALSE); - SITFramesSpin->SetValue(TheMtl->SITFrames,FALSE); - - DCTRateSpin->SetValue(TheMtl->DCTFrameRate,FALSE); - DITRateSpin->SetValue(TheMtl->DITFrameRate,FALSE); - SCTRateSpin->SetValue(TheMtl->SCTFrameRate,FALSE); - SITRateSpin->SetValue(TheMtl->SITFrameRate,FALSE); - - /* - ** Opacity, translucency, etc - */ - OpacitySpin->SetValue(TheMtl->Opacity,FALSE); - TranslucencySpin->SetValue(TheMtl->Translucency,FALSE); - ShininessSpin->SetValue(TheMtl->Shininess,FALSE); - FogSpin->SetValue(TheMtl->FogCoeff,FALSE); - - /* - ** Init the Psx flags state - */ - SetCheckBox(HwndPsx,IDC_NO_RT_LIGHTING, TheMtl->GetAttribute(GAMEMTL_PSX_NO_RT_LIGHTING)); - - SetCheckBox(HwndPsx,IDC_NO_TRANS, false); - SetCheckBox(HwndPsx,IDC_100_TRANS, false); - SetCheckBox(HwndPsx,IDC_50_TRANS, false); - SetCheckBox(HwndPsx,IDC_25_TRANS, false); - SetCheckBox(HwndPsx,IDC_MINUS_100_TRANS, false); - - switch (TheMtl->GetMaskedAttribute(GAMEMTL_PSX_TRANS_MASK)) { - case 0: - SetCheckBox(HwndPsx,IDC_NO_TRANS,true); - break; - case GAMEMTL_PSX_100_TRANS: - SetCheckBox(HwndPsx,IDC_100_TRANS,true); - break; - case GAMEMTL_PSX_50_TRANS: - SetCheckBox(HwndPsx,IDC_50_TRANS,true); - break; - case GAMEMTL_PSX_25_TRANS: - SetCheckBox(HwndPsx,IDC_25_TRANS,true); - break; - case GAMEMTL_PSX_MINUS_100_TRANS: - SetCheckBox(HwndPsx,IDC_MINUS_100_TRANS,true); - break; - } - - - /* - ** Init the Hints state - */ - SetCheckBox(HwndHints,IDC_DIT_OVER_DCT_CHECK, TheMtl->GetAttribute(GAMEMTL_DIT_OVER_DCT)); - SetCheckBox(HwndHints,IDC_SIT_OVER_SCT_CHECK, TheMtl->GetAttribute(GAMEMTL_SIT_OVER_SCT)); - SetCheckBox(HwndHints,IDC_DIT_OVER_DIG_CHECK, TheMtl->GetAttribute(GAMEMTL_DIT_OVER_DIG)); - SetCheckBox(HwndHints,IDC_SIT_OVER_SIG_CHECK, TheMtl->GetAttribute(GAMEMTL_SIT_OVER_SIG)); - SetCheckBox(HwndHints,IDC_FAST_SPECULAR_AFTER_ALPHA_CHECK, TheMtl->GetAttribute(GAMEMTL_FAST_SPECULAR_AFTER_ALPHA)); - - /* - ** Init the texmaps state - */ - for (int i=0; iMtlChanged(); -} - - -/*********************************************************************************************** - * GameMtlDlg::ActivateDlg -- Activates and deactivates the dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::ActivateDlg(BOOL onOff) -{ - if (DiffuseSwatch) { - DiffuseSwatch->Activate(onOff); - } - if (SpecularSwatch) { - SpecularSwatch->Activate(onOff); - } - if (AmbientCoeffSwatch) { - AmbientCoeffSwatch->Activate(onOff); - } - if (DiffuseCoeffSwatch) { - DiffuseCoeffSwatch->Activate(onOff); - } - if (SpecularCoeffSwatch) { - SpecularCoeffSwatch->Activate(onOff); - } - if (EmissiveCoeffSwatch) { - EmissiveCoeffSwatch->Activate(onOff); - } -} - -/*********************************************************************************************** - * GameMtlDlg::SetThing -- Sets the material to be edited * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::SetThing(ReferenceTarget *m) -{ - assert (m->SuperClassID()==MATERIAL_CLASS_ID); - assert (m->ClassID()==GameMaterialClassID); - - if (TheMtl) { - TheMtl->ParamPanel = NULL; - } - - TheMtl = (GameMtl *)m; - - if (TheMtl) { - TheMtl->ParamPanel = this; - } - - LoadDialog(TRUE); - - if (HwndPanel && DiffuseSwatch) { - DiffuseSwatch->InitColor(TheMtl->GetDiffuse()); - } - if (HwndPanel && SpecularSwatch) { - SpecularSwatch->InitColor(TheMtl->GetSpecular()); - } - if (HwndPanel && AmbientCoeffSwatch) { - AmbientCoeffSwatch->InitColor(TheMtl->GetAmbientCoeff()); - } - if (HwndPanel && DiffuseCoeffSwatch) { - DiffuseCoeffSwatch->InitColor(TheMtl->GetDiffuseCoeff()); - } - if (HwndPanel && SpecularCoeffSwatch) { - SpecularCoeffSwatch->InitColor(TheMtl->GetSpecularCoeff()); - } - if (HwndPanel && EmissiveCoeffSwatch) { - EmissiveCoeffSwatch->InitColor(TheMtl->GetEmissiveCoeff()); - } -} - -/*********************************************************************************************** - * GameMtlDlg::BuildDialog -- Adds the dialog to the material editor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::BuildDialog() -{ - if ((TheMtl->Flags&(GAMEMTL_ROLLUP_FLAGS))==0) { - TheMtl->SetFlag(GAMEMTL_ROLLUP1_OPEN,TRUE); - } - - HwndPanel = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_PANEL), - PanelDlgProc, - Get_String(IDS_PARAMETERS), - (LPARAM)this, - (TheMtl->GetFlag(GAMEMTL_ROLLUP1_OPEN) ? 0:APPENDROLL_CLOSED) - ); - - HwndPsx = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_PSX_PANEL), - PsxDlgProc, - Get_String(IDS_PSX_OPTIONS), - (LPARAM)this, - (TheMtl->GetFlag(GAMEMTL_ROLLUP2_OPEN) ? 0:APPENDROLL_CLOSED) - ); - - HwndHints = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_GAMEMTL_HINTS_PANEL), - HintsDlgProc, - Get_String(IDS_MATERIAL_HINTS), - (LPARAM)this, - (TheMtl->GetFlag(GAMEMTL_ROLLUP3_OPEN) ? 0:APPENDROLL_CLOSED) - ); - - HwndNotes = IParams->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_MATERIAL_NOTES_PANEL), - NotesDlgProc, - Get_String(IDS_NOTES), - (LPARAM)this, - (TheMtl->GetFlag(GAMEMTL_ROLLUP4_OPEN) ? 0:APPENDROLL_CLOSED) - ); - - IParams->SetRollupScrollPos(TheMtl->RollScroll); -} - -/*********************************************************************************************** - * GameMtlDlg::UpdateTexmapDisplay -- Updates the texture map buttons * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/26/1997 GH : Created. * - *=============================================================================================*/ -void GameMtlDlg::UpdateTexmapDisplay(int i) -{ - TSTR nm = Get_String(IDS_NONE); - Texmap *texmap = (*TheMtl->Maps)[i].Map; - if (texmap) nm = texmap->GetFullName(); - - // Diffuse Map -> Surrender Diffuse Color Channel - if (i == ID_DI) { - SetCheckBox(HwndPanel, IDC_MAPON_DCT, TheMtl->IsMapEnabled(i)); - SetDlgItemText(HwndPanel, IDC_DCT_BUTTON, nm.data()); - } - - // Self Illumination Map -> Surrender Diffuse Illumination Channel - if (i == ID_SI) { - SetCheckBox(HwndPanel, IDC_MAPON_DIT, TheMtl->IsMapEnabled(i)); - SetDlgItemText(HwndPanel, IDC_DIT_BUTTON, nm.data()); - } - - // Specular Map -> Surrender Specular Color Channel - if (i == ID_SP) { - SetCheckBox(HwndPanel, IDC_MAPON_SCT, TheMtl->IsMapEnabled(i)); - SetDlgItemText(HwndPanel, IDC_SCT_BUTTON, nm.data()); - } - - // Reflection Map -> Surrender Specular Illumination Channel - if (i == ID_RL) { - SetCheckBox(HwndPanel, IDC_MAPON_SIT, TheMtl->IsMapEnabled(i)); - SetDlgItemText(HwndPanel, IDC_SIT_BUTTON, nm.data()); - } - -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/gridsnapmodifier.cpp b/Generals/Code/Tools/WW3D/max2w3d/gridsnapmodifier.cpp deleted file mode 100644 index 5905ff1e56..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gridsnapmodifier.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/gridsnapmodifier.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/01/01 8:29p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#include "max.h" -#include "resource.h" -#include "simpmod.h" -#include "dllmain.h" -#include "iparamb2.h" - - -/* - - WARNING WARNING WARNING PLEASE READ - This modifier was an experiment to see if we could - solve cracks in adjacent meshes by snapping to a world-space grid. It didn't work for a - few reasons: - - I couldn't implement the world space snapping; the SimpleMod code seems to always force - you to work relative to each object. - - Snapping to a grid won't always snap vertices to the same grid. The probability that - it will work is a function of the distance between the points and the grid spacing - -*/ - - - -#define GRIDSNAPMOD_CLASSID Class_ID(0x7a2d399b, 0x1e3d2004) - - -/** -** GridSnapModifierClass -** This modifier will snap all vertices in the geometry being modified to a grid. Its motivation is to -** try to help solve the problem of cracks between adjacent meshes in Renegade levels. This will work -** a lot better if the objects have reset-transforms prior to being processed by this modifier. -*/ -class GridSnapModifierClass : public SimpleMod2 -{ -public: - - GridSnapModifierClass(); - - // From Animatable - void DeleteThis() { delete this; } - void GetClassName(TSTR& s) { s = Get_String(IDS_GRIDSNAPMODIFIER); } - virtual Class_ID ClassID() { return GRIDSNAPMOD_CLASSID; } - void BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev); - void EndEditParams( IObjParam *ip,ULONG flags,Animatable *next); - RefTargetHandle Clone(RemapDir& remap = NoRemap()); - TCHAR *GetObjectName() { return Get_String(IDS_GRIDSNAPMODIFIER);} - IOResult Load(ILoad *iload); - - // Direct paramblock access - int NumParamBlocks() { return 1; } - IParamBlock2* GetParamBlock(int i) { return pblock2; } - IParamBlock2* GetParamBlockByID(BlockID id) { return (pblock2->ID() == id) ? pblock2 : NULL; } - - // From simple mod - Deformer& GetDeformer(TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat); - Interval GetValidity(TimeValue t); - - //RefTargetHandle GetReference(int i) - //void SetReference(int i,RefTargetHandle rtar) - //Animatable * SubAnim(int i) -}; - -/** -** GridSnapDeformerClass -** This is the callback object used by GridSnapModifierClass to implement the actual geometry changes. This -** architecture is required by the SimpleMod base-class. This Deformer simply snaps vertex positions -** to the grid defined by its parameters. -*/ -class GridSnapDeformerClass : public Deformer -{ -public: - GridSnapDeformerClass(void) : GridDimension(0.001f) {} - - void Set_Grid_Dimension(float grid_dim) { GridDimension = grid_dim; } - float Get_Grid_Dimension(void) { return GridDimension; } - - void Set_Matrices(const Matrix3 & tm,const Matrix3 & invtm) { Transform = tm; InvTransform = invtm; } - - virtual Point3 Map(int i,Point3 p) - { - p = p*Transform; - p.x = floor(p.x / GridDimension) * GridDimension; - p.y = floor(p.y / GridDimension) * GridDimension; - p.z = floor(p.z / GridDimension) * GridDimension; - p = p*InvTransform; - - return p; - } - -private: - float GridDimension; - Matrix3 Transform; - Matrix3 InvTransform; -}; - - -/** -** GridSnapModifier Class Descriptor -** This object "links" the plugin into Max's plugin system. It links the Class-ID to a virtual construction -** method. The function Get_Grid_Snap_Modifier_Desc is the only hook to external code. -*/ -class GridSnapModifierClassDesc:public ClassDesc2 -{ -public: - int IsPublic() { return 1; } - void * Create(BOOL loading = FALSE) { return new GridSnapModifierClass; } - const TCHAR * ClassName() { return _T("Grid Snap Modifier"); } - SClass_ID SuperClassID() { return OSM_CLASS_ID; } - Class_ID ClassID() { return GRIDSNAPMOD_CLASSID; } - const TCHAR* Category() { return _T("Westwood Modifiers");} - HINSTANCE HInstance() { return AppInstance; } - const TCHAR * InternalName() { return _T("Westwood GridSnap"); } -}; - -static GridSnapModifierClassDesc _GridSnapModifierDesc; - -ClassDesc* Get_Grid_Snap_Modifier_Desc(void) -{ - return &_GridSnapModifierDesc; -} - - -/* -** ParamBlock2 Setup -*/ -enum -{ - GSM_PARAMS = 0, -}; - -enum -{ - GSM_PARAM_GRIDDIMENSION = 0, -}; - -static ParamBlockDesc2 _GridSnapParamBlockDesc -( - // parameter block settings - GSM_PARAMS,_T("GridSnap Parameters"), 0, &_GridSnapModifierDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, SIMPMOD_PBLOCKREF, - - // dialog box - IDD_GRIDSNAP_PARAMS, IDS_GRIDSNAP_TITLE, 0, 0, NULL, - - // parameters - GSM_PARAM_GRIDDIMENSION, _T("Grid Dimension"), TYPE_FLOAT, P_RESET_DEFAULT, IDS_GRID_DIMENSION, - p_default, 0.001f, - p_range, 0.0001f, 10.0f, - p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, IDC_GRIDDIM_EDIT, IDC_GRIDDIM_SPIN, 0.0001f, - end, - - end -); - - -/******************************************************************************************** -** -** GridSnapModifierClass Implementation -** -********************************************************************************************/ - -GridSnapModifierClass::GridSnapModifierClass() -{ - // create the parameter block, storing in the base-class's pblock variable - _GridSnapModifierDesc.MakeAutoParamBlocks(this); - assert(pblock2); -} - -void GridSnapModifierClass::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev) -{ - this->ip = ip; - - SimpleMod2::BeginEditParams(ip,flags,prev); - _GridSnapModifierDesc.BeginEditParams(ip, this, flags, prev); -} - -void GridSnapModifierClass::EndEditParams( IObjParam *ip,ULONG flags,Animatable *next) -{ - SimpleMod2::EndEditParams(ip,flags,next); - _GridSnapModifierDesc.EndEditParams(ip, this, flags, next); - - this->ip = NULL; -} - -RefTargetHandle GridSnapModifierClass::Clone(RemapDir& remap) -{ - GridSnapModifierClass * newmod = new GridSnapModifierClass(); - newmod->ReplaceReference(SIMPMOD_PBLOCKREF,pblock2->Clone(remap)); - newmod->SimpleModClone(this); - return(newmod); -} - -IOResult GridSnapModifierClass::Load(ILoad *iload) -{ - Modifier::Load(iload); - return IO_OK; -} - -Deformer& GridSnapModifierClass::GetDeformer(TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat) -{ - float dimension = 0.0f; Interval valid = FOREVER; - pblock2->GetValue(GSM_PARAM_GRIDDIMENSION, t, dimension, FOREVER); - - static GridSnapDeformerClass deformer; - deformer.Set_Grid_Dimension(dimension); - deformer.Set_Matrices(mat,invmat); - return deformer; -} - -Interval GridSnapModifierClass::GetValidity(TimeValue t) -{ - float f; - Interval valid = FOREVER; - pblock2->GetValue(GSM_PARAM_GRIDDIMENSION, t, f, valid); - return valid; -} - -RefTargetHandle SimpleMod2::GetReference(int i) -{ - switch (i) { - case 0: return tmControl; - case 1: return posControl; - case 2: return pblock2; - default: return NULL; - } -} - -void SimpleMod2::SetReference(int i,RefTargetHandle rtarg) -{ - switch (i) { - case 0: tmControl = (Control*)rtarg; break; - case 1: posControl = (Control*)rtarg; break; - case 2: pblock2 = (IParamBlock2*)rtarg; break; - } -} - -Animatable * SimpleMod2::SubAnim(int i) -{ - switch (i) { - case 0: return posControl; - case 1: return tmControl; - case 2: return pblock2; - default: return NULL; - } -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/gridsnapmodifier.h b/Generals/Code/Tools/WW3D/max2w3d/gridsnapmodifier.h deleted file mode 100644 index 559bea7ee2..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/gridsnapmodifier.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/gridsnapmodifier.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/01/01 5:56p $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef GRIDSNAPMODIFIER_H -#define GRIDSNAPMODIFIER_H - -class ClassDesc; - -ClassDesc * Get_Grid_Snap_Modifier_Desc(void); - - -#endif //GRIDSNAPMODIFIER_H \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/hiersave.cpp b/Generals/Code/Tools/WW3D/max2w3d/hiersave.cpp deleted file mode 100644 index b894244e2e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/hiersave.cpp +++ /dev/null @@ -1,1009 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/hiersave.cpp 56 10/30/00 6:58p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/hiersave.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 6:14p $* - * * - * $Revision:: 56 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * HierarchySaveClass::HierarchySaveClass -- constructor * - * HierarchySaveClass::HierarchySaveClass -- constructor * - * HierarchySaveClass::HierarchySaveClass -- constructor * - * HierarchySaveClass::~HierarchySaveClass -- destructor * - * HierarchySaveClass::Free -- releases all allocated memory * - * HierarchySaveClass::Get_Node_Transform -- returns the transformation matrix of specified n* - * HierarchySaveClass::get_relative_transform -- retruns tm between this node and its parent * - * HierarchySaveClass::Get_Name -- returns the name of this hierarchy * - * HierarchySaveClass::Get_Node -- Get the Max INode * - * HierarchySaveClass::Get_Node_Name -- returns name of this hierarchy node * - * HierarchySaveClass::Find_Named_Node -- returns index of a named node * - * HierarchySaveClass::Get_Export_Coordinate_System - find the bone and coordinate system * - * HierarchySaveClass::Save -- write the hierarchy into a W3D file * - * HierarchySaveClass::Load -- read the hierarchy from a W3D file * - * HierarchySaveClass::add_tree -- adds a node and all of its children * - * HierarchySaveClass::add_node -- adds a single node to the tree * - * HierarchySaveClass::Get_Fixup_Transform -- gets the "fixup" transform for a node * - * HierarchySaveClass::fixup_matrix -- conditions a matrix * - * HierarchySaveClass::save_header -- writes the header into a W3D file * - * HierarchySaveClass::save_pivots -- writes the pivots into a W3D file * - * HierarchySaveClass::save_fixups -- writes the fixup transforms into a W3D file * - * HierarchySaveClass::load_header -- reads the header from a W3D file * - * HierarchySaveClass::load_pivots -- reads the pivots from a W3D file * - * HierarchySaveClass::load_fixups -- reads the fixup transforms from a W3D file * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "hiersave.h" -#include "w3d_file.h" -#include "nodefilt.h" -#include "EULER.H" -#include "util.h" -#include "w3dappdata.h" -#include "errclass.h" -#include "exportlog.h" - - -bool HierarchySaveClass::TerrainModeEnabled = false; - - -/*********************************************************************************************** - * HierarchySaveClass::HierarchySaveClass -- constructor * - * * - * INPUT: * - * root - root INode to construct the HTree from * - * time - current time in Max, transforms at this time will be used * - * treemeter - progress meter * - * hname - name for the hierarchy tree * - * fixup_type - can be used to force all transforms to be translation only * - * fixuptree - htree loaded from a previous export * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -HierarchySaveClass::HierarchySaveClass -( - INode * root, - TimeValue time, - Progress_Meter_Class & treemeter, - char * hname, - int fixuptype, - HierarchySaveClass * fixuptree -) : - Node(DEFAULT_NODE_ARRAY_SIZE), - CurNode(0), - FixupType(fixuptype), - FixupTree(fixuptree) -{ - CurNode = 0; - CurTime = time; - - /* - ** This code-path is activated when the user has created a custom origin. In this case, we - ** need to compute the transform which will make all bones relative to this origin. - */ - OriginOffsetTransform = Inverse(root->GetNodeTM(CurTime)); - - /* - ** Build our tree from the given tree of nodes - */ - int rootidx = add_node(NULL,-1); - assert(rootidx == 0); - add_tree(root,rootidx); - - HierarchyHeader.Version = W3D_CURRENT_HTREE_VERSION; - Set_W3D_Name(HierarchyHeader.Name,hname); - HierarchyHeader.NumPivots = CurNode; - HierarchyHeader.Center.X = 0.0f; - HierarchyHeader.Center.Y = 0.0f; - HierarchyHeader.Center.Z = 0.0f; -} - -/*********************************************************************************************** - * HierarchySaveClass::HierarchySaveClass -- constructor * - * * - * INPUT: * - * * - * rootlist - list of root nodes to add to the htree * - * time - current time in Max, transforms at this time will be used * - * treemeter - progress meter * - * hname - name for the hierarchy tree * - * fixup_type - can be used to force all transforms to be translation only * - * fixuptree - htree loaded from a previous export * - * origin_offset - origin offset transform * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -HierarchySaveClass::HierarchySaveClass -( - INodeListClass * rootlist, - TimeValue time, - Progress_Meter_Class & treemeter, - char * hname, - int fixuptype, - HierarchySaveClass * fixuptree, - const Matrix3 & origin_offset -) : - Node(DEFAULT_NODE_ARRAY_SIZE), - CurNode(0), - FixupType(fixuptype), - FixupTree(fixuptree), - OriginOffsetTransform(origin_offset) -{ - CurNode = 0; - CurTime = time; - - /* - ** Build the tree with all leaves of all of the nodes given - */ - int rootidx = add_node(NULL,-1); - assert(rootidx == 0); - - for (unsigned int i = 0; i < rootlist->Num_Nodes(); i++) { - add_tree((*rootlist)[i],rootidx); - } - - HierarchyHeader.Version = W3D_CURRENT_HTREE_VERSION; - Set_W3D_Name(HierarchyHeader.Name,hname); - HierarchyHeader.NumPivots = CurNode; - HierarchyHeader.Center.X = 0.0f; - HierarchyHeader.Center.Y = 0.0f; - HierarchyHeader.Center.Z = 0.0f; - -} - -/*********************************************************************************************** - * HierarchySaveClass::HierarchySaveClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -HierarchySaveClass::HierarchySaveClass(): - Node(NULL), - CurNode(0), - CurTime(0) -{ -} - -/*********************************************************************************************** - * HierarchySaveClass::~HierarchySaveClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -HierarchySaveClass::~HierarchySaveClass(void) -{ - Free(); -} - -/*********************************************************************************************** - * HierarchySaveClass::Free -- releases all allocated memory * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void HierarchySaveClass::Free(void) -{ - Node.Clear(); -} - - -/*********************************************************************************************** - * HierarchySaveClass::Get_Node_Transform -- returns the transformation matrix of specified no * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 HierarchySaveClass::Get_Node_Transform(int nodeidx) const -{ - Matrix3 tm(1); - - int idx = nodeidx; - - while (idx != -1) { - tm = tm * get_relative_transform(idx); - idx = Node[idx].Pivot.ParentIdx; - } - - return tm; -} - - -/*********************************************************************************************** - * HierarchySaveClass::get_relative_transform -- retruns tm between this node and its parent * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 HierarchySaveClass::get_relative_transform(int nodeidx) const -{ - assert(nodeidx >= 0); - assert(nodeidx < CurNode); - - Point3 trans; - Quat rot; - Matrix3 tm(true); - Matrix3 rtm(true); - - trans.x = Node[nodeidx].Pivot.Translation.X; - trans.y = Node[nodeidx].Pivot.Translation.Y; - trans.z = Node[nodeidx].Pivot.Translation.Z; - - // WARNING! I had to fudge the orientation - // quaternion (Max's representation seems to - // rotate in the opposite sense as mine...) - rot[0] = -Node[nodeidx].Pivot.Rotation.Q[0]; - rot[1] = -Node[nodeidx].Pivot.Rotation.Q[1]; - rot[2] = -Node[nodeidx].Pivot.Rotation.Q[2]; - rot[3] = Node[nodeidx].Pivot.Rotation.Q[3]; - - tm.Translate(trans); - rot.MakeMatrix(rtm); - tm = rtm * tm; - - return tm; -} - - -/*********************************************************************************************** - * HierarchySaveClass::Get_Name -- returns the name of this hierarchy * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -const char * HierarchySaveClass::Get_Name(void) const -{ - return HierarchyHeader.Name; -} - - -/*********************************************************************************************** - * HierarchySaveClass::Get_Node -- Get the Max INode * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/15/98 GTH : Created. * - *=============================================================================================*/ -INode * HierarchySaveClass::Get_Node(int node) const -{ - assert(node >= 0); - assert(node < CurNode); - - return Node[node].MaxNode; -} - -/*********************************************************************************************** - * HierarchySaveClass::Get_Node_Name -- returns name of this hierarchy node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -const char * HierarchySaveClass::Get_Node_Name(int node) const -{ - assert(node >= 0); - assert(node < CurNode); - - return Node[node].Pivot.Name; -} - - -/*********************************************************************************************** - * HierarchySaveClass::Find_Named_Node -- returns index of a named node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -int HierarchySaveClass::Find_Named_Node(const char * name) const -{ - int match = -1; - for (int index=0; indexGetName()); - - boneidx = Find_Named_Node(name); - - if (boneidx != -1) { - - /* - ** We found the parent bone! - */ - done = true; - - } else if (Is_Origin(pbone)) { - - /* - ** Don't go up past our origin, use this as our bone. - */ - boneidx = 0; - done = true; - - } else { - - /* - ** Nope, try the next parent - */ - pbone = pbone->GetParentNode(); - assert(pbone != NULL); - -#if 0 - if (pbone == NULL) { - - /* - ** mesh isn't connected to a bone, use the root - */ - boneidx = 0; - pbone = node; - done = true; - } -#endif - } - } - - if (set_bone_index != NULL) { - *set_bone_index = boneidx; - } - if (set_bone_node != NULL) { - *set_bone_node = pbone; - } - if (set_transform != NULL) { - *set_transform = Get_Fixup_Transform(boneidx) * pbone->GetNodeTM(CurTime); - } -} - -/*********************************************************************************************** - * HierarchySaveClass::Save -- write the hierarchy into a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool HierarchySaveClass::Save(ChunkSaveClass & csave) -{ - ExportLog::printf("\nSaving Hierarchy Tree %s.\n",HierarchyHeader.Name); - ExportLog::printf("Node Count: %d\n",CurNode); - ExportLog::printf("Nodes: \n"); - for (int inode = 0; inode < CurNode; inode++) { - ExportLog::printf(" %s\n",Node[inode].Pivot.Name); - } - - if (!csave.Begin_Chunk(W3D_CHUNK_HIERARCHY)) { - return false; - } - - if (!save_header(csave)) { - return false; - } - - if (!save_pivots(csave)) { - return false; - } - - if (!save_fixups(csave)) { - return false; - } - - if (!csave.End_Chunk()) { - return false; - } - - return true; -} - - -/*********************************************************************************************** - * HierarchySaveClass::Load -- read the hierarchy from a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool HierarchySaveClass::Load(ChunkLoadClass & cload) -{ - Free(); - bool error = false; - - while (cload.Open_Chunk()) { - switch (cload.Cur_Chunk_ID()) { - case W3D_CHUNK_HIERARCHY_HEADER: - if (!load_header(cload)) error = true; - break; - case W3D_CHUNK_PIVOTS: - if (!load_pivots(cload)) error = true; - break; - case W3D_CHUNK_PIVOT_FIXUPS: - if (!load_fixups(cload)) error = true; - break; - default: - break; - } - - if (!cload.Close_Chunk() || error) { - return false; - } - } - - CurNode = HierarchyHeader.NumPivots; - - return true; -} - - -/*********************************************************************************************** - * HierarchySaveClass::add_tree -- adds a node and all of its children * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void HierarchySaveClass::add_tree(INode * node,int pidx) -{ - int nextparent; - - if (node->IsHidden ()) { - - // if the node is hidden, do not add it but add its children to the current parent. - nextparent = pidx; - - } else if (TerrainModeEnabled && (Is_Normal_Mesh(node) || Is_Null_Object(node))) { - - // terrain optimization, normal meshes are not allowed to have transforms - nextparent = pidx; - - } else if (!Is_Bone(node)) { - - // This node isn't a bone, don't add it - nextparent = pidx; - - } else { - - // Add new pivot! it will be parent of all below it. - nextparent = add_node(node,pidx); - - } - - // Add all of this nodes children - for (int i=0; i < node->NumberOfChildren(); i++) { - add_tree(node->GetChildNode(i),nextparent); - } -} - - -/*********************************************************************************************** - * HierarchySaveClass::add_node -- adds a single node to the tree * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -int HierarchySaveClass::add_node(INode * node,int pidx) -{ - /* - ** 'grow' the node array if necessary - */ - if (CurNode >= Node.Length ()) { - Node.Resize (Node.Length () + NODE_ARRAY_GROWTH_SIZE); - } - - /* - ** setup the pivot - */ - Node[CurNode].MaxNode = node; - Node[CurNode].Pivot.ParentIdx = pidx; - - if (node) { - Set_W3D_Name(Node[CurNode].Pivot.Name,node->GetName()); - } else { - Set_W3D_Name(Node[CurNode].Pivot.Name,"RootTransform"); - } - - /* - ** Now, check if there is a bone with this W3D name already - ** if there is, scold the user and bail out - */ - if (Find_Named_Node(Node[CurNode].Pivot.Name) != -1) { - char buf[128]; - sprintf(buf,"Bones with duplicate names found!\nDuplicated Name: %s\n",Node[CurNode].Pivot.Name); - throw ErrorClass(buf); - } - - /* - ** Compute the transformation for this node - */ - Matrix3 maxnodeTM(1); - Matrix3 ournodeTM(1); - Matrix3 fixupTM(1); - Point3 trans(0,0,0); - Quat rot(1); - Point3 scale(1,1,1); - - if (node) { - maxnodeTM = node->GetNodeTM(CurTime) * OriginOffsetTransform; - } else { - maxnodeTM = Matrix3(1); - } - - /* - ** If this tree is being "fixed up" the first thing we do - ** is to transform Max's nodeTM by the fixup transform. - ** This is done when a base pose was created using our own - ** types of transforms and we want to apply the same - ** changes to this tree. - ** - ** Note that if FixupType is not "NONE", FixupTree must be NULL, - */ - assert(!((FixupTree != NULL) && (FixupType != MATRIX_FIXUP_NONE))); - - if (FixupTree != NULL) { - int fi = FixupTree->Find_Named_Node(Node[CurNode].Pivot.Name); - if (fi == -1) { - char buf[128]; - sprintf(buf,"Incompatible Base Pose!\nMissing Bone: %s\n",Node[CurNode].Pivot.Name); - throw ErrorClass(buf); - } - - Matrix3 fixup = FixupTree->Get_Fixup_Transform(fi); - - maxnodeTM = fixup * maxnodeTM; - } - - - ournodeTM = fixup_matrix(maxnodeTM); - fixupTM = ournodeTM * Inverse(maxnodeTM); - - /* - ** Now, make ournodeTM relative to its parent transform. We - ** will always store relative transformations. (Also, note - ** that it is relative to our version of the parent transform - ** which is not necessarily the same as the MAX version...) - */ - if (pidx != -1) { - Matrix3 parentTM = Get_Node_Transform(pidx); - Matrix3 pinv = Inverse(parentTM); - ournodeTM = ournodeTM * pinv; - } - - - /* - ** Break the matrix down into a rotation and translation. - */ - DecomposeMatrix(ournodeTM,trans,rot,scale); - - /* - ** Save the "fixup" matrix - */ - for (int j=0;j<4;j++) { - Point3 row = fixupTM.GetRow(j); - Node[CurNode].Fixup.TM[j][0] = row.x; - Node[CurNode].Fixup.TM[j][1] = row.y; - Node[CurNode].Fixup.TM[j][2] = row.z; - } - - /* - ** Set the translation and rotation for this pivot. - */ - Node[CurNode].Pivot.Translation.X = trans.x; - Node[CurNode].Pivot.Translation.Y = trans.y; - Node[CurNode].Pivot.Translation.Z = trans.z; - - Node[CurNode].Pivot.Rotation.Q[0] = -rot[0]; - Node[CurNode].Pivot.Rotation.Q[1] = -rot[1]; - Node[CurNode].Pivot.Rotation.Q[2] = -rot[2]; - Node[CurNode].Pivot.Rotation.Q[3] = rot[3]; - - /* - ** Compute the Euler angles and set them. - */ - Matrix3 rotmat; - rot.MakeMatrix(rotmat); - EulerAnglesClass eangs(rotmat,EulerOrderXYZr); - - Node[CurNode].Pivot.EulerAngles.X = eangs.Get_Angle(0); - Node[CurNode].Pivot.EulerAngles.Y = eangs.Get_Angle(1); - Node[CurNode].Pivot.EulerAngles.Z = eangs.Get_Angle(2); - - return CurNode++; -} - -/*********************************************************************************************** - * HierarchySaveClass::Get_Fixup_Transform -- gets the "fixup" transform for a node * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 HierarchySaveClass::Get_Fixup_Transform(int node) const -{ - assert(node >= 0); - assert(node < CurNode); - - Matrix3 m; - - for (int j=0;j<4;j++) { - m.SetRow(j,Point3(Node[node].Fixup.TM[j][0],Node[node].Fixup.TM[j][1],Node[node].Fixup.TM[j][2])); - } - - return m; -} - -/*********************************************************************************************** - * HierarchySaveClass::fixup_matrix -- conditions a matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 HierarchySaveClass::fixup_matrix(const Matrix3 & csrc) const -{ - Matrix3 src = csrc; // the GetTrans function is not const correct... - Matrix3 newtm(1); - Point3 trans; - Quat rot; - Point3 scale; - - switch (FixupType) { - case MATRIX_FIXUP_NONE: - newtm = src; - break; - - case MATRIX_FIXUP_TRANS: - newtm.SetTrans(src.GetTrans()); - newtm = Cleanup_Orthogonal_Matrix(newtm); - break; - - case MATRIX_FIXUP_TRANS_ROT: - DecomposeMatrix(src,trans,rot,scale); - rot.MakeMatrix(newtm); - newtm.SetTrans(trans); - newtm = Cleanup_Orthogonal_Matrix(newtm); - break; - }; - - return newtm; -} - - -/*********************************************************************************************** - * HierarchySaveClass::save_header -- writes the header into a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool HierarchySaveClass::save_header(ChunkSaveClass & csave) -{ - if (!csave.Begin_Chunk(W3D_CHUNK_HIERARCHY_HEADER)) { - return false; - } - - if (csave.Write(&HierarchyHeader,sizeof(HierarchyHeader)) != sizeof(HierarchyHeader)) { - return false; - } - - if (!csave.End_Chunk()) { - return false; - } - - return true; -} - - -/*********************************************************************************************** - * HierarchySaveClass::save_pivots -- writes the pivots into a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool HierarchySaveClass::save_pivots(ChunkSaveClass & csave) -{ - if (!csave.Begin_Chunk(W3D_CHUNK_PIVOTS)) { - return false; - } - - for (uint32 i=0; i. -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/hiersave.h 29 10/26/00 5:59p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/hiersave.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/26/00 5:09p $* - * * - * $Revision:: 29 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef HIERSAVE_H -#define HIERSAVE_H - -#include "always.h" - -#include -#include - -#ifndef W3D_FILE_H -#include "w3d_file.h" -#endif - -#ifndef PROGRESS_H -#include "PROGRESS.H" -#endif - -#ifndef CHUNKIO_H -#include "chunkio.h" -#endif - -#ifndef NODELIST_H -#include "nodelist.h" -#endif - -#ifndef VECTOR_H -#include "Vector.H" -#endif - - - -struct HierarchyNodeStruct -{ - INode * MaxNode; - W3dPivotStruct Pivot; - W3dPivotFixupStruct Fixup; - - bool operator == (const HierarchyNodeStruct & that) { return false; } - bool operator != (const HierarchyNodeStruct & that) { return !(*this == that); } -}; - - -class HierarchySaveClass -{ - -public: - - enum { - MATRIX_FIXUP_NONE = 0, - MATRIX_FIXUP_TRANS = 1, - MATRIX_FIXUP_TRANS_ROT = 2 - }; - - HierarchySaveClass(); - - HierarchySaveClass( - INode * root, - TimeValue time, - Progress_Meter_Class & treemeter, - char * hname, - int fixup_type = MATRIX_FIXUP_NONE, - HierarchySaveClass * fixuptree = NULL); - - HierarchySaveClass( - INodeListClass * rootlist, - TimeValue time, - Progress_Meter_Class & treemeter, - char * hname, - int fixup_type = MATRIX_FIXUP_NONE, - HierarchySaveClass * fixuptree = NULL, - const Matrix3 & origin_offset = Matrix3(1)); - - ~HierarchySaveClass(); - - bool Save(ChunkSaveClass & csave); - bool Load(ChunkLoadClass & cload); - int Num_Nodes(void) const { return CurNode; } - const char * Get_Name(void) const; - const char * Get_Node_Name(int node) const; - - // get ahold of the max inode - INode * Get_Node(int node) const; - - // Returns the node's transform from object to world space - Matrix3 Get_Node_Transform(int node) const; - - // Returns the node's transform relative to its parent - Matrix3 Get_Node_Relative_Transform(int node) const { return get_relative_transform(node); } - - // Get the fixup matrix for the given pivot (always applied to the *relative* transform) - Matrix3 Get_Fixup_Transform(int node) const; - - // Finds a node by name - int Find_Named_Node(const char * name) const; - - // Get the coordinate system to use when exporting the given INode. Note that this - // function takes into account the multiple skeletons present when exporting LOD models. - void Get_Export_Coordinate_System(INode * node,int * set_bone_index,INode ** set_bone_node,Matrix3 * set_transform); - - // Turning on terrian mode will cause all HTrees to force all normal meshes to be - // attached to the RootTransform regardless of the status of their 'Export_Transform' flag - static void Enable_Terrain_Optimization(bool onoff) { TerrainModeEnabled = onoff; } - -private: - - enum { MAX_PIVOTS = 4096, DEFAULT_NODE_ARRAY_SIZE = 512, NODE_ARRAY_GROWTH_SIZE = 32 }; - - TimeValue CurTime; - W3dHierarchyStruct HierarchyHeader; - DynamicVectorClass Node; - int CurNode; - int FixupType; - Matrix3 OriginOffsetTransform; // this transform makes a node relative to the origin - HierarchySaveClass * FixupTree; - - static bool TerrainModeEnabled; - - void add_tree(INode * node,int pidx); - int add_node(INode * node,int pidx); - - bool save_header(ChunkSaveClass & csave); - bool save_pivots(ChunkSaveClass & csave); - bool save_fixups(ChunkSaveClass & csave); - - bool load_header(ChunkLoadClass & cload); - bool load_pivots(ChunkLoadClass & cload); - bool load_fixups(ChunkLoadClass & cload); - - Matrix3 get_relative_transform(int nodeidx) const; - Matrix3 fixup_matrix(const Matrix3 & src) const; - void Free(void); -}; - -#endif /*HIERSAVE_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/hlodsave.cpp b/Generals/Code/Tools/WW3D/max2w3d/hlodsave.cpp deleted file mode 100644 index 065ab1e228..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/hlodsave.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Renegade / G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/hlodsave.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 5:24p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * -- The constructor builds the whole HLOD tree in a * - * -- Destructor blows away the dynamic memory we used. * - * -- Method called when saving to a W3D file. Saves the chunks * - * -- Write the header * - * -- Writes each LOD * - * -- Writes the mesh to bone connectivity info for each mesh in an LOD. * - * HLodSaveClass::save_aggregate_array -- save the aggregates (if any) * - * HLodSaveClass::save_proxy_array -- save the array of proxies (if any) * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "hlodsave.h" -#include "meshcon.h" -#include "errclass.h" -#include "util.h" -#include "w3dappdata.h" -#include "wwmath.h" // NO_MAX_SCREEN_SIZE -#include "exportlog.h" - - - -/* Behold, the applicable snippets of code from w3d_file.h that are applicable to this module! - - W3D_CHUNK_HLOD =0x00000700, // description of an HLod object (see HLodClass) - W3D_CHUNK_HLOD_HEADER, // general information such as name and version - W3D_CHUNK_HLOD_LOD_ARRAY, // wrapper around the array of objects for each level of detail - W3D_CHUNK_HLOD_LOD_ARRAY_HEADER, // info on the objects in this level of detail array - W3D_CHUNK_HLOD_SUB_OBJECT, // an object in this level of detail array - -struct W3dHLodHeaderStruct -{ - uint32 Version; - uint32 LodCount; - char Name[W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; // name of the hierarchy tree to use (\0 if none) -}; - -struct W3dHLodArrayHeaderStruct -{ - uint32 ModelCount; - float32 MaxScreenSize; // if model is bigger than this, switch to higher lod. -}; - -struct W3dHLodSubObjectStruct -{ - uint32 BoneIndex; - char Name[W3D_NAME_LEN*2]; -}; -*/ - - -/*********************************************************************************************** - * HLodSaveClass -- The constructor builds the whole HLOD tree in a form suitable for saving * - * to a W3D file. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -HLodSaveClass::HLodSaveClass (MeshConnectionsClass **connections, int lod_count, TimeValue CurTime, - char *name, const char *htree_name, Progress_Meter_Class &meter, - INodeListClass *origin_list) -: lod_array(NULL) -{ - /* - ** Fill in the W3dHLodHeaderStruct - */ - header.Version = W3D_CURRENT_HLOD_VERSION; - header.LodCount = lod_count; - Set_W3D_Name(header.Name, name); - Set_W3D_Name(header.HierarchyName, htree_name); - ExportLog::printf("\nExporting HLOD object: %s\n",header.Name); - ExportLog::printf(" lod count: %d\n",header.LodCount); - - /* - ** Create the array of stuff for each LOD. - */ - lod_array = new HLodArrayEntry[lod_count]; - if (!lod_array) - throw ErrorClass("Out Of Memory!"); - - int i; - for (i = 0; i < lod_count; i++) - { - - ExportLog::printf(" Exporting LOD Array %d\n",i); - - INode *origin = connections[i]->Get_Origin(); - int sub_obj_count = connections[i]->Get_Sub_Object_Count(); - lod_array[i].Allocate_Sub_Objects(sub_obj_count); - lod_array[i].header.ModelCount = sub_obj_count; - - float screen_size = NO_MAX_SCREEN_SIZE; - if (origin) - origin->GetUserPropFloat("MaxScreenSize", screen_size); - lod_array[i].header.MaxScreenSize = screen_size; - - /* - ** Create the info per mesh in this LOD. - */ - int j; - W3dHLodSubObjectStruct *sub_obj = lod_array[i].sub_obj; - ExportLog::printf(" sub-object count: %d\n",sub_obj_count); - for (j = 0; j < sub_obj_count; j++) - { - char *mesh_name; - int bone_index; - INode *mesh_node; - if (!connections[i]->Get_Sub_Object_Data(j, &mesh_name, &bone_index, &mesh_node)) - throw ErrorClass("Model %s is missing connection data!", name); - - strcpy(sub_obj[j].Name, mesh_name); - sub_obj[j].BoneIndex = bone_index; - - ExportLog::printf(" Sub Object: %s Bone: %d\n",mesh_name,bone_index); - } - } - - /* - ** Copy aggregates from the Top-Level LOD - */ - int agg_count = connections[lod_count-1]->Get_Aggregate_Count(); - aggregate_array.Allocate_Sub_Objects(agg_count); - aggregate_array.header.ModelCount = agg_count; - aggregate_array.header.MaxScreenSize = 0.0f; - - ExportLog::printf(" Exporting Aggregates:\n"); - ExportLog::printf(" aggregate count: %d\n",agg_count); - - for (i=0; iGet_Aggregate_Data(i, &mesh_name, &bone_index, &mesh_node); - - W3dHLodSubObjectStruct & sub_obj = aggregate_array.sub_obj[i]; - strcpy(sub_obj.Name, mesh_name); - sub_obj.BoneIndex = bone_index; - - ExportLog::printf(" Aggregate object: %s Bone: %d\n",mesh_name,bone_index); - - } - - /* - ** Copy the proxy objects from the Top-Level LOD - */ - int proxy_count = connections[lod_count-1]->Get_Proxy_Count(); - proxy_array.Allocate_Sub_Objects(proxy_count); - proxy_array.header.ModelCount = proxy_count; - proxy_array.header.MaxScreenSize = 0.0f; - - ExportLog::printf(" Exporting Proxies\n"); - ExportLog::printf(" proxy count: %d\n",proxy_count); - for (i=0; iGet_Proxy_Data(i, &mesh_name, &bone_index, &mesh_node); - - W3dHLodSubObjectStruct & sub_obj = proxy_array.sub_obj[i]; - strcpy(sub_obj.Name, mesh_name); - sub_obj.BoneIndex = bone_index; - - ExportLog::printf(" Proxy object: %s Bone: %d\n",mesh_name,bone_index); - } - -} - - -/*********************************************************************************************** - * ~HLodSaveClass -- Destructor blows away the dynamic memory we used. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -HLodSaveClass::~HLodSaveClass (void) -{ - if (lod_array) - { - delete []lod_array; - lod_array = NULL; - } -} - - -/*********************************************************************************************** - * HLodSaveClass::Save -- Method called when saving to a W3D file. Saves the chunks that * - * define a HLOD. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -bool HLodSaveClass::Save(ChunkSaveClass &csave) -{ - if (!lod_array) - return false; - - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD)) - return false; - - if (!save_header(csave)) - return false; - - if (!save_lod_arrays(csave)) - return false; - - if (!save_aggregate_array(csave)) - return false; - - if (!save_proxy_array(csave)) - return false; - - if (!csave.End_Chunk()) - return false; - - return true; -} - - -/*********************************************************************************************** - * HLodSaveClass::save_header -- Write the header * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -bool HLodSaveClass::save_header (ChunkSaveClass &csave) -{ - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD_HEADER)) - return false; - - if (csave.Write(&header, sizeof(header)) != sizeof(header)) - return false; - - if (!csave.End_Chunk()) - return false; - - return true; -} - - -/*********************************************************************************************** - * HLodSaveClass::save_lod_arrays -- Writes each LOD * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -bool HLodSaveClass::save_lod_arrays(ChunkSaveClass &csave) -{ - for (int i = 0; i < header.LodCount; i++) - { - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD_LOD_ARRAY)) - return false; - - if (!save_sub_object_array(csave, lod_array[i])) - return false; - - if (!csave.End_Chunk()) - return false; - } - - return true; -} - - - -/*********************************************************************************************** - * HLodSaveClass::save_aggregate_array -- save the aggregates (if any) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/25/2000 gth : Created. * - *=============================================================================================*/ -bool HLodSaveClass::save_aggregate_array(ChunkSaveClass & csave) -{ - if (aggregate_array.num_sub_objects > 0) { - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD_AGGREGATE_ARRAY)) - return false; - - if (!save_sub_object_array(csave, aggregate_array)) - return false; - - if (!csave.End_Chunk()) - return false; - } - return true; -} - - -/*********************************************************************************************** - * HLodSaveClass::save_proxy_array -- save the array of proxies (if any) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/27/2000 gth : Created. * - *=============================================================================================*/ -bool HLodSaveClass::save_proxy_array(ChunkSaveClass & csave) -{ - if (proxy_array.num_sub_objects > 0) { - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD_PROXY_ARRAY)) - return false; - - if (!save_sub_object_array(csave, proxy_array)) - return false; - - if (!csave.End_Chunk()) - return false; - } - return true; -} - - -/*********************************************************************************************** - * HLodSaveClass::save_sub_object_array -- Writes the mesh to bone connectivity info for each * - * mesh in an LOD. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -bool HLodSaveClass::save_sub_object_array(ChunkSaveClass &csave, const HLodArrayEntry & array) -{ - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD_SUB_OBJECT_ARRAY_HEADER)) - return false; - - if (csave.Write(&(array.header), sizeof(array.header)) != sizeof(array.header)) - return false; - - if (!csave.End_Chunk()) - return false; - - for (int j = 0; j < array.num_sub_objects; j++) - { - if (!csave.Begin_Chunk(W3D_CHUNK_HLOD_SUB_OBJECT)) - return false; - - if (csave.Write(&(array.sub_obj[j]), sizeof(array.sub_obj[j])) != sizeof(array.sub_obj[j])) - return false; - - if (!csave.End_Chunk()) - return false; - } - - return true; -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/hlodsave.h b/Generals/Code/Tools/WW3D/max2w3d/hlodsave.h deleted file mode 100644 index a74189285b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/hlodsave.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Renegade / G * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/hlodsave.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 10:22a $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef HLODSAVE_H -#define HLODSAVE_H - -#include "always.h" - -#include -#include - -#include "w3d_file.h" -#include "PROGRESS.H" -#include "chunkio.h" -#include "meshcon.h" - - -class INodeListClass; -class MeshConnectionsClass; - - -/** -** HLodSaveClass -** This object takes an array of mesh-connections objects and exports an LOD model -** constructed from them. -*/ -class HLodSaveClass -{ -public: - HLodSaveClass (MeshConnectionsClass **connections, int lod_count, TimeValue CurTime, - char *name, const char *htree_name, Progress_Meter_Class &meter, - INodeListClass *origin_list); - ~HLodSaveClass (void); - - bool Save (ChunkSaveClass &csave); - - -protected: - - /* - ** class HLodArrayEntry hold the HLOD tree that we will save out in the Save() method. - */ - class HLodArrayEntry - { - public: - W3dHLodArrayHeaderStruct header; - W3dHLodSubObjectStruct *sub_obj; - int num_sub_objects; - - HLodArrayEntry (int num_sub_objs = 0) - { - sub_obj = NULL; - num_sub_objects = 0; - Allocate_Sub_Objects(num_sub_objs); - } - - ~HLodArrayEntry (void) - { - if (sub_obj) - { - delete sub_obj; - sub_obj = NULL; - num_sub_objects = 0; - } - } - - bool Allocate_Sub_Objects (int num) - { - if (num <= 0) return false; - num_sub_objects = 0; - sub_obj = new W3dHLodSubObjectStruct[num]; - if (!sub_obj) return false; - num_sub_objects = num; - return true; - } - - bool operator == (const HLodArrayEntry & that) { return false; } - bool operator != (const HLodArrayEntry & that) { return !(*this == that); } - }; - - bool save_header (ChunkSaveClass &csave); - bool save_lod_arrays (ChunkSaveClass &csave); - bool save_aggregate_array (ChunkSaveClass & csave); - bool save_proxy_array(ChunkSaveClass & csave); - bool save_sub_object_array(ChunkSaveClass & csave, const HLodArrayEntry & array); - - W3dHLodHeaderStruct header; - HLodArrayEntry * lod_array; - HLodArrayEntry aggregate_array; - HLodArrayEntry proxy_array; -}; - - - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/logdlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/logdlg.cpp deleted file mode 100644 index d5d26567fc..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/logdlg.cpp +++ /dev/null @@ -1,388 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/logdlg.cpp 5 11/07/00 5:40p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/logdlg.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 4:24p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "logdlg.h" -#include "resource.h" -#include "dllmain.h" -#include "w3dexp.h" -#include "util.h" -#include "rawfile.h" -#include "units.h" - - -/* -** Static functions -*/ -static BOOL CALLBACK _logdata_dialog_proc(HWND Hwnd,UINT message,WPARAM wParam,LPARAM lParam); -static DWORD WINAPI _logdata_thread_function(LPVOID log_obj_ptr); - - -/*********************************************************************************************** - * LogDataDialogClass::LogDataDialogClass -- constructor for the options dialog object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/09/2000 JGA : Created. * - *=============================================================================================*/ -LogDataDialogClass::LogDataDialogClass(HWND parent): - Hwnd(NULL), - ParentHwnd(parent), - buffer_index(0), - last_buffer_index(0), - status(0) -{ - ThreadHandle = CreateThread(NULL, 0, _logdata_thread_function, (LPVOID)this, 0, &ThreadID); - - if (ThreadHandle) { - while (status == 0) { - // sync, wait for init - } - } -} - -LogDataDialogClass::~LogDataDialogClass(void) -{ - status = 3; - if (::IsWindow(Hwnd)) { - SendMessage( Hwnd, WM_CLOSE, 0, 0 ); - } -} - - -/*********************************************************************************************** - * LogDataDialogClass::printf -- handles doing printfs into the current log window * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/11/2000 JGA : Created. * - *=============================================================================================*/ -void LogDataDialogClass::printf(const char *text, ...) -{ - va_list arguments; - va_start(arguments, text); -} // printf - -void LogDataDialogClass::printf(const char * text, va_list args) -{ - static char string_buffer[256]; - - vsprintf(string_buffer, text, args); - - HWND ctrlHwnd = GetDlgItem(Hwnd, IDC_ANIM_LOG_RICHEDIT); - - SendMessage(ctrlHwnd, EM_SETSEL, -1, -1 ); - SendMessage(ctrlHwnd, EM_REPLACESEL, FALSE, (long)string_buffer); - - last_buffer_index = buffer_index; - buffer_index+=strlen(string_buffer); - - //int min,max,pos; - //GetScrollRange(ctrlHwnd, SB_VERT, &min, &max); - //pos = GetScrollPos(ctrlHwnd, SB_VERT); - - //if (pos == max) { - SendMessage(GetDlgItem(Hwnd,IDC_ANIM_LOG_RICHEDIT), EM_SCROLLCARET, 0, 0); - //} - - -} - -/*********************************************************************************************** - * LogDataDialogClass::rprintf -- replace last printf, with this new printf * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/14/2000 JGA : Created. * - *=============================================================================================*/ -void LogDataDialogClass::rprintf(const char *text, ...) -{ - va_list arguments; - va_start(arguments, text); - - rprintf(text,arguments); -} - -void LogDataDialogClass::rprintf(const char *text, va_list args) -{ - static char string_buffer[256]; - vsprintf(string_buffer, text, args); - - HWND ctrlHwnd = GetDlgItem(Hwnd, IDC_ANIM_LOG_RICHEDIT); - - SendMessage(ctrlHwnd, EM_SETSEL, last_buffer_index, buffer_index ); - SendMessage(ctrlHwnd, EM_REPLACESEL, FALSE, (long)string_buffer); - - buffer_index = strlen(string_buffer) + last_buffer_index; - - //int min,max,pos; - //GetScrollRange(ctrlHwnd, SB_VERT, &min, &max); - //pos = GetScrollPos(ctrlHwnd, SB_VERT); - - //SendMessage(GetDlgItem(Hwnd,IDC_ANIM_LOG_RICHEDIT), EM_SCROLLCARET, 0, 0); - -} // rprintf - - -/*********************************************************************************************** - * LogDataDialogClass::updatebar - send message to progress meter * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/14/2000 JGA : Created. * - *=============================================================================================*/ -void LogDataDialogClass::updatebar(float position, float total) -{ - int pos; - - pos = ((position / total) * 100.0f); - - HWND ctrlHwnd = GetDlgItem(Hwnd, IDC_ANIM_COMPRESS_PROGRESS); - - SendMessage(ctrlHwnd, PBM_SETPOS, pos, 0 ); - -} // updatebar - - -/*********************************************************************************************** - * LogDataDialogClass::Wait_OK - Give user a chance to review log, then hit ok * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/14/2000 JGA : Created. * - *=============================================================================================*/ -void LogDataDialogClass::Wait_OK() -{ - ::EnableWindow(GetDlgItem(Hwnd,IDOK),TRUE); - ::SetForegroundWindow(Hwnd); - - while (status < 2) { - // wait for the OK - } - -} // Wait_OK - - - -/*********************************************************************************************** - * LogDataDialogClass::Dialog_Proc -- Handles the windows message for the options dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -bool LogDataDialogClass::Dialog_Proc -( - HWND hwnd, - UINT message, - WPARAM wParam, - LPARAM -) -{ - int code = HIWORD(wParam); - - switch (message ) { - - /******************************************************************* - * WM_INITDIALOG - * - * Initialize all of the custom controls for the dialog box - * - *******************************************************************/ - case WM_INITDIALOG: - - Dialog_Init(); - return TRUE; - - - /******************************************************************* - * WM_COMMAND - * - * - *******************************************************************/ - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - - status = 2; - - EndDialog(Hwnd, 1); - Hwnd = NULL; - return TRUE; - break; - - } - break; - - //case WM_VSCROLL: - // return TRUE; - // break; - - case WM_CLOSE: - - if (status >= 2) { - EndDialog(Hwnd, 1); - Hwnd = NULL; - } - - return TRUE; - break; - - } - return FALSE; - -} // Dialog_Proc - -void LogDataDialogClass::Dialog_Init() -{ - - SetCursor(LoadCursor (NULL, IDC_ARROW)); - - RECT desktop; - RECT ourwin; - - GetWindowRect(GetDesktopWindow(), &desktop); - GetWindowRect(Hwnd, &ourwin); - - int sx,sy,cx,cy; - - sx = ourwin.right - ourwin.left; - sy = ourwin.bottom - ourwin.top; - - cx = (((desktop.right - desktop.left) - sx)/2) + desktop.left; - cy = (((desktop.bottom - desktop.top) - sy)/2) + desktop.top; - - //SetWindowPos(Hwnd, HWND_TOPMOST, cx, cy, 0, 0, SWP_NOSIZE); - SetWindowPos(Hwnd, HWND_TOP, cx, cy, 0, 0, SWP_NOSIZE); - - EnableWindow(GetDlgItem(Hwnd,IDOK),FALSE); - - status = 1; // signal init - - -} // Dialog_Init - - - -/*********************************************************************************************** - * _logdata_dialog_proc -- thunks into the logdata dialog class's windows message handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/09/2000 JGA : Created. * - *=============================================================================================*/ -BOOL CALLBACK _logdata_dialog_proc -( - HWND hwnd, - UINT message, - WPARAM wParam, - LPARAM lParam -) -{ - if (message == WM_INITDIALOG) { - LogDataDialogClass * log = (LogDataDialogClass *)lParam; - log->Hwnd = hwnd; - ::SetProp(hwnd,"LogDataDialogClass",(HANDLE)log); - } - - LogDataDialogClass * log = (LogDataDialogClass *)::GetProp(hwnd,"LogDataDialogClass"); - - if (message == WM_DESTROY) { - ::RemoveProp(hwnd,"LogDataDialogClass"); - } - - if (log) { - return log->Dialog_Proc(hwnd,message,wParam,lParam); - } else { - return FALSE; - } - -} // _logdata_dialog_proc - - -DWORD WINAPI _logdata_thread_function(LPVOID log_obj_ptr) -{ - // put logdata dialog box (lpParameter is the "this" pointer of the object) - DialogBoxParam( AppInstance, - MAKEINTRESOURCE(IDD_W3D_LOG), - ((LogDataDialogClass*)log_obj_ptr)->ParentHwnd, - (DLGPROC) _logdata_dialog_proc, - (LPARAM) log_obj_ptr); - - - // When this exits it should terminate the thread - return(0); -} - - -// EOF - logdlg.cpp diff --git a/Generals/Code/Tools/WW3D/max2w3d/logdlg.h b/Generals/Code/Tools/WW3D/max2w3d/logdlg.h deleted file mode 100644 index 23e0a12336..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/logdlg.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/logdlg.h 4 11/07/00 5:40p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/logdlg.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 3:15p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef LOGDLG_H -#define LOGDLG_H - -#include - - -class LogDataDialogClass -{ -public: - - LogDataDialogClass(HWND parent); - ~LogDataDialogClass(); - - void Wait_OK(); // wait for user to hit OK - - void printf(const char *, ...); - void printf(const char * text, va_list args); - void rprintf(const char *, ...); - void rprintf(const char *text, va_list args); - - void updatebar(float position, float total); - - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - -public: -// public variables - HWND Hwnd; - HWND ParentHwnd; - -private: - - void Dialog_Init(); - -private: - - HANDLE ThreadHandle; - DWORD ThreadID; - - int last_buffer_index; - int buffer_index; - -volatile int status; - -}; - - -#endif - -// EOF - logdlg.h diff --git a/Generals/Code/Tools/WW3D/max2w3d/max2w3d.rc b/Generals/Code/Tools/WW3D/max2w3d/max2w3d.rc deleted file mode 100644 index ed224c713b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/max2w3d.rc +++ /dev/null @@ -1,1994 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_VOXEL_DEBUG_DIALOG DIALOG DISCARDABLE 0, 0, 171, 114 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Voxelization Debugging" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,114,7,50,14 - CTEXT "Voxel Viewport",IDC_VOXEL_VIEWPORT,7,7,100,100, - SS_CENTERIMAGE - CONTROL "",IDC_LAYER_EDIT,"CustEdit",WS_TABSTOP,120,50,28,10 - CONTROL "",IDC_LAYER_SPIN,"SpinnerControl",0x0,148,50,10,10 - LTEXT "Current Layer",IDC_STATIC,115,36,43,8 -END - -IDD_W3D_EXPORT_OPTIONS DIALOG DISCARDABLE 0, 0, 259, 282 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "W3D Export Options" -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "Hierarchy",IDC_STATIC,7,7,245,64 - GROUPBOX "Animation",IDC_STATIC,7,78,245,107 - GROUPBOX "Geometry",IDC_STATIC,7,188,245,67 - CONTROL "Export",IDC_WHT_EXPORT_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,17,22,36,10 - CONTROL "Load from file:",IDC_WHT_LOAD_RADIO,"Button", - BS_AUTORADIOBUTTON,17,37,60,10 - CONTROL "Don't Export",IDC_WHT_NO_EXPORT_RADIO,"Button", - BS_AUTORADIOBUTTON,17,53,55,10 - CONTROL "Use Translation Only",IDC_TRANSLATION_ONLY_CHECK,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,83,54,81,10 - PUSHBUTTON "Browse",IDC_WHT_BROWSE_BUTTON,79,37,165,12,WS_GROUP - CONTROL "Export",IDC_WHA_EXPORT_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,17,93,36,10 - CONTROL "Don't Export",IDC_WHA_NO_EXPORT_RADIO,"Button", - BS_AUTORADIOBUTTON,17,108,55,10 - LTEXT "Frames:",IDC_STATIC,84,94,26,10,NOT WS_GROUP - CONTROL "",IDC_RANGE_LOW_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP, - 128,93,28,10 - CONTROL "",IDC_RANGE_LOW_SPIN,"SpinnerControl",0x0,156,93,10,10 - LTEXT "To",IDC_STATIC,168,93,10,10 - CONTROL "",IDC_RANGE_HIGH_EDIT,"CustEdit",WS_TABSTOP,182,93,28, - 10 - CONTROL "",IDC_RANGE_HIGH_SPIN,"SpinnerControl",0x0,210,93,10,10 - CONTROL "Export",IDC_WTM_EXPORT_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,15,202,36,10 - CONTROL "Don't Export",IDC_WTM_NO_EXPORT_RADIO,"Button", - BS_AUTORADIOBUTTON,15,220,55,10 - CONTROL "&Smooth Vertex Normals Across Meshes", - IDC_EXPORT_MESH_SMOOTH_CHECK,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,87,203,139,10 - DEFPUSHBUTTON "OK",IDOK,66,261,50,14 - PUSHBUTTON "Cancel",IDCANCEL,144,261,50,14 - CONTROL "&Compress",IDC_COMPRESS_ANIMATION_CHECK,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,17,131,47,10 - LTEXT "Max Translation Error:(unit)",IDC_STATIC,16,150,85,8 - GROUPBOX "Compression Settings",IDC_STATIC,13,120,233,61 - LTEXT "Max Rotational Error:(deg)",IDC_STATIC,16,166,83,8 - CONTROL "Force Key Reduction",IDC_REDUCE_ANIMATION_CHECK,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,156,148,83,10 - COMBOBOX IDC_REDUCE_ANIMATION_COMBO,213,163,29,81, - CBS_DROPDOWNLIST | WS_VSCROLL | WS_GROUP | WS_TABSTOP - LTEXT "Key Reduction %:",IDC_STATIC,153,165,57,8 - LTEXT "Current FPS: %d",IDC_ANIMATION_FPS_STATIC,79,108,80,8 - COMBOBOX IDC_COMPRESS_ANIMATION_FLAVOR_COMBO,65,129,96,49, - CBS_DROPDOWNLIST | WS_VSCROLL | WS_GROUP | WS_TABSTOP - EDITTEXT IDC_MAX_TRANS_ERROR_EDIT,103,147,40,14,ES_AUTOHSCROLL | - WS_GROUP - EDITTEXT IDC_MAX_ROT_ERROR_EDIT,103,163,40,14,ES_AUTOHSCROLL | - WS_GROUP - CONTROL "Review Log",IDC_VIEWLOG_CHECK,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,188,108,54,10 - CONTROL "Optimize Collision Detection",IDC_EXPORT_MESH_AABTREES, - "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,87,220, - 103,10 - CONTROL "Optimize Mesh Data (mesh names will be lost)", - IDC_EXPORT_MESH_OPTIMIZE,"Button",BS_AUTOCHECKBOX | - BS_MULTILINE | WS_GROUP | WS_TABSTOP,87,237,162,10 - CONTROL "Terrain Mode (all meshes exported in world space)", - IDC_TERRAIN_MODE_CHECK,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,79,22,173,10 -END - -IDD_BONE_INFLUENCE_PARAMS DIALOG DISCARDABLE 0, 0, 108, 78 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Link to Bone by Name",IDC_LINK_BY_NAME_BUTTON, - "CustButton",WS_TABSTOP,7,7,94,13 - CONTROL "Auto-Link",IDC_AUTO_LINK_BUTTON,"CustButton",WS_TABSTOP, - 7,41,94,13 - CONTROL "Link to Bone",IDC_LINK_BUTTON,"CustButton",WS_TABSTOP,7, - 24,94,13 - CONTROL "Unlink",IDC_UNLINK_BUTTON,"CustButton",WS_TABSTOP,7,58, - 94,13 -END - -IDD_SKELETON_PARAMETERS DIALOG DISCARDABLE 0, 0, 108, 137 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "",IDC_BASE_POSE_EDIT,"CustEdit",WS_TABSTOP,55,7,37,10 - CONTROL "",IDC_BASE_POSE_SPIN,"SpinnerControl",0x0,93,7,7,10 - LTEXT "Base Pose:",IDC_STATIC,7,7,37,10 - CONTROL "Add Bones",IDC_ADD_BONES_BUTTON,"CustButton",WS_TABSTOP, - 7,22,94,13 - CONTROL "Remove Bones",IDC_REMOVE_BONES_BUTTON,"CustButton", - WS_TABSTOP,7,39,94,13 - GROUPBOX "Bones",IDC_STATIC,7,63,94,67 - LISTBOX IDC_BONE_LIST,13,75,81,49,LBS_SORT | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP -END - -IDD_SKIN_SOT DIALOG DISCARDABLE 0, 0, 108, 22 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "- All Geometric Objects",IDC_STATIC,7,7,94,8 -END - -IDD_GAMEMTL_PANEL DIALOG DISCARDABLE 0, 0, 217, 286 -STYLE DS_3DLOOK | WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "User1",IDC_DIFFUSE_COLOR,"ColorSwatch",0x0,65,9,34,12 - LTEXT "Diffuse Color:",IDC_STATIC,13,13,43,8 - GROUPBOX "Maps",IDC_STATIC,7,73,203,154 - GROUPBOX "Lighting Coefficients",IDC_STATIC,7,231,203,47 - CONTROL "Diffuse Color:",IDC_MAPON_DCT,"Button",BS_AUTOCHECKBOX, - 11,87,64,10 - PUSHBUTTON "None",IDC_DCT_BUTTON,75,86,132,11 - CONTROL "",IDC_DCT_FRAMES_EDIT,"CustEdit",WS_TABSTOP,37,103,19, - 10 - CONTROL "",IDC_DCT_FRAMES_SPIN,"SpinnerControl",0x0,57,103,7,10 - LTEXT "Frames:",IDC_STATIC,11,104,26,8 - CONTROL "Specular Color:",IDC_MAPON_SCT,"Button",BS_AUTOCHECKBOX, - 11,159,64,10 - PUSHBUTTON "None",IDC_SCT_BUTTON,75,158,132,11 - CONTROL "Diffuse Light:",IDC_MAPON_DIT,"Button",BS_AUTOCHECKBOX, - 11,123,64,10 - PUSHBUTTON "None",IDC_DIT_BUTTON,75,122,132,11 - CONTROL "Specular Light:",IDC_MAPON_SIT,"Button",BS_AUTOCHECKBOX, - 11,193,64,10 - PUSHBUTTON "None",IDC_SIT_BUTTON,75,192,132,11 - CONTROL "User1",IDC_SPECULAR_COLOR,"ColorSwatch",0x0,65,25,34,12 - LTEXT "Specular Color:",IDC_STATIC,14,29,49,8 - LTEXT "Opacity:",IDC_STATIC,110,11,27,8 - LTEXT "Emissive:",IDC_STATIC,87,260,30,8 - CONTROL "",IDC_OPACITY_EDIT,"CustEdit",WS_TABSTOP,160,9,37,10 - CONTROL "",IDC_OPACITY_SPIN,"SpinnerControl",0x0,198,9,7,10 - LTEXT "Shininess:",IDC_STATIC,110,37,33,8 - LTEXT "Translucency:",IDC_STATIC,110,24,46,8 - CONTROL "",IDC_TRANSULCENCY_EDIT,"CustEdit",WS_TABSTOP,160,22,37, - 10 - CONTROL "",IDC_TRANSLUCENCY_SPIN,"SpinnerControl",0x0,198,22,7, - 10 - CONTROL "Ambient Coefficients",IDC_AMBIENT_COEFF,"ColorSwatch", - 0x0,44,244,34,12 - CONTROL "Diffuse Coefficients",IDC_DIFFUSE_COEFF,"ColorSwatch", - 0x0,44,258,34,12 - LTEXT "Ambient:",IDC_STATIC,13,245,28,8 - LTEXT "Diffuse:",IDC_STATIC,16,260,25,8 - CONTROL "Emissive Coefficients",IDC_EMISSIVE_COEFF,"ColorSwatch", - 0x0,119,258,34,12 - CONTROL "Specular Coefficients",IDC_SPECULAR_COEFF,"ColorSwatch", - 0x0,119,243,34,12 - LTEXT "Mapping:",IDC_STATIC,117,104,30,8 - LTEXT "Specular:",IDC_STATIC,86,245,31,8 - COMBOBOX IDC_DCT_MAPPING_COMBO,151,101,56,87,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - CONTROL "Use Alpha",IDC_USE_ALPHA_CHECK,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,14,44,49,10 - CONTROL "Use Sorting",IDC_USE_SORTING_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,14,58,53,10 - LTEXT "Rate:",IDC_STATIC,68,104,18,8 - CONTROL "",IDC_DCT_RATE_EDIT,"CustEdit",WS_TABSTOP,88,103,19,10 - CONTROL "",IDC_DCT_RATE_SPIN,"SpinnerControl",0x0,108,103,7,10 - CONTROL "",IDC_DIT_FRAMES_EDIT,"CustEdit",WS_TABSTOP,38,139,19, - 10 - CONTROL "",IDC_DIT_FRAMES_SPIN,"SpinnerControl",0x0,58,139,7,10 - LTEXT "Frames:",IDC_STATIC,12,141,26,8 - LTEXT "Mapping:",IDC_STATIC,118,141,30,8 - COMBOBOX IDC_DIT_MAPPING_COMBO,152,138,56,87,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Rate:",IDC_STATIC,68,141,18,8 - CONTROL "",IDC_DIT_RATE_EDIT,"CustEdit",WS_TABSTOP,88,139,19,10 - CONTROL "",IDC_DIT_RATE_SPIN,"SpinnerControl",0x0,108,139,7,10 - CONTROL "",IDC_SCT_FRAMES_EDIT,"CustEdit",WS_TABSTOP,37,176,19, - 10 - CONTROL "",IDC_SCT_FRAMES_SPIN,"SpinnerControl",0x0,57,176,7,10 - LTEXT "Frames:",IDC_STATIC,11,177,26,8 - LTEXT "Mapping:",IDC_STATIC,117,177,30,8 - COMBOBOX IDC_SCT_MAPPING_COMBO,151,174,56,87,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Rate:",IDC_STATIC,68,177,18,8 - CONTROL "",IDC_SCT_RATE_EDIT,"CustEdit",WS_TABSTOP,88,176,19,10 - CONTROL "",IDC_SCT_RATE_SPIN,"SpinnerControl",0x0,108,176,7,10 - CONTROL "",IDC_SIT_FRAMES_EDIT,"CustEdit",WS_TABSTOP,38,210,19, - 10 - CONTROL "",IDC_SIT_FRAMES_SPIN,"SpinnerControl",0x0,58,210,7,10 - LTEXT "Frames:",IDC_STATIC,12,211,26,8 - LTEXT "Mapping:",IDC_STATIC,118,211,30,8 - COMBOBOX IDC_SIT_MAPPING_COMBO,152,208,56,87,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Rate:",IDC_STATIC,69,211,18,8 - CONTROL "",IDC_SIT_RATE_EDIT,"CustEdit",WS_TABSTOP,89,210,19,10 - CONTROL "",IDC_SIT_RATE_SPIN,"SpinnerControl",0x0,109,210,7,10 - CONTROL "",IDC_FOG_EDIT,"CustEdit",WS_TABSTOP,177,245,19,10 - CONTROL "",IDC_FOG_SPIN,"SpinnerControl",0x0,197,245,7,10 - LTEXT "Fog:",IDC_STATIC,160,245,15,8 - CONTROL "",IDC_SHININESS_EDIT,"CustEdit",WS_TABSTOP,160,35,37,10 - CONTROL "",IDC_SHININESS_SPIN,"SpinnerControl",0x0,198,35,7,10 - CONTROL "Display in Viewport",IDC_VIEWPORT_DISPLAY_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,110,58,75,10 -END - -IDD_GAMEMTL_NOTES_PANEL DIALOG DISCARDABLE 0, 0, 217, 58 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "Texture Maps are subject to the following limitations:", - IDC_STATIC,8,19,164,8 - LTEXT "Width and height must be a power of 2",IDC_STATIC,16,30, - 123,8 - LTEXT "Maximum width and height is 256",IDC_STATIC,16,41,105,8 - LTEXT "All maps must be Bitmap Textures which use Targa files", - IDC_STATIC,7,8,175,8 -END - -IDD_GAMEMTL_HINTS_PANEL DIALOG DISCARDABLE 0, 0, 217, 79 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Favor diffuse light texture over diffuse color texture", - IDC_DIT_OVER_DCT_CHECK,"Button",BS_AUTOCHECKBOX | - BS_CENTER | BS_PUSHLIKE | WS_TABSTOP,8,9,204,10 - CONTROL "Favor specular light texture over specular color texture", - IDC_SIT_OVER_SCT_CHECK,"Button",BS_AUTOCHECKBOX | - BS_CENTER | BS_PUSHLIKE | WS_TABSTOP,8,22,204,10 - CONTROL "Favor diffuse light texture over calculated diffuse lighting", - IDC_DIT_OVER_DIG_CHECK,"Button",BS_AUTOCHECKBOX | - BS_CENTER | BS_PUSHLIKE | WS_TABSTOP,8,35,204,10 - CONTROL "Favor specular light texture over calculated specular lighting", - IDC_SIT_OVER_SIG_CHECK,"Button",BS_AUTOCHECKBOX | - BS_CENTER | BS_PUSHLIKE | WS_TABSTOP,8,48,204,10 - CONTROL "Allow fast specular after alpha", - IDC_FAST_SPECULAR_AFTER_ALPHA_CHECK,"Button", - BS_AUTOCHECKBOX | BS_CENTER | BS_PUSHLIKE | WS_TABSTOP,8, - 61,204,10 -END - -IDD_GAMEMTL_PSX_PANEL DIALOG DISCARDABLE 0, 0, 217, 66 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "None",IDC_NO_TRANS,"Button",BS_AUTORADIOBUTTON,17,32,33, - 10 - GROUPBOX "Translucency",IDC_STATIC,7,21,203,38 - CONTROL "100%",IDC_100_TRANS,"Button",BS_AUTORADIOBUTTON,17,45, - 33,10 - CONTROL "50%",IDC_50_TRANS,"Button",BS_AUTORADIOBUTTON,91,33,29, - 10 - CONTROL "25%",IDC_25_TRANS,"Button",BS_AUTORADIOBUTTON,91,45,29, - 10 - CONTROL "-100%",IDC_MINUS_100_TRANS,"Button",BS_AUTORADIOBUTTON, - 161,33,35,10 - CONTROL "Disable real-time lighting",IDC_NO_RT_LIGHTING,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,17,9,91,10 -END - -IDD_GAMEMTL_PASS DIALOG DISCARDABLE 0, 0, 217, 184 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Tab1",IDC_GAMEMTL_TAB,"SysTabControl32",0x0,7,7,203,170 -END - -IDD_GAMEMTL_VERTEX_MATERIAL DIALOG DISCARDABLE 0, 0, 198, 151 -STYLE WS_CHILD | WS_CAPTION -CAPTION "Vertex Material" -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Ambient Color",IDC_AMBIENT_COLOR,"ColorSwatch",0x0,46,4, - 34,12 - CONTROL "Diffuse Color",IDC_DIFFUSE_COLOR,"ColorSwatch",0x0,46, - 19,34,12 - CONTROL "Specular Color",IDC_SPECULAR_COLOR,"ColorSwatch",0x0,46, - 34,34,12 - CONTROL "Emissive Color",IDC_EMISSIVE_COLOR,"ColorSwatch",0x0,46, - 49,34,12 - CONTROL "",IDC_OPACITY_EDIT,"CustEdit",WS_TABSTOP,138,3,37,10 - CONTROL "",IDC_OPACITY_SPIN,"SpinnerControl",0x0,176,3,7,10 - CONTROL "",IDC_TRANSULCENCY_EDIT,"CustEdit",WS_TABSTOP,138,14,37, - 10 - CONTROL "",IDC_TRANSLUCENCY_SPIN,"SpinnerControl",0x0,176,14,7, - 10 - CONTROL "",IDC_SHININESS_EDIT,"CustEdit",WS_TABSTOP,138,25,37,10 - CONTROL "",IDC_SHININESS_SPIN,"SpinnerControl",0x0,176,25,7,10 - CONTROL "Specular To Diffuse",IDC_COPY_SPECULAR_DIFFUSE,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,92,41,79,10 - COMBOBOX IDC_MAPPING0_COMBO,27,79,65,87,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_MAPPING0_ARGS_EDIT,27,93,65,37,ES_MULTILINE | - ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN | - WS_VSCROLL - CONTROL "",IDC_STAGE0UVCHAN_EDIT,"CustEdit",WS_GROUP | - WS_TABSTOP,59,134,18,10 - CONTROL "",IDC_STAGE0UVCHAN_SPIN,"SpinnerControl",0x0,77,134,10, - 10 - COMBOBOX IDC_MAPPING1_COMBO,124,79,65,87,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_MAPPING1_ARGS_EDIT,124,93,65,37,ES_MULTILINE | - ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN | - WS_VSCROLL - CONTROL "",IDC_STAGE1UVCHAN_EDIT,"CustEdit",WS_GROUP | - WS_TABSTOP,152,134,18,10 - CONTROL "",IDC_STAGE1UVCHAN_SPIN,"SpinnerControl",0x0,170,134,10, - 10 - LTEXT "Ambient:",IDC_STATIC,9,6,28,8 - LTEXT "Diffuse:",IDC_STATIC,9,21,25,8 - LTEXT "Specular:",IDC_STATIC,9,36,31,8 - LTEXT "Emissive:",IDC_STATIC,9,51,30,8 - LTEXT "Opacity:",IDC_STATIC,88,3,27,8 - LTEXT "Translucency:",IDC_STATIC,88,13,46,8 - LTEXT "Shininess:",IDC_STATIC,88,23,33,8 - GROUPBOX "Stage 0 Mapping",IDC_STATIC,3,67,94,81 - LTEXT "Type:",IDC_STATIC,8,79,19,8 - LTEXT "Args:",IDC_STATIC,8,92,17,8 - LTEXT "UV Channel:",IDC_STATIC,9,134,41,8 - LTEXT "UV Channel:",IDC_STATIC,104,134,41,8 - GROUPBOX "Stage 1 Mapping",IDC_STATIC,99,67,96,81 - LTEXT "Type:",IDC_STATIC,104,79,19,8 - LTEXT "Args:",IDC_STATIC,104,92,17,8 -END - -IDD_GAMEMTL_SHADER DIALOG DISCARDABLE 0, 0, 198, 134 -STYLE WS_CHILD | WS_CAPTION -CAPTION "Shader" -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "Blend",IDC_STATIC,7,0,184,73 - LTEXT "Blend Mode:",IDC_STATIC,30,15,41,8 - COMBOBOX IDC_PRESET_COMBO,73,13,94,131,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - GROUPBOX "Custom",IDC_STATIC,13,30,172,40 - LTEXT "Src:",IDC_STATIC,16,41,15,11 - COMBOBOX IDC_SRCBLEND_COMBO,34,40,62,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Dest:",IDC_STATIC,99,41,16,11 - COMBOBOX IDC_DESTBLEND_COMBO,119,40,62,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - CONTROL "Write ZBuffer",IDC_DEPTHMASK_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,25,56,58,10 - CONTROL "Alpha Test",IDC_ALPHATEST_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,110,56,50,10 - GROUPBOX "Advanced",IDC_STATIC,7,74,184,57 - PUSHBUTTON "Defaults",IDC_SHADER_DEFAULTS_BUTTON,18,87,34,12 - LTEXT "Pri Gradient:",IDC_STATIC,71,80,40,8 - COMBOBOX IDC_PRIGRADIENT_COMBO,71,90,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Sec Gradient:",IDC_STATIC,131,80,44,8 - COMBOBOX IDC_SECGRADIENT_COMBO,131,90,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Depth Cmp:",IDC_STATIC,11,104,38,8 - COMBOBOX IDC_DEPTHCOMPARE_COMBO,11,114,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Detail Color:",IDC_STATIC,71,104,39,8 - COMBOBOX IDC_DETAILCOLOR_COMBO,71,114,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Detail Alpha:",IDC_STATIC,131,104,41,8 - COMBOBOX IDC_DETAILALPHA_COMBO,131,114,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP -END - -IDD_GAMEMTL_TEXTURES DIALOG DISCARDABLE 0, 0, 198, 135 -STYLE WS_CHILD | WS_CAPTION -CAPTION "Textures" -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "",IDC_STATIC,7,0,184,65 - PUSHBUTTON "None",IDC_STAGE0_BUTTON,14,11,104,11 - CONTROL "Publish",IDC_STAGE0_PUBLISH_BUTTON,"CustButton", - WS_TABSTOP,121,11,29,11 - CONTROL "Display",IDC_STAGE0_DISPLAY_BUTTON,"CustButton", - WS_TABSTOP,154,11,29,11 - CONTROL "Clamp U",IDC_STAGE0_CLAMP_U_BUTTON,"CustButton", - WS_TABSTOP,14,24,34,11 - CONTROL "Clamp V",IDC_STAGE0_CLAMP_V_BUTTON,"CustButton", - WS_TABSTOP,51,24,34,11 - LTEXT "Frames:",IDC_STATIC,15,37,26,8 - CONTROL "",IDC_STAGE0_FRAMES_EDIT,"CustEdit",WS_TABSTOP,41,37,19, - 10 - CONTROL "",IDC_STAGE0_FRAMES_SPIN,"SpinnerControl",0x0,61,37,7, - 10 - LTEXT "Rate:",IDC_STATIC,79,37,18,8 - CONTROL "",IDC_STAGE0_RATE_EDIT,"CustEdit",WS_TABSTOP,98,37,19, - 10 - CONTROL "",IDC_STAGE0_RATE_SPIN,"SpinnerControl",0x0,118,37,7,10 - COMBOBOX IDC_STAGE0_ANIM_COMBO,135,37,48,63,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Pass Hint:",IDC_STATIC,15,49,33,8 - COMBOBOX IDC_STAGE0_HINT_COMBO,50,48,75,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - CONTROL "Alpha Button",IDC_STAGE0_ALPHA_BITMAP_BUTTON,"CustButton", - WS_TABSTOP,135,51,47,11 - GROUPBOX "",IDC_STATIC,7,65,184,66 - CONTROL "Stage 1 Texture (Detail Texture)",IDC_STAGE1_ENABLE, - "Button",BS_AUTOCHECKBOX,13,65,117,10 - PUSHBUTTON "None",IDC_STAGE1_BUTTON,14,76,104,11 - CONTROL "Stage 0 Texture ",IDC_STAGE0_ENABLE,"Button", - BS_AUTOCHECKBOX,13,0,68,10 - CONTROL "Publish",IDC_STAGE1_PUBLISH_BUTTON,"CustButton", - WS_TABSTOP,121,76,29,11 - CONTROL "Display",IDC_STAGE1_DISPLAY_BUTTON,"CustButton", - WS_TABSTOP,154,76,29,11 - CONTROL "Clamp U",IDC_STAGE1_CLAMP_U_BUTTON,"CustButton", - WS_TABSTOP,14,89,34,11 - CONTROL "Clamp V",IDC_STAGE1_CLAMP_V_BUTTON,"CustButton", - WS_TABSTOP,51,89,34,11 - LTEXT "Frames:",IDC_STATIC,15,102,26,8 - CONTROL "",IDC_STAGE1_FRAMES_EDIT,"CustEdit",WS_TABSTOP,41,102, - 19,10 - CONTROL "",IDC_STAGE1_FRAMES_SPIN,"SpinnerControl",0x0,61,102,7, - 10 - LTEXT "Rate:",IDC_STATIC,79,102,18,8 - CONTROL "",IDC_STAGE1_RATE_EDIT,"CustEdit",WS_TABSTOP,100,102,19, - 10 - CONTROL "",IDC_STAGE1_RATE_SPIN,"SpinnerControl",0x0,120,102,7, - 10 - COMBOBOX IDC_STAGE1_ANIM_COMBO,135,102,48,63,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Pass Hint:",IDC_STATIC,15,113,33,8 - COMBOBOX IDC_STAGE1_HINT_COMBO,50,113,75,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - CONTROL "Alpha Button",IDC_STAGE1_ALPHA_BITMAP_BUTTON,"CustButton", - WS_TABSTOP,135,117,47,11 - CONTROL "NoLOD",IDC_STAGE0_NOLOD_BUTTON,"CustButton",WS_TABSTOP, - 87,24,34,11 - CONTROL "NoLOD",IDC_STAGE1_NOLOD_BUTTON,"CustButton",WS_TABSTOP, - 87,89,34,11 -END - -IDD_GAMEMTL_PASS_COUNT DIALOGEX 0, 0, 217, 27 -STYLE WS_CHILD | WS_VISIBLE -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - PUSHBUTTON "Change",IDC_SETPASSCOUNT,146,8,41,11 - CTEXT "1",IDC_GAMEMTL_PASSCOUNT_STATIC,96,8,20,11,0, - WS_EX_CLIENTEDGE - LTEXT "Current Pass Count:",IDC_STATIC,26,9,64,8 -END - -IDD_GAMEMTL_PASS_COUNT_DIALOG DIALOG DISCARDABLE 0, 0, 190, 45 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Set pass count" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,133,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,133,23,50,14 - CONTROL "woohoo!",IDC_PASSCOUNT_SPIN,"SpinnerControl",WS_TABSTOP, - 113,16,10,12 - CONTROL "Custom1",IDC_PASSCOUNT_EDIT,"CustEdit",WS_TABSTOP,90,16, - 22,12 - LTEXT "Set number of passes",IDC_STATIC,15,17,70,11 -END - -IDD_GENERATE_NAMES_DIALOG DIALOG DISCARDABLE 0, 0, 201, 199 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Generate Node Names" -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "",IDC_STATIC,7,7,130,50 - CONTROL "Assign Names",IDC_ASSIGN_NAMES_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,15,7,61,10 - GROUPBOX "",IDC_STATIC,7,131,130,42 - CONTROL "Assign Collision Bits",IDC_ASSIGN_COLLISION_BITS_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,131,77,10 - DEFPUSHBUTTON "OK",IDOK,141,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,141,24,50,14 - LTEXT "Root Name:",IDC_STATIC,15,20,39,8 - EDITTEXT IDC_BASE_NAME_EDIT,62,17,63,14,ES_AUTOHSCROLL - LTEXT "Starting Name Index:",IDC_STATIC,15,40,67,8 - CONTROL "",IDC_NAME_INDEX_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP, - 87,39,28,10 - CONTROL "",IDC_NAME_INDEX_SPIN,"SpinnerControl",0x0,115,39,10,10 - CONTROL "Affect All",IDC_AFFECT_ALL_RADIO,"Button", - BS_AUTORADIOBUTTON,15,179,44,10 - CONTROL "Affect Selected",IDC_AFFECT_SELECTED_RADIO,"Button", - BS_AUTORADIOBUTTON,67,179,65,10 - CONTROL "Physical",IDC_COLLISION_PHYSICAL,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,15,146,42,10 - CONTROL "Vis",IDC_COLLISION_VIS,"Button",BS_AUTOCHECKBOX,63,146, - 25,10 - CONTROL "Projectile",IDC_COLLISION_PROJECTILE,"Button", - BS_AUTOCHECKBOX,15,158,45,10 - GROUPBOX "",IDC_STATIC,7,60,130,31 - CONTROL "Assign Prefix",IDC_ASSIGN_PREFIX_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,15,59,56,10 - LTEXT "Prefix:",IDC_STATIC,15,74,20,8 - EDITTEXT IDC_PREFIX_EDIT,62,71,63,14,ES_AUTOHSCROLL - GROUPBOX "",IDC_STATIC,7,96,130,31 - CONTROL "Assign Suffix",IDC_ASSIGN_SUFFIX_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,15,95,56,10 - LTEXT "Suffix:",IDC_STATIC,15,109,20,8 - EDITTEXT IDC_SUFFIX_EDIT,61,106,63,14,ES_AUTOHSCROLL - LTEXT "Remember that W3D names must be no longer than 15 characters. Using Prefix or Suffix can exceed this limit.", - IDC_STATIC,142,42,52,75 -END - -IDD_MESH_DEFORM_PANEL DIALOG DISCARDABLE 0, 0, 108, 168 -STYLE WS_CHILD | WS_CLIPSIBLINGS -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "Vertex &Color:",IDC_STATIC,7,7,41,8 - CONTROL "Vertex Color",IDC_VERTEX_COLOR,"ColorSwatch",0x0,53,3, - 48,15 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,4,24,98,1 - LTEXT "Deform &Progression",IDC_STATIC,7,21,62,8 - CONTROL "Slider1",IDC_STATE_SLIDER,"msctls_trackbar32", - TBS_AUTOTICKS | WS_TABSTOP,7,33,94,12 - CONTROL 130,IDC_STATIC,"Static",SS_BITMAP,9,50,11,10 - CONTROL 131,IDC_STATIC,"Static",SS_BITMAP,89,50,11,10 - CONTROL "Link Set States",IDC_LOCK_SETS,"CustButton",WS_TABSTOP, - 7,66,70,13 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,4,86,99,1 - LTEXT "&Deform Sets",IDC_STATIC,7,82,40,8 - LTEXT "&Max Sets:",IDC_STATIC,11,95,32,8 - CONTROL "",IDC_MAX_SETS_EDIT,"CustEdit",WS_TABSTOP,55,95,22,10 - CONTROL "",IDC_MAX_SETS_SPIN,"SpinnerControl",WS_TABSTOP,79,95, - 10,10 - LTEXT "Current Set:",IDC_STATIC,11,111,38,8 - LTEXT "Static",IDC_CURRENT_SET_STATIC,55,110,30,11,SS_SUNKEN - CONTROL "Slider1",IDC_CURRENT_SET_SLIDER,"msctls_trackbar32", - TBS_AUTOTICKS | WS_TABSTOP,7,123,94,12 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,4,145,99,1 - LTEXT "&Runtime Options",IDC_STATIC,7,141,53,8 - CONTROL "&Manual Deform",IDC_MANUALAPPLY,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,11,153,64,10 -END - -IDD_GAMEMTL_SURFACE_TYPE DIALOG DISCARDABLE 0, 0, 217, 42 -STYLE WS_CHILD | WS_VISIBLE -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "Surface &Type:",IDC_STATIC,26,9,46,8 - COMBOBOX IDC_SURFACE_TYPE_COMBO,77,7,133,77,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Static Sorting Level:",IDC_STATIC,8,25,64,8 - CONTROL "Enabled",IDC_ENABLE_SORT_LEVEL,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,77,25,42,10 - CONTROL "",IDC_SORT_LEVEL,"CustEdit",WS_TABSTOP,123,25,19,10 - CONTROL "",IDC_SORT_LEVEL_SPIN,"SpinnerControl",0x0,143,25,7,10 -END - -IDD_GAMEMTL_DISPLACEMENT_MAP DIALOG DISCARDABLE 0, 0, 217, 25 -STYLE WS_CHILD | WS_VISIBLE -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "None",IDC_TEXTURE_BUTTON,106,7,104,11 - RTEXT "Amount:",IDC_STATIC,7,8,55,8 - CONTROL "",IDC_AMOUNT_EDIT,"CustEdit",WS_TABSTOP,67,8,19,10 - CONTROL "",IDC_AMOUNT_SPIN,"SpinnerControl",0x0,87,8,7,10 -END - -IDD_GENERATE_MTL_NAMES_DIALOG DIALOG DISCARDABLE 0, 0, 204, 70 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Generate Material Names" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,147,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,147,25,50,14 - LTEXT "Root Name:",IDC_STATIC,15,12,39,8 - EDITTEXT IDC_BASE_NAME_EDIT,62,9,63,14,ES_AUTOHSCROLL - LTEXT "Starting Name Index:",IDC_STATIC,15,32,67,8 - CONTROL "",IDC_NAME_INDEX_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP, - 87,31,28,10 - CONTROL "",IDC_NAME_INDEX_SPIN,"SpinnerControl",0x0,115,31,10,10 - CONTROL "Affect All",IDC_AFFECT_ALL_RADIO,"Button", - BS_AUTORADIOBUTTON,15,51,44,10 - CONTROL "Affect Selected",IDC_AFFECT_SELECTED_RADIO,"Button", - BS_AUTORADIOBUTTON,67,51,65,10 -END - -IDD_GENERATE_LOD_EXTENSION_DIALOG DIALOG DISCARDABLE 0, 0, 203, 86 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Generate Extensions" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,146,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,146,24,50,14 - LTEXT "This will append an extension to the currently selected objects. LOD 0 should be your highest-poly model, with increasing LOD numbers going to your lower-poly models. Damage models should be extension numbers 1 and up.", - IDC_STATIC,7,45,189,34 - LTEXT "Extension number:",IDC_STATIC,21,20,59,8 - CONTROL "",IDC_LOD_INDEX_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP, - 85,19,28,10 - CONTROL "",IDC_LOD_INDEX_SPIN,"SpinnerControl",0x0,113,19,10,10 -END - -IDD_EXPORT_ALL DIALOG DISCARDABLE 0, 0, 203, 74 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Export All Max Scenes" -FONT 8, "MS Sans Serif" -BEGIN - EDITTEXT IDC_DIRECTORY,35,14,107,14,ES_AUTOHSCROLL - PUSHBUTTON "&Browse...",IDC_BROWSE,146,14,50,14 - CONTROL "Traverse &Subfolders",IDC_RECURSIVE,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,35,34,79,10 - DEFPUSHBUTTON "OK",IDOK,87,53,50,14 - PUSHBUTTON "Cancel",IDCANCEL,146,53,50,14 - LTEXT "Folder:",IDC_STATIC,7,17,22,8 -END - -IDD_SCENE_SETUP DIALOG DISCARDABLE 0, 0, 222, 245 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "LOD and Damage Configuration" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,165,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,165,24,50,14 - GROUPBOX "LOD",IDC_STATIC,7,7,144,114 - LTEXT "Number of LODs to create:",IDC_STATIC,15,20,86,8 - LTEXT "Offset from original (X Axis):",IDC_STATIC,15,36,86,8 - EDITTEXT IDC_LOD_COUNT,112,18,25,14,ES_AUTOHSCROLL | ES_NUMBER - EDITTEXT IDC_LOD_OFFSET,112,34,25,14,ES_AUTOHSCROLL - GROUPBOX "Create as",IDC_STATIC,17,52,84,61 - CONTROL "Copies",IDC_LOD_AS_COPY,"Button",BS_AUTORADIOBUTTON | - WS_TABSTOP,35,66,37,10 - CONTROL "Instances",IDC_LOD_AS_INSTANCE,"Button", - BS_AUTORADIOBUTTON,35,81,47,10 - CONTROL "References",IDC_LOD_AS_REFERENCE,"Button", - BS_AUTORADIOBUTTON,35,96,53,10 - GROUPBOX "Damage",IDC_STATIC,7,124,144,114 - LTEXT "Number of damage models:",IDC_STATIC,15,140,87,8 - LTEXT "Offset from original (Y Axis):",IDC_STATIC,15,154,86,8 - EDITTEXT IDC_DAMAGE_COUNT,112,137,25,14,ES_AUTOHSCROLL | - ES_NUMBER - EDITTEXT IDC_DAMAGE_OFFSET,112,153,25,14,ES_AUTOHSCROLL - GROUPBOX "Create as",IDC_STATIC,15,170,86,64 - CONTROL "Copies",IDC_DAMAGE_AS_COPY,"Button",BS_AUTORADIOBUTTON | - WS_TABSTOP,35,186,37,10 - CONTROL "Instances",IDC_DAMAGE_AS_INSTANCE,"Button", - BS_AUTORADIOBUTTON,35,200,47,10 - CONTROL "References",IDC_DAMAGE_AS_REFERENCE,"Button", - BS_AUTORADIOBUTTON,35,214,53,10 -END - -IDD_GAMEMTL_PS2_SHADER DIALOGEX 0, 0, 198, 134 -STYLE WS_CHILD | WS_CAPTION -CAPTION "Playstation 2 Shader" -FONT 8, "MS Sans Serif", 0, 0, 0x1 -BEGIN - GROUPBOX "Blend",IDC_STATIC,7,0,184,73 - LTEXT "Blend Mode:",IDC_STATIC,31,9,41,8 - COMBOBOX IDC_PS2_PRESET_COMBO,75,7,94,131,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - GROUPBOX "Custom",IDC_STATIC,13,30,172,40 - LTEXT "A:",IDC_STATIC,15,38,15,11 - COMBOBOX IDC_A_COMBO,32,38,62,157,CBS_DROPDOWNLIST | WS_VSCROLL | - WS_TABSTOP - LTEXT "B:",IDC_STATIC,98,38,16,11 - COMBOBOX IDC_B_COMBO,118,38,62,157,CBS_DROPDOWNLIST | WS_VSCROLL | - WS_TABSTOP - CONTROL "ZBuffer",IDC_DEPTHMASK_CHECK,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,132,83,39,10 - CONTROL "Alpha Test",IDC_ALPHATEST_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,132,95,50,10 - GROUPBOX "Advanced",IDC_STATIC,7,74,184,57 - PUSHBUTTON "Defaults",IDC_SHADER_DEFAULTS_BUTTON,18,87,34,12 - LTEXT "Pri Gradient:",IDC_STATIC,71,80,40,8 - COMBOBOX IDC_PRIGRADIENT_COMBO,71,90,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Depth Cmp:",IDC_STATIC,11,104,38,8 - COMBOBOX IDC_DEPTHCOMPARE_COMBO,11,114,57,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - LTEXT "Detail Color:",IDC_STATIC,71,104,39,8,WS_DISABLED - COMBOBOX IDC_DETAILCOLOR_COMBO,71,114,57,157,CBS_DROPDOWNLIST | - WS_DISABLED | WS_VSCROLL | WS_TABSTOP - LTEXT "Detail Alpha:",IDC_STATIC,131,104,41,8,WS_DISABLED - COMBOBOX IDC_DETAILALPHA_COMBO,131,114,57,157,CBS_DROPDOWNLIST | - WS_DISABLED | WS_VSCROLL | WS_TABSTOP - LTEXT "(A - B) * C + D",IDC_STATIC,15,20,60,10 - LTEXT "D:",IDC_STATIC,98,52,15,11 - COMBOBOX IDC_D_COMBO,118,52,62,157,CBS_DROPDOWNLIST | WS_VSCROLL | - WS_TABSTOP - LTEXT "C:",IDC_STATIC,15,52,15,11 - COMBOBOX IDC_C_COMBO,32,52,62,157,CBS_DROPDOWNLIST | WS_VSCROLL | - WS_TABSTOP - CONTROL "",IDC_COMPATIBLE,"RICHEDIT",ES_READONLY | ES_NUMBER | - WS_BORDER | WS_TABSTOP,100,20,79,14,WS_EX_DLGMODALFRAME -END - -IDD_GAMEMTL_PS2_TEXTURES DIALOG DISCARDABLE 0, 0, 198, 135 -STYLE WS_CHILD | WS_CAPTION -CAPTION "Textures" -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "",IDC_STATIC,7,0,184,65 - PUSHBUTTON "None",IDC_STAGE0_BUTTON,14,11,104,11 - CONTROL "Publish",IDC_STAGE0_PUBLISH_BUTTON,"CustButton", - WS_TABSTOP,121,11,29,11 - CONTROL "Display",IDC_STAGE0_DISPLAY_BUTTON,"CustButton", - WS_TABSTOP,154,11,29,11 - CONTROL "Clamp U",IDC_STAGE0_CLAMP_U_BUTTON,"CustButton", - WS_TABSTOP,14,24,40,11 - CONTROL "Clamp V",IDC_STAGE0_CLAMP_V_BUTTON,"CustButton", - WS_TABSTOP,60,24,40,11 - LTEXT "Frames:",IDC_STATIC,15,37,26,8,WS_DISABLED - CONTROL "",IDC_STAGE0_FRAMES_EDIT,"CustEdit",WS_DISABLED | - WS_TABSTOP,41,37,19,10 - CONTROL "",IDC_STAGE0_FRAMES_SPIN,"SpinnerControl",WS_DISABLED, - 61,37,7,10 - LTEXT "Rate:",IDC_STATIC,79,37,18,8,WS_DISABLED - CONTROL "",IDC_STAGE0_RATE_EDIT,"CustEdit",WS_DISABLED | - WS_TABSTOP,98,37,19,10 - CONTROL "",IDC_STAGE0_RATE_SPIN,"SpinnerControl",WS_DISABLED,118, - 37,7,10 - COMBOBOX IDC_STAGE0_ANIM_COMBO,135,37,48,63,CBS_DROPDOWNLIST | - WS_DISABLED | WS_VSCROLL | WS_TABSTOP - LTEXT "Pass Hint:",IDC_STATIC,15,49,33,8 - COMBOBOX IDC_STAGE0_HINT_COMBO,50,48,75,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - CONTROL "Alpha Button",IDC_STAGE0_ALPHA_BITMAP_BUTTON,"CustButton", - WS_TABSTOP,135,51,47,11 - CONTROL "Stage 1 Texture (Detail Texture)",IDC_STAGE1_ENABLE, - "Button",BS_AUTOCHECKBOX,13,65,117,10 - PUSHBUTTON "None",IDC_STAGE1_BUTTON,14,76,104,11 - CONTROL "hoax",IDC_STAGE1_PUBLISH_BUTTON,"CustButton",WS_TABSTOP, - 121,76,29,11 - CONTROL "hoax",IDC_STAGE1_DISPLAY_BUTTON,"CustButton",WS_TABSTOP, - 154,76,29,11 - CONTROL "Clamp U",IDC_STAGE1_CLAMP_U_BUTTON,"CustButton", - WS_TABSTOP,14,89,40,11 - CONTROL "Clamp V",IDC_STAGE1_CLAMP_V_BUTTON,"CustButton", - WS_TABSTOP,60,89,40,11 - LTEXT "Frames:",IDC_STATIC,15,102,26,8,WS_DISABLED - CONTROL "",IDC_STAGE1_FRAMES_EDIT,"CustEdit",WS_DISABLED | - WS_TABSTOP,41,102,19,10 - CONTROL "",IDC_STAGE1_FRAMES_SPIN,"SpinnerControl",WS_DISABLED, - 61,102,7,10 - LTEXT "Rate:",IDC_STATIC,79,102,18,8,WS_DISABLED - CONTROL "",IDC_STAGE1_RATE_EDIT,"CustEdit",WS_DISABLED | - WS_TABSTOP,100,102,19,10 - CONTROL "",IDC_STAGE1_RATE_SPIN,"SpinnerControl",WS_DISABLED,120, - 102,7,10 - COMBOBOX IDC_STAGE1_ANIM_COMBO,135,102,48,63,CBS_DROPDOWNLIST | - WS_DISABLED | WS_VSCROLL | WS_TABSTOP - LTEXT "Pass Hint:",IDC_STATIC,15,113,33,8 - COMBOBOX IDC_STAGE1_HINT_COMBO,50,113,75,157,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_TABSTOP - CONTROL "Alpha Button",IDC_STAGE1_ALPHA_BITMAP_BUTTON,"CustButton", - WS_TABSTOP,135,117,47,11 - CONTROL "Stage 0 Texture ",IDC_STAGE0_ENABLE,"Button", - BS_AUTOCHECKBOX,13,0,68,10 - GROUPBOX "",IDC_STATIC,7,65,184,66 - CONTROL "NoLOD",IDC_STAGE0_NOLOD_BUTTON,"CustButton",WS_TABSTOP, - 105,24,34,11 - CONTROL "NoLOD",IDC_STAGE1_NOLOD_BUTTON,"CustButton",WS_TABSTOP, - 105,89,34,11 -END - -IDD_ALPHA_MODIFIER DIALOG DISCARDABLE 0, 0, 100, 38 -STYLE WS_CHILD | WS_VISIBLE | WS_BORDER -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "",IDC_ALPHA_EDIT,"CustEdit",WS_TABSTOP,11,21,37,10 - CONTROL "",IDC_ALPHA_SPIN,"SpinnerControl",0x0,49,21,7,10 - LTEXT "Vertex Alpha Value:",IDC_STATIC,18,7,63,8, - SS_CENTERIMAGE - CONTROL "Find",IDC_ALPHA_CHECKBOX,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,62,21,29,10 -END - -IDD_W3D_LOG DIALOG DISCARDABLE 0, 0, 334, 319 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Animation Export Log" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,277,298,50,14 - CONTROL "Progress1",IDC_ANIM_COMPRESS_PROGRESS,"msctls_progress32", - PBS_SMOOTH | WS_BORDER,7,296,260,16 - CONTROL "",IDC_ANIM_LOG_RICHEDIT,"RICHEDIT",ES_MULTILINE | - ES_AUTOVSCROLL | ES_READONLY | ES_NUMBER | WS_BORDER | - WS_VSCROLL | WS_TABSTOP,7,7,320,282 -END - -IDD_INPUT_DIALOG DIALOG DISCARDABLE 0, 0, 197, 47 -STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE | - WS_CAPTION | WS_SYSMENU -CAPTION "Dialog Caption" -FONT 8, "MS Sans Serif" -BEGIN - EDITTEXT IDC_VALUE,7,24,129,14,ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,140,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,140,24,50,14 - LTEXT "Label",IDC_LABEL,7,7,129,17 -END - -IDD_W3DUTILITY_FLOATER_DIALOG DIALOG DISCARDABLE 0, 0, 114, 50 -STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "W3D Export Settings" -FONT 8, "MS Sans Serif" -BEGIN -END - -IDD_W3DUTILITY_SETTINGS_DIALOG DIALOG DISCARDABLE 0, 0, 108, 239 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "Object Export Options",-1,4,7,100,65 - CONTROL "Export Transform (Bone)",IDC_HIERARCHY_CHECK,"Button", - BS_3STATE | WS_GROUP | WS_TABSTOP,11,34,90,10 - CONTROL "Export Geometry",IDC_GEOMETRY_CHECK,"Button",BS_3STATE, - 11,46,68,10 - GROUPBOX "Geometry Options",-1,4,72,100,113 - CONTROL "Normal",IDC_GEOMETRY_NORMAL,"Button",BS_AUTORADIOBUTTON | - WS_GROUP,7,81,38,10 - CONTROL "Cam-Parallel",IDC_GEOMETRY_CAMERA_ALIGNED,"Button", - BS_AUTORADIOBUTTON,7,91,55,10 - CONTROL "Cam-Orient",IDC_GEOMETRY_CAMERA_ORIENTED,"Button", - BS_AUTORADIOBUTTON,7,102,51,10 - CONTROL "AABox",IDC_GEOMETRY_AABOX,"Button",BS_AUTORADIOBUTTON,7, - 113,37,10 - CONTROL "OBBox",IDC_GEOMETRY_OBBOX,"Button",BS_AUTORADIOBUTTON,7, - 124,38,10 - CONTROL "2Side",IDC_GEOMETRY_TWO_SIDED,"Button",BS_3STATE | - WS_GROUP | WS_TABSTOP,63,81,34,10 - CONTROL "Hide",IDC_GEOMETRY_HIDE,"Button",BS_3STATE,63,92,31,10 - CONTROL "ZNrm",IDC_GEOMETRY_ZNORMALS,"Button",BS_3STATE,63,103, - 33,10 - GROUPBOX "Collision Options",-1,4,185,100,50 - CONTROL "Physical",IDC_COLLISION_PHYSICAL,"Button",BS_3STATE | - WS_GROUP | WS_TABSTOP,14,198,42,10 - CONTROL "Projectile",IDC_COLLISION_PROJECTILE,"Button",BS_3STATE, - 14,210,45,10 - CONTROL "Vis",IDC_COLLISION_VIS,"Button",BS_3STATE,61,198,25,10 - CONTROL "VAlpha",IDC_GEOMETRY_VERTEX_ALPHA,"Button",BS_3STATE,63, - 114,39,10 - CONTROL "Null (LOD)",IDC_GEOMETRY_NULL,"Button", - BS_AUTORADIOBUTTON,7,135,49,10 - LTEXT "Damage Region:",-1,11,59,54,8 - CONTROL "",IDC_DAMREG_INDEX_EDIT,"CustEdit",WS_GROUP | - WS_TABSTOP,69,58,18,10 - CONTROL "",IDC_DAMREG_INDEX_SPIN,"SpinnerControl",0x0,88,58,10, - 10 - CONTROL "Shadw",IDC_GEOMETRY_CAST_SHADOW,"Button",BS_3STATE,63, - 126,38,10 - CONTROL "Shatter",IDC_GEOMETRY_SHATTERABLE,"Button",BS_3STATE,63, - 138,39,10 - CONTROL "Camera",IDC_COLLISION_CAMERA,"Button",BS_3STATE,61,210, - 40,10 - CONTROL "Dazzle",IDC_GEOMETRY_DAZZLE,"Button",BS_AUTORADIOBUTTON, - 7,156,37,10 - COMBOBOX IDC_DAZZLE_COMBO,8,168,90,86,CBS_DROPDOWN | WS_VSCROLL | - WS_TABSTOP - CONTROL "Object Name",IDC_OBJ_NAME,"CustEdit",WS_TABSTOP,11,18, - 88,12 - CONTROL "Aggregate",IDC_GEOMETRY_AGGREGATE,"Button", - BS_AUTORADIOBUTTON,7,146,49,10 - CONTROL "Vehicle",IDC_COLLISION_VEHICLE,"Button",BS_3STATE,14, - 222,39,10 - CONTROL "NPatch",IDC_GEOMETRY_NPATCH,"Button",BS_3STATE,63,150, - 40,10 -END - -IDD_W3DUTILITY_TOOLS_DIALOG DIALOG DISCARDABLE 0, 0, 108, 212 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - GROUPBOX "Naming Utilities",-1,4,85,100,67 - PUSHBUTTON "Assign Node Names",IDC_COLLECTION_NAMES_GENERATE,13,98, - 79,14 - GROUPBOX "Select by W3D Type",-1,4,3,100,80 - PUSHBUTTON "Select Bones",IDC_SELECT_HIERARCHY,13,14,79,14 - PUSHBUTTON "Select Geometry",IDC_SELECT_GEOMETRY,13,30,79,14 - PUSHBUTTON "Select Alpha Meshes",IDC_SELECT_ALPHA_MESHES,13,46,79, - 14 - PUSHBUTTON "Phys",IDC_SELECT_PHYSICAL,13,62,25,14 - PUSHBUTTON "Proj",IDC_SELECT_PROJECTILE,40,62,25,14 - PUSHBUTTON "Vis",IDC_SELECT_VIS,67,62,25,14 - PUSHBUTTON "Assign Material Names",IDC_MATERIAL_NAMES_GENERATE,13, - 115,79,14 - PUSHBUTTON "Assign Extensions",IDC_LOD_EXTENSION_GENERATE,13,132,79, - 14 - GROUPBOX "Export Utilities",IDC_EXPORT_UTILITIES_GROUP,4,153,100, - 36 - PUSHBUTTON "Export with Std Mtls",IDC_EXPORT_STANDARD_MATERIALS,13, - 166,79,14 - PUSHBUTTON "Create Settings Floater",IDC_CREATE_SETTINGS_FLOATER,14, - 194,79,14 -END - -IDD_W3D_PRESET_EXPORT_OPTIONS DIALOG DISCARDABLE 0, 0, 234, 330 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "W3D Export Options" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,58,309,50,14 - PUSHBUTTON "Cancel",IDCANCEL,124,309,50,14 - CONTROL 158,IDC_STATIC,"Static",SS_BITMAP | SS_CENTERIMAGE,7,7, - 220,47 - CONTROL "&Hierarchical Model",IDC_HLOD_RADIO,"Button", - BS_AUTORADIOBUTTON,9,61,109,10 - CONTROL "Hierarchical &Animated Model",IDC_ANIM_HLOD_RADIO, - "Button",BS_AUTORADIOBUTTON,9,77,109,10 - CONTROL "&Pure Animation",IDC_ANIM_RADIO,"Button", - BS_AUTORADIOBUTTON,9,93,109,10 - CONTROL "&Renegade Terrain",IDC_TERRAIN_RADIO,"Button", - BS_AUTORADIOBUTTON,134,61,89,10 - CONTROL "&Skeleton",IDC_SKELETON_RADIO,"Button", - BS_AUTORADIOBUTTON,134,77,89,10 - CONTROL "Simple &Mesh",IDC_MESH_RADIO,"Button", - BS_AUTORADIOBUTTON,134,93,89,10 - GROUPBOX "Se&ttings",IDC_GROUP_BOX,7,109,220,180 - CONTROL "Review &Log",IDC_REVIEW_LOG,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,7,295,54,10 -END - -IDD_EXPORT_PANE_HLOD DIALOG DISCARDABLE 0, 0, 201, 164 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "This will export a model without animation data.", - IDC_STATIC,7,7,187,13 - PUSHBUTTON "&Browse...",IDC_WHT_BROWSE_BUTTON,18,99,165,12,WS_GROUP - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,7,79,186,1 - CONTROL "&Smooth Vertex Normals Across Meshes", - IDC_EXPORT_MESH_SMOOTH_CHECK,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,7,24,139,10 - CONTROL "&Optimize Collision Detection",IDC_EXPORT_MESH_AABTREES, - "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,39, - 103,10 - CONTROL "Optimize &Mesh Data (mesh names will be lost)", - IDC_EXPORT_MESH_OPTIMIZE,"Button",BS_AUTOCHECKBOX | - BS_MULTILINE | WS_DISABLED | WS_GROUP | WS_TABSTOP,7,54, - 162,10 - CONTROL "Export Using Existing Skeleton:",IDC_USE_SKELETON_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,86,114,10 - CONTROL "&Convert Material Diffuse Colors to Texture", - IDC_EXPORT_MESH_MAT_TO_TEXTURE,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,7,67,147,10 -END - -IDD_EXPORT_PANE_ANIMATED_HLOD DIALOG DISCARDABLE 0, 0, 201, 164 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "This will export the model with geometry and animation data.", - IDC_STATIC,7,7,187,17 - PUSHBUTTON "&Browse...",IDC_WHT_BROWSE_BUTTON,18,99,165,12,WS_GROUP - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,7,79,186,1 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,8,119,186,1 - LTEXT "&Frames:",IDC_STATIC,9,127,26,10,NOT WS_GROUP - CONTROL "",IDC_RANGE_LOW_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP, - 43,125,28,12 - CONTROL "",IDC_RANGE_LOW_SPIN,"SpinnerControl",0x0,71,125,10,12 - LTEXT "To",IDC_STATIC,87,127,10,10 - CONTROL "",IDC_RANGE_HIGH_EDIT,"CustEdit",WS_TABSTOP,104,125,28, - 12 - CONTROL "",IDC_RANGE_HIGH_SPIN,"SpinnerControl",0x0,132,125,10, - 12 - PUSHBUTTON "&Settings...",IDC_COMPRESSION_SETTINGS,59,145,126,12, - WS_GROUP - CONTROL "&Smooth Vertex Normals Across Meshes", - IDC_EXPORT_MESH_SMOOTH_CHECK,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,7,30,139,10 - CONTROL "&Optimize Collision Detection",IDC_EXPORT_MESH_AABTREES, - "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,45, - 103,10 - CONTROL "Optimize &Mesh Data (mesh names will be lost)", - IDC_EXPORT_MESH_OPTIMIZE,"Button",BS_AUTOCHECKBOX | - BS_MULTILINE | WS_DISABLED | WS_GROUP | WS_TABSTOP,7,60, - 162,10 - CONTROL "Export Using Existing Skeleton:",IDC_USE_SKELETON_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,86,114,10 - CONTROL "&Compress",IDC_COMPRESS_ANIMATION_CHECK,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,147,47,10 -END - -IDD_EXPORT_PANE_ANIMATION DIALOG DISCARDABLE 0, 0, 201, 164 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "This will export the animation without any geometry data.", - IDC_STATIC,7,6,187,14 - PUSHBUTTON "&Browse...",IDC_WHT_BROWSE_BUTTON,18,42,165,12,WS_GROUP - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,8,60,186,1 - CONTROL "Export Using Existing Skeleton:",IDC_USE_SKELETON_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,30,114,10 - LTEXT "&Frames:",IDC_STATIC,9,70,26,10,NOT WS_GROUP - CONTROL "",IDC_RANGE_LOW_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP, - 43,68,28,12 - CONTROL "",IDC_RANGE_LOW_SPIN,"SpinnerControl",0x0,71,68,10,12 - LTEXT "To",IDC_STATIC,87,70,10,10 - CONTROL "",IDC_RANGE_HIGH_EDIT,"CustEdit",WS_TABSTOP,104,68,28, - 12 - CONTROL "",IDC_RANGE_HIGH_SPIN,"SpinnerControl",0x0,132,68,10,12 - PUSHBUTTON "&Settings...",IDC_COMPRESSION_SETTINGS,59,87,126,12, - WS_GROUP - CONTROL "&Compress",IDC_COMPRESS_ANIMATION_CHECK,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,89,47,10 -END - -IDD_EXPORT_PANE_MESH DIALOG DISCARDABLE 0, 0, 201, 164 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "This will export a single mesh. If there are more then one mesh, only the first one will be exported.", - IDC_STATIC,7,7,187,19 - CONTROL "Optimize Collision Detection",IDC_EXPORT_MESH_AABTREES, - "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,30, - 103,10 - CONTROL "Convert Material Diffuse Colors to Texture", - IDC_EXPORT_MESH_MAT_TO_TEXTURE,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,7,45,147,10 -END - -IDD_EXPORT_PANE_SKELETON DIALOG DISCARDABLE 0, 0, 201, 164 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "This will export the hierarchy tree without any geometry or animation data.", - IDC_STATIC,7,7,187,24 -END - -IDD_EXPORT_PANE_TERRAIN DIALOG DISCARDABLE 0, 0, 201, 164 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "This will export the geometry in the Renegade terrain format.", - IDC_STATIC,7,7,187,15 - CONTROL "&Smooth Vertex Normals Across Meshes", - IDC_EXPORT_MESH_SMOOTH_CHECK,"Button",BS_AUTOCHECKBOX | - WS_GROUP | WS_TABSTOP,7,30,139,10 - CONTROL "Optimize Mesh Data (mesh names will be lost)", - IDC_EXPORT_MESH_OPTIMIZE,"Button",BS_AUTOCHECKBOX | - BS_MULTILINE | WS_DISABLED | WS_GROUP | WS_TABSTOP,7,45, - 162,10 -END - -IDD_ANIMATION_COMPRESSION DIALOG DISCARDABLE 0, 0, 170, 162 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Animation Compression Settings" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDI_DISK,IDC_STATIC,7,7,20,20 - LTEXT "Specify compression settings for the exported animation.", - IDC_STATIC,42,7,121,15 - LTEXT "Compresion &Type:",IDC_STATIC,7,35,62,8 - COMBOBOX IDC_COMPRESS_ANIMATION_FLAVOR_COMBO,72,33,91,49, - CBS_DROPDOWNLIST | WS_VSCROLL | WS_GROUP | WS_TABSTOP - LTEXT "Max Translation Error:",IDC_STATIC,7,57,70,8 - EDITTEXT IDC_MAX_TRANS_ERROR_EDIT,83,54,40,14,ES_AUTOHSCROLL | - WS_GROUP - LTEXT "units",IDC_STATIC,128,57,16,8 - LTEXT "Max Rotational Error:",IDC_STATIC,7,77,67,8 - EDITTEXT IDC_MAX_ROT_ERROR_EDIT,83,74,40,14,ES_AUTOHSCROLL | - WS_GROUP - LTEXT "degrees",IDC_STATIC,128,77,26,8 - LTEXT "Key Reduction %:",IDC_STATIC,7,100,57,8 - COMBOBOX IDC_REDUCE_ANIMATION_COMBO,67,97,31,81,CBS_DROPDOWNLIST | - WS_VSCROLL | WS_GROUP | WS_TABSTOP - CONTROL "Force Key Reduction",IDC_REDUCE_ANIMATION_CHECK,"Button", - BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,118,83,10 - DEFPUSHBUTTON "OK",IDOK,29,141,50,14 - PUSHBUTTON "Cancel",IDCANCEL,91,141,50,14 -END - -IDD_GRIDSNAP_PARAMS DIALOG DISCARDABLE 0, 0, 108, 24 -STYLE WS_CHILD -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "",IDC_GRIDDIM_EDIT,"CustEdit",WS_GROUP | WS_TABSTOP,57, - 7,33,10 - CONTROL "",IDC_GRIDDIM_SPIN,"SpinnerControl",0x0,91,7,10,10 - LTEXT "Grid Dimension",IDC_STATIC,7,8,48,8 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_VOXEL_DEBUG_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 164 - TOPMARGIN, 7 - BOTTOMMARGIN, 107 - END - - IDD_W3D_EXPORT_OPTIONS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 252 - TOPMARGIN, 7 - BOTTOMMARGIN, 275 - END - - IDD_BONE_INFLUENCE_PARAMS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 101 - TOPMARGIN, 7 - BOTTOMMARGIN, 71 - END - - IDD_SKELETON_PARAMETERS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 101 - TOPMARGIN, 7 - BOTTOMMARGIN, 130 - END - - IDD_SKIN_SOT, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 101 - TOPMARGIN, 7 - BOTTOMMARGIN, 15 - END - - IDD_GAMEMTL_PANEL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 279 - END - - IDD_GAMEMTL_NOTES_PANEL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 51 - END - - IDD_GAMEMTL_HINTS_PANEL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 72 - END - - IDD_GAMEMTL_PSX_PANEL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 59 - END - - IDD_GAMEMTL_PASS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 177 - END - - IDD_GAMEMTL_VERTEX_MATERIAL, DIALOG - BEGIN - LEFTMARGIN, 3 - RIGHTMARGIN, 195 - TOPMARGIN, 1 - BOTTOMMARGIN, 144 - END - - IDD_GAMEMTL_SHADER, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 191 - TOPMARGIN, 7 - BOTTOMMARGIN, 127 - END - - IDD_GAMEMTL_TEXTURES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 191 - TOPMARGIN, 7 - BOTTOMMARGIN, 128 - END - - IDD_GAMEMTL_PASS_COUNT, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 20 - END - - IDD_GAMEMTL_PASS_COUNT_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 183 - TOPMARGIN, 7 - BOTTOMMARGIN, 38 - END - - IDD_GENERATE_NAMES_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 7 - BOTTOMMARGIN, 192 - END - - IDD_MESH_DEFORM_PANEL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 101 - TOPMARGIN, 3 - BOTTOMMARGIN, 165 - END - - IDD_GAMEMTL_SURFACE_TYPE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 35 - END - - IDD_GAMEMTL_DISPLACEMENT_MAP, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 18 - END - - IDD_GENERATE_MTL_NAMES_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 197 - TOPMARGIN, 7 - BOTTOMMARGIN, 62 - END - - IDD_GENERATE_LOD_EXTENSION_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 196 - TOPMARGIN, 7 - BOTTOMMARGIN, 79 - END - - IDD_EXPORT_ALL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 196 - TOPMARGIN, 7 - BOTTOMMARGIN, 67 - END - - IDD_SCENE_SETUP, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 215 - TOPMARGIN, 7 - BOTTOMMARGIN, 238 - END - - IDD_GAMEMTL_PS2_SHADER, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 191 - TOPMARGIN, 7 - BOTTOMMARGIN, 127 - END - - IDD_GAMEMTL_PS2_TEXTURES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 191 - TOPMARGIN, 7 - BOTTOMMARGIN, 128 - END - - IDD_ALPHA_MODIFIER, DIALOG - BEGIN - BOTTOMMARGIN, 36 - END - - IDD_W3D_LOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 327 - TOPMARGIN, 7 - BOTTOMMARGIN, 312 - END - - IDD_INPUT_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 190 - TOPMARGIN, 7 - BOTTOMMARGIN, 40 - END - - IDD_W3DUTILITY_FLOATER_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 107 - TOPMARGIN, 7 - BOTTOMMARGIN, 43 - END - - IDD_W3DUTILITY_SETTINGS_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 4 - RIGHTMARGIN, 104 - TOPMARGIN, 7 - BOTTOMMARGIN, 235 - END - - IDD_W3DUTILITY_TOOLS_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 4 - RIGHTMARGIN, 104 - TOPMARGIN, 7 - BOTTOMMARGIN, 208 - END - - IDD_W3D_PRESET_EXPORT_OPTIONS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 227 - TOPMARGIN, 7 - BOTTOMMARGIN, 323 - END - - IDD_EXPORT_PANE_HLOD, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 7 - BOTTOMMARGIN, 157 - END - - IDD_EXPORT_PANE_ANIMATED_HLOD, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 7 - BOTTOMMARGIN, 157 - END - - IDD_EXPORT_PANE_ANIMATION, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 6 - BOTTOMMARGIN, 157 - END - - IDD_EXPORT_PANE_MESH, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 7 - BOTTOMMARGIN, 157 - END - - IDD_EXPORT_PANE_SKELETON, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 7 - BOTTOMMARGIN, 157 - END - - IDD_EXPORT_PANE_TERRAIN, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 194 - TOPMARGIN, 7 - BOTTOMMARGIN, 157 - END - - IDD_ANIMATION_COMPRESSION, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 163 - TOPMARGIN, 7 - BOTTOMMARGIN, 155 - END - - IDD_GRIDSNAP_PARAMS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 101 - TOPMARGIN, 7 - BOTTOMMARGIN, 17 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog Info -// - -IDD_GAMEMTL_PANEL DLGINIT -BEGIN - IDC_DCT_MAPPING_COMBO, 0x403, 3, 0 -0x5655, "\000" - IDC_DCT_MAPPING_COMBO, 0x403, 5, 0 -0x6e45, 0x6f76, "\000" - IDC_DIT_MAPPING_COMBO, 0x403, 3, 0 -0x5655, "\000" - IDC_DIT_MAPPING_COMBO, 0x403, 5, 0 -0x6e45, 0x6f76, "\000" - IDC_SCT_MAPPING_COMBO, 0x403, 3, 0 -0x5655, "\000" - IDC_SCT_MAPPING_COMBO, 0x403, 5, 0 -0x6e45, 0x6f76, "\000" - IDC_SIT_MAPPING_COMBO, 0x403, 3, 0 -0x5655, "\000" - IDC_SIT_MAPPING_COMBO, 0x403, 5, 0 -0x6e45, 0x6f76, "\000" - 0 -END - -IDD_GAMEMTL_SHADER DLGINIT -BEGIN - IDC_SRCBLEND_COMBO, 0x403, 5, 0 -0x655a, 0x6f72, "\000" - IDC_SRCBLEND_COMBO, 0x403, 4, 0 -0x6e4f, 0x0065, - IDC_SRCBLEND_COMBO, 0x403, 10, 0 -0x7253, 0x2063, 0x6c41, 0x6870, 0x0061, - IDC_SRCBLEND_COMBO, 0x403, 12, 0 -0x2d31, 0x7253, 0x2063, 0x6c41, 0x6870, 0x0061, - IDC_DESTBLEND_COMBO, 0x403, 5, 0 -0x655a, 0x6f72, "\000" - IDC_DESTBLEND_COMBO, 0x403, 4, 0 -0x6e4f, 0x0065, - IDC_DESTBLEND_COMBO, 0x403, 10, 0 -0x7253, 0x2063, 0x6f43, 0x6f6c, 0x0072, - IDC_DESTBLEND_COMBO, 0x403, 12, 0 -0x2d31, 0x7253, 0x2063, 0x6f43, 0x6f6c, 0x0072, - IDC_DESTBLEND_COMBO, 0x403, 10, 0 -0x7253, 0x2063, 0x6c41, 0x6870, 0x0061, - IDC_DESTBLEND_COMBO, 0x403, 12, 0 -0x2d31, 0x7253, 0x2063, 0x6c41, 0x6870, 0x0061, - IDC_DESTBLEND_COMBO, 0x403, 17, 0 -0x7253, 0x2063, 0x6f43, 0x6f6c, 0x2072, 0x7250, 0x4665, 0x676f, "\000" - IDC_PRIGRADIENT_COMBO, 0x403, 8, 0 -0x6944, 0x6173, 0x6c62, 0x0065, - IDC_PRIGRADIENT_COMBO, 0x403, 9, 0 -0x6f4d, 0x7564, 0x616c, 0x6574, "\000" - IDC_PRIGRADIENT_COMBO, 0x403, 4, 0 -0x6441, 0x0064, - IDC_PRIGRADIENT_COMBO, 0x403, 17, 0 -0x7542, 0x706d, 0x452d, 0x766e, 0x7269, 0x6e6f, 0x656d, 0x746e, "\000" - IDC_SECGRADIENT_COMBO, 0x403, 8, 0 -0x6944, 0x6173, 0x6c62, 0x0065, - IDC_SECGRADIENT_COMBO, 0x403, 7, 0 -0x6e45, 0x6261, 0x656c, "\000" - IDC_DEPTHCOMPARE_COMBO, 0x403, 11, 0 -0x6150, 0x7373, 0x4e20, 0x7665, 0x7265, "\000" - IDC_DEPTHCOMPARE_COMBO, 0x403, 10, 0 -0x6150, 0x7373, 0x4c20, 0x7365, 0x0073, - IDC_DEPTHCOMPARE_COMBO, 0x403, 11, 0 -0x6150, 0x7373, 0x4520, 0x7571, 0x6c61, "\000" - IDC_DEPTHCOMPARE_COMBO, 0x403, 12, 0 -0x6150, 0x7373, 0x4c20, 0x7145, 0x6175, 0x006c, - IDC_DEPTHCOMPARE_COMBO, 0x403, 13, 0 -0x6150, 0x7373, 0x4720, 0x6572, 0x7461, 0x7265, "\000" - IDC_DEPTHCOMPARE_COMBO, 0x403, 12, 0 -0x6150, 0x7373, 0x4e20, 0x7145, 0x6175, 0x006c, - IDC_DEPTHCOMPARE_COMBO, 0x403, 12, 0 -0x6150, 0x7373, 0x4720, 0x7145, 0x6175, 0x006c, - IDC_DEPTHCOMPARE_COMBO, 0x403, 12, 0 -0x6150, 0x7373, 0x4120, 0x776c, 0x7961, 0x0073, - IDC_DETAILCOLOR_COMBO, 0x403, 8, 0 -0x6944, 0x6173, 0x6c62, 0x0065, - IDC_DETAILCOLOR_COMBO, 0x403, 7, 0 -0x6544, 0x6174, 0x6c69, "\000" - IDC_DETAILCOLOR_COMBO, 0x403, 6, 0 -0x6353, 0x6c61, 0x0065, - IDC_DETAILCOLOR_COMBO, 0x403, 9, 0 -0x6e49, 0x5376, 0x6163, 0x656c, "\000" - IDC_DETAILCOLOR_COMBO, 0x403, 4, 0 -0x6441, 0x0064, - IDC_DETAILCOLOR_COMBO, 0x403, 4, 0 -0x7553, 0x0062, - IDC_DETAILCOLOR_COMBO, 0x403, 5, 0 -0x7553, 0x5262, "\000" - IDC_DETAILCOLOR_COMBO, 0x403, 6, 0 -0x6c42, 0x6e65, 0x0064, - IDC_DETAILCOLOR_COMBO, 0x403, 12, 0 -0x6544, 0x6174, 0x6c69, 0x6c42, 0x6e65, 0x0064, - IDC_DETAILALPHA_COMBO, 0x403, 8, 0 -0x6944, 0x6173, 0x6c62, 0x0065, - IDC_DETAILALPHA_COMBO, 0x403, 7, 0 -0x6544, 0x6174, 0x6c69, "\000" - IDC_DETAILALPHA_COMBO, 0x403, 6, 0 -0x6353, 0x6c61, 0x0065, - IDC_DETAILALPHA_COMBO, 0x403, 9, 0 -0x6e49, 0x5376, 0x6163, 0x656c, "\000" - 0 -END - -IDD_GAMEMTL_VERTEX_MATERIAL DLGINIT -BEGIN - IDC_MAPPING0_COMBO, 0x403, 3, 0 -0x5655, "\000" - IDC_MAPPING0_COMBO, 0x403, 12, 0 -0x6e45, 0x6976, 0x6f72, 0x6d6e, 0x6e65, 0x0074, - IDC_MAPPING0_COMBO, 0x403, 12, 0 -0x6c43, 0x7361, 0x6973, 0x2063, 0x6e45, 0x0076, - IDC_MAPPING0_COMBO, 0x403, 7, 0 -0x6353, 0x6572, 0x6e65, "\000" - IDC_MAPPING0_COMBO, 0x403, 14, 0 -0x694c, 0x656e, 0x7261, 0x4f20, 0x6666, 0x6573, 0x0074, - IDC_MAPPING0_COMBO, 0x403, 22, 0 -0x6953, 0x686c, 0x756f, 0x7465, 0x6574, 0x2820, 0x626f, 0x6f73, 0x656c, -0x6574, 0x0029, - IDC_MAPPING0_COMBO, 0x403, 6, 0 -0x6353, 0x6c61, 0x0065, - IDC_MAPPING0_COMBO, 0x403, 5, 0 -0x7247, 0x6469, "\000" - IDC_MAPPING0_COMBO, 0x403, 7, 0 -0x6f52, 0x6174, 0x6574, "\000" - IDC_MAPPING0_COMBO, 0x403, 5, 0 -0x6953, 0x656e, "\000" - IDC_MAPPING0_COMBO, 0x403, 5, 0 -0x7453, 0x7065, "\000" - IDC_MAPPING0_COMBO, 0x403, 7, 0 -0x695a, 0x7a67, 0x6761, "\000" - IDC_MAPPING0_COMBO, 0x403, 15, 0 -0x5357, 0x6320, 0x616c, 0x7373, 0x6369, 0x6520, 0x766e, "\000" - IDC_MAPPING0_COMBO, 0x403, 15, 0 -0x5357, 0x6520, 0x766e, 0x7269, 0x6e6f, 0x656d, 0x746e, "\000" - IDC_MAPPING0_COMBO, 0x403, 17, 0 -0x7247, 0x6469, 0x6320, 0x616c, 0x7373, 0x6369, 0x6520, 0x766e, "\000" - IDC_MAPPING0_COMBO, 0x403, 17, 0 -0x7247, 0x6469, 0x6520, 0x766e, 0x7269, 0x6e6f, 0x656d, 0x746e, "\000" - IDC_MAPPING0_COMBO, 0x403, 7, 0 -0x6152, 0x646e, 0x6d6f, "\000" - IDC_MAPPING0_COMBO, 0x403, 5, 0 -0x6445, 0x6567, "\000" - IDC_MAPPING0_COMBO, 0x403, 8, 0 -0x7542, 0x706d, 0x6e45, 0x0076, - IDC_MAPPING1_COMBO, 0x403, 3, 0 -0x5655, "\000" - IDC_MAPPING1_COMBO, 0x403, 12, 0 -0x6e45, 0x6976, 0x6f72, 0x6d6e, 0x6e65, 0x0074, - IDC_MAPPING1_COMBO, 0x403, 12, 0 -0x6c43, 0x7361, 0x6973, 0x2063, 0x6e45, 0x0076, - IDC_MAPPING1_COMBO, 0x403, 7, 0 -0x6353, 0x6572, 0x6e65, "\000" - IDC_MAPPING1_COMBO, 0x403, 14, 0 -0x694c, 0x656e, 0x7261, 0x4f20, 0x6666, 0x6573, 0x0074, - IDC_MAPPING1_COMBO, 0x403, 22, 0 -0x6953, 0x686c, 0x756f, 0x7465, 0x6574, 0x2820, 0x626f, 0x6f73, 0x656c, -0x6574, 0x0029, - IDC_MAPPING1_COMBO, 0x403, 6, 0 -0x6353, 0x6c61, 0x0065, - IDC_MAPPING1_COMBO, 0x403, 5, 0 -0x7247, 0x6469, "\000" - IDC_MAPPING1_COMBO, 0x403, 7, 0 -0x6f52, 0x6174, 0x6574, "\000" - IDC_MAPPING1_COMBO, 0x403, 5, 0 -0x6953, 0x656e, "\000" - IDC_MAPPING1_COMBO, 0x403, 5, 0 -0x7453, 0x7065, "\000" - IDC_MAPPING1_COMBO, 0x403, 7, 0 -0x695a, 0x7a67, 0x6761, "\000" - IDC_MAPPING1_COMBO, 0x403, 15, 0 -0x5357, 0x6320, 0x616c, 0x7373, 0x6369, 0x6520, 0x766e, "\000" - IDC_MAPPING1_COMBO, 0x403, 15, 0 -0x5357, 0x6520, 0x766e, 0x7269, 0x6e6f, 0x656d, 0x746e, "\000" - IDC_MAPPING1_COMBO, 0x403, 17, 0 -0x7247, 0x6469, 0x6320, 0x616c, 0x7373, 0x6369, 0x6520, 0x766e, "\000" - IDC_MAPPING1_COMBO, 0x403, 17, 0 -0x7247, 0x6469, 0x6520, 0x766e, 0x7269, 0x6e6f, 0x656d, 0x746e, "\000" - IDC_MAPPING1_COMBO, 0x403, 7, 0 -0x6152, 0x646e, 0x6d6f, "\000" - IDC_MAPPING1_COMBO, 0x403, 5, 0 -0x6445, 0x6567, "\000" - IDC_MAPPING1_COMBO, 0x403, 8, 0 -0x7542, 0x706d, 0x6e45, 0x0076, - 0 -END - -IDD_GAMEMTL_TEXTURES DLGINIT -BEGIN - IDC_STAGE0_ANIM_COMBO, 0x403, 5, 0 -0x6f4c, 0x706f, "\000" - IDC_STAGE0_ANIM_COMBO, 0x403, 10, 0 -0x6950, 0x676e, 0x502d, 0x6e6f, 0x0067, - IDC_STAGE0_ANIM_COMBO, 0x403, 5, 0 -0x6e4f, 0x6563, "\000" - IDC_STAGE0_ANIM_COMBO, 0x403, 7, 0 -0x614d, 0x756e, 0x6c61, "\000" - IDC_STAGE0_HINT_COMBO, 0x403, 13, 0 -0x6142, 0x6573, 0x5420, 0x7865, 0x7574, 0x6572, "\000" - IDC_STAGE0_HINT_COMBO, 0x403, 18, 0 -0x6d45, 0x7369, 0x6973, 0x6576, 0x4c20, 0x6769, 0x7468, 0x616d, 0x0070, - - IDC_STAGE0_HINT_COMBO, 0x403, 16, 0 -0x6e45, 0x6976, 0x6f72, 0x6d6e, 0x6e65, 0x2074, 0x614d, 0x0070, - IDC_STAGE0_HINT_COMBO, 0x403, 15, 0 -0x6853, 0x6e69, 0x6e79, 0x7365, 0x2073, 0x614d, 0x6b73, "\000" - IDC_STAGE1_ANIM_COMBO, 0x403, 5, 0 -0x6f4c, 0x706f, "\000" - IDC_STAGE1_ANIM_COMBO, 0x403, 10, 0 -0x6950, 0x676e, 0x502d, 0x6e6f, 0x0067, - IDC_STAGE1_ANIM_COMBO, 0x403, 5, 0 -0x6e4f, 0x6563, "\000" - IDC_STAGE1_ANIM_COMBO, 0x403, 7, 0 -0x614d, 0x756e, 0x6c61, "\000" - IDC_STAGE1_HINT_COMBO, 0x403, 13, 0 -0x6142, 0x6573, 0x5420, 0x7865, 0x7574, 0x6572, "\000" - IDC_STAGE1_HINT_COMBO, 0x403, 18, 0 -0x6d45, 0x7369, 0x6973, 0x6576, 0x4c20, 0x6769, 0x7468, 0x616d, 0x0070, - - IDC_STAGE1_HINT_COMBO, 0x403, 16, 0 -0x6e45, 0x6976, 0x6f72, 0x6d6e, 0x6e65, 0x2074, 0x614d, 0x0070, - IDC_STAGE1_HINT_COMBO, 0x403, 15, 0 -0x6853, 0x6e69, 0x6e79, 0x7365, 0x2073, 0x614d, 0x6b73, "\000" - 0 -END - -IDD_GAMEMTL_PS2_SHADER DLGINIT -BEGIN - IDC_A_COMBO, 0x403, 7, 0 -0x6f53, 0x7275, 0x6563, "\000" - IDC_A_COMBO, 0x403, 12, 0 -0x6544, 0x7473, 0x6e69, 0x7461, 0x6f69, 0x006e, - IDC_A_COMBO, 0x403, 5, 0 -0x655a, 0x6f72, "\000" - IDC_B_COMBO, 0x403, 7, 0 -0x6f53, 0x7275, 0x6563, "\000" - IDC_B_COMBO, 0x403, 12, 0 -0x6544, 0x7473, 0x6e69, 0x7461, 0x6f69, 0x006e, - IDC_B_COMBO, 0x403, 5, 0 -0x655a, 0x6f72, "\000" - IDC_PRIGRADIENT_COMBO, 0x403, 6, 0 -0x6544, 0x6163, 0x006c, - IDC_PRIGRADIENT_COMBO, 0x403, 9, 0 -0x6f4d, 0x7564, 0x616c, 0x6574, "\000" - IDC_PRIGRADIENT_COMBO, 0x403, 10, 0 -0x6948, 0x6867, 0x696c, 0x6867, 0x0074, - IDC_PRIGRADIENT_COMBO, 0x403, 12, 0 -0x6948, 0x6867, 0x696c, 0x6867, 0x2074, 0x0032, - IDC_DEPTHCOMPARE_COMBO, 0x403, 11, 0 -0x6150, 0x7373, 0x4e20, 0x7665, 0x7265, "\000" - IDC_DEPTHCOMPARE_COMBO, 0x403, 10, 0 -0x6150, 0x7373, 0x4c20, 0x7365, 0x0073, - IDC_DEPTHCOMPARE_COMBO, 0x403, 12, 0 -0x6150, 0x7373, 0x4120, 0x776c, 0x7961, 0x0073, - IDC_DEPTHCOMPARE_COMBO, 0x403, 12, 0 -0x6150, 0x7373, 0x4c20, 0x7145, 0x6175, 0x006c, - IDC_DETAILCOLOR_COMBO, 0x403, 8, 0 -0x6944, 0x6173, 0x6c62, 0x0065, - IDC_DETAILCOLOR_COMBO, 0x403, 7, 0 -0x6544, 0x6174, 0x6c69, "\000" - IDC_DETAILCOLOR_COMBO, 0x403, 6, 0 -0x6353, 0x6c61, 0x0065, - IDC_DETAILCOLOR_COMBO, 0x403, 9, 0 -0x6e49, 0x5376, 0x6163, 0x656c, "\000" - IDC_DETAILCOLOR_COMBO, 0x403, 4, 0 -0x6441, 0x0064, - IDC_DETAILCOLOR_COMBO, 0x403, 4, 0 -0x7553, 0x0062, - IDC_DETAILCOLOR_COMBO, 0x403, 5, 0 -0x7553, 0x5262, "\000" - IDC_DETAILCOLOR_COMBO, 0x403, 6, 0 -0x6c42, 0x6e65, 0x0064, - IDC_DETAILCOLOR_COMBO, 0x403, 12, 0 -0x6544, 0x6174, 0x6c69, 0x6c42, 0x6e65, 0x0064, - IDC_DETAILALPHA_COMBO, 0x403, 8, 0 -0x6944, 0x6173, 0x6c62, 0x0065, - IDC_DETAILALPHA_COMBO, 0x403, 7, 0 -0x6544, 0x6174, 0x6c69, "\000" - IDC_DETAILALPHA_COMBO, 0x403, 6, 0 -0x6353, 0x6c61, 0x0065, - IDC_DETAILALPHA_COMBO, 0x403, 9, 0 -0x6e49, 0x5376, 0x6163, 0x656c, "\000" - IDC_D_COMBO, 0x403, 7, 0 -0x6f53, 0x7275, 0x6563, "\000" - IDC_D_COMBO, 0x403, 12, 0 -0x6544, 0x7473, 0x6e69, 0x7461, 0x6f69, 0x006e, - IDC_D_COMBO, 0x403, 5, 0 -0x655a, 0x6f72, "\000" - IDC_C_COMBO, 0x403, 10, 0 -0x7253, 0x2063, 0x6c41, 0x6870, 0x0061, - IDC_C_COMBO, 0x403, 11, 0 -0x6544, 0x7473, 0x4120, 0x706c, 0x6168, "\000" - IDC_C_COMBO, 0x403, 4, 0 -0x6e4f, 0x0065, - 0 -END - -IDD_GAMEMTL_PS2_TEXTURES DLGINIT -BEGIN - IDC_STAGE0_ANIM_COMBO, 0x403, 5, 0 -0x6f4c, 0x706f, "\000" - IDC_STAGE0_ANIM_COMBO, 0x403, 10, 0 -0x6950, 0x676e, 0x502d, 0x6e6f, 0x0067, - IDC_STAGE0_ANIM_COMBO, 0x403, 5, 0 -0x6e4f, 0x6563, "\000" - IDC_STAGE0_ANIM_COMBO, 0x403, 7, 0 -0x614d, 0x756e, 0x6c61, "\000" - IDC_STAGE0_HINT_COMBO, 0x403, 13, 0 -0x6142, 0x6573, 0x5420, 0x7865, 0x7574, 0x6572, "\000" - IDC_STAGE0_HINT_COMBO, 0x403, 18, 0 -0x6d45, 0x7369, 0x6973, 0x6576, 0x4c20, 0x6769, 0x7468, 0x616d, 0x0070, - - IDC_STAGE0_HINT_COMBO, 0x403, 16, 0 -0x6e45, 0x6976, 0x6f72, 0x6d6e, 0x6e65, 0x2074, 0x614d, 0x0070, - IDC_STAGE0_HINT_COMBO, 0x403, 15, 0 -0x6853, 0x6e69, 0x6e79, 0x7365, 0x2073, 0x614d, 0x6b73, "\000" - IDC_STAGE1_ANIM_COMBO, 0x403, 5, 0 -0x6f4c, 0x706f, "\000" - IDC_STAGE1_ANIM_COMBO, 0x403, 10, 0 -0x6950, 0x676e, 0x502d, 0x6e6f, 0x0067, - IDC_STAGE1_ANIM_COMBO, 0x403, 5, 0 -0x6e4f, 0x6563, "\000" - IDC_STAGE1_ANIM_COMBO, 0x403, 7, 0 -0x614d, 0x756e, 0x6c61, "\000" - IDC_STAGE1_HINT_COMBO, 0x403, 13, 0 -0x6142, 0x6573, 0x5420, 0x7865, 0x7574, 0x6572, "\000" - IDC_STAGE1_HINT_COMBO, 0x403, 18, 0 -0x6d45, 0x7369, 0x6973, 0x6576, 0x4c20, 0x6769, 0x7468, 0x616d, 0x0070, - - IDC_STAGE1_HINT_COMBO, 0x403, 16, 0 -0x6e45, 0x6976, 0x6f72, 0x6d6e, 0x6e65, 0x2074, 0x614d, 0x0070, - IDC_STAGE1_HINT_COMBO, 0x403, 15, 0 -0x6853, 0x6e69, 0x6e79, 0x7365, 0x2073, 0x614d, 0x6b73, "\000" - 0 -END - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,5,0 - PRODUCTVERSION 1,0,5,0 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "Coded by Greg Hjelstrom\0" - VALUE "CompanyName", "Westwood Studios\0" - VALUE "FileDescription", "max2w3d\0" - VALUE "FileVersion", "1, 0, 5, 0\0" - VALUE "InternalName", "max2w3d\0" - VALUE "LegalCopyright", "Copyright © 1998\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "max2w3d.dle\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "Westwood Studios max2w3d\0" - VALUE "ProductVersion", "1, 0, 5, 0\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ORIG ICON DISCARDABLE "Res\\orig.ico" -IDI_DEFORMED ICON DISCARDABLE "res\\orig1.ico" -IDI_DISK ICON DISCARDABLE "Res\\DISK12.ICO" - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_NORM BITMAP DISCARDABLE "Res\\one.bmp" -IDB_DEFORM BITMAP DISCARDABLE "Res\\two.bmp" -IDB_WW3D BITMAP DISCARDABLE "Res\\ww3d.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_COPYRIGHT_NOTICE "Copyright 1997 Westwood Studios" - IDS_AUTHOR_NAME "Greg Hjelstrom" - IDS_GAMEMTL "W3D" - IDS_MAP_TEXTURE "Texture" - IDS_ENVMAP "Env-Map" - IDS_SCENE_EXPORT "Scene Export" - IDS_LIB_DESCRIPTION "Westwood 3D Export Plugins" - IDS_FILE_OPEN_ERROR "Unable to open file" - IDS_DLL_NAME "max2w3d.dle" - IDS_WTM_SHORT_DESCRIPTION "Westwood Textured Mesh" - IDS_WTM_LONG_DESCRIPTION "Westwood Textured Mesh" - IDS_WHT_SHORT_DESCRIPTION "Westwood Hierarchy Tree" - IDS_WHT_LONG_DESCRIPTION "Westwood Hierarchy Tree" - IDS_WHA_SHORT_DESCRIPTION "Westwood Hierarchy Animation" - IDS_WHA_LONG_DESCRIPTION "Westwood Hierarchy Animation" -END - -STRINGTABLE DISCARDABLE -BEGIN - IDS_WTM_FILE_EXTEN "wtm" - IDS_WHT_FILE_EXTEN "wht" - IDS_WHA_FILE_EXTEN "wha" - IDS_W3D_FILE_EXTEN "w3d" - IDS_W3D_LONG_DESCRIPTION "Westwood 3D Assets" - IDS_W3D_SHORT_DESCRIPTION "Westwood 3D Assets" - IDS_W3D_UTILITY_CLASS_NAME "W3D Tools" - IDS_W3DMENU_CATEGORY "Westwood Tools" - IDS_W3DMENU_TITLE "W3D Tools" - IDS_SOT "Supports Objects of Type" - IDS_DIFFUSE_COLOR "Diffuse Color" - IDS_PARAMETERS "Parameters" - IDS_TEXTURE_MAP "Texture Map" - IDS_ENVIRONMENT_MAP "Environment Map" - IDS_TEXMAPS "Texture Maps" - IDS_AM "Ambient" -END - -STRINGTABLE DISCARDABLE -BEGIN - IDS_SKIN_CLASS_NAME "Westwood Skin" - IDS_SKIN_OBJECT_NAME "Westwood Skin" - IDS_SKIN "Westwood Skin" - IDS_SKIN_PARAMETERS "Skin Parameters" - IDS_SKIN_INFO "Westwood Skin Info" -END - -STRINGTABLE DISCARDABLE -BEGIN - IDS_BONE_INFLUENCE_PARAMS "Bone Influence" - IDS_SOT2 "Supports Objects of Type" - IDS_SKELETON_PARAMETERS "Skeleton Parameters" - IDS_PICK_BONE_DIALOG_TITLE "Select bones" - IDS_PICK_BONE_BUTTON_TEXT "Ok" - IDS_MULTIPLE_OBJECTS "Multiple Objects Selected" - IDS_NO_OBJECT "No Object Selected" - IDS_SPECULAR_COLOR "Specular Color" - IDS_AMBIENT_COLOR "Ambient Color" - IDS_EMISSIVE_COLOR "Emissive" - IDS_MATERIAL_HINTS "Material Hints" - IDS_PSX_OPTIONS "Playstation Options" - IDS_UV_MAPPING "UV" - IDS_ENVIRONMENT_MAPPING "Environment" -END - -STRINGTABLE DISCARDABLE -BEGIN - IDS_DI "Diffuse" - IDS_SP "Specular" - IDS_SH "Shininess" - IDS_SS "Shininess Strength" - IDS_SI "Self-Illumination" - IDS_OP "Opacity" - IDS_FI "Blend" - IDS_BU "Bump" - IDS_RL "Reflection" - IDS_RR "Refraction" - IDS_NONE "None" - IDS_NOTES "Important Info" -END - -STRINGTABLE DISCARDABLE -BEGIN - IDS_PASS_COUNT "Material Pass Count" - IDS_PASS_SETTINGS "Pass %d Settings" - IDS_PUBLISH "Publish" - IDS_DISPLAY "Display" - IDS_RESIZE "Resize" - IDS_NO_MIPMAP "No Mipmap" - IDS_CLAMP_U "Clamp U" - IDS_CLAMP_V "Clamp V" - IDS_ALPHA_BITMAP "Alpha Bitmap" - IDS_SURFACE_TYPE "Material Surface Type" - IDS_DISPLACEMENT_MAP "Displacement Map" - IDS_ALPHA_MODIFIER_CLASS "Alpha Modifier" - IDS_PS2_GAMEMTL "W3D PS2" - IDS_PC_TO_PS2_MAT_CONVERTER "PC to PS2 Material Converter" - IDS_NO_LOD "No LOD" - IDS_W3DUTILITY_SETTINGS "W3D Export Settings" -END - -STRINGTABLE DISCARDABLE -BEGIN - IDS_W3DUTILITY_TOOLS "W3D Tools" - IDS_GRIDSNAPMODIFIER "Grid Snap Modifier" - IDS_GRIDSNAP_TITLE "Grid Snap Settings" - IDS_GRID_DIMENSION "Grid Dimension" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Generals/Code/Tools/WW3D/max2w3d/maxworldinfo.cpp b/Generals/Code/Tools/WW3D/max2w3d/maxworldinfo.cpp deleted file mode 100644 index f37b8b59ba..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/maxworldinfo.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/maxworldinfo.cpp $* - * * - * Original Author:: Patrick Smith * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 7:11p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "maxworldinfo.h" -#include "geometryexporttask.h" - -/* -** Get_Shared_Vertex_Normal -** Loops through all the other meshes in the world and builds a vertex normal for -** the verticies that share the same space and are part of the same smoothing group. -*/ -Vector3 MaxWorldInfoClass::Get_Shared_Vertex_Normal (Vector3 pos, int smgroup) -{ - Point3 normal(0,0,0); - Point3 world_pos = ExportTrans * Point3(pos.X,pos.Y,pos.Z); - - // - // Loop through all the meshes in the world and see which ones contain - // verticies that share the same space and are part of the same smoothing group. - // - for(unsigned int index = 0; index < MeshList.Count(); index ++) { - GeometryExportTaskClass * task = MeshList[index]; - if (task != CurrentTask) { - normal += task->Get_Shared_Vertex_Normal(world_pos,smgroup); - } - } - - return Vector3(normal.x,normal.y,normal.z); -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/maxworldinfo.h b/Generals/Code/Tools/WW3D/max2w3d/maxworldinfo.h deleted file mode 100644 index d8b3459080..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/maxworldinfo.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/maxworldinfo.h $* - * * - * Original Author:: Patrick Smith * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 6:55p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef MAXWORLDINFO_H -#define MAXWORLDINFO_H - - -#include -#include "meshbuild.h" -#include "nodelist.h" -#include "Vector.H" - - -class GeometryExportTaskClass; - - -/** -** MaxWorldInfoClass - Provides information about the max 'world' (or scene) -** This class is used by the plugin to cause the MeshBuilder to smooth normals -** across adjacent meshes. -*/ -class MaxWorldInfoClass : public WorldInfoClass -{ - public: - MaxWorldInfoClass(DynamicVectorClass & mesh_list) - : MeshList (mesh_list), - SmoothBetweenMeshes (true), - CurrentTask(NULL), - CurrentTime(0) { } - virtual ~MaxWorldInfoClass(void) { } - - // Public methods - virtual Vector3 Get_Shared_Vertex_Normal(Vector3 pos, int smgroup); - - virtual GeometryExportTaskClass * Get_Current_Task(void) const { return CurrentTask; } - virtual void Set_Current_Task(GeometryExportTaskClass * task) { CurrentTask = task; } - - virtual TimeValue Get_Current_Time(void) const { return CurrentTime; } - virtual void Set_Current_Time(TimeValue &time) { CurrentTime = time; } - - virtual Matrix3 Get_Export_Transform(void) const { return ExportTrans; } - virtual void Set_Export_Transform(const Matrix3 &matrix) { ExportTrans = matrix; } - - virtual void Allow_Mesh_Smoothing (bool onoff) { SmoothBetweenMeshes = onoff; } - virtual bool Are_Meshes_Smoothed (void) const { return SmoothBetweenMeshes; } - - private: - - DynamicVectorClass & MeshList; - GeometryExportTaskClass * CurrentTask; - TimeValue CurrentTime; - Matrix3 ExportTrans; - bool SmoothBetweenMeshes; -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/meshbuild.cpp b/Generals/Code/Tools/WW3D/max2w3d/meshbuild.cpp deleted file mode 100644 index 654a626df8..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/meshbuild.cpp +++ /dev/null @@ -1,1835 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/meshbuild.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 11/02/00 6:28p $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * MeshBuilderClass::VertClass::Reset -- reset this vertex * - * MeshBuilderClass::FaceClass::Reset -- rest this face * - * MeshBuilderClass::FaceClass::Compute_Plane -- compute the plane for this face * - * MeshBuilderClass::FaceClass::Is_Degenerate -- check if a face is degenerate * - * MeshBuilderClass::MeshStatsStruct::Reset -- reset the stats to all false * - * MeshBuilderClass::MeshBuilderClass -- constructor * - * MeshBuilderClass::~MeshBuilderClass -- destructor * - * MeshBuilderClass::Free -- release all memory in use * - * MeshBuilderClass::Reset -- Get the builder ready to process a mesh * - * MeshBuilderClass::Add_Face -- Add a face to the mesh * - * MeshBuilderClass::Build_Mesh -- process the mesh * - * MeshBuilderClass::Compute_Face_Normals -- computes all of the face normals from the index * - * MeshBuilderClass::Verify_Face_Normals -- checks if any faces have flipped * - * MeshBuilderClass::Compute_Vertex_Normals -- Computes the vertex normals for the mesh * - * MeshBuilderClass::Remove_Degenerate_Faces -- discard invalid or duplicated faces * - * MeshBuilderClass::Compute_Mesh_Stats -- compute some stats about the mesh * - * MeshBuilderClass::Compute_Bounding_Box -- computes an axis-aligned bounding box for the m * - * MeshBuilderClass::Compute_Bounding_Sphere -- computes a bounding sphere for the mesh * - * MeshBuilderClass::Optimize_Mesh -- "optimize" the mesh * - * MeshBuilderClass::Strip_Optimize_Mesh -- optimize the mesh for triangle strips * - * MeshBuilderClass::Grow_Face_Array -- increases the size of the face array * - * MeshBuilderClass::Sort_Vertices -- Sorts vertices according to the given key array * - * MeshBuilderClass::Sort_Vertices_By_Bone_Index -- sorts verts by bone index * - * MeshBuilderClass::Sort_Vertices_By_Vertex_Material -- sorts verts by vertex mtl in pass0 * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "meshbuild.h" -#include "uarray.h" -#include -#include -#include - - -const float EPSILON = 0.0001f; - -/* -** qsort compare functions -*/ -static int face_material_compare(const void *elem1, const void *elem2); -static int pass0_stage0_compare(const void *elem1, const void *elem2); -static int pass0_stage1_compare(const void *elem1, const void *elem2); -static int pass1_stage0_compare(const void *elem1, const void *elem2); -static int pass1_stage1_compare(const void *elem1, const void *elem2); -static int pass2_stage0_compare(const void *elem1, const void *elem2); -static int pass2_stage1_compare(const void *elem1, const void *elem2); -static int pass3_stage0_compare(const void *elem1, const void *elem2); -static int pass3_stage1_compare(const void *elem1, const void *elem2); -static int vertex_compare(const void *elem1, const void *elem2); - -typedef int (*COMPARE_FUNC_TYPE)(const void * elem1,const void * elem2); - -COMPARE_FUNC_TYPE Texture_Compare_Funcs[MeshBuilderClass::MAX_PASSES][MeshBuilderClass::MAX_STAGES] = -{ - { pass0_stage0_compare, pass0_stage1_compare }, - { pass1_stage0_compare, pass1_stage1_compare }, - { pass2_stage0_compare, pass2_stage1_compare }, - { pass3_stage0_compare, pass3_stage1_compare }, -}; - - -/************************************************************************************ -** -** FaceHasherClass, support class for the unique faces hash table. The unique -** faces table is going to detect exactly duplicated faces and discard them. It -** appears that the artists occasionally accidentally duplicate a face which causes -** problems in the stripping algorithm... -** -************************************************************************************/ -class FaceHasherClass : public HashCalculatorClass -{ -public: - - virtual bool Items_Match(const MeshBuilderClass::FaceClass & a, const MeshBuilderClass::FaceClass & b) - { - // Note: if we want this to detect duplicates that are "rotated", must change - // both this function and the Compute_Hash function... - return - ( - (a.VertIdx[0] == b.VertIdx[0]) && - (a.VertIdx[1] == b.VertIdx[1]) && - (a.VertIdx[2] == b.VertIdx[2]) - ); - } - - virtual void Compute_Hash(const MeshBuilderClass::FaceClass & item) - { - HashVal = (int)(item.VertIdx[0]*12345.6f + item.VertIdx[1]*1714.38484f + item.VertIdx[2]*27561.3f)&1023; - } - - virtual int Num_Hash_Bits(void) - { - return 10; - } - - virtual int Num_Hash_Values(void) - { - return 1; - } - - virtual int Get_Hash_Value(int /*index*/) - { - return HashVal; - } - -private: - - int HashVal; - -}; - - -/************************************************************************************ -** -** VertexArray, build an array of unique vertices. Can't use the UniqueArray -** template due to the special considerations needed to properly handle smoothing -** groups... (DAMN!!! this was the reason I *WROTE* UniqueArray, oh well :-) -** -************************************************************************************/ -class VertexArrayClass -{ -public: - - enum - { - HASH_TABLE_SIZE = 4096, - }; - - VertexArrayClass(int maxsize,int match_normals = 0) - { - Verts = NULL; - assert(maxsize > 0); - Verts = new MeshBuilderClass::VertClass[maxsize]; - assert(Verts); - VertCount = 0; - UVSplits = 0; - - HashTable = new MeshBuilderClass::VertClass * [HASH_TABLE_SIZE]; - memset(HashTable,0,sizeof(MeshBuilderClass::VertClass *) * HASH_TABLE_SIZE); - - MatchNormals = match_normals; - - // initialize the center and extent to do nothing to the points input - Center.Set(0.0f,0.0f,0.0f); - Extent.Set(1.0f,1.0f,1.0f); - } - - ~VertexArrayClass(void) - { - delete[] Verts; - delete[] HashTable; - } - - void Set_Bounds(const Vector3 & minv,const Vector3 & maxv) - { - Extent = (maxv - minv) / 2.0f; - Center = (maxv + minv) / 2.0f; - } - - int Submit_Vertex(const MeshBuilderClass::VertClass & vert) - { - // 2D floating point hashing... - unsigned int lasthash = 0xFFFFFFFF; - unsigned int hash; - unsigned int shadeindex = 0xFFFFFFFF; - - // transform the position of the point into the range - // -1 < p < 1 as defined by the center and extent. - // aja/ehc 19991005 - Handle the case where an extent is zero. - Vector3 position = (vert.Position - Center); - double xstart; - if(fabs(Extent.X) > EPSILON) - xstart = (vert.Position.X - Center.X) / Extent.X; - else - xstart = Center.X; - - double ystart; - if(fabs(Extent.Y) > EPSILON) - ystart = (vert.Position.Y - Center.Y) / Extent.Y; - else - ystart = Center.Y; - - double x,y; - - for (x = xstart - EPSILON; x <= xstart + EPSILON + 0.0000001; x+= EPSILON) { - for (y = ystart - EPSILON; y <= ystart + EPSILON + 0.000001; y+= EPSILON) { - - hash = compute_hash((float)x,(float)y); - - if (hash != lasthash) { - MeshBuilderClass::VertClass * test_vert = HashTable[hash]; - while (test_vert) { - - if (Verts_Shading_Match(vert,*test_vert)) { - if (shadeindex == 0xFFFFFFFF) { - shadeindex = test_vert->UniqueIndex; - - // mask the "master" smoothed vertex's smoothing group with our - // face's smoothing group since we are going to be smoothed with it. - Verts[shadeindex].SharedSmGroup &= vert.SmGroup; - } - } - - if (Verts_Match(vert,*test_vert)) { - return test_vert->UniqueIndex; - } - test_vert = test_vert->NextHash; - } - } - - lasthash = hash; - } - } - - // Not found, add to the end of the array - int newindex = VertCount; - VertCount++; - - Verts[newindex] = vert; - Verts[newindex].UniqueIndex = newindex; - if (shadeindex == 0xFFFFFFFF) { - - Verts[newindex].ShadeIndex = newindex; - - // This is a new vertex,so store the face's smoothing group into SharedSmGroup - Verts[newindex].SharedSmGroup = Verts[newindex].SmGroup; - - } else { - - Verts[newindex].ShadeIndex = shadeindex; - - } - - // This is a new vertex, store the face's smoothing group with it - //Verts[newindex].SmoothingGroup = face_smooth_group; - - // And add to the hash table - x = (vert.Position.X - Center.X) / Extent.X; - y = (vert.Position.Y - Center.Y) / Extent.Y; - hash = compute_hash((float)x,(float)y); - Verts[newindex].NextHash = HashTable[hash]; - HashTable[hash] = &Verts[newindex]; - - return newindex; - } - - int Verts_Match(const MeshBuilderClass::VertClass & v0,const MeshBuilderClass::VertClass & v1) - { - // if user is specifying unique id's, they must match: - if (v0.Id != v1.Id) return 0; - - // position must match: - float dp = (v0.Position - v1.Position).Length(); - if (dp > EPSILON) return 0; - - // normal or smoothing group must match: - if (MatchNormals == 0) { - int smgroup_match = ((v0.SmGroup & v1.SmGroup) || (v0.SmGroup == v1.SmGroup)); - if (!smgroup_match) - return 0; - } else { - float dn = (v0.Normal - v1.Normal).Length(); - if (dn > EPSILON) return 0; - } - - // colors, and material id's must match for all passes - int pass=0; - for (; pass < MeshBuilderClass::MAX_PASSES; pass++) { - - if (v0.DiffuseColor[pass] != v1.DiffuseColor[pass]) - return 0; - if (v0.SpecularColor[pass] != v1.SpecularColor[pass]) - return 0; - if (v0.DiffuseIllumination[pass] != v1.DiffuseIllumination[pass]) - return 0; - if (v0.Alpha[pass] != v1.Alpha[pass]) - return 0; - if (v0.VertexMaterialIndex[pass] != v1.VertexMaterialIndex[pass]) - return 0; - - } - - // texcoords must match for all passes and stages - // Note: I'm checking them separately and last so that I can keep track - // of how many splits are caused solely by u-v discontinuities... - for (pass=0; pass 0.0000001f) { - ok = false; - } - } - return ok; -} - -/*********************************************************************************************** - * MeshBuilderClass::Compute_Vertex_Normals -- Computes the vertex normals for the mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This function should only be called after the mesh has been "optimized". The algorithm * - * relies on non-smooth vertices having been split... * - * * - * HISTORY: * - * 5/15/98 GTH : Created. * - *=============================================================================================*/ -void MeshBuilderClass::Compute_Vertex_Normals(void) -{ - int vertidx; - int faceidx; - int facevertidx; - - /* - ** First, zero all vertex normals - */ - for (vertidx = 0; vertidx < VertCount; vertidx++) { - Verts[vertidx].Normal.Set(0,0,0); - } - - /* - ** Now, go through all of the faces, accumulating the face normals into the - ** "first" vertices containing the appropriate vertex normal for each vertex. - */ - for (faceidx = 0; faceidx < FaceCount; faceidx++) { - for (facevertidx = 0; facevertidx < 3; facevertidx++) { - int vertindex = Faces[faceidx].VertIdx[facevertidx]; - int shadeindex = Verts[vertindex].ShadeIndex; - Verts[shadeindex].Normal += Faces[faceidx].Normal; - } - } - - /* - ** Smooth this mesh with neighboring meshes! - */ - if (WorldInfo != NULL && WorldInfo->Are_Meshes_Smoothed ()) { - for (vertidx = 0; vertidx < VertCount; vertidx++) { - if (Verts[vertidx].ShadeIndex == vertidx) { - Verts[vertidx].Normal += WorldInfo->Get_Shared_Vertex_Normal(Verts[vertidx].Position, Verts[vertidx].SharedSmGroup); - } - } - } - - /* - ** Propogate the accumulated normals to all of the other verts which share them - */ - for (vertidx = 0; vertidx < VertCount; vertidx++) { - int shadeindex = Verts[vertidx].ShadeIndex; - Verts[vertidx].Normal = Verts[shadeindex].Normal; - Verts[vertidx].Normal.Normalize(); - } -} - -/*********************************************************************************************** - * MeshBuilderClass::Remove_Degenerate_Faces -- discard invalid or duplicated faces * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/10/98 GTH : Created. * - *=============================================================================================*/ -void MeshBuilderClass::Remove_Degenerate_Faces(void) -{ - int faceidx; - FaceHasherClass facehasher; - UniqueArrayClass uniquefaces(FaceCount,FaceCount/4,&facehasher); - - for (faceidx = 0; faceidx < FaceCount; faceidx++) { - if (!Faces[faceidx].Is_Degenerate()) { - uniquefaces.Add(Faces[faceidx]); - } - } - - FaceCount = uniquefaces.Count(); - AllocFaceCount = uniquefaces.Count(); - CurFace = FaceCount; - - delete[] Faces; - Faces = new FaceClass[AllocFaceCount]; - - for (faceidx = 0; faceidx < FaceCount; faceidx++) { - Faces[faceidx] = uniquefaces.Get(faceidx); - } -} - - - -/*********************************************************************************************** - * MeshBuilderClass::Compute_Mesh_Stats -- compute some stats about the mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/19/98 GTH : Created. * - *=============================================================================================*/ -void MeshBuilderClass::Compute_Mesh_Stats(void) -{ - int pass; - int stage; - int face_index; - int vert_index; - - int tex_index[MAX_PASSES][MAX_STAGES]; - int shader_index[MAX_PASSES]; - int vmat_index[MAX_PASSES]; - - Stats.Reset(); - - for (pass = 0; passX = Verts[0].Position.X; - set_min->Y = Verts[0].Position.Y; - set_min->Z = Verts[0].Position.Z; - set_max->X = Verts[0].Position.X; - set_max->Y = Verts[0].Position.Y; - set_max->Z = Verts[0].Position.Z; - - for (i=0; iX) set_min->X = Verts[i].Position.X; - if (Verts[i].Position.Y < set_min->Y) set_min->Y = Verts[i].Position.Y; - if (Verts[i].Position.Z < set_min->Z) set_min->Z = Verts[i].Position.Z; - - if (Verts[i].Position.X > set_max->X) set_max->X = Verts[i].Position.X; - if (Verts[i].Position.Y > set_max->Y) set_max->Y = Verts[i].Position.Y; - if (Verts[i].Position.Z > set_max->Z) set_max->Z = Verts[i].Position.Z; - } -} - - -/*********************************************************************************************** - * MeshBuilderClass::Compute_Bounding_Sphere -- computes a bounding sphere for the mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/29/98 GTH : Created. * - *=============================================================================================*/ -void MeshBuilderClass::Compute_Bounding_Sphere(Vector3 * set_center,float * set_radius) -{ - int i; - double dx,dy,dz; - - // bounding sphere - // Using the algorithm described in Graphics Gems I page 301. - // This algorithm supposedly generates a bounding sphere within - // 5% of the optimal one but is much faster and simpler to implement. - Vector3 xmin(Verts[0].Position.X,Verts[0].Position.Y,Verts[0].Position.Z); - Vector3 xmax(Verts[0].Position.X,Verts[0].Position.Y,Verts[0].Position.Z); - Vector3 ymin(Verts[0].Position.X,Verts[0].Position.Y,Verts[0].Position.Z); - Vector3 ymax(Verts[0].Position.X,Verts[0].Position.Y,Verts[0].Position.Z); - Vector3 zmin(Verts[0].Position.X,Verts[0].Position.Y,Verts[0].Position.Z); - Vector3 zmax(Verts[0].Position.X,Verts[0].Position.Y,Verts[0].Position.Z); - - - // FIRST PASS: - // finding the 6 minima and maxima points - for (i=1; i xmax.X) { - xmax.X = Verts[i].Position.X; xmax.Y = Verts[i].Position.Y; xmax.Z = Verts[i].Position.Z; - } - if (Verts[i].Position.Y < ymin.Y) { - ymin.X = Verts[i].Position.X; ymin.Y = Verts[i].Position.Y; ymin.Z = Verts[i].Position.Z; - } - if (Verts[i].Position.Y > ymax.Y) { - ymax.X = Verts[i].Position.X; ymax.Y = Verts[i].Position.Y; ymax.Z = Verts[i].Position.Z; - } - if (Verts[i].Position.Z < zmin.Z) { - zmin.X = Verts[i].Position.X; zmin.Y = Verts[i].Position.Y; zmin.Z = Verts[i].Position.Z; - } - if (Verts[i].Position.Z > zmax.Z) { - zmax.X = Verts[i].Position.X; zmax.Y = Verts[i].Position.Y; zmax.Z = Verts[i].Position.Z; - } - } - - // xspan = distance between the 2 points xmin and xmax squared. - // same goes for yspan and zspan. - dx = xmax.X - xmin.X; - dy = xmax.Y - xmin.Y; - dz = xmax.Z - xmin.Z; - double xspan = dx*dx + dy*dy + dz*dz; - - dx = ymax.X - ymin.X; - dy = ymax.Y - ymin.Y; - dz = ymax.Z - ymin.Z; - double yspan = dx*dx + dy*dy + dz*dz; - - dx = zmax.X - zmin.X; - dy = zmax.Y - zmin.Y; - dz = zmax.Z - zmin.Z; - double zspan = dx*dx + dy*dy + dz*dz; - - - // Set points dia1 and dia2 to the maximally separated pair - // This will be the diameter of the initial sphere - Vector3 dia1 = xmin; - Vector3 dia2 = xmax; - double maxspan = xspan; - - if (yspan > maxspan) { - maxspan = yspan; - dia1 = ymin; - dia2 = ymax; - } - if (zspan > maxspan) { - maxspan = zspan; - dia1 = zmin; - dia2 = zmax; - } - - - // Compute initial center and radius and radius squared - Vector3 center; - center.X = (dia1.X + dia2.X) / 2.0f; - center.Y = (dia1.Y + dia2.Y) / 2.0f; - center.Z = (dia1.Z + dia2.Z) / 2.0f; - - dx = dia2.X - center.X; - dy = dia2.Y - center.Y; - dz = dia2.Z - center.Z; - - double radsqr = dx*dx + dy*dy + dz*dz; - double radius = sqrt(radsqr); - - - // SECOND PASS: - // Increment current sphere if any points fall outside of it. - for (i=0; i radsqr) { - - // this point was outside the old sphere, compute a new - // center point and radius which contains this point - double testrad = sqrt(testrad2); - - // adjust center and radius - radius = (radius + testrad) / 2.0; - radsqr = radius * radius; - - double oldtonew = testrad - radius; - center.X = (radius * center.X + oldtonew * Verts[i].Position.X) / testrad; - center.Y = (radius * center.Y + oldtonew * Verts[i].Position.Y) / testrad; - center.Z = (radius * center.Z + oldtonew * Verts[i].Position.Z) / testrad; - } - } - - *set_center = center; - *set_radius = radius; -} - -/*********************************************************************************************** - * MeshBuilderClass::Optimize_Mesh -- "optimize" the mesh * - * * - * Generates the array of unique vertices and sets the vertex indices in each face. Then * - * all of the faces are sorted by material and then into stripping order. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/15/98 GTH : Created. * - *=============================================================================================*/ -void MeshBuilderClass::Optimize_Mesh(bool compute_normals) -{ - int faceidx; - int vertidx; - int facevertidx; - - int match_normals = 0; - if (!compute_normals) { - match_normals = 1; - } - - VertexArrayClass unique_verts(FaceCount * 3,match_normals); - - /* - ** Find the min and max of the array of vertices - */ - Vector3 minv = Faces[0].Verts[0].Position; - Vector3 maxv = Faces[0].Verts[0].Position; - - for (faceidx = 0; faceidx < FaceCount; faceidx++) { - for (facevertidx = 0; facevertidx < 3; facevertidx++) { - - minv.Update_Min(Faces[faceidx].Verts[facevertidx].Position); - maxv.Update_Max(Faces[faceidx].Verts[facevertidx].Position); - } - } - - /* - ** Tell the vertex array the bounds so that it can do better hashing. - */ - unique_verts.Set_Bounds(minv,maxv); - - /* - ** Build the array of unique vertices - */ - for (faceidx = 0; faceidx < FaceCount; faceidx++) { - for (facevertidx = 0; facevertidx < 3; facevertidx++) { - Faces[faceidx].VertIdx[facevertidx] = - unique_verts.Submit_Vertex(Faces[faceidx].Verts[facevertidx]); - } - } - - /* - ** Assign the shared smoothing groups from each 'master' vertex - ** to each referring vertex. - */ - unique_verts.Propogate_Shared_Smooth_Groups(); - - /* - ** Replace the vertex array with the new unique vertex array - */ - VertCount = unique_verts.VertCount; - Verts = new VertClass[VertCount]; - - for (vertidx=0; vertidx v1) { int tmp = v0; v0 = v1; v1 = tmp; } - - // hash value for the edge - hash = (v0 + v1*119)&511; - - // seek edge from hash table - for (edge = edgehash[hash]; edge; edge = edge->Next) { - if (edge->Vertex[0] == v0 && edge->Vertex[1] == v1 && edge->MaterialIdx == mat) - break; - } - - if (edge) { - - // found the edge - edge->Poly[1] = i; - - } else { - - // create new edge and link it to hash table - edge = edgetab + edgecount++; - edge->Next = edgehash[hash]; - edgehash[hash] = edge; - edge->Vertex[0] = v0; - edge->Vertex[1] = v1; - edge->Poly[0] = i; - edge->Poly[1] = -1; - edge->MaterialIdx = mat; - } - - pedges[i].Edge[j] = edge; - } - } - - // the following loop inserts polygons into a new polygon list until - // all polygons have been inserted. Internally it attempts to create - // as long strips as possible while minimizing material switches - // and maintaining vertex reusage coherency to optimize geometry - // engine performance. - while (polysinserted < FaceCount) { - - int startpoly = -1; // best polygon found so far - int bestc = (1<<29); // best polygon weight value found so far - int startpass = 0; // should we start from pass 0 or 1? - int findpass; // 0 = same material only, 1 = any polygon - int c; // c = number of shared edges - - // first attempt to minimize material switches by choosing a polygon with same material - // as the starting poly. Basically what we want is the poly with same material with - // least shared edges and most recent vertices (as we'd like to start the strip from - // a 'corner polygon'). This pass is done only if mesh has multiple materials. - // The second pass scans through all polygons. - - // this loop is O(N*N) -> might turn a bit nasty on larger meshes. Try - // to figure out a way to solve the problem... - - for (findpass = startpass; findpass < 2; findpass++) - { - // loop through all polygons - for (i = 0; i < FaceCount; i++) { - - // if polygon not picked yet - if (premap[i]==-1) { - - // if material mismatch, cannot choose poly (except in pass 1) - if (findpass == 0 && Faces[i].TextureIndex[PolyOrderPass][PolyOrderStage] != lastmat) - continue; - - // calculate number of shared edges - for (c = 0, j = 0; j < 3; j++) { - - // if edge j is shared by two tris, - // use a weight factor of vCount for each edge - if (pedges[i].Edge[j]->Poly[1] >= 0) { - c += (vcount+1); - } - } - - // calculate delta vertex timestamp - for (j = 0; j < 3; j++) { - c += (vcount-vtimestamp[Faces[i].VertIdx[j]]); - } - - // if better than current best pick - if (c < bestc) { - bestc = c; - startpoly = i; - } - } - } - - // if we managed to find a suitable starting poly - if (startpoly != -1) - break; - } - - // track the fact that we created a new strip: - Stats.StripCount++; - - // update the material index - lastmat = Faces[startpoly].TextureIndex[PolyOrderPass][PolyOrderStage]; - newmat[polysinserted] = Faces[startpoly].TextureIndex[PolyOrderPass][PolyOrderStage]; - - // Add the selected polygon to the new polygon list. - // for each edge of start poly, see if the "other" polygon using that edge - // is untaken, if so, store the new polygon such that that edge index is last - - bool found_shared_edge = false; - newpolys[polysinserted] = Faces[startpoly]; - FaceClass * newpoly = &(newpolys[polysinserted]); - - for (int edge_index = 0; (edge_index < 3) && !found_shared_edge; edge_index++) { - - for (int side_index = 0; (side_index < 2) && !found_shared_edge; side_index++) { - - // if this polygon is not the startpoly and it is not "taken", then this edge is ok! - int poly = pedges[startpoly].Edge[edge_index]->Poly[side_index]; - if ((poly != -1) && (poly != startpoly) && (premap[poly] == -1)) { - - // find vert which is not on the final edge - int first_vert = -1; - for (int vidx=0; vidx<3; vidx++) { - if ( (newpoly->VertIdx[vidx] != pedges[startpoly].Edge[edge_index]->Vertex[0]) && - (newpoly->VertIdx[vidx] != pedges[startpoly].Edge[edge_index]->Vertex[1])) { - - first_vert = newpoly->VertIdx[vidx]; - break; - } - } - assert(first_vert != -1); - - // rotate the vertex indices until first_vert is the index of VertIdx[0] - while (newpoly->VertIdx[0] != first_vert) { - int tmp = newpoly->VertIdx[0]; - newpoly->VertIdx[0] = newpoly->VertIdx[1]; - newpoly->VertIdx[1] = newpoly->VertIdx[2]; - newpoly->VertIdx[2] = tmp; - } - - // ok, we found a shareable edge and adjusted our poly so the strip - // will start with it. Now break out of this loop... - found_shared_edge = true; - break; - } - } - } - - // if a shared edge wasn't found, just copy the poly - if (!found_shared_edge) { - newpolys[polysinserted] = Faces[startpoly]; - } - - // Increment the count. Mark the vertices as used (i.e. update their timestamps) - premap[startpoly] = polysinserted; - polysinserted++; - - for (i = 0; i < 3; i++) { - if (vtimestamp[Faces[startpoly].VertIdx[i]]==-1) { - vtimestamp[Faces[startpoly].VertIdx[i]] = vcount++; - } - } - - // If we have no shared edges, this is a lone poly, start another strip - if (pedges[startpoly].Edge[0]->Poly[1] == -1 && - pedges[startpoly].Edge[1]->Poly[1] == -1 && - pedges[startpoly].Edge[2]->Poly[1] == -1) - continue; - - // Build the strip starting from the polygon chosen in the previous loop - int vFIFO[2]; // vertex fifo - int scnt = 0; // strip index count (for poly order flipping) - int nextpoly = startpoly; - - vFIFO[0] = newpoly->VertIdx[1]; // setup the vFIFO - vFIFO[1] = newpoly->VertIdx[2]; - - while (nextpoly != -1) - { - startpoly = nextpoly; - nextpoly = -1; - - for (i = 0; i < 3; i++) { - - // if edge 'i' of startpoly matches the vertices in the fifo - if ((pedges[startpoly].Edge[i]->Vertex[0] == vFIFO[0] && pedges[startpoly].Edge[i]->Vertex[1] == vFIFO[1]) || - (pedges[startpoly].Edge[i]->Vertex[1] == vFIFO[0] && pedges[startpoly].Edge[i]->Vertex[0] == vFIFO[1])) - { - - for (j = 0; j < 2; j++) { - - // if poly 'j' attached to this edge has not been used already, use it! - if (pedges[startpoly].Edge[i]->Poly[j] > -1 && - premap[pedges[startpoly].Edge[i]->Poly[j]] == -1) - { - nextpoly = pedges[startpoly].Edge[i]->Poly[j]; - goto found; - } - } - } - } - - // couldn't find another poly, break from loop - break; - - found:; - - // now, find the new vertex (two verts are on the edge, find the third) - int nw = -1; - for (i = 0; i < 3; i++) { - if (Faces[nextpoly].VertIdx[i] != vFIFO[0] && Faces[nextpoly].VertIdx[i] != vFIFO[1]) { - nw = i; - break; - } - } - assert(nw != -1); - - int new_vindex = Faces[nextpoly].VertIdx[nw]; - - newmat[polysinserted] = Faces[nextpoly].TextureIndex[PolyOrderPass][PolyOrderStage]; - - // add the poly to the newpolys array. - newpolys[polysinserted].VertIdx[0] = vFIFO[0]; - newpolys[polysinserted].VertIdx[1] = vFIFO[1]; - newpolys[polysinserted].VertIdx[2] = new_vindex; - - // if we are on an even triangle, swap the vertex ordering - if (!(scnt&1)) { - int tmp = newpolys[polysinserted].VertIdx[0]; - newpolys[polysinserted].VertIdx[0] = newpolys[polysinserted].VertIdx[1]; - newpolys[polysinserted].VertIdx[1] = tmp; - } - - // push the new vertex into the fifo - vFIFO[0] = vFIFO[1]; - vFIFO[1] = new_vindex; - - if (vtimestamp[new_vindex]==-1) { - vtimestamp[new_vindex] = vcount++; - } - - premap[nextpoly] = polysinserted++; - scnt++; - } - - // scnt+1 is the number of polys that were added to the strip - Stats.AvgStripLength += scnt+1; - if (scnt+1 > Stats.MaxStripLength) { - Stats.MaxStripLength = scnt+1; - } - } - - // Use the premap array to get the rest of the info into the new face table, - for (i=0; iTextureIndex[0][0] < f1->TextureIndex[0][0]) return -1; - if (f0->TextureIndex[0][0] > f1->TextureIndex[0][0]) return 1; - return 0; -} - -inline int tex_compare(const void * elem1,const void * elem2,int pass,int stage) -{ - MeshBuilderClass::FaceClass * f0 = (MeshBuilderClass::FaceClass *)elem1; - MeshBuilderClass::FaceClass * f1 = (MeshBuilderClass::FaceClass *)elem2; - - /* - ** Primarily, sort by texture - */ - if (f0->TextureIndex[pass][stage] < f1->TextureIndex[pass][stage]) return -1; - if (f0->TextureIndex[pass][stage] > f1->TextureIndex[pass][stage]) return 1; - - /* - ** Secondarily, sort by vertex material index - */ - if (f0->Verts[0].VertexMaterialIndex[pass] < f1->Verts[0].VertexMaterialIndex[pass]) return -1; - if (f0->Verts[0].VertexMaterialIndex[pass] > f1->Verts[0].VertexMaterialIndex[pass]) return 1; - - return 0; -} - -int pass0_stage0_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,0,0); -} - -int pass0_stage1_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,0,1); -} - -int pass1_stage0_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,1,0); -} - -int pass1_stage1_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,1,1); -} - -int pass2_stage0_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,2,0); -} - -int pass2_stage1_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,2,1); -} - -int pass3_stage0_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,3,0); -} - -int pass3_stage1_compare(const void *elem1, const void *elem2) -{ - return tex_compare(elem1,elem2,3,1); -} - -int vertex_compare(const void *elem1, const void *elem2) -{ - MeshBuilderClass::VertClass * v0 = (MeshBuilderClass::VertClass *)elem1; - MeshBuilderClass::VertClass * v1 = (MeshBuilderClass::VertClass *)elem2; - - /* - ** Sort first by bone index, then by vertex material in pass0 - */ - if (v0->BoneIndex < v1->BoneIndex) return -1; - if (v0->BoneIndex > v1->BoneIndex) return 1; - - if (v0->VertexMaterialIndex[0] < v1->VertexMaterialIndex[0]) return -1; - if (v0->VertexMaterialIndex[0] > v1->VertexMaterialIndex[0]) return 1; - - return 0; -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/meshbuild.h b/Generals/Code/Tools/WW3D/max2w3d/meshbuild.h deleted file mode 100644 index 3173b7e6e2..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/meshbuild.h +++ /dev/null @@ -1,379 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/meshbuild.h $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 5/22/00 3:17p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MESHBUILD_H -#define MESHBUILD_H - -#include "always.h" -#include "vector2.h" -#include "vector3.h" -#include "BITTYPE.H" - -#include - -/* -** WorldInfoClass -** Abstract base class that defines an interface for 'world information'. -** This class provides the mesh builder with information about the world -** outside of its mesh. -*/ -class WorldInfoClass -{ - public: - WorldInfoClass(void) { } - virtual ~WorldInfoClass(void) { } - - // Public methods - virtual Vector3 Get_Shared_Vertex_Normal (Vector3 pos, int smgroup) = 0; - virtual bool Are_Meshes_Smoothed (void) const { return true; } -}; - -/* -** MeshBuilderClass -** This class will process meshes for you, splitting all vertices which do not -** share all parameters (such as texture coordinates), sort the polygons by -** material, and put them into strip order. -** -** To "build" a mesh: -** 1. Reset the builder with the number of polys you're going to sumbit -** 2. Enable the vertex channels that you want -** 3. Submit each face in the form of a FaceClass -** 4. Call Build_Mesh -** -** To use the results: -** 1. Call Get_Vertex_Count and Get_Face_Count to get the counts -** 2. Loop through the verts, looking at each one using Get_Vertex -** 3. Loop through the faces, looking at each one using Get_Face -** -** *NOTE* This class is meant to be relatively self-sufficient. It is used in a -** variety of different applications which are built on completely different -** code-bases. Do not introduce dependencies into this module lightly! :-) -*/ -class MeshBuilderClass -{ - -public: - - enum { - STATE_ACCEPTING_INPUT = 0, // mesh builder is accepting input triangles - STATE_MESH_PROCESSED, // mesh builder has processed the mesh - - MAX_PASSES = 4, // maximum number of material passes supported - MAX_STAGES = 2, // maximum number of texture stages supported in a single pass - }; - - /* - ** Constructor, Destructor - */ - MeshBuilderClass(int pass_count=1,int face_count_guess=255,int face_count_growth_rate=64); - ~MeshBuilderClass(void); - - /* - ** VertClass. The MeshBuilder deals with vertices in this format. - */ - class VertClass - { - public: - VertClass(void) { Reset(); } - void Reset(void); - - public: - - Vector3 Position; // position of the vertex - Vector3 Normal; // vertex normal (can be calculated by mesh builder) - int SmGroup; // smoothing group of the face this vertex was submitted with - int Id; // id of the vertex, must match for vert to be welded, ok at zero if you don't care - int BoneIndex; // bone influence if the mesh is a skin - - int MaxVertColIndex; // Index into the Max mesh.vertCol array of this vertex. - - Vector2 TexCoord[MAX_PASSES][MAX_STAGES]; - Vector3 DiffuseColor[MAX_PASSES]; // diffuse color - Vector3 SpecularColor[MAX_PASSES]; // specular color - Vector3 DiffuseIllumination[MAX_PASSES]; // pre-calced diffuse illum - float Alpha[MAX_PASSES]; // alpha - int VertexMaterialIndex[MAX_PASSES]; // vertex material index - - int Attribute0; // user-set attributes (passed on through...) - int Attribute1; // user-set attributes - - // These values are set up by the mesh builder: - - int SharedSmGroup; // smooth bits that were on in all faces that contributed to this final vertex - int UniqueIndex; // used internally! - int ShadeIndex; // used internally! - VertClass * NextHash; // used internally! - - }; - - /* - ** FaceClass. The MeshBuilder deals faces in this format. When inputing faces, set the - ** top half of the struct and the builder will fill in the bottom (vertex indices, normal, - ** and distance). - */ - class FaceClass - { - public: - FaceClass(void) { Reset(); } - void Reset(void); // reset this face - - public: - VertClass Verts[3]; // array of 3 verts - int SmGroup; // smoothing group - int Index; // user-set index of the face - int Attributes; // user-set attributes - int TextureIndex[MAX_PASSES][MAX_STAGES]; // texture to use for each pass - int ShaderIndex[MAX_PASSES]; // shader for each pass - uint32 SurfaceType; // surface type identifier - - int AddIndex; // set by builder: index of addition - int VertIdx[3]; // set by builder: "optimized" vertex indices - Vector3 Normal; // set by builder: Face normal - float32 Dist; // set by builder: Plane distance - - void Compute_Plane(void); - bool operator != (const FaceClass & that) { return !(*this == that); } - bool operator == (const FaceClass & /*that*/) { return false; } - bool Is_Degenerate(void); - - friend class MeshBuilderClass; - }; - - /* - ** To "build" a mesh: - ** 1. Reset the builder with the approximate number of polys you're going to sumbit, etc. - ** 3. Submit each face in the form of a FaceClass, set only the fields you need (leave others at default) - ** 4. Call Build_Mesh - */ - void Reset(int pass_count,int face_count_guess,int face_count_growth_rate); - int Add_Face(const FaceClass & face); - void Build_Mesh(bool compute_normals); - - /* - ** Optional controls: - ** If one of your passes has more textures than another, you may wish to do the - ** stripping and sorting based on that channel. By default, everything will - ** be stripped and sorted based on pass 0, stage 0 - ** Sort_Vertices can be used to order the vertices arbitrarily. I use it to - ** sort them according to the bone they are attached for skin meshes. - */ - void Set_Polygon_Ordering_Channel(int pass,int texstage); - - /* - ** To use the results: - ** 1. Call Get_Vertex_Count and Get_Face_Count to get the counts - ** 2. Loop through the verts, looking at each one using Get_Vertex - ** 3. Loop through the faces, looking at each one using Get_Face - */ - int Get_Pass_Count(void) const; - int Get_Vertex_Count(void) const; - int Get_Face_Count(void) const; - const VertClass & Get_Vertex(int index) const; - const FaceClass & Get_Face(int index) const; - - /* - ** Access to the Vertices and Faces for modifications. This is used by - ** the max plugin when generating a skin mesh for example. Be careful - ** what you do to them. (I haven't thought through all of the - ** possible things you might do to mess up my nice clean mesh...). - */ - VertClass & Get_Vertex(int index); - FaceClass & Get_Face(int index); - - /* - ** Bounding volume information about the mesh. These functions can compute - ** various types of bounding volumes for the mesh you just processed... - */ - void Compute_Bounding_Box(Vector3 * set_min,Vector3 * set_max); - void Compute_Bounding_Sphere(Vector3 * set_center,float * set_radius); - - /* - ** World information managment. Used to give the mesh builder information - ** about the world outside of its mesh. - */ - WorldInfoClass * Peek_World_Info(void) const { return WorldInfo; } - void Set_World_Info(WorldInfoClass *world_info) { WorldInfo = world_info; } - - /* - ** Mesh Stats, mainly lots of flags for whether this mesh has various - ** channels of information. - */ - struct MeshStatsStruct - { - void Reset(void); - - bool HasTexture[MAX_PASSES][MAX_STAGES]; // has at least one texture in given pass/stage - bool HasShader[MAX_PASSES]; // has at least one shader in given pass - bool HasVertexMaterial[MAX_PASSES]; // has at least one vert material in given pass - - bool HasPerPolyTexture[MAX_PASSES][MAX_STAGES]; // has 2+ textures in given pass/stage - bool HasPerPolyShader[MAX_PASSES]; // has 2+ shaders in given pass - bool HasPerVertexMaterial[MAX_PASSES]; // has 2+ vertex materials in given pass - - bool HasDiffuseColor[MAX_PASSES]; // has diffuse colors in given pass - bool HasSpecularColor[MAX_PASSES]; // has specular colors in given pass - bool HasDiffuseIllumination[MAX_PASSES]; // has diffuse illum in given pass - - bool HasTexCoords[MAX_PASSES][MAX_STAGES]; // has texture coords in given pass - - int UVSplitCount; // how many vertices were split due solely to UV discontinuities - int StripCount; // number of strips that were created - int MaxStripLength; // longest strip created - float AvgStripLength; // average strip length - }; - - const MeshStatsStruct & Get_Mesh_Stats(void) const; - -private: - - void Free(void); - void Compute_Mesh_Stats(void); - void Optimize_Mesh(bool compute_normals); - void Strip_Optimize_Mesh(void); - void Remove_Degenerate_Faces(void); - void Compute_Face_Normals(void); - bool Verify_Face_Normals(void); - void Compute_Vertex_Normals(void); - void Grow_Face_Array(void); - void Sort_Vertices(void); - - /* - ** Winged edge stuff is used by the strip optimize function - */ - struct WingedEdgeStruct - { - int MaterialIdx; - WingedEdgeStruct * Next; - int Vertex[2]; - int Poly[2]; - }; - - struct WingedEdgePolyStruct - { - WingedEdgeStruct * Edge[3]; - }; - - - int State; // is the builder accepting input or already processed the mesh. - int PassCount; // number of render passes for this mesh - int FaceCount; // number of faces - FaceClass * Faces; // array of faces - int InputVertCount; // number of input verts; - int VertCount; // number of verts; - VertClass * Verts; // array of verts; - int CurFace; // current face being added - - WorldInfoClass * WorldInfo; // obj containing info about other meshes in the world - - MeshStatsStruct Stats; // internally useful junk about the mesh being processed. - int PolyOrderPass; // order the polys using the texture indices in this pass - int PolyOrderStage; // order the polys using the texture indices in this stage - - int AllocFaceCount; // number of faces allocated - int AllocFaceGrowth; // growth rate of face array -}; - -inline void MeshBuilderClass::Set_Polygon_Ordering_Channel(int pass,int texstage) -{ - assert(pass >= 0); - assert(pass < MAX_PASSES); - assert(texstage >= 0); - assert(texstage < MAX_STAGES); - - PolyOrderPass = pass; - PolyOrderStage = texstage; -} - -inline int MeshBuilderClass::Get_Pass_Count(void) const -{ - return PassCount; -} - -inline int MeshBuilderClass::Get_Vertex_Count(void) const -{ - assert(State == STATE_MESH_PROCESSED); - return VertCount; -} - -inline int MeshBuilderClass::Get_Face_Count(void) const -{ - assert(State == STATE_MESH_PROCESSED); - return FaceCount; -} - -inline const MeshBuilderClass::VertClass & MeshBuilderClass::Get_Vertex(int index) const -{ - assert(State == STATE_MESH_PROCESSED); - assert(index >= 0); - assert(index < VertCount); - return Verts[index]; -} - -inline const MeshBuilderClass::FaceClass & MeshBuilderClass::Get_Face(int index) const -{ - assert(State == STATE_MESH_PROCESSED); - assert(index >= 0); - assert(index < FaceCount); - return Faces[index]; -} - -inline MeshBuilderClass::VertClass & MeshBuilderClass::Get_Vertex(int index) -{ - assert(State == STATE_MESH_PROCESSED); - assert(index >= 0); - assert(index < VertCount); - return Verts[index]; -} - -inline MeshBuilderClass::FaceClass & MeshBuilderClass::Get_Face(int index) -{ - assert(State == STATE_MESH_PROCESSED); - assert(index >= 0); - assert(index < FaceCount); - return Faces[index]; -} - -inline const MeshBuilderClass::MeshStatsStruct & MeshBuilderClass::Get_Mesh_Stats(void) const -{ - assert(State == STATE_MESH_PROCESSED); - return Stats; -} - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/meshcon.cpp b/Generals/Code/Tools/WW3D/max2w3d/meshcon.cpp deleted file mode 100644 index 7fc479a334..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/meshcon.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/meshcon.cpp 34 10/27/00 4:12p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G Math Library * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/meshcon.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 10:39a $* - * * - * $Revision:: 34 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * MeshConnectionsClass::MeshConnectionsClass -- Constructor * - * MeshConnectionsClass::~MeshConnectionsClass -- Destructor * - * MeshConnectionsClass::Get_Aggregate_Data -- name and bone for the given aggregate * - * MeshConnectionsClass::Get_Proxy_Data -- name and transform for the specified proxy object * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "meshcon.h" -#include "util.h" -#include "SnapPoints.h" -#include "w3dappdata.h" -#include "geometryexporttask.h" -#include "geometryexportcontext.h" - - -/*********************************************************************************************** - * MeshConnectionsClass::MeshConnectionsClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/19/2000 gth : New version which uses the GeometryExportTasks * - *=============================================================================================*/ -MeshConnectionsClass::MeshConnectionsClass -( - DynamicVectorClass sub_object_list, - GeometryExportContextClass & context -) : - CurTime(context.CurTime), - Origin(context.Origin) -{ - unsigned int i; - assert(Origin != NULL); - - /* - ** Set the name, count the sub-objects and aggregates - */ - Set_W3D_Name(Name,context.ModelName); - - /* - ** For each sub-object, record the bone it is attached to and its name - */ - int count = sub_object_list.Count(); - for (i=0; iGet_Full_Name(con.ObjectName,sizeof(con.ObjectName)); - con.BoneIndex = sub_object_list[i]->Get_Bone_Index(); - con.MeshINode = sub_object_list[i]->Get_Object_Node(); - - if (sub_object_list[i]->Is_Aggregate()) { - Aggregates.Add(con); - } else if (sub_object_list[i]->Is_Proxy()) { - ProxyObjects.Add(con); - } else { - SubObjects.Add(con); - } - } -} - - -/*********************************************************************************************** - * MeshConnectionsClass::~MeshConnectionsClass -- Destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -MeshConnectionsClass::~MeshConnectionsClass(void) -{ -} - - -/*********************************************************************************************** - * MeshConnectionsClass::Get_Sub_Object_Data -- Returns the name and bone index for a given obj* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/14/1999 AJA : Created. * - *=============================================================================================*/ -bool MeshConnectionsClass::Get_Sub_Object_Data (int mesh_idx, char **out_name, int *out_boneindex, - INode **out_inode) -{ - if (mesh_idx >= SubObjects.Count()) return false; - - if (out_name) - *out_name = SubObjects[mesh_idx].ObjectName; - if (out_boneindex) - *out_boneindex = SubObjects[mesh_idx].BoneIndex; - if (out_inode) - *out_inode = SubObjects[mesh_idx].MeshINode; - - return true; -} - - -/*********************************************************************************************** - * MeshConnectionsClass::Get_Aggregate_Data -- name and bone for the given aggregate * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/25/2000 gth : Created. * - *=============================================================================================*/ -bool MeshConnectionsClass::Get_Aggregate_Data(int mesh_idx, char **out_name, int *out_boneindex, - INode **out_inode) -{ - if (mesh_idx >= Aggregates.Count()) return false; - - if (out_name) - *out_name = Aggregates[mesh_idx].ObjectName; - if (out_boneindex) - *out_boneindex = Aggregates[mesh_idx].BoneIndex; - if (out_inode) - *out_inode = Aggregates[mesh_idx].MeshINode; - - return true; -} - - -/*********************************************************************************************** - * MeshConnectionsClass::Get_Proxy_Data -- name and transform for the specified proxy object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/2000 gth : Created. * - *=============================================================================================*/ -bool MeshConnectionsClass::Get_Proxy_Data(int index, char **out_name, int *out_boneindex, - INode **out_inode) -{ - if (index >= ProxyObjects.Count()) return false; - - if (out_name) - *out_name = ProxyObjects[index].ObjectName; - if (out_boneindex) - *out_boneindex = ProxyObjects[index].BoneIndex; - if (out_inode) - *out_inode = ProxyObjects[index].MeshINode; - - return true; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/meshcon.h b/Generals/Code/Tools/WW3D/max2w3d/meshcon.h deleted file mode 100644 index 848e1fe074..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/meshcon.h +++ /dev/null @@ -1,149 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/meshcon.h 26 10/27/00 4:11p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G Tools * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/meshcon.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 10:31a $* - * * - * $Revision:: 26 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef MESHCON_H -#define MESHCON_H - - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef CHUNKIO_H -#include "chunkio.h" -#endif - -#ifndef NODELIST_H -#include "nodelist.h" -#endif - -#ifndef HIERSAVE_H -#include "hiersave.h" -#endif - -#ifndef W3D_FILE -#include "w3d_file.h" -#endif - -#ifndef VECTOR_H -#include "Vector.H" -#endif - - -class GeometryExportTaskClass; -class GeometryExportContextClass; - - -struct ConnectionStruct -{ - ConnectionStruct(void) : BoneIndex(0),MeshINode(NULL) - { - memset(ObjectName,0,sizeof(ObjectName)); - } - - int BoneIndex; - char ObjectName[2*W3D_NAME_LEN]; - INode * MeshINode; - - // required by DynamicVectorClass... - operator == (const ConnectionStruct & that) { return false; } - operator != (const ConnectionStruct & that) { return !(*this==that); } -}; - - -/** -** MeshConnectionsClass -** This class is the description of a hierarchical model. It contains an array of "ConnectionStructs" which -** associate pieces of geometry with nodes in a hierarchy tree. -*/ -class MeshConnectionsClass -{ -public: - - MeshConnectionsClass( DynamicVectorClass sub_objects, - GeometryExportContextClass & context ); - - ~MeshConnectionsClass(void); - - /* - ** Get the name of the mesh connections object (will be - ** the name of the runtime HierarchyModel that this - ** object is describing. - */ - const char * Get_Name(void) const { return Name; } - - /* - ** Get the total number of meshes (of all types). - */ - int Get_Sub_Object_Count (void) const { return SubObjects.Count(); } - int Get_Aggregate_Count(void) const { return Aggregates.Count(); } - int Get_Proxy_Count(void) const { return ProxyObjects.Count(); } - - /* - ** Retrieve data about the mesh of the given index. - ** out_name - name of the mesh is passed back by setting the char* pointed to by this value. - ** out_boneindex - the index of the bone used is passed back by setting the int pointed to by this value. - ** out_inode - mesh INode is passed by setting the INode* pointed to by this value. If this - ** parameter is NULL, the value is not passed back. - */ - bool Get_Sub_Object_Data(int index, char **out_name, int *out_boneindex, INode **out_inode = NULL); - bool Get_Aggregate_Data(int index, char **out_name, int *out_boneindex, INode **out_inode = NULL); - bool Get_Proxy_Data(int index, char **out_name, int *out_boneindex, INode **out_inode = NULL); - - /* - ** Returns the origin node used by this model. - */ - INode * Get_Origin (void) const { return Origin; } - -private: - - TimeValue CurTime; - INode * Origin; - - char Name[W3D_NAME_LEN]; - - // array of SubObjects - DynamicVectorClass SubObjects; - DynamicVectorClass Aggregates; - DynamicVectorClass ProxyObjects; - - -}; - - -#endif /*MESHCON_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/meshsave.cpp b/Generals/Code/Tools/WW3D/max2w3d/meshsave.cpp deleted file mode 100644 index 49955e87d1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/meshsave.cpp +++ /dev/null @@ -1,2246 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/meshsave.cpp 107 8/21/01 10:28a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : MESHSAVE.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/10/97 * - * * - * Last Update : 10/20/1999997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * MeshSaveClass::MeshSaveClass -- constructor, processes a Max mesh * - * MeshSaveClass::~MeshSaveClass -- destructor, frees all allocated memory * - * MeshSaveClass::write_verts -- write the vertex chunk into a wtm file * - * MeshSaveClass::write_header -- write a mesh header chunk into a wtm file * - * MeshSaveClass::Write_To_File -- Append the mesh to an open wtm file * - * MeshSaveClass::write_normals -- writes the vertex normals chunk into a wtm file * - * MeshSaveClass::write_vert_normals -- Writes the surrender normal chunk into a wtm file * - * MeshSaveClass::write_triangles -- Write the triangles chunk into a wtm file. * - * MeshSaveClass::write_sr_triangles -- writes the triangles in surrender friendly format * - * MeshSaveClass::write_triangles -- write the triangles chunk * - * MeshSaveClass::compute_surrender_vertex -- Compute the surrender vertex normals * - * MeshSaveClass::setup_material -- Gets the texture names and base colors for a material * - * MeshSaveClass::compute_bounding_volumes -- computes a bounding box and bounding sphere for* - * MeshSaveClass::set_transform -- set the default transformation matrix for the mesh * - * MeshSaveClass::compute_physical_properties -- computes the volume and moment of inertia * - * MeshSaveClass::prep_mesh -- pre-transform the MAX mesh by a specified matrix * - * MeshSaveClass::write_user_text -- write the user text chunk * - * MeshSaveClass::get_htree_bone_index_for_inode -- searches the htree for the given INode * - * MeshSaveClass::get_skin_modifier_objects -- Searches for the WWSkin modifier for this mes * - * MeshSaveClass::inv_deform_mesh -- preprocess the mesh for skinning * - * MeshSaveClass::create_materials -- create the materials for this mesh * - * MeshSaveClass::write_ps2_shaders -- Write shaders specific to the PS2 in their own chunk. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "meshsave.h" -#include -#include -#include -#include "gamemtl.h" -#include "errclass.h" -#include "vxl.h" -#include "vxldbg.h" -#include "nodelist.h" -#include "hiersave.h" -#include "util.h" -#include "w3dappdata.h" -#include "skin.h" -#include "skindata.h" -#include "meshbuild.h" -#include "AlphaModifier.h" -#include "aabtreebuilder.h" -#include "exportlog.h" - - -static char _string1[512]; -const int VOXEL_RESOLUTION = 64; // resolution to use when computing I, V and CM - -#define DEBUG_VOXELS 0 -#define MIN_AABTREE_POLYGONS 8 -#define DIFFUSE_HOUSECOLOR_TEXTURE_PREFIX 0x4443485A //'ZHCD' prefix put on all code generated textures -#define DIFFUSE_COLOR_TEXTURE_PREFIX 0x44434d5A //'ZMCD' prefix put on all code generated textures -#define DIFFUSE_COLOR_TEXTURE_MASK 0x4443005A - -/************************************************************************************ -** -** Compute the determinant of the 3x3 portion of the given matrix -** -************************************************************************************/ -float Compute_3x3_Determinant(const Matrix3 & tm) -{ - float det = tm[0][0] * (tm[1][1]*tm[2][2] - tm[1][2]*tm[2][1]); - det -= tm[0][1] * (tm[1][0]*tm[2][2] - tm[1][2]*tm[2][0]); - det += tm[0][2] * (tm[1][0]*tm[2][1] - tm[1][1]*tm[2][0]); - - return det; -} - -/************************************************************************************ -** -** check if this is a mesh which should use a simple rendering method. I don't -** compute vertex normals or store u-v's in that case (prevents vertex splitting) -** -************************************************************************************/ -bool use_simple_rendering(int geo_type) -{ - geo_type &= W3D_MESH_FLAG_GEOMETRY_TYPE_MASK; - - if ( (geo_type == OBSOLETE_W3D_MESH_FLAG_GEOMETRY_TYPE_SHADOW) || - (geo_type == W3D_MESH_FLAG_GEOMETRY_TYPE_AABOX) || - (geo_type == W3D_MESH_FLAG_GEOMETRY_TYPE_OBBOX) ) - { - return true; - } else { - return false; - } -} - -/************************************************************************************ -** -** build the bitfield of W3D mesh attributes for the given node -** -************************************************************************************/ -uint32 setup_mesh_attributes(INode * node) -{ - uint32 attributes = W3D_MESH_FLAG_NONE; - - /* - ** Mesh will be one of: - ** W3D_MESH_FLAG_NONE, - ** W3D_MESH_FLAG_COLLISION_BOX, - ** W3D_MESH_FLAG_SKIN, - ** W3D_MESH_FLAG_ALIGNED - ** W3D_MESH_FLAG_ORIENTED - */ - if (Is_Collision_AABox(node)) { - attributes = W3D_MESH_FLAG_GEOMETRY_TYPE_AABOX; - } else if (Is_Collision_OBBox(node)) { - attributes = W3D_MESH_FLAG_GEOMETRY_TYPE_OBBOX; - } else if (Is_Skin(node)) { - attributes = W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN; - } else if (Is_Camera_Aligned_Mesh(node)) { - attributes = W3D_MESH_FLAG_GEOMETRY_TYPE_CAMERA_ALIGNED; - } else if (Is_Camera_Oriented_Mesh(node)) { - attributes = W3D_MESH_FLAG_GEOMETRY_TYPE_CAMERA_ORIENTED; - } - - /* - ** And, a mesh may have one or more types of collision detection enabled. - ** W3D_MESH_FLAG_COLLISION_TYPE_PHYSICAL - ** W3D_MESH_FLAG_COLLISION_TYPE_PROJECTILE - ** However, if the mesh is SKIN, SHADOW, ALIGNED, ORIENTED or NULL, don't let - ** the collision bits get set... - */ - if ( attributes != W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN && - attributes != W3D_MESH_FLAG_GEOMETRY_TYPE_CAMERA_ALIGNED && - attributes != W3D_MESH_FLAG_GEOMETRY_TYPE_CAMERA_ORIENTED ) - { - - if (Is_Physical_Collision(node)) { - attributes |= W3D_MESH_FLAG_COLLISION_TYPE_PHYSICAL; - } - - if (Is_Projectile_Collision(node)) { - attributes |= W3D_MESH_FLAG_COLLISION_TYPE_PROJECTILE; - } - - if (Is_Vis_Collision(node)) { - attributes |= W3D_MESH_FLAG_COLLISION_TYPE_VIS; - } - - if (Is_Camera_Collision(node)) { - attributes |= W3D_MESH_FLAG_COLLISION_TYPE_CAMERA; - } - - if (Is_Vehicle_Collision(node)) { - attributes |= W3D_MESH_FLAG_COLLISION_TYPE_VEHICLE; - } - - } - - /* - ** A mesh may have one of the following bits set as well - */ - if (Is_Hidden(node)) { - attributes |= W3D_MESH_FLAG_HIDDEN; - } - if (Is_Two_Sided(node)) { - attributes |= W3D_MESH_FLAG_TWO_SIDED; - } - if (Is_Shadow(node)) { - attributes |= W3D_MESH_FLAG_CAST_SHADOW; - } - if (Is_Shatterable(node)) { - attributes |= W3D_MESH_FLAG_SHATTERABLE; - } - if (Is_NPatchable(node)) { - attributes |= W3D_MESH_FLAG_NPATCHABLE; - } - - return attributes; -} - - - -/*********************************************************************************************** - * MeshSaveClass::MeshSaveClass -- constructor, processes a Max mesh * - * * - * This class takes a MAX mesh and computes the information for a W3D mesh or skin. * - * * - * INPUT: * - * * - * inode - the max INode containing the mesh/skin to export * - * exportspace - matrix defining the desired coordinate system for the mesh * - * htree - hierarchy tree that this mesh is being connected to * - * curtime - current time in Max. * - * meter - progress meter * - * mesh_name - name to use for the mesh * - * container_name - name of the container * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -MeshSaveClass::MeshSaveClass -( - char * mesh_name, - char * container_name, - INode * inode, - const Mesh * input_mesh, - Matrix3 & exportspace, - W3DAppData2Struct & exportoptions, - HierarchySaveClass * htree, - TimeValue curtime, - Progress_Meter_Class & meter, - unsigned int * materialColors, - int &numMaterialColors, - int &numHouseColors, - char *materialColorTexture, - WorldInfoClass * world_info -) : - MaxINode(inode), - ExportOptions(exportoptions), - CurTime(curtime), - ExportSpace(exportspace), - HTree(htree), - UserText(NULL), - VertInfluences(NULL), - MaterialRemapTable(NULL) -{ - Mesh mesh = *input_mesh; // copy the mesh so we can modify it - Mtl * nodemtl = inode->GetMtl(); - DWORD wirecolor = inode->GetWireColor(); - - PS2Material = FALSE; - - // Check to see if the mesh uses PS2 game materials. If so, set a flag so - // that write_shaders will know to make a PS2 shader chunk. - if (nodemtl) { - if (nodemtl->ClassID() == PS2GameMaterialClassID) { - PS2Material = TRUE; - } else if (nodemtl->IsMultiMtl()) { - for (int i = 0; i < nodemtl->NumSubMtls(); i++) { - Mtl *sub = nodemtl->GetSubMtl(i); - if (sub->ClassID() == PS2GameMaterialClassID) { - PS2Material = TRUE; - } - } - } - } - - ////////////////////////////////////////////////////////////////////// - // Check if the mesh is being inverted by its transform. If this - // is the case, then we will need to reverse the winding of all - // polygons later. - ////////////////////////////////////////////////////////////////////// - Matrix3 objtm = MaxINode->GetObjectTM(curtime); - MeshInverted = (Compute_3x3_Determinant(objtm) < 0.0f); - - ////////////////////////////////////////////////////////////////////// - // Prep the mesh by transforming it by the delta between exportspace - // and this INodes current space - // (this is the delta between the bone and the mesh if one exists...) - ////////////////////////////////////////////////////////////////////// - MeshToExportSpace = objtm * Inverse(ExportSpace); - prep_mesh(mesh,MeshToExportSpace); - - ////////////////////////////////////////////////////////////////////// - // Prepare the mesh header. - ////////////////////////////////////////////////////////////////////// - assert(mesh_name != NULL); - assert(container_name != NULL); - - memset(&Header,0,sizeof(Header)); - Set_W3D_Name(Header.MeshName,mesh_name); - Set_W3D_Name(Header.ContainerName,container_name); - - Header.Version = W3D_CURRENT_MESH_VERSION; - Header.Attributes = setup_mesh_attributes(MaxINode); - - meter.Finish_In_Steps( - 3*Header.NumTris + // normals - Header.NumVertices + // surrender normals - 64 // voxelization - ); - - ExportLog::printf("\nProcessing Mesh: %s\n",Header.MeshName); - - ////////////////////////////////////////////////////////////////////// - // Enforce that we have enough data to actually make a mesh - ////////////////////////////////////////////////////////////////////// - if (mesh.getNumFaces() <= 0) { - throw ErrorClass("No Triangles in Mesh: %s",Header.MeshName); - } - - if (mesh.getNumVerts() <= 0) { - throw ErrorClass("No Vertices in Mesh: %s",Header.MeshName); - } - - ////////////////////////////////////////////////////////////////////// - // process the materials - ////////////////////////////////////////////////////////////////////// - DebugPrint("processing materials\n"); - scan_used_materials(mesh,nodemtl); - create_materials(nodemtl,wirecolor,materialColorTexture); - - ////////////////////////////////////////////////////////////////////// - // what face and vertex attributes are we going to export? - ////////////////////////////////////////////////////////////////////// - Header.FaceChannels = W3D_FACE_CHANNEL_FACE; - Header.VertexChannels = W3D_VERTEX_CHANNEL_LOCATION; - - if (!use_simple_rendering(Header.Attributes)) { - Header.VertexChannels |= W3D_VERTEX_CHANNEL_NORMAL; - } - - if (((Header.Attributes & W3D_MESH_FLAG_GEOMETRY_TYPE_MASK) == W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN) && (HTree != NULL)) { - Header.VertexChannels |= W3D_VERTEX_CHANNEL_BONEID; - } - - ////////////////////////////////////////////////////////////////////// - // Process the mesh - ////////////////////////////////////////////////////////////////////// - Builder.Set_World_Info (world_info); - Build_Mesh(mesh, nodemtl, materialColors, numMaterialColors, numHouseColors); - - if (materialColorTexture) - { //diffuse color materials are replaced by textures - //set diffuse to 255,255,255 so it has no effect. - fix_diffuse_materials(numHouseColors != 0); - } - - ////////////////////////////////////////////////////////////////////// - // Create damage (deform) information for the mesh - ////////////////////////////////////////////////////////////////////// - Object *ref_obj = MaxINode->GetObjectRef (); - DeformSave.Initialize(Builder, ref_obj, mesh, &MeshToExportSpace); - - ////////////////////////////////////////////////////////////////////// - // Determine if the deformer should use alpha or v-color info - ////////////////////////////////////////////////////////////////////// - if (ExportOptions.Is_Vertex_Alpha_Enabled()) { - unsigned int alpha_passes = 0; - for (int pass=0; pass < MaterialDesc.Pass_Count(); pass++) { - if (MaterialDesc.Pass_Uses_Vertex_Alpha(pass)) { - alpha_passes |= (1 << pass); - } - } - DeformSave.Set_Alpha_Passes(alpha_passes); - } - - ////////////////////////////////////////////////////////////////////// - // Set the counts in the mesh header - ////////////////////////////////////////////////////////////////////// - Header.NumTris = Builder.Get_Face_Count(); - Header.NumVertices = Builder.Get_Vertex_Count(); - - ////////////////////////////////////////////////////////////////////// - // Compute the mesh's bounding box and sphere. This must be done - // before we pre-deform the mesh (if its a skin). - ////////////////////////////////////////////////////////////////////// - compute_bounding_volumes(); - - ////////////////////////////////////////////////////////////////////// - // Voxelize the mesh and compute the Moment of Inertia and - // Center of Mass. This must come after we compute the bounding - // volumes and before we pre-deform the mesh. - ////////////////////////////////////////////////////////////////////// - Progress_Meter_Class voxelmeter(meter, 64.0f * meter.Increment); - compute_physical_constants(MaxINode,voxelmeter,false /*usevoxelizer*/); - - ////////////////////////////////////////////////////////////////////// - // If this is a skin, pre-deform the mesh. - ////////////////////////////////////////////////////////////////////// - if (((Header.Attributes & W3D_MESH_FLAG_GEOMETRY_TYPE_MASK) == W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN) && (HTree != NULL)) { - inv_deform_mesh(); - } - - ////////////////////////////////////////////////////////////////////// - // Get the user text from MAX's properties window. - ////////////////////////////////////////////////////////////////////// - TSTR usertext; - MaxINode->GetUserPropBuffer(usertext); - CStr usertext8 = usertext; - - if (usertext8.Length() > 0) { - UserText = new char[usertext8.Length() + 1]; - memset(UserText,0,usertext8.Length() + 1); - memcpy(UserText,usertext8.data(),usertext8.Length()); - } -} - -/*********************************************************************************************** - * MeshSaveClass::~MeshSaveClass -- destructor, frees all allocated memory * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -MeshSaveClass::~MeshSaveClass(void) -{ - if (UserText) { - delete[] UserText; - UserText = NULL; - } - - if (VertInfluences) { - delete[] VertInfluences; - VertInfluences = NULL; - } - - if (MaterialRemapTable) { - delete[] MaterialRemapTable; - MaterialRemapTable = NULL; - } -} - -//search through previously found material colors and return index. house colors are always placed in top row. -void getMaterialUV(UVVert &tvert,unsigned int diffuse, unsigned int *materialColors, int &numMaterialColors, int &numHouseColors, bool house) -{ - int i; - - if (house) - { //this material is a house color, place it in first row. - for (i=0; i<16; i++) - { - if (materialColors[i]==diffuse) - { - tvert.x=((double)(i%16)+0.5)/16.0; ///@todo: MW: Remove hard-coded texture size - tvert.y=1.0-((double)(i/16)+0.5)/16.0; - numHouseColors=16; - return; - } - } - - ExportLog::printf("\nUndefined House Color %d,%d,%d",(diffuse>>16)&0xff,(diffuse>>8)&0xff,diffuse&0xff); - assert(0); //all house colors must be from a predefined range of reds - } - - for (i=16; i<(16+numMaterialColors); i++) - { - if (materialColors[i]==diffuse) - { - tvert.x=((double)(i%16)+0.5)/16.0; ///@todo: MW: Remove hard-coded texture size - tvert.y=1.0-((double)(i/16)+0.5)/16.0; - return; - } - } - - //new color found - tvert.x=((double)(i%16)+0.5)/16.0; ///@todo: MW: Remove hard-coded texture size - tvert.y=1.0-((double)(i/16)+0.5)/16.0; - - materialColors[i]=diffuse; - numMaterialColors++; -} - -void MeshSaveClass::Build_Mesh(Mesh & mesh, Mtl *node_mtl, unsigned int *materialColors, int &numMaterialColors, int &numHouseColors) -{ - int vert_counter; - int face_index; - int pass; - int stage; - float *vdata = NULL; - int firstSolidColoredMaterial=-1; - - Builder.Reset(true,mesh.getNumFaces(),mesh.getNumFaces()/3); - - // Get a pointer to the channel that has alpha values entered by the artist. - // This pointer will be NULL if they didn't use the channel. - vdata = mesh.vertexFloat(ALPHA_VERTEX_CHANNEL); - - /* - ** Get the skin info - */ - bool is_skin = false; - SkinDataClass * skindata = NULL; - SkinWSMObjectClass * skinobj = NULL; - - get_skin_modifier_objects(&skindata,&skinobj); - - if ( ((Header.Attributes & W3D_MESH_FLAG_GEOMETRY_TYPE_MASK) == W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN) && - (HTree != NULL) ) - { - is_skin = ((skindata != NULL) && (skinobj != NULL)); - } - - /* - ** Submit all of the faces - */ - MeshBuilderClass::FaceClass face; - for (face_index = 0; face_index < mesh.getNumFaces(); face_index++) { - - Face maxface = mesh.faces[face_index]; - - int mat_index = 0; - if (Header.NumMaterials > 0) { - mat_index = MaterialRemapTable[(maxface.getMatID() % Header.NumMaterials)]; - } - assert(mat_index != -1); - - for (pass=0; passNumSubMtls() > 1)) { - mtl_to_use = node_mtl->GetSubMtl (maxface.getMatID() % node_mtl->NumSubMtls()); - } - - if ((mtl_to_use != NULL) && ((mtl_to_use->ClassID() == GameMaterialClassID) || - (mtl_to_use->ClassID() == PS2GameMaterialClassID))) { - face.SurfaceType = ((GameMtl *)mtl_to_use)->Get_Surface_Type (); - } - - for (vert_counter = 0; vert_counter < 3; vert_counter++) { - - /* - ** if this mesh is being inverted, we need to insert the verts in - ** the opposite order. max_vert_counter will count backwards - ** in this case; causing all vertex data to be entered in the - ** reverse winding. - */ - int max_vert_counter; - - if (MeshInverted) { - max_vert_counter = 2 - vert_counter; - } else { - max_vert_counter = vert_counter; - } - - int max_vert_index = maxface.v[max_vert_counter]; - - /* - ** Vertex Id, to prevent unwanted welding! - */ - face.Verts[vert_counter].Id = max_vert_index; - - /* - ** Vertex Position - */ - face.Verts[vert_counter].Position.X = mesh.verts[max_vert_index].x; - face.Verts[vert_counter].Position.Y = mesh.verts[max_vert_index].y; - face.Verts[vert_counter].Position.Z = mesh.verts[max_vert_index].z; - - if (vdata) { - - // If an alpha channel has been created, use its value. - for (int pass=0; pass < MaterialDesc.Pass_Count(); pass++) { - if (MaterialDesc.Pass_Uses_Vertex_Alpha(pass)) { - // Mulitiply by .01 to change from percentage. - face.Verts[vert_counter].Alpha[pass] = vdata[max_vert_index] * .01; - } - } - } - - - /* - ** Texture coordinate. Apply uv coords if the mesh has them and is not being - ** instructed to ignore them. - ** - check if the mesh needs them (uses_simple_rendering() == false) - ** - for each pass and stage, look up what map channel this face's material is using - ** - ask Max for the tfaces and tverts for that map channel - ** - copy the values into each vertex - */ - for (pass=0; passFilename && *((unsigned int *)map3d->Filename) == DIFFUSE_COLOR_TEXTURE_PREFIX) //check for prefix - { - double Diffuse = vmat->Diffuse.Get_Color() >> 8; //get material color - - //MW: Encode the material color into the u texture coordinate - tvert.x=Diffuse; - tvert.y=Diffuse; - - //find out material color location within texture page - if (strnicmp(MaterialDesc.Get_Vertex_Material_Name(mat_index,pass),"HouseColor",10)==0) - getMaterialUV(tvert,vmat->Diffuse.Get_Color() >> 8, materialColors, numMaterialColors, numHouseColors, true); - else - getMaterialUV(tvert,vmat->Diffuse.Get_Color() >> 8, materialColors, numMaterialColors, numHouseColors, false); - - //Keep track of first vertex material converted, so we can remap all other non-textured - //materials to use the same material. - if (firstSolidColoredMaterial == -1) - firstSolidColoredMaterial=MaterialDesc.Get_Vertex_Material_Index(mat_index,pass); - } - - /* - ** If the mesh needs uv coords and they are present, copy the uv into tvert - */ - else - if (!use_simple_rendering(Header.Attributes)) { - - int channel = MaterialDesc.Get_Map_Channel(mat_index,pass,stage); - - UVVert * uvarray = mesh.mapVerts(channel); - TVFace * tvfacearray = mesh.mapFaces(channel); - - ///@todo: MW: Forced ingoring of uv coordinates if no texture! Is this ok? - W3dMapClass *map3d=MaterialDesc.Get_Texture(mat_index,pass,stage); - - if (map3d && (uvarray != NULL) && (tvfacearray != NULL)) { - - int tvert_index = tvfacearray[face_index].t[max_vert_counter]; - tvert = uvarray[tvert_index]; - } - } - - /* - ** Copy the texture coordinate into the vertex structure - */ - face.Verts[vert_counter].TexCoord[pass][stage].X = tvert.x; - face.Verts[vert_counter].TexCoord[pass][stage].Y = tvert.y; - - } - } - - /* - ** Vertex Color - */ - if (mesh.vcFace) { - - /* - ** If the mesh is being mirrored, remap the index - */ - int max_cvert_index = mesh.vcFace[face_index].t[max_vert_counter]; - - VertColor vc; - vc = mesh.vertCol[max_cvert_index]; - - /* - ** If Vertex Alpha is specified, the vertex color is converted - ** to alpha. If the (obsolete) Node-flag for vertex alpha is enabled, - ** the alpha is put into each pass which has alpha enabled. Otherwise, - ** we check the material settings for which passes should get the alpha - ** values. If neither alpha options are enabled, we put the color - ** value into the first pass. - */ - if (ExportOptions.Is_Vertex_Alpha_Enabled()) { - - float alpha = (vc.x + vc.y + vc.z) / 3.0f; - for (int pass=0; pass < MaterialDesc.Pass_Count(); pass++) { - if (MaterialDesc.Pass_Uses_Vertex_Alpha(pass)) { - face.Verts[vert_counter].Alpha[pass] = alpha; - } - } - } else { - face.Verts[vert_counter].DiffuseColor[0].X = vc.x; - face.Verts[vert_counter].DiffuseColor[0].Y = vc.y; - face.Verts[vert_counter].DiffuseColor[0].Z = vc.z; - } - - face.Verts[vert_counter].MaxVertColIndex = max_cvert_index; - - } else { - face.Verts[vert_counter].MaxVertColIndex = 0; - } - - /* - ** Vertex materials (get's index of sub-material) - */ - for (pass = 0; passFilename && *((unsigned int *)map3d->Filename) == DIFFUSE_COLOR_TEXTURE_PREFIX) //check for prefix - face.Verts[vert_counter].VertexMaterialIndex[pass]=firstSolidColoredMaterial; - else - face.Verts[vert_counter].VertexMaterialIndex[pass] = MaterialDesc.Get_Vertex_Material_Index(mat_index,pass); - } - - face.Verts[vert_counter].Attribute0 = max_vert_index; - face.Verts[vert_counter].Attribute1 = face_index; - - /* - ** Skin attachment - */ - face.Verts[vert_counter].BoneIndex = 0; - if (is_skin) { - - int skin_bone_index = skindata->VertData[max_vert_index].BoneIdx[0]; - - // If this is a valid bone, try to find the corresponding bone index in the HTree - if ( (skin_bone_index != -1) && - (skin_bone_index < skinobj->Num_Bones()) && - (skinobj->BoneTab[skin_bone_index] != NULL) ) - { - face.Verts[vert_counter].BoneIndex = get_htree_bone_index_for_inode(skinobj->BoneTab[skin_bone_index]); - } - } - } - - Builder.Add_Face(face); - } - - /* - ** Process the mesh - */ - Builder.Build_Mesh(true); - - const MeshBuilderClass::MeshStatsStruct & stats = Builder.Get_Mesh_Stats(); - int vcount = Builder.Get_Vertex_Count(); - int pcount = mesh.numFaces; - float vert_poly_ratio = (float)vcount / (float)pcount; - - ExportLog::printf(" triangle count: %d\n",pcount); - ExportLog::printf(" final vertex count: %d\n",vcount); - ExportLog::printf(" vertex/triangle ratio: %f\n",vert_poly_ratio); - ExportLog::printf(" strip count: %d\n",stats.StripCount); - ExportLog::printf(" average strip length: %f\n",stats.AvgStripLength); - ExportLog::printf(" longest strip: %d\n",stats.MaxStripLength); -} - - -/*********************************************************************************************** - * MeshSaveClass::get_skin_modifier_objects -- Searches for the WWSkin modifier for this mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void MeshSaveClass::get_skin_modifier_objects(SkinDataClass ** skin_data_ptr,SkinWSMObjectClass ** skin_obj_ptr) -{ - *skin_data_ptr = NULL; - *skin_obj_ptr = NULL; - - // loop through the references that our node has - for (int i = 0; i < MaxINode->NumRefs(); i++) { - - ReferenceTarget *refTarg = MaxINode->GetReference(i); - - // if the reference is a WSM Derived Object. - if (refTarg != NULL && refTarg->ClassID() == Class_ID(WSM_DERIVOB_CLASS_ID,0)) { - - IDerivedObject * wsm_der_obj = (IDerivedObject *)refTarg; - - // loop through the WSM's attached to this WSM Derived object - for (int j = 0; j < wsm_der_obj->NumModifiers(); j++) { - Modifier * mod = wsm_der_obj->GetModifier(j); - if (mod->ClassID() == SKIN_MOD_CLASS_ID) { - - // This is our modifier! Get the data from it! - SkinModifierClass * skinmod = (SkinModifierClass *)mod; - ModContext * mc = wsm_der_obj->GetModContext(j); - *skin_data_ptr = (SkinDataClass *)(mc->localData); - *skin_obj_ptr = (SkinWSMObjectClass *)skinmod->GetReference(SkinModifierClass::OBJ_REF); - } - } - } - } -} - - -/*********************************************************************************************** - * MeshSaveClass::get_htree_bone_index_for_inode -- searches the htree for the given INode * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/1/2000 gth : Created. * - *=============================================================================================*/ -int MeshSaveClass::get_htree_bone_index_for_inode(INode * node) -{ - // index of this INode in the hierarchy tree (it better be there :-) - char w3dname[W3D_NAME_LEN]; - Set_W3D_Name(w3dname,node->GetName()); - int bindex = HTree->Find_Named_Node(w3dname); - - // If the desired bone isn't being exported, export the point - // relative to the root. - if (bindex == -1) { - bindex = 0; - } - - return bindex; -} - -/*********************************************************************************************** - * MeshSaveClass::inv_deform_mesh -- preprocess the mesh for skinning * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - * 5/1/2000 gth : Created. * - *=============================================================================================*/ -void MeshSaveClass::inv_deform_mesh() -{ - // Got the skinning info, now pre-deform each vertex and - // create an array of vertex influence indexes. - VertInfluences = new W3dVertInfStruct[Builder.Get_Vertex_Count()]; - memset(VertInfluences,0,sizeof(W3dVertInfStruct) * Builder.Get_Vertex_Count()); - Header.VertexChannels |= W3D_VERTEX_CHANNEL_BONEID; - - for (int vert_index = 0; vert_index < Builder.Get_Vertex_Count(); vert_index++) { - - MeshBuilderClass::VertClass & vert = Builder.Get_Vertex(vert_index); - - if (vert.BoneIndex == 0) { - - // set the influence to 0 (root node) and leave the vert and normal unchanged - // (gth) 07/11/2000: Note that in this case, the mesh coordinates have already been - // transformed relative to the user or scene origin and do not need to be further modified. - VertInfluences[vert_index].BoneIdx = 0; - - } else { - - // here we go! get the matrix from the hierarchy tree and transform - // the point into the bone's coordinate system. - // (gth) 07/11/2000: The origin_offset_tm is no longer needed because - // skin meshes are transformed into the origin coordinate system before - // we get to this code. - Matrix3 bonetm = HTree->Get_Node_Transform(vert.BoneIndex); - Matrix3 invbonetm = Inverse(bonetm); - Point3 pos; - - pos.x = vert.Position.X; - pos.y = vert.Position.Y; - pos.z = vert.Position.Z; - - pos = pos * invbonetm; - - vert.Position.X = pos.x; - vert.Position.Y = pos.y; - vert.Position.Z = pos.z; - - // Now, transform the normal into the bone's coordinate system. - invbonetm.NoTrans(); - Point3 norm; - - norm.x = vert.Normal.X; - norm.y = vert.Normal.Y; - norm.z = vert.Normal.Z; - - norm = norm * invbonetm; - - vert.Normal.X = norm.x; - vert.Normal.Y = norm.y; - vert.Normal.Z = norm.z; - - VertInfluences[vert_index].BoneIdx = vert.BoneIndex; - } - } -} - - -/*********************************************************************************************** - * MeshSaveClass::Write_To_File -- Append the mesh to an open wtm file * - * * - * INPUT: * - * csave - ChunkSaveClass object to handle writing the chunk-based file * - * export_aabtree - should we generate an aabtree for this mesh * - * * - * OUTPUT: * - * 0 if nothing went wrong, Non-Zero otherwise * - * * - * WARNINGS: * - * * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -int MeshSaveClass::Write_To_File(ChunkSaveClass & csave,bool export_aabtree) -{ - if (!csave.Begin_Chunk(W3D_CHUNK_MESH)) { - return 1; - } - - if (write_header(csave) != 0) { - return 1; - } - - if (write_user_text(csave) != 0) { - return 1; - } - - if (write_verts(csave) != 0) { - return 1; - } - - if (write_vert_normals(csave) != 0) { - return 1; - } - - if (write_triangles(csave) != 0) { - return 1; - } - - if (write_vert_influences(csave) != 0) { - return 1; - } - - if (write_vert_shade_indices(csave) != 0) { - return 1; - } - - if (write_material_info(csave) != 0) { - return 1; - } - - if (write_vertex_materials(csave) != 0) { - return 1; - } - - if (PS2Material == TRUE) { - - // The ps2 shaders must be written out first. - if (write_ps2_shaders(csave) != 0) { - return 1; - } - } - - if (write_shaders(csave) != 0) { - return 1; - } - - - if (write_textures(csave) != 0) { - return 1; - } - - for (int pass=0; pass 0); - assert(Builder.Get_Vertex_Count() == (int)Header.NumVertices); - - for (int i=0; i= Header.Min.X); - assert(vert.Position.Y >= Header.Min.Y); - assert(vert.Position.Z >= Header.Min.Z); - - } - - W3dVectorStruct w3dvert; - w3dvert.X = vert.Position.X; - w3dvert.Y = vert.Position.Y; - w3dvert.Z = vert.Position.Z; - - if (csave.Write(&(w3dvert),sizeof(W3dVectorStruct)) != sizeof(W3dVectorStruct)) { - return 1; - } - } - - if (!csave.End_Chunk()) { - return 1; - } - return 0; -} - - -/*********************************************************************************************** - * MeshSaveClass::write_vert_normals -- Writes the surrender normal chunk into a wtm file * - * * - * INPUT: * - * csave - chunk save object * - * * - * OUTPUT: * - * 0 if nothing went wrong, Non-Zero otherwise * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -int MeshSaveClass::write_vert_normals(ChunkSaveClass & csave) -{ - if (!(Header.VertexChannels & W3D_VERTEX_CHANNEL_NORMAL)) return 0; - - if (!csave.Begin_Chunk(W3D_CHUNK_VERTEX_NORMALS)) { - return 1; - } - - for (int i=0; i < Builder.Get_Vertex_Count(); i++) { - - const MeshBuilderClass::VertClass & vert = Builder.Get_Vertex(i); - - W3dVectorStruct norm; - - if (ExportOptions.Is_ZNormals_Enabled()) { - norm.X = 0.0f; - norm.Y = 0.0f; - norm.Z = 1.0f; - } else { - norm.X = vert.Normal.X; - norm.Y = vert.Normal.Y; - norm.Z = vert.Normal.Z; - } - - if (csave.Write(&(norm),sizeof(W3dVectorStruct)) != sizeof(W3dVectorStruct)) { - return 1; - } - } - - if (!csave.End_Chunk()) { - return 1; - } - - return 0; -} - -/*********************************************************************************************** - * MeshSaveClass::write_vert_influences -- skins will have this chunk that binds verts to bones* - * * - * INPUT: * - * csave - chunk save object * - * * - * OUTPUT: * - * 0 if nothing went wrong, Non-Zero otherwise * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -int MeshSaveClass::write_vert_influences(ChunkSaveClass & csave) -{ - if (((Header.Attributes & W3D_MESH_FLAG_GEOMETRY_TYPE_MASK) != W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN) || - !(Header.VertexChannels & W3D_VERTEX_CHANNEL_BONEID) || - (VertInfluences == NULL)) { - return 0; - } - - if (!csave.Begin_Chunk(W3D_CHUNK_VERTEX_INFLUENCES)) { - return 1; - } - - int count = Builder.Get_Vertex_Count(); - if (csave.Write(VertInfluences,count * sizeof(W3dVertInfStruct)) != count * sizeof(W3dVertInfStruct)) { - return 1; - } - - if (!csave.End_Chunk()) { - return 1; - } - - return 0; -} - - -/*********************************************************************************************** - * MeshSaveClass::write_triangles -- write the triangles chunk * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/7/98 GTH : Created. * - *=============================================================================================*/ -int MeshSaveClass::write_triangles(ChunkSaveClass & csave) -{ - if (!csave.Begin_Chunk(W3D_CHUNK_TRIANGLES)) { - return 1; - } - - assert(Builder.Get_Face_Count() == (int)Header.NumTris); - for (int i=0; i 0); - - if (PS2Material == TRUE) { - - // Make the PC shader as close to the PS2 shader as possible. - // This will allow for viewing in W3D View. - setup_PC_shaders_from_PS2_shaders(); - } - - if (!csave.Begin_Chunk(W3D_CHUNK_SHADERS)) { - return 1; - } - - W3dShaderStruct * shader; - - for (int i=0; iFilename,strlen(map->Filename) + 1) != strlen(map->Filename) + 1) return 1; - csave.End_Chunk(); - - // optionally write an animation info chunk - if (map->AnimInfo != NULL) { - csave.Begin_Chunk(W3D_CHUNK_TEXTURE_INFO); - if (csave.Write(map->AnimInfo,sizeof(W3dTextureInfoStruct)) != sizeof(W3dTextureInfoStruct)) return 1; - csave.End_Chunk(); - } - - csave.End_Chunk(); - } - - if (!csave.End_Chunk()) { - return 1; - } - return 0; -} - -int MeshSaveClass::write_pass(ChunkSaveClass & csave,int pass) -{ - assert(pass >= 0); - assert(pass < MaterialDesc.Pass_Count()); - - if (!csave.Begin_Chunk(W3D_CHUNK_MATERIAL_PASS)) { - return 1; - } - - const MeshBuilderClass::MeshStatsStruct & stats = Builder.Get_Mesh_Stats(); - - if (stats.HasVertexMaterial[pass]) { - write_vertex_material_ids(csave,pass); - } - - if (stats.HasShader[pass]) { - write_shader_ids(csave,pass); - } - - if (stats.HasDiffuseColor[pass] || DeformSave.Does_Deformer_Modify_DCG ()) { - write_dcg(csave,pass); - } - - for (int stage = 0; stage < MeshBuilderClass::MAX_STAGES; stage++) { - write_texture_stage(csave,pass,stage); - } - - if (!csave.End_Chunk()) { - return 1; - } - return 0; -} - -int MeshSaveClass::write_vertex_material_ids(ChunkSaveClass & csave,int pass) -{ - const MeshBuilderClass::MeshStatsStruct & stats = Builder.Get_Mesh_Stats(); - - if (!csave.Begin_Chunk(W3D_CHUNK_VERTEX_MATERIAL_IDS)) { - return 1; - } - - uint32 matid; - - if (stats.HasPerVertexMaterial[pass]) { - for (int i=0; i= MIN_AABTREE_POLYGONS) && - ((Header.Attributes & W3D_MESH_FLAG_GEOMETRY_TYPE_MASK) == W3D_MESH_FLAG_GEOMETRY_TYPE_NORMAL) - ) - { - - /* - ** Build temporary array representations of the mesh - */ - int vertcount = Builder.Get_Vertex_Count(); - int polycount = Builder.Get_Face_Count(); - Vector3 * verts = new Vector3[vertcount]; - Vector3i * polys = new Vector3i[polycount]; - - for (int vi=0; viNumSubMtls() <= 1)) { - - MaterialRemapTable = new int[1]; - MaterialRemapTable[0] = 0; - return 1; - - } else { - - int sub_mtl_count = nodemtl->NumSubMtls(); - MaterialRemapTable = new int[sub_mtl_count]; - - // Initialize each remap to -1 (indicates that the material is un-used) - for (mat_index=0; mat_index 0); - return matcount; - } -} - -//Check if material is solid, non-textured. -int isTexturedMaterial(Mtl * mtl) -{ - Texmap * tmap; - - tmap = mtl->GetSubTexmap(ID_DI); - if (mtl->ClassID() == GameMaterialClassID) - { - GameMtl * gamemtl=(GameMtl *)mtl; - - for (int pass=0;passGet_Pass_Count(); pass++) - { - for (int stage=0; stage < W3dMaterialClass::MAX_STAGES; stage++) - { if (gamemtl->Get_Texture_Enable(pass,stage) && gamemtl->Get_Texture(pass,stage)) - return 1; //using a texture - } - } - return 0; - } - else - { - return (tmap && tmap->ClassID() == Class_ID(BMTEX_CLASS_ID,0)); - } -} - -//count number of used solid materials (no texture) -int MeshSaveClass::getNumSolidMaterials(Mtl * nodemtl) -{ - int mat_index; - int numSolid=0; - - if ((nodemtl == NULL) || (nodemtl->NumSubMtls() <= 1)) - { //Check if diffuse texture present - if (isTexturedMaterial(nodemtl)) - return 00; - return 1; - } - else - { - int sub_mtl_count = nodemtl->NumSubMtls(); - - for (mat_index=0; mat_indexGetSubMtl(mat_index))) - continue; - numSolid++; - } - } - return numSolid; - } -} - -//Cancels out the material colors by setting them to white. -//Also changes prefix on texture names to use DIFFUSE_HOUSECOLOR_TEXTURE_PREFIX -//if house color is used. -void MeshSaveClass::fix_diffuse_materials(bool isHouseColor) -{ - uint8 color=255; - char materialColorFilename[_MAX_FNAME + 1]; - - for (int mat_index=0; mat_indexFilename && (*((unsigned int *)map3d->Filename) & 0xffff00ff) == DIFFUSE_COLOR_TEXTURE_MASK) //check for 'TXC^' prefix - { //found a material which had its material color replaced by a texture - //set the material color to white so it's not being used. - vmat->Diffuse.Set(color,color,color); - vmat->Ambient.Set(color,color,color); - - if (isHouseColor && *(map3d->Filename+1) != 'H') - { //our material texture contains house colors, adjust the name - //by adding H prefix. - sprintf(materialColorFilename,"%s%s","ZHCD",map3d->Filename+4); - map3d->Set_Filename(materialColorFilename); - } - } - } - } - } -} - -/*********************************************************************************************** - * MeshSaveClass::create_materials -- create the materials for this mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - * 2/8/99 GTH : modified to use the MaterialRemapTable * - *=============================================================================================*/ -void MeshSaveClass::create_materials(Mtl * nodemtl,DWORD wirecolor, char *materialColorTexture) -{ - bool domaps = !use_simple_rendering(Header.Attributes); - - ////////////////////////////////////////////////////////////////////// - // Create materials - // Four cases: - // - Creating a collision object: use a hard-coded material - // - The material is null: use wire color - // - The material is a simple material: create one material - // - The material is a multi-material: create n materials - ////////////////////////////////////////////////////////////////////// - int geo_type = Header.Attributes & W3D_MESH_FLAG_GEOMETRY_TYPE_MASK; - if ((geo_type == W3D_MESH_FLAG_GEOMETRY_TYPE_AABOX) || - (geo_type == W3D_MESH_FLAG_GEOMETRY_TYPE_OBBOX)) - { - Header.NumMaterials = 1; - - W3dVertexMaterialStruct vmat; - W3dShaderStruct shader; - W3dMaterialClass material; - - Color diffuse; - if (Header.Attributes & W3D_MESH_FLAG_COLLISION_TYPE_PHYSICAL) { - diffuse.r = 0.0f; - diffuse.g = 0.0f; - diffuse.b = 1.0f; - } else { - diffuse.r = 0.4f; - diffuse.g = 1.0f; - diffuse.b = 0.4f; - } - - W3d_Shader_Reset(&shader); - W3d_Shader_Set_Dest_Blend_Func(&shader,W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA); - W3d_Shader_Set_Src_Blend_Func(&shader,W3DSHADER_SRCBLENDFUNC_SRC_ALPHA); - - W3d_Vertex_Material_Reset(&vmat); - vmat.Opacity = 0.5f; - - // add material 0 - vmat.Diffuse.R = (uint8)(diffuse.r * 255.0f); - vmat.Diffuse.G = (uint8)(diffuse.g * 255.0f); - vmat.Diffuse.B = (uint8)(diffuse.b * 255.0f); - material.Set_Pass_Count(1); - material.Set_Vertex_Material(vmat,0); - material.Set_Shader(shader,0); - MaterialDesc.Add_Material(material); - - assert(MaterialDesc.Material_Count() == 1); - - } else if (!nodemtl) { - - // Create a single material using the wire color - Header.NumMaterials = 1; - - W3dVertexMaterialStruct vmat; - W3dShaderStruct shader; - W3dMaterialClass material; - - W3d_Vertex_Material_Reset(&vmat); - W3d_Shader_Reset(&shader); - - vmat.Diffuse.R = GetRValue(wirecolor); - vmat.Diffuse.G = GetGValue(wirecolor); - vmat.Diffuse.B = GetBValue(wirecolor); - - material.Set_Pass_Count(1); - material.Set_Vertex_Material(vmat,0); - material.Set_Shader(shader,0); - - MaterialDesc.Add_Material(material,"WireColor"); - assert(MaterialDesc.Material_Count() == 1); - - } else if (!nodemtl->IsMultiMtl()) { - - Header.NumMaterials = 1; - W3dMaterialClass mat; - - if (isTexturedMaterial(nodemtl) == 0) - mat.Init(nodemtl,materialColorTexture); - else - mat.Init(nodemtl,NULL); - - W3dMaterialDescClass::ErrorType err; - err = MaterialDesc.Add_Material(mat,nodemtl->GetName()); - if (err == W3dMaterialDescClass::MULTIPASS_TRANSPARENT) { - sprintf(_string1,"Exporting Materials for Mesh: %s\nMaterial %s is multi-pass and transparent\nMulti-pass transparent materials are not allowed.\n", - Header.MeshName, - nodemtl->GetName()); - ExportLog::printf(_string1); - throw ErrorClass(_string1); - } - assert(MaterialDesc.Material_Count() == 1); - - } else { - - Header.NumMaterials = nodemtl->NumSubMtls(); - W3dMaterialClass mat; - - for (unsigned mi = 0; mi < Header.NumMaterials; mi++) { - - // only process materials that were found to be used in the scan_used_materials call - if (MaterialRemapTable[mi] != -1) { - - if (isTexturedMaterial(nodemtl->GetSubMtl(mi)) == 0) - mat.Init(nodemtl->GetSubMtl(mi),materialColorTexture); - else - mat.Init(nodemtl->GetSubMtl(mi),NULL); - - char * name; - W3dMaterialDescClass::ErrorType err; - - name = nodemtl->GetSubMtl(mi)->GetName(); - err = MaterialDesc.Add_Material(mat,name); - - if (err == W3dMaterialDescClass::INCONSISTENT_PASSES) { - sprintf(_string1,"Exporting Materials for Mesh: %s\nMaterial %s has %d passes.\nThe other materials have %d passes.\nAll Materials must have the same number of passes.\n", - Header.MeshName, - nodemtl->GetSubMtl(mi)->GetName(), - mat.Get_Pass_Count(), - MaterialDesc.Pass_Count()); - ExportLog::printf(_string1); - throw ErrorClass(_string1); - } - if (err == W3dMaterialDescClass::MULTIPASS_TRANSPARENT) { - sprintf(_string1,"Exporting Materials for Mesh: %s\nMaterial %s is multi-pass and transparent\nMulti-pass transparent materials are not allowed.\n", - Header.MeshName, - nodemtl->GetSubMtl(mi)->GetName()); - throw ErrorClass(_string1); - } - if (err == W3dMaterialDescClass::INCONSISTENT_SORT_LEVEL) { - sprintf(_string1,"Exporting Materials for Mesh: %s\nMaterial %s does not have the same Static Sort Level as other materials used on the mesh.\nAll materials for a mesh must use the same Static Sort Level value.\n", - Header.MeshName, - nodemtl->GetSubMtl(mi)->GetName()); - ExportLog::printf(_string1); - throw ErrorClass(_string1); - } - } - } - } - - // Store the material's sort level in the mesh header. - Header.SortLevel = MaterialDesc.Get_Sort_Level(); -} - -/*********************************************************************************************** - * MeshSaveClass::compute_bounding_volumes -- computes a bounding box and bounding sphere for * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/01/1997 GH : Created. * - *=============================================================================================*/ -void MeshSaveClass::compute_bounding_volumes(void) -{ - Vector3 min,max,center; - float radius; - - Builder.Compute_Bounding_Box(&min,&max); - Builder.Compute_Bounding_Sphere(¢er,&radius); - - Header.SphCenter.X = center.X; - Header.SphCenter.Y = center.Y; - Header.SphCenter.Z = center.Z; - Header.SphRadius = radius; - - Header.Min.X = min.X; - Header.Min.Y = min.Y; - Header.Min.Z = min.Z; - Header.Max.X = max.X; - Header.Max.Y = max.Y; - Header.Max.Z = max.Z; -} - - -/*********************************************************************************************** - * MeshSaveClass::compute_physical_properties -- computes the volume and moment of inertia * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/01/1997 GH : Created. * - *=============================================================================================*/ -void MeshSaveClass::compute_physical_constants -( - INode * inode, - Progress_Meter_Class & meter, - bool voxelize -) -{ - -#if 0 // IF we need this again, move the data to a physics chunk (header doesn't have it anymore) - - if (voxelize) { - - // Create an INodeList object for this mesh - AnyINodeFilter nodefilt; - INodeListClass meshlist(CurTime,&nodefilt); - meshlist.Insert(inode); - - // Create a Voxel object for this mesh - VoxelClass * voxel = new VoxelClass - ( - meshlist, - VOXEL_RESOLUTION, - ExportSpace, - CurTime, - meter - ); - -#if DEBUG_VOXELS - VoxelDebugWindowClass dbgwin(voxel); - dbgwin.Display_Window(); -#endif - - double vol[1]; - double cm[3]; - double inertia[9]; - - voxel->Compute_Physical_Properties(vol,cm,inertia); - - Header.Volume = (float)vol[0]; - - Header.MassCenter.X = (float)cm[0]; - Header.MassCenter.Y = (float)cm[1]; - Header.MassCenter.Z = (float)cm[2]; - - Header.Inertia[0] = (float)inertia[0]; - Header.Inertia[1] = (float)inertia[1]; - Header.Inertia[2] = (float)inertia[2]; - Header.Inertia[3] = (float)inertia[3]; - Header.Inertia[4] = (float)inertia[4]; - Header.Inertia[5] = (float)inertia[5]; - Header.Inertia[6] = (float)inertia[6]; - Header.Inertia[7] = (float)inertia[7]; - Header.Inertia[8] = (float)inertia[8]; - - } else { - - // Set mass center to the center of the bounding box - Header.MassCenter.X = (Header.Max.X + Header.Min.X) / 2.0f; - Header.MassCenter.Y = (Header.Max.Y + Header.Min.Y) / 2.0f; - Header.MassCenter.Z = (Header.Max.Z + Header.Min.Z) / 2.0f; - - // Set inertia tensor to inertia tensor of the bounding box - // (gth) !!!! DO THIS !!!! - Header.Inertia[0] = 1.0f; - Header.Inertia[1] = 0.0f; - Header.Inertia[2] = 0.0f; - Header.Inertia[3] = 0.0f; - Header.Inertia[4] = 1.0f; - Header.Inertia[5] = 0.0f; - Header.Inertia[6] = 0.0f; - Header.Inertia[7] = 0.0f; - Header.Inertia[8] = 1.0f; - - Header.Volume = (Header.Max.X - Header.Min.X) * (Header.Max.Y - Header.Min.Y) * (Header.Max.Z - Header.Min.Z); - } - -#endif -} - - -/*********************************************************************************************** - * MeshSaveClass::prep_mesh -- pre-transform the MAX mesh by a specified matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/01/1997 GH : Created. * - *=============================================================================================*/ -void MeshSaveClass::prep_mesh(Mesh & mesh,Matrix3 & objoff) -{ - int vert_index; - - // Transform the mesh's vertices so that they are relative to the coordinate - // system that we want to use with the mesh - for (vert_index = 0; vert_index < mesh.getNumVerts (); vert_index++) { - mesh.verts[vert_index] = mesh.verts[vert_index] * objoff; - } - - // Re-Build the normals. - mesh.buildNormals(); -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/meshsave.h b/Generals/Code/Tools/WW3D/max2w3d/meshsave.h deleted file mode 100644 index 48c9b6681d..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/meshsave.h +++ /dev/null @@ -1,226 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/meshsave.h 44 10/30/00 1:12p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : MESHSAVE.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/10/97 * - * * - * Last Update : June 10, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MESHSAVE_H -#define MESHSAVE_H - -#include "rawfile.h" // have to include this before Max.h -#include -#include "BITTYPE.H" -#include "w3d_file.h" -#include "chunkio.h" -#include "PROGRESS.H" -#include "nodelist.h" -#include "util.h" -#include "w3dmtl.h" -#include "meshbuild.h" -#include "MeshDeformSave.h" -#include "w3dappdata.h" - -class HierarchySaveClass; -class MeshConnectionsClass; -class MeshSaveClass; -class SkinDataClass; - - -/******************************************************************************************* -** -** VertStruct -** -*******************************************************************************************/ -struct VertStruct -{ - Point3 Vertex; - Point3 Normal; - Point2 TexCoord; - Color Color; - - uint32 MaxVertIdx; // index of the MAX vertex that this vert came from - uint32 MaxFaceIdx; // index of the MAX face that this vert came from - VertStruct * Next; // used by the hash table... -}; - -/******************************************************************************************* -** -** FaceStruct -** -*******************************************************************************************/ -struct FaceStruct -{ - uint32 MaxVidx[3]; // original 3ds-MAX vertex index (for smoothing computations) - uint32 OurVidx[3]; // vertex, vertex normal, and texture coord indices - uint32 MaterialIdx; // material index - uint32 SmGroup; // smoothing group (not really needed, normals pre-calced) - Point3 Normal; // Face normal - float32 Dist; // Plane distance - uint32 Attributes; // collision flags, sort method, etc -}; - -/******************************************************************************************* -** -** MeshSaveClass - this is the big one, create meshes and skins from a MAX mesh. -** -*******************************************************************************************/ -class MeshSaveClass -{ -public: - - enum { - EX_UNKNOWN = 0, // exception error codes - EX_CANCEL = 1 - }; - - MeshSaveClass( - char * mesh_name, - char * container_name, - INode * inode, - const Mesh * input_mesh, - Matrix3 & exportspace, - W3DAppData2Struct & exportoptions, - HierarchySaveClass * htree, - TimeValue curtime, - Progress_Meter_Class & meter, - unsigned int * materialColors, - int &numMaterialColors, - int &numHouseColors, - char * materialColorTexture, - WorldInfoClass * world_info = NULL - ); - - ~MeshSaveClass(void); - - int Write_To_File(ChunkSaveClass & csave,bool export_aabtrees = false); - -private: - - INode * MaxINode; - W3DAppData2Struct & ExportOptions; - - W3dMeshHeader3Struct Header; - W3dMaterialDescClass MaterialDesc; - MeshBuilderClass Builder; - MeshDeformSaveClass DeformSave; - TimeValue CurTime; - Matrix3 ExportSpace; - Matrix3 MeshToExportSpace; - Matrix3 PivotSpace; - HierarchySaveClass * HTree; - char * UserText; - bool MeshInverted; // this flag indicates that the transform is inverting this mesh - W3dVertInfStruct * VertInfluences; - - int * MaterialRemapTable; // reindexes mtl_idx after un-used mtls are removed - - // Flag set if the mesh uses a PS2 material. - int PS2Material; - -private: - - // Use a MeshBuilderClass to process the mesh - void Build_Mesh(Mesh & mesh, Mtl *node_mtl, unsigned int *materialColors, int &numMaterialColors, int &numHouseColors); - - // compute properties for the mesh - void compute_bounding_volumes(void); - void compute_physical_constants(INode * inode,Progress_Meter_Class & meter,bool voxelize); - - // create the materials - int scan_used_materials(Mesh & mesh, Mtl * nodemtl); - void create_materials(Mtl * nodemtl,DWORD wirecolor, char *materialColorTexture); - void fix_diffuse_materials(bool isHouseColor); - - // count number of used solid materials (no texture) - int getNumSolidMaterials(Mtl * nodemtl); - - // creating damage stages - void add_damage_stage(MeshSaveClass * damage_mesh); - - // methods used in building the wtm file - int write_header(ChunkSaveClass & csave); - int write_user_text(ChunkSaveClass & csave); - - int write_verts(ChunkSaveClass & csave); - int write_vert_normals(ChunkSaveClass & csave); - int write_vert_influences(ChunkSaveClass & csave); - int write_vert_shade_indices(ChunkSaveClass & csave); - - int write_triangles(ChunkSaveClass & csave); - - int write_material_info(ChunkSaveClass & csave); - int write_shaders(ChunkSaveClass & csave); - int write_vertex_materials(ChunkSaveClass & csave); - int write_textures(ChunkSaveClass & csave); - - int write_pass(ChunkSaveClass & csave,int pass); - int write_vertex_material_ids(ChunkSaveClass & csave,int pass); - int write_shader_ids(ChunkSaveClass & csave,int pass); - int write_dcg(ChunkSaveClass & csave,int pass); - - int write_texture_stage(ChunkSaveClass & csave,int pass,int stage); - int write_texture_ids(ChunkSaveClass & csave,int pass,int stage); - int write_texture_coords(ChunkSaveClass & csave,int pass,int stage); - - int write_aabtree(ChunkSaveClass & csave); - - // transforms mesh so that it uses the desired coordinate system - void prep_mesh(Mesh & mesh,Matrix3 & objoff); - - // inverse deform the mesh so that its ready to be used as a skin! - void get_skin_modifier_objects(SkinDataClass ** skin_data_ptr,SkinWSMObjectClass ** skin_obj_ptr); - int get_htree_bone_index_for_inode(INode * node); - void inv_deform_mesh(void); - - // get rendering settings for the materials - void customize_materials(void); - - // Write the ps2 shaders and approximate them as close as possible in the W3D shaders. - int write_ps2_shaders(ChunkSaveClass & csave); - - // Make the PC shader emulate the PS2 shader. - void setup_PC_shaders_from_PS2_shaders(); - - friend class DamageClass; -}; - - - - - -#endif /*MESHSAVE_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/motion.cpp b/Generals/Code/Tools/WW3D/max2w3d/motion.cpp deleted file mode 100644 index f2c883ba05..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/motion.cpp +++ /dev/null @@ -1,1027 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/motion.cpp 26 10/30/00 6:56p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/motion.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 5:25p $* - * * - * $Revision:: 26 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * MotionClass::MotionClass -- constructor * - * MotionClass::MotionClass -- constructor * - * MotionClass::init -- initialize * - * MotionClass::~MotionClass -- destructor * - * MotionClass::compute_frame_motion -- compute the motion for a specified frame * - * MotionClass::set_motion_matrix -- save a motin matrix * - * MotionClass::get_motion_matrix -- retrieve a motion matrix * - * MotionClass::set_eulers -- store euler angles * - * MotionClass::get_eulers -- retrieve euler angles * - * MotionClass::Save -- save the motion to a W3D file * - * MotionClass::save_header -- save the header * - * MotionClass::save_channels -- save the motion channels * - * MotionClass::set_visibility -- store a visibility bit * - * MotionClass::get_visibility -- retrieve the visibility bit for this node:frame * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "motion.h" -#include "w3d_file.h" -#include "vchannel.h" -#include "bchannel.h" -#include "EULER.H" -#include "util.h" -#include "errclass.h" -#include "w3dutil.h" -#include "exportlog.h" - - - -/*********************************************************************************************** - * MotionClass::MotionClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -MotionClass::MotionClass -( - IScene * scene, - INode * rootnode, - HierarchySaveClass * basepose, - W3dExportOptionsStruct & options, - int framerate, - Progress_Meter_Class * meter, - HWND MaxHwnd, - char * name, - Matrix3 & offset -): - BasePose(basepose), - Scene(scene), - RootNode(rootnode), - RootList(NULL), - StartFrame(options.StartFrame), - EndFrame(options.EndFrame), - ReduceAnimation(options.ReduceAnimation), - ReduceAnimationPercent(options.ReduceAnimationPercent), - CompressAnimation(options.CompressAnimation), - CompressAnimationFlavor(options.CompressAnimationFlavor), - CompressAnimationTranslationError(options.CompressAnimationTranslationError), - CompressAnimationRotationError(options.CompressAnimationRotationError), - FrameRate(framerate), - Meter(meter), - Offset(offset) -{ - - ExportLog::printf("Initializing Capture....\n"); - - init(); - - Set_W3D_Name(Name,name); -} - -/*********************************************************************************************** - * MotionClass::MotionClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -MotionClass::MotionClass -( - IScene * scene, - INodeListClass * rootlist, - HierarchySaveClass * basepose, - W3dExportOptionsStruct & options, - int framerate, - Progress_Meter_Class * meter, - HWND MaxHwnd, - char * name, - Matrix3 & offset -): - BasePose(basepose), - Scene(scene), - RootNode(NULL), - RootList(rootlist), - StartFrame(options.StartFrame), - EndFrame(options.EndFrame), - ReduceAnimation(options.ReduceAnimation), - ReduceAnimationPercent(options.ReduceAnimationPercent), - CompressAnimation(options.CompressAnimation), - CompressAnimationFlavor(options.CompressAnimationFlavor), - CompressAnimationTranslationError(options.CompressAnimationTranslationError), - CompressAnimationRotationError(options.CompressAnimationRotationError), - FrameRate(framerate), - Meter(meter), - Offset(offset) -{ - - ExportLog::printf("Initializing Capture....\n"); - - init(); - - Set_W3D_Name(Name,name); -} - -/*********************************************************************************************** - * MotionClass::init -- initialize * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void MotionClass::init(void) -{ - int i,j; - - NumFrames = (EndFrame - StartFrame + 1); - - ExportLog::printf("Extracting %d frames of animation from Max\n", NumFrames); - ExportLog::printf("\n"); - - /* - ** Allocate space for a matrix per frame per node - ** and an XYZEulers per frame per node. - */ - MotionMatrix = new Matrix3 * [BasePose->Num_Nodes()]; - if (MotionMatrix == NULL) { - throw (ErrorClass("Out of Memory")); - } - - EulerDelta = new Point3 * [BasePose->Num_Nodes()]; - if (EulerDelta == NULL) { - throw (ErrorClass("Out of Memory")); - } - - for (i=0; iNum_Nodes(); i++) { - MotionMatrix[i] = new Matrix3[NumFrames]; - if (MotionMatrix[i] == NULL) { - throw (ErrorClass("Out of Memory")); - } - - /* - ** Initialize all of the matrices to identity. - */ - for (j=0; jNum_Nodes(); i++) { - EulerDelta[i] = new Point3[NumFrames]; - if (EulerDelta[i] == NULL) { - throw (ErrorClass("Out of Memory")); - } - - /* - ** Initialize all of the Euler angles to 0,0,0 - */ - for (j=0; jNum_Nodes()]; - - for (i=0; iNum_Nodes(); i++) { - VisData[i].Resize(NumFrames); - - /* - ** initialize to always visible - */ - for (j=0; jNum_Nodes()]; - - for (i=0; iNum_Nodes(); i++) { - BinMoveData[i].Resize(NumFrames); - - /* - ** initialize to always interpolate - */ - for (j=0; jNum_Nodes()); - - for (i=0; iNum_Nodes(); i++) { - NodeValidFlags[i] = 0; - } - - /* - ** Compute motion data for each frame - */ - for (i=0; i < NumFrames; i++) { - ExportLog::rprintf("( %d ) ", i); - ExportLog::updatebar(i, NumFrames); - compute_frame_motion(i); - } - - ExportLog::updatebar(1, 1); // 100% - ExportLog::rprintf("Extraction Complete.\n"); -} - - - -/*********************************************************************************************** - * MotionClass::~MotionClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -MotionClass::~MotionClass(void) -{ - int i; - - for (i=0; iNum_Nodes(); i++) { - if (MotionMatrix[i]) delete[] MotionMatrix[i]; - } - if (MotionMatrix) { - delete[] MotionMatrix; - } - - for (i=0; iNum_Nodes(); i++) { - if (EulerDelta[i]) delete[] EulerDelta[i]; - } - if (EulerDelta) { - delete[] EulerDelta; - } - - if (VisData) { - delete[] VisData; - } - - if (BinMoveData) { - delete[] BinMoveData; - } - - ExportLog::printf("Destroy Log..%d,%d,%d,%d, %s..\n",1,2,3,4,"go"); - -} - - -/*********************************************************************************************** - * MotionClass::compute_frame_motion -- compute the motion for a specified frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void MotionClass::compute_frame_motion(int frame) -{ - /* - ** Compute MAX's time value for this frame - ** NOTE: the frame index passed in is the offset from StartFrame - ** to get the original MAX frame number, we add StartFrame. - */ - TimeValue frametime = (StartFrame + frame) * GetTicksPerFrame(); - - /* - ** Create a hierarchy tree object for the scene at this frame - */ - HierarchySaveClass * tree; - - if (RootNode != NULL) { - tree = new HierarchySaveClass(RootNode,frametime,*Meter,"NoName",false,BasePose); - } else { - tree = new HierarchySaveClass(RootList,frametime,*Meter,"NoName",false,BasePose,Offset); - } - - if (tree == NULL) { - throw (ErrorClass("Out of memory!")); - } - - /* - ** Loop over each node in this frame's tree - */ - for (int tindex=0; tindexNum_Nodes(); tindex++) { - - /* - ** Find the node in the Base Pose corresponding to this node. - ** If this node is not in the base pose, skip - */ - int bindex = BasePose->Find_Named_Node(tree->Get_Node_Name(tindex)); - - if (bindex != -1) { - - /* - ** Get the relative transform from the base and from - ** this frame's tree. Assume that both have already been "fixed"; - ** obviously the base pose has... However, the current tree - ** needs to be built by passing the basepose in as the "fixup tree" - ** - ** What are the "fixup" matrices? These are the transforms which - ** were applied to the base pose when the user wanted to force the - ** base pose to use only matrices with certain properties. For - ** example, if we wanted the base pose to use translations only, - ** the fixup transform for each node is a transform which when - ** multiplied by the real node's world transform, yeilds a pure - ** translation matrix. Fixup matrices also show up in the mesh - ** exporter since all vertices must be transformed by their inverses - ** in order to make things work... - */ - Matrix3 basetm = BasePose->Get_Node_Relative_Transform(bindex); - Matrix3 thistm = tree->Get_Node_Relative_Transform(tindex); - INode *tree_node = tree->Get_Node(tindex); - - Matrix3 motion = thistm * Inverse(basetm); - - motion = Cleanup_Orthogonal_Matrix(motion); - - set_motion_matrix(bindex,frame,motion); - - /* - ** Also, store the Euler angles for this node - */ - EulerAnglesClass my_eulers(motion,EulerOrderXYZr); - float ex = my_eulers.Get_Angle(0); - float ey = my_eulers.Get_Angle(1); - float ez = my_eulers.Get_Angle(2); - - set_eulers(bindex,frame,ex,ey,ez); - - /* - ** Store the visibility bit for this node - */ - INode * node = tree->Get_Node(tindex); - bool vis; - if (node) { - vis = (node->GetVisibility(frametime) > 0.0f); - } else { - vis = 1; - } - set_visibility(bindex,frame,vis); - - // - // Store out binary move or not - // - bool binary_move = false; - - if ((node)&&(vis)) { - - if (frame != 0) { - // sample previous frame, and an inbetween time - // to determine if there's a binary movement - - TimeValue frametime_prev = frametime - GetTicksPerFrame(); - TimeValue frametime_mid = (frametime + frametime_prev) / 2; - - // if data at frametime_prev == data at frametime_mid and != data at frametime - // then we have a binary movement! - - Control *c; - - c = node->GetTMController()->GetPositionController(); - - if (c) { - - Interval iValid; - - Matrix3 smat1; // sample matrix 1 - Matrix3 smat2; // sample matrix 2 - Matrix3 smat3; // sample matrix 3 - - iValid = FOREVER; - smat1 = node->GetParentTM(frametime_prev); - c->GetValue(frametime_prev, &smat1, iValid, CTRL_RELATIVE); - - iValid = FOREVER; - smat2 = node->GetParentTM(frametime_mid); - c->GetValue(frametime_mid, &smat2, iValid, CTRL_RELATIVE); - - iValid = FOREVER; - smat3 = node->GetParentTM(frametime); - c->GetValue(frametime, &smat3, iValid, CTRL_RELATIVE); - - if ((smat1 == smat2) && (!(smat2 == smat3))) { - binary_move = true; - DebugPrint(_T("Binary Move on Translation\n")); - } - - if (false == binary_move) { - c = node->GetTMController()->GetRotationController(); - - if (c) { - - iValid = FOREVER; - smat1 = node->GetParentTM(frametime_prev); - c->GetValue(frametime_prev, &smat1, iValid, CTRL_RELATIVE); - - iValid = FOREVER; - smat2 = node->GetParentTM(frametime_mid); - c->GetValue(frametime_mid, &smat2, iValid, CTRL_RELATIVE); - - iValid = FOREVER; - smat3 = node->GetParentTM(frametime); - c->GetValue(frametime, &smat3, iValid, CTRL_RELATIVE); - - if ((smat1 == smat2) && (!(smat2 == smat3))) { - binary_move = true; - DebugPrint(_T("Binary Move on Rotation\n")); - } - } - } - } - } - } - - - set_binary_movement(bindex, frame, binary_move); - - } // if(bindex!=-1) - } - - /* - ** release allocated memory - */ - delete tree; -} - - -/*********************************************************************************************** - * MotionClass::set_motion_matrix -- store a motion matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void MotionClass::set_motion_matrix(int node,int frame,const Matrix3 & motion) -{ - assert(node >= 0); - assert(frame >= 0); - assert(node < BasePose->Num_Nodes()); - assert(frame < NumFrames); - - MotionMatrix[node][frame] = motion; - NodeValidFlags[node] = 1; -} - - -/*********************************************************************************************** - * MotionClass::get_motion_matrix -- retrieve a motion matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 MotionClass::get_motion_matrix(int node,int frame) -{ - assert(node >= 0); - assert(frame >= 0); - assert(node < BasePose->Num_Nodes()); - assert(frame < NumFrames); - - return MotionMatrix[node][frame]; -} - - -/*********************************************************************************************** - * MotionClass::set_eulers -- store euler angles * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void MotionClass::set_eulers(int node,int frame, float x, float y, float z) -{ - /* - ** if we're past the first frame, massage the euler angles to the - ** representation closest to the previous frame. - */ - if (frame > 0) { - - /* - ** First, compute equivalent euler angles - */ - double x2 = PI + x; - double y2 = PI - y; - double z2 = PI + z; - - if (x2 > PI) { - x2 = x2 - 2*PI; - } - - if (y2 > PI) { - y2 = y2 - 2*PI; - } - - if (z2 > PI) { - z2 = z2 - 2*PI; - } - - /* - ** load up the previous frame eulers - */ - double px,py,pz; - px = get_eulers(node,frame - 1)[0]; - py = get_eulers(node,frame - 1)[1]; - pz = get_eulers(node,frame - 1)[2]; - - // now, pick between the two - double mag0 = (x - px) * (x - px) + (y - py) * (y - py) + (z - pz) * (z - pz); - double mag1 = (x2 - px) * (x2 - px) + (y2 - py) * (y2 - py) + (z2 - pz) * (z2 - pz); - - if (mag1 < mag0) { - x = x2; - y = y2; - z = z2; - } - } - - EulerDelta[node][frame].x = x; - EulerDelta[node][frame].y = y; - EulerDelta[node][frame].z = z; - NodeValidFlags[node] = 1; -} - - -/*********************************************************************************************** - * MotionClass::get_eulers -- retrieve euler angles * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Point3 MotionClass::get_eulers(int node,int frame) -{ - return Point3( - EulerDelta[node][frame].x, - EulerDelta[node][frame].y, - EulerDelta[node][frame].z - ); -} - - -/*********************************************************************************************** - * MotionClass::set_visibility -- store a visibility bit * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/15/98 GTH : Created. * - *=============================================================================================*/ -void MotionClass::set_visibility(int node,int frame,bool visible) -{ - VisData[node][frame] = visible; - NodeValidFlags[node] = 1; -} - - -/*********************************************************************************************** - * MotionClass::get_visibility -- retrieve the visibility bit for this node:frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/15/98 GTH : Created. * - *=============================================================================================*/ -bool MotionClass::get_visibility(int node,int frame) -{ - return VisData[node][frame]; -} - - -/*********************************************************************************************** - * MotionClass::set_binary_movement -- store a binary movement bit * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/15/98 GTH : Created. * - *=============================================================================================*/ -void MotionClass::set_binary_movement(int node,int frame,bool visible) -{ - BinMoveData[node][frame] = visible; - //NodeValidFlags[node] = 1; -} - - -/*********************************************************************************************** - * MotionClass::get_visibility -- retrieve the movement bit for this node:frame * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/15/98 GTH : Created. * - *=============================================================================================*/ -bool MotionClass::get_binary_movement(int node,int frame) -{ - return BinMoveData[node][frame]; -} - - - -/*********************************************************************************************** - * MotionClass::Save -- save the motion to a W3D file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool MotionClass::Save(ChunkSaveClass & csave) -{ - uint32 chunk_anim_type = W3D_CHUNK_ANIMATION; - - ExportLog::printf("\nBegin Save Motion Data\n"); - - if (CompressAnimation) { - chunk_anim_type = W3D_CHUNK_COMPRESSED_ANIMATION; - } - - if (!csave.Begin_Chunk( chunk_anim_type )) { - return false; - } - - if (!save_header(csave)) { - return false; - } - - if (!save_channels(csave)) { - return false; - } - - if (!csave.End_Chunk()) { - return false; - } - - return true; -} - - -/*********************************************************************************************** - * MotionClass::save_header -- save the header * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool MotionClass::save_header(ChunkSaveClass & csave) -{ - - ExportLog::printf("Save Header Type: "); - - if (CompressAnimation) { - // New Compressed Style - if (!csave.Begin_Chunk(W3D_CHUNK_COMPRESSED_ANIMATION_HEADER)) { - return false; - } - - W3dCompressedAnimHeaderStruct aheader; - aheader.Version = W3D_CURRENT_COMPRESSED_HANIM_VERSION; - Set_W3D_Name(aheader.Name,Name); - Set_W3D_Name(aheader.HierarchyName,BasePose->Get_Name()); - aheader.NumFrames = NumFrames; - aheader.FrameRate = FrameRate; - aheader.Flavor = CompressAnimationFlavor; // for future expansion - - switch (CompressAnimationFlavor) { - - case ANIM_FLAVOR_TIMECODED: - ExportLog::printf("TimeCoded\n"); - break; - case ANIM_FLAVOR_ADAPTIVE_DELTA: - ExportLog::printf("Adaptive Delta\n"); - break; - default: - ExportLog::printf("UNKNOWN\n"); - break; - } - - if (csave.Write(&aheader,sizeof(aheader)) != sizeof(aheader)) { - return false; - } - - if (!csave.End_Chunk()) { - return false; - } - } - else { - - ExportLog::printf("Non-Compressed.\n"); - - // Classic Non-Compressed Style - if (!csave.Begin_Chunk(W3D_CHUNK_ANIMATION_HEADER)) { - return false; - } - - W3dAnimHeaderStruct aheader; - aheader.Version = W3D_CURRENT_HANIM_VERSION; - Set_W3D_Name(aheader.Name,Name); - Set_W3D_Name(aheader.HierarchyName,BasePose->Get_Name()); - aheader.NumFrames = NumFrames; - aheader.FrameRate = FrameRate; - - if (csave.Write(&aheader,sizeof(aheader)) != sizeof(aheader)) { - return false; - } - - if (!csave.End_Chunk()) { - return false; - } - } - - - return true; -} - -/*********************************************************************************************** - * MotionClass::save_channels -- save the motion channels * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool MotionClass::save_channels(ChunkSaveClass & csave) -{ - - int NumNodes = BasePose->Num_Nodes(); - - ExportLog::printf("\nSaving Channel Data for %d Nodes\n", NumNodes); - - for (int nodeidx = 0; nodeidx < BasePose->Num_Nodes(); nodeidx++) { - - ExportLog::printf("\nnode: %d ", nodeidx); - - /* - ** Just ignore this node if it didn't appear in the max scene. - */ - if (NodeValidFlags[nodeidx]) { - - float identity[] = { 0.0f,0.0f,0.0f,1.0f }; - - VectorChannelClass xchan (nodeidx, NumFrames, ANIM_CHANNEL_X, 1, identity); - VectorChannelClass ychan (nodeidx, NumFrames, ANIM_CHANNEL_Y, 1, identity); - VectorChannelClass zchan (nodeidx, NumFrames, ANIM_CHANNEL_Z, 1, identity); - VectorChannelClass xrchan(nodeidx, NumFrames, ANIM_CHANNEL_XR, 1, identity); - VectorChannelClass yrchan(nodeidx, NumFrames, ANIM_CHANNEL_YR, 1, identity); - VectorChannelClass zrchan(nodeidx, NumFrames, ANIM_CHANNEL_ZR, 1, identity); - VectorChannelClass qchan (nodeidx, NumFrames, ANIM_CHANNEL_Q, 4, identity); - - xchan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - ychan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - zchan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - xrchan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - yrchan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - zrchan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - qchan.SetSaveOptions(CompressAnimation, CompressAnimationFlavor, CompressAnimationTranslationError, CompressAnimationRotationError, ReduceAnimation, ReduceAnimationPercent); - - BitChannelClass vischan(nodeidx, NumFrames, BIT_CHANNEL_VIS, 1); - vischan.Set_Bits(VisData[nodeidx]); - - BitChannelClass binmovechan(nodeidx, NumFrames, 0, 0); - binmovechan.Set_Bits(BinMoveData[nodeidx]); - - for (int frameidx = 0; frameidx < NumFrames; frameidx++) { - - float vec[4]; - Matrix3 tm = get_motion_matrix(nodeidx,frameidx); - Point3 eulers = get_eulers(nodeidx,frameidx); - - - Point3 old_tran = tm.GetTrans(); - Quat old_rot(tm); - - Point3 tran; - Point3 scale; - Quat rot; - - DecomposeMatrix(tm,tran,rot,scale); - - /* - ** fixup the quaternion - max's quaternions are different than mine(?) - */ - rot[0] = -rot[0]; - rot[1] = -rot[1]; - rot[2] = -rot[2]; - rot[3] = rot[3]; - - /* - ** Build the x translation channel - */ - vec[0] = tran.x; - xchan.Set_Vector(frameidx,vec); - - /* - ** Build the y translation channel - */ - vec[0] = tran.y; - ychan.Set_Vector(frameidx,vec); - - /* - ** Build the z translation channel - */ - vec[0] = tran.z; - zchan.Set_Vector(frameidx,vec); - - /* - ** Build the x rotation channel - */ - vec[0] = eulers.x; - xrchan.Set_Vector(frameidx,vec); - - /* - ** Build the y rotation channel - */ - vec[0] = eulers.y; - yrchan.Set_Vector(frameidx,vec); - - /* - ** Build the z rotation channel - */ - vec[0] = eulers.z; - zrchan.Set_Vector(frameidx,vec); - - /* - ** Build the quaternion rotation channel - */ - vec[0] = rot[0]; - vec[1] = rot[1]; - vec[2] = rot[2]; - vec[3] = rot[3]; - - qchan.Set_Vector(frameidx,vec); - - /* - ** build the visibility channel - */ - vischan.Set_Bit(frameidx,get_visibility(nodeidx,frameidx)); - // - // build binarymovement channel - // - binmovechan.Set_Bit(frameidx, get_binary_movement(nodeidx, frameidx)); - } - - // If objects arn't visible, then the channel data may as well be empty - - if (!vischan.Is_Empty()) { - - if (!xchan.Is_Empty()) xchan.ClearInvisibleData(&vischan); - if (!ychan.Is_Empty()) ychan.ClearInvisibleData(&vischan); - if (!zchan.Is_Empty()) zchan.ClearInvisibleData(&vischan); - if (!qchan.Is_Empty()) qchan.ClearInvisibleData(&vischan); - - } - - if (!xchan.Is_Empty()) { - ExportLog::printf("x"); - xchan.Save(csave, &binmovechan ); - } - if (!ychan.Is_Empty()) { - ExportLog::printf("y"); - ychan.Save(csave, &binmovechan ); - } - if (!zchan.Is_Empty()) { - ExportLog::printf("z"); - zchan.Save(csave, &binmovechan ); - } - - - // (gth) not saving Euler angles any more since we don't use them -// if (!xrchan.Is_Empty()) xrchan.Save(csave); -// if (!yrchan.Is_Empty()) yrchan.Save(csave); -// if (!zrchan.Is_Empty()) zrchan.Save(csave); - - if (!qchan.Is_Empty()) { - ExportLog::printf("q"); - qchan.Save(csave, &binmovechan); - } - - if (!vischan.Is_Empty()) { - ExportLog::printf("v"); - vischan.Save(csave, CompressAnimation); - } - } - - ExportLog::updatebar(nodeidx ,NumNodes); - - } - - ExportLog::updatebar(1,1); - - ExportLog::printf("\n\nSave Channel Data Complete.\n"); - - return true; -} - -// EOF - motion.cpp - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/motion.h b/Generals/Code/Tools/WW3D/max2w3d/motion.h deleted file mode 100644 index 1caade3ffe..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/motion.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/motion.h 13 10/30/00 6:56p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/motion.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 5:25p $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef MOTION_H -#define MOTION_H - - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#include - -#ifndef HIERSAVE_H -#include "hiersave.h" -#endif - -#ifndef PROGRESS_H -#include "PROGRESS.H" -#endif - -#ifndef CHUNKIO_H -#include "chunkio.h" -#endif - -#ifndef VECTOR_H -#include "Vector.H" -#endif - -#ifndef LOGDLG_H -#include "logdlg.h" -#endif - -struct W3dExportOptionsStruct; - - -class MotionClass -{ -public: - - MotionClass ( - IScene * scene, - INode * rootnode, - HierarchySaveClass * basepose, - W3dExportOptionsStruct & options, - int framerate, - Progress_Meter_Class * meter, - HWND MaxHwnd, - char * name, - Matrix3 & offset = Matrix3(1) // matrix to bring current object space into - // base object space (for damage animations) - ); - - MotionClass ( - IScene * scene, - INodeListClass * rootlist, - HierarchySaveClass * basepose, - W3dExportOptionsStruct & options, - int framerate, - Progress_Meter_Class * meter, - HWND MaxHwnd, - char * name, - Matrix3 & offset = Matrix3(1) // matrix to bring current object space into - // base object space (for damage animations) - ); - - ~MotionClass(void); - - bool Save(ChunkSaveClass & csave); - -private: - - IScene * Scene; - INode * RootNode; - INodeListClass * RootList; - HierarchySaveClass * BasePose; - int StartFrame; - int EndFrame; - int NumFrames; - int FrameRate; - - bool ReduceAnimation; - int ReduceAnimationPercent; - - bool CompressAnimation; - int CompressAnimationFlavor; - float CompressAnimationTranslationError; - float CompressAnimationRotationError; - - Progress_Meter_Class * Meter; - char Name[W3D_NAME_LEN]; - Matrix3 Offset; - - // 2D array of matrices, one per node per frame - Matrix3 * * MotionMatrix; - - // 2D array of euler angles, one per node per frame - Point3 * * EulerDelta; - - // Visibility bits, one bit per node per frame - BooleanVectorClass * VisData; - - // Movement bits, one bit per node per frame, to designate a movement as interpolated, or not - BooleanVectorClass * BinMoveData; - - // flag for each node in the base pose, indicating - // whether the node actually appeard in the max scene - // being exported. - BooleanVectorClass NodeValidFlags; - - void compute_frame_motion(int frame); - void set_motion_matrix(int node,int frame,const Matrix3 & motion); - Matrix3 get_motion_matrix(int node,int frame); - void set_eulers(int node,int frame,float x,float y,float z); - Point3 get_eulers(int node,int frame); - void set_visibility(int node,int frame,bool visible); - bool get_visibility(int node,int frame); - void set_binary_movement(int node,int frame,bool visible); - bool get_binary_movement(int node,int frame); - - bool save_header(ChunkSaveClass & csave); - bool save_channels(ChunkSaveClass & csave); - - void init(void); - -}; - - -#endif /*MOTION_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/namedsel.cpp b/Generals/Code/Tools/WW3D/max2w3d/namedsel.cpp deleted file mode 100644 index 42acab32b7..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/namedsel.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/namedsel.cpp 4 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/namedsel.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/26/97 1:29p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "namedsel.h" - - -NamedSelSetList::~NamedSelSetList() -{ - for (int i=0; i= 0) Delete_Set(i); -} - -void NamedSelSetList::Reset(void) -{ - while (Sets.Count() > 0) { - Delete_Set(0); - } -} - -void NamedSelSetList::Set_Size(int size) -{ - for (int i=0; iSetSize(size,TRUE); - } -} - -NamedSelSetList& NamedSelSetList::operator=(NamedSelSetList& from) -{ - for (int i=0; iBeginChunk(NAMED_SEL_SET_CHUNK); - - isave->BeginChunk(NAMED_SEL_NAME_CHUNK); - isave->WriteWString(*Names[i]); - isave->EndChunk(); - - isave->BeginChunk(NAMED_SEL_BITS_CHUNK); - Sets[i]->Save(isave); - isave->EndChunk(); - - isave->EndChunk(); - - } - return IO_OK; -} - - -IOResult NamedSelSetList::Load(ILoad *iload) -{ - IOResult res; - - while (IO_OK==(res=iload->OpenChunk())) { - - switch (iload->CurChunkID()) { - - case NAMED_SEL_SET_CHUNK: - res = Load_Set(iload); - break; - - default: - assert(0); - break; - } - - iload->CloseChunk(); - if (res!=IO_OK) return res; - } - return IO_OK; -} - -IOResult NamedSelSetList::Load_Set(ILoad * iload) -{ - IOResult res; - BitArray set; - TCHAR * name; - - BOOL gotset = FALSE; - BOOL gotname = FALSE; - - res = iload->OpenChunk(); - - while (IO_OK==(res=iload->OpenChunk())) { - - switch (iload->CurChunkID()) { - - case NAMED_SEL_BITS_CHUNK: - { - res = set.Load(iload); - gotset = TRUE; - break; - } - - case NAMED_SEL_NAME_CHUNK: - { - res = iload->ReadWStringChunk(&name); - gotname = TRUE; - break; - } - } - iload->CloseChunk(); - if (res != IO_OK) return res; - } - - assert(gotset && gotname); - Append_Set(set,TSTR(name)); - - return IO_OK; -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/namedsel.h b/Generals/Code/Tools/WW3D/max2w3d/namedsel.h deleted file mode 100644 index bc03d3b653..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/namedsel.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/namedsel.h 4 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/namedsel.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/21/97 2:05p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef NAMEDSEL_H -#define NAMEDSEL_H - - -#include "max.h" - -/* -** This is a class for containing bit arrays for -** the named selection sets. I stole it from -** the Edit Mesh modifier code... -** It is basically a dynamically sized array -** of bitarrays. -*/ -class NamedSelSetList -{ -public: - Tab Sets; - Tab Names; - - ~NamedSelSetList(); - - BitArray & operator[](int i) { return *Sets[i]; } - int Count() { return Sets.Count(); } - - int Find_Set(TSTR & setname); - void Delete_Set(int i); - void Delete_Set(TSTR & setname); - void Reset(void); - void Append_Set(BitArray & nset,TSTR & setname); - - IOResult Load(ILoad * iload); - IOResult Save(ISave * isave); - IOResult Load_Set(ILoad * iload); - - void Set_Size(int size); - NamedSelSetList & operator=(NamedSelSetList & from); - - enum { - NAMED_SEL_SET_CHUNK = 0x0021, - NAMED_SEL_BITS_CHUNK = 0x0022, - NAMED_SEL_NAME_CHUNK = 0x0023 - }; -}; - - -#endif /*NAMEDSEL_H*/ diff --git a/Generals/Code/Tools/WW3D/max2w3d/nullsave.cpp b/Generals/Code/Tools/WW3D/max2w3d/nullsave.cpp deleted file mode 100644 index 008d365674..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/nullsave.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/nullsave.cpp $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/05/99 3:14p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "nullsave.h" - - -NullSaveClass::NullSaveClass -( - char * mesh_name, - char * container_name, - Progress_Meter_Class & meter -) -{ - ////////////////////////////////////////////////////////////////////// - // Set up the NullObject description - ////////////////////////////////////////////////////////////////////// - memset(&NullData,0,sizeof(NullData)); - - NullData.Version = W3D_NULL_OBJECT_CURRENT_VERSION; - if ((container_name != NULL) && (strlen(container_name) > 0)) { - strcpy(NullData.Name,container_name); - strcat(NullData.Name,"."); - } - strcat(NullData.Name,mesh_name); -} - - - -int NullSaveClass::Write_To_File(ChunkSaveClass & csave) -{ - csave.Begin_Chunk(W3D_CHUNK_NULL_OBJECT); - csave.Write(&NullData,sizeof(NullData)); - csave.End_Chunk(); - return 0; -} - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/nullsave.h b/Generals/Code/Tools/WW3D/max2w3d/nullsave.h deleted file mode 100644 index a7ce19de37..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/nullsave.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/nullsave.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 8/05/99 3:05p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef NULLSAVE_H -#define NULLSAVE_H - - -#include -#include "w3d_file.h" -#include "chunkio.h" -#include "PROGRESS.H" - - -/******************************************************************************************* -** -** NullSaveClass - Create a Null object. -** -*******************************************************************************************/ -class NullSaveClass -{ -public: - - enum { - EX_UNKNOWN = 0, // exception error codes - EX_CANCEL = 1 - }; - - NullSaveClass( char * mesh_name, - char * container_name, - Progress_Meter_Class & meter); - - int Write_To_File(ChunkSaveClass & csave); - -private: - - W3dNullObjectStruct NullData; - -}; - - - - -#endif //NULLSAVE_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp b/Generals/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp deleted file mode 100644 index c4f31e2fd1..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.cpp +++ /dev/null @@ -1,914 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/presetexportoptionsdialog.cpp $* - * * - * Original Author:: Patrick Smith * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/10/00 2:26p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "presetexportoptionsdialog.h" -#include "dllmain.h" -#include "resource.h" -#include "w3dexp.h" -#include "animationcompressionsettings.h" - - -//////////////////////////////////////////////////////////////////////////////////////// -// Constants -//////////////////////////////////////////////////////////////////////////////////////// - -static const char *BROWSE_FILTER = "W3D Files (*.W3D)\0*.W3D\0WHT Files (*.WHT)\0*.WHT\0\0"; - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// PresetExportOptionsDialogClass -// -//////////////////////////////////////////////////////////////////////////////////////// -PresetExportOptionsDialogClass::PresetExportOptionsDialogClass (Interface *maxinterface, HWND parent_wnd) : - MaxInterface (maxinterface), - Options (NULL), - Wnd (NULL), - ParentWnd (parent_wnd), - CurrentPane (-1) -{ - ::memset (PaneWnds, 0, sizeof (PaneWnds)); - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// ~PresetExportOptionsDialogClass -// -//////////////////////////////////////////////////////////////////////////////////////// -PresetExportOptionsDialogClass::~PresetExportOptionsDialogClass (void) -{ - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Do_Modal -// -//////////////////////////////////////////////////////////////////////////////////////// -int -PresetExportOptionsDialogClass::Do_Modal (void) -{ - int retval = ::DialogBoxParam (AppInstance, MAKEINTRESOURCE (IDD_W3D_PRESET_EXPORT_OPTIONS), - ParentWnd, Real_Message_Proc, (LPARAM)this); - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Real_Message_Proc -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL CALLBACK -PresetExportOptionsDialogClass::Real_Message_Proc -( - HWND wnd, - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - PresetExportOptionsDialogClass *dialog_obj = NULL; - - // - // Setup the framework we need so that the instance - // can process the messages instead of this static callback. - // - if (message == WM_INITDIALOG) { - dialog_obj = (PresetExportOptionsDialogClass *)lparam; - dialog_obj->Wnd = wnd; - ::SetProp (wnd, "DIALOG_OBJ", (HANDLE)dialog_obj); - } else { - dialog_obj = (PresetExportOptionsDialogClass *)::GetProp (wnd, "DIALOG_OBJ"); - } - - // - // Allow the instance to handle the call - // - BOOL retval = FALSE; - if (dialog_obj != NULL) { - retval = dialog_obj->Message_Proc (message, wparam, lparam); - } - - // - // Cleanup the framework - // - if (message == WM_DESTROY) { - ::RemoveProp (wnd, "DIALOG_OBJ"); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Settings_Pane_Message_Proc -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL CALLBACK -PresetExportOptionsDialogClass::Settings_Pane_Message_Proc -( - HWND wnd, - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - PresetExportOptionsDialogClass *dialog_obj = NULL; - - // - // Setup the framework we need so that the instance - // can process the messages instead of this static callback. - // - if (message == WM_INITDIALOG) { - dialog_obj = (PresetExportOptionsDialogClass *)lparam; - ::SetProp (wnd, "DIALOG_OBJ", (HANDLE)dialog_obj); - } else { - dialog_obj = (PresetExportOptionsDialogClass *)::GetProp (wnd, "DIALOG_OBJ"); - } - - // - // Allow the instance to handle the call - // - BOOL retval = FALSE; - if (dialog_obj != NULL) { - retval = dialog_obj->Pane_Message_Proc (message, wparam, lparam); - } - - // - // Cleanup the framework - // - if (message == WM_DESTROY) { - ::RemoveProp (wnd, "DIALOG_OBJ"); - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Pane_Message_Proc -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL -PresetExportOptionsDialogClass::Pane_Message_Proc -( - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - BOOL retval = FALSE; - - switch (message) - { - case WM_CUSTEDIT_ENTER: - - switch (wparam) - { - case IDC_RANGE_LOW_EDIT: - { - // - // Update the start frame - // - ICustEdit *edit_ctrl = GetICustEdit ((HWND)lparam); - if (edit_ctrl != NULL) { - Options->StartFrame = edit_ctrl->GetInt (); - - // - // Bounds check the value - // - if (Options->StartFrame > Options->EndFrame) { - Options->StartFrame = Options->EndFrame; - } - - Update_Controls (); - } - } - break; - - case IDC_RANGE_HIGH_EDIT: - { - // - // Update the end frame - // - ICustEdit *edit_ctrl = GetICustEdit ((HWND)lparam); - if (edit_ctrl != NULL) { - Options->EndFrame = edit_ctrl->GetInt (); - - // - // Bounds check the value - // - if (Options->EndFrame < Options->StartFrame) { - Options->EndFrame = Options->StartFrame; - } - - Update_Controls (); - } - } - break; - } - - break; - - case CC_SPINNER_BUTTONUP: - { - ISpinnerControl *spin_ctrl = (ISpinnerControl *)lparam; - if (spin_ctrl != NULL) { - - switch (LOWORD (wparam)) - { - // - // Update the start frame - // - case IDC_RANGE_LOW_SPIN: - Options->StartFrame = spin_ctrl->GetIVal (); - - // - // Bounds check the value - // - if (Options->StartFrame > Options->EndFrame) { - Options->StartFrame = Options->EndFrame; - } - Update_Controls (); - break; - - // - // Update the end frame - // - case IDC_RANGE_HIGH_SPIN: - Options->EndFrame = spin_ctrl->GetIVal (); - - // - // Bounds check the value - // - if (Options->EndFrame < Options->StartFrame) { - Options->EndFrame = Options->StartFrame; - } - - Update_Controls (); - break; - } - } - } - break; - - case WM_COMMAND: - { - HWND control_wnd = reinterpret_cast (lparam); - bool update_controls = true; - - switch (LOWORD (wparam)) - { - case IDC_EXPORT_MESH_SMOOTH_CHECK: - Options->SmoothBetweenMeshes = (SendMessage (control_wnd, BM_GETCHECK, 0, 0L) == 1); - break; - - case IDC_EXPORT_MESH_AABTREES: - Options->DisableExportAABTrees = (SendMessage (control_wnd, BM_GETCHECK, 0, 0L) != 1); - break; - -#if 0 - case IDC_EXPORT_MESH_OPTIMIZE: - Options->EnableOptimizeMeshData = (SendMessage (control_wnd, BM_GETCHECK, 0, 0L) == 1); - break; -#endif - - case IDC_USE_SKELETON_CHECK: - Options->LoadHierarchy = (SendMessage (control_wnd, BM_GETCHECK, 0, 0L) == 1); - break; - - case IDC_COMPRESS_ANIMATION_CHECK: - Options->CompressAnimation = (SendMessage (control_wnd, BM_GETCHECK, 0, 0L) == 1); - break; - - case IDC_WHT_BROWSE_BUTTON: - { - OPENFILENAME ofn = { sizeof (OPENFILENAME), 0 }; - ofn.lpstrFilter = BROWSE_FILTER; - ofn.nMaxFile = _MAX_PATH; - ofn.nMaxFileTitle = _MAX_FNAME + _MAX_EXT; - ofn.Flags = OFN_HIDEREADONLY | OFN_CREATEPROMPT; - ofn.lpstrDefExt = "wht"; - ofn.hwndOwner = Wnd; - ofn.lpstrFile = Options->HierarchyFilename; - - if (::GetOpenFileName (&ofn)) { - - // - // Get the relative path between the current export path - // and the full file path to the hierarchy file: - // - Create_Relative_Path (Options->RelativeHierarchyFilename, - W3dExportClass::CurrentExportPath, - ofn.lpstrFile); - } - } - break; - - case IDC_COMPRESSION_SETTINGS: - { - // - // Display the compression options dialog - // - AnimationCompressionSettingsDialogClass dialog (MaxInterface, Wnd); - dialog.Set_Options (Options); - dialog.Do_Modal (); - } - break; - - case IDC_EXPORT_MESH_MAT_TO_TEXTURE: - Options->EnableMaterialColorToTextureConversion = (SendMessage (control_wnd, BM_GETCHECK, 0, 0L) == 1); - break; - - default: - update_controls = false; - break; - } - - if (update_controls) { - Update_Controls (); - } - } - break; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Message_Proc -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL -PresetExportOptionsDialogClass::Message_Proc -( - UINT message, - WPARAM wparam, - LPARAM lparam -) -{ - BOOL retval = FALSE; - - switch (message) - { - case WM_INITDIALOG: - { - // - // Center the dialog - // - RECT parent_rect = { 0 }; - RECT rect = { 0 }; - ::GetWindowRect (ParentWnd, &parent_rect); - ::GetWindowRect (Wnd, &rect); - int width = parent_rect.right - parent_rect.left; - int height = parent_rect.bottom - parent_rect.top; - ::SetWindowPos ( Wnd, NULL, - parent_rect.left + (width / 2) - ((rect.right - rect.left) / 2), - parent_rect.top + (height / 2) - ((rect.bottom - rect.top) / 2), - 0, 0, SWP_NOZORDER | SWP_NOSIZE); - - // - // Initialize the controls - // - Create_Settings_Panes (); - Initialize_Controls (); - Update_Controls (); - Determine_Preset_Type (); - retval = TRUE; - } - break; - - case WM_COMMAND: - retval = On_Command (wparam, lparam); - break; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// On_Command -// -//////////////////////////////////////////////////////////////////////////////////////// -BOOL -PresetExportOptionsDialogClass::On_Command (WPARAM wparam, LPARAM lparam) -{ - BOOL retval = FALSE; - - switch (LOWORD (wparam)) - { - case IDC_HLOD_RADIO: - Show_Settings_Pane (PANE_HLOD); - break; - - case IDC_ANIM_HLOD_RADIO: - Show_Settings_Pane (PANE_ANIM_HLOD); - break; - - case IDC_ANIM_RADIO: - Show_Settings_Pane (PANE_ANIM); - break; - - case IDC_TERRAIN_RADIO: - Show_Settings_Pane (PANE_TERRAIN); - break; - - case IDC_SKELETON_RADIO: - Show_Settings_Pane (PANE_SKELETON); - break; - - case IDC_MESH_RADIO: - Show_Settings_Pane (PANE_MESH); - break; - - case IDCANCEL: - ::memcpy (Options, &OrigOptions, sizeof (OrigOptions)); - EndDialog (Wnd, IDCANCEL); - break; - - case IDOK: - Save_Settings (); - EndDialog (Wnd, IDOK); - break; - } - - return retval; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Show_Settings_Pane -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Show_Settings_Pane (int pane_id) -{ - if (pane_id != CurrentPane) { - - // - // Show the new pane and hide the old pane - // - ::ShowWindow (PaneWnds[pane_id], SW_SHOW); - if (CurrentPane >= 0) { - ::ShowWindow (PaneWnds[CurrentPane], SW_HIDE); - } - CurrentPane = pane_id; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Create_Settings_Panes -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Create_Settings_Panes (void) -{ - PaneWnds[PANE_HLOD] = ::CreateDialogParam (AppInstance, MAKEINTRESOURCE (IDD_EXPORT_PANE_HLOD), - Wnd, Settings_Pane_Message_Proc, (LPARAM)this); - - PaneWnds[PANE_ANIM_HLOD] = ::CreateDialogParam (AppInstance, MAKEINTRESOURCE (IDD_EXPORT_PANE_ANIMATED_HLOD), - Wnd, Settings_Pane_Message_Proc, (LPARAM)this); - - PaneWnds[PANE_ANIM] = ::CreateDialogParam (AppInstance, MAKEINTRESOURCE (IDD_EXPORT_PANE_ANIMATION), - Wnd, Settings_Pane_Message_Proc, (LPARAM)this); - - PaneWnds[PANE_TERRAIN] = ::CreateDialogParam (AppInstance, MAKEINTRESOURCE (IDD_EXPORT_PANE_TERRAIN), - Wnd, Settings_Pane_Message_Proc, (LPARAM)this); - - PaneWnds[PANE_SKELETON] = ::CreateDialogParam (AppInstance, MAKEINTRESOURCE (IDD_EXPORT_PANE_SKELETON), - Wnd, Settings_Pane_Message_Proc, (LPARAM)this); - - PaneWnds[PANE_MESH] = ::CreateDialogParam (AppInstance, MAKEINTRESOURCE (IDD_EXPORT_PANE_MESH), - Wnd, Settings_Pane_Message_Proc, (LPARAM)this); - - - // - // Get the position and size of the group box the settings panes will be - // displayed inside - // - RECT group_rect = { 0 }; - ::GetWindowRect (::GetDlgItem (Wnd, IDC_GROUP_BOX), &group_rect); - ::ScreenToClient (Wnd, (LPPOINT)&group_rect); - ::ScreenToClient (Wnd, ((LPPOINT)&group_rect) + 1); - int width = group_rect.right - group_rect.left; - int height = group_rect.bottom - group_rect.top; - - // - // Loop over all the panes and make sure they are in the proper location - // - for (int index = 0; index < PANE_MAX; index ++) { - HWND pane_wnd = PaneWnds[index]; - - // - // Get the size of this pane - // - RECT rect = { 0 }; - ::GetWindowRect (pane_wnd, &rect); - - // - // Center the pane inside of the group box - // - ::SetWindowPos ( pane_wnd, ::GetDlgItem (Wnd, IDC_GROUP_BOX), - group_rect.left + (width / 2) - ((rect.right - rect.left) / 2), - group_rect.top + (height / 2) - ((rect.bottom - rect.top) / 2), - 0, 0, SWP_NOSIZE); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Destroy_Settings_Panes -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Destroy_Settings_Panes (void) -{ - // - // Loop over all the panes and destroy them - // - for (int index = 0; index < PANE_MAX; index ++) { - ::DestroyWindow (PaneWnds[index]); - PaneWnds[index] = NULL; - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Determine_Preset_Type -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Determine_Preset_Type (void) -{ - // - // Examine the current options and try to determine which - // preset best matches this configuration. - // - - if (Options->EnableTerrainMode) { - - // - // Select the terrain UI - // - Show_Settings_Pane (PANE_TERRAIN); - SendDlgItemMessage (Wnd, IDC_TERRAIN_RADIO, BM_SETCHECK, (WPARAM)TRUE, 0L); - - } else if (Options->ExportGeometry == false) { - - if (Options->ExportAnimation == false) { - - // - // Select the skeleton UI - // - Show_Settings_Pane (PANE_SKELETON); - SendDlgItemMessage (Wnd, IDC_SKELETON_RADIO, BM_SETCHECK, (WPARAM)TRUE, 0L); - } else { - - // - // Select the anim UI - // - Show_Settings_Pane (PANE_ANIM); - SendDlgItemMessage (Wnd, IDC_ANIM_RADIO, BM_SETCHECK, (WPARAM)TRUE, 0L); - } - - } else if (Options->ExportHierarchy == false && Options->LoadHierarchy == false) { - - // - // Select the mesh UI - // - Show_Settings_Pane (PANE_MESH); - SendDlgItemMessage (Wnd, IDC_MESH_RADIO, BM_SETCHECK, (WPARAM)TRUE, 0L); - - } else if (Options->ExportAnimation == false) { - - // - // Select the HLOD UI - // - Show_Settings_Pane (PANE_HLOD); - SendDlgItemMessage (Wnd, IDC_HLOD_RADIO, BM_SETCHECK, (WPARAM)TRUE, 0L); - - } else { - - // - // Select the HLOD anim UI - // - Show_Settings_Pane (PANE_ANIM_HLOD); - SendDlgItemMessage (Wnd, IDC_ANIM_HLOD_RADIO, BM_SETCHECK, (WPARAM)TRUE, 0L); - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Initialize_Controls -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Initialize_Controls (void) -{ - // - // Check the review log file button if necessary - // - CheckDlgButton (Wnd, IDC_REVIEW_LOG, Options->ReviewLog); - - // - // Precompute some of the animation data - // - int ticksperframe = ::GetTicksPerFrame(); - int startframe = MaxInterface->GetAnimRange ().Start () / ticksperframe; - int endframe = MaxInterface->GetAnimRange ().End () / ticksperframe; - - // - // Clamp the real options the same way the displayed values are clamped - // - if (startframe > Options->StartFrame) { - Options->StartFrame = startframe; - } - if (endframe < Options->EndFrame) { - Options->EndFrame = endframe; - } - - // - // Loop over all the panes and update any of the controls therein - // - for (int index = 0; index < PANE_MAX; index ++) { - HWND pane_wnd = PaneWnds[index]; - - // - // Are there any animation controls on this pane to initialize? - // - if (::GetDlgItem (pane_wnd, IDC_RANGE_LOW_SPIN) != NULL) { - - ISpinnerControl *low_spin = NULL; - ISpinnerControl *high_spin = NULL; - - low_spin = ::SetupIntSpinner (pane_wnd, IDC_RANGE_LOW_SPIN, IDC_RANGE_LOW_EDIT, - startframe, endframe, 0); - - high_spin = ::SetupIntSpinner (pane_wnd, IDC_RANGE_HIGH_SPIN, IDC_RANGE_HIGH_EDIT, - startframe, endframe, 0); - - ::SetProp (::GetDlgItem (pane_wnd, IDC_RANGE_LOW_SPIN), "ISpinnerControl", (HANDLE)low_spin); - ::SetProp (::GetDlgItem (pane_wnd, IDC_RANGE_HIGH_SPIN), "ISpinnerControl", (HANDLE)high_spin); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Update_Controls -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Update_Controls (void) -{ - // - // Loop over all the panes and update any of the controls therein - // - for (int index = 0; index < PANE_MAX; index ++) { - HWND pane_wnd = PaneWnds[index]; - - // - // Handle the check boxes - // - CheckDlgButton (pane_wnd, IDC_EXPORT_MESH_SMOOTH_CHECK, Options->SmoothBetweenMeshes); - CheckDlgButton (pane_wnd, IDC_EXPORT_MESH_AABTREES, !Options->DisableExportAABTrees); -#if ENABLE_MESH_OPTIMIZING - CheckDlgButton (pane_wnd, IDC_EXPORT_MESH_OPTIMIZE, Options->EnableOptimizeMeshData); -#endif - CheckDlgButton (pane_wnd, IDC_USE_SKELETON_CHECK, Options->LoadHierarchy); - CheckDlgButton (pane_wnd, IDC_COMPRESS_ANIMATION_CHECK, Options->CompressAnimation); - CheckDlgButton (pane_wnd, IDC_EXPORT_MESH_MAT_TO_TEXTURE, Options->EnableMaterialColorToTextureConversion); - - // - // Enable/disable the compression settings button - // - HWND compress_settings_btn = ::GetDlgItem (pane_wnd, IDC_COMPRESSION_SETTINGS); - if (compress_settings_btn != NULL) { - ::EnableWindow (compress_settings_btn, Options->CompressAnimation); - } - - // - // Setup the skeleton browse button - // - HWND skeleten_browse_btn = ::GetDlgItem (pane_wnd, IDC_WHT_BROWSE_BUTTON); - if (skeleten_browse_btn != NULL) { - - // - // Honor the relative path if it is present - // - if (Options->RelativeHierarchyFilename[0] != 0) { - SetWindowText (skeleten_browse_btn, Options->RelativeHierarchyFilename); - ::Create_Full_Path (Options->HierarchyFilename, - W3dExportClass::CurrentExportPath, - Options->RelativeHierarchyFilename); - - } else if (Options->HierarchyFilename[0] != 0) { - SetWindowText (skeleten_browse_btn, Options->HierarchyFilename); - ::Create_Relative_Path (Options->RelativeHierarchyFilename, - W3dExportClass::CurrentExportPath, - Options->HierarchyFilename); - } - - // - // Set the enable state of the window - // - ::EnableWindow (skeleten_browse_btn, Options->LoadHierarchy); - } - - // - // Are there any animation controls on this pane to update? - // - HWND low_spin_wnd = ::GetDlgItem (pane_wnd, IDC_RANGE_LOW_SPIN); - HWND high_spin_wnd = ::GetDlgItem (pane_wnd, IDC_RANGE_HIGH_SPIN); - if (low_spin_wnd != NULL && high_spin_wnd != NULL) { - - // - // Peek at the spinner control objects - // - ISpinnerControl *low_spin = NULL; - ISpinnerControl *high_spin = NULL; - low_spin = (ISpinnerControl *)::GetProp (low_spin_wnd, "ISpinnerControl"); - high_spin = (ISpinnerControl *)::GetProp (high_spin_wnd, "ISpinnerControl"); - - // - // Update the spin controls - // - low_spin->SetValue (Options->StartFrame, FALSE); - high_spin->SetValue (Options->EndFrame, FALSE); - } - } - - return ; -} - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// Save_Settings -// -//////////////////////////////////////////////////////////////////////////////////////// -void -PresetExportOptionsDialogClass::Save_Settings (void) -{ - // - // Force settings that certain preset types need - // - if (::IsDlgButtonChecked (Wnd, IDC_TERRAIN_RADIO)) { - - // - // Force some settings for the "Renegade Terrain" preset - // - Options->ExportHierarchy = true; - Options->LoadHierarchy = false; - Options->ExportAnimation = false; - Options->ExportGeometry = true; - Options->CompressAnimation = false; - Options->ReduceAnimation = false; - Options->EnableTerrainMode = true; - Options->DisableExportAABTrees = false; - Options->EnableMaterialColorToTextureConversion = false; - } else if (::IsDlgButtonChecked (Wnd, IDC_SKELETON_RADIO)) { - - // - // Force some settings for the "Skeleton" preset - // - Options->ExportHierarchy = true; - Options->LoadHierarchy = false; - Options->ExportAnimation = false; - Options->ExportGeometry = false; - Options->CompressAnimation = false; - Options->ReduceAnimation = false; - Options->EnableTerrainMode = false; - Options->EnableOptimizeMeshData = false; - Options->DisableExportAABTrees = true; - Options->SmoothBetweenMeshes = false; - Options->EnableTerrainMode = false; - Options->EnableMaterialColorToTextureConversion = false; - } else if (::IsDlgButtonChecked (Wnd, IDC_MESH_RADIO)) { - - // - // Force some settings for the "Simple Mesh" preset - // - Options->ExportHierarchy = false; - Options->LoadHierarchy = false; - Options->ExportAnimation = false; - Options->ExportGeometry = true; - Options->CompressAnimation = false; - Options->ReduceAnimation = false; - Options->EnableTerrainMode = false; - Options->EnableOptimizeMeshData = false; - Options->SmoothBetweenMeshes = false; - Options->EnableTerrainMode = false; - } else if (::IsDlgButtonChecked (Wnd, IDC_HLOD_RADIO)) { - - // - // Force some settings for the "Hierarchical Model" preset - // - Options->ExportHierarchy = !Options->LoadHierarchy; - Options->ExportAnimation = false; - Options->ExportGeometry = true; - Options->CompressAnimation = false; - Options->ReduceAnimation = false; - Options->EnableTerrainMode = false; - } else if (::IsDlgButtonChecked (Wnd, IDC_ANIM_HLOD_RADIO)) { - - // - // Force some settings for the "Hierarchical Animated Model" preset - // - Options->ExportHierarchy = !Options->LoadHierarchy; - Options->ExportAnimation = true; - Options->ExportGeometry = true; - Options->EnableTerrainMode = false; - } else if (::IsDlgButtonChecked (Wnd, IDC_ANIM_RADIO)) { - - // - // Force some settings for the "Pure Animation" preset - // - Options->ExportHierarchy = !Options->LoadHierarchy; - Options->ExportAnimation = true; - Options->ExportGeometry = false; - Options->EnableTerrainMode = false; - Options->EnableOptimizeMeshData = false; - Options->DisableExportAABTrees = true; - Options->SmoothBetweenMeshes = false; - Options->EnableMaterialColorToTextureConversion = false; - } - - // - // Record the "Review Log File" option - // - Options->ReviewLog = (::IsDlgButtonChecked (Wnd, IDC_REVIEW_LOG) == 1); - - // - // Check to see if anything has changed - // - if (::memcmp (Options, &OrigOptions, sizeof (OrigOptions)) != 0) { - SetSaveRequiredFlag (true); - } - - return ; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.h b/Generals/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.h deleted file mode 100644 index 66b8c52912..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/presetexportoptionsdialog.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/presetexportoptionsdialog.h $* - * * - * Original Author:: Patrick Smith * - * * - * $Author:: Patrick $* - * * - * $Modtime:: 10/30/00 2:45p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef __PRESET_EXPORT_OPTIONS_DIALOG_H -#define __PRESET_EXPORT_OPTIONS_DIALOG_H - -#include -#include -#include "w3dutil.h" - - -//////////////////////////////////////////////////////////////////////////////////////// -// -// PresetExportOptionsDialogClass -// -//////////////////////////////////////////////////////////////////////////////////////// -class PresetExportOptionsDialogClass -{ -public: - - ////////////////////////////////////////////////////////////////// - // Public constructors/destructors - ////////////////////////////////////////////////////////////////// - PresetExportOptionsDialogClass (Interface *maxinterface, HWND parent_wnd = NULL); - ~PresetExportOptionsDialogClass (void); - - - ////////////////////////////////////////////////////////////////// - // Public methods - ////////////////////////////////////////////////////////////////// - - void Set_Options (W3dExportOptionsStruct *options) { Options = options; ::memcpy (&OrigOptions, Options, sizeof (OrigOptions)); } - int Do_Modal (void); - -private: - - ////////////////////////////////////////////////////////////////// - // Private data types - ////////////////////////////////////////////////////////////////// - - enum - { - PANE_HLOD = 0, - PANE_ANIM_HLOD, - PANE_ANIM, - PANE_TERRAIN, - PANE_SKELETON, - PANE_MESH, - PANE_MAX - }; - - - ////////////////////////////////////////////////////////////////// - // Static methods - ////////////////////////////////////////////////////////////////// - static BOOL CALLBACK Real_Message_Proc (HWND wnd, UINT message, WPARAM wparam, LPARAM lparam); - static BOOL CALLBACK Settings_Pane_Message_Proc (HWND wnd, UINT message, WPARAM wparam, LPARAM lparam); - - ////////////////////////////////////////////////////////////////// - // Private methods - ////////////////////////////////////////////////////////////////// - BOOL Message_Proc (UINT message, WPARAM wparam, LPARAM lparam); - BOOL Pane_Message_Proc (UINT message, WPARAM wparam, LPARAM lparam); - BOOL Settings_Message_Proc (UINT message, WPARAM wparam, LPARAM lparam); - BOOL On_Command (WPARAM wparam, LPARAM lparam); - void Show_Settings_Pane (int pane_id); - void Create_Settings_Panes (void); - void Destroy_Settings_Panes (void); - void Determine_Preset_Type (void); - void Initialize_Controls (void); - void Update_Controls (void); - void Save_Settings (void); - - ////////////////////////////////////////////////////////////////// - // Private member data - ////////////////////////////////////////////////////////////////// - W3dExportOptionsStruct * Options; - W3dExportOptionsStruct OrigOptions; - Interface * MaxInterface; - HWND Wnd; - HWND ParentWnd; - HWND PaneWnds[PANE_MAX]; - int CurrentPane; -}; - - -#endif //__PRESET_EXPORT_OPTIONS_DIALOG_H - diff --git a/Generals/Code/Tools/WW3D/max2w3d/rcmenu.cpp b/Generals/Code/Tools/WW3D/max2w3d/rcmenu.cpp deleted file mode 100644 index 08ba749ac7..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/rcmenu.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/rcmenu.cpp 6 4/19/00 12:24p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/rcmenu.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 4/18/00 8:26p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RCMenuClass::Init -- initialize the "right-click" menu * - * RCMenuClass::Selected -- menu selection callback * - * RCMenuClass::Toggle_Hierarchy -- toggle the "export hierarchy" option * - * RCMenuClass::Toggle_Geometry -- toggle the "export geometry" option * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "rcmenu.h" -#include "w3dutil.h" -#include "util.h" - - -RCMenuClass TheRCMenu; - -/*********************************************************************************************** - * RCMenuClass::Init -- initialize the "right-click" menu * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void RCMenuClass::Init(RightClickMenuManager* manager, HWND hWnd, IPoint2 m) -{ - Installed=TRUE; - - SelNode = InterfacePtr->PickNode(hWnd,m); - - if (SelNode) { - - UINT menuflags; - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(SelNode); - - /* - ** Add the menu separator - */ - manager->AddMenu(this, MF_SEPARATOR, MENU_SEPARATOR, NULL); - - /* - ** Add the Name of the object - */ - char string[64]; - sprintf(string,"%s:",SelNode->GetName()); - manager->AddMenu(this, MF_STRING | MF_DISABLED, MENU_NODE_NAME, string); - - /* - ** Add the pointer - */ -// sprintf(string,"0x%X",(unsigned long)SelNode); -// manager->AddMenu(this, MF_STRING | MF_GRAYED, MENU_NODE_POINTER, string); - - /* - ** Add the hierarchy menu option - */ - if (wdata->Is_Bone()) { - menuflags = MF_STRING | MF_CHECKED; - } else { - menuflags = MF_STRING; - } - manager->AddMenu(this, menuflags, MENU_TOGGLE_HIERARCHY, "W3D: Export Hierarchy"); - - /* - ** Add the geometry menu option - */ - if (wdata->Is_Geometry()) { - menuflags = MF_STRING | MF_CHECKED; - } else { - menuflags = MF_STRING; - } - manager->AddMenu(this, menuflags, MENU_TOGGLE_GEOMETRY, "W3D: Export Geometry"); - - } -} - -/*********************************************************************************************** - * RCMenuClass::Selected -- menu selection callback * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void RCMenuClass::Selected(UINT id) -{ - switch (id) { - - case MENU_TOGGLE_HIERARCHY: - Toggle_Hierarchy(SelNode); - break; - case MENU_TOGGLE_GEOMETRY: - Toggle_Geometry(SelNode); - break; - - } -} - -/*********************************************************************************************** - * RCMenuClass::Toggle_Hierarchy -- toggle the "export hierarchy" option * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void RCMenuClass::Toggle_Hierarchy(INode * node) -{ - - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(SelNode); - assert(wdata); - - if (wdata->Is_Bone()) { - wdata->Enable_Export_Transform(false); - } else { - wdata->Enable_Export_Transform(true); - } -} - -/*********************************************************************************************** - * RCMenuClass::Toggle_Geometry -- toggle the "export geometry" option * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void RCMenuClass::Toggle_Geometry(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(SelNode); - assert(wdata); - - if (wdata->Is_Geometry()) { - wdata->Enable_Export_Geometry(false); - } else { - wdata->Enable_Export_Geometry(true); - } -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/rcmenu.h b/Generals/Code/Tools/WW3D/max2w3d/rcmenu.h deleted file mode 100644 index 024c8878c6..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/rcmenu.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/rcmenu.h 3 1/14/98 10:23a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/rcmenu.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/13/98 3:44p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef RCMENU_H -#define RCMENU_H - -#include "max.h" -#include "dllmain.h" -#include "resource.h" -#include "istdplug.h" - -class W3DUtilityClass; - -/********************************************************************************************** -** -** RCMenuClass - W3D Utility's right-click menu. -** -**********************************************************************************************/ -class RCMenuClass : public RightClickMenu -{ - -public: - - RCMenuClass() {Installed=FALSE;} - ~RCMenuClass() {} - - void Bind(Interface * ipi, W3DUtilityClass * eni) { InterfacePtr = ipi; UtilityPtr = eni; } - - void Init(RightClickMenuManager* manager, HWND hWnd, IPoint2 m); - void Selected(UINT id); - void Toggle_Hierarchy(INode * node); - void Toggle_Geometry(INode * node); - -public: - - BOOL Installed; - -private: - - Interface * InterfacePtr; - W3DUtilityClass * UtilityPtr; - INode * SelNode; - - enum { - MENU_SEPARATOR = 0, - MENU_TOGGLE_HIERARCHY, - MENU_TOGGLE_GEOMETRY, - MENU_NODE_NAME, - MENU_NODE_POINTER - }; -}; - -extern RCMenuClass TheRCMenu; - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/resource.h b/Generals/Code/Tools/WW3D/max2w3d/resource.h deleted file mode 100644 index 06a6e74f00..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/resource.h +++ /dev/null @@ -1,422 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by max2w3d.rc -// -#define IDS_COPYRIGHT_NOTICE 1 -#define IDS_AUTHOR_NAME 2 -#define IDS_GAMEMTL 3 -#define IDS_MAP_TEXTURE 4 -#define IDS_ENVMAP 5 -#define IDS_SCENE_EXPORT 6 -#define IDS_LIB_DESCRIPTION 7 -#define IDS_FILE_OPEN_ERROR 8 -#define IDS_DLL_NAME 9 -#define IDS_WTM_SHORT_DESCRIPTION 10 -#define IDS_WTM_LONG_DESCRIPTION 11 -#define IDS_WHT_SHORT_DESCRIPTION 12 -#define IDS_WHT_LONG_DESCRIPTION 13 -#define IDS_WHA_SHORT_DESCRIPTION 14 -#define IDS_WHA_LONG_DESCRIPTION 15 -#define IDS_WTM_FILE_EXTEN 16 -#define IDS_WHT_FILE_EXTEN 17 -#define IDS_WHA_FILE_EXTEN 18 -#define IDS_W3D_FILE_EXTEN 19 -#define IDS_W3D_LONG_DESCRIPTION 20 -#define IDS_W3D_SHORT_DESCRIPTION 21 -#define IDS_W3D_UTILITY_CLASS_NAME 22 -#define IDS_W3DMENU_CATEGORY 23 -#define IDS_W3DMENU_TITLE 24 -#define IDS_SOT 25 -#define IDS_DIFFUSE_COLOR 26 -#define IDS_PARAMETERS 27 -#define IDS_TEXTURE_MAP 28 -#define IDS_ENVIRONMENT_MAP 29 -#define IDS_TEXMAPS 30 -#define IDS_AM 31 -#define IDS_DI 32 -#define IDS_SP 33 -#define IDS_SH 34 -#define IDS_SS 35 -#define IDS_SI 36 -#define IDS_OP 37 -#define IDS_FI 38 -#define IDS_BU 39 -#define IDS_RL 40 -#define IDS_RR 41 -#define IDS_NONE 42 -#define IDS_NOTES 43 -#define IDD_GAMEMTL_PASS_COUNT 101 -#define IDD_VOXEL_DEBUG_DIALOG 103 -#define IDD_W3D_EXPORT_OPTIONS 106 -#define IDD_W3D_UTILITY_DIALOG 107 -#define IDD_BONE_INFLUENCE_PARAMS 108 -#define IDD_SKELETON_PARAMETERS 109 -#define IDD_SKIN_SOT 110 -#define IDD_GAMEMTL_PANEL 111 -#define IDD_GAMEMTL_NOTES_PANEL 112 -#define IDD_GAMEMTL_HINTS_PANEL 114 -#define IDD_GAMEMTL_PSX_PANEL 115 -#define IDD_GAMEMTL_PASS 118 -#define IDD_GAMEMTL_VERTEX_MATERIAL 119 -#define IDD_GAMEMTL_SHADER 120 -#define IDD_GAMEMTL_TEXTURES 121 -#define IDD_GAMEMTL_PASS_COUNT_DIALOG 122 -#define IDD_GENERATE_NAMES_DIALOG 126 -#define IDD_MESH_DEFORM_PANEL 127 -#define IDI_ORIG 127 -#define IDI_DEFORMED 128 -#define IDD_GAMEMTL_SURFACE_TYPE 128 -#define IDD_GAMEMTL_DISPLACEMENT_MAP 129 -#define IDB_NORM 130 -#define IDB_DEFORM 131 -#define IDD_GENERATE_MTL_NAMES_DIALOG 133 -#define IDD_GENERATE_LOD_EXTENSION_DIALOG 135 -#define IDD_EXPORT_ALL 136 -#define IDD_SCENE_SETUP 137 -#define IDD_GAMEMTL_PS2_SHADER 138 -#define IDD_GAMEMTL_PS2_TEXTURES 139 -#define IDD_ALPHA_MODIFIER 140 -#define IDD_W3D_LOG 142 -#define IDD_INPUT_DIALOG 143 -#define IDD_W3DUTILITY_FLOATER_DIALOG 145 -#define IDD_W3DUTILITY_SETTINGS_DIALOG 147 -#define IDD_W3DUTILITY_TOOLS_DIALOG 148 -#define IDD_W3D_EXPORT_OPTIONS1 149 -#define IDD_W3D_PRESET_EXPORT_OPTIONS 149 -#define IDD_EXPORT_PANE_HLOD 150 -#define IDD_EXPORT_PANE_ANIMATED_HLOD 151 -#define IDD_EXPORT_PANE_ANIMATION 152 -#define IDD_EXPORT_PANE_MESH 153 -#define IDD_EXPORT_PANE_SKELETON 154 -#define IDD_EXPORT_PANE_TERRAIN 155 -#define IDD_ANIMATION_COMPRESSION 156 -#define IDI_DISK 157 -#define IDB_WW3D 158 -#define IDD_GRIDSNAP_PARAMS 159 -#define IDC_TRANSLATION_ONLY_CHECK 1000 -#define IDC_TERRAIN_MODE_CHECK 1001 -#define IDC_SETPASSCOUNT 1014 -#define IDC_PASSCOUNT_SPIN 1016 -#define IDC_PASSCOUNT_EDIT 1017 -#define IDC_MAPON_DCT 1018 -#define IDC_MAX_SETS_SPIN 1018 -#define IDC_GAMEMTL_PASSCOUNT_STATIC 1019 -#define IDC_MAX_SETS_EDIT 1019 -#define IDC_MAPON_SCT 1020 -#define IDC_STAGE0_DISPLAY_BUTTON 1020 -#define IDC_VOXEL_VIEWPORT 1021 -#define IDC_MAPON_DIT 1021 -#define IDC_STAGE0_PUBLISH_BUTTON 1021 -#define IDC_MAPON_SIT 1022 -#define IDC_STAGE1_DISPLAY_BUTTON 1022 -#define IDC_WHT_EXPORT_RADIO 1023 -#define IDC_STAGE1_PUBLISH_BUTTON 1023 -#define IDC_WHT_LOAD_RADIO 1024 -#define IDC_STAGE0_RESIZE_BUTTON 1024 -#define IDC_WHA_EXPORT_RADIO 1025 -#define IDC_STAGE0_NO_MIPMAP_BUTTON 1025 -#define IDC_WHT_BROWSE_BUTTON 1026 -#define IDC_STAGE0_CLAMP_U_BUTTON 1026 -#define IDC_WHA_NO_EXPORT_RADIO 1027 -#define IDC_STAGE0_CLAMP_V_BUTTON 1027 -#define IDC_WTM_EXPORT_RADIO 1028 -#define IDC_STAGE1_RESIZE_BUTTON 1028 -#define IDC_WTM_NO_EXPORT_RADIO 1029 -#define IDC_STAGE1_NO_MIPMAP_BUTTON 1029 -#define IDC_STAGE1_CLAMP_U_BUTTON 1030 -#define IDC_WHT_NO_EXPORT_RADIO 1031 -#define IDC_STAGE1_CLAMP_V_BUTTON 1031 -#define IDC_STAGE0_ALPHA_BITMAP_BUTTON 1032 -#define IDC_LAYER_EDIT 1033 -#define IDC_RANGE_LOW_EDIT 1033 -#define IDC_STAGE1_ALPHA_BITMAP_BUTTON 1033 -#define IDC_RANGE_HIGH_EDIT 1034 -#define IDC_NAME_INDEX_EDIT 1034 -#define IDC_STAGE0_NOLOD_BUTTON 1034 -#define IDC_DCT_FRAMES_EDIT 1035 -#define IDC_STAGE1_NOLOD_BUTTON 1035 -#define IDC_DCT_FRAMES_SPIN 1036 -#define IDC_OPACITY_EDIT 1037 -#define IDC_HIERARCHY_CHECK 1038 -#define IDC_OPACITY_SPIN 1038 -#define IDC_UNHIDE_GEOMETRY 1039 -#define IDC_SCT_FRAMES_EDIT 1039 -#define IDC_SELECT_ALPHA_MESHES 1039 -#define IDC_LINK_BY_NAME_BUTTON 1040 -#define IDC_BASE_POSE_EDIT 1040 -#define IDC_UNHIDE_HIERARCHY 1040 -#define IDC_SCT_FRAMES_SPIN 1040 -#define IDC_SELECT_GEOMETRY 1040 -#define IDC_AUTO_LINK_BUTTON 1041 -#define IDC_BASE_POSE_SPIN 1041 -#define IDC_HIDE_ALL 1041 -#define IDC_FOG_EDIT 1041 -#define IDC_SELECT_HIERARCHY 1041 -#define IDC_ADD_BONES_BUTTON 1042 -#define IDC_GEOMETRY_CHECK 1042 -#define IDC_FOG_SPIN 1042 -#define IDC_LINK_BUTTON 1042 -#define IDC_REMOVE_BONES_BUTTON 1043 -#define IDC_TRANSULCENCY_EDIT 1043 -#define IDC_COLLECTION_NAMES_GENERATE 1043 -#define IDC_UNLINK_BUTTON 1043 -#define IDC_BONE_LIST 1044 -#define IDC_TRANSLUCENCY_SPIN 1044 -#define IDC_COLLECTION_NAMES_INCREMENT_LOD 1044 -#define IDC_SELECT_PHYSICAL 1044 -#define IDC_SIT_FRAMES_EDIT 1045 -#define IDC_GEOMETRY_CAMERA_ALIGNED 1045 -#define IDC_SIT_FRAMES_SPIN 1046 -#define IDC_GEOMETRY_CAMERA_ORIENTED 1046 -#define IDC_SHININESS_EDIT 1047 -#define IDC_GEOMETRY_NORMAL 1047 -#define IDC_SHININESS_SPIN 1048 -#define IDC_GEOMETRY_AABOX 1048 -#define IDC_SELECT_PROJECTILE 1049 -#define IDC_COLLISION_PHYSICAL 1050 -#define IDC_DCT_RATE_EDIT 1051 -#define IDC_SELECT_VIS 1051 -#define IDC_DCT_RATE_SPIN 1052 -#define IDC_GEOMETRY_OBBOX 1052 -#define IDC_LAYER_SPIN 1053 -#define IDC_RANGE_LOW_SPIN 1053 -#define IDC_OBJ_NAME 1053 -#define IDC_DIT_FRAMES_EDIT 1053 -#define IDC_RANGE_HIGH_SPIN 1054 -#define IDC_DIT_FRAMES_SPIN 1054 -#define IDC_NAME_INDEX_SPIN 1054 -#define IDC_MATERIAL_NAMES_GENERATE 1054 -#define IDC_DIT_RATE_EDIT 1055 -#define IDC_GEOMETRY_SHADOW 1055 -#define IDC_DIT_RATE_SPIN 1056 -#define IDC_GEOMETRY_NULL 1056 -#define IDC_SCT_RATE_EDIT 1057 -#define IDC_LOD_EXTENSION_GENERATE 1057 -#define IDC_GEOMETRY_AGGREGATE 1057 -#define IDC_DCT_MAPPING_COMBO 1058 -#define IDC_GEOMETRY_LIGHTGLARE 1058 -#define IDC_GEOMETRY_DAZZLE 1058 -#define IDC_DIT_MAPPING_COMBO 1059 -#define IDC_MAPPING_COMBO 1059 -#define IDC_MAPPING0_COMBO 1059 -#define IDC_SCT_MAPPING_COMBO 1060 -#define IDC_MAPPING1_COMBO 1060 -#define IDC_SCT_RATE_SPIN 1061 -#define IDC_USE_ALPHA_CHECK 1062 -#define IDC_SIT_MAPPING_COMBO 1063 -#define IDC_SIT_RATE_EDIT 1064 -#define IDC_SIT_RATE_SPIN 1065 -#define IDC_DIT_OVER_DCT_CHECK 1067 -#define IDC_SIT_OVER_SCT_CHECK 1068 -#define IDC_USE_SORTING_CHECK 1068 -#define IDC_DIT_OVER_DIG_CHECK 1069 -#define IDC_NO_TRANS 1069 -#define IDC_SIT_OVER_SIG_CHECK 1070 -#define IDC_100_TRANS 1070 -#define IDC_FAST_SPECULAR_AFTER_ALPHA_CHECK 1071 -#define IDC_50_TRANS 1071 -#define IDC_25_TRANS 1072 -#define IDC_MINUS_100_TRANS 1073 -#define IDC_NO_RT_LIGHTING 1074 -#define IDC_VIEWPORT_DISPLAY_CHECK 1075 -#define IDC_COLORMASK_CHECK 1081 -#define IDC_DEPTHMASK_CHECK 1082 -#define IDC_ALPHATEST_CHECK 1083 -#define IDC_DEPTHCOMPARE_COMBO 1085 -#define IDC_DESTBLEND_COMBO 1086 -#define IDC_FOG_COMBO 1087 -#define IDC_PRIGRADIENT_COMBO 1088 -#define IDC_SRCBLEND_COMBO 1089 -#define IDC_DETAILCOLOR_COMBO 1090 -#define IDC_DETAILALPHA_COMBO 1091 -#define IDC_STAGE0_HINT_COMBO 1092 -#define IDC_SECGRADIENT_COMBO 1093 -#define IDC_STAGE1_HINT_COMBO 1095 -#define IDC_STAGE0_FRAMES_EDIT 1096 -#define IDC_STAGE0_FRAMES_SPIN 1097 -#define IDC_STAGE0_RATE_EDIT 1098 -#define IDC_STAGE0_RATE_SPIN 1099 -#define IDC_DCT_BUTTON 1100 -#define IDC_GAMEMTL_TAB 1100 -#define IDC_STAGE0_BUTTON 1101 -#define IDC_SCT_BUTTON 1102 -#define IDC_STAGE1_BUTTON 1102 -#define IDC_DIT_BUTTON 1103 -#define IDC_AMBIENT_COLOR 1103 -#define IDC_SIT_BUTTON 1104 -#define IDC_EMISSIVE_COLOR 1104 -#define IDC_SHADEMODEL_COMBO 1105 -#define IDC_STAGE1_FRAMES_EDIT 1106 -#define IDC_STAGE1_FRAMES_SPIN 1107 -#define IDC_STAGE1_RATE_EDIT 1108 -#define IDC_STAGE1_RATE_SPIN 1109 -#define IDC_DITHERMASK_COMBO 1110 -#define IDC_DIFFUSE_COLOR 1113 -#define IDC_STAGE0_ENABLE 1113 -#define IDC_SPECULAR_COLOR 1114 -#define IDC_STAGE1_ENABLE 1114 -#define IDC_AMBIENT_COEFF 1115 -#define IDC_STAGE1_ANIM_COMBO 1115 -#define IDC_DIFFUSE_COEFF 1116 -#define IDC_PRESET_COMBO 1116 -#define IDC_EMISSIVE_COEFF 1117 -#define IDC_STAGE0_ANIM_COMBO 1117 -#define IDC_SPECULAR_COEFF 1118 -#define IDC_GEOMETRY_TWO_SIDED 1119 -#define IDC_COLLISION_VIS 1120 -#define IDC_GEOMETRY_HIDE 1121 -#define IDC_GEOMETRY_ZNORMALS 1122 -#define IDC_GEOMETRY_VERTEX_ALPHA 1123 -#define IDC_BASE_NAME_EDIT 1124 -#define IDC_GEOMETRY_CAST_SHADOW 1124 -#define IDC_PREFIX_EDIT 1125 -#define IDC_COLLISION_CAMERA 1125 -#define IDC_GEOMETRY_SHATTERABLE 1126 -#define IDC_SUFFIX_EDIT 1126 -#define IDC_GEOMETRY_NPATCH 1127 -#define IDC_AFFECT_ALL_RADIO 1131 -#define IDC_AFFECT_SELECTED_RADIO 1132 -#define IDC_LOD_INDEX_EDIT 1133 -#define IDC_LOD_INDEX_SPIN 1134 -#define IDC_ASSIGN_COLLISION_BITS_CHECK 1135 -#define IDC_ASSIGN_NAMES_CHECK 1137 -#define IDC_COLLISION_PROJECTILE 1138 -#define IDC_COPY_SPECULAR_DIFFUSE 1139 -#define IDC_ASSIGN_PREFIX_CHECK 1139 -#define IDC_COLLISION_VEHICLE 1139 -#define IDC_MAPPING_ARGS_EDIT 1140 -#define IDC_ASSIGN_SUFFIX_CHECK 1140 -#define IDC_MAPPING0_ARGS_EDIT 1140 -#define IDC_MAPPING1_ARGS_EDIT 1141 -#define IDC_SHADER_DEFAULTS_BUTTON 1143 -#define IDC_STATE_SLIDER 1145 -#define IDC_CURRENT_SET_SLIDER 1146 -#define IDC_CURRENT_SET_STATIC 1147 -#define IDC_VERTEX_COLOR 1149 -#define IDC_RESTORE_BUTTON 1150 -#define IDC_MANUALAPPLY 1151 -#define IDC_SURFACE_TYPE_COMBO 1152 -#define IDC_EXPORT_MESH_SMOOTH_CHECK 1153 -#define IDC_LOCK_SETS 1154 -#define IDC_EXPORT_MESH_AABTREES 1154 -#define IDC_TEXTURE_BUTTON 1155 -#define IDC_EXPORT_MESH_MAT_TO_TEXTURE 1155 -#define IDC_AMOUNT_EDIT 1156 -#define IDC_EXPORT_MESH_OPTIMIZE 1156 -#define IDC_AMOUNT_SPIN 1157 -#define IDC_DAMREG_INDEX_EDIT 1161 -#define IDC_DAMREG_INDEX_SPIN 1162 -#define IDC_DIRECTORY 1163 -#define IDC_STAGE0UVCHAN_EDIT 1163 -#define IDC_BROWSE 1164 -#define IDC_STAGE0UVCHAN_SPIN 1164 -#define IDC_RECURSIVE 1165 -#define IDC_STAGE1UVCHAN_EDIT 1165 -#define IDC_LOD_COUNT 1166 -#define IDC_STAGE1UVCHAN_SPIN 1166 -#define IDC_LOD_OFFSET 1167 -#define IDC_LOD_AS_COPY 1168 -#define IDC_LOD_AS_INSTANCE 1169 -#define IDC_LOD_AS_REFERENCE 1170 -#define IDC_DAMAGE_COUNT 1171 -#define IDC_DAMAGE_OFFSET 1172 -#define IDC_DAMAGE_AS_COPY 1173 -#define IDC_PS2_PRESET_COMBO 1173 -#define IDC_DAMAGE_AS_INSTANCE 1174 -#define IDC_COMPATIBLE 1174 -#define IDC_DAMAGE_AS_REFERENCE 1175 -#define IDC_ALPHA_EDIT 1175 -#define IDC_A_COMBO 1176 -#define IDC_B_COMBO 1177 -#define IDC_EXPORT_STANDARD_MATERIALS 1177 -#define IDC_C_COMBO 1178 -#define IDC_EXPORT_UTILITIES_GROUP 1178 -#define IDC_D_COMBO 1179 -#define IDC_COMPRESS_ANIMATION_CHECK 1179 -#define IDC_ALPHA_SPIN 1180 -#define IDC_ALPHA_SPIN2 1181 -#define IDC_REDUCE_ANIMATION_CHECK 1188 -#define IDC_REDUCE_ANIMATION_COMBO 1190 -#define IDC_ANIMATION_FPS_STATIC 1191 -#define IDC_COMPRESS_ANIMATION_FLAVOR_COMBO 1192 -#define IDC_MAX_TRANS_ERROR_EDIT 1193 -#define IDC_MAX_ROT_ERROR_EDIT 1194 -#define IDC_ANIM_COMPRESS_PROGRESS 1196 -#define IDC_ANIM_LOG_RICHEDIT 1198 -#define IDC_VIEWLOG_CHECK 1199 -#define IDC_VALUE 1200 -#define IDC_LABEL 1201 -#define IDC_ALPHA_CHECKBOX 1204 -#define IDC_DAZZLE_COMBO 1205 -#define IDC_CREATE_SETTINGS_FLOATER 1208 -#define IDC_RADIO1 1212 -#define IDC_HLOD_RADIO 1212 -#define IDC_RADIO2 1213 -#define IDC_COMPRESSION_SETTINGS 1213 -#define IDC_ANIM_RADIO 1213 -#define IDC_RADIO3 1214 -#define IDC_MESH_RADIO 1214 -#define IDC_RADIO4 1215 -#define IDC_SKELETON_RADIO 1215 -#define IDC_GROUP_BOX 1216 -#define IDC_RADIO5 1217 -#define IDC_TERRAIN_RADIO 1217 -#define IDC_USE_SKELETON_CHECK 1217 -#define IDC_RADIO6 1218 -#define IDC_ANIM_HLOD_RADIO 1218 -#define IDC_REVIEW_LOG 1219 -#define IDC_ENABLE_SORT_LEVEL 1220 -#define IDC_SORT_LEVEL 1221 -#define IDC_SORT_LEVEL_SPIN 1222 -#define IDC_GRIDDIM_EDIT 1223 -#define IDC_GRIDDIM_SPIN 1224 -#define IDS_SKIN_CLASS_NAME 60011 -#define IDS_SKIN_OBJECT_NAME 60012 -#define IDS_SKIN 60013 -#define IDS_SKIN_PARAMETERS 60014 -#define IDS_SKIN_INFO 60015 -#define IDS_BONE_INFLUENCE_PARAMS 60016 -#define IDS_SOT2 60017 -#define IDS_SKELETON_PARAMETERS 60018 -#define IDS_PICK_BONE_DIALOG_TITLE 60019 -#define IDS_PICK_BONE_BUTTON_TEXT 60020 -#define IDS_MULTIPLE_OBJECTS 60021 -#define IDS_NO_OBJECT 60022 -#define IDS_SPECULAR_COLOR 60023 -#define IDS_AMBIENT_COLOR 60024 -#define IDS_EMISSIVE_COLOR 60027 -#define IDS_MATERIAL_HINTS 60028 -#define IDS_PSX_OPTIONS 60029 -#define IDS_UV_MAPPING 60030 -#define IDS_ENVIRONMENT_MAPPING 60031 -#define IDS_PASS_COUNT 60032 -#define IDS_PASS_SETTINGS 60033 -#define IDS_PUBLISH 60034 -#define IDS_DISPLAY 60035 -#define IDS_RESIZE 60036 -#define IDS_NO_MIPMAP 60037 -#define IDS_CLAMP_U 60038 -#define IDS_CLAMP_V 60039 -#define IDS_ALPHA_BITMAP 60040 -#define IDS_SURFACE_TYPE 60041 -#define IDS_DISPLACEMENT_MAP 60042 -#define IDS_ALPHA_MODIFIER_CLASS 60043 -#define IDS_PS2_GAMEMTL 60044 -#define IDS_PC_TO_PS2_MAT_CONVERTER 60045 -#define IDS_NO_LOD 60046 -#define IDS_W3DUTILITY_SETTINGS 60047 -#define IDS_W3DUTILITY_TOOLS 60048 -#define IDS_GRIDSNAPMODIFIER 60049 -#define IDS_GRIDSNAP_TITLE 60050 -#define IDS_GRID_DIMENSION 60051 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 160 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1225 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/simpdib.cpp b/Generals/Code/Tools/WW3D/max2w3d/simpdib.cpp deleted file mode 100644 index 4558c9a9f0..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/simpdib.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/simpdib.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/14/97 3:07p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "simpdib.h" - - -SimpleDIBClass::SimpleDIBClass(HWND hwnd,int width,int height,PaletteClass & pal): - IsZombie(false), - Info(NULL), - Handle(0), - Pixels(NULL), - Width(width), - Height(height), - PixelBase(NULL), - Pitch(NULL) -{ - // Allocate a BITMAPINFO structure - Info = (BITMAPINFO *) new char [sizeof(BITMAPINFO) + 256*sizeof(RGBQUAD)]; - - if (Info == NULL) { - IsZombie = true; - return; - } - - // Describe the type of DIB we want. - Info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - Info->bmiHeader.biWidth = width; - Info->bmiHeader.biHeight = -height; //ask for a top-down dib. - Info->bmiHeader.biPlanes = 1; - Info->bmiHeader.biBitCount = 8; - Info->bmiHeader.biCompression = BI_RGB; - Info->bmiHeader.biSizeImage = 0; - Info->bmiHeader.biXPelsPerMeter = 0; - Info->bmiHeader.biYPelsPerMeter = 0; - Info->bmiHeader.biClrUsed = 256; - Info->bmiHeader.biClrImportant = 256; - - // Fill in the DIB's palette. - for (int i=0; i<256; i++) { - Info->bmiColors[i].rgbBlue = (unsigned char)pal[i].Get_Blue(); - Info->bmiColors[i].rgbGreen = (unsigned char)pal[i].Get_Green(); - Info->bmiColors[i].rgbRed = (unsigned char)pal[i].Get_Red(); - Info->bmiColors[i].rgbReserved = 0; - } - - // Create the DIB. - HDC hdc = GetDC(hwnd); - Handle = CreateDIBSection(hdc, Info, DIB_RGB_COLORS,(void**)&Pixels, NULL, 0); - ReleaseDC(hwnd, hdc); - - if (!Handle) { - IsZombie = true; - return; - } - - Width = Info->bmiHeader.biWidth; - Height = abs(Info->bmiHeader.biHeight); - Pitch = (Width + 3) & 0xfffffffC; - - // Check if the DIB is bottom-up or top-down. - // (it better be top-down, thats what I'm asking for!!!) - if (Info->bmiHeader.biHeight > 0) { - - // bottom-up DIB - PixelBase = (Pixels + (Height - 1) * Width); - Pitch = -Pitch; - - } else { - - // top-down DIB - PixelBase = Pixels; - Pitch = Pitch; - } -} - -SimpleDIBClass::~SimpleDIBClass(void) -{ - if (Info) delete [] Info; - if (Handle) DeleteObject(Handle); -} - - -void SimpleDIBClass::Clear(unsigned char color) -{ - if (Pixels) { - memset(Pixels, color, abs(Pitch)*Height); - } -} - -void SimpleDIBClass::Set_Pixel(int i,int j,unsigned char color) -{ - if ((i < 0) || (j < 0) || (i >= Width) || (j >= Height)) { - return; - } - - *(PixelBase + j*Pitch + i) = color; -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/simpdib.h b/Generals/Code/Tools/WW3D/max2w3d/simpdib.h deleted file mode 100644 index ceb44c6e3b..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/simpdib.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/simpdib.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/14/97 3:07p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef SIMPDIB_H -#define SIMPDIB_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#include - -#ifndef WIN_H -#include "win.h" -#endif - -#ifndef PALETTE_H -#include "palette.h" -#endif - -class SimpleDIBClass -{ -public: - - SimpleDIBClass(HWND hwnd,int width, int height,PaletteClass & pal); - ~SimpleDIBClass(void); - - HBITMAP Get_Handle() { return Handle; } - int Get_Width(void) { return Width; } - int Get_Height(void) { return Height; } - - void Clear(unsigned char color); - void Set_Pixel(int i,int j,unsigned char color); - -private: - - bool IsZombie; // object constructor failed, its a living-dead object! - BITMAPINFO * Info; // info used in creating the dib + the palette. - HBITMAP Handle; // handle to the actual dib - unsigned char * Pixels; // address of memory containing the pixel data - int Width; // width of the dib - int Height; // height of the dib - unsigned char * PixelBase; // address of upper left pixel (this and DIBPitch abstract up/down DIBS) - int Pitch; // offset from DIBPixelBase to next row (can be negative for bottom-up DIBS) - -}; - - -#endif /*SIMPDIB_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/skin.cpp b/Generals/Code/Tools/WW3D/max2w3d/skin.cpp deleted file mode 100644 index 65a1f251aa..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/skin.cpp +++ /dev/null @@ -1,1916 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/skin.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 4/24/01 5:15p $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "skin.h" -#include "dllmain.h" -#include "max.h" -#include "simpmod.h" -#include "simpobj.h" -#include "resource.h" - -#include "skindata.h" -#include "bpick.h" -#include "namedsel.h" -#include "boneicon.h" - -#if defined W3D_MAX4 //defined as in the project (.dsp) -static GenSubObjType _SubObjectTypeVertex(1); -#endif - -/* -** Static functions -*/ -static BOOL CALLBACK _sot_dialog_proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); -static BOOL CALLBACK _skeleton_dialog_thunk(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); -static BOOL CALLBACK _bone_influence_dialog_thunk(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); -static TriObject * Get_Tri_Object(TimeValue t,ObjectState & os,Interval & valid,BOOL & needsdel); -static float Bone_Distance(INode * bone,TimeValue time,const Point3 & vertex); - -/* -** Static variables -*/ -HWND SkinWSMObjectClass::SotHWND = NULL; -HWND SkinWSMObjectClass::SkeletonHWND = NULL; -HWND SkinWSMObjectClass::BoneListHWND = NULL; -IObjParam * SkinWSMObjectClass::InterfacePtr = NULL; -ICustButton * SkinWSMObjectClass::AddBonesButton = NULL; -ICustButton * SkinWSMObjectClass::RemoveBonesButton = NULL; -ISpinnerControl * SkinWSMObjectClass::BasePoseSpin = NULL; - - -/******************************************************************************* -** -** Class Descriptor for SkinWSMObjectClass -** -*******************************************************************************/ -class SkinWSMObjectClassDesc:public ClassDesc -{ -public: - - int IsPublic() { return 1; } - void * Create(BOOL loading = FALSE) { return new SkinWSMObjectClass; } - const TCHAR * ClassName() { return _T("WWSkin"); } - SClass_ID SuperClassID() { return WSM_OBJECT_CLASS_ID; } - Class_ID ClassID() { return SKIN_OBJ_CLASS_ID; } - const TCHAR* Category() { return _T("Westwood Space Warps"); } -}; - -static SkinWSMObjectClassDesc _SkinWSMObjectDesc; -ClassDesc * Get_Skin_Obj_Desc() { return &_SkinWSMObjectDesc; } - - -/******************************************************************************* -** -** Class Descriptor for the SkinModifier -** -*******************************************************************************/ -class SkinModClassDesc:public ClassDesc -{ -public: - - int IsPublic() { return 0; } - void * Create(BOOL loading = FALSE) { return new SkinModifierClass; } - const TCHAR * ClassName() { return _T("WWSkin"); } - SClass_ID SuperClassID() { return WSM_CLASS_ID; } - Class_ID ClassID() { return SKIN_MOD_CLASS_ID; } - const TCHAR * Category() { return _T("Westwood Space Warps"); } -}; - -static SkinModClassDesc _SkinModDesc; -ClassDesc * Get_Skin_Mod_Desc() { return &_SkinModDesc; } - - - -/******************************************************************************* -** -** SkinWSMObjectCreateCallback -** A class derived from CreateMouseCallBack to handle -** the user input during the creation phase of the SkinWSMObject. -** -*******************************************************************************/ -class SkinWSMObjectCreateCallBack : public CreateMouseCallBack -{ -public: - int proc( ViewExp * vpt,int msg, int point, int flags, IPoint2 m, Matrix3 & mat) - { - if (msg == MOUSE_POINT) { - Point3 pos = vpt->GetPointOnCP(m); - mat.IdentityMatrix(); - mat.SetTrans(pos); - return CREATE_STOP; - } - return TRUE; - } -}; - -static SkinWSMObjectCreateCallBack _SkinCreateCB; - -/******************************************************************************* -** -** SkinWSMObjectClass -** -*******************************************************************************/ -SkinWSMObjectClass::SkinWSMObjectClass() -{ - /* - ** Initialize class variables to default state! - */ - MeshBuilt = FALSE; - BoneSelectionMode = BONE_SEL_MODE_NONE; - BoneTab.SetCount(0); - BasePoseFrame = 0; - - pblock = NULL; -} - -SkinWSMObjectClass::~SkinWSMObjectClass(void) -{ - assert(!((InterfacePtr == NULL) && (SotHWND != NULL))); - if (SotHWND != NULL) { - InterfacePtr->UnRegisterDlgWnd(SotHWND); - InterfacePtr->DeleteRollupPage(SotHWND); - SotHWND = NULL; - } - - assert(!((InterfacePtr == NULL) && (SkeletonHWND != NULL))); - if (SkeletonHWND != NULL) { - InterfacePtr->UnRegisterDlgWnd(SkeletonHWND); - InterfacePtr->DeleteRollupPage(SkeletonHWND); - SkeletonHWND = NULL; - } -} - -void SkinWSMObjectClass::BeginEditParams(IObjParam *ip, ULONG flags,Animatable *prev) -{ - SimpleWSMObject::BeginEditParams(ip,flags,prev); - - /* - ** save off a copy of the interface pointer - */ - InterfacePtr = ip; - - /* - ** Install the "supports objects of type" rollup - */ - if (SotHWND == NULL) { - SotHWND = ip->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_SKIN_SOT), - _sot_dialog_proc, - Get_String(IDS_SOT), - (LPARAM)InterfacePtr, - APPENDROLL_CLOSED); - } else { - SetWindowLong(SotHWND,GWL_USERDATA,(LPARAM)ip); - } - - /* - ** Install the skeleton rollup - */ - if (SkeletonHWND == NULL) { - SkeletonHWND = InterfacePtr->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_SKELETON_PARAMETERS), - _skeleton_dialog_thunk, - Get_String(IDS_SKELETON_PARAMETERS), - (LPARAM)this, - 0); - } else { - SetWindowLong(SkeletonHWND,GWL_USERDATA,(LPARAM)this); - } - - Update_Bone_List(); -} - -void SkinWSMObjectClass::EndEditParams(IObjParam *ip, ULONG flags,Animatable *next) -{ - SimpleWSMObject::EndEditParams(ip,flags,next); - - if (flags & END_EDIT_REMOVEUI) { - /* - ** Remove the Sot rollup - */ - if (SotHWND != NULL) { - InterfacePtr->UnRegisterDlgWnd(SotHWND); - InterfacePtr->DeleteRollupPage(SotHWND); - SotHWND = NULL; - } - - /* - ** Remove the info rollup - */ - if (SkeletonHWND != NULL) { - InterfacePtr->UnRegisterDlgWnd(SkeletonHWND); - InterfacePtr->DeleteRollupPage(SkeletonHWND); - SkeletonHWND = NULL; - } - } - - /* - ** get rid of our copy of the interface pointer - */ - InterfacePtr = NULL; -} - -RefTargetHandle SkinWSMObjectClass::Clone(RemapDir & remap) -{ - /* - ** create another SkinWSMObject and return it. - */ - SkinWSMObjectClass * sobj = new SkinWSMObjectClass(); - return(sobj); -} - -RefTargetHandle SkinWSMObjectClass::GetReference(int i) -{ - /* - ** return reference "i". If i==0, the reference belongs - ** to SimpleWSMObject so thunk down to it. - */ - if (i < SimpleWSMObject::NumRefs()) { - return SimpleWSMObject::GetReference(i); - } - - /* - ** The rest of the references are ours. - */ - int boneidx = To_Bone_Index(i); - return BoneTab[boneidx]; -} - -void SkinWSMObjectClass::SetReference(int i, RefTargetHandle rtarg) -{ - if (i < SimpleWSMObject::NumRefs()) { - SimpleWSMObject::SetReference(i,rtarg); - } else { - int boneidx = To_Bone_Index(i); - assert(boneidx >= 0); - assert(boneidx < BoneTab.Count()); - BoneTab[boneidx] = (INode *)rtarg; - } -} - -RefResult SkinWSMObjectClass::NotifyRefChanged(Interval changeInt,RefTargetHandle hTarget,PartID& partID, RefMessage message) -{ - int i; - switch (message) { - - case REFMSG_TARGET_DELETED: - for (i=0; isetVerts(a, b, c); - f->setSmGroup(0); - f->setEdgeVisFlags(1,1,1); -} - -void SkinWSMObjectClass::User_Picked_Bone(INode * node) -{ - // TODO: Undo/Redo! - switch (BoneSelectionMode) { - case BONE_SEL_MODE_ADD: - Add_Bone(node); - break; - - case BONE_SEL_MODE_REMOVE: - Remove_Bone(node); - break; - - default: - assert(0); - } - - Set_Bone_Selection_Mode(BONE_SEL_MODE_NONE); - Update_Bone_List(); -} - -void SkinWSMObjectClass::User_Picked_Bones(INodeTab & nodetab) -{ - // TODO: Undo/Redo! - switch (BoneSelectionMode) { - case BONE_SEL_MODE_ADD_MANY: - Add_Bones(nodetab); - break; - - case BONE_SEL_MODE_REMOVE_MANY: - Remove_Bones(nodetab); - break; - - default: - assert(0); - } - - Set_Bone_Selection_Mode(BONE_SEL_MODE_NONE); - Update_Bone_List(); -} - -void SkinWSMObjectClass::Set_Bone_Selection_Mode(int mode) -{ - assert(mode >= BONE_SEL_MODE_NONE); - assert(mode <= BONE_SEL_MODE_REMOVE_MANY); - - /* - ** store the selection mode - */ - BoneSelectionMode = mode; - - /* - ** update the dialog box buttons - */ - AddBonesButton->SetCheck(mode == BONE_SEL_MODE_ADD_MANY); - RemoveBonesButton->SetCheck(mode == BONE_SEL_MODE_REMOVE_MANY); -} - -int SkinWSMObjectClass::Add_Bone(INode * node) -{ - int refidx; - int boneidx; - - /* - ** If we already have this bone, just return - */ - boneidx = Find_Bone(node); - if (boneidx != -1) { - return boneidx; - } - - /* - ** Otherwise, look for a NULL bone and we'll re-use - ** its slot. This happens when a user removes a bone or - ** a bone in the scene is deleted. - */ - boneidx = Find_Bone(NULL); - if (boneidx != -1) { - refidx = To_Ref_Index(boneidx); - MakeRefByID(FOREVER,refidx,node); - return boneidx; - } - - /* - ** If we made it here, add the bone to the end of the - ** reference array. - */ - BoneTab.Append(1,&node); - boneidx = BoneTab.Count() - 1; - refidx = To_Ref_Index(boneidx); - MakeRefByID(FOREVER,refidx,node); - return boneidx; -} - -void SkinWSMObjectClass::Add_Bones(INodeTab & nodetab) -{ - /* - ** Add each bone individually - */ - for (int i=0; iGetName()); - } - } -} - -int SkinWSMObjectClass::Find_Bone(INode * node) -{ - for (int i=0; i 0) { - isave->BeginChunk(NUM_BONES_CHUNK); - isave->Write(&numbones,sizeof(ULONG),&nb); - isave->EndChunk(); - } - return IO_OK; -} - -IOResult SkinWSMObjectClass::Load(ILoad * iload) -{ - SimpleWSMObject::Load(iload); - - IOResult res; - ULONG nb; - int level = -1; - - while (IO_OK==(res=iload->OpenChunk())) { - - switch (iload->CurChunkID()) { - - case NUM_BONES_CHUNK: { - ULONG numbones; - res = iload->Read(&numbones,sizeof(numbones),&nb); - BoneTab.SetCount(numbones); - for (int i=0; iCloseChunk(); - - if (res!=IO_OK) { - return res; - } - } - return IO_OK; -} - - -int SkinWSMObjectClass::Find_Closest_Bone(const Point3 & vertex) -{ - float mindist = 10000.0f; - int minindex = -1; - TimeValue basetime = Get_Base_Pose_Time(); - - for (int boneidx = 0; boneidx < BoneTab.Count(); boneidx++) { - - if (BoneTab[boneidx] == NULL) continue; - - float bonedist = Bone_Distance(BoneTab[boneidx],basetime,vertex); - if (bonedist < mindist) { - mindist = bonedist; - minindex = boneidx; - } - } - - return minindex; -} - - - -/******************************************************************************* -** -** SkinModifierClass -** -*******************************************************************************/ - -SkinModifierClass::SkinModifierClass(void) -{ - Default_Init(); -} - -SkinModifierClass::SkinModifierClass(INode * node,SkinWSMObjectClass * skin_obj) -{ - Default_Init(); - - /* - ** Make the reference to the space warp node. - */ - MakeRefByID(FOREVER,NODE_REF,node); - - /* - ** Make reference to the WSMObject - */ - MakeRefByID(FOREVER,OBJ_REF,skin_obj); - -} - -void SkinModifierClass::Default_Init(void) -{ - SubObjSelLevel = VERTEX_SEL_LEVEL; - WSMObjectRef = NULL; - WSMNodeRef = NULL; - InterfacePtr = NULL; - - BoneInfluenceHWND = NULL; - LinkButton = NULL; - LinkByNameButton = NULL; - AutoLinkButton = NULL; - UnLinkButton = NULL; -} - - -RefTargetHandle SkinModifierClass::Clone(RemapDir & remap) -{ - SkinModifierClass * newmod = new SkinModifierClass(WSMNodeRef,(SkinWSMObjectClass *)WSMObjectRef); - return newmod; -} - - -void SkinModifierClass::BeginEditParams(IObjParam * ip, ULONG flags,Animatable * prev) -{ - static int i=0; - - i++; - - /* - ** Grab a copy of the interface pointer - */ - InterfacePtr = ip; - - /* - ** allocate the selection command mode for use in vertex selection - */ - SelectMode = new SelectModBoxCMode(this,InterfacePtr); - - /* - ** register the desired sub-object selection types. - */ - const TCHAR * ptype[] = { "Vertices" }; -#if defined W3D_MAX4 //defined as in the project (.dsp) - InterfacePtr->SetSubObjectLevel(1); -#else - //---This call is obsolete from version 4. - InterfacePtr->RegisterSubObjectTypes( ptype, 1); -#endif - /* - ** Restore the selection level. - */ - ip->SetSubObjectLevel(SubObjSelLevel); - -} - - -void SkinModifierClass::EndEditParams(IObjParam *ip, ULONG flags,Animatable *next) -{ - /* - ** just checking... - */ - assert(ip == InterfacePtr); - - /* - ** Make sure we clear out the pick mode - */ - InterfacePtr->ClearPickMode(); - - /* - ** remove and deallocate the selection command mode - */ - InterfacePtr->DeleteMode(SelectMode); - if (SelectMode ) delete SelectMode; - SelectMode = NULL; - - /* - ** Remove the rollup window(s) if needed - */ - if (flags & END_EDIT_REMOVEUI) { - Remove_Bone_Influence_Dialog(); - } - - /* - ** Make sure we don't hang onto an invalid interface - */ - InterfacePtr = NULL; -} - -Interval SkinModifierClass::Get_Validity(TimeValue t) -{ - /* - ** Start with an infinite interval and chop it down - ** using the validity intervals of each of the controlling bones - */ - Interval valid = FOREVER; - - /* - ** Now intersect the validity with the validities of all of - ** the controlling bones. - */ - SkinWSMObjectClass * obj = (SkinWSMObjectClass *)Get_WSMObject(); - -// for (int i=0; iNum_Bones(); i++) { -// valid &= obj->Get_Bone(i)->tmValid(); //TODO: is this right? -// } - -// return valid; - return Interval(t,t+1); //KLUDGE - only valid for this frame -} - -RefTargetHandle SkinModifierClass::GetReference(int i) -{ - switch (i) { - case OBJ_REF: return WSMObjectRef; - case NODE_REF: return WSMNodeRef; - default: return NULL; - } -} - -void SkinModifierClass::SetReference(int i, RefTargetHandle rtarg) -{ - switch (i) { - case OBJ_REF: WSMObjectRef = (SkinWSMObjectClass *)rtarg; break; - case NODE_REF: WSMNodeRef = (INode *)rtarg; break; - } -} - -RefResult SkinModifierClass::NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message) -{ - switch (message) { - - case REFMSG_TARGET_DELETED: - - /* - ** This means the WSM node is being deleted. As a result, - ** we must delete ourselves. - */ - DeleteMe(); // also deletes all refs and - // sends REFMSG_TARGET_DELETED to all Dependents - return REF_STOP; - } - - return(REF_SUCCEED); - -} - -void SkinModifierClass::ModifyObject(TimeValue t, ModContext & mc, ObjectState * os, INode * node) -{ - /* - ** Get a TriObject from the object state - */ - assert(os->obj->IsSubClassOf(triObjectClassID)); - TriObject *triobj = (TriObject *)os->obj; - - /* - ** Get the skin data from the ModContext. - */ - SkinDataClass * skindata = (SkinDataClass *)mc.localData; - - /* - ** If there is no skin data, allocate it - ** Also, do an initial auto attach. - */ - if (skindata == NULL) { - mc.localData = skindata = new SkinDataClass(&triobj->mesh); - } - - if (!skindata->IsValid()) { - skindata->Validate(&triobj->mesh); - } - - /* - ** If in vertex selection mode, tell the mesh to display the - ** selected vertices and turn on vertex tick marks. Otherwise - ** make sure vertex tick marks are off. - */ - if (SubObjSelLevel == VERTEX_SEL_LEVEL) { - triobj->mesh.vertSel = skindata->VertSel; - triobj->mesh.SetDispFlag(DISP_VERTTICKS|DISP_SELVERTS); - - if (triobj->mesh.selLevel != MESH_VERTEX) { - triobj->mesh.selLevel = MESH_VERTEX; - } - } else { - triobj->mesh.selLevel = MESH_OBJECT; - triobj->mesh.ClearDispFlag(DISP_VERTTICKS|DISP_SELVERTS); - } - - /* - ** Loop through the points in the deformable object - */ - for (int vidx = 0; vidx < triobj->NumPoints(); vidx++) { - - - // TODO: Allow multiple bone influences here... - // issues - UI to set the weights, rebalance weights whenever - // a bone is deleted, should also then never get NULL bones - // and remove the need to check for NULL bones in this routine... - - /* - ** Get a pointer to the bone that this vertex is attached to - */ - InfluenceStruct * inf = &(skindata->VertData[vidx]); - - int boneidx = inf->BoneIdx[0]; - if ((boneidx != -1) && (boneidx < WSMObjectRef->Num_Bones())) { - - INode * bone = WSMObjectRef->Get_Bone(inf->BoneIdx[0]); - - if (bone == NULL) { - /* - ** this bone has gone away for some reason so - ** clear this vert's bone influence index - */ - inf->BoneIdx[0] = -1; - - } else { - - /* - ** Ok, got the bone, now transform the point and - ** give it back to the mesh - */ - Point3 pnew; - Matrix3 tm; - - pnew = triobj->GetPoint(vidx); - - if (os->GetTM()) { - tm = *(os->GetTM()); - } else { - tm.IdentityMatrix(); - } - - pnew = tm * pnew; - - TimeValue basetime = WSMObjectRef->Get_Base_Pose_Time(); - Matrix3 basetm = bone->GetObjectTM(basetime); - Matrix3 curtm = bone->GetObjectTM(t); - pnew = (pnew * Inverse(basetm)) * curtm; - - pnew = Inverse(tm) * pnew; - - triobj->SetPoint(vidx,pnew); - } - } - } - - /* - ** Tell the object that points were changed - */ - triobj->PointsWereChanged(); - - /* - ** Set the validity of the updated geometry data - */ - triobj->UpdateValidity(GEOM_CHAN_NUM,Get_Validity(t)); -} - -IOResult SkinModifierClass::Save(ISave * isave) -{ - ULONG nb; - Modifier::Save(isave); - - /* - ** Save the sub object selection level - */ - short sl = SubObjSelLevel; - isave->BeginChunk(SEL_LEVEL_CHUNK); - isave->Write(&sl,sizeof(short),&nb); - isave->EndChunk(); - - return IO_OK; -} - -IOResult SkinModifierClass::Load(ILoad * iload) -{ - Modifier::Load(iload); - - IOResult res; - ULONG nb; - int level = -1; - - while (IO_OK==(res=iload->OpenChunk())) { - - switch (iload->CurChunkID()) { - - case SEL_LEVEL_CHUNK: { - short sl; - res = iload->Read(&sl,sizeof(short),&nb); - SubObjSelLevel = sl; - } - break; - } - - iload->CloseChunk(); - - if (res!=IO_OK) { - return res; - } - } - return IO_OK; -} - -IOResult SkinModifierClass::SaveLocalData(ISave *isave, LocalModData *ld) -{ - SkinDataClass * skindata = (SkinDataClass *)ld; - - return skindata->Save(isave); -} - -IOResult SkinModifierClass::LoadLocalData(ILoad *iload, LocalModData **pld) -{ - /* - ** Create a new SkinDataClass - */ - if (*pld==NULL) { - *pld = (SkinDataClass *) new SkinDataClass(); - } - SkinDataClass * newskin = (SkinDataClass *)*pld; - - /* - ** Initialize it from ILoad... - */ - return newskin->Load(iload); -} - - -void SkinModifierClass::ActivateSubobjSel(int level, XFormModes & modes) -{ - /* - ** Storing the current sub-object selection level - */ - SubObjSelLevel = level; - - /* - ** Set the appropriate command mode. We only want selection. - */ - switch (SubObjSelLevel) - { - case OBJECT_SEL_LEVEL: - Remove_Bone_Influence_Dialog(); - break; - - case VERTEX_SEL_LEVEL: // Modifying Vertices - modes = XFormModes(NULL,NULL,NULL,NULL,NULL,SelectMode); - Install_Bone_Influence_Dialog(); - break; - } - - /* - ** Put our named subobject selection sets into the drop down list - */ - Create_Named_Selection_Sets(); - - /* - ** Notify our dependents that the subselection type, - ** and the display have changed - */ - NotifyDependents(FOREVER, PART_SUBSEL_TYPE|PART_DISPLAY, REFMSG_CHANGE); - - /* - ** Notify the pipeline that the selection level has changed. - */ - InterfacePtr->PipeSelLevelChanged(); - - /* - ** Notify our dependents that the selection channel, - ** display attributes, and subselection type channels have changed - */ - NotifyDependents(FOREVER, SELECT_CHANNEL|DISP_ATTRIB_CHANNEL|SUBSEL_TYPE_CHANNEL, REFMSG_CHANGE); -} - -int SkinModifierClass::HitTest -( - TimeValue t, - INode * inode, - int type, - int crossing, - int flags, - IPoint2 * p, - ViewExp * vpt, - ModContext * mc -) -{ - Interval valid = FOREVER; - int needsdel; - int savedLimits; - int res = 0; - HitRegion hr; - Matrix3 mat; - - MakeHitRegion(hr,type, crossing,4,p); - mat = inode->GetObjectTM(t); - - /* - ** Set up the graphics window to do the hit test - */ - GraphicsWindow *gw = vpt->getGW(); - gw->setHitRegion(&hr); - gw->setTransform(mat); - gw->setRndLimits(((savedLimits = gw->getRndLimits()) | GW_PICK) & ~GW_ILLUM); - - if (1 /*IgnoreBackfaces*/) { - gw->setRndLimits(gw->getRndLimits() | GW_BACKCULL); - } else { - gw->setRndLimits(gw->getRndLimits() & ~GW_BACKCULL); - } - - gw->clearHitCode(); - - /* - ** Do the hit test! - */ - SubObjHitList hitlist; - MeshSubHitRec * rec; - - ObjectState os = inode->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - res = tobj->mesh.SubObjectHitTest(gw,gw->getMaterial(),&hr,flags | SUBHIT_VERTS,hitlist); - - /* - ** Record all of the hits - */ - rec = hitlist.First(); - while (rec) - { - /* - ** rec->index is the index of vertex which was hit! - ** Remember that we are always turning on vertex hit testing; - ** if we were testing for edges, index would be the edge index. - */ - vpt->LogHit(inode,mc,rec->dist,rec->index,NULL); - rec = rec->Next(); - } - - /* - ** Cleanup - */ - gw->setRndLimits(savedLimits); - - if (needsdel) { - tobj->DeleteThis(); - } - - return res; -} - -void SkinModifierClass::SelectSubComponent(HitRecord *hitRec, BOOL selected, BOOL all, BOOL invert) -{ - SkinDataClass * skindata = NULL; - int count = 0; - - switch (SubObjSelLevel) { - - case VERTEX_SEL_LEVEL: - - while (hitRec) { - - skindata = (SkinDataClass *)hitRec->modContext->localData; - - /* - ** Undo/Redo functionality - */ -#if 0 - if (theHold.Holding() && !SelData->held) { - theHold.Put(new SubSelRestore(this,SelData)); - } - theHold.Accept(_T("Select Vertex")); -#endif - - BitArray * array = &(skindata->VertSel); - - if (all & invert) { - - /* - ** hitRec->hitInfo is the MeshSubHitRec::index that was stored in the - ** HitTest method through LogHit - */ - if ((*array)[hitRec->hitInfo]) { - array->Clear(hitRec->hitInfo); - } else { - array->Set(hitRec->hitInfo,selected); - } - } else { - array->Set(hitRec->hitInfo,selected); - } - - if (!all) break; - hitRec = hitRec->Next(); - } - break; - } - - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); -} - -void SkinModifierClass::ClearSelection(int selLevel) -{ - int needsdel = 0; - Interval valid = FOREVER; - ModContextList mcList; - INodeTab nodes; - - if (!InterfacePtr ) return; - - InterfacePtr->GetModContexts(mcList,nodes); - InterfacePtr->ClearCurNamedSelSet(); - - for (int i = 0; i < mcList.Count(); i++) { - - SkinDataClass * skindata = (SkinDataClass *)mcList[i]->localData; - - if (skindata==NULL) continue; - - ObjectState os = nodes[i]->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - - switch (SubObjSelLevel) { -#if 0 - case OBJECT_SEL_LEVEL: - assert(0); - return; -#endif - - case VERTEX_SEL_LEVEL: -#if 0 // undo/redo - if (theHold.Holding()) { - theHold.Put(new VertexSelRestore(meshData,this)); - } -#endif - tobj->mesh.vertSel.ClearAll(); - skindata->VertSel.ClearAll(); - break; - } - - if (needsdel) { - tobj->DeleteThis(); - } - } - - /* - ** Get rid of the temporary copies of the INodes. - */ - nodes.DisposeTemporary(); - - /* - ** Tell our dependents that the selection set has changed - */ - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); - -} - -void SkinModifierClass::SelectAll(int selLevel) -{ - int needsdel = 0; - Interval valid = FOREVER; - ModContextList mclist; - INodeTab nodes; - - if (!InterfacePtr) return; - - InterfacePtr->GetModContexts(mclist,nodes); - InterfacePtr->ClearCurNamedSelSet(); - - for (int i = 0; i < mclist.Count(); i++) { - - SkinDataClass * skindata = (SkinDataClass *)mclist[i]->localData; - - if (skindata==NULL) continue; - - ObjectState os = nodes[i]->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - - switch (SubObjSelLevel) { - - case OBJECT_SEL_LEVEL: - assert(0); - return; - - case VERTEX_SEL_LEVEL: -#if 0 // undo/redo - if (theHold.Holding()) { - theHold.Put(new VertexSelRestore(meshData,this)); - } -#endif - tobj->mesh.vertSel.SetAll(); - skindata->VertSel.SetAll(); - break; - } - - if (needsdel) { - tobj->DeleteThis(); - } - } - - /* - ** Get rid of the temporary copies of the INodes. - */ - nodes.DisposeTemporary(); - - /* - ** Tell our dependents that the selection set has changed - */ - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); -} - -void SkinModifierClass::InvertSelection(int selLevel) -{ - int needsdel = 0; - Interval valid = FOREVER; - ModContextList mclist; - INodeTab nodes; - - if (!InterfacePtr) return; - - InterfacePtr->GetModContexts(mclist,nodes); - InterfacePtr->ClearCurNamedSelSet(); - - for (int i = 0; i < mclist.Count(); i++) { - - SkinDataClass * skindata = (SkinDataClass *)mclist[i]->localData; - - if (skindata==NULL) continue; - - ObjectState os = nodes[i]->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - - switch (SubObjSelLevel) { - - case OBJECT_SEL_LEVEL: - assert(0); - return; - - case VERTEX_SEL_LEVEL: -#if 0 // undo/redo - if (theHold.Holding()) { - theHold.Put(new VertexSelRestore(meshData,this)); - } -#endif - for (int j=0; jmesh.vertSel.GetSize(); j++) { - if (tobj->mesh.vertSel[j]) tobj->mesh.vertSel.Clear(j); - else tobj->mesh.vertSel.Set(j); - } - skindata->VertSel = tobj->mesh.vertSel; - break; - } - - if (needsdel) { - tobj->DeleteThis(); - } - } - - /* - ** Get rid of the temporary copies of the INodes. - */ - nodes.DisposeTemporary(); - - /* - ** Tell our dependents that the selection set has changed - */ - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); - -} - -void SkinModifierClass::User_Picked_Bone(INode * node) -{ - assert(InterfacePtr != NULL); - - /* - ** Get a pointer to the ModContext and SkinData for - ** the mesh currently being messed with. - */ - ModContext * mc = NULL; - ModContextList mclist; - INodeTab nodelist; - - InterfacePtr->GetModContexts(mclist,nodelist); - - /* - ** This seems wrong... But I always get only one ModContext and - ** it is the one that I want so I'll just use it... - ** I believe that OS Modifiers can get multiple ones but WS modifiers - ** don't - */ - mc = mclist[0]; - assert(mc != NULL); - SkinDataClass * skindata = (SkinDataClass *)(mc->localData); - - /* - ** Add this bone to the influences of all selected vertices - */ - int boneidx = WSMObjectRef->Find_Bone(node); - assert(boneidx != -1); - skindata->Add_Influence(boneidx); - - /* - ** Recreate all of the named selection sets! - */ - Create_Named_Selection_Sets(); - - /* - ** Update dependents and redraw the views. - */ - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); - InterfacePtr->RedrawViews(InterfacePtr->GetTime()); -} - -void SkinModifierClass::User_Picked_Bones(INodeTab & nodetab) -{ - /* - ** One by one, add the selected bones to the influences of - ** all selected vertices. - */ - for (int i=0; iGetModContexts(mclist,nodes); - - for (int i = 0; i < mclist.Count(); i++) { - - SkinDataClass * skindata = (SkinDataClass *)mclist[i]->localData; - if (!skindata) continue; - - int index = skindata->VertSelSets.Find_Set(setname); - if (index < 0) continue; - - int needsdel; - Interval valid; - ObjectState os = nodes[i]->EvalWorldState(InterfacePtr->GetTime()); - TriObject * tobj = Get_Tri_Object(InterfacePtr->GetTime(),os,valid,needsdel); - Mesh * mesh = &(tobj->mesh); - - // TODO: undo redo -#if 0 - if (theHold.Holding()) { - theHold.Put(new VertexSelRestore(meshData,this)); - } -#endif - - if (skindata->VertSelSets[index].GetSize() != mesh->getNumVerts()) { - skindata->VertSelSets[index].SetSize(mesh->getNumVerts(),TRUE); - } - mesh->vertSel = skindata->VertSelSets[index]; - skindata->VertSel = mesh->vertSel; - - if (needsdel) { - tobj->DeleteThis(); - } - } - - nodes.DisposeTemporary(); - - NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); - InterfacePtr->RedrawViews(InterfacePtr->GetTime()); -} - -void SkinModifierClass::NewSetFromCurSel(TSTR &setname) -{ - Install_Named_Selection_Sets(); -} - -void SkinModifierClass::RemoveSubSelSet(TSTR &setname) -{ - Install_Named_Selection_Sets(); -} - -void SkinModifierClass::Create_Named_Selection_Sets(void) -{ - /* - ** This function creates a named selection set of vertices - ** for each bone in the skeleton. - */ - if (InterfacePtr == NULL) return; - - SkinWSMObjectClass * skinobj = WSMObjectRef; - if (skinobj == NULL) return; - - ModContextList mclist; - INodeTab nodes; - InterfacePtr->GetModContexts(mclist,nodes); - SkinDataClass * skindata = (SkinDataClass *)mclist[0]->localData; - if (skindata == NULL) return; - - /* - ** Clear out the old selection sets - */ - skindata->VertSelSets.Reset(); - - /* - ** Create and add a set for each bone - */ - for (int boneidx = 0; boneidx < skinobj->Num_Bones(); boneidx++) { - - if (skinobj->Get_Bone(boneidx) != NULL) { - BitArray boneverts; - boneverts.SetSize(skindata->VertData.Count()); - - for (int vertidx = 0; vertidx < skindata->VertData.Count(); vertidx++) { - if (skindata->VertData[vertidx].BoneIdx[0] == boneidx) boneverts.Set(vertidx); - else boneverts.Clear(vertidx); - } - - TSTR bonename = skinobj->Get_Bone(boneidx)->GetName(); - - skindata->VertSelSets.Append_Set(boneverts,bonename); - } - } - - Install_Named_Selection_Sets(); - - nodes.DisposeTemporary(); -} - -void SkinModifierClass::Install_Named_Selection_Sets(void) -{ - /* - ** If we are in sub-object selection mode add the sets - ** to the drop down box. - */ - if ((SubObjSelLevel == VERTEX_SEL_LEVEL) && (InterfacePtr != NULL)) { - - ModContextList mclist; - INodeTab nodes; - InterfacePtr->GetModContexts(mclist,nodes); - SkinDataClass * skindata = (SkinDataClass *)mclist[0]->localData; - if (skindata == NULL) return; - - InterfacePtr->ClearSubObjectNamedSelSets(); - for (int i=0; i < skindata->VertSelSets.Count(); i++) { - InterfacePtr->AppendSubObjectNamedSelSet(*skindata->VertSelSets.Names[i]); - } - - nodes.DisposeTemporary(); - } -} - -void SkinModifierClass::Auto_Attach_Verts(BOOL all) -{ - assert(InterfacePtr); - - /* - ** Get the skin data. - */ - ModContextList mclist; - INodeTab nodes; - InterfacePtr->GetModContexts(mclist,nodes); - SkinDataClass * skindata = (SkinDataClass *)mclist[0]->localData; - if (skindata == NULL) return; - - /* - ** get the skin WSM object. - */ - SkinWSMObjectClass * skinobj = WSMObjectRef; - if (skinobj == NULL) return; - - /* - ** Get a triobject representing the object state in the base pose. - */ - Interval valid; - BOOL needsdel; - - TimeValue basetime = WSMObjectRef->Get_Base_Pose_Time(); - ObjectState os = nodes[0]->EvalWorldState(basetime); - TriObject * triobj = Get_Tri_Object(basetime,os,valid,needsdel); - - /* - ** Attach each selected vertex (or all of them) to their closest bone. - */ - for (int vertidx = 0; vertidx < skindata->VertData.Count(); vertidx++){ - if (skindata->VertSel[vertidx] || all) { - - Point3 vert = triobj->GetPoint(vertidx); - if (os.GetTM()) vert = vert * (*os.GetTM()); - int boneidx = skinobj->Find_Closest_Bone(vert); - skindata->VertData[vertidx].Set_Influence(boneidx); - } - } - - /* - ** Re-create the named selection sets - */ - Create_Named_Selection_Sets(); - - /* - ** Update dependents and redraw the views. - */ - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); - InterfacePtr->RedrawViews(InterfacePtr->GetTime()); - - /* - ** Cleanup... - */ - nodes.DisposeTemporary(); - - if (needsdel) { - triobj->DeleteThis(); - } -} - -void SkinModifierClass::Unlink_Verts(void) -{ - assert(InterfacePtr); - - /* - ** Get the skin data. - */ - ModContextList mclist; - INodeTab nodes; - InterfacePtr->GetModContexts(mclist,nodes); - SkinDataClass * skindata = (SkinDataClass *)mclist[0]->localData; - if (skindata == NULL) return; - - /* - ** Unlink each selected vertex (give them bone index -1) - */ - for (int vertidx = 0; vertidx < skindata->VertData.Count(); vertidx++){ - if (skindata->VertSel[vertidx]) { - skindata->VertData[vertidx].Set_Influence(-1); - } - } - - /* - ** Re-create the named selection sets - */ - Create_Named_Selection_Sets(); - - /* - ** Update dependents and redraw the views. - */ - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); - InterfacePtr->RedrawViews(InterfacePtr->GetTime()); - - /* - ** Cleanup... - */ - nodes.DisposeTemporary(); -} - - -/**************************************************************************** -** -** DIALOG BOX JUNK -** -****************************************************************************/ - -void SkinModifierClass::Install_Bone_Influence_Dialog(void) -{ - if (BoneInfluenceHWND != NULL) return; - - /* - ** loading resource string for the name of the dialog - */ - static int loaded = 0; - static TCHAR string[MAX_STRING_LENGTH]; - - if (!loaded) { - LoadString(AppInstance,IDS_BONE_INFLUENCE_PARAMS,string,MAX_STRING_LENGTH); - loaded = 1; - } - - /* - ** Put up the UI that is used to assign vertices to bones - */ - BoneInfluenceHWND = InterfacePtr->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_BONE_INFLUENCE_PARAMS), - _bone_influence_dialog_thunk, - string, - (LPARAM)this, - 0); -} - -void SkinModifierClass::Remove_Bone_Influence_Dialog(void) -{ - /* - ** If it is currently up, remove the bone influences dialog - */ - if (BoneInfluenceHWND != NULL) { - InterfacePtr->UnRegisterDlgWnd(BoneInfluenceHWND); - InterfacePtr->DeleteRollupPage(BoneInfluenceHWND); - BoneInfluenceHWND = NULL; - } -} - -/********************************************************************************* -* -* _sot_dialog_proc -* -*********************************************************************************/ -static BOOL CALLBACK _sot_dialog_proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - IObjParam *ip = (IObjParam*)GetWindowLong(hWnd,GWL_USERDATA); - - switch (message) { - case WM_INITDIALOG: - SetWindowLong(hWnd,GWL_USERDATA,lParam); - break; - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - if (ip) ip->RollupMouseMessage(hWnd,message,wParam,lParam); - return FALSE; - - default: - return FALSE; - } - return TRUE; -} - - -/********************************************************************************* -* -* _skeleton_dialog_proc -* -*********************************************************************************/ -static BOOL CALLBACK _skeleton_dialog_thunk(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - SkinWSMObjectClass * skinobj = (SkinWSMObjectClass *)GetWindowLong(hWnd,GWL_USERDATA); - if (!skinobj && message != WM_INITDIALOG) return FALSE; - - if (message == WM_INITDIALOG) { - skinobj = (SkinWSMObjectClass *)lParam; - SetWindowLong(hWnd,GWL_USERDATA,(LONG)skinobj); - } - - return skinobj->Skeleton_Dialog_Proc(hWnd,message,wParam,lParam); -} - -BOOL SkinWSMObjectClass::Skeleton_Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - switch (message) { - - case WM_INITDIALOG: - - BoneListHWND = GetDlgItem(hWnd,IDC_BONE_LIST); - - /* - ** Intitialize the add bone and remove bone check buttons - */ - AddBonesButton = GetICustButton(GetDlgItem(hWnd, IDC_ADD_BONES_BUTTON)); - RemoveBonesButton = GetICustButton(GetDlgItem(hWnd, IDC_REMOVE_BONES_BUTTON)); - - AddBonesButton->SetType(CBT_CHECK); - AddBonesButton->SetHighlightColor(GREEN_WASH); - AddBonesButton->SetTooltip(TRUE, _T("Add bones by name")); - - RemoveBonesButton->SetType(CBT_CHECK); - RemoveBonesButton->SetHighlightColor(GREEN_WASH); - RemoveBonesButton->SetTooltip(TRUE, _T("Remove bones by name")); - - /* - ** Initialize the "Base Pose Frame" spinner - */ - BasePoseSpin = GetISpinner(GetDlgItem(hWnd, IDC_BASE_POSE_SPIN)); - BasePoseSpin->SetLimits(0,9999, FALSE); - BasePoseSpin->SetValue(0,FALSE); - BasePoseSpin->SetResetValue(0); - BasePoseSpin->LinkToEdit(GetDlgItem(hWnd,IDC_BASE_POSE_EDIT),EDITTYPE_INT); - return TRUE; - - case WM_DESTROY: - ReleaseICustButton(AddBonesButton); - ReleaseICustButton(RemoveBonesButton); - ReleaseISpinner(BasePoseSpin); - - AddBonesButton = NULL; - RemoveBonesButton = NULL; - BasePoseSpin = NULL; - BoneListHWND = NULL; - - return FALSE; - - case CC_SPINNER_CHANGE: - switch (LOWORD(wParam)) - { - case IDC_BASE_POSE_SPIN: - BasePoseFrame = BasePoseSpin->GetIVal(); - break; - } - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); - InterfacePtr->RedrawViews(InterfacePtr->GetTime(),REDRAW_INTERACTIVE); - return TRUE; - - case CC_SPINNER_BUTTONUP: - NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); - InterfacePtr->RedrawViews(InterfacePtr->GetTime(),REDRAW_END); - return TRUE; - - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - InterfacePtr->RollupMouseMessage(hWnd,message,wParam,lParam); - return FALSE; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - - case IDC_ADD_BONES_BUTTON: - TheBonePicker.Set_User(this); - Set_Bone_Selection_Mode(BONE_SEL_MODE_ADD_MANY); - InterfacePtr->DoHitByNameDialog(&TheBonePicker); - Set_Bone_Selection_Mode(BONE_SEL_MODE_NONE); - break; - - case IDC_REMOVE_BONES_BUTTON: - TheBonePicker.Set_User(this,FALSE,&(BoneTab)); - Set_Bone_Selection_Mode(BONE_SEL_MODE_REMOVE_MANY); - InterfacePtr->DoHitByNameDialog(&TheBonePicker); - Set_Bone_Selection_Mode(BONE_SEL_MODE_NONE); - break; - } - - default: - return FALSE; - } -} - -/********************************************************************************* -* -* Bone_Influence_Dialog_Proc -* -*********************************************************************************/ -static BOOL CALLBACK _bone_influence_dialog_thunk(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - SkinModifierClass * skinmod = (SkinModifierClass *)GetWindowLong(hWnd,GWL_USERDATA); - if (!skinmod && message != WM_INITDIALOG) return FALSE; - - if (message == WM_INITDIALOG) { - skinmod = (SkinModifierClass *)lParam; - SetWindowLong(hWnd,GWL_USERDATA,(LONG)skinmod); - } - - return skinmod->Bone_Influence_Dialog_Proc(hWnd,message,wParam,lParam); -} - - -BOOL SkinModifierClass::Bone_Influence_Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - switch (message) { - - case WM_INITDIALOG: - /* - ** Intitialize the bone influence buttons - */ - LinkButton = GetICustButton(GetDlgItem(hWnd, IDC_LINK_BUTTON)); - LinkByNameButton = GetICustButton(GetDlgItem(hWnd, IDC_LINK_BY_NAME_BUTTON)); - AutoLinkButton = GetICustButton(GetDlgItem(hWnd, IDC_AUTO_LINK_BUTTON)); - UnLinkButton = GetICustButton(GetDlgItem(hWnd, IDC_UNLINK_BUTTON)); - - LinkButton->SetType(CBT_PUSH); - LinkButton->SetTooltip(TRUE, _T("Link Vertices to a bone by selecting the bone")); - - LinkByNameButton->SetType(CBT_PUSH); - LinkByNameButton->SetTooltip(TRUE, _T("Link Vertices to a bone by name")); - - AutoLinkButton->SetType(CBT_PUSH); - AutoLinkButton->SetTooltip(TRUE, _T("Link Vertices to nearest bone")); - - UnLinkButton->SetType(CBT_PUSH); - UnLinkButton->SetTooltip(TRUE, _T("Unlink selected vertices")); - - return TRUE; - - case WM_DESTROY: - ReleaseICustButton(LinkButton); - ReleaseICustButton(LinkByNameButton); - ReleaseICustButton(AutoLinkButton); - ReleaseICustButton(UnLinkButton); - - LinkButton = NULL; - LinkByNameButton = NULL; - AutoLinkButton = NULL; - UnLinkButton = NULL; - return FALSE; - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - InterfacePtr->RollupMouseMessage(hWnd,message,wParam,lParam); - return FALSE; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDC_LINK_BUTTON: - { - /* - ** user picks a bone out of the scene to link to. - */ - assert(WSMObjectRef != NULL); - INodeTab * bonetab = &(WSMObjectRef->Get_Bone_List()); - TheBonePicker.Set_User(this,TRUE,bonetab); - InterfacePtr->SetPickMode(&TheBonePicker); - break; - } - - case IDC_LINK_BY_NAME_BUTTON: - { - /* - ** pop up a bone selection dialog - */ - assert(WSMObjectRef != NULL); - INodeTab * bonetab = &(WSMObjectRef->Get_Bone_List()); - TheBonePicker.Set_User(this,TRUE,bonetab); - InterfacePtr->DoHitByNameDialog(&TheBonePicker); - break; - } - - case IDC_AUTO_LINK_BUTTON: - { - Auto_Attach_Verts(); - break; - } - - case IDC_UNLINK_BUTTON: - { - Unlink_Verts(); - break; - } - } - - default: - return FALSE; - } -} - -static TriObject * Get_Tri_Object(TimeValue t,ObjectState & os,Interval & valid,BOOL & needsdel) -{ - needsdel = FALSE; - valid &= os.Validity(t); - - if (os.obj->IsSubClassOf(triObjectClassID)) { - return (TriObject *)os.obj; - } else { - if (os.obj->CanConvertToType(triObjectClassID)) { - Object * oldObj = os.obj; - TriObject * tobj = (TriObject *)os.obj->ConvertToType(t,triObjectClassID); - needsdel = (tobj != oldObj); - return tobj; - } - } - return NULL; -} - - -float Bone_Distance(INode * bone,TimeValue time,const Point3 & vertex) -{ - /* - ** Average the pivot point of this bone with the pivot points of - ** all of its children. - */ - Point3 icenter = bone->GetObjectTM(time).GetTrans(); - - for (int ci=0; ciNumberOfChildren(); ci++) { - icenter += bone->GetChildNode(ci)->GetObjectTM(time).GetTrans(); - } - - icenter = icenter / (float)(bone->NumberOfChildren() + 1); - - return Length(icenter - vertex); -} - -#if defined W3D_MAX4 //defined as in the project (.dsp) - -int SkinModifierClass::NumSubObjTypes() -{ - return 1; -} -//////////////////////////////////////////////////////////////////////////////////////// -ISubObjType *SkinModifierClass::GetSubObjType(int i) -{ - - static bool _initialized = false; - if(!_initialized){ - _initialized = true; - _SubObjectTypeVertex.SetName("Vertices"); - } - if(i == -1){ - if(GetSubObjectLevel() > 0){ - return GetSubObjType(GetSubObjectLevel()-1); - } - } - return &_SubObjectTypeVertex; -} -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/skin.h b/Generals/Code/Tools/WW3D/max2w3d/skin.h deleted file mode 100644 index 099881d159..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/skin.h +++ /dev/null @@ -1,405 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/skin.h $* - * * - * $Author:: Moumine_ballo $* - * * - * $Modtime:: 4/18/01 11:31a $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef SKIN_H -#define SKIN_H - -#include -#include "simpmod.h" -#include "simpobj.h" -#include "bpick.h" -#include "namedsel.h" -#include "w3d_file.h" - - -#define SKIN_OBJ_CLASS_ID Class_ID(0x32b37e0c, 0x5a9612e4) -#define SKIN_MOD_CLASS_ID Class_ID(0x6bad4898, 0x0d1d6ced) -extern ClassDesc * Get_Skin_Obj_Desc(); -extern ClassDesc * Get_Skin_Mod_Desc(); - - -/* - - Writing a space warp plug-in involves creating instances of two key classes. - One is derived from class WSMObject. (WSMObject stands for Word Space Modifier Object, - just another name for Space Warp Object). The other class is subclassed off Modifier. - These two classes work together. The space warp object handles the display and management - of its user interface parameters, the display of the space warp node in the scene, and - provides a world space orientation. The space warp modifier handles the actual deformation - of the geometry of nodes bound to the space warp. Each node bound to the space warp - will have a ModContext which we will store data in. - - The following class is the WSMObject for the westwood skin modifier. - -*/ -class SkinWSMObjectClass : public SimpleWSMObject, BonePickerUserClass -{ -public: - - SkinWSMObjectClass(); - virtual ~SkinWSMObjectClass(); - - /* - ** From Animatable - */ - void DeleteThis() { delete this; } - void BeginEditParams(IObjParam *ip, ULONG flags,Animatable *prev); - void EndEditParams(IObjParam *ip, ULONG flags,Animatable *next); - TCHAR * GetObjectName() { return _T("WWSkin"); } - Class_ID ClassID() { return SKIN_OBJ_CLASS_ID; } - - /* - ** From ReferenceTarget - */ - RefTargetHandle Clone(RemapDir& remap = NoRemap()); - - /* - ** From Reference Maker. These three functions give access to the "virtual array" of references. - ** For SkinWSMObjectClass, we have to remember that SimpleWSMObject already has a reference - ** so we are taking ours on after - */ - virtual int NumRefs() { return SimpleWSMObject::NumRefs() + Num_Bones();} - virtual RefTargetHandle GetReference(int i); - virtual void SetReference(int i, RefTargetHandle rtarg); - RefResult NotifyRefChanged(Interval changeInt,RefTargetHandle hTarget,PartID& partID, RefMessage message); - - /* - ** From Object - */ - int DoOwnSelectHilite() { return TRUE; } - CreateMouseCallBack * GetCreateMouseCallBack(); - - /* - ** From WSMObject - */ - Modifier *CreateWSMMod(INode *node); - - /* - ** From SimpleWSMObject - */ - void BuildMesh(TimeValue t); - - /* - ** Setup a triangle - */ - void Build_Tri(Face * f, int a, int b, int c); - - /* - ** Dialog box message processing - */ - BOOL SkinWSMObjectClass::Skeleton_Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); - - /* - ** Bone picking. - */ - virtual void User_Picked_Bone(INode * node); - virtual void User_Picked_Bones(INodeTab & nodetab); - void Set_Bone_Selection_Mode(int mode); - - int Add_Bone(INode * node); - void Add_Bones(INodeTab & nodetab); - void Remove_Bone(INode * node); - void Remove_Bones(INodeTab & nodetab); - void Update_Bone_List(void); - - /* - ** Converting between bone indexes and reference indexes - ** The bone references are a variable number of references which are - ** added at the end of the reference array. - */ - int To_Bone_Index(int refidx) { return refidx - SimpleWSMObject::NumRefs(); } - int To_Ref_Index(int boneidx) { return SimpleWSMObject::NumRefs() + boneidx; } - - /* - ** External access to the bones - */ - int Num_Bones(void) { return BoneTab.Count(); } - INode * Get_Bone(int idx) { return BoneTab[idx]; } - INodeTab & Get_Bone_List(void) { return BoneTab; } - int Find_Bone(INode * node); - int Get_Base_Pose_Frame(void) { return BasePoseFrame; } - int Get_Base_Pose_Time(void) { return BasePoseFrame * GetTicksPerFrame(); } - int Find_Closest_Bone(const Point3 & vertex); - - /* - ** Saving and loading. - */ - IOResult Save(ISave *isave); - IOResult Load(ILoad *iload); - - /* - ** Static UI variables. These have to be static due to the strange way - ** that MAX behaves during creation of objects. If you create an object - ** then delete it, EndEditParams is not called and its destructor isn't called... - */ - static HWND SotHWND; - static HWND SkeletonHWND; - static HWND BoneListHWND; - static IObjParam * InterfacePtr; - static ICustButton * AddBonesButton; - static ICustButton * RemoveBonesButton; - static ISpinnerControl * BasePoseSpin; - - /* - ** flag for whether we need to build the bones mesh for this object - */ - BOOL MeshBuilt; - - /* - ** Bone Selection! - */ - enum { - BONE_SEL_MODE_NONE = 0, - BONE_SEL_MODE_ADD, - BONE_SEL_MODE_REMOVE, - BONE_SEL_MODE_ADD_MANY, - BONE_SEL_MODE_REMOVE_MANY - }; - - int BoneSelectionMode; - INodeTab BoneTab; - - /* - ** Dialog controls - */ - int BasePoseFrame; - - /* - ** Chunk ID's - */ - enum { - NUM_BONES_CHUNK = 0x0001 - }; - - /* - ** Friend functions - */ - friend BOOL CALLBACK _skeleton_dialog_thunk(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); -}; - -/* -** SkinModifierClass -*/ -class SkinModifierClass : public Modifier, BonePickerUserClass -{ - -public: - - SkinModifierClass(void); - SkinModifierClass(INode * node,SkinWSMObjectClass * skin_obj); -#if defined W3D_MAX4 //defined as in the project (.dsp) - ISubObjType *GetSubObjType(int i); - int NumSubObjTypes(); -#endif - void Default_Init(void); - - /* - ** From Animatable - */ - void DeleteThis() { delete this; } - void GetClassName(TSTR& s) { s = TSTR(_T("WWSkin")); } - TCHAR * GetObjectName() { return _T("WWSkin Binding"); } - SClass_ID SuperClassID() { return WSM_CLASS_ID; } - Class_ID ClassID() { return SKIN_MOD_CLASS_ID; } - RefTargetHandle Clone(RemapDir& remap = NoRemap()); - RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); - void BeginEditParams(IObjParam *ip, ULONG flags,Animatable *prev); - void EndEditParams(IObjParam *ip, ULONG flags,Animatable *next); - CreateMouseCallBack * GetCreateMouseCallBack() { return NULL; } - - /* - ** From Reference Maker. These three functions give access to the "virtual array" of references. - */ - int NumRefs() { return 2; } - RefTargetHandle GetReference(int i); - void SetReference(int i, RefTargetHandle rtarg); - - /* - ** Tell MAX what channels we use and what channels we change: - ** Note that if we do not tell max that we use a channel, that channel is not - ** guaranteed to be valid. - */ - virtual ChannelMask ChannelsUsed() { return SELECT_CHANNEL|SUBSEL_TYPE_CHANNEL|GEOM_CHANNEL; } - virtual ChannelMask ChannelsChanged() { return SELECT_CHANNEL|SUBSEL_TYPE_CHANNEL|GEOM_CHANNEL; } - - /* - ** MAX tells us whenever an input changed. If we cache anything, we can use this - ** function to dump the cached data and regenerate it. - */ - virtual void NotifyInputChanged(Interval changeInt, PartID partID, RefMessage message, ModContext *mc) {} - - /* - ** This is where the modifier actually modifies the object! - */ - virtual void ModifyObject(TimeValue t, ModContext & mc, ObjectState * os, INode * node); - - /* - ** Since our modifier will be storing information based on the vertex indices, whenever - ** the topology of its input is changed things will no longer work correctly. Therefore, - ** we tell max that we depend on the topology remaining the same. - */ - virtual BOOL DependOnTopology(ModContext &mc) { return TRUE; } - - /* - ** What types of objects can we modify: The skin modifier will only work with TRIOBJ's - */ - virtual Class_ID InputType() { return Class_ID(TRIOBJ_CLASS_ID,0); } - - /* - ** Saving and loading. Remember to call the base class's save and load functions as well. - */ - IOResult Save(ISave *isave); - IOResult Load(ILoad *iload); - virtual IOResult LoadLocalData(ILoad *iload, LocalModData **pld); - virtual IOResult SaveLocalData(ISave *isave, LocalModData *ld); - - /* - ** For SkinModifierClass, we allow vertex sub-object selection. - ** This function notifies an object being edited that the current sub object - ** selection level has changed. level==0 indicates object level selection. - ** level==1 or greater refer to the types registered by the object in the - ** order they appeared in the list when registered. If level >= 1, the object - ** should specify sub-object xform modes in the modes structure (defined in cmdmode.h). - */ - void ActivateSubobjSel(int level, XFormModes& modes); - - int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt, ModContext* mc); - void SelectSubComponent(HitRecord *hitRec, BOOL selected, BOOL all, BOOL invert=FALSE); - void ClearSelection(int selLevel);// - void SelectAll(int selLevel); - void InvertSelection(int selLevel); - - /* - ** An object that supports sub-object selection can choose to - ** support named sub object selection sets. Methods in the the - ** interface passed to objects allow them to add items to the - ** sub-object selection set drop down. - ** The following methods implement named sub-obj selection sets - */ - virtual BOOL SupportsNamedSubSels() { return TRUE; } - virtual void ActivateSubSelSet(TSTR &setName); - virtual void NewSetFromCurSel(TSTR &setName); - virtual void RemoveSubSelSet(TSTR &setName); - void Create_Named_Selection_Sets(void); - void Install_Named_Selection_Sets(void); - - WSMObject * Get_WSMObject(void) { return (WSMObject*)GetReference(OBJ_REF); } - Interval Get_Validity(TimeValue t); - - /* - ** Bone picking - */ - virtual void User_Picked_Bone(INode * node); - virtual void User_Picked_Bones(INodeTab & nodetab); - - /* - ** Auto-Attach vertices to nearest bone - */ - void Auto_Attach_Verts(BOOL all = FALSE); - - /* - ** Unlink selected verts (links them to the root or origin) - */ - void Unlink_Verts(void); - -private: - - /* - ** Windows dialog management and communication functions - */ - void Install_Bone_Influence_Dialog(void); - void Remove_Bone_Influence_Dialog(void); - - BOOL Bone_Influence_Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); - -public: - - /* - ** References for SkinModifierClass - */ - enum { - OBJ_REF = 0, - NODE_REF = 1 - }; - - SkinWSMObjectClass * WSMObjectRef; - INode * WSMNodeRef; - - /* - ** Sub-Object Selection variables - */ - enum { - OBJECT_SEL_LEVEL = 0, - VERTEX_SEL_LEVEL = 1 - }; - - int SubObjSelLevel; - - - /* - ** Bone Influence Dialog panel variables - */ - HWND BoneInfluenceHWND; - ICustButton * LinkButton; - ICustButton * LinkByNameButton; - ICustButton * AutoLinkButton; - ICustButton * UnLinkButton; - - /* - ** Cached pointers to some MAX objects - */ - IObjParam * InterfacePtr; - SelectModBoxCMode * SelectMode; - - /* - ** Load/Save Chunk ID's - */ - enum { - SEL_LEVEL_CHUNK = 0xAA01, - }; - - /* - ** Friend "thunking" functions for the dialog handling. - */ - friend BOOL CALLBACK _bone_influence_dialog_thunk(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); -}; - - - - -#endif - diff --git a/Generals/Code/Tools/WW3D/max2w3d/skindata.cpp b/Generals/Code/Tools/WW3D/max2w3d/skindata.cpp deleted file mode 100644 index 3c690cad08..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/skindata.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/skindata.cpp 7 5/28/98 12:15p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/skindata.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/28/98 12:15p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * SkinDataClass::Save -- save the skindata in the MAX file * - * SkinDataClass::Load -- load the skindata from a MAX file * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "skindata.h" - - -/*********************************************************************************************** - * SkinDataClass::Save -- save the skindata in the MAX file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -IOResult SkinDataClass::Save(ISave *isave) -{ - ULONG nb; - - /* - ** save the flags - */ - short flags = 0; - if (Valid) flags |= 0x01; - if (Held) flags |= 0x02; - - isave->BeginChunk(FLAGS_CHUNK); - isave->Write(&flags,sizeof(flags),&nb); - isave->EndChunk(); - - /* - ** Save the bit array of currently selected vertices - */ - if (VertSel.NumberSet() > 0) { - isave->BeginChunk(VERT_SEL_CHUNK); - VertSel.Save(isave); - isave->EndChunk(); - } - - /* - ** Save the named selection sets of vertices - */ -#if 0 - if (VertSelSets.Count() > 0) { - isave->BeginChunk(INFLUENCE_DATA_CHUNK); - VertSelSets.Save(isave); - isave->EndChunk(); - } -#endif - - /* - ** Save the vertex influence data - */ - if (VertData.Count() > 0) { - isave->BeginChunk(INFLUENCE_DATA_CHUNK); - isave->Write(VertData.Addr(0),VertData.Count() * sizeof(InfluenceStruct), &nb); - isave->EndChunk(); - } - - return IO_OK; -} - - -/*********************************************************************************************** - * SkinDataClass::Load -- load the skindata from a MAX file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -IOResult SkinDataClass::Load(ILoad *iload) -{ - ULONG nb; - short flags; - int n; - IOResult res; - - while (IO_OK == (res=iload->OpenChunk())) { - - switch (iload->CurChunkID()) { - - case FLAGS_CHUNK: - res = iload->Read(&flags,sizeof(flags),&nb); - Valid = (flags & 0x01); - Held = (flags & 0x02); - break; - - case VERT_SEL_CHUNK: - res = VertSel.Load(iload); - break; - - case NAMED_SEL_SETS_CHUNK: - res = VertSelSets.Load(iload); - break; - - case INFLUENCE_DATA_CHUNK: - n = iload->CurChunkLength() / sizeof(InfluenceStruct); - VertData.SetCount(n); - res = iload->Read(VertData.Addr(0),n*sizeof(InfluenceStruct),&nb); - break; - } - - iload->CloseChunk(); - - if (res != IO_OK) { - return res; - } - } - - /* - ** ensure that the arrays are sized correctly - */ - Invalidate(); - - return IO_OK; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/skindata.h b/Generals/Code/Tools/WW3D/max2w3d/skindata.h deleted file mode 100644 index a7638befc4..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/skindata.h +++ /dev/null @@ -1,162 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/skindata.h 6 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - WWSkin * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/skindata.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/21/97 2:04p $* - * * - * $Revision:: 6 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef SKINDATA_H -#define SKINDATA_H - -#include "max.h" -#include "namedsel.h" - -/* -** InfluenceStruct - structure which stores the bone -** influence information for a single vertex. -*/ -struct InfluenceStruct -{ - /* - ** vertices can be influenced by up to two bones. - */ - int BoneIdx[2]; - float BoneWeight[2]; - - InfluenceStruct(void) { BoneIdx[0] = -1; BoneIdx[1] = -1; BoneWeight[0] = 1.0f; BoneWeight[1] = 0.0f; } - - void Set_Influence(int boneidx) { - // TODO: make this actually let you set two bones with - // weighting values. Need UI to furnish this info... - BoneIdx[0] = boneidx; - } -}; - - -/* -** SkinDataClass - a class which contains the bone influence data -** for the modifier. One of these will be hung off of the -** ModContext... -*/ -class SkinDataClass : public LocalModData -{ - -public: - - SkinDataClass(void) { Held = FALSE; Valid = FALSE; } - - SkinDataClass(Mesh *mesh) - { - VertSel = mesh->vertSel; - VertData.SetCount(mesh->getNumVerts()); - for (int i=0; ivertSel.GetSize(),1); - VertData.SetCount(mesh->getNumVerts()); - Valid = TRUE; - } - } - - virtual LocalModData * Clone(void) - { - SkinDataClass * newdata = new SkinDataClass(); - newdata->VertSel = VertSel; - newdata->VertData = VertData; - return newdata; - } - - void Add_Influence(int boneidx) - { - /* - ** Make this INode influence all currently selected vertices - */ - for (int i=0; i VertData; - - /* - ** Load/Save chunk ID's - */ - enum { - FLAGS_CHUNK = 0x0000, - VERT_SEL_CHUNK = 0x0010, - NAMED_SEL_SETS_CHUNK = 0x0020, - INFLUENCE_DATA_CHUNK = 0x0030 - }; - -}; - - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/util.cpp b/Generals/Code/Tools/WW3D/max2w3d/util.cpp deleted file mode 100644 index 1813675773..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/util.cpp +++ /dev/null @@ -1,622 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/util.cpp 28 10/27/00 4:12p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/util.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 1:13p $* - * * - * $Revision:: 28 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Cleanup_Orthogonal_Matrix -- removes very small numbers from the matrix * - * Set_W3D_Name -- set a W3D name * - * Split_Node_Name -- break a node name into the base and extension * - * Is_Max_Tri_Mesh -- Is this node a triangle mesh? * - * -- checks if the node is the origin of a model * - * -- Checks if the node is the origin for the base obect (non-LOD'd). * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "util.h" -#include "w3dutil.h" -#include "skin.h" -#include "skindata.h" -#include "modstack.h" - - -#define MAX_NODE_NAME_LEN 256 // max name size we can handle - -const float EPSILON = 0.00001f; -static char _string[256]; - - - -static int get_geometry_type(INode * node) -{ - assert(node != NULL); - return W3DAppData2Struct::Get_App_Data(node)->Get_Geometry_Type(); - - //return (get_w3d_bits(node) & GEO_TYPE_MASK); -} - - -/*********************************************************************************************** - * Cleanup_Orthogonal_Matrix -- removes very small numbers from the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 Cleanup_Orthogonal_Matrix(Matrix3 & mat) -{ - Matrix3 newmat = mat; - - for (int j=0; j<3; j++) { - Point3 row = newmat.GetRow(j); - - if (fabs(row.x) < EPSILON) row.x = 0.0f; - if (fabs(row.y) < EPSILON) row.y = 0.0f; - if (fabs(row.z) < EPSILON) row.z = 0.0f; - - row = Normalize(row); - - newmat.SetRow(j,row); - } - - return newmat; -} - -/*********************************************************************************************** - * Set_W3D_Name -- set a W3D name * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - * 9/13/1999 AJA : Strip off the trailing ".digits" since this is a convention we've set in * - * MAX to help artists manage LODs. * - *=============================================================================================*/ -void Set_W3D_Name(char * set_name,const char * src) -{ - memset(set_name,0,W3D_NAME_LEN); - strncpy(set_name,src,W3D_NAME_LEN-1); - char *dot = strrchr(set_name, '.'); - if (dot) - { - // If a number comes after the dot, strip it off - int value; - if (sscanf(dot+1, "%d", &value) == 1) - *dot = 0; - // If nothing comes after the dot, strip it off - else if (*(dot+1) == 0) - *dot = 0; - } - strupr(set_name); -} - -/*********************************************************************************************** - * Split_Node_Name -- break a node name into the base and extension * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -void Split_Node_Name(const char * name,char * set_base,char * set_exten,int * set_exten_index) -{ - // Nodes are assumed to be named in the following way: - // . - // for example: mesh.d1 - - char buf[MAX_NODE_NAME_LEN]; - char * ptr; - - assert(strlen(name) < MAX_NODE_NAME_LEN); - - // Initialize - if (set_base != NULL) set_base[0] = 0; - if (set_exten != NULL) set_exten[0] = 0; - if (set_exten_index != NULL) *set_exten_index = 0; - - // Get the base name - strncpy(buf,name,MAX_NODE_NAME_LEN); - ptr = buf; - while ((*ptr != 0) && (*ptr != '.')) { - ptr++; - } - - if (*ptr == '.') { - - // copy what we have so far into set_base - *ptr = 0; - if (set_base != NULL) strncpy(set_base,buf,MAX_NODE_NAME_LEN); - - // copy the rest back into the extension - ptr++; - if (set_exten != NULL) strncpy(set_exten,ptr,MAX_NODE_NAME_LEN); - - // now get the extension index - ptr++; - if (set_exten_index != NULL) *set_exten_index = atoi(ptr); - - } else { - - // no extension, just copy the base name - if (set_base != NULL) strncpy(set_base,buf,MAX_NODE_NAME_LEN); - return; - } -} - - -bool Append_Lod_Character (char *meshname, int lod_level, INodeListClass *origin_list) -{ - if (meshname == NULL || lod_level < 0) - return false; - - if (!origin_list) - return false; - - int num_lods = origin_list->Num_Nodes(); - - /* - ** Search the other LODs to see if there is a mesh with the same name. - ** If there is, we will append the current LOD level digit to the name. - ** If there is not, the name will not be modified. - */ - INode *conflict = NULL, *cur_origin = NULL; - int i, lod; - for (i = 0; i < num_lods; i++) - { - // Don't bother searching the current LOD. - lod = Get_Lod_Level((*origin_list)[i]); - if (lod == lod_level) - continue; - - // Search this lod for a node of the same name. - conflict = Find_Named_Node(meshname, (*origin_list)[i]); - if (conflict) - { - // Name length is a worry here, because the name plus the number - // must be less than W3D_NAME_LEN (which is fairly small!). - int length = strlen(meshname); - if ( (lod_level < 10) && (length < W3D_NAME_LEN - 1) ) - { - // Append a number corresponding to the LOD level to the mesh name. - // Highest-detail LOD is '0' (convention). - char *insert = meshname + length; - *insert++ = '0' + lod_level; - *insert = '\0'; - } - else if ( (lod_level < 100) && (length < W3D_NAME_LEN - 2) ) - { - // Append a number corresponding to the LOD level to the mesh name. - // Highest-detail LOD is '0' (convention). - char buf[3]; - sprintf(buf, "%d", lod_level); - strcat(meshname, buf); - } - else - { - // Replace the last character of the mesh name with the lod character (as above). - meshname[W3D_NAME_LEN-2] = '0' + lod_level; - } - - // Name mangling finished (conflict with other LODs is solved on their pass). - break; - } - } - - return true; -} - - - -void Create_Full_Path(char *full_path, const char *curr, const char *rel_path) -{ - // Copy current dir to full path. If it doesn't end with a slash, add one. - strcpy(full_path, curr); - int curr_len = strlen(curr); - char *full_p = full_path + curr_len; // Point at the terminating NULL - if (curr_len == 0 ||(*(full_p - 1) != '/' && *(full_p - 1) != '\\')) { - *full_p = '\\'; - *(++full_p) = '\000'; // Point at the terminating NULL - } - - // Scan "..\"s at the beginning of the rel path, scan backwards on the - // full path (current dir): - const char *rel_p; - for ( rel_p = rel_path; - *rel_p == '.' && *(rel_p+1) == '.' && ( *(rel_p+2) == '/' || *(rel_p+2) == '\\' ); - rel_p += 3) - { - full_p--; - for (; full_p > full_path && *(full_p-1) != '/' && *(full_p-1) != '\\'; full_p--); - *full_p = '\000'; - } - - // Copy the remainder of the relative path to the full path: - strcpy(full_p, rel_p); -} - -// This enum is used inside Create_Relative_Path: -enum PathCharType { - NULL_CHAR, - SLASH_CHAR, - PLAIN_CHAR -}; - -void Create_Relative_Path(char *rel_path, const char *curr, const char *full_path) -{ - // Copy both constant strings and convert them to uppercase: - int curr_len = strlen(curr); - char *up_curr = (char *)malloc(curr_len + 1); - strcpy(up_curr, curr); - _strupr(up_curr); - - int full_len = strlen(full_path); - char *up_full = (char *)malloc(full_len + 1); - strcpy(up_full, full_path); - _strupr(up_full); - - char *rel_p = rel_path; - - // Find shared prefix of curr and full path - const char *full_p = up_full; - const char *curr_p = up_curr; - for ( ; - *full_p && *full_p == *curr_p || (*full_p == '/' && *curr_p == '\\') || (*full_p == '\\' && *curr_p == '/'); - full_p++, curr_p++ - ); - - // If no shared prefix at this point set the relative path to 0 - // This will force the code to use the absolute path. - if (full_p == up_full) { - rel_path[0] = 0; - goto end; - } - - // The first different character for each string can be: a NULL, a slash, - // or an ordinary character. - PathCharType full_type, curr_type; - if (*full_p == '\000') { - full_type = NULL_CHAR; - } else { - if (*full_p == '/' || *full_p == '\\') { - full_type = SLASH_CHAR; - } else { - full_type = PLAIN_CHAR; - } - } - if (*curr_p == '\000') { - curr_type = NULL_CHAR; - } else { - if (*curr_p == '/' || *curr_p == '\\') { - curr_type = SLASH_CHAR; - } else { - curr_type = PLAIN_CHAR; - } - } - // If the last fullpath char is a NULL or both are slashes, we have an - // error - return full path - if (full_type == NULL_CHAR || (full_type == SLASH_CHAR && curr_type == SLASH_CHAR)) { - strcpy(rel_path, up_full); - goto end; - } - - // If the current path has ended (last char is a NULL) and the full path's - // last char is a slash, then just copy the remainder of the full path - // (w/o the slash) to the relative path, and exit. - if (curr_type == NULL_CHAR && full_type == SLASH_CHAR) { - full_p++; // skip slash - strcpy(rel_path, full_p); - goto end; - } - - // If one of following holds: - // 1) One of the last chars is a slash and the other is a plain char - // 2) The current path has ended (last char is NULL) and the last char - // of the full path is a plain char - // 3) The last char of both are plain chars and the previous char is not a - // slash - // Then we must backtrack both pointers until the characters before them - // are slashes. If there are no previous slashes, we have an error. - if ( (full_type == SLASH_CHAR && curr_type == PLAIN_CHAR) || - (curr_type == SLASH_CHAR && full_type == PLAIN_CHAR) || - (curr_type == NULL_CHAR && full_type == PLAIN_CHAR) || - (curr_type == PLAIN_CHAR && full_type == PLAIN_CHAR && - *(full_p-1) != '/' && *(full_p-1) != '\\') ) - { - for (; - full_p > up_full && - ( (*(full_p - 1) != '/' && *(full_p - 1) != '\\') || - (*(curr_p - 1) != '/' && *(curr_p - 1) != '\\') ); - full_p--, curr_p--); - } - - // If no shared prefix at this point (not even a drive letter) return the - // full path - if (full_p == up_full) { - strcpy(rel_path, up_full); - goto end; - } - - // Scan all directories levels in current path from shared point to end - - // for each one add a "../" to the relative path. Note that at this point - // we know we have to add at least one. - *rel_p++ = '.'; - *rel_p++ = '.'; - *rel_p++ = '\\'; - // Go over remaining current path, for each slash we find add one "../" to - // the relative path - for (; *curr_p; curr_p++) { - if (*curr_p == '/' || *curr_p == '\\') { - *rel_p++ = '.'; - *rel_p++ = '.'; - *rel_p++ = '\\'; - } - } - - // If the last char of the current path is a slash remove a "../" from the - // relative path. - if (*(curr_p - 1) == '/' || *(curr_p - 1) == '\\') { - rel_p -= 3; - } - - // Copy remaining full path (from shared point to end) to relative path - strcpy(rel_p, full_p); - -end: - free(up_curr); - free(up_full); -} - -bool Is_Full_Path(char * path) -{ - // first scan for a drive letter (scan for a colon) - if (strchr(path,':') != NULL) { - return true; - } - - // now scan for a "network" path (starts with "//") - if ((path[0] == '/') && (path[1] == '/')) { - return true; - } - if ((path[0] == '\\') && (path[1] == '\\')) { - return true; - } - - return false; -} - - -/*********************************************************************************************** - * Is_Max_Tri_Mesh -- Is this node a triangle mesh? * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/2/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Max_Tri_Mesh(INode * node) -{ - Object *obj = node->EvalWorldState(0).obj; - - if (obj && obj->CanConvertToType(Class_ID(TRIOBJ_CLASS_ID, 0))) { - return true; - } - return false; -} - - - -bool Is_Damage_Root(INode *node) -{ - if (node == NULL) - return false; - - // Is the node's parent the scene root? - INode *parent = node->GetParentNode(); - if (!parent || !parent->IsRootNode()) - return false; - - // Is the node's name in the form "damage.*"? - char *name = node->GetName(); - if (strnicmp(name, "damage.", strlen("damage.")) != 0) - return false; - -/* This won't pick up references to a dummy object for some reason. - // Does the node point to a dummy object? - Object *obj = node->GetObjectRef(); - if (!obj || !obj->CanConvertToType(Class_ID(DUMMY_CLASS_ID, 0))) - return false; -*/ - - return true; -} - - -/*********************************************************************************************** - * Is_Origin -- checks if the node is the origin of a model * - * * - * A node is an origin if its parent is the scene root, it is a dummy object, and its name * - * is of the form "origin.*" (case insensitive). All descendants of the origin will be * - * expressed in coordinates relative to the origin object. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/13/99 AJA : Created. - *=============================================================================================*/ -bool Is_Origin(INode * node) -{ - if (!node) return false; - if (node->IsRootNode()) return true; - if (node->IsHidden()) return false; - - // Is the node's parent the scene root? - INode *parent = node->GetParentNode(); - if (!parent || !parent->IsRootNode()) - return false; - - // Is the node's name in the form "origin.*"? - char *name = node->GetName(); - if (strnicmp(name, "origin.", strlen("origin.")) != 0) - return false; - -/* This won't pick up references to a dummy object for some reason. - // Does the node point to a dummy object? - Object *obj = node->GetObjectRef(); - if (!obj || !obj->CanConvertToType(Class_ID(DUMMY_CLASS_ID, 0))) - return false; -*/ - - // This is an origin. - return true; -} - - -/*********************************************************************************************** - * Is_Base_Origin -- Checks if the node is the origin for the base obect (non-LOD'd). * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/13/1999 AJA : Created. * - *=============================================================================================*/ -bool Is_Base_Origin(INode * node) -{ - if (!node) return false; - - if (node->IsRootNode()) return true; - - if (!Is_Origin(node)) return false; - - // An origin is the base object origin if it's name is "origin." or - // "origin.0" (a numeric value evaluating to zero as scanned by sscanf - // which would include "origin.00" "origin.000", etc.). - bool is_base_origin = false; - char *name = node->GetName(); - if (stricmp(name, "origin.") == 0) - is_base_origin = true; - else if (strlen(name) > strlen("origin.")) - { - // We know the first 7 characters are "origin." because that - // was tested in Is_Origin(). Is it "origin.0"? - int idx; - if ((sscanf(name+strlen("origin."), "%d", &idx) == 1) && (idx == 0)) - is_base_origin = true; - } - - return is_base_origin; -} - - -int Get_Lod_Level(INode *node) -{ - if (node->IsRootNode()) return 0; - if (!Is_Origin(node)) return -1; - - char *name = node->GetName(); - char *dot = strrchr(name, '.'); - assert(dot); - return atoi(dot+1); -} - -int Get_Damage_State(INode *node) -{ - if (!Is_Damage_Root(node)) return -1; - - char *name = node->GetName(); - char *dot = strrchr(name, '.'); - assert(dot); - return atoi(dot+1); -} - -INode *Find_Named_Node(char *nodename, INode *root) -{ - if (!root || !nodename) - return NULL; - - // Perform a breadth-first search of the tree for a node - // of the given name. - INode *child = NULL; - int i; - char cur_name[W3D_NAME_LEN]; - - // Is this the node we're looking for? - Set_W3D_Name(cur_name, root->GetName()); - if (strcmp(cur_name, nodename) == 0) - return root; - - // Check the children against the given name. - for (i = 0; i < root->NumChildren(); i++) - { - // Is it this child? - child = root->GetChildNode(i); - Set_W3D_Name(cur_name, child->GetName()); - if (strcmp(nodename, cur_name) == 0) - return child; - } - - // Wasn't any children. Check each child's descendants. - for (i = 0; i < root->NumChildren(); i++) - { - child = root->GetChildNode(i); - INode *found = Find_Named_Node(nodename, child); - if (found) - return found; - } - - // Didn't find the node anywhere. - return NULL; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/util.h b/Generals/Code/Tools/WW3D/max2w3d/util.h deleted file mode 100644 index b2ddd5e4e5..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/util.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/util.h 25 10/27/00 4:11p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/util.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/27/00 10:24a $* - * * - * $Revision:: 25 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef UTIL_H -#define UTIL_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#include - -#include "skin.h" -#include "nodelist.h" - - -/* -** Gets rid of very small numbers in the matrix -** (sets them to zero). -*/ -Matrix3 Cleanup_Orthogonal_Matrix(Matrix3 & mat); - -/* -** Naming utility functions -*/ -void Set_W3D_Name(char * set_name,const char * src); -void Split_Node_Name(const char * name,char * set_base,char * set_exten,int * set_exten_index); -bool Append_Lod_Character(char *meshname, int lod_level, INodeListClass *origin_list); - -/* -** File path utility functions -*/ -void Create_Full_Path(char *full_path, const char *cwd, const char *rel_path); -void Create_Relative_Path(char *rel_path, const char *cwd, const char *full_path); -bool Is_Full_Path(char * path); - -/* -** Check if this is some kind of triangle mesh inside of MAX. We will assume -** different default export behavior depending on whether the object is a -** triangle mesh or not. -*/ -bool Is_Max_Tri_Mesh(INode * node); - - -/* -** Origin support. -*/ -bool Is_Origin(INode *node); -bool Is_Base_Origin(INode *node); -INode *Find_Origin(INode *node); - -bool Is_Damage_Root(INode *node); - -/* -** Lod-Level and Damage State settings for an INode -*/ -int Get_Lod_Level(INode *node); -int Get_Damage_State(INode *node); - -/* -** Utility function to find a named node in a hierarchy. -*/ -INode *Find_Named_Node (char *nodename, INode *root); - - -/* -** Macros -*/ -#define SAFE_DELETE(pobject) \ - if (pobject) { \ - delete pobject; \ - pobject = NULL; \ - } \ - -#define SAFE_DELETE_ARRAY(pobject) \ - if (pobject) { \ - delete [] pobject; \ - pobject = NULL; \ - } \ - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/vchannel.cpp b/Generals/Code/Tools/WW3D/max2w3d/vchannel.cpp deleted file mode 100644 index 64d1dd846e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vchannel.cpp +++ /dev/null @@ -1,1396 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vchannel.cpp 10 10/30/00 6:56p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vchannel.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 5:26p $* - * * - * $Revision:: 10 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "vchannel.h" -#include -#include -#include -#include "w3d_file.h" -#include "w3dquat.h" -#include "bchannel.h" -#include "exportlog.h" - - -#define FILTER_TABLE_SIZE (256) -#define FILTER_TABLE_GEN_START (16) -#define FILTER_TABLE_GEN_SIZE (FILTER_TABLE_SIZE - FILTER_TABLE_GEN_START) - -static float filtertable[FILTER_TABLE_SIZE] = { - 0.00000001f, - 0.0000001f, - 0.000001f, - 0.00001f, - 0.0001f, - 0.001f, - 0.01f, - 0.1f, - 1.0f, - 10.0f, - 100.0f, - 1000.0f, - 10000.0f, - 100000.0f, - 1000000.0f, - 10000000.0f, - -}; -static bool table_valid = false; - - -VectorChannelClass::VectorChannelClass -( - uint32 id, - int maxframes, - uint32 flags, - int vectorlength, - float32 * identvect -) : - ID(id), - Flags(flags), - MaxFrames(maxframes), - VectorLen(vectorlength), - IsEmpty(true), - IdentVect(NULL), - Data(NULL), - Begin(0), - End(0), - ReduceAnimation(false), - ReduceAnimationPercent(0), - CompressAnimation(false), - CompressAnimationFlavor(0), - CompressAnimationTranslationError(0.0f), - CompressAnimationRotationError(0.0f) -{ - - assert(VectorLen > 0); - IdentVect = new float32[VectorLen]; - Data = new float32[MaxFrames * VectorLen]; - assert(Data); - assert(IdentVect); - - memcpy(IdentVect,identvect,VectorLen * sizeof(float32)); - memset(Data,0,MaxFrames * VectorLen * sizeof(float32)); - - // start "Begin" at the end of the array, whenever we set a value - // at an index less than "Begin", we push "Begin" back. - Begin = MaxFrames; - End = 0; - - if (false == table_valid) { - // Create Filter Table, used in delta compression - - for (int i=0; i= 0); - assert(frameidx < MaxFrames); - - for (int vi=0; vi= 0); - assert(frameidx < MaxFrames); - - return &(Data[frameidx * VectorLen]); -} - - -bool VectorChannelClass::SaveTimeCoded(ChunkSaveClass & csave, BitChannelClass *binmov) -{ - uint32 channelsize = sizeof(W3dTimeCodedAnimChannelStruct); - uint32 packetsize = (VectorLen * sizeof(float32)) + sizeof(uint32); - channelsize += packetsize * MaxFrames; - channelsize -= sizeof(uint32); - - W3dTimeCodedAnimChannelStruct * chn = (W3dTimeCodedAnimChannelStruct *)malloc(channelsize); - - if (chn == NULL) { - return false; - } - - chn->NumTimeCodes = MaxFrames; - chn->VectorLen = VectorLen; - chn->Pivot = ID; - chn->Flags = Flags; - - // Fetch Channel Data into new format - // tc [data] tc [data] tc [data] .. ... - uint32 fidx = 0; - - for (int fcount=0; fcount < MaxFrames; fcount++, fidx += (VectorLen+1) ) { - - uint32 * pivec; - float32 * pfvec; - - pivec = &chn->Data[ fidx ]; - pfvec = (float32 *) (pivec + 1); - - *pivec = fcount; - - if (binmov) { - - bool binary_move = binmov->Get_Bit( fcount ); - - // check for false binary movement - if (fcount != Begin) { - if (binary_move) { - *pivec |= W3D_TIMECODED_BINARY_MOVEMENT_FLAG; - } - } - else { - //if (log) log->printf("\nFALSE Binary\n"); - } - } - - - // Copy Vector - for (int vidx=0; vidx < VectorLen; vidx++) { - - pfvec[vidx] = get_value(fcount,vidx); - } - } - - // Compress the new structure - - VectorChannelClass::compress( chn ); - - // update the size - - float original_channelsize = channelsize; - - channelsize = sizeof(W3dTimeCodedAnimChannelStruct); - channelsize += packetsize * chn->NumTimeCodes; - channelsize -= sizeof(uint32); - - float percent = (((float)channelsize) / original_channelsize) * 100.0f; - // save - - ExportLog::printf("%.0f", percent); - - if (csave.Write(chn,channelsize) != channelsize) { - return false; - } - - if (chn != NULL) { - free(chn); - } - - if (!csave.End_Chunk()) { - return false; - } - - return true; - -} // SaveTimeCoded - - -/* -struct W3dAdaptiveDeltaAnimChannelStruct -{ - uint32 NumFrames; // number of frames of animation - uint16 Pivot; // pivot effected by this channel - uint8 VectorLen; // num Channels - uint8 Flags; // channel type - float Scale; // Filter Table Scale - - uint32 Data[1]; // OpCode Data Stream - -}; -*/ - -struct -{ - unsigned char filter : 7; - unsigned char flag : 1; - unsigned char d0 : 4; - unsigned char d1 : 4; - unsigned char d2 : 4; - unsigned char d3 : 4; - unsigned char d4 : 4; - unsigned char d5 : 4; - unsigned char d6 : 4; - unsigned char d7 : 4; - unsigned char d8 : 4; - unsigned char d9 : 4; - unsigned char d10 : 4; - unsigned char d11 : 4; - unsigned char d12 : 4; - unsigned char d13 : 4; - unsigned char d14 : 4; - unsigned char d15 : 4; - -} AdaptiveDeltaPacketStruct; - -// -// test compress Adaptive Delta packet -// -// inputs: filter - forced filter to use -// scale (filter table scale) -// value1 (continue compression from this initial value) -// float *indata // 16 values to compress -// float *outdata // 16 decompressed values -// -// output: float error; // aggregate error for packet -// -float VectorChannelClass::test_compress(int filter_index, float scale, float value1, float *indata, float *outdata) -{ - - float error = 0.0f; - - // compute filter - - float filter = filtertable[filter_index] * scale; - - assert(filter_index < FILTER_TABLE_SIZE); - - float last_value = value1; - - for(int data_idx=0; data_idx < 16; data_idx++) { - - // NOTE: DETERMINE best factor via Brute Force - // This helps under/over-flow problems - - // brute - int best_factor = 100; - float least_error = 999999999.9f; - for (float try_factor = -8.0f; try_factor < 8.0f; try_factor+=1.0f) { - float temp = (try_factor * filter) + last_value; // decompress using this filter - temp-=indata[data_idx]; // delta decompressed value, vs original value - temp=fabs(temp); - if (temp < least_error) { - least_error = temp; - best_factor = try_factor; - } - } - assert(best_factor <= 7); - assert(best_factor >=-8); - - float dfactor = best_factor; - - outdata[data_idx] = (dfactor * filter) + last_value; - // END BRUTE FORCE IT - - float delta = outdata[data_idx] - indata[data_idx]; - - //if (delta > error) error = delta; - error+= (delta * delta); - - last_value = outdata[data_idx]; - } - - return( sqrt(error) ); - -} // test_compress - -// -// compress Adaptive Delta packet -// -// inputs: filter - forced filter to use -// scale (filter table scale) -// value1 (continue compression from this initial value) -// float *indata // 16 values to compress -// unsigned char *pPacket -// -// output: float error; // aggregate error for packet -// -float VectorChannelClass::compress(int filter_index, float scale, float value1, float *indata, unsigned char *pPacket, float *outdata) -{ - float error = 0.0f; - - // compute filter - - float filter = filtertable[filter_index] * scale; - - assert(filter_index < FILTER_TABLE_SIZE); - - *pPacket = filter_index; - pPacket++; - - float last_value = value1; - - for(int data_idx=0; data_idx < 16; data_idx++) { - - // NOTE: PLAN TO ADD A LOOP IN HERE, to DETERMINE best factor via Brute Force - // This could help under/over-flow problems - { - // brute - int best_factor = 100; - float least_error = 999999999.9f; - for (float try_factor = -8.0f; try_factor < 8.0f; try_factor+=1.0f) { - float temp = (try_factor * filter) + last_value; // decompress using this filter - temp-=indata[data_idx]; // delta decompressed value, vs original value - temp=fabs(temp); - if (temp < least_error) { - least_error = temp; - best_factor = try_factor; - } - } - assert(best_factor <= 7); - assert(best_factor >=-8); - - float dfactor = best_factor; - - outdata[data_idx] = (dfactor * filter) + last_value; - - int pi = data_idx>>1; - - if (data_idx & 1) { - best_factor<<=4; - pPacket[pi]&=0x0f; - pPacket[pi]|=best_factor; - } - else { - best_factor&=0xf; - pPacket[pi]&=0xf0; - pPacket[pi]|=best_factor; - } - } - - // END BRUTE FORCE IT - - error+=fabs(outdata[data_idx] - indata[data_idx]); - - last_value = outdata[data_idx]; - - } - - return( error ); - -} // compress - - -bool VectorChannelClass::SaveAdaptiveDelta(ChunkSaveClass & csave, BitChannelClass *binmov) -{ - uint32 channelsize = sizeof(W3dAdaptiveDeltaAnimChannelStruct); - int packetsize = sizeof(AdaptiveDeltaPacketStruct); - int numpackets = (MaxFrames + 15) / 16; - channelsize += packetsize * numpackets * VectorLen; - channelsize -= sizeof(char); - channelsize += VectorLen * sizeof(float); - - W3dAdaptiveDeltaAnimChannelStruct * chn = (W3dAdaptiveDeltaAnimChannelStruct *)malloc(channelsize); - - if (chn == NULL) { - return false; - } - -// Brute Force Compressor - - // Initialize Chan Data - chn->NumFrames = MaxFrames; - chn->Pivot = ID; - chn->VectorLen = VectorLen; - chn->Flags = Flags; - chn->Scale = 0.0f; - memset(&chn->Data[0], channelsize - (sizeof(W3dAdaptiveDeltaAnimChannelStruct) - sizeof(char)), 0x00); - - assert(VectorLen <= 4); // otherwise temp vector won't have room - - float *initial = (float *)&chn->Data[0]; - float work[4]; - - // Fetch initial value - int i=0; - for (; i < VectorLen; i++) { - work[i] = initial[i] = get_value(0, i); - } - - float original_packet[16]; - float decompressed_packet[16]; - float scale = 0.0f; - float last_value=0.0f; - int frame = 1; - float delta; - - // Compute Scale - - for (int fidx=1; fidx < MaxFrames; fidx++) { - for (i=0; i scale) scale = delta; - } - } - - scale/=7.0f; // range of the delta encode is +- 7 units, in which ever filter range - // the smaller the scale, the better our precision is going to be - - // End Compute Scale - - for (i=0; i < numpackets; i++) { - for (int vi=0; viprintf("\nvi= %d frames %d to %d : error = %f ",vi, frame, frame+15, least_error); - - // Encode current packet - - unsigned char * pPacket; - - pPacket = (unsigned char *) &chn->Data[0]; // beginning of data struct - pPacket+= (VectorLen * sizeof(float)); // skip over initial values - pPacket+= (sizeof(AdaptiveDeltaPacketStruct) * VectorLen * ((frame-1)>>4)); // skip up to the appropriate packet - pPacket+= sizeof(AdaptiveDeltaPacketStruct) * vi; // skip up the appropriate vector index - - compress(best_filter, scale, last_value, original_packet, pPacket, decompressed_packet); - - // update work[vi]; - work[vi] = decompressed_packet[15]; - - } // for vi - frame+=16; - } // for numpackets - - - // print how big we are vs non-compressed - float rawsize = sizeof(W3dAnimChannelStruct); - rawsize += (VectorLen * sizeof(float32) * (MaxFrames)) - sizeof(float32); - - float percent = ((float)channelsize) / rawsize; - percent*=100.0f; - - ExportLog::printf("%.0f", percent); - - - // update final scale - chn->Scale = scale; - - if (csave.Write(chn,channelsize) != channelsize) { - return false; - } - - if (chn != NULL) { - free(chn); - } - - if (!csave.End_Chunk()) { - return false; - } - - return true; - -} // SaveAdaptiveDelta - - -bool VectorChannelClass::Save(ChunkSaveClass & csave, BitChannelClass *binmov) -{ - if (IsEmpty) return true; - - compute_range(); - if (EndFirstFrame = Begin; - chn->LastFrame = End; - chn->VectorLen = VectorLen; - chn->Pivot = ID; - chn->Flags = Flags; - - for (int fcount=0; fcount < End-Begin+1; fcount++) { - for (int vidx=0; vidx < VectorLen; vidx++) { - - int writeidx = fcount * VectorLen + vidx; - - chn->Data[writeidx] = get_value(Begin + fcount,vidx); - } - } - - if (csave.Write(chn,channelsize) != channelsize) { - return false; - } - - if (chn != NULL) { - free(chn); - } - - if (!csave.End_Chunk()) { - return false; - } - - } - - return true; -} - -void VectorChannelClass::SetSaveOptions(bool compress, int flavor, float Terr, float Rerr, bool reduce, int reduce_percent) -{ - - ReduceAnimation = reduce; - ReduceAnimationPercent = reduce_percent; - CompressAnimation = compress; - CompressAnimationFlavor = flavor; - CompressAnimationTranslationError = Terr; - CompressAnimationRotationError = DEG_TO_RAD(Rerr); - -} // SetSaveOptions - -// -// Set data in motion channel to identity vector -// R2 - set invisible data to repeat last known position, the previous algorthm caused problems with -// the current movie assets -// -void VectorChannelClass::ClearInvisibleData(BitChannelClass *vis) -{ - float *tvec; - - assert(VectorLen <= 8); - - bool prev_state = vis->Get_Bit( 0 ); - - tvec = Get_Vector( 0 ); - - for (int idx=0; idx < MaxFrames; idx++) { - - bool cur_state = vis->Get_Bit( idx ); - - if (cur_state != prev_state) { - prev_state = cur_state; - tvec = Get_Vector( idx ); - } - - if (false == cur_state) { - //Set_Vector( idx, IdentVect ); - Set_Vector( idx, tvec ); - } - } -} // ClearInvisibleData - - -void VectorChannelClass::set_value(int framenum,int vindex,float32 val) -{ - assert(framenum >= 0); - assert(framenum < MaxFrames); - assert(vindex >= 0); - assert(vindex < VectorLen); - - Data[framenum * VectorLen + vindex] = val; -} - -float32 VectorChannelClass::get_value(int framenum,int vindex) -{ - assert(framenum >= 0); - assert(framenum < MaxFrames); - assert(vindex >= 0); - assert(vindex < VectorLen); - - return Data[framenum * VectorLen + vindex]; -} - -bool VectorChannelClass::is_identity(float32 * vec) -{ - const double ERROR_TOLERANCE = 0.00005 * 0.00005; - double dist = 0.0; - - for (int vi=0; vi= 0) && (is_identity(Get_Vector(End)))) { - End--; - } -} // compute_range - - -// -// Remove a packet from a W3dTimeCodedAnimChanelStruct -// -void VectorChannelClass::remove_packet(W3dTimeCodedAnimChannelStruct * c, uint32 packet_idx) -{ - assert( c ); - assert( c->NumTimeCodes > 1 ); - - uint32 packet_size = c->VectorLen + 1; - uint32 packet_len = packet_size * sizeof(uint32); - - uint32 *src, *dst; - - dst = (uint32 *) &c->Data[ packet_size * packet_idx ]; - src = (uint32 *) &c->Data[ packet_size * (packet_idx + 1) ]; - - uint32 copy_length = (c->NumTimeCodes - (packet_idx + 1)) * packet_len; - - if (copy_length) { - - memcpy(dst, src, copy_length); - - } - - // Decrement Packet Count - c->NumTimeCodes--; - -} // remove_packet - -// -// Take a non-compressed TimeCoded Motion Channel -// and compress the packets -// -void VectorChannelClass::compress(W3dTimeCodedAnimChannelStruct * c) -{ - - assert( c ); - - - // Standard Error Threshold Compression - - double Terr = CompressAnimationTranslationError; - double Rerr = CompressAnimationRotationError; - - float TimeCodes_ct = c->NumTimeCodes; - - switch( c->Flags ) - { - case ANIM_CHANNEL_X: - case ANIM_CHANNEL_Y: - case ANIM_CHANNEL_Z: { - - while(1) { - - uint32 idx = find_useless_packet( c, Terr ); - - if (PACKETS_ALL_USEFUL == idx) break; - - remove_packet( c, idx ); - - } - - break; - } - - case ANIM_CHANNEL_XR: - case ANIM_CHANNEL_YR: - case ANIM_CHANNEL_ZR: { - - while(1) { - - uint32 idx = find_useless_packet( c, Rerr ); - - if (PACKETS_ALL_USEFUL == idx) break; - - remove_packet( c, idx ); - - } - - break; - } - - case ANIM_CHANNEL_Q: { - - while(1) { - - uint32 idx = find_useless_packetQ( c, Rerr ); - - if (PACKETS_ALL_USEFUL == idx) break; - - remove_packet( c, idx ); - - } - - break; - } - - default: // undefined channel - assert(0); - break; - } - - // Forced Reduction Phase - - if (ReduceAnimation) { - if (ReduceAnimationPercent) { - - float pct = ReduceAnimationPercent; - - pct *= (0.01f); - - pct = 1.0f - pct; - - // if out of range, don't even try - if (pct <= 0.0f) return; - if (pct >= 1.0f) return; - - pct*=TimeCodes_ct; - - pct+=0.5f; - - uint32 maxFrames = pct; - - if (maxFrames < 2) maxFrames = 2; - - if (maxFrames >= c->NumTimeCodes) return; // desired minimum already attained - - - switch( c->Flags ) - { - case ANIM_CHANNEL_X: - case ANIM_CHANNEL_Y: - case ANIM_CHANNEL_Z: - case ANIM_CHANNEL_XR: - case ANIM_CHANNEL_YR: - case ANIM_CHANNEL_ZR: { - - while(maxFrames < c->NumTimeCodes) { - - uint32 idx = find_least_useful_packet( c ); - if (PACKETS_ALL_USEFUL == idx) break; - remove_packet( c, idx ); - } - - break; - } - - case ANIM_CHANNEL_Q: { - - while(maxFrames < c->NumTimeCodes) { - - uint32 idx = find_least_useful_packetQ( c ); - if (PACKETS_ALL_USEFUL == idx) break; - remove_packet( c, idx ); - } - - break; - } - - default: // undefined channel - assert(0); - break; - } - } // if ReducePercent - - } // if Reduce - -} // compress - - - -// -// find a packet that isn't needed, and return the index -// if all packets are necessary, then return back PACKETS_ALL_USEFUL -// a useless packet is defined, as a packet that can be recreated -// via interpolation -// -// Make Sure we NEVER get rid of binary movement packets -// The rule is, you can't interpolate TOO a binary movement, but you can -// interpolate FROM -//#define W3D_TIMECODED_BINARY_MOVEMENT_FLAG 0x80000000 -// -uint32 VectorChannelClass::find_useless_packet(W3dTimeCodedAnimChannelStruct * c, double tolerance) -{ -#define MAX_VECTOR_SIZE 8 -static float32 tempvec[MAX_VECTOR_SIZE]; - - assert( c ); // make sure pointer exists - assert( c->NumTimeCodes ); // make sure some packets exist - assert( c->VectorLen <= MAX_VECTOR_SIZE ); - - uint32 packet_size = c->VectorLen + 1; - - if (c->NumTimeCodes > 1) { - if (c->NumTimeCodes > 2) { - - float32 *pVecSrc, *pVecDst, *pVecOriginal; - uint32 *pTcSrc, *pTcDst, *pTcOriginal; - - for(uint32 try_idx = 0; try_idx < (c->NumTimeCodes - 2); try_idx++) { - - // Src Pointers - pTcSrc = (uint32 *) &c->Data[ try_idx * packet_size ]; - pVecSrc = (float32 *) pTcSrc+1; - - // Original Vector we're trying to recreate - pTcOriginal = (uint32 *) &c->Data[ (try_idx + 1) * packet_size ]; - pVecOriginal = (float32 *) pTcOriginal+1; - - // Dst Pointers - pTcDst = (uint32 *) &c->Data[ (try_idx + 2 ) * packet_size ]; - pVecDst = (float32 *) pTcDst+1; - - // Skip automagically, if binary movement involved - if (*pTcOriginal & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy - } - if (*pTcDst & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy either - } - - // Linear Interpolate between Src, and Dst, to recreate the - // Original - - float32 tStart = ((*pTcSrc) & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG); // upgrade to floats - float32 tRecreate = *pTcOriginal; - float32 tEnd = *pTcDst; - float32 tRatio = (tRecreate - tStart) / (tEnd - tStart); - - uint32 idx=0; - for (; idx < c->VectorLen; idx++) { - - tempvec[ idx ] = WWMath::Lerp(pVecSrc[idx], pVecDst[idx], tRatio); - - } - - // Compare Original to our re-creation - - bool close_enough = true; - - for (idx=0; idx < c->VectorLen; idx++) { - - float32 delta; - - delta = fabs(pVecOriginal[idx] - tempvec[idx]); - - if (delta > tolerance) { - close_enough = false; - break; - } - - } - - // If our Recreation is very close to the original, - // then discard the original - - if (true == close_enough) { - return (try_idx + 1); - } - - // else continue - - } // for - - } - else { - // Special Case, when there are only 2 time codes - // Check to see if they are equal, value - // if so, then return the 2nd timecode as useless - - float32 *pVecSrc = (float32 *) &c->Data[ 1 ]; - float32 *pVecDst = (float32 *) &c->Data[ packet_size + 1 ]; - - bool identical = true; - - if ((c->Data[ packet_size ] & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) == 0) { - - for(uint32 idx=0; idx < c->VectorLen; idx++) { - - float32 delta; - - delta = fabs(pVecDst[idx] - pVecSrc[idx]); - - if (delta > tolerance) { - identical = false; - break; - } - - } - - if (identical) return( 1 ); - - } - } - } - - return( PACKETS_ALL_USEFUL ); - -} // find_useless_packet - - -// -// Special Case for Quaternion Packets -// -// Make Sure we NEVER get rid of binary movement packets -// The rule is, you can't interpolate TOO a binary movement, but you can -// interpolate FROM -//#define W3D_TIMECODED_BINARY_MOVEMENT_FLAG 0x80000000 -// -uint32 VectorChannelClass::find_useless_packetQ(W3dTimeCodedAnimChannelStruct * c, double tolerance) -{ - - assert( c ); // make sure pointer exists - assert( c->NumTimeCodes ); // make sure some packets exist - assert( c->VectorLen == 4); - - uint32 packet_size = c->VectorLen + 1; - - if (c->NumTimeCodes > 1) { - if (c->NumTimeCodes > 2) { - - float32 *pVecSrc, *pVecDst, *pVecOrg; - uint32 *pTcSrc, *pTcDst, *pTcOrg; - - for(uint32 try_idx = 0; try_idx < (c->NumTimeCodes - 2); try_idx++) { - - // Src Pointers - pTcSrc = (uint32 *) &c->Data[ try_idx * packet_size ]; - pVecSrc = (float32 *) pTcSrc+1; - - // Original Vector we're trying to recreate - pTcOrg = (uint32 *) &c->Data[ (try_idx + 1) * packet_size ]; - pVecOrg = (float32 *) pTcOrg+1; - - // Dst Pointers - pTcDst = (uint32 *) &c->Data[ (try_idx + 2 ) * packet_size ]; - pVecDst = (float32 *) pTcDst+1; - - // Sphereical Linear Interpolate between Src, and Dst, to recreate the - // Original - - // Skip automagically, if binary movement involved - if (*pTcOrg & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy - } - if (*pTcDst & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy either - } - - float32 tStart = ((*pTcSrc) & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG); // upgrade to floats - float32 tRecreate = *pTcOrg; - float32 tEnd = *pTcDst; - float32 tRatio = (tRecreate - tStart) / (tEnd - tStart); - - - Quaternion qSrc(1); - qSrc.Set(pVecSrc[0],pVecSrc[1],pVecSrc[2],pVecSrc[3]); - - Quaternion qOrg(1); - qOrg.Set(pVecOrg[0],pVecOrg[1],pVecOrg[2],pVecOrg[3]); - - Quaternion qDst(1); - qDst.Set(pVecDst[0],pVecDst[1],pVecDst[2],pVecDst[3]); - - Quaternion q = Slerp( qSrc, qDst, tRatio ); - - Quaternion Delta(1); - Delta = Inverse(qOrg) * q; - - double angle = acosf( fabs( Delta.W ) ) * 2.0; - - if (angle <= tolerance ) { - return (try_idx + 1); - } - - // else continue - - } // for - - } - - } - else { - // Special Case, when there are only 2 time codes - // Check to see if they are equal, value - // if so, then return the 2nd timecode as useless - - float32 *pVecSrc = (float32 *) &c->Data[ 1 ]; - float32 *pVecDst = (float32 *) &c->Data[ packet_size + 1 ]; - - if ((c->Data[ packet_size ] & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) == 0) { - - Quaternion qSrc(1); - qSrc.Set(pVecSrc[0], pVecSrc[1], pVecSrc[2], pVecSrc[3]); - - Quaternion qDst(1); - qDst.Set(pVecDst[0], pVecDst[1], pVecDst[2], pVecDst[3]); - - Quaternion Delta(1); - Delta = Inverse(qSrc) * qDst; - - double angle = acosf( fabs( Delta.W ) ) * 2.0; - - if (angle <= tolerance ) { - return (1); - } - } - } - - return( PACKETS_ALL_USEFUL ); - -} // find_useless_packetQ - - -// -// Instead of using a fixed error threshold, find the packet -// that generates the least amount of error, via removal -// -// Make Sure we NEVER get rid of binary movement packets -// The rule is, you can't interpolate too a binary movement, but you can -// interpolate FROM -//#define W3D_TIMECODED_BINARY_MOVEMENT_FLAG 0x80000000 -// -uint32 VectorChannelClass::find_least_useful_packet(W3dTimeCodedAnimChannelStruct *c) -{ - -static float32 tempvec[MAX_VECTOR_SIZE]; - - assert( c ); // make sure pointer exists - assert( c->NumTimeCodes ); // make sure some packets exist - assert( c->VectorLen <= MAX_VECTOR_SIZE ); - - uint32 packet_size = c->VectorLen + 1; - - double leasterror = 9999999.0f; - uint32 ret_idx = PACKETS_ALL_USEFUL; - - if (c->NumTimeCodes > 1) { - if (c->NumTimeCodes > 2) { - - float32 *pVecSrc, *pVecDst, *pVecOriginal; - uint32 *pTcSrc, *pTcDst, *pTcOriginal; - - for(uint32 try_idx = 0; try_idx < (c->NumTimeCodes - 2); try_idx++) { - - // Src Pointers - pTcSrc = (uint32 *) &c->Data[ try_idx * packet_size ]; - pVecSrc = (float32 *) pTcSrc+1; - - // Original Vector we're trying to recreate - pTcOriginal = (uint32 *) &c->Data[ (try_idx + 1) * packet_size ]; - pVecOriginal = (float32 *) pTcOriginal+1; - - // Dst Pointers - pTcDst = (uint32 *) &c->Data[ (try_idx + 2 ) * packet_size ]; - pVecDst = (float32 *) pTcDst+1; - - // Skip automagically, if binary movement involved - if (*pTcOriginal & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy - } - if (*pTcDst & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy either - } - - // Linear Interpolate between Src, and Dst, to recreate the - // Original - - float32 tStart = ((*pTcSrc) & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG); // upgrade to floats - float32 tRecreate = *pTcOriginal; - float32 tEnd = *pTcDst; - float32 tRatio = (tRecreate - tStart) / (tEnd - tStart); - - uint32 idx=0; - for (; idx < c->VectorLen; idx++) { - - tempvec[ idx ] = WWMath::Lerp(pVecSrc[idx], pVecDst[idx], tRatio); - - } - - // Compare Original to our re-creation - - double delta = 0.0; - - - for (idx=0; idx < c->VectorLen; idx++) { - - double tmp; - - tmp = pVecOriginal[idx] - tempvec[idx]; - - delta += (tmp * tmp); - - } - - delta = sqrtf( delta ); - - if (delta < leasterror) - { - - // If our Recreation is very close to the original, - // then discard the original - leasterror = delta; - ret_idx =(try_idx + 1); - } - - // else continue - - } // for - - return( ret_idx ); - - } - else { - - if ((c->Data[ packet_size ] & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) == 0) { - return( 1 ); - } - } - } - - - return( PACKETS_ALL_USEFUL ); - - -} // Find Least useful packet - - -// -// Instead of using a fixed error threshold, find the packet -// that generates the least amount of error, via removal -// special case for Quaternion channel -// -// Make Sure we NEVER get rid of binary movement packets -// The rule is, you can't interpolate FROM a binary movement, but you can -// interpolate TOO -//#define W3D_TIMECODED_BINARY_MOVEMENT_FLAG 0x80000000 -// -uint32 VectorChannelClass::find_least_useful_packetQ(W3dTimeCodedAnimChannelStruct *c) -{ - - assert( c ); // make sure pointer exists - assert( c->NumTimeCodes ); // make sure some packets exist - assert( c->VectorLen == 4); - - uint32 packet_size = c->VectorLen + 1; - - double leasterror = 9999999.0f; - uint32 ret_idx = PACKETS_ALL_USEFUL; - - if (c->NumTimeCodes > 1) { - if (c->NumTimeCodes > 2) { - - float32 *pVecSrc, *pVecDst, *pVecOrg; - uint32 *pTcSrc, *pTcDst, *pTcOrg; - - for(uint32 try_idx = 0; try_idx < (c->NumTimeCodes - 2); try_idx++) { - - // Src Pointers - pTcSrc = (uint32 *) &c->Data[ try_idx * packet_size ]; - pVecSrc = (float32 *) pTcSrc+1; - - // Original Vector we're trying to recreate - pTcOrg = (uint32 *) &c->Data[ (try_idx + 1) * packet_size ]; - pVecOrg = (float32 *) pTcOrg+1; - - // Dst Pointers - pTcDst = (uint32 *) &c->Data[ (try_idx + 2 ) * packet_size ]; - pVecDst = (float32 *) pTcDst+1; - - // Skip automagically, if binary movement involved - if (*pTcOrg & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy - } - if (*pTcDst & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) { - continue; // can't get rid of this guy either - } - - // Spherical Linear Interpolate between Src, and Dst, to recreate the - // Original - - float32 tStart = ((*pTcSrc) & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG); // upgrade to floats - float32 tRecreate = *pTcOrg; - float32 tEnd = *pTcDst; - float32 tRatio = (tRecreate - tStart) / (tEnd - tStart); - - - Quaternion qSrc(1); - qSrc.Set(pVecSrc[0],pVecSrc[1],pVecSrc[2],pVecSrc[3]); - - Quaternion qOrg(1); - qOrg.Set(pVecOrg[0],pVecOrg[1],pVecOrg[2],pVecOrg[3]); - - Quaternion qDst(1); - qDst.Set(pVecDst[0],pVecDst[1],pVecDst[2],pVecDst[3]); - - Quaternion q = Slerp( qSrc, qDst, tRatio ); - - Quaternion Delta(1); - Delta = Inverse(qOrg) * q; - - double angle = acosf( fabs( Delta.W ) ) * 2; - - if (angle < leasterror ) { - leasterror = angle; - ret_idx = (try_idx + 1); - } - - // else continue - - } // for - - return( ret_idx ); - - } - - } - else { - // Special Case, when there are only 2 time codes - // Check to see if they are equal, value - // if so, then return the 2nd timecode as useless - - if ((c->Data[ packet_size ] & W3D_TIMECODED_BINARY_MOVEMENT_FLAG) == 0) { - return( 1 ); - } - } - - - return( PACKETS_ALL_USEFUL ); - -} // find_least_useful_packetQ - - -// EOF - vchannel.cpp \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/vchannel.h b/Generals/Code/Tools/WW3D/max2w3d/vchannel.h deleted file mode 100644 index 6021f8da57..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vchannel.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vchannel.h 8 10/30/00 6:56p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vchannel.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/30/00 5:25p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef VCHANNEL_H -#define VCHANNEL_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef BITTYPE_H -#include "BITTYPE.H" -#endif - -#ifndef CHUNKIO_H -#include "chunkio.h" -#endif - -#ifndef W3D_FILE_H -#include "w3d_file.h" -#endif - - -class BitChannelClass; - -/* - - This class is a container for an array of vectors. It will keep - track of whether the entire array of vectors is zero, and if not - where the non-zero vectors begin and end. - - VectorChannelClass is used in exporting motion. Motion data - is broken into separate channels for X, Y, Z, and orientation. - Then if any of the channels are empty, they don't have to be stored. - The X,Y,Z channels all contain one-dimensional vectors and the - orientation channel contains four-dimensional vectors. - -*/ -// for compression -#define DEFAULT_LOSSY_ERROR_TOLERANCE (0.0001) -#define PACKETS_ALL_USEFUL (0xFFFFFFFF) - -class VectorChannelClass -{ -public: - - VectorChannelClass(uint32 id,int maxframes,uint32 flags,int vectorlength,float32 * identvec); - ~VectorChannelClass(void); - - void Set_Vector(int framenumber,float32 * vector); - float * Get_Vector(int frameidx); - bool Is_Empty(void) { return IsEmpty; } - void SetSaveOptions(bool compress, int flavor, float Terr, float Rerr, bool reduce, int reduce_percent); - bool Save(ChunkSaveClass & csave, BitChannelClass *binmov); - void ClearInvisibleData(BitChannelClass *vis); - -private: - - uint32 ID; - uint32 Flags; - int MaxFrames; - int VectorLen; - bool IsEmpty; - - float32 * IdentVect; - float32 * Data; - int Begin; - int End; - - // Save Options - - bool ReduceAnimation; - int ReduceAnimationPercent; - bool CompressAnimation; - int CompressAnimationFlavor; - float CompressAnimationTranslationError; - float CompressAnimationRotationError; - - // Write a single value - void set_value(int framenum,int vindex,float32 val); - - // Read a single value - float32 get_value(int framenum,int vindex); - - // Test a vector against the "identity" vector - bool is_identity(float32 * vec); - - // This function finds the start and end of the "non-identity" data - void compute_range(void); - - // compress functions - void compress(W3dTimeCodedAnimChannelStruct * c); - float compress(int filter_index, float scale, float value1, float *indata, unsigned char *pPacket, float *outdata); - float test_compress(int filter_index, float scale, float value1, float *indata, float *outdata); - uint32 find_useless_packet(W3dTimeCodedAnimChannelStruct * c, double tolerance); - uint32 find_useless_packetQ(W3dTimeCodedAnimChannelStruct * c, double tolerance); - uint32 find_least_useful_packet(W3dTimeCodedAnimChannelStruct *c); - uint32 find_least_useful_packetQ(W3dTimeCodedAnimChannelStruct *c); - void remove_packet(W3dTimeCodedAnimChannelStruct * c, uint32 packet_idx); - bool SaveTimeCoded(ChunkSaveClass & csave, BitChannelClass *binmov); - bool SaveAdaptiveDelta(ChunkSaveClass & csave, BitChannelClass *binmov); - -}; - -#endif /*VCHANNEL_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/vxl.cpp b/Generals/Code/Tools/WW3D/max2w3d/vxl.cpp deleted file mode 100644 index 574aee48b3..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vxl.cpp +++ /dev/null @@ -1,722 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vxl.cpp 4 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G Math Library * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vxl.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/14/97 3:07p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "vxl.h" -#include "errclass.h" - - -/* - - This module will voxelize one or more meshes. It is only used to compute - some things like Moment of Inertia and Center of Mass for the object. - Much of the code which was doing the shading and lighting computations - has been stripped out. - -*/ - -static void compute_dimensions( - INodeListClass & meshlist, - const Matrix3 & parenttm, - TimeValue curtime, - Point3 * min, - Point3 * max - ); - -#define VIS_UNKNOWN 0 -#define VIS_SOLID 1 -#define VIS_VISIBLE 2 - -/************************************************************************ -* VoxelClass Constructor -* -* Voxelize a list of meshes. -* -* INPUTS: -* -* OUTPUS: -* -************************************************************************/ -VoxelClass::VoxelClass -( - INodeListClass & meshlist, - int resolution, - Matrix3 parenttm, - TimeValue time, - Progress_Meter_Class & meter -) -{ - Resolution = resolution; - ParentTM = parenttm; - CurTime = time; - - XDim = resolution + 1; - YDim = resolution + 1; - ZDim = resolution + 1; - - // assert that none of the dimensions - // were too big. (if this happened, VoxelData is going - // to be a *HUMONGOUS* amount of memory...) - assert(XDim < 256); - assert(YDim < 256); - assert(ZDim < 256); - - // Allocate visibility flags array - VisData = new uint8[XDim * YDim * ZDim]; - if (VisData == NULL) { - throw ErrorClass("out of memory!"); - } - - memset(VisData,0,XDim*YDim*ZDim); - - /* - ** compute the two corners of the bounding box of - ** these meshes. Note that these coordinates are - ** be specified in the space defined by ParentTM. - */ - Point3 min; - Point3 max; - compute_dimensions(meshlist,ParentTM,CurTime,&min,&max); - - - /* - ** The voxelizer uses three values: offset, size, - ** and scale: - ** - ** offset - the position of the "most negative" corner - ** size - dimensions of the box - ** scale - scale factor to apply to vertices after they've - ** been translated by -offset - ** - */ - Size = max - min; - Offset = min; - Scale.x = Resolution / Size.x; - Scale.y = Resolution / Size.y; - Scale.z = Resolution / Size.z; - - - /* - ** Dimensions of a single voxel block - */ - BlockXDim = Size.x / Resolution; - BlockYDim = Size.y / Resolution; - BlockZDim = Size.z / Resolution; - - - /* - ** Voxelize the meshes! - */ - Quantize_Meshes - ( - meshlist, - meter - ); - -} - - -/************************************************************************ -* VoxelClass Destructor -* -* De-Allocates memory used by the voxel object -* -* INPUTS: -* none -* -* OUTPUS: -* none -* -************************************************************************/ -VoxelClass::~VoxelClass() -{ - if (VisData != NULL) delete[] VisData; -} - - -/************************************************************************ -* VoxelClass::Quantize_Meshes -* -* Generataes voxel data from the list of meshes passed in. -* -* INPUTS: -* meshlist - list of meshes to "voxelize" -* meter - progress meter object -* -* OUTPUS: -* none -* -************************************************************************/ -void VoxelClass::Quantize_Meshes -( - INodeListClass & meshlist, - Progress_Meter_Class & meter -) -{ - /* - ** Progress meter updating - */ - meter.Finish_In_Steps(2); - Progress_Meter_Class slabmeter(meter,meter.Increment); - slabmeter.Finish_In_Steps(ZDim); - - /* - ** Generate the Voxel Layer for each slice of the model - */ - float min_z = Offset.z; - float max_z = Offset.z + Size.z; - float sliceh = Size.z / (float)ZDim; - - for (int slicecount = 0; slicecount < ZDim; slicecount++ ) - { - float slicez = min_z + (max_z - min_z) * ((float)slicecount/(float)(ZDim-1)); - - VoxelLayerClass * vlayer = new VoxelLayerClass - ( - meshlist, - CurTime, - ParentTM, - Offset, - Scale, - slicez, - sliceh, - XDim, - YDim - ); - - Set_Layer(*vlayer,slicecount); - - slabmeter.Add_Increment(); - if (slabmeter.Cancelled()) throw ErrorClass("Export Cancelled"); - - delete vlayer; - } - - meter.Add_Increment(); - - // 3D visibility calculations - Progress_Meter_Class vismeter(meter,meter.Increment); - Compute_Visiblity(vismeter); - - meter.Add_Increment(); - - // Compute the voxel bounding box - Compute_Bounding_Box(Size,Offset); -} - -/************************************************************************ -* VoxelClass::Set_Layer -* -* Sets a layer of the Voxel data according to contents of the passed -* bitmap. -* -* INPUTS: -* bitmap - bitmap to use as the source data -* z - z co-ordinate of the layer to set -* -* OUTPUS: -* none -* -************************************************************************/ -void VoxelClass::Set_Layer -( - VoxelLayerClass & vlayer, - uint32 z -) -{ - // bitmap must have same x&y dimensions as the voxel space - if (vlayer.Get_Width() != (unsigned)XDim) return; - if (vlayer.Get_Height() != (unsigned)YDim) return; - - - // Copy the solid voxels into our voxel cube - for (unsigned j=0; j= 0; x--) { - if (raw_read_vis(x,y,z) == VIS_SOLID) break; - raw_set_vis(x,y,z,VIS_VISIBLE); - } - } - - // Tunneling in the Y direction - for (x = 0; x < (int)XDim; x++) { - - for (y = 0; y < (int)YDim; y++) { - if (raw_read_vis(x,y,z) == VIS_SOLID) break; - raw_set_vis(x,y,z,VIS_VISIBLE); - } - - for (y = (int)YDim-1; y >= 0; y--) { - if (raw_read_vis(x,y,z) == VIS_SOLID) break; - raw_set_vis(x,y,z,VIS_VISIBLE); - } - } - - meter.Add_Increment(); - if (meter.Cancelled()) throw ErrorClass("Export Cancelled"); - } // done with the X-Y layers - - - ///////////////////////////////////////////////////////////// - // Now I'm going to tunnel up and down through the object. - // To do this, I will loop across the width of the object - // (the X direction) and at each step tunnel through the - // Y-Z plane from all points along the top and bottom. - ///////////////////////////////////////////////////////////// - for (x = 0; x < (int)XDim; x++) { - - // Tunneling in the Z direction - for (y = 0; y < (int)YDim; y++) { - - for (z = 0; z < (int)ZDim; z++) { - if (raw_read_vis(x,y,z) == VIS_SOLID) break; - raw_set_vis(x,y,z,VIS_VISIBLE); - } - - for (z = (int)ZDim-1; z >= 0; z--) { - if (raw_read_vis(x,y,z) == VIS_SOLID) break; - raw_set_vis(x,y,z,VIS_VISIBLE); - } - } - - meter.Add_Increment(); - if (meter.Cancelled()) throw ErrorClass("Export Cancelled"); - } // done with the X-Z layers - - - /////////////////////////////////////////////////////////// - // Now, we search for all of the VIS_UNKNOWN voxels and - // set them to VIS_SOLID and we are done voxelizing - /////////////////////////////////////////////////////////// - for (z = 0; z < (int)ZDim; z++) { - for (y = 0; y < (int)YDim; y++) { - for (x = 0; x < (int)XDim; x++) { - - int vis = raw_read_vis(x,y,z); - if (vis == VIS_UNKNOWN) { - raw_set_vis(x,y,z,VIS_SOLID); - } - - } - } - meter.Add_Increment(); - if (meter.Cancelled()) throw ErrorClass("Export Cancelled"); - } -} - - -/************************************************************************ -* VoxelClass::raw_read_vis -* -* safe read of the visiblity data at i,j,k -* -* INPUTS: -* i,j,k - integer indices of the visiblity data to read -* -* OUTPUS: -* none -* -************************************************************************/ -uint8 VoxelClass::raw_read_vis -( - int i, - int j, - int k -) -{ - if (i<0) return 0; - if (j<0) return 0; - if (k<0) return 0; - if (i>=(int)XDim) return 0; - if (j>=(int)YDim) return 0; - if (k>=(int)ZDim) return 0; - - return VisData[i + j*XDim + k*XDim*YDim]; -} - -/************************************************************************ -* VoxelClass::raw_set_vis -* -* safe set of the visibility data at i,j,k -* -* INPUTS: -* i,j,k - integer indices of the visibility data to set -* val - value to set. -* -* OUTPUS: -* none -* -************************************************************************/ -void VoxelClass::raw_set_vis( - int i, - int j, - int k, - uint8 val -) -{ - if (i<0) return; - if (j<0) return; - if (k<0) return; - if (i>=(int)XDim) return; - if (j>=(int)YDim) return; - if (k>=(int)ZDim) return; - - VisData[i + j*XDim + k*XDim*YDim] = val; - return; -} - - -void compute_dimensions -( - INodeListClass & meshlist, - const Matrix3 & parenttm, - TimeValue curtime, - Point3 * set_min, - Point3 * set_max -) -{ - // Find the minimum and maximum extents in the X, Y, and Z directions. - // Also find the total surface area. - Point3 min; - Point3 max; - float surface_area = 0.0; - - BOOL first = TRUE; - - for ( unsigned i = 0; i < meshlist.Num_Nodes() ; ++ i ) - { - - // Get the relavent data from the INode - INode * n = meshlist[i]; - Object * obj = n->EvalWorldState(curtime).obj; - TriObject * tri = (TriObject *)obj->ConvertToType(curtime, triObjectClassID); - Mesh * mesh = &(tri->mesh); - Matrix3 tm = n->GetObjTMAfterWSM(curtime); - - - // Compute a matrix which takes vertices of this mesh into the - // specified parent space. - Matrix3 delta = tm * Inverse(parenttm); - - unsigned verts = mesh->getNumVerts(); - unsigned faces = mesh->getNumFaces(); - - for ( unsigned vert_index = 0; vert_index < verts; ++ vert_index ) - { - Point3 p = delta * mesh->verts [vert_index]; - - if ( first ) - { - first = FALSE; - min = max = p; - } - else - { - if ( p.x < min.x ) min.x = p.x; - if ( p.y < min.y ) min.y = p.y; - if ( p.z < min.z ) min.z = p.z; - - if ( p.x > max.x ) max.x = p.x; - if ( p.y > max.y ) max.y = p.y; - if ( p.z > max.z ) max.z = p.z; - } - } - - for ( unsigned face_index = 0; face_index < faces; ++ face_index ) - { - Face face = mesh->faces [ face_index ]; - - Point3 a = mesh->verts [ face.v[0] ]; - Point3 b = mesh->verts [ face.v[1] ]; - Point3 c = mesh->verts [ face.v[2] ]; - - double area = 0.5 * Length ( CrossProd ( b - a, c - a ) ); - - surface_area += (float) area; - } - } - - // In the odd case that there are no vertices.... - if ( first ) - { - min = max = Point3 (0,0,0); - } - - *set_min = min; - *set_max = max; -} - -uint8 VoxelClass::Is_Solid(int i,int j,int k) -{ - return (raw_read_vis(i,j,k) == VIS_SOLID); -} - -void VoxelClass::Compute_Physical_Properties(double Volume[1],double CM[3],double I[9]) -{ - int i,j,k; - - // volume of a single voxel block: - double bvol = BlockXDim * BlockYDim * BlockZDim; - - // volume of object - double volume = 0.0; - Point3 cm(0.0,0.0,0.0); - int numblocks = 0; - - //////////////////////////////////////////////////////////////////////// - // compute the volume and the center of mass - //////////////////////////////////////////////////////////////////////// - for (k=0; k < ZDim; k++) { - for (j=0; j < YDim; j++) { - for (i=0; i < XDim; i++) { - if (Is_Solid(i,j,k)) { - - // Add this block's volume to the total - volume += bvol; - - // Add this block's position to the CM computation - cm += Voxel_Position(i,j,k); - numblocks++; - } - } - } - } - - cm.x = cm.x / (double)numblocks; - cm.y = cm.y / (double)numblocks; - cm.z = cm.z / (double)numblocks; - - CM[0] = cm.x; - CM[1] = cm.y; - CM[2] = cm.z; - - Volume[0] = volume; - - //////////////////////////////////////////////////////////////////////// - // compute the inertia tensor assuming constant density and factoring - // density out: - // - // - // ( ( ( 2 2 - // | | | y + z -(xy) -(xz) - // | | | - // | | | 2 2 - // I= den*| | | -(xy) x + z -(yz) dx dy dz - // | | | - // | | | 2 2 - // | | | -(xz) -(yz) x + y - // ) ) ) - // - //////////////////////////////////////////////////////////////////////// - - for (i=0; i < 9; i++) { - I[i] = 0.0; - } - - for (k=0; k < ZDim; k++) { - for (j=0; j < YDim; j++) { - for (i=0; i < XDim; i++) { - if (Is_Solid(i,j,k)) { - - // position of block, relative to the CM - Point3 pos = Voxel_Position(i,j,k) - cm; - - // moments of inertia - double y2z2 = pos.y * pos.y + pos.z * pos.z; - double x2z2 = pos.x * pos.x + pos.z * pos.z; - double x2y2 = pos.x * pos.x + pos.y * pos.y; - - // products of inertia - double xy = pos.x * pos.y; - double xz = pos.x * pos.z; - double yz = pos.y * pos.z; - - // add to the running total! - I[0] += y2z2 * bvol; - I[1] += -xy * bvol; - I[2] += -xz * bvol; - - I[3] += -xy * bvol; - I[4] += x2z2 * bvol; - I[5] += -yz * bvol; - - I[6] += -xz * bvol; - I[7] += -yz * bvol; - I[8] += x2y2 * bvol; - } - } - } - } -} - -Point3 VoxelClass::Voxel_Position(int i,int j,int k) -{ - // returns the coordinates of the center of block(i,j,k) - return Point3( - Offset.x + i * BlockXDim + BlockXDim / 2.0, - Offset.y + j * BlockYDim + BlockYDim / 2.0, - Offset.z + k * BlockZDim + BlockZDim / 2.0 - ); -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/vxl.h b/Generals/Code/Tools/WW3D/max2w3d/vxl.h deleted file mode 100644 index 9cbc32e27e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vxl.h +++ /dev/null @@ -1,144 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vxl.h 4 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vxl.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/26/97 1:35p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef VXL_H -#define VXL_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#include - -#ifndef NODELIST_H -#include "nodelist.h" -#endif - -#ifndef VXLLAYER_H -#include "vxllayer.h" -#endif - -#ifndef PROGRESS_H -#include "PROGRESS.H" -#endif - - -/* - This class is used to compute approximate physical properties of a polygon - mesh or meshes. Some of these properties are listed below: - - - Moment of Inertia Tensor (with density factored out) - - Center of Mass - - Volume - - It is a cannibalized version of the code from the voxel plugin. -*/ - -class VoxelClass -{ -public: - - VoxelClass( - INodeListClass & meshlist, - int resolution, - Matrix3 parenttm, - TimeValue time, - Progress_Meter_Class & meter - ); - - ~VoxelClass(void); - - int Get_Width() { return XDim; } - int Get_Height() { return YDim; } - int Num_Layers() { return ZDim; } - uint8 Is_Solid(int i,int j,int k); - - void Compute_Physical_Properties(double Volume[1],double CM[3],double I[9]); - -private: - - int XDim; - int YDim; - int ZDim; - - double BlockXDim; - double BlockYDim; - double BlockZDim; - - unsigned char * VisData; - - float Resolution; // resolution of the voxel grid - TimeValue CurTime; - Point3 Offset; - Point3 Size; - Point3 Scale; // three scale values to fit the meshes into the desired grid - - Point3 BoxCorner[8]; // World-Space corners of the bounding box of the voxel space - Matrix3 ParentTM; // coordinate system of the parent of this object. - - void raw_set_vis(int i,int j,int k,uint8 val); - uint8 raw_read_vis(int i,int j,int k); - - int voxel_touches_space(int i,int j,int k); - void purge_interior(void); - - void Quantize_Meshes - ( - INodeListClass & meshlist, - Progress_Meter_Class & meter - ); - - // set one layer of the voxel object - void Set_Layer - ( - VoxelLayerClass & layer, - uint32 z - ); - - // compute the bounding box - void Compute_Bounding_Box(Point3 size,Point3 offset); - - // 3D visibility - void Compute_Visiblity(Progress_Meter_Class & meter); - - // returns the position of the center of voxel(i,j,k) - Point3 Voxel_Position(int i,int j,int k); -}; - - -#endif /*VXL_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/vxldbg.cpp b/Generals/Code/Tools/WW3D/max2w3d/vxldbg.cpp deleted file mode 100644 index 3928b7e139..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vxldbg.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vxldbg.cpp 3 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vxldbg.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/14/97 3:07p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "vxldbg.h" -#include "resource.h" -#include "dllmain.h" - -/* -** Static functions -*/ -static BOOL CALLBACK _dialog_proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); - -static PaletteClass _VoxelPalette; - -VoxelDebugWindowClass::VoxelDebugWindowClass(VoxelClass * vxl) : - CurLayer(0), - Bitmap(NULL), - Voxel(vxl), - WindowHWND(0), - ViewportHWND(0), - LayerSpin(NULL) -{ - _VoxelPalette[0] = RGBClass(0,0,0); - _VoxelPalette[1] = RGBClass(128,255,128); -} - -VoxelDebugWindowClass::~VoxelDebugWindowClass(void) -{ - ReleaseISpinner(LayerSpin); -} - -void VoxelDebugWindowClass::Display_Window(void) -{ - DialogBoxParam - ( - AppInstance, - MAKEINTRESOURCE (IDD_VOXEL_DEBUG_DIALOG), - NULL, - (DLGPROC) _dialog_proc, - (LPARAM) this - ); -} - - -bool VoxelDebugWindowClass::Dialog_Proc -( - HWND hWnd, - UINT message, - WPARAM wParam, - LPARAM -) -{ - RECT crect; - - switch (message ) { - - /******************************************************************* - * WM_INITDIALOG - * - * Initialize all of the custom controls for the dialog box - * - *******************************************************************/ - case WM_INITDIALOG: - - // keep a handle to the window - WindowHWND = hWnd; - - // keep a handle to the control that I'm using for the voxel viewport. - ViewportHWND = GetDlgItem(WindowHWND,IDC_VOXEL_VIEWPORT); - - // create a DIB that will be drawn on top of the VOXEL_VIEWPORT control. - GetClientRect(ViewportHWND,&crect); - Bitmap = new SimpleDIBClass(ViewportHWND,Voxel->Get_Width(),Voxel->Get_Height(),_VoxelPalette); - - // initialize the layer spinner - LayerSpin = SetupIntSpinner - ( - hWnd, - IDC_LAYER_SPIN, - IDC_LAYER_EDIT, - 0, - Voxel->Num_Layers(), - 0 - ); - - update_display(); - - SetCursor(LoadCursor (NULL, IDC_ARROW)); - - return 1; - - - /******************************************************************* - * WM_COMMAND - * - * - *******************************************************************/ - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - - // done! - SetCursor(LoadCursor (NULL, IDC_WAIT)); - EndDialog(hWnd, 1); - break; - } - return 1; - - /******************************************************************* - * CC_SPINNER_CHANGE - * - * Max custom spinner controls - * - *******************************************************************/ - case CC_SPINNER_CHANGE: - - switch (LOWORD(wParam) ) - { - case IDC_LAYER_SPIN: - - CurLayer = LayerSpin->GetIVal(); - update_display(); - break; - } - - - /******************************************************************* - * WM_PAINT - * - * - *******************************************************************/ - case WM_PAINT: - - update_display(); - - GetClientRect(ViewportHWND,&crect); - ValidateRect(ViewportHWND,&crect); - - break; - - } - return 0; -} - - -void VoxelDebugWindowClass::update_display(void) -{ - int i,j; - - /* - ** Bail out if everything isn't right - */ - if ((Bitmap == NULL) || (Voxel == NULL)) { - return; - } - - /* - ** Update the contents of the DIB based on - ** the contents of the current voxel layer. - */ - - Bitmap->Clear(0); - - for (j=0; j < Voxel->Get_Height(); j++) { - for (i=0; i < Voxel->Get_Width(); i++) { - if (Voxel->Is_Solid(i,j,CurLayer)) { - Bitmap->Set_Pixel(i,j,1); - } - } - } - - /* - ** Blit the DIB onto the dialog box. - */ - HDC hdcwindow = GetDC(ViewportHWND); - HDC hdcdib = CreateCompatibleDC(hdcwindow); - HBITMAP holdbitmap = (HBITMAP)SelectObject(hdcdib, Bitmap->Get_Handle()); - RECT crect; - - GetClientRect(ViewportHWND,&crect); - int cx = (crect.right - crect.left) / 2; - int cy = (crect.bottom - crect.top) / 2; - int x0 = 0; //cx - Bitmap->Get_Width(); - int y0 = 0; //cy - Bitmap->Get_Height(); - int x1 = 2 * Bitmap->Get_Width(); //cx + Bitmap->Get_Width(); - int y1 = 2 * Bitmap->Get_Height(); //cy + Bitmap->Get_Height(); - -// BitBlt(hdcwindow,0,0,Bitmap->Get_Width(),Bitmap->Get_Height(),hdcdib,0,0,SRCCOPY); - StretchBlt( hdcwindow, x0, y0, x1, y1, - hdcdib, 0, 0, Bitmap->Get_Width(), Bitmap->Get_Height(), SRCCOPY); - - SelectObject(hdcdib, holdbitmap); - - ReleaseDC(WindowHWND, hdcwindow); - DeleteDC(hdcdib); -} - - -BOOL CALLBACK _dialog_proc -( - HWND hWnd, - UINT message, - WPARAM wParam, - LPARAM lParam -) -{ - static VoxelDebugWindowClass * window = NULL; - - if (message == WM_INITDIALOG) { - window = (VoxelDebugWindowClass *) lParam; - } - - if (window) { - return window->Dialog_Proc(hWnd, message, wParam, lParam); - } else { - return FALSE; - } -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/vxldbg.h b/Generals/Code/Tools/WW3D/max2w3d/vxldbg.h deleted file mode 100644 index 5bafca4276..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vxldbg.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vxldbg.h 3 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vxldbg.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/14/97 3:07p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef VXLDBG_H -#define VXLDBG_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#include - -#ifndef SIMPDIB_H -#include "simpdib.h" -#endif - -#ifndef VXL_H -#include "vxl.h" -#endif - - -class VoxelDebugWindowClass -{ -public: - - VoxelDebugWindowClass(VoxelClass * vxl); - ~VoxelDebugWindowClass(void); - - void Display_Window(void); - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - -private: - - int CurLayer; - - SimpleDIBClass * Bitmap; - VoxelClass * Voxel; - HWND WindowHWND; - HWND ViewportHWND; - ISpinnerControl * LayerSpin; - - void update_display(void); -}; - - - -#endif diff --git a/Generals/Code/Tools/WW3D/max2w3d/vxllayer.cpp b/Generals/Code/Tools/WW3D/max2w3d/vxllayer.cpp deleted file mode 100644 index 4a6052ea71..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vxllayer.cpp +++ /dev/null @@ -1,783 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vxllayer.cpp 4 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : VXLLAYER.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/10/97 * - * * - * Last Update : June 10, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * VoxelLayerClass::VoxelLayerClass -- Constructor for VoxelLayerClass * - * VoxelLayerClass::Intersect_Triangle -- Intersect a triangle with the slab * - * VoxelLayerClass::Draw_Line -- Draw a line of voxels into the slab * - * VoxelLayerClass::Scan_Triangle -- Clip and scan-convert a triangle into the slab * - * clip_tri_to_slab -- Clips a triangle against a voxel slab * - * clip_poly -- clip a polygon against a single 3D plane * - * output -- Emit a vertex into a polygons vertex list * - * inside -- Test whether a point is in the front half-space of a plane * - * intersect -- compute intersection between a line and a plane * - * clear_scan_table -- clears the static scanline table * - * fixup_scan_table -- ensure all spans are left->right in order * - * scan_edge -- Scan convert an edge * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "vxllayer.h" -#include "plane.h" - - -/*************************************************************************************** -** local types -***************************************************************************************/ -struct vertexstruct -{ - Point3 Pos; - Point3 Bary; -}; - -struct scanstruct -{ - vertexstruct P[2]; -}; - - -/*************************************************************************************** -** static data -***************************************************************************************/ -static scanstruct _scantab[256]; - -const int LEFT = 0; -const int RIGHT = 1; -const float EMPTY_SPAN = -10000.0f; - - - -/*************************************************************************************** -** local functions -***************************************************************************************/ -static void clip_tri_to_slab( - Point3 p0, - Point3 p1, - Point3 p2, - float z0, - float z1, - vertexstruct * outverts, - int * setnum); - -static void clip_poly( - vertexstruct * inverts, - int innum, - vertexstruct * outverts, - int * outnum, - const PlaneClass & clipplane); - -static void output( - const vertexstruct & outvert, - vertexstruct * poly, - int * numverts); - -static int inside( - const vertexstruct & p, - const PlaneClass & plane); - -static vertexstruct intersect( - const vertexstruct & p0, - const vertexstruct & p1, - const PlaneClass & plane); - -static void clear_scan_table(void); - -static void fixup_scan_table( - int y0, - int y1); - -static void scan_edge( - const vertexstruct & p0, - const vertexstruct & p1); - - - - - - - -/*********************************************************************************************** - * VoxelLayerClass::VoxelLayerClass -- Constructor for VoxelLayerClass * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -VoxelLayerClass::VoxelLayerClass -( - INodeListClass & object_list, - TimeValue time, - Matrix3 parenttm, - Point3 offset, - Point3 scale, - float slicez, - float sliceh, - int bmwidth, - int bmheight -) -{ - unsigned i; - - SliceZ = slicez; - SliceH = sliceh; - SliceZ0 = slicez - sliceh / 2; - SliceZ1 = slicez + sliceh / 2; - - bitmap_width = bmwidth; - bitmap_height = bmheight; - - // Initialize everything with zero - memset ( &(Solid[0][0]), 0, sizeof(Solid)); - - // Go through the list of objects and intersect them with the plane. - for ( i = 0; i < object_list.Num_Nodes(); i++ ) - { - // Get relavent data from MAX - INode * inode = object_list[i]; - Object * obj = inode->EvalWorldState(time).obj; - TriObject * tri = (TriObject *)obj->ConvertToType(time, triObjectClassID); - Mesh * mesh = &(tri->mesh); - Matrix3 objtm = inode->GetObjectTM(time); - - // Compute a delta matrix which puts vertices into the parent space - Matrix3 delta = objtm * Inverse(parenttm); - - // Loop through each face, intersecting it with the slice. - unsigned faces = mesh->getNumFaces(); - for ( unsigned face_index = 0; face_index < faces; ++ face_index ) - { - Face & face = mesh->faces [ face_index ]; - - // transform the vertices into the parent space - Point3 a = mesh->verts [ face.v[0] ] * delta; - Point3 b = mesh->verts [ face.v[1] ] * delta; - Point3 c = mesh->verts [ face.v[2] ] * delta; - - // shift the vertices to the origin - a.x -= offset.x; - a.y -= offset.y; - b.x -= offset.x; - b.y -= offset.y; - c.x -= offset.x; - c.y -= offset.y; - - // scale the vertices into the voxel grid - a.x *= scale.x; - a.y *= scale.y; - b.x *= scale.x; - b.y *= scale.y; - c.x *= scale.x; - c.y *= scale.y; - -// Intersect_Triangle ( a, b, c, SliceZ ); - Scan_Triangle( a, b, c ); - } - } -} - - - -/*********************************************************************************************** - * VoxelLayerClass::Intersect_Triangle -- Intersect a triangle with the slab * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -void VoxelLayerClass::Intersect_Triangle -( - Point3 a, - Point3 b, - Point3 c, - float z -) -{ - double start_x, start_y, end_x, end_y; - - // If the triangle is wholly above or below the intersection plane, - // it does not intersect with the plane. - if ( a.z < z && b.z < z && c.z < z ) - return; - - if ( a.z > z && b.z > z && c.z > z ) - return; - - // Find the upward intersection moving counterclockwise. This will be - // the start of the edge. - if ( a.z < z && b.z >= z ) - { - start_x = a.x + (b.x - a.x) * (z - a.z) / (b.z - a.z); - start_y = a.y + (b.y - a.y) * (z - a.z) / (b.z - a.z); - } - else if ( b.z < z && c.z >= z ) - { - start_x = b.x + (c.x - b.x) * (z - b.z) / (c.z - b.z); - start_y = b.y + (c.y - b.y) * (z - b.z) / (c.z - b.z); - } - else if ( c.z < z && a.z >= z ) - { - start_x = c.x + (a.x - c.x) * (z - c.z) / (a.z - c.z); - start_y = c.y + (a.y - c.y) * (z - c.z) / (a.z - c.z); - } - else - { - return; - } - - // Find the downward intersection moving counterclockwise. This is the end - // of the edge. - if ( a.z >= z && b.z < z ) - { - end_x = a.x + (b.x - a.x) * (z - a.z) / (b.z - a.z); - end_y = a.y + (b.y - a.y) * (z - a.z) / (b.z - a.z); - } - else if ( b.z >= z && c.z < z ) - { - end_x = b.x + (c.x - b.x) * (z - b.z) / (c.z - b.z); - end_y = b.y + (c.y - b.y) * (z - b.z) / (c.z - b.z); - } - else if ( c.z >= z && a.z < z ) - { - end_x = c.x + (a.x - c.x) * (z - c.z) / (a.z - c.z); - end_y = c.y + (a.y - c.y) * (z - c.z) / (a.z - c.z); - } - else - { - return; - } - - // Draw the edge into the bitmap. - Draw_Line(start_x, start_y, end_x, end_y); -} - - -/*********************************************************************************************** - * VoxelLayerClass::Draw_Line -- Draw a line of voxels into the slab * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -void VoxelLayerClass::Draw_Line -( - double x0, - double y0, - double x1, - double y1 -) -{ - // Fill in the squares containing the line's endpoints. - Add_Solid((int)x0, (int)y0); - Add_Solid((int)x1, (int)y1); - - // Fill in the squares between the endpoints. - double delta_x = fabs (x1 - x0); - double delta_y = fabs (y1 - y0); - - if ( delta_x > delta_y ) - { - // This is an X-major line. - if ( x0 > x1 ) - { - double temp = x0; - x0 = x1; - x1 = temp; - - temp = y0; - y0 = y1; - y1 = temp; - } - - double step_y = (y1 - y0) / delta_x; - - double y = y0 + step_y * (floor (x0 + 1) - x0); - - for ( int x = (int) x0; x < (int) x1; ++ x ) - { - if ( (int) y >= 0 && (int) y < bitmap_height ) - { - Add_Solid(x, (int)y); - Add_Solid(x + 1, (int)y); - } - - y += step_y; - } - } - else - { - // This is a Y-major line. - if ( y0 > y1 ) - { - double temp = x0; - x0 = x1; - x1 = temp; - - temp = y0; - y0 = y1; - y1 = temp; - } - - double step_x = (x1 - x0) / delta_y; - - double x = x0 + step_x * (floor (y0 + 1) - y0); - - for ( int y = (int) y0; y < (int) y1; ++ y ) - { - if ( (int) x >= 0 && (int) x < 256 ) - { - Add_Solid((int)x, y); - Add_Solid((int)x, y+1); - } - } - } -} - - - -/*********************************************************************************************** - * VoxelLayerClass::Scan_Triangle -- Clip and scan-convert a triangle into the slab * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -void VoxelLayerClass::Scan_Triangle -( - Point3 p0, - Point3 p1, - Point3 p2 -) -{ - int i; - - // check if the entire triangle is above or below the slab: - if (p0.z < SliceZ0 && p1.z < SliceZ0 && p2.z < SliceZ1) return; - if (p0.z > SliceZ1 && p1.z > SliceZ1 && p2.z > SliceZ1) return; - - // clip the triangle to the slab - vertexstruct polyvert[8]; - int numverts; - - clip_tri_to_slab(p0,p1,p2,SliceZ0,SliceZ1,polyvert,&numverts); - if (numverts == 0) return; - - // clear the scanline table, get y-extents of polygon - clear_scan_table(); - - float miny = polyvert[0].Pos.y; - float maxy = polyvert[0].Pos.y; - - for (i=1; i maxy) maxy = polyvert[i].Pos.y; - } - - // scanconvert the triangle - int start = numverts - 1; - for (i=0; i= 0.0f) { - return 1; - } else { - return 0; - } -} - - -/*********************************************************************************************** - * intersect -- compute intersection between a line and a plane * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -static vertexstruct intersect -( - const vertexstruct & p0, - const vertexstruct & p1, - const PlaneClass & plane -) -{ - float t; - - Point3 delta = p1.Pos - p0.Pos; - - float num = -( plane.N[0] * p0.Pos.x + - plane.N[1] * p0.Pos.y + - plane.N[2] * p0.Pos.z + plane.D ); - - float den = plane.N[0] * delta.x + - plane.N[1] * delta.y + - plane.N[2] * delta.z; - - if (den != 0.0f) { - t = num / den; - } else { - t = 0.0f; - } - - vertexstruct i; - i.Pos = (1.0f - t) * p0.Pos + t*p1.Pos; - i.Bary = (1.0f - t) * p0.Bary + t*p1.Bary; - return i; -} - - -/*********************************************************************************************** - * clear_scan_table -- clears the static scanline table * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -static void clear_scan_table(void) -{ - memset(_scantab,0,sizeof(_scantab)); - for (int i=0; i<256; i++) { - _scantab[i].P[0].Pos.x = EMPTY_SPAN; - _scantab[i].P[1].Pos.x = EMPTY_SPAN; - } -} - -/*********************************************************************************************** - * fixup_scan_table -- ensure all spans are left->right in order * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -static void fixup_scan_table(int y0,int y1) -{ - int i; - assert(y1 >= y0); - - // Ensure the left -> right convention is followed. - for (i=y0; i<=y1; i++) { - if (_scantab[i].P[LEFT].Pos.x > _scantab[i].P[RIGHT].Pos.x) { - vertexstruct tmp = _scantab[i].P[LEFT]; - _scantab[i].P[LEFT] = _scantab[i].P[RIGHT]; - _scantab[i].P[RIGHT] = tmp; - } - } - - // Ensure that we leave no gaps. - for (i=y0; i _scantab[i].P[RIGHT].Pos.x) { - - _scantab[i+1].P[LEFT].Pos.x = _scantab[i].P[RIGHT].Pos.x; - - } - } -} - - -/*********************************************************************************************** - * scan_edge -- Scan convert an edge * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/10/1997 GH : Created. * - *=============================================================================================*/ -static void scan_edge -( - const vertexstruct & p0, - const vertexstruct & p1 -) -{ - // is this a perfectly horizontal edge: - if (floor(p0.Pos.y) == floor(p1.Pos.y)) { - - int si = (int)floor(p0.Pos.y); - const vertexstruct *left, *right; - - if (p0.Pos.x < p1.Pos.x) { - left = &p0; - right = &p1; - } else { - left = &p1; - right = &p0; - } - - // does this scanline already have a span in it? - if (_scantab[si].P[0].Pos.x != EMPTY_SPAN) { - - // yes, expand this scanline's span to include this span - if (left->Pos.x < _scantab[si].P[LEFT].Pos.x) { - _scantab[si].P[LEFT] = *left; - } - - if (right->Pos.x > _scantab[si].P[RIGHT].Pos.x) { - _scantab[si].P[RIGHT] = *right; - } - - } else { - - // no, set this scanline with the span for this edge - _scantab[si].P[LEFT] = *left; - _scantab[si].P[RIGHT] = *right; - - } - return; - } - - // is this a left or right edge: - int side; - const vertexstruct *top, *bot; - - if (p0.Pos.y < p1.Pos.y) { - side = RIGHT; - top = &p0; - bot = &p1; - } else { - side = LEFT; - top = &p1; - bot = &p0; - } - - // scan the edge into _scantab - for (double y = floor(top->Pos.y); y <= floor(bot->Pos.y); y += 1.0f) { - - // parametric position on the scanline: - double t = (y - floor(top->Pos.y)) / (floor(bot->Pos.y) - floor(top->Pos.y)); - - // position: - _scantab[(int)y].P[side].Pos = (1.0f - (float)t)*top->Pos + (float)t*bot->Pos; - - // barycentric coords: - _scantab[(int)y].P[side].Bary = (1.0f - (float)t)*top->Bary + (float)t*bot->Bary; - } -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/vxllayer.h b/Generals/Code/Tools/WW3D/max2w3d/vxllayer.h deleted file mode 100644 index a824bb092c..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/vxllayer.h +++ /dev/null @@ -1,149 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/vxllayer.h 3 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/vxllayer.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/26/97 1:35p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef VXLLAYER_H -#define VXLLAYER_H - -#include - - -#ifndef BITTYPE_H -#include "BITTYPE.H" -#endif - -#ifndef NODELIST_H -#include "nodelist.h" -#endif - -const sint8 VOXEL_VISIBLE = 0; // voxels that are "outside" the object -const sint8 VOXEL_SOLID = 1; // voxels that are part of the object -const sint8 VOXEL_UNKNOWN = -1; // either inside or outside, don't know yet -const int max_bitmap_width = 256; -const int max_bitmap_height = 256; - - -class VoxelLayerClass -{ -public: - - VoxelLayerClass(); - - VoxelLayerClass - ( - INodeListClass & objectlist, - TimeValue time, - Matrix3 parenttm, - Point3 offset, - Point3 scale, - float slicez, - float sliceh, - int bmwidth, - int bmheight - ); - - ~VoxelLayerClass() {}; - - BOOL Is_Visible( int x, int y ) - { - if (x < 0 || x >= bitmap_width || y < 0 || y >= bitmap_height) { - return TRUE; - } - - if (Solid[x][y] == 0) { - return TRUE; - } else { - return FALSE; - } - } - - BOOL Is_Solid( int x, int y ) - { - if (x < 0 || x >= bitmap_width || y < 0 || y >= bitmap_height) { - return FALSE; - } - - if (Solid[x][y] == VOXEL_SOLID) { - return TRUE; - } else { - return FALSE; - } - } - - unsigned int Get_Width(void) { return bitmap_width; } - unsigned int Get_Height(void) { return bitmap_height; } - -protected: - - void Set_Visible ( int x, int y ) - { - if (x >= 0 && x < bitmap_width && y >= 0 && y < bitmap_height && Solid[x][y] != VOXEL_SOLID ) - { - Solid[x][y] = VOXEL_VISIBLE; - } - } - - void Add_Solid(int x,int y) - { - // check if the point is outside the bitmap: - if (x >= 0 && x < bitmap_width && y >= 0 && y < bitmap_height) { - Solid[x][y] = VOXEL_SOLID; - } - } - - // draw a line of voxels into the bitmap - void Draw_Line(double x0,double y0,double x1,double y1); - - // draw the intersection between the triangle and the voxel plane - void Intersect_Triangle(Point3 a,Point3 b,Point3 c,float z); - - // scan convert the polygon fragment in this voxel slab - void Scan_Triangle(Point3 a,Point3 b,Point3 c); - - sint8 Solid[max_bitmap_width][max_bitmap_height]; - - float SliceZ; - float SliceH; - float SliceZ0; - float SliceZ1; - - int bitmap_width; - int bitmap_height; -}; - - -#endif /*VXLLAYER_H*/ diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3d_file.h b/Generals/Code/Tools/WW3D/max2w3d/w3d_file.h deleted file mode 100644 index f6612b1bf3..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3d_file.h +++ /dev/null @@ -1,2081 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /VSS_Sync/ww3d2/w3d_file.h 16 8/29/01 9:49p Vss_sync $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /VSS_Sync/ww3d2/w3d_file.h $* - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 7:29p $* - * * - * $Revision:: 16 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3D_FILE_H -#define W3D_FILE_H - -#include "always.h" -#include "BITTYPE.H" -#include "iostruct.h" -#include - -/******************************************************************************** - -NAMING CONVENTIONS: - - Typical render object name is 15 characters + NULL - Meshes have 31 + NULL character name formed from the concatenation of the "container" - model name and the mesh's name: "ContainerName.MeshName" - Animations have 31 + NULL character names formed from the concatenation of the Hierarchy tree - name with the animation name: "AnimationName.HierarchyName" - Textures have unlimited name length. - Typically you can determine which 'W3D' file a render object came from by looking - at its name. If the name contains a '.' then the filename is the string before - the '.' and if not, then the render object name is the name of the file. - -VERSION NUMBERS: - - Each Major chunk type will contain a "header" as its first - sub-chunk. The first member of this header will be a Version - number formatted so that its major revision number is the - high two bytes and its minor revision number is the lower two - bytes. - -Version 1.0: - - MESHES - contained the following chunks: - W3D_CHUNK_MESH_HEADER, // header for a mesh - W3D_CHUNK_VERTICES, // array of vertices - W3D_CHUNK_VERTEX_NORMALS, // array of normals - W3D_CHUNK_SURRENDER_NORMALS, // array of surrender normals (one per vertex as req. by surrender) - W3D_CHUNK_TEXCOORDS, // array of texture coordinates - W3D_CHUNK_MATERIALS, // array of materials - W3D_CHUNK_TRIANGLES, // array of triangles - W3D_CHUNK_SURRENDER_TRIANGLES,// array of surrender format tris - W3D_CHUNK_MESH_USER_TEXT, // Name of owning hierarchy, text from the MAX comment field - - HIERARCHY TREES - contained the following chunks: - W3D_CHUNK_HIERARCHY_HEADER, - W3D_CHUNK_PIVOTS, - W3D_CHUNK_PIVOT_FIXUPS, - - HIERARCHY ANIMATIONS - contained the following chunks: - W3D_CHUNK_ANIMATION_HEADER, - W3D_CHUNK_ANIMATION_CHANNEL, - - MESH CONNECTIONS - (blueprint for a hierarchical model) contained these chunks: - - -Version 2.0: - - MESHES: - - - Mesh header now contains the hierarchy model name. The mesh name will be built - as . instead of the old convention: . - - - The material chunk is replaced with a new material structure which contains - some information for animating materials. - - - Vertex Influences link vertices of a mesh to bones in a hierarchy, this is - the information needed for skinning. - - - Damage chunks added. A damage chunk contains a new set of materials, a set - of vertex offsets, and a set of vertex colors. - - Added the following chunks: - - W3D_CHUNK_VERTEX_COLORS, - W3D_CHUNK_VERTEX_INFLUENCES, - W3D_CHUNK_DAMAGE, - W3D_CHUNK_DAMAGE_HEADER, - W3D_CHUNK_DAMAGE_MATERIALS, - W3D_CHUNK_DAMAGE_VERTICES, - W3D_CHUNK_DAMAGE_COLORS, - W3D_CHUNK_MATERIALS2, - - MESH CONNECTIONS: Hierarchy models can now contain skins and collision meshes - in addition to the normal meshes. - - W3D_CHUNK_COLLISION_CONNECTION, // collision meshes connected to the hierarchy - W3D_CHUNK_SKIN_CONNECTION, // skins connected to the hierarchy - W3D_CHUNK_CONNECTION_AUX_DATA // extension of the connection header - - -Dec 12, 1997 - - Changed MESH_CONNECTIONS chunks into HMODEL chunks because the name - mesh connections was becoming more and more inappropriate... This was only - a data structure naming change so no-one other than the coders are affected - - Added W3D_CHUNK_LODMODEL. An LOD Model contains a set of names for - render objects, each with a specified distance range. - - -Feb 6, 1998 - - Added W3D_CHUNK_SECTMESH and its sub-chunks. This will be the file - format for the terrain geometry exported from POV's Atlas tool. - -March 29, 1998 : Version 3.0 - - - New material chunk which supports the new features of the 3D engine - - Modified HTrees to always have a root transform to remove all of the - special case -1 bone indexes. - - Added new mesh types, A mesh can now be categorized as: normal, - aligned, skin, collision, or shadow. - -June 22, 1998 - - Removed the "SECTMESH" chunks which were never implemented or used. - - Adding a new type of object: The 'Tilemap'. This simple-sounding object - is a binary partition tree of tiles where tiles are rectangular regions of - space. In each leaf to the tree, a mesh is referenced. The tile map is - made of several chunks: - - - W3D_CHUNK_TILEMAP - - W3D_CHUNK_TILEMAP_HEADER - - W3D_CHUNK_TILES - - W3D_CHUNK_MESH - - W3D_CHUNK_MESH - ... - - - W3D_CHUNK_PARTITION_TREE - - W3D_CHUNK_PARTITION_TREE_HEADER - - W3D_CHUNK_PARTITION_TREE_NODES - - - W3D_CHUNK_TILE_INSTANCES - - W3D_CHUNK_TILE_INSTANCE - -October 19, 1998 - - Created the w3d_obsolete.h header file and moved everything that I could into - it. This header was getting so messy that even I couldn't understand it so - hopefully this helps a little... - - Updating the mesh format as part of the conversion to Surrender1.40. Some - of the new features in this mesh format are: - - per pass, per stage U-V coordinate arrays - - per pass vertex diffuse color arrays - - per pass vertex specular color arrays - - per pass vertex pre-calced diffuse illumination arrays - - In addition, the way you describe the materials for a mesh has *completely* - changed. The new system separates the concepts of VertexMaterial, Texture - and Shader. A VertexMaterial defines the parameters which control the - gradient calculations for vertices. Textures you know about. Shaders - define how the gradients (diffuse and specular) are combined with the texture - and the frame buffer. In addition, a mesh can have several passes; each - pass having VertexMaterials, Textures and Shaders - - new chunk to describe a shader, contains a W3dShaderStruct - - new chunk to describe a vertex material, contains a W3dVertexMaterialStruct - - textures use the old 'Map3' chunk still - - new chunk to describe a "pass" for the mesh - - new chunk to tie up all of these vertex materials, shaders, and textures - - new chunks for specifying per-poly, per-pass arrays of texture, shader, and - vertex material indices. - - The culling system changed a bit requiring some re-working of the "Tilemap" - so I have removed the tilemap chunks. At this point in time, all of the AABTree - building is being done at run-time. Once we get the editor a little farther - along, we'll define some new chunks for this stuff. - - At this point in time, meshes look like the following. I've placed an asterisk - next to the new chunk types. - - W3D_CHUNK_MESH - W3D_CHUNK_MESH_HEADER3 - W3D_CHUNK_MESH_USER_TEXT - W3D_CHUNK_VERTICES - W3D_CHUNK_VERTEX_NORMALS - W3D_CHUNK_VERTEX_INFLUENCES - W3D_CHUNK_TRIANGLES -* W3D_CHUNK_VERTEX_SHADE_INDICES - -* W3D_CHUNK_MATERIAL_INFO // how many passes, vertex mtls, shaders, and textures... -* W3D_CHUNK_SHADERS // array of W3dShaderStruct's -* W3D_CHUNK_VERTEX_MATERIALS -* W3D_CHUNK_VERTEX_MATERIAL -* W3D_CHUNK_VERTEX_MATERIAL_NAME -* W3D_CHUNK_VERTEX_MATERIAL_INFO - ... - -* W3D_CHUNK_TEXTURES -* W3D_CHUNK_TEXTURE -* W3D_CHUNK_TEXTURE_NAME -* W3D_CHUNK_TEXTURE_INFO - ... - -* W3D_CHUNK_MATERIAL_PASS -* W3D_CHUNK_VERTEX_MATERIAL_IDS -* W3D_CHUNK_SHADER_IDS - -* W3D_CHUNK_DCG -* W3D_CHUNK_DIG -* W3D_CHUNK_SCG - -* W3D_CHUNK_TEXTURE_STAGE -* W3D_CHUNK_TEXTURE_IDS -* W3D_CHUNK_STAGE_TEXCOORDS - - - Added a Collection chunk type. When we export a bunch of independent meshes - (turning off the hierarchy and animation options) this chunk will be added - on to the end of the file. It lists by name each render object that was - defined in the file. Presumably the run-time asset manager will be able - to give you a "collection" render object which will be named the same as - the w3d file that it came from and will contain the name or an actual instance - of each of the meshes. This is a feature that was added for the Commando - level editor. - - Added the W3D_CHUNK_POINTS chunk. This is used to implement "snap points" - for the level editor. It is just an array of points that were found in - the max scene (helper object->point). We make these points co-incide in - the level editor to snap objects together. This chunk can occur inside a - mesh, hmodel, or collection chunk. When it does, the points should simply - be associated with the model being defined. - -August 5, 1999 - - Adding Null Object exporting - -March 28, 2000 - - Adding Merge objects to collections. We already have "Proxy" objects which ask - the level editor to instatiate an object at a given transform. Now we will - have "Merge" objects which mean a copy of the named model should be merged in - with this model. This is used in the case of building interiors. We can create - a building interior and lightmap it as a separate collection, then "merge" it - with the level collection (multiple times even) and the tool will pre-transform - the meshes and add them to the collection. - -March 31, 2000 - - Changed W3D_CHUNK_MERGE_NODE to W3D_CHUNK_TRANSFORM_NODE. Same data - slightly - different application. Now the information will indicate how a w3d asset with the - same name as that in the node should pre-transform itself relative to the object - that contains the transform node. - -April 07, 2000 - - Added W3D_CHUNK_LIGHTSCAPE, W3D_CHUNK_LIGHTSCAPE_LIGHT and W3D_CHUNK_LIGHT_TRANSFORM. - These chunks form part of the output of new Westwood light file type (.wlt). - -July 10, 2000 - - Added W3D_CHUNK_VERTEX_MAPPER_ARGS1 and renamed W3D_CHUNK_VERTEX_MAPPER_ARGS to - W3D_CHUNK_VERTEX_MAPPER_ARGS0. These are the mapper args for the first and second - texture stages. The choice of mapper for the second stage has been added to the - 'Attributes' field in W3dVertexMaterialStruct. - -August 5, 2000 - - Added W3D_CHUNK_LIGHT_GLARE and its sub-chunks. Light glares are going to - be a new 'geometry type' which simply define points where light glare effects - should be placed. The application will supply a callback to the WW3D code - which indicates the visibilty of any light glares in the view frustum. - -June 5, 2001 - - (gth) Adding line rendering options to particle systems today. This involves a - new line-properties chunk and a RenderMode variable added to the InfoV2 struct. - -********************************************************************************/ - - -#define W3D_MAKE_VERSION(major,minor) (((major) << 16) | (minor)) -#define W3D_GET_MAJOR_VERSION(ver) ((ver)>>16) -#define W3D_GET_MINOR_VERSION(ver) ((ver) & 0xFFFF) - -#define W3D_NAME_LEN 16 - - - -/******************************************************************************** - - CHUNK TYPES FOR ALL 3D DATA - - All 3d data is stored in chunks similar to an IFF file. Each - chunk will be headed by an ID and size field. - - All structures defined in this header file are prefixed with - W3d to prevent naming conflicts with in-game structures which - may be slightly different than the on-disk structures. - - Oct 19,1998: Moved obsolete chunk id's to w3d_obsolete.h, added many - new chunk types. - -********************************************************************************/ - -enum { - - W3D_CHUNK_MESH =0x00000000, // Mesh definition - W3D_CHUNK_VERTICES =0x00000002, // array of vertices (array of W3dVectorStruct's) - W3D_CHUNK_VERTEX_NORMALS =0x00000003, // array of normals (array of W3dVectorStruct's) - W3D_CHUNK_MESH_USER_TEXT =0x0000000C, // Text from the MAX comment field (Null terminated string) - W3D_CHUNK_VERTEX_INFLUENCES =0x0000000E, // Mesh Deformation vertex connections (array of W3dVertInfStruct's) - W3D_CHUNK_MESH_HEADER3 =0x0000001F, // mesh header contains general info about the mesh. (W3dMeshHeader3Struct) - W3D_CHUNK_TRIANGLES =0x00000020, // New improved triangles chunk (array of W3dTriangleStruct's) - W3D_CHUNK_VERTEX_SHADE_INDICES =0x00000022, // shade indexes for each vertex (array of uint32's) - - W3D_CHUNK_PRELIT_UNLIT =0x00000023, // optional unlit material chunk wrapper - W3D_CHUNK_PRELIT_VERTEX =0x00000024, // optional vertex-lit material chunk wrapper - W3D_CHUNK_PRELIT_LIGHTMAP_MULTI_PASS =0x00000025, // optional lightmapped multi-pass material chunk wrapper - W3D_CHUNK_PRELIT_LIGHTMAP_MULTI_TEXTURE =0x00000026, // optional lightmapped multi-texture material chunk wrapper - - W3D_CHUNK_MATERIAL_INFO =0x00000028, // materials information, pass count, etc (contains W3dMaterialInfoStruct) - - W3D_CHUNK_SHADERS =0x00000029, // shaders (array of W3dShaderStruct's) - - W3D_CHUNK_VERTEX_MATERIALS =0x0000002A, // wraps the vertex materials - W3D_CHUNK_VERTEX_MATERIAL =0x0000002B, - W3D_CHUNK_VERTEX_MATERIAL_NAME =0x0000002C, // vertex material name (NULL-terminated string) - W3D_CHUNK_VERTEX_MATERIAL_INFO =0x0000002D, // W3dVertexMaterialStruct - W3D_CHUNK_VERTEX_MAPPER_ARGS0 =0x0000002E, // Null-terminated string - W3D_CHUNK_VERTEX_MAPPER_ARGS1 =0x0000002F, // Null-terminated string - - W3D_CHUNK_TEXTURES =0x00000030, // wraps all of the texture info - W3D_CHUNK_TEXTURE =0x00000031, // wraps a texture definition - W3D_CHUNK_TEXTURE_NAME =0x00000032, // texture filename (NULL-terminated string) - W3D_CHUNK_TEXTURE_INFO =0x00000033, // optional W3dTextureInfoStruct - - W3D_CHUNK_MATERIAL_PASS =0x00000038, // wraps the information for a single material pass - W3D_CHUNK_VERTEX_MATERIAL_IDS =0x00000039, // single or per-vertex array of uint32 vertex material indices (check chunk size) - W3D_CHUNK_SHADER_IDS =0x0000003A, // single or per-tri array of uint32 shader indices (check chunk size) - W3D_CHUNK_DCG =0x0000003B, // per-vertex diffuse color values (array of W3dRGBAStruct's) - W3D_CHUNK_DIG =0x0000003C, // per-vertex diffuse illumination values (array of W3dRGBStruct's) - W3D_CHUNK_SCG =0x0000003E, // per-vertex specular color values (array of W3dRGBStruct's) - - W3D_CHUNK_TEXTURE_STAGE =0x00000048, // wrapper around a texture stage. - W3D_CHUNK_TEXTURE_IDS =0x00000049, // single or per-tri array of uint32 texture indices (check chunk size) - W3D_CHUNK_STAGE_TEXCOORDS =0x0000004A, // per-vertex texture coordinates (array of W3dTexCoordStruct's) - W3D_CHUNK_PER_FACE_TEXCOORD_IDS =0x0000004B, // indices to W3D_CHUNK_STAGE_TEXCOORDS, (array of Vector3i) - - - W3D_CHUNK_DEFORM =0x00000058, // mesh deform or 'damage' information. - W3D_CHUNK_DEFORM_SET =0x00000059, // set of deform information - W3D_CHUNK_DEFORM_KEYFRAME =0x0000005A, // a keyframe of deform information in the set - W3D_CHUNK_DEFORM_DATA =0x0000005B, // deform information about a single vertex - - W3D_CHUNK_PS2_SHADERS =0x00000080, // Shader info specific to the Playstation 2. - - W3D_CHUNK_AABTREE =0x00000090, // Axis-Aligned Box Tree for hierarchical polygon culling - W3D_CHUNK_AABTREE_HEADER, // catalog of the contents of the AABTree - W3D_CHUNK_AABTREE_POLYINDICES, // array of uint32 polygon indices with count=mesh.PolyCount - W3D_CHUNK_AABTREE_NODES, // array of W3dMeshAABTreeNode's with count=aabheader.NodeCount - - W3D_CHUNK_HIERARCHY =0x00000100, // hierarchy tree definition - W3D_CHUNK_HIERARCHY_HEADER, - W3D_CHUNK_PIVOTS, - W3D_CHUNK_PIVOT_FIXUPS, // only needed by the exporter... - - W3D_CHUNK_ANIMATION =0x00000200, // hierarchy animation data - W3D_CHUNK_ANIMATION_HEADER, - W3D_CHUNK_ANIMATION_CHANNEL, // channel of vectors - W3D_CHUNK_BIT_CHANNEL, // channel of boolean values (e.g. visibility) - - W3D_CHUNK_COMPRESSED_ANIMATION =0x00000280, // compressed hierarchy animation data - W3D_CHUNK_COMPRESSED_ANIMATION_HEADER, // describes playback rate, number of frames, and type of compression - W3D_CHUNK_COMPRESSED_ANIMATION_CHANNEL, // compressed channel, format dependent on type of compression - W3D_CHUNK_COMPRESSED_BIT_CHANNEL, // compressed bit stream channel, format dependent on type of compression - - W3D_CHUNK_MORPH_ANIMATION =0x000002C0, // hierarchy morphing animation data (morphs between poses, for facial animation) - W3D_CHUNK_MORPHANIM_HEADER, // W3dMorphAnimHeaderStruct describes playback rate, number of frames, and type of compression - W3D_CHUNK_MORPHANIM_CHANNEL, // wrapper for a channel - W3D_CHUNK_MORPHANIM_POSENAME, // name of the other anim which contains the poses for this morph channel - W3D_CHUNK_MORPHANIM_KEYDATA, // morph key data for this channel - W3D_CHUNK_MORPHANIM_PIVOTCHANNELDATA, // uin32 per pivot in the htree, indicating which channel controls the pivot - - W3D_CHUNK_HMODEL =0x00000300, // blueprint for a hierarchy model - W3D_CHUNK_HMODEL_HEADER, // Header for the hierarchy model - W3D_CHUNK_NODE, // render objects connected to the hierarchy - W3D_CHUNK_COLLISION_NODE, // collision meshes connected to the hierarchy - W3D_CHUNK_SKIN_NODE, // skins connected to the hierarchy - OBSOLETE_W3D_CHUNK_HMODEL_AUX_DATA, // extension of the hierarchy model header - OBSOLETE_W3D_CHUNK_SHADOW_NODE, // shadow object connected to the hierarchy - - W3D_CHUNK_LODMODEL =0x00000400, // blueprint for an LOD model. This is simply a - W3D_CHUNK_LODMODEL_HEADER, // collection of 'n' render objects, ordered in terms - W3D_CHUNK_LOD, // of their expected rendering costs. (highest is first) - - W3D_CHUNK_COLLECTION =0x00000420, // collection of render object names - W3D_CHUNK_COLLECTION_HEADER, // general info regarding the collection - W3D_CHUNK_COLLECTION_OBJ_NAME, // contains a string which is the name of a render object - W3D_CHUNK_PLACEHOLDER, // contains information about a 'dummy' object that will be instanced later - W3D_CHUNK_TRANSFORM_NODE, // contains the filename of another w3d file that should be transformed by this node - - W3D_CHUNK_POINTS =0x00000440, // array of W3dVectorStruct's. May appear in meshes, hmodels, lodmodels, or collections. - - W3D_CHUNK_LIGHT =0x00000460, // description of a light - W3D_CHUNK_LIGHT_INFO, // generic light parameters - W3D_CHUNK_SPOT_LIGHT_INFO, // extra spot light parameters - W3D_CHUNK_NEAR_ATTENUATION, // optional near attenuation parameters - W3D_CHUNK_FAR_ATTENUATION, // optional far attenuation parameters - - W3D_CHUNK_EMITTER =0x00000500, // description of a particle emitter - W3D_CHUNK_EMITTER_HEADER, // general information such as name and version - W3D_CHUNK_EMITTER_USER_DATA, // user-defined data that specific loaders can switch on - W3D_CHUNK_EMITTER_INFO, // generic particle emitter definition - W3D_CHUNK_EMITTER_INFOV2, // generic particle emitter definition (version 2.0) - W3D_CHUNK_EMITTER_PROPS, // Key-frameable properties - OBSOLETE_W3D_CHUNK_EMITTER_COLOR_KEYFRAME, // structure defining a single color keyframe - OBSOLETE_W3D_CHUNK_EMITTER_OPACITY_KEYFRAME, // structure defining a single opacity keyframe - OBSOLETE_W3D_CHUNK_EMITTER_SIZE_KEYFRAME, // structure defining a single size keyframe - W3D_CHUNK_EMITTER_LINE_PROPERTIES, // line properties, used by line rendering mode - W3D_CHUNK_EMITTER_ROTATION_KEYFRAMES, // rotation keys for the particles - W3D_CHUNK_EMITTER_FRAME_KEYFRAMES, // frame keys (u-v based frame animation) - - W3D_CHUNK_AGGREGATE =0x00000600, // description of an aggregate object - W3D_CHUNK_AGGREGATE_HEADER, // general information such as name and version - W3D_CHUNK_AGGREGATE_INFO, // references to 'contained' models - W3D_CHUNK_TEXTURE_REPLACER_INFO, // information about which meshes need textures replaced - W3D_CHUNK_AGGREGATE_CLASS_INFO, // information about the original class that created this aggregate - - W3D_CHUNK_HLOD =0x00000700, // description of an HLod object (see HLodClass) - W3D_CHUNK_HLOD_HEADER, // general information such as name and version - W3D_CHUNK_HLOD_LOD_ARRAY, // wrapper around the array of objects for each level of detail - W3D_CHUNK_HLOD_SUB_OBJECT_ARRAY_HEADER, // info on the objects in this level of detail array - W3D_CHUNK_HLOD_SUB_OBJECT, // an object in this level of detail array - W3D_CHUNK_HLOD_AGGREGATE_ARRAY, // array of aggregates, contains W3D_CHUNK_SUB_OBJECT_ARRAY_HEADER and W3D_CHUNK_SUB_OBJECT_ARRAY - W3D_CHUNK_HLOD_PROXY_ARRAY, // array of proxies, used for application-defined purposes, provides a name and a bone. - - W3D_CHUNK_BOX =0x00000740, // defines an collision box render object (W3dBoxStruct) - W3D_CHUNK_SPHERE, - W3D_CHUNK_RING, - - W3D_CHUNK_NULL_OBJECT =0x00000750, // defines a NULL object (W3dNullObjectStruct) - - W3D_CHUNK_LIGHTSCAPE =0x00000800, // wrapper for lights created with Lightscape. - W3D_CHUNK_LIGHTSCAPE_LIGHT, // definition of a light created with Lightscape. - W3D_CHUNK_LIGHT_TRANSFORM, // position and orientation (defined as right-handed 4x3 matrix transform W3dLightTransformStruct). - - W3D_CHUNK_DAZZLE =0x00000900, // wrapper for a glare object. Creates halos and flare lines seen around a bright light source - W3D_CHUNK_DAZZLE_NAME, // null-terminated string, name of the dazzle (typical w3d object naming: "container.object") - W3D_CHUNK_DAZZLE_TYPENAME, // null-terminated string, type of dazzle (from dazzle.ini) - - W3D_CHUNK_SOUNDROBJ =0x00000A00, // description of a sound render object - W3D_CHUNK_SOUNDROBJ_HEADER, // general information such as name and version - W3D_CHUNK_SOUNDROBJ_DEFINITION, // chunk containing the definition of the sound that is to play - -}; - - - -struct W3dChunkHeader -{ - uint32 ChunkType; // Type of chunk (see above enumeration) - uint32 ChunkSize; // Size of the chunk, (not including the chunk header) -}; - - - -///////////////////////////////////////////////////////////////////////////////////////////// -// vector -///////////////////////////////////////////////////////////////////////////////////////////// -typedef IOVector3Struct W3dVectorStruct; - -///////////////////////////////////////////////////////////////////////////////////////////// -// quaternion -///////////////////////////////////////////////////////////////////////////////////////////// -typedef IOQuaternionStruct W3dQuaternionStruct; - -///////////////////////////////////////////////////////////////////////////////////////////// -// texture coordinate -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dTexCoordStruct -{ - bool operator == (W3dTexCoordStruct t) - { - return ((U == t.U) && (V == t.V)); - } - - float32 U; // U,V coordinates - float32 V; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// rgb color, one byte per channel, padded to an even 4 bytes -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dRGBStruct -{ - W3dRGBStruct () {} - W3dRGBStruct (uint8 r, uint8 g, uint8 b) - { - R = r; - G = g; - B = b; - } - - void Set (uint8 r, uint8 g, uint8 b) - { - R = r; - G = g; - B = b; - } - - void Set (float r, float g, float b) - { - R = (unsigned char) MIN ((float) UCHAR_MAX, MAX (0.0f, r) * ((float) (UCHAR_MAX + 1))); - G = (unsigned char) MIN ((float) UCHAR_MAX, MAX (0.0f, g) * ((float) (UCHAR_MAX + 1))); - B = (unsigned char) MIN ((float) UCHAR_MAX, MAX (0.0f, b) * ((float) (UCHAR_MAX + 1))); - } - - bool operator == (W3dRGBStruct c) - { - return ((R == c.R) && (G == c.G) && (B == c.B)); - } - - bool operator != (W3dRGBStruct c) - { - return (!(*this == c)); - } - - W3dRGBStruct operator += (W3dRGBStruct c) - { - R = MIN (((unsigned) R) + ((unsigned) c.R), (unsigned) UCHAR_MAX); - G = MIN (((unsigned) G) + ((unsigned) c.G), (unsigned) UCHAR_MAX); - B = MIN (((unsigned) B) + ((unsigned) c.B), (unsigned) UCHAR_MAX); - return (*this); - } - - W3dRGBStruct operator *= (W3dRGBStruct c) - { - R = (((unsigned) R) * ((unsigned) c.R)) / ((unsigned) UCHAR_MAX); - G = (((unsigned) G) * ((unsigned) c.G)) / ((unsigned) UCHAR_MAX); - B = (((unsigned) B) * ((unsigned) c.B)) / ((unsigned) UCHAR_MAX); - return (*this); - } - - unsigned Get_Color() - { - return (R<<24)|(G<<16)|(B<<8); - } - - uint8 R; - uint8 G; - uint8 B; - uint8 pad; -}; - -struct W3dRGBAStruct -{ - uint8 R; - uint8 G; - uint8 B; - uint8 A; -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// MATERIALS -// -// Surrender 1.40 significantly changed the way that materials are described. To -// accomodate this, the w3d file format has changed since there are new features and -// optimizations that we want to take advangage of. -// -// The VertexMaterial defines parameters which control the calculation of the primary -// and secondary gradients. The shader defines how those gradients are combined with -// the texel and the frame buffer contents. -// -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterialInfoStruct -{ - uint32 PassCount; // how many material passes this render object uses - uint32 VertexMaterialCount; // how many vertex materials are used - uint32 ShaderCount; // how many shaders are used - uint32 TextureCount; // how many textures are used -}; - - -#define W3DVERTMAT_USE_DEPTH_CUE 0x00000001 -#define W3DVERTMAT_ARGB_EMISSIVE_ONLY 0x00000002 -#define W3DVERTMAT_COPY_SPECULAR_TO_DIFFUSE 0x00000004 -#define W3DVERTMAT_DEPTH_CUE_TO_ALPHA 0x00000008 - -#define W3DVERTMAT_STAGE0_MAPPING_MASK 0x00FF0000 -#define W3DVERTMAT_STAGE0_MAPPING_UV 0x00000000 -#define W3DVERTMAT_STAGE0_MAPPING_ENVIRONMENT 0x00010000 -#define W3DVERTMAT_STAGE0_MAPPING_CHEAP_ENVIRONMENT 0x00020000 -#define W3DVERTMAT_STAGE0_MAPPING_SCREEN 0x00030000 -#define W3DVERTMAT_STAGE0_MAPPING_LINEAR_OFFSET 0x00040000 -#define W3DVERTMAT_STAGE0_MAPPING_SILHOUETTE 0x00050000 -#define W3DVERTMAT_STAGE0_MAPPING_SCALE 0x00060000 -#define W3DVERTMAT_STAGE0_MAPPING_GRID 0x00070000 -#define W3DVERTMAT_STAGE0_MAPPING_ROTATE 0x00080000 -#define W3DVERTMAT_STAGE0_MAPPING_SINE_LINEAR_OFFSET 0x00090000 -#define W3DVERTMAT_STAGE0_MAPPING_STEP_LINEAR_OFFSET 0x000A0000 -#define W3DVERTMAT_STAGE0_MAPPING_ZIGZAG_LINEAR_OFFSET 0x000B0000 -#define W3DVERTMAT_STAGE0_MAPPING_WS_CLASSIC_ENV 0x000C0000 -#define W3DVERTMAT_STAGE0_MAPPING_WS_ENVIRONMENT 0x000D0000 -#define W3DVERTMAT_STAGE0_MAPPING_GRID_CLASSIC_ENV 0x000E0000 -#define W3DVERTMAT_STAGE0_MAPPING_GRID_ENVIRONMENT 0x000F0000 -#define W3DVERTMAT_STAGE0_MAPPING_RANDOM 0x00100000 -#define W3DVERTMAT_STAGE0_MAPPING_EDGE 0x00110000 -#define W3DVERTMAT_STAGE0_MAPPING_BUMPENV 0x00120000 - -#define W3DVERTMAT_STAGE1_MAPPING_MASK 0x0000FF00 -#define W3DVERTMAT_STAGE1_MAPPING_UV 0x00000000 -#define W3DVERTMAT_STAGE1_MAPPING_ENVIRONMENT 0x00000100 -#define W3DVERTMAT_STAGE1_MAPPING_CHEAP_ENVIRONMENT 0x00000200 -#define W3DVERTMAT_STAGE1_MAPPING_SCREEN 0x00000300 -#define W3DVERTMAT_STAGE1_MAPPING_LINEAR_OFFSET 0x00000400 -#define W3DVERTMAT_STAGE1_MAPPING_SILHOUETTE 0x00000500 -#define W3DVERTMAT_STAGE1_MAPPING_SCALE 0x00000600 -#define W3DVERTMAT_STAGE1_MAPPING_GRID 0x00000700 -#define W3DVERTMAT_STAGE1_MAPPING_ROTATE 0x00000800 -#define W3DVERTMAT_STAGE1_MAPPING_SINE_LINEAR_OFFSET 0x00000900 -#define W3DVERTMAT_STAGE1_MAPPING_STEP_LINEAR_OFFSET 0x00000A00 -#define W3DVERTMAT_STAGE1_MAPPING_ZIGZAG_LINEAR_OFFSET 0x00000B00 -#define W3DVERTMAT_STAGE1_MAPPING_WS_CLASSIC_ENV 0x00000C00 -#define W3DVERTMAT_STAGE1_MAPPING_WS_ENVIRONMENT 0x00000D00 -#define W3DVERTMAT_STAGE1_MAPPING_GRID_CLASSIC_ENV 0x00000E00 -#define W3DVERTMAT_STAGE1_MAPPING_GRID_ENVIRONMENT 0x00000F00 -#define W3DVERTMAT_STAGE1_MAPPING_RANDOM 0x00001000 -#define W3DVERTMAT_STAGE1_MAPPING_EDGE 0x00001100 -#define W3DVERTMAT_STAGE1_MAPPING_BUMPENV 0x00001200 - -#define W3DVERTMAT_PSX_MASK 0xFF000000 -#define W3DVERTMAT_PSX_TRANS_MASK 0x07000000 -#define W3DVERTMAT_PSX_TRANS_NONE 0x00000000 -#define W3DVERTMAT_PSX_TRANS_100 0x01000000 -#define W3DVERTMAT_PSX_TRANS_50 0x02000000 -#define W3DVERTMAT_PSX_TRANS_25 0x03000000 -#define W3DVERTMAT_PSX_TRANS_MINUS_100 0x04000000 -#define W3DVERTMAT_PSX_NO_RT_LIGHTING 0x08000000 - -struct W3dVertexMaterialStruct -{ - W3dVertexMaterialStruct(void) {} - - bool operator == (W3dVertexMaterialStruct vm) - { - return ( Attributes == vm.Attributes - && Ambient == vm.Ambient - && Diffuse == vm.Diffuse - && Specular == vm.Specular - && Emissive == vm.Emissive - && Shininess == vm.Shininess - && Opacity == vm.Opacity - && Translucency == vm.Translucency); - } - - bool operator != (W3dVertexMaterialStruct vm) - { - return (!(*this == vm)); - } - - uint32 Attributes; // bitfield for the flags defined above - W3dRGBStruct Ambient; - W3dRGBStruct Diffuse; - W3dRGBStruct Specular; - W3dRGBStruct Emissive; - float32 Shininess; // how tight the specular highlight will be, 1 - 1000 (default = 1) - float32 Opacity; // how opaque the material is, 0.0 = invisible, 1.0 = fully opaque (default = 1) - float32 Translucency; // how much light passes through the material. (default = 0) -}; - -inline void W3d_Vertex_Material_Reset(W3dVertexMaterialStruct * vmat) -{ - vmat->Attributes = 0; - vmat->Ambient.R = vmat->Ambient.G = vmat->Ambient.B = 255; - vmat->Diffuse.R = vmat->Diffuse.G = vmat->Diffuse.B = 255; - vmat->Specular.R = vmat->Specular.G = vmat->Specular.B = 0; - vmat->Emissive.R = vmat->Emissive.G = vmat->Emissive.B = 0; - vmat->Shininess = 1.0f; - vmat->Opacity = 1.0f; - vmat->Translucency = 0.0f; -} - - -// W3dShaderStruct bits. These control every setting in the shader. Use the helper functions -// to set them and test them more easily. -enum -{ - W3DSHADER_DEPTHCOMPARE_PASS_NEVER = 0, // pass never (i.e. always fail depth comparison test) - W3DSHADER_DEPTHCOMPARE_PASS_LESS, // pass if incoming less than stored - W3DSHADER_DEPTHCOMPARE_PASS_EQUAL, // pass if incoming equal to stored - W3DSHADER_DEPTHCOMPARE_PASS_LEQUAL, // pass if incoming less than or equal to stored (default) - W3DSHADER_DEPTHCOMPARE_PASS_GREATER, // pass if incoming greater than stored - W3DSHADER_DEPTHCOMPARE_PASS_NOTEQUAL, // pass if incoming not equal to stored - W3DSHADER_DEPTHCOMPARE_PASS_GEQUAL, // pass if incoming greater than or equal to stored - W3DSHADER_DEPTHCOMPARE_PASS_ALWAYS, // pass always - W3DSHADER_DEPTHCOMPARE_PASS_MAX, // end of enumeration - - W3DSHADER_DEPTHMASK_WRITE_DISABLE = 0, // disable depth buffer writes - W3DSHADER_DEPTHMASK_WRITE_ENABLE, // enable depth buffer writes (default) - W3DSHADER_DEPTHMASK_WRITE_MAX, // end of enumeration - - W3DSHADER_ALPHATEST_DISABLE = 0, // disable alpha testing (default) - W3DSHADER_ALPHATEST_ENABLE, // enable alpha testing - W3DSHADER_ALPHATEST_MAX, // end of enumeration - - W3DSHADER_DESTBLENDFUNC_ZERO = 0, // destination pixel doesn't affect blending (default) - W3DSHADER_DESTBLENDFUNC_ONE, // destination pixel added unmodified - W3DSHADER_DESTBLENDFUNC_SRC_COLOR, // destination pixel multiplied by fragment RGB components - W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_COLOR, // destination pixel multiplied by one minus (i.e. inverse) fragment RGB components - W3DSHADER_DESTBLENDFUNC_SRC_ALPHA, // destination pixel multiplied by fragment alpha component - W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA, // destination pixel multiplied by fragment inverse alpha - W3DSHADER_DESTBLENDFUNC_SRC_COLOR_PREFOG, // destination pixel multiplied by fragment RGB components prior to fogging - W3DSHADER_DESTBLENDFUNC_MAX, // end of enumeration - - W3DSHADER_PRIGRADIENT_DISABLE = 0, // disable primary gradient (same as OpenGL 'decal' texture blend) - W3DSHADER_PRIGRADIENT_MODULATE, // modulate fragment ARGB by gradient ARGB (default) - W3DSHADER_PRIGRADIENT_ADD, // add gradient RGB to fragment RGB, copy gradient A to fragment A - W3DSHADER_PRIGRADIENT_BUMPENVMAP, // environment-mapped bump mapping - W3DSHADER_PRIGRADIENT_MAX, // end of enumeration - - W3DSHADER_SECGRADIENT_DISABLE = 0, // don't draw secondary gradient (default) - W3DSHADER_SECGRADIENT_ENABLE, // add secondary gradient RGB to fragment RGB - W3DSHADER_SECGRADIENT_MAX, // end of enumeration - - W3DSHADER_SRCBLENDFUNC_ZERO = 0, // fragment not added to color buffer - W3DSHADER_SRCBLENDFUNC_ONE, // fragment added unmodified to color buffer (default) - W3DSHADER_SRCBLENDFUNC_SRC_ALPHA, // fragment RGB components multiplied by fragment A - W3DSHADER_SRCBLENDFUNC_ONE_MINUS_SRC_ALPHA, // fragment RGB components multiplied by fragment inverse (one minus) A - W3DSHADER_SRCBLENDFUNC_MAX, // end of enumeration - - W3DSHADER_TEXTURING_DISABLE = 0, // no texturing (treat fragment initial color as 1,1,1,1) (default) - W3DSHADER_TEXTURING_ENABLE, // enable texturing - W3DSHADER_TEXTURING_MAX, // end of enumeration - - W3DSHADER_DETAILCOLORFUNC_DISABLE = 0, // local (default) - W3DSHADER_DETAILCOLORFUNC_DETAIL, // other - W3DSHADER_DETAILCOLORFUNC_SCALE, // local * other - W3DSHADER_DETAILCOLORFUNC_INVSCALE, // ~(~local * ~other) = local + (1-local)*other - W3DSHADER_DETAILCOLORFUNC_ADD, // local + other - W3DSHADER_DETAILCOLORFUNC_SUB, // local - other - W3DSHADER_DETAILCOLORFUNC_SUBR, // other - local - W3DSHADER_DETAILCOLORFUNC_BLEND, // (localAlpha)*local + (~localAlpha)*other - W3DSHADER_DETAILCOLORFUNC_DETAILBLEND, // (otherAlpha)*local + (~otherAlpha)*other - W3DSHADER_DETAILCOLORFUNC_MAX, // end of enumeration - - W3DSHADER_DETAILALPHAFUNC_DISABLE = 0, // local (default) - W3DSHADER_DETAILALPHAFUNC_DETAIL, // other - W3DSHADER_DETAILALPHAFUNC_SCALE, // local * other - W3DSHADER_DETAILALPHAFUNC_INVSCALE, // ~(~local * ~other) = local + (1-local)*other - W3DSHADER_DETAILALPHAFUNC_MAX, // end of enumeration - - W3DSHADER_DEPTHCOMPARE_DEFAULT = W3DSHADER_DEPTHCOMPARE_PASS_LEQUAL, - W3DSHADER_DEPTHMASK_DEFAULT = W3DSHADER_DEPTHMASK_WRITE_ENABLE, - W3DSHADER_ALPHATEST_DEFAULT = W3DSHADER_ALPHATEST_DISABLE, - W3DSHADER_DESTBLENDFUNC_DEFAULT = W3DSHADER_DESTBLENDFUNC_ZERO, - W3DSHADER_PRIGRADIENT_DEFAULT = W3DSHADER_PRIGRADIENT_MODULATE, - W3DSHADER_SECGRADIENT_DEFAULT = W3DSHADER_SECGRADIENT_DISABLE, - W3DSHADER_SRCBLENDFUNC_DEFAULT = W3DSHADER_SRCBLENDFUNC_ONE, - W3DSHADER_TEXTURING_DEFAULT = W3DSHADER_TEXTURING_DISABLE, - W3DSHADER_DETAILCOLORFUNC_DEFAULT = W3DSHADER_DETAILCOLORFUNC_DISABLE, - W3DSHADER_DETAILALPHAFUNC_DEFAULT = W3DSHADER_DETAILALPHAFUNC_DISABLE, -}; - -enum PS2_SHADER_SETTINGS { - PSS_SRC = 0, - PSS_DEST, - PSS_ZERO, - - PSS_SRC_ALPHA = 0, - PSS_DEST_ALPHA, - PSS_ONE, - - // From combo box. To match the PC default gradient. - PSS_PRIGRADIENT_DECAL = 0, - PSS_PRIGRADIENT_MODULATE, - PSS_PRIGRADIENT_HIGHLIGHT, - PSS_PRIGRADIENT_HIGHLIGHT2, - - // Actual PS2 numbers. - PSS_PS2_PRIGRADIENT_MODULATE = 0, - PSS_PS2_PRIGRADIENT_DECAL, - PSS_PS2_PRIGRADIENT_HIGHLIGHT, - PSS_PS2_PRIGRADIENT_HIGHLIGHT2, - - - PSS_DEPTHCOMPARE_PASS_NEVER = 0, - PSS_DEPTHCOMPARE_PASS_LESS, - PSS_DEPTHCOMPARE_PASS_ALWAYS, - PSS_DEPTHCOMPARE_PASS_LEQUAL, -}; - -struct W3dShaderStruct -{ - W3dShaderStruct(void) {} - uint8 DepthCompare; - uint8 DepthMask; - uint8 ColorMask; // now obsolete and ignored - uint8 DestBlend; - uint8 FogFunc; // now obsolete and ignored - uint8 PriGradient; - uint8 SecGradient; - uint8 SrcBlend; - uint8 Texturing; - uint8 DetailColorFunc; - uint8 DetailAlphaFunc; - uint8 ShaderPreset; // now obsolete and ignored - uint8 AlphaTest; - uint8 PostDetailColorFunc; - uint8 PostDetailAlphaFunc; - uint8 pad[1]; -}; - -struct W3dPS2ShaderStruct -{ - uint8 DepthCompare; - uint8 DepthMask; - uint8 PriGradient; - uint8 Texturing; - uint8 AlphaTest; - uint8 AParam; - uint8 BParam; - uint8 CParam; - uint8 DParam; - uint8 pad[3]; -}; - -inline void W3d_Shader_Reset(W3dShaderStruct * s) { - s->DepthCompare = W3DSHADER_DEPTHCOMPARE_PASS_LEQUAL; - s->DepthMask = W3DSHADER_DEPTHMASK_WRITE_ENABLE; - s->ColorMask = 0; // obsolete - s->DestBlend = W3DSHADER_DESTBLENDFUNC_ZERO; - s->FogFunc = 0; // obsolete - s->PriGradient = W3DSHADER_PRIGRADIENT_MODULATE; - s->SecGradient = W3DSHADER_SECGRADIENT_DISABLE; - s->SrcBlend = W3DSHADER_SRCBLENDFUNC_ONE; - s->Texturing = W3DSHADER_TEXTURING_DISABLE; - s->DetailColorFunc = W3DSHADER_DETAILCOLORFUNC_DISABLE; - s->DetailAlphaFunc = W3DSHADER_DETAILALPHAFUNC_DISABLE; - s->ShaderPreset = 0; // obsolete - s->AlphaTest = W3DSHADER_ALPHATEST_DISABLE; - s->PostDetailColorFunc = W3DSHADER_DETAILCOLORFUNC_DISABLE; - s->PostDetailAlphaFunc = W3DSHADER_DETAILALPHAFUNC_DISABLE; - s->pad[0] = 0; - } - -inline void W3d_Shader_Set_Depth_Compare(W3dShaderStruct * s,int val) { s->DepthCompare = val; } -inline void W3d_Shader_Set_Depth_Mask(W3dShaderStruct * s,int val) { s->DepthMask = val; } -inline void W3d_Shader_Set_Dest_Blend_Func(W3dShaderStruct * s,int val) { s->DestBlend = val; } -inline void W3d_Shader_Set_Pri_Gradient(W3dShaderStruct * s,int val) { s->PriGradient = val; } -inline void W3d_Shader_Set_Sec_Gradient(W3dShaderStruct * s,int val) { s->SecGradient = val; } -inline void W3d_Shader_Set_Src_Blend_Func(W3dShaderStruct * s,int val) { s->SrcBlend = val; } -inline void W3d_Shader_Set_Texturing(W3dShaderStruct * s,int val) { s->Texturing = val; } -inline void W3d_Shader_Set_Detail_Color_Func(W3dShaderStruct * s,int val) { s->DetailColorFunc = val; } -inline void W3d_Shader_Set_Detail_Alpha_Func(W3dShaderStruct * s,int val) { s->DetailAlphaFunc = val; } -inline void W3d_Shader_Set_Alpha_Test(W3dShaderStruct * s,int val) { s->AlphaTest = val; } -inline void W3d_Shader_Set_Post_Detail_Color_Func(W3dShaderStruct * s,int val) { s->PostDetailColorFunc = val; } -inline void W3d_Shader_Set_Post_Detail_Alpha_Func(W3dShaderStruct * s,int val) { s->PostDetailAlphaFunc = val; } - -// These functions use the existing W3dShaderStruct unused members to store PS2 specific parameters. -// At mesh save time, if a PS2 material was used, a separate PS2 material chunk is saved out. -// If W3dShaderStruct is changed this should still work because it is only used for the PS2 stuff. -inline void W3d_Shader_Set_PS2_Param_A(W3dShaderStruct *s, int val) {s->ColorMask = val;} -inline void W3d_Shader_Set_PS2_Param_B(W3dShaderStruct *s, int val) {s->FogFunc = val;} -inline void W3d_Shader_Set_PS2_Param_C(W3dShaderStruct *s, int val) {s->ShaderPreset = val;} -inline void W3d_Shader_Set_PS2_Param_D(W3dShaderStruct *s, int val) {s->pad[0] = val;} - -inline int W3d_Shader_Get_PS2_Param_A(const W3dShaderStruct *s) {return (s->ColorMask);} -inline int W3d_Shader_Get_PS2_Param_B(const W3dShaderStruct *s) {return (s->FogFunc);} -inline int W3d_Shader_Get_PS2_Param_C(const W3dShaderStruct *s) {return (s->ShaderPreset);} -inline int W3d_Shader_Get_PS2_Param_D(const W3dShaderStruct *s) {return (s->pad[0]);} - -inline int W3d_Shader_Get_PS2_Param_A(const W3dPS2ShaderStruct *s) {return (s->AParam);} -inline int W3d_Shader_Get_PS2_Param_B(const W3dPS2ShaderStruct *s) {return (s->BParam);} -inline int W3d_Shader_Get_PS2_Param_C(const W3dPS2ShaderStruct *s) {return (s->CParam);} -inline int W3d_Shader_Get_PS2_Param_D(const W3dPS2ShaderStruct *s) {return (s->DParam);} - -inline int W3d_Shader_Get_Depth_Compare(const W3dPS2ShaderStruct * s) { return s->DepthCompare; } -inline int W3d_Shader_Get_Depth_Mask(const W3dPS2ShaderStruct * s) { return s->DepthMask; } -inline int W3d_Shader_Get_Pri_Gradient(const W3dPS2ShaderStruct * s) { return s->PriGradient; } -inline int W3d_Shader_Get_Texturing(const W3dPS2ShaderStruct * s) { return s->Texturing; } -inline int W3d_Shader_Get_Alpha_Test(const W3dPS2ShaderStruct * s) { return s->AlphaTest; } - - -inline int W3d_Shader_Get_Depth_Compare(const W3dShaderStruct * s) { return s->DepthCompare; } -inline int W3d_Shader_Get_Depth_Mask(const W3dShaderStruct * s) { return s->DepthMask; } -inline int W3d_Shader_Get_Dest_Blend_Func(const W3dShaderStruct * s) { return s->DestBlend; } -inline int W3d_Shader_Get_Pri_Gradient(const W3dShaderStruct * s) { return s->PriGradient; } -inline int W3d_Shader_Get_Sec_Gradient(const W3dShaderStruct * s) { return s->SecGradient; } -inline int W3d_Shader_Get_Src_Blend_Func(const W3dShaderStruct * s) { return s->SrcBlend; } -inline int W3d_Shader_Get_Texturing(const W3dShaderStruct * s) { return s->Texturing; } -inline int W3d_Shader_Get_Detail_Color_Func(const W3dShaderStruct * s) { return s->DetailColorFunc; } -inline int W3d_Shader_Get_Detail_Alpha_Func(const W3dShaderStruct * s) { return s->DetailAlphaFunc; } -inline int W3d_Shader_Get_Alpha_Test(const W3dShaderStruct * s) { return s->AlphaTest; } -inline int W3d_Shader_Get_Post_Detail_Color_Func(const W3dShaderStruct * s) { return s->PostDetailColorFunc; } -inline int W3d_Shader_Get_Post_Detail_Alpha_Func(const W3dShaderStruct * s) { return s->PostDetailAlphaFunc; } - - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Texture Animation parameters -// May occur inside a texture chunk if its needed -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3DTEXTURE_PUBLISH 0x0001 // this texture should be "published" (indirected so its changeable in code) -#define W3DTEXTURE_RESIZE_OBSOLETE 0x0002 // this texture should be resizeable (OBSOLETE!!!) -#define W3DTEXTURE_NO_LOD 0x0004 // this texture should not have any LOD (mipmapping or resizing) -#define W3DTEXTURE_CLAMP_U 0x0008 // this texture should be clamped on U -#define W3DTEXTURE_CLAMP_V 0x0010 // this texture should be clamped on V -#define W3DTEXTURE_ALPHA_BITMAP 0x0020 // this texture's alpha channel should be collapsed to one bit - -// Specify desired no. of mip-levels to be generated. -#define W3DTEXTURE_MIP_LEVELS_MASK 0x00c0 -#define W3DTEXTURE_MIP_LEVELS_ALL 0x0000 // generate all mip-levels -#define W3DTEXTURE_MIP_LEVELS_2 0x0040 // generate up to 2 mip-levels (NOTE: use W3DTEXTURE_NO_LOD to generate just 1 mip-level) -#define W3DTEXTURE_MIP_LEVELS_3 0x0080 // generate up to 3 mip-levels -#define W3DTEXTURE_MIP_LEVELS_4 0x00c0 // generate up to 4 mip-levels - -// Hints to describe the intended use of the various passes / stages -// This will go into the high byte of Attributes. -#define W3DTEXTURE_HINT_SHIFT 8 // number of bits to shift up -#define W3DTEXTURE_HINT_MASK 0x0000ff00 // mask for shifted hint value - -#define W3DTEXTURE_HINT_BASE 0x0000 // base texture -#define W3DTEXTURE_HINT_EMISSIVE 0x0100 // emissive map -#define W3DTEXTURE_HINT_ENVIRONMENT 0x0200 // environment/reflection map -#define W3DTEXTURE_HINT_SHINY_MASK 0x0300 // shinyness mask map - -#define W3DTEXTURE_TYPE_MASK 0x1000 -#define W3DTEXTURE_TYPE_COLORMAP 0x0000 // Color map. -#define W3DTEXTURE_TYPE_BUMPMAP 0x1000 // Grayscale heightmap (to be converted to bumpmap). - -// Animation types -#define W3DTEXTURE_ANIM_LOOP 0x0000 -#define W3DTEXTURE_ANIM_PINGPONG 0x0001 -#define W3DTEXTURE_ANIM_ONCE 0x0002 -#define W3DTEXTURE_ANIM_MANUAL 0x0003 - -struct W3dTextureInfoStruct -{ - W3dTextureInfoStruct(void) {} - uint16 Attributes; // flags for this texture - uint16 AnimType; // animation logic - uint32 FrameCount; // Number of frames (1 if not animated) - float32 FrameRate; // Frame rate, frames per second in floating point -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A triangle, occurs inside the W3D_CHUNK_TRIANGLES chunk -// This was introduced with version 3.0 of the file format -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dTriStruct -{ - uint32 Vindex[3]; // vertex,vnormal,texcoord,color indices - uint32 Attributes; // attributes bits - W3dVectorStruct Normal; // plane normal - float32 Dist; // plane distance -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Flags for the Triangle Attributes member -///////////////////////////////////////////////////////////////////////////////////////////// -typedef enum -{ - SURFACE_TYPE_LIGHT_METAL = 0, - SURFACE_TYPE_HEAVY_METAL, - SURFACE_TYPE_WATER, - SURFACE_TYPE_SAND, - SURFACE_TYPE_DIRT, - SURFACE_TYPE_MUD, - SURFACE_TYPE_GRASS, - SURFACE_TYPE_WOOD, - SURFACE_TYPE_CONCRETE, - SURFACE_TYPE_FLESH, - SURFACE_TYPE_ROCK, - SURFACE_TYPE_SNOW, - SURFACE_TYPE_ICE, - SURFACE_TYPE_DEFAULT, - SURFACE_TYPE_GLASS, - SURFACE_TYPE_CLOTH, - SURFACE_TYPE_TIBERIUM_FIELD, - SURFACE_TYPE_FOLIAGE_PERMEABLE, - SURFACE_TYPE_GLASS_PERMEABLE, - SURFACE_TYPE_ICE_PERMEABLE, - SURFACE_TYPE_CLOTH_PERMEABLE, - SURFACE_TYPE_ELECTRICAL, - SURFACE_TYPE_FLAMMABLE, - SURFACE_TYPE_STEAM, - SURFACE_TYPE_ELECTRICAL_PERMEABLE, - SURFACE_TYPE_FLAMMABLE_PERMEABLE, - SURFACE_TYPE_STEAM_PERMEABLE, - - SURFACE_TYPE_MAX // NOTE: if you add a surface type, add it to the SurfaceEffects.INI file! -} W3D_SURFACE_TYPES; - -const char * const SURFACE_TYPE_STRINGS[SURFACE_TYPE_MAX] = -{ - "Light Metal", - "Heavy Metal", - "Water", - "Sand", - "Dirt", - "Mud", - "Grass", - "Wood", - "Concrete", - "Flesh", - "Rock", - "Snow", - "Ice", - "Default", - "Glass", - "Cloth", - "Tiberium Field", - "Foliage Permeable", - "Glass Permeable", - "Ice Permeable", - "Cloth Permeable", - "Electrical", - "Electrical Permeable", - "Flammable", - "Flammable Permeable", - "Steam", - "Steam Permeable", -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Flags for the Mesh Attributes member -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3D_MESH_FLAG_NONE 0x00000000 // plain ole normal mesh -#define W3D_MESH_FLAG_COLLISION_BOX 0x00000001 // (obsolete as of 4.1) mesh is a collision box (should be 8 verts, should be hidden, etc) -#define W3D_MESH_FLAG_SKIN 0x00000002 // (obsolete as of 4.1) skin mesh -#define W3D_MESH_FLAG_SHADOW 0x00000004 // (obsolete as of 4.1) intended to be projected as a shadow -#define W3D_MESH_FLAG_ALIGNED 0x00000008 // (obsolete as of 4.1) always aligns with camera - -#define W3D_MESH_FLAG_COLLISION_TYPE_MASK 0x00000FF0 // mask for the collision type bits -#define W3D_MESH_FLAG_COLLISION_TYPE_SHIFT 4 // shifting to get to the collision type bits -#define W3D_MESH_FLAG_COLLISION_TYPE_PHYSICAL 0x00000010 // physical collisions -#define W3D_MESH_FLAG_COLLISION_TYPE_PROJECTILE 0x00000020 // projectiles (rays) collide with this -#define W3D_MESH_FLAG_COLLISION_TYPE_VIS 0x00000040 // vis rays collide with this mesh -#define W3D_MESH_FLAG_COLLISION_TYPE_CAMERA 0x00000080 // camera rays/boxes collide with this mesh -#define W3D_MESH_FLAG_COLLISION_TYPE_VEHICLE 0x00000100 // vehicles collide with this mesh (and with physical collision meshes) - -#define W3D_MESH_FLAG_HIDDEN 0x00001000 // this mesh is hidden by default -#define W3D_MESH_FLAG_TWO_SIDED 0x00002000 // render both sides of this mesh -#define OBSOLETE_W3D_MESH_FLAG_LIGHTMAPPED 0x00004000 // obsolete lightmapped mesh - // NOTE: retained for backwards compatibility - use W3D_MESH_FLAG_PRELIT_* instead. -#define W3D_MESH_FLAG_CAST_SHADOW 0x00008000 // this mesh casts shadows - -#define W3D_MESH_FLAG_GEOMETRY_TYPE_MASK 0x00FF0000 // (introduced with 4.1) -#define W3D_MESH_FLAG_GEOMETRY_TYPE_NORMAL 0x00000000 // (4.1+) normal mesh geometry -#define W3D_MESH_FLAG_GEOMETRY_TYPE_CAMERA_ALIGNED 0x00010000 // (4.1+) camera aligned mesh -#define W3D_MESH_FLAG_GEOMETRY_TYPE_SKIN 0x00020000 // (4.1+) skin mesh -#define OBSOLETE_W3D_MESH_FLAG_GEOMETRY_TYPE_SHADOW 0x00030000 // (4.1+) shadow mesh OBSOLETE! -#define W3D_MESH_FLAG_GEOMETRY_TYPE_AABOX 0x00040000 // (4.1+) aabox OBSOLETE! -#define W3D_MESH_FLAG_GEOMETRY_TYPE_OBBOX 0x00050000 // (4.1+) obbox OBSOLETE! -#define W3D_MESH_FLAG_GEOMETRY_TYPE_CAMERA_ORIENTED 0x00060000 // (4.1+) camera oriented mesh (points _towards_ camera) - -#define W3D_MESH_FLAG_PRELIT_MASK 0x0F000000 // (4.2+) -#define W3D_MESH_FLAG_PRELIT_UNLIT 0x01000000 // mesh contains an unlit material chunk wrapper -#define W3D_MESH_FLAG_PRELIT_VERTEX 0x02000000 // mesh contains a precalculated vertex-lit material chunk wrapper -#define W3D_MESH_FLAG_PRELIT_LIGHTMAP_MULTI_PASS 0x04000000 // mesh contains a precalculated multi-pass lightmapped material chunk wrapper -#define W3D_MESH_FLAG_PRELIT_LIGHTMAP_MULTI_TEXTURE 0x08000000 // mesh contains a precalculated multi-texture lightmapped material chunk wrapper - -#define W3D_MESH_FLAG_SHATTERABLE 0x10000000 // this mesh is shatterable. -#define W3D_MESH_FLAG_NPATCHABLE 0x20000000 // it is ok to NPatch this mesh - -/******************************************************************************** - - Meshes - - Version 3 Mesh Header, trimmed out some of the junk that was in the - previous versions. - -********************************************************************************/ - -#define W3D_CURRENT_MESH_VERSION W3D_MAKE_VERSION(4,2) - -#define W3D_VERTEX_CHANNEL_LOCATION 0x00000001 // object-space location of the vertex -#define W3D_VERTEX_CHANNEL_NORMAL 0x00000002 // object-space normal for the vertex -#define W3D_VERTEX_CHANNEL_TEXCOORD 0x00000004 // texture coordinate -#define W3D_VERTEX_CHANNEL_COLOR 0x00000008 // vertex color -#define W3D_VERTEX_CHANNEL_BONEID 0x00000010 // per-vertex bone id for skins - -#define W3D_FACE_CHANNEL_FACE 0x00000001 // basic face info, W3dTriStruct... - -// boundary values for W3dMeshHeaderStruct::SortLevel -#define SORT_LEVEL_NONE 0 -#define MAX_SORT_LEVEL 32 -#define SORT_LEVEL_BIN1 10 -#define SORT_LEVEL_BIN2 15 -#define SORT_LEVEL_BIN3 20 - -struct W3dMeshHeader3Struct -{ - uint32 Version; - uint32 Attributes; - - char MeshName[W3D_NAME_LEN]; - char ContainerName[W3D_NAME_LEN]; - - // - // Counts, these can be regarded as an inventory of what is to come in the file. - // - uint32 NumTris; // number of triangles - uint32 NumVertices; // number of unique vertices - uint32 NumMaterials; // number of unique materials - uint32 NumDamageStages; // number of damage offset chunks - sint32 SortLevel; // static sorting level of this mesh - uint32 PrelitVersion; // mesh generated by this version of Lightmap Tool - uint32 FutureCounts[1]; // future counts - - uint32 VertexChannels; // bits for presence of types of per-vertex info - uint32 FaceChannels; // bits for presence of types of per-face info - - // - // Bounding volumes - // - W3dVectorStruct Min; // Min corner of the bounding box - W3dVectorStruct Max; // Max corner of the bounding box - W3dVectorStruct SphCenter; // Center of bounding sphere - float32 SphRadius; // Bounding sphere radius - -}; - -// -// Vertex Influences. For "skins" each vertex can be associated with a -// different bone. -// -struct W3dVertInfStruct -{ - uint16 BoneIdx; - uint8 Pad[6]; -}; - -// -// Deform information. Each mesh can have sets of keyframes of -// deform info associated with it. -// -struct W3dMeshDeform -{ - uint32 SetCount; - uint32 AlphaPasses; - uint32 reserved[3]; -}; - -// -// Deform set information. Each set is made up of a series -// of keyframes. -// -struct W3dDeformSetInfo -{ - uint32 KeyframeCount; - uint32 flags; - uint32 reserved[1]; -}; - -#define W3D_DEFORM_SET_MANUAL_DEFORM 0x00000001 // set is isn't applied during sphere or point tests. - -// -// Deform keyframe information. Each keyframe is made up of -// a set of per-vert deform data. -// -struct W3dDeformKeyframeInfo -{ - float32 DeformPercent; - uint32 DataCount; - uint32 reserved[2]; -}; - -// -// Deform data. Contains deform information about a vertex -// in the mesh. -// -struct W3dDeformData -{ - uint32 VertexIndex; - W3dVectorStruct Position; - W3dRGBAStruct Color; - uint32 reserved[2]; -}; - -// -// AABTree header. Each mesh can have an associated Axis-Aligned-Bounding-Box tree -// which is used for collision detection and certain rendering algorithms (like -// texture projection. -// -struct W3dMeshAABTreeHeader -{ - uint32 NodeCount; - uint32 PolyCount; - uint32 Padding[6]; -}; - -// -// AABTree Node. This is a node in the AABTree. -// If the MSB of FrontOrPoly0 is 1, then the node is a leaf and contains Poly0 and PolyCount -// else, the node is not a leaf and contains indices to its front and back children. This matches -// the format used by AABTreeClass in WW3D. -// -struct W3dMeshAABTreeNode -{ - W3dVectorStruct Min; // min corner of the box - W3dVectorStruct Max; // max corner of the box - uint32 FrontOrPoly0; // index of the front child or poly0 (if MSB is set, then leaf and poly0 is valid) - uint32 BackOrPolyCount; // index of the back child or polycount -}; - - -/******************************************************************************** - - WHT ( Westwood Hierarchy Tree ) - - A hierarchy tree defines a set of coordinate systems which are connected - hierarchically. The header defines the name, number of pivots, etc. - The pivots chunk will contain a W3dPivotStructs for each node in the - tree. - - The W3dPivotFixupStruct contains a transform for each MAX coordinate - system and our version of that same coordinate system (bone). It is - needed when the user exports the base pose using "Translation Only". - These are the matrices which go from the MAX rotated coordinate systems - to a system which is unrotated in the base pose. These transformations - are needed when exporting a hierarchy animation with the given hierarchy - tree file. - - Another explanation of these kludgy "fixup" matrices: - - What are the "fixup" matrices? These are the transforms which - were applied to the base pose when the user wanted to force the - base pose to use only matrices with certain properties. For - example, if we wanted the base pose to use translations only, - the fixup transform for each node is a transform which when - multiplied by the real node's world transform, yeilds a pure - translation matrix. Fixup matrices are used in the mesh - exporter since all vertices must be transformed by their inverses - in order to make things work. They also show up in the animation - exporter because they are needed to make the animation work with - the new base pose. - -********************************************************************************/ - -#define W3D_CURRENT_HTREE_VERSION W3D_MAKE_VERSION(4,1) - -struct W3dHierarchyStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; // Name of the hierarchy - uint32 NumPivots; - W3dVectorStruct Center; -}; - -struct W3dPivotStruct -{ - char Name[W3D_NAME_LEN]; // Name of the node (UR_ARM, LR_LEG, TORSO, etc) - uint32 ParentIdx; // 0xffffffff = root pivot; no parent - W3dVectorStruct Translation; // translation to pivot point - W3dVectorStruct EulerAngles; // orientation of the pivot point - W3dQuaternionStruct Rotation; // orientation of the pivot point -}; - -struct W3dPivotFixupStruct -{ - float32 TM[4][3]; // this is a direct dump of a MAX 3x4 matrix -}; - - -/******************************************************************************** - - WHA (Westwood Hierarchy Animation) - - A Hierarchy Animation is a set of data defining deltas from the base - position of a hierarchy tree. Translation and Rotation channels can be - attached to any node of the hierarchy tree which the animation is - associated with. - -********************************************************************************/ - -#define W3D_CURRENT_HANIM_VERSION W3D_MAKE_VERSION(4,1) -#define W3D_CURRENT_COMPRESSED_HANIM_VERSION W3D_MAKE_VERSION(0,1) -#define W3D_CURRENT_MORPH_HANIM_VERSION W3D_MAKE_VERSION(0,1) - -struct W3dAnimHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; - uint32 NumFrames; - uint32 FrameRate; - -}; - -struct W3dCompressedAnimHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; - uint32 NumFrames; - uint16 FrameRate; - uint16 Flavor; -}; - - -enum -{ - ANIM_CHANNEL_X = 0, - ANIM_CHANNEL_Y, - ANIM_CHANNEL_Z, - ANIM_CHANNEL_XR, - ANIM_CHANNEL_YR, - ANIM_CHANNEL_ZR, - ANIM_CHANNEL_Q, - - ANIM_CHANNEL_TIMECODED_X, - ANIM_CHANNEL_TIMECODED_Y, - ANIM_CHANNEL_TIMECODED_Z, - ANIM_CHANNEL_TIMECODED_Q, - - ANIM_CHANNEL_ADAPTIVEDELTA_X, - ANIM_CHANNEL_ADAPTIVEDELTA_Y, - ANIM_CHANNEL_ADAPTIVEDELTA_Z, - ANIM_CHANNEL_ADAPTIVEDELTA_Q, -}; - -// -// Flavor Enumerations -// -enum -{ - ANIM_FLAVOR_TIMECODED = 0, - ANIM_FLAVOR_ADAPTIVE_DELTA, - - ANIM_FLAVOR_VALID -}; - -// Begin Classic Structures - -struct W3dAnimChannelStruct -{ - uint16 FirstFrame; - uint16 LastFrame; - uint16 VectorLen; // length of each vector in this channel - uint16 Flags; // channel type. - uint16 Pivot; // pivot affected by this channel - uint16 pad; - float32 Data[1]; // will be (LastFrame - FirstFrame + 1) * VectorLen long -}; - -enum -{ - BIT_CHANNEL_VIS = 0, // turn meshes on and off depending on anim frame. - BIT_CHANNEL_TIMECODED_VIS, -}; - -struct W3dBitChannelStruct -{ - uint16 FirstFrame; // all frames outside "First" and "Last" are assumed = DefaultVal - uint16 LastFrame; - uint16 Flags; // channel type. - uint16 Pivot; // pivot affected by this channel - uint8 DefaultVal; // default state when outside valid range. - uint8 Data[1]; // will be (LastFrame - FirstFrame + 1) / 8 long -}; - -// End Classic Structures -// Begin Time Coded Structures - -// A time code is a uint32 that prefixes each vector -// the MSB is used to indicate a binary (non interpolated) movement - -#define W3D_TIMECODED_BINARY_MOVEMENT_FLAG 0x80000000 - -struct W3dTimeCodedAnimChannelStruct -{ - uint32 NumTimeCodes; // number of time coded entries - uint16 Pivot; // pivot affected by this channel - uint8 VectorLen; // length of each vector in this channel - uint8 Flags; // channel type. - uint32 Data[1]; // will be (NumTimeCodes * ((VectorLen * sizeof(uint32)) + sizeof(uint32))) -}; - -// The bit channel is encoded right into the MSB of each time code -#define W3D_TIMECODED_BIT_MASK 0x80000000 - -struct W3dTimeCodedBitChannelStruct -{ - uint32 NumTimeCodes; // number of time coded entries - uint16 Pivot; // pivot affected by this channel - uint8 Flags; // channel type. - uint8 DefaultVal; // default state when outside valid range. - uint32 Data[1]; // will be (NumTimeCodes * sizeof(uint32)) -}; - -// End Time Coded Structures -// Begin AdaptiveDelta Structures -struct W3dAdaptiveDeltaAnimChannelStruct -{ - uint32 NumFrames; // number of frames of animation - uint16 Pivot; // pivot effected by this channel - uint8 VectorLen; // num Channels - uint8 Flags; // channel type - float Scale; // Filter Table Scale - - uint32 Data[1]; // OpCode Data Stream - -}; -// End AdaptiveDelta Structures - -/******************************************************************************** - - HMorphAnimClass - - This is an animation format which describes morphs between poses in another - animation. It is used for Renegade's facial animation system. There is - a normal anim which defines the pose for each phoneme and then a "Morph Anim" - which defines the transitions between phonemes over time. In addition there - is the concept of multiple morph channels in a morph anim. Each "channel" - controls a set of pivots in the skeleton and has its own set of morph keys - and poses. This lets us have one set of poses for expressions and another - for phonemes (a bone is only moved in one or the other anims though) - - The chunks used to describe a "morph" anim are as follows: - - W3D_CHUNK_MORPH_ANIMATION =0x000002C0, // wrapper for the entire anim - W3D_CHUNK_MORPHANIM_HEADER, // W3dMorphAnimHeaderStruct describes playback rate, number of frames, and type of compression - W3D_CHUNK_MORPHANIM_CHANNEL, // wrapper for a channel - W3D_CHUNK_MORPHANIM_POSENAME, // name of the other anim which contains the poses for this morph channel - W3D_CHUNK_MORPHANIM_KEYDATA, // array of W3dMorphAnimKeyStruct's (use chunk length to determine how many) - W3D_CHUNK_MORPHANIM_PIVOTCHANNELDATA, // uin32 per pivot in the htree, indicating which channel controls the pivot - - -********************************************************************************/ -struct W3dMorphAnimHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; - uint32 FrameCount; - float32 FrameRate; - uint32 ChannelCount; -}; - -struct W3dMorphAnimKeyStruct -{ - uint32 MorphFrame; - uint32 PoseFrame; -}; - - - -/******************************************************************************** - - HModel - Hiearchical Model - - A Hierarchy Model is a set of render objects which should be attached to - bones in a hierarchy tree. There can be multiple objects per node - in the tree. Or there may be no objects attached to a particular bone. - - (gth) 09/22/2000 - Simplified the HModel file format. The W3DHModelAuxDataStruct - was un-needed and moved to w3d_obsolete.h. The safe way to parse previous - and current HModel formats is this: - - Read in the header from W3D_CHUNK_HMODEL_HEADER - - Allocate space for 'NumConnections' nodes that will follow - - Read in the rest of the chunks - - Create a sub-object for W3D_CHUNK_NODE, W3D_CHUNK_COLLISION_NODE, or - W3D_CHUNK_SKIN_NODE. - - Skip the OBSOLETE_W3D_CHUNK_HMODEL_AUX_DATA and OBSOLETE_W3D_CHUNK_SHADOW_NODE - -********************************************************************************/ - -#define W3D_CURRENT_HMODEL_VERSION W3D_MAKE_VERSION(4,2) - -struct W3dHModelHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; // Name of this model - char HierarchyName[W3D_NAME_LEN]; // Name of the hierarchy tree this model uses - uint16 NumConnections; -}; - - -struct W3dHModelNodeStruct -{ - // Note: the full name of the Render object is expected to be: . - char RenderObjName[W3D_NAME_LEN]; - uint16 PivotIdx; -}; - - -/******************************************************************************** - - (LODModel - Level-Of-Detail Model) - - An LOD Model is a set of render objects which are interchangeable and - designed to be different resolution versions of the same object. - -********************************************************************************/ - -struct W3dLODModelHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; // Name of this LOD Model - uint16 NumLODs; -}; - -struct W3dLODStruct -{ - char RenderObjName[2*W3D_NAME_LEN]; - float32 LODMin; // "artist" inspired switching distances - float32 LODMax; -}; - - -/******************************************************************************** - - Collection - - A collection chunk is generated when the user exports a bunch of meshes. - The collection will be named with the root name of the w3d file and will - contain a string chunk for the name of each render object in the collection. - A collection may also contain a "Snap Points" chunk. - - W3D_CHUNK_COLLECTION - W3D_CHUNK_COLLECTION_HEADER - W3D_CHUNK_SNAP_POINTS - W3D_CHUNK_COLLECTION_OBJ_NAME - W3D_CHUNK_COLLECTION_OBJ_NAME - W3D_CHUNK_COLLECTION_OBJ_NAME - ... - -********************************************************************************/ - -#define W3D_CURRENT_COLLECTION_VERSION W3D_MAKE_VERSION(4,2) - -struct W3dCollectionHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; - uint32 RenderObjectCount; - uint32 pad[2]; -}; - - -/* -** Placeholder chunks. Also known as "PROXIES". These are used by the Renegade -** level editor to instruct the editor to instance a particular named object -*/ -#define W3D_CURRENT_PLACEHOLDER_VERSION W3D_MAKE_VERSION(1,0) - -// -// Note: This structure is follwed directly by an array of char's 'name_len' in length -// which specify the name of the placeholder object in our Commando-level editor. -// -struct W3dPlaceholderStruct -{ - uint32 version; - float32 transform[4][3]; // this is a direct dump of a MAX 3x4 matrix - uint32 name_len; -}; - - -/* -** Transform chunks. These chunks refer to other W3D files which should be transformed by -** this file. This feature is used to allow user to (for example) lightmap the interior -** of a building once and then just transform that into all of our levels that use it. -*/ -#define W3D_CURRENT_TRANSFORM_VERSION W3D_MAKE_VERSION(1,0) - -// -// Note: This structure is followed directly by an array of char's 'name_len' in length -// which specifies the name of the file to apply the transform to. -// -struct W3dTransformNodeStruct -{ - uint32 version; - float32 transform[4][3]; // this is a direct dump of a MAX 3x4 matrix - uint32 name_len; -}; - - - -/******************************************************************************** - - Lights - - The following structs are used to define lights in the w3d file. Currently - we have point lights, directional lights, and spot lights. - -********************************************************************************/ - -#define W3D_CURRENT_LIGHT_VERSION W3D_MAKE_VERSION(1,0) - -#define W3D_LIGHT_ATTRIBUTE_TYPE_MASK 0x000000FF -#define W3D_LIGHT_ATTRIBUTE_POINT 0x00000001 -#define W3D_LIGHT_ATTRIBUTE_DIRECTIONAL 0x00000002 -#define W3D_LIGHT_ATTRIBUTE_SPOT 0x00000003 -#define W3D_LIGHT_ATTRIBUTE_CAST_SHADOWS 0x00000100 - -struct W3dLightStruct -{ - uint32 Attributes; - uint32 Unused; // Old exclusion bit deprecated - W3dRGBStruct Ambient; - W3dRGBStruct Diffuse; - W3dRGBStruct Specular; - float32 Intensity; -}; - -struct W3dSpotLightStruct -{ - W3dVectorStruct SpotDirection; - float32 SpotAngle; - float32 SpotExponent; -}; - -struct W3dLightAttenuationStruct -{ - float32 Start; - float32 End; -}; - -struct W3dLightTransformStruct -{ - float32 Transform [3][4]; -}; - - -/******************************************************************************** - - Particle emitters - - The following structs are used to define emitters in the w3d file. - -********************************************************************************/ - -#define W3D_CURRENT_EMITTER_VERSION 0x00020000 - -// -// This enum contains valid defines for the Type field -// of the W3dEmitterUserInfoStruct. The programmer -// can add entries here that their specific loader -// can switch on to determine what type the emitter is. -// -// NOTE: Please add a string the the EMITTER_TYPE_NAMES -// array when you add an entry to the enum. -// -enum -{ - EMITTER_TYPEID_DEFAULT = 0, - EMITTER_TYPEID_COUNT -}; - -// -// The definition of this string array can be found in -// Part_Ldr.cpp. Please update this array accordingly. -// -extern const char *EMITTER_TYPE_NAMES[EMITTER_TYPEID_COUNT]; - -struct W3dEmitterHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; -}; - -struct W3dEmitterUserInfoStruct -{ - uint32 Type; // One of the EMITTER_TYPEID_ enum's defined above - uint32 SizeofStringParam; // Size (in bytes) of the following string data - char StringParam[1]; // Array of bytes. Where "count = SizeofStringParam" -}; - -struct W3dEmitterInfoStruct -{ - char TextureFilename[260]; - float32 StartSize; - float32 EndSize; - float32 Lifetime; - float32 EmissionRate; - float32 MaxEmissions; - float32 VelocityRandom; - float32 PositionRandom; - float32 FadeTime; - float32 Gravity; - float32 Elasticity; - W3dVectorStruct Velocity; - W3dVectorStruct Acceleration; - W3dRGBAStruct StartColor; - W3dRGBAStruct EndColor; -}; - -struct W3dVolumeRandomizerStruct -{ - uint32 ClassID; - float32 Value1; - float32 Value2; - float32 Value3; - uint32 reserved[4]; -}; - -#define W3D_EMITTER_RENDER_MODE_TRI_PARTICLES 0 -#define W3D_EMITTER_RENDER_MODE_QUAD_PARTICLES 1 -#define W3D_EMITTER_RENDER_MODE_LINE 2 - -#define W3D_EMITTER_FRAME_MODE_1x1 0 -#define W3D_EMITTER_FRAME_MODE_2x2 1 -#define W3D_EMITTER_FRAME_MODE_4x4 2 -#define W3D_EMITTER_FRAME_MODE_8x8 3 -#define W3D_EMITTER_FRAME_MODE_16x16 4 - -struct W3dEmitterInfoStructV2 -{ - uint32 BurstSize; - W3dVolumeRandomizerStruct CreationVolume; - W3dVolumeRandomizerStruct VelRandom; - float32 OutwardVel; - float32 VelInherit; - W3dShaderStruct Shader; - uint32 RenderMode; // render as particles or lines? - uint32 FrameMode; // chop the texture into a grid of smaller squares? - uint32 reserved[6]; -}; - -// W3D_CHUNK_EMITTER_PROPS -// Contains a W3dEmitterPropertyStruct followed by a number of color keyframes, -// opacity keyframes, and size keyframes - -struct W3dEmitterPropertyStruct -{ - uint32 ColorKeyframes; - uint32 OpacityKeyframes; - uint32 SizeKeyframes; - W3dRGBAStruct ColorRandom; - float32 OpacityRandom; - float32 SizeRandom; - uint32 reserved[4]; -}; - - -struct W3dEmitterColorKeyframeStruct -{ - float32 Time; - W3dRGBAStruct Color; -}; - -struct W3dEmitterOpacityKeyframeStruct -{ - float32 Time; - float32 Opacity; -}; - -struct W3dEmitterSizeKeyframeStruct -{ - float32 Time; - float32 Size; -}; - -// W3D_CHUNK_EMITTER_ROTATION_KEYFRAMES -// Contains a W3dEmitterRotationHeaderStruct followed by a number of -// rotational velocity keyframes. -struct W3dEmitterRotationHeaderStruct -{ - uint32 KeyframeCount; - float32 Random; // random initial rotational velocity (rotations/sec) - float32 OrientationRandom; // random initial orientation (rotations, 1.0=360deg) - uint32 Reserved[1]; -}; - -struct W3dEmitterRotationKeyframeStruct -{ - float32 Time; - float32 Rotation; // rotational velocity in rotations/sec -}; - -// W3D_CHUNK_EMITTER_FRAME_KEYFRAMES -// Contains a W3dEmitterFrameHeaderStruct followed by a number of -// frame keyframes (sub-texture indexing) -struct W3dEmitterFrameHeaderStruct -{ - uint32 KeyframeCount; - float32 Random; - uint32 Reserved[2]; -}; - -struct W3dEmitterFrameKeyframeStruct -{ - float32 Time; - float32 Frame; -}; - - -// W3D_CHUNK_EMITTER_LINE_PROPERTIES -// Contains a W3dEmitterLinePropertiesStruct. -// Emiter Line Flags (used in the Flags field of W3dEmitterLinePropertiesStruct): -#define W3D_ELINE_MERGE_INTERSECTIONS 0x00000001 // Merge intersections -#define W3D_ELINE_FREEZE_RANDOM 0x00000002 // Freeze random (note: offsets are in camera space) -#define W3D_ELINE_DISABLE_SORTING 0x00000004 // Disable sorting (even if shader has alpha-blending) -#define W3D_ELINE_END_CAPS 0x00000008 // Draw end caps on the line -#define W3D_ELINE_TEXTURE_MAP_MODE_MASK 0xFF000000 // Must cover all possible TextureMapMode values - -#define W3D_ELINE_TEXTURE_MAP_MODE_OFFSET 24 // By how many bits do I need to shift the texture mapping mode? -#define W3D_ELINE_UNIFORM_WIDTH_TEXTURE_MAP 0x00000000 // Entire line uses one row of texture (constant V) -#define W3D_ELINE_UNIFORM_LENGTH_TEXTURE_MAP 0x00000001 // Entire line uses one row of texture stretched length-wise -#define W3D_ELINE_TILED_TEXTURE_MAP 0x00000002 // Tiled continuously over line - -#define W3D_ELINE_DEFAULT_BITS (W3D_ELINE_MERGE_INTERSECTIONS | (W3D_ELINE_UNIFORM_WIDTH_TEXTURE_MAP << W3D_ELINE_TEXTURE_MAP_MODE_OFFSET)) - - -struct W3dEmitterLinePropertiesStruct -{ - uint32 Flags; - uint32 SubdivisionLevel; - float32 NoiseAmplitude; - float32 MergeAbortFactor; - float32 TextureTileFactor; - float32 UPerSec; - float32 VPerSec; - uint32 Reserved[9]; -}; - - -/******************************************************************************** - - Aggregate objects - - The following structs are used to define aggregates in the w3d file. An - 'aggregate' is simply a 'shell' that contains references to a hierarchy - model and subobjects to attach to its bones. - -********************************************************************************/ - -#define W3D_CURRENT_AGGREGATE_VERSION 0x00010003 -const int MESH_PATH_ENTRIES = 15; -const int MESH_PATH_ENTRY_LEN = (W3D_NAME_LEN * 2); - -struct W3dAggregateHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; -}; - -struct W3dAggregateInfoStruct -{ - char BaseModelName[W3D_NAME_LEN*2]; - uint32 SubobjectCount; -}; - -struct W3dAggregateSubobjectStruct -{ - char SubobjectName[W3D_NAME_LEN*2]; - char BoneName[W3D_NAME_LEN*2]; -}; - -// -// Structures for version 1.1 and newer -// -struct W3dTextureReplacerHeaderStruct -{ - uint32 ReplacedTexturesCount; -}; - -struct W3dTextureReplacerStruct -{ - char MeshPath[MESH_PATH_ENTRIES][MESH_PATH_ENTRY_LEN]; - char BonePath[MESH_PATH_ENTRIES][MESH_PATH_ENTRY_LEN]; - char OldTextureName[260]; - char NewTextureName[260]; - W3dTextureInfoStruct TextureParams; -}; - -// -// Flags used in the W3dAggregateMiscInfo structure -// -const int W3D_AGGREGATE_FORCE_SUB_OBJ_LOD = 0x00000001; - -// -// Structures for version 1.2 and newer -// -struct W3dAggregateMiscInfo -{ - uint32 OriginalClassID; - uint32 Flags; - uint32 reserved[3]; -}; - - -/******************************************************************************** - - HLod (Hierarchical LOD Model) - - This is a hierarchical model which has multiple arrays of models which can - be switched for LOD purposes. - - Relevant Chunks: - ---------------- - W3D_CHUNK_HLOD =0x00000700, // description of an HLod object (see HLodClass) - W3D_CHUNK_HLOD_HEADER, // general information such as name and version - W3D_CHUNK_HLOD_LOD_ARRAY, // wrapper around the array of objects for each level of detail - W3D_CHUNK_HLOD_SUB_OBJECT_ARRAY_HEADER, // info on the objects in this level of detail array - W3D_CHUNK_HLOD_SUB_OBJECT, // an object in this level of detail array - W3D_CHUNK_HLOD_AGGREGATE_ARRAY, // array of aggregates, contains W3D_CHUNK_SUB_OBJECT_ARRAY_HEADER and W3D_CHUNK_SUB_OBJECT_ARRAY - W3D_CHUNK_HLOD_PROXY_ARRAY, // array of proxies, used for application-defined purposes - - An HLOD is the basic hierarchical model format used by W3D. It references - an HTree for its hierarchical structure and animation data and several arrays - of sub-objects; one for each LOD in the model. In addition, it can contain - an array of "aggregates" which are references to external W3D objects to - be automatically attached into it. And it can have a list of "proxy" objects - which can be used for application purposes such as instantiating game objects - at the specified transform. - -********************************************************************************/ - -#define W3D_CURRENT_HLOD_VERSION W3D_MAKE_VERSION(1,0) -#define NO_MAX_SCREEN_SIZE WWMATH_FLOAT_MAX - -struct W3dHLodHeaderStruct -{ - uint32 Version; - uint32 LodCount; - char Name[W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; // name of the hierarchy tree to use (\0 if none) -}; - -struct W3dHLodArrayHeaderStruct -{ - uint32 ModelCount; - float32 MaxScreenSize; // if model is bigger than this, switch to higher lod. -}; - -struct W3dHLodSubObjectStruct -{ - uint32 BoneIndex; - char Name[W3D_NAME_LEN*2]; -}; - - -/******************************************************************************** - - Collision Boxes - - Collision boxes are meant to be used for, you guessed it, collision detection. - For this reason, they only contain a minimal amount of rendering information - (a color). - - Axis Aligned - This is a bounding box which is *always* aligned with the world - coordinate system. So, the center point is to be transformed by whatever - transformation matrix is being used but the extents always point down the - world space x,y, and z axes. (in effect, you are translating the center). - - Oriented - This is an oriented 3D box. It is aligned with the coordinate system - it is in. So its extents always point along the local coordinate system axes. - -********************************************************************************/ -#define W3D_BOX_CURRENT_VERSION W3D_MAKE_VERSION(1,0) - -#define W3D_BOX_ATTRIBUTE_ORIENTED 0x00000001 -#define W3D_BOX_ATTRIBUTE_ALIGNED 0x00000002 -#define W3D_BOX_ATTRIBUTE_COLLISION_TYPE_MASK 0x00000FF0 // mask for the collision type bits -#define W3D_BOX_ATTRIBUTE_COLLISION_TYPE_SHIFT 4 // shifting to get to the collision type bits -#define W3D_BOX_ATTRIBTUE_COLLISION_TYPE_PHYSICAL 0x00000010 // physical collisions -#define W3D_BOX_ATTRIBTUE_COLLISION_TYPE_PROJECTILE 0x00000020 // projectiles (rays) collide with this -#define W3D_BOX_ATTRIBTUE_COLLISION_TYPE_VIS 0x00000040 // vis rays collide with this mesh -#define W3D_BOX_ATTRIBTUE_COLLISION_TYPE_CAMERA 0x00000080 // cameras collide with this mesh -#define W3D_BOX_ATTRIBTUE_COLLISION_TYPE_VEHICLE 0x00000100 // vehicles collide with this mesh - -struct W3dBoxStruct -{ - uint32 Version; // file format version - uint32 Attributes; // box attributes (above #define's) - char Name[2*W3D_NAME_LEN]; // name is in the form . - W3dRGBStruct Color; // color to use when drawing the box - W3dVectorStruct Center; // center of the box - W3dVectorStruct Extent; // extent of the box -}; - - - - -/******************************************************************************** - - NULL Objects - - Null objects are used by the LOD system to make meshes dissappear at lower - levels of detail. - -********************************************************************************/ -#define W3D_NULL_OBJECT_CURRENT_VERSION W3D_MAKE_VERSION(1,0) - -struct W3dNullObjectStruct -{ - uint32 Version; // file format version - uint32 Attributes; // object attributes (currently un-used) - uint32 pad[2]; // pad space - char Name[2*W3D_NAME_LEN]; // name is in the form . -}; - - -/******************************************************************************** - - Dazzle Objects - - The only data needed to instantiate a dazzle object is the type-name of - the dazzle to use. The dazzle is always assumed to be at the pivot point - of the bone it is attached to (you should enable Export_Transform) for - dazzles. If the dazzle-type (from dazzle.ini) is directional, then the - coordinate-system of the bone will define the direction. - -********************************************************************************/ - - - -/******************************************************************************** - - Sound render objects - - The following structs are used to define sound render object in the w3d file. - - These objects are used to trigger a sound effect in the world. When the object - is shown, its associated sound is added to the world and played, when the object - is hidden, the associated sound is stopped and removed from the world. - - -********************************************************************************/ - -#define W3D_CURRENT_SOUNDROBJ_VERSION 0x00010000 - -// -// Note: This structure is follwed directly by a chunk (W3D_CHUNK_SOUNDROBJ_DEFINITION) -// that contains an embedded AudibleSoundDefinitionClass's storage. See audibledound.h -// for details. -// -struct W3dSoundRObjHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; - uint32 Flags; - uint32 Padding[8]; -}; - - -/* -** Include the obsolete structures and chunk ID's -*/ -#include "w3d_obsolete.h" - - -#endif // W3D_FILE_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3d_obsolete.h b/Generals/Code/Tools/WW3D/max2w3d/w3d_obsolete.h deleted file mode 100644 index d420ec2979..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3d_obsolete.h +++ /dev/null @@ -1,333 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3d_obsolete.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 9/22/00 10:40a $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3D_OBSOLETE_H -#define W3D_OBSOLETE_H - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Obsolete chunk id's -// At one point in time I was using the 'O' prefix to mean obsolete. Now we just move stuff -// into this file... -///////////////////////////////////////////////////////////////////////////////////////////// -enum -{ - W3D_CHUNK_MESH_HEADER =0x00000001, // header for a mesh - W3D_CHUNK_SURRENDER_NORMALS =0x00000004, // array of surrender normals (one per vertex as req. by surrender) - W3D_CHUNK_TEXCOORDS =0x00000005, // array of texture coordinates - O_W3D_CHUNK_MATERIALS =0x00000006, // array of materials - O_W3D_CHUNK_TRIANGLES =0x00000007, // array of triangles - O_W3D_CHUNK_QUADRANGLES =0x00000008, // array of quads - O_W3D_CHUNK_SURRENDER_TRIANGLES =0x00000009, // array of surrender format tris - O_W3D_CHUNK_POV_TRIANGLES =0x0000000A, // POV format triangles - O_W3D_CHUNK_POV_QUADRANGLES =0x0000000B, // POV format quads - W3D_CHUNK_VERTEX_COLORS =0x0000000D, // Pre-set vertex coloring - W3D_CHUNK_DAMAGE =0x0000000F, // Mesh damage, new set of materials, vertex positions, vertex colors - W3D_CHUNK_DAMAGE_HEADER =0x00000010, // Header for the damage data, tells what is coming - W3D_CHUNK_DAMAGE_VERTICES =0x00000011, // Array of modified vertices (W3dMeshDamageVertexStruct's) - W3D_CHUNK_DAMAGE_COLORS =0x00000012, // Array of modified vert colors (W3dMeshDamageColorStruct's) - W3D_CHUNK_DAMAGE_MATERIALS =0x00000013, - - O_W3D_CHUNK_MATERIALS2 =0x00000014, // array of version 2 materials (with animation frame counts) - - W3D_CHUNK_MATERIALS3 =0x00000015, // array of version 3 materials (all new surrender features supported) - W3D_CHUNK_MATERIAL3 =0x00000016, // Each version 3 material wrapped with this chunk ID - W3D_CHUNK_MATERIAL3_NAME =0x00000017, // Name of the material (array of chars, null terminated) - W3D_CHUNK_MATERIAL3_INFO =0x00000018, // contains a W3dMaterial3Struct, general material info - W3D_CHUNK_MATERIAL3_DC_MAP =0x00000019, // wraps the following two chunks, diffuse color texture - W3D_CHUNK_MAP3_FILENAME =0x0000001A, // filename of the texture - W3D_CHUNK_MAP3_INFO =0x0000001B, // a W3dMap3Struct - W3D_CHUNK_MATERIAL3_DI_MAP =0x0000001C, // diffuse illimination map, same format as other maps - W3D_CHUNK_MATERIAL3_SC_MAP =0x0000001D, // specular color map, same format as other maps - W3D_CHUNK_MATERIAL3_SI_MAP =0x0000001E, // specular illumination map, same format as other maps - W3D_CHUNK_PER_TRI_MATERIALS =0x00000021, // Multi-Mtl meshes - An array of uint16 material id's -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 1.0 Material, array of these are found inside the W3D_CHUNK_MATERIALS chunk. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterialStruct -{ - char MaterialName[W3D_NAME_LEN]; // name of the material (NULL terminated) - char PrimaryName[W3D_NAME_LEN]; // primary texture name (NULL terminated) - char SecondaryName[W3D_NAME_LEN]; // secondary texture name (NULL terminated) - uint32 RenderFlags; // Rendering flags - uint8 Red; // Rgb colors - uint8 Green; - uint8 Blue; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 2.0 Material, array of these are found inside the W3D_CHUNK_MATERIALS2 chunk. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterial2Struct -{ - char MaterialName[W3D_NAME_LEN]; // name of the material (NULL terminated) - char PrimaryName[W3D_NAME_LEN]; // primary texture name (NULL terminated) - char SecondaryName[W3D_NAME_LEN]; // secondary texture name (NULL terminated) - uint32 RenderFlags; // Rendering flags - uint8 Red; // Rgb colors - uint8 Green; - uint8 Blue; - uint8 Alpha; - - uint16 PrimaryNumFrames; // number of animated frames (if 1, not animated) - uint16 SecondaryNumFrames; // number of animated frames (if 1, not animated) - - char Pad[12]; // expansion room -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// MATERIAL ATTRIBUTES (version 3.0 onward) -///////////////////////////////////////////////////////////////////////////////////////////// -// Use alpha enables alpha channels, etc, Use sorting causes display lists using -// this material to be sorted (even with z-buf, translucent materials need to be sorted) -#define W3DMATERIAL_USE_ALPHA 0x00000001 -#define W3DMATERIAL_USE_SORTING 0x00000002 - -// Hints for render devices that cannot support all features -#define W3DMATERIAL_HINT_DIT_OVER_DCT 0x00000010 -#define W3DMATERIAL_HINT_SIT_OVER_SCT 0x00000020 -#define W3DMATERIAL_HINT_DIT_OVER_DIG 0x00000040 -#define W3DMATERIAL_HINT_SIT_OVER_SIG 0x00000080 -#define W3DMATERIAL_HINT_FAST_SPECULAR_AFTER_ALPHA 0x00000100 - -// Last byte is for PSX: Translucency type and a lighting disable flag. -#define W3DMATERIAL_PSX_MASK 0xFF000000 -#define W3DMATERIAL_PSX_TRANS_MASK 0x07000000 -#define W3DMATERIAL_PSX_TRANS_NONE 0x00000000 -#define W3DMATERIAL_PSX_TRANS_100 0x01000000 -#define W3DMATERIAL_PSX_TRANS_50 0x02000000 -#define W3DMATERIAL_PSX_TRANS_25 0x03000000 -#define W3DMATERIAL_PSX_TRANS_MINUS_100 0x04000000 -#define W3DMATERIAL_PSX_NO_RT_LIGHTING 0x08000000 - -///////////////////////////////////////////////////////////////////////////////////////////// -// MAPPING TYPES (version 3.0 onward) -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3DMAPPING_UV 0 -#define W3DMAPPING_ENVIRONMENT 1 - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 3.0 Material, A W3D_CHUNK_MATERIALS3 chunk will wrap a bunch of -// W3D_CHUNK_MATERIAL3 chunks. Inside each chunk will be a name chunk, an 'info' chunk which -// contains the following struct, and one or more map chunks. a mesh with 2 materials might -// look like: -// -// W3D_CHUNK_MATERIALS3 <-- simply a wrapper around the array of mtls -// W3D_CHUNK_MATERIAL3 <-- a wrapper around each material -// W3D_CHUNK_STRING <-- name of the material -// W3D_CHUNK_MATERIAL3_INFO <-- standard material properties, a W3dMaterial3Struct -// W3D_CHUNK_MATERIAL3_DC_MAP <-- a map, W3dMap3Struct -// W3D_CHUNK_STRING <-- filename of the map -// W3D_CHUNK_MAP_INFO <-- map parameters -// W3D_CHUNK_MATERIAL3_SC_MAP -// W3D_CHUNK_STRING <-- filename of the map -// W3D_CHUNK_MAP_INFO -// W3D_CHUNK_MATERIAL3 -// W3D_CHUNK_MATERIAL3_NAME -// W3D_CHUNK_MATERIAL3_INFO -// W3D_CHUNK_MATERIAL3_SI_MAP -// -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterial3Struct -{ - uint32 Attributes; // flags,hints,etc. - - W3dRGBStruct DiffuseColor; // diffuse color - W3dRGBStruct SpecularColor; // specular color - - W3dRGBStruct EmissiveCoefficients; // emmissive coefficients, default to 0,0,0 - W3dRGBStruct AmbientCoefficients; // ambient coefficients, default to 1,1,1 - W3dRGBStruct DiffuseCoefficients; // diffuse coeficients, default to 1,1,1 - W3dRGBStruct SpecularCoefficients; // specular coefficients, default to 0,0,0 - - float32 Shininess; // how tight the specular highlight will be, 1 - 1000 (default = 1) - float32 Opacity; // how opaque the material is, 0.0 = invisible, 1.0 = fully opaque (default = 1) - float32 Translucency; // how much light passes through the material. (default = 0) - float32 FogCoeff; // effect of fog (0.0=not fogged, 1.0=fogged) (default = 1) -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A map, only occurs as part of a material, will be preceeded by its name. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMap3Struct -{ - uint16 MappingType; // Mapping type, will be one of the above #defines (e.g. W3DMAPPING_UV) - uint16 FrameCount; // Number of frames (1 if not animated) - float32 FrameRate; // Frame rate, frames per second in floating point -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A triangle, occurs inside the W3D_CHUNK_SURRENDER_TRIANGLES chunk -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dSurrenderTriStruct -{ - uint32 Vindex[3]; // vertex, vert normal, and texture coord indexes (all use same index) - W3dTexCoordStruct TexCoord[3]; // texture coordinates (OBSOLETE!!!) - uint32 MaterialIdx; // material index - W3dVectorStruct Normal; // Face normal - uint32 Attributes; // collision flags, sort method, etc - W3dRGBStruct Gouraud[3]; // Pre-set shading values (OBSOLETE!!!) -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Original (Obsolete) Mesh Header -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMeshHeaderStruct -{ - uint32 Version; // Currently version 0x100 - char MeshName[W3D_NAME_LEN]; // name of the mesh (Null terminated) - uint32 Attributes; - - // - // Counts, these can be regarded as an inventory of what is to come in the file. - // - uint32 NumTris; // number of triangles (OBSOLETE!) - uint32 NumQuads; // number of quads; (OBSOLETE!) - uint32 NumSrTris; // number of triangles - - uint32 NumPovTris; // (NOT USED) - uint32 NumPovQuads; // (NOT USED) - - uint32 NumVertices; // number of unique vertices - uint32 NumNormals; // number of unique normals (OBSOLETE!) - uint32 NumSrNormals; // number of surrender normals (MUST EQUAL NumVertices or 0) - - uint32 NumTexCoords; // number of unique texture coords (MUST EQUAL NumVertices or 0) - uint32 NumMaterials; // number of unique materials needed - - uint32 NumVertColors; // number of vertex colors (MUST EQUAL NumVertices or 0) - uint32 NumVertInfluences;// vertex influences(MUST EQUAL NumVertices or 0) - uint32 NumDamageStages; // number of damage offset chunks - uint32 FutureCounts[5]; // reserve space for future counts (set to zero). - - // - // LOD controls - // - float32 LODMin; // min LOD distance - float32 LODMax; // max LOD distance - - // - // Collision / rendering quick-rejection - // - W3dVectorStruct Min; // Min corner of the bounding box - W3dVectorStruct Max; // Max corner of the bounding box - W3dVectorStruct SphCenter; // Center of bounding sphere - float32 SphRadius; // Bounding sphere radius - - // - // Default transformation - // - W3dVectorStruct Translation; - float32 Rotation[9]; - - // - // Physics Properties - // - W3dVectorStruct MassCenter; // Center of mass in object space - float32 Inertia[9]; // Inertia tensor (relative to MassCenter) - float32 Volume; // volume of the object - - // - // Name of possible hierarchy this mesh should be attached to - // - char HierarchyTreeName[W3D_NAME_LEN]; - char HierarchyModelName[W3D_NAME_LEN]; - uint32 FutureUse[24]; // Reserved for future use -}; - - -// -// Mesh Damage. This can include a new set of materials for the mesh, -// new positions for certain vertices in the mesh, and new vertex -// colors for certain vertices. -// -struct W3dMeshDamageStruct -{ - uint32 NumDamageMaterials; // number of materials to replace - uint32 NumDamageVerts; // number of vertices to replace - uint32 NumDamageColors; // number of vertex colors to replace - uint32 DamageIndex; // what index is this damage chunk assigned to - uint32 FutureUse[4]; -}; - -struct W3dMeshDamageVertexStruct -{ - uint32 VertexIndex; - W3dVectorStruct NewVertex; -}; - -struct W3dMeshDamageColorStruct -{ - uint32 VertexIndex; - W3dRGBStruct NewColor; -}; - - - -// -// W3dHModelAuxDataStruct. HModels had this extra chunk defining the counts of individual -// types of objects to be found in the model and some obsolete distance-based LOD settings. -// As changes were made to the ww3d library, all of this became useles so the chunk was -// "retired". -// -struct W3dHModelAuxDataStruct -{ - uint32 Attributes; - uint32 MeshCount; - uint32 CollisionCount; - uint32 SkinCount; - uint32 ShadowCount; - uint32 NullCount; - uint32 FutureCounts[6]; - - float32 LODMin; - float32 LODMax; - uint32 FutureUse[32]; -}; - - -#endif // W3D_OBSOLETE_H diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dappdata.cpp b/Generals/Code/Tools/WW3D/max2w3d/w3dappdata.cpp deleted file mode 100644 index e590ea8b74..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dappdata.cpp +++ /dev/null @@ -1,756 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dappdata.cpp $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/21/01 9:45a $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Is_Bone -- check if a node is a "bone" * - * Is_Geometry -- Check if an INode is marked for "geometry" export * - * Is_Normal_Mesh -- check if a node is a mesh * - * Is_Camera_Aligned_Mesh -- check if a node is to be a camera aligned mesh * - * Is_Camera_Oriented_Mesh -- check if a node is to be a camera oriented mesh * - * Is_Collision_AABox -- check if a node is a collision box mesh * - * Is_Collision_OBBox -- check if a node is a collision box mesh * - * Is_Skin -- check if a node is a skin * - * Is_Shadow -- check if a node marked to cast shadows * - * Is_Damage -- check if a node is a damage version of a mesh * - * Is_Damage_For_Mesh -- check if a node is a damage version of a particular mesh * - * Is_Physical_Collision -- Is node categorized as "physical collision geometry" * - * Is_Projectile_Collision -- Is node categorized as "projectile collision geometry"? * - * Is_Vis_Collision -- Is node categorized as "vis collision geometry"? * - * Is_Camera_Collision -- Is node categorized as "camera collision geometry"? * - * Is_Hidden -- checks whether the node should be hidden * - * Is_Two_Sided -- Checks whether the node should be two sided * - * Is_ZNormals -- checks if the node should be exported with 0,0,1 vert normals * - * Is_Dazzle -- check if a node is a dazzle object * - * Is_Aggregate -- check if a node is an aggregate object * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "w3dappdata.h" -#include "w3dutil.h" -#include "util.h" -#include "modstack.h" - - -/*********************************************************************************************** -** -** W3DAppData2Struct Implementation -** -***********************************************************************************************/ - -/* -** Current version of the W3dAppData2 structure -** History: -** version 0 - initial implementation. -** version 1 - added camera collision option, initialize to match physical collision settting -** when converting from version 0. -*/ -const int W3DAPPDATA2_CURRENT_VERSION = 1; - - - -W3DAppData2Struct::W3DAppData2Struct(void) : - ExportFlags(0), - GeometryType(0), - GeometryFlags(0), - CollisionFlags(0) -{ - memset(UnUsed,0,sizeof(UnUsed)); - Init_With_Other_Defaults(); -} - -W3DAppData2Struct::W3DAppData2Struct(W3DAppData0Struct & olddata) : - ExportFlags(0), - GeometryType(0), - GeometryFlags(0), - CollisionFlags(0) -{ - memset(UnUsed,0,sizeof(UnUsed)); - Init_From_AppData0(olddata); -} - -void W3DAppData2Struct::Init_With_Mesh_Defaults(void) -{ - ExportFlags = (EXPORT_TRANSFORM|EXPORT_GEOMETRY); - GeometryType = GEO_TYPE_NORMAL_MESH; - GeometryFlags = 0; - CollisionFlags = 0; - memset(UnUsed,0,sizeof(UnUsed)); - - Set_Version(W3DAPPDATA2_CURRENT_VERSION); -} - -void W3DAppData2Struct::Init_With_Other_Defaults(void) -{ - ExportFlags = 0; - GeometryType = 0; - GeometryFlags = 0; - CollisionFlags = 0; - memset(UnUsed,0,sizeof(UnUsed)); - - Set_Version(W3DAPPDATA2_CURRENT_VERSION); -} - -void W3DAppData2Struct::Init_From_AppData0(W3DAppData0Struct & olddata) -{ - Init_With_Other_Defaults(); - - Enable_Export_Transform(olddata.Is_Bone()); - Enable_Export_Geometry(olddata.Is_Geometry()); - - if (olddata.Is_Camera_Aligned_Mesh()) { - Set_Geometry_Type(GEO_TYPE_CAMERA_ALIGNED); - } - if (olddata.Is_Camera_Oriented_Mesh()) { - Set_Geometry_Type(GEO_TYPE_CAMERA_ORIENTED); - } - if (olddata.Is_Collision_AABox()) { - Set_Geometry_Type(GEO_TYPE_AABOX); - } - if (olddata.Is_Collision_OBBox()) { - Set_Geometry_Type(GEO_TYPE_OBBOX); - } - if (olddata.Is_Normal_Mesh()) { - Set_Geometry_Type(GEO_TYPE_NORMAL_MESH); - } - if (olddata.Is_Null()) { - Set_Geometry_Type(GEO_TYPE_NULL); - } - - Enable_Hidden(olddata.Is_Hidden()); - Enable_Two_Sided(olddata.Is_Two_Sided()); - Enable_Shadow(olddata.Is_Shadow()); - Enable_Vertex_Alpha(olddata.Is_Vertex_Alpha()); - Enable_ZNormals(olddata.Is_ZNormals()); - Enable_Physical_Collision(olddata.Is_Physical_Collision()); - Enable_Projectile_Collision(olddata.Is_Projectile_Collision()); - Enable_Vis_Collision(olddata.Is_Vis_Collision()); - Enable_Camera_Collision(olddata.Is_Physical_Collision()); // make camera setting match physical - - Set_Version(W3DAPPDATA2_CURRENT_VERSION); -} - -void W3DAppData2Struct::Update_Version(void) -{ - /* - ** If this is a version 0 struct, We need to initialize the camera collision - ** setting to be equal to the physical collision setting and convert to version 1 - */ - if (Get_Version() == 0) { - Enable_Camera_Collision(Is_Physical_Collision_Enabled()); - Set_Version(1); - } - - /* - ** Add future version conversion code here! - */ -} - -bool W3DAppData2Struct::operator == (const W3DAppData2Struct & that) -{ - /* - ** Export flags have to match - */ - if (ExportFlags != that.ExportFlags) return false; - - /* - ** If geometry is enabled, verify the geometry type and options - */ - if (Is_Geometry()) { - if (Get_Geometry_Type() != that.Get_Geometry_Type()) return false; - if (GeometryFlags != that.GeometryFlags) return false; - if (CollisionFlags != that.CollisionFlags) return false; - } - - return true; -} - -bool W3DAppData2Struct::Geometry_Options_Match(const W3DAppData2Struct & that) -{ - if (Get_Geometry_Type() != that.Get_Geometry_Type()) return false; - if (GeometryFlags != that.GeometryFlags) return false; - if (CollisionFlags != that.CollisionFlags) return false; - return true; -} - - -W3DAppData2Struct * W3DAppData2Struct::Get_App_Data -( - INode * node, - bool create_if_missing -) -{ - /* - ** Try to get our AppData which has the export flags - */ - W3DAppData2Struct * wdata = NULL; - AppDataChunk * appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,W3D_APPDATA_2); - - /* - ** If there wasn't one, look for an AppData0 chunk and convert that. - ** If there was one, get the data from it - */ - if (appdata) { - - wdata = (W3DAppData2Struct *)(appdata->data); - wdata->Update_Version(); - - } else { - - /* - ** Create a new W3DAppData2Struct for this node - */ - wdata = (W3DAppData2Struct *)malloc(sizeof(W3DAppData2Struct)); - - /* - ** If we have the old AppData0 then initialize from it otherwise - ** just initialize to the defaults - */ - AppDataChunk * oldappdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,W3D_APPDATA_0); - if (oldappdata) { - - /* - ** initializing from the old app data 0 chunk; - */ - wdata->Init_From_AppData0(*(W3DAppData0Struct*)(oldappdata->data)); - - /* - ** Destroy the old obsolete App Data 0 chunk - */ - node->RemoveAppDataChunk(W3DUtilityClassID, UTILITY_CLASS_ID, W3D_APPDATA_0); - - } else { - - /* - ** If this object looks like it is going to be a mesh, then default - ** it to have the mesh export flags (export its transform and the - ** triangle mesh). Otherwise use the default of completely ignoring it! - */ - if (Is_Max_Tri_Mesh(node)) { - wdata->Init_With_Mesh_Defaults(); - } else { - wdata->Init_With_Other_Defaults(); - } - - } - node->AddAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,2,sizeof(W3DAppData2Struct),wdata); - appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,2); - assert(appdata); - - } - - return wdata; -} - - -/*********************************************************************************************** -** -** W3DDazzleAppDataStruct Implementation -** -***********************************************************************************************/ -W3DDazzleAppDataStruct::W3DDazzleAppDataStruct(void) -{ - UnUsed[0] = 0; - UnUsed[1] = 0; - UnUsed[2] = 0; - UnUsed[3] = 0; - memset(DazzleType,0,sizeof(DazzleType)); - strcpy(DazzleType,"DEFAULT"); -} - - -W3DDazzleAppDataStruct * W3DDazzleAppDataStruct::Get_App_Data(INode * node,bool create_if_missing) -{ - /* - ** Try to get the existing AppData chunk - */ - W3DDazzleAppDataStruct * dazzledata = NULL; - AppDataChunk * appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,W3D_DAZZLE_APPDATA); - - if (appdata) { - - /* - ** Found it, get the pointer to the dazzle data - */ - dazzledata = (W3DDazzleAppDataStruct *)(appdata->data); - - } else if (create_if_missing) { - - /* - ** Create a new W3DDazzleAppDataStruct for this node - */ - dazzledata = new W3DDazzleAppDataStruct; - node->AddAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,W3D_DAZZLE_APPDATA,sizeof(W3DDazzleAppDataStruct),dazzledata); - - appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,W3D_DAZZLE_APPDATA); - assert(appdata); - } - return dazzledata; -} - - - - - -/*********************************************************************************************** -** -** Utility functions for reading the W3D options that are set for a given INode -** -***********************************************************************************************/ - -static int get_geometry_type(INode * node) -{ - assert(node != NULL); - return W3DAppData2Struct::Get_App_Data(node)->Get_Geometry_Type(); -} - -/*********************************************************************************************** - * Is_Bone -- check if a node is a "bone" * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool Is_Bone(INode * node) -{ - /* - ** regardless of the bits, skins should not have their transform exported. - */ - if (Is_Skin(node)) return false; - if (Is_Origin(node)) return false; - //if (Is_Proxy(*node)) return false; - else return (W3DAppData2Struct::Get_App_Data(node)->Is_Bone()); -} - -/*********************************************************************************************** - * Is_Geometry -- Check if an INode is marked for "geometry" export * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/13/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Geometry(INode * node) -{ - return (W3DAppData2Struct::Get_App_Data(node)->Is_Geometry()); -} - -/*********************************************************************************************** - * Is_Mesh -- check if a node is a mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool Is_Normal_Mesh(INode * node) -{ - if (!Is_Geometry(node)) return false; - if (Is_Skin(node)) return false; - if (Is_Proxy(*node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_NORMAL_MESH); -} - - -/*********************************************************************************************** - * Is_Camera_Aligned_Mesh -- check if a node is to be a camera aligned mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/5/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Camera_Aligned_Mesh(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_CAMERA_ALIGNED); -} - -/*********************************************************************************************** - * Is_Camera_Oriented_Mesh -- check if a node is to be a camera oriented mesh * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 3/2/99 NH : Created. * - *=============================================================================================*/ -bool Is_Camera_Oriented_Mesh(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_CAMERA_ORIENTED); -} - -/*********************************************************************************************** - * Is_Collision_AABox -- check if a node is a collision box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool Is_Collision_AABox(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_AABOX); -} - - -/*********************************************************************************************** - * Is_Collision_OBBox -- check if a node is a collision box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/17/1998 GH : Created. * - *=============================================================================================*/ -bool Is_Collision_OBBox(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_OBBOX); -} - -/*********************************************************************************************** - * Is_Skin -- check if a node is a skin * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool Is_Skin(INode * node) -{ - if (!Is_Geometry(node)) return false; - if (get_geometry_type(node) != W3DAppData2Struct::GEO_TYPE_NORMAL_MESH) return false; - - for (int i = 0; i < node->NumRefs(); i++) { - - ReferenceTarget *refTarg = node->GetReference(i); - - if (refTarg != NULL && refTarg->ClassID() == Class_ID(WSM_DERIVOB_CLASS_ID,0)) { - - IDerivedObject * wsm_der_obj = (IDerivedObject *)refTarg; - //MessageBox(NULL, "WSM found", _T("WSM"), MB_OK); - - for (int j = 0; j < wsm_der_obj->NumModifiers(); j++) { - Modifier * mod = wsm_der_obj->GetModifier(j); - if (mod->ClassID() == SKIN_MOD_CLASS_ID) { - return true; - } - } - } - } - - return false; -} - -/*********************************************************************************************** - * Is_Shadow -- check if a node marked to cast shadows * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool Is_Shadow(INode * node) -{ - if (!Is_Geometry(node)) return false; - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Shadow_Enabled()); -} - -/*********************************************************************************************** - * Is_Null_Object -- check if a node is a null object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/26/1997 GH : Created. * - *=============================================================================================*/ -bool Is_Null_Object(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_NULL); -} - - -/*********************************************************************************************** - * Is_Dazzle -- check if a node is a dazzle object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/5/2000 gth : Created. * - *=============================================================================================*/ -bool Is_Dazzle(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_DAZZLE); -} - - -/*********************************************************************************************** - * Is_Aggregate -- check if a node is an aggregate object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/24/2000 gth : Created. * - *=============================================================================================*/ -bool Is_Aggregate(INode * node) -{ - if (!Is_Geometry(node)) return false; - return (get_geometry_type(node) == W3DAppData2Struct::GEO_TYPE_AGGREGATE); -} - -/*********************************************************************************************** - * Is_Physical_Collision -- Is node categorized as "physical collision geometry" * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/23/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Physical_Collision(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Physical_Collision_Enabled()); -} - - -/*********************************************************************************************** - * Is_Projectile_Collision -- Is node categorized as "projectile collision geometry"? * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/23/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Projectile_Collision(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Projectile_Collision_Enabled()); -} - - -/*********************************************************************************************** - * Is_Projectile_Collision -- Is node categorized as "vis collision geometry"? * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/23/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Vis_Collision(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Vis_Collision_Enabled()); -} - - -/*********************************************************************************************** - * Is_Camera_Collision -- Is node categorized as "camera collision geometry"? * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/4/2000 gth : Created. * - *=============================================================================================*/ -bool Is_Camera_Collision(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Camera_Collision_Enabled()); -} - -/*********************************************************************************************** - * Is_Vehicle_Collision -- Is node categorized as "Vehicle collision geometry"? * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/4/2000 gth : Created. * - *=============================================================================================*/ -bool Is_Vehicle_Collision(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Vehicle_Collision_Enabled()); -} - -/*********************************************************************************************** - * Is_Hidden -- checks whether the node should be hidden * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This has nothing to do with its hidden status inside of max. Things hidden in max are * - * ignored by the exporter. (artist request way back...wierd huh?) * - * * - * HISTORY: * - * 11/18/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Hidden(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Hidden_Enabled()); -} - - -/*********************************************************************************************** - * Is_Two_Sided -- Checks whether the node should be two sided * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/18/98 GTH : Created. * - *=============================================================================================*/ -bool Is_Two_Sided(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Two_Sided_Enabled()); -} - - -/*********************************************************************************************** - * Is_ZNormals -- checks if the node should be exported with 0,0,1 vert normals * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/9/99 GTH : Created. * - *=============================================================================================*/ -bool Is_ZNormals(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_ZNormals_Enabled()); -} - - -bool Is_Vertex_Alpha(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Vertex_Alpha_Enabled()); -} - -bool Is_Shatterable(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_Shatterable_Enabled()); -} - -bool Is_NPatchable(INode * node) -{ - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - return (wdata->Is_NPatchable_Enabled()); -} - - - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dappdata.h b/Generals/Code/Tools/WW3D/max2w3d/w3dappdata.h deleted file mode 100644 index 0fd852893e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dappdata.h +++ /dev/null @@ -1,415 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dappdata.h $* - * * - * Original Author:: Greg Hjelstrom * - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/21/01 9:44a $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef W3DAPPDATA_H -#define W3DAPPDATA_H - -#include - -/* -** The W3DUtilityClass uses several app-data chunks to store user-options for INodes -** in the MAX scene. Below are the IDs for each app-data chunk type: -*/ - -#define W3D_APPDATA_0 0 -#define W3D_APPDATA_1 1 -#define W3D_APPDATA_2 2 -#define W3D_DAZZLE_APPDATA 3 - - -/* -** Classifying INodes for w3d exporting -** -** NOTE: Use these utility functions rather than going straight to the AppData -** structure! -** -** - There are bits stored in AppData for each node -** - These bits indicate wether something should be exported as hierarchy, -** geometry (and if so, what type of geometry: mesh, collision box, bitmap, etc) -** -** When we say something is "Hierarchy" that means its transform should be put -** into any hierarchy tree or motion being created. In some places I used -** the term "Bone" which means the same thing. -** -** When we say something is "Geometry" that means that the object will become -** some sort of render object (normal mesh, bitmap, collision mesh, etc) -** -*/ - -/* -** Either or both of these will return true for a given INode -*/ -bool Is_Bone(INode * node); -bool Is_Geometry(INode * node); - -/* -** Geometry Type: -** One of the following will return true if the given INode is -** to have its geometry exported -*/ -bool Is_Normal_Mesh(INode * node); -bool Is_Camera_Aligned_Mesh(INode * node); -bool Is_Camera_Oriented_Mesh(INode * node); -bool Is_Collision_AABox(INode * node); -bool Is_Collision_OBBox(INode * node); -bool Is_Skin(INode * node); -bool Is_Shadow(INode * node); -bool Is_Null_Object(INode * node); -bool Is_Dazzle(INode * node); -bool Is_Aggregate(INode * node); - -/* -** Collision Bits, any or all of these may return true for a given INode -*/ -bool Is_Physical_Collision(INode * node); -bool Is_Projectile_Collision(INode * node); -bool Is_Vis_Collision(INode * node); -bool Is_Camera_Collision(INode * node); -bool Is_Vehicle_Collision(INode * node); - -/* -** Miscellaneous settings -*/ -bool Is_Hidden(INode * node); -bool Is_Two_Sided(INode * node); -bool Is_ZNormals(INode * node); -bool Is_Vertex_Alpha(INode * node); -bool Is_Shatterable(INode * node); -bool Is_NPatchable(INode * node); - -/* -** Proxy support. If a node has a name which contains a ~ it is considered a -** proxy for an application defined named object. This overrides all other -** settings (in the future, we shouldn't do things this way!) -*/ -inline bool Is_Proxy(INode &node) -{ - return (::strchr (node.GetName (), '~') != NULL); -} - - - -/* -** AJA 9/24/99 -** NOTE: Whenever you add a new W3DAppDataStruct, you must add an accessor function -** to the bottom of this file. Then the WWScript.dlx project must be modified. That -** project implements an extension to the MAXScript language in the form of a function -** called "wwCopyAppData". The implementation of this wwCopyAppData function must be -** aware of the new W3DAppDataStruct. The modification is pretty straightfoward. -** -** The wwCopyAppData extension was added to MAXScript so that the data we define -** below can be preserve when a model is cloned (copy/instance/reference). What -** happens without using wwCopyAppData is that a new INode is created that contains -** a copy/instance/reference to the original mesh/bone in the source model. When -** this new INode is created, it has no app data. When the app data is examined later -** on, it gets the default values! That means all information concerning Export -** Geometry/Transform, mesh type, and damage region is lost. wwCopyAppData allows -** a script to duplicate a model INCLUDING all W3D app data, so that this information -** is preserved. -*/ - - -/* -** The W3DAppData0Struct contains a bitfield. These #defines are -** used to interpret the bits. -** (gth) NOTE: AppData0 is now OBSOLETE!!! Use W3DAppData2Struct now. -*/ -#define EXPORT_TYPE_MASK 0x000F -#define GEOMETRY_TYPE_MASK 0x01F0 -#define COLLISION_TYPE_MASK 0xF000 - -#define EXPORT_BONE_FLAG 0x0001 // export a bone (transform) for this node -#define EXPORT_GEOMETRY_FLAG 0x0002 // export the geometry for this node -#define EXPORT_HIDDEN_FLAG 0x0004 // mesh should be hidden by default -#define EXPORT_TWO_SIDED_FLAG 0x0008 // mesh should be two sided - -#define GEOMETRY_TYPE_CAMERA_ALIGNED 0x0010 // interpret this geometry as a camera-aligned mesh -#define GEOMETRY_TYPE_NORMAL_MESH 0x0020 // this is a normal mesh -#define GEOMETRY_TYPE_OBBOX 0x0030 // this is an oriented box (should have 8 verts, etc) -#define GEOMETRY_TYPE_AABOX 0x0040 // this is an axis aligned box -#define GEOMETRY_TYPE_CAMERA_ORIENTED 0x0050 // interpret this geometry as a camera-oriented mesh -#define GEOMETRY_TYPE_NULL 0x0100 // this is a null (for LOD) - -#define EXPORT_CAST_SHADOW_FLAG 0x0200 // this mesh casts a shadow -#define EXPORT_VERTEX_ALPHA_FLAG 0x0400 // convert vertex colors to alpha -#define EXPORT_ZNORMALS_FLAG 0x0800 // force vertex normals to point along +z - -#define COLLISION_TYPE_PHYSICAL 0x1000 // runtime engine performs physical collision against this mesh -#define COLLISION_TYPE_PROJECTILE 0x2000 // perform projectile collisions against this mesh -#define COLLISION_TYPE_VIS 0x4000 // perform vis group collisions against this mesh - -#define DEFAULT_MESH_EXPORT_FLAGS (EXPORT_BONE_FLAG | EXPORT_GEOMETRY_FLAG | GEOMETRY_TYPE_NORMAL_MESH) -#define DEFAULT_EXPORT_FLAGS 0 - - -/* -** W3D Utility AppData sub-type 0 (OBSOLETE!) -** ---------------------------------------------------- -** The utility provides a right-click menu which allows -** the user to toggle the export flags. -** (gth) NOTE: AppData0 is now OBSOLETE!!! Use W3DAppData2Struct now. -*/ -struct W3DAppData0Struct -{ - W3DAppData0Struct(void) : ExportFlags(DEFAULT_EXPORT_FLAGS) {} - - bool Is_Bone(void) { return (ExportFlags & EXPORT_BONE_FLAG) == EXPORT_BONE_FLAG; } - bool Is_Geometry(void) { return (ExportFlags & EXPORT_GEOMETRY_FLAG) == EXPORT_GEOMETRY_FLAG; } - - bool Is_Normal_Mesh(void) { return (ExportFlags & GEOMETRY_TYPE_MASK) == GEOMETRY_TYPE_NORMAL_MESH; } - bool Is_Camera_Aligned_Mesh(void) { return (ExportFlags & GEOMETRY_TYPE_MASK) == GEOMETRY_TYPE_CAMERA_ALIGNED; } - bool Is_Camera_Oriented_Mesh(void) { return (ExportFlags & GEOMETRY_TYPE_MASK) == GEOMETRY_TYPE_CAMERA_ORIENTED; } - bool Is_Collision_AABox(void) { return (ExportFlags & GEOMETRY_TYPE_MASK) == GEOMETRY_TYPE_AABOX; } - bool Is_Collision_OBBox(void) { return (ExportFlags & GEOMETRY_TYPE_MASK) == GEOMETRY_TYPE_OBBOX; } - bool Is_Null(void) { return (ExportFlags & GEOMETRY_TYPE_MASK) == GEOMETRY_TYPE_NULL; } - - bool Is_Physical_Collision(void) { return (ExportFlags & COLLISION_TYPE_PHYSICAL) == COLLISION_TYPE_PHYSICAL; } - bool Is_Projectile_Collision(void) { return (ExportFlags & COLLISION_TYPE_PROJECTILE) == COLLISION_TYPE_PROJECTILE; } - bool Is_Vis_Collision(void) { return (ExportFlags & COLLISION_TYPE_VIS) == COLLISION_TYPE_VIS; } - - bool Is_Hidden(void) { return (ExportFlags & EXPORT_HIDDEN_FLAG) == EXPORT_HIDDEN_FLAG; } - bool Is_Two_Sided(void) { return (ExportFlags & EXPORT_TWO_SIDED_FLAG) == EXPORT_TWO_SIDED_FLAG; } - bool Is_Vertex_Alpha(void) { return (ExportFlags & EXPORT_VERTEX_ALPHA_FLAG) == EXPORT_VERTEX_ALPHA_FLAG; } - bool Is_ZNormals(void) { return (ExportFlags & EXPORT_ZNORMALS_FLAG) == EXPORT_ZNORMALS_FLAG; } - bool Is_Shadow(void) { return (ExportFlags & EXPORT_CAST_SHADOW_FLAG) == EXPORT_CAST_SHADOW_FLAG; } - - unsigned short ExportFlags; // what was I thinking??? (gth) -}; - - - -/* -** W3D Utility AppData sub-type 1 -** ---------------------------------------------------- -** This AppData contains the damage region number for -** the current object. -*/ - -// Maximum number of damage regions on a model. -#define MAX_DAMAGE_REGIONS ((char)16) -// Value that represents no damage region. -#define NO_DAMAGE_REGION ((char)-1) - -struct W3DAppData1Struct -{ - W3DAppData1Struct(void) : DamageRegion(NO_DAMAGE_REGION) { } - - /* - ** NO_DAMAGE_REGION means the object isn't part of - ** any damage region, 0 through MAX_DAMAGE_REGIONS-1 - ** are valid damage regions. - */ - char DamageRegion; -}; - - - -/* -** W3D Utility AppData sub-type 2 -** ---------------------------------------------------- -** This is an app-data struct that is meant to contain all -** of the w3d export options for an object in MAX. It -** replaces the old AppData sub-type 0. Call the static -** member functions in the class to get a pointer to -** the AppData2 struct hanging off any INode and automatically -** create one for you if there isn't already one... -*/ - -struct W3DAppData2Struct -{ - W3DAppData2Struct(void); - W3DAppData2Struct(W3DAppData0Struct & olddata); - - void Init_With_Mesh_Defaults(void); - void Init_With_Other_Defaults(void); - void Init_From_AppData0(W3DAppData0Struct & olddata); - void Update_Version(void); - - enum GeometryTypeEnum - { - GEO_TYPE_CAMERA_ALIGNED = 0x00000001, // Geometry types are mutually exclusive - GEO_TYPE_NORMAL_MESH = 0x00000002, - GEO_TYPE_OBBOX = 0x00000003, - GEO_TYPE_AABOX = 0x00000004, - GEO_TYPE_CAMERA_ORIENTED = 0x00000005, - GEO_TYPE_NULL = 0x00000006, - GEO_TYPE_DAZZLE = 0x00000007, - GEO_TYPE_AGGREGATE = 0x00000008, - }; - - /* - ** Read Access - */ - bool Is_Bone(void) const { return (ExportFlags & EXPORT_TRANSFORM) == EXPORT_TRANSFORM; } - bool Is_Geometry(void) const { return (ExportFlags & EXPORT_GEOMETRY) == EXPORT_GEOMETRY; } - - int Get_Geometry_Type(void) const { return GeometryType; } - bool Is_Normal_Mesh(void) const { return GeometryType == GEO_TYPE_NORMAL_MESH; } - bool Is_Camera_Aligned_Mesh(void) const { return GeometryType == GEO_TYPE_CAMERA_ALIGNED; } - bool Is_Camera_Oriented_Mesh(void) const { return GeometryType == GEO_TYPE_CAMERA_ORIENTED; } - bool Is_Collision_AABox(void) const { return GeometryType == GEO_TYPE_AABOX; } - bool Is_Collision_OBBox(void) const { return GeometryType == GEO_TYPE_OBBOX; } - bool Is_Null(void) const { return GeometryType == GEO_TYPE_NULL; } - bool Is_Dazzle(void) const { return GeometryType == GEO_TYPE_DAZZLE; } - - bool Is_Hidden_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_HIDDEN) == GEOMETRY_FLAG_HIDDEN; } - bool Is_Two_Sided_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_TWO_SIDED) == GEOMETRY_FLAG_TWO_SIDED; } - bool Is_Vertex_Alpha_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_VERTEX_ALPHA) == GEOMETRY_FLAG_VERTEX_ALPHA; } - bool Is_ZNormals_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_ZNORMALS) == GEOMETRY_FLAG_ZNORMALS; } - bool Is_Shadow_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_CAST_SHADOW) == GEOMETRY_FLAG_CAST_SHADOW; } - bool Is_Shatterable_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_SHATTERABLE) == GEOMETRY_FLAG_SHATTERABLE; } - bool Is_NPatchable_Enabled(void) const { return (GeometryFlags & GEOMETRY_FLAG_NPATCHABLE) == GEOMETRY_FLAG_NPATCHABLE; } - - bool Is_Physical_Collision_Enabled(void) const { return (CollisionFlags & COLLISION_FLAG_PHYSICAL) == COLLISION_FLAG_PHYSICAL; } - bool Is_Projectile_Collision_Enabled(void) const { return (CollisionFlags & COLLISION_FLAG_PROJECTILE) == COLLISION_FLAG_PROJECTILE; } - bool Is_Vis_Collision_Enabled(void) const { return (CollisionFlags & COLLISION_FLAG_VIS) == COLLISION_FLAG_VIS; } - bool Is_Camera_Collision_Enabled(void) const { return (CollisionFlags & COLLISION_FLAG_CAMERA) == COLLISION_FLAG_CAMERA; } - bool Is_Vehicle_Collision_Enabled(void) const { return (CollisionFlags & COLLISION_FLAG_VEHICLE) == COLLISION_FLAG_VEHICLE; } - - /* - ** Write Access - */ - void Enable_Export_Transform(bool onoff) { if (onoff) { ExportFlags |= EXPORT_TRANSFORM; } else { ExportFlags &= ~EXPORT_TRANSFORM; } } - void Enable_Export_Geometry(bool onoff) { if (onoff) { ExportFlags |= EXPORT_GEOMETRY; } else { ExportFlags &= ~EXPORT_GEOMETRY; } } - - void Set_Geometry_Type(GeometryTypeEnum type) { GeometryType = (unsigned int)type; } - - void Enable_Hidden(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_HIDDEN; } else { GeometryFlags &= ~GEOMETRY_FLAG_HIDDEN; } } - void Enable_Two_Sided(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_TWO_SIDED; } else { GeometryFlags &= ~GEOMETRY_FLAG_TWO_SIDED; } } - void Enable_Shadow(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_CAST_SHADOW; } else { GeometryFlags &= ~GEOMETRY_FLAG_CAST_SHADOW; } } - void Enable_Vertex_Alpha(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_VERTEX_ALPHA; } else { GeometryFlags &= ~GEOMETRY_FLAG_VERTEX_ALPHA; } } - void Enable_ZNormals(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_ZNORMALS; } else { GeometryFlags &= ~GEOMETRY_FLAG_ZNORMALS; } } - void Enable_Shatterable(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_SHATTERABLE; } else { GeometryFlags &= ~GEOMETRY_FLAG_SHATTERABLE; } } - void Enable_NPatchable(bool onoff) { if (onoff) { GeometryFlags |= GEOMETRY_FLAG_NPATCHABLE; } else { GeometryFlags &= ~GEOMETRY_FLAG_NPATCHABLE; } } - - void Enable_Physical_Collision(bool onoff) { if (onoff) { CollisionFlags |= COLLISION_FLAG_PHYSICAL; } else { CollisionFlags &= ~COLLISION_FLAG_PHYSICAL; } } - void Enable_Projectile_Collision(bool onoff) { if (onoff) { CollisionFlags |= COLLISION_FLAG_PROJECTILE; } else { CollisionFlags &= ~COLLISION_FLAG_PROJECTILE; } } - void Enable_Vis_Collision(bool onoff) { if (onoff) { CollisionFlags |= COLLISION_FLAG_VIS; } else { CollisionFlags &= ~COLLISION_FLAG_VIS; } } - void Enable_Camera_Collision(bool onoff) { if (onoff) { CollisionFlags |= COLLISION_FLAG_CAMERA; } else { CollisionFlags &= ~COLLISION_FLAG_CAMERA; } } - void Enable_Vehicle_Collision(bool onoff) { if (onoff) { CollisionFlags |= COLLISION_FLAG_VEHICLE; } else { CollisionFlags &= ~COLLISION_FLAG_VEHICLE; } } - - /* - ** Comparison - */ - bool operator == (const W3DAppData2Struct & that); - bool operator != (const W3DAppData2Struct & that) { return !(*this == that); } - bool Geometry_Options_Match(const W3DAppData2Struct & that); - - /* - ** Get the W3DAppData2Struct for a given INode and create one if - ** there isn't already one. - */ - static W3DAppData2Struct * Get_App_Data(INode * node,bool create_if_missing = true); - -protected: - - void Set_Version(int ver) { ExportFlags &= ~VERSION_MASK; ExportFlags |= (ver<>VERSION_SHIFT; } - - enum ExportFlagsEnum - { - EXPORT_TRANSFORM = 0x00000001, // Export flags bit-field - EXPORT_GEOMETRY = 0x00000002, - - VERSION_MASK = 0xFFFF0000, // upper 16bits is version number. - VERSION_SHIFT = 16, - }; - - enum GeometryFlagsEnum - { - GEOMETRY_FLAG_HIDDEN = 0x00000001, // Geometry Flags bitfield - GEOMETRY_FLAG_TWO_SIDED = 0x00000002, - GEOMETRY_FLAG_CAST_SHADOW = 0x00000004, - GEOMETRY_FLAG_VERTEX_ALPHA = 0x00000008, - GEOMETRY_FLAG_ZNORMALS = 0x00000010, - GEOMETRY_FLAG_SHATTERABLE = 0x00000020, - GEOMETRY_FLAG_NPATCHABLE = 0x00000040, - }; - - enum CollisionFlagsEnum - { - COLLISION_FLAG_PHYSICAL = 0x00000001, - COLLISION_FLAG_PROJECTILE = 0x00000002, - COLLISION_FLAG_VIS = 0x00000004, - COLLISION_FLAG_CAMERA = 0x00000008, - COLLISION_FLAG_VEHICLE = 0x00000010, - }; - - unsigned int ExportFlags; - unsigned int GeometryType; - unsigned int GeometryFlags; - unsigned int CollisionFlags; - - // future expansion, initialized to zeros - unsigned int UnUsed[4]; -}; - - - -/* -** W3D Utility Dazzle App Data -** ---------------------------------------------------- -** This app-data struct is used to contain parameters -** specific to dazzle render objects. It currently only -** contains a type name which is limited to 128 characters -** and some padding variables for future use. -*/ - -struct W3DDazzleAppDataStruct -{ - /* - ** Constructor, zeros everything, then initializes DazzleType to "DEFAULT" - */ - W3DDazzleAppDataStruct(void); - - /* - ** Get the W3DAppData2Struct for a given INode and create one if - ** there isn't already one. - */ - static W3DDazzleAppDataStruct * Get_App_Data(INode * node,bool create_if_missing = true); - - /* - ** Members - */ - unsigned int UnUsed[4]; - char DazzleType[128]; -}; - - -#endif - diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3ddesc.cpp b/Generals/Code/Tools/WW3D/max2w3d/w3ddesc.cpp deleted file mode 100644 index 860c8b5856..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3ddesc.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3ddesc.cpp 3 3/04/99 1:58p Naty_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3ddesc.cpp $* - * * - * $Author:: Naty_h $* - * * - * $Modtime:: 3/03/99 11:29a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - - -#include "w3ddesc.h" -#include "w3dexp.h" -#include "dllmain.h" - -/*********************************************************************************************** - * W3dClassDesc::Create -- Creates a W3dExportClass object * - * * - * MAX calls this method when it needs a pointer to a new instance of the plug-in class. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -void * W3dClassDesc::Create(BOOL) -{ - return new W3dExportClass; -} - -/*********************************************************************************************** - * W3dClassDesc::IsPublic -- Controls if the plug-in shows up in lists from the user to choose * - * * - * Controls if the plug-in shows up in lists from the user to choose from. * - * * - * INPUT: none * - * * - * OUTPUT: true! * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -int W3dClassDesc::IsPublic() -{ - return 1; -} - -/*********************************************************************************************** - * W3dClassDesc::ClassName -- returns the name of the class * - * * - * This method returns the name of the class. This name appears in the button for the * - * plug-in in the MAX user interface. * - * * - * INPUT: none * - * * - * OUTPUT: Name of the class * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -const TCHAR * W3dClassDesc::ClassName() -{ - return Get_String(IDS_W3D_SHORT_DESCRIPTION); -} - -/*********************************************************************************************** - * W3dClassDesc::SuperClassID -- returns the SuperClassID of the plug-in. * - * * - * INPUT: none * - * * - * OUTPUT: The SuperClassID of the plug-in. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -SClass_ID W3dClassDesc::SuperClassID() -{ - return SCENE_EXPORT_CLASS_ID; -} - -/*********************************************************************************************** - * W3dClassDesc::ClassID -- Returns the class ID * - * * - * This method must return the unique ID for the object. If two ClassIDs conflict, the * - * system will only load the first one it finds. The ClassID consists of two unsigned 32-bit * - * quantities. * - * * - * INPUT: none * - * * - * OUTPUT: The unique ClassID of the plug-in. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -Class_ID W3dClassDesc::ClassID() -{ - return W3D_EXPORTER_CLASS_ID; -} - -/*********************************************************************************************** - * W3dClassDesc::Category -- returns a string describing the category a plug-in fits into * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -const TCHAR * W3dClassDesc::Category() -{ - return Get_String(IDS_SCENE_EXPORT); -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3ddesc.h b/Generals/Code/Tools/WW3D/max2w3d/w3ddesc.h deleted file mode 100644 index 868cec24ac..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3ddesc.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3ddesc.h 3 3/04/99 1:57p Naty_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3ddesc.h $* - * * - * $Author:: Naty_h $* - * * - * $Modtime:: 3/03/99 11:28a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef W3DDESC_H -#define W3DDESC_H - -#include "always.h" -#include - -/***************************************************************************** -* -* Class descriptors provide the system with information about the plug-in -* classes in the DLL. -* -*****************************************************************************/ -#define W3D_EXPORTER_CLASS_ID Class_ID(0x54d412df, 0x41466ae8) - -class W3dClassDesc : public ClassDesc -{ -public: - void * Create(BOOL); - int IsPublic(); - const TCHAR * ClassName(); - SClass_ID SuperClassID(); - Class_ID ClassID(); - const TCHAR * Category(); -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3ddlg.cpp b/Generals/Code/Tools/WW3D/max2w3d/w3ddlg.cpp deleted file mode 100644 index 16feee0ead..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3ddlg.cpp +++ /dev/null @@ -1,822 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3ddlg.cpp 24 11/07/00 5:40p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3ddlg.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 4:39p $* - * * - * $Revision:: 24 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "w3ddlg.h" -#include "resource.h" -#include "dllmain.h" -#include "w3dexp.h" -#include "util.h" -#include "rawfile.h" -#include -#include "units.h" -#include "presetexportoptionsdialog.h" - - -#define ENABLE_MESH_OPTIMIZING 0 - -/* -** Static functions -*/ -static BOOL CALLBACK _options_dialog_proc(HWND Hwnd,UINT message,WPARAM wParam,LPARAM lParam); -static void _init_ofn(void); - -/* -** Static data -*/ -static bool _OfnInited = false; -static OPENFILENAME _HierarchyFileOFN; - - -/*********************************************************************************************** - * W3dOptionsDialogClass::W3dOptionsDialogClass -- constructor for the options dialog object * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -W3dOptionsDialogClass::W3dOptionsDialogClass(Interface * maxinterface,ExpInterface * exportinterface) -{ - MaxInterface = maxinterface; - ExportInterface = exportinterface; - if (!_OfnInited) _init_ofn(); - GotHierarchyFilename = false; - - RangeLowSpin = NULL; - RangeHighSpin = NULL; - - GetMasterUnitInfo(&UnitsType, &UnitsScale); -} - -W3dOptionsDialogClass::~W3dOptionsDialogClass(void) -{ - ReleaseISpinner(RangeLowSpin); - ReleaseISpinner(RangeHighSpin); -} - -bool W3dOptionsDialogClass::Get_Export_Options(W3dExportOptionsStruct * options) -{ - Options = options; - - // Put up the options dialog box. - /*BOOL result = DialogBoxParam - ( - AppInstance, - MAKEINTRESOURCE (IDD_W3D_EXPORT_OPTIONS), - MaxInterface->GetMAXHWnd(), - (DLGPROC) _options_dialog_proc, - (LPARAM) this - );*/ - - PresetExportOptionsDialogClass dialog (MaxInterface, MaxInterface->GetMAXHWnd ()); - - dialog.Set_Options (Options); - int result = dialog.Do_Modal (); - - if (result == IDOK) { - return true; - } else { - return false; - } -} - - -/*********************************************************************************************** - * W3dOptionsDialogClass::Dialog_Proc -- Handles the windows message for the options dialog * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -bool W3dOptionsDialogClass::Dialog_Proc -( - HWND hwnd, - UINT message, - WPARAM wParam, - LPARAM -) -{ - int code = HIWORD(wParam); - - switch (message ) { - - /******************************************************************* - * WM_INITDIALOG - * - * Initialize all of the custom controls for the dialog box - * - *******************************************************************/ - case WM_INITDIALOG: - - Dialog_Init(); - return 1; - - - /******************************************************************* - * WM_COMMAND - * - * - *******************************************************************/ - case WM_COMMAND: - - switch (LOWORD(wParam)) - { - case IDOK: - - if (Dialog_Ok() == FALSE) { - MessageBox(Hwnd,"You have not supplied a Base Pose hierarchy file!","Error",MB_OK); - return 1; - } - - SetCursor(LoadCursor (NULL, IDC_WAIT)); - EndDialog(Hwnd, 1); - break; - - case IDCANCEL: - EndDialog(Hwnd, 0); - break; - - case IDC_WHT_EXPORT_RADIO: - case IDC_WHT_LOAD_RADIO: - case IDC_WHT_NO_EXPORT_RADIO: - WHT_Export_Radio_Changed(); - break; - - case IDC_WHA_EXPORT_RADIO: - case IDC_WHA_NO_EXPORT_RADIO: - WHA_Export_Radio_Changed(); - break; - - case IDC_WTM_EXPORT_RADIO: - case IDC_WTM_NO_EXPORT_RADIO: - WTM_Export_Radio_Changed(); - break; - - case IDC_COMPRESS_ANIMATION_CHECK: - WHA_Compress_Animation_Check_Changed(); - break; - - case IDC_REDUCE_ANIMATION_CHECK: - WHA_Reduce_Animation_Check_Changed(); - break; - - case IDC_COMPRESS_ANIMATION_FLAVOR_COMBO: - WHA_Compression_Flavor_Changed(); - break; - - case IDC_WHT_BROWSE_BUTTON: - - // use the open file common dialog to get a hierarchy filename. - _HierarchyFileOFN.hwndOwner = Hwnd; - _HierarchyFileOFN.lpstrFileTitle = NULL; - _HierarchyFileOFN.lpstrFile = Options->HierarchyFilename; - - if (GetOpenFileName(&_HierarchyFileOFN)) { - - // Get the relative path between the current export path - // and the full file path to the hierarchy file: - Create_Relative_Path(Options->RelativeHierarchyFilename, - W3dExportClass::CurrentExportPath, - _HierarchyFileOFN.lpstrFile); - - // set window text to the relative path. - HWND butHwnd = GetDlgItem(hwnd,IDC_WHT_BROWSE_BUTTON); - if (Options->RelativeHierarchyFilename[0] != 0) { - SetWindowText(butHwnd, Options->RelativeHierarchyFilename); - } else { - SetWindowText(butHwnd, Options->HierarchyFilename); - } - GotHierarchyFilename = true; - - SetSaveRequiredFlag(true); - } - - _HierarchyFileOFN.lpstrFile = NULL; - break; - } - return 1; - - /******************************************************************* - * CC_SPINNER_CHANGE - * - * Max custom spinner controls - * - *******************************************************************/ - case CC_SPINNER_CHANGE: - - switch (LOWORD(wParam)) - { - case IDC_RANGE_LOW_SPIN: - if (RangeLowSpin->GetIVal() > RangeHighSpin->GetIVal()) - { - RangeHighSpin->SetValue (RangeLowSpin->GetIVal(),FALSE); - } - break; - - case IDC_RANGE_HIGH_SPIN: - if (RangeHighSpin->GetIVal() < RangeLowSpin->GetIVal()) - { - RangeLowSpin->SetValue(RangeHighSpin->GetIVal(),FALSE); - } - break; - - } - - } - return 0; -} - -void W3dOptionsDialogClass::Dialog_Init() -{ - CenterWindow(Hwnd, GetParent(Hwnd)); - SetCursor(LoadCursor (NULL, IDC_ARROW)); - - // initialize the export radio buttons - if (Options->ExportHierarchy) { - CheckDlgButton(Hwnd,IDC_WHT_EXPORT_RADIO,BST_CHECKED); - Enable_WHT_Export(); - } else { - if (Options->LoadHierarchy) { - CheckDlgButton(Hwnd,IDC_WHT_LOAD_RADIO,BST_CHECKED); - Enable_WHT_Load(); - - // If the relative path is a full path, just erase both paths - // This case happens with files which were exported using a previous, - // bugged version of the exporter which did not handle files on - // different drives correctly. - if (Is_Full_Path(Options->RelativeHierarchyFilename)) { - Options->RelativeHierarchyFilename[0] = 0; - Options->HierarchyFilename[0] = 0; - } - - // Honor the relative path if it is present - if (Options->RelativeHierarchyFilename[0] != 0) - { - - HWND butHwnd = GetDlgItem(Hwnd,IDC_WHT_BROWSE_BUTTON); - SetWindowText(butHwnd, Options->RelativeHierarchyFilename); - Create_Full_Path(Options->HierarchyFilename, - W3dExportClass::CurrentExportPath, - Options->RelativeHierarchyFilename); - GotHierarchyFilename = true; - - } else if (Options->HierarchyFilename[0] != 0) { - - HWND butHwnd = GetDlgItem(Hwnd,IDC_WHT_BROWSE_BUTTON); - SetWindowText(butHwnd, Options->HierarchyFilename); - GotHierarchyFilename = true; - - } - - } else { - CheckDlgButton(Hwnd,IDC_WHT_NO_EXPORT_RADIO,BST_CHECKED); - Disable_WHT_Export(); - } - } - - if (Options->ExportGeometry) { - CheckDlgButton(Hwnd,IDC_WTM_EXPORT_RADIO,BST_CHECKED); - Enable_WTM_Export(); - } else { - CheckDlgButton(Hwnd,IDC_WTM_NO_EXPORT_RADIO,BST_CHECKED); - Disable_WTM_Export(); - } - - if (Options->SmoothBetweenMeshes && Options->ExportGeometry) { - CheckDlgButton(Hwnd,IDC_EXPORT_MESH_SMOOTH_CHECK,BST_CHECKED); - } else { - CheckDlgButton(Hwnd,IDC_EXPORT_MESH_SMOOTH_CHECK,BST_UNCHECKED); - } - - SetCheckBox(Hwnd, IDC_TRANSLATION_ONLY_CHECK, Options->TranslationOnly); - SetCheckBox(Hwnd, IDC_TERRAIN_MODE_CHECK, Options->EnableTerrainMode); - - // Initialize additional Animation Options - - SetCheckBox(Hwnd, IDC_COMPRESS_ANIMATION_CHECK, Options->CompressAnimation); - SetCheckBox(Hwnd, IDC_REDUCE_ANIMATION_CHECK , Options->ReduceAnimation); - SetCheckBox(Hwnd, IDC_VIEWLOG_CHECK, Options->ReviewLog); - - char string[128]; // temp string buffer - - sprintf(string, "Current FPS: %d", GetFrameRate()); - - SetDlgItemText(Hwnd, IDC_ANIMATION_FPS_STATIC, string); - - - // initialize animation combo/list boxes - - HwndReduce = GetDlgItem(Hwnd, IDC_REDUCE_ANIMATION_COMBO); - HwndFlavor = GetDlgItem(Hwnd, IDC_COMPRESS_ANIMATION_FLAVOR_COMBO); - - ComboBox_ResetContent(HwndReduce); - ComboBox_ResetContent(HwndFlavor); - - for (int i=1; i<100; i++) { - sprintf(string, "%d", i); - ComboBox_AddString(HwndReduce, string); - } - - ComboBox_AddString(HwndFlavor, "TimeCoded"); - ComboBox_AddString(HwndFlavor, "Adaptive Delta"); - - - if ((Options->ReduceAnimationPercent < 1) || (Options->ReduceAnimationPercent > 99)) { - Options->ReduceAnimationPercent = 50; - - } - - if ((Options->CompressAnimationFlavor < 0) || (Options->CompressAnimationFlavor >= ANIM_FLAVOR_VALID)) { - Options->CompressAnimationFlavor = 0; - } - - ComboBox_SetCurSel(HwndReduce, Options->ReduceAnimationPercent-1); - ComboBox_SetCurSel(HwndFlavor, Options->CompressAnimationFlavor); - - - HwndTError = GetDlgItem(Hwnd, IDC_MAX_TRANS_ERROR_EDIT); - HwndRError = GetDlgItem(Hwnd, IDC_MAX_ROT_ERROR_EDIT); - - sprintf(string, "%f", Options->CompressAnimationTranslationError); - Edit_SetText(HwndTError, string); - - sprintf(string, "%f", Options->CompressAnimationRotationError); - Edit_SetText(HwndRError, string); - - - // Make sure everything under animations is properly active/inactive - - WHA_Compress_Animation_Check_Changed(); - - if (Options->ExportAnimation) { - CheckDlgButton(Hwnd,IDC_WHA_EXPORT_RADIO,BST_CHECKED); - Enable_WHA_Export(); - } else { - CheckDlgButton(Hwnd,IDC_WHA_NO_EXPORT_RADIO,BST_CHECKED); - Disable_WHA_Export(); - } - - - // initialize the frame-range spinners - int ticksperframe = GetTicksPerFrame(); - int startframe = MaxInterface->GetAnimRange().Start() / ticksperframe; - int endframe = MaxInterface->GetAnimRange().End() / ticksperframe; - - RangeLowSpin = SetupIntSpinner - ( - Hwnd, - IDC_RANGE_LOW_SPIN, - IDC_RANGE_LOW_EDIT, - startframe, - endframe, - Options->StartFrame - ); - - RangeHighSpin = SetupIntSpinner - ( - Hwnd, - IDC_RANGE_HIGH_SPIN, - IDC_RANGE_HIGH_EDIT, - startframe, - endframe, - Options->EndFrame - ); - - // initialize the 'DisableExportAABTrees' option - CheckDlgButton(Hwnd,IDC_EXPORT_MESH_AABTREES,!Options->DisableExportAABTrees); - - CheckDlgButton(Hwnd,IDC_EXPORT_MESH_MAT_TO_TEXTURE,Options->EnableMaterialColorToTextureConversion); - -#if ENABLE_MESH_OPTIMIZING - CheckDlgButton(Hwnd,IDC_EXPORT_MESH_OPTIMIZE,Options->EnableOptimizeMeshData); -#endif -} - -BOOL W3dOptionsDialogClass::Dialog_Ok() -{ - bool changed = false; - - // export options: - bool export_h = (IsDlgButtonChecked(Hwnd,IDC_WHT_EXPORT_RADIO) == BST_CHECKED); - changed = changed || (Options->ExportHierarchy != export_h); - Options->ExportHierarchy = export_h; - - bool load_h = (IsDlgButtonChecked(Hwnd,IDC_WHT_LOAD_RADIO) == BST_CHECKED); - changed = changed || (Options->LoadHierarchy != load_h); - Options->LoadHierarchy = load_h; - - bool export_a = (IsDlgButtonChecked(Hwnd,IDC_WHA_EXPORT_RADIO) == BST_CHECKED); - changed = changed || (Options->ExportAnimation != export_a); - Options->ExportAnimation = export_a; - - bool export_g = (IsDlgButtonChecked(Hwnd,IDC_WTM_EXPORT_RADIO) == BST_CHECKED); - changed = changed || (Options->ExportGeometry != export_g); - Options->ExportGeometry = export_g; - - if (export_g) { - bool smooth_meshes = (IsDlgButtonChecked(Hwnd,IDC_EXPORT_MESH_SMOOTH_CHECK) == BST_CHECKED); - changed = changed || (Options->SmoothBetweenMeshes != smooth_meshes); - Options->SmoothBetweenMeshes = smooth_meshes; - - bool disable_export_aabs = (IsDlgButtonChecked(Hwnd,IDC_EXPORT_MESH_AABTREES) != BST_CHECKED); - changed = changed || (Options->DisableExportAABTrees != disable_export_aabs); - Options->DisableExportAABTrees = disable_export_aabs; - - bool convert_materials = (IsDlgButtonChecked(Hwnd,IDC_EXPORT_MESH_MAT_TO_TEXTURE) == BST_CHECKED); - changed = changed || (Options->EnableMaterialColorToTextureConversion != convert_materials); - Options->EnableMaterialColorToTextureConversion = convert_materials; - -#if ENABLE_MESH_OPTIMIZING - bool optimize_mesh_data = (IsDlgButtonChecked(Hwnd,IDC_EXPORT_MESH_OPTIMIZE) == BST_CHECKED); - changed = changed || (Options->EnableOptimizeMeshData != optimize_mesh_data); - Options->EnableOptimizeMeshData = optimize_mesh_data; -#else - Options->EnableOptimizeMeshData = false; -#endif - - } else { - Options->SmoothBetweenMeshes = false; - Options->DisableExportAABTrees = false; - Options->EnableOptimizeMeshData = false; - Options->EnableMaterialColorToTextureConversion = false; - } - - // Hierarchy Options: - bool xlation_only = (IsDlgButtonChecked(Hwnd,IDC_TRANSLATION_ONLY_CHECK) == BST_CHECKED); - changed = changed || (Options->TranslationOnly != xlation_only); - Options->TranslationOnly = xlation_only; - - bool terrain_mode = (IsDlgButtonChecked(Hwnd,IDC_TERRAIN_MODE_CHECK) == BST_CHECKED); - changed = changed || (Options->EnableTerrainMode != terrain_mode); - Options->EnableTerrainMode = terrain_mode; - - if (Options->LoadHierarchy && (Options->ExportAnimation || Options->ExportGeometry)) { - if (!GotHierarchyFilename) { - MessageBox(Hwnd,"You have not supplied a Base Pose hierarchy file!","Error",MB_OK); - if (changed) SetSaveRequiredFlag(true); - return FALSE; - } - - RawFileClass file(Options->HierarchyFilename); - if (!file.Open()) { - char buf[100+_MAX_FNAME+_MAX_EXT]; - sprintf(buf,"Unable to load hierarchy file: %s\nIf this Max file has been moved, please re-select the hierarchy file.",Options->HierarchyFilename); - MessageBox(Hwnd,buf,"Error",MB_OK); - return FALSE; - } - file.Close(); - } - - // Animation options: - int start_frame = RangeLowSpin->GetIVal(); - changed = changed || (Options->StartFrame != start_frame); - Options->StartFrame = start_frame; - - int end_frame = RangeHighSpin->GetIVal(); - changed = changed || (Options->EndFrame != end_frame); - Options->EndFrame = end_frame; - - bool compress_animation = (IsDlgButtonChecked(Hwnd, IDC_COMPRESS_ANIMATION_CHECK) == BST_CHECKED); - changed = changed || (Options->CompressAnimation != compress_animation); - Options->CompressAnimation = compress_animation; - - bool reduce_animation = (IsDlgButtonChecked(Hwnd, IDC_REDUCE_ANIMATION_CHECK) == BST_CHECKED); - changed = changed || (Options->ReduceAnimation != reduce_animation); - Options->ReduceAnimation = reduce_animation; - - int reduce_percent = ComboBox_GetCurSel(HwndReduce) + 1; - changed = changed || (Options->ReduceAnimationPercent != reduce_percent); - Options->ReduceAnimationPercent = reduce_percent; - - int flavor = ComboBox_GetCurSel(HwndFlavor); - changed = changed || (Options->CompressAnimationFlavor != flavor); - Options->CompressAnimationFlavor = flavor; - - char string[128]; - Edit_GetText(HwndTError, string, 128); - float trans_error = atof(string); - changed = changed || (Options->CompressAnimationTranslationError != trans_error); - Options->CompressAnimationTranslationError = trans_error; - - Edit_GetText(HwndRError, string, 128); - float rot_error = atof(string); - changed = changed || (Options->CompressAnimationRotationError != rot_error); - Options->CompressAnimationRotationError = rot_error; - - bool review_log = (IsDlgButtonChecked(Hwnd, IDC_VIEWLOG_CHECK) == BST_CHECKED); - changed = changed || (Options->ReviewLog != review_log); - Options->ReviewLog = review_log; - - // Geometry options: - //Options->UseVoxelizer = (IsDlgButtonChecked(Hwnd,IDC_VOXELIZER_CHECK) == BST_CHECKED); - Options->UseVoxelizer = false; - - if (changed) SetSaveRequiredFlag(true); - return TRUE; -} - -void W3dOptionsDialogClass::Enable_WHT_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_TRANSLATION_ONLY_CHECK),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_TERRAIN_MODE_CHECK),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_WHT_BROWSE_BUTTON),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_WHA_EXPORT_RADIO),TRUE); -} - -void W3dOptionsDialogClass::Enable_WHT_Load(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_TRANSLATION_ONLY_CHECK),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_TERRAIN_MODE_CHECK),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_WHT_BROWSE_BUTTON),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_WHA_EXPORT_RADIO),TRUE); -} - -void W3dOptionsDialogClass::Disable_WHT_Export(void) -{ - // since there will be no hierarchy tree, disable animation - CheckDlgButton(Hwnd,IDC_WHA_EXPORT_RADIO,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_WHA_NO_EXPORT_RADIO,BST_CHECKED); - Disable_WHA_Export(); - - EnableWindow(GetDlgItem(Hwnd,IDC_TRANSLATION_ONLY_CHECK),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_TERRAIN_MODE_CHECK),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_WHT_BROWSE_BUTTON),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_WHA_EXPORT_RADIO),FALSE); -} - -void W3dOptionsDialogClass::Enable_WHA_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_LOW_EDIT),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_LOW_SPIN),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_HIGH_EDIT),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_HIGH_SPIN),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_VIEWLOG_CHECK), TRUE); - - EnableWindow(GetDlgItem(Hwnd,IDC_COMPRESS_ANIMATION_CHECK),TRUE); - if (IsDlgButtonChecked(Hwnd, IDC_COMPRESS_ANIMATION_CHECK) == BST_CHECKED) { - Enable_CompressAnimationOptions_Export(); - - } -} - -void W3dOptionsDialogClass::Disable_WHA_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_LOW_EDIT),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_LOW_SPIN),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_HIGH_EDIT),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_RANGE_HIGH_SPIN),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_VIEWLOG_CHECK), FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_COMPRESS_ANIMATION_CHECK),FALSE); - Disable_CompressAnimationOptions_Export(); -} - -void W3dOptionsDialogClass::Enable_ReduceAnimationOptions_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_COMBO), TRUE); -} - -void W3dOptionsDialogClass::Disable_ReduceAnimationOptions_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_COMBO), FALSE); -} - -void W3dOptionsDialogClass::Enable_CompressAnimationOptions_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_COMPRESS_ANIMATION_FLAVOR_COMBO), TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_TRANS_ERROR_EDIT), TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_ROT_ERROR_EDIT), TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_CHECK), TRUE); - WHA_Reduce_Animation_Check_Changed(); - WHA_Compression_Flavor_Changed(); -} - -void W3dOptionsDialogClass::Disable_CompressAnimationOptions_Export(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_COMPRESS_ANIMATION_FLAVOR_COMBO), FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_TRANS_ERROR_EDIT), FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_ROT_ERROR_EDIT), FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_CHECK), FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_COMBO), FALSE); -} - -void W3dOptionsDialogClass::Enable_WTM_Export(void) -{ - ::EnableWindow(::GetDlgItem(Hwnd,IDC_EXPORT_MESH_SMOOTH_CHECK),TRUE); - ::EnableWindow(::GetDlgItem(Hwnd,IDC_EXPORT_MESH_AABTREES),TRUE); -#if ENABLE_MESH_OPTIMIZING - ::EnableWindow(::GetDlgItem(Hwnd,IDC_EXPORT_MESH_OPTIMIZE),TRUE); -#endif -} - -void W3dOptionsDialogClass::Disable_WTM_Export(void) -{ - ::EnableWindow(::GetDlgItem(Hwnd,IDC_EXPORT_MESH_SMOOTH_CHECK),FALSE); - ::EnableWindow(::GetDlgItem(Hwnd,IDC_EXPORT_MESH_AABTREES),FALSE); -#if ENABLE_MESH_OPTIMIZING - ::EnableWindow(::GetDlgItem(Hwnd,IDC_EXPORT_MESH_OPTIMIZE),FALSE); -#endif -} - -void W3dOptionsDialogClass::WHT_Export_Radio_Changed(void) -{ - if (IsDlgButtonChecked(Hwnd, IDC_WHT_EXPORT_RADIO) == BST_CHECKED) { - Enable_WHT_Export(); - } else if (IsDlgButtonChecked(Hwnd,IDC_WHT_LOAD_RADIO) == BST_CHECKED) { - Enable_WHT_Load(); - } else if (IsDlgButtonChecked(Hwnd,IDC_WHT_NO_EXPORT_RADIO) == BST_CHECKED) { - Disable_WHT_Export(); - } -} - -void W3dOptionsDialogClass::WHA_Export_Radio_Changed(void) -{ - if (IsDlgButtonChecked(Hwnd, IDC_WHA_EXPORT_RADIO) == BST_CHECKED) { - Enable_WHA_Export(); - } else if (IsDlgButtonChecked(Hwnd,IDC_WHA_NO_EXPORT_RADIO) == BST_CHECKED) { - Disable_WHA_Export(); - } -} - -void W3dOptionsDialogClass::WTM_Export_Radio_Changed(void) -{ - if (IsDlgButtonChecked(Hwnd, IDC_WTM_EXPORT_RADIO) == BST_CHECKED) { - Enable_WTM_Export(); - } else if (IsDlgButtonChecked(Hwnd,IDC_WTM_NO_EXPORT_RADIO) == BST_CHECKED) { - Disable_WTM_Export(); - } -} - - -void W3dOptionsDialogClass::WHA_Compress_Animation_Check_Changed(void) -{ - if (IsDlgButtonChecked(Hwnd, IDC_COMPRESS_ANIMATION_CHECK) == BST_CHECKED) { - Enable_CompressAnimationOptions_Export(); - } else { - Disable_CompressAnimationOptions_Export(); - } -} - -void W3dOptionsDialogClass::WHA_Reduce_Animation_Check_Changed(void) -{ - if (IsDlgButtonChecked(Hwnd, IDC_REDUCE_ANIMATION_CHECK) == BST_CHECKED) { - Enable_ReduceAnimationOptions_Export(); - } else { - Disable_ReduceAnimationOptions_Export(); - } -} - -void W3dOptionsDialogClass::WHA_Compression_Flavor_Changed() -{ - int flavor = ComboBox_GetCurSel(HwndFlavor); - - switch (flavor) { - - - case ANIM_FLAVOR_TIMECODED: { - WHA_Reduce_Animation_Check_Changed(); - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_CHECK), TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_TRANS_ERROR_EDIT), TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_ROT_ERROR_EDIT), TRUE); - - break; - } - - case ANIM_FLAVOR_ADAPTIVE_DELTA: { - // Disable Reduce animation controls - Disable_ReduceAnimationOptions_Export(); - EnableWindow(GetDlgItem(Hwnd,IDC_REDUCE_ANIMATION_CHECK), FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_TRANS_ERROR_EDIT), FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_MAX_ROT_ERROR_EDIT), FALSE); - - break; - } - - - default: - assert(0); // invalid compressed flavor setting - break; - - } - -} - - - -/*********************************************************************************************** - * _options_dialog_proc -- thunks into the Options dialog class's windows message handler * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -BOOL CALLBACK _options_dialog_proc -( - HWND hwnd, - UINT message, - WPARAM wParam, - LPARAM lParam -) -{ - static W3dOptionsDialogClass * optdialog = NULL; - - if (message == WM_INITDIALOG) { - optdialog = (W3dOptionsDialogClass *) lParam; - optdialog->Hwnd = hwnd; - } - - if (optdialog) { - return optdialog->Dialog_Proc(hwnd, message, wParam, lParam); - } else { - return FALSE; - } -} - - -/*********************************************************************************************** - * _init_ofn -- initialize the OpenFilename struct. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/24/1997 GH : Created. * - *=============================================================================================*/ -void _init_ofn(void) -{ - static char _szhierarchyfilter[] = "W3D Files (*.W3D)\0*.W3D\0WHT Files (*.WHT)\0*.WHT\0\0"; - - _HierarchyFileOFN.lStructSize = sizeof(OPENFILENAME); - _HierarchyFileOFN.hwndOwner = NULL; - _HierarchyFileOFN.hInstance = NULL; - _HierarchyFileOFN.lpstrFilter = _szhierarchyfilter; - _HierarchyFileOFN.lpstrCustomFilter = NULL; - _HierarchyFileOFN.nMaxCustFilter = 0; - _HierarchyFileOFN.nFilterIndex = 0; - _HierarchyFileOFN.lpstrFile = NULL; - _HierarchyFileOFN.nMaxFile = _MAX_PATH; - _HierarchyFileOFN.lpstrFileTitle = NULL; - _HierarchyFileOFN.nMaxFileTitle = _MAX_FNAME + _MAX_EXT; - _HierarchyFileOFN.lpstrInitialDir = NULL; - _HierarchyFileOFN.lpstrTitle = NULL; - _HierarchyFileOFN.Flags = OFN_HIDEREADONLY | OFN_CREATEPROMPT; - _HierarchyFileOFN.nFileOffset = 0; - _HierarchyFileOFN.nFileExtension = 0; - _HierarchyFileOFN.lpstrDefExt = "wht"; - _HierarchyFileOFN.lCustData = 0L; - _HierarchyFileOFN.lpfnHook = NULL; - _HierarchyFileOFN.lpTemplateName = NULL; - - _OfnInited = true; -} \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3ddlg.h b/Generals/Code/Tools/WW3D/max2w3d/w3ddlg.h deleted file mode 100644 index 440fb26344..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3ddlg.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3ddlg.h 9 2/10/00 5:45p Jason_a $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3ddlg.h $* - * * - * $Author:: Jason_a $* - * * - * $Modtime:: 2/09/00 9:50a $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef W3DDLG_H -#define W3DDLG_H - -#include "always.h" -#include -#include "w3dutil.h" - - -class W3dOptionsDialogClass -{ -public: - - W3dOptionsDialogClass(Interface * maxinterface,ExpInterface * exportinterface); - ~W3dOptionsDialogClass(); - - bool Get_Export_Options(W3dExportOptionsStruct * options); - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - -public: - - HWND Hwnd; - -private: - - void Dialog_Init(); - BOOL Dialog_Ok(); - void Enable_WHT_Export(); - void Enable_WHT_Load(); - void Disable_WHT_Export(); - void Enable_WHA_Export(); - void Disable_WHA_Export(); - void Enable_WTM_Export(); - void Disable_WTM_Export(); - - void Enable_ReduceAnimationOptions_Export(); - void Disable_ReduceAnimationOptions_Export(); - void Enable_CompressAnimationOptions_Export(); - void Disable_CompressAnimationOptions_Export(); - - void WHT_Export_Radio_Changed(); - void WHA_Export_Radio_Changed(); - void WTM_Export_Radio_Changed(); - - void WHA_Compress_Animation_Check_Changed(); - void WHA_Reduce_Animation_Check_Changed(); - - void WHA_Compression_Flavor_Changed(); - -private: - - W3dExportOptionsStruct * Options; - bool GotHierarchyFilename; - Interface * MaxInterface; - ExpInterface * ExportInterface; - - ISpinnerControl * RangeLowSpin; - ISpinnerControl * RangeHighSpin; - - HWND HwndReduce; - HWND HwndFlavor; - HWND HwndTError; - HWND HwndRError; - - int UnitsType; - float UnitsScale; -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dexp.cpp b/Generals/Code/Tools/WW3D/max2w3d/w3dexp.cpp deleted file mode 100644 index 7d1c028522..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dexp.cpp +++ /dev/null @@ -1,1292 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3dexp.cpp 78 1/03/01 11:06a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dexp.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 1/03/01 11:03a $* - * * - * $Revision:: 78 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * W3dExportClass::W3dExportClass -- constructor * - * W3dExportClass::~W3dExportClass -- destructor * - * W3dExportClass::Export_Hierarchy -- Export the hierarchy tree * - * W3dExportClass::Export_Animation -- Export animation data * - * W3dExportClass::Export_Damage_Animations -- Exports damage animations for the model * - * W3dExportClass::Export_Geometry -- Export the geometry data * - * W3dExportClass::get_hierarchy_tree -- get a pointer to the hierarchy tree * - * W3dExportClass::get_export_options -- get the export options * - * W3dExportClass::Start_Progress_Bar -- start the MAX progress meter * - * W3dExportClass::End_Progress_Bar -- end the progress meter * - * W3dExportClass::get_damage_root_list -- gets the list of damage root nodes * - * W3dExportClass::Export_HLod -- Export an HLOD description * - * W3dExportClass::Export_Collection -- exports a collection chunk * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "rawfile.h" -#include "chunkio.h" -#include "w3dexp.h" -#include "w3dutil.h" -#include "nodelist.h" -#include "meshsave.h" -#include "hiersave.h" -#include "hlodsave.h" -#include "meshcon.h" -#include "SnapPoints.h" -#include "w3ddlg.h" -#include "PROGRESS.H" -#include "errclass.h" -#include "motion.h" -#include "util.h" -#include "w3ddesc.h" -#include "colboxsave.h" -#include "nullsave.h" -#include "dazzlesave.h" -#include "maxworldinfo.h" -#include "exportlog.h" - -#include "geometryexporttask.h" -#include "geometryexportcontext.h" - -#include -#include "TARGA.H" - -// Used to communicate from the exporter to the dialog. -char W3dExportClass::CurrentExportPath[_MAX_DRIVE + _MAX_DIR + 1] = { '\000' }; - - -/* local functions */ -static DWORD WINAPI progress_callback( LPVOID arg); -static HierarchySaveClass * load_hierarchy_file(char * filename); -static bool dupe_check(const INodeListClass & list); -static bool check_lod_extensions (INodeListClass &list, INode *origin); - -/* -** Struct for export info (AppDataChunk hung off the scene pointer) -** This includes the export info struct and some padding. -** NOTE: to avoid file versioning issues, new data should be added after -** existing data in this struct, the padding array should be made smaller so -** the total size remains the same, and the new data should give reasonable -** results with a default content of zeros (which is what it will contain if -** an older file is loaded). -*/ -struct ExportInfoAppDataChunkStruct { - W3dExportOptionsStruct ExportOptions; - unsigned char Padding[89]; -}; - - - -/************************************************************************************************ -** -** GeometryFilterClass - filters out nodes which are not marked for W3D geometry export -** -************************************************************************************************/ -class GeometryFilterClass : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time) - { - Object * obj = node->EvalWorldState(time).obj; - - if - ( - obj -// && !Is_Proxy (*node) - && !Is_Origin(node) - && !node->IsHidden() - && Is_Geometry(node) - ) - { - return TRUE; - } else { - return FALSE; - } - } -}; - - - - -/************************************************************************************************ -** -** OriginFilterClass - Filters out nodes which are not "origin" objects. Origins are MAX dummy -** objects whose parents are the scene root, and are named "origin.*" (ie. first 7 characters -** in the name are "origin.". These origin objects will be (0,0,0) for all of its descendants. -** This allows an artist to create multiple models within one MAX scene but still have each -** mesh's coordinates equal without needing to stack all the models on the world origin. -** We iterate through the origin objects when exporting a scene containing multiple LODs of -** one model. -** -************************************************************************************************/ -class OriginFilterClass : public INodeFilterClass -{ -public: - - virtual BOOL Accept_Node(INode * node, TimeValue time) { return Is_Origin(node); } -}; - - -/************************************************************************************************ -** -** DamageRootFilterClass - Filters out all nodes which are not "damage root" objects. These nodes -** are MAX dummy objects whose parents are the scene root, and are named "damage.*" (ie. first 7 -** characters in the name are "damage.". These damage roots mean that all of its children -** represent a damaged model. -** -************************************************************************************************/ -class DamageRootFilterClass : public INodeFilterClass -{ -public: - - virtual BOOL Accept_Node(INode * node, TimeValue time) { return Is_Damage_Root(node); } -}; - - -/************************************************************************************************ -** -** DamageRegionFilterClass - Filters out all node that are not a bone which is part of a certain -** deformation region. Pass the region ID to the constructor. -** -************************************************************************************************/ -class DamageRegionFilterClass : public INodeFilterClass -{ -public: - DamageRegionFilterClass(int region_id) { RegionId = region_id; } - - virtual BOOL Accept_Node(INode * node, TimeValue time) - { - if (!Is_Bone(node)) return FALSE; - - // Check it's damage region ID (if it has one). - AppDataChunk * appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,1); - if (!appdata) return FALSE; - W3DAppData1Struct *wdata = (W3DAppData1Struct*)(appdata->data); - return wdata->DamageRegion == RegionId; - } - -protected: - - int RegionId; -}; - - -/*********************************************************************************************** - * W3dExportClass::DoExport -- This method is called for the plug-in to perform it's file expo * - * * - * INPUT: * - * name - filename to use * - * export - A pointer the plug-in may use to call methods to enumerate the scene * - * max - An interface pointer the plug-in may use to call methods of MAX. * - * * - * OUTPUT: * - * Nonzero on successful export; otherwise 0. * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - * 10/17/2000 gth : Removed the old export code-path, everything goes through an origin now * - *=============================================================================================*/ -int W3dExportClass::DoExport -( - const TCHAR *filename, - ExpInterface *do_export, - Interface *max, - BOOL suppressPrompts, - DWORD options -) -{ - ExportInterface = do_export; - MaxInterface = max; - RootNode = NULL; - OriginList = NULL; - DamageRootList = NULL; - HierarchyTree = NULL; - - try { - - CurTime = MaxInterface->GetTime(); - FrameRate = GetFrameRate(); - FixupType = HierarchySaveClass::MATRIX_FIXUP_TRANS_ROT; - - /* - ** The Animation and the Hierarchy will be named with the root portion of the W3D filename - ** and the path is used by the options dialog - */ - char rootname[_MAX_FNAME + 1]; - char drivename[_MAX_DRIVE + 1]; - char dirname[_MAX_DIR + 1]; - _splitpath(filename, drivename, dirname, rootname, NULL); - sprintf(CurrentExportPath, "%s%s", drivename, dirname); - - /* - ** The batch export process (suppressPrompt == TRUE) needs to know the directory of the - ** MAX file being exported. This is so that it can use the old relative pathname of the - ** W3D file containing the hierarchy. - */ - _splitpath(max->GetCurFilePath(), drivename, dirname, NULL, NULL); - sprintf(CurrentScenePath, "%s%s", drivename, dirname); - - /* - ** Get export options - */ - if (!get_export_options(suppressPrompts)) { - return 1; - } - - /* - ** If no data is going to be exported just bail - */ - if ((!ExportOptions.ExportHierarchy) && (!ExportOptions.ExportAnimation) && (!ExportOptions.ExportGeometry)) { - return 1; - } - - /* - ** Initialize the logging system - */ - ExportLog::Init(NULL); - - /* - ** Create a chunk saver to write the w3d file with - */ - RawFileClass stream(filename); - - if (!stream.Open(FileClass::WRITE)) { - MessageBox(NULL,"Unable to open file.","Error",MB_OK | MB_SETFOREGROUND); - return 1; - } - - ChunkSaveClass csave(&stream); - - /* - ** Export data from the scene. - ** - ** Are we doing an old export (one model/LOD per scene) or a new export (multiple LODs - ** for one model in a scene)? - */ - if (get_origin_list()) - { - DoOriginBasedExport(rootname, csave); - } - - /* - ** Done! - */ - stream.Close(); - - if (HierarchyTree != NULL) { - delete HierarchyTree; - HierarchyTree = NULL; - } - - if (OriginList != NULL) { - delete OriginList; - OriginList = NULL; - } - - if (DamageRootList != NULL) { - delete DamageRootList; - DamageRootList = NULL; - } - - } catch (ErrorClass error) { - - MessageBox(NULL,error.error_message,"Error",MB_OK | MB_SETFOREGROUND); - } - - ExportLog::Shutdown(ExportOptions.ReviewLog); - MaxInterface->RedrawViews(MaxInterface->GetTime()); - return 1; -} - - - -/*********************************************************************************************** - * W3dExportClass::DoOriginBasedExport -- New export codepath. Exports any objects linked to * - * an origin object. Assumes origins named "origin.01" and greater represent LODs of the * - * original object ("origin.00"). Also assumes "damage.01" and greater represent damaged * - * versions of the original object. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/13/1999 AJA : Created. * - * 9/21/1999 AJA : Added support for the new animation exporting process (damage-related). * - *=============================================================================================*/ -void W3dExportClass::DoOriginBasedExport(char *rootname,ChunkSaveClass &csave) -{ - /* - ** Build the damage root list. - */ - INodeListClass *damage_list = get_damage_root_list(); - assert(damage_list != NULL); - - /* - ** Start the progress meter - */ - Start_Progress_Bar(); - Progress_Meter_Class meter(MaxInterface,0.0f,100.0f); - - int steps = 0; - steps++; // Base Pose - steps+= OriginList->Num_Nodes(); // n Origins - steps++; // Basic Anim OR Damage Anims - steps++; // HLOD OR Collection - - meter.Finish_In_Steps(steps); - - /* - ** Find the base object's origin. - */ - bool is_base_object = false; - INodeListClass *origin_list = get_origin_list(); - unsigned int i, count = origin_list->Num_Nodes(); - INode *base_origin = NULL; - - for (i = 0; i < count; i++) - { - INode *node = (*origin_list)[i]; - if (Is_Base_Origin(node)) - { - base_origin = node; - break; - } - } - - /* - ** Write the Hierarchy Tree (if needed) - */ - Progress_Meter_Class treemeter(meter, meter.Increment); - if (!Export_Hierarchy(rootname, csave, treemeter, base_origin)) - { - MessageBox(NULL,"Hierarchy Export Failure!","Error",MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - meter.Add_Increment(); - - if (damage_list->Num_Nodes() <= 0) - { - /* - ** Write the Base Animation (if needed) - */ - Progress_Meter_Class animmeter(meter, meter.Increment); - if (!Export_Animation(rootname, csave, animmeter, base_origin)) - { - MessageBox(NULL,"Animation Export Failure!","Error",MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - meter.Add_Increment(); - } - else - { - /* - ** Write the damage animations. - */ - Progress_Meter_Class damagemeter(meter, meter.Increment); - for (i = 0; i < damage_list->Num_Nodes(); i++) - { - if (!Export_Damage_Animations(rootname, csave, damagemeter, (*damage_list)[i])) - { - MessageBox(NULL, "Damage Animation Export Failure!", "Error", MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - } - meter.Add_Increment(); - } - - /* - ** Create an array of pointers to MeshConnectionsClass objects. These objects - ** will be created below, and will be used to generate the HLOD with the - ** geometry of all models in the scene. - */ - MeshConnectionsClass **connections = new MeshConnectionsClass*[count]; - if (!connections) - { - MessageBox(NULL, "Memory allocation failure!", "Error", MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - memset(connections, 0, sizeof(MeshConnectionsClass*) * count); - - /* - ** For each model in the scene, write its animation and geometry (if needed). - ** All models share the above hierarchy tree. - */ - int idx = strlen(rootname); - rootname[idx+1] = '\0'; - - /* - ** If we're not exporting a hierarchical model, only export the "origin.00" - */ - if (!ExportOptions.LoadHierarchy && !ExportOptions.ExportHierarchy) { - count = 1; - } - - for (i = 0; i < count; i++) - { - /* - ** Get the current origin. - */ - INode *origin = (*origin_list)[i]; - - /* - ** Write each mesh (if needed) - */ - MeshConnectionsClass *meshcon = NULL; - Progress_Meter_Class meshmeter(meter, meter.Increment); - if (!Export_Geometry(rootname, csave, meshmeter, origin, &meshcon)) - { - MessageBox(NULL, "Geometry Export Failure!", "Error", MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - meter.Add_Increment(); - - /* - ** Put the MeshConnectionsClass object for this model into - ** the array in order of LOD (top-level last). - */ - int lod_level = Get_Lod_Level(origin); - if (lod_level >= count || connections[count - lod_level - 1] != NULL) - { - char text[256]; - sprintf(text, "Origin Naming Error! There are %d models defined in this " - "scene, therefore your origin names should be\n\"Origin.00\" through " - "\"Origin.%02d\", 00 being the high-poly model and %02d being the " - "lowest detail LOD.", count, count-1, count-1); - MessageBox(NULL, text, "Error", MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - connections[count - lod_level - 1] = meshcon; - } - - /* - ** Generate the HLOD based on all the mesh connections. - */ - if (ExportOptions.LoadHierarchy || ExportOptions.ExportHierarchy) { - rootname[idx] = '\0'; // remove the trailing character (signifies which lod level) - HierarchySaveClass *htree = get_hierarchy_tree(); - if (htree) - { - Progress_Meter_Class hlod_meter(meter, meter.Increment); - if (!Export_HLod(rootname, htree->Get_Name(), csave, hlod_meter, connections, count)) - { - MessageBox(NULL, "HLOD Generation Failure!", "Error", MB_OK | MB_SETFOREGROUND); - End_Progress_Bar(); - return; - } - meter.Add_Increment(); - } - } - - /* - ** Deallocate the array of mesh connections. - */ - for (i = 0; i < count; i++) - { - if (connections[i] != NULL) - delete connections[i]; - } - delete []connections; - - End_Progress_Bar(); -} - - -/*********************************************************************************************** - * W3dExportClass::Export_Hierarchy -- Export the hierarchy tree * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/16/1997 GH : Created. * - * 13/9/1999 AJA : Split into two calls, one that takes a node list and one that takes a * - * single root node. * - * 10/17/2000 gth : Removed the old code-path, we always use an origin now * - *=============================================================================================*/ -bool W3dExportClass::Export_Hierarchy(char *name,ChunkSaveClass & csave,Progress_Meter_Class & meter, - INode *root) -{ - if (!ExportOptions.ExportHierarchy) return true; - HierarchySaveClass::Enable_Terrain_Optimization(ExportOptions.EnableTerrainMode); - - if (root == NULL) return false; - - try { - HierarchyTree = new HierarchySaveClass(root,CurTime,meter,name,FixupType); - } catch (ErrorClass err) { - MessageBox(NULL, err.error_message,"Error!",MB_OK | MB_SETFOREGROUND); - return false; - } - - HierarchyTree->Save(csave); - - return true; -} - -/*********************************************************************************************** - * W3dExportClass::Export_Animation -- Export animation data * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/16/1997 GH : Created. * - * 13/9/1999 AJA : Split into two calls, one that takes a node list and one that takes a * - * single root node. * - * 10/17/2000 gth : Removed the old code-path, we always use an origin now * - *=============================================================================================*/ -bool W3dExportClass::Export_Animation(char * name,ChunkSaveClass & csave,Progress_Meter_Class & meter, - INode *root) -{ - if (!ExportOptions.ExportAnimation) return true; - HierarchySaveClass * htree = get_hierarchy_tree(); - - if ((root == NULL) || (htree == NULL)) { - return false; - } - - MotionClass * motion = NULL; - - try { - motion = new MotionClass( ExportInterface->theScene, - root, - htree, - ExportOptions, - FrameRate, - &meter, - MaxInterface->GetMAXHWnd(), - name); - } catch (ErrorClass err) { - MessageBox(NULL,err.error_message,"Error!",MB_OK | MB_SETFOREGROUND); - return false; - } - - motion->Save(csave); - - delete motion; - - return true; -} - - -/*********************************************************************************************** - * W3dExportClass::Export_Damage_Animations -- Exports damage animations for the model * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1999 AJA : Created. * - *=============================================================================================*/ -bool W3dExportClass::Export_Damage_Animations(char *name, ChunkSaveClass &csave, - Progress_Meter_Class &meter, - INode *damage_root) -{ - if (!ExportOptions.ExportAnimation) return true; - HierarchySaveClass *htree = get_hierarchy_tree(); - - if ((damage_root == NULL) || (htree == NULL)) - return false; - - int damage_state = Get_Damage_State(damage_root); - - /* - ** While exporting damage animations, we need the offset from our origin to the real - ** scene origin. - */ - Matrix3 originoffset = Inverse(damage_root->GetNodeTM(CurTime)); - - /* - ** For every damage region we find, export an animation. - */ - bool done = false; - int current_region = 0; - int num_damage_bones = 0; // number of bones assigned to a damage region - for (current_region = 0; current_region < MAX_DAMAGE_REGIONS; current_region++) - { - DamageRegionFilterClass region_filter(current_region); - INodeListClass bone_list(damage_root, CurTime, ®ion_filter); - - num_damage_bones += bone_list.Num_Nodes(); - - // Move to the next region if there aren't any bones in this one. - if (bone_list.Num_Nodes() <= 0) - continue; - - // Put together an animation name for this damage region. - char anim_name[W3D_NAME_LEN]; - sprintf(anim_name, "damage%d-%d", current_region, damage_state); - - // Export an animation for this damage region. - MotionClass *motion = NULL; - try - { - motion = new MotionClass( ExportInterface->theScene, - &bone_list, - htree, - ExportOptions, - FrameRate, - &meter, - MaxInterface->GetMAXHWnd(), - anim_name, - originoffset); - } - catch (ErrorClass err) - { - MessageBox(NULL, err.error_message, "Error!", MB_OK | MB_SETFOREGROUND); - return false; - } - - assert(motion != NULL); - motion->Save(csave); - - delete motion; - } - - if (num_damage_bones <= 0) - { - MessageBox(NULL, "Warning: Your damage bones need to be given damage region numbers. " - "You can do this in the W3D Tools panel.", name, MB_OK | MB_ICONINFORMATION | MB_SETFOREGROUND); - } - - return true; -} - -#define TEAM_COLOR_PALETTE_SIZE 16 -unsigned int houseColorScale[TEAM_COLOR_PALETTE_SIZE]= -{255,239,223,211,195,174,167,151,135,123,107,91,79,63,47,35}; - -/*********************************************************************************************** - * W3dExportClass::Export_Geometry -- Export the geometry data * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/16/1997 GH : Created. * - * 13/9/1999 AJA : Added an optional "root" parameter to export geometry of the node's * - * descendants. * - * 10/17/2000 gth : Made the "root" parameter a requirement, just pass in the scene root * - * if you want to export all geometry in the scene. * - * 10/30/2000 gth : If exporting only geometry, only export the first mesh * - *=============================================================================================*/ -bool W3dExportClass::Export_Geometry(char * name,ChunkSaveClass & csave,Progress_Meter_Class & meter, - INode *root,MeshConnectionsClass **out_connection) -{ - unsigned int i; - - assert(root != NULL); - if (!ExportOptions.ExportGeometry) return true; - - /* - ** If we're attaching the meshes to a hierarchy, get the tree - */ - HierarchySaveClass * htree = NULL; - if (ExportOptions.LoadHierarchy || ExportOptions.ExportHierarchy) { - htree = get_hierarchy_tree(); - if (htree == NULL) { - return false; - } - } - - DynamicVectorClass export_tasks; - INodeListClass *geometry_list = NULL; - - /* - ** Create the lists of nodes that we're going to work with - */ - GeometryFilterClass geometryfilter; - geometry_list = new INodeListClass(root,CurTime,&geometryfilter); - if (dupe_check(*geometry_list)) { - return false; - } - - MaxWorldInfoClass world_info(export_tasks); - world_info.Allow_Mesh_Smoothing (ExportOptions.SmoothBetweenMeshes); - unsigned int materialColors[16*16]; ///@todo: MW: Fix this to remove solid colors. - char materialColorFilename[_MAX_FNAME + 1]; - memset(materialColors,0,sizeof(materialColors)); - for (i=0; iNum_Nodes(); - if ((htree == NULL) && (geometry_list->Num_Nodes() > 1)) { - geometry_count = MIN(geometry_count,1); - ExportLog::printf("\nDiscarding extra meshes since we are not exporting a hierarchical model.\n"); - } - - for (i=0; iSet_Name(name); - export_tasks[0]->Set_Container_Name(""); - } - - /* - ** Generate the mesh-connections object to return to the caller - */ - MeshConnectionsClass * meshcon = NULL; - if (htree != NULL) { - Progress_Meter_Class mcmeter(meter,meter.Increment); - try { - meshcon = new MeshConnectionsClass(export_tasks,context); - } catch (ErrorClass err) { - MessageBox(NULL,err.error_message,"Error!",MB_OK | MB_SETFOREGROUND); - return false; - } - *out_connection = meshcon; - meter.Add_Increment(); - } - - /* - ** Export each piece of geometry - */ - for (i=0; iExport_Geometry(context); - } catch (ErrorClass err) { - MessageBox(MaxInterface->GetMAXHWnd(),err.error_message,"Error!",MB_OK | MB_SETFOREGROUND); - continue; - } - - meter.Add_Increment(); - } - - //Check if any textures need to be generated - if (context.numMaterialColors || context.numHouseColors) - { - Targa targ; - char imageBuffer[16*16*3]; - int px,py,buf_index; - unsigned int Diffuse; - - //clear to black - memset(imageBuffer,0,sizeof(imageBuffer)); - - for (i=0; i<(16+context.numMaterialColors); i++) - { - //get coordinates of this material within texture page - px=(i%16); ///@todo: MW: Remove hard-coded texture size - py=(i/16); - - Diffuse=context.materialColors[i]; - buf_index=(px+py*16)*3; - - imageBuffer[buf_index]=(Diffuse>>16)&0xff; - imageBuffer[buf_index+1]=(Diffuse>>8)&0xff; - imageBuffer[buf_index+2]=(Diffuse)&0xff; - } - - memset(&targ.Header,0,sizeof(targ.Header)); - targ.Header.Width=16; - targ.Header.Height=16; - targ.Header.PixelDepth=24; - targ.Header.ImageType=TGA_TRUECOLOR; - targ.SetImage(imageBuffer); - targ.YFlip(); - - if (context.numHouseColors) - sprintf(materialColorFilename,"%sZHCD_%s.tga",CurrentExportPath,name); - - targ.Save(materialColorFilename,TGAF_IMAGE,false); - } - - /* - ** Cleanup - */ - for (i=0; iGetMAXHWnd(),buf,"Error",MB_OK | MB_SETFOREGROUND); - return NULL; - } - } - - /* - ** Should never fall through to here... - ** This would only happen if ExportHierarchy was true and the Export_Hierarchy - ** function failed to create a hierarchy tree for us. - */ - assert(0); - return NULL; -} - - -/*********************************************************************************************** - * W3dExportClass::get_damage_root_list -- gets the list of damage root nodes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/17/2000 gth : Created. * - *=============================================================================================*/ -INodeListClass * W3dExportClass::get_damage_root_list(void) -{ - if (DamageRootList != NULL) return DamageRootList; - - /* - ** Create a list of all damage root objects in the scene. - */ - DamageRootFilterClass nodefilter; - DamageRootList = new INodeListClass(ExportInterface->theScene, CurTime, &nodefilter); - return DamageRootList; -} - - -/*********************************************************************************************** - * get_origin_list -- get the list of origin nodes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/13/1999 AJA : Created. * - *=============================================================================================*/ -INodeListClass * W3dExportClass::get_origin_list(void) -{ - if (OriginList != NULL) return OriginList; - - /* - ** Create a list of all origins in the scene. - */ - static OriginFilterClass originfilter; - OriginList = new INodeListClass (ExportInterface->theScene, CurTime, &originfilter); - - /* - ** If we didn't find any origins, add the scene root as an origin. - ** NOTE: it would also be a problem if the origin list contained both the scene root - ** and the user placed origins. Thats not happening now because the OriginList - ** does not collect the scene root... were that to change we'd have to update this - ** code as well. - */ - if (OriginList->Num_Nodes() == 0) { - OriginList->Insert(MaxInterface->GetRootNode()); - } - - return OriginList; -} - -/*********************************************************************************************** - * W3dExportClass::get_export_options -- get the export options * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/16/1997 GH : Created. * - * 9/30/1999 AJA : Added support for the MAX suppress_prompts flag. * - *=============================================================================================*/ -bool W3dExportClass::get_export_options(BOOL suppress_prompts) -{ - int ticksperframe = GetTicksPerFrame(); - - // Get the last export settings from the AppDataChunk attached to the - // scene pointer. If there is no such AppDataChunk create one and set it - // to default values. - - W3dExportOptionsStruct *options = NULL; - - AppDataChunk * appdata = MaxInterface->GetScenePointer()->GetAppDataChunk(W3D_EXPORTER_CLASS_ID,SCENE_EXPORT_CLASS_ID,0); - - if (appdata) { - options = &(((ExportInfoAppDataChunkStruct *)(appdata->data))->ExportOptions); - } else { - - ExportInfoAppDataChunkStruct *appdata_struct = - (ExportInfoAppDataChunkStruct *)malloc(sizeof(ExportInfoAppDataChunkStruct)); - - options = &(appdata_struct->ExportOptions); - - options->ExportHierarchy = true; - options->LoadHierarchy = false; - options->ExportAnimation = true; - options->EnableTerrainMode = false; - - options->ReduceAnimation = false; - options->ReduceAnimationPercent = 50; - - options->CompressAnimation = false; - options->CompressAnimationFlavor = ANIM_FLAVOR_TIMECODED; - options->CompressAnimationTranslationError = 0.001f; //DEFAULT_LOSSY_ERROR_TOLERANCE; - options->CompressAnimationRotationError = 0.050f; //DEFAULT_LOSSY_ERROR_TOLERANCE; - options->ReviewLog = false; - - options->ExportGeometry = true; - options->TranslationOnly = false; - options->SmoothBetweenMeshes = true; - - strcpy(options->HierarchyFilename,""); - strcpy(options->RelativeHierarchyFilename,""); - options->StartFrame = MaxInterface->GetAnimRange().Start() / ticksperframe; - options->EndFrame = MaxInterface->GetAnimRange().End() / ticksperframe; - options->UseVoxelizer = false; - options->DisableExportAABTrees = true; - options->EnableOptimizeMeshData = false; - options->EnableMaterialColorToTextureConversion = false; - - memset(&(appdata_struct->Padding), 0, sizeof(appdata_struct->Padding)); - - MaxInterface->GetScenePointer()->AddAppDataChunk(W3D_EXPORTER_CLASS_ID, - SCENE_EXPORT_CLASS_ID, 0, sizeof(ExportInfoAppDataChunkStruct), - appdata_struct); - - } - - // (gth) disabling the 'optimize mesh data' feature due to problems with external tools - options->EnableOptimizeMeshData = false; - - bool retval = true; - if (suppress_prompts == FALSE) - { - W3dOptionsDialogClass dialog(MaxInterface,ExportInterface); - retval = dialog.Get_Export_Options(options); - } - - if (suppress_prompts || retval) { - - ExportOptions = *options; - - if ( (suppress_prompts == TRUE) && (options->RelativeHierarchyFilename[0] != 0) ) - { - // Use the relative pathname WRT the max scene's directory to - // figure out the absolute directory where the hierarchy file - // is stored. - char curdir[_MAX_DRIVE + _MAX_DIR + 1]; - assert(_getcwd(curdir, sizeof(curdir))); - assert(_chdir(CurrentScenePath) != -1); - assert(_fullpath(HierarchyFilename, options->RelativeHierarchyFilename, - sizeof(HierarchyFilename))); - assert(_chdir(curdir) != -1); - } - else - strcpy(HierarchyFilename,options->HierarchyFilename); - - if (ExportOptions.TranslationOnly) { - FixupType = HierarchySaveClass::MATRIX_FIXUP_TRANS; - } else { - FixupType = HierarchySaveClass::MATRIX_FIXUP_TRANS_ROT; - } - } - - return retval; -} - - - - -/*********************************************************************************************** - * W3dExportClass::Start_Progress_Bar -- start the MAX progress meter * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/16/1997 GH : Created. * - *=============================================================================================*/ -void W3dExportClass::Start_Progress_Bar(void) -{ - MaxInterface->ProgressStart( - "Processing Triangle Mesh", - TRUE, - progress_callback, - NULL); -} - -/*********************************************************************************************** - * W3dExportClass::End_Progress_Bar -- end the progress meter * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/16/1997 GH : Created. * - *=============================================================================================*/ -void W3dExportClass::End_Progress_Bar(void) -{ - MaxInterface->ProgressUpdate( 100); - MaxInterface->ProgressEnd(); -} - -static bool dupe_check(const INodeListClass & list) -{ - for (unsigned i=0; iGetName(),list[j]->GetName()) == 0) { - char buf[256]; - sprintf(buf,"Geometry Nodes with duplicated names found!\nDuplicated Name: %s\n",list[i]->GetName()); - MessageBox(NULL,buf,"Error",MB_OK | MB_SETFOREGROUND); - return true; - } - } - } - } - return false; -} - -static bool check_lod_extensions (INodeListClass &list, INode *origin) -{ - /* - ** Assumptions: - ** - If origin == NULL, then we're just exporting a single model and don't need to - ** worry about lod extensions at all. - ** - If origin is the root of the scene, then we're just exporting a single model as well. - ** - Otherwise origin actually points to an Origin and not just any INode. - */ - if (origin == NULL) return true; - if (origin->IsRootNode()) return true; - - char *extension = strrchr(origin->GetName(), '.'); - int ext_len = strlen(extension); - for (unsigned i = 0; i < list.Num_Nodes(); i++) - { - char *this_ext = strrchr(list[i]->GetName(), '.'); - - // Check for the existance of an extension in this node. - if (this_ext == NULL) - return false; - - // Check that the extensions are the same. - if (strcmp(this_ext, extension) != 0) - return false; - } - - return true; -} - - -bool W3dExportClass::get_base_object_tm (Matrix3 &tm) -{ - INodeListClass *origin_list = get_origin_list(); - if (!origin_list) - return false; - - unsigned int i, count = origin_list->Num_Nodes(); - INode *base_origin = NULL; - for (i = 0; i < count; i++) - { - INode *node = (*origin_list)[i]; - if (Is_Base_Origin(node)) - { - // we found origin.00, fall through - base_origin = node; - break; - } - } - if (!base_origin) - return false; - - tm = base_origin->GetNodeTM(CurTime); - return true; -} - -static DWORD WINAPI progress_callback( LPVOID arg ) -{ - return 0; -} - - -static HierarchySaveClass * load_hierarchy_file(char * filename) -{ - HierarchySaveClass * hier = NULL; - - RawFileClass file(filename); - - if (!file.Open()) { - return NULL; - } - ChunkLoadClass cload(&file); - - cload.Open_Chunk(); - if (cload.Cur_Chunk_ID() == W3D_CHUNK_HIERARCHY) { - hier = new HierarchySaveClass(); - hier->Load(cload); - } else { - hier = NULL; - file.Close(); - return NULL; - } - - cload.Close_Chunk(); - file.Close(); - - return hier; -} - diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dexp.h b/Generals/Code/Tools/WW3D/max2w3d/w3dexp.h deleted file mode 100644 index 8f50c6f7d3..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dexp.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3dexp.h 22 10/23/00 5:34p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dexp.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/23/00 5:24p $* - * * - * $Revision:: 22 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef W3DEXP_H -#define W3DEXP_H - -#include "always.h" -#include -#include "dllmain.h" -#include "hiersave.h" -#include "w3dutil.h" -#include "resource.h" - - -class MeshConnectionsClass; -class GeometryExportTaskClass; - -class W3dExportClass : public SceneExport -{ - -public: - - W3dExportClass() {}; - ~W3dExportClass() {}; - - int ExtCount() { return 1; }; - const TCHAR * Ext(int n) { return Get_String(IDS_W3D_FILE_EXTEN); }; - const TCHAR * LongDesc() { return Get_String(IDS_W3D_LONG_DESCRIPTION); }; - const TCHAR * ShortDesc() { return Get_String(IDS_W3D_SHORT_DESCRIPTION); }; - const TCHAR * AuthorName() { return Get_String(IDS_AUTHOR_NAME); }; - const TCHAR * CopyrightMessage() { return Get_String(IDS_COPYRIGHT_NOTICE); }; - const TCHAR * OtherMessage1() { return _T(""); }; - const TCHAR * OtherMessage2() { return _T(""); }; - unsigned int Version() { return 100; }; - - void ShowAbout(HWND hWnd) {}; - int DoExport(const TCHAR *name,ExpInterface *ei,Interface *i, BOOL suppressPrompts=FALSE, DWORD options=0); // Export file - -protected: - - void DoOriginBasedExport(char *rootname, ChunkSaveClass &csave); - -public: - - friend BOOL CALLBACK ExportOptionsDlgProc(HWND hDlg,UINT message,WPARAM wParam,LPARAM lParam); - - static char CurrentExportPath[_MAX_DRIVE + _MAX_DIR + 1]; // Used to communicate from the exporter to the dialog. - char CurrentScenePath[_MAX_DRIVE + _MAX_DIR + 1]; // directory where the current .max file is stored - -private: - - ExpInterface * ExportInterface; - Interface * MaxInterface; - TimeValue CurTime; - int FrameRate; - - W3dExportOptionsStruct ExportOptions; - - char HierarchyFilename[_MAX_PATH]; - int FixupType; - INode * RootNode; - INodeListClass * RootList; - INodeListClass * OriginList; - INodeListClass * DamageRootList; - - HierarchySaveClass * HierarchyTree; - - bool get_export_options(BOOL suppress_prompts = FALSE); - INodeListClass * get_origin_list(void); - INodeListClass * get_damage_root_list(void); - HierarchySaveClass * get_hierarchy_tree(void); - - bool get_base_object_tm(Matrix3 &tm); - - bool Export_Hierarchy(char * name,ChunkSaveClass & csave,Progress_Meter_Class & meter,INode *root); - bool Export_Animation(char * name,ChunkSaveClass & csave,Progress_Meter_Class & meter,INode *root); - bool Export_Damage_Animations(char * name,ChunkSaveClass & csave,Progress_Meter_Class &meter,INode *damage_root); - bool Export_Geometry(char * name,ChunkSaveClass & csave,Progress_Meter_Class & meter,INode *root=NULL, MeshConnectionsClass **out_connection=NULL); - bool Export_HLod (char *name, const char *htree_name, ChunkSaveClass &csave, Progress_Meter_Class &meter, MeshConnectionsClass **connections, int lod_count); - bool Export_Collection(const char * name,ChunkSaveClass & csave,DynamicVectorClass & objlist,INodeListClass & placeholder_list,INodeListClass & transform_node_list); - - void Start_Progress_Bar(void); - void End_Progress_Bar(void); - -}; - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dmtl.cpp b/Generals/Code/Tools/WW3D/max2w3d/w3dmtl.cpp deleted file mode 100644 index c14a3eea70..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dmtl.cpp +++ /dev/null @@ -1,1239 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dmtl.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/22/01 7:47a $* - * * - * $Revision:: 32 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "w3dmtl.h" -#include -#include -#include "gamemtl.h" -#include "realcrc.h" - -static W3dRGBStruct Color_To_W3d(Color & c) -{ - W3dRGBStruct wc; - wc.R = (c.r * 255.0f); - wc.G = (c.g * 255.0f); - wc.B = (c.b * 255.0f); - wc.pad = 0; - return wc; -} - -/* - - - Implementation of W3dMapClass - - - -*/ - -W3dMapClass::W3dMapClass(const W3dMapClass & that) -{ - Set_Filename(that.Filename); - if (that.AnimInfo) { - Set_Anim_Info(that.AnimInfo); - } -} - -W3dMapClass & W3dMapClass::operator = (const W3dMapClass & that) -{ - if (this != &that) { - Set_Filename(that.Filename); - Set_Anim_Info(that.AnimInfo); - } - return *this; -} - -W3dMapClass::~W3dMapClass(void) -{ - if (Filename) free(Filename); - if (AnimInfo) delete AnimInfo; -} - -void W3dMapClass::Reset(void) -{ - if (Filename) free(Filename); - if (AnimInfo) delete AnimInfo; - Filename = NULL; - AnimInfo = NULL; -} - -void W3dMapClass::Set_Filename(const char * fullpath) -{ - if (Filename) { - free(Filename); - } - if (fullpath) { - char name[_MAX_FNAME]; - char exten[_MAX_EXT]; - char fname[_MAX_FNAME+_MAX_EXT+2]; - - _splitpath(fullpath,NULL,NULL,name,exten); - _makepath(fname,NULL,NULL,name,exten); - //strupr(fname); (gth) need to preserve case since unix/PS2 is case sensitive... - Filename = strdup(fname); - } else { - Filename = NULL; - } -} - -void W3dMapClass::Set_Anim_Info(const W3dTextureInfoStruct * info) -{ - if (info == NULL) { - if (AnimInfo) { - delete AnimInfo; - AnimInfo = NULL; - return; - } - } else { - if (AnimInfo == NULL) { - AnimInfo = new W3dTextureInfoStruct; - } - *AnimInfo = *info; - } -} - -void W3dMapClass::Set_Anim_Info(int framecount,float framerate) -{ - if (AnimInfo == NULL) { - AnimInfo = new W3dTextureInfoStruct; - } - - AnimInfo->FrameCount = framecount; - AnimInfo->FrameRate = framerate; -} - - - -/* - - - Implementation of W3dMaterialClass - - -*/ - - -W3dMaterialClass::W3dMaterialClass(void) -{ - PassCount = 0; - SortLevel = SORT_LEVEL_NONE; - for (int pass = 0; pass < MAX_PASSES; pass++) { - Materials[pass] = NULL; - W3d_Shader_Reset(&(Shaders[pass])); - for (int stage = 0; stage < MAX_STAGES; stage++) { - Textures[pass][stage] = NULL; - MapChannel[pass][stage] = 1; - MapperArgs[pass][stage] = NULL; - } - } -} - -W3dMaterialClass::~W3dMaterialClass(void) -{ - Free(); -} - -void W3dMaterialClass::Free(void) -{ - for (int pass = 0; pass < MAX_PASSES; pass++) { - - if (Materials[pass]) { - delete Materials[pass]; - Materials[pass] = NULL; - } - - for (int stage = 0; stage < MAX_STAGES; stage++) { - if (Textures[pass][stage]) { - delete Textures[pass][stage]; - Textures[pass][stage] = NULL; - } - - if (MapperArgs[pass][stage]) { - delete [] MapperArgs[pass][stage]; - MapperArgs[pass][stage] = NULL; - } - } - } -} - -void W3dMaterialClass::Reset(void) -{ - Free(); - SortLevel = SORT_LEVEL_NONE; - for (int pass=0; pass < MAX_PASSES; pass++) { - W3d_Shader_Reset(&(Shaders[pass])); - - for (int stage=0; stage < MAX_STAGES; stage++) { - MapChannel[pass][stage] = 1; - } - } -} - -void W3dMaterialClass::Set_Surface_Type(unsigned int type) -{ - SurfaceType = type; -} - -void W3dMaterialClass::Set_Sort_Level(int level) -{ - assert(level <= MAX_SORT_LEVEL); - SortLevel = level; -} - -void W3dMaterialClass::Set_Pass_Count(int count) -{ - assert(count >= 0); - assert(count < MAX_PASSES); - PassCount = count; -} - -void W3dMaterialClass::Set_Vertex_Material(const W3dVertexMaterialStruct & vmat,int pass) -{ - assert(pass >= 0); - assert(pass < PassCount); - - if (Materials[pass] == NULL) { - Materials[pass] = new W3dVertexMaterialStruct; - } - *(Materials[pass]) = vmat; -} - -void W3dMaterialClass::Set_Mapper_Args(const char *args_buffer, int pass, int stage) -{ - assert(pass >= 0); - assert(pass < PassCount); - assert(stage >= 0); - assert(stage < MAX_STAGES); - - if (MapperArgs[pass][stage] != NULL) { - delete [] MapperArgs[pass][stage]; - MapperArgs[pass][stage] = NULL; - } - if (args_buffer) { - int len = strlen(args_buffer); - MapperArgs[pass][stage] = new char [len + 1]; - strcpy(MapperArgs[pass][stage], args_buffer); - } -} - -void W3dMaterialClass::Set_Shader(const W3dShaderStruct & shader,int pass) -{ - assert(pass >= 0); - assert(pass < PassCount); - - Shaders[pass] = shader; -} - -void W3dMaterialClass::Set_Texture(const W3dMapClass & map,int pass,int stage) -{ - assert(pass >= 0); - assert(pass < PassCount); - - if (Textures[pass][stage] == NULL) { - Textures[pass][stage] = new W3dMapClass; - } - *(Textures[pass][stage]) = map; -} - -void W3dMaterialClass::Set_Map_Channel(int pass,int stage,int channel) -{ - assert(pass >= 0); - assert(pass < PassCount); - MapChannel[pass][stage] = channel; -} - -unsigned int W3dMaterialClass::Get_Surface_Type(void) const -{ - return SurfaceType; -} - -int W3dMaterialClass::Get_Sort_Level(void) const -{ - return SortLevel; -} - -int W3dMaterialClass::Get_Pass_Count(void) const -{ - return PassCount; -} - -W3dVertexMaterialStruct * W3dMaterialClass::Get_Vertex_Material(int pass ) const -{ - assert(pass >= 0); - assert(pass < PassCount); - - return Materials[pass]; -} - -const char * W3dMaterialClass::Get_Mapper_Args(int pass, int stage) const -{ - assert(pass >= 0); - assert(pass < PassCount); - assert(stage >= 0); - assert(stage < MAX_STAGES); - - return MapperArgs[pass][stage]; -} - -W3dShaderStruct W3dMaterialClass::Get_Shader(int pass) const -{ - assert(pass >= 0); - assert(pass < PassCount); - return Shaders[pass]; -} - -W3dMapClass * W3dMaterialClass::Get_Texture(int pass,int stage) const -{ - assert(pass >= 0); - assert(pass < PassCount); - assert(stage >= 0); - assert(stage < MAX_STAGES); - - return Textures[pass][stage]; -} - -int W3dMaterialClass::Get_Map_Channel(int pass,int stage) const -{ - assert(pass >= 0); - assert(pass < PassCount); - assert(stage >= 0); - assert(stage < MAX_STAGES); - - return MapChannel[pass][stage]; -} - -void W3dMaterialClass::Init(Mtl * mtl, char *materialColorTexture) -{ - bool ps2_mat = false; - Reset(); - - if (mtl->ClassID() == PS2GameMaterialClassID) - { - ps2_mat = true; - } - - if ((mtl->ClassID() == GameMaterialClassID) || ps2_mat) { - Init((GameMtl*)mtl, materialColorTexture); ///@todo: Fix this for substituted textures. - return; - } - - Texmap * tmap; - PassCount = 1; - - tmap = mtl->GetSubTexmap(ID_RL); - if (tmap && tmap->ClassID() == Class_ID(BMTEX_CLASS_ID,0)) { - PassCount++; - } - - W3dVertexMaterialStruct mat; - W3dShaderStruct shader; - W3dMapClass tex; - - /* - ** Setting up the diffuse color pass - */ - W3d_Shader_Reset(&shader); - - mat.Attributes = 0; - mat.Emissive.R = mat.Emissive.G = mat.Emissive.B = 0; //(uint8)(255 .0f * mtl->GetSelfIllum()); - - Color diffuse = mtl->GetDiffuse(); - mat.Diffuse.R = (uint8)(diffuse.r * 255.0f); - mat.Diffuse.G = (uint8)(diffuse.g * 255.0f); - mat.Diffuse.B = (uint8)(diffuse.b * 255.0f); - mat.Ambient = mat.Diffuse; - - Color specular = mtl->GetSpecular(); - mat.Specular.R = (uint8)(specular.r * 255.0f); - mat.Specular.G = (uint8)(specular.g * 255.0f); - mat.Specular.B = (uint8)(specular.b * 255.0f); - - mat.Shininess = mtl->GetShininess(); - mat.Opacity = 1.0f - mtl->GetXParency(); - mat.Translucency = 0.0f; - - tmap = mtl->GetSubTexmap(ID_DI); - if (tmap && tmap->ClassID() == Class_ID(BMTEX_CLASS_ID,0)) { - - char * tname = ((BitmapTex *)tmap)->GetMapName(); - if (tname) { - tex.Set_Filename(tname); - mat.Diffuse.R = mat.Diffuse.G = mat.Diffuse.B = 255; - W3d_Shader_Set_Texturing(&shader,W3DSHADER_TEXTURING_ENABLE); - Set_Texture(tex,0,0); - } - } - - if (materialColorTexture && !mtl->GetSubTexmap(ID_DI) && !mtl->GetSubTexmap(ID_RL)) - { //no textures on material, substitute textures to improve rendering speed. - tex.Set_Filename(materialColorTexture); ///@todo: Fix this to procedural name/path - W3d_Shader_Set_Texturing(&shader,W3DSHADER_TEXTURING_ENABLE); - //This texture will hold solid pixels of material color, don't need any filtering. -// W3dTextureInfoStruct texinfo; -// memset(&texinfo,0,sizeof(texinfo)); -// texinfo.Attributes = texinfo.Attributes | /*W3DTEXTURE_NO_LOD|*/W3DTEXTURE_CLAMP_U | W3DTEXTURE_CLAMP_V; -// tex.Set_Anim_Info(&texinfo); - Set_Texture(tex,0,0); - } - - if (mat.Opacity != 1.0f) { - W3d_Shader_Set_Dest_Blend_Func(&shader,W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA); - W3d_Shader_Set_Src_Blend_Func(&shader,W3DSHADER_SRCBLENDFUNC_SRC_ALPHA); - } - - Set_Vertex_Material(mat,0); - Set_Shader(shader,0); - - - /* - ** Setting up the reflection pass (envmap) - */ - if (PassCount == 2) { - - W3d_Shader_Reset(&shader); - if (ps2_mat) - { - W3d_Shader_Set_Pri_Gradient(&shader,PSS_PRIGRADIENT_MODULATE); - } - else - { - W3d_Shader_Set_Pri_Gradient(&shader,W3DSHADER_PRIGRADIENT_MODULATE); - } - W3d_Shader_Set_Sec_Gradient(&shader,W3DSHADER_SECGRADIENT_DISABLE); - W3d_Shader_Set_Depth_Mask(&shader,W3DSHADER_DEPTHMASK_WRITE_DISABLE); - W3d_Shader_Set_Dest_Blend_Func(&shader,W3DSHADER_DESTBLENDFUNC_ONE); - W3d_Shader_Set_Src_Blend_Func(&shader,W3DSHADER_SRCBLENDFUNC_ONE); - W3d_Shader_Set_Texturing(&shader,W3DSHADER_TEXTURING_ENABLE); - - // PS2 specific paramaters. - W3d_Shader_Set_PS2_Param_A(&shader, PSS_SRC); - W3d_Shader_Set_PS2_Param_B(&shader, PSS_ZERO); - W3d_Shader_Set_PS2_Param_B(&shader, PSS_ONE); - W3d_Shader_Set_PS2_Param_B(&shader, PSS_DEST); - - W3d_Vertex_Material_Reset(&mat); - mat.Diffuse.R = mat.Diffuse.G = mat.Diffuse.B = 128; - mat.Attributes &= W3DVERTMAT_STAGE0_MAPPING_MASK; - mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_ENVIRONMENT; - - tmap = mtl->GetSubTexmap(ID_RL); - if (tmap && tmap->ClassID() == Class_ID(BMTEX_CLASS_ID,0)) { - - char * tname = ((BitmapTex *)tmap)->GetMapName(); - if (tname) { - tex.Set_Filename(tname); - Set_Texture(tex,1); - } - } - - Set_Vertex_Material(mat,1); - Set_Shader(shader,1); - } -} - -void W3dMaterialClass::Init(GameMtl * gamemtl, char *materialColorTexture) -{ - Reset(); - PassCount = gamemtl->Get_Pass_Count(); - Set_Surface_Type (gamemtl->Get_Surface_Type ()); - Set_Sort_Level(gamemtl->Get_Sort_Level()); - - for (int pass=0;passGet_Pass_Count(); pass++) { - - /* - ** set up the shader - */ - W3dShaderStruct shader; - W3d_Shader_Reset(&shader); - shader.DepthCompare = gamemtl->Get_Depth_Compare(pass); - shader.DepthMask = gamemtl->Get_Depth_Mask(pass); - shader.AlphaTest = gamemtl->Get_Alpha_Test(pass); - shader.DestBlend = gamemtl->Get_Dest_Blend(pass); - shader.PriGradient = gamemtl->Get_Pri_Gradient(pass); - shader.SecGradient = gamemtl->Get_Sec_Gradient(pass); - shader.SrcBlend = gamemtl->Get_Src_Blend(pass); - shader.DetailColorFunc = gamemtl->Get_Detail_Color_Func(pass); - shader.DetailAlphaFunc = gamemtl->Get_Detail_Alpha_Func(pass); - shader.Texturing = W3DSHADER_TEXTURING_DISABLE; - shader.PostDetailColorFunc = gamemtl->Get_Detail_Color_Func(pass); // (gth) set up the post-detail options - shader.PostDetailAlphaFunc = gamemtl->Get_Detail_Alpha_Func(pass); - - // PS2 specific paramaters. - W3d_Shader_Set_PS2_Param_A(&shader, gamemtl->Get_PS2_Shader_Param_A(pass)); - W3d_Shader_Set_PS2_Param_B(&shader, gamemtl->Get_PS2_Shader_Param_B(pass)); - W3d_Shader_Set_PS2_Param_C(&shader, gamemtl->Get_PS2_Shader_Param_C(pass)); - W3d_Shader_Set_PS2_Param_D(&shader, gamemtl->Get_PS2_Shader_Param_D(pass)); - - /* - ** set up the vertex material - */ - W3dVertexMaterialStruct mat; - mat.Attributes = 0; - - if (gamemtl->Get_Copy_Specular_To_Diffuse(pass)) { - mat.Attributes |= W3DVERTMAT_COPY_SPECULAR_TO_DIFFUSE; - } - - // mapping type for stage 0 - switch(gamemtl->Get_Mapping_Type(pass, 0)) - { - case GAMEMTL_MAPPING_UV: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_UV; break; - case GAMEMTL_MAPPING_ENV: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_ENVIRONMENT; break; - case GAMEMTL_MAPPING_CHEAP_ENV: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_CHEAP_ENVIRONMENT; break; - case GAMEMTL_MAPPING_SCREEN: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_SCREEN; break; - case GAMEMTL_MAPPING_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_SILHOUETTE: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_SILHOUETTE; break; - - case GAMEMTL_MAPPING_SCALE: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_SCALE; break; - case GAMEMTL_MAPPING_GRID: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_GRID; break; - case GAMEMTL_MAPPING_ROTATE: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_ROTATE; break; - case GAMEMTL_MAPPING_SINE_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_SINE_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_STEP_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_STEP_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_ZIGZAG_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_ZIGZAG_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_WS_CLASSIC_ENV: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_WS_CLASSIC_ENV; break; - case GAMEMTL_MAPPING_WS_ENVIRONMENT: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_WS_ENVIRONMENT; break; - case GAMEMTL_MAPPING_GRID_CLASSIC_ENV: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_GRID_CLASSIC_ENV; break; - case GAMEMTL_MAPPING_GRID_ENVIRONMENT: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_GRID_ENVIRONMENT; break; - case GAMEMTL_MAPPING_RANDOM: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_RANDOM; break; - case GAMEMTL_MAPPING_EDGE: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_EDGE; break; - case GAMEMTL_MAPPING_BUMPENV: mat.Attributes |= W3DVERTMAT_STAGE0_MAPPING_BUMPENV; break; - }; - - // mapping type for stage 1 - switch(gamemtl->Get_Mapping_Type(pass, 1)) - { - case GAMEMTL_MAPPING_UV: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_UV; break; - case GAMEMTL_MAPPING_ENV: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_ENVIRONMENT; break; - case GAMEMTL_MAPPING_CHEAP_ENV: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_CHEAP_ENVIRONMENT; break; - case GAMEMTL_MAPPING_SCREEN: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_SCREEN; break; - case GAMEMTL_MAPPING_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_SILHOUETTE: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_SILHOUETTE; break; - - case GAMEMTL_MAPPING_SCALE: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_SCALE; break; - case GAMEMTL_MAPPING_GRID: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_GRID; break; - case GAMEMTL_MAPPING_ROTATE: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_ROTATE; break; - case GAMEMTL_MAPPING_SINE_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_SINE_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_STEP_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_STEP_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_ZIGZAG_LINEAR_OFFSET: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_ZIGZAG_LINEAR_OFFSET; break; - case GAMEMTL_MAPPING_WS_CLASSIC_ENV: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_WS_CLASSIC_ENV; break; - case GAMEMTL_MAPPING_WS_ENVIRONMENT: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_WS_ENVIRONMENT; break; - case GAMEMTL_MAPPING_GRID_CLASSIC_ENV: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_GRID_CLASSIC_ENV; break; - case GAMEMTL_MAPPING_GRID_ENVIRONMENT: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_GRID_ENVIRONMENT; break; - case GAMEMTL_MAPPING_RANDOM: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_RANDOM; break; - case GAMEMTL_MAPPING_EDGE: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_EDGE; break; - case GAMEMTL_MAPPING_BUMPENV: mat.Attributes |= W3DVERTMAT_STAGE1_MAPPING_BUMPENV; break; - }; - - switch(gamemtl->Get_PSX_Translucency(pass)) - { - case GAMEMTL_PSX_TRANS_NONE: mat.Attributes |= W3DVERTMAT_PSX_TRANS_NONE; break; - case GAMEMTL_PSX_TRANS_100: mat.Attributes |= W3DVERTMAT_PSX_TRANS_100; break; - case GAMEMTL_PSX_TRANS_50: mat.Attributes |= W3DVERTMAT_PSX_TRANS_50; break; - case GAMEMTL_PSX_TRANS_25: mat.Attributes |= W3DVERTMAT_PSX_TRANS_25; break; - case GAMEMTL_PSX_TRANS_MINUS_100:mat.Attributes |= W3DVERTMAT_PSX_TRANS_MINUS_100; break; - }; - - if (!gamemtl->Get_PSX_Lighting(pass)) { - mat.Attributes |= W3DVERTMAT_PSX_NO_RT_LIGHTING; - } - - mat.Ambient = Color_To_W3d(gamemtl->Get_Ambient(pass,0)); - mat.Diffuse = Color_To_W3d(gamemtl->Get_Diffuse(pass,0)); - mat.Specular = Color_To_W3d(gamemtl->Get_Specular(pass,0)); - mat.Emissive = Color_To_W3d(gamemtl->Get_Emissive(pass,0)); - mat.Shininess = gamemtl->Get_Shininess(pass,0); - mat.Opacity = gamemtl->Get_Opacity(pass,0); - mat.Translucency = gamemtl->Get_Translucency(pass,0); - - /* - ** install the two textures if present - */ - W3dMapClass w3dmap; - BitmapTex * tex = NULL; - - for (int stage=0; stage < MAX_STAGES; stage++) { - - if (gamemtl->Get_Texture_Enable(pass,stage) && gamemtl->Get_Texture(pass,stage)) { - - w3dmap.Reset(); - - // get the filename for the w3dmap texture - tex = (BitmapTex *)gamemtl->Get_Texture(pass,stage); - assert(tex->GetMapName()); - w3dmap.Set_Filename(tex->GetMapName()); - - // get the animation and flags for the w3dmap texture - W3dTextureInfoStruct texinfo; - memset(&texinfo,0,sizeof(texinfo)); - - texinfo.AnimType = gamemtl->Get_Texture_Anim_Type(pass,stage); - - if (gamemtl->Get_Texture_Publish(pass,stage)) { - texinfo.Attributes = texinfo.Attributes | W3DTEXTURE_PUBLISH; - } - if (gamemtl->Get_Texture_No_LOD(pass,stage)) { - texinfo.Attributes = texinfo.Attributes | W3DTEXTURE_NO_LOD; - } - if (gamemtl->Get_Texture_Clamp_U(pass,stage)) { - texinfo.Attributes = texinfo.Attributes | W3DTEXTURE_CLAMP_U; - } - if (gamemtl->Get_Texture_Clamp_V(pass,stage)) { - texinfo.Attributes = texinfo.Attributes | W3DTEXTURE_CLAMP_V; - } - if (gamemtl->Get_Texture_Alpha_Bitmap(pass,stage)) { - texinfo.Attributes = texinfo.Attributes | W3DTEXTURE_ALPHA_BITMAP; - } - texinfo.Attributes = texinfo.Attributes | ( - (gamemtl->Get_Texture_Hint(pass,stage) << W3DTEXTURE_HINT_SHIFT) - & W3DTEXTURE_HINT_MASK); - - // If the shader indicates bump-environment mapping mark this texture as a bumpmap. - if ((stage == 0) && (gamemtl->Get_Pri_Gradient (pass) == W3DSHADER_PRIGRADIENT_BUMPENVMAP)) { - texinfo.Attributes |= W3DTEXTURE_TYPE_BUMPMAP; - } - - texinfo.FrameCount = gamemtl->Get_Texture_Frame_Count(pass,stage); - texinfo.FrameRate = gamemtl->Get_Texture_Frame_Rate(pass,stage); - - if ((texinfo.FrameCount > 1) || (texinfo.Attributes != 0)) { - w3dmap.Set_Anim_Info(&texinfo); - } - - // plug it in and turn on texturing in the shader - Set_Texture(w3dmap,pass,stage); - shader.Texturing = W3DSHADER_TEXTURING_ENABLE; - - // copy over the mapping channel - Set_Map_Channel(pass,stage,gamemtl->Get_Map_Channel(pass,stage)); - - // copy over the mapper args - Set_Mapper_Args(gamemtl->Get_Mapping_Arg_Buffer(pass, stage), pass, stage); - - } else { - if (materialColorTexture) - { //no textures on material, substitute textures to improve rendering speed. - w3dmap.Reset(); - w3dmap.Set_Filename(materialColorTexture); - - // plug it in and turn on texturing in the shader - Set_Texture(w3dmap,pass,stage); - shader.Texturing = W3DSHADER_TEXTURING_ENABLE; - } - break; // break out of the loop (and dont put in stage 1 if stage 0 is missing...) - } - } - - Set_Shader(shader,pass); - Set_Vertex_Material(mat,pass); - } -} - - -bool W3dMaterialClass::Is_Multi_Pass_Transparent(void) const -{ - return ((PassCount >= 2) && (Get_Shader(0).DestBlend != W3DSHADER_DESTBLENDFUNC_ZERO)); -} - - -/* - - - Implementation of W3dMaterialDescClass::VertClass - - -*/ -W3dMaterialDescClass::VertMatClass::VertMatClass(void) : - PassIndex(-1), - Crc(0), - Name(NULL) -{ - for (int stage=0; stage < W3dMaterialClass::MAX_STAGES; ++stage) { - MapperArgs[stage] = NULL; - } -} - -W3dMaterialDescClass::VertMatClass::~VertMatClass(void) -{ - if (Name) free(Name); - - for (int stage=0; stage < W3dMaterialClass::MAX_STAGES; ++stage) { - if (MapperArgs[stage]) { - delete [] (MapperArgs[stage]); - MapperArgs[stage] = NULL; - } - } -} - -W3dMaterialDescClass::VertMatClass & -W3dMaterialDescClass::VertMatClass::operator = (const VertMatClass & that) -{ - if (this != &that) { - Material = that.Material; - PassIndex = that.PassIndex; - Crc = that.Crc; - Set_Name(that.Name); - for (int stage=0; stage < W3dMaterialClass::MAX_STAGES; stage++) { - Set_Mapper_Args(that.MapperArgs[stage], stage); - } - } - return *this; -} - -bool W3dMaterialDescClass::VertMatClass::operator != (const VertMatClass & that) -{ - return !(*this == that); -} - -bool W3dMaterialDescClass::VertMatClass::operator == (const VertMatClass & that) -{ - assert(0); return false; -} - -void W3dMaterialDescClass::VertMatClass::Set_Name(const char * name) -{ - if (Name) free(Name); - - if (name) { - Name = strdup(name); - } else { - Name = NULL; - } -} - -void W3dMaterialDescClass::VertMatClass::Set_Mapper_Args(const char * args, int stage) -{ - if (MapperArgs[stage]) { - delete [] (MapperArgs[stage]); - MapperArgs[stage] = NULL; - } - - if (args) { - int len = strlen(args); - MapperArgs[stage] = new char [len + 1]; - strcpy(MapperArgs[stage], args); - } else { - MapperArgs[stage] = NULL; - } -} - - -/* - - - Implementation of W3dMaterialDescClass - - -*/ -W3dMaterialDescClass::MaterialRemapClass::MaterialRemapClass(void) -{ - PassCount = -1; - for (int pass=0; pass= 0); - assert(vmat_index < VertexMaterials.Count()); - return &(VertexMaterials[vmat_index].Material); -} - -const char * W3dMaterialDescClass::Get_Mapper_Args(int vmat_index, int stage) -{ - assert(vmat_index >= 0); - assert(vmat_index < VertexMaterials.Count()); - assert(stage >= 0); - assert(stage < W3dMaterialClass::MAX_STAGES); - return VertexMaterials[vmat_index].MapperArgs[stage]; -} - -W3dShaderStruct * W3dMaterialDescClass::Get_Shader(int shader_index) -{ - assert(shader_index >= 0); - assert(shader_index < Shaders.Count()); - return &(Shaders[shader_index].Shader); -} - -W3dMapClass * W3dMaterialDescClass::Get_Texture(int texture_index) -{ - assert(texture_index >= 0); - assert(texture_index < Textures.Count()); - return &(Textures[texture_index].Map); -} - -int W3dMaterialDescClass::Get_Vertex_Material_Index(int mat_index,int pass) -{ - assert(mat_index >= 0); - assert(mat_index < MaterialRemaps.Count()); - assert(pass >= 0); - assert(pass < PassCount); - return MaterialRemaps[mat_index].VertexMaterialIdx[pass]; -} - -int W3dMaterialDescClass::Get_Shader_Index(int mat_index,int pass) -{ - assert(mat_index >= 0); - assert(mat_index < MaterialRemaps.Count()); - assert(pass >= 0); - assert(pass < PassCount); - return MaterialRemaps[mat_index].ShaderIdx[pass]; -} - -int W3dMaterialDescClass::Get_Texture_Index(int mat_index,int pass,int stage) -{ - assert(mat_index >= 0); - assert(mat_index < MaterialRemaps.Count()); - assert(pass >= 0); - assert(pass < PassCount); - assert(stage >= 0); - assert(stage < W3dMaterialClass::MAX_STAGES); - return MaterialRemaps[mat_index].TextureIdx[pass][stage]; -} - -W3dVertexMaterialStruct * W3dMaterialDescClass::Get_Vertex_Material(int mat_index,int pass) -{ - int index = Get_Vertex_Material_Index(mat_index,pass); - if (index == -1) { - return NULL; - } else { - return Get_Vertex_Material(index); - } -} - -const char * W3dMaterialDescClass::Get_Mapper_Args(int mat_index,int pass,int stage) -{ - int index = Get_Vertex_Material_Index(mat_index,pass); - if (index == -1) { - return NULL; - } else { - return Get_Mapper_Args(index,stage); - } -} - -W3dShaderStruct * W3dMaterialDescClass::Get_Shader(int mat_index,int pass) -{ - int index = Get_Shader_Index(mat_index,pass); - if (index == -1) { - return NULL; - } else { - return Get_Shader(index); - } -} - -W3dMapClass * W3dMaterialDescClass::Get_Texture(int mat_index,int pass,int stage) -{ - int index = Get_Texture_Index(mat_index,pass,stage); - if (index == -1) { - return NULL; - } else { - return Get_Texture(index); - } -} - -int W3dMaterialDescClass::Get_Map_Channel(int mat_index,int pass,int stage) -{ - return MaterialRemaps[mat_index].MapChannel[pass][stage]; -} - -const char * W3dMaterialDescClass::Get_Vertex_Material_Name(int mat_index,int pass) -{ - int index = Get_Vertex_Material_Index(mat_index,pass); - if (index == -1) { - return NULL; - } else { - return VertexMaterials[index].Name; - } -} - -const char * W3dMaterialDescClass::Get_Vertex_Material_Name(int vmat_index) -{ - return VertexMaterials[vmat_index].Name; -} - -bool W3dMaterialDescClass::Stage_Needs_Texture_Coordinates(int pass,int stage) -{ - for (int mi=0; miFilename == NULL)) { - return -1; - } - - int crc = Compute_Crc(*map); - for (int ti=0; tiAttributes,sizeof(map.AnimInfo->Attributes),crc); - crc = CRC_Memory((const unsigned char *)&map.AnimInfo->AnimType,sizeof(map.AnimInfo->AnimType),crc); - crc = CRC_Memory((const unsigned char *)&map.AnimInfo->FrameCount,sizeof(map.AnimInfo->FrameCount),crc); - crc = CRC_Memory((const unsigned char *)&map.AnimInfo->FrameRate,sizeof(map.AnimInfo->FrameRate),crc); - } - crc = CRC_Stringi(map.Filename, crc); - return crc; -} - -unsigned long W3dMaterialDescClass::Add_String_To_Crc(const char *str, unsigned long in_crc) -{ - unsigned long out_crc = in_crc; - if (str) { - int len = strlen(str); - char *temp = new char[len + 1]; - const char *p_in = str; - - // skip leading spaces, tabs, newlines - for (; *p_in == ' ' || *p_in == '\t' || *p_in == '\r' || *p_in == '\n'; p_in++); - - // copy string, skipping spaces and tabs - char * p_out = temp; - int count = 0; - for (; *p_in; p_in++) { - for (; *p_in == ' ' || *p_in == '\t'; p_in++); - if (!(*p_in)) break; - *p_out = *p_in; - p_out++; - count++; - } - *p_out = 0; - - // Erase any trailing newlines: - if (count) { - // p_out now points to the ending null - make it point to the - // character before it (the last character of the string proper) - p_out--; - - for (; *p_out == '\r' || *p_out == '\n'; p_out--) { - *p_out = '\000'; - count--; - } - } - - out_crc = CRC_Memory((const unsigned char *)temp,count,in_crc); - delete [] temp; - } - return out_crc; -} - - diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dmtl.h b/Generals/Code/Tools/WW3D/max2w3d/w3dmtl.h deleted file mode 100644 index 32d647a0b5..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dmtl.h +++ /dev/null @@ -1,313 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Max2W3d * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dmtl.h $* - * * - * $Author:: Andre_a $* - * * - * $Modtime:: 12/07/00 2:47p $* - * * - * $Revision:: 15 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef W3DMTL_H -#define W3DMTL_H - -#include "always.h" -#include "w3d_file.h" -#include "Vector.H" - -class GameMtl; -class Mtl; -class ChunkSaveClass; - - -/* -** W3dMapClass. -** This class simply ties together the map info and the map filename -*/ -class W3dMapClass -{ -public: - W3dMapClass(void) : Filename(NULL), AnimInfo(NULL) {}; - W3dMapClass(const W3dMapClass & that); - ~W3dMapClass(void); - - W3dMapClass & operator = (const W3dMapClass & that); - - void Reset(void); - void Set_Filename(const char * name); - void Set_Anim_Info(const W3dTextureInfoStruct * info); - void Set_Anim_Info(int framecount,float framerate); - - char * Filename; - W3dTextureInfoStruct * AnimInfo; -}; - - -/* -** W3dMaterialClass. -** This class ties together w3d structures for up to 'MAX_PASSES' material passes. -** It is typically plugged into the next class (W3dMaterialDescClass) so that -** duplicate members can detected and shared. -*/ -class W3dMaterialClass -{ -public: - - W3dMaterialClass(void); - ~W3dMaterialClass(void); - - enum { MAX_PASSES = 4, MAX_STAGES = 2 }; - - void Reset(void); - - /* - ** Construction from Max materials - */ - void Init(Mtl * mtl, char *materialColorTexture=NULL); - void Init(GameMtl * gamemtl, char *materialColorTexture=NULL); - - /* - ** Manual Construction - */ - void Set_Surface_Type(unsigned int type); - void Set_Sort_Level(int level); - void Set_Pass_Count(int count); - void Set_Vertex_Material(const W3dVertexMaterialStruct & vmat,int pass = 0); - void Set_Mapper_Args(const char *args_buffer, int pass = 0, int stage = 0); - void Set_Shader(const W3dShaderStruct & shader,int pass = 0); - void Set_Texture(const W3dMapClass & map,int pass = 0,int stage = 0); - void Set_Map_Channel(int pass,int stage,int channel); - - /* - ** Inspection - */ - unsigned int Get_Surface_Type(void) const; - int Get_Sort_Level(void) const; - int Get_Pass_Count(void) const; - W3dVertexMaterialStruct * Get_Vertex_Material(int pass = 0) const; - const char * Get_Mapper_Args(int pass /*= 0*/, int stage /*= 0*/) const; - W3dShaderStruct Get_Shader(int pass = 0) const; - W3dMapClass * Get_Texture(int pass = 0,int stage = 0) const; - int Get_Map_Channel(int pass = 0,int stage = 0) const; - - bool Is_Multi_Pass_Transparent(void) const; - -protected: - - void Free(void); - - unsigned int SurfaceType; - int SortLevel; - int PassCount; - - W3dShaderStruct Shaders[MAX_PASSES]; - W3dVertexMaterialStruct * Materials[MAX_PASSES]; - char * MapperArgs[MAX_PASSES][MAX_STAGES]; - W3dMapClass * Textures[MAX_PASSES][MAX_STAGES]; - int MapChannel[MAX_PASSES][MAX_STAGES]; - -}; - - -/* -** W3dMaterialDescClass -** This class's purpose is to process the set of w3dmaterials used by a mesh into a set -** of surrender passes with shaders, vertexmaterials, textures. Part of its job is -** to detect duplicated shaders and vertex materials and remove them. -*/ -class W3dMaterialDescClass -{ -public: - - typedef enum ErrorType - { - OK = 0, // material description was built successfully - INCONSISTENT_PASSES, // material doesn't have same number of passes - MULTIPASS_TRANSPARENT, // material is transparent and multi-pass (NO-NO!) - INCONSISTENT_SORT_LEVEL, // material doesn't have the same sort level! - }; - - W3dMaterialDescClass(void); - ~W3dMaterialDescClass(void); - - void Reset(void); - - /* - ** Interface for adding a material description. The material will be assigned - ** an index based on the order at which they are added. Add your materials in - ** order, then use their indices to find the remapped vertex materials, textures, - ** and shaders... - */ - ErrorType Add_Material(const W3dMaterialClass & mat,const char * name = NULL); - - /* - ** Global Information. These methods give access to all of the unique vertex materials, - ** shaders, and textures being used. - */ - int Material_Count(void); - int Pass_Count(void); - int Vertex_Material_Count(void); - int Shader_Count(void); - int Texture_Count(void); - int Get_Sort_Level(void); - - W3dVertexMaterialStruct * Get_Vertex_Material(int vmat_index); - const char * Get_Mapper_Args(int vmat_index, int stage); - W3dShaderStruct * Get_Shader(int shader_index); - W3dMapClass * Get_Texture(int texture_index); - - /* - ** Per-Pass Information. These methods convert a material index and pass index pair into - ** an index to the desired vertex material, texture or shader. - */ - int Get_Vertex_Material_Index(int mat_index,int pass); - int Get_Shader_Index(int mat_index,int pass); - int Get_Texture_Index(int mat_index,int pass,int stage); - W3dVertexMaterialStruct * Get_Vertex_Material(int mat_index,int pass); - const char * Get_Mapper_Args(int mat_index,int pass,int stage); - W3dShaderStruct * Get_Shader(int mat_index,int pass); - W3dMapClass * Get_Texture(int mat_index,int pass,int stage); - int Get_Map_Channel(int mat_index,int pass,int stage); - bool Stage_Needs_Texture_Coordinates(int pass,int stage); - bool Pass_Uses_Vertex_Alpha(int pass); - bool Pass_Uses_Alpha(int pass); - - /* - ** Vertex Material Names. It will be useful to have named vertex materials. I'll keep - ** the name of the first material which contained each vertex material as its name. Use - ** these functions to get the name associated with a vertex material - */ - const char * Get_Vertex_Material_Name(int mat_index,int pass); - const char * Get_Vertex_Material_Name(int vmat_index); - -private: - - int Add_Vertex_Material(W3dVertexMaterialStruct * vmat,const char *mapper_args0,const char *mapper_args1,int pass,const char * name); - int Add_Shader(const W3dShaderStruct & shader,int pass); - int Add_Texture(W3dMapClass * map,int pass,int stage); - unsigned long Compute_Crc(const W3dVertexMaterialStruct & vmat,const char *mapper_args0,const char *mapper_args1); - unsigned long Compute_Crc(const W3dShaderStruct & shader); - unsigned long Compute_Crc(const W3dMapClass & map); - unsigned long Add_String_To_Crc(const char *str, unsigned long crc); - - /* - ** MaterialRemapClass - ** When the user supplies a W3dMaterial to this material description class, - ** its sub-parts are installed and an instance of this class is created to - ** re-index to each one. - */ - class MaterialRemapClass - { - public: - MaterialRemapClass(void); - - bool operator != (const MaterialRemapClass & that); - bool operator == (const MaterialRemapClass & that); - - int PassCount; - int VertexMaterialIdx[W3dMaterialClass::MAX_PASSES]; - int ShaderIdx[W3dMaterialClass::MAX_PASSES]; - int TextureIdx[W3dMaterialClass::MAX_PASSES][W3dMaterialClass::MAX_STAGES]; - int MapChannel[W3dMaterialClass::MAX_PASSES][W3dMaterialClass::MAX_STAGES]; - }; - - /* - ** VertMatClass - ** This class encapsulates a vertex material structure and makes it extendable for - ** any purposes needed by the plugin code. For example, the pass index is stored - ** so that we can prevent "welding" of vertex materials in different passes (since - ** this may not be desireable...) - */ - class VertMatClass - { - public: - VertMatClass(void); - ~VertMatClass(void); - - VertMatClass & operator = (const VertMatClass & that); - bool operator != (const VertMatClass & that); - bool operator == (const VertMatClass & that); - void Set_Name(const char * name); - void Set_Mapper_Args(const char * args, int stage); - - W3dVertexMaterialStruct Material; - char * MapperArgs[W3dMaterialClass::MAX_STAGES]; // note: these strings are new'ed, not malloc'ed (unlike Name) - int PassIndex; // using this to prevent joining of vertmats in different passes. - int Crc; // crc, used for quick rejection when checking for matches. - char * Name; // material name associated with the first occurence of this vmat. - }; - - /* - ** ShadeClass - ** Again, simply here to make the shader extendable for any purposes needed by this - ** pre-processing code... - */ - class ShadeClass - { - public: - ShadeClass & operator = (const ShadeClass & that) { Shader = that.Shader; Crc = that.Crc; return *this;} - bool operator != (const ShadeClass & that) { return !(*this == that); } - bool operator == (const ShadeClass & that) { assert(0); return false; } - - W3dShaderStruct Shader; - int Crc; - }; - - /* - ** TexClass - ** Simply here to allow extra info to be stored with each texture, as needed by this - ** pre-processing code... - */ - class TexClass - { - public: - TexClass & operator = (const TexClass & that) { Map = that.Map; Crc = that.Crc; return *this; } - bool operator != (const TexClass & that) { return !(*this == that); } - bool operator == (const TexClass & that) { assert(0); return false; } - - W3dMapClass Map; - int Crc; - }; - - int PassCount; - int SortLevel; - DynamicVectorClass < MaterialRemapClass > MaterialRemaps; - DynamicVectorClass < ShadeClass > Shaders; - DynamicVectorClass < VertMatClass > VertexMaterials; - DynamicVectorClass < TexClass > Textures; - -}; - - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dutil.cpp b/Generals/Code/Tools/WW3D/max2w3d/w3dutil.cpp deleted file mode 100644 index 584e336e8e..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dutil.cpp +++ /dev/null @@ -1,2047 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3dutil.cpp 45 8/21/01 10:28a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dutil.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/21/01 9:41a $* - * * - * $Revision:: 45 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "w3dutil.h" -#include "w3ddesc.h" -#include "rcmenu.h" -#include "util.h" -#include "nodelist.h" -#include "tchar.h" -#include "gamemtl.h" -#include "notify.h" -#include "gennamesdialog.h" -#include "genmtlnamesdialog.h" -#include "genlodextensiondialog.h" -#include "floaterdialog.h" -#include - - -#define DAZZLE_SETTINGS_FILENAME "dazzle.ini" -#define DAZZLE_TYPES_SECTION "Dazzles_List" -#define DAZZLE_SECTION_BUFFERSIZE 32767 - - -static BOOL CALLBACK _settings_form_dlg_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -static BOOL CALLBACK _w3d_utility_tools_dlg_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); - -static VisibleSelectedINodeFilter _INodeFilter; - - -/********************************************************************************************** -** -** MaterialReferenceMaker - Class to support Export Utilities in the W3D Tools panel. -** -**********************************************************************************************/ -class MaterialReferenceMaker : public ReferenceMaker -{ - public: - - ~MaterialReferenceMaker() {DeleteAllRefs();} - - virtual int NumRefs(); - virtual RefTargetHandle GetReference (int i); - virtual void SetReference (int i, RefTargetHandle rtarg); - RefResult NotifyRefChanged (Interval changeInt,RefTargetHandle hTarget,PartID& partID, RefMessage message); - - Mtl *MaterialPtr; - static int ReferenceCount; -}; - -int MaterialReferenceMaker::NumRefs() -{ - return (ReferenceCount); -} - -RefTargetHandle MaterialReferenceMaker::GetReference (int i) -{ - assert (i < ReferenceCount); - return (MaterialPtr); -} - -void MaterialReferenceMaker::SetReference (int i, RefTargetHandle rtarg) -{ - assert (i < ReferenceCount); - MaterialPtr = (Mtl*) rtarg; -} - -RefResult MaterialReferenceMaker::NotifyRefChanged(Interval changeInt,RefTargetHandle hTarget,PartID& partID, RefMessage message) -{ - return (REF_SUCCEED); -} - -int MaterialReferenceMaker::ReferenceCount; - - -/********************************************************************************************** -** -** SettingsFormClass - code for the W3DUTILITY_SETTINGS_DIALOG. Used in the command panel -** and in the floating settings dialog. -** -**********************************************************************************************/ -class SettingsFormClass -{ -public: - - SettingsFormClass(HWND hwnd); - ~SettingsFormClass(void); - - bool Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM); - void Selection_Changed(void); - - static void Update_All_Instances(void); - -private: - - void Init(void); - void Destroy(void); - void Disable_Controls(void); - void Update_Controls(INodeListClass * nodelist = NULL); - - HWND Hwnd; - ISpinnerControl * RegionSpin; - SettingsFormClass * Next; - - static SettingsFormClass * ActiveList; - -}; - - -/********************************************************************************************** -** -** W3DUtilityClass - Utility plugin which presents windows controls for setting all of -** the W3D export options for the currently selected nodes -** -**********************************************************************************************/ -class W3DUtilityClass : public UtilityObj -{ -public: - - W3DUtilityClass(); - ~W3DUtilityClass(); - - void BeginEditParams(Interface *ip,IUtil *iu); - void EndEditParams(Interface *ip,IUtil *iu); - void SelectionSetChanged(Interface *ip,IUtil *iu); - void DeleteThis() {} - - void Select_Hierarchy(void); - void Select_Geometry(void); - void Select_Alpha(void); - void Select_Physical(void); - void Select_Projectile(void); - void Select_Vis(void); - -public: - - Interface * InterfacePtr; - FloaterDialogClass SettingsFloater; - HWND SettingsPanelHWND; - HWND ToolsPanelHWND; - bool UpdateSpinnerValue; - - GenNamesDialogClass::OptionsStruct NameOptions; - GenMtlNamesDialogClass::OptionsStruct MtlNameOptions; - GenLodExtensionDialogClass::OptionsStruct LodExtensionOptions; - - int WorkingNameIndex; - - enum { - NONE = 0, - HIDE, - SELECT_GEOM, - SELECT_HIER, - SELECT_ALPHA, - SELECT_PHYSICAL, - SELECT_PROJECTILE, - SELECT_VIS, - GENERATE_NAME, - GENERATE_MATERIAL_NAME, - GENERATE_LOD_EXTENSION - }; - - enum MaterialConversionEnum { - GAME_REFERENCE_COUNT, - GAME_TO_STANDARD, - STANDARD_TO_GAME - }; - - struct NodeStatesStruct - { - int ExportHierarchy; - int ExportGeometry; - int GeometryTwoSided; - int GeometryHidden; - int GeometryZNormals; - int GeometryVertexAlpha; - int GeometryCastShadow; - int GeometryShatterable; - int GeometryNPatch; - int CollisionPhysical; - int CollisionProjectile; - int CollisionVis; - int CollisionCamera; - int CollisionVehicle; - bool GeometryCameraAligned; - bool GeometryCameraOriented; - bool GeometryNormal; - bool GeometryAABox; - bool GeometryOBBox; - bool GeometryNull; - bool GeometryDazzle; - bool GeometryAggregate; - - int DamageRegion; - int DazzleCount; - char DazzleType[128]; - }; - - /* - ** Evaluate the status of nodes in the given list - */ - static int eval_tri_state(int totalcount,int oncount); - static void eval_node_states(INodeListClass * node_list,NodeStatesStruct * ns); - - /* - ** Update the controls in any active settings panels - */ - static void update_settings_controls(INodeListClass * node_list = NULL); - - /* - ** Modify the state of all selected nodes - */ - static void set_hierarchy_in_all_selected(INodeListClass * list,bool onoff); - static void set_geometry_in_all_selected(INodeListClass * list,bool onoff); - static void enable_hidden_in_all_selected(INodeListClass * list,bool onoff); - static void enable_two_sided_in_all_selected(INodeListClass * list,bool onoff); - static void enable_znormals_in_all_selected(INodeListClass * list,bool onoff); - static void enable_vertex_alpha_in_all_selected(INodeListClass * list,bool onoff); - static void enable_shadow_in_all_selected(INodeListClass * list,bool onoff); - static void enable_shatterable_in_all_selected(INodeListClass * list,bool onoff); - static void enable_npatches_in_all_selected(INodeListClass * list,bool onoff); - static void enable_physical_collision_in_all_selected(INodeListClass * list,bool onoff); - static void enable_projectile_collision_in_all_selected(INodeListClass * list,bool onoff); - static void enable_vis_collision_in_all_selected(INodeListClass * list,bool onoff); - static void enable_camera_collision_in_all_selected(INodeListClass * list,bool onoff); - static void enable_vehicle_collision_in_all_selected(INodeListClass * list,bool onoff); - - static void set_geometry_type_in_all_selected(INodeListClass * list,int geotype); - static void set_dazzle_type_in_all_selected(INodeListClass * list,char * dazzletype); - - static void set_region_in_all_selected(INodeListClass * list,char region); - - /* - ** Functions used by the tools rollup in the command panel - */ - void descend_tree(INode * node,int action); - void hide_node(INode * node); - void select_geometry_node(INode * node); - void select_hierarchy_node(INode * node); - void select_alpha_node(INode * node); - void select_physical_node(INode * node); - void select_projectile_node(INode * node); - void select_vis_node(INode * node); - bool is_alpha_material(Mtl * nodemtl); - bool is_alpha_mesh(INode * node,Mtl * nodemtl); - - void generate_names(void); - void generate_node_name(INode * node); - void generate_material_names(void); - void generate_material_names_for_node(INode * node); - void generate_material_names(Mtl * mtl); - void generate_lod_extensions(void); - void generate_lod_ext(INode * node); - - void create_floater(void); - - void export_with_standard_materials(); - int convert_materials (MaterialConversionEnum conversion, MaterialReferenceMaker *gamenodematerials); - StdMat * new_standard_material (GameMtl *gamemtl); - - static W3DAppData0Struct * get_app_data_0(INode * node); - static W3DAppData1Struct * get_app_data_1(INode * node); - static W3DAppData2Struct * get_app_data_2(INode * node); - static W3DDazzleAppDataStruct * get_dazzle_app_data(INode * node); -}; - -static W3DUtilityClass TheW3DUtility; - - -/********************************************************************************************** -** -** W3DUtilityClassDesc - Class Descriptor for the W3D Utility -** -**********************************************************************************************/ -class W3DUtilityClassDesc:public ClassDesc -{ -public: - - int IsPublic() { return 1; } - void * Create(BOOL loading = FALSE) { return &TheW3DUtility; } - const TCHAR * ClassName() { return Get_String(IDS_W3D_UTILITY_CLASS_NAME); } - SClass_ID SuperClassID() { return UTILITY_CLASS_ID; } - Class_ID ClassID() { return W3DUtilityClassID; } - const TCHAR* Category() { return Get_String(IDS_W3DMENU_CATEGORY); } -}; - -static W3DUtilityClassDesc W3DUtilityDesc; - -ClassDesc * Get_W3D_Utility_Desc(void) -{ - return &W3DUtilityDesc; -} - -/********************************************************************************************** -** -** W3DUtilityClass Implementation -** -**********************************************************************************************/ -W3DUtilityClass::W3DUtilityClass(void) -{ - InterfacePtr = NULL; - SettingsPanelHWND = NULL; - ToolsPanelHWND = NULL; - UpdateSpinnerValue = true; -} - -W3DUtilityClass::~W3DUtilityClass(void) -{ -} - -void W3DUtilityClass::BeginEditParams(Interface *ip,IUtil *iu) -{ - InterfacePtr = ip; - - SettingsPanelHWND = InterfacePtr->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_W3DUTILITY_SETTINGS_DIALOG), - _settings_form_dlg_proc, - Get_String(IDS_W3DUTILITY_SETTINGS), - 0); - - ToolsPanelHWND = InterfacePtr->AddRollupPage( - AppInstance, - MAKEINTRESOURCE(IDD_W3DUTILITY_TOOLS_DIALOG), - _w3d_utility_tools_dlg_proc, - Get_String(IDS_W3DUTILITY_TOOLS), - 0); - - -// TheRCMenu.Bind(TheW3DUtility.InterfacePtr,&TheW3DUtility); -// RightClickMenuManager *rcm = ip->GetRightClickMenuManager(); -// if (TheRCMenu.Installed!=TRUE) { -// rcm->Register(&TheRCMenu); -// } - - SettingsFormClass::Update_All_Instances(); -} - -void W3DUtilityClass::EndEditParams(Interface *ip,IUtil *iu) -{ - InterfacePtr = NULL; - - ip->DeleteRollupPage(SettingsPanelHWND); - ip->DeleteRollupPage(ToolsPanelHWND); - - SettingsPanelHWND = NULL; - ToolsPanelHWND = NULL; -} - -void W3DUtilityClass::SelectionSetChanged(Interface *ip,IUtil *iu) -{ - // (gth) the settings panels which need to respond to the selection set changing - // are now registered directly with MAX and don't need to be updated here - // update_dialog(); -} - -int W3DUtilityClass::eval_tri_state(int totalcount,int oncount) -{ - if (oncount == 0) { - return 0; - } - if (oncount == totalcount) { - return 1; - } - return 2; -} - -void W3DUtilityClass::eval_node_states(INodeListClass * list,NodeStatesStruct * ns) -{ - // initialize the counters and booleans - ns->ExportHierarchy = 0; - ns->ExportGeometry = 0; - ns->GeometryHidden = 0; - ns->GeometryTwoSided = 0; - ns->GeometryZNormals = 0; - ns->GeometryVertexAlpha = 0; - ns->GeometryCastShadow = 0; - ns->GeometryShatterable = 0; - ns->GeometryNPatch = 0; - ns->CollisionPhysical = 0; - ns->CollisionProjectile = 0; - ns->CollisionVis = 0; - ns->CollisionCamera = 0; - ns->CollisionVehicle = 0; - - ns->GeometryCameraAligned = false; - ns->GeometryCameraOriented = false; - ns->GeometryNormal = false; - ns->GeometryAABox = false; - ns->GeometryOBBox = false; - ns->GeometryNull = false; - ns->GeometryDazzle = false; - ns->GeometryAggregate = false; - - /* - ** ns->DamageRegion will be MAX_DAMAGE_REGIONS if not all - ** of the selected nodes are in the same damage region. If - ** they are, then ns->DamageRegion will be the region they - ** share. - */ - if (list->Num_Nodes() > 0) - { - // Use the first damage region for comparing to the others. - W3DAppData1Struct *wdata = get_app_data_1((*list)[0]); - ns->DamageRegion = wdata->DamageRegion; - } - else - ns->DamageRegion = MAX_DAMAGE_REGIONS; - - /* - ** ns->DazzleType will be DEFAULT if not all of the selected - ** nodes are the same. If they are the same, it will be the - ** dazzle type that they all share - */ - ns->DazzleCount = 0; - if (list->Num_Nodes() > 0) { - W3DDazzleAppDataStruct * dazzledata = get_dazzle_app_data((*list)[0]); - strncpy(ns->DazzleType,dazzledata->DazzleType,sizeof(ns->DazzleType)); - } else { - strcpy(ns->DazzleType,"DEFAULT"); - } - - /* - ** evaluate each node - */ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - - W3DAppData2Struct * wdata = get_app_data_2((*list)[ni]); - assert(wdata); - - ns->ExportHierarchy += (wdata->Is_Bone() ? 1 : 0); - ns->ExportGeometry += (wdata->Is_Geometry() ? 1 : 0); - ns->GeometryHidden += (wdata->Is_Hidden_Enabled() ? 1 : 0); - ns->GeometryTwoSided += (wdata->Is_Two_Sided_Enabled() ? 1 : 0); - ns->GeometryZNormals += (wdata->Is_ZNormals_Enabled() ? 1 : 0); - ns->GeometryVertexAlpha += (wdata->Is_Vertex_Alpha_Enabled() ? 1 : 0); - ns->GeometryCastShadow += (wdata->Is_Shadow_Enabled() ? 1 : 0); - ns->GeometryShatterable += (wdata->Is_Shatterable_Enabled() ? 1 : 0); - ns->GeometryNPatch += (wdata->Is_NPatchable_Enabled() ? 1 : 0); - ns->CollisionPhysical += (wdata->Is_Physical_Collision_Enabled() ? 1 : 0); - ns->CollisionProjectile += (wdata->Is_Projectile_Collision_Enabled() ? 1 : 0); - ns->CollisionVis += (wdata->Is_Vis_Collision_Enabled() ? 1 : 0); - ns->CollisionCamera += (wdata->Is_Camera_Collision_Enabled() ? 1 : 0); - ns->CollisionVehicle += (wdata->Is_Vehicle_Collision_Enabled() ? 1 : 0); - - switch (wdata->Get_Geometry_Type()) { - case W3DAppData2Struct::GEO_TYPE_CAMERA_ALIGNED: ns->GeometryCameraAligned = true; break; - case W3DAppData2Struct::GEO_TYPE_CAMERA_ORIENTED: ns->GeometryCameraOriented = true; break; - case W3DAppData2Struct::GEO_TYPE_NORMAL_MESH: ns->GeometryNormal = true; break; - case W3DAppData2Struct::GEO_TYPE_AABOX: ns->GeometryAABox = true; break; - case W3DAppData2Struct::GEO_TYPE_OBBOX: ns->GeometryOBBox = true; break; - case W3DAppData2Struct::GEO_TYPE_NULL: ns->GeometryNull = true; break; - case W3DAppData2Struct::GEO_TYPE_DAZZLE: ns->GeometryDazzle = true; ns->DazzleCount++; break; - case W3DAppData2Struct::GEO_TYPE_AGGREGATE: ns->GeometryAggregate = true; break; - } - - // Compare this damage region to our existing one. If it's not the same, - // use MAX_DAMAGE_REGION (an invalid value) as a sentinel value. - if (ns->DamageRegion != MAX_DAMAGE_REGIONS) - { - W3DAppData1Struct *wdata1 = get_app_data_1((*list)[ni]); - assert(wdata1); - if (wdata1->DamageRegion != ns->DamageRegion) - ns->DamageRegion = MAX_DAMAGE_REGIONS; - } - - // compare this objects dazzle type to our existing one. If its not - // the same, use 'DEFAULT'. - W3DDazzleAppDataStruct * dazzledata = get_dazzle_app_data((*list)[ni]); - if (strcmp(ns->DazzleType,dazzledata->DazzleType) != 0) { - strcpy(ns->DazzleType,"DEFAULT"); - } - } - - // If any of the counters are zero, that means none of the objects had that - // bit set. If any of them are equal to the number of objects, then they - // all had that bit set. Otherwise, there was a mix and we should use the - // third state for the checkbox (greyed out check). - int count = list->Num_Nodes(); - ns->ExportHierarchy = eval_tri_state(count, ns->ExportHierarchy); - ns->ExportGeometry = eval_tri_state(count, ns->ExportGeometry); - ns->GeometryHidden = eval_tri_state(count, ns->GeometryHidden); - ns->GeometryTwoSided = eval_tri_state(count, ns->GeometryTwoSided); - ns->GeometryZNormals = eval_tri_state(count, ns->GeometryZNormals); - ns->GeometryVertexAlpha = eval_tri_state(count, ns->GeometryVertexAlpha); - ns->GeometryCastShadow = eval_tri_state(count, ns->GeometryCastShadow); - ns->GeometryShatterable = eval_tri_state(count, ns->GeometryShatterable); - ns->GeometryNPatch = eval_tri_state(count, ns->GeometryNPatch); - ns->CollisionPhysical = eval_tri_state(count, ns->CollisionPhysical); - ns->CollisionProjectile = eval_tri_state(count, ns->CollisionProjectile); - ns->CollisionVis = eval_tri_state(count, ns->CollisionVis); - ns->CollisionCamera = eval_tri_state(count, ns->CollisionCamera); - ns->CollisionVehicle = eval_tri_state(count, ns->CollisionVehicle); - -} - -void W3DUtilityClass::update_settings_controls(INodeListClass * node_list) -{ - SettingsFormClass::Update_All_Instances(); -} - -void W3DUtilityClass::set_hierarchy_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Export_Transform(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::set_geometry_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Export_Geometry(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_hidden_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Hidden(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_two_sided_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Two_Sided(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_znormals_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_ZNormals(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_vertex_alpha_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Vertex_Alpha(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_shadow_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Shadow(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_shatterable_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Shatterable(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_npatches_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_NPatchable(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_physical_collision_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Physical_Collision(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_projectile_collision_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Projectile_Collision(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_vis_collision_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Vis_Collision(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_camera_collision_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Camera_Collision(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::enable_vehicle_collision_in_all_selected(INodeListClass * node_list,bool onoff) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Enable_Vehicle_Collision(onoff); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::set_geometry_type_in_all_selected(INodeListClass * node_list,int geotype) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DAppData2Struct * wdata = get_app_data_2((*node_list)[ni]); - wdata->Set_Geometry_Type((W3DAppData2Struct::GeometryTypeEnum)geotype); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::set_dazzle_type_in_all_selected(INodeListClass * node_list,char * dazzle_type) -{ - for (unsigned int ni=0; niNum_Nodes(); ni++) { - W3DDazzleAppDataStruct * dazzledata = get_dazzle_app_data((*node_list)[ni]); - strncpy(dazzledata->DazzleType,dazzle_type,sizeof(dazzledata->DazzleType) - 1); - } - update_settings_controls(node_list); -} - -void W3DUtilityClass::set_region_in_all_selected(INodeListClass * list,char region) -{ - if (list->Num_Nodes() == 0) return; - - // Damage regions are stored in each node's AppData1. - for (int i = 0; i < list->Num_Nodes(); i++) - { - W3DAppData1Struct *wdata = get_app_data_1((*list)[i]); - wdata->DamageRegion = region; - } - update_settings_controls(list); -} - -void W3DUtilityClass::generate_names(void) -{ - GenNamesDialogClass dialog(InterfacePtr); - bool retval = dialog.Get_Options(&NameOptions); - WorkingNameIndex = NameOptions.NameIndex; - - if (retval) { - descend_tree(InterfacePtr->GetRootNode(),GENERATE_NAME); - } -} - -void W3DUtilityClass::generate_material_names(void) -{ - GenMtlNamesDialogClass dialog(InterfacePtr); - bool retval = dialog.Get_Options(&MtlNameOptions); - WorkingNameIndex = MtlNameOptions.NameIndex; - - if (retval) { - descend_tree(InterfacePtr->GetRootNode(),GENERATE_MATERIAL_NAME); - } -} - -void W3DUtilityClass::generate_lod_extensions(void) -{ - GenLodExtensionDialogClass dialog(InterfacePtr); - bool retval = dialog.Get_Options(&LodExtensionOptions); - - if (retval) { - descend_tree(InterfacePtr->GetRootNode(),GENERATE_LOD_EXTENSION); - } -} - -void W3DUtilityClass::generate_lod_ext(INode * node) -{ - /* - ** Only works on selected nodes. - */ - if (!node->Selected()) - return; - - /* - ** If this node already has an LOD extension, we'll replace it - ** with the new LOD index. Otherwise we'll tack it on the end. - ** Display a error message if the name is too long to append - ** the extension, and skip the node without changing the name. - */ - char msg[256]; - char newname[W3D_NAME_LEN]; - char *oldname = node->GetName(); - char *ext = strrchr(oldname, '.'); - int old_lod; - if ( (ext != NULL) && (sscanf(ext, ".%d", &old_lod) == 1) ) - { - /* - ** An existing LOD index. If it's different than the new - ** one, replace it. - */ - if (old_lod == LodExtensionOptions.LodIndex) - return; // same lod index - - /* - ** Room for the new extension? (2 because when we export, the extension will, - ** be replaced by a single character [A..Z] to indicate the LOD level. - ** ie. 2==strlen("A")+1) - */ - if (ext - oldname + 2 <= W3D_NAME_LEN) - { - *ext = '\0'; - sprintf(newname, "%s.%02d", oldname, LodExtensionOptions.LodIndex); - *ext = '.'; - node->SetName(newname); - } - else - { - *ext = '\0'; - sprintf(msg, "The maximum W3D object name is %d characters. Adding the LOD " - "extension to \"%s\" will pass this limit! Please shorten its name.", - W3D_NAME_LEN - 1, oldname); - *ext = '.'; - MessageBox(NULL, msg, "Error", MB_OK); - } - } - else - { - /* - ** Room for the new extension? (2 because when we export, the extension will, - ** be replaced by a single character [A..Z] to indicate the LOD level. - ** ie. 2==strlen("A")+1) - */ - if (strlen(oldname) + 2 <= W3D_NAME_LEN) - { - sprintf(newname, "%s.%02d", oldname, LodExtensionOptions.LodIndex); - node->SetName(newname); - } - else - { - sprintf(msg, "The maximum W3D object name is %d characters. Adding the LOD " - "extension to \"%s\" will pass this limit! Please shorten its name.", - W3D_NAME_LEN - 1, oldname); - MessageBox(NULL, msg, "Error", MB_OK); - } - } -} - -void W3DUtilityClass::create_floater(void) -{ - SettingsFloater.Create(InterfacePtr,IDD_W3DUTILITY_SETTINGS_DIALOG,_settings_form_dlg_proc); - SettingsFormClass::Update_All_Instances(); -} - -void W3DUtilityClass::export_with_standard_materials() -{ - char *convertingmessage = "Converting materials..."; - - // Count the no. of references to game materials. - MaterialReferenceMaker::ReferenceCount = convert_materials (GAME_REFERENCE_COUNT, NULL); - - MaterialReferenceMaker *gamenodematerials = NULL; - - if (MaterialReferenceMaker::ReferenceCount > 0) { - gamenodematerials = new MaterialReferenceMaker [MaterialReferenceMaker::ReferenceCount]; - assert (gamenodematerials != NULL); - } - - InterfacePtr->PushPrompt (convertingmessage); - SetCursor (LoadCursor (NULL, IDC_WAIT)); - convert_materials (GAME_TO_STANDARD, gamenodematerials); - InterfacePtr->PopPrompt(); - InterfacePtr->FileExport(); - UpdateWindow (InterfacePtr->GetMAXHWnd()); - InterfacePtr->PushPrompt (convertingmessage); - SetCursor (LoadCursor (NULL, IDC_WAIT)); - convert_materials (STANDARD_TO_GAME, gamenodematerials); - InterfacePtr->PopPrompt(); - - // Clean-up. - if (gamenodematerials != NULL) delete [] gamenodematerials; -} - -int W3DUtilityClass::convert_materials (MaterialConversionEnum conversion, MaterialReferenceMaker *gamenodematerials) -{ - int gamenodematerialindex = 0; - - INode *rootnode = InterfacePtr->GetRootNode(); - if (rootnode != NULL) { - - INodeListClass *meshlist = new INodeListClass (rootnode, 0); - if (meshlist != NULL) { - - for (unsigned nodeindex = 0; nodeindex < meshlist->Num_Nodes(); nodeindex++) { - - Mtl *nodemtl = ((*meshlist) [nodeindex])->GetMtl(); - - // Is this a non-null material? - if (nodemtl != NULL) { - - // Is this not a multi-material? - if (!nodemtl->IsMultiMtl()) { - - switch (conversion) { - - case GAME_REFERENCE_COUNT: - if (nodemtl->ClassID() == GameMaterialClassID) { - assert (((GameMtl*) nodemtl)->Substitute_Material() == NULL); - } - break; - - case GAME_TO_STANDARD: - - if (nodemtl->ClassID() == GameMaterialClassID) { - - // Make a reference to the game material to ensure that it is not deleted by the system. - gamenodematerials [gamenodematerialindex].MakeRefByID (FOREVER, gamenodematerialindex, nodemtl); - - // Does this material already have an equivalent standard material? - if (((GameMtl*) nodemtl)->Substitute_Material() == NULL) { - ((GameMtl*) nodemtl)->Set_Substitute_Material (new_standard_material ((GameMtl*) nodemtl)); - } - ((*meshlist) [nodeindex])->SetMtl (((GameMtl*) nodemtl)->Substitute_Material()); - - } else { - gamenodematerials [gamenodematerialindex].MaterialPtr = NULL; - } - break; - - case STANDARD_TO_GAME: - - // Change materials to game materials if they were previously game materials before being - // converted to standard materials. - if (gamenodematerials [gamenodematerialindex].MaterialPtr != NULL) { - ((*meshlist) [nodeindex])->SetMtl (gamenodematerials [gamenodematerialindex].MaterialPtr); - ((GameMtl*) gamenodematerials [gamenodematerialindex].MaterialPtr)->Set_Substitute_Material (NULL); - } - break; - } - gamenodematerialindex++; - - } else { - - // For each sub-material... - for (int materialindex = 0; materialindex < nodemtl->NumSubMtls(); materialindex++) { - - Mtl *submaterial = nodemtl->GetSubMtl (materialindex); - - // Is this a non-null submaterial? - if (submaterial != NULL) { - - switch (conversion) { - - case GAME_REFERENCE_COUNT: - if (submaterial->ClassID() == GameMaterialClassID) { - assert (((GameMtl*) submaterial)->Substitute_Material() == NULL); - } - break; - - case GAME_TO_STANDARD: - - if (submaterial->ClassID() == GameMaterialClassID) { - - // Make a reference to the game material to ensure that it is not deleted by the system. - gamenodematerials [gamenodematerialindex].MakeRefByID (FOREVER, gamenodematerialindex, submaterial); - - // Does this material already have an equivalent standard material? - if (((GameMtl*) submaterial)->Substitute_Material() == NULL) { - ((GameMtl*) submaterial)->Set_Substitute_Material (new_standard_material ((GameMtl*) submaterial)); - } - nodemtl->SetSubMtl (materialindex, ((GameMtl*) submaterial)->Substitute_Material()); - - } else { - gamenodematerials [gamenodematerialindex].MaterialPtr = NULL; - } - break; - - case STANDARD_TO_GAME: - - // Change materials to game materials if they were previously game materials before being - // converted to standard materials. - if (gamenodematerials [gamenodematerialindex].MaterialPtr != NULL) { - nodemtl->SetSubMtl (materialindex, gamenodematerials [gamenodematerialindex].MaterialPtr); - ((GameMtl*) gamenodematerials [gamenodematerialindex].MaterialPtr)->Set_Substitute_Material (NULL); - } - break; - } - gamenodematerialindex++; - } - } - } - } - } - - // Clean-up. - delete meshlist; - } - } - - return (gamenodematerialindex); -} - -StdMat *W3DUtilityClass::new_standard_material (GameMtl *gamemtl) -{ - Color emissive; - - // Create a new standard material. - StdMat *stdmtl = NewDefaultStdMat(); - - // Set its properties by translating the supplied game material. - // NOTE 0: Only consider pass 0 in the game material - ignore all other passes. - // NOTE 1: Use defaults for all standard material attributes that cannot be - // converted from the game material in a meaningful way. - stdmtl->SetName (gamemtl->GetName()); - stdmtl->SetAmbient (gamemtl->GetAmbient(), 0); - stdmtl->SetDiffuse (gamemtl->GetDiffuse(), 0); - stdmtl->SetSpecular (gamemtl->GetSpecular(), 0); - stdmtl->SetOpacity (gamemtl->Get_Opacity (0, 0), 0); - stdmtl->SetShininess (gamemtl->Get_Shininess (0, 0), 0); - stdmtl->SetShinStr (gamemtl->GetShinStr(), 0); - stdmtl->SetSubTexmap (ID_DI, gamemtl->Get_Texture (0, 0)); - emissive = gamemtl->Get_Emissive (0, 0); - stdmtl->SetSelfIllum ((emissive.r + emissive.g + emissive.b) / 3.0f, 0); - - return (stdmtl); -} - -void W3DUtilityClass::Select_Hierarchy(void) -{ - InterfacePtr->SelectNode(NULL); - INode * root = InterfacePtr->GetRootNode(); - descend_tree(root,SELECT_HIER); - InterfacePtr->ForceCompleteRedraw(); -} - -void W3DUtilityClass::Select_Geometry(void) -{ - InterfacePtr->SelectNode(NULL); - INode * root = InterfacePtr->GetRootNode(); - descend_tree(root,SELECT_GEOM); - InterfacePtr->ForceCompleteRedraw(); -} - -void W3DUtilityClass::Select_Alpha(void) -{ - InterfacePtr->SelectNode(NULL); - INode * root = InterfacePtr->GetRootNode(); - descend_tree(root,SELECT_ALPHA); - InterfacePtr->ForceCompleteRedraw(); -} - -void W3DUtilityClass::Select_Physical(void) -{ - InterfacePtr->SelectNode(NULL); - INode * root = InterfacePtr->GetRootNode(); - descend_tree(root,SELECT_PHYSICAL); - InterfacePtr->ForceCompleteRedraw(); -} - -void W3DUtilityClass::Select_Projectile(void) -{ - InterfacePtr->SelectNode(NULL); - INode * root = InterfacePtr->GetRootNode(); - descend_tree(root,SELECT_PROJECTILE); - InterfacePtr->ForceCompleteRedraw(); -} - -void W3DUtilityClass::Select_Vis(void) -{ - InterfacePtr->SelectNode(NULL); - INode * root = InterfacePtr->GetRootNode(); - descend_tree(root,SELECT_VIS); - InterfacePtr->ForceCompleteRedraw(); -} - -void W3DUtilityClass::descend_tree(INode * node,int func) -{ - if (!node) return; - - switch (func) - { - case HIDE: - hide_node(node); - break; - - case SELECT_GEOM: - select_geometry_node(node); - break; - - case SELECT_HIER: - select_hierarchy_node(node); - break; - - case SELECT_ALPHA: - select_alpha_node(node); - break; - - case SELECT_PHYSICAL: - select_physical_node(node); - break; - - case SELECT_PROJECTILE: - select_projectile_node(node); - break; - - case SELECT_VIS: - select_vis_node(node); - break; - - case GENERATE_NAME: - generate_node_name(node); - break; - - case GENERATE_MATERIAL_NAME: - generate_material_names_for_node(node); - break; - - case GENERATE_LOD_EXTENSION: - generate_lod_ext(node); - break; - - default: - break; - }; - - for (int i=0; iNumberOfChildren(); i++) { - INode * child = node->GetChildNode(i); - descend_tree(child,func); - } -} - -void W3DUtilityClass::hide_node(INode * node) -{ - if (!node->IsHidden()) node->Hide(TRUE); - InterfacePtr->NodeInvalidateRect(node); -} - -void W3DUtilityClass::select_geometry_node(INode * node) -{ - if (Is_Geometry(node) && !node->IsHidden()) { - InterfacePtr->SelectNode(node,0); - } -} - -void W3DUtilityClass::select_hierarchy_node(INode * node) -{ - if (Is_Bone(node) && !node->IsHidden()) { - InterfacePtr->SelectNode(node,0); - } -} - -void W3DUtilityClass::select_alpha_node(INode * node) -{ - if (node->IsHidden() || !Is_Geometry(node)) { - return; - } - - Mtl * nodemtl = node->GetMtl(); - if (is_alpha_material(nodemtl)) { - if (is_alpha_mesh(node,nodemtl)) { - InterfacePtr->SelectNode(node,0); - } - } -} - -void W3DUtilityClass::select_physical_node(INode * node) -{ - if (!node->IsHidden() && Is_Geometry(node) && Is_Physical_Collision(node)) { - InterfacePtr->SelectNode(node,0); - } -} - -void W3DUtilityClass::select_projectile_node(INode * node) -{ - if (!node->IsHidden() && Is_Geometry(node) && Is_Projectile_Collision(node)) { - InterfacePtr->SelectNode(node,0); - } -} - -void W3DUtilityClass::select_vis_node(INode * node) -{ - if (!node->IsHidden() && Is_Geometry(node) && Is_Vis_Collision(node)) { - InterfacePtr->SelectNode(node,0); - } -} - -bool W3DUtilityClass::is_alpha_material(Mtl * nodemtl) -{ - if (nodemtl == NULL) { - return false; - } - - bool is_alpha = false; - if (nodemtl->IsMultiMtl()) { - for (int mi=0; miNumSubMtls(); mi++) { - is_alpha |= is_alpha_material(nodemtl->GetSubMtl(mi)); - } - } else { - if (nodemtl->ClassID() == GameMaterialClassID) { - GameMtl * gamemtl = (GameMtl *)nodemtl; - - if ( (gamemtl->Get_Dest_Blend(0) == W3DSHADER_DESTBLENDFUNC_SRC_ALPHA) || - (gamemtl->Get_Dest_Blend(0) == W3DSHADER_DESTBLENDFUNC_ONE_MINUS_SRC_ALPHA) || - (gamemtl->Get_Src_Blend(0) == W3DSHADER_SRCBLENDFUNC_SRC_ALPHA) || - (gamemtl->Get_Src_Blend(0) == W3DSHADER_SRCBLENDFUNC_ONE_MINUS_SRC_ALPHA) || - (gamemtl->Get_Alpha_Test(0) == W3DSHADER_ALPHATEST_ENABLE) ) - { - is_alpha = true; - } - } - } - return is_alpha; -} - -bool W3DUtilityClass::is_alpha_mesh(INode * node,Mtl * nodemtl) -{ - Object * obj = node->EvalWorldState(0).obj; - TriObject * tri = (TriObject *)obj->ConvertToType(0, triObjectClassID); - - if (tri != NULL) { - Mesh & mesh = tri->mesh; - - int face_index; - int mat_index; - - if (nodemtl == NULL) { - - return false; - - } else if (nodemtl->NumSubMtls() <= 1) { - - return is_alpha_material(nodemtl); - - } else { - - int sub_mtl_count = nodemtl->NumSubMtls(); - bool * sub_mtl_flags = new bool[sub_mtl_count]; - - // Initialize each sub-material flag to false (indicates that the material is un-used) - for (mat_index=0; mat_indexGetSubMtl(mat_index))) { - return true; - } - } - } - } - } - return false; -} - -void W3DUtilityClass::generate_node_name(INode * node) -{ - TCHAR temp_string[256]; - - if (NameOptions.OnlyAffectSelected && !node->Selected()) { - return; - } - - if (!Is_Bone(node) && !Is_Geometry(node)) { - return; - } - - if (NameOptions.AssignNames) { - _stprintf(temp_string,"%s%03d",NameOptions.RootName,WorkingNameIndex); - node->SetName(temp_string); - WorkingNameIndex++; - } - - if (NameOptions.AssignPrefix) { - _stprintf(temp_string,"%s%s",NameOptions.PrefixName,node->GetName()); - node->SetName(temp_string); - } - - if (NameOptions.AssignSuffix) { - _stprintf(temp_string,"%s%s",node->GetName(),NameOptions.SuffixName); - node->SetName(temp_string); - } - - if (NameOptions.AssignCollisionBits) { - - W3DAppData2Struct * wdata = W3DAppData2Struct::Get_App_Data(node); - assert(wdata); - - wdata->Enable_Physical_Collision(NameOptions.PhysicalCollision); - wdata->Enable_Projectile_Collision(NameOptions.ProjectileCollision); - wdata->Enable_Vis_Collision(NameOptions.VisCollision); - wdata->Enable_Camera_Collision(NameOptions.CameraCollision); - wdata->Enable_Vehicle_Collision(NameOptions.VehicleCollision); - } -} - -void W3DUtilityClass::generate_material_names_for_node(INode * node) -{ - if (MtlNameOptions.OnlyAffectSelected && !node->Selected()) { - return; - } - generate_material_names(node->GetMtl()); -} - -void W3DUtilityClass::generate_material_names(Mtl * mtl) -{ - if (mtl == NULL) { - return; - } - - // set the name of this material and increment the index - TCHAR newname[GenMtlNamesDialogClass::MAX_MATERIAL_NAME_LEN]; - _stprintf(newname,"%s%03d",MtlNameOptions.RootName,WorkingNameIndex); - mtl->SetName(newname); - WorkingNameIndex++; - - // recurse into children - if (mtl->IsMultiMtl()) { - for (int mi=0; miNumSubMtls(); mi++) { - generate_material_names(mtl->GetSubMtl(mi)); - } - } -} - - -W3DAppData0Struct * W3DUtilityClass::get_app_data_0(INode * node) -{ - /* - ** Try to get our AppData which has the export flags - */ - W3DAppData0Struct * wdata = NULL; - AppDataChunk * appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,0); - - /* - ** If there wasn't one, return NULL since this app data chunk is obsolete now. - ** If there was one, get the data from it - */ - if (appdata) { - wdata = (W3DAppData0Struct *)(appdata->data); - } - - return wdata; -} - - -W3DAppData1Struct * W3DUtilityClass::get_app_data_1(INode * node) -{ - // Try to get our AppData which has the damage region - W3DAppData1Struct * wdata = NULL; - AppDataChunk * appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,1); - - // If there wasn't one, add one. If there was one, get the data from it - if (appdata) { - wdata = (W3DAppData1Struct *)(appdata->data); - } else { - wdata = new W3DAppData1Struct; - node->AddAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,1,sizeof(W3DAppData1Struct),wdata); - - appdata = node->GetAppDataChunk(W3DUtilityClassID,UTILITY_CLASS_ID,1); - assert(appdata); - } - - return wdata; -} - - -W3DAppData2Struct * W3DUtilityClass::get_app_data_2(INode * node) -{ - return W3DAppData2Struct::Get_App_Data(node); -} - - -W3DDazzleAppDataStruct * W3DUtilityClass::get_dazzle_app_data(INode * node) -{ - return W3DDazzleAppDataStruct::Get_App_Data(node); -} - - -/********************************************************************************************** -** -** Dialog procs for the W3DUtilityClass -** -**********************************************************************************************/ -static BOOL CALLBACK _w3d_utility_tools_dlg_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - switch (msg) { - - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MOUSEMOVE: - TheW3DUtility.InterfacePtr->RollupMouseMessage(hWnd,msg,wParam,lParam); - break; - - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - /* - ** Buttons - */ - case IDC_SELECT_GEOMETRY: - TheW3DUtility.Select_Geometry(); - break; - - case IDC_SELECT_HIERARCHY: - TheW3DUtility.Select_Hierarchy(); - break; - - case IDC_SELECT_ALPHA_MESHES: - TheW3DUtility.Select_Alpha(); - break; - - case IDC_SELECT_PHYSICAL: - TheW3DUtility.Select_Physical(); - break; - - case IDC_SELECT_PROJECTILE: - TheW3DUtility.Select_Projectile(); - break; - - case IDC_SELECT_VIS: - TheW3DUtility.Select_Vis(); - break; - - case IDC_COLLECTION_NAMES_GENERATE: - TheW3DUtility.generate_names(); - TheW3DUtility.update_settings_controls(); - break; - - case IDC_MATERIAL_NAMES_GENERATE: - TheW3DUtility.generate_material_names(); - TheW3DUtility.update_settings_controls(); - break; - - case IDC_LOD_EXTENSION_GENERATE: - TheW3DUtility.generate_lod_extensions(); - TheW3DUtility.update_settings_controls(); - break; - - case IDC_EXPORT_STANDARD_MATERIALS: - TheW3DUtility.export_with_standard_materials(); - break; - - case IDC_CREATE_SETTINGS_FLOATER: - TheW3DUtility.create_floater(); - break; - } - return TRUE; - } - - default: - return FALSE; - } - return TRUE; -} - - - -/********************************************************************************************** -** -** SettingsFormClass Implementation -** NOTE: When you use the _settings_form_dlg_proc, a SettingsFormClass will automatically -** be allocated and attached to the dialog. You can cause all of the active forms to -** refresh their status by calling Update_All_Instances. The forms will be destroyed when -** the window is destroyed. -** -**********************************************************************************************/ -SettingsFormClass * SettingsFormClass::ActiveList = NULL; - -BOOL CALLBACK _settings_form_dlg_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - if (msg == WM_INITDIALOG) { - SettingsFormClass * form = new SettingsFormClass(hWnd); - ::SetProp(hWnd,"SettingsFormClass",(HANDLE)form); - } - - SettingsFormClass * form = (SettingsFormClass *)::GetProp(hWnd,"SettingsFormClass"); - if (form) { - return form->Dialog_Proc(hWnd,msg,wParam,lParam); - } else { - return FALSE; - } -} - -static void _settings_form_selection_changed_callback(void * param,NotifyInfo * info) -{ - ((SettingsFormClass*)param)->Selection_Changed(); -} - -SettingsFormClass::SettingsFormClass(HWND hwnd) : - Hwnd(hwnd), - RegionSpin(NULL) -{ - /* - ** Link into the active list - */ - Next = ActiveList; - ActiveList = this; - - /* - ** Register with MAX - */ - ::RegisterNotification(_settings_form_selection_changed_callback, this, NOTIFY_SELECTIONSET_CHANGED); -} - -SettingsFormClass::~SettingsFormClass(void) -{ - /* - ** Unregister from MAX - */ - ::UnRegisterNotification(_settings_form_selection_changed_callback, this, NOTIFY_SELECTIONSET_CHANGED); - - /* - ** Unlink from the active list - */ - if (ActiveList == this) { - ActiveList = Next; - } else { - - SettingsFormClass * prev = ActiveList; - SettingsFormClass * cur = ActiveList->Next; - - while ((cur != this) && (cur != NULL)) { - cur = cur->Next; - prev = prev->Next; - } - - assert(cur == this); - if (cur == this) { - prev->Next = cur->Next; - } - } - - Hwnd = NULL; -} - - -void SettingsFormClass::Update_All_Instances(void) -{ - if (ActiveList == NULL) { - return; - } - - /* - ** Build a list of the selected nodes - */ - INodeListClass node_list( ::GetCOREInterface()->GetRootNode(), - ::GetCOREInterface()->GetTime(), - &_INodeFilter ); - - /* - ** Update all settings forms - */ - SettingsFormClass * form = ActiveList; - while (form != NULL) { - form->Update_Controls(&node_list); - form = form->Next; - } -} - - -void SettingsFormClass::Init(void) -{ - // Initialize the contents of the dazzle combo - // Reset the dazzle combo - HWND dazzle_combo = GetDlgItem(Hwnd,IDC_DAZZLE_COMBO); - assert(dazzle_combo != NULL); - SendMessage(dazzle_combo,CB_RESETCONTENT,0,0); - - // Load the section of Dazzle.INI that defines all of the types. The windows function - // that I'm using here, reads in a NULL-terminated string for each entry in the section. Each - // string is of the form 'key=value'. Based on my testing, it appears that windows removes any white - // space before or after the equal sign as well. - char dllpath[_MAX_PATH]; - ::GetModuleFileName(AppInstance,dllpath,sizeof(dllpath)); - char * last_slash = strrchr(dllpath,'\\'); - last_slash++; - strcpy(last_slash,DAZZLE_SETTINGS_FILENAME); - - char * dazzle_types_buffer = new char[DAZZLE_SECTION_BUFFERSIZE]; // max size of a section for Win95 - - ::GetPrivateProfileSection( DAZZLE_TYPES_SECTION, dazzle_types_buffer, DAZZLE_SECTION_BUFFERSIZE, dllpath); - - // Now we need to handle each string in the section buffer; skipping the 'key=' and adding - // the dazzle type name into the combo box. - char * entry = dazzle_types_buffer; - if (entry != NULL) { - while (*entry != NULL) { - entry = strchr(entry,'='); - if (entry != NULL) { - entry++; - ::SendMessage(dazzle_combo,CB_ADDSTRING,0,(LPARAM)entry); - entry += strlen(entry) + 1; - } - } - } else { - ::SendMessage(dazzle_combo,CB_ADDSTRING,0,(LPARAM)"Default"); - } - - ::SendMessage(dazzle_combo,CB_SETCURSEL,(WPARAM)0,0); - - delete dazzle_types_buffer; - - /* - ** Setup the damage region spinner control. - */ - RegionSpin = SetupIntSpinner - ( - Hwnd, - IDC_DAMREG_INDEX_SPIN, - IDC_DAMREG_INDEX_EDIT, - NO_DAMAGE_REGION, MAX_DAMAGE_REGIONS-1, NO_DAMAGE_REGION - ); - -} - -void SettingsFormClass::Destroy(void) -{ - ReleaseISpinner(RegionSpin); - RegionSpin = NULL; -} - -bool SettingsFormClass::Dialog_Proc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) -{ - int check; - - switch (message) { - case WM_INITDIALOG: - Init(); - break; - - case WM_DESTROY: - Destroy(); - delete this; - break; - - case WM_COMMAND: - { - /* - ** handle the tri-state checkboxes. - ** MAKE SURE YOU PUT ANY NEW CHECKBOX ID's IN HERE!!! - */ - int control_id = LOWORD(wParam); - if ( (control_id == IDC_HIERARCHY_CHECK) || - (control_id == IDC_GEOMETRY_CHECK) || - (control_id == IDC_GEOMETRY_HIDE) || - (control_id == IDC_GEOMETRY_TWO_SIDED) || - (control_id == IDC_GEOMETRY_ZNORMALS) || - (control_id == IDC_GEOMETRY_VERTEX_ALPHA) || - (control_id == IDC_GEOMETRY_CAST_SHADOW) || - (control_id == IDC_GEOMETRY_SHATTERABLE) || - (control_id == IDC_GEOMETRY_NPATCH) || - (control_id == IDC_COLLISION_PHYSICAL) || - (control_id == IDC_COLLISION_PROJECTILE) || - (control_id == IDC_COLLISION_VIS) || - (control_id == IDC_COLLISION_CAMERA) || - (control_id == IDC_COLLISION_VEHICLE)) - { - check = !SendDlgItemMessage(hWnd,LOWORD(wParam),BM_GETCHECK,0,0L); - SendDlgItemMessage(hWnd,LOWORD(wParam),BM_SETCHECK,check,0L); - } - - INodeListClass node_list( ::GetCOREInterface()->GetRootNode(), - ::GetCOREInterface()->GetTime(), - &_INodeFilter ); - - - switch (LOWORD(wParam)) - { - /* - ** Tri-State Checkboxes, make sure that the ID of all checkboxes is present - ** in the 'if' statement above! - */ - case IDC_HIERARCHY_CHECK: - W3DUtilityClass::set_hierarchy_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_CHECK: - W3DUtilityClass::set_geometry_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_HIDE: - W3DUtilityClass::enable_hidden_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_TWO_SIDED: - W3DUtilityClass::enable_two_sided_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_ZNORMALS: - W3DUtilityClass::enable_znormals_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_VERTEX_ALPHA: - W3DUtilityClass::enable_vertex_alpha_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_CAST_SHADOW: - W3DUtilityClass::enable_shadow_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_SHATTERABLE: - W3DUtilityClass::enable_shatterable_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_GEOMETRY_NPATCH: - W3DUtilityClass::enable_npatches_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_COLLISION_PHYSICAL: - W3DUtilityClass::enable_physical_collision_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_COLLISION_PROJECTILE: - W3DUtilityClass::enable_projectile_collision_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_COLLISION_VIS: - W3DUtilityClass::enable_vis_collision_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_COLLISION_CAMERA: - W3DUtilityClass::enable_camera_collision_in_all_selected(&node_list,check == BST_CHECKED); - break; - - case IDC_COLLISION_VEHICLE: - W3DUtilityClass::enable_vehicle_collision_in_all_selected(&node_list,check == BST_CHECKED); - break; - - /* - ** Radio buttons for the Geometry type - */ - case IDC_GEOMETRY_NORMAL: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_NORMAL_MESH); - break; - - case IDC_GEOMETRY_CAMERA_ALIGNED: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_CAMERA_ALIGNED); - break; - - case IDC_GEOMETRY_CAMERA_ORIENTED: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_CAMERA_ORIENTED); - break; - - case IDC_GEOMETRY_NULL: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_NULL); - break; - - case IDC_GEOMETRY_AABOX: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_AABOX); - break; - - case IDC_GEOMETRY_OBBOX: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_OBBOX); - break; - - case IDC_GEOMETRY_AGGREGATE: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_AGGREGATE); - break; - - case IDC_GEOMETRY_DAZZLE: - W3DUtilityClass::set_geometry_type_in_all_selected(&node_list,W3DAppData2Struct::GEO_TYPE_DAZZLE); - break; - - /* - ** Dazzle type setting. Whenever the user changes the selected dazzle type, apply - ** the new setting to all selected nodes. - */ - case IDC_DAZZLE_COMBO: - if (HIWORD(wParam) == CBN_SELCHANGE) { - - HWND dazzle_combo = GetDlgItem(hWnd,IDC_DAZZLE_COMBO); - if (dazzle_combo != NULL) { - - char dazzle_type[128]; - int cursel = ::SendMessage(dazzle_combo,CB_GETCURSEL,0,0); - int len = ::SendMessage(dazzle_combo,CB_GETLBTEXTLEN,cursel,0); - if (len < 128) { - ::SendMessage(dazzle_combo,CB_GETLBTEXT,(WPARAM)cursel,(LPARAM)dazzle_type); - W3DUtilityClass::set_dazzle_type_in_all_selected(&node_list,dazzle_type); - } - } - } - break; - - } - return TRUE; - } - - /* - ** Spinners - */ - case CC_SPINNER_CHANGE: - { - INodeListClass node_list( ::GetCOREInterface()->GetRootNode(), - ::GetCOREInterface()->GetTime(), - &_INodeFilter ); - - W3DUtilityClass::set_region_in_all_selected(&node_list,RegionSpin->GetIVal()); - break; - } - - /* - ** Max Custom Edit boxes - */ - case WM_CUSTEDIT_ENTER: - { - INodeListClass node_list( ::GetCOREInterface()->GetRootNode(), - ::GetCOREInterface()->GetTime(), - &_INodeFilter ); - - ICustEdit * edit_ctrl = GetICustEdit(GetDlgItem(hWnd,wParam)); - if (wParam == IDC_OBJ_NAME) { - if (edit_ctrl && node_list.Num_Nodes() == 1) { - char buffer[64]; - edit_ctrl->GetText(buffer,sizeof(buffer)); - node_list[0]->SetName(buffer); - Update_All_Instances(); - } - } - ReleaseICustEdit(edit_ctrl); - break; - } - - - default: - return FALSE; - } - return TRUE; -} - -void SettingsFormClass::Selection_Changed(void) -{ - INodeListClass node_list( ::GetCOREInterface()->GetRootNode(), - ::GetCOREInterface()->GetTime(), - &_INodeFilter ); - - Update_Controls(&node_list); -} - -void SettingsFormClass::Update_Controls(INodeListClass * node_list) -{ - /* - ** Update name of currently selected object - ** "Multiple" if more than one, "None" if no selected objs... - */ - ICustEdit * edit_ctrl = GetICustEdit(GetDlgItem(Hwnd,IDC_OBJ_NAME)); - if (edit_ctrl != NULL) { - if (node_list->Num_Nodes() == 0) { - edit_ctrl->Enable(FALSE); - edit_ctrl->SetText(Get_String(IDS_NO_OBJECT)); - } else if (node_list->Num_Nodes() == 1) { - edit_ctrl->Enable(TRUE); - edit_ctrl->SetText((*node_list)[0]->GetName()); - } else { - edit_ctrl->Enable(FALSE); - edit_ctrl->SetText(Get_String(IDS_MULTIPLE_OBJECTS)); - } - - ReleaseICustEdit(edit_ctrl); - } - - if (node_list->Num_Nodes() == 0) { - Disable_Controls(); - return; - } - - W3DUtilityClass::NodeStatesStruct ns; - W3DUtilityClass::eval_node_states(node_list,&ns); - - /* - ** Enable hierarchy and geometry checks since they are always available - */ - EnableWindow(GetDlgItem(Hwnd,IDC_HIERARCHY_CHECK),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CHECK),TRUE); - - /* - ** Enable/Disable the geometry controls - */ - if (ns.ExportGeometry == 1) { - - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAMERA_ALIGNED),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAMERA_ORIENTED),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NORMAL),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NULL),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_AABOX),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_OBBOX),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_AGGREGATE),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_DAZZLE),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_HIDE),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_TWO_SIDED),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_ZNORMALS),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_VERTEX_ALPHA),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAST_SHADOW),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_SHATTERABLE),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NPATCH),TRUE); - - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PHYSICAL),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PROJECTILE),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VIS),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_CAMERA),TRUE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VEHICLE),TRUE); - - } else { - - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAMERA_ALIGNED),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAMERA_ORIENTED),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NORMAL),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NULL),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_AABOX),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_OBBOX),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_AGGREGATE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_DAZZLE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_HIDE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_TWO_SIDED),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_ZNORMALS),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_VERTEX_ALPHA),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAST_SHADOW),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_SHATTERABLE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NPATCH),FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PHYSICAL),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PROJECTILE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VIS),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_CAMERA),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VEHICLE),FALSE); - } - - /* - ** Set the checks based on the nodes states: - ** no check - none of the selected nodes had this setting - ** check - all of the selected nodes had this setting - ** grey check - some of the selected nodes had this setting - */ - SendDlgItemMessage(Hwnd,IDC_HIERARCHY_CHECK,BM_SETCHECK,ns.ExportHierarchy,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_CHECK,BM_SETCHECK,ns.ExportGeometry,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_HIDE,BM_SETCHECK,ns.GeometryHidden,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_TWO_SIDED,BM_SETCHECK,ns.GeometryTwoSided,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_ZNORMALS,BM_SETCHECK,ns.GeometryZNormals,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_VERTEX_ALPHA,BM_SETCHECK,ns.GeometryVertexAlpha,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_CAST_SHADOW,BM_SETCHECK,ns.GeometryCastShadow,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_SHATTERABLE,BM_SETCHECK,ns.GeometryShatterable,0L); - SendDlgItemMessage(Hwnd,IDC_GEOMETRY_NPATCH,BM_SETCHECK,ns.GeometryNPatch,0L); - SendDlgItemMessage(Hwnd,IDC_COLLISION_PHYSICAL,BM_SETCHECK,ns.CollisionPhysical,0L); - SendDlgItemMessage(Hwnd,IDC_COLLISION_PROJECTILE,BM_SETCHECK,ns.CollisionProjectile,0L); - SendDlgItemMessage(Hwnd,IDC_COLLISION_VIS,BM_SETCHECK,ns.CollisionVis,0L); - SendDlgItemMessage(Hwnd,IDC_COLLISION_CAMERA,BM_SETCHECK,ns.CollisionCamera,0L); - SendDlgItemMessage(Hwnd,IDC_COLLISION_VEHICLE,BM_SETCHECK,ns.CollisionVehicle,0L); - - /* - ** The damage region spinner should only be enabled if - ** Export Hierarchy is checked for all selected nodes. - */ - BOOL spinner_enable = false; - if (ns.ExportHierarchy == 1) - { - if (ns.DamageRegion != MAX_DAMAGE_REGIONS) - { - // Show the damage region in the spinner. - RegionSpin->SetIndeterminate(FALSE); - RegionSpin->SetValue(ns.DamageRegion, FALSE); - } - else - { - // The selected objects aren't all in the same region. - RegionSpin->SetIndeterminate(TRUE); - } - - spinner_enable = true; - } - EnableWindow(GetDlgItem(Hwnd,IDC_DAMREG_INDEX_EDIT),spinner_enable); - EnableWindow(GetDlgItem(Hwnd,IDC_DAMREG_INDEX_SPIN),spinner_enable); - - /* - ** The dazzle combo box should only be enabled if - ** Export Geometry, and geometry type dazzle is set for all - ** selected nodes. - */ - bool dazzle_combo_enable = false; - if (ns.ExportGeometry == 1) { - if (ns.DazzleCount == node_list->Num_Nodes()) { - dazzle_combo_enable = true; - } - } - HWND dazzle_combo = GetDlgItem(Hwnd,IDC_DAZZLE_COMBO); - EnableWindow(dazzle_combo,dazzle_combo_enable); - int selindex = ::SendMessage(dazzle_combo,CB_FINDSTRING,(WPARAM)0,(LPARAM)ns.DazzleType); - if (selindex != CB_ERR) { - ::SendMessage(dazzle_combo,CB_SETCURSEL,(WPARAM)selindex,(LPARAM)0); - } else { - ::SendMessage(dazzle_combo,CB_SETCURSEL,(WPARAM)0,(LPARAM)0); - } - - /* - ** Set any radio buttons present - */ - CheckDlgButton(Hwnd,IDC_GEOMETRY_CAMERA_ALIGNED,(ns.GeometryCameraAligned ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_CAMERA_ORIENTED,(ns.GeometryCameraOriented ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_NORMAL,(ns.GeometryNormal ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_NULL,(ns.GeometryNull ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_AABOX,(ns.GeometryAABox ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_OBBOX,(ns.GeometryOBBox ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_AGGREGATE,(ns.GeometryAggregate ? BST_CHECKED : BST_UNCHECKED)); - CheckDlgButton(Hwnd,IDC_GEOMETRY_DAZZLE,(ns.GeometryDazzle ? BST_CHECKED : BST_UNCHECKED)); -} - - -void SettingsFormClass::Disable_Controls(void) -{ - EnableWindow(GetDlgItem(Hwnd,IDC_OBJ_NAME),FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_HIERARCHY_CHECK),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CHECK),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_DAMREG_INDEX_EDIT),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_DAMREG_INDEX_SPIN),FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NORMAL),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAMERA_ALIGNED),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAMERA_ORIENTED),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_AABOX),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_OBBOX),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NULL),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_AGGREGATE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_DAZZLE),FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_HIDE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_TWO_SIDED),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_ZNORMALS),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_VERTEX_ALPHA),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_CAST_SHADOW),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_SHATTERABLE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_GEOMETRY_NPATCH),FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PHYSICAL),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_PROJECTILE),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VIS),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_CAMERA),FALSE); - EnableWindow(GetDlgItem(Hwnd,IDC_COLLISION_VEHICLE),FALSE); - - EnableWindow(GetDlgItem(Hwnd,IDC_DAZZLE_COMBO),FALSE); - - CheckDlgButton(Hwnd,IDC_HIERARCHY_CHECK,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_CHECK,BST_UNCHECKED); - - CheckDlgButton(Hwnd,IDC_GEOMETRY_CAMERA_ALIGNED,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_CAMERA_ORIENTED,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_NORMAL,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_AABOX,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_OBBOX,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_NULL,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_AGGREGATE,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_DAZZLE,BST_UNCHECKED); - - CheckDlgButton(Hwnd,IDC_GEOMETRY_HIDE,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_TWO_SIDED,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_ZNORMALS,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_VERTEX_ALPHA,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_CAST_SHADOW,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_SHATTERABLE,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_GEOMETRY_NPATCH,BST_UNCHECKED); - - CheckDlgButton(Hwnd,IDC_COLLISION_PHYSICAL,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_PROJECTILE,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_VIS,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_CAMERA,BST_UNCHECKED); - CheckDlgButton(Hwnd,IDC_COLLISION_VEHICLE,BST_UNCHECKED); -} - - -/* -** Functions to access the W3D AppData of any INode. -*/ -W3DAppData0Struct * GetW3DAppData0 (INode *node) -{ - return TheW3DUtility.get_app_data_0(node); -} - -W3DAppData1Struct * GetW3DAppData1 (INode *node) -{ - return TheW3DUtility.get_app_data_1(node); -} - -W3DAppData2Struct * GetW3DAppData2 (INode *node) -{ - return TheW3DUtility.get_app_data_2(node); -} - -W3DDazzleAppDataStruct * GetW3DDazzleAppData(INode *node) -{ - return TheW3DUtility.get_dazzle_app_data(node); -} diff --git a/Generals/Code/Tools/WW3D/max2w3d/w3dutil.h b/Generals/Code/Tools/WW3D/max2w3d/w3dutil.h deleted file mode 100644 index 005ba6230d..0000000000 --- a/Generals/Code/Tools/WW3D/max2w3d/w3dutil.h +++ /dev/null @@ -1,130 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3dutil.h 29 10/26/00 5:59p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/w3dutil.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/26/00 4:40p $* - * * - * $Revision:: 29 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef W3DUTIL_H -#define W3DUTIL_H - -#include -#include "utilapi.h" -#include "dllmain.h" -#include "resource.h" -#include "util.h" -#include "w3dappdata.h" - -#define W3DUtilityClassID Class_ID(0x3c362c97, 0x5fc73ab0) - -ClassDesc * Get_W3D_Utility_Desc(void); - - - -/* -** W3dExportOptionsStruct - This structure is AppData that is attached -** not to an INode, but to the exporter class itself. It stores the -** export settings so that they come up the same next time, which -** facilitates batch exporting (just use the stored settings). -** -** WWScript.dlx uses this structure to tell if a scene depends on -** the HTree exported by another scene. -*/ -struct W3dExportOptionsStruct -{ - bool ExportHierarchy; - bool LoadHierarchy; - bool ExportAnimation; - bool ExportGeometry; - - // Hierarchy Export options: - bool TranslationOnly; - char HierarchyFilename[_MAX_PATH]; - char RelativeHierarchyFilename[_MAX_PATH]; // For storing in MAX file - - // Animation Export options: - int StartFrame; - int EndFrame; - - // Geometry Export options; - bool UseVoxelizer; - - // Option to apply smoothing between mesh boundaries - bool SmoothBetweenMeshes; - - int space[10]; // blank space, so compression options default proper - - // More Animation Options - bool CompressAnimation; - bool ReduceAnimation; - int ReduceAnimationPercent; - int CompressAnimationFlavor; - float CompressAnimationTranslationError; - float CompressAnimationRotationError; - bool ReviewLog; - - // Option to prevent the exporter from exporting AABTrees with the meshes - // Defined with the "inverse" sense so that older Max files default to having - // AABTrees exported with their meshes. - bool DisableExportAABTrees; - - // Option to cause the exporter to optimize mesh data. Defaulting to zero - // causes older Max files to default to not messing with their mesh data. - bool EnableOptimizeMeshData; - - // Option to cause the exporter to ignore the Export_Transform setting for - // all meshes. Terrains should have all meshes exported in world space. - bool EnableTerrainMode; - - // Option to cause the exporter to generate textures from all materials using - // only diffuse color (no textures). All such material colors will be placed - // into one texture page to improve batch rendering of models. - bool EnableMaterialColorToTextureConversion; -}; - - - - -/* -** Functions to access the W3D AppData of any INode. -** An accessor function for each AppData we define is required. -** Our extensions to the MAXScript language (wwCopyAppData) -** uses these accessors. -*/ -W3DAppData0Struct * GetW3DAppData0 (INode *node); -W3DAppData1Struct * GetW3DAppData1 (INode *node); -W3DAppData2Struct * GetW3DAppData2 (INode *node); -W3DDazzleAppDataStruct * GetW3DDazzleAppData(INode *node); - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/CMakeLists.txt b/Generals/Code/Tools/WW3D/pluglib/CMakeLists.txt deleted file mode 100644 index 11d7770c53..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -set(PLUGLIB_SRC - "aaplane.h" - "always.h" - "BITTYPE.H" - "bool.h" - "borlandc.h" - "chunkio.cpp" - "chunkio.h" - "errclass.h" - "EULER.CPP" - "EULER.H" - "hashcalc.h" - "hsv.cpp" - "hsv.h" - "iostruct.h" - "jshell.cpp" - "matrix3d.cpp" - "matrix3d.h" - "matrix4.cpp" - "matrix4.h" - "nodefilt.cpp" - "nodefilt.h" - "nodelist.cpp" - "nodelist.h" - "noinit.h" - "palette.cpp" - "palette.h" - "plane.h" - "PROGRESS.H" - "rawfile.cpp" - "rawfile.h" - "realcrc.cpp" - "realcrc.h" - "rgb.cpp" - "rgb.h" - "uarray.h" - "Vector.CPP" - "Vector.H" - "vector2.h" - "vector3.h" - "vector3i.h" - "vector4.h" - "visualc.h" - "w3d_file.h" - "w3dquat.cpp" - "w3dquat.h" - "watcom.h" - "win.h" - "wwfile.h" - "wwmath.cpp" - "wwmath.h" - "WWmatrix3.cpp" - "WWmatrix3.h" -) - -add_library(g_pluglib STATIC) -set_target_properties(g_pluglib PROPERTIES OUTPUT_NAME pluglib) - -target_sources(g_pluglib PRIVATE ${PLUGLIB_SRC}) - -target_link_libraries(g_pluglib PRIVATE maxsdk) diff --git a/Generals/Code/Tools/WW3D/pluglib/EULER.CPP b/Generals/Code/Tools/WW3D/pluglib/EULER.CPP deleted file mode 100644 index 281baf84a6..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/EULER.CPP +++ /dev/null @@ -1,334 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/EULER.CPP 5 12/02/97 10:14p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/EULER.CPP $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/13/97 7:16p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "EULER.H" -#include - - -/********************************************************************* - - There are 24 possible conventions for Euler angles. They can - be designated by: - - EulerAxis = Axis used initially - EulerParity = parity of axis permutation (even = x,y,z) - EulerRepeat = is last axis a repeat of the initial axis? - EulerFrame = frame from which axes are taken (rotating or static) - -*********************************************************************/ - -#define EULER_FRAME_STATIC 0x00000000 -#define EULER_FRAME_ROTATING 0x00000001 -#define EULER_FRAME(order) ((unsigned)(order) & 1) - -#define EULER_REPEAT_NO 0x00000000 -#define EULER_REPEAT_YES 0x00000001 -#define EULER_REPEAT(order) (((unsigned)(order) >> 1) & 1) - -#define EULER_PARITY_EVEN 0x00000000 -#define EULER_PARITY_ODD 0x00000001 -#define EULER_PARITY(order) (((unsigned)(order) >> 2) & 1) - -#define EULER_BUILD_ORDER(i,p,r,f) (((((((i) << 1) + (p)) << 1) + (r)) << 1) + (f)) - - -/* static axes */ -int EulerOrderXYZs = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderXYXs = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderXZYs = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderXZXs = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderYZXs = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderYZYs = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderYXZs = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderYXYs = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderZXYs = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderZXZs = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_STATIC); -int EulerOrderZYXs = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_STATIC); -int EulerOrderZYZs = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_STATIC); - -/* rotating axes */ -int EulerOrderZYXr = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderXYXr = EULER_BUILD_ORDER(0, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderYZXr = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderXZXr = EULER_BUILD_ORDER(0, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderXZYr = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderYZYr = EULER_BUILD_ORDER(1, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderZXYr = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderYXYr = EULER_BUILD_ORDER(1, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderYXZr = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderZXZr = EULER_BUILD_ORDER(2, EULER_PARITY_EVEN, EULER_REPEAT_YES, EULER_FRAME_ROTATING); -int EulerOrderXYZr = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_NO, EULER_FRAME_ROTATING); -int EulerOrderZYZr = EULER_BUILD_ORDER(2, EULER_PARITY_ODD, EULER_REPEAT_YES, EULER_FRAME_ROTATING); - -/* local functions */ -static void _euler_unpack_order(int order,int &i,int &j,int &k,int &h,int &n,int &s,int &f); -static int _euler_axis_i(int order); -static int _euler_axis_j(int order); -static int _euler_axis_k(int order); -static int _euler_axis_h(int order); -static void _mat_to_array(const Matrix3 & tm, float M[3][4]); -static void _array_to_mat(float M[3][4], Matrix3 & tm); - - - -EulerAnglesClass::EulerAnglesClass(const Matrix3 & M,int order) -{ - this->From_Matrix(M,order); -} - -double EulerAnglesClass::Get_Angle(int i) -{ - return Angle[i]; -} - -void EulerAnglesClass::From_Matrix(const Matrix3 & tm, int order) -{ - float M[3][4]; - _mat_to_array(tm,M); - - int i,j,k,h,n,s,f; - - Order = order; - _euler_unpack_order(order,i,j,k,h,n,s,f); - - if (s == EULER_REPEAT_YES) { - double sy = sqrt(M[i][j]*M[i][j] + M[i][k]*M[i][k]); - - if (sy > 16*FLT_EPSILON) { - - Angle[0] = atan2(M[i][j],M[i][k]); - Angle[1] = atan2(sy,M[i][i]); - Angle[2] = atan2(M[j][i],-M[k][i]); - - } else { - - Angle[0] = atan2(-M[j][k],M[j][j]); - Angle[1] = atan2(sy,M[i][i]); - Angle[2] = 0.0; - } - - } else { - - double cy = sqrt(M[i][i]*M[i][i] + M[j][i]*M[j][i]); - - if (cy > 16*FLT_EPSILON) { - - Angle[0] = atan2(M[k][j],M[k][k]); - Angle[1] = atan2(-M[k][i],cy); - Angle[2] = atan2(M[j][i],M[i][i]); - - } else { - - Angle[0] = atan2(-M[j][k],M[j][j]); - Angle[1] = atan2(-M[k][i],cy); - Angle[2] = 0; - } - } - - if (n==EULER_PARITY_ODD) { Angle[0] = -Angle[0]; Angle[1] = -Angle[1]; Angle[2] = -Angle[2]; } - if (f==EULER_FRAME_ROTATING) { double t = Angle[0]; Angle[0] = Angle[2]; Angle[2] = t; } - - // Trying to "clean" up the eulers, special cased for XYZr - if (order == EulerOrderXYZr) { - - double x2 = PI + Angle[0]; - double y2 = PI - Angle[1]; - double z2 = PI + Angle[2]; - - if (x2 > PI) { - x2 = x2 - 2*PI; - } - - if (y2 > PI) { - y2 = y2 - 2*PI; - } - - if (z2 > PI) { - z2 = z2 - 2*PI; - } - - double mag0 = Angle[0]*Angle[0] + Angle[1]*Angle[1] + Angle[2]*Angle[2]; - double mag1 = x2*x2 + y2*y2 + z2*z2; - - if (mag1 < mag0) { - Angle[0] = x2; - Angle[1] = y2; - Angle[2] = z2; - } - } -} - - - -void EulerAnglesClass::To_Matrix(Matrix3 & tm) -{ - float M[3][4] = { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - }; - - double a0,a1,a2; - double ti,tj,th,ci,cj,ch,si,sj,sh,cc,cs,sc,ss; - int i,j,k,h,n,s,f; - - a0 = Angle[0]; - a1 = Angle[1]; - a2 = Angle[2]; - - _euler_unpack_order(Order,i,j,k,h,n,s,f); - if (f == EULER_FRAME_ROTATING) { - double t = a0; a0 = a2; a2 = t; - } - - if (n == EULER_PARITY_ODD) { - a0 = -a0; a1 = -a1; a2 = -a2; - } - - ti = a0; tj = a1; th = a2; - ci = cos(ti); cj = cos(tj); ch = cos(th); - si = sin(ti); sj = sin(tj); sh = sin(th); - - cc = ci*ch; - cs = ci*sh; - sc = si*ch; - ss = si*sh; - - if (s == EULER_REPEAT_YES) { - - M[i][i] = (float)(cj); M[i][j] = (float)(sj*si); M[i][k] = (float)(sj*ci); - M[j][i] = (float)(sj*sh); M[j][j] = (float)(-cj*ss+cc); M[j][k] = (float)(-cj*cs-sc); - M[k][i] = (float)(-sj*ch); M[k][j] = (float)(cj*sc+cs); M[k][k] = (float)(cj*cc-ss); - - } else { - - M[i][i] = (float)(cj*ch); M[i][j] = (float)(sj*sc-cs); M[i][k] = (float)(sj*cc+ss); - M[j][i] = (float)(cj*sh); M[j][j] = (float)(sj*ss+cc); M[j][k] = (float)(sj*cs-sc); - M[k][i] = (float)(-sj); M[k][j] = (float)(cj*si); M[k][k] = (float)(cj*ci); - - } - _array_to_mat(M,tm); -} - - -static int _euler_safe[] = { 0,1,2,0 }; -static int _euler_next[] = { 1,2,0,1 }; - -int _euler_axis_i(int order) -{ - return _euler_safe[ (order>>3) & 3 ]; -} - -int _euler_axis_j(int order) -{ - int index = _euler_axis_i(order); - if (EULER_PARITY(order) == 1) { - index++; - } - - return _euler_next[ index ]; -} - -int _euler_axis_k(int order) -{ - int index = _euler_axis_i(order); - if (EULER_PARITY(order) != 1) { - index++; - } - - return _euler_next[ index ]; -} - -int _euler_axis_h(int order) -{ - if (EULER_REPEAT(order) == 1) { - return _euler_axis_k(order); - } else { - return _euler_axis_i(order); - } -} - -void _euler_unpack_order(int order,int &i,int &j,int &k,int &h,int &n,int &s,int &f) -{ - - f = order & 1; - order >>= 1; - - s = order & 1; - order >>= 1; - - n = order & 1; - order >>= 1; - - i = _euler_safe[order & 3]; - j = _euler_next[i+n]; - k = _euler_next[i+1-n]; - h = (s ? k : i); -} - -void _mat_to_array(const Matrix3 & tm, float M[3][4]) -{ - // Translation vector - Point3 trans = tm.GetRow(3); - M[0][3] = trans.x; - M[1][3] = trans.y; - M[2][3] = trans.z; - - // Rotation matrix - for (int k=0; k<3; k++) { - Point3 v = tm.GetRow(k); - M[0][k] = v.x; - M[1][k] = v.y; - M[2][k] = v.z; - } -} - -void _array_to_mat(float M[3][4], Matrix3 & tm) -{ - // translation - Point3 row(M[3][0],M[3][1],M[3][2]); - tm.SetRow(3, row); - - // rotation - for (int k=0; k<3; k++) { - row = Point3(M[0][k],M[1][k],M[2][k]); - tm.SetRow(k, row); - } -} - - diff --git a/Generals/Code/Tools/WW3D/pluglib/EULER.H b/Generals/Code/Tools/WW3D/pluglib/EULER.H deleted file mode 100644 index da992b5add..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/EULER.H +++ /dev/null @@ -1,119 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/EULER.H 3 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Engine * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/EULER.H $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 10/14/97 3:08p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef EULER_H -#define EULER_H - -#include - - -/********************************************************************* - - Euler Order Types - - When creating an EulerAngles object, use one of the below - constants to describe the axis convention. - - XYZ - order of the axes - s/r - whether the rotations are applied to the static or - rotating frame. - -*********************************************************************/ - -/* static axes */ -extern int EulerOrderXYZs; -extern int EulerOrderXYXs; -extern int EulerOrderXZYs; -extern int EulerOrderXZXs; -extern int EulerOrderYZXs; -extern int EulerOrderYZYs; -extern int EulerOrderYXZs; -extern int EulerOrderYXYs; -extern int EulerOrderZXYs; -extern int EulerOrderZXZs; -extern int EulerOrderZYXs; -extern int EulerOrderZYZs; - -/* rotating axes */ -extern int EulerOrderXYZr; -extern int EulerOrderXYXr; -extern int EulerOrderXZYr; -extern int EulerOrderXZXr; -extern int EulerOrderYZXr; -extern int EulerOrderYZYr; -extern int EulerOrderYXZr; -extern int EulerOrderYXYr; -extern int EulerOrderZXYr; -extern int EulerOrderZXZr; -extern int EulerOrderZYXr; -extern int EulerOrderZYZr; - - -/********************************************************************* - - EulerAnglesClass - - The purpose for this class is mainly for conversion. You can - choose a convention for the order of your rotations and then - convert matrices into a set of euler angles. - - This implementation is based on the code in Graphics Gems IV - by Ken Shoemake. The original article is on page 222. - -*********************************************************************/ -class EulerAnglesClass -{ - -public: - - EulerAnglesClass(void) : Order(0) { Angle[0] = 0.0; Angle[1] = 0.0; Angle[2] = 0.0; }; - EulerAnglesClass(const Matrix3 & from,int order); - void From_Matrix(const Matrix3 & from,int order); - void To_Matrix(Matrix3 & M); - - double Get_Angle(int i); - -private: - - double Angle[3]; - int Order; - -}; - - -#endif /*EULER_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/PROGRESS.H b/Generals/Code/Tools/WW3D/pluglib/PROGRESS.H deleted file mode 100644 index f25dd1362b..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/PROGRESS.H +++ /dev/null @@ -1,125 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/PROGRESS.H 5 10/28/97 6:08p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D engine * - * * - * File Name : PROGRESS.H * - * * - * Programmer : James McNeil * - * * - * Start Date : 06/19/97 * - * * - * Last Update : June 19, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef PROGRESS_H -#define PROGRESS_H - -#include "always.h" - -class Progress_Meter_Class -{ -public: - - Progress_Meter_Class - ( - Interface * gi, - float base, - float range - ): - Max ( gi ), - Base ( base ), - Range ( range ), - Amount_Done ( 0.0f ), - Increment ( 0.0f ), - Accum( 0.0f ), - Cancel_Requested ( FALSE ) - { - } - - Progress_Meter_Class ( Progress_Meter_Class & other, float sub_amount ): - Max ( other.Max ), - Base ( other.Base + other.Amount_Done * other.Range ), - Range ( other.Range * sub_amount ), - Amount_Done ( 0.0f ), - Increment ( 0.0f ), - Accum ( other.Accum ), - Cancel_Requested ( other.Cancel_Requested ) - { - } - - void Finish_In_Steps ( int number_of_steps ) - { - Increment = (1.0f - Amount_Done) / number_of_steps; - } - - void Add_Increment () - { - Set_Amount_Done ( Amount_Done + Increment ); - } - - void Set_Amount_Done ( float percentage ) - { - Accum += percentage; - Amount_Done = percentage; - if (Accum > 0.01f) { - Max->ProgressUpdate ( (int) (Amount_Done * Range + Base) ); - Accum = 0.0f; - } - - if (Max->GetCancel()) - { - int choice = MessageBox - ( - Max->GetMAXHWnd(), - _T("Do you really want to cancel the export?"), - _T("Cancel Export?"), MB_ICONQUESTION | MB_YESNO - ); - - if ( choice == IDYES ) - Cancel_Requested = TRUE; - else - Max->SetCancel ( FALSE ); - } - } - - BOOL Cancelled () { return Cancel_Requested; } - - float Increment; - -private: - - Interface * Max; - - float Base; - float Range; - float Amount_Done; - float Accum; - - BOOL Cancel_Requested; -}; - -#endif /* PROGRESS_H */ diff --git a/Generals/Code/Tools/WW3D/pluglib/Vector.CPP b/Generals/Code/Tools/WW3D/pluglib/Vector.CPP deleted file mode 100644 index 7db77d1a69..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/Vector.CPP +++ /dev/null @@ -1,355 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/Tools/pluglib/Vector.CPP $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 3/29/98 10:42a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * BooleanVectorClass::BooleanVectorClass -- Copy constructor for boolean array. * - * BooleanVectorClass::BooleanVectorClass -- Explicit data buffer constructor. * - * BooleanVectorClass::Clear -- Resets boolean vector to empty state. * - * BooleanVectorClass::Fixup -- Updates the boolean vector to a known state. * - * BooleanVectorClass::Reset -- Clear all boolean values in array. * - * BooleanVectorClass::Resize -- Resizes a boolean vector object. * - * BooleanVectorClass::Set -- Forces all boolean elements to true. * - * BooleanVectorClass::operator = -- Assignment operator. * - * BooleanVectorClass::operator == -- Comparison operator for boolean vector. * - * VectorClass::Clear -- Frees and clears the vector. * - * VectorClass::ID -- Finds object ID based on value. * - * VectorClass::ID -- Pointer based conversion to index number. * - * VectorClass::Resize -- Changes the size of the vector. * - * VectorClass::VectorClass -- Constructor for vector class. * - * VectorClass::VectorClass -- Copy constructor for vector object. * - * VectorClass::operator = -- The assignment operator. * - * VectorClass::operator == -- Equality operator for vector objects. * - * VectorClass::~VectorClass -- Default destructor for vector class. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "always.h" -#include "Vector.H" -#include - -/* -** The following template function can be located here ONLY if all the instantiations are -** declared in a header file this module includes. By placing the template functions here, -** it speeds up compiler operation and reduces object module size. -*/ - -//---------------------------------------------------------------------------------------------- - -/*********************************************************************************************** - * BooleanVectorClass::BooleanVectorClass -- Explicit data buffer constructor. * - * * - * This is the constructor for a boolean array. This constructor takes the memory pointer * - * provided as assigns that as the array data pointer. * - * * - * INPUT: size -- The size of the array (in bits). * - * * - * array -- Pointer to the memory that the array is to use. * - * * - * OUTPUT: none * - * * - * WARNINGS: You must make sure that the memory specified is large enough to contain the * - * bits specified. * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -BooleanVectorClass::BooleanVectorClass(unsigned size, unsigned char * array) : - BitCount(size), - Copy(false), - LastIndex(-1), - BitArray(0, 0) -{ - BitArray.Resize(((size + (8-1)) / 8), array); -// LastIndex = -1; -// BitCount = size; -} - - -/*********************************************************************************************** - * BooleanVectorClass::BooleanVectorClass -- Copy constructor of boolean array. * - * * - * This is the copy constructor for a boolean array. It is used to make a duplicate of the * - * boolean array. * - * * - * INPUT: vector -- Reference to the vector to be duplicated. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -BooleanVectorClass::BooleanVectorClass(BooleanVectorClass const & vector) -{ - LastIndex = -1; - *this = vector; -} - - -/*********************************************************************************************** - * BooleanVectorClass::operator = -- Assignment operator. * - * * - * This routine will make a copy of the specified boolean vector array. The vector is * - * copied into an already constructed existing vector. The values from the existing vector * - * are destroyed by this copy. * - * * - * INPUT: vector -- Reference to the vector to make a copy of. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -BooleanVectorClass & BooleanVectorClass::operator =(BooleanVectorClass const & vector) -{ - Fixup(); - Copy = vector.Copy; - LastIndex = vector.LastIndex; - BitArray = vector.BitArray; - BitCount = vector.BitCount; - return(*this); -} - - -/*********************************************************************************************** - * BooleanVectorClass::operator == -- Comparison operator for boolean vector. * - * * - * This is the comparison operator for a boolean vector class. Boolean vectors are equal * - * if the bit count and bit values are identical. * - * * - * INPUT: vector -- Reference to the vector to compare to. * - * * - * OUTPUT: Are the boolean vectors identical? * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -bool BooleanVectorClass::operator == (const BooleanVectorClass & vector) -{ - Fixup(LastIndex); - return(BitCount == vector.BitCount && BitArray == vector.BitArray); -} - - -/*********************************************************************************************** - * BooleanVectorClass::Resize -- Resizes a boolean vector object. * - * * - * This routine will resize the boolean vector object. An index value used with a boolean * - * vector must be less than the value specified in as the new size. * - * * - * INPUT: size -- The new maximum size of this boolean vector. * - * * - * OUTPUT: Was the boolean vector sized successfully? * - * * - * WARNINGS: The boolean array might be reallocated or even deleted by this routine. * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -int BooleanVectorClass::Resize(unsigned size) -{ - Fixup(); - - if (size > 0) { - - /* - ** Record the previous bit count of the boolean vector. This is used - ** to determine if the array has grown in size and thus clearing is - ** necessary. - */ - unsigned oldsize = BitCount; - - /* - ** Actually resize the bit array. Since this is a bit packed array, - ** there are 8 elements per byte (rounded up). - */ - int success = BitArray.Resize(((size + (8-1)) / 8)); - - /* - ** Since there is no default constructor for bit packed integers, a manual - ** clearing of the bits is required. - */ - BitCount = size; - if (success && oldsize < size) { - for (unsigned index = oldsize; index < size; index++) { - (*this)[index] = 0; - } - } - - return(success); - } - - /* - ** Resizing to zero is the same as clearing and deallocating the array. - ** This is always successful. - */ - Clear(); - return(true); -} - - -/*********************************************************************************************** - * BooleanVectorClass::Clear -- Resets boolean vector to empty state. * - * * - * This routine will clear out the boolean array. This will free any allocated memory and * - * result in the boolean vector being unusable until the Resize function is subsequently * - * called. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: The boolean vector cannot be used until it is resized to a non null condition. * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -void BooleanVectorClass::Clear(void) -{ - Fixup(); - BitCount = 0; - BitArray.Clear(); -} - - -/*********************************************************************************************** - * BooleanVectorClass::Reset -- Clear all boolean values in array. * - * * - * This is the preferred (and quick) method to clear the boolean array to a false condition.* - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -void BooleanVectorClass::Reset(void) -{ - LastIndex = -1; - if (BitArray.Length() > 0) { - memset(&BitArray[0], '\0', BitArray.Length()); - } -} - - -/*********************************************************************************************** - * BooleanVectorClass::Set -- Forces all boolean elements to true. * - * * - * This is the preferred (and fast) way to set all boolean elements to true. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -void BooleanVectorClass::Set(void) -{ - LastIndex = -1; - if (BitArray.Length() > 0) { - memset(&BitArray[0], '\xFF', BitArray.Length()); - } -} - - -/*********************************************************************************************** - * BooleanVectorClass::Fixup -- Updates the boolean vector to a known state. * - * * - * Use this routine to set the boolean value copy to match the appropriate bit in the * - * boolean array. The boolean array will be updated with any changes from the last time * - * a value was fetched from the boolean vector. By using this update method, the boolean * - * array can be treated as a normal array even though the elements are composed of * - * otherwise inaccessible bits. * - * * - * INPUT: index -- The index to set the new copy value to. If the index is -1, then the * - * previous value will be updated into the vector array, but no new value * - * will be fetched from it. * - * * - * OUTPUT: none * - * * - * WARNINGS: Always call this routine with "-1" if any direct manipulation of the bit * - * array is to occur. This ensures that the bit array is accurate. * - * * - * HISTORY: * - * 07/18/1995 JLB : Created. * - *=============================================================================================*/ -void BooleanVectorClass::Fixup(int index) const -{ - /* - ** If the requested index value is illegal, then force the index - ** to be -1. This is the default non-index value. - */ - if ((unsigned)index >= (unsigned)BitCount) { - index = -1; - } - - /* - ** If the new index is different than the previous index, there might - ** be some fixing up required. - */ - if (index != LastIndex) { - - /* - ** If the previously fetched boolean value was changed, then update - ** the boolean array accordingly. - */ - if (LastIndex != -1) { - assert(unsigned(LastIndex) < unsigned(BitCount)); - Set_Bit((void*)&BitArray[0], LastIndex, Copy); - } - - /* - ** If this new current index is valid, then fill in the reference boolean - ** value with the appropriate data from the bit array. - */ - if (index != -1) { - assert(unsigned(index) < unsigned(BitCount)); - ((unsigned char &)Copy) = (unsigned char)Get_Bit((void*)&BitArray[0], index); -// ((unsigned char&)Copy) = Get_Bit((void*)&BitArray[0], index); - } - - ((BooleanVectorClass *)this)->LastIndex = index; - } -} - - diff --git a/Generals/Code/Tools/WW3D/pluglib/Vector.H b/Generals/Code/Tools/WW3D/pluglib/Vector.H deleted file mode 100644 index 38057cf85a..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/Vector.H +++ /dev/null @@ -1,1006 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/Library/Vector.H $* - * * - * $Author:: Byon_g $* - * * - * $Modtime:: 3/12/98 2:09p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * VectorClass::VectorClass -- Constructor for vector class. * - * VectorClass::~VectorClass -- Default destructor for vector class. * - * VectorClass::VectorClass -- Copy constructor for vector object. * - * VectorClass::operator = -- The assignment operator. * - * VectorClass::operator == -- Equality operator for vector objects. * - * VectorClass::Clear -- Frees and clears the vector. * - * VectorClass::Resize -- Changes the size of the vector. * - * DynamicVectorClass::DynamicVectorClass -- Constructor for dynamic vector. * - * DynamicVectorClass::Resize -- Changes the size of a dynamic vector. * - * DynamicVectorClass::Add -- Add an element to the vector. * - * DynamicVectorClass::Delete -- Remove the specified object from the vector. * - * DynamicVectorClass::Delete -- Deletes the specified index from the vector. * - * VectorClass::ID -- Pointer based conversion to index number. * - * VectorClass::ID -- Finds object ID based on value. * - * DynamicVectorClass::ID -- Find matching value in the dynamic vector. * - * DynamicVectorClass::Uninitialized_Add -- Add an empty place to the vector. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef VECTOR_H -#define VECTOR_H - -#include "noinit.h" -#include -#include -#include -#include -#include - - -/************************************************************************** -** This is a general purpose vector class. A vector is defined by this -** class, as an array of arbitrary objects where the array can be dynamically -** sized. Because is deals with arbitrary object types, it can handle everything. -** As a result of this, it is not terribly efficient for integral objects (such -** as char or int). It will function correctly, but the copy constructor and -** equality operator could be highly optimized if the integral type were known. -** This efficiency can be implemented by deriving an integral vector template -** from this one in order to supply more efficient routines. -*/ - -// Why, oh why does Visual C need this!!! It's bugged. -#pragma warning(disable : 4505) - - -template -class VectorClass -{ - public: - VectorClass(NoInitClass const &) {}; - VectorClass(int size=0, T const * array=0); - VectorClass(VectorClass const &); // Copy constructor. - virtual ~VectorClass(void); - - T & operator[](int index) {assert(unsigned(index) < unsigned(VectorMax));return(Vector[index]);}; - T const & operator[](int index) const {assert(unsigned(index) < unsigned(VectorMax));return(Vector[index]);}; - VectorClass & operator = (VectorClass const &); // Assignment operator. - - virtual bool operator == (VectorClass const &) const; // Equality operator. - - virtual bool Resize(int newsize, T const * array=0); - virtual void Clear(void); - int Length(void) const {return VectorMax;}; - virtual int ID(T const * ptr); // Pointer based identification. - virtual int ID(T const & ptr); // Value based identification. - - protected: - - /* - ** This is a pointer to the allocated vector array of elements. - */ - T * Vector; - - /* - ** This is the maximum number of elements allowed in this vector. - */ - int VectorMax; - - /* - ** This indicates if the vector is in a valid (even if empty) state. - */ - bool IsValid; - - /* - ** Does the vector data pointer refer to memory that this class has manually - ** allocated? If so, then this class is responsible for deleting it. - */ - bool IsAllocated; -}; - - -/*********************************************************************************************** - * VectorClass::VectorClass -- Constructor for vector class. * - * * - * This constructor for the vector class is passed the initial size of the vector and an * - * optional pointer to a preallocated block of memory that the vector will be placed in. * - * If this optional pointer is NULL (or not provided), then the vector is allocated out * - * of free store (with the "new" operator). * - * * - * INPUT: size -- The number of elements to initialize this vector to. * - * * - * array -- Optional pointer to a previously allocated memory block to hold the * - * vector. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -VectorClass::VectorClass(int size, T const * array) : - Vector(0), - VectorMax(size), - IsValid(true), - IsAllocated(false) -{ - /* - ** Allocate the vector. The default constructor will be called for every - ** object in this vector. - */ - if (size) { - if (array) { - Vector = new((void*)array) T[size]; - } else { - Vector = new T[size]; - IsAllocated = true; - } - } -} - - -/*********************************************************************************************** - * VectorClass::~VectorClass -- Default destructor for vector class. * - * * - * This is the default destructor for the vector class. It will deallocate any memory * - * that it may have allocated. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -VectorClass::~VectorClass(void) -{ - VectorClass::Clear(); -} - - -/*********************************************************************************************** - * VectorClass::VectorClass -- Copy constructor for vector object. * - * * - * This is the copy constructor for the vector class. It will duplicate the provided * - * vector into the new vector being created. * - * * - * INPUT: vector -- Reference to the vector to use as a copy. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -VectorClass::VectorClass(VectorClass const & vector) : - Vector(0), - VectorMax(0), - IsValid(true), - IsAllocated(false) -{ - *this = vector; -} - - -/*********************************************************************************************** - * VectorClass::operator = -- The assignment operator. * - * * - * This the the assignment operator for vector objects. It will alter the existing lvalue * - * vector to duplicate the rvalue one. * - * * - * INPUT: vector -- The rvalue vector to copy into the lvalue one. * - * * - * OUTPUT: Returns with reference to the newly copied vector. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -VectorClass & VectorClass::operator =(VectorClass const & vector) -{ - if (this != &vector) { - Clear(); - VectorMax = vector.Length(); - if (VectorMax) { - Vector = new T[VectorMax]; - if (Vector) { - IsAllocated = true; - for (int index = 0; index < VectorMax; index++) { - Vector[index] = vector[index]; - } - } - } else { - Vector = 0; - IsAllocated = false; - } - } - return(*this); -} - - -/*********************************************************************************************** - * VectorClass::operator == -- Equality operator for vector objects. * - * * - * This operator compares two vectors for equality. It does this by performing an object * - * by object comparison between the two vectors. * - * * - * INPUT: vector -- The right vector expression. * - * * - * OUTPUT: bool; Are the two vectors essentially equal? (do they contain comparable elements * - * in the same order?) * - * * - * WARNINGS: The equality operator must exist for the objects that this vector contains. * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -bool VectorClass::operator == (VectorClass const & vector) const -{ - if (VectorMax == vector.Length()) { - for (int index = 0; index < VectorMax; index++) { - if (Vector[index] != vector[index]) { - return(false); - } - } - return(true); - } - return(false); -} - - -/*********************************************************************************************** - * VectorClass::ID -- Pointer based conversion to index number. * - * * - * Use this routine to convert a pointer to an element in the vector back into the index * - * number of that object. This routine ONLY works with actual pointers to object within * - * the vector. For "equivalent" object index number (such as with similar integral values) * - * then use the "by value" index number ID function. * - * * - * INPUT: pointer -- Pointer to an actual object in the vector. * - * * - * OUTPUT: Returns with the index number for the object pointed to by the parameter. * - * * - * WARNINGS: This routine is only valid for actual pointers to object that exist within * - * the vector. All other object pointers will yield undefined results. * - * * - * HISTORY: * - * 03/13/1995 JLB : Created. * - *=============================================================================================*/ -template -inline int VectorClass::ID(T const * ptr) -{ - if (!IsValid) return(0); - return(((unsigned long)ptr - (unsigned long)&(*this)[0]) / sizeof(T)); -} - - -/*********************************************************************************************** - * VectorClass::ID -- Finds object ID based on value. * - * * - * Use this routine to find the index value of an object with equivalent value in the * - * vector. Typical use of this would be for integral types. * - * * - * INPUT: object -- Reference to the object that is to be looked up in the vector. * - * * - * OUTPUT: Returns with the index number of the object that is equivalent to the one * - * specified. If no matching value could be found then -1 is returned. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/13/1995 JLB : Created. * - *=============================================================================================*/ -template -int VectorClass::ID(T const & object) -{ - if (!IsValid) return(0); - - for (int index = 0; index < VectorMax; index++) { - if ((*this)[index] == object) { - return(index); - } - } - return(-1); -} - - -/*********************************************************************************************** - * VectorClass::Clear -- Frees and clears the vector. * - * * - * Use this routine to reset the vector to an empty (non-allocated) state. A vector will * - * free all allocated memory when this routine is called. In order for the vector to be * - * useful after this point, the Resize function must be called to give it element space. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -void VectorClass::Clear(void) -{ - if (Vector && IsAllocated) { - delete[] Vector; - Vector = 0; - } - IsAllocated = false; - VectorMax = 0; -} - - -/*********************************************************************************************** - * VectorClass::Resize -- Changes the size of the vector. * - * * - * This routine is used to change the size (usually to increase) the size of a vector. This * - * is the only way to increase the vector's working room (number of elements). * - * * - * INPUT: newsize -- The desired size of the vector. * - * * - * array -- Optional pointer to a previously allocated memory block that the * - * array will be located in. If this parameter is not supplied, then * - * the array will be allocated from free store. * - * * - * OUTPUT: bool; Was the array resized successfully? * - * * - * WARNINGS: Failure to succeed could be the result of running out of memory. * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -bool VectorClass::Resize(int newsize, T const * array) -{ - if (newsize) { - - /* - ** Allocate a new vector of the size specified. The default constructor - ** will be called for every object in this vector. - */ - T * newptr; - - /* - ** Either create a new memory block for the object array or initialize - ** an existing block as indicated by the array parameter. When creating a new - ** memory block, flag that the vector object is currently in an invalid - ** state. This is necessary because the default constructor for the object - ** elements may look to the vector to fetch their ID number. - */ - IsValid = false; - if (!array) { - newptr = new T[newsize]; - } else { - newptr = new((void*)array) T[newsize]; - } - IsValid = true; - if (!newptr) { - return(false); - } - - /* - ** If there is an old vector, then it must be copied (as much as is feasible) - ** to the new vector. - */ - if (Vector != NULL) { - - /* - ** Copy as much of the old vector into the new vector as possible. This - ** presumes that there is a functional assignment operator for each - ** of the objects in the vector. - */ - int copycount = (newsize < VectorMax) ? newsize : VectorMax; - for (int index = 0; index < copycount; index++) { - newptr[index] = Vector[index]; - } - - /* - ** Delete the old vector. This might cause the destructors to be called - ** for all of the old elements. This makes the implementation of suitable - ** assignment operator very important. The default assignment operator will - ** only work for the simplest of objects. - */ - if (IsAllocated) { - delete[] Vector; - Vector = 0; - } - } - - /* - ** Assign the new vector data to this class. - */ - Vector = newptr; - VectorMax = newsize; - IsAllocated = (Vector && !array); - - } else { - - /* - ** Resizing to zero is the same as clearing the vector. - */ - Clear(); - } - return(true); -} - - - -/************************************************************************** -** This derivative vector class adds the concept of adding and deleting -** objects. The objects are packed to the beginning of the vector array. -** If this is instantiated for a class object, then the assignment operator -** and the equality operator must be supported. If the vector allocates its -** own memory, then the vector can grow if it runs out of room adding items. -** The growth rate is controlled by setting the growth step rate. A growth -** step rate of zero disallows growing. -*/ -template -class DynamicVectorClass : public VectorClass -{ -protected: - using VectorClass::IsAllocated; - using VectorClass::Vector; - using VectorClass::VectorMax; - public: - using VectorClass::Length; - - public: - DynamicVectorClass(unsigned size=0, T const * array=0); - - // Change maximum size of vector. - virtual bool Resize(int newsize, T const * array=0); - - // Resets and frees the vector array. - virtual void Clear(void) {ActiveCount = 0;VectorClass::Clear();}; - - // Fetch number of "allocated" vector objects. - int Count(void) const {return(ActiveCount);}; - - // Add object to vector (growing as necessary). - bool Add(T const & object); - bool Add_Head(T const & object); - - // Delete object just like this from vector. - bool Delete(T const & object); - - // Delete object at this vector index. - bool Delete(int index); - - // Deletes all objects in the vector. - void Delete_All(void) {ActiveCount = 0;}; - - // Set amount that vector grows by. - int Set_Growth_Step(int step) {return(GrowthStep = step);}; - - // Fetch current growth step rate. - int Growth_Step(void) {return GrowthStep;}; - - virtual int ID(T const * ptr) {return(VectorClass::ID(ptr));}; - virtual int ID(T const & ptr); - - DynamicVectorClass & operator =(DynamicVectorClass const & rvalue) { - VectorClass::operator = (rvalue); - ActiveCount = rvalue.ActiveCount; - GrowthStep = rvalue.GrowthStep; - return(*this); - } - - // Uninitialized Add - does everything an Add does, except copying an - // object into the 'new' spot in the array. It returns a pointer to - // the 'new' spot. (NULL if the Add failed). NOTE - you must then fill - // this memory area with a valid object (e.g. by using placement new), - // or chaos will result! - T * Uninitialized_Add(void); - - protected: - - /* - ** This is a count of the number of active objects in this - ** vector. The memory array often times is bigger than this - ** value. - */ - int ActiveCount; - - /* - ** If there is insufficient room in the vector array for a new - ** object to be added, then the vector will grow by the number - ** of objects specified by this value. This is controlled by - ** the Set_Growth_Step() function. - */ - int GrowthStep; -}; - - -/*********************************************************************************************** - * DynamicVectorClass::DynamicVectorClass -- Constructor for dynamic vector. * - * * - * This is the normal constructor for the dynamic vector class. It is similar to the normal * - * vector class constructor. The vector is initialized to contain the number of elements * - * specified in the "size" parameter. The memory is allocated from free store unless the * - * optional array parameter is provided. In this case it will place the vector at the * - * memory location specified. * - * * - * INPUT: size -- The maximum number of objects allowed in this vector. * - * * - * array -- Optional pointer to the memory area to place the vector at. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -DynamicVectorClass::DynamicVectorClass(unsigned size, T const * array) - : VectorClass(size, array) -{ - GrowthStep = 10; - ActiveCount = 0; -} - - -/*********************************************************************************************** - * DynamicVectorClass::Resize -- Changes the size of a dynamic vector. * - * * - * Use this routine to change the size of the vector. The size changed is the maximum * - * number of allocated objects within this vector. If a memory buffer is provided, then * - * the vector will be located there. Otherwise, the memory will be allocated out of free * - * store. * - * * - * INPUT: newsize -- The desired maximum size of this vector. * - * * - * array -- Optional pointer to a previously allocated memory array. * - * * - * OUTPUT: bool; Was vector successfully resized according to specifications? * - * * - * WARNINGS: Failure to resize the vector could be the result of lack of free store. * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -bool DynamicVectorClass::Resize(int newsize, T const * array) -{ - if (VectorClass::Resize(newsize, array)) { - if (Length() < ActiveCount) ActiveCount = Length(); - return(true); - } - return(false); -} - - -/*********************************************************************************************** - * DynamicVectorClass::ID -- Find matching value in the dynamic vector. * - * * - * Use this routine to find a matching object (by value) in the vector. Unlike the base * - * class ID function of similar name, this one restricts the scan to the current number * - * of valid objects. * - * * - * INPUT: object -- A reference to the object that a match is to be found in the * - * vector. * - * * - * OUTPUT: Returns with the index number of the object that is equivalent to the one * - * specified. If no equivalent object could be found then -1 is returned. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/13/1995 JLB : Created. * - *=============================================================================================*/ -template -int DynamicVectorClass::ID(T const & object) -{ - for (int index = 0; index < Count(); index++) { - if ((*this)[index] == object) return(index); - } - return(-1); -} - - -/*********************************************************************************************** - * DynamicVectorClass::Add -- Add an element to the vector. * - * * - * Use this routine to add an element to the vector. The vector will automatically be * - * resized to accomodate the new element IF the vector was allocated previously and the * - * growth rate is not zero. * - * * - * INPUT: object -- Reference to the object that will be added to the vector. * - * * - * OUTPUT: bool; Was the object added successfully? If so, the object is added to the end * - * of the vector. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -bool DynamicVectorClass::Add(T const & object) -{ - if (ActiveCount >= Length()) { - if ((IsAllocated || !VectorMax) && GrowthStep > 0) { - if (!Resize(Length() + GrowthStep)) { - - /* - ** Failure to increase the size of the vector is an error condition. - ** Return with the error flag. - */ - return(false); - } - } else { - - /* - ** Increasing the size of this vector is not allowed! Bail this - ** routine with the error code. - */ - return(false); - } - } - - /* - ** There is room for the new object now. Add it to the end of the object vector. - */ - (*this)[ActiveCount++] = object; - return(true); -} - - -/*********************************************************************************************** - * DynamicVectorClass::Add_Head -- Adds element to head of the list. * - * * - * This routine will add the specified element to the head of the vector. If necessary, * - * the vector will be expanded accordingly. * - * * - * INPUT: object -- Reference to the object to add to the head of this vector. * - * * - * OUTPUT: bool; Was the object added without error? * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 09/21/1995 JLB : Created. * - *=============================================================================================*/ -template -bool DynamicVectorClass::Add_Head(T const & object) -{ - if (ActiveCount >= Length()) { - if ((IsAllocated || !VectorMax) && GrowthStep > 0) { - if (!Resize(Length() + GrowthStep)) { - - /* - ** Failure to increase the size of the vector is an error condition. - ** Return with the error flag. - */ - return(false); - } - } else { - - /* - ** Increasing the size of this vector is not allowed! Bail this - ** routine with the error code. - */ - return(false); - } - } - - /* - ** There is room for the new object now. Add it to the end of the object vector. - */ - if (ActiveCount) { - memmove(&(*this)[1], &(*this)[0], ActiveCount * sizeof(T)); - } - (*this)[0] = object; - ActiveCount++; -// (*this)[ActiveCount++] = object; - return(true); -} - - -/*********************************************************************************************** - * DynamicVectorClass::Delete -- Remove the specified object from the vector. * - * * - * This routine will delete the object referenced from the vector. All objects in the * - * vector that follow the one deleted will be moved "down" to fill the hole. * - * * - * INPUT: object -- Reference to the object in this vector that is to be deleted. * - * * - * OUTPUT: bool; Was the object deleted successfully? This should always be true. * - * * - * WARNINGS: Do no pass a reference to an object that is NOT part of this vector. The * - * results of this are undefined and probably catastrophic. * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -bool DynamicVectorClass::Delete(T const & object) -{ - int id = ID(object); - if (id != -1) { - return(Delete(id)); - } - return(false); -} - - -/*********************************************************************************************** - * DynamicVectorClass::Delete -- Deletes the specified index from the vector. * - * * - * Use this routine to delete the object at the specified index from the objects in the * - * vector. This routine will move all the remaining objects "down" in order to fill the * - * hole. * - * * - * INPUT: index -- The index number of the object in the vector that is to be deleted. * - * * - * OUTPUT: bool; Was the object index deleted successfully? Failure might mean that the index * - * specified was out of bounds. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 03/10/1995 JLB : Created. * - *=============================================================================================*/ -template -bool DynamicVectorClass::Delete(int index) -{ - if (index < ActiveCount) { - ActiveCount--; - - /* - ** If there are any objects past the index that was deleted, copy those - ** objects down in order to fill the hole. A simple memory copy is - ** not sufficient since the vector could contain class objects that - ** need to use the assignment operator for movement. - */ - for (int i = index; i < ActiveCount; i++) { - (*this)[i] = (*this)[i+1]; - } - return(true); - } - return(false); -} - - -/*********************************************************************************************** - * DynamicVectorClass::Uninitialized_Add -- Add an empty place to the vector. * - * * - * To avoid copying when creating an object and adding it to the vector, use this and * - * immediately fill the area that the return value points to with a valid object (by hand * - * for a struct or by using placement new for a class object). * - * This function does everything Add does except copying an object into the new space, * - * thus leaving an uninitialized area of memory. * - * * - * INPUT: none. * - * * - * OUTPUT: T *; Points to the empty space where the new object is to be created. (If the * - * space was not added succesfully, returns NULL). * - * * - * WARNINGS: If memory area is left uninitialized, Very Bad Things will happen. * - * * - * HISTORY: * - * 03/04/1998 NH : Created. * - *=============================================================================================*/ -template -T * DynamicVectorClass::Uninitialized_Add(void) -{ - if (ActiveCount >= Length()) { - if ((IsAllocated || !VectorMax) && GrowthStep > 0) { - if (!Resize(Length() + GrowthStep)) { - - /* - ** Failure to increase the size of the vector is an error condition. - ** Return with the error value. - */ - return(NULL); - } - } else { - - /* - ** Increasing the size of this vector is not allowed! Bail this - ** routine with the error value. - */ - return(NULL); - } - } - - /* - ** There is room for the new space now. Add it to the end of the object - ** vector. and return a pointer to it. - */ - return &((*this)[ActiveCount++]); -} - - -void Set_Bit(void * array, int bit, int value); -int Get_Bit(void const * array, int bit); -int First_True_Bit(void const * array); -int First_False_Bit(void const * array); - - -/************************************************************************** -** This is a derivative of a vector class that supports boolean flags. Since -** a boolean flag can be represented by a single bit, this class packs the -** array of boolean flags into an array of bytes containing 8 boolean values -** each. For large boolean arrays, this results in an 87.5% savings. Although -** the indexing "[]" operator is supported, DO NOT pass pointers to sub elements -** of this bit vector class. A pointer derived from the indexing operator is -** only valid until the next call. Because of this, only simple -** direct use of the "[]" operator is allowed. -*/ -class BooleanVectorClass -{ - public: - BooleanVectorClass(unsigned size=0, unsigned char * array=0); - BooleanVectorClass(BooleanVectorClass const & vector); - - // Assignment operator. - BooleanVectorClass & operator =(BooleanVectorClass const & vector); - - // Equivalency operator. - bool operator == (BooleanVectorClass const & vector); - - // Fetch number of boolean objects in vector. - int Length(void) {return BitCount;}; - - // Set all boolean values to false; - void Reset(void); - - // Set all boolean values to true. - void Set(void); - - // Resets vector to zero length (frees memory). - void Clear(void); - - // Change size of this boolean vector. - int Resize(unsigned size); - - // Fetch reference to specified index. - bool const & operator[](int index) const { - if (LastIndex != index) Fixup(index); - return(Copy); - }; - bool & operator[](int index) { - if (LastIndex != index) Fixup(index); - return(Copy); - }; - - // Quick check on boolean state. - bool Is_True(int index) const { - if (index == LastIndex) return(Copy); - return(Get_Bit(&BitArray[0], index) != 0); - }; - - // Find first index that is false. - int First_False(void) const { - if (LastIndex != -1) Fixup(-1); - - int retval = First_False_Bit(&BitArray[0]); - if (retval < BitCount) return(retval); - - /* - ** Failure to find a false boolean value in the vector. Return this - ** fact in the form of an invalid index number. - */ - return(-1); - } - - // Find first index that is true. - int First_True(void) const { - if (LastIndex != -1) Fixup(-1); - - int retval = First_True_Bit(&BitArray[0]); - if (retval < BitCount) return(retval); - - /* - ** Failure to find a true boolean value in the vector. Return this - ** fact in the form of an invalid index number. - */ - return(-1); - } - - private: - void Fixup(int index=-1) const; - - /* - ** This is the number of boolean values in the vector. This value is - ** not necessarily a multiple of 8, even though the underlying character - ** vector contains a multiple of 8 bits. - */ - int BitCount; - - /* - ** This is a referential copy of an element in the bit vector. The - ** purpose of this copy is to allow normal reference access to this - ** object (for speed reasons). This hides the bit packing scheme from - ** the user of this class. - */ - bool Copy; - - /* - ** This records the index of the value last fetched into the reference - ** boolean variable. This index is used to properly restore the value - ** when the reference copy needs updating. - */ - int LastIndex; - - /* - ** This points to the allocated bitfield array. - */ - VectorClass BitArray; -}; - - -template -int Pointer_Vector_Add(T * ptr, VectorClass & vec) -{ - int id = 0; - bool foundspot = false; - for (int index = 0; index < vec.Length(); index++) { - if (vec[index] == NULL) { - id = index; - foundspot = true; - break; - } - } - if (!foundspot) { - id = vec.Length(); - vec.Resize((vec.Length()+1) * 2); - for (int index = id; index < vec.Length(); index++) { - vec[index] = NULL; - } - } - vec[id] = ptr; - return(id); -} - - -template -bool Pointer_Vector_Remove(T const * ptr, VectorClass & vec) -{ - int id = vec.ID((T *)ptr); - if (id != -1) { - vec[id] = NULL; - return(true); - } - return(false); -} - - -#endif - diff --git a/Generals/Code/Tools/WW3D/pluglib/WWmatrix3.cpp b/Generals/Code/Tools/WW3D/pluglib/WWmatrix3.cpp deleted file mode 100644 index 1a9fbb4d7e..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/WWmatrix3.cpp +++ /dev/null @@ -1,404 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/Tools/max2w3d/WWmatrix3.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 2/02/00 2:05p $* - * * - * $Revision:: 17 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "WWmatrix3.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "w3dquat.h" - - -/* -** Some pre-initialized Matrix3's -*/ -const Matrix3 Matrix3::Identity -( - 1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0 -); - -const Matrix3 Matrix3::RotateX90 -( - 1.0, 0.0, 0.0, - 0.0, 0.0, -1.0, - 0.0, 1.0, 0.0 -); - -const Matrix3 Matrix3::RotateX180 -( - 1.0, 0.0, 0.0, - 0.0, -1.0, 0.0, - 0.0, 0.0, -1.0 -); - -const Matrix3 Matrix3::RotateX270 -( - 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, - 0.0, -1.0, 0.0 -); - -const Matrix3 Matrix3::RotateY90 -( - 0.0, 0.0, 1.0, - 0.0, 1.0, 0.0, - -1.0, 0.0, 0.0 -); - -const Matrix3 Matrix3::RotateY180 -( - -1.0, 0.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, -1.0 -); - -const Matrix3 Matrix3::RotateY270 -( - 0.0, 0.0, -1.0, - 0.0, 1.0, 0.0, - 1.0, 0.0, 0.0 -); - -const Matrix3 Matrix3::RotateZ90 -( - 0.0, -1.0, 0.0, - 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0 -); - -const Matrix3 Matrix3::RotateZ180 -( - -1.0, 0.0, 0.0, - 0.0, -1.0, 0.0, - 0.0, 0.0, 1.0 -); - -const Matrix3 Matrix3::RotateZ270 -( - 0.0, 1.0, 0.0, - -1.0, 0.0, 0.0, - 0.0, 0.0, 1.0 -); - - - -/*********************************************************************************************** - * Matrix3::Matrix3 -- Convert a Matrix3D (fake 4x4) to a Matrix3 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -Matrix3::Matrix3(const Matrix3D & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -Matrix3::Matrix3(const Matrix4 & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -void Matrix3::Set(const Matrix3D & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -void Matrix3::Set(const Matrix4 & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); -} - -void Matrix3::Set(const Quaternion & q) -{ - Row[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - Row[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - Row[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - Row[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - Row[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - Row[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - Row[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - Row[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - Row[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); -} - - -Matrix3 & Matrix3::operator = (const Matrix3D & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); - return *this; -} - -Matrix3 & Matrix3::operator = (const Matrix4 & m) -{ - Row[0].Set(m[0][0],m[0][1],m[0][2]); - Row[1].Set(m[1][0],m[1][1],m[1][2]); - Row[2].Set(m[2][0],m[2][1],m[2][2]); - return *this; -} - -void Matrix3::Multiply(const Matrix3D & a, const Matrix3 & b,Matrix3 * res) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - - #undef ROWCOL -} - -void Matrix3::Multiply(const Matrix3 & a, const Matrix3D & b,Matrix3 * res) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - - #undef ROWCOL -} - -Matrix3 operator * (const Matrix3D & a, const Matrix3 & b) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - return Matrix3( - Vector3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2) ), - Vector3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2) ), - Vector3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2) ) - ); - - #undef ROWCOL -} - -Matrix3 operator * (const Matrix3 & a, const Matrix3D & b) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - return Matrix3( - Vector3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2) ), - Vector3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2) ), - Vector3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2) ) - ); - - #undef ROWCOL -} - - -#if 0 - -void Matrix3::Compute_Jacobi_Rotation(int i,int j,Matrix3 * r,Matrix3 * rinv) -{ - -} - -void Matrix3::Symmetric_Eigen_Solve(void) -{ - Matrix3 eigen_vals = *this; - Matrix3 eigen_vecs(1); - - Matrix3 jr,jrinv; - - while (!done) { - eigen_vals.Compute_Jacobi_Rotation(i,j,&jr,&jrinv); - eigen_vals = jr * (eigenvals) * jrinv; - eigen_vecs = eigen_vecs * jr; - } - - /* - ** Done! Eigen values are the diagonals of - ** the eigen_vals matrix and the eigen vectors - ** are the columns of the eigen_vecs matrix - */ - -} - -#endif - - -void Matrix3::Multiply(const Matrix3 & A,const Matrix3 & B,Matrix3 * set_res) -{ - Matrix3 tmp; - Matrix3 * Aptr; - float tmp1,tmp2,tmp3; - - // Check for aliased parameters, copy the 'A' matrix into a temporary if the - // result is going into 'A'. (in this case, this function is no better than - // the overloaded C++ operator...) - if (set_res == &A) { - tmp = A; - Aptr = &tmp; - } else { - Aptr = (Matrix3 *)&A; - } - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - (*set_res)[0][0] = (float)((*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3); - (*set_res)[1][0] = (float)((*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3); - (*set_res)[2][0] = (float)((*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3); - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - (*set_res)[0][1] = (float)((*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3); - (*set_res)[1][1] = (float)((*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3); - (*set_res)[2][1] = (float)((*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3); - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - (*set_res)[0][2] = (float)((*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3); - (*set_res)[1][2] = (float)((*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3); - (*set_res)[2][2] = (float)((*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3); -} - -int Matrix3::Is_Orthogonal(void) const -{ - Vector3 x(Row[0].X,Row[0].Y,Row[0].Z); - Vector3 y(Row[1].X,Row[1].Y,Row[1].Z); - Vector3 z(Row[2].X,Row[2].Y,Row[2].Z); - - if (Vector3::Dot_Product(x,y) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(y,z) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(z,x) > WWMATH_EPSILON) return 0; - - if (WWMath::Fabs(x.Length() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(y.Length() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(z.Length() - 1.0f) > WWMATH_EPSILON) return 0; - - return 1; -} - -void Matrix3::Re_Orthogonalize(void) -{ - Vector3 x(Row[0][0],Row[0][1],Row[0][2]); - Vector3 y(Row[1][0],Row[1][1],Row[1][2]); - Vector3 z; - - Vector3::Cross_Product(x,y,&z); - Vector3::Cross_Product(z,x,&y); - - float len = x.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - x /= len; - } - - len = y.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - y /= len; - } - - len = z.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - z /= len; - } - - Row[0][0] = x.X; - Row[0][1] = x.Y; - Row[0][2] = x.Z; - - Row[1][0] = y.X; - Row[1][1] = y.Y; - Row[1][2] = y.Z; - - Row[2][0] = z.X; - Row[2][1] = z.Y; - Row[2][2] = z.Z; -} - -void Matrix3::Rotate_AABox_Extent(const Vector3 & extent,Vector3 * set_extent) -{ - // push each extent out to the projections of the original extents - for (int i=0; i<3; i++) { - - // start the center out at the translation portion of the matrix - // and the extent at zero - (*set_extent)[i] = 0.0f; - - for (int j=0; j<3; j++) { - (*set_extent)[i] += WWMath::Fabs(Row[i][j] * extent[j]); - } - } -} diff --git a/Generals/Code/Tools/WW3D/pluglib/WWmatrix3.h b/Generals/Code/Tools/WW3D/pluglib/WWmatrix3.h deleted file mode 100644 index 754140cbdb..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/WWmatrix3.h +++ /dev/null @@ -1,1011 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/WWmatrix3.h 33 2/03/00 4:55p Jason_a $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * File Name : MATRIX3.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/02/97 * - * * - * Last Update : June 2, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix3::Matrix3 -- Constructor, optionally initialize to Identitiy matrix * - * Matrix3::Matrix3 -- Copy Constructor * - * Matrix3::Matrix3 -- Convert a Matrix3D (fake 4x4) to a Matrix3 * - * Matrix3::Matrix3 -- Constructor * - * Matrix3::Transpose -- Returns transpose of the matrix * - * Matrix3::Inverse -- returns the inverse of the matrix * - * Matrix3::Determinant -- returns the determinant of the matrix * - * Matrix3::operator = -- assignment operator * - * Matrix3::operator += -- "plus equals" operator * - * Matrix3::operator-= -- "minus equals" operator * - * Matrix3::operator *= -- "times equals" operator * - * Matrix3::operator /= -- "divide equals" operator * - * Create_X_Rotation_Matrix3 -- creates a matrix3 which is a rotation about X * - * Create_Y_Rotation_Matrix3 -- Creates a Matrix3 which is a rotation about Y * - * Create_Z_Rotation_Matrix3 -- Creates a matrix3 which is a rotation about Z * - * Matrix3::Rotate_X -- Post-mutiplies an x rotation onto the current matrix * - * Matrix3::Rotate_Y -- Post-multiplies the matrix with a rotation about Y * - * Matrix3::Rotate_Z -- Post-multiplies the matrix with a rotation about Z * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef Matrix3_H -#define Matrix3_H - -#include "always.h" -#include "vector3.h" -//#include "wwdebug.h" - - -class Matrix3D; -class Matrix4; -class Quaternion; - -class Matrix3 -{ -public: - - /* - ** Constructors - */ - Matrix3(void) {}; - Matrix3(const Matrix3 & m); - - explicit Matrix3(bool identity); - explicit Matrix3(const Vector3 & v0, const Vector3 & v1, const Vector3 & v2); - explicit Matrix3(const Matrix3D & m); - explicit Matrix3(const Matrix4 & m); - explicit Matrix3( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 - ); - explicit Matrix3(const Vector3 & axis,float angle); - explicit Matrix3(const Vector3 & axis,float s_angle,float c_angle); - explicit Matrix3(const Quaternion & q); - - /* - ** 'Set' functions - */ - void Set(const Matrix3D & m); - void Set(const Matrix4 & m); - void Set(const Vector3 & v0, const Vector3 & v1, const Vector3 & v2); - void Set( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 - ); - void Set(const Vector3 & axis,float angle); - void Set(const Vector3 & axis,float s_angle,float c_angle); - void Set(const Quaternion & q); - - /* - ** Access operators - */ - Vector3 & operator [] (int i) { return Row[i]; } - const Vector3 & operator [] (int i) const { return Row[i]; } - - /* - ** Transpose and Inverse - */ - Matrix3 Transpose (void) const; - Matrix3 Inverse (void) const; - float Determinant (void) const; - - /* - ** Assignment operators - */ - Matrix3 & operator = (const Matrix3 & m); - Matrix3 & operator = (const Matrix3D & m); - Matrix3 & operator = (const Matrix4 & m); - - Matrix3 & operator += (const Matrix3 & m); - Matrix3 & operator -= (const Matrix3 & m); - Matrix3 & operator *= (float d); - Matrix3 & operator /= (float d); - - void Make_Identity(void); - - /* - ** Automatically concatenate a rotation onto the current matrix - */ - void Rotate_X(float theta); - void Rotate_X(float s,float c); - - void Rotate_Y(float theta); - void Rotate_Y(float s,float c); - - void Rotate_Z(float theta); - void Rotate_Z(float s,float c); - - /* - ** These functions will give you the approximate amount that the - ** matrix has been rotated about a given axis. These functions - ** cannot be used to re-build a matrx. Use the EulerAnglesClass - ** to convert a matrix into a set of three Euler angles. - */ - float Get_X_Rotation(void) const; - float Get_Y_Rotation(void) const; - float Get_Z_Rotation(void) const; - - /* - ** These functions return a vector representing the direction an - ** axis is pointing. - */ - Vector3 Get_X_Vector(void) const; - Vector3 Get_Y_Vector(void) const; - Vector3 Get_Z_Vector(void) const; - void Get_X_Vector(Vector3 * set_x) const; - void Get_Y_Vector(Vector3 * set_y) const; - void Get_Z_Vector(Vector3 * set_z) const; - - /* - ** Negation - */ - friend Matrix3 operator - (const Matrix3& a); - - /* - ** Scalar multiplication and division - */ - friend Matrix3 operator * (const Matrix3& a,float d); - friend Matrix3 operator * (float d,const Matrix3& a); - friend Matrix3 operator / (const Matrix3& a,float d); - - /* - ** matrix addition - */ - friend Matrix3 operator + (const Matrix3& a, const Matrix3& b); - static void Add(const Matrix3 & a, const Matrix3 & b,Matrix3 * res); - - /* - ** matrix subtraction - */ - friend Matrix3 operator - (const Matrix3 & a, const Matrix3 & b); - static void Subtract(const Matrix3 & a, const Matrix3 & b,Matrix3 * res); - - /* - ** matrix multiplication - */ - friend Matrix3 operator * (const Matrix3 & a, const Matrix3 & b); - friend Matrix3 operator * (const Matrix3D & a, const Matrix3 & b); - friend Matrix3 operator * (const Matrix3 & a, const Matrix3D & b); - - static void Multiply(const Matrix3 & a, const Matrix3 & b,Matrix3 * res); - static void Multiply(const Matrix3D & a, const Matrix3 & b,Matrix3 * res); - static void Multiply(const Matrix3 & a, const Matrix3D & b,Matrix3 * res); - - /* - ** Matrix-Vector multiplication - */ - friend Vector3 operator * (const Matrix3 & a, const Vector3 & v); - static void Rotate_Vector(const Matrix3 & tm,const Vector3 & in,Vector3 * out); - static void Transpose_Rotate_Vector(const Matrix3 & tm,const Vector3 & in,Vector3 * out); - - /* - ** Comparison operators - */ - friend int operator == (const Matrix3 & a, const Matrix3 & b); - friend int operator != (const Matrix3 & a, const Matrix3 & b); - - /* - ** Swap two matrices in place - */ - friend void Swap(Matrix3 & a,Matrix3 & b); - - /* - ** Check whether a matrix is orthogonal, make it orthogonal - */ - int Is_Orthogonal(void) const; - void Re_Orthogonalize(void); - - /* - ** Miscellaneous - */ - void Rotate_AABox_Extent(const Vector3 & extent,Vector3 * new_extent); - - /* - ** Some useful pre-initialized Matrix3's - */ - static const Matrix3 Identity; - static const Matrix3 RotateX90; - static const Matrix3 RotateX180; - static const Matrix3 RotateX270; - static const Matrix3 RotateY90; - static const Matrix3 RotateY180; - static const Matrix3 RotateY270; - static const Matrix3 RotateZ90; - static const Matrix3 RotateZ180; - static const Matrix3 RotateZ270; - -protected: - - Vector3 Row[3]; - -}; - - -/*********************************************************************************************** - * Matrix3::Matrix3 -- Constructor, optionally initialize to Identitiy matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3::Matrix3(bool identity) -{ - if (identity) { - Row[0].Set(1.0,0.0,0.0); - Row[1].Set(0.0,1.0,0.0); - Row[2].Set(0.0,0.0,1.0); - } -} - -/*********************************************************************************************** - * Matrix3::Matrix3 -- Copy Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3::Matrix3(const Matrix3 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; -} - -/*********************************************************************************************** - * Matrix3::Matrix3 -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3::Matrix3(const Vector3 & r0, const Vector3 & r1, const Vector3 & r2) -{ - Row[0] = r0; - Row[1] = r1; - Row[2] = r2; -} - -inline void Matrix3::Set(const Vector3 & r0, const Vector3 & r1, const Vector3 & r2) -{ - Row[0] = r0; - Row[1] = r1; - Row[2] = r2; -} - -inline void Matrix3::Make_Identity(void) -{ - Row[0].Set(1.0f,0.0f,0.0f); - Row[1].Set(0.0f,1.0f,0.0f); - Row[2].Set(0.0f,0.0f,1.0f); -} - - -inline Matrix3::Matrix3 -( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 -) -{ - Row[0].Set(m11,m12,m13); - Row[1].Set(m21,m22,m23); - Row[2].Set(m31,m32,m33); -} - -inline void Matrix3::Set -( - float m11,float m12,float m13, - float m21,float m22,float m23, - float m31,float m32,float m33 -) -{ - Row[0].Set(m11,m12,m13); - Row[1].Set(m21,m22,m23); - Row[2].Set(m31,m32,m33); -} - -inline Matrix3::Matrix3(const Vector3 & axis,float angle) -{ - Set(axis,angle); -} - -inline Matrix3::Matrix3(const Vector3 & axis,float s_angle,float c_angle) -{ - Set(axis,s_angle,c_angle); -} - -inline void Matrix3::Set(const Vector3 & axis,float angle) -{ - Set(axis,sinf(angle),cosf(angle)); -} - -inline void Matrix3::Set(const Vector3 & axis,float s,float c) -{ - assert(WWMath::Fabs(axis.Length2() - 1.0f) < 0.001f); - - Row[0].Set( - (float)(axis[0]*axis[0] + c*(1.0f - axis[0]*axis[0])), - (float)(axis[0]*axis[1]*(1.0f - c) - axis[2]*s), - (float)(axis[2]*axis[0]*(1.0f - c) + axis[1]*s) - ); - - Row[1].Set( - (float)(axis[0]*axis[1]*(1.0f - c) + axis[2]*s), - (float)(axis[1]*axis[1] + c*(1.0f - axis[1]*axis[1])), - (float)(axis[1]*axis[2]*(1.0f - c) - axis[0]*s) - ); - - Row[2].Set( - (float)(axis[2]*axis[0]*(1.0f - c) - axis[1]*s), - (float)(axis[1]*axis[2]*(1.0f - c) + axis[0]*s), - (float)(axis[2]*axis[2] + c*(1 - axis[2]*axis[2])) - ); -} - -inline Matrix3::Matrix3(const Quaternion & q) -{ - this->Set(q); -} - -/*********************************************************************************************** - * Matrix3::Transpose -- Returns transpose of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3 Matrix3::Transpose() const -{ - return Matrix3( - Vector3(Row[0][0], Row[1][0], Row[2][0]), - Vector3(Row[0][1], Row[1][1], Row[2][1]), - Vector3(Row[0][2], Row[1][2], Row[2][2]) - ); -} - -/*********************************************************************************************** - * Matrix3::Inverse -- returns the inverse of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3 Matrix3::Inverse() const // Gauss-Jordan elimination with partial pivoting -{ - Matrix3 a(*this); // As a evolves from original mat into identity - Matrix3 b(true); // b evolves from identity into inverse(a) - int i, j, i1; - - // Loop over cols of a from left to right, eliminating above and below diagonal - for (j=0; j<3; j++) { - - // Find largest pivot in column j among rows j..3 - i1 = j; - for (i=j+1; i<3; i++) { - if (WWMath::Fabs(a[i][j]) > WWMath::Fabs(a[i1][j])) { - i1 = i; - } - } - - // Swap rows i1 and j in a and b to put pivot on diagonal - Swap(a.Row[i1], a.Row[j]); - Swap(b.Row[i1], b.Row[j]); - - // Scale row j to have a unit diagonal - if (a[j][j]==0.) { - //Matrix3::inverse: singular matrix; can't invert - } - b.Row[j] /= a.Row[j][j]; - a.Row[j] /= a.Row[j][j]; - - // Eliminate off-diagonal elems in col j of a, doing identical ops to b - for (i=0; i<3; i++) { - if (i != j) { - b.Row[i] -= a[i][j] * b.Row[j]; - a.Row[i] -= a[i][j] * a.Row[j]; - } - } - } - return b; -} - - -/*********************************************************************************************** - * Matrix3::Determinant -- returns the determinant of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/7/20 DRM : Created. * - *=============================================================================================*/ -inline float Matrix3::Determinant(void) const -{ - return Row[0][0] * (Row[1][1] * Row[2][2] - Row[1][2] * Row[2][1]) - - Row[0][1] * (Row[1][0] * Row[2][2] - Row[1][2] * Row[2][0]) - - Row[0][2] * (Row[1][0] * Row[2][1] - Row[1][1] * Row[2][0]); -} - -/*********************************************************************************************** - * Matrix3::operator = -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3 & Matrix3::operator = (const Matrix3 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; - return *this; -} - -/*********************************************************************************************** - * Matrix3::operator += -- "plus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3& Matrix3::operator += (const Matrix3 & m) -{ - Row[0] += m.Row[0]; Row[1] += m.Row[1]; Row[2] += m.Row[2]; - return *this; -} - -/*********************************************************************************************** - * Matrix3::operator-= -- "minus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3& Matrix3::operator -= (const Matrix3 & m) -{ - Row[0] -= m.Row[0]; Row[1] -= m.Row[1]; Row[2] -= m.Row[2]; - return *this; -} - -/*********************************************************************************************** - * Matrix3::operator *= -- "times equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3& Matrix3::operator *= (float d) -{ - Row[0] *= d; Row[1] *= d; Row[2] *= d; - return *this; -} - -/*********************************************************************************************** - * Matrix3::operator /= -- "divide equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3& Matrix3::operator /= (float d) -{ - Row[0] /= d; Row[1] /= d; Row[2] /= d; - return *this; -} - -/*********************************************************************************************** - * Matrix3::Get_X_Rotation -- approximates the rotation about the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -inline float Matrix3::Get_X_Rotation(void) const -{ - Vector3 v = (*this) * Vector3(0.0,1.0,0.0); - return atan2(v[2], v[1]); -} - -/*********************************************************************************************** - * Matrix3::Get_Y_Rotation -- approximates the rotation about the Y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -inline float Matrix3::Get_Y_Rotation(void) const -{ - Vector3 v = (*this) * Vector3(0.0,0.0,1.0); - return atan2(v[0],v[2]); -} - -/*********************************************************************************************** - * Matrix3::Get_Z_Rotation -- approximates the rotation about the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -inline float Matrix3::Get_Z_Rotation(void) const -{ - Vector3 v = (*this) * Vector3(1.0,0.0,0.0); - return atan2(v[1],v[0]); -} - -inline Vector3 Matrix3::Get_X_Vector(void) const -{ - return Vector3(Row[0][0], Row[1][0], Row[2][0]); -} - -inline Vector3 Matrix3::Get_Y_Vector(void) const -{ - return Vector3(Row[0][1], Row[1][1], Row[2][1]); -} - -inline Vector3 Matrix3::Get_Z_Vector(void) const -{ - return Vector3(Row[0][2], Row[1][2], Row[2][2]); -} - -inline void Matrix3::Get_X_Vector(Vector3 * set) const -{ - set->Set(Row[0][0], Row[1][0], Row[2][0]); -} - -inline void Matrix3::Get_Y_Vector(Vector3 * set) const -{ - set->Set(Row[0][1], Row[1][1], Row[2][1]); -} - -inline void Matrix3::Get_Z_Vector(Vector3 * set) const -{ - set->Set(Row[0][2], Row[1][2], Row[2][2]); -} - -inline Matrix3 operator - (const Matrix3 & a) -{ - return Matrix3(-a.Row[0], -a.Row[1], -a.Row[2]); -} - -inline Matrix3 operator * (const Matrix3 & a, float d) -{ - return Matrix3(a.Row[0] * d, a.Row[1] * d, a.Row[2] * d); -} - -inline Matrix3 operator * (float d, const Matrix3 & a) -{ - return a*d; -} - -inline Matrix3 operator / (const Matrix3 & a, float d) -{ - float ood = 1.0f / d; - return Matrix3(a.Row[0] * ood, a.Row[1] * ood, a.Row[2] * ood); -} - -/* -** matrix addition -*/ -inline Matrix3 operator + (const Matrix3 & a, const Matrix3 & b) -{ - return Matrix3( - a.Row[0] + b.Row[0], - a.Row[1] + b.Row[1], - a.Row[2] + b.Row[2] - ); -} - -inline void Matrix3::Add(const Matrix3 & a, const Matrix3 & b,Matrix3 * c) -{ - assert(c); - Vector3::Add(a.Row[0],b.Row[0],&(c->Row[0])); - Vector3::Add(a.Row[1],b.Row[1],&(c->Row[1])); - Vector3::Add(a.Row[2],b.Row[2],&(c->Row[2])); -} - -/* -** matrix subtraction -*/ -inline Matrix3 operator - (const Matrix3 & a, const Matrix3 & b) -{ - return Matrix3( - a.Row[0] - b.Row[0], - a.Row[1] - b.Row[1], - a.Row[2] - b.Row[2] - ); -} - -inline void Matrix3::Subtract(const Matrix3 & a, const Matrix3 & b,Matrix3 * c) -{ - assert(c); - Vector3::Subtract(a.Row[0],b.Row[0],&(c->Row[0])); - Vector3::Subtract(a.Row[1],b.Row[1],&(c->Row[1])); - Vector3::Subtract(a.Row[2],b.Row[2],&(c->Row[2])); -} - -/* -** matrix multiplication -*/ -inline Matrix3 operator * (const Matrix3 & a, const Matrix3 & b) -{ - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - - return Matrix3( - Vector3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2) ), - Vector3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2) ), - Vector3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2) ) - ); - - #undef ROWCOL -} - - -/* -** Multiply a Matrix3 by a Vector3. Yeilds a Vector3 result -*/ -inline Vector3 operator * (const Matrix3 & a, const Vector3 & v) -{ - return Vector3( - a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2], - a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2], - a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] - ); -} - - -inline int operator == (const Matrix3 & a, const Matrix3 & b) -{ - return ((a [0] == b [0]) && (a [1] == b [1]) && (a [2] == b [2])); -} - - -inline int operator != (const Matrix3 & a, const Matrix3 & b) -{ - return (!(a == b)); -} - - -/*********************************************************************************************** - * Matrix3::Rotate_X -- Post-mutiplies an x rotation onto the current matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3::Rotate_X(float theta) -{ - Rotate_X(sinf(theta),cosf(theta)); -} - -inline void Matrix3::Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][1]; tmp2 = Row[0][2]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[0][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[1][2]; - Row[1][1] = (float)( c*tmp1 + s*tmp2); - Row[1][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][1]; tmp2 = Row[2][2]; - Row[2][1] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * Matrix3::Rotate_Y -- Post-multiplies the matrix with a rotation about Y * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3::Rotate_Y(float theta) -{ - Rotate_Y(sinf(theta),cosf(theta)); -} - -inline void Matrix3::Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][2]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[0][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][2]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][2]; - Row[2][0] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * Matrix3::Rotate_Z -- Post-multiplies the matrix with a rotation about Z * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3::Rotate_Z(float theta) -{ - Rotate_Z(sinf(theta),cosf(theta)); -} - -inline void Matrix3::Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][1]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[0][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][1]; - Row[1][0] = (float)( c*tmp1 + s*tmp2); - Row[1][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][1]; - Row[2][0] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * Create_X_Rotation_Matrix3 -- creates a matrix3 which is a rotation about X * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3 Create_X_Rotation_Matrix3(float s,float c) -{ - Matrix3 mat; - - mat[0][0] = 1.0f; - mat[0][1] = 0.0f; - mat[0][2] = 0.0f; - - mat[1][0] = 0.0f; - mat[1][1] = c; - mat[1][2] = -s; - - mat[2][0] = 0.0f; - mat[2][1] = s; - mat[2][2] = c; - - return mat; -} - -inline Matrix3 Create_X_Rotation_Matrix3(float rad) -{ - return Create_X_Rotation_Matrix3(sinf(rad),cosf(rad)); -} - -/*********************************************************************************************** - * Create_Y_Rotation_Matrix3 -- Creates a Matrix3 which is a rotation about Y * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3 Create_Y_Rotation_Matrix3(float s,float c) -{ - Matrix3 mat; - - mat[0][0] = c; - mat[0][1] = 0.0f; - mat[0][2] = s; - - mat[1][0] = 0.0f; - mat[1][1] = 1.0f; - mat[1][2] = 0.0f; - - mat[2][0] = -s; - mat[2][1] = 0.0f; - mat[2][2] = c; - - return mat; -} - -inline Matrix3 Create_Y_Rotation_Matrix3(float rad) -{ - return Create_Y_Rotation_Matrix3(sinf(rad),cosf(rad)); -} - -/*********************************************************************************************** - * Create_Z_Rotation_Matrix3 -- Creates a matrix3 which is a rotation about Z * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/26/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3 Create_Z_Rotation_Matrix3(float s,float c) -{ - Matrix3 mat; - - mat[0][0] = c; - mat[0][1] = -s; - mat[0][2] = 0.0f; - - mat[1][0] = s; - mat[1][1] = c; - mat[1][2] = 0.0f; - - mat[2][0] = 0.0f; - mat[2][1] = 0.0f; - mat[2][2] = 1.0f; - - return mat; -} - -inline Matrix3 Create_Z_Rotation_Matrix3(float rad) -{ - return Create_Z_Rotation_Matrix3(sinf(rad),cosf(rad)); -} - -inline void Matrix3::Rotate_Vector(const Matrix3 & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z); -} - -inline void Matrix3::Transpose_Rotate_Vector(const Matrix3 & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ - } - out->X = (A[0][0] * v->X + A[1][0] * v->Y + A[2][0] * v->Z); - out->Y = (A[0][1] * v->X + A[1][1] * v->Y + A[2][1] * v->Z); - out->Z = (A[0][2] * v->X + A[1][2] * v->Y + A[2][2] * v->Z); -} - -#endif /*Matrix3_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/aaplane.h b/Generals/Code/Tools/WW3D/pluglib/aaplane.h deleted file mode 100644 index 2f52f7633f..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/aaplane.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/aaplane.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/19/00 3:12p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef AAPLANE_H -#define AAPLANE_H - -#include "always.h" -#include "vector3.h" - - -/* -** This class is used to describe an "axis-aligned" plane. I.e, the normal -** of the plane is one of the three coordinate axes. -*/ -class AAPlaneClass -{ -public: - - enum AxisEnum { XNORMAL = 0, YNORMAL = 1, ZNORMAL = 2 }; - - AAPlaneClass(void) { } - AAPlaneClass(AxisEnum normal,float dist) : Normal(normal),Dist(dist) { } - - void Set(AxisEnum normal,float dist); - void Get_Normal(Vector3 * normal) const; - -public: - - AxisEnum Normal; - float Dist; - -}; - -inline void AAPlaneClass::Set(AxisEnum normal,float dist) -{ - Normal = normal; - Dist = dist; -} - -inline void AAPlaneClass::Get_Normal(Vector3 * normal) const -{ - normal->Set(0,0,0); - (*normal)[Normal] = 1.0f; -} - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/always.h b/Generals/Code/Tools/WW3D/pluglib/always.h deleted file mode 100644 index 37b236dc83..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/always.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/wwlib/always.h $* - * * - * $Author:: Steve_t $* - * * - * $Modtime:: 8/28/01 3:21p $* - * * - * $Revision:: 13 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef ALWAYS_H -#define ALWAYS_H - -// Disable warning about exception handling not being enabled. It's used as part of STL - in a part of STL we don't use. -#pragma warning(disable : 4530) - -/* -** Define for debug memory allocation to include __FILE__ and __LINE__ for every memory allocation. -** This helps find leaks. -*/ -//#define STEVES_NEW_CATCHER -#ifdef _DEBUG -#ifdef _MSC_VER -#ifdef STEVES_NEW_CATCHER - -#include -#include -#include - -#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__) -#define calloc(c, s) _calloc_dbg(c, s, _NORMAL_BLOCK, __FILE__, __LINE__) -#define realloc(p, s) _realloc_dbg(p, s, _NORMAL_BLOCK, __FILE__, __LINE__) -#define _expand(p, s) _expand_dbg(p, s, _NORMAL_BLOCK, __FILE__, __LINE__) -#define free(p) _free_dbg(p, _NORMAL_BLOCK) -#define _msize(p) _msize_dbg(p, _NORMAL_BLOCK) - -void* __cdecl operator new(unsigned int s); - -#endif //STEVES_NEW_CATCHER -#endif //_MSC_VER -#endif //_DEBUG - - -// Jani: Intel's C++ compiler issues too many warnings in WW libraries when using warning level 4 -#if defined (__ICL) // Detect Intel compiler -#pragma warning (3) -#pragma warning ( disable: 981 ) // parameters defined in unspecified order -#pragma warning ( disable: 279 ) // controlling expressaion is constant -#pragma warning ( disable: 271 ) // trailing comma is nonstandard -#pragma warning ( disable: 171 ) // invalid type conversion -#pragma warning ( disable: 1 ) // last line of file ends without a newline -#endif - -// Jani: MSVC doesn't necessarily inline code with inline keyword. Using __forceinline results better inlining -// and also prints out a warning if inlining wasn't possible. __forceinline is MSVC specific. -#if defined(_MSC_VER) -#define WWINLINE __forceinline -#else -#define WWINLINE inline -#endif - -/* -** Define the MIN and MAX macros. -** NOTE: Joe used to #include in the various compiler header files. This -** header defines 'min' and 'max' macros which conflict with the surrender code so -** I'm relpacing all occurances of 'min' and 'max with 'MIN' and 'MAX'. For code which -** is out of our domain (e.g. Max sdk) I'm declaring template functions for 'min' and 'max' -*/ -#define NOMINMAX - -#ifndef MAX -#define MAX(a,b) (((a) > (b)) ? (a) : (b)) -#endif - -#ifndef MIN -#define MIN(a,b) (((a) < (b)) ? (a) : (b)) -#endif - -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -template T min(T a,T b) -{ - if (a T max(T a,T b) -{ - if (a>b) { - return a; - } else { - return b; - } -} - - -/* -** This includes the minimum set of compiler defines and pragmas in order to bring the -** various compilers to a common behavior such that the C&C engine will compile without -** error or warning. -*/ -#if defined(__BORLANDC__) -#include "borlandc.h" -#endif - -#if defined(_MSC_VER) -#include "visualc.h" -#endif - -#if defined(__WATCOMC__) -#include "watcom.h" -#endif - - -#ifndef NULL - #define NULL 0 -#endif - -/********************************************************************** -** This macro serves as a general way to determine the number of elements -** within an array. -*/ -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(x) int(sizeof(x)/sizeof(x[0])) -#endif - -#ifndef size_of -#define size_of(typ,id) sizeof(((typ*)0)->id) -#endif - - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/bool.h b/Generals/Code/Tools/WW3D/pluglib/bool.h deleted file mode 100644 index ff6e3e4167..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/bool.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/bool.h $* - * * - * $Author:: Neal_k $* - * * - * $Modtime:: 9/23/99 1:46p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#if !defined(TRUE_FALSE_DEFINED) && !defined(__BORLANDC__) && (_MSC_VER < 1100) && !defined(__WATCOMC__) -#define TRUE_FALSE_DEFINED - -/********************************************************************** -** The "bool" integral type was defined by the C++ comittee in -** November of '94. Until the compiler supports this, use the following -** definition. -*/ -#ifdef _MSC_VER - -#include "yvals.h" -#define bool unsigned - -#elif defined(_UNIX) - -/////#define bool unsigned - -#else - -enum {false=0,true=1}; -typedef int bool; - -#endif - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/borlandc.h b/Generals/Code/Tools/WW3D/pluglib/borlandc.h deleted file mode 100644 index efde253669..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/borlandc.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/borlandc.h $* - * * - * $Author:: Eric_c $* - * * - * $Modtime:: 4/02/99 11:57a $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#if !defined(BORLANDC_H) && defined(__BORLANDC__) -#define BORLANDC_H - -/* -** Funny, but there are no required overrides to make Borland C match C++ standards. This -** is because Borland C more closely matches the C++ standard than the other compilers. -*/ - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/chunkio.cpp b/Generals/Code/Tools/WW3D/pluglib/chunkio.cpp deleted file mode 100644 index 983fa99825..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/chunkio.cpp +++ /dev/null @@ -1,796 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwlib/chunkio.cpp 11 7/12/01 7:44p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Tiberian Sun / Commando / G Library * - * * - * $Archive:: /Commando/Code/wwlib/chunkio.cpp $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 7/10/01 7:38p $* - * * - * $Revision:: 11 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * ChunkSaveClass::ChunkSaveClass -- Constructor * - * ChunkSaveClass::Begin_Chunk -- Begin a new chunk in the file * - * ChunkSaveClass::End_Chunk -- Close a chunk, computes the size and adds to the header * - * ChunkSaveClass::Begin_Micro_Chunk -- begins a new "micro-chunk" * - * ChunkSaveClass::End_Micro_Chunk -- close a micro-chunk * - * ChunkSaveClass::Write -- Write data into the current chunk * - * ChunkSaveClass::Write -- write an IOVector2Struct * - * ChunkSaveClass::Write -- write an IOVector3Struct * - * ChunkSaveClass::Write -- write an IOVector4Struct * - * ChunkSaveClass::Write -- write an IOQuaternionStruct * - * ChunkSaveClass::Cur_Chunk_Depth -- returns the current chunk recursion depth (debugging) * - * ChunkLoadClass::ChunkLoadClass -- Constructor * - * ChunkLoadClass::Open_Chunk -- Open a chunk in the file, reads in the chunk header * - * ChunkLoadClass::Close_Chunk -- Close a chunk, seeks to the end if needed * - * ChunkLoadClass::Cur_Chunk_ID -- Returns the ID of the current chunk * - * ChunkLoadClass::Cur_Chunk_Length -- Returns the current length of the current chunk * - * ChunkLoadClass::Cur_Chunk_Depth -- returns the current chunk recursion depth * - * ChunkLoadClass::Contains_Chunks -- Test whether the current chunk contains chunks (or dat * - * ChunkLoadClass::Open_Micro_Chunk -- reads in a micro-chunk header * - * ChunkLoadClass::Close_Micro_Chunk -- closes a micro-chunk * - * ChunkLoadClass::Cur_Micro_Chunk_ID -- returns the ID of the current micro-chunk (asserts * - * ChunkLoadClass::Cur_Micro_Chunk_Length -- returns the size of the current micro chunk * - * ChunkLoadClass::Read -- Read data from the file * - * ChunkLoadClass::Read -- read an IOVector2Struct * - * ChunkLoadClass::Read -- read an IOVector3Struct * - * ChunkLoadClass::Read -- read an IOVector4Struct * - * ChunkLoadClass::Read -- read an IOQuaternionStruct * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "chunkio.h" -#include -#include - - -/*********************************************************************************************** - * ChunkSaveClass::ChunkSaveClass -- Constructor * - * * - * INPUT: * - * file - pointer to a FileClass object to write to * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -ChunkSaveClass::ChunkSaveClass(FileClass * file) : - File(file), - StackIndex(0), - InMicroChunk(false), - MicroChunkPosition(0) -{ - memset(PositionStack,0,sizeof(PositionStack)); - memset(HeaderStack,0,sizeof(HeaderStack)); - memset(&MCHeader,0,sizeof(MCHeader)); -} - - -/*********************************************************************************************** - * ChunkSaveClass::Begin_Chunk -- Begin a new chunk in the file * - * * - * INPUT: * - * id - id of the chunk * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -bool ChunkSaveClass::Begin_Chunk(uint32 id) -{ - ChunkHeader chunkh; - int filepos; - - // If we have a parent chunk, set its 'Contains_Chunks' flag - if (StackIndex > 0) { - HeaderStack[StackIndex-1].Set_Sub_Chunk_Flag(true); - } - - // Save the current file position and chunk header - // for the call to End_Chunk. - chunkh.Set_Type(id); - chunkh.Set_Size(0); - filepos = File->Seek(0); - - PositionStack[StackIndex] = filepos; - HeaderStack[StackIndex] = chunkh; - StackIndex++; - - // write a temporary chunk header (size = 0) - if (File->Write(&chunkh,sizeof(chunkh)) != sizeof(chunkh)) { - return false; - } - return true; -} - - -/*********************************************************************************************** - * ChunkSaveClass::End_Chunk -- Close a chunk, computes the size and adds to the header * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -bool ChunkSaveClass::End_Chunk(void) -{ - // If the user didn't close his micro chunks bad things are gonna happen - assert(!InMicroChunk); - - // Save the current position - int curpos = File->Seek(0); - - // Pop the position and chunk header off the stacks - StackIndex--; - int chunkpos = PositionStack[StackIndex]; - ChunkHeader chunkh = HeaderStack[StackIndex]; - - // write the completed header - File->Seek(chunkpos,SEEK_SET); - if (File->Write(&chunkh,sizeof(chunkh)) != sizeof(chunkh)) { - return false; - } - - // Add the total bytes written to any encompasing chunk - if (StackIndex != 0) { - HeaderStack[StackIndex-1].Add_Size(chunkh.Get_Size() + sizeof(chunkh)); - } - - // Go back to the end of the file - File->Seek(curpos,SEEK_SET); - - return true; -} - - -/*********************************************************************************************** - * ChunkSaveClass::Begin_Micro_Chunk -- begins a new "micro-chunk" * - * * - * Micro chunks are used to wrap individual variables. They aren't hierarchical so if you * - * attempt to open a micro chunk while already in one, an assert will occur. * - * * - * INPUT: * - * id - 8bit id * - * * - * OUTPUT: * - * * - * WARNINGS: * - * id is asserted to be between 0 and 255 * - * cannot nest micro chunks so it asserts that you are currently not in another micro-chunk * - * * - * HISTORY: * - * 9/3/99 GTH : Created. * - *=============================================================================================*/ -bool ChunkSaveClass::Begin_Micro_Chunk(uint32 id) -{ - assert(id < 256); - assert(!InMicroChunk); - - // Save the current file position and chunk header - // for the call to End_Micro_Chunk. - MCHeader.Set_Type(id); - MCHeader.Set_Size(0); - MicroChunkPosition = File->Seek(0); - - // Write a temporary chunk header - // NOTE: I'm calling the ChunkSaveClass::Write method so that the bytes for - // this header are tracked in the wrapping chunk. This is because micro-chunks - // are simply data inside the normal chunks... - if (Write(&MCHeader,sizeof(MCHeader)) != sizeof(MCHeader)) { - return false; - } - - InMicroChunk = true; - return true; -} - - -/*********************************************************************************************** - * ChunkSaveClass::End_Micro_Chunk -- close a micro-chunk * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/3/99 GTH : Created. * - *=============================================================================================*/ -bool ChunkSaveClass::End_Micro_Chunk(void) -{ - assert(InMicroChunk); - - // Save the current position - int curpos = File->Seek(0); - - // Seek back and write the micro chunk header - File->Seek(MicroChunkPosition,SEEK_SET); - if (File->Write(&MCHeader,sizeof(MCHeader)) != sizeof(MCHeader)) { - return false; - } - - // Go back to the end of the file - File->Seek(curpos,SEEK_SET); - InMicroChunk = false; - return true; -} - -/*********************************************************************************************** - * ChunkSaveClass::Write -- Write data into the current chunk * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -uint32 ChunkSaveClass::Write(const void * buf, uint32 nbytes) -{ - // If this assert hits, you mixed data and chunks within the same chunk NO NO! - assert(HeaderStack[StackIndex-1].Get_Sub_Chunk_Flag() == 0); - - // If this assert hits, you didnt open any chunks yet - assert(StackIndex > 0); - - // write the bytes into the file - if (File->Write(buf,nbytes) != (int)nbytes) return 0; - - // track them in the wrapping chunk - HeaderStack[StackIndex-1].Add_Size(nbytes); - - // track them if you are using a micro-chunk too. - if (InMicroChunk) { - assert(MCHeader.Get_Size() < 255 - nbytes); // micro chunks can only be 255 bytes - MCHeader.Add_Size(nbytes); - } - - return nbytes; -} - - -/*********************************************************************************************** - * ChunkSaveClass::Write -- write an IOVector2Struct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkSaveClass::Write(const IOVector2Struct & v) -{ - return Write(&v,sizeof(v)); -} - - -/*********************************************************************************************** - * ChunkSaveClass::Write -- write an IOVector3Struct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkSaveClass::Write(const IOVector3Struct & v) -{ - return Write(&v,sizeof(v)); -} - - -/*********************************************************************************************** - * ChunkSaveClass::Write -- write an IOVector4Struct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkSaveClass::Write(const IOVector4Struct & v) -{ - return Write(&v,sizeof(v)); -} - -/*********************************************************************************************** - * ChunkSaveClass::Write -- write an IOQuaternionStruct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkSaveClass::Write(const IOQuaternionStruct & q) -{ - return Write(&q,sizeof(q)); -} - -/*********************************************************************************************** - * ChunkSaveClass::Cur_Chunk_Depth -- returns the current chunk recursion depth (debugging) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -int ChunkSaveClass::Cur_Chunk_Depth(void) -{ - return StackIndex; -} - - -/*********************************************************************************************** - * ChunkLoadClass::ChunkLoadClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -ChunkLoadClass::ChunkLoadClass(FileClass * file) : - File(file), - StackIndex(0), - InMicroChunk(false), - MicroChunkPosition(0) -{ - memset(PositionStack,0,sizeof(PositionStack)); - memset(HeaderStack,0,sizeof(HeaderStack)); - memset(&MCHeader,0,sizeof(MCHeader)); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Open_Chunk -- Open a chunk in the file, reads in the chunk header * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -bool ChunkLoadClass::Open_Chunk() -{ - // if user didn't close any micro chunks that he opened, bad things could happen - assert(InMicroChunk == false); - - // check for stack overflow - assert(StackIndex < MAX_STACK_DEPTH-1); - - // if the parent chunk has been completely eaten, return false - if ((StackIndex > 0) && (PositionStack[StackIndex-1] == HeaderStack[StackIndex-1].Get_Size())) { - return false; - } - - // read the chunk header - if (File->Read(&HeaderStack[StackIndex],sizeof(ChunkHeader)) != sizeof(ChunkHeader)) { - return false; - } - - PositionStack[StackIndex] = 0; - StackIndex++; - return true; -} - - -/*********************************************************************************************** - * ChunkLoadClass::Close_Chunk -- Close a chunk, seeks to the end if needed * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -bool ChunkLoadClass::Close_Chunk() -{ - // if user didn't close any micro chunks that he opened, bad things could happen - assert(InMicroChunk == false); - - // check for stack overflow - assert(StackIndex > 0); - - int csize = HeaderStack[StackIndex-1].Get_Size(); - int pos = PositionStack[StackIndex-1]; - - if (pos < csize) { - File->Seek(csize - pos,SEEK_CUR); - } - - StackIndex--; - if (StackIndex > 0) { - PositionStack[StackIndex - 1] += csize + sizeof(ChunkHeader); - } - - return true; -} - - -/*********************************************************************************************** - * ChunkLoadClass::Cur_Chunk_ID -- Returns the ID of the current chunk * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Cur_Chunk_ID() -{ - assert(StackIndex >= 1); - return HeaderStack[StackIndex-1].Get_Type(); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Cur_Chunk_Length -- Returns the current length of the current chunk * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Cur_Chunk_Length() -{ - assert(StackIndex >= 1); - return HeaderStack[StackIndex-1].Get_Size(); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Cur_Chunk_Depth -- returns the current chunk recursion depth * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -int ChunkLoadClass::Cur_Chunk_Depth() -{ - return StackIndex; -} - - -/*********************************************************************************************** - * ChunkLoadClass::Contains_Chunks -- Test whether the current chunk contains chunks (or data) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/24/99 GTH : Created. * - *=============================================================================================*/ -int ChunkLoadClass::Contains_Chunks() -{ - return HeaderStack[StackIndex-1].Get_Sub_Chunk_Flag(); -} - -/*********************************************************************************************** - * ChunkLoadClass::Open_Micro_Chunk -- reads in a micro-chunk header * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/3/99 GTH : Created. * - *=============================================================================================*/ -bool ChunkLoadClass::Open_Micro_Chunk() -{ - assert(!InMicroChunk); - - // read the chunk header - // calling the ChunkLoadClass::Read fn so that if we exhaust the chunk, the read will fail - if (Read(&MCHeader,sizeof(MCHeader)) != sizeof(MCHeader)) { - return false; - } - - InMicroChunk = true; - MicroChunkPosition = 0; - return true; -} - - -/*********************************************************************************************** - * ChunkLoadClass::Close_Micro_Chunk -- closes a micro-chunk (seeks to end) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/3/99 GTH : Created. * - *=============================================================================================*/ -bool ChunkLoadClass::Close_Micro_Chunk() -{ - assert(InMicroChunk); - InMicroChunk = false; - - int csize = MCHeader.Get_Size(); - int pos = MicroChunkPosition; - - // seek the file past this micro chunk - if (pos < csize) { - - File->Seek(csize - pos,SEEK_CUR); - - // update the tracking variables for where we are in the normal chunk. - if (StackIndex > 0) { - PositionStack[StackIndex-1] += csize - pos; - } - } - - return true; -} - - -/*********************************************************************************************** - * ChunkLoadClass::Cur_Micro_Chunk_ID -- returns the ID of the current micro-chunk (asserts if * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Asserts if you are not currently inside a micro-chunk * - * Micro chunks have an id between 0 and 255 * - * * - * HISTORY: * - * 9/3/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Cur_Micro_Chunk_ID() -{ - assert(InMicroChunk); - return MCHeader.Get_Type(); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Cur_Micro_Chunk_Length -- returns the size of the current micro chunk * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Asserts if you are not currently inside a micro-chunk * - * Micro chunks have a maximum size of 255 bytes * - * * - * HISTORY: * - * 9/3/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Cur_Micro_Chunk_Length() -{ - assert(InMicroChunk); - return MCHeader.Get_Size(); -} - -// Seek over nbytes in the stream -uint32 ChunkLoadClass::Seek(uint32 nbytes) -{ - assert(StackIndex >= 1); - - // Don't seek if we would go past the end of the current chunk - if (PositionStack[StackIndex-1] + nbytes > (int)HeaderStack[StackIndex-1].Get_Size()) { - return 0; - } - - // Don't read if we are in a micro chunk and would go past the end of it - if (InMicroChunk && MicroChunkPosition + nbytes > MCHeader.Get_Size()) { - return 0; - } - - uint32 curpos=File->Tell(); - if (File->Seek(nbytes,SEEK_CUR)-curpos != (int)nbytes) { - return 0; - } - - // Update our position in the chunk - PositionStack[StackIndex-1] += nbytes; - - // Update our position in the micro chunk if we are in one - if (InMicroChunk) { - MicroChunkPosition += nbytes; - } - - return nbytes; -} - -/*********************************************************************************************** - * ChunkLoadClass::Read -- Read data from the file * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/17/1997 GH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Read(void * buf,uint32 nbytes) -{ - assert(StackIndex >= 1); - - // Don't read if we would go past the end of the current chunk - if (PositionStack[StackIndex-1] + nbytes > (int)HeaderStack[StackIndex-1].Get_Size()) { - return 0; - } - - // Don't read if we are in a micro chunk and would go past the end of it - if (InMicroChunk && MicroChunkPosition + nbytes > MCHeader.Get_Size()) { - return 0; - } - - if (File->Read(buf,nbytes) != (int)nbytes) { - return 0; - } - - // Update our position in the chunk - PositionStack[StackIndex-1] += nbytes; - - // Update our position in the micro chunk if we are in one - if (InMicroChunk) { - MicroChunkPosition += nbytes; - } - - return nbytes; -} - - -/*********************************************************************************************** - * ChunkLoadClass::Read -- read an IOVector2Struct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Read(IOVector2Struct * v) -{ - assert(v != NULL); - return Read(v,sizeof(v)); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Read -- read an IOVector3Struct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Read(IOVector3Struct * v) -{ - assert(v != NULL); - return Read(v,sizeof(v)); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Read -- read an IOVector4Struct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Read(IOVector4Struct * v) -{ - assert(v != NULL); - return Read(v,sizeof(v)); -} - - -/*********************************************************************************************** - * ChunkLoadClass::Read -- read an IOQuaternionStruct * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/4/99 GTH : Created. * - *=============================================================================================*/ -uint32 ChunkLoadClass::Read(IOQuaternionStruct * q) -{ - assert(q != NULL); - return Read(q,sizeof(q)); -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/chunkio.h b/Generals/Code/Tools/WW3D/pluglib/chunkio.h deleted file mode 100644 index 5ff2f9fe58..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/chunkio.h +++ /dev/null @@ -1,380 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwlib/chunkio.h 21 7/31/01 6:41p Patrick $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Tiberian Sun / Commando / G Library * - * * - * $Archive:: /Commando/Code/wwlib/chunkio.h $* - * * - * $Author:: Patrick $* - * * - * $Modtime:: 7/27/01 2:47p $* - * * - * $Revision:: 21 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef CHUNKIO_H -#define CHUNKIO_H - -#ifndef ALWAYS_H -#include "always.h" -#endif - -#ifndef BITTYPE_H -#include "BITTYPE.H" -#endif - -#ifndef WWFILE_H -#include "wwfile.h" -#endif - -#ifndef IOSTRUCT_H -#include "iostruct.h" -#endif - - -/************************************************************************************ - - ChunkIO - - (gth) This module provides classes for reading and writing chunk-based files. - For example, all of the w3d files are stored in a hierarchical-chunk format. - Basically the format is similar to IFF. All data in the file has chunk headers - wrapped around it. A chunk header contains an ID, and a Size. The size - is the number of bytes in the chunk (not including the header). The - contents of a chunk may be either: more "sub-chunks" or raw data. These classes - will automatically keep track of your positions within all of the sub and parent - chunks (to some maximum recursion depth). - - Sept 3, 1999 - (gth) Adding the new concept of "micro-chunks". Instead of filling the contents of a - chunk with data, you can fill it with "micro-chunks" which contain a single byte - id and a single byte size. Micro-chunks are used for storing simple variables - in a form that can survive revisions to the file format without paying the price - for a full chunk header. You CANNOT recursively embed micro-chunks due to their - size limitations.... - - Sept 24, 1999 - (gth) Using the MSB of the chunksize to indicate whether a chunk contains other - chunks or pure data. If the MSB is 0, the chunk contains data (so that the reader - I'm going to write doesn't break on older files) and if it is 1 then it is - assumed to contain other chunks. This does not apply to micro-chunks as they - are considered data. - -**************************************************************************************/ - -struct ChunkHeader -{ - // Functions. - ChunkHeader() : ChunkType(0), ChunkSize(0) {} - ChunkHeader(uint32 type, uint32 size) {ChunkType = type; ChunkSize = size;} - - // Use these accessors to ensure you correctly deal with the data in the chunk header - void Set_Type(uint32 type) { ChunkType = type; } - uint32 Get_Type(void) { return ChunkType; } - void Set_Size(uint32 size) { ChunkSize &= 0x80000000; ChunkSize |= (size & 0x7FFFFFFF); } - void Add_Size(uint32 add) { Set_Size(Get_Size() + add); } - uint32 Get_Size(void) { return (ChunkSize & 0x7FFFFFFF); } - void Set_Sub_Chunk_Flag(bool onoff) { if (onoff) { ChunkSize |= 0x80000000; } else { ChunkSize &= 0x7FFFFFFF; } } - int Get_Sub_Chunk_Flag(void) { return (ChunkSize & 0x80000000); } - - // Chunk type and size. - // Note: MSB of ChunkSize is used to indicate whether this chunk - // contains other chunks or data. - uint32 ChunkType; - uint32 ChunkSize; -}; - -struct MicroChunkHeader -{ - MicroChunkHeader() {} - MicroChunkHeader(uint8 type, uint8 size) { ChunkType = type, ChunkSize = size; } - - void Set_Type(uint8 type) { ChunkType = type; } - uint8 Get_Type(void) { return ChunkType; } - void Set_Size(uint8 size) { ChunkSize = size; } - void Add_Size(uint8 add) { Set_Size(Get_Size() + add); } - uint8 Get_Size(void) { return ChunkSize; } - - uint8 ChunkType; - uint8 ChunkSize; -}; - - -/************************************************************************************** -** -** ChunkSaveClass -** Wrap an instance of this class around an opened file for easy chunk -** creation. -** -**************************************************************************************/ -class ChunkSaveClass -{ -public: - ChunkSaveClass(FileClass * file); - - // Chunk methods - bool Begin_Chunk(uint32 id); - bool End_Chunk(); - int Cur_Chunk_Depth(); - - // Micro chunk methods - bool Begin_Micro_Chunk(uint32 id); - bool End_Micro_Chunk(); - - // Write data into the file - uint32 Write(const void *buf, uint32 nbytes); - uint32 Write(const IOVector2Struct & v); - uint32 Write(const IOVector3Struct & v); - uint32 Write(const IOVector4Struct & v); - uint32 Write(const IOQuaternionStruct & q); - -private: - - enum { MAX_STACK_DEPTH = 256 }; - - FileClass * File; - - // Chunk building support - int StackIndex; - int PositionStack[MAX_STACK_DEPTH]; - ChunkHeader HeaderStack[MAX_STACK_DEPTH]; - - // MicroChunk building support - bool InMicroChunk; - int MicroChunkPosition; - MicroChunkHeader MCHeader; -}; - - -/************************************************************************************** -** -** ChunkLoadClass -** wrap an instance of one of these objects around an opened file -** to easily parse the chunks in the file -** -**************************************************************************************/ -class ChunkLoadClass -{ -public: - - ChunkLoadClass(FileClass * file); - - // Chunk methods - bool Open_Chunk(); - bool Close_Chunk(); - uint32 Cur_Chunk_ID(); - uint32 Cur_Chunk_Length(); - int Cur_Chunk_Depth(); - int Contains_Chunks(); - - // Micro Chunk methods - bool Open_Micro_Chunk(); - bool Close_Micro_Chunk(); - uint32 Cur_Micro_Chunk_ID(); - uint32 Cur_Micro_Chunk_Length(); - - // Read a block of bytes from the output stream. - uint32 Read(void *buf, uint32 nbytes); - uint32 Read(IOVector2Struct * v); - uint32 Read(IOVector3Struct * v); - uint32 Read(IOVector4Struct * v); - uint32 Read(IOQuaternionStruct * q); - - // Seek over a block of bytes in the stream (same as Read but don't copy the data to a buffer) - uint32 Seek(uint32 nbytes); - -private: - - enum { MAX_STACK_DEPTH = 256 }; - - FileClass * File; - - // Chunk reading support - int StackIndex; - uint32 PositionStack[MAX_STACK_DEPTH]; - ChunkHeader HeaderStack[MAX_STACK_DEPTH]; - - // Micro-chunk reading support - bool InMicroChunk; - int MicroChunkPosition; - MicroChunkHeader MCHeader; - -}; - -/* -** WRITE_WWSTRING_CHUNK - use this one-line macro to easily create a chunk to save a potentially -** long string. Note: This macro does NOT create a micro chunk... -** Example: -** -** csave.Begin_Chunk(CHUNKID_PARENT); -** ParentClass::Save (csave); -** csave.End_Chunk(); -** -** WRITE_WWSTRING_CHUNK(csave, CHUNKID_NAME, string); -** WRITE_WIDESTRING_CHUNK(csave, CHUNKID_WIDE_NAME, wide_string); -** -** csave.Begin_Chunk(PHYSGRID_CHUNK_VARIABLES); -** WRITE_MICRO_CHUNK(csave,PHYSGRID_VARIABLE_VERSION,version); -** WRITE_MICRO_CHUNK(csave,PHYSGRID_VARIABLE_DUMMYVISID,DummyVisId); -** WRITE_MICRO_CHUNK(csave,PHYSGRID_VARIABLE_BASEVISID,BaseVisId); -** csave.End_Chunk(); -** -*/ -#define WRITE_WWSTRING_CHUNK(csave,id,var) { \ - csave.Begin_Chunk(id); \ - csave.Write((const TCHAR *)var, var.Get_Length () + 1); \ - csave.End_Chunk(); } - -#define WRITE_WIDESTRING_CHUNK(csave,id,var) { \ - csave.Begin_Chunk(id); \ - csave.Write((const WCHAR *)var, (var.Get_Length () + 1) * 2); \ - csave.End_Chunk(); } - - -/* -** READ_WWSTRING_CHUNK - use this macro in a switch statement to read the contents -** of a chunk into a string object. -** Example: -** -** while (cload.Open_Chunk()) { -** -** switch(cload.Cur_Chunk_ID()) { -** READ_WWSTRING_CHUNK(cload,CHUNKID_NAME,string); -** READ_WIDESTRING_CHUNK(cload,CHUNKID_WIDE_NAME,wide_string); -** } -** cload.Close_Chunk(); -** } -** -*/ -#define READ_WWSTRING_CHUNK(cload,id,var) \ - case (id): cload.Read(var.Get_Buffer(cload.Cur_Chunk_Length()),cload.Cur_Chunk_Length()); break; \ - -#define READ_WIDESTRING_CHUNK(cload,id,var) \ - case (id): cload.Read(var.Get_Buffer((cload.Cur_Chunk_Length()+1)/2),cload.Cur_Chunk_Length()); break; \ - - -/* -** WRITE_MICRO_CHUNK - use this one-line macro to easily make a micro chunk for an individual variable. -** Note that you should always wrap your micro-chunks inside a normal chunk. -** Example: -** -** csave.Begin_Chunk(PHYSGRID_CHUNK_VARIABLES); -** WRITE_MICRO_CHUNK(csave,PHYSGRID_VARIABLE_VERSION,version); -** WRITE_MICRO_CHUNK(csave,PHYSGRID_VARIABLE_DUMMYVISID,DummyVisId); -** WRITE_MICRO_CHUNK(csave,PHYSGRID_VARIABLE_BASEVISID,BaseVisId); -** csave.End_Chunk(); -*/ -#define WRITE_MICRO_CHUNK(csave,id,var) { \ - csave.Begin_Micro_Chunk(id); \ - csave.Write(&var,sizeof(var)); \ - csave.End_Micro_Chunk(); } - -#define WRITE_SAFE_MICRO_CHUNK(csave,id,var,type) { \ - csave.Begin_Micro_Chunk(id); \ - type data = (type)var; \ - csave.Write(&data,sizeof(data)); \ - csave.End_Micro_Chunk(); } - -#define WRITE_MICRO_CHUNK_STRING(csave,id,var) { \ - csave.Begin_Micro_Chunk(id); \ - csave.Write(var, strlen(var) + 1); \ - csave.End_Micro_Chunk(); } - -#define WRITE_MICRO_CHUNK_WWSTRING(csave,id,var) { \ - csave.Begin_Micro_Chunk(id); \ - csave.Write((const TCHAR *)var, var.Get_Length () + 1); \ - csave.End_Micro_Chunk(); } - -#define WRITE_MICRO_CHUNK_WIDESTRING(csave,id,var) { \ - csave.Begin_Micro_Chunk(id); \ - csave.Write((const WCHAR *)var, (var.Get_Length () + 1) * 2); \ - csave.End_Micro_Chunk(); } - - -/* -** READ_MICRO_CHUNK - use this macro in a switch statement to read a micro chunk into a variable -** Example: -** -** while (cload.Open_Micro_Chunk()) { -** -** switch(cload.Cur_Micro_Chunk_ID()) { -** READ_MICRO_CHUNK(cload,PHYSGRID_VARIABLE_VERSION,version); -** READ_MICRO_CHUNK(cload,PHYSGRID_VARIABLE_DUMMYVISID,DummyVisId); -** READ_MICRO_CHUNK(cload,PHYSGRID_VARIABLE_BASEVISID,BaseVisId); -** } -** cload.Close_Micro_Chunk(); -** } -*/ -#define READ_MICRO_CHUNK(cload,id,var) \ - case (id): cload.Read(&var,sizeof(var)); break; \ - -/* -** Like READ_MICRO_CHUNK but reads items straight into the data safe. -*/ -#define READ_SAFE_MICRO_CHUNK(cload,id,var,type) \ - case (id): { \ - void *temp_read_buffer_on_the_stack = _alloca(sizeof(var)); \ - cload.Read(temp_read_buffer_on_the_stack, sizeof(var)); \ - var = *((type*)temp_read_buffer_on_the_stack); \ - break; \ - } - -#define READ_MICRO_CHUNK_STRING(cload,id,var,size) \ - case (id): WWASSERT(cload.Cur_Micro_Chunk_Length() <= size); cload.Read(var,cload.Cur_Micro_Chunk_Length()); break; \ - -#define READ_MICRO_CHUNK_WWSTRING(cload,id,var) \ - case (id): cload.Read(var.Get_Buffer(cload.Cur_Micro_Chunk_Length()),cload.Cur_Micro_Chunk_Length()); break; \ - -#define READ_MICRO_CHUNK_WIDESTRING(cload,id,var) \ - case (id): cload.Read(var.Get_Buffer((cload.Cur_Micro_Chunk_Length()+1)/2),cload.Cur_Micro_Chunk_Length()); break; \ - -/* -** These load macros make it easier to add extra code to a specifc case -*/ -#define LOAD_MICRO_CHUNK(cload,var) \ - cload.Read(&var,sizeof(var)); \ - -#define LOAD_MICRO_CHUNK_WWSTRING(cload,var) \ - cload.Read(var.Get_Buffer(cload.Cur_Micro_Chunk_Length()),cload.Cur_Micro_Chunk_Length()); \ - -#define LOAD_MICRO_CHUNK_WIDESTRING(cload,var) \ - cload.Read(var.Get_Buffer((cload.Cur_Micro_Chunk_Length()+1)/2),cload.Cur_Micro_Chunk_Length()); \ - - -/* -** OBSOLETE_MICRO_CHUNK - use this macro in a switch statement when you want your code -** to skip a given micro chunk but not fall through to your 'default' case statement which -** prints an "unrecognized chunk" warning message. -*/ -#define OBSOLETE_MICRO_CHUNK(id) \ - case (id): break; - - - -#endif // CHUNKIO_H diff --git a/Generals/Code/Tools/WW3D/pluglib/errclass.h b/Generals/Code/Tools/WW3D/pluglib/errclass.h deleted file mode 100644 index 98c4dcbd6d..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/errclass.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/pluglib/errclass.h 5 6/25/99 10:46a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando Tools - W3D export * - * * - * $Archive:: /Commando/Code/Tools/pluglib/errclass.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 6/24/99 3:38p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef ERRCLASS_H -#define ERRCLASS_H - -#include - - -class ErrorClass -{ -public: - ErrorClass(char * format,...); - ErrorClass(const ErrorClass & that); - ~ErrorClass(void) { if (error_message != NULL) free(error_message); } - - ErrorClass & operator = (const ErrorClass & that); - - char * error_message; -}; - -inline ErrorClass::ErrorClass(char * format,...) -{ - va_list va; - char tmp[1024]; - va_start(va,format); - vsprintf(tmp,format,va); - assert(strlen(tmp) < 1024); - va_end(va); - error_message = strdup(tmp); -} - -inline ErrorClass::ErrorClass(const ErrorClass & that) : - error_message(NULL) -{ - *this = that; -} - -inline ErrorClass & ErrorClass::operator = (const ErrorClass & that) -{ - if (error_message != NULL) { - free(error_message); - error_message = NULL; - } - - if (that.error_message != NULL) { - error_message = strdup(that.error_message); - } - - return *this; -} - - -#endif //ERRCLASS_H \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/hashcalc.h b/Generals/Code/Tools/WW3D/pluglib/hashcalc.h deleted file mode 100644 index 5a3e992eb3..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/hashcalc.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Westwood Library * - * * - * $Archive:: /G/wwlib/hashcalc.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 4/02/99 11:59a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - - -#ifndef HASHCALC_H -#define HASHCALC_H - - -/* -** HashCalculatorClass -** The hash calculator is used to abstract the process of computing a hash -** value for an object. Also, when dealing with floating point values, you -** may need to have a fudge factor and therefore have several valid hash -** values for a particular object (generated by adding and subtracting an -** epsilon to the number(s)). This class lets you define any number -** of hash values. This class is used by the UniqueArrayClass and the HashTableClass -** templates. Basically, you give one of these to the UniqueArrayClass at -** construction time. It will call the Num_Hash_Bits function in order to -** properly allocate its hash table. Then, for each object you pass into the -** Add function, it will call Compute_Hash, then it will loop through -** Num_Hash_Values, calling Get_Hash_Value for each index and see if the object -** is found in the indicated slot. Also, when it is checking to see if it has -** the object you "Added", the Items_Match function is called. This again -** allows you to do epsilon tests. Make sense? -*/ -template class HashCalculatorClass -{ -public: - virtual bool Items_Match(const T & a, const T & b) = 0; - virtual void Compute_Hash(const T & item) = 0; - virtual int Num_Hash_Bits(void) = 0; - virtual int Num_Hash_Values(void) = 0; - virtual int Get_Hash_Value(int index = 0) = 0; -}; - - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/hsv.cpp b/Generals/Code/Tools/WW3D/pluglib/hsv.cpp deleted file mode 100644 index 81a7e6bffe..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/hsv.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Library/HSV.CPP $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 7/22/97 11:37a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * HSVClass::Adjust -- Adjust an HSV color toward specified color. * - * HSVClass::Difference -- Finds the difference between two HSV color objects. * - * HSVClass::operator RGBClass -- Conversion operator for RGBClass object. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "always.h" -#include "hsv.h" -#include "rgb.h" - -HSVClass const HSVClass::BlackColor(0, 0, 0); - - -/*********************************************************************************************** - * HSVClass::Adjust -- Adjust an HSV color toward specified color. * - * * - * This routine will adjust the HSV color object toward the color of the specified HSV * - * object. Typical users of this would be palette morphing or fading routines. * - * * - * INPUT: ratio -- The ratio to move the HSV object toward the color specified. A value * - * of zero means no movement at all. A value of 255 means move completely * - * toward the specified color (changed completely). * - * * - * hsv -- A reference to the color that the current HSV object is to change * - * toward. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 02/20/1996 JLB : Created. * - *=============================================================================================*/ -void HSVClass::Adjust(int ratio, HSVClass const & hsv) -{ - /* - ** Ratio conversion is limited to 0 through 100%. This is - ** the range of 0 to 255. - */ - ratio &= 0x00FF; - - /* - ** Adjust the color guns by the ratio specified toward the - ** destination color. - */ - int value = hsv.Get_Value() - Get_Value(); - Value = (unsigned char)(Get_Value() + (value * ratio) / 256); - - int saturation = hsv.Get_Saturation() - Get_Saturation(); - Saturation = (unsigned char)(Get_Saturation() + (saturation * ratio) / 256); - - int hue = hsv.Get_Hue() - Get_Hue(); - Hue = (unsigned char)(Get_Hue() + (hue * ratio) / 256); -} - - -/*********************************************************************************************** - * HSVClass::Difference -- Finds the difference between two HSV color objects. * - * * - * This routine will determine a color difference between two HSV objects. The difference * - * has no particular meaning other that larger numbers meaning greater difference. * - * * - * INPUT: hsv -- The other HSV object to compare this HSV object to. * - * * - * OUTPUT: Returns with a relative distance (in arbitrary units) between this HSV object and * - * the HSV object supplied. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 02/20/1996 JLB : Created. * - *=============================================================================================*/ -int HSVClass::Difference(HSVClass const & hsv) const -{ - int hue = (int)Hue - (int)hsv.Hue; - if (hue < 0) hue = -hue; - - int saturation = (int)Saturation - (int)hsv.Saturation; - if (saturation < 0) saturation = -saturation; - - int value = (int)Value - (int)hsv.Value; - if (value < 0) value = -value; - - return(hue*hue + saturation*saturation + value*value); -} - - -/*********************************************************************************************** - * HSVClass::operator RGBClass -- Conversion operator for RGBClass object. * - * * - * This conversion operator will convert the HSV object into an RGB object. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with a reference (implied) of the RGBClass object that most closely * - * matches this HSVClass object. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 02/20/1996 JLB : Created. * - *=============================================================================================*/ -HSVClass::operator RGBClass (void) const -{ - unsigned int i; // Integer part. - unsigned int f; // Fractional or remainder part. f/HSV_BASE gives fraction. - unsigned int tmp; // Temporary variable to help with calculations. - unsigned int values[7]; // Possible rgb values. Don't use zero. - - int hue = Get_Hue(); - int saturation = Get_Saturation(); - int value = Get_Value(); - int red, green, blue; - - - hue *= 6; - f = hue % 255; - - // Set up possible red, green and blue values. - values[1] = - values[2] = value; - - // - // The following lines of code change - // values[3] = (v * (255 - ( (s * f) / 255) )) / 255; - // values[4] = values[5] = (v * (255 - s)) / 255; - // values[6] = (v * (255 - (s * (255 - f)) / 255)) / 255; - // so that the are rounded divides. - // - - tmp = (saturation * f) / 255; - values[3] = (value * (255 - tmp)) / 255; - - values[4] = - values[5] = (value * (255 - saturation)) / 255; - - tmp = 255 - (saturation * (255 - f)) / 255; - values[6] = (value * tmp) / 255; - - - // This should not be rounded. - i = hue / 255; - - i += (i > 4) ? -4 : 2; - red = values[i]; - - i += (i > 4) ? -4 : 2; - blue = values[i]; - - i += (i > 4) ? -4 : 2; - green = values[i]; - - RGBClass rgb((unsigned char)red, (unsigned char)green, (unsigned char)blue); - return(rgb); -} - - diff --git a/Generals/Code/Tools/WW3D/pluglib/hsv.h b/Generals/Code/Tools/WW3D/pluglib/hsv.h deleted file mode 100644 index ed57918d33..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/hsv.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Library/HSV.H $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 7/22/97 11:37a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef HSV_H -#define HSV_H - -class RGBClass; -class HSVClass; - -/* -** Each color entry is represented by this class. It holds the values for the color -** attributes. The values are recorded in a range from 0 to 255 with 255 being the -** maximum. -*/ -class HSVClass -{ - private: - static HSVClass const BlackColor; - - public: - HSVClass(void) : Hue(0), Saturation(0), Value(0) {}; - HSVClass(unsigned char hue, unsigned char saturation, unsigned char value) : - Hue(hue), - Saturation(saturation), - Value(value) - {}; - operator RGBClass (void) const; - - enum { - MAX_VALUE=255 - }; - - void Adjust(int ratio, HSVClass const & hsv); - int Difference(HSVClass const & hsv) const; - int Get_Hue(void) const {return(Hue);}; - int Get_Saturation(void) const {return(Saturation);}; - int Get_Value(void) const {return(Value);}; - void Set_Hue(unsigned char value) {Hue = value;} - void Set_Saturation(unsigned char value) {Saturation = value;} - void Set_Value(unsigned char value) {Value = value;} - - private: - unsigned char Hue; - unsigned char Saturation; - unsigned char Value; -}; - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/iostruct.h b/Generals/Code/Tools/WW3D/pluglib/iostruct.h deleted file mode 100644 index 1d1565fdf6..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/iostruct.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWLib * - * * - * $Archive:: /G/wwlib/iostruct.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 4/02/99 11:59a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef IOSTRUCT_H -#define IOSTRUCT_H - -#ifndef BITTYPE_H -#include "BITTYPE.H" -#endif - -/* -** Some useful structures for writing/writing (safe from changes). -** The chunk IO classes contain code for reading and writing these. -*/ -struct IOVector2Struct -{ - float32 X; - float32 Y; -}; - -struct IOVector3Struct -{ - float32 X; // X,Y,Z coordinates - float32 Y; - float32 Z; -}; - -struct IOVector4Struct -{ - float32 X; - float32 Y; - float32 Z; - float32 W; -}; - -struct IOQuaternionStruct -{ - float32 Q[4]; -}; - - - -#endif - diff --git a/Generals/Code/Tools/WW3D/pluglib/jshell.cpp b/Generals/Code/Tools/WW3D/pluglib/jshell.cpp deleted file mode 100644 index 8f2ba0e54e..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/jshell.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/Tools/pluglib/jshell.cpp $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 11/07/00 2:32p $* - * * - * $Revision:: 28 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Fatal -- General purpose fatal error handler. * - * Set_Bit -- Set bit in a bit array. * - * Get_Bit -- Fetch the bit value from a bit array. * - * First_True_Bit -- Return with the first true bit index. * - * First_False_Bit -- Find the first false bit in the bit array. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "always.h" - - -/*********************************************************************************************** - * Set_Bit -- Set bit in a bit array. * - * * - * This routine is used to set (or clear) a bit in a bit array. * - * * - * INPUT: array -- Pointer to the bit array. * - * * - * bit -- The bit number to set. I.e., bit 32 is the first bit in the second * - * long word of memory. * - * * - * value -- The value to set the bit. The only values supported are 0 and 1. * - * * - * OUTPUT: none * - * * - * WARNINGS: Be sure that the array is big enough to set the specified bit. * - * * - * HISTORY: * - * 10/06/1997 JLB : Created. * - *=============================================================================================*/ -void Set_Bit(void * array, int bit, int value) -{ - unsigned char mask = (unsigned char)(1 << (bit % 8)); - - if (value != 0) { - *((unsigned char *)array + (bit/8)) |= mask; - } else { - *((unsigned char *)array + (bit/8)) &= (unsigned char)~mask; - } -} - - -/*********************************************************************************************** - * Get_Bit -- Fetch the bit value from a bit array. * - * * - * This routine will fetch the specified bit value from the bit array. This is the * - * counterpart function to the Set_Bit() function. * - * * - * INPUT: array -- Pointer to the bit array to fetch the bit value from. * - * * - * bit -- The bit number to fetch. * - * * - * OUTPUT: Returns with the value of the bit. This return value will be either 1 or 0. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/06/1997 JLB : Created. * - *=============================================================================================*/ -int Get_Bit(void const * array, int bit) -{ - unsigned char mask = (unsigned char)(1 << (bit % 8)); - return((*((unsigned char *)array + (bit/8)) & mask) != 0); -} - - -/*********************************************************************************************** - * First_True_Bit -- Return with the first true bit index. * - * * - * This routine will scan the bit array and return with the index for the first true bit * - * in the array. * - * * - * INPUT: array -- Pointer to the bit array to scan. * - * * - * OUTPUT: Returns with the index of the first true (set to 1) bit in the array. * - * * - * WARNINGS: This routine does not stop at the end of the array (it doesn't know where the * - * end is) so there must be at least one true bit in the array or else it will * - * end up scanning past the end (undefined results in that case). * - * * - * HISTORY: * - * 10/06/1997 JLB : Created. * - *=============================================================================================*/ -int First_True_Bit(void const * array) -{ - int index = 0; - while (*((unsigned char *)array) == 0) { - index++; - array = ((char*)array) + 1; - } - int subindex; - for (subindex = 0; subindex < 8; subindex++) { - if (Get_Bit(array, subindex)) break; - } - return(index * 8 + subindex); -} - - -/*********************************************************************************************** - * First_False_Bit -- Find the first false bit in the bit array. * - * * - * This routine will scan the bit array and return with the index of the first false (set * - * to 0) bit found. * - * * - * INPUT: array -- Pointer to the bit array to scan. * - * * - * OUTPUT: Returns with the index of the first false bit found in the array. * - * * - * WARNINGS: This routine will not stop scanning until a false bit was found. This means * - * that there must be at least one false bit in the array or else it will scan * - * past the end of the array. * - * * - * HISTORY: * - * 10/06/1997 JLB : Created. * - *=============================================================================================*/ -int First_False_Bit(void const * array) -{ - int index = 0; - while (*((unsigned char *)array) == 0xFF) { - index++; - array = ((char*)array) + 1; - } - int subindex; - for (subindex = 0; subindex < 8; subindex++) { - if (!Get_Bit(array, subindex)) break; - } - return(index * 8 + subindex); -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/matrix3d.cpp b/Generals/Code/Tools/WW3D/pluglib/matrix3d.cpp deleted file mode 100644 index 324b8c8f9b..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/matrix3d.cpp +++ /dev/null @@ -1,841 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/matrix3d.cpp 39 2/03/00 4:55p Jason_a $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : MATRIX3D.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 28, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * Matrix3D::Set -- Init a matrix3D from a matrix3 and a position * - * Matrix3D::Set -- Init a matrix3D from a quaternion and a position * - * Matrix3D::Get_X_Rotation -- approximates the rotation about the X axis * - * Matrix3D::Get_Y_Rotation -- approximates the rotation about the Y axis * - * Matrix3D::Get_Z_Rotation -- approximates the rotation about the Z axis * - * Matrix3D::Multiply -- matrix multiplication without temporaries. * - * Matrix3D::Inverse_Rotate_Vector -- rotates a vector by the inverse of the 3x3 sub-matrix * - * Matrix3D::Transform_Min_Max_AABox -- compute transformed axis-aligned box * - * Matrix3D::Transform_Center_Extent_AABox -- compute transformed axis-aligned box * - * Matrix3D::Get_Inverse -- calculate the inverse of this matrix * - * Matrix3D::Get_Orthogonal_Inverse -- Returns the inverse of the matrix * - * Matrix3D::Re_Orthogonalize -- makes this matrix orthogonal. * - * Matrix3D::Is_Orthogonal -- checks whether this matrix is orthogonal * - * Lerp - linearly interpolate matrices (orientation is slerped) * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "matrix3d.h" - -#include -#include -#include -//#include -#include "vector3.h" -#include "WWmatrix3.h" -#include "matrix4.h" -#include "w3dquat.h" - -// some static matrices which are sometimes useful -const Matrix3D Matrix3D::Identity -( - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateX90 -( - 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0, - 0.0, 1.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateX180 -( - 1.0, 0.0, 0.0, 0.0, - 0.0, -1.0, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateX270 -( - 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, -1.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateY90 -( - 0.0, 0.0, 1.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - -1.0, 0.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateY180 -( - -1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateY270 -( - 0.0, 0.0, -1.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, 0.0 -); - -const Matrix3D Matrix3D::RotateZ90 -( - 0.0, -1.0, 0.0, 0.0, - 1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateZ180 -( - -1.0, 0.0, 0.0, 0.0, - 0.0, -1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - -const Matrix3D Matrix3D::RotateZ270 -( - 0.0, 1.0, 0.0, 0.0, - -1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0 -); - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix3D from a matrix3 and a position * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Set(const Matrix3 & rot,const Vector3 & pos) -{ - Row[0].Set( rot[0][0], rot[0][1], rot[0][2], pos[0]); - Row[1].Set( rot[1][0], rot[1][1], rot[1][2], pos[1]); - Row[2].Set( rot[2][0], rot[2][1], rot[2][2], pos[2]); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix3D from a quaternion and a position * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Set(const Quaternion & rot,const Vector3 & pos) -{ - Set_Rotation(rot); - Set_Translation(pos); -} - - -/*********************************************************************************************** - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/11/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Set_Rotation(const Matrix3 & m) -{ - Row[0][0] = m[0][0]; - Row[0][1] = m[0][1]; - Row[0][2] = m[0][2]; - - Row[1][0] = m[1][0]; - Row[1][1] = m[1][1]; - Row[1][2] = m[1][2]; - - Row[2][0] = m[2][0]; - Row[2][1] = m[2][1]; - Row[2][2] = m[2][2]; -} - - -/*********************************************************************************************** - * Matrix3D::Set_Rotation -- Sets the rotation part of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/11/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Set_Rotation(const Quaternion & q) -{ - Row[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - Row[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - Row[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - Row[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - Row[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - Row[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - Row[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - Row[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - Row[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); -} - - -/*********************************************************************************************** - * Matrix3D::Get_X_Rotation -- approximates the rotation about the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -float Matrix3D::Get_X_Rotation(void) const -{ - return atan2(Row[2][1], Row[1][1]); -} - - -/*********************************************************************************************** - * Matrix3D::Get_Y_Rotation -- approximates the rotation about the Y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -float Matrix3D::Get_Y_Rotation(void) const -{ - return atan2(Row[0][2], Row[2][2]); -} - - -/*********************************************************************************************** - * Matrix3D::Get_Z_Rotation -- approximates the rotation about the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -float Matrix3D::Get_Z_Rotation(void) const -{ - return atan2(Row[1][0], Row[0][0]); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Vector -- Uses the 3x3 sub-matrix to rotate a vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -Vector3 Matrix3D::Rotate_Vector(const Vector3 &vect) const -{ - return Vector3( - (Row[0][0]*vect[0] + Row[0][1]*vect[1] + Row[0][2]*vect[2]), - (Row[1][0]*vect[0] + Row[1][1]*vect[1] + Row[1][2]*vect[2]), - (Row[2][0]*vect[0] + Row[2][1]*vect[1] + Row[2][2]*vect[2]) - ); -} - - -/*********************************************************************************************** - * Matrix3D::Inverse_Rotate_Vector -- rotates a vector by the inverse of the 3x3 sub-matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/27/98 GTH : Created. * - *=============================================================================================*/ -Vector3 Matrix3D::Inverse_Rotate_Vector(const Vector3 &vect) const -{ - return Vector3( - (Row[0][0]*vect[0] + Row[1][0]*vect[1] + Row[2][0]*vect[2]), - (Row[0][1]*vect[0] + Row[1][1]*vect[1] + Row[2][1]*vect[2]), - (Row[0][2]*vect[0] + Row[1][2]*vect[1] + Row[2][2]*vect[2]) - ); -} - -/*********************************************************************************************** - * M3DC::Look_At -- Creates a "look at" transformation. * - * * - * Builds a transformation matrix which positions the origin at p, * - * points the negative z-axis towards a target t, and rolls about the z-axis * - * by the angle specified by roll. * - * * - * This can be useful for creating a camera matrix, just invert * - * the matrix after initializing it with this function... * - * * - * INPUT: * - * p - position of the coordinate system * - * t - target of the coordinate system * - * roll - roll angle (in radians) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This function is written assuming the convention that the "ground" is the X-Y plane and * - * Z is altitude. * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Look_At(const Vector3 &p,const Vector3 &t,float roll) -{ - float dx,dy,dz; //vector from p to t - float len1,len2; - float sinp,cosp; //sine and cosine of the pitch ("up-down" tilt about x) - float siny,cosy; //sine and cosine of the yaw ("left-right"tilt about z) - - dx = (t[0] - p[0]); - dy = (t[1] - p[1]); - dz = (t[2] - p[2]); - - len1 = (float)WWMath::Sqrt(dx*dx + dy*dy + dz*dz); - len2 = (float)WWMath::Sqrt(dx*dx + dy*dy); - - if (len1 != 0.0f) { - sinp = dz/len1; - cosp = len2/len1; - } else { - sinp = 0.0f; - cosp = 1.0f; - } - - if (len2 != 0.0f) { - siny = dy/len2; - cosy = dx/len2; - } else { - siny = 0.0f; - cosy = 1.0f; - } - - // init the matrix with position p and -z pointing down +x and +y up - Row[0].X = 0.0f; Row[0].Y = 0.0f; Row[0].Z = -1.0f; - Row[1].X = -1.0f; Row[1].Y = 0.0f; Row[1].Z = 0.0f; - Row[2].X = 0.0f; Row[2].Y = 1.0f; Row[2].Z = 0.0f; - - Row[0].W = p.X; - Row[1].W = p.Y; - Row[2].W = p.Z; - - // Yaw rotation to make the matrix look at the projection of the target - // into the x-y plane - Rotate_Y(siny,cosy); - - // rotate about local x axis to pitch up to the targets position - Rotate_X(sinp,cosp); - - // roll about the local z axis (negate since we look down -z) - Rotate_Z(-roll); -} - - -/*********************************************************************************************** - * M3DC::Obj_Look_At -- Commando Object "look at" transformation. * - * * - * Builds a transformation matrix which positions the origin at p, * - * points the positive X axis towards a target t, and rolls about the X axis * - * by the angle specified by roll. * - * * - * The object convention used by Commando and G is Forward = +X, Left = +Y, Up = +Z. The * - * world is basically the x-y plane with z as altitude and +x is the default "forward". * - * * - * INPUT: * - * p - position of the coordinate system * - * t - target of the coordinate system * - * roll - roll angle (in radians) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Obj_Look_At(const Vector3 &p,const Vector3 &t,float roll) -{ - float dx,dy,dz; //vector from p to t - float len1,len2; - float sinp,cosp; //sine and cosine of the pitch ("up-down" tilt about y) - float siny,cosy; //sine and cosine of the yaw ("left-right"tilt about z) - - dx = (t[0] - p[0]); - dy = (t[1] - p[1]); - dz = (t[2] - p[2]); - - len1 = (float)sqrt(dx*dx + dy*dy + dz*dz); - len2 = (float)sqrt(dx*dx + dy*dy); - - if (len1 != 0.0f) { - sinp = dz/len1; - cosp = len2/len1; - } else { - sinp = 0.0f; - cosp = 1.0f; - } - - if (len2 != 0.0f) { - siny = dy/len2; - cosy = dx/len2; - } else { - siny = 0.0f; - cosy = 1.0f; - } - - Make_Identity(); - Translate(p); - - // Yaw rotation to projection of target in x-y plane - Rotate_Z(siny,cosy); - - // Pitch rotation - Rotate_Y(-sinp,cosp); - - // Roll rotation - Rotate_X(roll); -} - - -/*********************************************************************************************** - * Matrix3D::Get_Inverse -- calculate the inverse of this matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 8/7/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Get_Inverse(Matrix3D & inv) const -{ - // TODO: Implement the general purpose inverse function here (once we need it :-) - Get_Orthogonal_Inverse(inv); -} - -/*********************************************************************************************** - * Matrix3D::Get_Orthogonal_Inverse -- Returns the inverse of the matrix * - * * - * NOTE!!! This only works if the matrix is really ORTHOGONAL!!! * - * * - *********************************************************************************************** - * Inverting an orthogonal Matrix3D * - * * - * M is the original transform, * - * R is rotation submatrix, * - * T is translation vector in M. * - * * - * To build MINV * - * * - * R' = transpose of R (inverse of orthogonal 3x3 matrix is transpose) * - * T' = -R'T * - * * - * Build MINV with R'and T' * - * MINV is the inverse of M * - * * - *********************************************************************************************** - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix3D::Get_Orthogonal_Inverse(Matrix3D & inv) const -{ - // Transposing the rotation submatrix - inv.Row[0][0] = Row[0][0]; - inv.Row[0][1] = Row[1][0]; - inv.Row[0][2] = Row[2][0]; - - inv.Row[1][0] = Row[0][1]; - inv.Row[1][1] = Row[1][1]; - inv.Row[1][2] = Row[2][1]; - - inv.Row[2][0] = Row[0][2]; - inv.Row[2][1] = Row[1][2]; - inv.Row[2][2] = Row[2][2]; - - // Now, calculate translation portion of matrix: - // T' = -R'T - Vector3 trans = Get_Translation(); - trans = inv.Rotate_Vector(trans); - trans = -trans; - - inv.Row[0][3] = trans[0]; - inv.Row[1][3] = trans[1]; - inv.Row[2][3] = trans[2]; -} - -/*********************************************************************************************** - * Copy_3x3_Matrix(float *matrix) -- Copies a 3x3 (float[9]) matrix into this matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/16/98 EHC : Created. * - *=============================================================================================*/ -void Matrix3D::Copy_3x3_Matrix(float matrix[3][3]) -{ - Row[0][0] = matrix[0][0]; - Row[0][1] = matrix[0][1]; - Row[0][2] = matrix[0][2]; - Row[0][3] = 0; - Row[1][0] = matrix[1][0]; - Row[1][1] = matrix[1][1]; - Row[1][2] = matrix[1][2]; - Row[1][3] = 0; - Row[2][0] = matrix[2][0]; - Row[2][1] = matrix[2][1]; - Row[2][2] = matrix[2][2]; - Row[2][3] = 0; -} - - - -/*********************************************************************************************** - * Matrix3D::Multiply -- matrix multiplication without temporaries. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/22/98 GTH : Created. * - *=============================================================================================*/ -//void print_matrix(const Matrix3D & m); -void Matrix3D::Multiply(const Matrix3D & A,const Matrix3D & B,Matrix3D * set_res) -{ - assert(set_res != NULL); - - Matrix3D tmp; - Matrix3D * Aptr; - float tmp1,tmp2,tmp3; - - // Check for aliased parameters, copy the 'A' matrix into a temporary if the - // result is going into 'A'. (in this case, this function is no better than - // the overloaded C++ operator...) - if (set_res == &A) { - tmp = A; - Aptr = &tmp; - } else { - Aptr = (Matrix3D *)&A; - } - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - (*set_res)[0][0] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][0] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][0] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - (*set_res)[0][1] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][1] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][1] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - (*set_res)[0][2] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3; - (*set_res)[1][2] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3; - (*set_res)[2][2] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3; - - tmp1 = B[0][3]; - tmp2 = B[1][3]; - tmp3 = B[2][3]; - - (*set_res)[0][3] = (*Aptr)[0][0]*tmp1 + (*Aptr)[0][1]*tmp2 + (*Aptr)[0][2]*tmp3 + (*Aptr)[0][3]; - (*set_res)[1][3] = (*Aptr)[1][0]*tmp1 + (*Aptr)[1][1]*tmp2 + (*Aptr)[1][2]*tmp3 + (*Aptr)[1][3]; - (*set_res)[2][3] = (*Aptr)[2][0]*tmp1 + (*Aptr)[2][1]*tmp2 + (*Aptr)[2][2]*tmp3 + (*Aptr)[2][3]; - -} - - -/*********************************************************************************************** - * Matrix3D::Transform_Min_Max_AABox -- compute transformed axis-aligned box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/17/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Transform_Min_Max_AABox -( - const Vector3 & min, - const Vector3 & max, - Vector3 * set_min, - Vector3 * set_max -) const -{ - assert(set_min != &min); - assert(set_max != &max); - - float tmp0,tmp1; - - // init the min and max to the translation of the transform - set_min->X = set_max->X = Row[0][3]; - set_min->Y = set_max->Y = Row[1][3]; - set_min->Z = set_max->Z = Row[2][3]; - - // now push them both out by the projections of the original intervals - for (int i=0; i<3; i++) { - - for (int j=0; j<3; j++) { - - tmp0 = Row[i][j] * min[j]; - tmp1 = Row[i][j] * max[j]; - - if (tmp0 < tmp1) { - - (*set_min)[i] += tmp0; - (*set_max)[i] += tmp1; - - } else { - - (*set_min)[i] += tmp1; - (*set_max)[i] += tmp0; - - } - } - } -} - - -/*********************************************************************************************** - * Matrix3D::Transform_Center_Extent_AABox -- compute transformed axis-aligned box * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/17/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Transform_Center_Extent_AABox -( - const Vector3 & center, - const Vector3 & extent, - Vector3 * set_center, - Vector3 * set_extent -) const -{ - assert(set_center != ¢er); - assert(set_extent != &extent); - - // push each extent out to the projections of the original extents - for (int i=0; i<3; i++) { - - // start the center out at the translation portion of the matrix - // and the extent at zero - (*set_center)[i] = Row[i][3]; - (*set_extent)[i] = 0.0f; - - for (int j=0; j<3; j++) { - - (*set_center)[i] += Row[i][j] * center[j]; - (*set_extent)[i] += WWMath::Fabs(Row[i][j] * extent[j]); - - } - } -} - - -/*********************************************************************************************** - * Matrix3D::Is_Orthogonal -- checks whether this matrix is orthogonal * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 9/16/98 GTH : Created. * - *=============================================================================================*/ -int Matrix3D::Is_Orthogonal(void) const -{ - Vector3 x(Row[0].X,Row[0].Y,Row[0].Z); - Vector3 y(Row[1].X,Row[1].Y,Row[1].Z); - Vector3 z(Row[2].X,Row[2].Y,Row[2].Z); - - if (Vector3::Dot_Product(x,y) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(y,z) > WWMATH_EPSILON) return 0; - if (Vector3::Dot_Product(z,x) > WWMATH_EPSILON) return 0; - - if (WWMath::Fabs(x.Length() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(y.Length() - 1.0f) > WWMATH_EPSILON) return 0; - if (WWMath::Fabs(z.Length() - 1.0f) > WWMATH_EPSILON) return 0; - - return 1; -} - -/*********************************************************************************************** - * Matrix3D::Re_Orthogonalize -- makes this matrix orthogonal. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * This function is rather expensive, should only be used if you *know* numerical error is * - * killing you. * - * * - * HISTORY: * - * 9/16/98 GTH : Created. * - *=============================================================================================*/ -void Matrix3D::Re_Orthogonalize(void) -{ - Vector3 x(Row[0][0],Row[0][1],Row[0][2]); - Vector3 y(Row[1][0],Row[1][1],Row[1][2]); - Vector3 z; - - Vector3::Cross_Product(x,y,&z); - Vector3::Cross_Product(z,x,&y); - - float len = x.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - x *= 1.0f/len; - } - - len = y.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - y *= 1.0f/len; - } - - len = z.Length(); - if (len < WWMATH_EPSILON) { - Make_Identity(); - return; - } else { - z *= 1.0f/len; - } - - Row[0][0] = x.X; - Row[0][1] = x.Y; - Row[0][2] = x.Z; - - Row[1][0] = y.X; - Row[1][1] = y.Y; - Row[1][2] = y.Z; - - Row[2][0] = z.X; - Row[2][1] = z.Y; - Row[2][2] = z.Z; -} - - -/*********************************************************************************************** - * Lerp - linearly interpolate matrices (orientation is slerped) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/05/1998 NH : Created. * - *=============================================================================================*/ -Matrix3D Lerp(const Matrix3D &A, const Matrix3D &B, float factor) -{ - assert(factor >= 0.0f); - assert(factor <= 1.0f); - - // Lerp position - Vector3 pos = Lerp(A.Get_Translation(), B.Get_Translation(), factor); - Quaternion rot = Slerp(Build_Quaternion(A), Build_Quaternion(B), factor); - return Matrix3D(rot, pos); -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/matrix3d.h b/Generals/Code/Tools/WW3D/pluglib/matrix3d.h deleted file mode 100644 index 8b91fa13ea..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/matrix3d.h +++ /dev/null @@ -1,1516 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /G/WWMath/matrix3d.h 49 1/13/00 2:57p Naty_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : MATRIX3D.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix3D::Matrix3D -- Constructors for Matrix3D * - * Matrix3D::Set -- init a Matrix3D from an arrray of 12 floats * - * Matrix3D::Set -- Init a Matrix3D from 12 individual floats * - * Matrix3D::Set -- Init a matrix from 3 axis vectors and a position * - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * Matrix3D::Set -- Init a matrix to be a pure translation * - * Matrix3D::Make_Identity -- Initializes the matrix to be the identity matrix * - * Matrix3D::Translate -- Post-Multiplies by a Translation Matrix * - * Matrix3D::Translate -- Post-Multiplies the matrix by a translation matrix * - * M3DC::Translate_X -- Post-Multiplies the matrix by a translation matrix with X only * - * M3DC::Translate_Y -- Post-Multiplies the matrix by a translation matrix with Y only * - * M3DC::Translate_Z -- Post-Multiplies the matrix by a translation matrix with Z only * - * Matrix3D::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * Matrix3D::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * Matrix3D::Rotate_Y -- Post-multiplies the matrix by a rotation about the Y axis * - * Matrix3D::Rotate_Y -- Post-Multiplies the matrix by a rotation about Y * - * Matrix3D::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * Matrix3D::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by rotation about X * - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by rotation about Y * - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by rotation about Z * - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by rotation about X * - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by rotation about Y * - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by rotation about Z * - * operator * -- Matrix multiplication * - * operator * -- Matrix - vector multiplication * - * operator == -- Matrix equality operator * - * operator != -- Matrix inequality operator * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MATRIX3D_H -#define MATRIX3D_H - -#ifdef _UNIX -#include "osdep.h" -#endif - -#include "always.h" -#include -#include "vector2.h" -#include "vector3.h" -#include "vector4.h" - -class Matrix3; -class Matrix4; -class Quaternion; - -/******************************************************************************* - - Matrix3D - - Three important notes: - - I use *column-vectors* - - I use a *right-handed* coordinate system - - These matrices are *orthogonal* - - 3D Transformation matrices. This class is really a 4x4 homogeneous - matrix where the last row is assumed to always be 0 0 0 1. However, - since I don't store the last row, you cant do some things that you can - do with a real 4x4 homogeneous matrix. - - I use column-vectors so normally transformations are post-multiplied - and camera transformations should be pre-multiplied. The methods of - this class called Translate, Rotate_X, etc. all perform post-multiplication - with the current matix. These methods (Translate, Rotate_X, etc) also - have been hand-coded to only perform the necessary arithmetic. The - * operator can be used for general purpose matrix multiplication or to - transform a vector by a matrix. - - Some operations in this class assume that the matrix is orthogonal. - -*********************************************************************************/ - -class Matrix3D -{ -public: - - // Constructors - Matrix3D(void) {} - - explicit Matrix3D(bool init) { if (init) Make_Identity(); } - - explicit Matrix3D(float m[12]); - - explicit Matrix3D( - float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34 - ); - - explicit Matrix3D( - const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos // position - ); - - explicit Matrix3D( - const Vector3 &axis, - float angle - ); - - explicit Matrix3D( - const Vector3 &axis, - float sine, - float cosine - ); - - explicit Matrix3D( - const Matrix3 & rotation, - const Vector3 & position - ); - - explicit Matrix3D( - const Quaternion & rotation, - const Vector3 & position - ); - - // Creates identity rotation w. given position. - explicit Matrix3D(const Vector3 & position); - - // Copy constructor - Matrix3D(const Matrix3D & m); - - // Assignment operator - Matrix3D & operator = (const Matrix3D & m); - - // Init functions - void Set(float m[12]); - - void Set( - float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34 - ); - - void Set( - const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos // position - ); - - void Set(const Vector3 & axis,float angle); - - void Set(const Vector3 & axis,float sine,float cosine); - - void Set(const Matrix3 & rotation,const Vector3 & position); - - void Set(const Quaternion & rotation,const Vector3 & position); - - // Creates identity rotation w. given position. - void Set(const Vector3 & position); - - // access functions: - Vector4 & operator [] (int i) { return Row[i]; } - const Vector4 & operator [] (int i) const { return Row[i]; } - - Vector3 Get_Translation(void) const { return Vector3(Row[0][3],Row[1][3],Row[2][3]); } - void Get_Translation(Vector3 * set) const { set->X = Row[0][3]; set->Y = Row[1][3]; set->Z = Row[2][3]; } - void Set_Translation(const Vector3 & t) { Row[0][3] = t[0]; Row[1][3] = t[1];Row[2][3] = t[2]; } - - void Set_Rotation(const Matrix3 & m); - void Set_Rotation(const Quaternion & q); - - float Get_X_Translation(void) const { return Row[0][3]; }; - float Get_Y_Translation(void) const { return Row[1][3]; }; - float Get_Z_Translation(void) const { return Row[2][3]; }; - - void Set_X_Translation(float x) { Row[0][3] = x; }; - void Set_Y_Translation(float y) { Row[1][3] = y; }; - void Set_Z_Translation(float z) { Row[2][3] = z; }; - - void Adjust_Translation(const Vector3 & t) { Row[0][3] += t[0]; Row[1][3] += t[1]; Row[2][3] += t[2]; }; - void Adjust_X_Translation(float x) { Row[0][3] += x; }; - void Adjust_Y_Translation(float y) { Row[1][3] += y; }; - void Adjust_Z_Translation(float z) { Row[2][3] += z; }; - - // These functions will give you the approximate amount that the - // matrix has been rotated about a given axis. These functions - // cannot be used to re-build a matrx. Use the EulerAnglesClass - // to convert a matrix into a set of three Euler angles. - float Get_X_Rotation(void) const; - float Get_Y_Rotation(void) const; - float Get_Z_Rotation(void) const; - - // Each of the transformation methods performs an - // "optimized" post-multiplication with the current matrix. - // All angles are assumed to be radians. - void Make_Identity(void); - void Translate(float x,float y,float z); - void Translate(const Vector3 &t); - void Translate_X(float x); - void Translate_Y(float y); - void Translate_Z(float z); - void Rotate_X(float theta); - void Rotate_Y(float theta); - void Rotate_Z(float theta); - void Rotate_X(float s,float c); - void Rotate_Y(float s,float c); - void Rotate_Z(float s,float c); - - // Each of these performs an "optimized" pre-multiplication with the - // current matrix. All angles are assumed to be radians. The "In_Place" - // versions do not affect the translation part of the matrix, - void Pre_Rotate_X(float theta); - void Pre_Rotate_Y(float theta); - void Pre_Rotate_Z(float theta); - void Pre_Rotate_X(float s,float c); - void Pre_Rotate_Y(float s,float c); - void Pre_Rotate_Z(float s,float c); - void In_Place_Pre_Rotate_X(float theta); - void In_Place_Pre_Rotate_Y(float theta); - void In_Place_Pre_Rotate_Z(float theta); - void In_Place_Pre_Rotate_X(float s,float c); - void In_Place_Pre_Rotate_Y(float s,float c); - void In_Place_Pre_Rotate_Z(float s,float c); - - // Points the negative Z axis at the target t. Assumes that - // the "world" uses x-y as the ground and z as altitude. - // Used for pointing cameras at targets. - void Look_At(const Vector3 &p,const Vector3 &t,float roll); - - // Previous look_at function follows the camera coordinate convention. - // This one follows the object convention used in Commando and G. I - // special cased this convention since it is used so much by us rather - // than supporting every one of the 24(?) possible conventions... - void Obj_Look_At(const Vector3 &p,const Vector3 &t,float roll); - - // use the 3x3 sub-matrix only (ignore translation) - Vector3 Rotate_Vector(const Vector3 &vect) const; - Vector3 Inverse_Rotate_Vector(const Vector3 &vect) const; - - // these get the a vector representing the direction an axis is pointing - Vector3 Get_X_Vector() const { return Vector3(Row[0][0], Row[1][0], Row[2][0]); } - Vector3 Get_Y_Vector() const { return Vector3(Row[0][1], Row[1][1], Row[2][1]); } - Vector3 Get_Z_Vector() const { return Vector3(Row[0][2], Row[1][2], Row[2][2]); } - void Get_X_Vector(Vector3 * set_x) const { set_x->Set(Row[0][0], Row[1][0], Row[2][0]); } - void Get_Y_Vector(Vector3 * set_y) const { set_y->Set(Row[0][1], Row[1][1], Row[2][1]); } - void Get_Z_Vector(Vector3 * set_z) const { set_z->Set(Row[0][2], Row[1][2], Row[2][2]); } - - // Get the inverse of the matrix. - // TODO: currently the "intended-to-be" general inverse function just calls - // the special case Orthogonal inverse functions. Also, when we implement - // general case, check where we were using Get_Inverse since usually it should - // be changed to Get_Orthogonal_Inverse... - void Get_Inverse(Matrix3D & set_inverse) const; - void Get_Orthogonal_Inverse(Matrix3D & set_inverse) const; - - // used for importing SurRender matrices - void Copy_3x3_Matrix(float matrix[3][3]); - - // Optimized Axis-Aligned Box transforms. One for each of the common forms of - // axis aligned box: min,max vectors and center,extent vectors. - void Transform_Min_Max_AABox(const Vector3 & min,const Vector3 & max,Vector3 * set_min,Vector3 * set_max) const; - void Transform_Center_Extent_AABox(const Vector3 & center,const Vector3 & extent,Vector3 * set_center,Vector3 * set_extent) const; - - // matrix multiplication without temporaries - static void Multiply(const Matrix3D &A,const Matrix3D &B,Matrix3D * set_result); - static void Transform_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - static void Rotate_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - - // transform a vector by the inverse of this matrix (note: assumes the matrix - // is orthogonal; if you've manually scaled or sheared the matrix this function - // will not give correct results) - static void Inverse_Transform_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - static void Inverse_Rotate_Vector(const Matrix3D & tm,const Vector3 & in,Vector3 * out); - - // Check whether a matrix is orthogonal or FORCE it to be :-) - int Is_Orthogonal(void) const; - void Re_Orthogonalize(void); - - // some static matrices which are sometimes useful - static const Matrix3D Identity; - static const Matrix3D RotateX90; - static const Matrix3D RotateX180; - static const Matrix3D RotateX270; - static const Matrix3D RotateY90; - static const Matrix3D RotateY180; - static const Matrix3D RotateY270; - static const Matrix3D RotateZ90; - static const Matrix3D RotateZ180; - static const Matrix3D RotateZ270; - -protected: - - Vector4 Row[3]; - - friend Vector3 operator * (const Matrix3D &A,const Vector3 &a); -}; - - - -/* --------------------------------------------------------------- - Vector Transformation, Matrix concatenation ---------------------------------------------------------------- */ -Vector3 operator * (const Matrix3D &A,const Vector3 &v); -Matrix3D operator * (const Matrix3D &A,const Matrix3D &B); - -/* --------------------------------------------------------------- - Equality and inequality operators ---------------------------------------------------------------- */ -bool operator == (const Matrix3D &A, const Matrix3D &B); -bool operator != (const Matrix3D &A, const Matrix3D &B); - -/* --------------------------------------------------------------- - Matrix interpolation ---------------------------------------------------------------- */ -Matrix3D Lerp(const Matrix3D &A, const Matrix3D &B, float factor); - - -/*********************************************************************************************** - * M3DC::Matrix3D -- Constructors for Matrix3D * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3D::Matrix3D(float m[12]) -{ - Row[0].Set(m[0],m[1],m[2],m[3]); - Row[1].Set(m[4],m[5],m[6],m[7]); - Row[2].Set(m[8],m[9],m[10],m[11]); -} - -inline Matrix3D::Matrix3D -( - float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34 -) -{ - Row[0].Set(m11,m12,m13,m14); - Row[1].Set(m21,m22,m23,m24); - Row[2].Set(m31,m32,m33,m34); -} - -inline Matrix3D::Matrix3D -( - const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos // position -) -{ - Set(x,y,z,pos); -} - -inline Matrix3D::Matrix3D(const Vector3 & axis,float angle) -{ - Set(axis,angle); -} - -inline Matrix3D::Matrix3D(const Vector3 & axis,float sine,float cosine) -{ - Set(axis,sine,cosine); -} - -inline Matrix3D::Matrix3D(const Matrix3 & rot,const Vector3 & pos) -{ - Set(rot,pos); -} - -inline Matrix3D::Matrix3D(const Quaternion & rot,const Vector3 & pos) -{ - Set(rot,pos); -} - -inline Matrix3D::Matrix3D(const Vector3 & position) -{ - Set(position); -} - -// Copy Constructor -inline Matrix3D::Matrix3D(const Matrix3D & m) -{ - Row[0] = m.Row[0]; - Row[1] = m.Row[1]; - Row[2] = m.Row[2]; -} - -// Assignment operator -inline Matrix3D & Matrix3D::operator = (const Matrix3D & m) -{ - Row[0] = m.Row[0]; - Row[1] = m.Row[1]; - Row[2] = m.Row[2]; - return *this; -} - - -/*********************************************************************************************** - * Matrix3D::Set -- init a Matrix3D from an arrray of 12 floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Set(float m[12]) -{ - Row[0].Set(m[0],m[1],m[2],m[3]); - Row[1].Set(m[4],m[5],m[6],m[7]); - Row[2].Set(m[8],m[9],m[10],m[11]); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a Matrix3D from 12 individual floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Set( float m11,float m12,float m13,float m14, - float m21,float m22,float m23,float m24, - float m31,float m32,float m33,float m34) -{ - Row[0].Set(m11,m12,m13,m14); - Row[1].Set(m21,m22,m23,m24); - Row[2].Set(m31,m32,m33,m34); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix from 3 axis vectors and a position * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Set( const Vector3 &x, // x-axis unit vector - const Vector3 &y, // y-axis unit vector - const Vector3 &z, // z-axis unit vector - const Vector3 &pos) // position -{ - Row[0].Set(x[0],y[0],z[0],pos[0]); - Row[1].Set(x[1],y[1],z[1],pos[1]); - Row[2].Set(x[2],y[2],z[2],pos[2]); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Set(const Vector3 & axis,float angle) -{ - float c = cosf(angle); - float s = sinf(angle); - - Set(axis,s,c); -} - -/*********************************************************************************************** - * Matrix3D::Set -- init a matrix to be a rotation about the given axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Set(const Vector3 & axis,float s,float c) -{ - assert(WWMath::Fabs(axis.Length2() - 1.0f) < 0.001f); - - Row[0].Set( - (float)(axis[0]*axis[0] + c*(1.0f - axis[0]*axis[0])), - (float)(axis[0]*axis[1]*(1.0f - c) - axis[2]*s), - (float)(axis[2]*axis[0]*(1.0f - c) + axis[1]*s), - 0.0f - ); - - Row[1].Set( - (float)(axis[0]*axis[1]*(1.0f - c) + axis[2]*s), - (float)(axis[1]*axis[1] + c*(1.0f - axis[1]*axis[1])), - (float)(axis[1]*axis[2]*(1.0f - c) - axis[0]*s), - 0.0f - ); - - Row[2].Set( - (float)(axis[2]*axis[0]*(1.0f - c) - axis[1]*s), - (float)(axis[1]*axis[2]*(1.0f - c) + axis[0]*s), - (float)(axis[2]*axis[2] + c*(1 - axis[2]*axis[2])), - 0.0f - ); -} - - -/*********************************************************************************************** - * Matrix3D::Set -- Init a matrix to be a pure translation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/24/98 GTH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Set(const Vector3 & position) -{ - Row[0].Set(1.0f,0.0f,0.0f,position[0]); - Row[1].Set(0.0f,1.0f,0.0f,position[1]); - Row[2].Set(0.0f,0.0f,1.0f,position[2]); -} - - -/*********************************************************************************************** - * M3DC::Make_Identity -- Initializes the matrix to be the identity matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Make_Identity(void) -{ - Row[0].Set(1.0f,0.0f,0.0f,0.0f); - Row[1].Set(0.0f,1.0f,0.0f,0.0f); - Row[2].Set(0.0f,0.0f,1.0f,0.0f); -} - - -/*********************************************************************************************** - * M3DC::Translate -- Post-Multiplies by a Translation Matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Translate(float x,float y,float z) -{ - Row[0][3] += (float)(Row[0][0]*x + Row[0][1]*y + Row[0][2]*z); - Row[1][3] += (float)(Row[1][0]*x + Row[1][1]*y + Row[1][2]*z); - Row[2][3] += (float)(Row[2][0]*x + Row[2][1]*y + Row[2][2]*z); -} - - -/*********************************************************************************************** - * M3DC::Translate -- Post-Multiplies the matrix by a translation matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Translate(const Vector3 &t) -{ - Row[0][3] += Row[0][0]*t[0] + Row[0][1]*t[1] + Row[0][2]*t[2]; - Row[1][3] += Row[1][0]*t[0] + Row[1][1]*t[1] + Row[1][2]*t[2]; - Row[2][3] += Row[2][0]*t[0] + Row[2][1]*t[1] + Row[2][2]*t[2]; -} - - -/*********************************************************************************************** - * M3DC::Translate_X -- Post-Multiplies the matrix by a translation matrix with X only * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/06/1998 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Translate_X(float x) -{ - Row[0][3] += (float)(Row[0][0]*x); - Row[1][3] += (float)(Row[1][0]*x); - Row[2][3] += (float)(Row[2][0]*x); -} - - -/*********************************************************************************************** - * M3DC::Translate_Y -- Post-Multiplies the matrix by a translation matrix with Y only * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/06/1998 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Translate_Y(float y) -{ - Row[0][3] += (float)(Row[0][1]*y); - Row[1][3] += (float)(Row[1][1]*y); - Row[2][3] += (float)(Row[2][1]*y); -} - - -/*********************************************************************************************** - * M3DC::Translate_Z -- Post-Multiplies the matrix by a translation matrix with Z only * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/06/1998 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Translate_Z(float z) -{ - Row[0][3] += (float)(Row[0][2]*z); - Row[1][3] += (float)(Row[1][2]*z); - Row[2][3] += (float)(Row[2][2]*z); -} - - -/*********************************************************************************************** - * M3DC::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Rotate_X(float theta) -{ - float tmp1,tmp2; - float s,c; - - s = sinf(theta); - c = cosf(theta); - - tmp1 = Row[0][1]; tmp2 = Row[0][2]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[0][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[1][2]; - Row[1][1] = (float)( c*tmp1 + s*tmp2); - Row[1][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][1]; tmp2 = Row[2][2]; - Row[2][1] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); - -} - - -/*********************************************************************************************** - * M3DC::Rotate_X -- Post-Multiplies the matrix by a rotation about the X axis * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][1]; tmp2 = Row[0][2]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[0][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[1][2]; - Row[1][1] = (float)( c*tmp1 + s*tmp2); - Row[1][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][1]; tmp2 = Row[2][2]; - Row[2][1] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Y -- Post-multiplies the matrix by a rotation about the Y axis * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Rotate_Y(float theta) -{ - float tmp1,tmp2; - float s,c; - - s = sinf(theta); - c = cosf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[0][2]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[0][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][2]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][2]; - Row[2][0] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Y -- Post-Multiplies the matrix by a rotation about Y * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][2]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[0][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][2]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][2]; - Row[2][0] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Rotate_Z(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[0][1]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[0][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][1]; - Row[1][0] = (float)( c*tmp1 + s*tmp2); - Row[1][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][1]; - Row[2][0] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); -} - - -/*********************************************************************************************** - * M3DC::Rotate_Z -- Post-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[0][1]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[0][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[1][0]; tmp2 = Row[1][1]; - Row[1][0] = (float)( c*tmp1 + s*tmp2); - Row[1][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[2][0]; tmp2 = Row[2][1]; - Row[2][0] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Pre_Rotate_X(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][3]; tmp2 = Row[2][3]; - Row[1][3] = (float)(c*tmp1 - s*tmp2); - Row[2][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Pre_Rotate_Y(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[2][3]; - Row[0][3] = (float)( c*tmp1 + s*tmp2); - Row[2][3] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Pre_Rotate_Z(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[1][3]; - Row[0][3] = (float)(c*tmp1 - s*tmp2); - Row[1][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_X -- Pre-multiplies the matrix by a rotation about X * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Pre_Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][3]; tmp2 = Row[2][3]; - Row[1][3] = (float)(c*tmp1 - s*tmp2); - Row[2][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Y -- Pre-multiplies the matrix by a rotation about Y * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Pre_Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[2][3]; - Row[0][3] = (float)( c*tmp1 + s*tmp2); - Row[2][3] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::Pre_Rotate_Z -- Pre-multiplies the matrix by a rotation about Z * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::Pre_Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][3]; tmp2 = Row[1][3]; - Row[0][3] = (float)(c*tmp1 - s*tmp2); - Row[1][3] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by a rotation about X * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::In_Place_Pre_Rotate_X(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by a rotation about Y * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::In_Place_Pre_Rotate_Y(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by a rotation about Z * - * * - * INPUT: * - * theta - angle (in radians) to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::In_Place_Pre_Rotate_Z(float theta) -{ - float tmp1,tmp2; - float c,s; - - c = cosf(theta); - s = sinf(theta); - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_X -- Pre-multiplies rotation part of matrix by a rotation about X * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::In_Place_Pre_Rotate_X(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[1][0]; tmp2 = Row[2][0]; - Row[1][0] = (float)(c*tmp1 - s*tmp2); - Row[2][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][1]; tmp2 = Row[2][1]; - Row[1][1] = (float)(c*tmp1 - s*tmp2); - Row[2][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[1][2]; tmp2 = Row[2][2]; - Row[1][2] = (float)(c*tmp1 - s*tmp2); - Row[2][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Y -- Pre-multiplies rotation part of matrix by a rotation about Y * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::In_Place_Pre_Rotate_Y(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[2][0]; - Row[0][0] = (float)( c*tmp1 + s*tmp2); - Row[2][0] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[2][1]; - Row[0][1] = (float)( c*tmp1 + s*tmp2); - Row[2][1] = (float)(-s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[2][2]; - Row[0][2] = (float)( c*tmp1 + s*tmp2); - Row[2][2] = (float)(-s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * M3DC::In_Place_Pre_Rotate_Z -- Pre-multiplies rotation part of matrix by a rotation about Z * - * * - * INPUT: * - * s - sine of the angle to rotate * - * c - cosine of the angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/1/1999 NH : Created. * - *=============================================================================================*/ -inline void Matrix3D::In_Place_Pre_Rotate_Z(float s,float c) -{ - float tmp1,tmp2; - - tmp1 = Row[0][0]; tmp2 = Row[1][0]; - Row[0][0] = (float)(c*tmp1 - s*tmp2); - Row[1][0] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][1]; tmp2 = Row[1][1]; - Row[0][1] = (float)(c*tmp1 - s*tmp2); - Row[1][1] = (float)(s*tmp1 + c*tmp2); - - tmp1 = Row[0][2]; tmp2 = Row[1][2]; - Row[0][2] = (float)(c*tmp1 - s*tmp2); - Row[1][2] = (float)(s*tmp1 + c*tmp2); -} - -/*********************************************************************************************** - * operator * -- Matrix multiplication * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix3D operator * (const Matrix3D &A,const Matrix3D &B) -{ - Matrix3D C; - float tmp1,tmp2,tmp3; - - tmp1 = B[0][0]; - tmp2 = B[1][0]; - tmp3 = B[2][0]; - - C[0][0] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3); - C[1][0] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3); - C[2][0] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3); - - tmp1 = B[0][1]; - tmp2 = B[1][1]; - tmp3 = B[2][1]; - - C[0][1] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3); - C[1][1] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3); - C[2][1] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3); - - tmp1 = B[0][2]; - tmp2 = B[1][2]; - tmp3 = B[2][2]; - - C[0][2] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3); - C[1][2] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3); - C[2][2] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3); - - tmp1 = B[0][3]; - tmp2 = B[1][3]; - tmp3 = B[2][3]; - - C[0][3] = (float)(A[0][0]*tmp1 + A[0][1]*tmp2 + A[0][2]*tmp3 + A[0][3]); - C[1][3] = (float)(A[1][0]*tmp1 + A[1][1]*tmp2 + A[1][2]*tmp3 + A[1][3]); - C[2][3] = (float)(A[2][0]*tmp1 + A[2][1]*tmp2 + A[2][2]*tmp3 + A[2][3]); - - return C; -} - -/*********************************************************************************************** - * operator * -- Matrix - vector multiplication * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -inline Vector3 operator * (const Matrix3D &A,const Vector3 &a) -{ -#if 0 - return Vector3 - ( - (A[0][0]*a[0] + A[0][1]*a[1] + A[0][2]*a[2] + A[0][3]), - (A[1][0]*a[0] + A[1][1]*a[1] + A[1][2]*a[2] + A[1][3]), - (A[2][0]*a[0] + A[2][1]*a[1] + A[2][2]*a[2] + A[2][3]) - ); -#else - return Vector3 - ( - (A.Row[0].X*a.X + A.Row[0].Y*a.Y + A.Row[0].Z*a.Z + A.Row[0].W), - (A.Row[1].X*a.X + A.Row[1].Y*a.Y + A.Row[1].Z*a.Z + A.Row[1].W), - (A.Row[2].X*a.X + A.Row[2].Y*a.Y + A.Row[2].Z*a.Z + A.Row[2].W) - ); -#endif -} - - -/*********************************************************************************************** - * operator == -- Matrix equality operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/29/1998 NH : Created. * - *=============================================================================================*/ -inline bool operator == (const Matrix3D &A, const Matrix3D &B) -{ - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 4; j++) { - if (A[i][j] != B[i][j]) return false; - } - } - return true; -} - - -/*********************************************************************************************** - * operator != -- Matrix inequality operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/29/1998 NH : Created. * - *=============================================================================================*/ -inline bool operator != (const Matrix3D &A, const Matrix3D &B) -{ - return !(A == B); -} - - -inline void Matrix3D::Transform_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z + A[0][3]); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z + A[1][3]); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z + A[2][3]); -} - -inline void Matrix3D::Rotate_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z); -} - -inline void Matrix3D::Inverse_Transform_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - Vector3 diff(v->X - A[0][3], v->Y - A[1][3], v->Z - A[2][3]); - Matrix3D::Inverse_Rotate_Vector(A, diff, out); -} - -inline void Matrix3D::Inverse_Rotate_Vector(const Matrix3D & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ - } - out->X = (A[0][0] * v->X + A[1][0] * v->Y + A[2][0] * v->Z); - out->Y = (A[0][1] * v->X + A[1][1] * v->Y + A[2][1] * v->Z); - out->Z = (A[0][2] * v->X + A[1][2] * v->Y + A[2][2] * v->Z); -} - -#endif /* MATRIX3D_H */ diff --git a/Generals/Code/Tools/WW3D/pluglib/matrix4.cpp b/Generals/Code/Tools/WW3D/pluglib/matrix4.cpp deleted file mode 100644 index 580d8a1416..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/matrix4.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/matrix4.cpp $* - * * - * Author:: Greg_h * - * * - * $Modtime:: 11/13/99 10:50a $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix4::Multiply -- Multiply two Matrix4's together * - * Matrix4::Multiply -- Multiply a Matrix3D * Matrix4 * - * Matrix4::Multiply -- Multiply a Matrix4 * Matrix3D * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "matrix4.h" -#include - -/*********************************************************************************************** - * Matrix4::Multiply -- Multiply two Matrix4's together * - * * - * INPUT: * - * a - first operand * - * b - second operand * - * res - pointer to matrix to store the result in (must not point to a or b) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/13/99 gth : Created. * - *=============================================================================================*/ -void Matrix4::Multiply(const Matrix4 &a,const Matrix4 &b,Matrix4 * res) -{ - assert(res != &a); - assert(res != &b); - - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - (*res)[0][3] = ROWCOL(0,3); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - (*res)[1][3] = ROWCOL(1,3); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - (*res)[2][3] = ROWCOL(2,3); - - (*res)[3][0] = ROWCOL(3,0); - (*res)[3][1] = ROWCOL(3,1); - (*res)[3][2] = ROWCOL(3,2); - (*res)[3][3] = ROWCOL(3,3); - - #undef ROWCOL -} - - -/*********************************************************************************************** - * Matrix4::Multiply -- Multiply a Matrix3D * Matrix4 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/13/99 gth : Created. * - *=============================================================================================*/ -void Matrix4::Multiply(const Matrix3D &a,const Matrix4 &b,Matrix4 * res) -{ - assert(res != &b); - - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - (*res)[0][3] = ROWCOL(0,3); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - (*res)[1][3] = ROWCOL(1,3); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - (*res)[2][3] = ROWCOL(2,3); - - (*res)[3][0] = b[3][0]; // last row of a is 0,0,0,1 - (*res)[3][1] = b[3][1]; // this leaves the last row of b unchanged - (*res)[3][2] = b[3][2]; - (*res)[3][3] = b[3][3]; - - #undef ROWCOL -} - - -/*********************************************************************************************** - * Matrix4::Multiply -- Multiply a Matrix4 * Matrix3D * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -void Matrix4::Multiply(const Matrix4 & a,const Matrix3D & b,Matrix4 * res) -{ - assert(res != &a); - - // ROWCOL multiplies a row of 'a' by one of the first three columns of 'b' (4th entry in b is zero) - // ROWCOL4 multiplies a row of 'a' by the fourth column of 'b' (4th entry in b is one) - - #define ROWCOL(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] - #define ROWCOL4(i,j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3] - - (*res)[0][0] = ROWCOL(0,0); - (*res)[0][1] = ROWCOL(0,1); - (*res)[0][2] = ROWCOL(0,2); - (*res)[0][3] = ROWCOL4(0,3); - - (*res)[1][0] = ROWCOL(1,0); - (*res)[1][1] = ROWCOL(1,1); - (*res)[1][2] = ROWCOL(1,2); - (*res)[1][3] = ROWCOL4(1,3); - - (*res)[2][0] = ROWCOL(2,0); - (*res)[2][1] = ROWCOL(2,1); - (*res)[2][2] = ROWCOL(2,2); - (*res)[2][3] = ROWCOL4(2,3); - - (*res)[3][0] = ROWCOL(3,0); - (*res)[3][1] = ROWCOL(3,1); - (*res)[3][2] = ROWCOL(3,2); - (*res)[3][3] = ROWCOL4(3,3); - - #undef ROWCOL - #undef ROWCOL4 -} diff --git a/Generals/Code/Tools/WW3D/pluglib/matrix4.h b/Generals/Code/Tools/WW3D/pluglib/matrix4.h deleted file mode 100644 index 947af37034..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/matrix4.h +++ /dev/null @@ -1,716 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/matrix4.h 15 2/03/00 4:55p Jason_a $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : WW3D * - * * - * File Name : MATRIX4.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/02/97 * - * * - * Last Update : June 2, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Matrix4::Matrix4 -- Constructor, optionally initialize to Identitiy matrix * - * Matrix4::Matrix4 -- Copy Constructor * - * Matrix4::Matrix4 -- Convert a Matrix3D (fake 4x4) to a Matrix4 * - * Matrix4::Matrix4 -- Constructor * - * Matrix4::Make_Identity -- Initializes the matrix to Identity * - * Matrix4::Init -- Initializes from the contents of the give Matrix3D * - * Matrix4::Init -- Initializes the rows from the given Vector4s * - * Matrix4::Init_Ortho -- Initialize to an orthographic projection matrix * - * Matrix4::Init_Perspective -- Initialize to a perspective projection matrix * - * Matrix4::Init_Perspective -- Initialize to a perspective projection matrix * - * Matrix4::Transpose -- Returns transpose of the matrix * - * Matrix4::Inverse -- returns the inverse of the matrix * - * Matrix4::operator = -- assignment operator * - * Matrix4::operator += -- "plus equals" operator * - * Matrix4::operator-= -- "minus equals" operator * - * Matrix4::operator *= -- "times equals" operator * - * Matrix4::operator /= -- "divide equals" operator * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef MATRIX4_H -#define MATRIX4_H - -#include "always.h" -#include "vector4.h" -#include "matrix3d.h" -#include "WWmatrix3.h" - - -class Matrix4 -{ -public: - - /* - ** Constructors - */ - Matrix4(void) {}; - Matrix4(const Matrix4 & m); - - explicit Matrix4(bool identity); - explicit Matrix4(const Matrix3D & m); - explicit Matrix4(const Matrix3 & m); - explicit Matrix4(const Vector4 & v0, const Vector4 & v1, const Vector4 & v2, const Vector4 & v3); - - void Make_Identity(void); - void Init(const Matrix3D & m); - void Init(const Matrix3 & m); - void Init(const Vector4 & v0, const Vector4 & v1, const Vector4 & v2, const Vector4 & v3); - - void Init_Ortho(float left,float right,float bottom,float top,float znear,float zfar); - void Init_Perspective(float hfov,float vfov,float znear,float zfar); - void Init_Perspective(float left,float right,float bottom,float top,float znear,float zfar); - - /* - ** Access operators - */ - Vector4 & operator [] (int i) { return Row[i]; } - const Vector4 & operator [] (int i) const { return Row[i]; } - - /* - ** Transpose and Inverse - */ - Matrix4 Transpose(void) const; - Matrix4 Inverse(void) const; - - /* - ** Assignment operators - */ - Matrix4 & operator = (const Matrix4 & m); - Matrix4 & operator += (const Matrix4 & m); - Matrix4 & operator -= (const Matrix4 & m); - Matrix4 & operator *= (float d); - Matrix4 & operator /= (float d); - - /* - ** Negation - */ - friend Matrix4 operator - (const Matrix4& a); - - /* - ** Scalar multiplication and division - */ - friend Matrix4 operator * (const Matrix4& a,float d); - friend Matrix4 operator * (float d,const Matrix4& a); - friend Matrix4 operator / (const Matrix4& a,float d); - - /* - ** matrix addition - */ - friend Matrix4 operator + (const Matrix4& a, const Matrix4& b); - friend Matrix4 Add(const Matrix4& a); - - /* - ** matrix subtraction - */ - friend Matrix4 operator - (const Matrix4 & a, const Matrix4 & b); - friend Matrix4 Subtract(const Matrix4 & a, const Matrix4 & b); - - /* - ** matrix multiplication - */ - friend Matrix4 operator * (const Matrix4 & a, const Matrix4 & b); - friend Matrix4 Multiply(const Matrix4 & a, const Matrix4 & b); - - /* - ** Comparison operators - */ - friend int operator == (const Matrix4 & a, const Matrix4 & b); - friend int operator != (const Matrix4 & a, const Matrix4 & b); - - /* - ** Swap two matrices in place - */ - friend void Swap(Matrix4 & a,Matrix4 & b); - - /* - ** Linear Transforms - */ - friend Vector4 operator * (const Matrix4 & a, const Vector4 & v); - friend Vector4 operator * (const Matrix4 & a, const Vector3 & v); - - /* - ** Matrix multiplication without temporaries... - */ - static void Multiply(const Matrix4 &A,const Matrix4 &B,Matrix4 * set_result); - static void Multiply(const Matrix3D &A,const Matrix4 &B,Matrix4 * set_result); - static void Multiply(const Matrix4 &A,const Matrix3D &B,Matrix4 * set_result); - - static void Transform_Vector(const Matrix4 & tm,const Vector3 & in,Vector3 * out); - -protected: - - Vector4 Row[4]; - -}; - - -/*********************************************************************************************** - * Matrix4::Matrix4 -- Constructor, optionally initialize to Identitiy matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4::Matrix4(bool identity) -{ - if (identity) { - Make_Identity(); - } -} - -/*********************************************************************************************** - * Matrix4::Matrix4 -- Copy Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4::Matrix4(const Matrix4 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; Row[3] = m.Row[3]; -} - -/*********************************************************************************************** - * Matrix4::Matrix4 -- Convert a Matrix3D (fake 4x4) to a Matrix4 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4::Matrix4(const Matrix3D & m) -{ - Init(m); -} - -/*********************************************************************************************** - * Matrix4::Matrix4 -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4::Matrix4(const Vector4 & r0, const Vector4 & r1, const Vector4 & r2, const Vector4 & r3) -{ - Init(r0,r1,r2,r3); -} - - -/*********************************************************************************************** - * Matrix4::Make_Identity -- Initializes the matrix to Identity * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -inline void Matrix4::Make_Identity(void) -{ - Row[0].Set(1.0,0.0,0.0,0.0); - Row[1].Set(0.0,1.0,0.0,0.0); - Row[2].Set(0.0,0.0,1.0,0.0); - Row[3].Set(0.0,0.0,0.0,1.0); -} - - -/*********************************************************************************************** - * Matrix4::Init -- Initializes from the contents of the give Matrix3D * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -inline void Matrix4::Init(const Matrix3D & m) -{ - Row[0] = m[0]; Row[1] = m[1]; Row[2] = m[2]; Row[3] = Vector4(0.0,0.0,0.0,1.0); -} - - -/*********************************************************************************************** - * Matrix4::Init -- Initializes the rows from the given Vector4s * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -inline void Matrix4::Init(const Vector4 & r0, const Vector4 & r1, const Vector4 & r2, const Vector4 & r3) -{ - Row[0] = r0; Row[1] = r1; Row[2] = r2; Row[3] = r3; -} - - -/*********************************************************************************************** - * Matrix4::Init_Ortho -- Initialize to an orthographic projection matrix * - * * - * You can find the formulas for this in the appendix of the OpenGL programming guide. Also * - * this happens to be the same convention used by Surrender. * - * * - * The result of this projection will be that points inside the volume will have all coords * - * between -1 and +1. A point at znear will project to z=-1. A point at zfar will project * - * to z=+1... * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Note that the znear and zfar parameters are positive distances to the clipping planes * - * even though in the camera coordinate system, the clipping planes are at negative z * - * coordinates. This holds for all of the projection initializations and is consistent * - * with OpenGL's convention. * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -inline void Matrix4::Init_Ortho -( - float left, - float right, - float bottom, - float top, - float znear, - float zfar -) -{ - assert(znear >= 0.0f); - assert(zfar > znear); - - Make_Identity(); - Row[0][0] = 2.0f / (right - left); - Row[0][3] = -(right + left) / (right - left); - Row[1][1] = 2.0f / (top - bottom); - Row[1][3] = -(top + bottom) / (top - bottom); - Row[2][2] = -2.0f / (zfar - znear); - Row[2][3] = -(zfar + znear) / (zfar - znear); -} - - -/*********************************************************************************************** - * Matrix4::Init_Perspective -- Initialize to a perspective projection matrix * - * * - * You can find the formulas for this matrix in the appendix of the OpenGL programming guide. * - * Also, this happens to be the same convention used by Surrender. * - * * - * INPUT: * - * hfov - horizontal field of view (in radians) * - * vfov - vertical field of view (in radians) * - * znear - distance to near z clipping plane (positive) * - * zfar - distance to the far z clipping plane (positive) * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Note that the znear and zfar parameters are positive distances to the clipping planes * - * even though in the camera coordinate system, the clipping planes are at negative z * - * coordinates. This holds for all of the projection initializations and is consistent * - * with OpenGL's convention. * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -inline void Matrix4::Init_Perspective(float hfov,float vfov,float znear,float zfar) -{ - assert(znear > 0.0f); - assert(zfar > znear); - - Make_Identity(); - Row[0][0] = (1.0 / tan(hfov*0.5)); - Row[1][1] = (1.0 / tan(vfov*0.5)); - Row[2][2] = -(zfar + znear) / (zfar - znear); - Row[2][3] = -(2.0*zfar*znear) / (zfar - znear); - Row[3][2] = -1.0f; - Row[3][3] = 0.0f; -} - - -/*********************************************************************************************** - * Matrix4::Init_Perspective -- Initialize to a perspective projection matrix * - * * - * You can find the formulas for this matrix in the appendix of the OpenGL programming guide. * - * Also, this happens to be the same convention used by Surrender. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Note that the znear and zfar parameters are positive distances to the clipping planes * - * even though in the camera coordinate system, the clipping planes are at negative z * - * coordinates. This holds for all of the projection initializations and is consistent * - * with OpenGL's convention. * - * * - * HISTORY: * - * 11/5/99 gth : Created. * - *=============================================================================================*/ -inline void Matrix4::Init_Perspective -( - float left, - float right, - float bottom, - float top, - float znear, - float zfar -) -{ - assert(znear > 0.0f); - assert(zfar > 0.0f); - - Make_Identity(); - Row[0][0] = 2.0*znear / (right - left); - Row[0][2] = (right + left) / (right - left); - Row[1][1] = 2.0*znear / (top - bottom); - Row[1][2] = (top + bottom) / (top - bottom); - Row[2][2] = -(zfar + znear) / (zfar - znear); - Row[2][3] = -(2.0*zfar*znear) / (zfar - znear); - Row[3][2] = -1.0f; - Row[3][3] = 0.0f; -} - -/*********************************************************************************************** - * Matrix4::Transpose -- Returns transpose of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4 Matrix4::Transpose() const -{ - return Matrix4( - Vector4(Row[0][0], Row[1][0], Row[2][0], Row[3][0]), - Vector4(Row[0][1], Row[1][1], Row[2][1], Row[3][1]), - Vector4(Row[0][2], Row[1][2], Row[2][2], Row[3][2]), - Vector4(Row[0][3], Row[1][3], Row[2][3], Row[3][3]) - ); -} - -/*********************************************************************************************** - * Matrix4::Inverse -- returns the inverse of the matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4 Matrix4::Inverse() const // Gauss-Jordan elimination with partial pivoting -{ - Matrix4 a(*this); // As a evolves from original mat into identity - Matrix4 b(true); // b evolves from identity into inverse(a) - int i, j, i1; - - // Loop over cols of a from left to right, eliminating above and below diagonal - for (j=0; j<4; j++) { - - // Find largest pivot in column j among rows j..3 - i1 = j; - for (i=j+1; i<4; i++) { - if (WWMath::Fabs(a[i][j]) > WWMath::Fabs(a[i1][j])) { - i1 = i; - } - } - - // Swap rows i1 and j in a and b to put pivot on diagonal - Swap(a.Row[i1], a.Row[j]); - Swap(b.Row[i1], b.Row[j]); - - // Scale row j to have a unit diagonal - if (a[j][j]==0.) { - //ALGEBRA_ERROR("Matrix4::inverse: singular matrix; can't invert\n"); - } - b.Row[j] /= a.Row[j][j]; - a.Row[j] /= a.Row[j][j]; - - // Eliminate off-diagonal elems in col j of a, doing identical ops to b - for (i=0; i<4; i++) { - if (i != j) { - b.Row[i] -= a[i][j] * b.Row[j]; - a.Row[i] -= a[i][j] * a.Row[j]; - } - } - } - return b; -} - -/*********************************************************************************************** - * Matrix4::operator = -- assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4 & Matrix4::operator = (const Matrix4 & m) -{ - Row[0] = m.Row[0]; Row[1] = m.Row[1]; Row[2] = m.Row[2]; Row[3] = m.Row[3]; - return *this; -} - -/*********************************************************************************************** - * Matrix4::operator += -- "plus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4& Matrix4::operator += (const Matrix4 & m) -{ - Row[0] += m.Row[0]; Row[1] += m.Row[1]; Row[2] += m.Row[2]; Row[3] += m.Row[3]; - return *this; -} - -/*********************************************************************************************** - * Matrix4::operator-= -- "minus equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4& Matrix4::operator -= (const Matrix4 & m) -{ - Row[0] -= m.Row[0]; Row[1] -= m.Row[1]; Row[2] -= m.Row[2]; Row[3] -= m.Row[3]; - return *this; -} - -/*********************************************************************************************** - * Matrix4::operator *= -- "times equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4& Matrix4::operator *= (float d) -{ - Row[0] *= d; Row[1] *= d; Row[2] *= d; Row[3] *= d; - return *this; -} - -/*********************************************************************************************** - * Matrix4::operator /= -- "divide equals" operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline Matrix4& Matrix4::operator /= (float d) -{ - float ood = d; - Row[0] *= ood; Row[1] *= ood; Row[2] *= ood; Row[3] *= ood; - return *this; -} - -inline Matrix4 operator - (const Matrix4 & a) -{ - return Matrix4(-a.Row[0], -a.Row[1], -a.Row[2], -a.Row[3]); -} - -inline Matrix4 operator * (const Matrix4 & a, float d) -{ - return Matrix4(a.Row[0] * d, a.Row[1] * d, a.Row[2] * d, a.Row[3] * d); -} - -inline Matrix4 operator * (float d, const Matrix4 & a) -{ - return a*d; -} - -inline Matrix4 operator / (const Matrix4 & a, float d) -{ - float ood = 1.0f / d; - return Matrix4(a.Row[0] * ood, a.Row[1] * ood, a.Row[2] * ood, a.Row[3] * ood); -} - -/* -** matrix addition -*/ -inline Matrix4 operator + (const Matrix4 & a, const Matrix4 & b) -{ - return Matrix4( - a.Row[0] + b.Row[0], - a.Row[1] + b.Row[1], - a.Row[2] + b.Row[2], - a.Row[3] + b.Row[3] - ); -} - -inline Matrix4 Add(const Matrix4 & a, const Matrix4 & b) -{ return a+b; } - -/* -** matrix subtraction -*/ -inline Matrix4 operator - (const Matrix4 & a, const Matrix4 & b) -{ - return Matrix4( - a.Row[0] - b.Row[0], - a.Row[1] - b.Row[1], - a.Row[2] - b.Row[2], - a.Row[3] - b.Row[3] - ); -} - -inline Matrix4 Subtract(const Matrix4 & a, const Matrix4 & b) -{ return a-b; } - -/* -** matrix multiplication -*/ -inline Matrix4 operator * (const Matrix4 & a, const Matrix4 & b) -{ - #define ROWCOL(i, j) a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j] + a[i][3]*b[3][j] - - return Matrix4( - Vector4(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2), ROWCOL(0,3)), - Vector4(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2), ROWCOL(1,3)), - Vector4(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2), ROWCOL(2,3)), - Vector4(ROWCOL(3,0), ROWCOL(3,1), ROWCOL(3,2), ROWCOL(3,3)) - ); - - #undef ROWCOL -} - -inline Matrix4 Multiply(const Matrix4 & a, const Matrix4 & b) -{ return a*b; } - - - -/* -** Multiply a Matrix4 by a Vector3 (assumes w=1.0!!!). Yeilds a Vector4 result -*/ -inline Vector4 operator * (const Matrix4 & a, const Vector3 & v) { - return Vector4( - a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2] + a[0][3] * 1.0, - a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2] + a[1][3] * 1.0, - a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] + a[2][3] * 1.0, - a[3][0] * v[0] + a[3][1] * v[1] + a[3][2] * v[2] + a[3][3] * 1.0 - ); -} - -/* -** Multiply a Matrix4 by a Vector4 -*/ -inline Vector4 operator * (const Matrix4 & a, const Vector4 & v) { - return Vector4( - a[0][0] * v[0] + a[0][1] * v[1] + a[0][2] * v[2] + a[0][3] * v[3], - a[1][0] * v[0] + a[1][1] * v[1] + a[1][2] * v[2] + a[1][3] * v[3], - a[2][0] * v[0] + a[2][1] * v[1] + a[2][2] * v[2] + a[2][3] * v[3], - a[3][0] * v[0] + a[3][1] * v[1] + a[3][2] * v[2] + a[3][3] * v[3] - ); -} - -/* -** Multiply a Matrix4 by a Vector4 -*/ -inline void Matrix4::Transform_Vector(const Matrix4 & A,const Vector3 & in,Vector3 * out) -{ - Vector3 tmp; - Vector3 * v; - - // check for aliased parameters - if (out == &in) { - tmp = in; - v = &tmp; - } else { - v = (Vector3 *)∈ // whats the right way to do this... - } - - out->X = (A[0][0] * v->X + A[0][1] * v->Y + A[0][2] * v->Z + A[0][3]); - out->Y = (A[1][0] * v->X + A[1][1] * v->Y + A[1][2] * v->Z + A[1][3]); - out->Z = (A[2][0] * v->X + A[2][1] * v->Y + A[2][2] * v->Z + A[2][3]); -} - -#endif /*MATRIX4_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/nodefilt.cpp b/Generals/Code/Tools/WW3D/pluglib/nodefilt.cpp deleted file mode 100644 index 388e6bf791..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/nodefilt.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/nodefilt.cpp 9 1/16/98 10:34a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : NODEFILT.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/09/97 * - * * - * Last Update : June 9, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * VisibleMeshINodeFilter::Accept_Node -- Accepts visible meshes * - * AnimatedINodeFilter::Accept_Node -- Accepts animated INodes * - * RootINodeFilter::Accept_Node -- Accepts root INodes * - * VisibleHelperINodeFilter::Accept_Node -- Accepts visible helper objects * - * VisibleMeshOrHelperINodeFilter::Accept_Node -- Accepts visible helper or mesh objects * - * HelperINodeFilter::Accept_Node -- Accepts all helper inodes (including hidden) * - * MeshINodeFilter::Accept_Node -- Accepts all mesh inodes (including hidden) * - * VisibleSelectedINodeFilter::Accept_Node -- Accepts Visible and selected inodes * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "nodefilt.h" -#include - - -/* -** The default node filter: -*/ -VisibleMeshINodeFilter DefaultINodeFilter; - - -/*********************************************************************************************** - * HelperINodeFilter::Accept_Node -- Accepts all helper inodes (including hidden) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/10/1997 GH : Created. * - *=============================================================================================*/ -BOOL HelperINodeFilter::Accept_Node(INode * node,TimeValue time) -{ - Object * obj = node->EvalWorldState(time).obj; - - if (obj && obj->SuperClassID() == HELPER_CLASS_ID) { - - return TRUE; - - } - - return FALSE; -} - - -/*********************************************************************************************** - * MeshINodeFilter::Accept_Node -- Accepts all mesh inodes (including hidden) * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/10/1997 GH : Created. * - *=============================================================================================*/ -BOOL MeshINodeFilter::Accept_Node(INode * node,TimeValue time) -{ - Object * obj = node->EvalWorldState(time).obj; - - if (obj && - obj->CanConvertToType(triObjectClassID) && - obj->SuperClassID() == GEOMOBJECT_CLASS_ID) - { - - return TRUE; - - } else { - - return FALSE; - - } -} - - -/*********************************************************************************************** - * VisibleMeshINodeFilter::Accept_Node -- Accepts visible meshes * - * * - * Accepts nodes which: * - * - can be converted to tri-meshes * - * - are not hidden * - * - whose visibility > 0.0 * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -BOOL VisibleMeshINodeFilter::Accept_Node(INode * node, TimeValue time) -{ - Object * obj = node->EvalWorldState(time).obj; - - if - ( - obj - && !node->IsHidden () - && obj->CanConvertToType(triObjectClassID) - && obj->SuperClassID() == GEOMOBJECT_CLASS_ID -// && node->GetVisibility (time) > 0.0f - ) - { - - return TRUE; - - } else { - - return FALSE; - - } -} - -/*********************************************************************************************** - * VisibleHelperINodeFilter::Accept_Node -- Accepts visible helper objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/03/1997 GH : Created. * - *=============================================================================================*/ -BOOL VisibleHelperINodeFilter::Accept_Node(INode * node, TimeValue time) -{ - Object * obj = node->EvalWorldState(time).obj; - - if ((!obj) || (node->IsHidden()) /*|| (node->GetVisibility(time) <= 0.0f)*/) { - - return FALSE; - - } - - if (obj->SuperClassID() == HELPER_CLASS_ID) { - - return TRUE; - - } - - return FALSE; -} - - -/*********************************************************************************************** - * VisibleMeshOrHelperINodeFilter::Accept_Node -- Accepts visible helper or mesh objects * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/03/1997 GH : Created. * - *=============================================================================================*/ -BOOL VisibleMeshOrHelperINodeFilter::Accept_Node(INode * node, TimeValue time) -{ - Object * obj = node->EvalWorldState(time).obj; - - if ((!obj) || (node->IsHidden()) /*|| (node->GetVisibility(time) <= 0.0f)*/) { - - return FALSE; - - } - - if (obj->CanConvertToType(triObjectClassID) && obj->SuperClassID() == GEOMOBJECT_CLASS_ID) { - - return TRUE; - - } - - if (obj->SuperClassID() == HELPER_CLASS_ID) { - - return TRUE; - - } - - return FALSE; -} - -/*********************************************************************************************** - * AnimatedINodeFilter::Accept_Node -- Accepts animated INodes * - * * - * Accepts nodes which: * - * - can be converted to tri-meshes * - * - are not hidden * - * - whose visibility > 0.0 * - * - have animation keys! * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -BOOL AnimatedINodeFilter::Accept_Node(INode * node, TimeValue time) -{ - Object * obj = node->EvalWorldState(time).obj; - Control * poscon = node->GetTMController()->GetPositionController(); - Control * rotcon = node->GetTMController()->GetRotationController(); - - int numkeys = 0; - if (poscon != NULL) { - IKeyControl * poskeys = GetKeyControlInterface(poscon); - if (poskeys != NULL) numkeys += poskeys->GetNumKeys(); - } - - if (rotcon != NULL) { - IKeyControl * rotkeys = GetKeyControlInterface(rotcon); - if (rotkeys != NULL) numkeys += rotkeys->GetNumKeys(); - } - - if (obj && !node->IsHidden() && numkeys > 0) { - return TRUE; - } - - return FALSE; -} - - -/*********************************************************************************************** - * VisibleSelectedINodeFilter::Accept_Node -- Accepts Visible and selected inodes * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/13/98 GTH : Created. * - *=============================================================================================*/ -BOOL VisibleSelectedINodeFilter::Accept_Node(INode * node, TimeValue time) -{ - if (!node->IsHidden() && node->Selected()) { - return TRUE; - } else { - return FALSE; - } -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/nodefilt.h b/Generals/Code/Tools/WW3D/pluglib/nodefilt.h deleted file mode 100644 index 928cf95581..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/nodefilt.h +++ /dev/null @@ -1,178 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/nodefilt.h 6 1/14/98 10:23a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : NODEFILT.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/09/97 * - * * - * Last Update : June 9, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef NODEFILT_H -#define NODEFILT_H - -#include "always.h" -#include - -/*************************************************************** -* -* INodeFilterClass -* -* This is simply an object used to accept or reject INodes -* based on whatever criteria you desire. There are some -* default node filters defined in this module or you can -* create your own by inheriting the Abstract Base Class -* INodeFilterClass and implementing the Accept_Node method. -* -***************************************************************/ -class INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time) = 0; -}; - - -/*************************************************************** -* -* AnyINodeFilter -* -* Accepts all INodes... -* -***************************************************************/ -class AnyINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time) { return TRUE; } -}; - - -/*************************************************************** -* -* HelperINodeFilter -* -* Accepts INodes which are Helper objects -* -***************************************************************/ -class HelperINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - - -/*************************************************************** -* -* MeshINodeFilter -* -* Only accepts INodes which are Triangle meshes -* -***************************************************************/ -class MeshINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - -/*************************************************************** -* -* VisibleMeshINodeFilter -* -* Only accepts INodes which are Triangle meshes and are -* currently visible -* -***************************************************************/ -class VisibleMeshINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - -/*************************************************************** -* -* VisibleHelperINodeFilter -* -* Only accepts INodes which are Helper objects and are -* currently visible -* -***************************************************************/ -class VisibleHelperINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - - -/*************************************************************** -* -* VisibleMeshOrHelperINodeFilter -* -* Only accepts INodes which are Triangle meshes or helper -* objects and are currently visible -* -***************************************************************/ -class VisibleMeshOrHelperINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - - -/*************************************************************** -* -* AnimatedINodeFilter -* -* Only accepts INodes which contain at least on animation -* key. -* -***************************************************************/ -class AnimatedINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - - -/*************************************************************** -* -* VisibleSelectedINodeFilter -* -* Only accepts INodes which are Visible and Selected -* -***************************************************************/ -class VisibleSelectedINodeFilter : public INodeFilterClass -{ -public: - virtual BOOL Accept_Node(INode * node, TimeValue time); -}; - - - -#endif /*NODEFILT_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/nodelist.cpp b/Generals/Code/Tools/WW3D/pluglib/nodelist.cpp deleted file mode 100644 index 5eecc4499c..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/nodelist.cpp +++ /dev/null @@ -1,373 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/pluglib/nodelist.cpp 8 1/02/01 6:31p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : NODELIST.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/09/97 * - * * - * Last Update : June 9, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * INodeListClass::INodeListClass -- Create an INodeList * - * INodeListClass::~INodeListClass -- Delete the INode List * - * INode * INodeListClass::operator[] -- Array-like access to the list members * - * INodeListClass::callback -- callback function for MAX * - * INodeListClass::INodeListClass -- A "copy" contstructor with filtering... * - * INodeListClass::INodeListClass -- constructor * - * INodeListClass::INodeListClass -- Constructor * - * INodeListClass::Insert -- insert a list of nodes into this list * - * INodeListClass::Insert -- Inserts an INode into the list * - * INodeListClass::Add_Tree -- Add a tree of INodes to the list * - * INodeListClass::Remove -- Remove the i'th element of the list * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "nodelist.h" - - -static AnyINodeFilter _AnyFilter; - - -/******************************************************************************* -* ListEntryClass -* -* Used to implement a linked list of INodes. -* -*******************************************************************************/ -class INodeListEntryClass -{ -public: - - INodeListEntryClass(INode * n,TimeValue /*time*/) { Node = n; } - ~INodeListEntryClass(void) {} - - INode * Node; - INodeListEntryClass * Next; -}; - -/*********************************************************************************************** - * INodeListClass::INodeListClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/02/1997 GH : Created. * - *=============================================================================================*/ -INodeListClass::INodeListClass(TimeValue time,INodeFilterClass * inodefilter) : - NumNodes(0), - Time(time), - ListHead(NULL), - INodeFilter(inodefilter) -{ - if (INodeFilter == NULL) { - INodeFilter = &_AnyFilter; - } -} - -/*********************************************************************************************** - * INodeListClass::INodeListClass -- Create an INodeList * - * * - * INPUT: * - * scene - 3dsMAX scene to enumerate * - * time - time at which to create the list of INodes * - * inodefilter - object which will accept or reject each INode in the scene * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -INodeListClass::INodeListClass(IScene * scene,TimeValue time,INodeFilterClass * inodefilter) : - NumNodes(0), - Time(time), - ListHead(NULL), - INodeFilter(inodefilter) -{ - if (INodeFilter == NULL) { - INodeFilter = &_AnyFilter; - } - scene->EnumTree(this); -} - - -/*********************************************************************************************** - * INodeListClass::INodeListClass -- Constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/13/98 GTH : Created. * - *=============================================================================================*/ -INodeListClass::INodeListClass(INode * root,TimeValue time,INodeFilterClass * nodefilter) : - NumNodes(0), - Time(time), - ListHead(NULL), - INodeFilter(nodefilter) -{ - if (INodeFilter == NULL) { - INodeFilter = &_AnyFilter; - } - Add_Tree(root); -} - - -/*********************************************************************************************** - * INodeListClass::INodeListClass -- A "copy" contstructor with filtering... * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 07/02/1997 GH : Created. * - *=============================================================================================*/ -INodeListClass::INodeListClass(INodeListClass & copyfrom,TimeValue time,INodeFilterClass * inodefilter) : - NumNodes(0), - Time(time), - ListHead(NULL), - INodeFilter(inodefilter) -{ - if (INodeFilter == NULL) { - INodeFilter = &_AnyFilter; - } - for (unsigned i=0; iNext; - delete ListHead; - ListHead = next; - } - - NumNodes = 0; - ListHead = NULL; -} - - -/*********************************************************************************************** - * INode * INodeListClass::operator[] -- Array-like access to the list members * - * * - * INPUT: * - * index - index of the list entry * - * * - * OUTPUT: * - * pointer to an INode * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -INode * INodeListClass::operator[] ( int index ) const -{ - INodeListEntryClass * entry = ListHead; - while (index > 0 && entry != NULL ) - { - entry = entry->Next; - index--; - } - return entry->Node; -} - - -/*********************************************************************************************** - * INodeListClass::Insert -- insert a list of nodes into this list * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/14/98 GTH : Created. * - *=============================================================================================*/ -void INodeListClass::Insert(INodeListClass & insertlist) -{ - for (unsigned int i=0; iAccept_Node(node,Time)) - { - INodeListEntryClass * newentry = new INodeListEntryClass(node, Time); - newentry->Next = ListHead; - ListHead = newentry; - NumNodes++; - } -} - - -/*********************************************************************************************** - * INodeListClass::Remove -- Remove the i'th element of the list * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/27/2000 gth : Created. * - *=============================================================================================*/ -void INodeListClass::Remove(int i) -{ - if ((i < 0) || (i > Num_Nodes())) { - return; - } - - INodeListEntryClass * prev = ListHead; - while (i > 1) { - prev = prev->Next; - } - - INodeListEntryClass * deleteme = prev->Next; - if (deleteme != NULL) { - prev->Next = prev->Next->Next; - delete deleteme; - } -} - - -/*********************************************************************************************** - * INodeListClass::Add_Tree -- Add a tree of INodes to the list * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 1/13/98 GTH : Created. * - *=============================================================================================*/ -void INodeListClass::Add_Tree(INode * root) -{ - if (root == NULL) return; - - Insert(root); - for (int i=0; iNumberOfChildren(); i++) { - Add_Tree(root->GetChildNode(i)); - } -} - - -/*********************************************************************************************** - * INodeListClass::callback -- callback function for MAX * - * * - * 3dsMAX calls this function with a pointer to each INode in the scene. We keep a pointer * - * to the ones we like. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/09/1997 GH : Created. * - *=============================================================================================*/ -int INodeListClass::callback(INode * node) -{ - Insert(node); - - return TREE_CONTINUE; // Keep on enumerating.... -} - - -void INodeListClass::Sort(const INodeCompareClass & node_compare) -{ - for (unsigned int i=0; iNode,nj->Node) > 0) { - INode * tmp = ni->Node; - ni->Node = nj->Node; - nj->Node = tmp; - } - } - } -} - -INodeListEntryClass * INodeListClass::get_nth_item(int index) -{ - INodeListEntryClass * entry = ListHead; - while (index > 0 && entry != NULL ) - { - entry = entry->Next; - index--; - } - return entry; -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/nodelist.h b/Generals/Code/Tools/WW3D/pluglib/nodelist.h deleted file mode 100644 index 426f59d713..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/nodelist.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/pluglib/nodelist.h 7 1/02/01 6:31p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G * - * * - * File Name : NODELIST.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 06/09/97 * - * * - * Last Update : June 9, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef NODELIST_H -#define NODELIST_H - -#include "always.h" -#include - -#ifndef NODEFILT_H -#include "nodefilt.h" -#endif - - -class INodeListEntryClass; -class INodeCompareClass; - - -/******************************************************************************* -* INodeListClass -* -* This is a class that can enumerate a 3dsMax scene and build a list of -* all of the INodes that meet your desired criteria. -* -*******************************************************************************/ -class INodeListClass : public ITreeEnumProc -{ -public: - - INodeListClass(TimeValue time,INodeFilterClass * nodefilter = NULL); - INodeListClass(IScene * scene,TimeValue time,INodeFilterClass * nodefilter = NULL); - INodeListClass(INode * root,TimeValue time,INodeFilterClass * nodefilter = NULL); - INodeListClass(INodeListClass & copyfrom,TimeValue time,INodeFilterClass * inodefilter = NULL); - ~INodeListClass(); - - void Set_Filter(INodeFilterClass * inodefilter) { INodeFilter = inodefilter; } - void Insert(INodeListClass & insertlist); - void Insert(INode * node); - void Remove(int i); - unsigned Num_Nodes(void) const { return NumNodes; } - INode * operator[] (int index) const; - void Sort(const INodeCompareClass & node_compare); - void Add_Tree(INode * root); - -private: - - unsigned NumNodes; - TimeValue Time; - INodeListEntryClass * ListHead; - INodeFilterClass * INodeFilter; - - INodeListEntryClass * get_nth_item(int index); - int callback(INode * node); -}; - - -class INodeCompareClass -{ -public: - // returns <0 if nodea < node b. - // returns =0 if nodea = node b. - // returns >0 if nodea > node b. - virtual int operator() (INode * nodea,INode * nodeb) const = 0; -}; - - -#endif /*NODELIST_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/noinit.h b/Generals/Code/Tools/WW3D/pluglib/noinit.h deleted file mode 100644 index f397238258..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/noinit.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/noinit.h $* - * * - * $Author:: Eric_c $* - * * - * $Modtime:: 3/23/99 5:20p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef NOINIT_H -#define NOINIT_H - -/********************************************************************** -** This class is solely used as a parameter to a constructor that does -** absolutely no initialization to the object being constructed. By using -** this method, it is possible to load and save data directly from a -** class that has virtual functions. The construction process automatically -** takes care of initializing the virtual function table pointer and the -** rest of the constructor doesn't initialize any data members. After loading -** into a class object, simply perform an in-place new operation. -*/ -#ifndef NoInitClass -class NoInitClass { - public: - void operator () (void) const {}; -}; -#endif - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/palette.cpp b/Generals/Code/Tools/WW3D/pluglib/palette.cpp deleted file mode 100644 index 75bbace1c1..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/palette.cpp +++ /dev/null @@ -1,268 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Library/PALETTE.CPP $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 7/22/97 11:37a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * PaletteClass::Adjust -- Adjusts the palette toward another palette. * - * PaletteClass::Adjust -- Adjusts this palette toward black. * - * PaletteClass::Closest_Color -- Finds closest match to color specified. * - * PaletteClass::PaletteClass -- Constructor that fills palette with color specified. * - * PaletteClass::operator = -- Assignment operator for palette objects. * - * PaletteClass::operator == -- Equality operator for palette objects. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "always.h" -#include "palette.h" -#include - - -/*********************************************************************************************** - * PaletteClass::PaletteClass -- Constructor that fills palette with color specified. * - * * - * This constructor will fill the palette with the color specified. * - * * - * INPUT: rgb -- Reference to the color to fill the entire palette with. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -PaletteClass::PaletteClass(RGBClass const & rgb) -{ - for (int index = 0; index < COLOR_COUNT; index++) { - Palette[index] = rgb; - } -} - -PaletteClass::PaletteClass(unsigned char *binary_palette) -{ - memcpy(&Palette[0], binary_palette, sizeof(Palette)); -} - -/*********************************************************************************************** - * PaletteClass::operator == -- Equality operator for palette objects. * - * * - * This is the comparison for equality operator. It will compare palette objects to * - * determine if they are identical. * - * * - * INPUT: palette -- Reference to the palette to compare to this palette. * - * * - * OUTPUT: Are the two palettes identical? * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -int PaletteClass::operator == (PaletteClass const & palette) const -{ - if (this == &palette) return(true); - return(memcmp(&Palette[0], &palette.Palette[0], sizeof(Palette)) == 0); -} - - -/*********************************************************************************************** - * PaletteClass::operator = -- Assignment operator for palette objects. * - * * - * This is the assignment operator for palette objects. Although the default C++ generated * - * assignment operator would function correctly, it would not check for self-assignment * - * and thus this routine can be faster. * - * * - * INPUT: palette -- Reference to that palette that will be copied into this palette. * - * * - * OUTPUT: Returns with a reference to the newly copied to palette. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -PaletteClass & PaletteClass::operator = (PaletteClass const & palette) -{ - if (this == &palette) return(*this); - - memcpy(&Palette[0], &palette.Palette[0], sizeof(Palette)); - return(*this); -} - - -/*********************************************************************************************** - * PaletteClass::Adjust -- Adjusts this palette toward black. * - * * - * This routine is used to adjust this palette toward black. Typical use of this routine * - * is when fading the palette to black. * - * * - * INPUT: ratio -- The ratio to fade this palette to black. 0 means no fading at all. 255 * - * means 100% faded to black. * - * * - * OUTPUT: none * - * * - * WARNINGS: This routine doesn't actually set the palette to the video card. Use the Set() * - * function to achieve that purpose. * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -void PaletteClass::Adjust(int ratio) -{ - for (int index = 0; index < COLOR_COUNT; index++) { - Palette[index].Adjust(ratio, BlackColor); - } -} - - -/*********************************************************************************************** - * PaletteClass::Adjust -- Adjusts the palette toward another palette. * - * * - * This routine is used to adjust a palette toward a destination palette by the ratio * - * specified. This is primarily used by the palette fading routines. * - * * - * INPUT: palette -- Reference to the destination palette. * - * * - * ratio -- The ratio to adjust this palette toward the destination palette. A * - * value of 0 means no adjustment at all. A value of 255 means 100% * - * adjustment. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -void PaletteClass::Adjust(int ratio, PaletteClass const & palette) -{ - for (int index = 0; index < COLOR_COUNT; index++) { - Palette[index].Adjust(ratio, palette[index]); - } -} - - -/*********************************************************************************************** - * PaletteClass::Partial_Adjust -- Adjusts the specified parts of this palette toward black. * - * * - * This routine is used to adjust this palette toward black. Typical use of this routine * - * is when fading the palette to black. The input lookup table is used to determine * - * which entries should fade and which should stay the same * - * * - * INPUT: ratio -- The ratio to fade this palette to black. 0 means no fading at all. 255 * - * means 100% faded to black. * - * * - * lookup -- ptr to lookup table * - * * - * OUTPUT: none * - * * - * WARNINGS: This routine doesn't actually set the palette to the video card. Use the Set() * - * function to achieve that purpose. * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -void PaletteClass::Partial_Adjust(int ratio, char *lut) -{ - for (int index = 0; index < COLOR_COUNT; index++) { - if (lut[index]) { - Palette[index].Adjust(ratio, BlackColor); - } - } -} - - -/*********************************************************************************************** - * PaletteClass::Partial_Adjust -- Adjusts the palette toward another palette. * - * * - * This routine is used to adjust a palette toward a destination palette by the ratio * - * specified. This is primarily used by the palette fading routines. The input lookup * - * table is used to determine which entries should fade and which should stay the same * - * * - * * - * INPUT: palette -- Reference to the destination palette. * - * * - * ratio -- The ratio to adjust this palette toward the destination palette. A * - * value of 0 means no adjustment at all. A value of 255 means 100% * - * adjustment. * - * * - * lookup -- ptr to lookup table * - * * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -void PaletteClass::Partial_Adjust(int ratio, PaletteClass const & palette, char *lut) -{ - for (int index = 0; index < COLOR_COUNT; index++) { - if (lut[index]) { - Palette[index].Adjust(ratio, palette[index]); - } - } -} - - -/*********************************************************************************************** - * PaletteClass::Closest_Color -- Finds closest match to color specified. * - * * - * This routine will examine the palette and return with the color index number for the * - * color that most closely matches the color specified. Remap operations rely heavily on * - * this routine to allow working with a constant palette. * - * * - * INPUT: rgb -- Reference to a color to search for in the current palette. * - * * - * OUTPUT: Returns with a color index value to most closely matches the specified color. * - * * - * WARNINGS: This routine will quite likely not find an exact match. * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -int PaletteClass::Closest_Color(RGBClass const & rgb) const -{ - int closest = 0; - int value = -1; - - RGBClass const * ptr = &Palette[0]; - for (int index = 0; index < COLOR_COUNT; index++) { - int difference = rgb.Difference(*ptr++); - if (value == -1 || difference < value) { - value = difference; - closest = index; - } - } - return(closest); -} diff --git a/Generals/Code/Tools/WW3D/pluglib/palette.h b/Generals/Code/Tools/WW3D/pluglib/palette.h deleted file mode 100644 index cfea843f97..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/palette.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/PALETTE.H $* - * * - * $Author:: Eric_c $* - * * - * $Modtime:: 4/02/99 12:00p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef PALETTE_H -#define PALETTE_H - -#include "rgb.h" - -/* -** The palette class is used to manipulate a palette as a whole. All 256 colors are -** represented by the palette class object. -*/ -class PaletteClass -{ - public: - enum { - COLOR_COUNT=256 // Number of color indices on the palette. - }; - - PaletteClass(void) {}; - PaletteClass(RGBClass const & rgb); - PaletteClass(unsigned char *binary_palette); - - RGBClass & operator[] (int index) {return(Palette[index % COLOR_COUNT]);}; - RGBClass const & operator[] (int index) const {return(Palette[index % COLOR_COUNT]);}; - RGBClass & Get_Color(int index) {return(Palette[index % COLOR_COUNT]);}; - RGBClass const & Get_Color(int index) const {return(Palette[index % COLOR_COUNT]);}; - int operator == (PaletteClass const & palette) const; - int operator != (PaletteClass const & palette) const {return(!(operator ==(palette)));}; - PaletteClass & operator = (PaletteClass const & palette); - operator const unsigned char * (void) const {return((const unsigned char *)&Palette[0]);}; - operator unsigned char * (void) {return((unsigned char *)&Palette[0]);}; - - void Adjust(int ratio); - void Adjust(int ratio, PaletteClass const & palette); - void Partial_Adjust(int ratio, char *lut); - void Partial_Adjust(int ratio, PaletteClass const & palette, char *lut); - int Closest_Color(RGBClass const & rgb) const; - - protected: - RGBClass Palette[COLOR_COUNT]; -}; - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/plane.h b/Generals/Code/Tools/WW3D/pluglib/plane.h deleted file mode 100644 index 4ea15f8a28..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/plane.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/pluglib/plane.h 8 4/22/98 6:36p Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : PLANE.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 03/17/97 * - * * - * Last Update : March 17, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#ifndef PLANE_H -#define PLANE_H - -#ifndef VECTOR3_H -#include "vector3.h" -#endif - -/* -** PlaneClass -** -** 3D-planes. This class needs to be fleshed out but it does what I need for now. -*/ - -class PlaneClass -{ -public: - - Vector3 N; - float D; - - PlaneClass(void) : N(0.0f,0.0f,1.0f), D(0.0f) { } - PlaneClass(float a,float b,float c,float d) : N(a,b,c),D(d) { } - PlaneClass(const Vector3 & normal,float dist) : N(normal), D(dist) { } - - // Create a plane given the normal and a point on the plane - PlaneClass(const Vector3 & normal,const Vector3 & point); - - // Create a plane out of three points, ordered according to a right-hand convention. - PlaneClass(const Vector3 & point1, const Vector3 & point2, const Vector3 & point3); - - void Set(float a,float b,float c,float d) { N[0] = a; N[1] = b; N[2] = c; D = d; } -}; - -inline PlaneClass::PlaneClass(const Vector3 & normal,const Vector3 & point) -{ - N = normal; - D = Vector3::Dot_Product(normal , point); -} - -inline PlaneClass::PlaneClass(const Vector3 & point1, const Vector3 & point2, const Vector3 & point3) -{ - N = Vector3::Cross_Product((point2 - point1), (point3 - point1)); - if (N != Vector3(0.0f, 0.0f, 0.0f)) { - // Points are not colinear. Normalize N and calculate D. - N.Normalize(); - D = N * point1; - } else { - // They are colinear - return default plane (constructors can't fail). - N = Vector3(0.0f, 0.0f, 1.0f); - D = 0.0f; - } -} - -inline bool In_Front(const Vector3 & point,const PlaneClass & plane) -{ - double dist = point * plane.N; - return (dist > plane.D); -} - - - -#endif /*PLANE_H*/ \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/rawfile.cpp b/Generals/Code/Tools/WW3D/pluglib/rawfile.cpp deleted file mode 100644 index 3b43850314..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/rawfile.cpp +++ /dev/null @@ -1,1262 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /VSS_Sync/wwlib/rawfile.cpp $* - * * - * $Author:: Vss_sync $* - * * - * $Modtime:: 8/29/01 10:24p $* - * * - * $Revision:: 12 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RawFileClass::Bias -- Bias a file with a specific starting position and length. * - * RawFileClass::Close -- Perform a closure of the file. * - * RawFileClass::Create -- Creates an empty file. * - * RawFileClass::Delete -- Deletes the file object from the disk. * - * RawFileClass::Error -- Handles displaying a file error message. * - * RawFileClass::Get_Date_Time -- Gets the date and time the file was last modified. * - * RawFileClass::Is_Available -- Checks to see if the specified file is available to open. * - * RawFileClass::Open -- Assigns name and opens file in one operation. * - * RawFileClass::Open -- Opens the file object with the rights specified. * - * RawFileClass::RawFileClass -- Simple constructor for a file object. * - * RawFileClass::Raw_Seek -- Performs a seek on the unbiased file * - * RawFileClass::Read -- Reads the specified number of bytes into a memory buffer. * - * RawFileClass::Seek -- Reposition the file pointer as indicated. * - * RawFileClass::Set_Date_Time -- Sets the date and time the file was last modified. * - * RawFileClass::Set_Name -- Manually sets the name for a file object. * - * RawFileClass::Size -- Determines size of file (in bytes). * - * RawFileClass::Write -- Writes the specified data to the buffer specified. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "always.h" -#include "rawfile.h" -#include -//#include -#include -#include -#include -#include -#include "win.h" -#include -#include -#ifdef _UNIX -#include -#include -#endif - - -#if 0 //#ifdef NEVER (gth) the MAX sdk must #define NEVER! yikes :-) - /* - ** This is a duplicate of the error numbers. The error handler for the RawFileClass handles - ** these errors. If the error routine is overridden and additional errors are defined, then - ** use numbers starting with 100. Note that these errors here are listed in numerical order. - ** These errors are defined in the standard header file "ERRNO.H". - */ - EZERO, // Non-error. - EINVFNC, // Invalid function number. - ENOFILE, // File not found. - ENOENT=ENOFILE, // No such file or directory. - ENOPATH, // Path not found. - EMFILE, // Too many open files. - EACCES, // Permission denied. - EBADF, // Bad file number. - ECONTR, // Memory blocks destroyed. - ENOMEM, // Not enough core memory. - EINVMEM, // Invalid memory block address. - EINVENV, // Invalid environment. - EINVFMT, // Invalid format. - EINVACC, // Invalid access code. - EINVDAT, // Invalid data. - EFAULT, // Unknown error. - EINVDRV, // Invalid drive specified. - ENODEV=EINVDRV, // No such device. - ECURDIR, // Attempt to remove CurDir. - ENOTSAM, // Not same device. - ENMFILE, // No more files. - EINVAL, // Invalid argument. - E2BIG, // Argument list too long. - ENOEXEC, // exec format error. - EXDEV, // Cross-device link. - ENFILE, // Too many open files. - ECHILD, // No child process. - ENOTTY, // not used - ETXTBSY, // not used - EFBIG, // not used - ENOSPC, // No space left on device. - ESPIPE, // Illegal seek. - EROFS, // Read-only file system. - EMLINK, // not used - EPIPE, // Broken pipe. - EDOM, // Math argument. - ERANGE, // Result too large. - EEXIST, // File already exists. - EDEADLOCK, // Locking violation. - EPERM, // Operation not permitted. - ESRCH, // not used - EINTR, // Interrupted function call. - EIO, // Input/output error. - ENXIO, // No such device or address. - EAGAIN, // Resource temporarily unavailable. - ENOTBLK, // not used - EBUSY, // Resource busy. - ENOTDIR, // not used - EISDIR, // not used - EUCLEAN, // not used -#endif - - -/*********************************************************************************************** - * RawFileClass::RawFileClass -- Default constructor for a file object. * - * * - * This constructs a null file object. A null file object has no file handle or filename * - * associated with it. In order to use a file object created in this fashion it must be * - * assigned a name and then opened. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -RawFileClass::RawFileClass(void) : - Rights(READ), - BiasStart(0), - BiasLength(-1), - Handle(NULL_HANDLE), - Filename(0), - Date(0), - Time(0), - Allocated(false) -{ -} - - - -/*********************************************************************************************** - * RawFileClass::Is_Open -- Checks to see if the file is open or not. * - * * - * Use this routine to determine if the file is open. It returns true if it is. * - * * - * INPUT: none * - * * - * OUTPUT: bool; Is the file open? * - * * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -bool RawFileClass::Is_Open(void) const -{ - return(Handle != NULL_HANDLE); -} - -/*********************************************************************************************** - * RawFileClass::Error -- Handles displaying a file error message. * - * * - * Display an error message as indicated. If it is allowed to retry, then pressing a key * - * will return from this function. Otherwise, it will exit the program with "exit()". * - * * - * INPUT: error -- The error number (same as the DOSERR.H error numbers). * - * * - * canretry -- Can this routine exit normally so that retrying can occur? If this is * - * false, then the program WILL exit in this routine. * - * * - * filename -- Optional filename to report with this error. If no filename is * - * supplied, then no filename is listed in the error message. * - * * - * OUTPUT: none, but this routine might not return at all if the "canretry" parameter is * - * false or the player pressed ESC. * - * * - * WARNINGS: This routine may not return at all. It handles being in text mode as well as * - * if in a graphic mode. * - * * - * HISTORY: * - * 10/17/1994 JLB : Created. * - *=============================================================================================*/ -void RawFileClass::Error(int, int, char const * ) -{ -} - -/*********************************************************************************************** - * RawFileClass::Transfer_Block_Size * - * * - * This function returns the largest size a low level DOS read or write may * - * perform. Larger file transfers are performed in chunks of this size or less. * - * * - * INPUT: none * - * * - * OUTPUT: * - * * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Transfer_Block_Size(void) -{ - return (int)((unsigned)UINT_MAX)-16L; -} - -/*********************************************************************************************** - * RawFileClass::RawFileClass -- Simple constructor for a file object. * - * * - * This constructor is called when a file object is created with a supplied filename, but * - * not opened at the same time. In this case, an assumption is made that the supplied * - * filename is a constant string. A duplicate of the filename string is not created since * - * it would be wasteful in that case. * - * * - * INPUT: filename -- The filename to assign to this file object. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/17/1994 JLB : Created. * - *=============================================================================================*/ -RawFileClass::RawFileClass(char const * filename) : - Rights(0), - BiasStart(0), - BiasLength(-1), - Handle(NULL_HANDLE), - Filename(filename), - Date(0), - Time(0), - Allocated(false) -{ -} - -/*********************************************************************************************** - * RawFileClass::~RawFileClass -- Default deconstructor for a file object. * - * * - * This constructs a null file object. A null file object has no file handle or filename * - * associated with it. In order to use a file object created in this fashion it must be * - * assigned a name and then opened. * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -RawFileClass::~RawFileClass(void) -{ - Reset (); -} - -/*********************************************************************************************** - * RawFileClass::Reset -- Closes the file handle and resets the object's state. - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 06/10/1999 PDS : Created. * - *=============================================================================================*/ -void RawFileClass::Reset(void) -{ - Close(); - if (Allocated && Filename) { - free((char *)Filename); - Filename = NULL; - Allocated = false; - } -} - -/*********************************************************************************************** - * RawFileClass::Set_Name -- Manually sets the name for a file object. * - * * - * This routine will set the name for the file object to the name specified. This name is * - * duplicated in free store. This allows the supplied name to be a temporarily constructed * - * text string. Setting the name in this fashion doesn't affect the closed or opened state * - * of the file. * - * * - * INPUT: filename -- The filename to assign to this file object. * - * * - * OUTPUT: Returns with a pointer to the allocated copy of this filename. This pointer is * - * guaranteed to remain valid for the duration of this file object or until the name * - * is changed -- whichever is sooner. * - * * - * WARNINGS: Because of the allocation this routine must perform, memory could become * - * fragmented. * - * * - * HISTORY: * - * 10/17/1994 JLB : Created. * - *=============================================================================================*/ -char const * RawFileClass::Set_Name(char const * filename) -{ - if (Filename != NULL && Allocated) { - free((char *)Filename); - Filename = NULL; - Allocated = false; - } - - if (filename == NULL) return(NULL); - - Bias(0); - - char *nameptr = strdup(filename); - if (nameptr == NULL) { - Error(ENOMEM, false, filename); - } - - /* - ** If this is a UNIX build, fix the filename from the DOS-like name passed in - */ - #ifdef _UNIX - for (int i=0; i 0) { - bytesread = 0; - - int readok=TRUE; - - #ifdef _UNIX - readok=TRUE; - bytesread=fread(buffer,1,size,Handle); - if ((bytesread == 0)&&( ! feof(Handle))) - readok=ferror(Handle); - #else - readok=ReadFile(Handle, buffer, size, &(unsigned long&)bytesread, NULL); - #endif - - - if (! readok) { - size -= bytesread; - total += bytesread; - Error(GetLastError(), true, Filename); - continue; - } - size -= bytesread; - total += bytesread; - if (bytesread == 0) break; - } - bytesread = total; - - /* - ** Close the file if it was opened by this routine and return - ** the actual number of bytes read into the buffer. - */ - if (opened) Close(); - return(bytesread); -} - - -/*********************************************************************************************** - * RawFileClass::Write -- Writes the specified data to the buffer specified. * - * * - * This routine will write the data specified to the file. * - * * - * INPUT: buffer -- The buffer that holds the data to write. * - * * - * size -- The number of bytes to write to the file. * - * * - * OUTPUT: Returns with the number of bytes written to the file. This routine catches the * - * case of a disk full condition, so this routine will always return with the number * - * matching the size request. * - * * - * WARNINGS: A fatal file condition could cause this routine to never return. * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Write(void const * buffer, int size) -{ - long byteswritten = 0; - int opened = false; // Was the file manually opened? - - /* - ** Check to open status of the file. If the file is open, then merely write to - ** it. Otherwise, open the file for writing and then close the file when the - ** output is finished. - */ - if (!Is_Open()) { - if (!Open(WRITE)) { - return(0); - } - opened = true; - } - - int writeok=TRUE; - #ifdef _UNIX - byteswritten = fwrite(buffer, 1, size, Handle); - if (byteswritten != size) - writeok = FALSE; - #else - writeok=WriteFile(Handle, buffer, size, &(unsigned long&)byteswritten, NULL); - #endif - - if (! writeok) { - Error(GetLastError(), false, Filename); - } - - /* - ** Fixup the bias length if necessary. - */ - if (BiasLength != -1) { - if (Raw_Seek(0) > BiasStart+BiasLength) { - BiasLength = Raw_Seek(0) - BiasStart; - } - } - - /* - ** If this routine had to open the file, then close it before returning. - */ - if (opened) { - Close(); - } - - /* - ** Return with the number of bytes written. This will always be the number of bytes - ** requested, since the case of the disk being full is caught by this routine. - */ - return(byteswritten); -} - - -/*********************************************************************************************** - * RawFileClass::Seek -- Reposition the file pointer as indicated. * - * * - * Use this routine to move the filepointer to the position indicated. It can move either * - * relative to current position or absolute from the beginning or ending of the file. This * - * routine will only return if it successfully performed the seek. * - * * - * INPUT: pos -- The position to seek to. This is interpreted as relative to the position * - * indicated by the "dir" parameter. * - * * - * dir -- The relative position to relate the seek to. This can be either SEEK_SET * - * for the beginning of the file, SEEK_CUR for the current position, or * - * SEEK_END for the end of the file. * - * * - * OUTPUT: This routine returns the position that the seek ended up at. * - * * - * WARNINGS: If there was a file error, then this routine might never return. * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Seek(int pos, int dir) -{ - - /* - ** A file that is biased will have a seek operation modified so that the file appears to - ** exist only within the bias range. All bytes outside of this range appear to be - ** non-existant. - */ - if (BiasLength != -1) { - switch (dir) { - case SEEK_SET: - if (pos > BiasLength) { - pos = BiasLength; - } - pos += BiasStart; - break; - - case SEEK_CUR: - break; - - case SEEK_END: - dir = SEEK_SET; - pos += BiasStart + BiasLength; -// pos = (pos <= BiasStart+BiasLength) ? pos : BiasStart+BiasLength; -// pos = (pos >= BiasStart) ? pos : BiasStart; - break; - } - - /* - ** Perform the modified raw seek into the file. - */ - long newpos = Raw_Seek(pos, dir) - BiasStart; - - /* - ** Perform a final double check to make sure the file position fits with the bias range. - */ - if (newpos < 0) { - newpos = Raw_Seek(BiasStart, SEEK_SET) - BiasStart; - } - if (newpos > BiasLength) { - newpos = Raw_Seek(BiasStart+BiasLength, SEEK_SET) - BiasStart; - } - return(newpos); - } - - /* - ** If the file is not biased in any fashion, then the normal seek logic will - ** work just fine. - */ - return(Raw_Seek(pos, dir)); -} - - -/*********************************************************************************************** - * RawFileClass::Size -- Determines size of file (in bytes). * - * * - * Use this routine to determine the size of the file. The file must exist or this is an * - * error condition. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with the number of bytes in the file. * - * * - * WARNINGS: This routine handles error conditions and will not return unless the file * - * exists and can successfully be queried for file length. * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Size(void) -{ - int size = 0; - - /* - ** A biased file already has its length determined. - */ - if (BiasLength != -1) { - return(BiasLength); - } - - /* - ** If the file is open, then proceed normally. - */ - if (Is_Open()) { - - #ifdef _UNIX - fpos_t curpos,startpos,endpos; - fgetpos(Handle,&curpos); - - fseek(Handle,0,SEEK_SET); - fgetpos(Handle,&startpos); - - fseek(Handle,0,SEEK_END); - fgetpos(Handle,&endpos); - - size=endpos-startpos; - fsetpos(Handle,&curpos); - #else - size = GetFileSize(Handle, NULL); - #endif - - /* - ** If there was in internal error, then call the error function. - */ - if (size == 0xFFFFFFFF) { - Error(GetLastError(), false, Filename); - } - - } else { - - /* - ** If the file wasn't open, then open the file and call this routine again. Count on - ** the fact that the open function must succeed. - */ - if (Open()) { - size = Size(); - - /* - ** Since we needed to open the file we must remember to close the file when the - ** size has been determined. - */ - Close(); - } - } - - BiasLength = size-BiasStart; - return(BiasLength); -} - - -/*********************************************************************************************** - * RawFileClass::Create -- Creates an empty file. * - * * - * This routine will create an empty file from the file object. The file object's filename * - * must already have been assigned before this routine will function. * - * * - * INPUT: none * - * * - * OUTPUT: bool; Was the file successfully created? This routine will always return true. * - * * - * WARNINGS: A fatal error condition could occur with this routine. Especially if the disk * - * is full or a read-only media was selected. * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Create(void) -{ - Close(); - if (Open(WRITE)) { - - /* - ** A biased file must be at least as long as the bias offset. Seeking to the - ** appropriate start offset has the effect of lengthening the file to the - ** correct length. - */ - if (BiasLength != -1) { - Seek(0, SEEK_SET); - } - - Close(); - return(true); - } - return(false); -} - - -/*********************************************************************************************** - * RawFileClass::Delete -- Deletes the file object from the disk. * - * * - * This routine will delete the file object from the disk. If the file object doesn't * - * exist, then this routine will return as if it had succeeded (since the effect is the * - * same). * - * * - * INPUT: none * - * * - * OUTPUT: bool; Was the file deleted? If the file was already missing, the this value will * - * be false. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Delete(void) -{ - /* - ** If the file was open, then it must be closed first. - */ - Close(); - - /* - ** If there is no filename associated with this object, then this indicates a fatal error - ** condition. Report this and abort. - */ - if (!Filename) { - Error(ENOENT, false); - } - - /* - ** Repetitively try to delete the file if possible. Either return with success, or - ** abort the program with an error. - */ - for (;;) { - - /* - ** If the file is already missing, then return with this fact. No action is necessary. - ** This can occur as this section loops if the file exists on a floppy and the floppy - ** was removed, the file deleted on another machine, and then the floppy was - ** reinserted. Admittedly, this is a rare case, but is handled here. - */ - if (!Is_Available()) { - return(false); - } - - int deleteok; - #ifdef _UNIX - deleteok=(unlink(Filename)==0)?TRUE:FALSE; - #else - deleteok=DeleteFile(Filename); - #endif - - if (! deleteok) { - Error(GetLastError(), false, Filename); - return(false); - } - break; - } - - /* - ** DOS reports that the file was successfully deleted. Return with this fact. - */ - return(true); -} - - -/*********************************************************************************************** - * RawFileClass::Get_Date_Time -- Gets the date and time the file was last modified. * - * * - * Use this routine to get the date and time of the file. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with the file date and time as a long. * - * Use the YEAR(long), MONTH(),.... * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 11/14/1995 DRD : Created. * - * 07/13/1996 JLB : Handles win32 method. * - *=============================================================================================*/ -unsigned long RawFileClass::Get_Date_Time(void) -{ -#ifdef _UNIX - struct stat statbuf; - lstat(Filename, &statbuf); - return(statbuf.st_mtime); -#else - BY_HANDLE_FILE_INFORMATION info; - - if (GetFileInformationByHandle(Handle, &info)) { - WORD dosdate; - WORD dostime; - FileTimeToDosDateTime(&info.ftLastWriteTime, &dosdate, &dostime); - return((dosdate << 16) | dostime); - } - return(0); -#endif -} - - -/*********************************************************************************************** - * RawFileClass::Set_Date_Time -- Sets the date and time the file was last modified. * - * * - * Use this routine to set the date and time of the file. * - * * - * INPUT: the file date and time as a long * - * * - * OUTPUT: successful or not if the file date and time was changed. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 11/14/1995 DRD : Created. * - * 07/13/1996 JLB : Handles win 32 method * - *=============================================================================================*/ -bool RawFileClass::Set_Date_Time(unsigned long datetime) -{ -#ifdef _UNIX - assert(0); - return(false); -#else - if (RawFileClass::Is_Open()) { - BY_HANDLE_FILE_INFORMATION info; - - if (GetFileInformationByHandle(Handle, &info)) { - FILETIME filetime; - if (DosDateTimeToFileTime((WORD)(datetime >> 16), (WORD)(datetime & 0x0FFFF), &filetime)) { - return(SetFileTime(Handle, &info.ftCreationTime, &filetime, &filetime) != 0); - } - } - } - return(false); -#endif -} - - -/*********************************************************************************************** - * RawFileClass::Bias -- Bias a file with a specific starting position and length. * - * * - * This will bias a file by giving it an artificial starting position and length. By * - * using this routine, it is possible to 'fool' the file into ignoring a header and * - * trailing extra data. An example of this would be a file inside of a mixfile. * - * * - * INPUT: start -- The starting offset that will now be considered the start of the * - * file. * - * * - * length -- The forced length of the file. For files that are opened for write, * - * this serves as the artificial constraint on the file's length. For * - * files opened for read, this limits the usable file size. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 06/02/1996 JLB : Created. * - *=============================================================================================*/ -void RawFileClass::Bias(int start, int length) -{ - if (start == 0) { - BiasStart = 0; - BiasLength = -1; - return; - } - - BiasLength = RawFileClass::Size(); - BiasStart += start; - if (length != -1) { - BiasLength = BiasLength < length ? BiasLength : length; - } - BiasLength = BiasLength > 0 ? BiasLength : 0; - - /* - ** Move the current file offset to a legal position if necessary and the - ** file was open. - */ - if (Is_Open()) { - RawFileClass::Seek(0, SEEK_SET); - } -} - - -/*********************************************************************************************** - * RawFileClass::Raw_Seek -- Performs a seek on the unbiased file * - * * - * This will perform a seek on the file as if it were unbiased. This is in spite of any * - * bias setting the file may have. The ability to perform a raw seek in this fasion is * - * necessary to maintain the bias ability. * - * * - * INPUT: pos -- The position to seek the file relative to the "dir" parameter. * - * * - * dir -- The origin of the seek operation. * - * * - * OUTPUT: Returns with the new position of the seek operation. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 08/04/1996 JLB : Created. * - *=============================================================================================*/ -int RawFileClass::Raw_Seek(int pos, int dir) -{ - /* - ** If the file isn't opened, then this is a fatal error condition. - */ - if (!Is_Open()) { - Error(EBADF, false, Filename); - } - - #ifdef _UNIX - pos=fseek(Handle, pos, dir); - #else - switch (dir) { - case SEEK_SET: - dir = FILE_BEGIN; - break; - - case SEEK_CUR: - dir = FILE_CURRENT; - break; - - case SEEK_END: - dir = FILE_END; - break; - } - pos = SetFilePointer(Handle, pos, NULL, dir); - #endif - - /* - ** If there was an error in the seek, then bail with an error condition. - */ - if (pos == 0xFFFFFFFF) { - Error(GetLastError(), false, Filename); - } - - /* - ** Return with the new position of the file. This will range between zero and the number of - ** bytes the file contains. - */ - return(pos); -} - -/*********************************************************************************************** - * RawFileClass::Attach -- Provides a file handle for the class to use. - * * - * INPUT: handle -- the Win32 file handle. - * * - * OUTPUT: - * * - * WARNINGS: none * - * * - * HISTORY: * - * 06/10/1999 PDS : Created. * - *=============================================================================================*/ -void RawFileClass::Attach (void *handle, int rights) -{ - Reset (); - - Rights = rights; - BiasStart = 0; - BiasLength = -1; - Date = 0; - Time = 0; - Allocated = false; - - #ifdef _UNIX - Handle = (FILE *)handle; - #else - Handle = handle; - #endif -} - -/*********************************************************************************************** - * RawFileClass::Detach -- Removes the file handle from the object without closing the handle. - * * - * INPUT - * * - * OUTPUT: - * * - * WARNINGS: none * - * * - * HISTORY: * - * 06/10/1999 PDS : Created. * - *=============================================================================================*/ -void RawFileClass::Detach (void) -{ - Rights = 0; - BiasStart = 0; - BiasLength = -1; - Date = 0; - Time = 0; - Allocated = false; - Handle = NULL_HANDLE; -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/rawfile.h b/Generals/Code/Tools/WW3D/pluglib/rawfile.h deleted file mode 100644 index 0cbfa37ae5..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/rawfile.h +++ /dev/null @@ -1,205 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/rawfile.h $* - * * - * $Author:: Neal_k $* - * * - * $Modtime:: 10/04/99 10:25a $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RawFileClass::File_Name -- Returns with the filename associate with the file object. * - * RawFileClass::RawFileClass -- Default constructor for a file object. * - * RawFileClass::~RawFileClass -- Default deconstructor for a file object. * - * RawFileClass::Is_Open -- Checks to see if the file is open or not. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef RAWFILE_Hx -#define RAWFILE_Hx - -//#include - -// #include "win.h" - -#ifdef _UNIX -#include -#include "osdep.h" - #define NULL_HANDLE NULL - #define HANDLE_TYPE FILE* -#else - #define NULL_HANDLE INVALID_HANDLE_VALUE - #define HANDLE_TYPE HANDLE -#endif - -#include "wwfile.h" - - -#ifndef WWERROR -#define WWERROR -1 -#endif - -/* -** This is the definition of the raw file class. It is derived from the abstract base FileClass -** and handles the interface to the low level DOS routines. This is the first class in the -** chain of derived file classes that actually performs a useful function. With this class, -** I/O is possible. More sophisticated features, such as packed files, CD-ROM support, -** file caching, and XMS/EMS memory support, are handled by derived classes. -** -** Of particular importance is the need to override the error routine if more sophisticated -** error handling is required. This is more than likely if greater functionality is derived -** from this base class. -*/ -class RawFileClass : public FileClass -{ - typedef FileClass BASECLASS; - - public: - - /* - ** This is a record of the access rights used to open the file. These rights are - ** used if the file object is duplicated. - */ - int Rights; - - RawFileClass(char const *filename); - RawFileClass(void); - RawFileClass (RawFileClass const & f); - RawFileClass & operator = (RawFileClass const & f); - virtual ~RawFileClass(void); - - virtual char const * File_Name(void) const; - virtual char const * Set_Name(char const *filename); - virtual int Create(void); - virtual int Delete(void); - virtual bool Is_Available(int forced=false); - virtual bool Is_Open(void) const; - virtual int Open(char const *filename, int rights=READ); - virtual int Open(int rights=READ); - virtual int Read(void *buffer, int size); - virtual int Seek(int pos, int dir=SEEK_CUR); - virtual int Size(void); - virtual int Write(void const *buffer, int size); - virtual void Close(void); - virtual unsigned long Get_Date_Time(void); - virtual bool Set_Date_Time(unsigned long datetime); - virtual void Error(int error, int canretry = false, char const * filename=NULL); - - void Bias(int start, int length=-1); - - virtual void * Get_File_Handle(void) { return Handle; } - - virtual void Attach (void *handle, int rights=READ); - virtual void Detach (void); - - /* - ** These bias values enable a sub-portion of a file to appear as if it - ** were the whole file. This comes in very handy for multi-part files such as - ** mixfiles. - */ - int BiasStart; - int BiasLength; - - protected: - - /* - ** This function returns the largest size a low level DOS read or write may - ** perform. Larger file transfers are performed in chunks of this size or less. - */ - int Transfer_Block_Size(void); - - int Raw_Seek(int pos, int dir=SEEK_CUR); - void Reset(void); - - private: - - /* - ** This is the low level DOS handle. A -1 indicates an empty condition. - */ - #ifdef _UNIX - FILE* Handle; - #else - void * Handle; - #endif - - /* - ** This points to the filename as a NULL terminated string. It may point to either a - ** constant or an allocated string as indicated by the "Allocated" flag. - */ - char const * Filename; - - // - // file date and time are in the following formats: - // - // date bits 0-4 day (0-31) - // bits 5-8 month (1-12) - // bits 9-15 year (0-119 representing 1980-2099) - // - // time bits 0-4 second/2 (0-29) - // bits 5-10 minutes (0-59) - // bits 11-15 hours (0-23) - // - unsigned short Date; - unsigned short Time; - - /* - ** Filenames that were assigned as part of the construction process - ** are not allocated. It is assumed that the filename string is a - ** constant in that case and thus making duplication unnecessary. - ** This value will be non-zero if the filename has be allocated - ** (using strdup()). - */ - bool Allocated; -}; - - -/*********************************************************************************************** - * RawFileClass::File_Name -- Returns with the filename associate with the file object. * - * * - * Use this routine to determine what filename is associated with this file object. If no * - * filename has yet been assigned, then this routing will return NULL. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with a pointer to the file name associated with this file object or NULL * - * if one doesn't exist. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 10/18/1994 JLB : Created. * - *=============================================================================================*/ -inline char const * RawFileClass::File_Name(void) const -{ - return(Filename); -} - - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/realcrc.cpp b/Generals/Code/Tools/WW3D/pluglib/realcrc.cpp deleted file mode 100644 index 9da812b164..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/realcrc.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Westwood Library * - * * - * $Archive:: /Commando/Code/wwlib/realcrc.cpp $* - * * - * Author:: Byon Garrabrant * - * * - * $Modtime:: 7/09/99 1:44p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * CRC_Memory -- calculates a CRC for a block of memory * - * CRC_String -- Calculates a CRC for a NULL-terminated string * - * CRC_Stringi -- Calculates a CRC for a string, case-insensitive * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "realcrc.h" -#include - -// CRC for poly 0x04C11DB7 -unsigned long CRC32_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,crc) (CRC32_Table[((unsigned long)(crc) ^ (c)) & 0xFFL] ^ (((crc) >> 8) & 0x00FFFFFFL)) - - -/*********************************************************************************************** - * CRC_Memory -- calculates a CRC for a block of memory * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -unsigned long CRC_Memory( const unsigned char *data, unsigned long length, unsigned long crc ) -{ - crc ^= 0xFFFFFFFF; // invert previous CRC - while ( length-- ) { - crc = CRC32( *data++, crc ); // calc crc for each byte - } - return (crc ^ 0xFFFFFFFF); // invert new CRC and return it -} - - -/*********************************************************************************************** - * CRC_String -- Calculates a CRC for a NULL-terminated string * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -unsigned long CRC_String( const char *string, unsigned long crc ) -{ - crc ^= 0xFFFFFFFF; // invert previous CRC - while ( *string ) { - crc = CRC32( *string++, crc ); // calc crc for each byte - } - return (crc ^ 0xFFFFFFFF); // invert new CRC and return it -} - - -/*********************************************************************************************** - * CRC_Stringi -- Calculates a CRC for a string, case-insensitive * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *=============================================================================================*/ -unsigned long CRC_Stringi( const char *string, unsigned long crc ) -{ - crc ^= 0xFFFFFFFF; // invert previous CRC - while ( *string ) { - char c = (char)toupper(*string++); - crc = CRC32( c, crc ); // calc crc for each byte - } - return (crc ^ 0xFFFFFFFF); // invert new CRC and return it -} diff --git a/Generals/Code/Tools/WW3D/pluglib/realcrc.h b/Generals/Code/Tools/WW3D/pluglib/realcrc.h deleted file mode 100644 index 793692934f..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/realcrc.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Westwood Library * - * * - * $Archive:: /G/wwlib/realcrc.h $* - * * - * Author:: Byon Garrabrant * - * * - * $Modtime:: 4/02/99 12:00p $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef REALCRC_H -#define REALCRC_H - - -unsigned long CRC_Memory( const unsigned char *data, unsigned long length, unsigned long crc = 0 ); -unsigned long CRC_String( const char *string, unsigned long crc = 0 ); -unsigned long CRC_Stringi( const char *string, unsigned long crc = 0 ); - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/rgb.cpp b/Generals/Code/Tools/WW3D/pluglib/rgb.cpp deleted file mode 100644 index 3249f90e71..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/rgb.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Library/RGB.CPP $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 7/22/97 11:37a $* - * * - * $Revision:: 1 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * RGBClass::Adjust -- Adjust one RGB value toward another. * - * RGBClass::Difference -- Determines the "distance" between two colors. * - * RGBClass::operator HSVClass -- Conversion operator for RGB to HSV object. * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "always.h" -#include "hsv.h" -#include "palette.h" -#include "rgb.h" - -RGBClass const BlackColor(0, 0, 0); - - -/*********************************************************************************************** - * RGBClass::Adjust -- Adjust one RGB value toward another. * - * * - * This routine is used to modify an RGB value to proportionately match another RGB value * - * according to the ratio parameter specified. Typical use of this routine is in palette * - * fading from one palette to another or to black. * - * * - * INPUT: ratio -- The ration of transformation. This value is in the form of 0 to 255, * - * with 0 being no change, and 255 being 100% transformed into the * - * destination color. * - * * - * rgb -- Reference to the destination RGB color to transform this color into. * - * * - * OUTPUT: none * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -void RGBClass::Adjust(int ratio, RGBClass const & rgb) -{ - /* - ** Ratio conversion is limited to 0 through 100%. This is - ** the range of 0 to 255. - */ - ratio &= 0x00FF; - - - /* - ** Adjust the color guns by the ratio specified toward the - ** destination color. - */ - int value = (int)rgb.Red - (int)Red; - Red = (unsigned char)((int)Red + (value * ratio) / 256); - - value = (int)rgb.Green - (int)Green; - Green = (unsigned char)((int)Green + (value * ratio) / 256); - - value = (int)rgb.Blue - (int)Blue; - Blue = (unsigned char)((int)Blue + (value * ratio) / 256); -} - - -/*********************************************************************************************** - * RGBClass::Difference -- Determines the "distance" between two colors. * - * * - * This routine is used to calculate a relative distance between two colors. The value is * - * relative only to itself and thus is useful only for determining the magnitude of * - * color difference rather than the nature of the color difference. Palette remapping * - * code uses this routine to find closest matches for colors. * - * * - * INPUT: rgb -- Reference to the color to be compared to this color. * - * * - * OUTPUT: Returns the difference between the two colors. The value returned is zero if the * - * colors exactly match. The greater the positive value the greater the difference * - * between the colors. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 12/02/1995 JLB : Created. * - *=============================================================================================*/ -int RGBClass::Difference(RGBClass const & rgb) const -{ - int r = (int)Red - (int)rgb.Red; - if (r < 0) r = -r; - - int g = (int)Green - (int)rgb.Green; - if (g < 0) g = -g; - - int b = (int)Blue - (int)rgb.Blue; - if (b < 0) b = -b; - - /* - ** At first crack, the difference algorithm might be coded as the sum of the color differences - ** (or sum of the square of the color distances). However, this would not take advantage of the - ** fact that the human eye is most sensative to green, followed by the color blue. With this - ** thought in mind, the following difference algorithm is used. - */ - return(4*g + 3*b + 2*r); -} - - -/*********************************************************************************************** - * RGBClass::operator HSVClass -- Conversion operator for RGB to HSV object. * - * * - * This conversion operator will convert an RGBClass object into an HSVClass object. * - * * - * INPUT: none * - * * - * OUTPUT: Returns with a reference (implicit) to the HSVClass object that most closely * - * represents the RGBClass object. * - * * - * WARNINGS: none * - * * - * HISTORY: * - * 02/20/1996 JLB : Created. * - *=============================================================================================*/ -RGBClass::operator HSVClass (void) const -{ - int hue; - int saturation; - int value; - - /* - ** Fetch working component values for the color guns. - */ - int red = Get_Red(); - int green = Get_Green(); - int blue = Get_Blue(); - - /* - ** The hue defaults to none. Only if there is a saturation value will the - ** hue be calculated. - */ - hue = 0; - - /* - ** Set the value (brightness) to match the brightest color gun. - */ - value = (red > green) ? red : green; - if (blue > value) value = blue; - - /* - ** Determine the amount of true white present in the color. This is the - ** minimum color gun value. The white component is used to determine - ** color saturation. - */ - int white = (red < green) ? red : green; - if (blue < white) white = blue; - - /* - ** Determine the saturation (intensity) of the color by comparing the - ** ratio of true white as a component of the overall color. The more - ** white component, the less saturation. - */ - saturation = 0; - if (value) { - saturation = ((value - white) * 255) / value; - } - - /* - ** If there is any saturation at all, then the hue must be calculated. The - ** hue is based on a six sided color wheel. - */ - if (saturation != 0) { - unsigned int tmp = value - white; - unsigned int r1 = ((value - red) * 255) / tmp; - unsigned int g1 = ((value - green) * 255) / tmp; - unsigned int b1 = ((value - blue) * 255) / tmp; - - // Find effect of second most predominant color. - // In which section of the hexagon of colors does the color lie? - if (value == red) { - if (white == green) { - tmp = 5 * 256 + b1; - } else { - tmp = 1 * 256 - g1; - } - } else { - if (value == green) { - if (white == blue) { - tmp = 1 * 256 + r1; - } else { - tmp = 3 * 256 - b1; - } - } else { - if (white == red) { - tmp = 3 * 256 + g1; - } else { - tmp = 5 * 256 - r1; - } - } - } - - // Divide by six and round. - hue = tmp / 6; - } - - HSVClass hsv((unsigned char)hue, (unsigned char)saturation, (unsigned char)value); - return(hsv); -} - diff --git a/Generals/Code/Tools/WW3D/pluglib/rgb.h b/Generals/Code/Tools/WW3D/pluglib/rgb.h deleted file mode 100644 index 3b001a8298..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/rgb.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/RGB.H $* - * * - * $Author:: Eric_c $* - * * - * $Modtime:: 4/02/99 12:00p $* - * * - * $Revision:: 2 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef RGB_H -#define RGB_H - -class PaletteClass; -class HSVClass; - - -/* -** Each color entry is represented by this class. It holds the values for the color -** guns. The gun values are recorded in device dependant format, but the interface -** uses gun values from 0 to 255. -*/ -class RGBClass -{ - public: - RGBClass(void) : Red(0), Green(0), Blue(0) {} - RGBClass(unsigned char red, unsigned char green, unsigned char blue) : Red(red), Green(green), Blue(blue) {} - operator HSVClass (void) const; - RGBClass & operator = (RGBClass const & rgb) { - if (this == &rgb) return(*this); - - Red = rgb.Red; - Green = rgb.Green; - Blue = rgb.Blue; - return(*this); - } - - enum { - MAX_VALUE=255 - }; - - void Adjust(int ratio, RGBClass const & rgb); - int Difference(RGBClass const & rgb) const; - int Get_Red(void) const {return (Red);} - int Get_Green(void) const {return(Green);} - int Get_Blue(void) const {return(Blue);} - void Set_Red(unsigned char value) {Red = value;} - void Set_Green(unsigned char value) {Green = value;} - void Set_Blue(unsigned char value) {Blue = value;} - - private: - - friend class PaletteClass; - - /* - ** These hold the actual color gun values in machine independant scale. This - ** means the values range from 0 to 255. - */ - unsigned char Red; - unsigned char Green; - unsigned char Blue; -}; - -extern RGBClass const BlackColor; - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/uarray.h b/Generals/Code/Tools/WW3D/pluglib/uarray.h deleted file mode 100644 index cc2918599d..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/uarray.h +++ /dev/null @@ -1,228 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Library * - * * - * $Archive:: /G/wwlib/uarray.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 9/24/99 1:56p $* - * * - * $Revision:: 7 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * UniqueArrayClass::UniqueArrayClass -- constructor * - * UniqueArrayClass::~UniqueArrayClass -- destructor * - * UniqueArrayClass::Add -- Add an item to the array * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef UARRAY_H -#define UARRAY_H - -#ifndef HASHCALC_H -#include "hashcalc.h" -#endif - -#ifndef VECTOR_H -#include "Vector.H" -#endif - - -/* -** UniqueArrayClass -** This template class can be used to generate an array of unique objects -** amongst a huge list of objects which may or may not be unique. However, -** in order to use the UniqueArrayClass, you will need to implement a -** HashCalculatorClass for the type you are using. -** -** Note that the UniqueArrayClass does *copies* of the objects you are -** giving it. It is meant to be used with relatively lightweight objects. -*/ -template class UniqueArrayClass -{ - -public: - - UniqueArrayClass(int initialsize,int growthrate,HashCalculatorClass * hasher); - ~UniqueArrayClass(void); - - int Add(const T & new_item); - - int Count(void) const { return Get_Unique_Count(); } - int Get_Unique_Count(void) const { return UniqueItems.Count(); } - const T & Get(int index) const { return UniqueItems[index].Item; } - const T & operator [] (int index) const { return Get(index); } - -private: - - enum { NO_ITEM = 0xFFFFFFFF }; - - class HashItem - { - public: - T Item; - int NextHashIndex; - - bool operator == (const HashItem & that) { return ((Item == that.Item) && (NextHashIndex == that.NextHashIndex)); } - bool operator != (const HashItem & that) { return !(*this == that); } - }; - - // Dynamic Vector of the unique items: - DynamicVectorClass UniqueItems; - - // Hash table: - int HashTableSize; - int * HashTable; - - // object which does the hashing for the type - HashCalculatorClass * HashCalculator; - - friend class VectorClass; - friend class DynamicVectorClass; -}; - - - -/*********************************************************************************************** - * UniqueArrayClass::UniqueArrayClass -- constructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/29/98 GTH : Created. * - *=============================================================================================*/ -template -UniqueArrayClass::UniqueArrayClass(int initial_size,int growth_rate,HashCalculatorClass * hasher) : - UniqueItems(initial_size), - HashCalculator(hasher) -{ - // set the growth rate. - UniqueItems.Set_Growth_Step(growth_rate); - - // sizing and allocating the actual hash table - int bits = HashCalculator->Num_Hash_Bits(); - assert(bits > 0); - assert(bits < 24); - HashTableSize = 1<::~UniqueArrayClass -- destructor * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/29/98 GTH : Created. * - *=============================================================================================*/ -template -UniqueArrayClass::~UniqueArrayClass(void) -{ - if (HashTable != NULL) { - delete[] HashTable; - HashTable = NULL; - } -} - - -/*********************************************************************************************** - * UniqueArrayClass::Add -- Add an item to the array * - * * - * Only adds the item to the end of the array if another duplicate item is not found. Returns * - * the array index of where the item is stored. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 5/29/98 GTH : Created. * - *=============================================================================================*/ -template -inline int UniqueArrayClass::Add(const T & new_item) -{ - /* - ** Use the hash table to quickly (hopefully :-) detect - ** whether this item is already in the array - */ - int num_hash_vals; - HashCalculator->Compute_Hash(new_item); - num_hash_vals = HashCalculator->Num_Hash_Values(); - - unsigned int lasthash = 0xFFFFFFFF; - unsigned int hash; - - for (int hidx = 0; hidx < num_hash_vals; hidx++) { - hash = HashCalculator->Get_Hash_Value(hidx); - if (hash != lasthash) { - - int test_item_index = HashTable[hash]; - - while (test_item_index != 0xFFFFFFFF) { - if (HashCalculator->Items_Match(UniqueItems[test_item_index].Item,new_item)) { - return test_item_index; - } - test_item_index = UniqueItems[test_item_index].NextHashIndex; - } - } - lasthash = hash; - } - - /* - ** Ok, this is a new item so add it (copy it!) into the array - */ - int index = UniqueItems.Count(); - int hash_index = HashCalculator->Get_Hash_Value(0); - - HashItem entry; - entry.Item = new_item; - entry.NextHashIndex = HashTable[hash_index]; - HashTable[hash_index] = index; - - UniqueItems.Add(entry); - - return index; -} - - -#endif // UARRAY_H - diff --git a/Generals/Code/Tools/WW3D/pluglib/vector2.h b/Generals/Code/Tools/WW3D/pluglib/vector2.h deleted file mode 100644 index 1c9b96ceca..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/vector2.h +++ /dev/null @@ -1,640 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/vector2.h 19 9/01/00 5:30p Ian_l $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Westwood 3D * - * * - * File Name : VECTOR2.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Scalar Division Operator -- Divide a vector by a scalar * - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * Vector Addition Operator -- Add two vectors * - * Vector Subtraction Operator -- Subract two vectors * - * Vector Inner Product Operator -- Compute the inner or dot product * - * Vector Equality Operator -- Detemine if two vectors are identical * - * Equal_Within_Epsilon -- Determine if two vectors are identical within * - * Vector Inequality Operator -- Detemine if two vectors are identical * - * Swap -- swap two Vector2's * - * Vector2::Is_Valid -- Verifies that all components are valid floats * - * Vector2::Update_Min -- sets each component of the vector to the min of this and a. * - * Vector2::Update_Max -- sets each component of the vector to the max of this and a. * - * Vector2::Scale -- multiply components of a vector by independant scaling factors. * - * Vector2::Lerp -- linearly interpolates two Vector2's * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR2_H -#define VECTOR2_H - -#include "always.h" -#include "wwmath.h" -#include - - -/* -** 2-Dimensional Vectors -*/ - -class Vector2 -{ - -public: - - union { - float X; - float U; - }; - - union { - float Y; - float V; - }; - - // Constructors - Vector2(void) {}; - Vector2(const Vector2 & v) { X = v.X; Y = v.Y; } - Vector2(float x, float y) { X = x; Y = y; } - Vector2(const float vector[2]) { X = vector[0]; Y = vector[1]; } - - - // Assignment - Vector2 & operator = (const Vector2 & v) { X = v[0]; Y = v[1]; return *this; } - void Set(float x, float y) { X = x; Y = y; } - void Set(const Vector2 & v) { X = v.X; Y = v.Y; } - - // Array access - float & operator [](int i) { return (&X)[i]; } - const float & operator [](int i) const { return (&X)[i]; } - - // normalize, compute length - void Normalize(void); - float Length(void) const; - float Length2(void) const; - - // unary operators - Vector2 operator-() const { return Vector2(-X,-Y); } - Vector2 operator+() const { return *this; } - - Vector2 & operator += (const Vector2 & v) { X += v.X; Y += v.Y; return *this; } - Vector2 & operator -= (const Vector2 & v) { X -= v.X; Y -= v.Y; return *this; } - Vector2 & operator *= (float k) { X = (float)(X*k); Y=(float)(Y*k); return *this; } - Vector2 & operator /= (float k) { k=1.0f/k; X*=k; Y*=k; return *this; } - - // scalar multiplication, division - friend Vector2 operator * (const Vector2 &a,float k); - friend Vector2 operator * (float k,const Vector2 &a); - friend Vector2 operator / (const Vector2 &a,float k); - - // vector addition,subtraction - friend Vector2 operator + (const Vector2 &a,const Vector2 &b); - friend Vector2 operator - (const Vector2 &a,const Vector2 &b); - - // dot product / inner product - friend float operator * (const Vector2 &a,const Vector2 &b); - static float Dot_Product(const Vector2 &a,const Vector2 &b); - - // dot product between a and perpendicular vector to b - static float Perp_Dot_Product(const Vector2 &a,const Vector2 &b); - - // Equality operators - friend bool operator == (const Vector2 &a,const Vector2 &b); - friend bool operator != (const Vector2 &a,const Vector2 &b); - friend bool Equal_Within_Epsilon(const Vector2 &a,const Vector2 &b,float epsilon); - - // Rotation - void Rotate(float theta); - void Rotate(float s, float c); - bool Rotate_Towards_Vector(Vector2 &target, float max_theta, bool & positive_turn); - bool Rotate_Towards_Vector(Vector2 &target, float max_s, float max_c, bool & positive_turn); - - // verify that none of the members of this vector are invalid floats - bool Is_Valid(void) const; - - // make this vector the min or max of itself and the passed vector - void Update_Min (const Vector2 & a); - void Update_Max (const Vector2 & a); - void Scale (float a, float b); - - static float Distance(const Vector2 &p1, const Vector2 &p2); - static float Quick_Distance(const Vector2 &p1, const Vector2 &p2); - - // interpolate between two Vector2's - static void Lerp(const Vector2 & a,const Vector2 & b,float t,Vector2 * set_result); -}; - - -/************************************************************************** - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -inline Vector2 operator * (const Vector2 &a,float k) -{ - return Vector2((a[0] * k),(a[1] * k)); -} - -inline Vector2 operator * (float k, const Vector2 &a) -{ - return Vector2((a[0] * k),(a[1] * k)); -} - -/************************************************************************** - * Scalar Division Operator -- Divide a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline Vector2 operator / (const Vector2 &a,float k) -{ - float ook=1.0f/k; - return Vector2((a[0] * ook),(a[1] * ook)); -} - -/************************************************************************** - * Vector Addition Operator -- Add two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -inline Vector2 operator + (const Vector2 &a,const Vector2 &b) -{ - return Vector2( - a.X + b.X, - a.Y + b.Y - ); -} - -/************************************************************************** - * Vector Subtraction Operator -- Subract two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -inline Vector2 operator - (const Vector2 &a,const Vector2 &b) -{ - return Vector2( - a.X - b.X, - a.Y - b.Y - ); -} - -/************************************************************************** - * Vector Inner Product -- Compute the inner or dot product of two vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline float operator * (const Vector2 &a,const Vector2 &b) -{ - return a.X*b.X + a.Y*b.Y; -} - -inline float Vector2::Dot_Product(const Vector2 &a,const Vector2 &b) -{ - return a*b; -} - -inline float Vector2::Perp_Dot_Product(const Vector2 &a,const Vector2 &b) -{ - return a.X * -b.Y + a.Y * b.X; -} - -/************************************************************************** - * Vector Equality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline bool operator == (const Vector2 &a,const Vector2 &b) -{ - return ( (a[0] == b[0]) && (a[1] == b[1])); -} - -/************************************************************************** - * Vector Inequality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline bool operator != (const Vector2 &a,const Vector2 &b) -{ - return ( (a[0] != b[0]) || (a[1] != b[1])); -} - -/************************************************************************** - * Equal_Within_Epsilon -- Determine if two vectors are identical within e* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline bool Equal_Within_Epsilon(const Vector2 &a,const Vector2 &b,float epsilon) -{ - return( (WWMath::Fabs(a.X - b.X) < epsilon) && (WWMath::Fabs(a.Y - b.Y) < epsilon) ); -} - -/************************************************************************** - * Vector2::Normalize -- Normalizes the vector. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline void Vector2::Normalize() -{ - float len2 = Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - X *= oolen; - Y *= oolen; - } -} - -inline Vector2 Normalize(const Vector2 & vec) -{ - float len2 = vec.Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - return vec / oolen; - } -} - -/************************************************************************** - * Vector2::Length -- Returns the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline float Vector2::Length() const -{ - return (float)WWMath::Sqrt(Length2()); -} - -/************************************************************************** - * Vector2::Length -- Returns the square of the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline float Vector2::Length2() const -{ - return (X*X + Y*Y); -} - -/************************************************************************** - * Vector2::Rotate -- Rotate vector * - * * - * INPUT: * - * float theta - angle to rotate * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline void Vector2::Rotate(float theta) -{ - Rotate(sin(theta), cos(theta)); -} - -/************************************************************************** - * Vector2::Rotate -- Rotate vector * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline void Vector2::Rotate(float s, float c) -{ - float new_x = X * c + Y * -s; - float new_y = X * s + Y * c; - X = new_x; - Y = new_y; -} - -/************************************************************************** - * Vector2::Rotate -- Rotate towards given vector (stop on reaching it) * - * * - * INPUT: * - * float theta - angle to rotate * - * * - * OUTPUT: * - * bool - true if we have reached the desired vector * - * * - * WARNINGS: * - * This function assumes both vectors are normalized! * - * * - * HISTORY: * - *========================================================================*/ -inline bool Vector2::Rotate_Towards_Vector(Vector2 &target, float max_theta, bool & positive_turn) -{ - return Rotate_Towards_Vector(target, sin(max_theta), cos(max_theta), positive_turn); -} - -/************************************************************************** - * Vector2::Rotate -- Rotate towards given vector (stop on reaching it) * - * * - * INPUT: * - * s - sine of the angle * - * c - cosine of the angle * - * * - * OUTPUT: * - * bool - true if we have reached the desired vector * - * * - * WARNINGS: * - * This function assumes both vectors are normalized! * - * * - * HISTORY: * - *========================================================================*/ -inline bool Vector2::Rotate_Towards_Vector(Vector2 &target, float max_s, float max_c, bool & positive_turn) -{ - bool return_value = false; - - positive_turn = Vector2::Perp_Dot_Product(target, *this) > 0.0f; - - if (Vector2::Dot_Product(*this, target) >= max_c) { - Set(target); - return_value = true; - } else { - // Determine turn direction and rotate accordingly. - if (positive_turn) { - Rotate(max_s, max_c); - } else { - Rotate(-max_s, max_c); - } - } - - return return_value; -} - -/*********************************************************************************************** - * Swap -- swap two Vector2's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -inline void Swap(Vector2 & a,Vector2 & b) -{ - Vector2 tmp(a); - a = b; - b = tmp; -} - - -/*********************************************************************************************** - * Vector2::Is_Valid -- Verifies that all components are valid floats * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -inline bool Vector2::Is_Valid(void) const -{ - return (WWMath::Is_Valid_Float(X) && WWMath::Is_Valid_Float(Y)); -} - - -/*********************************************************************************************** - * Vector2::Update_Min -- Set each component of the vector to the min of this and a. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/12/00 IML : Created. * - *=============================================================================================*/ -inline void Vector2::Update_Min (const Vector2 & a) -{ - if (a.X < X) X = a.X; - if (a.Y < Y) Y = a.Y; -} - - -/*********************************************************************************************** - * Vector2::Update_Max -- Set each component of the vector to the max of this and a. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/12/00 IML : Created. * - *=============================================================================================*/ -inline void Vector2::Update_Max (const Vector2 & a) -{ - if (a.X > X) X = a.X; - if (a.Y > Y) Y = a.Y; -} - - -/*********************************************************************************************** - * Vector2::Scale -- multiply components of a vector by independant scaling factors. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/19/2000 IML : Created. * - *=============================================================================================*/ -inline void Vector2::Scale (float a, float b) -{ - X *= a; - Y *= b; -} - - -/*********************************************************************************************** - * Quick_Distance -- Fast but inaccurate 2D distance calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -inline float Quick_Distance(float x1, float y1, float x2, float y2) -{ - // From Graphic Gems I. - float x_diff = x1 - x2; - float y_diff = y1 - y2; - - WWMath::Fabs(x_diff); - WWMath::Fabs(y_diff); - - if (x_diff > y_diff) - { - return ((y_diff / 2) + x_diff); - } - else - { - return ((x_diff / 2) + y_diff); - } -} - -inline float Vector2::Quick_Distance(const Vector2 &a, const Vector2 &b) -{ - return ::Quick_Distance(a.X, a.Y, b.X, b.Y); -} - - -/*********************************************************************************************** - * Distance -- Accurate distance 2D calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -inline float Vector2::Distance(const Vector2 &a, const Vector2 &b) -{ - Vector2 temp; - temp = a - b; - - return (temp.Length()); -} - -inline float Distance(float x1, float y1, float x2, float y2) -{ - float x_diff = x1 - x2; - float y_diff = y1 - y2; - - return (WWMath::Sqrt((x_diff * x_diff) + (y_diff * y_diff))); -} - - -/*********************************************************************************************** - * Vector2::Lerp -- linearly interpolates two Vector2's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 4/14/2000 gth : Created. * - *=============================================================================================*/ -inline void Vector2::Lerp(const Vector2 & a,const Vector2 & b,float t,Vector2 * set_result) -{ - assert(set_result != NULL); - set_result->X = (a.X + (b.X - a.X)*t); - set_result->Y = (a.Y + (b.Y - a.Y)*t); -} - - -#endif /* VECTOR2_H */ - diff --git a/Generals/Code/Tools/WW3D/pluglib/vector3.h b/Generals/Code/Tools/WW3D/pluglib/vector3.h deleted file mode 100644 index fb3e007620..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/vector3.h +++ /dev/null @@ -1,930 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/vector3.h 40 5/11/01 7:11p Jani_p $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Westwood 3D * - * * - * File Name : VECTOR3.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Scalar Division Operator -- Divide a vector by a scalar * - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * Vector Addition Operator -- Add two vectors * - * Vector Subtraction Operator -- Subract two vectors * - * Vector Inner Product Operator -- Compute the inner or dot product * - * Vector Equality Operator -- Determine if two vectors are identical * - * Vector Inequality Operator -- Determine if two vectors are identical * - * Equal_Within_Epsilon -- Determine if two vectors are identical within * - * Cross_Product -- compute the cross product of two vectors * - * Vector3::Normalize -- Normalizes the vector. * - * Vector3::Length -- Returns the length of the vector * - * Vector3::Length2 -- Returns the square of the length of the vector * - * Vector3::Quick_Length -- returns a quick approximation of the length * - * Swap -- swap two Vector3's * - * Lerp -- linearly interpolate two Vector3's by an interpolation factor. * - * Lerp -- linearly interpolate two Vector3's without return-by-value * - * Vector3::Add -- Add two vector3's without return-by-value * - * Vector3::Subtract -- Subtract two vector3's without return-by-value * - * Vector3::Update_Min -- sets each component of the vector to the min of this and a * - * Vector3::Update_Max -- Sets each component of the vector to the max of this and a * - * Vector3::Scale -- scale this vector by 3 independent scale factors * - * Vector3::Rotate_X -- rotates this vector around the X axis * - * Vector3::Rotate_X -- Rotates this vector around the x axis * - * Vector3::Rotate_Y -- Rotates this vector around the y axis * - * Vector3::Rotate_Y -- Rotates this vector around the Y axis * - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * Vector3::Is_Valid -- Verifies that each component of this vector is a valid float * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR3_H -#define VECTOR3_H - -#include "always.h" -#include "wwmath.h" -#include -#ifdef _UNIX -#include "osdep.h" -#endif - - -/* -** Vector3 - 3-Dimensional Vectors -*/ -class Vector3 -{ - -public: - - - float X; - float Y; - float Z; - - - // Constructors - WWINLINE Vector3(void) {}; - WWINLINE Vector3(const Vector3 & v) { X = v.X; Y = v.Y; Z = v.Z; } - WWINLINE Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } - WWINLINE Vector3(const float vector[3]) { X = vector[0]; Y = vector[1]; Z = vector[2]; } - - // Assignment - WWINLINE Vector3 & operator = (const Vector3 & v) { X = v.X; Y = v.Y; Z = v.Z; return *this; } - WWINLINE void Set(float x, float y, float z) { X = x; Y = y; Z = z; } - WWINLINE void Set(const Vector3 & that) { X = that.X; Y = that.Y; Z = that.Z; } - - // Array access - WWINLINE float & operator [](int i) { return (&X)[i]; } - WWINLINE const float & operator [](int i) const { return (&X)[i]; } - - // normalize, compute length - void Normalize(void); - WWINLINE float Length(void) const; - WWINLINE float Length2(void) const; - float Quick_Length(void) const; - void Scale(const Vector3 & scale); - - // rotation, (warning, modifies this vector!) - WWINLINE void Rotate_X(float angle); - WWINLINE void Rotate_X(float s_angle,float c_angle); - WWINLINE void Rotate_Y(float angle); - WWINLINE void Rotate_Y(float s_angle,float c_angle); - WWINLINE void Rotate_Z(float angle); - WWINLINE void Rotate_Z(float s_angle,float c_angle); - - // unary operators - WWINLINE Vector3 operator-() const { return(Vector3(-X,-Y,-Z)); } - WWINLINE Vector3 operator+() const { return *this; } - - WWINLINE Vector3 & operator += (const Vector3 & v) { X += v.X; Y += v.Y; Z += v.Z; return *this; } - WWINLINE Vector3 & operator -= (const Vector3 & v) { X -= v.X; Y -= v.Y; Z -= v.Z; return *this; } - WWINLINE Vector3 & operator *= (float k) { X = X*k; Y=Y*k; Z=Z*k; return *this; } - WWINLINE Vector3 & operator /= (float k) { float ook=1.0f/k; X=X*ook; Y=Y*ook; Z=Z*ook; return *this; } - - // scalar multiplication, division - WWINLINE friend Vector3 operator * (const Vector3 &a,float k); - WWINLINE friend Vector3 operator * (float k,const Vector3 &a); - WWINLINE friend Vector3 operator / (const Vector3 &a,float k); - - // vector addition,subtraction - WWINLINE friend Vector3 operator + (const Vector3 &a,const Vector3 &b); - WWINLINE friend Vector3 operator - (const Vector3 &a,const Vector3 &b); - - // Equality operators - friend bool operator == (const Vector3 &a,const Vector3 &b); - friend bool operator != (const Vector3 &a,const Vector3 &b); - WWINLINE friend bool Equal_Within_Epsilon(const Vector3 &a,const Vector3 &b,float epsilon); - - // dot product / inner product - WWINLINE friend float operator * (const Vector3 &a,const Vector3 &b); - static WWINLINE float Dot_Product(const Vector3 &a,const Vector3 &b); - - // cross product / outer product - static WWINLINE Vector3 Cross_Product(const Vector3 &a,const Vector3 &b); - static WWINLINE void Cross_Product(const Vector3 &a,const Vector3 &b,Vector3 * result); - static WWINLINE float Cross_Product_X(const Vector3 &a,const Vector3 &b); - static WWINLINE float Cross_Product_Y(const Vector3 &a,const Vector3 &b); - static WWINLINE float Cross_Product_Z(const Vector3 &a,const Vector3 &b); - - // add and subtract without return by value - static WWINLINE void Add(const Vector3 & a,const Vector3 & b,Vector3 * c); - static WWINLINE void Subtract(const Vector3 & a,const Vector3 & b,Vector3 * c); - - // Line intersection functions. - static WWINLINE float Find_X_At_Y(float y, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_X_At_Z(float z, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Y_At_X(float x, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Y_At_Z(float z, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Z_At_X(float x, const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Find_Z_At_Y(float z, const Vector3 &p1, const Vector3 &p2); - - // make this vector the min or max of itself and the passed vector - WWINLINE void Update_Min(const Vector3 & a); - WWINLINE void Update_Max(const Vector3 & a); - WWINLINE void Cap_Absolute_To(const Vector3 & a); - - // verify that none of the members of this vector are invalid floats - WWINLINE bool Is_Valid(void) const; - - static WWINLINE float Quick_Distance(const Vector3 &p1, const Vector3 &p2); - static WWINLINE float Distance(const Vector3 &p1, const Vector3 &p2); - - // Linearly interpolate two Vector3's - static void Lerp(const Vector3 & a, const Vector3 & b, float alpha,Vector3 * set_result); - - // Color Conversion - WWINLINE unsigned long Convert_To_ABGR( void ) const; - WWINLINE unsigned long Convert_To_ARGB( void ) const; -}; - - -/************************************************************************** - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector3 operator * (const Vector3 &a,float k) -{ - return Vector3((a.X * k),(a.Y * k),(a.Z * k)); -} - -WWINLINE Vector3 operator * (float k, const Vector3 &a) -{ - return Vector3((a.X * k),(a.Y * k),(a.Z * k)); -} - -/************************************************************************** - * Scalar Division Operator -- Divide a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE Vector3 operator / (const Vector3 &a,float k) -{ - float ook = 1.0f/k; - return Vector3((a.X * ook),(a.Y * ook),(a.Z * ook)); -} - -/************************************************************************** - * Vector Addition Operator -- Add two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector3 operator + (const Vector3 &a,const Vector3 &b) -{ - return Vector3( - a.X+b.X, - a.Y+b.Y, - a.Z+b.Z - ); -} - -/************************************************************************** - * Vector Subtraction Operator -- Subract two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -WWINLINE Vector3 operator - (const Vector3 &a,const Vector3 &b) -{ - return Vector3( - a.X-b.X, - a.Y-b.Y, - a.Z-b.Z - ); -} - -/************************************************************************** - * Vector Inner Product -- Compute the inner or dot product of two vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float operator * (const Vector3 &a,const Vector3 &b) -{ - return a.X*b.X + - a.Y*b.Y + - a.Z*b.Z; -} - -WWINLINE float Vector3::Dot_Product(const Vector3 &a,const Vector3 &b) -{ - return a*b; -} - - -/************************************************************************** - * Vector Equality Operator -- Determine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator == (const Vector3 &a,const Vector3 &b) -{ - return ( (a.X == b.X) && (a.Y == b.Y) && (a.Z == b.Z)); -} - -/************************************************************************** - * Vector Inequality Operator -- Determine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool operator != (const Vector3 &a,const Vector3 &b) -{ - return ( (a.X != b.X) || (a.Y != b.Y) || (a.Z != b.Z)); -} - -/************************************************************************** - * Equal_Within_Epsilon -- Determine if two vectors are identical within e* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE bool Equal_Within_Epsilon(const Vector3 &a,const Vector3 &b,float epsilon) -{ - return( (WWMath::Fabs(a.X - b.X) < epsilon) && - (WWMath::Fabs(a.Y - b.Y) < epsilon) && - (WWMath::Fabs(a.Z - b.Z) < epsilon) ); -} - - -/************************************************************************** - * Cross_Product -- compute the cross product of two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE Vector3 Vector3::Cross_Product(const Vector3 &a,const Vector3 &b) -{ - return Vector3( - (a.Y * b.Z - a.Z * b.Y), - (a.Z * b.X - a.X * b.Z), - (a.X * b.Y - a.Y * b.X) - ); -} - -WWINLINE void Vector3::Cross_Product(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != &a); - set_result->X = (a.Y * b.Z - a.Z * b.Y); - set_result->Y = (a.Z * b.X - a.X * b.Z); - set_result->Z = (a.X * b.Y - a.Y * b.X); -} - -WWINLINE float Vector3::Cross_Product_X(const Vector3 &a,const Vector3 &b) -{ - return a.Y * b.Z - a.Z * b.Y; -} - -WWINLINE float Vector3::Cross_Product_Y(const Vector3 &a,const Vector3 &b) -{ - return a.Z * b.X - a.X * b.Z; -} - -WWINLINE float Vector3::Cross_Product_Z(const Vector3 &a,const Vector3 &b) -{ - return a.X * b.Y - a.Y * b.X; -} - -/************************************************************************** - * Vector3::Normalize -- Normalizes the vector. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE void Vector3::Normalize() -{ - float len2 = Length2(); - if (len2 != 0.0f) - { - float oolen = WWMath::Inv_Sqrt(len2); - X *= oolen; - Y *= oolen; - Z *= oolen; - } -} - -#ifdef ALLOW_TEMPORARIES -WWINLINE Vector3 Normalize(const Vector3 & vec) -{ - float len2 = vec.Length2(); - if (len2 != 0.0f) - { - float oolen = WWMath::Inv_Sqrt(len2); - return vec * oolen; - } - return vec; -} -#endif - -/************************************************************************** - * Vector3::Length -- Returns the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector3::Length() const -{ - return WWMath::Sqrt(Length2()); -} - -/************************************************************************** - * Vector3::Length2 -- Returns the square of the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -WWINLINE float Vector3::Length2() const -{ - return X*X + Y*Y + Z*Z; -} - - -/*********************************************************************************************** - * Vector3::Quick_Length -- returns a quick approximation of the length * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 7/15/98 GTH : Created. * - *=============================================================================================*/ -WWINLINE float Vector3::Quick_Length(void) const -{ - // this method of approximating the length comes from Graphics Gems 1 and - // supposedly gives an error of +/- 8% - float max = WWMath::Fabs(X); - float mid = WWMath::Fabs(Y); - float min = WWMath::Fabs(Z); - float tmp; - - if (max < mid) { tmp = max; max = mid; mid = tmp; } - if (max < min) { tmp = max; max = min; min = tmp; } - if (mid < min) { tmp = mid; mid = min; min = mid; } - - return max + (11.0f / 32.0f)*mid + (1.0f / 4.0f)*min; -} - - -/*********************************************************************************************** - * Swap -- swap two Vector3's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE void Swap(Vector3 & a,Vector3 & b) -{ - Vector3 tmp(a); - a = b; - b = tmp; -} - -/*********************************************************************************************** - * Lerp -- linearly interpolate two Vector3's by an interpolation factor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: No checking is done to ensure that alpha is between 0 and 1. * - * * - * HISTORY: * - * 08/11/1997 GH : Created. * - *=============================================================================================*/ -WWINLINE Vector3 Lerp(const Vector3 & a, const Vector3 & b, float alpha) -{ - return Vector3( - (a.X + (b.X - a.X)*alpha), - (a.Y + (b.Y - a.Y)*alpha), - (a.Z + (b.Z - a.Z)*alpha) - ); -} - - -/*********************************************************************************************** - * Lerp -- linearly interpolate two Vector3's without return-by-value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Lerp(const Vector3 & a, const Vector3 & b, float alpha,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = (a.X + (b.X - a.X)*alpha); - set_result->Y = (a.Y + (b.Y - a.Y)*alpha); - set_result->Z = (a.Z + (b.Z - a.Z)*alpha); -} - -WWINLINE void Vector3::Lerp(const Vector3 & a, const Vector3 & b, float alpha,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = (a.X + (b.X - a.X)*alpha); - set_result->Y = (a.Y + (b.Y - a.Y)*alpha); - set_result->Z = (a.Z + (b.Z - a.Z)*alpha); -} - -/*********************************************************************************************** - * Vector3::Add -- Add two vector3's without return-by-value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Add(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = a.X + b.X; - set_result->Y = a.Y + b.Y; - set_result->Z = a.Z + b.Z; -} - - -/*********************************************************************************************** - * Vector3::Subtract -- Subtract two vector3's without return-by-value * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Subtract(const Vector3 &a,const Vector3 &b,Vector3 * set_result) -{ - assert(set_result != NULL); - set_result->X = a.X - b.X; - set_result->Y = a.Y - b.Y; - set_result->Z = a.Z - b.Z; -} - - -/*********************************************************************************************** - * Vector3::Update_Min -- sets each component of the vector to the min of this and a * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Update_Min(const Vector3 & a) -{ - if (a.X < X) X = a.X; - if (a.Y < Y) Y = a.Y; - if (a.Z < Z) Z = a.Z; -} - - -/*********************************************************************************************** - * Vector3::Update_Max -- Sets each component of the vector to the max of this and a * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Update_Max(const Vector3 & a) -{ - if (a.X > X) X = a.X; - if (a.Y > Y) Y = a.Y; - if (a.Z > Z) Z = a.Z; -} - -/*********************************************************************************************** - * Vector3::Cap_To_Absolute_Of -- Sets each component of the vector to no larger than the -ve or +ve of* - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 11/29/99 wst : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Cap_Absolute_To(const Vector3 & a) -{ - if (X > 0) - { - if (a.X < X) X = a.X; - } - else - { - if (-a.X > X) X = -a.X; - } - - if (Y > 0) - { - if (a.Y < Y) Y = a.Y; - } - else - { - if (-a.Y > Y) Y = -a.Y; - } - - if (Z > 0) - { - if (a.Z < Z) Z = a.Z; - } - else - { - if (-a.Z > Z) Z = -a.Z; - } - -} - -/*********************************************************************************************** - * Vector3::Scale -- scale this vector by 3 independent scale factors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Scale(const Vector3 & scale) -{ - X *= scale.X; - Y *= scale.Y; - Z *= scale.Z; -} - - -/*********************************************************************************************** - * Vector3::Rotate_X -- rotates this vector around the X axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_X(float angle) -{ - Rotate_X(sinf(angle),cosf(angle)); -} - - -/*********************************************************************************************** - * Vector3::Rotate_X -- Rotates this vector around the x axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_X(float s_angle,float c_angle) -{ - float tmp_y = Y; - float tmp_z = Z; - - Y = c_angle * tmp_y - s_angle * tmp_z; - Z = s_angle * tmp_y + c_angle * tmp_z; -} - - -/*********************************************************************************************** - * Vector3::Rotate_Y -- Rotates this vector around the y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Y(float angle) -{ - Rotate_Y(sinf(angle),cosf(angle)); -} - - -/*********************************************************************************************** - * Vector3::Rotate_Y -- Rotates this vector around the Y axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Y(float s_angle,float c_angle) -{ - float tmp_x = X; - float tmp_z = Z; - - X = c_angle * tmp_x + s_angle * tmp_z; - Z = -s_angle * tmp_x + c_angle * tmp_z; -} - - -/*********************************************************************************************** - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Z(float angle) -{ - Rotate_Z(sinf(angle),cosf(angle)); -} - - -/*********************************************************************************************** - * Vector3::Rotate_Z -- Rotates this vector around the Z axis * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE void Vector3::Rotate_Z(float s_angle,float c_angle) -{ - float tmp_x = X; - float tmp_y = Y; - - X = c_angle * tmp_x - s_angle * tmp_y; - Y = s_angle * tmp_x + c_angle * tmp_y; -} - - -/*********************************************************************************************** - * Vector3::Is_Valid -- Verifies that each component of this vector is a valid float * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -WWINLINE bool Vector3::Is_Valid(void) const -{ - return (WWMath::Is_Valid_Float(X) && WWMath::Is_Valid_Float(Y) && WWMath::Is_Valid_Float(Z)); -} - -WWINLINE float Vector3::Find_X_At_Y(float y, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.X + ((y - p1.Y) * ((p2.X - p1.X) / (p2.Y - p1.Y)))); -} -WWINLINE float Vector3::Find_X_At_Z(float z, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.X + ((z - p1.Z) * ((p2.X - p1.X) / (p2.Z - p1.Z)))); -} -WWINLINE float Vector3::Find_Y_At_X(float x, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Y + ((x - p1.X) * ((p2.Y - p1.Y) / (p2.X - p1.X)))); -} -WWINLINE float Vector3::Find_Y_At_Z(float z, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Y + ((z - p1.Z) * ((p2.Y - p1.Y) / (p2.Z - p1.Z)))); -} -WWINLINE float Vector3::Find_Z_At_X(float x, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Z + ((x - p1.X) * ((p2.Z - p1.Z) / (p2.X - p1.X)))); -} -WWINLINE float Vector3::Find_Z_At_Y(float y, const Vector3 &p1, const Vector3 &p2) -{ - return(p1.Z + ((y - p1.Y) * ((p2.Z - p1.Z) / (p2.Y - p1.Y)))); -} - -/*********************************************************************************************** - * Vector3::Distance -- Accurate distance calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE float Vector3::Distance(const Vector3 &p1, const Vector3 &p2) -{ - Vector3 temp; - temp = p1 - p2; - return (temp.Length()); -} - -/*********************************************************************************************** - * Vector3::Quick_Distance -- Fast but inaccurate distance calculation. * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE float Vector3::Quick_Distance(const Vector3 &p1, const Vector3 &p2) -{ - Vector3 temp; - temp = p1 - p2; - return (temp.Quick_Length()); -} - -/*********************************************************************************************** - * Vector3::Convert_To_ABGR -- Converts to SR packed color . * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE unsigned long Vector3::Convert_To_ABGR( void ) const -{ - return (unsigned(255)<<24) | - (unsigned(Z*255.0f)<<16) | - (unsigned(Y*255.0f)<<8) | - (unsigned(X*255.0f)); -} - -/*********************************************************************************************** - * Vector3::Convert_To_ARGB -- Converts to packed color . * - * * - * * - * * - * * - * HISTORY: * - * 11/29/1999MLL: Created. * - *=============================================================================================*/ -WWINLINE unsigned long Vector3::Convert_To_ARGB( void ) const -{ - return (unsigned(255)<<24) | - (unsigned(X*255.0f)<<16) | - (unsigned(Y*255.0f)<<8) | - (unsigned(Z*255.0f)); -} - -#endif /* Vector3_H */ - diff --git a/Generals/Code/Tools/WW3D/pluglib/vector3i.h b/Generals/Code/Tools/WW3D/pluglib/vector3i.h deleted file mode 100644 index ad43313d69..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/vector3i.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/vector3i.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 5/10/01 11:37p $* - * * - * $Revision:: 4 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR3I_H -#define VECTOR3I_H - -#include "always.h" - -class Vector3i -{ -public: - - int I; - int J; - int K; - - WWINLINE Vector3i(void); - WWINLINE Vector3i(int i,int j,int k); - - WWINLINE bool operator== (const Vector3i & v) const; - WWINLINE bool operator!= (const Vector3i& v) const; - WWINLINE const int& operator[] (int n) const; - WWINLINE int& operator[] (int n); -}; - - -WWINLINE Vector3i::Vector3i(void) -{ -} - -WWINLINE Vector3i::Vector3i(int i,int j,int k) -{ - I = i; J = j; K = k; -} - -WWINLINE bool Vector3i::operator == (const Vector3i & v) const -{ - return (I == v.I && J == v.J && K == v.K); -} - -WWINLINE bool Vector3i::operator != (const Vector3i& v) const -{ - return !(I == v.I && J == v.J && K == v.K); -} - -WWINLINE const int& Vector3i::operator[] (int n) const -{ - return ((int*)this)[n]; -} - -WWINLINE int& Vector3i::operator[] (int n) -{ - return ((int*)this)[n]; -} - -#endif \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/vector4.h b/Generals/Code/Tools/WW3D/pluglib/vector4.h deleted file mode 100644 index 87fb6a460d..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/vector4.h +++ /dev/null @@ -1,390 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/wwmath/vector4.h 12 12/14/99 11:08a Greg_h $ */ -/*************************************************************************** - *** Confidential - Westwood Studios *** - *************************************************************************** - * * - * Project Name : Westwood 3D * - * * - * File Name : VECTOR4.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : June 2, 1997 [GH] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * Scalar Division Operator -- Divide a vector by a scalar * - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * Vector Addition Operator -- Add two vectors * - * Vector Subtraction Operator -- Subract two vectors * - * Vector Inner Product Operator -- Compute the inner or dot product * - * Vector Equality Operator -- Detemine if two vectors are identical * - * Vector Inequality Operator -- Detemine if two vectors are identical * - * Swap -- swap two Vector4's * - * Vector4::Is_Valid -- Vector4::Is_Valid * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef VECTOR4_H -#define VECTOR4_H - -#include "always.h" -#include "wwmath.h" -#include - -/* -** Vector4 - 4 dimensional vectors -*/ -class Vector4 -{ - -public: - - float X; - float Y; - float Z; - float W; - - - // Constructors - Vector4(void) {}; - Vector4(const Vector4 & v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; } - Vector4(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } - Vector4(const float vector[4]) { X = vector[0]; Y = vector[1]; Z = vector[2]; W = vector[3]; } - - // Assignment - Vector4 & operator = (const Vector4 & v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; return *this; } - void Set(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } - - // Array access - float & operator [](int i) { return (&X)[i]; } - const float & operator [](int i) const { return (&X)[i]; } - - // normalize, compute length - void Normalize(void); - float Length(void) const; - float Length2(void) const; - - // unary operators - Vector4 operator-() const { return(Vector4(-X,-Y,-Z,-W)); } - Vector4 operator+() const { return *this; } - - Vector4 & operator += (const Vector4 & v) { X += v.X; Y += v.Y; Z += v.Z; W += v.W; return *this; } - Vector4 & operator -= (const Vector4 & v) { X -= v.X; Y -= v.Y; Z -= v.Z; W += v.W; return *this; } - Vector4 & operator *= (float k) { X = X*k; Y=Y*k; Z=Z*k; W=W*k; return *this; } - Vector4 & operator /= (float k) { k=1.0f/k; X = X*k; Y=Y*k; Z=Z*k; W=W*k; return *this; } - - // scalar multiplication, division - friend Vector4 operator * (const Vector4 &a,float k); - friend Vector4 operator * (float k,const Vector4 &a); - friend Vector4 operator / (const Vector4 &a,float k); - - // vector addition,subtraction - friend Vector4 operator + (const Vector4 &a,const Vector4 &b); - friend Vector4 operator - (const Vector4 &a,const Vector4 &b); - - // dot product / inner product - friend float operator * (const Vector4 &a,const Vector4 &b); - static float Dot_Product(const Vector4 &a,const Vector4 &b); - - // Equality operators - friend bool operator == (const Vector4 &a,const Vector4 &b); - friend bool operator != (const Vector4 &a,const Vector4 &b); - - // verify that none of the members of this vector are invalid floats - bool Is_Valid(void) const; -}; - -/************************************************************************** - * Scalar Multiply Operator -- Multiply a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -inline Vector4 operator * (const Vector4 &a,float k) -{ - return Vector4((a.X * k),(a.Y * k),(a.Z * k),(a.W * k)); -} - -inline Vector4 operator * (float k, const Vector4 &a) -{ - return a*k; -} - -/************************************************************************** - * Scalar Division Operator -- Divide a vector by a scalar * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline Vector4 operator / (const Vector4 &a,float k) -{ - float ook=1.0f/k; - return Vector4((a[0] * ook),(a[1] * ook),(a[2] * ook),(a[3] * ook)); -} - -/************************************************************************** - * Vector Addition Operator -- Add two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -inline Vector4 operator + (const Vector4 &a,const Vector4 &b) -{ - return Vector4( - a[0]+b[0], - a[1]+b[1], - a[2]+b[2], - a[3]+b[3] - ); -} - -/************************************************************************** - * Vector Subtraction Operator -- Subract two vectors * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *========================================================================*/ -inline Vector4 operator - (const Vector4 &a,const Vector4 &b) -{ - return Vector4( - a[0]-b[0], - a[1]-b[1], - a[2]-b[2], - a[3]-b[3] - ); -} - -/************************************************************************** - * Vector Inner Product -- Compute the inner or dot product of two vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline float operator * (const Vector4 &a,const Vector4 &b) -{ - return a[0]*b[0] + - a[1]*b[1] + - a[2]*b[2] + - a[3]*b[3]; -} - -inline float Vector4::Dot_Product(const Vector4 &a,const Vector4 &b) -{ - return a*b; -} - - -/************************************************************************** - * Vector Equality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline bool operator == (const Vector4 &a,const Vector4 &b) -{ - return ( (a[0] == b[0]) && (a[1] == b[1]) && (a[2] == b[2]) && (a[3] == b[3])); -} - -/************************************************************************** - * Vector Inequality Operator -- Detemine if two vectors are identical * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline bool operator != (const Vector4 &a,const Vector4 &b) -{ - return ( (a[0] != b[0]) || (a[1] != b[1]) || (a[2] != b[2]) || (a[3] != b[3])); -} - -/************************************************************************** - * Vector4::Normalize -- Normalizes the vector. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline void Vector4::Normalize() -{ - float len2 = Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - X *= oolen; - Y *= oolen; - Z *= oolen; - W *= oolen; - } -} - -inline Vector4 Normalize(const Vector4 & vec) -{ - float len2 = vec.Length2(); - if (len2 != 0.0f) { - float oolen = WWMath::Inv_Sqrt(len2); - return vec * oolen; - } -} - -/************************************************************************** - * Vector4::Length -- Returns the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline float Vector4::Length() const -{ - return WWMath::Sqrt(Length2()); -} - -/************************************************************************** - * Vector4::Length -- Returns the square of the length of the vector * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - *========================================================================*/ -inline float Vector4::Length2() const -{ - return X*X + Y*Y + Z*Z + W*W; -} - - -/*********************************************************************************************** - * Swap -- swap two Vector4's * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 06/02/1997 GH : Created. * - *=============================================================================================*/ -inline void Swap(Vector4 & a,Vector4 & b) -{ - Vector4 tmp(a); - a = b; - b = tmp; -} - -/*********************************************************************************************** - * Lerp -- linearly interpolate two Vector4's by an interpolation factor. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: No checking is done to ensure that alpha is between 0 and 1. * - * * - * HISTORY: * - * 01/14/1999 NH : Created. * - *=============================================================================================*/ -inline Vector4 Lerp(const Vector4 & a, const Vector4 & b, float alpha) -{ - return Vector4( - (a.X + (b.X - a.X)*alpha), - (a.Y + (b.Y - a.Y)*alpha), - (a.Z + (b.Z - a.Z)*alpha), - (a.W + (b.W - a.W)*alpha) - ); -} - - -/*********************************************************************************************** - * Vector4::Is_Valid -- Vector4::Is_Valid * - * * - * verifies that all members of this vector are valid floats * - * * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 10/18/99 gth : Created. * - *=============================================================================================*/ -inline bool Vector4::Is_Valid(void) const -{ - return (WWMath::Is_Valid_Float(X) && WWMath::Is_Valid_Float(Y) && WWMath::Is_Valid_Float(Z) && WWMath::Is_Valid_Float(W)); -} - - -#endif /* VECTOR4_H */ - diff --git a/Generals/Code/Tools/WW3D/pluglib/visualc.h b/Generals/Code/Tools/WW3D/pluglib/visualc.h deleted file mode 100644 index aec680e3f2..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/visualc.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/wwlib/visualc.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 5/16/01 4:11p $* - * * - * $Revision:: 9 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#if defined(_MSC_VER) - -/********************************************************************** -** The "bool" integral type was defined by the C++ comittee in -** November of '94. Until the compiler supports this, use the following -** definition. -*/ -#include "bool.h" - - -/* -** Make the inline depth 255 -*/ -#pragma inline_depth(255) - - -/* -** Turn off some unneeded warnings. -*/ - -// "unreferenced inline function has been removed" Yea, so what? -#pragma warning(disable : 4514) - -// "conversion from 'double' to 'float', possible loss of data" Yea, so what? -#pragma warning(disable : 4244) - -// "overflow in floating-point constant arithmetic" This warning occurs even if the -// loss of precision is insignificant. -#pragma warning(disable : 4056) - -// "function not inlined" This warning is typically useless. The inline keyword -// only serves as a suggestion to the compiler and it may or may not inline a -// function on a case by case basis. No need to be told of this. -#pragma warning(disable : 4710) - -// "'this' used in base member initializer list" Using "this" in a base member -// initializer is valid -- no need for this warning. -#pragma warning(disable : 4355) - -// "typedef-name used as a synonym for class-name". This is by design and should -// not be a warning. -#pragma warning(disable : 4097) - -// Unreferenced local function removed. -#pragma warning(disable : 4505) - -// 'function selected for automatic inlining' -#pragma warning(disable : 4711) - -// 'copy constructor could not be generated' -#pragma warning(disable : 4511) - -// 'assignment operator could not be generated' -#pragma warning(disable : 4512) - -// 'unreferenced formal parameter' -#pragma warning(disable : 4100) - -// HIDE WARNING 4786 "identifier was truncated to '255' characters in the browser information" -// Tempates create LLLOOONNNGGG identifiers! -#pragma warning(disable : 4786) - -// 'function selected for automatic inline expansion'. Cool, but since we're treating -// warnings as errors, don't warn me about this! -#pragma warning(disable : 4711) - - - -#define M_E 2.71828182845904523536 -#define M_LOG2E 1.44269504088896340736 -#define M_LOG10E 0.434294481903251827651 -#define M_LN2 0.693147180559945309417 -#define M_LN10 2.30258509299404568402 -#define M_PI 3.14159265358979323846 -#define M_PI_2 1.57079632679489661923 -#define M_PI_4 0.785398163397448309616 -#define M_1_PI 0.318309886183790671538 -#define M_2_PI 0.636619772367581343076 -#define M_1_SQRTPI 0.564189583547756286948 -#define M_2_SQRTPI 1.12837916709551257390 -#define M_SQRT2 1.41421356237309504880 -#define M_SQRT_2 0.707106781186547524401 - - -#endif - diff --git a/Generals/Code/Tools/WW3D/pluglib/w3d_file.h b/Generals/Code/Tools/WW3D/pluglib/w3d_file.h deleted file mode 100644 index 29f63966c8..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/w3d_file.h +++ /dev/null @@ -1,889 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/ww3d/w3d_file.h 56 8/12/98 11:16a Greg_h $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Commando / G 3D Library * - * * - * $Archive:: /Commando/Code/ww3d/w3d_file.h $* - * * - * $Author:: Greg_h $* - * * - * $Modtime:: 8/11/98 4:15p $* - * * - * $Revision:: 56 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#ifndef W3D_FILE_H -#define W3D_FILE_H - -#include "always.h" - -#ifndef BITTYPE_H -#include "BITTYPE.H" -#endif - - -/******************************************************************************** - -VERSION NUMBERS: - - Each Major chunk type will contain a "header" as its first - sub-chunk. The first member of this header will be a Version - number formatted so that its major revision number is the - high two bytes and its minor revision number is the lower two - bytes. - -Version 1.0: - - MESHES - contained the following chunks: - W3D_CHUNK_MESH_HEADER, // header for a mesh - W3D_CHUNK_VERTICES, // array of vertices - W3D_CHUNK_VERTEX_NORMALS, // array of normals - W3D_CHUNK_SURRENDER_NORMALS, // array of surrender normals (one per vertex as req. by surrender) - W3D_CHUNK_TEXCOORDS, // array of texture coordinates - W3D_CHUNK_MATERIALS, // array of materials - W3D_CHUNK_TRIANGLES, // array of triangles - W3D_CHUNK_SURRENDER_TRIANGLES,// array of surrender format tris - W3D_CHUNK_MESH_USER_TEXT, // Name of owning hierarchy, text from the MAX comment field - - HIERARCHY TREES - contained the following chunks: - W3D_CHUNK_HIERARCHY_HEADER, - W3D_CHUNK_PIVOTS, - W3D_CHUNK_PIVOT_FIXUPS, - - HIERARCHY ANIMATIONS - contained the following chunks: - W3D_CHUNK_ANIMATION_HEADER, - W3D_CHUNK_ANIMATION_CHANNEL, - - MESH CONNECTIONS - (blueprint for a hierarchical model) contained these chunks: - - -Version 2.0: - - MESHES: - - - Mesh header now contains the hierarchy model name. The mesh name will be built - as . instead of the old convention: . - - - The material chunk is replaced with a new material structure which contains - some information for animating materials. - - - Vertex Influences link vertices of a mesh to bones in a hierarchy, this is - the information needed for skinning. - - - Damage chunks added. A damage chunk contains a new set of materials, a set - of vertex offsets, and a set of vertex colors. - - Added the following chunks: - - W3D_CHUNK_VERTEX_COLORS, - W3D_CHUNK_VERTEX_INFLUENCES, - W3D_CHUNK_DAMAGE, - W3D_CHUNK_DAMAGE_HEADER, - W3D_CHUNK_DAMAGE_MATERIALS, - W3D_CHUNK_DAMAGE_VERTICES, - W3D_CHUNK_DAMAGE_COLORS, - W3D_CHUNK_MATERIALS2, - - MESH CONNECTIONS: Hierarchy models can now contain skins and collision meshes - in addition to the normal meshes. - - W3D_CHUNK_COLLISION_CONNECTION, // collision meshes connected to the hierarchy - W3D_CHUNK_SKIN_CONNECTION, // skins connected to the hierarchy - W3D_CHUNK_CONNECTION_AUX_DATA // extension of the connection header - - -Dec 12, 1997 - - Changed MESH_CONNECTIONS chunks into HMODEL chunks because the name - mesh connections was becoming more and more inappropriate... This was only - a data structure naming change so no-one other than the coders are affected - - Added W3D_CHUNK_LODMODEL. An LOD Model contains a set of names for - render objects, each with a specified distance range. - - -Feb 6, 1998 - - Added W3D_CHUNK_SECTMESH and its sub-chunks. This will be the file - format for the terrain geometry exported from POV's Atlas tool. - -March 29, 1998 : Version 3.0 - - - New material chunk which supports the new features of the 3D engine - - Modified HTrees to always have a root transform to remove all of the - special case -1 bone indexes. - - Added new mesh types, A mesh can now be categorized as: normal, - aligned, skin, collision, or shadow. - -June 22, 1998 - - Removed the "SECTMESH" chunks which were never implemented or used. - - Adding a new type of object: The 'Tilemap'. This simple-sounding object - is a binary partition tree of tiles where tiles are rectangular regions of - space. In each leaf to the tree, a mesh is referenced. The tile map is - made of several chunks: - - - W3D_CHUNK_TILEMAP - - W3D_CHUNK_TILEMAP_HEADER - - W3D_CHUNK_TILES - - W3D_CHUNK_MESH - - W3D_CHUNK_MESH - ... - - - W3D_CHUNK_PARTITION_TREE - - W3D_CHUNK_PARTITION_TREE_HEADER - - W3D_CHUNK_PARTITION_TREE_NODES - - - W3D_CHUNK_TILE_INSTANCES - - W3D_CHUNK_TILE_INSTANCE - - - -********************************************************************************/ - - -#define W3D_MAKE_VERSION(major,minor) (((major) << 16) | (minor)) -#define W3D_GET_MAJOR_VERSION(ver) ((ver)>>16) -#define W3D_GET_MINOR_VERSION(ver) ((ver) & 0xFFFF) - -#define W3D_CURRENT_VERSION W3D_MAKE_VERSION(3,0) - - - -/******************************************************************************** - - CHUNK TYPES FOR ALL 3D DATA - - All 3d data is stored in chunks similar to an IFF file. Each - chunk will be headed by an ID and size field. - - All structures defined in this header file are prefixed with - W3d to prevent naming conflicts with in-game structures which - may be slightly different than the on-disk structures. - -********************************************************************************/ - -enum { - - W3D_CHUNK_MESH = 0, // Mesh definition (.WTM file) - W3D_CHUNK_MESH_HEADER, // header for a mesh - W3D_CHUNK_VERTICES, // array of vertices - W3D_CHUNK_VERTEX_NORMALS, // array of normals - W3D_CHUNK_SURRENDER_NORMALS, // array of surrender normals (one per vertex as req. by surrender) - W3D_CHUNK_TEXCOORDS, // array of texture coordinates - W3D_CHUNK_MATERIALS, // array of materials - O_W3D_CHUNK_TRIANGLES, // array of triangles (obsolete) - O_W3D_CHUNK_QUADRANGLES, // array of quads (obsolete) - W3D_CHUNK_SURRENDER_TRIANGLES,// array of surrender format tris - O_W3D_CHUNK_POV_TRIANGLES, // POV format triangles (obsolete) - O_W3D_CHUNK_POV_QUADRANGLES, // POV format quads (obsolete) - W3D_CHUNK_MESH_USER_TEXT, // Name of owning hierarchy, text from the MAX comment field - W3D_CHUNK_VERTEX_COLORS, // Pre-set vertex coloring - W3D_CHUNK_VERTEX_INFLUENCES, // Mesh Deformation vertex connections - W3D_CHUNK_DAMAGE, // Mesh damage, new set of materials, vertex positions, vertex colors - W3D_CHUNK_DAMAGE_HEADER, // Header for the damage data, tells what is coming - W3D_CHUNK_DAMAGE_VERTICES, // Array of modified vertices (W3dMeshDamageVertexStruct's) - W3D_CHUNK_DAMAGE_COLORS, // Array of modified vert colors (W3dMeshDamageColorStruct's) - O_W3D_CHUNK_DAMAGE_MATERIALS, // (OBSOLETE) Damage materials simply wrapped with MATERIALS3 or higher - - W3D_CHUNK_MATERIALS2, // array of version 2 materials (with animation frame counts) - - W3D_CHUNK_MATERIALS3, // array of version 3 materials (all new surrender features supported) - W3D_CHUNK_MATERIAL3, // Each version 3 material wrapped with this chunk ID - W3D_CHUNK_MATERIAL3_NAME, // Name of the material (array of chars, null terminated) - W3D_CHUNK_MATERIAL3_INFO, // contains a W3dMaterial3Struct, general material info - W3D_CHUNK_MATERIAL3_DC_MAP, // wraps the following two chunks, diffuse color texture - W3D_CHUNK_MAP3_FILENAME, // filename of the texture - W3D_CHUNK_MAP3_INFO, // a W3dMap3Struct - W3D_CHUNK_MATERIAL3_DI_MAP, // diffuse illimination map, same format as other maps - W3D_CHUNK_MATERIAL3_SC_MAP, // specular color map, same format as other maps - W3D_CHUNK_MATERIAL3_SI_MAP, // specular illumination map, same format as other maps - - W3D_CHUNK_MESH_HEADER3, // New improved mesh header - W3D_CHUNK_TRIANGLES, // New improved triangles chunk - W3D_CHUNK_PER_TRI_MATERIALS, // Multi-Mtl meshes - An array of uint16 material id's - - W3D_CHUNK_HIERARCHY = 0x100, // hierarchy tree definition (.WHT file) - W3D_CHUNK_HIERARCHY_HEADER, - W3D_CHUNK_PIVOTS, - W3D_CHUNK_PIVOT_FIXUPS, // only needed by the exporter... - - W3D_CHUNK_ANIMATION = 0x200, // hierarchy animation data (.WHA file) - W3D_CHUNK_ANIMATION_HEADER, - W3D_CHUNK_ANIMATION_CHANNEL, - W3D_CHUNK_BIT_CHANNEL, // channel of boolean values (e.g. visibility) - - W3D_CHUNK_HMODEL = 0x300, // blueprint for a hierarchy model - W3D_CHUNK_HMODEL_HEADER, // usually found at end of a .WTM file - W3D_CHUNK_NODE, // render objects connected to the hierarchy - W3D_CHUNK_COLLISION_NODE, // collision meshes connected to the hierarchy - W3D_CHUNK_SKIN_NODE, // skins connected to the hierarchy - W3D_CHUNK_HMODEL_AUX_DATA, // extension of the connection header - W3D_CHUNK_SHADOW_NODE, // shadow object connected to the hierarchy - - W3D_CHUNK_LODMODEL = 0x400, // blueprint for an LOD model. This is simply a - W3D_CHUNK_LODMODEL_HEADER, // collection of 'n' render objects, ordered in terms - W3D_CHUNK_LOD, // of their expected rendering costs. - - W3D_CHUNK_TILEMAP = 0x600, // Tile Map definition. - W3D_CHUNK_TILEMAP_NAME, - W3D_CHUNK_TILEMAP_HEADER, - W3D_CHUNK_TILEMAP_TILE_INSTANCES, - W3D_CHUNK_TILEMAP_PARTITION_TREE, - W3D_CHUNK_TILEMAP_PARTITION_NODE, - -}; - - -struct W3dChunkHeader -{ - uint32 ChunkType; // Type of chunk (see above enumeration) - uint32 ChunkSize; // Size of the chunk, (not including the chunk header) -}; - - -/******************************************************************************** - - WTM ( Westwood Triangle Mesh ) - - Each mesh will be contained within a WTM_CHUNK_MESH within - this chunk will be the following chunks: - - The header will be the first chunk and it tells general - information about the mesh such as how many triangles there - are, how many vertices, the bounding box, center - of mass, inertia matrix, etc. - - The vertex array is an array of Vectors giving the object - space location of each vertex - - The normal array is an array of all of the unique vertex - normal vectors needed by the mesh. This allows for vertices - with multiple normals so that we can duplicate the effect - of the smoothing groups in 3dsMax. - - The surrender normal array is an array of vertex normals which - correspond 1to1 with the vertices. This is because the current - version of surrender can only handle one vertex normal per vertex. - In this case, the application should skip the normal array chunk - and read the surrender normal chunk into its SR_VERTs - - The texture coord array is all of the unique texture coordinates - for the mesh. This allows triangles to share vertices but not - necessarily share texture coordinates. - - The material array is a list of the names and rgb colors of - all of the unique materials used by the mesh. All triangles will - have a material index into this list. - - The triangle array is all of the triangles which make up the - mesh. Each triangle has 3 indices to its vertices, vertex normals, - and texture coordinates. Each also has a material id and the - coefficients for its plane equation. - - The Surrender Triangle array is all of the triangles in a slightly - different format. Surrender triangles contain their u-v coordinates - so there is no indirection and no possibility for sharing. To - make the importer faster, the triangles will also be stored in this - format. The application can read whichever chunk it wants to. - - The mesh user text chunk is a NULL-terminated text buffer. - -********************************************************************************/ - -#define W3D_NAME_LEN 16 - -///////////////////////////////////////////////////////////////////////////////////////////// -// vector -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dVectorStruct -{ - float32 X; // X,Y,Z coordinates - float32 Y; - float32 Z; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// quaternion -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dQuaternionStruct -{ - float32 Q[4]; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// texture coordinate -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dTexCoordStruct -{ - float32 U; // U,V coordinates - float32 V; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// rgb color, one byte per channel, padded to an even 4 bytes -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dRGBStruct -{ - uint8 R; - uint8 G; - uint8 B; - uint8 pad; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 1.0 Material, array of these are found inside the W3D_CHUNK_MATERIALS chunk. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterialStruct -{ - char MaterialName[W3D_NAME_LEN]; // name of the material (NULL terminated) - char PrimaryName[W3D_NAME_LEN]; // primary texture name (NULL terminated) - char SecondaryName[W3D_NAME_LEN]; // secondary texture name (NULL terminated) - uint32 RenderFlags; // Rendering flags - uint8 Red; // Rgb colors - uint8 Green; - uint8 Blue; -}; - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 2.0 Material, array of these are found inside the W3D_CHUNK_MATERIALS2 chunk. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterial2Struct -{ - char MaterialName[W3D_NAME_LEN]; // name of the material (NULL terminated) - char PrimaryName[W3D_NAME_LEN]; // primary texture name (NULL terminated) - char SecondaryName[W3D_NAME_LEN]; // secondary texture name (NULL terminated) - uint32 RenderFlags; // Rendering flags - uint8 Red; // Rgb colors - uint8 Green; - uint8 Blue; - uint8 Alpha; - - uint16 PrimaryNumFrames; // number of animated frames (if 1, not animated) - uint16 SecondaryNumFrames; // number of animated frames (if 1, not animated) - - char Pad[12]; // expansion room -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// MATERIAL ATTRIBUTES (version 3.0 onward) -///////////////////////////////////////////////////////////////////////////////////////////// -// Use alpha enables alpha channels, etc, Use sorting causes display lists using -// this material to be sorted (even with z-buf, translucent materials need to be sorted) -#define W3DMATERIAL_USE_ALPHA 0x00000001 -#define W3DMATERIAL_USE_SORTING 0x00000002 - -// Hints for render devices that cannot support all features -#define W3DMATERIAL_HINT_DIT_OVER_DCT 0x00000010 -#define W3DMATERIAL_HINT_SIT_OVER_SCT 0x00000020 -#define W3DMATERIAL_HINT_DIT_OVER_DIG 0x00000040 -#define W3DMATERIAL_HINT_SIT_OVER_SIG 0x00000080 -#define W3DMATERIAL_HINT_FAST_SPECULAR_AFTER_ALPHA 0x00000100 - -// Last byte is for PSX: Translucency type and a lighting disable flag. -#define W3DMATERIAL_PSX_MASK 0xFF000000 -#define W3DMATERIAL_PSX_TRANS_MASK 0x07000000 -#define W3DMATERIAL_PSX_TRANS_NONE 0x00000000 -#define W3DMATERIAL_PSX_TRANS_100 0x01000000 -#define W3DMATERIAL_PSX_TRANS_50 0x02000000 -#define W3DMATERIAL_PSX_TRANS_25 0x03000000 -#define W3DMATERIAL_PSX_TRANS_MINUS_100 0x04000000 -#define W3DMATERIAL_PSX_NO_RT_LIGHTING 0x08000000 - -///////////////////////////////////////////////////////////////////////////////////////////// -// MAPPING TYPES (version 3.0 onward) -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3DMAPPING_UV 0 -#define W3DMAPPING_ENVIRONMENT 1 - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 3.0 Material, A W3D_CHUNK_MATERIALS3 chunk will wrap a bunch of -// W3D_CHUNK_MATERIAL3 chunks. Inside each chunk will be a name chunk, an 'info' chunk which -// contains the following struct, and one or more map chunks. a mesh with 2 materials might -// look like: -// -// W3D_CHUNK_MATERIALS3 <-- simply a wrapper around the array of mtls -// W3D_CHUNK_MATERIAL3 <-- a wrapper around each material -// W3D_CHUNK_STRING <-- name of the material -// W3D_CHUNK_MATERIAL3_INFO <-- standard material properties, a W3dMaterial3Struct -// W3D_CHUNK_MATERIAL3_DC_MAP <-- a map, W3dMap3Struct -// W3D_CHUNK_STRING <-- filename of the map -// W3D_CHUNK_MAP_INFO <-- map parameters -// W3D_CHUNK_MATERIAL3_SC_MAP -// W3D_CHUNK_STRING <-- filename of the map -// W3D_CHUNK_MAP_INFO -// W3D_CHUNK_MATERIAL3 -// W3D_CHUNK_MATERIAL3_NAME -// W3D_CHUNK_MATERIAL3_INFO -// W3D_CHUNK_MATERIAL3_SI_MAP -// -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMaterial3Struct -{ - uint32 Attributes; // flags,hints,etc. - - W3dRGBStruct DiffuseColor; // diffuse color - W3dRGBStruct SpecularColor; // specular color - - W3dRGBStruct EmissiveCoefficients; // emmissive coefficients, default to 0,0,0 - W3dRGBStruct AmbientCoefficients; // ambient coefficients, default to 1,1,1 - W3dRGBStruct DiffuseCoefficients; // diffuse coeficients, default to 1,1,1 - W3dRGBStruct SpecularCoefficients; // specular coefficients, default to 0,0,0 - - float32 Shininess; // how tight the specular highlight will be, 1 - 1000 (default = 1) - float32 Opacity; // how opaque the material is, 0.0 = invisible, 1.0 = fully opaque (default = 1) - float32 Translucency; // how much light passes through the material. (default = 0) - float32 FogCoeff; // effect of fog (0.0=not fogged, 1.0=fogged) (default = 1) -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A map, only occurs as part of a material, will be preceeded by its name. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMap3Struct -{ - uint16 MappingType; // Mapping type, will be one of the above #defines (e.g. W3DMAPPING_UV) - uint16 FrameCount; // Number of frames (1 if not animated) - float32 FrameRate; // Frame rate, frames per second in floating point -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A triangle, occurs inside the W3D_CHUNK_SURRENDER_TRIANGLES chunk -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dSurrenderTriStruct -{ - uint32 Vindex[3]; // vertex, vert normal, and texture coord indexes (all use same index) - W3dTexCoordStruct TexCoord[3]; // texture coordinates (OBSOLETE!!!) - uint32 MaterialIdx; // material index - W3dVectorStruct Normal; // Face normal - uint32 Attributes; // collision flags, sort method, etc - W3dRGBStruct Gouraud[3]; // Pre-set shading values (OBSOLETE!!!) -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// A triangle, occurs inside the W3D_CHUNK_TRIANGLES chunk -// This is NEW for Version 3. -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dTriStruct -{ - uint32 Vindex[3]; // vertex,vnormal,texcoord,color indices - uint32 Attributes; // attributes bits - W3dVectorStruct Normal; // plane normal - float32 Dist; // plane distance -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Flags for the Mesh Attributes member -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3D_MESH_FLAG_NONE 0x00000000 // plain ole normal mesh -#define W3D_MESH_FLAG_COLLISION_BOX 0x00000001 // mesh is a collision box (should be 8 verts, should be hidden, etc) -#define W3D_MESH_FLAG_SKIN 0x00000002 // skin mesh -#define W3D_MESH_FLAG_SHADOW 0x00000004 // intended to be projected as a shadow -#define W3D_MESH_FLAG_ALIGNED 0x00000008 // always aligns with camera - -#define W3D_MESH_FLAG_COLLISION_TYPE_MASK 0x00000FF0 // mask for the collision type bits -#define W3D_MESH_FLAG_COLLISION_TYPE_SHIFT 4 // shifting to get to the collision type bits -#define W3D_MESH_FLAG_COLLISION_TYPE_PHYSICAL 0x00000010 // physical collisions -#define W3D_MESH_FLAG_COLLISION_TYPE_PROJECTILE 0x00000020 // projectiles (rays) collide with this - -#define W3D_MESH_FLAG_HIDDEN 0x00001000 // this mesh is hidden by default - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Original (Obsolete) Mesh Header -///////////////////////////////////////////////////////////////////////////////////////////// -struct W3dMeshHeaderStruct -{ - uint32 Version; // Currently version 0x100 - char MeshName[W3D_NAME_LEN]; // name of the mesh (Null terminated) - uint32 Attributes; - - // - // Counts, these can be regarded as an inventory of what is to come in the file. - // - uint32 NumTris; // number of triangles (OBSOLETE!) - uint32 NumQuads; // number of quads; (OBSOLETE!) - uint32 NumSrTris; // number of triangles - - uint32 NumPovTris; // (NOT USED) - uint32 NumPovQuads; // (NOT USED) - - uint32 NumVertices; // number of unique vertices - uint32 NumNormals; // number of unique normals (OBSOLETE!) - uint32 NumSrNormals; // number of surrender normals (MUST EQUAL NumVertices or 0) - - uint32 NumTexCoords; // number of unique texture coords (MUST EQUAL NumVertices or 0) - uint32 NumMaterials; // number of unique materials needed - - uint32 NumVertColors; // number of vertex colors (MUST EQUAL NumVertices or 0) - uint32 NumVertInfluences;// vertex influences(MUST EQUAL NumVertices or 0) - uint32 NumDamageStages; // number of damage offset chunks - uint32 FutureCounts[5]; // reserve space for future counts (set to zero). - - // - // LOD controls - // - float32 LODMin; // min LOD distance - float32 LODMax; // max LOD distance - - // - // Collision / rendering quick-rejection - // - W3dVectorStruct Min; // Min corner of the bounding box - W3dVectorStruct Max; // Max corner of the bounding box - W3dVectorStruct SphCenter; // Center of bounding sphere - float32 SphRadius; // Bounding sphere radius - - // - // Default transformation - // - W3dVectorStruct Translation; - float32 Rotation[9]; - - // - // Physics Properties - // - W3dVectorStruct MassCenter; // Center of mass in object space - float32 Inertia[9]; // Inertia tensor (relative to MassCenter) - float32 Volume; // volume of the object - - // - // Name of possible hierarchy this mesh should be attached to - // - char HierarchyTreeName[W3D_NAME_LEN]; - char HierarchyModelName[W3D_NAME_LEN]; - uint32 FutureUse[24]; // Reserved for future use -}; - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Version 3 Mesh Header, trimmed out some of the junk that was in the -// previous versions. -///////////////////////////////////////////////////////////////////////////////////////////// -#define W3D_VERTEX_CHANNEL_LOCATION 0x00000001 // object-space location of the vertex -#define W3D_VERTEX_CHANNEL_NORMAL 0x00000002 // object-space normal for the vertex -#define W3D_VERTEX_CHANNEL_TEXCOORD 0x00000004 // texture coordinate -#define W3D_VERTEX_CHANNEL_COLOR 0x00000008 // vertex color -#define W3D_VERTEX_CHANNEL_BONEID 0x00000010 // per-vertex bone id for skins - -#define W3D_FACE_CHANNEL_FACE 0x00000001 // basic face info, W3dTriStruct... - -struct W3dMeshHeader3Struct -{ - uint32 Version; - uint32 Attributes; - - char MeshName[W3D_NAME_LEN]; - char HierarchyModelName[W3D_NAME_LEN]; - - // - // Counts, these can be regarded as an inventory of what is to come in the file. - // - uint32 NumTris; // number of triangles - uint32 NumVertices; // number of unique vertices - uint32 NumMaterials; // number of unique materials - uint32 NumDamageStages; // number of damage offset chunks - uint32 FutureCounts[3]; // future counts - - uint32 VertexChannels; // bits for presence of types of per-vertex info - uint32 FaceChannels; // bits for presence of types of per-face info - - // - // Bounding volumes - // - W3dVectorStruct Min; // Min corner of the bounding box - W3dVectorStruct Max; // Max corner of the bounding box - W3dVectorStruct SphCenter; // Center of bounding sphere - float32 SphRadius; // Bounding sphere radius - -}; - -// -// Vertex Influences. For "skins" each vertex can be associated with a -// different bone. -// -struct W3dVertInfStruct -{ - uint16 BoneIdx; - uint8 Pad[6]; -}; - -// -// Mesh Damage. This can include a new set of materials for the mesh, -// new positions for certain vertices in the mesh, and new vertex -// colors for certain vertices. -// -struct W3dMeshDamageStruct -{ - uint32 NumDamageMaterials; // number of materials to replace - uint32 NumDamageVerts; // number of vertices to replace - uint32 NumDamageColors; // number of vertex colors to replace - uint32 DamageIndex; // what index is this damage chunk assigned to - uint32 FutureUse[4]; -}; - -struct W3dMeshDamageVertexStruct -{ - uint32 VertexIndex; - W3dVectorStruct NewVertex; -}; - -struct W3dMeshDamageColorStruct -{ - uint32 VertexIndex; - W3dRGBStruct NewColor; -}; - - -/******************************************************************************** - - WHT ( Westwood Hierarchy Tree ) - - A hierarchy tree defines a set of coordinate systems which are connected - hierarchically. The header defines the name, number of pivots, etc. - The pivots chunk will contain a W3dPivotStructs for each node in the - tree. - - The W3dPivotFixupStruct contains a transform for each MAX coordinate - system and our version of that same coordinate system (bone). It is - needed when the user exports the base pose using "Translation Only". - These are the matrices which go from the MAX rotated coordinate systems - to a system which is unrotated in the base pose. These transformations - are needed when exporting a hierarchy animation with the given hierarchy - tree file. - - Another explanation of these kludgy "fixup" matrices: - - What are the "fixup" matrices? These are the transforms which - were applied to the base pose when the user wanted to force the - base pose to use only matrices with certain properties. For - example, if we wanted the base pose to use translations only, - the fixup transform for each node is a transform which when - multiplied by the real node's world transform, yeilds a pure - translation matrix. Fixup matrices are used in the mesh - exporter since all vertices must be transformed by their inverses - in order to make things work. They also show up in the animation - exporter because they are needed to make the animation work with - the new base pose. - -********************************************************************************/ - -struct W3dHierarchyStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; // Name of the hierarchy - uint32 NumPivots; - W3dVectorStruct Center; -}; - -struct W3dPivotStruct -{ - char Name[W3D_NAME_LEN]; // Name of the node (UR_ARM, LR_LEG, TORSO, etc) - uint32 ParentIdx; // 0xffffffff = root pivot; no parent - W3dVectorStruct Translation; // translation to pivot point - W3dVectorStruct EulerAngles; // orientation of the pivot point - W3dQuaternionStruct Rotation; // orientation of the pivot point -}; - -struct W3dPivotFixupStruct -{ - float32 TM[4][3]; // this is a direct dump of a MAX 3x4 matrix -}; - - -/******************************************************************************** - - WHA (Westwood Hierarchy Animation) - - A Hierarchy Animation is a set of data defining deltas from the base - position of a hierarchy tree. Translation and Rotation channels can be - attached to any node of the hierarchy tree which the animation is - associated with. - -********************************************************************************/ - -struct W3dAnimHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; - char HierarchyName[W3D_NAME_LEN]; - uint32 NumFrames; - uint32 FrameRate; -}; - -enum -{ - ANIM_CHANNEL_X = 0, - ANIM_CHANNEL_Y, - ANIM_CHANNEL_Z, - ANIM_CHANNEL_XR, - ANIM_CHANNEL_YR, - ANIM_CHANNEL_ZR, - ANIM_CHANNEL_Q -}; - -struct W3dAnimChannelStruct -{ - uint16 FirstFrame; - uint16 LastFrame; - uint16 VectorLen; // length of each vector in this channel - uint16 Flags; // channel type. - uint16 Pivot; // pivot affected by this channel - uint16 pad; - float32 Data[1]; // will be (LastFrame - FirstFrame + 1) * VectorLen long -}; - -enum -{ - BIT_CHANNEL_VIS = 0, // turn meshes on and off depending on anim frame. -}; - -struct W3dBitChannelStruct -{ - uint16 FirstFrame; // all frames outside "First" and "Last" are assumed = DefaultVal - uint16 LastFrame; - uint16 Flags; // channel type. - uint16 Pivot; // pivot affected by this channel - uint8 DefaultVal; // default state when outside valid range. - uint8 Data[1]; // will be (LastFrame - FirstFrame + 1) / 8 long -}; - -/******************************************************************************** - - (HModel - Hiearchy Model) - - A Hierarchy Model is a set of render objects which should be attached to - bones in a hierarchy tree. There can be multiple objects per node - in the tree. Or there may be no objects attached to a particular bone. - -********************************************************************************/ - -struct W3dHModelHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; // Name of this connection set (NULL terminated) - char HierarchyName[W3D_NAME_LEN]; // Name of hierarchy associated with these connections (NULL terminated) - uint16 NumConnections; -}; - -struct W3dHModelAuxDataStruct -{ - uint32 Attributes; - uint32 MeshCount; - uint32 CollisionCount; - uint32 SkinCount; - uint32 ShadowCount; - uint32 FutureCounts[7]; - - float32 LODMin; - float32 LODMax; - uint32 FutureUse[32]; -}; - -struct W3dHModelNodeStruct -{ - // Note: the full name of the Render object is expected to be: . - char RenderObjName[W3D_NAME_LEN]; - uint16 PivotIdx; -}; - - -/******************************************************************************** - - (LODModel - Level-Of-Detail Model) - - An LOD Model is a set of render objects which are interchangeable and - designed to be different resolution versions of the same object. - -********************************************************************************/ - -struct W3dLODModelHeaderStruct -{ - uint32 Version; - char Name[W3D_NAME_LEN]; // Name of this LOD Model - uint16 NumLODs; -}; - -struct W3dLODStruct -{ - char RenderObjName[2*W3D_NAME_LEN]; - float32 LODMin; // "artist" inspired switching distances - float32 LODMax; -}; - - -/******************************************************************************** - - TileMap - - - -********************************************************************************/ - -struct W3dTileMapHeaderStruct -{ - uint32 Version; - uint32 TileInstanceCount; -}; - -#define W3D_TILE_ROTATION_0 0x00 -#define W3D_TILE_ROTATION_90 0x01 -#define W3D_TILE_ROTATION_180 0x02 -#define W3D_TILE_ROTATION_270 0x03 - -struct W3dTileInstanceStruct -{ - char RenderObjName[2*W3D_NAME_LEN]; - uint32 Rotation; - W3dVectorStruct Position; -}; - -#define W3D_TILEMAP_PARTITION_FLAGS_PARTITION 0x0001 -#define W3D_TILEMAP_PARTITION_FLAGS_LEAF 0x0002 -#define W3D_TILEMAP_PARTITION_FLAGS_XNORMAL 0x0004 -#define W3D_TILEMAP_PARTITION_FLAGS_YNORMAL 0x0008 -#define W3D_TILEMAP_PARTITION_FLAGS_ZNORMAL 0x0010 -#define W3D_TILEMAP_PARTITION_FLAGS_FRONT_CHILD 0x0020 -#define W3D_TILEMAP_PARTITION_FLAGS_BACK_CHILD 0x0040 - -struct W3dTileMapPartitionStruct -{ - uint16 Flags; // type of node, type of plane, flags for presence of children. - uint16 InstanceIndex; // if Type==LEAF, this field will store the tile instance index. - float32 Dist; // distance along plane axis. - W3dVectorStruct Min; // min corner of the bounding box - W3dVectorStruct Max; // max corner of the bounding box -}; - - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/w3dquat.cpp b/Generals/Code/Tools/WW3D/pluglib/w3dquat.cpp deleted file mode 100644 index 921e77d377..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/w3dquat.cpp +++ /dev/null @@ -1,709 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3dquat.cpp 29 2/03/00 4:55p Jason_a $ */ -/*********************************************************************************************** - *** Confidential - Westwood Studios *** - *********************************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : QUAT.CPP * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 28, 1997 [GH] * - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * Quaternion::Quaternion -- constructor * - * Quaternion::Set -- Set the quaternion * - * Quaternion::operator= -- Assignment operator * - * Quaternion::Make_Closest -- Use nearest representation to the given quaternion. * - * Trackball -- Computes a "trackball" quaternion given 2D mouse coordinates * - * Axis_To_Quat -- Creates a quaternion given an axis and angle of rotation * - * Slerp -- Spherical Linear interpolation! * - * Build_Quaternion -- Creates a quaternion from a Matrix * - * Build_Matrix -- Creates a Matrix from a Quaternion * - * Normalize -- normalizes a quaternion * - * Quaternion::Quaternion -- constructor * - * Slerp_Setup -- Get ready to call "Cached_Slerp" * - * Cached_Slerp -- Quaternion slerping, optimized with cached values * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "w3dquat.h" -#include "matrix3d.h" -#include "matrix4.h" -#include "wwmath.h" - -#include -//#include -#include -#include -#include - -#define SLERP_EPSILON 0.001 - -static int _nxt[3] = { 1 , 2 , 0 }; - - -// ------------------------------------------------------------ -// local functions -// ------------------------------------------------------------ -static float project_to_sphere(float,float,float); - - -/*********************************************************************************************** - * Quaternion::Quaternion -- constructor * - * * - * constructs a quaternion from the given axis and angle of rotation (in RADIANS of course) * - * * - * INPUT: * - * axis - axis of the rotation * - * angle - rotation angle * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 12/10/97 GTH : Created. * - *=============================================================================================*/ -Quaternion::Quaternion(const Vector3 & axis,float angle) -{ - float s = sinf(angle/2); - float c = cosf(angle/2); - X = s * axis.X; - Y = s * axis.Y; - Z = s * axis.Z; - W = c; -} - - -/*********************************************************************************************** - * Quaternion::Normalize -- Normalize to a unit quaternion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -void Quaternion::Normalize() -{ - float mag = WWMath::Sqrt(X * X + Y * Y + Z * Z + W * W); - - if (0.0f == mag) { - return; - } else { - X /= mag; - Y /= mag; - Z /= mag; - W /= mag; - } -} - -/*********************************************************************************************** - * Quaternion::operator= -- Assignment operator * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/24/1997 GH : Created. * - *=============================================================================================*/ -Quaternion & Quaternion::operator = (const Quaternion & source) -{ - X = source[0]; - Y = source[1]; - Z = source[2]; - W = source[3]; - - return *this; -} - -/*********************************************************************************************** - * Q::Make_Closest -- Use nearest representation to the given quaternion. * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion & Quaternion::Make_Closest(const Quaternion & qto) -{ - float cos_t = qto.X * X + qto.Y * Y + qto.Z * Z + qto.W * W; - - // if we are on opposite hemisphere from qto, negate ourselves - if (cos_t < 0.0) { - X = -X; - Y = -Y; - Z = -Z; - W = -W; - } - - return *this; -} - -/*********************************************************************************************** - * Trackball -- Computes a "trackball" quaternion given 2D mouse coordinates * - * * - * INPUT: * - * x0,y0 - x1,y1 - "normalized" mouse coordinates for the mouse movement * - * sphsize - size of the trackball sphere * - * * - * OUTPUT: * - * a quaternion representing the rotation of a trackball * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Trackball(float x0, float y0, float x1, float y1, float sphsize) -{ - Vector3 a; - Vector3 p1; - Vector3 p2; - Vector3 d; - - float phi,t; - - if ((x0 == x1) && (y0 == y1)) { - return Quaternion(0.0f, 0.0f, 0.0f, 1.0f); // Zero rotation - } - - - // Compute z coordinates for projection of p1 and p2 to - // deformed sphere - p1[0] = x0; - p1[1] = y0; - p1[2] = project_to_sphere(sphsize, x0, y0); - - p2[0] = x1; - p2[1] = y1; - p2[2] = project_to_sphere(sphsize, x1, y1); - - - // Find their cross product - Vector3::Cross_Product(p2,p1,&a); - - // Compute how much to rotate - d = p1 - p2; - t = d.Length() / (2.0f * sphsize); - - // Avoid problems with out of control values - if (t > 1.0f) t = 1.0f; - if (t < -1.0f) t = -1.0f; - phi = 2.0f * asin(t); - - return Axis_To_Quat(a, phi); -} - - -/*********************************************************************************************** - * Axis_To_Quat -- Creates a quaternion given an axis and angle of rotation * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Axis_To_Quat(const Vector3 &a, float phi) -{ - Quaternion q; - Vector3 tmp = a; - - tmp.Normalize(); - q[0] = tmp[0]; - q[1] = tmp[1]; - q[2] = tmp[2]; - - q.Scale(sinf(phi / 2.0f)); - q[3] = cosf(phi / 2.0f); - - return q; -} - -/*********************************************************************************************** - * Slerp -- Spherical Linear interpolation! * - * * - * INPUT: * - * p - start quaternion * - * q - end quaternion * - * alpha - interpolating parameter * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Slerp(const Quaternion & p,const Quaternion & q,float alpha) -{ - float beta; // complementary interploation parameter - float theta; // angle between p and q - float sin_t,cos_t; // sine, cosine of theta - float oo_sin_t; - int qflip; // use flip of q? - - // cos theta = dot product of p and q - cos_t = p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W; - - // if q is on opposite hemisphere from A, use -B instead - if (cos_t < 0.0) { - cos_t = -cos_t; - qflip = true; - } else { - qflip = false; - } - - if (1.0 - cos_t < SLERP_EPSILON) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0 - alpha; - - } else { - - // normal slerp! - theta = acos(cos_t); - sin_t = sinf(theta); - oo_sin_t = 1.0 / sin_t; - beta = sinf(theta - alpha*theta) * oo_sin_t; - alpha = sinf(alpha*theta) * oo_sin_t; - } - - if (qflip) { - alpha = -alpha; - } - - Quaternion res; - res.X = beta*p.X + alpha*q.X; - res.Y = beta*p.Y + alpha*q.Y; - res.Z = beta*p.Z + alpha*q.Z; - res.W = beta*p.W + alpha*q.W; - - return res; -} - - -/*********************************************************************************************** - * Slerp_Setup -- Get ready to call "Cached_Slerp" * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/27/98 GTH : Created. * - *=============================================================================================*/ -void Slerp_Setup(const Quaternion & p,const Quaternion & q,SlerpInfoStruct * slerpinfo) -{ - float cos_t; - - assert(slerpinfo != NULL); - - // cos theta = dot product of p and q - cos_t = p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W; - - // if q is on opposite hemisphere from A, use -B instead - if (cos_t < 0.0) { - cos_t = -cos_t; - slerpinfo->Flip = true; - } else { - slerpinfo->Flip = false; - } - - if (1.0 - cos_t < SLERP_EPSILON) { - - slerpinfo->Linear = true; - slerpinfo->Theta = 0.0f; - slerpinfo->SinT = 0.0f; - - } else { - - slerpinfo->Linear = false; - slerpinfo->Theta = acos(cos_t); - slerpinfo->SinT = sinf(slerpinfo->Theta); - - } -} - -/*********************************************************************************************** - * Cached_Slerp -- Quaternion slerping, optimized with cached values * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 2/27/98 GTH : Created. * - *=============================================================================================*/ -Quaternion Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo) -{ - float beta; // complementary interploation parameter - float oo_sin_t; - - if (slerpinfo->Linear) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0 - alpha; - - } else { - - // normal slerp! - oo_sin_t = 1.0 / slerpinfo->Theta; - beta = sin(slerpinfo->Theta - alpha*slerpinfo->Theta) * oo_sin_t; - alpha = sin(alpha*slerpinfo->Theta) * oo_sin_t; - } - - if (slerpinfo->Flip) { - alpha = -alpha; - } - - Quaternion res; - res.X = beta*p.X + alpha*q.X; - res.Y = beta*p.Y + alpha*q.Y; - res.Z = beta*p.Z + alpha*q.Z; - res.W = beta*p.W + alpha*q.W; - - return res; -} - -void Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo,Quaternion * set_q) -{ - float beta; // complementary interploation parameter - float oo_sin_t; - - if (slerpinfo->Linear) { - - // if q is very close to p, just linearly interpolate - // between the two. - beta = 1.0 - alpha; - - } else { - - // normal slerp! - oo_sin_t = 1.0 / slerpinfo->Theta; - beta = sin(slerpinfo->Theta - alpha*slerpinfo->Theta) * oo_sin_t; - alpha = sin(alpha*slerpinfo->Theta) * oo_sin_t; - } - - if (slerpinfo->Flip) { - alpha = -alpha; - } - - set_q->X = beta*p.X + alpha*q.X; - set_q->Y = beta*p.Y + alpha*q.Y; - set_q->Z = beta*p.Z + alpha*q.Z; - set_q->W = beta*p.W + alpha*q.W; -} - -/*********************************************************************************************** - * Build_Quaternion -- Creates a quaternion from a Matrix * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * Matrix MUST NOT have scaling! * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Quaternion Build_Quaternion(const Matrix3D & mat) -{ - float tr,s; - int i,j,k; - Quaternion q; - - // sum the diagonal of the rotation matrix - tr = mat[0][0] + mat[1][1] + mat[2][2]; - - if (tr > 0.0f) { - - s = sqrt(tr + 1.0); - q[3] = s * 0.5; - s = 0.5 / s; - - q[0] = (mat[2][1] - mat[1][2]) * s; - q[1] = (mat[0][2] - mat[2][0]) * s; - q[2] = (mat[1][0] - mat[0][1]) * s; - - } else { - - i=0; - if (mat[1][1] > mat[0][0]) i = 1; - if (mat[2][2] > mat[i][i]) i = 2; - j = _nxt[i]; - k = _nxt[j]; - - s = sqrt((mat[i][i] - (mat[j][j] + mat[k][k])) + 1.0); - - q[i] = s * 0.5; - if (s != 0.0) { - s = 0.5 / s; - } - - q[3] = ( mat[k][j] - mat[j][k] ) * s; - q[j] = ( mat[j][i] + mat[i][j] ) * s; - q[k] = ( mat[k][i] + mat[i][k] ) * s; - - } - - return q; -} - -Quaternion Build_Quaternion(const Matrix3 & mat) -{ - float tr,s; - int i,j,k; - Quaternion q; - - // sum the diagonal of the rotation matrix - tr = mat[0][0] + mat[1][1] + mat[2][2]; - - if (tr > 0.0) { - - s = sqrt(tr + 1.0); - q[3] = s * 0.5; - s = 0.5 / s; - - q[0] = (mat[2][1] - mat[1][2]) * s; - q[1] = (mat[0][2] - mat[2][0]) * s; - q[2] = (mat[1][0] - mat[0][1]) * s; - - } else { - - i = 0; - if (mat[1][1] > mat[0][0]) i = 1; - if (mat[2][2] > mat[i][i]) i = 2; - - j = _nxt[i]; - k = _nxt[j]; - - s = sqrt( (mat[i][i] - (mat[j][j]+mat[k][k])) + 1.0); - - q[i] = s * 0.5; - - if (s != 0.0) { - s = 0.5/s; - } - - q[3] = ( mat[k][j] - mat[j][k] ) * s; - q[j] = ( mat[j][i] + mat[i][j] ) * s; - q[k] = ( mat[k][i] + mat[i][k] ) * s; - } - - return q; -} - -Quaternion Build_Quaternion(const Matrix4 & mat) -{ - float tr,s; - int i,j,k; - Quaternion q; - - // sum the diagonal of the rotation matrix - tr = mat[0][0] + mat[1][1] + mat[2][2]; - - if (tr > 0.0) { - - s = sqrt(tr + 1.0); - q[3] = s * 0.5; - s = 0.5 / s; - - q[0] = (mat[2][1] - mat[1][2]) * s; - q[1] = (mat[0][2] - mat[2][0]) * s; - q[2] = (mat[1][0] - mat[0][1]) * s; - - } else { - - i = 0; - if (mat[1][1] > mat[0][0]) i = 1; - if (mat[2][2] > mat[i][i]) i = 2; - - j = _nxt[i]; - k = _nxt[j]; - - s = sqrt( (mat[i][i] - (mat[j][j]+mat[k][k])) + 1.0); - - q[i] = s * 0.5; - if (s != 0.0) { - s = 0.5/s; - } - q[3] = ( mat[k][j] - mat[j][k] ) * s; - q[j] = ( mat[j][i] + mat[i][j] ) * s; - q[k] = ( mat[k][i] + mat[i][k] ) * s; - } - - return q; -} - - -/*********************************************************************************************** - * Build_Matrix -- Creates a Matrix from a Quaternion * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 02/28/1997 GH : Created. * - *=============================================================================================*/ -Matrix3 Build_Matrix3(const Quaternion & q) -{ - Matrix3 m; - - m[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - m[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - m[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - m[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - m[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - m[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - m[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - m[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - m[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); - - return m; -} - -Matrix3D Build_Matrix3D(const Quaternion & q) -{ - Matrix3D m; - - // initialize the rotation sub-matrix - m[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - m[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - m[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - m[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - m[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - m[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - m[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - m[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - m[2][2] =(float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); - - // no translation - m[0][3] = m[1][3] = m[2][3] = 0.0f; - - return m; -} - -Matrix4 Build_Matrix4(const Quaternion & q) -{ - Matrix4 m; - - // initialize the rotation sub-matrix - m[0][0] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])); - m[0][1] = (float)(2.0 * (q[0] * q[1] - q[2] * q[3])); - m[0][2] = (float)(2.0 * (q[2] * q[0] + q[1] * q[3])); - - m[1][0] = (float)(2.0 * (q[0] * q[1] + q[2] * q[3])); - m[1][1] = (float)(1.0 - 2.0f * (q[2] * q[2] + q[0] * q[0])); - m[1][2] = (float)(2.0 * (q[1] * q[2] - q[0] * q[3])); - - m[2][0] = (float)(2.0 * (q[2] * q[0] - q[1] * q[3])); - m[2][1] = (float)(2.0 * (q[1] * q[2] + q[0] * q[3])); - m[2][2] = (float)(1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0])); - - // no translation - m[0][3] = m[1][3] = m[2][3] = 0.0f; - - // last row - m[3][0] = m[3][1] = m[3][2] = 0.0f; - m[3][3] = 1.0f; - return m; -} - -void Quaternion::Rotate_X(float theta) -{ - // TODO: optimize this - *this = (*this) * Quaternion(Vector3(1,0,0),theta); -} - -void Quaternion::Rotate_Y(float theta) -{ - // TODO: optimize this - *this = (*this) * Quaternion(Vector3(0,1,0),theta); -} - -void Quaternion::Rotate_Z(float theta) -{ - // TODO: optimize this - *this = (*this) * Quaternion(Vector3(0,0,1),theta); -} - -float project_to_sphere(float r, float x, float y) -{ - const float SQRT2 = 1.41421356f; - float t, z; - float d = WWMath::Sqrt(x * x + y * y); - - if (d < r * (SQRT2/(2.0f))) // inside sphere - z = WWMath::Sqrt(r * r - d * d); - else { // on hyperbola - t = r / SQRT2; - z = t * t / d; - } - - return z; -} - - -void Quaternion::Randomize(void) -{ - X = ((float) (rand() & 0xFFFF)) / 65536.0f; - Y = ((float) (rand() & 0xFFFF)) / 65536.0f; - Z = ((float) (rand() & 0xFFFF)) / 65536.0f; - W = ((float) (rand() & 0xFFFF)) / 65536.0f; - - Normalize(); -} - - diff --git a/Generals/Code/Tools/WW3D/pluglib/w3dquat.h b/Generals/Code/Tools/WW3D/pluglib/w3dquat.h deleted file mode 100644 index 09e7567a15..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/w3dquat.h +++ /dev/null @@ -1,262 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* $Header: /Commando/Code/Tools/max2w3d/w3dquat.h 27 2/03/00 4:55p Jason_a $ */ -/*************************************************************************** - *** Confidential - Westwood Studios *** - *************************************************************************** - * * - * Project Name : Voxel Technology * - * * - * File Name : QUAT.H * - * * - * Programmer : Greg Hjelstrom * - * * - * Start Date : 02/24/97 * - * * - * Last Update : February 24, 1997 [GH] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef QUAT_H -#define QUAT_H - -#include "always.h" -#include "wwmath.h" -#include "WWmatrix3.h" -#include "vector3.h" - - -class Quaternion -{ -private: - -public: - - // X,Y,Z are the imaginary parts of the quaterion - // W is the real part - float X; - float Y; - float Z; - float W; - -public: - - Quaternion(void) {}; - explicit Quaternion(bool init) { if (init) { X = 0.0f; Y = 0.0f; Z = 0.0f; W = 1.0f; } } - explicit Quaternion(float a, float b, float c, float d) { X=a; Y=b; Z=c; W=d; } - explicit Quaternion(const Vector3 & axis,float angle); - Quaternion & operator=(const Quaternion & source); - - void Set(float a = 0.0, float b = 0.0, float c = 0.0, float d = 1.0) { X = a; Y = b; Z = c; W = d; } - void Make_Identity(void) { Set(); }; - void Scale(float s) { X = (float)(s*X); Y = (float)(s*Y); Z = (float)(s*Z); W = (float)(s*W); } - - // Array access - float & operator [](int i) { return (&X)[i]; } - const float & operator [](int i) const { return (&X)[i]; } - - // Unary operators. - // Remember that q and -q represent the same 3D rotation. - Quaternion operator-() const { return(Quaternion(-X,-Y,-Z,-W)); } - Quaternion operator+() const { return *this; } - - // Every 3D rotation can be expressed by two different quaternions, This - // function makes the current quaternion convert itself to the representation - // which is closer on the 4D unit-hypersphere to the given quaternion. - Quaternion & Make_Closest(const Quaternion & qto); - - // Square of the magnitude of the quaternion - float Length2(void) const { return (X*X + Y*Y + Z*Z + W*W); } - - // Magnitude of the quaternion - float Length(void) const { return WWMath::Sqrt(Length2()); } - - // Make the quaternion unit length - void Normalize(void); - - // post-concatenate rotations about the coordinate axes - void Rotate_X(float theta); - void Rotate_Y(float theta); - void Rotate_Z(float theta); - - // initialize this quaternion randomly (creates a random *unit* quaternion) - void Randomize(void); - - // transform (rotate) a vector with this quaternion - Vector3 Rotate_Vector(const Vector3 & v) const; - void Rotate_Vector(const Vector3 & v,Vector3 * set_result) const; - - // verify that none of the members of this quaternion are invalid floats - bool Is_Valid(void) const; -}; - -// Inverse of the quaternion (1/q) -inline Quaternion Inverse(const Quaternion & a) -{ - return Quaternion(-a[0],-a[1],-a[2],a[3]); -} - -// Conjugate of the quaternion -inline Quaternion Conjugate(const Quaternion & a) -{ - return Quaternion(-a[0],-a[1],-a[2],a[3]); -} - -// Add two quaternions -inline Quaternion operator + (const Quaternion & a,const Quaternion & b) -{ - return Quaternion(a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]); -} - -// Subract two quaternions -inline Quaternion operator - (const Quaternion & a,const Quaternion & b) -{ - return Quaternion(a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]); -} - -// Multiply a quaternion by a scalar: -inline Quaternion operator * (float scl, const Quaternion & a) -{ - return Quaternion(scl*a[0], scl*a[1], scl*a[2], scl*a[3]); -} - -// Multiply a quaternion by a scalar -inline Quaternion operator * (const Quaternion & a, float scl) -{ - return scl*a; -} - -// Multiply two quaternions -inline Quaternion operator * (const Quaternion & a,const Quaternion & b) -{ - return Quaternion - ( - a.W*b.X + b.W*a.X + (a.Y*b.Z - b.Y*a.Z), - a.W*b.Y + b.W*a.Y - (a.X*b.Z - b.X*a.Z), - a.W*b.Z + b.W*a.Z + (a.X*b.Y - b.X*a.Y), - a.W * b.W - (a.X * b.X + a.Y * b.Y + a.Z * b.Z) - ); -} - -// Divide two quaternions -inline Quaternion operator / (const Quaternion & a,const Quaternion & b) -{ - return a * Inverse(b); -} - -// Normalized version of the quaternion -inline Quaternion Normalize(const Quaternion & a) -{ - float mag = a.Length(); - if (0.0f == mag) { - return a; - } else { - float oomag = 1.0f / mag; - return Quaternion(a[0] * oomag, a[1] * oomag, a[2] * oomag, a[3] * oomag); - } -} - -// This function computes a quaternion based on an axis -// (defined by the given Vector a) and an angle about -// which to rotate. The angle is expressed in radians. -Quaternion Axis_To_Quat(const Vector3 &a, float angle); - -// Pass the x and y coordinates of the last and current position -// of the mouse, scaled so they are from -1.0 to 1.0 -// The quaternion is the computed as the rotation of a trackball -// between the two points projected onto a sphere. This can -// be used to implement an intuitive viewing control system. -Quaternion Trackball(float x0, float y0, float x1, float y1, float sphsize); - -// Spherical Linear interpolation of quaternions -Quaternion Slerp(const Quaternion & a,const Quaternion & b,float t); - -// Convert a rotation matrix into a quaternion -Quaternion Build_Quaternion(const Matrix3 & matrix); -Quaternion Build_Quaternion(const Matrix3D & matrix); -Quaternion Build_Quaternion(const Matrix4 & matrix); - -// Convert a quaternion into a rotation matrix -Matrix3 Build_Matrix3(const Quaternion & quat); -Matrix3D Build_Matrix3D(const Quaternion & quat); -Matrix4 Build_Matrix4(const Quaternion & quat); - - -// Some values can be cached if you are performing multiple slerps -// between the same two quaternions... -struct SlerpInfoStruct -{ - float SinT; - float Theta; - bool Flip; - bool Linear; -}; - -// Cached slerp implementation -void Slerp_Setup(const Quaternion & p,const Quaternion & q,SlerpInfoStruct * slerpinfo); -void Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo,Quaternion * set_q); -Quaternion Cached_Slerp(const Quaternion & p,const Quaternion & q,float alpha,SlerpInfoStruct * slerpinfo); - -inline Vector3 Quaternion::Rotate_Vector(const Vector3 & v) const -{ - float x = W*v.X + (Y*v.Z - v.Y*Z); - float y = W*v.Y - (X*v.Z - v.X*Z); - float z = W*v.Z + (X*v.Y - v.X*Y); - float w = -(X*v.X + Y*v.Y + Z*v.Z); - - return Vector3 - ( - w*(-X) + W*x + (y*(-Z) - (-Y)*z), - w*(-Y) + W*y - (x*(-Z) - (-X)*z), - w*(-Z) + W*z + (x*(-Y) - (-X)*y) - ); -} - -inline void Quaternion::Rotate_Vector(const Vector3 & v,Vector3 * result) const -{ - assert(result != NULL); - - float x = W*v.X + (Y*v.Z - v.Y*Z); - float y = W*v.Y - (X*v.Z - v.X*Z); - float z = W*v.Z + (X*v.Y - v.X*Y); - float w = -(X*v.X + Y*v.Y + Z*v.Z); - - result->X = w*(-X) + W*x + (y*(-Z) - (-Y)*z); - result->Y = w*(-Y) + W*y - (x*(-Z) - (-X)*z); - result->Z = w*(-Z) + W*z + (x*(-Y) - (-X)*y); -} - -inline bool Quaternion::Is_Valid(void) const -{ - return ( WWMath::Is_Valid_Float(X) && - WWMath::Is_Valid_Float(Y) && - WWMath::Is_Valid_Float(Z) && - WWMath::Is_Valid_Float(W) ); -} - -#endif /* QUAT_H */ - - - diff --git a/Generals/Code/Tools/WW3D/pluglib/watcom.h b/Generals/Code/Tools/WW3D/pluglib/watcom.h deleted file mode 100644 index 58e8cd07ff..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/watcom.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /G/wwlib/WATCOM.H $* - * * - * $Author:: Eric_c $* - * * - * $Modtime:: 4/02/99 11:56a $* - * * - * $Revision:: 3 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#if !defined(WATCOM_H) && defined(__WATCOMC__) -#define WATCOM_H - - -/********************************************************************** -** The "bool" integral type was defined by the C++ comittee in -** November of '94. Until the compiler supports this, use the following -** definition. -*/ -#include "bool.h" - -// Turn all warnings into errors. -#pragma warning * 0 - -// Disables warning when "sizeof" is used on an object with virtual functions. -#pragma warning 549 9 - -// Disable the "Integral value may be truncated during assignment or initialization". -#pragma warning 389 9 - -// Allow constructing a temporary to be used as a parameter. -#pragma warning 604 9 - -// Disable the construct resolved as an expression warning. -#pragma warning 595 9 - -// Disable the strange "construct resolved as a declaration/type" warning. -#pragma warning 594 9 - -// Disable the "pre-compiled header file cannot be used" warning. -#pragma warning 698 9 - -// Disable the "temporary object used to initialize a non-constant reference" warning. -#pragma warning 665 9 - -// Disable the "pointer or reference truncated by cast. Cast is supposed to REMOVE warnings, not create them. -#pragma warning 579 9 - -// Disable the warning that suggests a null destructor be placed in class definition. -#pragma warning 656 9 - -// Disable the warning about moving empty constructors/destructors to the class declaration. -#pragma warning 657 9 - -// No virtual destructor is not an error in C&C. -#pragma warning 004 9 - -// Integral constant will be truncated warning is usually ok when dealing with bitfields. -#pragma warning 388 9 - -// Turns off unreferenced function parameter warning. -//#pragma off(unreferenced) - -/* -** The "bool" integral type was defined by the C++ comittee in -** November of '94. Until the compiler supports this, use the following -** definition. -*/ -#include "bool.h" - -#if !defined(__BORLANDC__) -#define M_E 2.71828182845904523536 -#define M_LOG2E 1.44269504088896340736 -#define M_LOG10E 0.434294481903251827651 -#define M_LN2 0.693147180559945309417 -#define M_LN10 2.30258509299404568402 -#define M_PI 3.14159265358979323846 -#define M_PI_2 1.57079632679489661923 -#define M_PI_4 0.785398163397448309616 -#define M_1_PI 0.318309886183790671538 -#define M_2_PI 0.636619772367581343076 -#define M_1_SQRTPI 0.564189583547756286948 -#define M_2_SQRTPI 1.12837916709551257390 -#define M_SQRT2 1.41421356237309504880 -#define M_SQRT_2 0.707106781186547524401 -#endif - - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/win.h b/Generals/Code/Tools/WW3D/pluglib/win.h deleted file mode 100644 index b8bf81f40e..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/win.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/wwlib/win.h $* - * * - * $Author:: Denzil_l $* - * * - * $Modtime:: 6/26/01 1:59p $* - * * - * $Revision:: 10 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef WIN_H -#define WIN_H - -/* -** This header file includes the Windows headers. If there are any special pragmas that need -** to occur around this process, they are performed here. Typically, certain warnings will need -** to be disabled since the Windows headers are repleat with illegal and dangerous constructs. -** -** Within the windows headers themselves, Microsoft has disabled the warnings 4290, 4514, -** 4069, 4200, 4237, 4103, 4001, 4035, 4164. Makes you wonder, eh? -*/ - -// When including windows, lets just bump the warning level back to 3... -#if (_MSC_VER >= 1200) -#pragma warning(push, 3) -#endif - -// this define should also be in the DSP just in case someone includes windows stuff directly -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#include -//#include -//#include -//#include -//#include - -#if (_MSC_VER >= 1200) -#pragma warning(pop) -#endif - -#ifdef _WINDOWS -extern HINSTANCE ProgramInstance; -extern HWND MainWindow; -extern bool GameInFocus; - -#ifdef _DEBUG - -void __cdecl Print_Win32Error(unsigned long win32Error); - -#else // _DEBUG - -#define Print_Win32Error - -#endif // _DEBUG - -#else // _WINDOWS -#include -#endif // _WINDOWS - -#endif // WIN_H diff --git a/Generals/Code/Tools/WW3D/pluglib/wwfile.h b/Generals/Code/Tools/WW3D/pluglib/wwfile.h deleted file mode 100644 index 8356f4315d..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/wwfile.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Commando/Code/wwlib/wwfile.h $* - * * - * $Author:: Jani_p $* - * * - * $Modtime:: 5/04/01 7:43p $* - * * - * $Revision:: 8 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef WWFILE_Hx -#define WWFILE_Hx - -#ifdef _UNIX -#include "osdep.h" -#endif - -#define YEAR(dt) (((dt & 0xFE000000) >> (9 + 16)) + 1980) -#define MONTH(dt) ((dt & 0x01E00000) >> (5 + 16)) -#define DAY(dt) ((dt & 0x001F0000) >> (0 + 16)) -#define HOUR(dt) ((dt & 0x0000F800) >> 11) -#define MINUTE(dt) ((dt & 0x000007E0) >> 5) -#define SECOND(dt) ((dt & 0x0000001F) << 1) - -#ifndef SEEK_SET -#define SEEK_SET 0 // Seek from start of file. -#define SEEK_CUR 1 // Seek relative from current location. -#define SEEK_END 2 // Seek from end of file. -#endif - -#ifndef NULL - #define NULL 0 -#endif - - -class FileClass -{ - public: - - enum - { - READ = 1, - WRITE = 2, - PRINTF_BUFFER_SIZE = 1024 - }; - - virtual ~FileClass(void) {}; - virtual char const * File_Name(void) const = 0; - virtual char const * Set_Name(char const *filename) = 0; - virtual int Create(void) = 0; - virtual int Delete(void) = 0; - virtual bool Is_Available(int forced=false) = 0; - virtual bool Is_Open(void) const = 0; - virtual int Open(char const *filename, int rights=READ) = 0; - virtual int Open(int rights=READ) = 0; - virtual int Read(void *buffer, int size) = 0; - virtual int Seek(int pos, int dir=SEEK_CUR) = 0; - virtual int Tell(void) { return Seek(0); } - virtual int Size(void) = 0; - virtual int Write(void const *buffer, int size) = 0; - virtual void Close(void) = 0; - virtual unsigned long Get_Date_Time(void) {return(0);} - virtual bool Set_Date_Time(unsigned long ) {return(false);} - virtual void Error(int error, int canretry = false, char const * filename=NULL) = 0; - virtual void * Get_File_Handle(void) { return reinterpret_cast(-1); } - - operator char const * () - { - return File_Name(); - } - - // this form uses a stack buffer of PRINTF_BUFFER_SIZE - int Printf(char *str, ...); - - // this form uses the supplied buffer if PRINTF_BUFFER_SIZE is expected to be too small. - int Printf(char *buffer, int bufferSize, char *str, ...); - - // this form uses the stack buffer but will prepend any output with the indicated number of tab characters '\t' - int Printf_Indented(unsigned depth, char *str, ...); - -}; - -#endif diff --git a/Generals/Code/Tools/WW3D/pluglib/wwmath.cpp b/Generals/Code/Tools/WW3D/pluglib/wwmath.cpp deleted file mode 100644 index 4b7cc68826..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/wwmath.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/wwmath.cpp $* - * * - * Author:: Eric_c * - * * - * $Modtime:: 3/18/99 10:39a $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#include "wwmath.h" -#include - -/* -** -*/ -float WWMath::Random_Float(void) -{ - return ((float)(rand() & 0xFFF)) / (float)(0xFFF); -} diff --git a/Generals/Code/Tools/WW3D/pluglib/wwmath.h b/Generals/Code/Tools/WW3D/pluglib/wwmath.h deleted file mode 100644 index 0966d29a7e..0000000000 --- a/Generals/Code/Tools/WW3D/pluglib/wwmath.h +++ /dev/null @@ -1,257 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : WWMath * - * * - * $Archive:: /Commando/Code/wwmath/wwmath.h $* - * * - * Author:: Greg Hjelstrom * - * * - * $Modtime:: 3/16/00 8:28p $* - * * - * $Revision:: 40 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WWMATH_H -#define WWMATH_H - -#include "always.h" -#include -#include - -/* -** Some global constants. -*/ -#define WWMATH_EPSILON 0.0001f -#define WWMATH_EPSILON2 WWMATH_EPSILON * WWMATH_EPSILON -#define WWMATH_PI 3.141592654f -#define WWMATH_FLOAT_MAX (FLT_MAX) -#define WWMATH_SQRT2 1.414213562f -#define WWMATH_SQRT3 1.732050808f -#define WWMATH_OOSQRT2 0.707106781f -#define WWMATH_OOSQRT3 0.577350269f - - -/* -** Macros to convert between degrees and radians -*/ -#ifndef RAD_TO_DEG -#define RAD_TO_DEG(x) (((double)x)*180.0/WWMATH_PI) -#endif - -#ifndef DEG_TO_RAD -#define DEG_TO_RAD(x) (((double)x)*WWMATH_PI/180.0) -#endif - -#ifndef RAD_TO_DEGF -#define RAD_TO_DEGF(x) (((float)x)*180.0f/WWMATH_PI) -#endif - -#ifndef DEG_TO_RADF -#define DEG_TO_RADF(x) (((float)x)*WWMATH_PI/180.0f) -#endif - - - -/* -** Some simple math functions which work on the built-in types. -** Include the various other header files in the WWMATH library -** in order to get matrices, quaternions, etc. -*/ -class WWMath -{ -public: - -static float Fabs(float val) { return (float)fabs(val); } -static float Sqrt(float val) { return (float)sqrt(val); } -static float Inv_Sqrt(float val) { return 1.0f / (float)sqrt(val); } -static float Sign(float val); -static float Floor(float val) { return (float)floor(val); } -static bool Fast_Is_Float_Positive(const float & val); - -static float Random_Float(void); -static float Random_Float(float min,float max); -static float Clamp(float val, float min = 0.0f, float max = 1.0f); -static double Clamp(double val, double min = 0.0f, double max = 1.0f); -static float Wrap(float val, float min = 0.0f, float max = 1.0f); -static double Wrap(double val, double min = 0.0f, double max = 1.0f); -static float Min(float a, float b); -static float Max(float a, float b); - -static float Lerp(float a, float b, float lerp ); -static double Lerp(double a, double b, float lerp ); - -static long Float_To_Long(float f); -static long Float_To_Long(double f); - -static unsigned char Unit_Float_To_Byte(float f) { return (unsigned char)(f*255.0f); } -static float Byte_To_Unit_Float(unsigned char byte) { return ((float)byte) / 255.0f; } - -static bool Is_Valid_Float(float x); -static bool Is_Valid_Double(double x); - -}; - -inline float WWMath::Sign(float val) -{ - if (val > 0.0f) { - return +1.0f; - } - if (val < 0.0f) { - return -1.0f; - } - return 0.0f; -} - -inline bool WWMath::Fast_Is_Float_Positive(const float & val) -{ - return !((*(int *)(&val)) & 0x80000000); -} - -inline float WWMath::Random_Float(float min,float max) -{ - return Random_Float() * (max-min) + min; -} - -inline float WWMath::Clamp(float val, float min /*= 0.0f*/, float max /*= 1.0f*/) -{ - if(val < min) return min; - if(val > max) return max; - return val; -} - -inline double WWMath::Clamp(double val, double min /*= 0.0f*/, double max /*= 1.0f*/) -{ - if(val < min) return min; - if(val > max) return max; - return val; -} - -inline float WWMath::Wrap(float val, float min /*= 0.0f*/, float max /*= 1.0f*/) -{ - // Implemented as an if rather than a while, to long loops - if ( val >= max ) val -= (max-min); - if ( val < min ) val += (max-min); - - if ( val < min ) { - val = min; - } - if ( val > max ) { - val = max; - } - return val; -} - -inline double WWMath::Wrap(double val, double min /*= 0.0f*/, double max /*= 1.0f*/) -{ - // Implemented as an if rather than a while, to long loops - if ( val >= max ) val -= (max-min); - if ( val < min ) val += (max-min); - if ( val < min ) { - val = min; - } - if ( val > max ) { - val = max; - } - return val; -} - -inline float WWMath::Min(float a, float b) -{ - if (ab) return a; - return b; -} - -inline float WWMath::Lerp(float a, float b, float lerp ) -{ - return (a + (b - a)*lerp); -} - -inline double WWMath::Lerp(double a, double b, float lerp ) -{ - return (a + (b - a)*lerp); -} - - -inline long WWMath::Float_To_Long (float f) -{ -#if defined(_MSC_VER) && defined(_M_IX86) - long retval; - __asm fld dword ptr [f] - __asm fistp dword ptr [retval] - return retval; -#else - return (long) f; -#endif -} - -inline long WWMath::Float_To_Long (double f) -{ -#if defined(_MSC_VER) && defined(_M_IX86) - long retval; - __asm fld qword ptr [f] - __asm fistp dword ptr [retval] - return retval; -#else - return (long) f; -#endif -} - -inline bool WWMath::Is_Valid_Float(float x) -{ - unsigned long * plong = (unsigned long *)(&x); - unsigned long exponent = ((*plong) & 0x7F800000) >> (32-9); - - // if exponent is 0xFF, this is a NAN - if (exponent == 0xFF) { - return false; - } - return true; -} - -inline bool WWMath::Is_Valid_Double(double x) -{ - unsigned long * plong = (unsigned long *)(&x) + 1; - unsigned long exponent = ((*plong) & 0x7FF00000) >> (32-12); - - // if exponent is 0x7FF, this is a NAN - if (exponent == 0x7FF) { - return false; - } - return true; -} - -#endif diff --git a/Generals/Code/Tools/WorldBuilder/CMakeLists.txt b/Generals/Code/Tools/WorldBuilder/CMakeLists.txt index da0f3cda1c..42bd24e67e 100644 --- a/Generals/Code/Tools/WorldBuilder/CMakeLists.txt +++ b/Generals/Code/Tools/WorldBuilder/CMakeLists.txt @@ -1,4 +1,3 @@ -# Set source files set(WORLDBUILDER_SRC "src/addplayerdialog.cpp" "src/AutoEdgeOutTool.cpp" @@ -195,11 +194,10 @@ set(WORLDBUILDER_SRC "include/WorldBuilderView.h" ) -# Targets to build. add_executable(g_worldbuilder WIN32) target_include_directories(g_worldbuilder PRIVATE - . + ${CMAKE_CURRENT_SOURCE_DIR} include res ) diff --git a/Generals/Code/Tools/WorldBuilder/include/MainFrm.h b/Generals/Code/Tools/WorldBuilder/include/MainFrm.h index 7fdd512245..27d34951ff 100644 --- a/Generals/Code/Tools/WorldBuilder/include/MainFrm.h +++ b/Generals/Code/Tools/WorldBuilder/include/MainFrm.h @@ -79,7 +79,7 @@ class CMainFrame : public CFrameWnd // Implementation public: virtual ~CMainFrame(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/Generals/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h b/Generals/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h index 8844a16974..4a58b7a8f2 100644 --- a/Generals/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h +++ b/Generals/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h @@ -170,7 +170,7 @@ class CWorldBuilderDoc : public CDocument // Implementation public: virtual ~CWorldBuilderDoc(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/Generals/Code/Tools/WorldBuilder/include/WorldBuilderView.h b/Generals/Code/Tools/WorldBuilder/include/WorldBuilderView.h index 066d1b9d37..1abb3d820b 100644 --- a/Generals/Code/Tools/WorldBuilder/include/WorldBuilderView.h +++ b/Generals/Code/Tools/WorldBuilder/include/WorldBuilderView.h @@ -60,7 +60,7 @@ class CWorldBuilderView : public WbView // Implementation public: virtual ~CWorldBuilderView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/Generals/Code/Tools/WorldBuilder/include/wbview.h b/Generals/Code/Tools/WorldBuilder/include/wbview.h index 981c7001d8..9ff305cc97 100644 --- a/Generals/Code/Tools/WorldBuilder/include/wbview.h +++ b/Generals/Code/Tools/WorldBuilder/include/wbview.h @@ -160,7 +160,7 @@ class WbView : public CView // Implementation protected: virtual ~WbView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/Generals/Code/Tools/WorldBuilder/include/wbview3d.h b/Generals/Code/Tools/WorldBuilder/include/wbview3d.h index 6b6eaa9652..63006b13ce 100644 --- a/Generals/Code/Tools/WorldBuilder/include/wbview3d.h +++ b/Generals/Code/Tools/WorldBuilder/include/wbview3d.h @@ -85,7 +85,7 @@ class WbView3d : public WbView, public DX8_CleanupHook // Implementation protected: virtual ~WbView3d(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/Generals/Code/Tools/WorldBuilder/res/WorldBuilder.rc b/Generals/Code/Tools/WorldBuilder/res/WorldBuilder.rc index 0011c40f90..a707c881b4 100644 --- a/Generals/Code/Tools/WorldBuilder/res/WorldBuilder.rc +++ b/Generals/Code/Tools/WorldBuilder/res/WorldBuilder.rc @@ -1751,7 +1751,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 0,8,0,0 PRODUCTVERSION 0,8,0,0 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/Generals/Code/Tools/WorldBuilder/src/DrawObject.cpp b/Generals/Code/Tools/WorldBuilder/src/DrawObject.cpp index 6378070e64..ee68ccb790 100644 --- a/Generals/Code/Tools/WorldBuilder/src/DrawObject.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/DrawObject.cpp @@ -55,7 +55,7 @@ #include "Common/WellKnownKeys.h" #include "Common/BorderColors.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define NO_INTENSE_DEBUG 1 #endif diff --git a/Generals/Code/Tools/WorldBuilder/src/EditAction.cpp b/Generals/Code/Tools/WorldBuilder/src/EditAction.cpp index a6ee38b8ea..a594ca4b71 100644 --- a/Generals/Code/Tools/WorldBuilder/src/EditAction.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/EditAction.cpp @@ -25,7 +25,7 @@ #include "EditParameter.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/Tools/WorldBuilder/src/EditParameter.cpp b/Generals/Code/Tools/WorldBuilder/src/EditParameter.cpp index df123f92b8..a7c1f1237e 100644 --- a/Generals/Code/Tools/WorldBuilder/src/EditParameter.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/EditParameter.cpp @@ -64,7 +64,7 @@ #include "W3DDevice/GameClient/W3DGameFont.h" #include "W3DDevice/GameClient/HeightMap.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/Tools/WorldBuilder/src/EulaDialog.cpp b/Generals/Code/Tools/WorldBuilder/src/EulaDialog.cpp index 461f5690fe..68a796175f 100644 --- a/Generals/Code/Tools/WorldBuilder/src/EulaDialog.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/EulaDialog.cpp @@ -23,7 +23,7 @@ #include "WorldBuilder.h" #include "euladialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/Generals/Code/Tools/WorldBuilder/src/MainFrm.cpp b/Generals/Code/Tools/WorldBuilder/src/MainFrm.cpp index 279b3218d2..86450a5fc2 100644 --- a/Generals/Code/Tools/WorldBuilder/src/MainFrm.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/MainFrm.cpp @@ -414,7 +414,7 @@ void CMainFrame::OnEditGloballightoptions() ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); @@ -425,7 +425,7 @@ void CMainFrame::Dump(CDumpContext& dc) const CFrameWnd::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers diff --git a/Generals/Code/Tools/WorldBuilder/src/MapPreview.cpp b/Generals/Code/Tools/WorldBuilder/src/MapPreview.cpp index 52b48c76e5..1ce0db6cb0 100644 --- a/Generals/Code/Tools/WorldBuilder/src/MapPreview.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/MapPreview.cpp @@ -411,13 +411,15 @@ void MapPreview::buildMapPreviewTexture( CString tgaName ) } // end for x } // end for y - Targa tga; - tga.Header.Width = MAP_PREVIEW_WIDTH; - tga.Header.Height = MAP_PREVIEW_HEIGHT; - tga.Header.PixelDepth = 32; - tga.Header.ImageType = TGA_TRUECOLOR; - tga.SetImage((char *)m_pixelBuffer); - tga.Save(tgaName,TGAF_IMAGE, FALSE); + { + Targa tga; + tga.Header.Width = MAP_PREVIEW_WIDTH; + tga.Header.Height = MAP_PREVIEW_HEIGHT; + tga.Header.PixelDepth = 32; + tga.Header.ImageType = TGA_TRUECOLOR; + tga.SetImage((char *)m_pixelBuffer); + tga.Save(tgaName,TGAF_IMAGE, FALSE); + } } // end buildTerrainTexture diff --git a/Generals/Code/Tools/WorldBuilder/src/ObjectTool.cpp b/Generals/Code/Tools/WorldBuilder/src/ObjectTool.cpp index d4801a1be7..fcff295df2 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ObjectTool.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ObjectTool.cpp @@ -70,7 +70,7 @@ Real ObjectTool::calcAngle(Coord3D downPt, Coord3D curPt, WbView* pView) if (dx<0) angle = PI-angle; } if (angle > PI) angle -= 2*PI; -#ifdef _DEBUG +#ifdef RTS_DEBUG CString buf; buf.Format("Angle %f rad, %d degrees\n", angle, (int)(angle*180/PI)); ::OutputDebugString(buf); diff --git a/Generals/Code/Tools/WorldBuilder/src/OpenMap.cpp b/Generals/Code/Tools/WorldBuilder/src/OpenMap.cpp index c689c665d7..fc8e8f6b85 100644 --- a/Generals/Code/Tools/WorldBuilder/src/OpenMap.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/OpenMap.cpp @@ -33,7 +33,7 @@ OpenMap::OpenMap(TOpenMapInfo *pInfo, CWnd* pParent /*=NULL*/) m_pInfo(pInfo) { m_pInfo->browse = false; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_usingSystemDir = ::AfxGetApp()->GetProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", TRUE); #else m_usingSystemDir = FALSE; @@ -110,7 +110,7 @@ void OpenMap::OnOK() void OpenMap::populateMapListbox( Bool systemMaps ) { m_usingSystemDir = systemMaps; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ::AfxGetApp()->WriteProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", m_usingSystemDir); #endif @@ -190,7 +190,7 @@ BOOL OpenMap::OnInitDialog() if (pUserMaps != NULL) pUserMaps->SetCheck( !m_usingSystemDir ); -#if !defined(_DEBUG) && !defined(_INTERNAL) +#if !defined(RTS_DEBUG) && !defined(RTS_INTERNAL) if (pSystemMaps) pSystemMaps->ShowWindow( FALSE ); if (pUserMaps) diff --git a/Generals/Code/Tools/WorldBuilder/src/SaveMap.cpp b/Generals/Code/Tools/WorldBuilder/src/SaveMap.cpp index f0e2cb9a4a..4618ee3604 100644 --- a/Generals/Code/Tools/WorldBuilder/src/SaveMap.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/SaveMap.cpp @@ -32,7 +32,7 @@ SaveMap::SaveMap(TSaveMapInfo *pInfo, CWnd* pParent /*=NULL*/) : CDialog(SaveMap::IDD, pParent), m_pInfo(pInfo) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_pInfo->usingSystemDir = m_usingSystemDir = ::AfxGetApp()->GetProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", TRUE); #else m_pInfo->usingSystemDir = m_usingSystemDir = FALSE; @@ -121,7 +121,7 @@ void SaveMap::OnBrowse() void SaveMap::populateMapListbox( Bool systemMaps ) { m_pInfo->usingSystemDir = m_usingSystemDir = systemMaps; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ::AfxGetApp()->WriteProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", m_usingSystemDir); #endif @@ -225,7 +225,7 @@ BOOL SaveMap::OnInitDialog() if (pUserMaps != NULL) pUserMaps->SetCheck( !m_usingSystemDir ); -#if !defined(_DEBUG) && !defined(_INTERNAL) +#if !defined(RTS_DEBUG) && !defined(RTS_INTERNAL) if (pSystemMaps) pSystemMaps->ShowWindow( FALSE ); if (pUserMaps) diff --git a/Generals/Code/Tools/WorldBuilder/src/ScriptProperties.cpp b/Generals/Code/Tools/WorldBuilder/src/ScriptProperties.cpp index 23311ca8b0..f99b1e059d 100644 --- a/Generals/Code/Tools/WorldBuilder/src/ScriptProperties.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/ScriptProperties.cpp @@ -24,7 +24,7 @@ #include "ScriptProperties.h" #include "GameLogic/Scripts.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index 5cbf831f06..bb898a6cce 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -388,7 +388,7 @@ void WorldHeightMapEdit::loadBaseImages(void) { /// @todo - take this out when we are done evaluating terrain textures. -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) loadDirectoryOfImages("..\\TestArt\\TestTerrain"); #endif diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index 0fbafd9098..7024305a4b 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -83,7 +83,7 @@ #include "Win32Device/Common/Win32LocalFileSystem.h" #include "Win32Device/Common/Win32BIGFileSystem.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -282,11 +282,11 @@ BOOL CWorldBuilderApp::InitInstance() // start the log DEBUG_INIT(DEBUG_FLAGS_DEFAULT); DEBUG_LOG(("starting Worldbuilder.\n")); -#ifdef _INTERNAL - DEBUG_LOG(("_INTERNAL defined.\n")); +#ifdef RTS_INTERNAL + DEBUG_LOG(("RTS_INTERNAL defined.\n")); #endif -#ifdef _DEBUG - DEBUG_LOG(("_DEBUG defined.\n")); +#ifdef RTS_DEBUG + DEBUG_LOG(("RTS_DEBUG defined.\n")); #endif initMemoryManager(); #ifdef MEMORYPOOL_CHECKPOINTING @@ -339,7 +339,7 @@ BOOL CWorldBuilderApp::InitInstance() initSubsystem(TheWritableGlobalData, new GlobalData(), "Data\\INI\\Default\\GameData.ini", "Data\\INI\\GameData.ini"); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ini.load( AsciiString( "Data\\INI\\GameDataDebug.ini" ), INI_LOAD_MULTIFILE, NULL ); #endif @@ -411,7 +411,7 @@ BOOL CWorldBuilderApp::InitInstance() DEBUG_ASSERTCRASH(!TheGlobalData->m_useHalfHeightMap, ("TheGlobalData->m_useHalfHeightMap : Don't use this setting in WB.")); TheWritableGlobalData->m_useHalfHeightMap = false; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // WB never uses the shroud. TheWritableGlobalData->m_shroudOn = FALSE; #endif diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp index 0a51895a6e..6c6472486c 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp @@ -849,7 +849,7 @@ void CWorldBuilderDoc::autoSave(void) ///////////////////////////////////////////////////////////////////////////// // CWorldBuilderDoc diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWorldBuilderDoc::AssertValid() const { CDocument::AssertValid(); @@ -859,7 +859,7 @@ void CWorldBuilderDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWorldBuilderDoc commands diff --git a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp index 30583f40b8..be53dd5c05 100644 --- a/Generals/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp @@ -137,7 +137,7 @@ void CWorldBuilderView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) ///////////////////////////////////////////////////////////////////////////// // CWorldBuilderView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWorldBuilderView::AssertValid() const { WbView::AssertValid(); @@ -148,7 +148,7 @@ void CWorldBuilderView::Dump(CDumpContext& dc) const WbView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG /** Set the cell size, and invalidate. */ void CWorldBuilderView::setCellSize(Int cellSize) diff --git a/Generals/Code/Tools/WorldBuilder/src/wbview.cpp b/Generals/Code/Tools/WorldBuilder/src/wbview.cpp index 72d39bb4cd..bf6b06db56 100644 --- a/Generals/Code/Tools/WorldBuilder/src/wbview.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/wbview.cpp @@ -149,7 +149,7 @@ void WbView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // WbView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void WbView::AssertValid() const { CView::AssertValid(); @@ -159,7 +159,7 @@ void WbView::Dump(CDumpContext& dc) const { CView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // WbView message handlers diff --git a/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp b/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp index fbe4e0452a..b29b202d74 100644 --- a/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp +++ b/Generals/Code/Tools/WorldBuilder/src/wbview3d.cpp @@ -95,7 +95,7 @@ #include -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -138,7 +138,7 @@ static void Debug_Refs(void); // ---------------------------------------------------------------------------- static void WWDebug_Message_Callback(DebugType type, const char * message) { -#ifdef _DEBUG +#ifdef RTS_DEBUG ::OutputDebugString(message); #endif } @@ -146,7 +146,7 @@ static void WWDebug_Message_Callback(DebugType type, const char * message) // ---------------------------------------------------------------------------- static void WWAssert_Callback(const char * message) { -#ifdef _DEBUG +#ifdef RTS_DEBUG ::OutputDebugString(message); ::DebugBreak(); #endif @@ -176,7 +176,7 @@ class PlaceholderView : public View virtual Int iterateDrawablesInRegion( IRegion2D *screenRegion, Bool (*callback)( Drawable *draw, void *userData ), void *userData ) {return 0;}; - virtual Bool worldToScreen( const Coord3D *w, ICoord2D *s ) { return FALSE; }; ///< Transform world coordinate "w" into screen coordinate "s" + virtual WorldToScreenReturn worldToScreenTriReturn( const Coord3D *w, ICoord2D *s ) { return WTS_INVALID; }; ///< Transform world coordinate "w" into screen coordinate "s" virtual void screenToWorld( const ICoord2D *s, Coord3D *w ) {}; ///< Transform screen coordinate "s" into world coordinate "w" virtual void screenToTerrain( const ICoord2D *screen, Coord3D *world ) {}; ///< transform screen coord to a point on the 3D terrain virtual void screenToWorldAtZ( const ICoord2D *s, Coord3D *w, Real z ) {}; ///< transform screen point to world point at the specified world Z value @@ -2128,7 +2128,7 @@ void WbView3d::OnDraw(CDC* pDC) // ---------------------------------------------------------------------------- // WbView3d diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG // ---------------------------------------------------------------------------- void WbView3d::AssertValid() const { @@ -2140,7 +2140,7 @@ void WbView3d::Dump(CDumpContext& dc) const { WbView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG // ---------------------------------------------------------------------------- void WbView3d::initWW3D() @@ -2207,7 +2207,6 @@ void WbView3d::initWW3D() } WW3D::Enable_Static_Sort_Lists(true); - WW3D::Set_Texture_Compression_Mode(WW3D::TEXTURE_COMPRESSION_ENABLE); WW3D::Set_Thumbnail_Enabled(false); WW3D::Set_Screen_UV_Bias( TRUE ); ///< this makes text look good :) diff --git a/Generals/Code/Tools/buildVersionUpdate/CMakeLists.txt b/Generals/Code/Tools/buildVersionUpdate/CMakeLists.txt deleted file mode 100644 index 5ea708e93b..0000000000 --- a/Generals/Code/Tools/buildVersionUpdate/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -set(BUILDVERSIONUPDATE_SRC - "buildVersionUpdate.cpp" -) - -add_executable(g_buildversionupdate WIN32) -set_target_properties(g_buildversionupdate PROPERTIES OUTPUT_NAME buildversionupdate) - -target_sources(g_buildversionupdate PRIVATE ${BUILDVERSIONUPDATE_SRC}) - -target_link_libraries(g_buildversionupdate PRIVATE - core_config -) diff --git a/Generals/Code/Tools/buildVersionUpdate/buildVersionUpdate.cpp b/Generals/Code/Tools/buildVersionUpdate/buildVersionUpdate.cpp deleted file mode 100644 index 2ec1ee8815..0000000000 --- a/Generals/Code/Tools/buildVersionUpdate/buildVersionUpdate.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: buildVersionUpdate.cpp ////////////////////////////////////////////////////// -// Generals version number class updater -// Author: Matthew D. Campbell, November 2001 - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#define WIN32_LEAN_AND_MEAN // only bare bones windows stuff wanted -#include -#include -#include -#include -#include - -// Local defines -#define VERSION_MAJOR "VERSION_MAJOR" -#define VERSION_MINOR "VERSION_MINOR" -#define VERSION_BUILDNUM "VERSION_BUILDNUM" -#define VERSION_STRING "VERSION_STRING" -#define FORMAT "#define " VERSION_STRING " \"%d.%d.%d\"\n" -#define COMMENTS "// Do not modify this file by hand. Auto-created and\n// Updated by buildVersionUpdate.\n" -#define NUMFMT "#define %s %d\n" -#define NUMFMT_MINOR "#define %s %d ///< This effects the replay version number.\n" - -static void writeVersion(char *file, int major, int minor, int build) -{ - FILE *filePtr = fopen(file, "w"); - // Clobber the file. Hey, this is a simple program. - if (file) - { - if (filePtr) - { - fprintf(filePtr, COMMENTS); - fprintf(filePtr, FORMAT, major, minor, build); - fprintf(filePtr, NUMFMT, VERSION_MAJOR, major); - fprintf(filePtr, NUMFMT_MINOR, VERSION_MINOR, minor); - fprintf(filePtr, NUMFMT, VERSION_BUILDNUM, build); - fclose(filePtr); - } - else - { - printf("Cannot write file\n"); - } - } - else - { - printf("No file to write\n"); - } -} - -static void usage(char *progname) -{ - if (progname) - { - printf ("Usage: %s versionfile.h", progname); - } -} - - -// strtrim ==================================================================== -/** Trim leading and trailing whitespace from a character string (in place). */ -//============================================================================= -static char* strtrim(char* buffer) -{ - if (buffer != NULL) { - // Strip leading white space from the string. - char * source = buffer; - while ((*source != 0) && ((unsigned char)*source <= 32)) - { - source++; - } - - if (source != buffer) - { - strcpy(buffer, source); - } - - // Clip trailing white space from the string. - for (int index = strlen(buffer)-1; index >= 0; index--) - { - if ((*source != 0) && ((unsigned char)buffer[index] <= 32)) - { - buffer[index] = '\0'; - } - else - { - break; - } - } - } - - return buffer; -} - -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR lpCmdLine, - int nCmdShow) -{ - /* - ** Convert WinMain arguments to simple main argc and argv - */ - int argc = 1; - char * argv[20]; - argv[0] = NULL; - - char * token = strtok(lpCmdLine, " "); - while (argc < 20 && token != NULL) - { - argv[argc++] = strtrim(token); - token = strtok(NULL, " "); - } - - int major = 1; - int minor = 0; - int build = 0; - - if (argc != 2) - { - usage(argv[0]); - } - else - { - char *target = argv[argc-1]; - FILE *filePtr; - - if (target) { - filePtr = fopen(target, "r+"); - if (filePtr) - { - char buffer[256]; - char *stringPtr = NULL; - - while (!feof(filePtr)) - { - fread(buffer, 256, 1, filePtr); - if ((stringPtr = strstr(buffer, VERSION_STRING)) != NULL) - { - char *ptr; - - // Looking for '#define VERSION "x.y.z"' - ptr = strtok(stringPtr, " "); // The VERSION - ptr = strtok(NULL, "\n"); // The remainder - - if (*ptr == '\"') - { - ptr++; // Inc past the first " - ptr = strtok(ptr, "."); // The first number - major = atoi(ptr); - ptr = strtok(NULL, "."); // The second number - minor = atoi(ptr); - ptr = strtok(NULL, "\""); // The final number - build = atoi(ptr); - fclose(filePtr); - - writeVersion(target, major, minor, ++build); - printf ("Build %d Version %d.%d.%d\n", build, major, minor, build); - break; - } else - { - printf ("Build 0. Oops, didn't find a string of the format: '#define VERSION \"x.y.z\"'"); - } - } // End if if (strstr - } // End of while - } // End of if filePtr - else - { - // Didn't find the file, write a new one - writeVersion(target, major, minor, build); - } - } - } - - return 0; -} \ No newline at end of file diff --git a/Generals/Code/Tools/mangler/CMakeLists.txt b/Generals/Code/Tools/mangler/CMakeLists.txt deleted file mode 100644 index 21d297d23b..0000000000 --- a/Generals/Code/Tools/mangler/CMakeLists.txt +++ /dev/null @@ -1,95 +0,0 @@ -set(MANGLERLIB_SRC - "crc.cpp" - "crc.h" - "endian.h" - "wlib/arraylist.h" - "wlib/configfile.cpp" - "wlib/configfile.h" - "wlib/critsec.cpp" - "wlib/critsec.h" - "wlib/dictionary.h" - "wlib/filed.h" - "wlib/linkedlist.h" - "wlib/mboxd.h" - "wlib/monod.cpp" - "wlib/monod.h" - "wlib/odevice.h" - "wlib/sem4.cpp" - "wlib/sem4.h" - "wlib/stderrd.h" - "wlib/stdoutd.h" - "wlib/streamer.cpp" - "wlib/streamer.h" - "wlib/syslogd.cpp" - "wlib/syslogd.h" - "wlib/threadfac.cpp" - "wlib/threadfac.h" - "wlib/threadsafe.h" - "wlib/timezone.cpp" - "wlib/timezone.h" - "wlib/ustring.h" - "wlib/wdebug.cpp" - "wlib/wdebug.h" - "wlib/wstring.cpp" - "wlib/wstring.h" - "wlib/wstypes.h" - "wlib/wtime.cpp" - "wlib/wtime.h" - "wlib/xtime.cpp" - "wlib/xtime.h" - "wnet/field.cpp" - "wnet/field.h" - "wnet/packet.cpp" - "wnet/packet.h" - "wnet/tcp.cpp" - "wnet/tcp.h" - "wnet/udp.cpp" - "wnet/udp.h" -) - -set(MANGLER_SRC - "mangler.cpp" - "mangler.h" -) - -set(MANGLERTEST_SRC - "manglertest.cpp" -) - -add_library(g_manglerlib STATIC) -set_target_properties(g_manglerlib PROPERTIES OUTPUT_NAME manglerlib) - -target_sources(g_manglerlib PUBLIC ${MANGLERLIB_SRC}) -target_include_directories(g_manglerlib PRIVATE . wlib wnet) -target_link_libraries(g_manglerlib PRIVATE wsock32) -target_link_libraries(g_manglerlib PUBLIC - core_config - core_utility -) - -# mangler app - -add_executable(g_mangler WIN32) -set_target_properties(g_mangler PROPERTIES OUTPUT_NAME mangler) - -target_sources(g_mangler PRIVATE ${MANGLER_SRC}) -target_include_directories(g_mangler PRIVATE . wlib wnet) -target_link_libraries(g_mangler PRIVATE g_manglerlib) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(g_mangler PRIVATE /subsystem:console) -endif() - - -# manglertest app - -add_executable(g_manglertest WIN32) -set_target_properties(g_manglertest PROPERTIES OUTPUT_NAME manglertest) - -target_sources(g_manglertest PRIVATE ${MANGLERTEST_SRC}) -target_include_directories(g_manglertest PRIVATE . wlib wnet) -target_link_libraries(g_manglertest PRIVATE g_manglerlib) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(g_manglertest PRIVATE /subsystem:console) -endif() diff --git a/Generals/Code/Tools/mangler/Makefile b/Generals/Code/Tools/mangler/Makefile deleted file mode 100644 index d1176c2b04..0000000000 --- a/Generals/Code/Tools/mangler/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -all = mangler - -TARGET=mangler -TESTTARGET=manglertest - -OBJECTS=mangler.o crc.o -TESTOBJECTS=manglertest.o crc.o - - -LINKFLAGS= -LINKDIRS=-L. -Lwlib -Lwnet -############################################################################ -### -lpthread ### MUST MUST MUST be the last library! -############################################################################ -LINKLIBS = -lwnet -lwlib -lsocket -lnsl -lposix4 -lpthread - -INCDIR=-I. -Iwlib -Iwnet - -CPPFLAGS=$(INCDIR) -c -gstabs+ -DDEBUG -D_UNIX -#CPPFLAGS=$(INCDIR) -c -gstabs+ -D_UNIX - -CPPFILES=${OBJECTS:.o=.cpp} -CFILES=${OBJECTS:.o=.c} -.SUFFIXES : .c .cpp - - -$(TARGET) : $(OBJECTS) - g++ $(LINKFLAGS) $(OBJECTS) $(LINKDIRS) $(LINKLIBS) -o $(TARGET) - -$(TESTTARGET) : $(TESTOBJECTS) $(TARGET) - g++ $(LINKFLAGS) $(TESTOBJECTS) $(LINKDIRS) $(LINKLIBS) -o $(TESTTARGET) - -.cpp.o: - g++ $(CPPFLAGS) $< - -.c.o: - g++ $(CPPFLAGS) $< - - -depend: - g++ -M $(INCDIR) ${CFILES} $(CPPFILES) > dependencies - - -clean: - -rm *.o $(TARGET) $(TESTTARGET) core *.dat - -rebuild: - make clean; make - -run: - make; $(TARGET) - -debug: - gdb -s noxc noxc - -dist: - make clean; make; cp wdtd gavin; cp START gavin; cp STOP gavin; cp world.wdt gavin; - -#include dependencies diff --git a/Generals/Code/Tools/mangler/crc.cpp b/Generals/Code/Tools/mangler/crc.cpp deleted file mode 100644 index 42ec2f3fb5..0000000000 --- a/Generals/Code/Tools/mangler/crc.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#include -#ifdef _WINDOWS -#include // *MUST* be included before ANY Wnet/Wlib headers if _REENTRANT is defined -#endif - -#include "crc.h" - -#include "configfile.h" -#include "threadfac.h" - -#include "endian.h" - -#include "xtime.h" -#include -#include -#include -#include - - - - -/*************************************************************************** - * Add_CRC -- Adds a value to a CRC * - * * - * INPUT: * - * crc ptr to crc * - * val value to add * - * * - * OUTPUT: * - * none * - * * - * WARNINGS: * - * none * - * * - * HISTORY: * - * 05/09/1995 BRR : Created. * - *=========================================================================*/ -void Add_CRC(unsigned long *crc, unsigned char val) -{ - int hibit; - - //cout << "\t\t" << hex << val; -// val = htonl(val); - //cout << " / " << hex << val <. -*/ - -#ifndef __CRC_H__ -#define __CRC_H__ - -void Build_Packet_CRC(unsigned char *buf, int len); // len includes 4-byte CRC at head -bool Passes_CRC_Check(unsigned char *buf, int len); // len includes 4-byte CRC at head -void Add_CRC(unsigned long *crc, unsigned long val); - -#endif // __CRC_H__ diff --git a/Generals/Code/Tools/mangler/endian.h b/Generals/Code/Tools/mangler/endian.h deleted file mode 100644 index 2908003359..0000000000 --- a/Generals/Code/Tools/mangler/endian.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __ENDIAN_H__ -#define __ENDIAN_H__ - - - -/* -** Network order is big-endian. -** -** Packet router and mangler order is big or little endian depending on server platform. -** -** Game client order is little endian. -*/ -extern bool BigEndian; - -template inline T Endian(T val) -{ - if (!BigEndian) { - return(val); - } - -/* - char temp[sizeof(T)]; - *((T*)(&temp[0])) = val; -*/ - - T retval = 0; - -/* - for (int i=0 ; i. -*/ - - -#include - -#include -#ifdef _WINDOWS -#include // *MUST* be included before ANY Wnet/Wlib headers if _REENTRANT is defined -#endif - -#include "mangler.h" -#include "crc.h" -#include "endian.h" - -#include -#include "threadfac.h" - -#include "xtime.h" -#include -#include -#include -#include - -void DisplayHelp(const char *prog) -{ - cout << "Usage: " << prog << " " << endl; - exit(0); -} - -int main(int argc, char **argv) -{ - ConfigFile config; - FILE* conf; - - if( argc <= 1 ) - { - // No args - use a default config file - if ((conf = fopen("mangler.cfg", "r")) == NULL) { - cout << "Cannot open mangler.cfg for reading." << endl; - DisplayHelp(argv[0]); - } - config.readFile(conf); - fclose(conf); - } - else if( argc == 2 && (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "?") == 0 || - strcmp(argv[1], "-h") == 0) ) - DisplayHelp(argv[0]); - else if( argc == 2 ) - { - // Use a user-supplied config file - if ((conf = fopen(argv[1], "r")) == NULL) { - cout << "Cannot open " << argv[1] << " for reading." << endl; - DisplayHelp(argv[0]); - } - config.readFile(conf); - fclose(conf); - } - - // ----- LOGGING ----- - // Setup debugging & logging output - Wstring output_file("mangler.log"); - config.getString("LOGFILE", output_file); - Wstring backup_file; - backup_file = output_file; - backup_file += ".bak"; - rename(output_file.get(),backup_file.get()); // save the old file - FileD output_device(output_file.get()); - MsgManager::setAllStreams(&output_device); - DBGMSG("DBG working..."); - INFMSG("INF working..."); - WRNMSG("WRN working..."); - - if (htonl(0x12345678) == 0x12345678) - { - INFMSG("Host is network-byte-order"); - } - else - { - INFMSG("Host is Intel-byte-order"); - } - - - // ----- Initialize Winsock ----- -#ifdef _WINDOWS - WORD verReq = MAKEWORD(2, 2); - WSADATA wsadata; - - int err = WSAStartup(verReq, &wsadata); - if (err != 0) { - ERRMSG("Winsock Init failed."); - return 1; - } - - if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) { - ERRMSG("Winsock DLL is not 2.2"); - WSACleanup(); - ERRMSG("Winsock Init failed."); - return 1; - } - INFMSG("Winsock Init done."); -#endif - - - // Set up a UDP listener - uint8 *buff=new uint8[1024]; - int retval; - UDP udp; - UDP udp2; - UDP udp3; - UDP udp4; - int port = 4321; - config.getInt("PORT", port); - uint8 blitz = 0; - - uint32 localIP = 0; - Wstring hostIPStr = ""; - config.getString("IP", hostIPStr); - if (hostIPStr.length()) - { - INFMSG("Binding to "< 0) - { - ManglerData *packet = (ManglerData *)buf; - theAddr = (unsigned char *)&(addr.sin_addr.s_addr); - if (retval != packet_size) - { - WRNMSG("Recieved mis-sized packet (" << retval << " bytes) from " << theAddr[0] << "." << theAddr[1] << "." << theAddr[2] << "." << theAddr[3] << ":" << addr.sin_port); - } - else - { - if (!Passes_CRC_Check(buf, packet_size)) - { - WRNMSG("Recieved a bad packet - good length!"); - continue; - } - packet->NetCommandType = 44; - packet->MyMangledPortNumber = addr.sin_port; // not changing to host order, cause its in network byte order now, and the game will expect it to stay that way. - packet->MyMangledAddress[0] = theAddr[0]; - packet->MyMangledAddress[1] = theAddr[1]; - packet->MyMangledAddress[2] = theAddr[2]; - packet->MyMangledAddress[3] = theAddr[3]; - blitz = packet->BlitzMe; - INFMSG("Packet ID = " << packet->packetID); - Build_Packet_CRC(buf, packet_size); - udp.Write(buf,packet_size,ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)); - INFMSG("Saw " << (int)theAddr[0] << "." << (int)theAddr[1] << "." << (int)theAddr[2] << "." << (int)theAddr[3] << ":" << ntohs(addr.sin_port) << ((blitz)?" Blitzed":"") ); - - if (blitz) - { - udp2.Write(buf,packet_size,ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)+1); - udp3.Write(buf,packet_size,ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)+2); - udp4.Write(buf,packet_size,ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)+3); - } - } - } - } - - - return 0; -} - - diff --git a/Generals/Code/Tools/mangler/mangler.h b/Generals/Code/Tools/mangler/mangler.h deleted file mode 100644 index e455648fdb..0000000000 --- a/Generals/Code/Tools/mangler/mangler.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __MANGLER_H__ -#define __MANGLER_H__ - -// Packet should consist of a GlobalHeaderType followed by a GlobalPacketType with the fields set as -// indicated. - - -/* -********************************** Defines ********************************** -*/ - -// This is the number of additional ports to which to reply. -#define BLITZ_SIZE 3 - -#define MPLAYER_NAME_MAX 20 -#define SERIAL_MAX 23 -typedef unsigned char ForwardMaskType; -typedef enum NetCommandType { - NET_MANGLER_REQUEST = 43, - NET_MANGLER_RESPONSE = 44 -} NetCommandType; - -/* -** One byte alignment. -*/ -#if !defined(__GNUC__) -#pragma pack(push, 1) -#define PACK -#else -#define PACK __attribute__ ((__packed__)) -#endif - -// size = 20 bytes -struct ManglerData { - unsigned int CRC PACK; - unsigned short magic PACK; - unsigned short packetID PACK; - unsigned short MyMangledPortNumber PACK; - unsigned short OriginalPortNumber PACK; - unsigned char MyMangledAddress[4] PACK; - unsigned char NetCommandType PACK; - unsigned char BlitzMe PACK; - unsigned short Padding PACK; -}; - -/* - This is for older GCC versions that can't do byte-packing. - Instead of declaring - GlobalPacketType p; - p.Command = NET_MANGLER_REQUEST; - you would do something like this: - GlobalPacketStruct p; - Eval(&p, GPCommand, NetCommandType) = NET_MANGLER_REQUEST; -*/ -#define Eval(x, y, z) ( *((z *)(&((x)->payload[(y)]))) ) - -#if !defined(__GNUC__) -#pragma pack(pop) -#endif - -#endif // __MANGLER_H__ diff --git a/Generals/Code/Tools/mangler/manglertest.cpp b/Generals/Code/Tools/mangler/manglertest.cpp deleted file mode 100644 index 6faaad6d4b..0000000000 --- a/Generals/Code/Tools/mangler/manglertest.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - - -#include - -#include -#ifdef _WINDOWS -#include // *MUST* be included before ANY Wnet/Wlib headers if _REENTRANT is defined -#endif - -#include "mangler.h" -#include "crc.h" - -#include -#include "threadfac.h" - -#include "endian.h" - -#include "xtime.h" -#include -#include -#include -#include - -// ST - 2/1/01 12:46PM -bool BigEndian = false; - -unsigned long ResolveIP(const char *Server) -{ - char serverName[100]; - struct hostent *serverStruct; - struct in_addr *serverNode; - - if (Server == NULL) - { - ERRMSG("Can't resolve NULL"); - return 0; - } - - if (isdigit(Server[0])) - return ( ntohl(inet_addr(Server)) ); - - strcpy(serverName, Server); - - serverStruct = gethostbyname(Server); - if (serverStruct == NULL) - { - ERRMSG("Can't resolve " << Server); - return 0; - } - serverNode = (struct in_addr *) serverStruct->h_addr; - return ( ntohl(serverNode->s_addr) ); -} - -void DisplayHelp(const char *prog) -{ - cout << "Usage: " << prog << " " << endl; - exit(0); -} - -int main(int argc, char **argv) -{ - ConfigFile config; - FILE* conf; - - if( argc <= 1 ) - { - // No args - use a default config file - if ((conf = fopen("manglertest.cfg", "r")) == NULL) { - cout << "Cannot open mangler.cfg for reading." << endl; - DisplayHelp(argv[0]); - } - config.readFile(conf); - fclose(conf); - } - else if( argc == 2 && (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "?") == 0 || - strcmp(argv[1], "-h") == 0) ) - DisplayHelp(argv[0]); - else if( argc == 2 ) - { - // Use a user-supplied config file - if ((conf = fopen(argv[1], "r")) == NULL) { - cout << "Cannot open " << argv[1] << " for reading." << endl; - DisplayHelp(argv[0]); - } - config.readFile(conf); - fclose(conf); - } - - // ----- LOGGING ----- - // Setup debugging & logging output - Wstring output_file("manglertest.log"); - config.getString("LOGFILE", output_file); - Wstring backup_file; - backup_file = output_file; - backup_file += ".bak"; - rename(output_file.get(),backup_file.get()); // save the old file - FileD output_device(output_file.get()); - MsgManager::setAllStreams(&output_device); - DBGMSG("DBG working..."); - INFMSG("INF working..."); - WRNMSG("WRN working..."); - - - // - // See if our processor is big or little endian. Network order is big endian. - // ST - 2/1/01 12:11PM - // - if (htonl(0x12345678) == 0x12345678) { - BigEndian = true; - } - - - // ----- Initialize Winsock ----- -#ifdef _WINDOWS - WORD verReq = MAKEWORD(2, 2); - WSADATA wsadata; - - int err = WSAStartup(verReq, &wsadata); - if (err != 0) { - ERRMSG("Winsock Init failed."); - return 1; - } - - if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) { - ERRMSG("Winsock DLL is not 2.2"); - WSACleanup(); - ERRMSG("Winsock Init failed."); - return 1; - } - INFMSG("Winsock Init done."); -#endif - - - // Set up a UDP listener - uint8 *buff=new uint8[1024]; - int retval; - UDP udp; - int port = 4321; - config.getInt("MANGLERPORT", port); - - int localport = 4444; - config.getInt("CLIENTPORT", localport); - retval = udp.Bind((uint32)0,(uint16)localport); - DBGMSG("Bind returned " << retval); - - //----------------------------------------------------------------------------------------- - const int packet_size = sizeof(ManglerData); - INFMSG("sizeof(packet) == " << packet_size); - - unsigned char buf[packet_size]; - memset(buf, 0x44, packet_size); // init to something known for memory dumps :) - struct sockaddr_in addr; - - int doBlitz = 0; - config.getInt("BLITZ", doBlitz); - if (doBlitz) - { - INFMSG("Requsting port blitz"); - } - - unsigned char *theAddr; - fd_set fdset; - unsigned long server_addr; - Wstring manglername = "localhost"; - config.getString("MANGLERIP", manglername); - server_addr = ResolveIP(manglername.get()); - if (!server_addr) - { - ERRMSG("Cannot resolve mangler server IP"); - return 1; - } - - ManglerData *packet = (ManglerData *)buf; - packet->NetCommandType = 12; - packet->packetID = 9999; - packet->BlitzMe = doBlitz; - packet->magic = htons((unsigned short)0xf00d); - Build_Packet_CRC(buf, packet_size); - DBGMSG("Writing to " << manglername.get() << ":" << port); - udp.Write(buf,packet_size,server_addr, 4321); - - retval = udp.Wait(5, 0, fdset); - if (retval) - { - DBGMSG("Wait returned " << retval); - retval = udp.Read(buf, packet_size, &addr); // Wait until there is something on the socket - if (retval > 0) - { - theAddr = (unsigned char *)&(addr.sin_addr.s_addr); - if (retval != packet_size) - { - WRNMSG("Recieved mis-sized packet (" << retval << " bytes) from " << theAddr[0] << "." << theAddr[1] << "." << theAddr[2] << "." << theAddr[3] << ":" << addr.sin_port); - } - else - { - int packetCommand; - packetCommand = packet->NetCommandType; - if (!Passes_CRC_Check(buf, packet_size)) - { - WRNMSG("CRC error!"); - } - else if (packetCommand != 13) - { - WRNMSG("Returned packet had command type " << packetCommand); - } - else - { - int addr[4]; - unsigned short retPort; - retPort = htons(packet->MyMangledPortNumber); - addr[0] = packet->MyMangledAddress[0]; - addr[1] = packet->MyMangledAddress[1]; - addr[2] = packet->MyMangledAddress[2]; - addr[3] = packet->MyMangledAddress[3]; - DBGMSG("Saw " << addr[0] << "." << addr[1] << "." << addr[2] << "." << addr[3] << ":" << retPort); - } - } - } - } - else - { - DBGMSG("Wait timed out"); - } - - - return 0; -} - - diff --git a/Generals/Code/Tools/mangler/wlib/Makefile b/Generals/Code/Tools/mangler/wlib/Makefile deleted file mode 100644 index 1163a2ba61..0000000000 --- a/Generals/Code/Tools/mangler/wlib/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -########################################################################### -# WLIB library makefile -########################################################################## - -#Define cc to be your C compiler -CC = g++ - -#This tells make how to go from a .cpp to a .o -.SUFFIXES: .cpp -.cpp.o: - ${CC} ${CFLAGS} -c $< - -INCLUDE = -I. -I.. - -CFLAGS = ${INCLUDE} -D_REENTRANT -DDEBUG -D_UNIX - -AR = ar -r -#CC is dumb and won't include templates in a library uness you define -#CC -xar as your replacement for 'ar' -#AR = CC -xar - -RM = rm -f -RANLIB = ranlib - -############################################################################ -#Dont mess with any of this stuff -OBJECTS = wtime.o monod.o wdebug.o sem4.o streamer.o syslogd.o wstring.o \ - configfile.o threadfac.o critsec.o xtime.o timezone.o - -LIBRARY = libwlib.a - -all: $(LIBRARY) - -$(LIBRARY): $(OBJECTS) - ${RM} libwlib.a - ${AR} libwlib.a $(OBJECTS) - #${AR} $(OBJECTS) -o libwlib.a - $(RANLIB) libwlib.a - -clean: - - rm -f $(LIBRARY) *.o core diff --git a/Generals/Code/Tools/mangler/wlib/arraylist.h b/Generals/Code/Tools/mangler/wlib/arraylist.h deleted file mode 100644 index efcd3abd65..0000000000 --- a/Generals/Code/Tools/mangler/wlib/arraylist.h +++ /dev/null @@ -1,709 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: -File Name : arraylist.h -Author : Neal Kettler -Start Date : Jan 19, 1997 -Last Update : Jan 19, 1997 ------------------------------------------------------------------------------- - -Array implementation of a list. Note: There are some freaky C++ memory tricks -going on here. If you think there's a leak, see me before changing it. -The way this works is that it allocates an array to hold 'N' items on the -first list add. It doesn't call the constructors for those 'N' items until -necessary (for efficiency). When an item is added to a slot then a new -class is constructed inside the array element using the placement new operator -and the class's copy constructor. When elements are removed the destructor -is then manually called on this memory location. - -All data added to the list is copied so feel free to delete/destroy/modify -the original after an add. - -You _must_ have a good copy constructor for any classes that you use this template -for! A good copy constructor is one that won't blindly duplicate pointers -that don't belong to them, etc... - -\****************************************************************************/ - -#ifndef ARRAYLIST_HEADER -#define ARRAYLIST_HEADER - -#include -#include -#include -#include -#include -#include - -#include "wstypes.h" - -// -// Usage: ArrayList TheList; -// -template -class ArrayList -{ - public: - ArrayList(); - ArrayList(ArrayList &other); - ~ArrayList(); - - // Remove all entries from the lsit - void clear(void); - - // Add a node after the zero based 'pos' - bit8 add(IN T &node,sint32 pos); - bit8 addTail(IN T &node); - bit8 addHead(IN T &node); - bit8 addSortedAsc(IN T &node); // Ascending - bit8 addSortedDes(IN T &node); // Descending - /*bit8 addNumSortedAsc(IN T &node); // Ascending - bit8 addNumSortedDes(IN T &node); // Descending*/ - - // Remove a node - bit8 remove(OUT T &node,sint32 pos); - bit8 remove(sint32 pos); - bit8 removeHead(OUT T &node); - bit8 removeTail(OUT T &node); - - // Replace one obj with another - bit8 replace(IN T &node, sint32 pos); - - - // Get a node without removing from the list - bit8 get(OUT T &node,sint32 pos) RO; - bit8 getHead(OUT T &node) RO; - bit8 getTail(OUT T &node) RO; - - // Get a pointer to the interally managed copy (careful!) - bit8 getPointer(OUT T **node,sint32 pos) RO; - - // Get the number of entries in the list - sint32 length(void) RO; - - // UNSAFE! for classes, see note below! - bit8 setSize(sint32 newsize, IN T &filler); - - // Print information on the list - void print(FILE *out); - - // assignment operator - ArrayList &operator=(IN ArrayList &other); - - private: - sint32 _sortedLookup(IN T &target, int ascending); - sint32 Entries_; // Number of entries - sint32 Slots_; // Number of available slots - - T *Vector_; // The actual memory where the list is held - - enum - { - INITIAL_SIZE = 10 - }; - - bit8 growVector(void); // Expand the number of slots - bit8 shrinkVector(void); // Reduce the number of slots -}; - - -//Create the empty list -template -ArrayList::ArrayList() -{ - Entries_=0; - Slots_=0; - Vector_=NULL; -} - -// copy constructor -template -ArrayList::ArrayList(ArrayList &other) -{ - Entries_=0; - Slots_=0; - Vector_=NULL; - (*this)=other; -} - -//Free all the memory... -template -ArrayList::~ArrayList() -{ - clear(); // Remove the entries & call destructors on them - - delete[]((uint8*)Vector_); // this will prevent the destructors from - // gettting called on elements not - // containing valid objects. - - //fprintf(stderr,"Arraylist destructor\n"); -} - -// assignment operator -template -ArrayList &ArrayList::operator=(IN ArrayList &other) -{ - T node; - clear(); - for (int i=0; i -void ArrayList::clear() -{ - for (int i=0; i~T(); // Call the destructor manually. Don't try this - // at home kiddies! - } - Entries_=0; -} - -// ************************* UNSAFE UNSAFE UNSAFE ************************* -// Note - Don't call this on any type with a constructor/destructor since this -// is really dumb and just puts a new one of filler in. Well, it's kindof safe -// just be careful. -// It's fine for simple classes like ints though.. -// -// Add/remove entries in a stupid manner... -// -// ************************************************************************** -template -bit8 ArrayList::setSize(sint32 newsize, IN T &filler) -{ - int oldEntries=Entries_; - Entries_ = newsize; - - if (newsize<0) - return(false); - - // Grow the vector as much as we need to - while (newsize > Slots_) - growVector(); - - // Create new objects in the blank holes - for (int i=oldEntries; i -bit8 ArrayList::add(IN T &node,sint32 pos) -{ - if (pos > Entries_) // You can only access one of the end of the vector - pos=Entries_; - if (pos >= Slots_) // If we're at the end, grow the list - growVector(); - if (Entries_ >= Slots_) // enuff space? - growVector(); - - // If we are insering into the middle or front of the list we have to - // slide the old objects forward. - if (pos < Entries_) // If there are elements after the add point - memmove(Vector_+pos+1,Vector_+pos,sizeof(T)*(Entries_-pos)); // move them forward - - //fprintf(stderr,"Placement new to %p\n",(Vector_+pos)); - - // This uses the placement new operator. placement new allows us to - // specify the memory address for the new object. In this case we - // want it at the 'pos' index into our array. - new((void *)(Vector_+pos)) T((T &)node); // Trust me, this isn't a memory leak - Entries_++; // one new entry - return(TRUE); -} - - -// Add to the first node, all others get shifted down one slot -template -bit8 ArrayList::addHead(IN T &node) -{ - return(add(node,0)); -} - - -// Append to the end of the list -template -bit8 ArrayList::addTail(IN T &node) -{ - return(add(node,length())); -} - - -// addSortedX only works (properly) if evrerything else in the list is added -// using addSorted. -template -bit8 ArrayList::addSortedAsc(IN T &node) -{ - sint32 pos = _sortedLookup(node, 1); - return(add(node, pos)); -} - - -// addSortedX only works (properly) if evrerything else in the list is added -// using addSorted. -template -bit8 ArrayList::addSortedDes(IN T &node) -{ - sint32 pos = _sortedLookup(node, 0); - return(add(node, pos)); -} - - -// This is the binary search used by addSorted -template -sint32 ArrayList::_sortedLookup(IN T &target, int ascending) -{ - int low, mid, high; - T* lowtarget; - T* hightarget; - T* midtarget; - - - // Trivial cases - if( Entries_ == 0 ) - return 0; - - low = 0; - high = Entries_ - 1; - while( 1 ) - { - assert( low <= high ); - mid = low + (int)(floor(((double)high - (double)low) / (double)2)); - - getPointer(&lowtarget, low); - getPointer(&hightarget, high); - getPointer(&midtarget, mid); - - // Exact match - if( *midtarget == target ) return mid; - - // Single element - if( high == low ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else - return low + 1; - } - else - { - if( target <= *lowtarget ) - return low + 1; - else - return low; - } - } - - // Two elemsnts - if( (high - low) == 1 ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else if( target <= *hightarget ) - return high; - else - return high + 1; - } - else - { - if( target <= *hightarget ) - return high + 1; - else if( target <= *lowtarget ) - return high; - else - return low; - } - } - - // Sorry, try again... - if( ascending ) - { - if( target < *midtarget ) - high = mid; - else - low = mid; - } - else - { - if( target < *midtarget ) - low = mid; - else - high = mid; - } - } -} - - -/*// addNumSortedX works in much the same way as addSortedX, except that I needed -// it for a very specific thing. I needed a list of strings numerically sorted, -// not alphabetically sorted. Furthermore these strings were composed of numbers -// delimited by underscores. In the interest of keeping it generic, these -// functions take as args a node, a delimiting character, and a count of the -// number of fields to include in a sort. If this is the list of strings: -// -// 55_100, 2_5, 23_32, 98_445, 2_48, 8_88, 2_3, 2_4 -// -// An alphabetical sort is: -// -// 2_3, 2_4, 2_48, 2_5, 55_100, 8_88, 98_445 -// -// But a numerical sort by calling addNumSortedAsc(, "_", 2) will result in: -// -// 2_3, 2_4, 2_5, 2_48, 8_88, 55_100, 98_445 -// -// Yes...now that you mention it I am on crack... -// -template -bit8 ArrayList::addNumSortedAsc(IN T &node, char delim, int fields) -{ - sint32 pos = _numSortedLookup(node, delim, fields, 1); - return(add(node, pos)); -} - - -// See addNumSortedAsc comment above. -template -bit8 ArrayList::addSortedDes(IN T &node, char delim, int fields) -{ - sint32 pos = _sortedLookup(node, delim, fields, 0); - return(add(node, pos)); -} - - -// This is the binary search used by addSorted -template -sint32 ArrayList::_numSortedLookup(IN T &target, char delim, int fields, int ascending) -{ - int low, mid, high; - T* lowtarget; - T* hightarget; - T* midtarget; - - - // Trivial case - if( Entries_ == 0 ) - return 0; - - low = 0; - high = Entries_; - while( 1 ) - { - assert( low <= high ); - mid = low + (int)(floor(((double)high - (double)low) / (double)2)); - - getPointer(&lowtarget, low); - getPointer(&hightarget, high); - getPointer(&midtarget, mid); - - // Exact match - if( *midtarget == target ) return mid; - - // Single element - if( high == low ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else - return low + 1; - } - else - { - if( target <= *lowtarget ) - return low + 1; - else - return low; - } - } - - // Two elemsnts - if( (high - low) == 1 ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else - return high; - } - else - { - if( target <= *lowtarget ) - return high; - else - return low; - } - } - - // Sorry, try again... - if( ascending ) - { - if( target < *midtarget ) - high = mid; - else - low = mid; - } - else - { - if( target < *midtarget ) - low = mid; - else - high = mid; - } - } -}*/ - - -// -// Delete an item at this index and construct a new one in it's place -// -template -bit8 ArrayList::replace(IN T &node, sint32 pos) -{ - if (Entries_==0) - return(FALSE); - if (pos<0) - pos=0; - if (pos >= Entries_) - pos=Entries_-1; - - (Vector_+pos)->~T(); // Call the destructor manually. Don't try this - // at home kiddies! - - // Now put the replacement object in there... - new((void *)(Vector_+pos)) T(node); // Trust me, this isn't a memory leak - - return(TRUE); -} - - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 ArrayList::remove(sint32 pos) -{ - if (Entries_==0) - return(FALSE); - if (pos<0) - pos=0; - if (pos >= Entries_) - pos=Entries_-1; - - (Vector_+pos)->~T(); // Call the destructor manually. Don't try this - // at home kiddies! - - memmove(Vector_+pos,Vector_+pos+1,sizeof(T)*(Entries_-pos-1)); - - Entries_--; - - // If we're at 33% usage or less, shrink the vector - if ( (Entries_*3) <= Slots_) - shrinkVector(); - - return(TRUE); -} - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 ArrayList::remove(OUT T &node, sint32 pos) -{ - bit8 retval; - retval=get(node,pos); - if (retval==FALSE) - return(FALSE); - return(remove(pos)); -} - - -// Remove the first node of the list -template -bit8 ArrayList::removeHead(OUT T &node) -{ - return(remove(node,0)); -} - - -// Remove the last node of the list -template -bit8 ArrayList::removeTail(OUT T &node) -{ - return(remove(node,Entries_-1)); -} - -// get a pointer to the internally managed object. Try and avoid this, but -// sometimes efficiency requires it... -// get a copy of an item -template -bit8 ArrayList::getPointer(OUT T **node,sint32 pos) RO -{ - if ((pos < 0)||(pos >= Entries_)) - return(FALSE); - *node=&(Vector_[pos]); - return(TRUE); -} - - -// get a copy of an item -template -bit8 ArrayList::get(OUT T &node,sint32 pos) RO -{ - if ((pos < 0)||(pos >= Entries_)) - return(FALSE); - node=Vector_[pos]; - return(TRUE); -} - - -// get a copy of the first node of the list -template -bit8 ArrayList::getHead(OUT T &node) RO -{ - return(get(node,0)); -} - - -// get a copy of the last node -template -bit8 ArrayList::getTail(OUT T &node) RO -{ - return(get(node,Entries_-1)); -} - -// just for debugging -template -void ArrayList::print(FILE *out) -{ - fprintf(out,"--------------------\n"); - //for (int i=0; i -sint32 ArrayList::length(void) RO -{ - return(Entries_); -} - -// Grow the vector by a factor of 2X -template -bit8 ArrayList::growVector(void) -{ - if (Entries_ < Slots_) // Don't grow until we're at 100% usage - return(FALSE); - - int newSlots=Entries_*2; - if(newSlots < INITIAL_SIZE) - newSlots=INITIAL_SIZE; - - //fprintf(stderr,"Growing vector to: %d\n",newSlots); - - // The goofy looking new below prevents operator new from getting called - // unnecessarily. This is severall times faster than allocating all of - // the slots as objects and then calling the assignment operator on them - // when they actually get used. - // - T *newVector=(T *)(new uint8[newSlots * sizeof(T)]); - memset(newVector,0,newSlots * sizeof(T)); // zero just to be safe - - if (Vector_ != NULL) - memcpy(newVector,Vector_,Entries_*sizeof(T)); - - delete[]((uint8 *)Vector_); // Get rid of the old vector without calling - // destructors - - Vector_=newVector; - Slots_=newSlots; - - return(TRUE); -} - - -// Shrink the vector by a factor of 2X -template -bit8 ArrayList::shrinkVector(void) -{ - //fprintf(stderr,"Shrink called\n"); - - // Don't need to shrink until usage goes below 33% - if ( (Entries_*3) > Slots_) - return(FALSE); - - int newSlots=Slots_/2; - if(newSlots < INITIAL_SIZE) // never shrink past initial size - newSlots=INITIAL_SIZE; - - if (newSlots >= Slots_) // don't need to shrink - return(FALSE); - - //fprintf(stderr,"Shrinking vector to: %d\n",newSlots); - - // The goofy looking new below prevents operator new from getting called - // unnecessarily. This is severall times faster than allocating all of - // the slots as objects and then calling the assignment operator on them - // when they actually get used. - // - T *newVector=(T *)(new uint8[newSlots * sizeof(T)]); - - if (Vector_ != NULL) // Vector_ better not be NULL! - memcpy(newVector,Vector_,Entries_*sizeof(T)); - - delete[]((uint8 *)Vector_); // Get rid of the old vector without calling - // destructors - - Vector_=newVector; - Slots_=newSlots; - - return(TRUE); -} - - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/configfile.cpp b/Generals/Code/Tools/mangler/wlib/configfile.cpp deleted file mode 100644 index b0f9e5a91c..0000000000 --- a/Generals/Code/Tools/mangler/wlib/configfile.cpp +++ /dev/null @@ -1,490 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : configfile.cpp -Author : Neal Kettler -Start Date : June 9, 1997 -Last Update : June 17, 1997 - - -This class will read in a config file and store the key value pairs for -later access. This is a fairly simple class, the config file is assumed -to be of the form: - -#comment -key = value - -The value can then be retrieved as a string or an integer. The key on -the left is used for retrieval and it must be specified in uppercase -for the 'get' functions. E.g. getString("KEY",valWstring); -\***************************************************************************/ - -#include -#include -#include - -#include "configfile.h" -#include "wdebug.h" - -static uint32 Wstring_Hash(const Wstring &string); -static char *Eat_Spaces(char *string); - -ConfigFile::ConfigFile() : Dictionary_(Wstring_Hash) -{ } - -ConfigFile::~ConfigFile() -{ } - -// Read and parse the config file. The key value pairs will be stored -// for later access by the getString/getInt functions. -bit8 ConfigFile::readFile(FILE *in) -{ - char string[256]; - char sectionname[256]; // section name like '[user parameters]' - Wstring key; - Wstring value; - char *cptr; - - memset(string,0,256); - memset(sectionname,0,256); - sectionList.clear(); - - while (fgets(string,256,in)) - { - cptr=Eat_Spaces(string); - if ((*cptr==0)||(*cptr=='#')) // '#' signals a comment - continue; - - if (*cptr=='[') // new section - { - key=cptr; - key.truncate(']'); // remove after & including the ] - key.cat("]"); // put the ] back - strcpy(sectionname,key.get()); // set the current section name - Wstring wssectionname; - - if (strlen(sectionname)==2) // clear section with a "[]" - { - sectionname[0]=0; - wssectionname.set(""); - } - else - wssectionname.set(sectionname+1); - - wssectionname.truncate(']'); - sectionList.addTail(wssectionname); - - - continue; - } - - if (strchr(cptr,'=')==NULL) // All config entries must have a '=' - continue; - key=cptr; - key.truncate('='); - key.removeSpaces(); // No spaces allowed in the key - key.toUpper(); // make key all caps - - // Add the section name to the end of the key - if (strlen(sectionname)) - key.cat(sectionname); - - cptr=Eat_Spaces(strchr(cptr,'=')+1); // Jump to after the '=' - value=cptr; - value.truncate('\r'); - value.truncate('\n'); - value.truncate('#'); - - // TheSuperHackers @compile xezon 25/03/2025 Re-implement algorithm to avoid writing into string buffer directly. - // Remove trailing spaces - { - const char* valueStr = value.get(); - const uint32 valueLen = value.length(); - uint32 spaceIdx = valueLen; - for (; spaceIdx > 0 && isgraph(valueStr[spaceIdx - 1])==0; --spaceIdx); - if (spaceIdx != valueLen) - value.truncate(spaceIdx); - } - - Critsec_.lock(); - Dictionary_.add(key,value); - Critsec_.unlock(); - } - return(TRUE); -} - - -// -// Enum through the config strings. To start, index & offset should be 0 -// If retval is false you're done, ignore whatever's in key & value. -// -// Section specifies the configfile section. Set to NULL if you don't care. -// -bit8 ConfigFile::enumerate(int &index, int &offset, Wstring &key, Wstring &value, IN char *section) const -{ - int seclen = strlen(section); - while(1) - { - Critsec_.lock(); - if (Dictionary_.iterate(index,offset,key,value)==FALSE) // out of keys? - { - Critsec_.unlock(); - return(FALSE); - } - Critsec_.unlock(); - - if (section==NULL) // no specified section, so any will do... - break; - - if (strlen(section)+2 >= strlen(key.get())) // key should have form: X[section] - continue; - - // Is this key part of our section? - const char *keystr = key.get() + strlen(key.get())-seclen-1; - if (strncmp(keystr,section,strlen(section))==0) - break; - } - key.truncate('['); // remove the section name - return(TRUE); -} - - - -// Get a config entry as a string -bit8 ConfigFile::getString(IN Wstring &_key, Wstring &value, IN char *section) const -{ - Wstring key(_key); - key.toUpper(); - - if (section) // append section name to key - { - key+="["; - key+=section; - key+="]"; - } - - Critsec_.lock(); - bit8 retval=Dictionary_.getValue(key,value); - Critsec_.unlock(); - - if (retval==FALSE) - { - DBGMSG("Config entry missing: "<>24); // ROL 8 - } - return(retval); -} - -static char *Eat_Spaces(char *string) -{ - char *retval=string; - while (isspace(*retval)) - retval++; - return(retval); -} diff --git a/Generals/Code/Tools/mangler/wlib/configfile.h b/Generals/Code/Tools/mangler/wlib/configfile.h deleted file mode 100644 index b622f1354e..0000000000 --- a/Generals/Code/Tools/mangler/wlib/configfile.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : configfile.h -Author : Neal Kettler -Start Date : June 9, 1997 -Last Update : May 13, 1999 -\***************************************************************************/ - -#ifndef CONFIGFILE_HEADER -#define CONFIGFILE_HEADER - -#include "wstypes.h" -#include "dictionary.h" -#include "wstring.h" -#include "critsec.h" -#include "arraylist.h" - -class ConfigFile -{ - public: - ConfigFile(); - ~ConfigFile(); - bit8 readFile(FILE *config); - bit8 getString(IN Wstring &key,OUT Wstring &value, IN char *section=NULL) const; - bit8 getString(IN char *key,OUT Wstring &value, IN char *section=NULL) const; - - bit8 getInt(IN Wstring &key,OUT sint32 &value, IN char *section=NULL) const; - bit8 getInt(IN char *key,OUT sint32 &value, IN char *section=NULL) const; - - bit8 getInt(IN Wstring &key,OUT sint16 &value, IN char *section=NULL) const; - bit8 getInt(IN char *key,OUT sint16 &value, IN char *section=NULL) const; - - // Enumerate through the config lines - bit8 enumerate(int &index, int &offset, Wstring &key, Wstring &value, IN char *section=NULL) const; - - // Manual update of config file - bit8 setString(IN Wstring &key,IN Wstring &value, IN char *section=NULL); - bit8 setString(IN char *key,IN Wstring &value, IN char *section=NULL); - bit8 setInt(IN Wstring &key,IN sint32 &value, IN char *section=NULL); - bit8 setInt(IN char *key,IN sint32 &value, IN char *section=NULL); - bit8 removeEntry(IN Wstring &key, IN char *section=NULL); - bit8 removeEntry(IN char *key, IN char *section=NULL); - bit8 writeFile(FILE *config); // Does not preserve comments, etc - - ArrayList sectionList; // stores the names of all sections - - private: - Dictionary Dictionary_; // stores the mappings from keys - // to value strings - - // The lock is only needed around the immediate access to the dictionary, no writes - // are allowed so you don't need to worry about an outer lock around the enumerate - CritSec Critsec_; // lock around dictionary -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/critsec.cpp b/Generals/Code/Tools/mangler/wlib/critsec.cpp deleted file mode 100644 index 21b8ced2b7..0000000000 --- a/Generals/Code/Tools/mangler/wlib/critsec.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "critsec.h" -#include -#include "wlib/wdebug.h" - - - -CritSec::CritSec() -{ -#ifdef _UNIX - pthread_mutex_init(&Mutex_, NULL); - RefCount_ = 0; -#elif defined(_WIN32) - InitializeCriticalSection(&CritSec_); -#endif -} - -CritSec::~CritSec() -{ - #ifdef _UNIX - pthread_mutex_destroy(&Mutex_); - #elif defined(_WIN32) - DeleteCriticalSection(&CritSec_); - #endif -} - -// The "lock" function blocks until the mutex is available. -// Returns 0 on success, error code on error. -// -// A thread that already has a lock will increment a reference count if it calls -// lock again. It must then call unlock() enough times to get the reference to 0. -// -// If refcount is not null you can get the current ref counter after the lock. -// -sint32 CritSec::lock(int *refcount) RO -{ - #ifdef _UNIX - sint32 status; - - // I TRY to get the lock. IF I succeed, OR if I fail because - // I already have the lock, I just increment the reference - // count and return. - if (((status = pthread_mutex_trylock(&Mutex_)) == 0) || - ((status == EBUSY) && (ThreadId_ == pthread_self()))) - { - ThreadId_ = pthread_self(); - RefCount_++; - if (refcount) - *refcount=RefCount_; - return(0); - } - - // Otherwise, I wait for the lock. - if ((status = pthread_mutex_lock(&Mutex_)) == 0) - { - assert(RefCount_ == 0); - ThreadId_ = pthread_self(); - RefCount_++; - } - else - { - ERRMSG("pthread_mutex_lock: " << strerror(errno)); - } - - if (refcount) - *refcount=RefCount_; - - return(status); - #elif defined(_WIN32) - // TOFIX update the refcount - EnterCriticalSection(&CritSec_); - return(0); - #else - #error Must define either _WIN32 or _UNIX - #endif -} - -// The "unlock" function release the critical section. -sint32 CritSec::unlock(void) RO -{ - #ifdef _UNIX - sint32 status = 0; - - assert(RefCount_ >= 0); - if (RefCount_ <= 0) - { - //ERRMSG("unlocking unlocked mutex!"); - return(-1); - } - - ///assert(ThreadId_ == pthread_self()); - if (ThreadId_ != pthread_self()) - { - WRNMSG("tried to unlock a mutex not owned by self"); - return(-1); - } - - if (--RefCount_ == 0) - { - // Set thread id to zero -- we're going to release mutex - ThreadId_ = (pthread_t)0; - - // Unlock the mutex. - if ((status = pthread_mutex_unlock(&Mutex_)) != 0) - ERRMSG("pthread_mutex_lock: " << strerror(errno)); - } - return status; - #elif defined(_WIN32) - LeaveCriticalSection(&CritSec_); - return(0); - #endif -} diff --git a/Generals/Code/Tools/mangler/wlib/critsec.h b/Generals/Code/Tools/mangler/wlib/critsec.h deleted file mode 100644 index c25759cf04..0000000000 --- a/Generals/Code/Tools/mangler/wlib/critsec.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef CRITSEC_HEADER -#define CRITSEC_HEADER - -#include "wstypes.h" -#ifdef _WIN32 - #include - #include -#elif defined(_UNIX) - #include - #include -#endif - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -// -// Critical Section built either on a POSIX Mutex, or a Win32 Critical Section -// -// POSIX version is done by keeping a thread_id and a reference count. Win32 version -// just calls the built in functions. -// -class CritSec -{ - public: - CritSec(); - ~CritSec(); - - sint32 lock(int *refcount=NULL) RO; - sint32 unlock(void) RO; - - protected: - #ifdef _WIN32 - mutable CRITICAL_SECTION CritSec_; - #else - mutable pthread_mutex_t Mutex_; // Mutex lock - mutable pthread_t ThreadId_; // Owner of mutex - mutable int RefCount_; // Reference count - #endif -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/dictionary.h b/Generals/Code/Tools/mangler/wlib/dictionary.h deleted file mode 100644 index 56e1cc346b..0000000000 --- a/Generals/Code/Tools/mangler/wlib/dictionary.h +++ /dev/null @@ -1,681 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : dictionary.h -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 - -This template file implements a hash dictionary. A hash dictionary is -used to quickly match a value with a key. This works well for very -large sets of data. A table is constructed that has some power of two -number of pointers in it. Any value to be put in the table has a hashing -function applied to the key. That key/value pair is then put in the -linked list at the slot the hashing function specifies. If everything -is working well, this is much faster than a linked list, but only if -your hashing function is good. -\****************************************************************************/ - - -#ifndef DICTIONARY_HEADER -#define DICTIONARY_HEADER - - -#include -#include -#include -#include -#include - -#include "wstypes.h" - -// Every entry in the hash dictionary must be an instance of the DNode -// template. 'K' and 'V' denote Key and Value. -template -class DNode -{ - public: - K key; - V value; - DNode *hashNext; -}; - -template -class Dictionary -{ - public: - ////////////////Dictionary(uint32 (* hashFn)(K &key)); - - -// Note: I had to put this inside the class definition because VC5 sucks butt - -//Create the empty hash dictionary -Dictionary(uint32 (*hashFn)(const K &key)) : - SHRINK_THRESHOLD(0.20), // When table is only 20% full shrink it - EXPAND_THRESHOLD(0.80), // When table is 80% full grow it - MIN_TABLE_SIZE(128) // must be a power of 2 -{ - log2Size=MIN_TABLE_SIZE; - size=MIN_TABLE_SIZE; - assert(size>=4); - tableBits=0; - while(log2Size) { tableBits++; log2Size>>=1; } - tableBits--; - size=1< **)new DNode* [size]; - assert(table!=NULL); - - memset((void *)table,0,size*sizeof(void *)); - hashFunc=hashFn; -} - - - ~Dictionary(); - - void clear(void); - bit8 add(IN K &key,IN V &value); - bool getValue(IN K &key, OUT V &value) RO; - bool getPointer(IN K &key, OUT V **value) RO; // ptr to internal storage (Careful!) - void print(FILE *out) RO; - uint32 getSize(void) RO; - uint32 getEntries(void) RO; - bit8 contains(IN K &key) RO; - bit8 updateValue(IN K &key,IN V &value); - bit8 remove(IN K &key,OUT V &value); - bit8 remove(IN K &key); - bit8 removeAny(OUT K &key,OUT V &value); - bit8 iterate(INOUT int &index,INOUT int &offset, OUT V &value) RO; - bit8 iterate(INOUT int &index,INOUT int &offset, OUT K &key, OUT V &value) RO; - Dictionary &operator=(Dictionary &other); - - private: - void shrink(void); // halve the number of slots - void expand(void); // double the number of slots - - - DNode **table; // This stores the lists at each slot - - uint32 entries; // number of entries - uint32 size; // size of table - uint32 tableBits; // table is 2^tableBits big - uint32 log2Size; // Junk variable - bit8 keepSize; // If true don't shrink or expand - - uint32 (* hashFunc)(IN K &key); // User provided hash function - uint32 keyHash(IN K &key) RO; // This will reduce to correct range - - - // See initilizer list of constructor for values - const double SHRINK_THRESHOLD; // When table is this % full shrink it - const double EXPAND_THRESHOLD; // When table is this % full grow it - const int MIN_TABLE_SIZE; // must be a power of 2 -}; - - - -//Free all the memory... -template -Dictionary::~Dictionary() -{ - clear(); // Remove the entries - delete[](table); // And the table as well -} - -// Remove all the entries and free the memory -template -void Dictionary::clear() -{ - DNode *temp,*del; - uint32 i; - //free all the data - for (i=0; ihashNext; - delete(del); - } - table[i]=NULL; - } - entries=0; - - while ((getSize()>(uint32)MIN_TABLE_SIZE)&&(keepSize==FALSE)) - shrink(); -} - -template -uint32 Dictionary::keyHash(IN K &key) RO -{ - uint32 retval=hashFunc(key); - retval &= ((1< -void Dictionary::print(FILE *out) RO -{ - DNode *temp; - uint32 i; - - fprintf(out,"--------------------\n"); - for (i=0; ihashNext; - } - fprintf(out,"\n"); - } - fprintf(out,"--------------------\n"); -} - - -template -Dictionary &Dictionary::operator=(Dictionary &other) -{ - _ASSERTE(0); -} - - - -// -// Iterate through all the records. Index is for the table, offset specifies the -// element in the linked list. Set both to 0 and continue calling till false -// is returned. -template -bit8 Dictionary::iterate(INOUT int &index,INOUT int &offset, - OUT V &value) RO -{ - DNode *temp; - - // index out of range - if ((index<0)||(index >= (int)getSize())) - return(FALSE); - - temp=table[index]; - while ((temp==NULL)&&((++index) < (int)getSize())) - { - temp=table[index]; - offset=0; - } - - if (temp==NULL) // no more slots with data - return(FALSE); - - uint32 i=0; - while ((temp!=NULL) && ((int)i < offset)) - { - temp=temp->hashNext; - i++; - } - - if (temp==NULL) // should never happen - return(FALSE); - - value=temp->value; - if (temp->hashNext==NULL) - { - index++; - offset=0; - } - else - offset++; - - return(TRUE); -} - - - - -// -// Iterate through all the records. Index is for the table, offset specifies the -// element in the linked list. Set both to 0 and continue calling till false -// is returned. -template -bit8 Dictionary::iterate(INOUT int &index,INOUT int &offset, - OUT K &key, OUT V &value) RO -{ - DNode *temp; - - // index out of range - if ((index<0)||(index >= (int)getSize())) - return(FALSE); - - temp=table[index]; - while ((temp==NULL)&&((++index) < (int)getSize())) - { - temp=table[index]; - offset=0; - } - - if (temp==NULL) // no more slots with data - return(FALSE); - - uint32 i=0; - while ((temp!=NULL) && ((int)i < offset)) - { - temp=temp->hashNext; - i++; - } - - if (temp==NULL) // should never happen - return(FALSE); - - value=temp->value; - key=temp->key; - if (temp->hashNext==NULL) - { - index++; - offset=0; - } - else - offset++; - - return(TRUE); -} - - - - -// Return the current size of the hash table -template -uint32 Dictionary::getSize(void) RO -{ return(size); } - - -// Return the current number of entries in the table -template -uint32 Dictionary::getEntries(void) RO -{ return(entries); } - - -// Does the Dictionary contain the key? -template -bit8 Dictionary::contains(IN K &key) RO -{ - int offset; - DNode *node; - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - { return(FALSE); } // can't find it - - while(node!=NULL) - { - if ((node->key)==key) - { return(TRUE); } - node=node->hashNext; - } - return(FALSE); -} - - -// Try and update the value of an already existing object -template -bit8 Dictionary::updateValue(IN K &key,IN V &value) -{ - sint32 retval; - - retval=remove(key); - if (retval==FALSE) - return(FALSE); - - add(key,value); - return(TRUE); -} - - -// Add to the dictionary (if key exists, value is updated with the new V) -template -bit8 Dictionary::add(IN K &key,IN V &value) -{ - int offset; - DNode *node,*item,*temp; - float percent; - - item=(DNode *)new DNode; - assert(item!=NULL); - - #ifdef KEY_MEM_OPS - memcpy(&(item->key),&key,sizeof(K)); - #else - item->key=key; - #endif - - #ifdef VALUE_MEM_OPS - memcpy(&(item->value),&value,sizeof(V)); - #else - item->value=value; - #endif - - item->hashNext=NULL; - - //If key already exists, it will be overwritten - remove(key); // Hopefully this will be false... - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - { table[offset]=item; } - else - { - temp=table[offset]; - table[offset]=item; - item->hashNext=temp; - } - - entries++; - percent=(float)entries; - percent/=(float)getSize(); - if (percent>= EXPAND_THRESHOLD ) expand(); - - return(TRUE); -} - -// Remove an item from the dictionary -template -bit8 Dictionary::remove(IN K &key,OUT V &value) -{ - int offset; - DNode *node,*last,*temp; - float percent; - - if (entries==0) - return(FALSE); - - percent=(float)(entries-1); - percent/=(float)getSize(); - - offset=keyHash(key); - node=table[offset]; - - last=node; - if (node==NULL) - return(FALSE); - - //special case table points to thing to delete - - #ifdef KEY_MEM_OPS - if (0==memcmp(&(node->key),&key,sizeof(K))) - #else - if ((node->key)==key) - #endif - { - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - temp=table[offset]->hashNext; - delete(table[offset]); - table[offset]=temp; - entries--; - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); - } - node=node->hashNext; - - bit8 retval=FALSE; // wow, didn't add this for years... (DOH!) - - //Now the case if the thing to delete is not the first - while (node!=NULL) - { - #ifdef KEY_MEM_OPS - if (0==memcmp(&(node->key),&key,sizeof(K))) - #else - if (node->key==key) - #endif - { - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - last->hashNext=node->hashNext; - entries--; - delete(node); - retval=TRUE; // yes, we deleted something - break; - } - last=node; - node=node->hashNext; - } - - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(retval); -} - - -template -bit8 Dictionary::remove(IN K &key) -{ - V temp; - return(remove(key,temp)); -} - - -// Remove some random K/V pair that's in the Dictionary -template -bit8 Dictionary::removeAny(OUT K &key,OUT V &value) -{ - int offset; - DNode *node,*last,*temp; - float percent; - - if (entries==0) - return(FALSE); - - percent=(entries-1); - percent/=(float)getSize(); - - int i; - offset=-1; - for (i=0; i<(int)getSize(); i++) - if (table[i]!=NULL) - { - offset=i; - break; - } - - if (offset==-1) // Nothing there - return(FALSE); - - node=table[offset]; - last=node; - - #ifdef KEY_MEM_OPS - memcpy(&key,&(node->key),sizeof(K)); - #else - key=node->key; - #endif - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - - temp=table[offset]->hashNext; - delete(table[offset]); - table[offset]=temp; - entries--; - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); -} - - -template -bool Dictionary::getValue(IN K &key,OUT V &value) RO -{ - V *valptr=NULL; - bool retval=getPointer(key,&valptr); - if (retval && valptr) - { - #ifdef VALUE_MEM_OPS - assert(0); - #else - value=*valptr; - #endif - } - return(retval); -} - -// Try and avoid this since you're getting a pointer to the internally -// managed data! -template -bool Dictionary::getPointer(IN K &key,OUT V **valptr) RO -{ - int offset; - DNode *node; - - if (entries==0) - return(FALSE); - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - return(FALSE); - - #ifdef KEY_MEM_OPS - while ((node!=NULL)&&(memcmp(&(node->key),&key,sizeof(K)))) - #else - while ((node!=NULL)&&( ! ((node->key)==key)) ) // odd syntax so you don't - #endif // have to do oper != - { node=node->hashNext; } - - if (node==NULL) - { return(FALSE); } - - *valptr=&(node->value); - - return(TRUE); -} - - -//A note about Shrink and Expand: They are never necessary, they are -//only here to improve performance of the hash table by reducing -//the length of the linked list at each table entry. - -// Shrink the hash table by a factor of 2 (and relocate entries) -template -void Dictionary::shrink(void) -{ - int i; - int oldsize; - uint32 offset; - DNode **oldtable,*temp,*first,*next; - - if ((size<=(uint32)MIN_TABLE_SIZE)||(keepSize==TRUE)) - return; - - //fprintf(stderr,"Shrinking....\n"); - - oldtable=table; - oldsize=size; - size/=2; - tableBits--; - - table=(DNode **)new DNode*[size]; - assert(table!=NULL); - memset((void *)table,0,size*sizeof(void *)); - - for (i=0; ikey); - first=table[offset]; - table[offset]=temp; - next=temp->hashNext; - temp->hashNext=first; - temp=next; - } - } - delete[](oldtable); -} - - -template -void Dictionary::expand(void) -{ - int i; - int oldsize; - uint32 offset; - DNode **oldtable,*temp,*first,*next; - - if (keepSize==TRUE) - return; - - //fprintf(stderr,"Expanding...\n"); - - oldtable=table; - oldsize=size; - size*=2; - tableBits++; - - table=(DNode **)new DNode* [size]; - assert(table!=NULL); - memset((void *)table,0,size*sizeof(void *)); - - for (i=0; ikey); - first=table[offset]; - table[offset]=temp; - next=temp->hashNext; - temp->hashNext=first; - temp=next; - } - } - delete[](oldtable); -} - - -#endif - diff --git a/Generals/Code/Tools/mangler/wlib/filed.h b/Generals/Code/Tools/mangler/wlib/filed.h deleted file mode 100644 index ac68d7c705..0000000000 --- a/Generals/Code/Tools/mangler/wlib/filed.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef FILED_HEADER -#define FILED_HEADER - -#include "odevice.h" - -class FileD : public OutputDevice -{ - public: - FileD(IN char *filename, IN char *mode = "w") - { - out=fopen(filename,mode); - if (out==NULL) - out=fopen("FileDev.out",mode); - } - - virtual ~FileD() - { fclose(out); } - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - fprintf(out,"%s",string); - delete[](string); - fflush(out); - return(len); - } - - FILE *out; -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/linkedlist.h b/Generals/Code/Tools/mangler/wlib/linkedlist.h deleted file mode 100644 index d546d3e96c..0000000000 --- a/Generals/Code/Tools/mangler/wlib/linkedlist.h +++ /dev/null @@ -1,495 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: -File Name : linkedlist.h -Author : Neal Kettler -Start Date : June 19, 1997 -Last Update : June 19, 1997 - -Linked list template. This is a fairly standard doubly linked list that -allows insertion and removal at any point in the list. A current pointer -is used to quickly access items when they are examined sequentially. -Copies of the data are stored instead of a pointer to the original. - -If you want to store pointers then the template should be of a pointer type. -\****************************************************************************/ - -#ifndef LINKEDLIST_HEADER -#define LINKEDLIST_HEADER - -#include -#include -#include -#include - -#include "wstypes.h" - -template -class LNode -{ - public: - T Node; - LNode *Next; - LNode *Prev; -}; - -template -class LinkedList -{ - public: - LinkedList(); - LinkedList(LinkedList &other); - ~LinkedList(); - - // Remove all entries from the lsit - void clear(void); - - // Add a node after the zero based 'pos' - bit8 add(IN T &node,sint32 pos, OUT T **newnodeptr=NULL); - bit8 addTail(IN T &node, OUT T **newnodeptr=NULL); - bit8 addHead(IN T &node, OUT T **newnodeptr=NULL); - - // Remove a node - bit8 remove(OUT T &node,sint32 pos); - bit8 remove(sint32 pos); - bit8 removeHead(OUT T &node); - bit8 removeTail(OUT T &node); - - - // Get a node without removing from the list - bit8 get(OUT T &node,sint32 pos); - bit8 getHead(OUT T &node); - bit8 getTail(OUT T &node); - - // Get a pointer to the internally managed data (careful!) - bit8 getPointer(OUT T **node, sint32 pos); - - // Get the number of entries in the list - sint32 length(void); - - // Print information on the list - void print(IN FILE *out); - - // assignment operator - LinkedList &operator=(LinkedList &other); - - private: - sint32 Entries; // Number of entries - LNode *Head; // Head of the list - LNode *Tail; // Tail of the list - - LNode *Current; // Current pointer & index for speed only - sint32 CurIndex; -}; - - -//Create the empty list -template -LinkedList::LinkedList() -{ - Entries=0; - Head=Tail=Current=NULL; - CurIndex=-1; // Not valid when 0 entries -} - -// copy constructor -template -LinkedList::LinkedList(LinkedList &other) -{ - Entries=0; - Head=Tail=Current=NULL; - CurIndex=-1; // Not valid when 0 entries - (*this)=other; -} - -//Free all the memory... -template -LinkedList::~LinkedList() -{ - clear(); // Remove the entries -} - -// assignment operator -template -LinkedList &LinkedList::operator=(LinkedList &other) -{ - T node; - clear(); - for (int i=0; i -void LinkedList::clear() -{ - LNode *temp,*del; - - temp=Head; - while (temp) { - del=temp; - temp=temp->Next; - delete(del); - } - Entries=0; - CurIndex=-1; - Head=Tail=Current=NULL; -} - -// When adding into a position, the new node goes at the zero based slot -// specified by pos. All other nodes get moved one slot down. -template -bit8 LinkedList::add(IN T &node,sint32 pos, OUT T **newnodeptr) -{ - LNode *temp; - LNode *item; - - if (pos<0) - pos=0; - if (pos>Entries) - pos=Entries; - - item=(LNode *)new LNode; - assert(item!=NULL); - item->Node=node; // copy the passed in object - item->Prev=NULL; - item->Next=NULL; - - if (newnodeptr) - *newnodeptr=&(item->Node); - - if ((pos==0)||(pos==Entries)) { // Both cases can be true for a new list! - if (pos==0) { - item->Next=Head; - if (Head) - Head->Prev=item; - Head=item; - } - if (pos==Entries) { - item->Prev=Tail; - if (Tail) - Tail->Next=item; - Tail=item; - } - Entries++; - Current=item; - CurIndex=pos; - return(TRUE); - } - - // If control is here, we know the new node is not an endpoint - - // Check for possible speedup, so we don't have to scan the list - if (pos==CurIndex) { - item->Next=Current; - item->Prev=Current->Prev; - Current->Prev=item; - item->Prev->Next=item; - Current=item; - Entries++; - return(TRUE); - } - // Check the other possible speedup (adding after CurIndex) - if (pos==CurIndex+1) { - item->Next=Current->Next; - item->Prev=Current; - Current->Next=item; - item->Next->Prev=item; - Current=item; - CurIndex++; - Entries++; - return(TRUE); - } - - // If control reaches here we have to scan the whole thing - temp=Head->Next; // Can start at node '1' because head was special cased - for (int i=1; iNext; - assert(temp!=NULL); - } - item->Next=temp; - item->Prev=temp->Prev; - temp->Prev=item; - item->Prev->Next=item; - Current=item; - CurIndex=pos; - Entries++; - - return(TRUE); -} - - -// Add to the first node, all others get shifted down one slot -template -bit8 LinkedList::addHead(IN T &node, OUT T **newnodeptr) -{ - return(add(node,0,newnodeptr)); -} - - -// Append to the end of the list -template -bit8 LinkedList::addTail(IN T &node, OUT T **newnodeptr) -{ - return(add(node,length(),newnodeptr)); -} - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 LinkedList::remove(OUT T &node, sint32 pos) -{ - ////////LNode *temp; - LNode *item; - - if (Entries==0) - return(FALSE); - - if (pos<0) - pos=0; - if (pos>=Entries) - pos=Entries-1; - - if ((pos==0)||(pos==Entries-1)) { // Both can be true for a 1 item list - if (pos==0) { - item=Head; - if (item->Next) - item->Next->Prev=NULL; - Head=item->Next; - node=item->Node; - Current=Head; - CurIndex=0; - } - if (pos==Entries-1) { - item=Tail; - if (item->Prev) - item->Prev->Next=NULL; - Tail=item->Prev; - node=item->Node; - Current=Tail; - CurIndex=Entries-2; - } - delete(item); - Entries--; - - if (Entries==0) { // Super paranoia check - assert(Current==NULL); - assert(CurIndex==-1); - assert(Head==NULL); - assert(Tail==NULL); - } - return(TRUE); - } - // If control is here, we know the target node is not an endpoint - - // Check for possible speedup, so we don't have to scan the list - if (pos==CurIndex) { - item=Current; - item->Prev->Next=item->Next; - item->Next->Prev=item->Prev; - Current=item->Next; - // CurIndex stays the same - node=item->Node; - delete(item); - Entries--; - return(TRUE); - } - - // Check the other possible speedup (removing after CurIndex) - if (pos==CurIndex+1) { - item=Current->Next; - item->Prev->Next=item->Next; - item->Next->Prev=item->Prev; - Current=item->Next; - CurIndex++; - node=item->Node; - delete(item); - Entries--; - return(TRUE); - } - - - // If control reaches here we have to scan the whole thing - item=Head->Next; // Can start at node '1' because head was special cased - for (int i=1; iNext; - assert(item!=NULL); - } - - item->Prev->Next=item->Next; - item->Next->Prev=item->Prev; - Current=item->Next; - CurIndex=pos; - node=item->Node; - delete(item); - Entries--; - - return(TRUE); -} - - - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 LinkedList::remove(sint32 pos) -{ - T temp_node; - return(remove(temp_node,pos)); -} - - -// Remove the first node of the list -template -bit8 LinkedList::removeHead(OUT T &node) -{ - return(remove(node,0)); -} - - -// Remove the last node of the list -template -bit8 LinkedList::removeTail(OUT T &node) -{ - return(remove(node,Entries-1)); -} - - - -template -bit8 LinkedList::get(OUT T &node, sint32 pos) -{ - T *objptr; - bool retval=getPointer(&objptr,pos); - if (retval && objptr) - node=*objptr; - - return(retval); -} - - -template -bit8 LinkedList::getPointer(OUT T **node,sint32 pos) -{ - if ((node==0)||(Entries==0)) - return(FALSE); - - LNode *item; - - if (pos<0) - { - //pos=0; - return(FALSE); - } - if (pos>=Entries) - { - //pos=Entries-1; - return(FALSE); - } - - if (pos==0) { - *node=&(Head->Node); - return(TRUE); - } else if (pos==Entries-1) { - *node=&(Tail->Node); - return(TRUE); - } - // If control reaches here, we know target is not an endpoint - - // Check for possible speedup, so we don't have to scan the list - if (pos==CurIndex) { - *node=&(Current->Node); - return(TRUE); - } else if (pos==CurIndex+1) { - *node=&(Current->Next->Node); - CurIndex++; - Current=Current->Next; - return(TRUE); - } else if (pos==CurIndex-1) { - *node=&(Current->Prev->Node); - CurIndex--; - Current=Current->Prev; - return(TRUE); - } - - // If control reaches here we have to scan the whole thing - item=Head->Next; // Can start at node '1' because head was special cased - for (int i=1; iNext; - assert(item!=NULL); - } - *node=&(item->Node); - CurIndex=pos; - Current=item; - - return(TRUE); -} - - -// Remove the first node of the list -template -bit8 LinkedList::getHead(OUT T &node) -{ - return(get(node,0)); -} - - -// Remove the last node of the list -template -bit8 LinkedList::getTail(OUT T &node) -{ - return(get(node,Entries-1)); -} - - -template -void LinkedList::print(IN FILE *out) -{ - LNode *temp; - - fprintf(out,"--------------------\n"); - fprintf(out,"Entries = %d\n",length()); - fprintf(out,"H = %8p C = %8p (%d) T = %8p\n",Head,Current,CurIndex,Tail); - - temp=Head; - while (temp) { - fprintf(out," %8p<-((%8p))->%8p \n",temp->Prev,temp,temp->Next); - temp=temp->Next; - } - - fprintf(out,"--------------------\n"); -} - -// Return the current length of the list -template -sint32 LinkedList::length(void) { - return(Entries); -} - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/mboxd.h b/Generals/Code/Tools/mangler/wlib/mboxd.h deleted file mode 100644 index 4bd1e7f121..0000000000 --- a/Generals/Code/Tools/mangler/wlib/mboxd.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef MBOXD_HEADER -#define MBOXD_HEADER - -#include "odevice.h" - -class MboxD : public OutputDevice -{ - public: - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - MessageBox(NULL,string,"Debug Message", MB_OK | MB_ICONINFORMATION); - delete[](string); - return(len); - } - -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/monod.cpp b/Generals/Code/Tools/mangler/wlib/monod.cpp deleted file mode 100644 index 5448e627f1..0000000000 --- a/Generals/Code/Tools/mangler/wlib/monod.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "monod.h" - -MonoD::MonoD(void) -{ -#ifdef _WIN32 - unsigned long retval; - handle = CreateFile("\\\\.\\MONO", GENERIC_READ|GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - if (handle != INVALID_HANDLE_VALUE) - { - DeviceIoControl(handle, (DWORD)IOCTL_MONO_CLEAR_SCREEN, NULL, 0, NULL, 0, - &retval,0); - } -#endif -} - -MonoD::~MonoD() -{ - #ifdef _WIN32 - CloseHandle(handle); - handle=NULL; - #endif -} - -int MonoD::print(const char *str, int len) -{ - #ifdef _WIN32 - unsigned long retval; - WriteFile(handle, str, len, &retval, NULL); - ////DeviceIoControl(handle, (DWORD)IOCTL_MONO_PRINT_RAW, (void *)str, len, NULL, 0, - //// &retval,0); - return(len); - #else - for (int i=0; i. -*/ - -#ifndef MONOD_HEADER -#define MONOD_HEADER - - -#include -#include -#include "odevice.h" - -///////////////////////// WIN32 ONLY /////////////////////////////////// - -#ifdef _WIN32 -#include -#include - - -/* -** This is the identifier for the Monochrome Display Driver -*/ -#define FILE_DEVICE_MONO 0x00008000 - -/* -** These are the IOCTL commands supported by the Monochrome Display Driver. -*/ -#define IOCTL_MONO_HELP_SCREEN CTL_CODE(FILE_DEVICE_MONO, 0x800, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_CLEAR_SCREEN CTL_CODE(FILE_DEVICE_MONO, 0x801, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_PRINT_RAW CTL_CODE(FILE_DEVICE_MONO, 0x802, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_CURSOR CTL_CODE(FILE_DEVICE_MONO, 0x803, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SCROLL CTL_CODE(FILE_DEVICE_MONO, 0x804, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_BRING_TO_TOP CTL_CODE(FILE_DEVICE_MONO, 0x805, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_ATTRIBUTE CTL_CODE(FILE_DEVICE_MONO, 0x806, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_PAN CTL_CODE(FILE_DEVICE_MONO, 0x807, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_LOCK CTL_CODE(FILE_DEVICE_MONO, 0x808, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_UNLOCK CTL_CODE(FILE_DEVICE_MONO, 0x809, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_WINDOW CTL_CODE(FILE_DEVICE_MONO, 0x80A, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_RESET_WINDOW CTL_CODE(FILE_DEVICE_MONO, 0x80B, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_FLAG CTL_CODE(FILE_DEVICE_MONO, 0x80C, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_CLEAR_FLAG CTL_CODE(FILE_DEVICE_MONO, 0x80D, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_FILL_ATTRIB CTL_CODE(FILE_DEVICE_MONO, 0x80E, METHOD_BUFFERED, FILE_WRITE_DATA) - -#endif // ifdef _WIN32 - -class MonoD : public OutputDevice -{ - public: - MonoD(); - ~MonoD(); - - virtual int print(const char *str,int len); - - private: - #ifdef _WIN32 - HANDLE handle; - #endif -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/odevice.h b/Generals/Code/Tools/mangler/wlib/odevice.h deleted file mode 100644 index f04bffaec1..0000000000 --- a/Generals/Code/Tools/mangler/wlib/odevice.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef ODEVICE_HEADER -#define ODEVICE_HEADER - -// This virtual base class provides an interface for output devices -// that can be used for the debugging package. -class OutputDevice -{ - public: - OutputDevice() {} - virtual ~OutputDevice() {}; - virtual int print(const char *s,int len)=0; -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/sem4.cpp b/Generals/Code/Tools/mangler/wlib/sem4.cpp deleted file mode 100644 index 9c7f7e42a1..0000000000 --- a/Generals/Code/Tools/mangler/wlib/sem4.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/******************************************************************************\ -sem4.cpp Neal Kettler - -Simple Posix semaphore class -This is useful because the constructor will automatically call sem_init - and you don't have to worry about it. It also allows for other semaphore - libraries if you don't have posix. -\******************************************************************************/ - -#include "sem4.h" - -#ifdef _REENTRANT - -Sem4::Sem4() -{ -#ifndef _WINDOWS - sem_init(&sem,1,1); -#else - sem = CreateSemaphore(NULL, 1, 1, NULL); -#endif -} - -Sem4::Sem4(uint32 value) -{ -#ifndef _WINDOWS - sem_init(&sem,1,value); -#else - sem = CreateSemaphore(NULL, value, value, NULL); -#endif -} - -Sem4::~Sem4() -{ -#ifndef _WINDOWS - sem_destroy(&sem); -#else - if (sem) CloseHandle(sem); -#endif -} - -sint32 Sem4::Wait(void) const -{ -#ifndef _WINDOWS - return(sem_wait((sem_t *)&sem)); -#else - if (!sem) - return -1; // no semaphore! - - DWORD dwWaitResult = WaitForSingleObject(sem, INFINITE); - switch (dwWaitResult) { - case WAIT_OBJECT_0: // The semaphore object was signaled. - return 0; - break; - case WAIT_TIMEOUT: // Should not happen ;) - return -1; - break; - } - return -1; -#endif -} - -sint32 Sem4::Post(void) const -{ -#ifndef _WINDOWS - return(sem_post((sem_t *)&sem)); -#else - if (!sem) - return -1; - if (!ReleaseSemaphore(sem, 1 ,NULL)) - return -1; - return 0; -#endif -} - -sint32 Sem4::TryWait(void) const -{ -#ifndef _WINDOWS - return(sem_trywait((sem_t *)&sem)); -#else - if (!sem) - return -1; - DWORD dwWaitResult = WaitForSingleObject(sem, 0L); - switch (dwWaitResult) { - case WAIT_OBJECT_0: // The semaphore object was signaled. - return 0; - break; - case WAIT_TIMEOUT: - return -1; - break; - } - return -1; -#endif -} - -sint32 Sem4::GetValue(int *sval) const -{ -#ifndef _WINDOWS - return(sem_getvalue((sem_t *)&sem,sval)); -#else - if (!sem) - return -1; - long prev; - if (!ReleaseSemaphore(sem, 0, &prev)) - return -1; - if (sval) - *sval = prev; - return 0; -#endif -} - -sint32 Sem4::Destroy(void) -{ -#ifndef _WINDOWS - return(sem_destroy(&sem)); -#else - return CloseHandle(sem); -#endif -} - -#else - -/**************************************************************************** -non threaded versions that do nothing -*****************************************************************************/ - -Sem4::Sem4() -{ -} - -Sem4::Sem4(uint32) -{ -} - -Sem4::~Sem4() -{ -} - -sint32 Sem4::Wait(void) const -{ - return(0); -} - -sint32 Sem4::Post(void) const -{ - return(0); -} - -sint32 Sem4::TryWait(void) const -{ - return(0); -} - -sint32 Sem4::GetValue(int *) const -{ - return(0); -} - -sint32 Sem4::Destroy(void) -{ - return(0); -} - -#endif - diff --git a/Generals/Code/Tools/mangler/wlib/sem4.h b/Generals/Code/Tools/mangler/wlib/sem4.h deleted file mode 100644 index c96f2f7b78..0000000000 --- a/Generals/Code/Tools/mangler/wlib/sem4.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef SEM4_HEADER -#define SEM4_HEADER - -#include -#ifndef _WINDOWS -#include -#endif -#include "wstypes.h" - -#ifdef _REENTRANT -#ifndef _WINDOWS -#include -#else -#include -#endif // _WINDOWS -#endif // _REENTRANT - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -class Sem4 -{ - private: - #ifdef _REENTRANT -#ifndef _WINDOWS - sem_t sem; -#else - HANDLE sem; -#endif - #endif - public: - Sem4(); - Sem4(uint32 value); - ~Sem4(); - - sint32 Wait(void) const; - sint32 TryWait(void) const; - sint32 Post(void) const; - sint32 GetValue(int *sval) const; - sint32 Destroy(void); -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/stderrd.h b/Generals/Code/Tools/mangler/wlib/stderrd.h deleted file mode 100644 index 4559bea747..0000000000 --- a/Generals/Code/Tools/mangler/wlib/stderrd.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STDERRD_HEADER -#define STDERRD_HEADER - -#include "odevice.h" - -class StderrD : public OutputDevice -{ - public: - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - fprintf(stderr,"%s",string); - delete[](string); - return(len); - } -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/stdoutd.h b/Generals/Code/Tools/mangler/wlib/stdoutd.h deleted file mode 100644 index a3d20fc3c5..0000000000 --- a/Generals/Code/Tools/mangler/wlib/stdoutd.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STDOUTD_HEADER -#define STDOUTD_HEADER - -#include "odevice.h" - -class StdoutD : public OutputDevice -{ - public: - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memcpy(string,str,len); - string[len]=0; - fprintf(stdout,"%s",string); - fflush(stdout); - delete[](string); - return(len); - } -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/streamer.cpp b/Generals/Code/Tools/mangler/wlib/streamer.cpp deleted file mode 100644 index b8a8eca1c1..0000000000 --- a/Generals/Code/Tools/mangler/wlib/streamer.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "streamer.h" -#ifdef _WIN32 - #include -#endif - -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) -#define STREAMER_UNBUFFERED unbuffered() -#else -#define STREAMER_UNBUFFERED 0 -#endif - -Streamer::Streamer() : streambuf(), Output_Device(NULL), Buf(NULL) -{ -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) - int state=unbuffered(); - unbuffered(0); // 0 = buffered, 1 = unbuffered -#else - static_assert(STREAMER_UNBUFFERED==0, "std::streambuf is assumed to be buffered by default"); -#endif -} - -Streamer::~Streamer() -{ - ///////// calling sync seems to cause crashes here on Win32 - //sync(); - ///////// - if (Buf) - delete[] Buf; -} - -int Streamer::setOutputDevice(OutputDevice *device) -{ - Output_Device=device; - return(0); -} - - -// put n chars from string into buffer -int Streamer::xsputn(const char* buf, int size) //implementation of sputn -{ - if (size<=0) // Nothing to do - return(0); - - const unsigned char *ptr=(const unsigned char *)buf; - for (int i=0; i= epptr()) && (sync()==EOF)) - return(EOF); - else { - sputc(c); - if ((STREAMER_UNBUFFERED && c=='\n' || pptr() >= epptr()) - && sync()==EOF) { - return(EOF); - } - return(c); - } -} - -// This is a write only stream, this should never happen -int Streamer::underflow(void) -{ - return(EOF); -} - -int Streamer::doallocate() -{ - if (Buf==NULL) - { - Buf=new char[(2*STREAMER_BUFSIZ)]; // deleted by destructor - memset(Buf,0,2*STREAMER_BUFSIZ); - - // Buffer -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) - setb( - Buf, // base pointer - Buf+STREAMER_BUFSIZ, // ebuf pointer (end of buffer); - 0); // 0 = manual deletion of buff -#else - pubsetbuf(Buf, 2*STREAMER_BUFSIZ); -#endif - - // Get area - setg( - Buf, // eback - Buf, // gptr - Buf); // egptr - - Buf+=STREAMER_BUFSIZ; - // Put area - setp(Buf,Buf+STREAMER_BUFSIZ); - return(1); - } - else - return(0); -} - - -int Streamer::sync() -{ - if (pptr()<=pbase()) { - return(0); - } - - int wlen=pptr()-pbase(); - - if (Output_Device) - { - Output_Device->print(pbase(),wlen); - } - - if (STREAMER_UNBUFFERED) { - setp(pbase(),pbase()); - } - else { - setp(pbase(),pbase()+STREAMER_BUFSIZ); - } - return(0); -} diff --git a/Generals/Code/Tools/mangler/wlib/streamer.h b/Generals/Code/Tools/mangler/wlib/streamer.h deleted file mode 100644 index 8dce9298f9..0000000000 --- a/Generals/Code/Tools/mangler/wlib/streamer.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STREAMER_HEADER -#define STREAMER_HEADER - -#include -#include -#include -#include -#include - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#include "odevice.h" - -#ifndef STREAMER_BUFSIZ -// This limits the number of characters that can be sent to a single 'print' -// call. If your debug message is bigger than this, it will get split over -// multiple 'print' calls. That's usually not a problem. - #define STREAMER_BUFSIZ 2048 -#endif - - -// Provide a streambuf interface for a class that can 'print' -class Streamer : public streambuf -{ - public: - Streamer(); - virtual ~Streamer(); - - int setOutputDevice(OutputDevice *output_device); - - protected: - // Virtual methods from streambuf - int xsputn(const char* s, int n); // buffer some characters - int overflow(int = EOF); // flush buffer and make more room - int underflow(void); // Does nothing - int sync(); - - int doallocate(); // allocate a buffer - - - OutputDevice *Output_Device; - char* Buf; -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/syslogd.cpp b/Generals/Code/Tools/mangler/wlib/syslogd.cpp deleted file mode 100644 index 7568868b24..0000000000 --- a/Generals/Code/Tools/mangler/wlib/syslogd.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "syslogd.h" - -SyslogD::SyslogD(char *ident,int logopt,int facility,int _priority) -{ -#ifndef _WINDOWS - openlog(ident,logopt,facility); - priority=_priority; -#endif -} - -int SyslogD::print(const char *str, int len) -{ -#ifndef _WINDOWS - char *temp_str=new char[len+1]; - memset(temp_str,0,len+1); - strncpy(temp_str,str,len); - syslog(priority,temp_str); - delete[](temp_str); -#endif - return(len); -} diff --git a/Generals/Code/Tools/mangler/wlib/threadfac.cpp b/Generals/Code/Tools/mangler/wlib/threadfac.cpp deleted file mode 100644 index 0f42558536..0000000000 --- a/Generals/Code/Tools/mangler/wlib/threadfac.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#define THREADFAC_CODE - -#include "threadfac.h" - -int Runnable::ThreadCount_ = 0; -CritSec Runnable::CritSec_; // to protect ThreadCount_ - -// MDC: Made all this dependent on _REENTRANT being defined so VC++ doesn't complain on -// single-threaded programs... - - -// -// Note: I chose the following type signature for thread functions -// void function(void *data); -// -// -// Since Win32 & POSIX have different type signatures for the thread entry points -// an intermediate system-dependent function in this file gets called first. -// That function then calls the system independent version. So the system dependent -// version needs 2 Items 1) The address of the _real_ thread func 2) the data -// to pass. We only have 1 argument available, so you figure out the rest... -// -// This is for internal use only -// -struct ThreadInformation -{ - void *startPoint; // The address of the _real_ thread function, or class - void *data; // data to pass to real thread function or class - bit8 destroy; // only applies to classes, should delete after execution? -}; - - - -// -// Start a thread inside a class -// -bit8 ThreadFactory::startThread(Runnable &runable, void *data, bit8 destroy) -{ -#ifdef _REENTRANT - - { - Runnable::CritSec_.lock(); - Runnable::ThreadCount_++; - Runnable::CritSec_.unlock(); - } - - - ThreadInformation *tInfo=new ThreadInformation; - tInfo->startPoint=(void *)&runable; - tInfo->data=data; - tInfo->destroy=destroy; - - #ifdef _WIN32 - // Under windows call _beginthreadex instead of CreateThread so you can - // use all the normal C library stuff. (IMPORTANT!!!) - uint32 handle; - uint32 stup1d; - handle=_beginthreadex(NULL,0, threadClassLauncher, tInfo, 0, &stup1d); - if (handle!=NULL) - return(TRUE); - else - { - { - runable.CritSec_.lock(); - runable.ThreadCount_--; // Ok, so it didn't really start - runable.CritSec_.unlock(); - } - return(FALSE); - } - #else // UNIX - // Setup thread attributes for client threads - int retval; - pthread_attr_t threadAttr; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED); - pthread_attr_setscope(&threadAttr,PTHREAD_SCOPE_SYSTEM); - retval=pthread_create(NULL,&threadAttr, threadClassLauncher, tInfo); - if (retval==0) - return(TRUE); - else - { - { - runable.CritSec_.lock(); - runable.ThreadCount_--; // Ok, so it didn't really start - runable.CritSec_.unlock(); - } - return(FALSE); - } - #endif -#else - return (FALSE); -#endif /* _REENTRANT */ -} - - -// -// Start a thread inside a function -// -bit8 ThreadFactory::startThread(void (*start_func)(void *), void *data) -{ -#ifdef _REENTRANT - ThreadInformation *tInfo=new ThreadInformation; - tInfo->startPoint=start_func; - tInfo->data=data; - - #ifdef _WIN32 - // Under windows call _beginthreadex instead of CreateThread so you can - // use all the normal C library stuff. (IMPORTANT!!!) - uint32 handle; - unsigned temp; - handle=_beginthreadex(NULL,0, threadFuncLauncher, tInfo, 0, &temp); - if (handle!=NULL) - return(TRUE); - return(FALSE); - #else // UNIX - // Setup thread attributes for client threads - int retval; - pthread_attr_t threadAttr; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED); - pthread_attr_setscope(&threadAttr,PTHREAD_SCOPE_SYSTEM); - retval=pthread_create(NULL,&threadAttr, threadFuncLauncher, tInfo); - if (retval==0) - return(TRUE); - else - return(FALSE); - #endif -#else - return(FALSE); -#endif /* REENTRANT */ -} - -#ifdef _WIN32 - unsigned __stdcall threadFuncLauncher(void *temp) -#else // UNIX - void *threadFuncLauncher(void *temp) -#endif -{ - ThreadInformation *tInfo=(ThreadInformation *)temp; - - void (*start_func)(void *); - start_func=(void (*)(void *))tInfo->startPoint; - - void *data=tInfo->data; - delete(tInfo); - - start_func(data); - return(0); -} - -#ifdef _WIN32 - unsigned __stdcall threadClassLauncher(void *temp) -#else // UNIX - void *threadClassLauncher(void *temp) -#endif -{ - ThreadInformation *tInfo=(ThreadInformation *)temp; - - Runnable *thrClass=(Runnable *)tInfo->startPoint; - void *data=tInfo->data; - bit8 destroy=tInfo->destroy; - delete(tInfo); - - thrClass->run(data); - - if (destroy) // May want to free memory after thread finishes - delete(thrClass); - - { - Runnable::CritSec_.lock(); - Runnable::ThreadCount_--; - Runnable::CritSec_.unlock(); - } - - #ifdef _WIN32 - ExitThread(0); // is this really needed? - #endif - return(0); -} - -Runnable::Runnable() -{ } - -Runnable::~Runnable() -{ } - -// Is there a thread running in this class -bit8 Runnable::isRunning(void) -{ - // Don't need to lock a simple assignment - int temp=ThreadCount_; - return((temp>0)?TRUE:FALSE); -} - -// How many threads are running in this class -int Runnable::getThreadCount(void) -{ - // Don't need to lock a simple assignment - int temp=ThreadCount_; - return(temp); -} - -#undef THREADFAC_CODE diff --git a/Generals/Code/Tools/mangler/wlib/threadfac.h b/Generals/Code/Tools/mangler/wlib/threadfac.h deleted file mode 100644 index a4edbc3680..0000000000 --- a/Generals/Code/Tools/mangler/wlib/threadfac.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Platform independent thread creation (Win32 & POSIX) -// - -#ifndef THREADFAC_HEADER -#define THREADFAC_HEADER - -#ifdef _WIN32 - #include -#endif -#include "wstypes.h" -#include - -#ifdef _WIN32 - #include -#else // UNIX - #include -#endif - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#include "critsec.h" - - - -#ifdef THREADFAC_CODE - // This is the fake thread entry point for functions - #ifdef _WIN32 - static unsigned __stdcall threadFuncLauncher(void *temp); - #else // UNIX - static void *threadFuncLauncher(void *temp); - #endif - - // Fake entry point for classes - #ifdef _WIN32 - static unsigned __stdcall threadClassLauncher(void *temp); - #else // UNIX - static void *threadClassLauncher(void *temp); - #endif -#endif - - - - - -// Forward definition of base class for threaded classes -class Runnable; - -// -// Call the static method startThread to begin a new thread. -// -class ThreadFactory -{ - public: - static bit8 startThread(void (*start_func)(void *), void *data); - static bit8 startThread(Runnable &runable, void *data, bit8 destroy=FALSE); -}; - - - -// -// Base class for when you want a thread to execute inside a class -// instead of a function. -// -class Runnable -{ - public: - Runnable(); - virtual ~Runnable(); - - - // ThreadFactory needs to be able to access the private - // IsRunning_ field. - friend class ThreadFactory; - - // So do the threadClassLaunchers - #ifdef _WIN32 - friend static unsigned __stdcall threadClassLauncher(void *temp); - #else // UNIX - friend void *threadClassLauncher(void *temp); - #endif - - virtual void run(void *data)=0; // Thread entry point - - void startThread(void *data,bit8 destroy=FALSE) // nice way to start a thread - { - ThreadFactory::startThread(*this,data,destroy); - }; - - // Is there a thread running in this class? - static bit8 isRunning(void); - - // Get the count of threads running inside this class - static int getThreadCount(); - - - private: - static int ThreadCount_; - static CritSec CritSec_; // to protect ThreadCount_ -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/threadsafe.h b/Generals/Code/Tools/mangler/wlib/threadsafe.h deleted file mode 100644 index 8a2addac60..0000000000 --- a/Generals/Code/Tools/mangler/wlib/threadsafe.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// threadsafe.h -// -// If you include this file and call non-threadsafe functions, it'll -// prevent your program from compiling. It's meant to be a slap -// on the wrist in case you forget and call an unsafe function -// from a threadsafe program. -// - -// -// Reminder to self - use sigwait, not signal handlers! -// - -#ifdef _REENTRANT - -#ifndef THREADSAFE_HEADER -#define THREADSAFE_HEADER - -#define strtok ("strtok() is not MT-SAFE!") -#define ascctime ("asctime() is not MT-SAFE!") -// Can't just do ctime, as Windows' objidl.h uses it as a FILETIME thingie -#define ctime(x) ("ctime() is not MT-SAFE!") -#define gmtime ("gmtime() is not MT-SAFE!") -#define localtime ("localtime() is not MT-SAFE!") -#define tzset ("tzset() is not MT-SAFE!") -#define tzsetwall ("tzsetwall() is not MT-SAFE!") -#define readdir ("readdir() is not MT-SAFE!") - -#define rand ("rand() is not MT-SAFE!") -#define srand ("srand() is not MT-SAFE!") -#define random ("random() is not MT-SAFE!") -#define srandom ("srandom() is not MT-SAFE!") - -#define tmpnam ("tmpnam() is not MT-SAFE!") -#define vfork ("vfork() is not MT-SAFE!") - -#define system ("system() is not MT-SAFE!") -#define popen ("popen() is not MT-SAFE!") -#define pclose ("pclose() is not MT-SAFE!") -#define ctermid ("ctermid() is not MT-SAFE!") -#define getlogin ("getlogin() is not MT-SAFE!"); - -#endif // THREADSAFE_HEADER -#endif // _REENTRANT diff --git a/Generals/Code/Tools/mangler/wlib/timezone.cpp b/Generals/Code/Tools/mangler/wlib/timezone.cpp deleted file mode 100644 index 6e191ebb17..0000000000 --- a/Generals/Code/Tools/mangler/wlib/timezone.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "wlib/xtime.h" -#include "timezone.h" - -void GetTimezoneInfo(const char * &timezone_str, int &timezone_offset) { - timezone_str = "Unknown Timezone"; - timezone_offset = 0; -#ifdef _WINDOWS - struct _timeb wintime; - _ftime(&wintime); - - if (wintime.dstflag) { - // Daylight savings time - if (_daylight) { - timezone_str = _tzname[1]; - } - } else { - timezone_str = _tzname[0]; - } - timezone_offset = wintime.timezone * 60; // its in minutes... - -#endif -#ifndef _WINDOWS - struct timeval unixtime; - struct timezone unixtzone; - gettimeofday(&unixtime,&unixtzone); - - struct tm unixtm; - localtime_r(&unixtime.tv_sec, &unixtm); - - if (unixtm.tm_isdst) { - // Daylight savings time - if (daylight) timezone_str = tzname[1]; - timezone_offset = altzone; - } else { - timezone_str = tzname[0]; - timezone_offset = timezone; - } -#endif -} - -const char * TimezoneString(void) { - const char *timezone_str; - int timezone_offset; - GetTimezoneInfo(timezone_str, timezone_offset); - return timezone_str; -} - -int TimezoneOffset(void) { - const char *timezone_str; - int timezone_offset; - GetTimezoneInfo(timezone_str, timezone_offset); - return timezone_offset; -} diff --git a/Generals/Code/Tools/mangler/wlib/timezone.h b/Generals/Code/Tools/mangler/wlib/timezone.h deleted file mode 100644 index 95e4c37f38..0000000000 --- a/Generals/Code/Tools/mangler/wlib/timezone.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -timezone Matthew D. Campbell - -This is just a couple of convenience functions for determining what timezone -we are now in. It even accounts for daylight savings! One caveat is that it -only tells you info about what the daylight savings info is now, not 5 minutes -from now, not 2 hours ago. Oh well. -\****************************************************************************/ - -#ifndef _TIMEZONE_H_ -#define _TIMEZONE_H_ - -// Just fill in both the timezone description and its offset from GMT -void GetTimezoneInfo(const char * &timezone_str, int &timezone_offset); - -// Returns the description of the current timezone (daylight savings included) -const char * TimezoneString(void); - -// Returns the offset from GMT of the current timezone -int TimezoneOffset(void); - -#endif // _TIMEZONE_H_ - diff --git a/Generals/Code/Tools/mangler/wlib/ustring.h b/Generals/Code/Tools/mangler/wlib/ustring.h deleted file mode 100644 index 12fee83b68..0000000000 --- a/Generals/Code/Tools/mangler/wlib/ustring.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef USTRING_HEADER -#define USTRING_HEADER - -#include -#include -#include -#include - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#define MAX_BYTES_PER_CHAR 1 - -template -class UstringT : public basic_string > -{ - public: - explicit UstringT(int max_charlength) { - set_max_bytelength(max_charlength*MAX_BYTES_PER_CHAR); - } - - UstringT() { max_bytelength=4000; } - - size_t get_max_bytelength(void) { return(max_bytelength); } - void set_max_bytelength(size_t max) { max_bytelength=max; } - - bool operator==(const UstringT &other) - { - const basic_string > *other_basic=&other; - const basic_string > *this_basic=this; - return((*other_basic)==(*this_basic)); - } - - private: - size_t max_bytelength; -}; - -typedef UstringT Ustring; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/wdebug.cpp b/Generals/Code/Tools/mangler/wlib/wdebug.cpp deleted file mode 100644 index 8e2d14f7e4..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wdebug.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include -#include "wdebug.h" -#include "streamer.h" -#include "odevice.h" - - -static MsgManager *msg_manager=NULL; - -static int debug_enabled=0; -static ostream *debug_ostream=NULL; -static Streamer debug_streamer; - -static int info_enabled=0; -static ostream *info_ostream=NULL; -static Streamer info_streamer; - -static int warn_enabled=0; -static ostream *warn_ostream=NULL; -static Streamer warn_streamer; - -static int error_enabled=0; -static ostream *error_ostream=NULL; -static Streamer error_streamer; - - -// Don't dare touch this semaphore in application code! -#ifdef USE_DEBUG_SEM -Sem4 DebugLibSemaphore; -#else -CritSec DebugLibSemaphore; -#endif - - -int MsgManager::setAllStreams(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - debug_streamer.setOutputDevice(device); - delete(debug_ostream); - debug_ostream=new ostream(&debug_streamer); - - info_streamer.setOutputDevice(device); - delete(info_ostream); - info_ostream=new ostream(&info_streamer); - - warn_streamer.setOutputDevice(device); - delete(warn_ostream); - warn_ostream=new ostream(&warn_streamer); - - error_streamer.setOutputDevice(device); - delete(error_ostream); - error_ostream=new ostream(&error_streamer); - - DEBUGUNLOCK; - - return(0); -} - - -int MsgManager::ReplaceAllStreams(FileD * output_device, IN char *device_filename, IN char *copy_filename) -{ - DebugLibSemaphore.Wait(); - - delete(debug_ostream); - delete(info_ostream); - delete(warn_ostream); - delete(error_ostream); - - if (output_device != NULL) - { - delete(output_device); - output_device = NULL; - } - - rename(device_filename, copy_filename); - -// FileD new_device(device_filename); - output_device = new FileD(device_filename); - - debug_streamer.setOutputDevice(output_device); - debug_ostream = new ostream(&debug_streamer); - - info_streamer.setOutputDevice(output_device); - info_ostream=new ostream(&info_streamer); - - warn_streamer.setOutputDevice(output_device); - warn_ostream = new ostream(&warn_streamer); - - error_streamer.setOutputDevice(output_device); - error_ostream = new ostream(&error_streamer); - - DebugLibSemaphore.Post(); - - return(0); -} - - -int MsgManager::setDebugStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - debug_streamer.setOutputDevice(device); - delete(debug_ostream); - debug_ostream=new ostream(&debug_streamer); - DEBUGUNLOCK; - return(0); -} - -int MsgManager::setInfoStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - info_streamer.setOutputDevice(device); - delete(info_ostream); - info_ostream=new ostream(&info_streamer); - DEBUGUNLOCK; - return(0); -} - -int MsgManager::setWarnStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - warn_streamer.setOutputDevice(device); - delete(warn_ostream); - warn_ostream=new ostream(&warn_streamer); - DEBUGUNLOCK; - return(0); -} - -int MsgManager::setErrorStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - error_streamer.setOutputDevice(device); - delete(error_ostream); - error_ostream=new ostream(&error_streamer); - DEBUGUNLOCK; - return(0); -} - - - -ostream *MsgManager::debugStream(void) -{ - return(debug_ostream); -} - -ostream *MsgManager::infoStream(void) -{ - return(info_ostream); -} - -ostream *MsgManager::warnStream(void) -{ - return(warn_ostream); -} - -ostream *MsgManager::errorStream(void) -{ - return(error_ostream); -} diff --git a/Generals/Code/Tools/mangler/wlib/wdebug.h b/Generals/Code/Tools/mangler/wlib/wdebug.h deleted file mode 100644 index a37c9ee75f..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wdebug.h +++ /dev/null @@ -1,314 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*****************************************************************************\ -wdebug Neal Kettler - -MT-LEVEL - MT-Safe - -The debugging module is pretty good for debugging and it has some message -printing stuff as well. The basic idea is that you write a class that -inherits from OutputDevice (several are provided) and assign that output -device to a stream. There are seperate streams for debugging, information, -warning, and error messages. Each one can have a seperate output device, -or they can all have the same one. Debugging messages only get compiled -in if your module defines 'DEBUG'. If you don't define debug, then not even -the text of the debugging message gets into the binary. All the other -output streams get printed regardless of whether DEBUG is defined. - -Sample usage: -FileD debug_device("gameres.debug"); // create a file device -MsgManager::setDebugStream(&debug_device); -DBGMSG("This debug message #" << 1 << " you use C++ streams"); - -Note that since these are defines you really don't need to put a semicolon -at the end, and it can be bad in situations like this: - -if (x) - DBGMSG("Stuff is broken"); -else - DBGMSG("Stuff is NOT broken"); - -This won't compile, read the code until you figure it out. Only then -will you be ready to leave grasshopper. - -\*****************************************************************************/ - -#ifndef WDEBUG_HEADER -#define WDEBUG_HEADER - -#define USE_DEBUG_SEM - -#include "wstypes.h" - -#include -#include - -#if !defined(_WINDOWS) -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const -#endif - -#ifdef USE_DEBUG_SEM -#include "sem4.h" -#else -#include "critsec.h" -#endif -#include "odevice.h" -#include "streamer.h" -#include "xtime.h" -#include "timezone.h" // MDC -#include "filed.h" - -// This is needed because the streams return a pointer. Every time you -// change the output device the old stream is deleted, and a new one -// is created. -// MDC: Added a macro to switch between semaphores & critsecs to debug a -// problem in Win32. - -#ifdef USE_DEBUG_SEM -extern Sem4 DebugLibSemaphore; -#define DEBUGLOCK DebugLibSemaphore.Wait() -#define DEBUGUNLOCK DebugLibSemaphore.Post() -#else -extern CritSec DebugLibSemaphore; -#define DEBUGLOCK DebugLibSemaphore.lock() -#define DEBUGUNLOCK DebugLibSemaphore.unlock() -#endif - -// Print an information message -#define INFMSG(X)\ -{\ - char timebuf[40]; \ - Xtime now; \ - now -= TimezoneOffset(); \ - now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ - DEBUGLOCK; \ - if (MsgManager::infoStream()) \ - (*(MsgManager::infoStream())) << "INF " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ - DEBUGUNLOCK; \ -} - -// Print a warning message -#define WRNMSG(X)\ -{\ - char timebuf[40]; \ - Xtime now; \ - now -= TimezoneOffset(); \ - now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ - DEBUGLOCK; \ - if (MsgManager::warnStream()) \ - (*(MsgManager::warnStream())) << "WRN " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ - DEBUGUNLOCK; \ -} - -// Print an error message -#define ERRMSG(X)\ -{\ - char timebuf[40]; \ - Xtime now; \ - now -= TimezoneOffset(); \ - now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ - DEBUGLOCK; \ - if (MsgManager::errorStream()) \ - (*(MsgManager::errorStream())) << "ERR " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ - DEBUGUNLOCK; \ -} - - -// Just get a stream to the information device, no extra junk -#define INFSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::infoStream()) \ - (*(MsgManager::infoStream())) << X;\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the warning device, no extra junk -#define WRNSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::warnStream()) \ - (*(MsgManager::warnStream())) << X;\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the error device, no extra junk -#define ERRSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::errorStream()) \ - (*(MsgManager::errorStream())) << X;\ - DEBUGUNLOCK; \ -} - -#ifndef DEBUG - -// No debugging, no debug messages. -// Note that anything enclosed in "DBG()" will NOT get executed -// unless DEBUG is defined. -// They are defined to {} for consistency when DEBUG is defined - -#define DBG(X) -#define DBGSTREAM(X) {} -#define PVAR(v) {} -#define DBGMSG(X) {} -#define VERBOSE(X) {} - -#else // DEBUG _is_ defined - -// Execute only if in debugging mode -#define DBG(X) X - -// In Windows, send a copy to the debugger window -#ifdef _WINDOWS - -// Print a variable -#define PVAR(v) \ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << endl; \ - strstream __s;\ - __s << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << '\n' << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - - -#define DBGMSG(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << endl;\ - strstream __s;\ - __s << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << '\n' << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the debugging device, no extra junk -#define DBGSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << X;\ - strstream __s;\ - __s << X << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - -// Verbosely execute a statement -#define VERBOSE(X)\ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(DebugManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << endl; X \ - strstream __s;\ - __s << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << '\n' << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - -#else // _WINDOWS - -// Print a variable -#define PVAR(v) \ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << endl; \ - DEBUGUNLOCK; \ -} - - -#define DBGMSG(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << endl;\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the debugging device, no extra junk -#define DBGSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << X;\ - DEBUGUNLOCK; \ -} - -// Verbosely execute a statement -#define VERBOSE(X)\ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(DebugManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << endl; X \ - DEBUGUNLOCK; \ -} -#endif // _WINDOWS - -#endif // DEBUG - -//#undef DEBUGLOCK -//#undef DEBUGUNLOCK - -class MsgManager -{ - protected: - MsgManager(); - - public: - static int setAllStreams(OutputDevice *device); - static int ReplaceAllStreams(FileD *output_device, IN char *device_filename, IN char *copy_filename); - static int setDebugStream(OutputDevice *device); - static int setInfoStream(OutputDevice *device); - static int setWarnStream(OutputDevice *device); - static int setErrorStream(OutputDevice *device); - - static void enableDebug(int flag); - static void enableInfo(int flag); - static void enableWarn(int flag); - static void enableError(int flag); - - static ostream *debugStream(void); - static ostream *infoStream(void); - static ostream *warnStream(void); - static ostream *errorStream(void); -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/wstring.cpp b/Generals/Code/Tools/mangler/wlib/wstring.cpp deleted file mode 100644 index e7fa32cff3..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wstring.cpp +++ /dev/null @@ -1,597 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : string.cpp -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 - -A fairly typical string class. This string class always copies any input -string to it's own memory (for assignment or construction). -\***************************************************************************/ - -#include -#include -#include -#include -#include - -#include "wstring.h" - -#define PADSIZE 32 // include a little padding on alloc for future growth - -Wstring::Wstring() : str(NULL), strsize(0) -{ } - -Wstring::Wstring(const char *string):str(NULL), strsize(0) -{ set(string); } - -Wstring::Wstring(const Wstring &other):str(NULL), strsize(0) -{ - if (other.str!=NULL) - { - str=new char[strlen(other.str)+PADSIZE+1]; - strsize=strlen(other.str)+PADSIZE+1; - strcpy(str,other.str); - } -} - -Wstring::~Wstring() -{ - clear(); -} - -bool Wstring::operator<(const Wstring &other) const -{ - if (str == NULL && other.str == NULL) - return false; - - if (str == NULL) - return true; - - return ( strcmp(str, other.str) < 0 ); -} - -bit8 Wstring::operator==(const char *other) const -{ - if ((str==NULL)&&(other==NULL)) - return(TRUE); - if(strcmp(str, other) != 0) - return(FALSE); - else - return(TRUE); -} - -bit8 Wstring::operator==(const Wstring &other) const -{ - if((str == NULL) && (other.str == NULL)) - return(TRUE); - - if((str == NULL) || (other.str == NULL)) - return(FALSE); - - if(strcmp(str, other.str) != 0) - return(FALSE); - else - return(TRUE); -} - - -bit8 Wstring::operator!=(const char *other) const -{ - if(strcmp(str, other) != 0) - return(TRUE); - else - return(FALSE); -} - - -bit8 Wstring::operator!=(const Wstring &other) const -{ - if((str == NULL) && (other.str == NULL)) - return(FALSE); - - if((str == NULL) || (other.str == NULL)) - return(TRUE); - - if(strcmp(str, other.str) != 0) - return(TRUE); - else - return(FALSE); -} - - -Wstring &Wstring::operator=(const char *other) -{ - set(other); - return(*this); -} - - -Wstring &Wstring::operator=(const Wstring &other) -{ - if(*this == other) - return(*this); - - set(other.get()); - return(*this); -} - - -bit8 Wstring::cat(const char *s) -{ - uint32 len; - - if (s==NULL) // it's OK to cat nothing - return(TRUE); - - // Determine the length of the resultant string. - len = strlen(s) + 1; - if(str) - len += strlen(str); - - // Space check - strgrow(len); - - strcat(str, s); - - return(TRUE); -} - - -bit8 Wstring::cat(uint32 size, const char *s) -{ - uint32 len; - - // Determine the length of the resultant string. - len = size + 1; - if(str) - len += strlen(str); - - // Allocate memory for the new string. - strgrow(len); - - strncat(str, s, size); - str[len-1]=0; // make sure null term'd - - return(TRUE); -} - -bit8 Wstring::cat(const Wstring &other) -{ - return cat(other.get()); -} - -Wstring &Wstring::operator+=(const char *string) -{ - cat(string); - return(*this); -} - -Wstring &Wstring::operator+=(const Wstring &other) -{ - cat(other.get()); - return(*this); -} - -Wstring Wstring::operator+(const char *string) -{ - Wstring temp = *this; - temp.cat(string); - return(temp); -} - -Wstring Wstring::operator+(const Wstring &s) -{ - Wstring temp = *this; - temp.cat(s); - return(temp); -} - -// -// This function deletes 'count' characters indexed by `pos' from the Wstring. -// If `pos'+'count' is > the length of the array, the last 'count' characters -// of the string are removed. If an error occurs, FALSE is returned. -// Otherwise, TRUE is returned. Note: count has a default value of 1. -// -// -char Wstring::remove(sint32 pos,sint32 count) -{ - //char *s; - sint32 len; - - len = (sint32)strlen(str); - - if(pos+count > len) - pos = len - count; - if (pos < 0) - { - count+=pos; // If they remove before 0, ignore up till beginning - pos=0; - } - if (count<=0) - return(FALSE); - - memmove(str+pos,str+pos+count,len-pos-count+1); - - return(TRUE); -} - -// Remove all instances of a char from the string -bit8 Wstring::removeChar(char c) -{ - int len=0; - char *cptr=NULL; - bit8 removed=FALSE; - - if (str==NULL) - return(FALSE); - - len=strlen(str); - while ((cptr=strchr(str,c)) !=NULL) - { - memmove(cptr,cptr+1,len-1-((int)(cptr-str))); - len--; - str[len]=0; - removed=TRUE; - } - return(removed); -} - -void Wstring::removeSpaces(void) -{ - removeChar(' '); - removeChar('\t'); -} - -void Wstring::clear(void) -{ - if(str) - delete[](str); - strsize=0; - str=NULL; -} - -// This is usually used for raw storage instead of string ops... -void Wstring::setSize(sint32 size) -{ - clear(); - if (size<0) - return; - - str=new char[size]; - strsize=size; - memset(str,0,size); -} - -void Wstring::cellCopy(char *dest, uint32 len) -{ - uint32 i; - - strncpy(dest, str, len); - for(i = (uint32)strlen(str); i < len; i++) - dest[i] = ' '; - dest[len] = 0; -} - -const char *Wstring::get(void) const -{ - if(!str) - return ""; - return str; -} - -char Wstring::get(uint32 index) const -{ - if(index < strlen(str)) - return str[index]; - return(0); -} - -uint32 Wstring::length(void) const -{ - if(str == NULL) - return(0); - return((uint32)strlen(str)); -} - - -// Insert at given position and shift old stuff to right -bit8 Wstring::insert(const char *instring, uint32 pos) -{ - if (str==NULL) - return(set(instring)); - if (pos>strlen(str)) - pos=strlen(str); - - strgrow(strlen(str)+strlen(instring)+1); - memmove(str+pos+strlen(instring),str+pos,strlen(str)-pos+1); - memmove(str+pos,instring,strlen(instring)); - - return(TRUE); -} - -// This function inserts the character specified by `k' into the string at the -// position indexed by `pos'. If `pos' is >= the length of the string, it is -// appended to the string. If an error occurs, FALSE is returned. Otherwise, -// TRUE is returned. -bit8 Wstring::insert(char k, uint32 pos) -{ - char temp[2]; - temp[0]=k; - temp[1]=0; - return(insert(temp,pos)); -} - - -// Joe Howes (05/19/2000): This function inserts commas to nicely format a -// large number (i.e. 1234567890 -> 1,234,567,890). It doesn't really care -// if the string is really a number or not. -bit8 Wstring::beautifyNumber() -{ - int len = length(); - int accum = 3 - (len % 3); - int numcommas = 0; - - - if( accum == 3 ) accum = -1; - for(int i = 0; i < len; i++) - { - if( accum == 3 ) - { - insert(',', i + numcommas); - numcommas++; - } - accum = ( accum == 3 || accum == -1 ) ? 1 : accum + 1; - } - - return(TRUE); -} - - -// This function replaces any occurences of the string pointed to by -// `replaceThis' with the string pointed to by `withThis'. If an error -// occurs, FALSE is returned. Otherwise, TRUE is returned. -bit8 Wstring::replace(const char *replaceThis,const char *withThis) -{ - Wstring dest; - const char *foundStr, *src; - uint32 len; - - src=get(); - while(src && src[0]) - { - foundStr = strstr(src, replaceThis); - if(foundStr) - { - len = (uint32)foundStr - (uint32)src; - if(len) - { - if(!dest.cat(len, src)) - return(FALSE); - } - if(!dest.cat(withThis)) - return(FALSE); - src = foundStr + strlen(replaceThis); - } - else - { - if(!dest.cat(src)) - return(FALSE); - - src=NULL; - } - } - return(set(dest.get())); -} - - -bit8 Wstring::set(const char *s) -{ - //uint32 len; - - strgrow(strlen(s)+1); - strcpy(str,s); - - return(TRUE); -} - - -bit8 Wstring::set(char c, uint32 index) -{ - if(index >= (uint32)strlen(str)) - return FALSE; - - str[index] = c; - - return TRUE; -} - - -char Wstring::set(uint32 size, const char *string) -{ - //uint32 len; - - strgrow(size+1); - strncpy(str,string,size); - str[size]=0; - - return(TRUE); -} - - -// Added by Joe Howes. Takes a printf formatted string and a set of args. -// The expanded string must not exceed 1k or twice the length of the format -// string, whichever is larger. It would probably be better to traverse -// the format string and properly calculate, the length so this will -// work in all cases, but this should be good enough for 99% of Wstring usage. -char Wstring::setFormatted(const char *msg, ...) -{ - if( msg == NULL || strlen(msg) <= 0 ) return FALSE; - - char* string; - va_list args; - int len = (strlen(msg) < 1024) ? 1024 : (strlen(msg)*2); - - string = new char[len]; - va_start(args, msg); - vsprintf(string, msg, args); - va_end(args); - set(string); - delete[] string; - return(TRUE); -} - - -// This function converts all alphabetical characters in the string to lower -// case. -void Wstring::toLower(void) -{ - uint32 i; - int strlength=length(); - - for(i = 0; i < (uint32)strlength; i++) - { - if((str[i] >= 'A') && (str[i] <= 'Z')) - str[i] = (sint8)tolower(str[i]); - } -} - - -// This function converts all alphabetical characters in the string to upper -// case. -void Wstring::toUpper(void) -{ - uint32 i; - int strlength=length(); - - for(i = 0; i < (uint32)strlength; i++) - { - if((str[i] >= 'a') && (str[i] <= 'z')) - str[i] = (sint8)toupper(str[i]); - } -} - - -// This function truncates the string so its length will match the specified -// `len'. If an error occurs, FALSE is returned. Otherwise, TRUE is returned. -bit8 Wstring::truncate(uint32 len) -{ - strgrow(len+1); - str[len]=0; - return(TRUE); -} - -// Truncate the string after the character 'c' (gets rid of 'c' as well) -// Do nothing if 'c' isn't in the string -bit8 Wstring::truncate(char c) -{ - sint32 len; - - if (str==NULL) - return(FALSE); - - char *cptr=strchr(str,c); - if (cptr==NULL) - return(FALSE); - len=(sint32)(cptr-str); - truncate((uint32)len); - return(TRUE); -} - -// Get a token from this string that's seperated by one or more -// chars from the 'delim' string , start at offset & return offset -sint32 Wstring::getToken(int offset,const char *delim,Wstring &out) const -{ - int i; - sint32 start; - sint32 stop; - - if (offset<0) // check for bad input - return(-1); - - for (i=offset; i<(int)length(); i++) { - if(strchr(delim,str[i])==NULL) - break; - } - if (i>=(int)length()) - return(-1); - start=i; - - for (; i<(int)length(); i++) { - if(strchr(delim,str[i])!=NULL) - break; - } - stop=i-1; - out.set(str+start); - out.truncate((uint32)stop-start+1); - return(stop+1); -} - -// Get the first line of text after offset. Lines are terminated by '\r\n' or '\n' -sint32 Wstring::getLine(int offset, Wstring &out) -{ - int i; - sint32 start; - sint32 stop; - - start=i=offset; - if (start >= (sint32)length()) - return(-1); - - for (; i<(int)length(); i++) { - if(strchr("\r\n",str[i])!=NULL) - break; - } - stop=i; - if ((str[stop]=='\r')&&(str[stop+1]=='\n')) - stop++; - - out.set(str+start); - out.truncate((uint32)stop-start+1); - return(stop+1); -} - -// -// Make sure there's AT LEAST length bytes in this string object -// -void Wstring::strgrow(int length) -{ - if (str==NULL) - { - str=new char[length+PADSIZE]; - str[0]=0; - strsize=length+PADSIZE; - return; - } - else if (strsize >= length) // no need to alloc more data - return; - else // bah, gotta grow... - { - char *newstr=new char[length+PADSIZE]; - strsize=length+PADSIZE; - strcpy(newstr,str); - delete[](str); - str=newstr; - return; - } -} diff --git a/Generals/Code/Tools/mangler/wlib/wstring.h b/Generals/Code/Tools/mangler/wlib/wstring.h deleted file mode 100644 index 484815c1ba..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wstring.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : main.cpp -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 -\****************************************************************************/ - -#ifndef WSTRING_HEADER -#define WSTRING_HEADER - -#include -#include -#include "wstypes.h" - -class Wstring -{ - public: - Wstring(); - Wstring(const Wstring &other); - Wstring(const char *string); - ~Wstring(); - - void clear(void); - - bit8 cat(const char *string); - bit8 cat(uint32 size,const char *string); - bit8 cat(const Wstring &string); - - void cellCopy(OUT char *dest, uint32 len); - char remove(sint32 pos, sint32 count); - bit8 removeChar(char c); - void removeSpaces(void); - const char *get(void) const; - char get(uint32 index) const; - uint32 length(void) const; - bit8 insert(char c, uint32 pos); - bit8 insert(const char *instring, uint32 pos); - bit8 beautifyNumber(); - bit8 replace(const char *replaceThis,const char *withThis); - char set(const char *str); - char set(uint32 size,const char *str); - bit8 set(char c, uint32 index); - char setFormatted(const char *str, ...); // Added by Joe Howes - void setSize(sint32 bytes); // create an empty string - void toLower(void); - void toUpper(void); - bit8 truncate(uint32 len); - bit8 truncate(char c); // trunc after char c - sint32 getToken(int offset,const char *delim,Wstring &out) const; - sint32 getLine(int offset, Wstring &out); - void strgrow(int length); - - bit8 operator==(const char *other) const; - bit8 operator==(const Wstring &other) const; - bit8 operator!=(const char *other) const; - bit8 operator!=(const Wstring &other) const; - - Wstring &operator=(const char *other); - Wstring &operator=(const Wstring &other); - Wstring &operator+=(const char *other); - Wstring &operator+=(const Wstring &other); - Wstring operator+(const char *other); - Wstring operator+(const Wstring &other); - - bool operator<(const Wstring &other) const; - - private: - char *str; // Pointer to allocated string. - int strsize; // allocated data length -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/wstypes.h b/Generals/Code/Tools/mangler/wlib/wstypes.h deleted file mode 100644 index dbc5824563..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wstypes.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : wstypes.h -Author : Neal Kettler -Start Date : June 3, 1997 -Last Update : June 17, 1997 - -Standard type definitions for the sake of portability and readability. -\***************************************************************************/ - -#ifndef WSTYPES_HEADER -#define WSTYPES_HEADER - -#ifdef _REENTRANT // reentrant = threaded -// Headers with non threadsafe libs need to come before my hacky -// threadsafe.h otherwise they won't compile - -#include -#ifndef _WINDOWS -#define _POSIX_C_SOURCE 199506L -#define _POSIX_PTHREAD_SEMANTICS -#define __EXTENSIONS__ -#endif -#include -#include -#include -#ifndef _WINDOWS -#include -#include -#include -#else -#include -#include -#endif -#include "threadsafe.h" // enforce threadsafe-only calls -#endif - -#define adelete(X) (delete[](X)) - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - -#ifndef MIN -#define MIN(x,y) (((x)<(y))?(x):(y)) -#endif - -#ifndef MAX -#define MAX(x,y) (((x)>(y))?(x):(y)) -#endif - -#ifndef NULL -#define NULL 0 -#endif - -//These are used for readability purposes mostly, when a method takes a -// pointer or reference these help specify what will happen to the data -// that is sent in. -#ifdef IN -#undef IN -#endif -#define IN const -#define OUT -#define INOUT -#define _IN_ const - -// Used to declare a function or method as const or Read Only -#define RO const - -typedef char bit8; -typedef char sint8; -typedef unsigned char uint8; -typedef signed short int sint16; -typedef unsigned short int uint16; -typedef signed int sint32; -typedef unsigned int uint32; - -typedef float float32; -typedef double float64; - -#define MAX_BIT8 0x1 -#define MAX_UINT32 0xFFFFFFFF -#define MAX_UINT16 0xFFFF -#define MAX_UINT8 0xFF -#define MAX_SINT32 0x7FFFFFFF -#define MAX_SINT16 0x7FFF -#define MAX_SINT8 0x7F - -#ifdef _WINDOWS -#define strncasecmp _strnicmp -#define strcasecmp _stricmp -#endif - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/wtime.cpp b/Generals/Code/Tools/mangler/wlib/wtime.cpp deleted file mode 100644 index 5b40cb1df1..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wtime.cpp +++ /dev/null @@ -1,802 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -wtime Neal Kettler -\****************************************************************************/ - -#include -#include "wtime.h" - -static const char *DAYS[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; - -static const char *FULLDAYS[]={"Sunday","Monday","Tuesday","Wednesday","Thursday", - "Friday","Saturday"}; - -static const char *MONTHS[]={"Jan","Feb","Mar","Apr","May","Jun","Jul", - "Aug","Sep","Oct","Nov","Dec"}; - -static const char *FULLMONTHS[]={"January","February","March","April","May","June", - "July","August","September","October","November","December"}; - -// MDC: Windows doesn't provide a localtime_r, so make our own... -#ifdef _WINDOWS -#ifdef _REENTRANT -#include "critsec.h" -static CritSec localtime_critsec; -#undef localtime -struct tm *localtime(const time_t *clockval); -#endif // _REENTRANT - -static struct tm *localtime_r(const time_t *clockval, struct tm *res) { -#ifdef _REENTRANT - localtime_critsec.lock(); -#endif - struct tm *static_tm = localtime(clockval); - res = (struct tm *)memcpy(res, static_tm, sizeof(tm)); -#ifdef _REENTRANT - localtime_critsec.unlock(); -#endif - return res; -} -#endif // _WINDOWS - -Wtime::Wtime(void) -{ - Update(); -} - -Wtime::Wtime( Wtime &other ) -{ - sign=other.sign; - sec=other.sec; - usec=other.usec; -} - -Wtime::Wtime( uint32 other ) -{ - sign=POSITIVE; - sec=other; - usec=0; -} - -Wtime::~Wtime() -{ -} - -void Wtime::Update(void) -{ - sign=POSITIVE; - #ifdef _WINDOWS - struct _timeb wintime; - _ftime(&wintime); - sec=wintime.time; - usec=(wintime.millitm)*1000; - #endif - #ifndef _WINDOWS - struct timeval unixtime; - struct timezone unixtzone; - gettimeofday(&unixtime,&unixtzone); - sec=unixtime.tv_sec; - usec=unixtime.tv_usec; - #endif -} - - -// Parses a date string that's in modified RFC 1123 format -// Can have a +minutes after the normal time -// eg: Thu, 20 Jun 1996 17:33:49 +100 -// Returns true if successfully parsed, false otherwise -bit8 Wtime::ParseDate(char *in) -{ - int i; - uint32 minOffset; - struct tm t; - char *ptr=in; - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of string - if (*ptr==0) return(FALSE); - t.tm_wday=-1; - for (i=0; i<7; i++) // parse day of week - if (strncmp(ptr,DAYS[i],strlen(DAYS[i]))==0) - t.tm_wday=i; - if (t.tm_wday==-1) - return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to day of month - if (*ptr==0) return(FALSE); - t.tm_mday=atoi(ptr); - while ((!isalpha(*ptr))&&(*ptr!=0)) ptr++; // skip to month - if (*ptr==0) return(FALSE); - t.tm_mon=-1; - for (i=0; i<12; i++) // match month - if (strncmp(ptr,MONTHS[i],strlen(MONTHS[i]))==0) t.tm_mon=i; - if (t.tm_mon==-1) return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(FALSE); - t.tm_year=atoi(ptr); - if (t.tm_year<70) // if they specify a 2 digit year, we'll be nice - t.tm_year+=2000; - else if (t.tm_year<100) - t.tm_year+=1900; - if (t.tm_year>2200) // I doubt my code will be around for another 203 years - return(FALSE); - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to end of year - if (*ptr==0) return(FALSE); - - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of time - if (*ptr==0) return(FALSE); - - t.tm_hour=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_min=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_sec=atoi(ptr); - t.tm_year%=100; // 1996 is stored as 96, not 1996 - t.tm_isdst=-1; // daylight savings info isn't available - - sec=(uint32)(mktime(&t)); - if ((sint32)sec==-1) - return(FALSE); - - - // The next part of the time is OPTIONAL (+minutes) - - // first skip past the seconds - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(TRUE); - - // skip past any spaces - while ((isspace(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr!='+') - { - //printf("\nNOPE ptr was '%s'\n",ptr); - return(TRUE); - } - ptr++; - if (*ptr==0) - { - //printf("\nPTR WAS 0\n"); - return(TRUE); - } - - minOffset=atol(ptr); - //printf("\n\nAdding %d minutes!\n\n",minOffset); - sec+=minOffset*60; // add the minutes as seconds - return(TRUE); -} - - -// This takes the standard Microsoft time formatting string -// make sure the out string is big enough -// An example format would be "mm/dd/yy hh:mm:ss" -// CHANGE: Joe Howes 06/30/99 -// To specify 12-hour format, use "aa" instead of "hh". -// The hours will be 12 hour and the string will be -// appended with " AM" or " PM". -bit8 Wtime::FormatTime(char *out, const char *format) -{ - int lastWasH=0; - int ampmflag = 0; - out[0]=0; - const char *ptr=format; - - if (*ptr=='"') ptr++; // skip past open quote if exists - - while (*ptr!=0) - { - if (lastWasH>0) - lastWasH--; - - if (isspace(*ptr)) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),"%c",*ptr); - ptr+=1; - } - else if (strncmp(ptr,"\"",1)==0) - { - break; - } - else if (strncmp(ptr,":",1)==0) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),":"); - ptr+=1; - } - else if (strncmp(ptr,"/",1)==0) - { - sprintf(out+strlen(out),"/"); - ptr+=1; - } - else if (strncmp(ptr,"c",1)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld %ld:%02ld:%02ld",GetMonth(), - GetMDay(),GetYear()%100,GetHour(),GetMinute(),GetSecond()); - ptr+=1; - } - else if (strncmp(ptr,"dddddd",6)==0) - { - sprintf(out+strlen(out),"%s %02ld, %ld",FULLMONTHS[GetMonth()-1], - GetMDay(),GetYear()); - ptr+=6; - } - else if (strncmp(ptr,"ddddd",5)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld",GetMonth(),GetMDay(), - GetYear()%100); - ptr+=5; - } - else if (strncmp(ptr,"dddd",4)==0) - { - sprintf(out+strlen(out),"%s",FULLDAYS[GetWDay()-1]); - ptr+=4; - } - else if (strncmp(ptr,"ddd",3)==0) - { - sprintf(out+strlen(out),"%s",DAYS[GetWDay()-1]); - ptr+=3; - } - else if (strncmp(ptr,"dd",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetMDay()); - ptr+=2; - } - else if (strncmp(ptr,"d",1)==0) - { - sprintf(out+strlen(out),"%ld",GetMDay()); - ptr+=1; - } - else if (strncmp(ptr,"ww",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetYWeek()); - ptr+=2; - } - else if (strncmp(ptr,"w",1)==0) - { - sprintf(out+strlen(out),"%ld",GetWDay()); - ptr+=1; - } - else if (strncmp(ptr,"mmmm",4)==0) - { - sprintf(out+strlen(out),"%s",FULLMONTHS[GetMonth()-1]); - ptr+=4; - } - else if (strncmp(ptr,"mmm",3)==0) - { - sprintf(out+strlen(out),"%s",MONTHS[GetMonth()-1]); - ptr+=3; - } - else if (strncmp(ptr,"mm",2)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%02ld",GetMinute()); - else - sprintf(out+strlen(out),"%02ld",GetMonth()); - ptr+=2; - } - else if (strncmp(ptr,"m",1)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%ld",GetMinute()); - else - sprintf(out+strlen(out),"%ld",GetMonth()); - ptr+=1; - } - else if (strncmp(ptr,"q",1)==0) - { - sprintf(out+strlen(out),"%ld",((GetMonth()-1)/4)+1); // GetQuarter - ptr+=1; - } - else if (strncmp(ptr,"yyyy",4)==0) - { - sprintf(out+strlen(out),"%ld",GetYear()); - ptr+=4; - } - else if (strncmp(ptr,"yy",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetYear()%100); - ptr+=2; - } - else if (strncmp(ptr,"y",1)==0) - { - sprintf(out+strlen(out),"%ld",GetYDay()); - ptr+=1; - } - else if (strncmp(ptr,"hh",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - } - else if (strncmp(ptr,"h",1)==0) - { - sprintf(out+strlen(out),"%ld",GetHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=1; - } - else if (strncmp(ptr,"nn",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetMinute()); - ptr+=2; - } - else if (strncmp(ptr,"n",1)==0) - { - sprintf(out+strlen(out),"%ld",GetMinute()); - ptr+=1; - } - else if (strncmp(ptr,"ss",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetSecond()); - ptr+=2; - } - else if (strncmp(ptr,"s",1)==0) - { - sprintf(out+strlen(out),"%ld",GetSecond()); - ptr+=1; - } - else if (strncmp(ptr,"ttttt",5)==0) - { - sprintf(out+strlen(out),"%ld:%02ld:%02ld",GetHour(),GetMinute(), - GetSecond()); - ptr+=5; - } - else if (strncmp(ptr,"aa",2)==0) - { - uint32 tmp = (GetHour() <= 12) ? GetHour() : GetHour() - 12; - sprintf(out+strlen(out),"%02ld", tmp); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - ampmflag = 1; - } - else // an unknown char, move to next - ptr++; - } - if(ampmflag) - { - char ampm[4]; - if( GetHour() < 12 ) - strcpy(ampm, " AM"); - else - strcpy(ampm, " PM"); - sprintf(out+strlen(out), "%s", ampm); - } - return(TRUE); -} - - - -// In addition to PrintTime & PrintDate there is the 'Print' function -// which prints both in RFC 1123 format - -void Wtime::PrintTime(FILE *out) const -{ - char string[80]; - PrintTime(string); - fprintf(out,"%s",string); -} - -void Wtime::PrintTime(char *out) const -{ - sprintf(out," %02lu:%02lu:%02lu",GetHour(),GetMinute(),GetSecond()); -} - -void Wtime::PrintDate(FILE *out) const -{ - char string[80]; - PrintDate(string); - fprintf(out,"%s",string); -} - -void Wtime::PrintDate(char *out) const -{ - sprintf(out,"%s, %lu %s %lu",DAYS[GetWDay()-1],GetMDay(),MONTHS[GetMonth()-1], - GetYear()); -} - -uint32 Wtime::GetSec(void) const -{ - return(sec); -} - -uint32 Wtime::GetUsec(void) const -{ - return(usec); -} - -void Wtime::SetSec(uint32 newsec) -{ - sec=newsec; -} - -void Wtime::SetUsec(uint32 newusec) -{ - usec=newusec; -} - -void Wtime::Set(uint32 newsec, uint32 newusec) -{ - sec=newsec; - usec=newusec; -} - -// Get a timeval ptr from a Wtime class -struct timeval *Wtime::GetTimeval(void) -{ - static struct timeval tv; - tv.tv_sec=sec; - tv.tv_usec=usec; - return(&tv); -} - -// Get a timeval ptr from a Wtime class -void Wtime::GetTimevalMT(struct timeval &tv) -{ - tv.tv_sec=sec; - tv.tv_usec=usec; -} - - -uint32 Wtime::GetSecond(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_sec); -} -uint32 Wtime::GetMinute(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_min); -} -uint32 Wtime::GetHour(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_hour); -} -uint32 Wtime::GetMDay(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_mday); -} -uint32 Wtime::GetWDay(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_wday+1); -} -uint32 Wtime::GetYDay(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_yday+1); -} -uint32 Wtime::GetYWeek(void) const -{ - uint32 yweek; - uint32 yday=GetYDay(); - uint32 wday=GetWDay(); - //phase holds the first weekday of the year. If (Jan 1 = Sun) phase = 0 - sint32 phase=((wday-yday)%7); - if (phase<0) phase+=7; - yweek=((yday+phase-1)/7)+1; - return(yweek); -} -uint32 Wtime::GetMonth(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_mon+1); -} - -uint32 Wtime::GetYear(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - if ((tptr->tm_year)>=70) - return((tptr->tm_year)+1900); - else - return((tptr->tm_year)+2000); -} - - -bit8 Wtime::GetSign(void) const -{ - return(sign); -} - -// 1 = *this > other -//-1 = *this < other -// 0 = *this == other -int Wtime::Compare(const Wtime &other) const -{ - if ((sec==other.sec)&&(usec==other.usec)) - return(0); // equal - - else if (sec>other.sec) - return(1); - else if (secother.usec) - return(1); - else - return(-1); -} - - -bit8 Wtime::operator == ( const Wtime &other ) const -{ - bit8 retval=Compare(other); - if (retval==0) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator != ( const Wtime &other ) const -{ - bit8 retval=Compare(other); - if (retval==0) - return(FALSE); - else - return(TRUE); -} - -bit8 Wtime::operator < ( const Wtime &other ) const -{ - int retval=Compare(other); - if (retval==-1) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator > ( const Wtime &other ) const -{ - int retval=Compare(other); - if (retval==1) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator <= ( const Wtime &other ) const -{ - int retval=Compare(other); - if ((retval==-1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator >= ( const Wtime &other ) const -{ - int retval=Compare(other); - if ((retval==1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - - -// None of the operators pay attention to sign -// only the functions that begin with 'Signed' -void Wtime::SignedAdd(const Wtime &other) -{ - Wtime temp; - - if ((sign==POSITIVE)&&(other.sign==POSITIVE)) - { - *this+=other; - sign=POSITIVE; - } - else if ((sign==POSITIVE)&&(other.sign==NEGATIVE)) - { - if (*this>other) - { - *this-=other; - sign=POSITIVE; - } - else - { - temp=other; - temp-=*this; - *this=temp; - sign=NEGATIVE; - } - } - else if ((sign==NEGATIVE)&&(other.sign==POSITIVE)) - { - if (*thisother) - { - *this-=other; - sign=POSITIVE; - } - else - { - temp=other; - temp-=*this; - *this=temp; - sign=NEGATIVE; - } - } - else if ((sign==NEGATIVE)&&(other.sign==NEGATIVE)) - { - if (*this1000000) - { - sec++; - usec-=1000000; - } - return *this; -} - -Wtime &Wtime::operator -= (const Wtime &other) -{ - sint32 temp; - if (Compare(other)==-1) - { - sec=0; // can't handle negative time - usec=0; - return *this; - } - sec-=other.sec; - temp=(sint32)usec; - temp-=(sint32)other.usec; - if (temp<0) - { - sec--; - temp+=1000000; - } - usec=temp; - return *this; -} - -Wtime Wtime::operator - (Wtime &other) -{ - Wtime temp(*this); - temp-=other; - return(temp); -} - -Wtime Wtime::operator + (Wtime &other) -{ - Wtime temp(*this); - temp+=other; - return(temp); -} - - -Wtime &Wtime::operator = (const Wtime &other) -{ - sign=other.sign; - sec=other.sec; - usec=other.usec; - return *this; -} - - -Wtime &Wtime::operator += (const uint32 other) -{ - sec+=other; - return *this; -} - - -Wtime &Wtime::operator -= (const uint32 other) -{ - sec-=other; - return *this; -} - - -Wtime Wtime::operator - (uint32 other) -{ - Wtime temp(*this); - temp-=other; - return(temp); -} - - -Wtime Wtime::operator + (uint32 other) -{ - Wtime temp(*this); - temp+=other; - return(temp); -} - - -Wtime &Wtime::operator = (const uint32 other) -{ - sign=POSITIVE; - sec=other; - usec=0; - return *this; -} diff --git a/Generals/Code/Tools/mangler/wlib/wtime.h b/Generals/Code/Tools/mangler/wlib/wtime.h deleted file mode 100644 index 3f0d1cf723..0000000000 --- a/Generals/Code/Tools/mangler/wlib/wtime.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -wtime Neal Kettler - -\****************************************************************************/ -#ifndef WTIME_HEADER -#define WTIME_HEADER - - -#include -#include -#include -#include - -#ifndef _WINDOWS -#include -#include -#include -#else -#include -#include -#endif - -#include -#include - -#include "wstypes.h" - -class Wtime -{ - public: - - enum - { - POSITIVE=0, - NEGATIVE=1 - }; - - Wtime(); // init to system time - Wtime( Wtime &other ); - Wtime( uint32 other ); - ~Wtime(); - - void Update(); // Update members sec & usec to system time - - - void PrintTime(FILE *out) const; - void PrintTime(char *out) const; - void PrintDate(FILE *out) const; - void PrintDate(char *out) const; - - uint32 GetSec(void) const; // Get member variable 'sec' - uint32 GetUsec(void) const; // Get member variable 'usec' - void SetSec(uint32 newsec); - void SetUsec(uint32 newusec); - void Set(uint32 newsec,uint32 newusec); - bit8 ParseDate(char *in); - bit8 FormatTime(char *out, const char *format); - - struct timeval *GetTimeval(void); - void GetTimevalMT(struct timeval &tv); - - uint32 GetSecond(void) const; // Second (0- 60) (60 is for a leap second) - uint32 GetMinute(void) const; // Minute (0 - 59) - uint32 GetHour(void) const; // Hour (0-23) - uint32 GetMDay(void) const; // Day of Month (1-31) - uint32 GetWDay(void) const; // Day of Week (1-7) - uint32 GetYDay(void) const; // Day of Year (1-366) - uint32 GetMonth(void) const; // Month (1-12) - uint32 GetYWeek(void) const; // Week of Year (1-53) - uint32 GetYear(void) const; // Year (e.g. 1997) - - bit8 GetSign(void) const; // 0 = pos 1 = neg - - int Compare(const Wtime &other) const; - - // comparisons - bit8 operator == ( const Wtime &other ) const; - bit8 operator != ( const Wtime &other ) const; - bit8 operator < ( const Wtime &other ) const; - bit8 operator > ( const Wtime &other ) const; - bit8 operator <= ( const Wtime &other ) const; - bit8 operator >= ( const Wtime &other ) const; - - // assignments - Wtime &operator = (const Wtime &other); - Wtime &operator = (const uint32 other); - - // math - // signed - void SignedAdd(const Wtime &other); - void SignedSubtract(const Wtime &other); - - // unsigned - Wtime &operator += (const Wtime &other); - Wtime &operator -= (const Wtime &other); - Wtime operator + (Wtime &other); - Wtime operator - (Wtime &other); - - Wtime &operator += (const uint32 other); - Wtime &operator -= (const uint32 other); - Wtime operator + (uint32 other); - Wtime operator - (uint32 other); - - protected: - uint32 sec; // seconds since Jan 1, 1970 - uint32 usec; // microseconds (millionths of a second) - bit8 sign; // for time differences 0 = pos 1 = neg -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wlib/xtime.cpp b/Generals/Code/Tools/mangler/wlib/xtime.cpp deleted file mode 100644 index 28181d6f36..0000000000 --- a/Generals/Code/Tools/mangler/wlib/xtime.cpp +++ /dev/null @@ -1,1015 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ - -xtime Neal Kettler - -Improved version of the Wtime library (V->W->X...) - -Handles signed times better and dates long -long long after you'll be dead. - -\****************************************************************************/ - -#include -#include -#ifndef _WINDOWS -#include -#endif -#include "xtime.h" - -static const char *DAYS[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; - -static const char *FULLDAYS[]={"Sunday","Monday","Tuesday","Wednesday","Thursday", - "Friday","Saturday"}; - -static const char *MONTHS[]={"Jan","Feb","Mar","Apr","May","Jun","Jul", - "Aug","Sep","Oct","Nov","Dec"}; - -static const char *FULLMONTHS[]={"January","February","March","April","May","June", - "July","August","September","October","November","December"}; - - -#define IS_LEAP(y) ((y) % 4) == 0 && (! ((y) % 100) == 0 || ((y) % 400) == 0) -#define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400) - - -/////////////// Utility functions /////////////////// - -// -// Return the daycount since year 0 for the specified date. -// month = 1-12, day = 1-31 year = 0... -// -static sint32 Get_Day(int month, int day, int year) -{ - time_t days; - - static int DaysAtMonth[] = - {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; - - /* Add up number of straight days + number of leap days + days */ - /* up to the month + the day of month. */ - - days = (year * 365) + (year / 4) - (year / 100) + (year / 400) + - DaysAtMonth[month-1] + day; - - /* If we haven't hit Feb 29, and this is a leap year, we need to */ - /* subtract out the leap day that was added above for this year */ - - if (month < 3 && IS_LEAP(year)) - --days; - return(days); -} - - - -// -// Get the year from a daycount since year 0 -// Also get the daycount since the start of the year -// -// Ayecarumba what a pain in the ass! -// -static bit8 Get_Date_From_Day(sint32 days, OUT sint32 &year, OUT sint32 &yday) -{ - //register long int rem; - register long int y; - //register const unsigned short int *ip; - - if (days <= 365) - { - year=0; - yday=days+1; // 1 based - return(TRUE); - } - - y = 1; - days-=365; - - days--; // zero based - - // - // As far as I can tell there's no non-iteritive way to - // do this... - // - while (days < 0 || days >= (IS_LEAP (y) ? 366 : 365)) - { - /* Guess a corrected year, assuming 365 days per year. */ - long int yg = y + days / 365 - (days % 365 < 0); - - /* Adjust DAYS and Y to match the guessed year. */ - days -= ((yg - y) * 365 - + LEAPS_THRU_END_OF (yg - 1) - - LEAPS_THRU_END_OF (y - 1)); - y = yg; - } - year=y; - yday=days+1; // 1 based - return(TRUE); -} - - -// -// Get the max day of a given month in a given year -// -int Max_Day(int month, int year) -{ - static char dayTable[2][13] = { - {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, - {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} - }; - bit8 isleap=IS_LEAP(year); - return(dayTable[isleap][month]); -} - - - -/********************************************************** -int main(int argc, char *argv[]) -{ - Xtime wtime; - int month,mday,year,hour,minute,second,day; - int i; - int dayoffset; - int yr; - int yday; - int ydaycount; - - wtime.set(719528,0); - -*********************************************** - for (year=0; year<10000; year++) - { - ydaycount=1; - for (month=1; month<=12; month++) - { - for (day=1; day<=Max_Day(month,year); day++) - { - dayoffset=Get_Day(month,day,year); - assert (GetDateFromDay(dayoffset,yr,yday)==TRUE); - - //printf("Yday=%d YdayCount=%d\n",yday,ydaycount); - - if (yr!=year) - { - printf("MO=%d DAY=%d YEAR=%d YR=%d\n",month,day,year,yr); - assert(0); - } - if (yday != ydaycount) - { - printf("MO=%d DAY=%d YEAR=%d YR=%d\n",month,day,year,yr); - printf("Yday=%d YdayCount=%d\n",yday,ydaycount); - assert(0); - } - ydaycount++; - } - } - printf("(%d) ",year); - } -*************************************** - - ///////wtime.addSeconds((60*60*24)-(60*60*8)); - ////////wtime.addSeconds(-(60*60*8)); // timezone delta - - dayoffset=Get_Day(1,1,1970); - printf("DAYOFFSET = %d\n",dayoffset); - - - wtime.getTime(month, mday, year, hour, minute, second); - printf("\n%s %d %d %d:%02d:%02d\n\n", - MONTHS[month-1],mday,year,hour,minute,second); - - struct timeval unixtime; - struct timezone unixtzone; - time_t ttime; - tm tmtime; - - memset(&tmtime,0,sizeof(tmtime)); - ttime=0; - unixtime.tv_sec=0; - unixtime.tv_usec=0; - - //gettimeofday(&unixtime,&unixtzone); - //ttime=time(NULL); - tmtime=*gmtime(&ttime); - - printf("TIME->CTIME = %s\n",ctime(&ttime)); - printf("GTOD->CTIE = %s\n",ctime(&(unixtime.tv_sec))); - printf("TIME->GMT->ASCTIME = %s\n",asctime(&tmtime)); -} -***************************************************************/ - - - -// -// Construct with current clock time -// -Xtime::Xtime(void) -{ - update(); -} - -// -// Copy constructor -// -Xtime::Xtime( Xtime &other ) -{ - day_=other.day_; - msec_=other.msec_; -} - -// -// Set to a time_t (1970-2038) -// -Xtime::Xtime( time_t other ) -{ - day_=719528; // days from year 0 to Jan1, 1970 - // Add seconds from time_t - addSeconds(other); - msec_=0; -} - -Xtime::~Xtime() -{ -} - -// -// Add some number of seconds to the time (seconds can be negative) -// -void Xtime::addSeconds(sint32 seconds) -{ - // Add to day counter first - day_+=(seconds/86400); - msec_+=(seconds % 86400)*1000; - - // Now normalize in case msec is > 1 days worth - normalize(); -} - -// -// If msec is > 1 days worth, adjust the day count -// & decrement the msec counter until OK. -// -void Xtime::normalize(void) -{ - day_+=(msec_/86400000); - msec_%=86400000; - - while (msec_ < 0) - { - day_--; - msec_+=86400000; - } -} - -// -// Update time to hold the current clock time -// (breaks in 2038 :-) -// -void Xtime::update(void) -{ - day_=719528; // day_s from year 0 to Jan1, 1970 - msec_=0; - - #ifdef _WINDOWS - struct _timeb wintime; - _ftime(&wintime); - addSeconds(wintime.time); - msec_+=wintime.millitm; - #endif - #ifndef _WINDOWS - struct timeval unixtime; - struct timezone unixtzone; - gettimeofday(&unixtime,&unixtzone); - addSeconds(unixtime.tv_sec); - msec_+=(unixtime.tv_usec/1000); - #endif - - // Now normalize in case msec is > 1 days worth - normalize(); -} - - -// This takes the standard Microsoft time formatting string -// make sure the out string is big enough -// An example format would be "mm/dd/yy hh:mm:ss" -// CHANGE: Joe Howes 06/30/99 -// To specify 12-hour format, use "aa" instead of "hh". -// The hours will be 12 hour and the string will be -// appended with " AM" or " PM". -bit8 Xtime::FormatTime(char *out, const char *format) -{ - int lastWasH=0; - int ampmflag = 0; - out[0]=0; - const char *ptr=format; - - if (*ptr=='"') ptr++; // skip past open quote if exists - - while (*ptr!=0) - { - if (lastWasH>0) - lastWasH--; - - if (isspace(*ptr)) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),"%c",*ptr); - ptr+=1; - } - else if (strncmp(ptr,"\"",1)==0) - { - break; - } - else if (strncmp(ptr,":",1)==0) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),":"); - ptr+=1; - } - else if (strncmp(ptr,"/",1)==0) - { - sprintf(out+strlen(out),"/"); - ptr+=1; - } - else if (strncmp(ptr,"c",1)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld %ld:%02ld:%02ld",getMonth(), - getMDay(),getYear()%100,getHour(),getMinute(),getSecond()); - ptr+=1; - } - else if (strncmp(ptr,"dddddd",6)==0) - { - sprintf(out+strlen(out),"%s %02ld, %ld",FULLMONTHS[getMonth()-1], - getMDay(),getYear()); - ptr+=6; - } - else if (strncmp(ptr,"ddddd",5)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld",getMonth(),getMDay(), - getYear()%100); - ptr+=5; - } - /*else if (strncmp(ptr,"dddd",4)==0) - { - sprintf(out+strlen(out),"%s",FULLDAYS[getWDay()-1]); - ptr+=4; - } - else if (strncmp(ptr,"ddd",3)==0) - { - sprintf(out+strlen(out),"%s",DAYS[getWDay()-1]); - ptr+=3; - }*/ - else if (strncmp(ptr,"dd",2)==0) - { - sprintf(out+strlen(out),"%02ld",getMDay()); - ptr+=2; - } - else if (strncmp(ptr,"d",1)==0) - { - sprintf(out+strlen(out),"%ld",getMDay()); - ptr+=1; - } - /*else if (strncmp(ptr,"ww",2)==0) - { - sprintf(out+strlen(out),"%02ld",getYWeek()); - ptr+=2; - }*/ - /*else if (strncmp(ptr,"w",1)==0) - { - sprintf(out+strlen(out),"%ld",getWDay()); - ptr+=1; - }*/ - else if (strncmp(ptr,"mmmm",4)==0) - { - sprintf(out+strlen(out),"%s",FULLMONTHS[getMonth()-1]); - ptr+=4; - } - else if (strncmp(ptr,"mmm",3)==0) - { - sprintf(out+strlen(out),"%s",MONTHS[getMonth()-1]); - ptr+=3; - } - else if (strncmp(ptr,"mm",2)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%02ld",getMinute()); - else - sprintf(out+strlen(out),"%02ld",getMonth()); - ptr+=2; - } - else if (strncmp(ptr,"m",1)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%ld",getMinute()); - else - sprintf(out+strlen(out),"%ld",getMonth()); - ptr+=1; - } - else if (strncmp(ptr,"q",1)==0) - { - sprintf(out+strlen(out),"%ld",((getMonth()-1)/4)+1); // GetQuarter - ptr+=1; - } - else if (strncmp(ptr,"yyyy",4)==0) - { - sprintf(out+strlen(out),"%ld",getYear()); - ptr+=4; - } - else if (strncmp(ptr,"yy",2)==0) - { - sprintf(out+strlen(out),"%02ld",getYear()%100); - ptr+=2; - } - /*else if (strncmp(ptr,"y",1)==0) - { - sprintf(out+strlen(out),"%ld",getYDay()); - ptr+=1; - }*/ - else if (strncmp(ptr,"hh",2)==0) - { - sprintf(out+strlen(out),"%02ld",getHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - } - else if (strncmp(ptr,"h",1)==0) - { - sprintf(out+strlen(out),"%ld",getHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=1; - } - else if (strncmp(ptr,"nn",2)==0) - { - sprintf(out+strlen(out),"%02ld",getMinute()); - ptr+=2; - } - else if (strncmp(ptr,"n",1)==0) - { - sprintf(out+strlen(out),"%ld",getMinute()); - ptr+=1; - } - else if (strncmp(ptr,"ss",2)==0) - { - sprintf(out+strlen(out),"%02ld",getSecond()); - ptr+=2; - } - else if (strncmp(ptr,"s",1)==0) - { - sprintf(out+strlen(out),"%ld",getSecond()); - ptr+=1; - } - else if (strncmp(ptr,"ttttt",5)==0) - { - sprintf(out+strlen(out),"%ld:%02ld:%02ld",getHour(),getMinute(), - getSecond()); - ptr+=5; - } - else if (strncmp(ptr,"aa",2)==0) - { - uint32 tmp = (getHour() <= 12) ? getHour() : getHour() - 12; - sprintf(out+strlen(out),"%02ld", tmp); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - ampmflag = 1; - } - else // an unknown char, move to next - ptr++; - } - if(ampmflag) - { - char ampm[4]; - if( getHour() < 12 ) - strcpy(ampm, " AM"); - else - strcpy(ampm, " PM"); - sprintf(out+strlen(out), "%s", ampm); - } - return(TRUE); -} - -/************************************** - - REPLACE THIS CRAP - -// Parses a date string that's in modified RFC 1123 format -// Can have a +minutes after the normal time -// eg: Thu, 20 Jun 1996 17:33:49 +100 -// Returns true if successfully parsed, false otherwise -bit8 Xtime::ParseDate(char *in) -{ - int i; - uint32 minOffset; - struct tm t; - char *ptr=in; - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of string - if (*ptr==0) return(FALSE); - t.tm_wday_=-1; - for (i=0; i<7; i++) // parse day_ of week - if (strncmp(ptr,DAYS[i],strlen(DAYS[i]))==0) - t.tm_wday_=i; - if (t.tm_wday_==-1) - return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to day_ of month - if (*ptr==0) return(FALSE); - t.tm_mday_=atoi(ptr); - while ((!isalpha(*ptr))&&(*ptr!=0)) ptr++; // skip to month - if (*ptr==0) return(FALSE); - t.tm_mon=-1; - for (i=0; i<12; i++) // match month - if (strncmp(ptr,MONTHS[i],strlen(MONTHS[i]))==0) t.tm_mon=i; - if (t.tm_mon==-1) return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(FALSE); - t.tm_year=atoi(ptr); - if (t.tm_year<70) // if they specify a 2 digit year, we'll be nice - t.tm_year+=2000; - else if (t.tm_year<100) - t.tm_year+=1900; - if (t.tm_year>2200) // I doubt my code will be around for another 203 years - return(FALSE); - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to end of year - if (*ptr==0) return(FALSE); - - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of time - if (*ptr==0) return(FALSE); - - t.tm_hour=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_min=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_sec=atoi(ptr); - t.tm_year%=100; // 1996 is stored as 96, not 1996 - t.tm_isdst=-1; // day_light savings info isn't available - - sec=(uint32)(mktime(&t)); - if ((sint32)sec==-1) - return(FALSE); - - - // The next part of the time is OPTIONAL (+minutes) - - // first skip past the seconds - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(TRUE); - - // skip past any spaces - while ((isspace(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr!='+') - { - //printf("\nNOPE ptr was '%s'\n",ptr); - return(TRUE); - } - ptr++; - if (*ptr==0) - { - //printf("\nPTR WAS 0\n"); - return(TRUE); - } - - minOffset=atol(ptr); - //printf("\n\nAdding %d minutes!\n\n",minOffset); - sec+=minOffset*60; // add the minutes as seconds - return(TRUE); -} - - - -// In addition to PrintTime & PrintDate there is the 'Print' function -// which prints both in RFC 1123 format - -void Xtime::PrintTime(FILE *out) const -{ - char string[80]; - PrintTime(string); - fprintf(out,"%s",string); -} - -void Xtime::PrintTime(char *out) const -{ - sprintf(out," %02lu:%02lu:%02lu",GetHour(),GetMinute(),GetSecond()); -} - -void Xtime::PrintDate(FILE *out) const -{ - char string[80]; - PrintDate(string); - fprintf(out,"%s",string); -} - -void Xtime::PrintDate(char *out) const -{ - sprintf(out,"%s, %lu %s %lu",DAYS[GetWDay()-1],GetMDay(),MONTHS[GetMonth()-1], - GetYear()); -} -********************************************/ - -// Get day_s since year 0 -sint32 Xtime::getDay(void) const -{ - return(day_); -} - -// Get msecs since start of day -sint32 Xtime::getMsec(void) const -{ - return(msec_); -} - -// Set days since year 0 -void Xtime::setDay(sint32 newday) -{ - day_=newday; -} - -// Set msec since start of this day -void Xtime::setMsec(sint32 newmsec) -{ - msec_=newmsec; -} - -// Set both -void Xtime::set(sint32 newday, sint32 newmsec) -{ - day_=newday; - msec_=newmsec; -} - - -// -// Get a timeval ptr from a Xtime class -// May fail if timeval can't hold a year this big or small -// -bit8 Xtime::getTimeval(struct timeval &tv) -{ - // A timeval can only hold dates from 1970-2038 - if ((day_ < 719528) || (day_ >= 719528+24855)) - return(FALSE); - - // Compute seconds since Jan 1, 1970 - uint32 seconds=day_-719528; - seconds*=(60*60*24); - seconds+=(msec_/1000); - - tv.tv_sec=seconds; - tv.tv_usec=(msec_%1000)*1000; - return(TRUE); -} - -// -// Set the time -// -bit8 Xtime::setTime(int month, int mday, int year, int hour, int minute, int second) -{ - day_=Get_Day(month,mday,year); - msec_=(hour*1000*60*60)+(minute*1000*60)+(second*1000); - return(TRUE); -} - - - -int Xtime::getYDay(void) const // Day of Year (1-366) (366 = leap yr) -{ - int year; - sint32 dayofyear; - if (Get_Date_From_Day(day_,year,dayofyear)==FALSE) - return(-1); - return dayofyear; -} - - -// -// Get all the components of the time in the usual normalized format. -// -// Most of the uglyness is in Get_Date_From_Day() -// -bit8 Xtime::getTime(int &month, int &mday, int &year, int &hour, int &minute, int &second) const -{ - int i; - sint32 dayofyear; - if (Get_Date_From_Day(day_,year,dayofyear)==FALSE) - return(FALSE); - - static int DaysAtMonth[2][12] = { - {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}, // normal - {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335} // leap year - }; - - month=0; - - bit8 isleap=IS_LEAP(year); - for (i=0; i<12; i++) - { - if (DaysAtMonth[isleap][i] >= dayofyear) - break; - month=i; - } - month++; // 1 based - - mday=dayofyear-DaysAtMonth[isleap][month-1]; - - // Whew! Now all we have to do is figure out H/M/S from the msec! - hour=(msec_/3600000)%24; // 1000*60*60 - minute=(msec_/60000)%60; // 1000*60 - second=(msec_/ 1000)%60; // 1000 - - return(TRUE); -} - -// -// These are for getting components of the time in the -// standard ranges. Like Day 1-31, Second 0-59, etc... -// -int Xtime::getSecond(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(second); -} -int Xtime::getMinute(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(minute); -} -int Xtime::getHour(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(hour); -} -int Xtime::getMDay(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(mday); -} - -int Xtime::getMonth(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(month); -} - -// based at year 0 (real 0, not 1970) -int Xtime::getYear(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(year); -} - - -// -// Set the seconds value (0-59) -// -bit8 Xtime::setSecond(sint32 sec) -{ - sint32 second=(msec_/ 1000)%60; - msec_-=(second*1000); - msec_+=(sec*1000); - return(TRUE); -} - -// -// Set the minutes value (0-59) -// -bit8 Xtime::setMinute(sint32 min) -{ - sint32 minute=(msec_/60000)%60; // 1000*60 - msec_-=(minute*60000); - msec_+=(min*60000); - return(TRUE); -} - -// -// Set the minutes value (0-23) -// -bit8 Xtime::setHour(sint32 hour) -{ - hour=(msec_/3600000)%24; // 1000*60*60 - msec_-=(hour*3600000); - msec_+=(hour*3600000); - return(TRUE); -} - -// -// Set the year value -// Results are undefined if you're moving from Feb 29, to a non leap year -// -bit8 Xtime::setYear(sint32 _year) -{ - // extract the date - int month,mday,year,hour,min,sec; - getTime(month,mday,year,hour,min,sec); - - // modify & rebuild - year=_year; - day_=Get_Day(month,mday,year); - return(TRUE); -} - -// -// Modify the month -// -bit8 Xtime::setMonth(sint32 _month) -{ - // extract the date - int month,mday,year,hour,min,sec; - getTime(month,mday,year,hour,min,sec); - - // modify & rebuild - month=_month; - day_=Get_Day(month,mday,year); - return(TRUE); -} - - -// -// Modify the day of the month -// -bit8 Xtime::setMDay(sint32 _mday) -{ - // extract the date - int month,mday,year,hour,min,sec; - getTime(month,mday,year,hour,min,sec); - - // modify & rebuild - mday=_mday; - day_=Get_Day(month,mday,year); - return(TRUE); -} - - -// -// Compare two times. The time better be normalized -// which it would be unless you've put bad stuff in it! -// -// 1 = *this > other -//-1 = *this < other -// 0 = *this == other -int Xtime::compare(const Xtime &other) const -{ - if ((day_==other.day_)&&(msec_==other.msec_)) - return(0); // equal - - else if (day_>other.day_) - return(1); - else if (day_other.msec_) - return(1); - else - return(-1); -} - - -bit8 Xtime::operator == ( const Xtime &other ) const -{ - bit8 retval=compare(other); - if (retval==0) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator != ( const Xtime &other ) const -{ - bit8 retval=compare(other); - if (retval==0) - return(FALSE); - else - return(TRUE); -} - -bit8 Xtime::operator < ( const Xtime &other ) const -{ - int retval=compare(other); - if (retval==-1) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator > ( const Xtime &other ) const -{ - int retval=compare(other); - if (retval==1) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator <= ( const Xtime &other ) const -{ - int retval=compare(other); - if ((retval==-1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator >= ( const Xtime &other ) const -{ - int retval=compare(other); - if ((retval==1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - - -Xtime &Xtime::operator += (const Xtime &other) -{ - day_+=other.day_; - msec_+=other.msec_; - normalize(); - return *this; -} - -Xtime &Xtime::operator -= (const Xtime &other) -{ - day_-=other.day_; - msec_-=other.msec_; - normalize(); - return *this; -} - -Xtime Xtime::operator - (Xtime &other) -{ - Xtime temp(*this); - temp-=other; - return(temp); -} - -Xtime Xtime::operator + (Xtime &other) -{ - Xtime temp(*this); - temp+=other; - return(temp); -} - - -Xtime &Xtime::operator = (const Xtime &other) -{ - day_=other.day_; - msec_=other.msec_; - return *this; -} - - -Xtime &Xtime::operator += (const time_t other) -{ - addSeconds(other); - return *this; -} - - -Xtime &Xtime::operator -= (const time_t other) -{ - addSeconds(-((sint32)other)); - return *this; -} - - -Xtime Xtime::operator - (time_t other) -{ - Xtime temp(*this); - temp-=other; - return(temp); -} - - -Xtime Xtime::operator + (time_t other) -{ - Xtime temp(*this); - temp+=other; - return(temp); -} - -Xtime &Xtime::operator = (const time_t other) -{ - msec_=0; - day_=719528; // Jan 1, 1970 - addSeconds(other); - return *this; -} diff --git a/Generals/Code/Tools/mangler/wlib/xtime.h b/Generals/Code/Tools/mangler/wlib/xtime.h deleted file mode 100644 index b6210eee2c..0000000000 --- a/Generals/Code/Tools/mangler/wlib/xtime.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -xtime Neal Kettler - -This is version 2 of the Wtime library (now xtime). It now supports -time storage from the year 0 to well after the sun -will have gone supernova (OK, OK I admit it'll break in the -year 5 Million.) - -The call to update the current time will break in 2038. -Hopefully by then somebody will replace the lame time() -function :-) -\****************************************************************************/ - -#ifndef XTIME_HEADER -#define XTIME_HEADER - - -#include -#include -#include -#include - -#ifndef _WINDOWS -#include -#include -#include -#else -#include -#include -#endif - -#include -#include - -#include "wstypes.h" - -class Xtime -{ - public: - - Xtime(); // init to system time - Xtime( Xtime &other ); - Xtime( time_t other ); // 1970-2038 - ~Xtime(); - - void addSeconds(sint32 seconds); - - bit8 getTime(int &month, int &mday, int &year, int &hour, int &minute, - int &second) const; - - bit8 setTime(int month, int mday, int year, int hour, int minute, - int second); - - void update(); // Update members sec & usec to system time - // This will break after 2038 - -/******** - void PrintTime(FILE *out) const; - void PrintTime(char *out) const; - void PrintDate(FILE *out) const; - void PrintDate(char *out) const; -**********/ - - sint32 getDay(void) const; // Get days since year 0 - sint32 getMsec(void) const; // Get milliseconds into the day - - void setDay(sint32 day); - void setMsec(sint32 msec); - - void set(sint32 newday, sint32 newmsec); - bit8 ParseDate(char *in); - bit8 FormatTime(char *out, const char *format); - - bit8 getTimeval(struct timeval &tv); - - // All of these may return -1 if the time is invalid - int getSecond(void) const; // Second (0-60) (60 is for a leap second) - int getMinute(void) const; // Minute (0-59) - int getHour(void) const; // Hour (0-23) - int getMDay(void) const; // Day of Month (1-31) - int getWDay(void) const; // Day of Week (1-7) - int getYDay(void) const; // Day of Year (1-366) (366 = leap yr) - int getMonth(void) const; // Month (1-12) - int getYWeek(void) const; // Week of Year (1-53) - int getYear(void) const; // Year (e.g. 1997) - - // Modify the time components. Return FALSE if fail - bit8 setSecond(sint32 sec); - bit8 setMinute(sint32 min); - bit8 setHour(sint32 hour); - bit8 setYear(sint32 year); - bit8 setMonth(sint32 month); - bit8 setMDay(sint32 mday); - - void normalize(void); // move msec overflows to the day - - // Compare two times - int compare(const Xtime &other) const; - - // comparisons - bit8 operator == ( const Xtime &other ) const; - bit8 operator != ( const Xtime &other ) const; - bit8 operator < ( const Xtime &other ) const; - bit8 operator > ( const Xtime &other ) const; - bit8 operator <= ( const Xtime &other ) const; - bit8 operator >= ( const Xtime &other ) const; - - // assignments - Xtime &operator = (const Xtime &other); - Xtime &operator = (const time_t other); - - // signed - Xtime &operator += (const Xtime &other); - Xtime &operator -= (const Xtime &other); - Xtime operator + (Xtime &other); - Xtime operator - (Xtime &other); - - Xtime &operator += (const time_t other); - Xtime &operator -= (const time_t other); - Xtime operator + (time_t other); - Xtime operator - (time_t other); - - protected: - sint32 day_; // days since Jan 1, 0 - sint32 msec_; // milliseconds (thousandths of a sec) -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wnet/Makefile b/Generals/Code/Tools/mangler/wnet/Makefile deleted file mode 100644 index e5321ff0a3..0000000000 --- a/Generals/Code/Tools/mangler/wnet/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -########################################################################### -# TCP library makefile -########################################################################## - -#Define cc to be your C compiler -CC = g++ -CFLAGS = -gstabs ${INCLUDE} -D_REENTRANT #-DDEBUG - -#This tells make how to go from a .cpp to a .o -.SUFFIXES: .cpp -.cpp.o: - ${CC} ${CFLAGS} -c $< - -INCLUDE = -I.. -I. - -AR = ar -r -RM = rm -f -RANLIB = ranlib - -############################################################################ -#Dont mess with any of this stuff -OBJECTS = tcp.o udp.o packet.o field.o -LIBRARY = libwnet.a - -all: $(LIBRARY) - -$(LIBRARY): $(OBJECTS) - $(RM) $(LIBRARY) - $(AR) $(LIBRARY) $(OBJECTS) - $(RANLIB) $(LIBRARY) - -clean: - - rm -f $(LIBRARY) $(OBJECTS) core diff --git a/Generals/Code/Tools/mangler/wnet/field.cpp b/Generals/Code/Tools/mangler/wnet/field.cpp deleted file mode 100644 index 3597370937..0000000000 --- a/Generals/Code/Tools/mangler/wnet/field.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : FIELD.CPP * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/22/96 * - * * - * Last Update : April 22, 1996 [PWG] * - * * - * Actual member function for the field class. * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#include -#include -#ifndef _WINDOWS -#include -#else -#define Win32_Winsock -#include -#endif -#include "field.h" - - -// private member func -void FieldClass::Clear(void) -{ - delete[](Data); - - strcpy(ID,""); - DataType=0; - Size=0; - Data=NULL; - Next=NULL; -} - - -FieldClass::FieldClass(char *id, char data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, unsigned char data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, short data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, unsigned short data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, long data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, unsigned long data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, char *data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, void *data, int length) -{ - Data=NULL; - Set(id,data,length); -} - -void FieldClass::Set(char *id, char data) -{ - FieldClass *Nextsave=Next; - - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_CHAR; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, unsigned char data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_UNSIGNED_CHAR; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, short data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_SHORT; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, unsigned short data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_UNSIGNED_SHORT; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, long data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_LONG; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, unsigned long data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_UNSIGNED_LONG; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, char *data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_STRING; - Size = (unsigned short)(strlen(data)+1); - Data = new char[Size]; - memcpy(Data, data, Size); - Next = Nextsave; -} - - -void FieldClass::Set(char *id, void *data, int length) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_CHUNK; - Size = (unsigned short)length; - Data = new char[Size]; - memcpy(Data, data, Size); - Next = Nextsave; -} - - -FieldClass::~FieldClass() -{ - Clear(); -} - -// Fetch the datatype -int FieldClass::Get_Type(void) -{ - return(DataType); -} - -void *FieldClass::Get_Data(void) -{ -return(Data); -} - -char *FieldClass::Get_ID(void) -{ -return(ID); -} - -/************************************************************************** - * PACKETCLASS::HOST_TO_NET_FIELD -- Converts host field to net format * - * * - * INPUT: FIELD * to the data field we need to convert * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -void FieldClass::Host_To_Net(void) -{ - // - // Before we convert the data type, we should convert the actual data - // sent. - // - switch (DataType) { - case TYPE_CHAR: - case TYPE_UNSIGNED_CHAR: - case TYPE_STRING: - break; - - case TYPE_SHORT: - case TYPE_UNSIGNED_SHORT: - *((unsigned short *)Data) = htons(*((unsigned short *)Data)); - break; - - case TYPE_LONG: - case TYPE_UNSIGNED_LONG: - *((unsigned long *)Data) = htonl(*((unsigned long *)Data)); - break; - - // - // Might be good to insert some type of error message here for unknown - // datatypes -- but will leave that for later. - // - default: - break; - } - // - // Finally convert over the data type and the size of the packet. - // - DataType = htons(DataType); - Size = htons(Size); -} - -/************************************************************************** - * PACKETCLASS::NET_TO_HOST_FIELD -- Converts net field to host format * - * * - * INPUT: FIELD * to the data field we need to convert * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -void FieldClass::Net_To_Host(void) -{ - // - // Finally convert over the data type and the size of the packet. - // - DataType = ntohs(DataType); - Size = ntohs(Size); - - // - // Before we convert the data type, we should convert the actual data - // sent. - // - switch (DataType) { - case TYPE_CHAR: - case TYPE_UNSIGNED_CHAR: - case TYPE_STRING: - break; - - case TYPE_SHORT: - case TYPE_UNSIGNED_SHORT: - *((unsigned short *)Data) = ntohs(*((unsigned short *)Data)); - break; - - case TYPE_LONG: - case TYPE_UNSIGNED_LONG: - *((unsigned long *)Data) = ntohl(*((unsigned long *)Data)); - break; - - // - // Might be good to insert some type of error message here for unknown - // datatypes -- but will leave that for later. - // - default: - break; - } -} - diff --git a/Generals/Code/Tools/mangler/wnet/field.h b/Generals/Code/Tools/mangler/wnet/field.h deleted file mode 100644 index 8a58f68f55..0000000000 --- a/Generals/Code/Tools/mangler/wnet/field.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : FIELD.H * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/22/96 * - * * - * Last Update : April 22, 1996 [PWG] * - * * - * This module takes care of maintaining the field list used to process * - * packets. * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#define FIELD_HEADER_SIZE (sizeof(FieldClass) - (sizeof(void *) * 2)) - -#define TYPE_CHAR 1 -#define TYPE_UNSIGNED_CHAR 2 -#define TYPE_SHORT 3 -#define TYPE_UNSIGNED_SHORT 4 -#define TYPE_LONG 5 -#define TYPE_UNSIGNED_LONG 6 -#define TYPE_STRING 7 -#define TYPE_CHUNK 20 - -class PacketClass; - -class FieldClass -{ - public: - friend PacketClass; - // - // Define constructors to be able to create all the different kinds - // of fields. - // - FieldClass(void) {}; - FieldClass(char *id, char data); - FieldClass(char *id, unsigned char data); - FieldClass(char *id, short data); - FieldClass(char *id, unsigned short data); - FieldClass(char *id, long data); - FieldClass(char *id, unsigned long data); - FieldClass(char *id, char *data); - FieldClass(char *id, void *data, int length); - - ~FieldClass(); - - // Change the field contents - void Set(char *id, char data); - void Set(char *id, unsigned char data); - void Set(char *id, short data); - void Set(char *id, unsigned short data); - void Set(char *id, long data); - void Set(char *id, unsigned long data); - void Set(char *id, char *data); - void Set(char *id, void *data, int length); - - int Get_Type(void); // get the datatype of this field - unsigned short Get_Size(void) { return Size; } - void * Get_Data(void); // get the datatype of this field - char * Get_ID(void); // get the datatype of this field - - void Host_To_Net(void); - void Net_To_Host(void); - - private: - - void Clear(void); // dealloc mem & zero safely - - char ID[4]; // id value of this field - unsigned short DataType; // id of the data type we are using - unsigned short Size; // size of the data portion of this field - char *Data; // pointer to the data portion of this field - FieldClass *Next; // pointer to the next field in the field list -}; - - - diff --git a/Generals/Code/Tools/mangler/wnet/packet.cpp b/Generals/Code/Tools/mangler/wnet/packet.cpp deleted file mode 100644 index a2741dbe48..0000000000 --- a/Generals/Code/Tools/mangler/wnet/packet.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : PACKET.CPP * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/22/96 * - * * - * Last Update : April 24, 1996 [PWG] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * *PacketClass::Find_Field -- Finds a field if it exists in the packets * - * Get_Field -- Find specified name and returns data * - * PacketClass::~PacketClass -- destroys a packet class be freeing list * - * PacketClass::Add_Field -- Adds a FieldClass entry to head of packet li* - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#include -#include -#include -#include -#ifndef _WINDOWS -#include -#else -#define Win32_Winsock -#include -#endif - -#include "packet.h" - - -/************************************************************************** - * PACKETCLASS::~PACKETCLASS -- destroys a packet class be freeing list * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/24/1996 PWG : Created. * - *========================================================================*/ -PacketClass::~PacketClass() -{ - FieldClass *current; - FieldClass *next; - - // - // Loop through the entire field list and delete each entry. - // - for (current = Head; current; current = next) { - next = current->Next; - delete(current); - } -} - - -/************************************************************************** - * PACKETCLASS::ADD_FIELD -- Adds a FieldClass entry to head of packet li * - * * - * INPUT: FieldClass * - a properly constructed field class entry. * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/24/1996 PWG : Created. * - *========================================================================*/ -void PacketClass::Add_Field(FieldClass *field) -{ - field->Next = Head; - Head = field; -} - -/************************************************************************** - * PACKETCLASS::PACKETCLASS -- Creates a Packet object from a COMMS packe * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -PacketClass::PacketClass(char *curbuf) -{ - int remaining_size; - // - // Pull the size and packet ID out of the linear packet stream. - // - Size = *((unsigned short *)curbuf); - curbuf += sizeof(unsigned short); - Size = ntohs(Size); - ID = *((short *)curbuf); - curbuf += sizeof(unsigned short); - ID = ntohs(ID); - Head = NULL; - - // - // Calculate the remaining size so that we can loop through the - // packets and extract them. - // - remaining_size = Size - 4; - - // - // Loop through the linear packet until we run out of room and - // create a field for each. - // - while (remaining_size > 0) - { - FieldClass *field = new FieldClass; - - // - // Copy the adjusted header into the buffer and then advance the buffer - // - memcpy(field, curbuf, FIELD_HEADER_SIZE); - curbuf += FIELD_HEADER_SIZE; - remaining_size -= FIELD_HEADER_SIZE; - - // - // Copy the data into the buffer - // - int size = ntohs(field->Size); - field->Data = new char[size]; - memcpy(field->Data, curbuf, size); - curbuf += size; - remaining_size -= size; - - // - // Make sure we allow for the pad bytes. - // - int pad = (4 - (ntohs(field->Size) & 3)) & 3; - curbuf += pad; - remaining_size -= pad; - - // - // Convert the field back to the host format - // - field->Net_To_Host(); - - // - // Finally add the field to the field list in the packet - // structure. - // - Add_Field(field); - } -} - -/************************************************************************** - * CREATE_COMMS_PACKET -- Walks field list creating a packet * - * * - * INPUT: short - the id of the packet so the server can identify it * - * unsigned short & - the size of the packet returned here * - * * - * OUTPUT: void * pointer to the linear packet data * - * * - * WARNINGS: This routine allocates memory that the user is responsible * - * for freeing. * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -char *PacketClass::Create_Comms_Packet(int &size) -{ - FieldClass *current; - - // - // Size starts at four because that is the size of the packet header. - // - size = 4; - - // - // Take a quick spin through and calculate the size of the packet we - // are building. - // - for (current = Head; current; current=current->Next) - { - size += (unsigned short)FIELD_HEADER_SIZE; // add in packet header size - size += current->Size; // add in data size - size += (4 - (size & 3)) & 3; // add in pad value to dword align next packet - } - - // - // Now that we know the size allocate a buffer big enough to hold the - // packet. - // - char *retval = new char[size]; - char *curbuf = retval; - - // - // write the size into the packet header - // - *((unsigned short *)curbuf) = (unsigned short)htons(size); - curbuf += sizeof(unsigned short); - *((short *)curbuf) = htons(ID); - curbuf += sizeof(unsigned short); - - // - // Ok now that the actual header information has been written we need to write out - // field information. - // - for (current = Head; current; current = current->Next) - { - // - // Temporarily convert the packet to net format (this saves alot of - // effort, and seems safe...) - // - current->Host_To_Net(); - - // - // Copy the adjusted header into the buffer and then advance the buffer - // - memcpy(curbuf, current, FIELD_HEADER_SIZE); - curbuf += FIELD_HEADER_SIZE; - - // - // Copy the data into the buffer and then advance the buffer - // - memcpy(curbuf, current->Data, ntohs(current->Size)); - curbuf += ntohs(current->Size); - - // - // Finally take care of any pad bytes by setting them to 0 - // - int pad = (4 - (ntohs(current->Size) & 3)) & 3; - curbuf += pad; - - current->Net_To_Host(); - } - return(retval); -} - - -/************************************************************************** - * PACKETCLASS::FIND_FIELD -- Finds a field if it exists in the packets * - * * - * INPUT: char * - the id of the field we are looking for. * - * * - * OUTPUT: FieldClass * pointer to the field class * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -FieldClass *PacketClass::Find_Field(char *id) -{ - for (FieldClass *current = Head; current; current = current->Next) - { - if ( strncmp(id, current->ID, 4) == 0) - return current; - } - return NULL; -} - -// gks 9/25/2000 -FieldClass *PacketClass::Get_Field_At(int position) -{ - int i = 0; - FieldClass *current = Head; - for (; (current && (i < position)); current = current->Next, i++) { - } - - if (current) return current; - else return NULL; -} - -// gks 9/25/2000 -int PacketClass::Get_Num_Fields() -{ - int i = 0; - - for (FieldClass *current = Head; current; current = current->Next, i++) {} - - return i; - -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * char & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, char &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((char *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * unsigned char & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, unsigned char &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned char *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * short & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, short &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((short *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * unsigned short & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, unsigned short &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned short *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * long & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, long &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((long *)field->Data); - } - return((field) ? true : false); -} - - - -bit8 PacketClass::Get_Field(char *id, int &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((int *)field->Data); - } - return((field) ? true : false); -} - - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data as a string * - * * - * INPUT: char * - the id of the field that holds the data. * - * char * - the string to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The string is not changed if the field is not found. It * - * is assumed that the string variabled specified by the * - * pointer is large enough to hold the data. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, char *data) -{ - FieldClass *field = Find_Field(id); - if (field) { - strcpy(data, (char *)field->Data); - } - return((field) ? true : false); -} - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * unsigned long & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, unsigned long &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned long *)field->Data); - } - return((field) ? true : false); -} - -bit8 PacketClass::Get_Field(char *id, unsigned &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned *)field->Data); - } - return((field) ? true : false); -} - - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * void * - the reference to store the data into * - * int - the length of the buffer passed in * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 6/4/96 4:46PM ST : Created * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, void *data, int &length) -{ - FieldClass *field = Find_Field(id); - if (field) { - memcpy (data, field->Data, MIN(field->Size, length)); - length = (int) field->Size; - } - return((field) ? true : false); -} - - -unsigned short PacketClass::Get_Field_Size(char* id) -{ - FieldClass *field = Find_Field(id); - if (field) - return field->Get_Size(); - else - return 0; -} - diff --git a/Generals/Code/Tools/mangler/wnet/packet.h b/Generals/Code/Tools/mangler/wnet/packet.h deleted file mode 100644 index 1bd2141833..0000000000 --- a/Generals/Code/Tools/mangler/wnet/packet.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : PACKET.H * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/19/96 * - * * - * Last Update : April 19, 1996 [PWG] * - * * - * This header defines the functions for the PacketClass. The packet * - * class is used to create a linked list of field entries which can be * - * converted to a linear packet in a COMMS API compatible format. * - * * - * Packets can be created empty and then have fields added to them or can * - * be created from an existing linear packet. * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "field.h" -#include - - -class PacketClass -{ - public: - - PacketClass(short id = 0) - { - Size = 0; - ID = id; - Head = 0; - } - PacketClass(char *cur_buf); - ~PacketClass(); - - // - // This function allows us to add a field to the start of the list. As the field is just - // a big linked list it makes no difference which end we add a member to. - // - void Add_Field(FieldClass *field); - - // - // These conveniance functions allow us to add a field directly to the list without - // having to worry about newing one first. - // - void Add_Field(char *field, char data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, unsigned char data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, short data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, unsigned short data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, long data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, unsigned long data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, char *data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, void *data, int length) {Add_Field(new FieldClass(field, data, length));}; - - // - // These functions search for a field of a given name in the list and - // return the data via a reference value. - // - FieldClass *Find_Field(char *id); - - bit8 Get_Field(char *id, int &data); - bit8 Get_Field(char *id, char &data); - bit8 Get_Field(char *id, unsigned char &data); - bit8 Get_Field(char *id, short &data); - bit8 Get_Field(char *id, unsigned short &data); - bit8 Get_Field(char *id, long &data); - bit8 Get_Field(char *id, unsigned long &data); - bit8 Get_Field(char *id, unsigned &data); - bit8 Get_Field(char *id, char *data); - bit8 Get_Field(char *id, void *data, int &length); - unsigned short Get_Field_Size(char* id); - - // gks 9/25/2000 - FieldClass *Get_Field_At(int position); - int Get_Num_Fields(); - - char *Create_Comms_Packet(int &size); - - private: - unsigned short Size; - short ID; - FieldClass *Head; - FieldClass *Current; -}; - diff --git a/Generals/Code/Tools/mangler/wnet/tcp.cpp b/Generals/Code/Tools/mangler/wnet/tcp.cpp deleted file mode 100644 index 4c26d3231d..0000000000 --- a/Generals/Code/Tools/mangler/wnet/tcp.cpp +++ /dev/null @@ -1,1242 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -TCP Neal Kettler neal@westwood.com -****************************************************************************** - -A general purpose TCP class that can be used in either CLIENT or -SERVER mode. Note that this uses non-blocking sockets. - -The FD_* macros: - - FD_CLR(int fd, fd_set *set); // clear a single FD - FD_ISSET(int fd, fd_set *set); // check whether a single FD is set - FD_SET(int fd, fd_set *set); // set a single FD - FD_ZERO(fd_set * set); // clear the entire set - -NOTE: The fd_set returned by 'Wait' is static, don't call delete -on it! - - -If you are writing a CLIENT: - The last argument to many functions is an integer whichFD, this is used -only by SERVER mode, so you can omit this argument. Sample Code: - -fd_set *fdSet; -uint8 *buff=new uint8[1024]; -int retval; -TCP tcp(CLIENT); - -tcp.Bind((uint32)0,(uint16)0); // let system pick local IP and a Port for you -tcp.Connect("tango",13); // can connect by name or "10.1.1.10" - // or the integer in host byte order - -fdSet=tcp.Wait(10,0); // wait for UP TO 10 sec and 0 microseconds -if (FD_ISSET(tcp.GetFD(),fdSet)) // Is there something to read? -{ - retval=tcp.Read(buff,1024); // Read something - // Retval will contain the number of - // bytes read, or... - // 0 = remote end closed connection - // -1 = nothing to read - fprintf(stderr,"%s",buff); -} -else - fprintf(stderr,"Nothing was read!\n"); - - -If you are writing a SERVER: - - The structure called 'clientList' contains all the File Descriptors -that have connected to the server. Make sure you look at the FD_* -functions so you can use this sort of structure. When you are writing -a server, you need to specify the 'whichFD' arguments to all the -functions. Sample Code: - -fd_set *fdSet; -uint8 *buff=new uint8[1024]; -int retval; -TCP tcp(SERVER); - -tcp.Bind((uint32)0,(uint16)2121); // You need to bind to a well defined - // port number or nobody will know where - // to connect to. - -while (1) -{ - fdSet=tcp.Wait(-1,-1); // Wait until there is something on the socket - if (FD_ISSET(tcp.GetFD(),fdSet)) // somebody must want a connection - { - retval=tcp.GetConnection(); // Get a connection if somebody's trying - if (retval!=-1) - { - tcp.Write("Hello World!\n",strlen("Hello World!\n"),retval); - tcp.Close(retval); - } - } -} - - -\****************************************************************************/ - - -#include "tcp.h" -#include - -#ifndef _WINDOWS -#include -#define closesocket close -#endif - -// newMode should be either CLIENT or SERVER -TCP::TCP(int new_mode) -{ - mode=CLIENT; - maxFD=0; - fd = -1; - clientCount=0; - if ((new_mode==CLIENT)||(new_mode==SERVER)) - mode=new_mode; - FD_ZERO(&clientList); - connectionState=CLOSED; - inputDelay=5; - outputDelay=5; -} - -// Create a TCP object on a pre-existing socket -TCP::TCP(int new_mode,sint16 socket) -{ - sint32 retval; - - mode=CLIENT; - maxFD= socket; - fd = socket; - clientCount=0; - if ((new_mode==CLIENT)||(new_mode==SERVER)) - mode=new_mode; - FD_ZERO(&clientList); - - inputDelay=5; - outputDelay=5; - - - retval=SetBlocking(FALSE,socket); // set to NB mode - //DBGMSG("Setblocking: "<0)&&(c!=0)) - { - string[i]=c; - if (c=='\n') - return(string); - i++; - } - else if ((retval==0)&&(i==0)) - { - DBGMSG("Remote endpoint closed (1)"); - return(NULL); - } - else if (retval==0) - return(string); - } - return(string); -} - - -// only specify whichFD if this is a server -sint32 TCP::Read(uint8 *msg,uint32 len,sint32 whichFD) -{ - sint32 retval; - //DBGMSG("In read, mode: "<0) - bytes_read+=retval; - // otherwise some error - } - return(bytes_read); -} - - - -// only specify whichFD if this is a server -// Peek at data in system buffer -sint32 TCP::Peek(uint8 *msg,uint32 len,sint32 whichFD) -{ - sint32 retval; - if (mode==CLIENT) - { - retval=recv(fd,(char *)msg,len,MSG_PEEK); - if (retval==0) - Close(); - return(retval); - } - else if (mode==SERVER) - { - if ((whichFD<=maxFD) && (FD_ISSET(whichFD,&clientList))) - { - retval=recv(whichFD,(char *)msg,len,MSG_PEEK); - if (retval==0) - Close(whichFD); - return(retval); - } - else - return(0); // closed - } - return(-1); -} - - -// only specify whichFD if this is a server -// (this is used for non-8 bit clean pipes, you probably don't -// want to use it!) -sint32 TCP::EncapsulatedRead(uint8 *msg,uint32 len,sint32 whichFD) -{ - sint32 retval,bytesRead=0; - uint32 i; - char data; - - if (mode==CLIENT) - whichFD=fd; - else if (mode==SERVER) - { - if ((whichFD>maxFD) || (!FD_ISSET(whichFD,&clientList))) - return(0); - } - else - return(-1); - - for (i=0; i=0; i--) - if (FD_ISSET(i,&clientList)) - { - maxFD=i; - break; - } - } - FD_CLR((uint32)whichFD,&clientList); - clientCount--; - return(closesocket(whichFD)); - } - } - return(-1); -} - - - -// if 'sec' AND 'usec' are -1 then this will sleep until -// there is socket activity - -int TCP::Wait(sint32 sec,sint32 usec,fd_set &returnSet,sint32 whichFD) -{ - fd_set inputSet; - - FD_ZERO(&inputSet); - - if (mode==SERVER) - { - if (whichFD==0) - { - inputSet=clientList; - if (fd > 0) - FD_SET(fd,&inputSet); - } - else if (whichFD > 0) - FD_SET(whichFD,&inputSet); - } - else if (mode==CLIENT) - { - if (whichFD==0) - whichFD=fd; - if (whichFD > 0) - FD_SET(whichFD,&inputSet); - } - - return(Wait(sec,usec,inputSet,returnSet)); -} - -int TCP::Wait(sint32 sec,sint32 usec,fd_set &givenSet,fd_set &returnSet) -{ - Wtime timeout; - Wtime timenow; - Wtime timethen; - fd_set backupSet; - int retval=0,done,givenMax; - bit8 noTimeout=FALSE; - timeval tv; - - returnSet=givenSet; - backupSet=returnSet; - - if ((sec==-1)&&(usec==-1)) - noTimeout=TRUE; - - timeout.SetSec(sec); - timeout.SetUsec(usec); - timethen+=timeout; - - givenMax=maxFD; - for (uint32 i=0; i<(sizeof(fd_set)*8); i++) // i=maxFD+1 - { - if (FD_ISSET(i,&givenSet)) - givenMax=i; - } - - done=0; - while( ! done) - { - if (noTimeout) - retval=select(givenMax+1,&returnSet,0,0,NULL); - else - { - timeout.GetTimevalMT(tv); - retval=select(givenMax+1,&returnSet,0,0,&tv); - } - - if (retval>=0) - done=1; - - else if ((retval==-1)&&(errno==EINTR)) // in case of signal - { - if (noTimeout==FALSE) - { - timenow.Update(); - timeout=timethen-timenow; - } - if ((noTimeout==FALSE)&&(timenow.GetSec()==0)&&(timenow.GetUsec()==0)) - done=1; - else - returnSet=backupSet; - } - else // maybe out of memory? - { - done=1; - } - } - return(retval); -} - - -void TCP::WaitWrite(sint32 whichFD) -{ - fd_set backupSet; - int retval=0,done; - fd_set outputSet; - - if (whichFD==0) - whichFD=fd; - - if (whichFD==-1) - return; - - FD_ZERO(&outputSet); - FD_SET(whichFD,&outputSet); - backupSet=outputSet; - - done=0; - while( ! done) - { - retval=select(maxFD+1,0,&outputSet,0,NULL); - - if (retval>=0) - done=1; - - else if ((retval==-1)&&(errno==EINTR)) // in case of signal - outputSet=backupSet; - else // maybe out of memory? - done=1; - } -} - -// Can a FD be written to? -bit8 TCP::CanWrite(sint32 whichFD) -{ - int retval=0; - fd_set outputSet; - Wtime timeout; - timeval tv; - - timeout.SetSec(0); - timeout.SetUsec(0); - - if (whichFD==0) - whichFD=fd; - - FD_ZERO(&outputSet); - FD_SET(whichFD,&outputSet); - - timeout.GetTimevalMT(tv); - retval=select(whichFD+1,0,&outputSet,0,&tv); - if (retval>0) - return(TRUE); - else - return(FALSE); -} - - -bit8 TCP::Bind(char *Host,uint16 port,bit8 reuseAddr) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( Bind( ntohl(inet_addr(Host)), port,reuseAddr) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - return (0); - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( Bind(ntohl(hostNode->s_addr),port,reuseAddr) ); -} - - -// You must call bind, implicit binding is for sissies -// Well... you can get implicit binding if you pass 0 for either arg - -bit8 TCP::Bind(uint32 IP,uint16 Port,bit8 reuseAddr) -{ - int retval; - int status; - - IP=htonl(IP); - Port=htons(Port); - - addr.sin_family=AF_INET; - addr.sin_port=Port; - addr.sin_addr.s_addr=IP; - fd=socket(AF_INET,SOCK_STREAM,DEFAULT_PROTOCOL); - if (fd==-1) - return(FALSE); - - retval=SetBlocking(FALSE,fd); - if (retval==-1) - ERRMSG("Couldn't set nonblocking mode!"); - - if (reuseAddr==TRUE) - { - uint32 opval; - - #ifdef SO_REUSEPORT -/****************** this may make the socket get garbage data?? - opval=1; - retval=setsockopt(fd,SOL_SOCKET,SO_REUSEPORT,(char *)&opval,sizeof(opval)); - if (retval!=0) - fprintf(stderr,"Could not set socket to SO_REUSEPORT\n"); -**********************/ - #endif - #ifdef SO_REUSEADDR - opval=1; - retval=setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char *)&opval,sizeof(opval)); - if (retval!=0) - fprintf(stderr,"Could not set socket to SO_REUSEADDR\n"); - #endif - } - - retval=bind(fd,(struct sockaddr *)&addr,sizeof(addr)); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - - if (retval==-1) - { - status=GetStatus(); - DBGMSG("Bind failure (" << status << ") IP "<< IP <<" PORT "<< ntohs(Port)); - return(FALSE); - } - myIP=IP; - myPort=Port; - maxFD=fd; - - if (mode==SERVER) - listen(fd,64); //Solaris needs lots of listen slots for some reason - - return(TRUE); -} - - -// This is only for clients - -bit8 TCP::Connect(char *Host,uint16 port) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( Connect( ntohl(inet_addr(Host)), port) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - {ERRMSG("Can't resolve host");return (0);} - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( Connect(ntohl(hostNode->s_addr),port) ); -} - -bit8 TCP::Connect(uint32 IP,uint16 Port) -{ - int tries,result; - struct timeval sleep_time; - struct sockaddr_in serverAddr; - int status; - - IP=htonl(IP); - Port=htons(Port); - - serverAddr.sin_family=AF_INET; - serverAddr.sin_port=Port; - serverAddr.sin_addr.s_addr=IP; - - if (mode!=CLIENT) - {ERRMSG("Can't connect in server mode");return(FALSE);} - - tries=0; - result=-1; - - - // try 10 connects with a greater and greater sleep time after each one - // this can go on for upto 5.4 seconds - while ((tries < 10) && (result == -1)) - { - ClearStatus(); - result = connect(fd,(struct sockaddr *)&serverAddr, sizeof(serverAddr)); - status=GetStatus(); - - #ifdef _WINDOWS - if (result==SOCKET_ERROR) - result=-1; - #endif - - if ((status == ISCONN) && (result == -1)) - { - result = 0; - } - if (result == -1) - { - if ((status!=INPROGRESS)&&(status!=ALREADY)&&(status!=AGAIN)&& - (status!=WOULDBLOCK)) - { - Close(); - Bind(myIP,myPort); - } - tries++; - sleep_time.tv_sec = 0; - sleep_time.tv_usec = (100000*(tries+1)); - #ifdef WIN32 - Sleep((sleep_time.tv_usec)/1000); - #else - select(0, 0, 0, 0, &sleep_time); - #endif - } - } - - if (result == -1) - { - return(FALSE); - } - connectionState=CONNECTED; - return (TRUE); -} - - - -// Asynchronous Connection -bit8 TCP::ConnectAsync(char *Host,uint16 port) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( ConnectAsync( ntohl(inet_addr(Host)), port) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - return (0); - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( ConnectAsync(ntohl(hostNode->s_addr),port) ); -} - -// Asynchronous Connection -bit8 TCP::ConnectAsync(uint32 IP,uint16 Port) -{ - int result; - struct sockaddr_in serverAddr; - int status,connectErrno; - int retval; - - IP=htonl(IP); - Port=htons(Port); - - serverAddr.sin_family=AF_INET; - serverAddr.sin_port=Port; - serverAddr.sin_addr.s_addr=IP; - - if (mode!=CLIENT) - return(FALSE); - - result=-1; - - if (connectionState==CONNECTING) - { - if (IsConnected(fd)) - { - DBGMSG("CONNECTION COMPLETE at point 1"); - connectionState=CONNECTED; - return(TRUE); - } - else - return(TRUE); // Still trying - } - - ClearStatus(); - result = connect(fd,(struct sockaddr *)&serverAddr, sizeof(serverAddr)); - connectErrno=errno; - status=GetStatus(); - - #ifdef _WINDOWS - if (result==SOCKET_ERROR) - { - DBGMSG("Socket error 1 " << status); - result=-1; - } - #endif - - // If we have a bogus FD, try again after closing and re-binding - if ((result==-1)&&((status==BADF)||(status==NOTSOCK)||(status==INVAL))) - { - Close(); - retval=Bind(myIP,myPort); - DBGMSG("BIND = "<maxFD) - maxFD=clientFD; - FD_SET(clientFD,&clientList); - clientCount++; - } - return(clientFD); -} - -sint32 TCP::GetConnection(struct sockaddr *clientAddr) -{ - if (mode!=SERVER) - return(-1); - - sint32 clientFD; - int addrlen=sizeof(struct sockaddr); - - clientFD=accept(fd,(struct sockaddr *)clientAddr,&addrlen); - if (clientFD!=-1) - { - if (clientFD>maxFD) - maxFD=clientFD; - FD_SET(clientFD,&clientList); - clientCount++; - } - return(clientFD); -} - diff --git a/Generals/Code/Tools/mangler/wnet/tcp.h b/Generals/Code/Tools/mangler/wnet/tcp.h deleted file mode 100644 index 3f63e4e9d3..0000000000 --- a/Generals/Code/Tools/mangler/wnet/tcp.h +++ /dev/null @@ -1,199 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -TCP Neal Kettler neal@westwood.com - -\****************************************************************************/ - -#ifndef TCP_HEADER -#define TCP_HEADER - -#include -#include -#include -#include -#include -#include - -#ifdef _WINDOWS - -#include -#include -#define close _close -#define read _read -#define write _write - -#else //UNIX -#include -#include -#include -#include -#include -#include -#include -#include -#include - -typedef signed int SOCKET; - -#endif - - -#ifdef AIX -#include -#endif - -#define DEFAULT_PROTOCOL 0 - -#include "wlib/wstypes.h" -#include "wlib/wdebug.h" -#include "wlib/wtime.h" - -class TCP -{ - -// DATA --------------- - -private: - int mode; // client or server - sint32 fd; // the primary FD - - uint32 myIP; // after bind myIP & myPort will be - uint16 myPort; // whatever we bound to - - struct sockaddr_in addr; - int maxFD; // value of the biggest FD - int clientCount; // how many clients open - - - sint32 inputDelay; // default delay for semi-blocking reads - sint32 outputDelay; // default delay for semi-blocking writes - - enum ConnectionState - { - CLOSED, - CONNECTING, - CONNECTED - } connectionState; // What state is client FD in - -public: - - enum - { - CLIENT = 1, - SERVER = 2 - }; - - // These defines specify a system independent way to - // get error codes for socket services. - enum - { - OK, // Everything's cool - UNKNOWN, // There was an error of unknown type - ISCONN, // The socket is already connected - INPROGRESS, // The socket is non-blocking and the operation - // isn't done yet - ALREADY, // The socket is already attempting a connection - // but isn't done yet - AGAIN, // Try again. - ADDRINUSE, // Address already in use - ADDRNOTAVAIL, // That address is not available on the remote host - BADF, // Not a valid FD - CONNREFUSED, // Connection was refused - INTR, // Operation was interrupted - NOTSOCK, // FD wasn't a socket - PIPE, // That operation just made a SIGPIPE - WOULDBLOCK, // That operation would block - INVAL, // Invalid - TIMEDOUT // Timeout - }; - - // for client list (if this is a server) - fd_set clientList; - - -// CODE ---------------- - -public: - TCP(int newMode); - TCP(int newMode,sint16 socket); - ~TCP(); - bit8 Bind(uint32 IP,uint16 port,bit8 reuseAddr=FALSE); - bit8 Bind(char *Host,uint16 port,bit8 reuseAddr=FALSE); - - sint32 GetMaxFD(void); - - bit8 Connect(uint32 IP,uint16 port); - bit8 Connect(char *Host,uint16 port); - bit8 ConnectAsync(uint32 IP,uint16 port); - bit8 ConnectAsync(char *Host,uint16 port); - - bit8 IsConnected(sint32 whichFD=0); - - sint32 GetFD(void); - sint32 GetClientCount(void) { return(clientCount); } - - // Get IP or Port of a connected endpoint - uint32 GetRemoteIP(sint32 whichFD=0); - uint16 GetRemotePort(sint32 whichFD=0); - - sint32 GetConnection(void); - sint32 GetConnection(struct sockaddr *clientAddr); - void WaitWrite(sint32 whichFD=0); - bit8 CanWrite(sint32 whichFD=0); - sint32 Write(const uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 WriteNB(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 EncapsulatedWrite(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 WriteString(char *msg,sint32 whichFD=0); - sint32 Printf(sint32 whichFD,const char *format,...); - sint32 Read(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 TimedRead(uint8 *msg,uint32 len,int seconds,sint32 whichFD=0); - sint32 Peek(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 EncapsulatedRead(uint8 *msg,uint32 len,sint32 whichFD=0); - - char *Gets(char *string,int n,int whichFD=0); - - // Wait on all sockets (or a specified one) - // return when ready for reading (or timeout occurs) - int Wait(sint32 sec,sint32 usec,fd_set &returnSet,sint32 whichFD=0); - int Wait(sint32 sec,sint32 usec,fd_set &inputSet,fd_set &returnSet); - - int GetStatus(void); - void ClearStatus(void); - - //sint32 GetSockStatus(sint32 whichFD=0); - - // give up ownership of the socket without closing it - void DisownSocket(void); - - sint32 Close(sint32 whichFD=0); - sint32 CloseAll(void); // close all sockets (same as close for client) - - sint32 SetBlocking(bit8 block,sint32 whichFD=0); - - // Set default delays for semi-blocking reads & writes - // default input = 5, output = 5 - // this is new and not used everywhere - // - bit8 SetInputDelay(sint32 delay) { inputDelay=delay; return(TRUE); }; - bit8 SetOutputDelay(sint32 delay) { outputDelay=delay; return(TRUE); }; - -}; - -#endif diff --git a/Generals/Code/Tools/mangler/wnet/udp.cpp b/Generals/Code/Tools/mangler/wnet/udp.cpp deleted file mode 100644 index afa6d16150..0000000000 --- a/Generals/Code/Tools/mangler/wnet/udp.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "udp.h" -#include "wlib/wdebug.h" - -UDP::UDP() -{ - fd=0; -} - -UDP::~UDP() -{ -} - -sint32 UDP::Bind(char *Host,uint16 port) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( Bind( ntohl(inet_addr(Host)), port) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - return (0); - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( Bind(ntohl(hostNode->s_addr),port) ); -} - -// You must call bind, implicit binding is for sissies -// Well... you can get implicit binding if you pass 0 for either arg -sint32 UDP::Bind(uint32 IP,uint16 Port) -{ - int retval; - int status; - - IP=htonl(IP); - Port=htons(Port); - - addr.sin_family=AF_INET; - addr.sin_port=Port; - addr.sin_addr.s_addr=IP; - fd=socket(AF_INET,SOCK_DGRAM,DEFAULT_PROTOCOL); - #ifdef _WINDOWS - if (fd==SOCKET_ERROR) - fd=-1; - #endif - if (fd==-1) - return(UNKNOWN); - - retval=bind(fd,(struct sockaddr *)&addr,sizeof(addr)); - - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - if (retval==-1) - { - status=GetStatus(); - //CERR("Bind failure (" << status << ") IP " << IP << " PORT " << Port ) - return(status); - } - - int namelen=sizeof(addr); - getsockname(fd, (struct sockaddr *)&addr, &namelen); - - myIP=ntohl(addr.sin_addr.s_addr); - myPort=ntohs(addr.sin_port); - - retval=SetBlocking(FALSE); - if (retval==-1) - fprintf(stderr,"Couldn't set nonblocking mode!\n"); - - return(OK); -} - -bit8 UDP::getLocalAddr(uint32 &ip, uint16 &port) -{ - ip=myIP; - port=myPort; - return(OK); -} - - -// private function -sint32 UDP::SetBlocking(bit8 block) -{ - #ifdef _WINDOWS - unsigned long flag=1; - if (block) - flag=0; - int retval; - retval=ioctlsocket(fd,FIONBIO,&flag); - if (retval==SOCKET_ERROR) - return(UNKNOWN); - else - return(OK); - #else // UNIX - int flags = fcntl(fd, F_GETFL, 0); - if (block==FALSE) // set nonblocking - flags |= O_NONBLOCK; - else // set blocking - flags &= ~(O_NONBLOCK); - - if (fcntl(fd, F_SETFL, flags) < 0) - { - return(UNKNOWN); - } - return(OK); - #endif -} - - -sint32 UDP::Write(uint8 *msg,uint32 len,uint32 IP,uint16 port) -{ - sint32 retval; - struct sockaddr_in to; - - // This happens frequently - if ((IP==0)||(port==0)) return(ADDRNOTAVAIL); - - errno=0; - to.sin_port=htons(port); - to.sin_addr.s_addr=htonl(IP); - to.sin_family=AF_INET; - - ClearStatus(); - retval=sendto(fd,(char *)msg,len,0,(struct sockaddr *)&to,sizeof(to)); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - - return(retval); -} - -sint32 UDP::Read(uint8 *msg,uint32 len,sockaddr_in *from) -{ - sint32 retval; - int alen=sizeof(sockaddr_in); - - if (from!=NULL) - { - retval=recvfrom(fd,(char *)msg,len,0,(struct sockaddr *)from,&alen); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - } - else - { - retval=recvfrom(fd,(char *)msg,len,0,NULL,NULL); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - } - return(retval); -} - - -void UDP::ClearStatus(void) -{ - #ifndef _WINDOWS - errno=0; - #endif -} - -UDP::sockStat UDP::GetStatus(void) -{ - #ifdef _WINDOWS - int status=WSAGetLastError(); - if (status==0) return(OK); - else if (status==WSAEINTR) return(INTR); - else if (status==WSAEINPROGRESS) return(INPROGRESS); - else if (status==WSAECONNREFUSED) return(CONNREFUSED); - else if (status==WSAEINVAL) return(INVAL); - else if (status==WSAEISCONN) return(ISCONN); - else if (status==WSAENOTSOCK) return(NOTSOCK); - else if (status==WSAETIMEDOUT) return(TIMEDOUT); - else if (status==WSAEALREADY) return(ALREADY); - else if (status==WSAEWOULDBLOCK) return(WOULDBLOCK); - else if (status==WSAEBADF) return(BADF); - else return(UNKNOWN); - #else - int status=errno; - if (status==0) return(OK); - else if (status==EINTR) return(INTR); - else if (status==EINPROGRESS) return(INPROGRESS); - else if (status==ECONNREFUSED) return(CONNREFUSED); - else if (status==EINVAL) return(INVAL); - else if (status==EISCONN) return(ISCONN); - else if (status==ENOTSOCK) return(NOTSOCK); - else if (status==ETIMEDOUT) return(TIMEDOUT); - else if (status==EALREADY) return(ALREADY); - else if (status==EAGAIN) return(AGAIN); - else if (status==EWOULDBLOCK) return(WOULDBLOCK); - else if (status==EBADF) return(BADF); - else return(UNKNOWN); - #endif -} - - - -// -// Wait for net activity on this socket -// -int UDP::Wait(sint32 sec,sint32 usec,fd_set &returnSet) -{ - fd_set inputSet; - - FD_ZERO(&inputSet); - FD_SET(fd,&inputSet); - - return(Wait(sec,usec,inputSet,returnSet)); -} - -// -// Wait for net activity on a list of sockets -// -int UDP::Wait(sint32 sec,sint32 usec,fd_set &givenSet,fd_set &returnSet) -{ - Wtime timeout,timenow,timethen; - fd_set backupSet; - int retval=0,done,givenMax; - bit8 noTimeout=FALSE; - timeval tv; - - returnSet=givenSet; - backupSet=returnSet; - - if ((sec==-1)&&(usec==-1)) - noTimeout=TRUE; - - timeout.SetSec(sec); - timeout.SetUsec(usec); - timethen+=timeout; - - givenMax=fd; - for (uint32 i=0; i<(sizeof(fd_set)*8); i++) // i=maxFD+1 - { - if (FD_ISSET(i,&givenSet)) - givenMax=i; - } - ///DBGMSG("WAIT fd="<. -*/ - -#ifndef UDP_HEADER -#define UDP_HEADER - -#include -#include -#include -#include -#include - -#ifdef _WINDOWS -#include -#include -#define close _close -#define read _read -#define write _write - -#else //UNIX -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -#ifdef AIX -#include -#endif - -#define DEFAULT_PROTOCOL 0 - -#include -#include - -class UDP -{ - // DATA - private: - sint32 fd; - uint32 myIP; - uint16 myPort; - struct sockaddr_in addr; - - // These defines specify a system independent way to - // get error codes for socket services. - enum sockStat - { - OK = 0, // Everything's cool - UNKNOWN = -1, // There was an error of unknown type - ISCONN = -2, // The socket is already connected - INPROGRESS = -3, // The socket is non-blocking and the operation - // isn't done yet - ALREADY = -4, // The socket is already attempting a connection - // but isn't done yet - AGAIN = -5, // Try again. - ADDRINUSE = -6, // Address already in use - ADDRNOTAVAIL = -7, // That address is not available on the remote host - BADF = -8, // Not a valid FD - CONNREFUSED = -9, // Connection was refused - INTR =-10, // Operation was interrupted - NOTSOCK =-11, // FD wasn't a socket - PIPE =-12, // That operation just made a SIGPIPE - WOULDBLOCK =-13, // That operation would block - INVAL =-14, // Invalid - TIMEDOUT =-15 // Timeout - }; - -// CODE - private: - sint32 SetBlocking(bit8 block); - - public: - UDP(); - ~UDP(); - sint32 Bind(uint32 IP,uint16 port); - sint32 Bind(char *Host,uint16 port); - sint32 Write(uint8 *msg,uint32 len,uint32 IP,uint16 port); - sint32 Read(uint8 *msg,uint32 len,sockaddr_in *from); - sockStat GetStatus(void); - void ClearStatus(void); - int Wait(sint32 sec,sint32 usec,fd_set &returnSet); - int Wait(sint32 sec,sint32 usec,fd_set &givenSet,fd_set &returnSet); - - bit8 getLocalAddr(uint32 &ip, uint16 &port); - sint32 getFD(void) { return(fd); } - - bit8 SetInputBuffer(uint32 bytes); - bit8 SetOutputBuffer(uint32 bytes); - int GetInputBuffer(void); - int GetOutputBuffer(void); -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/debug.cpp b/Generals/Code/Tools/matchbot/debug.cpp deleted file mode 100644 index 642fc38d22..0000000000 --- a/Generals/Code/Tools/matchbot/debug.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: debug.cpp //////////////////////////////////////////////////////// -// Minmal debug info -// Author: Matthew D. Campbell, Sept 2002 - -#include -#include "debug.h" -#include - -#ifdef DEBUG - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef _WINDOWS - -#include -void DebugCrash( const char *fmt, ... ) {} -char* TheCurrentIgnoreCrashPtr; - -#else - -#endif - -void DebugLog(const char *fmt, ...) -{ - static char buffer[1024]; - va_list va; - va_start( va, fmt ); - vsnprintf(buffer, 1024, fmt, va ); - buffer[1023] = 0; - va_end( va ); - - //printf( buffer ); - DBGMSG(buffer); -} - -#ifdef __cplusplus -} -#endif - -#endif // DEBUG - diff --git a/Generals/Code/Tools/matchbot/debug.h b/Generals/Code/Tools/matchbot/debug.h deleted file mode 100644 index 2749241fee..0000000000 --- a/Generals/Code/Tools/matchbot/debug.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: debug.h ////////////////////////////////////////////////////////////// -// Minimal debug info -// Author: Matthew D. Campbell, Sept 2002 - -#ifndef __DEBUG_H__ -#define __DEBUG_H__ - -#ifdef DEBUG - -#include - -#ifdef __cplusplus -extern "C" { -#endif -void DebugLog( const char *fmt, ... ); -#ifdef __cplusplus -} -#endif -#define DEBUG_LOG(x) DebugLog x - -#else // DEBUG - -#define DEBUG_LOG(x) {} - -#endif // DEBUG - -#endif // __DEBUG_H__ - diff --git a/Generals/Code/Tools/matchbot/encrypt.cpp b/Generals/Code/Tools/matchbot/encrypt.cpp deleted file mode 100644 index 06950a9001..0000000000 --- a/Generals/Code/Tools/matchbot/encrypt.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include -#include -#include "encrypt.h" - -#define MAX_CHARS 65 -static char Base_String[MAX_CHARS] = - - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"; - -static char Return_Buffer[MAX_ENCRYPTED_STRING + 1]; -static char Temp_Buffer [MAX_ENCRYPTED_STRING + 1]; - -/*******************************************************/ -/* This function is a simple one-way encryption that */ -/* is portable across many platforms */ -/* */ -/* The 'String' to encrypt MUST be up to 8 chars long */ -/* and should be no shorter than 4 characters. */ -/* It can contain letters and numbers and '.' and '/' */ -/*******************************************************/ - -/* String is the original string to encrypt */ -/* Seed is the string to encrypt */ -//char *encrypt(char *String, char *Seed) -char *do_encrypt(char *String) -{ - /* We need a 56 bit key, so use two 32 bit values */ - /* and we'll strip off the high order 8 bits */ - //unsigned long Random_Seed_Value_high = 0; /* 32 bit seed value */ - //unsigned long Random_Seed_Value_low = 0; /* 32 bit seed value */ - //unsigned long Temp_high = 0; /* 32 bit storage value */ - //unsigned long Temp_low = 0; /* 32 bit storage value */ - unsigned int UpCnt = 0, DnCnt = 0, Cnt = 0; - unsigned int Length = strlen(String); - - /* Ok, here is the algorithm: */ - /* */ - - if (Length > MAX_ENCRYPTED_STRING) - Length = MAX_ENCRYPTED_STRING; - - for (UpCnt = 0, DnCnt = Length; UpCnt < Length; UpCnt++, DnCnt--) - if (String[UpCnt] & 0x01) - Temp_Buffer[UpCnt] = (String[UpCnt] << (String[UpCnt] & 0x01)) & - String[DnCnt]; - else - Temp_Buffer[UpCnt] = (String[UpCnt] << (String[UpCnt] & 0x01)) ^ - String[DnCnt]; - - for (Cnt = 0; Cnt < MAX_ENCRYPTED_STRING; Cnt++) - Return_Buffer[Cnt] = Base_String[Temp_Buffer[Cnt] & 0x3F]; - - Return_Buffer[Cnt] = NULL; - return (Return_Buffer); - -} - - -#ifdef UNIT_TEST -void main(void) -{ - char Input_String[9]; - char *new_string; - - while (1) - { - printf ("Enter a string to encrypt:"); - gets(Input_String); - printf("\nString enterred was: %s", Input_String); - new_string = encrypt(Input_String, "ab"); - printf("\nEncrypted string is: %s", new_string); - } -} - -#endif - diff --git a/Generals/Code/Tools/matchbot/encrypt.h b/Generals/Code/Tools/matchbot/encrypt.h deleted file mode 100644 index 97f7d69ed4..0000000000 --- a/Generals/Code/Tools/matchbot/encrypt.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef ENCRYPT_HEADER -#define ENCRYPT_HEADER - -#define MAX_ENCRYPTED_STRING 8 -//char *do_encrypt(char *, char *); -char *do_encrypt(char *); - -#endif - - diff --git a/Generals/Code/Tools/matchbot/generals.cpp b/Generals/Code/Tools/matchbot/generals.cpp deleted file mode 100644 index 3a72c24d51..0000000000 --- a/Generals/Code/Tools/matchbot/generals.cpp +++ /dev/null @@ -1,1322 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifdef _WIN32 -#include -#endif - -#include -#include -#include -#include "mydebug.h" - -#include - -#include -#include -#include -#include - -#ifdef _UNIX -using namespace std; -#endif - -/* -#ifdef IN -#undef IN -#endif -#define IN const -*/ -#include "generals.h" -/* -#ifdef IN -#undef IN -#endif -#define IN const -*/ -#include "global.h" -/* -#ifdef IN -#undef IN -#endif -#define IN const -*/ - -std::string intToString(int val) -{ - std::string s = ""; - bool neg = (val < 0); - if (val < 0) - { - val = -val; - } - if (val == 0) - return "0"; - - char buf[2]; - buf[1] = 0; - while (val) - { - buf[0] = '0' + val%10; - val /= 10; - s.insert(0, buf); - } - if (neg) - s.insert(0, "-"); - return s; -} - -std::string uintToString(unsigned int val) -{ - std::string s = ""; - if (val == 0) - return "0"; - - char buf[2]; - buf[1] = 0; - while (val) - { - buf[0] = '0' + val%10; - val /= 10; - s.insert(0, buf); - } - return s; -} - -MapBitSet MapSetUnion(const MapBitSet& a, const MapBitSet& b) -{ - MapBitSet c; - if (a.size() != b.size()) - return c; - - for (int i=0; i<(int)a.size(); ++i) - { - c.push_back(a[i] && b[i]); - } - - return c; -} - -int MapSetCount(const MapBitSet& a) -{ - int count=0; - for (int i=0; i<(int)a.size(); ++i) - { - //DBGMSG(a[i]); - if (a[i]) - ++count; - } - return count; -} - -// ===================================================================== -// Users -// ===================================================================== - -GeneralsUser::GeneralsUser(void) -{ - status = STATUS_INCHANNEL; - points = 1; - minPoints = maxPoints = 100; - country = color = -1; - pseudoPing.clear(); - matchStart = time(NULL); - timeToWiden = 0; - widened = false; - numPlayers = 2; - discons = maxDiscons = 2; - maps.clear(); - maxPing = 1000; -} - -static const int MaxPingValue = 255*255*2; - -int calcPingDelta(const GeneralsUser *a, const GeneralsUser *b) -{ - if (!a || !b || a->pseudoPing.size() != b->pseudoPing.size()) - return MaxPingValue; // Max ping - - int bestPing = MaxPingValue; - for (int i=0; i<(int)a->pseudoPing.size(); ++i) - { - int p1, p2; - p1 = a->pseudoPing[i]; - p2 = b->pseudoPing[i]; - - if (p1 * p1 + p2 * p2 < bestPing) - bestPing = p1 * p1 + p2 * p2; - } - - return (int)sqrt(bestPing); -} - - -// ===================================================================== -// Matcher thread -// ===================================================================== - -GeneralsMatcher::GeneralsMatcher() -{ - // Read some values from the config file - int quietTMP = 0; - Global.config.getInt("NOECHO", quietTMP); - if (quietTMP) - quiet = true; - else - quiet = false; - - // Grab the weights for different parameters - Global.config.getInt("MATCH_WEIGHT_LOWPING", weightLowPing, "GENERALS"); - Global.config.getInt("MATCH_WEIGHT_AVGPOINTS", weightAvgPoints, "GENERALS"); - totalWeight = weightLowPing + weightAvgPoints; - - INFMSG("weightLowPing = " << weightLowPing); - INFMSG("weightAvgPoints = " << weightAvgPoints); - INFMSG("totalWeight = " << totalWeight); - - Global.config.getInt("SecondsBetweenPoolSizeAnnouncements", m_secondsBetweenPoolSizeAnnouncements, NULL); - if (m_secondsBetweenPoolSizeAnnouncements < 10) - { - m_secondsBetweenPoolSizeAnnouncements = 10; - } - m_nextPoolSizeAnnouncement = time(NULL); -} - -void GeneralsMatcher::init(void) -{} - - -#define W(x) setw(x) << -void GeneralsMatcher::dumpUsers(void) -{} - - - -void GeneralsMatcher::sendMatchInfo(std::string name1, std::string name2, std::string name3, std::string name4, - std::string name5, std::string name6, std::string name7, std::string name8, - GeneralsUser *user1, GeneralsUser *user2, GeneralsUser *user3, GeneralsUser *user4, - GeneralsUser *user5, GeneralsUser *user6, GeneralsUser *user7, GeneralsUser *user8, - int numPlayers, int ladderID) -{ - MapBitSet tmp = MapSetUnion(user1->maps, user2->maps); - if (numPlayers > 2) - { - tmp = MapSetUnion(tmp, user3->maps); - tmp = MapSetUnion(tmp, user4->maps); - } - if (numPlayers > 4) - { - tmp = MapSetUnion(tmp, user5->maps); - tmp = MapSetUnion(tmp, user6->maps); - } - if (numPlayers > 6) - { - tmp = MapSetUnion(tmp, user7->maps); - tmp = MapSetUnion(tmp, user8->maps); - } - - int numMaps = MapSetCount(tmp); - - if (!numMaps) - { - DBGMSG("No maps!"); - user1->status = STATUS_WORKING; - user2->status = STATUS_WORKING; - if (numPlayers > 2) - { - user3->status = STATUS_WORKING; - user4->status = STATUS_WORKING; - } - if (numPlayers > 4) - { - user5->status = STATUS_WORKING; - user6->status = STATUS_WORKING; - } - if (numPlayers > 6) - { - user7->status = STATUS_WORKING; - user8->status = STATUS_WORKING; - } - return; - } - user1->status = STATUS_MATCHED; - user2->status = STATUS_MATCHED; - if (numPlayers > 2) - { - user3->status = STATUS_MATCHED; - user4->status = STATUS_MATCHED; - } - if (numPlayers > 4) - { - user5->status = STATUS_MATCHED; - user6->status = STATUS_MATCHED; - } - if (numPlayers > 6) - { - user7->status = STATUS_MATCHED; - user8->status = STATUS_MATCHED; - } - - int whichMap = Global.rnd.Int(0, RAND_MAX-1); - DBGMSG(whichMap); - whichMap = whichMap%numMaps; - DBGMSG(whichMap); - ++whichMap; - DBGMSG(whichMap); - DBGMSG("Random map #" << whichMap << "/" << numMaps); - - int i; - for (i=0; i<(int)user1->maps.size(); ++i) - { - if (tmp[i]) - --whichMap; - if (whichMap == 0) - break; - } - DBGMSG("Playing on map in pos " << i); - - std::string s; - s = "MBOT:MATCHED "; - s.append(intToString(i)); - s.append(" "); - s.append(intToString( Global.rnd.Int(0, RAND_MAX-1) )); - s.append(" "); - s.append(name1); - s.append(" "); - s.append(uintToString(user1->IP)); - s.append(" "); - s.append(intToString(user1->country)); - s.append(" "); - s.append(intToString(user1->color)); - s.append(" "); - s.append(intToString(user1->NAT)); - s.append(" "); - s.append(name2); - s.append(" "); - s.append(uintToString(user2->IP)); - s.append(" "); - s.append(intToString(user2->country)); - s.append(" "); - s.append(intToString(user2->color)); - s.append(" "); - s.append(intToString(user2->NAT)); - if (user3) - { - s.append(" "); - s.append(name3); - s.append(" "); - s.append(uintToString(user3->IP)); - s.append(" "); - s.append(intToString(user3->country)); - s.append(" "); - s.append(intToString(user3->color)); - s.append(" "); - s.append(intToString(user3->NAT)); - } - if (user4) - { - s.append(" "); - s.append(name4); - s.append(" "); - s.append(uintToString(user4->IP)); - s.append(" "); - s.append(intToString(user4->country)); - s.append(" "); - s.append(intToString(user4->color)); - s.append(" "); - s.append(intToString(user4->NAT)); - } - if (user5) - { - s.append(" "); - s.append(name5); - s.append(" "); - s.append(uintToString(user5->IP)); - s.append(" "); - s.append(intToString(user5->country)); - s.append(" "); - s.append(intToString(user5->color)); - s.append(" "); - s.append(intToString(user5->NAT)); - } - if (user6) - { - s.append(" "); - s.append(name6); - s.append(" "); - s.append(uintToString(user6->IP)); - s.append(" "); - s.append(intToString(user6->country)); - s.append(" "); - s.append(intToString(user6->color)); - s.append(" "); - s.append(intToString(user6->NAT)); - } - if (user7) - { - s.append(" "); - s.append(name7); - s.append(" "); - s.append(uintToString(user7->IP)); - s.append(" "); - s.append(intToString(user7->country)); - s.append(" "); - s.append(intToString(user7->color)); - s.append(" "); - s.append(intToString(user7->NAT)); - } - if (user8) - { - s.append(" "); - s.append(name8); - s.append(" "); - s.append(uintToString(user8->IP)); - s.append(" "); - s.append(intToString(user8->country)); - s.append(" "); - s.append(intToString(user8->color)); - s.append(" "); - s.append(intToString(user8->NAT)); - } - - std::string n; - n = name1; - n.append(","); - n.append(name2); - if (user3) - { - n.append(","); - n.append(name3); - } - if (user4) - { - n.append(","); - n.append(name4); - } - if (user5) - { - n.append(","); - n.append(name5); - } - if (user6) - { - n.append(","); - n.append(name6); - } - if (user7) - { - n.append(","); - n.append(name7); - } - if (user8) - { - n.append(","); - n.append(name8); - } - peerMessagePlayer(m_peer, n.c_str(), s.c_str(), NormalMessage); -} - -void GeneralsMatcher::checkMatches(void) -{ - bool showPoolSize = false; - time_t now = time(NULL); - if (now > m_nextPoolSizeAnnouncement) - { - m_nextPoolSizeAnnouncement = now + m_secondsBetweenPoolSizeAnnouncements; - showPoolSize = true; - } - checkMatchesInUserMap(m_nonLadderUsers1v1, 0, 2, showPoolSize); - checkMatchesInUserMap(m_nonLadderUsers2v2, 0, 4, showPoolSize); - checkMatchesInUserMap(m_nonLadderUsers3v3, 0, 6, showPoolSize); - checkMatchesInUserMap(m_nonLadderUsers4v4, 0, 8, showPoolSize); - - for (LadderMap::iterator it = m_ladders.begin(); it != m_ladders.end(); ++it) - { - checkMatchesInUserMap(it->second, it->first, 2, showPoolSize); - } -} - -double GeneralsMatcher::computeMatchFitness(const std::string& i1, const GeneralsUser *u1, const std::string& i2, const GeneralsUser *u2) -{ - //DBGMSG("matching "<status != STATUS_WORKING || u2->status != STATUS_WORKING) - return 0.0; - - // see if they pinged the same # of servers (sanity). - if (u1->pseudoPing.size() != u2->pseudoPing.size()) - return 0.0; - - // check point percentage ranges - int p1 = max(1,u1->points), p2 = max(1,u2->points); - double p1percent = (double)p2/(double)p1; - double p2percent = (double)p1/(double)p2; - //DBGMSG("points: " << p1 << "," << p2 << " - " << p1percent << "," << p2percent); - if (!u1->widened && ( p1percent < u1->minPoints || p1percent > u1->maxPoints )) - return 0.0; - - if (!u2->widened && ( p2percent < u2->minPoints || p2percent > u2->maxPoints )) - return 0.0; - - - int minP = min(p1, p2); - int maxP = max(p1, p2); - double pointPercent = (double)minP/(double)maxP; - //DBGMSG("\tpointPercent = "<widened && pingDelta > u1->maxPing) - return 0.0; - if (!u2->widened && pingDelta > u2->maxPing) - return 0.0; - //DBGMSG("pingDelta="<discons << "," << u1->maxDiscons << " " << u2->discons << "," << u2->maxDiscons); - // check discons - if (u1->maxDiscons && (!u1->widened && u2->discons > u1->maxDiscons)) - return 0.0; - if (u2->maxDiscons && (!u2->widened && u1->discons > u2->maxDiscons)) - return 0.0; - //DBGMSG("Made it through discons"); - - { - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - if (!MapSetCount(tmp)) - return 0.0; - } - - // they have something in common. calculate match fitness. - double matchFitness = ( weightAvgPoints * (1-pointPercent) + - weightLowPing * (MaxPingValue - pingDelta)/MaxPingValue ) / (double)totalWeight; - //DBGMSG("Match fitness: "<first << " vs " << i2->first << " has fitness " << matchFitness << "\n" - "\tpointPercent: " << pointPercent << "\n" - "\tpingDelta: " << pingDelta << "\n" - "\twidened: " << u1->widened << u2->widened << "\n" - "\tweightAvgPoints: " << weightAvgPoints << "\n" - "\tweightLowPing: " << weightLowPing << "\n" - "\ttotalWeight: " << totalWeight - ); - */ - - return matchFitness; -} - -void GeneralsMatcher::checkMatchesInUserMap(UserMap& userMap, int ladderID, int numPlayers, bool showPoolSize) -{ - UserMap::iterator i1, i2, i3, i4, i5, i6, i7, i8; - GeneralsUser *u1, *u2, *u3, *u4, *u5, *u6, *u7, *u8; - static const double fitnessThreshold = 0.3; - time_t now = time(NULL); - - std::string s; - if (showPoolSize) - { - s = "MBOT:POOLSIZE "; - s.append(intToString(userMap.size())); - } - - // iterate through users, timing them out as neccessary - for (i1 = userMap.begin(); i1 != userMap.end(); ++i1) - { - if (showPoolSize) - { - peerMessagePlayer(m_peer, i1->first.c_str(), s.c_str(), NormalMessage); - } - - u1 = i1->second; - if (u1->timeToWiden && u1->timeToWiden < now) - { - u1->timeToWiden = 0; - u1->widened = true; - for (int m=0; m<(int)u1->maps.size(); ++m) - u1->maps[m] = 1; - DBGMSG("Widening search for " << i1->first); - peerMessagePlayer(m_peer, i1->first.c_str(), "MBOT:WIDENINGSEARCH", NormalMessage); - } - } - - // iterate through all users, looking for a match - for (i1 = userMap.begin(); i1 != userMap.end(); ++i1) - { - u1 = i1->second; - if (u1->status != STATUS_WORKING) - continue; - - GeneralsUser *bestUser = NULL; - double bestMatchFitness = 0.0; - std::string bestName = ""; - - // look at everybody left - i2 = i1; - for (++i2; i2 != userMap.end(); ++i2) - { - u2 = i2->second; - if (u2->status != STATUS_WORKING) - continue; - - double matchFitness = computeMatchFitness(i1->first, u1, i2->first, u2); - if (matchFitness > fitnessThreshold) - { - if (numPlayers == 2) - { - if (matchFitness > bestMatchFitness) - { - // possibly match 2 players - bestMatchFitness = matchFitness; - bestUser = u2; - bestName = i2->first; - } - } - else - { - i3 = i2; - for (++i3; i3 != userMap.end(); ++i3) - { - u3 = i3->second; - if (u3->status != STATUS_WORKING) - continue; - - double matchFitness1 = computeMatchFitness(i1->first, u1, i3->first, u3); - double matchFitness2 = computeMatchFitness(i2->first, u2, i3->first, u3); - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - tmp = MapSetUnion(tmp, u3->maps); - if (MapSetCount(tmp) && matchFitness1 > fitnessThreshold && matchFitness2 > fitnessThreshold) - { - i4 = i3; - for (++i4; i4 != userMap.end(); ++i4) - { - u4 = i4->second; - if (u4->status != STATUS_WORKING) - continue; - - double matchFitness1 = computeMatchFitness(i1->first, u1, i4->first, u4); - double matchFitness2 = computeMatchFitness(i2->first, u2, i4->first, u4); - double matchFitness3 = computeMatchFitness(i3->first, u3, i4->first, u4); - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - tmp = MapSetUnion(tmp, u3->maps); - tmp = MapSetUnion(tmp, u4->maps); - if (MapSetCount(tmp) && matchFitness1 > fitnessThreshold && matchFitness2 > fitnessThreshold && matchFitness3 > fitnessThreshold) - { - if (numPlayers == 4) - { - // match 4 players - sendMatchInfo(i1->first, i2->first, i3->first, i4->first, "", "", "", "", - u1, u2, u3, u4, NULL, NULL, NULL, NULL, 4, ladderID); - break; - } - else - { - - i5 = i4; - for (++i5; i5 != userMap.end(); ++i3) - { - u5 = i5->second; - if (u5->status != STATUS_WORKING) - continue; - - double matchFitness1 = computeMatchFitness(i1->first, u1, i5->first, u5); - double matchFitness2 = computeMatchFitness(i2->first, u2, i5->first, u5); - double matchFitness3 = computeMatchFitness(i3->first, u3, i5->first, u5); - double matchFitness4 = computeMatchFitness(i4->first, u4, i5->first, u5); - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - tmp = MapSetUnion(tmp, u3->maps); - tmp = MapSetUnion(tmp, u4->maps); - tmp = MapSetUnion(tmp, u5->maps); - if (MapSetCount(tmp) && matchFitness1 > fitnessThreshold && matchFitness2 > fitnessThreshold && matchFitness3 > fitnessThreshold && matchFitness4 > fitnessThreshold) - { - i6 = i5; - for (++i6; i6 != userMap.end(); ++i6) - { - u6 = i6->second; - if (u6->status != STATUS_WORKING) - continue; - - double matchFitness1 = computeMatchFitness(i1->first, u1, i6->first, u6); - double matchFitness2 = computeMatchFitness(i2->first, u2, i6->first, u6); - double matchFitness3 = computeMatchFitness(i3->first, u3, i6->first, u6); - double matchFitness4 = computeMatchFitness(i4->first, u4, i6->first, u6); - double matchFitness5 = computeMatchFitness(i5->first, u5, i6->first, u6); - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - tmp = MapSetUnion(tmp, u3->maps); - tmp = MapSetUnion(tmp, u4->maps); - tmp = MapSetUnion(tmp, u5->maps); - tmp = MapSetUnion(tmp, u6->maps); - if (MapSetCount(tmp) && matchFitness1 > fitnessThreshold && matchFitness2 > fitnessThreshold && matchFitness3 > fitnessThreshold && matchFitness4 > fitnessThreshold && matchFitness5 > fitnessThreshold) - { - if (numPlayers == 6) - { - // match 6 players - sendMatchInfo(i1->first, i2->first, i3->first, i4->first, i5->first, i6->first, "", "", - u1, u2, u3, u4, u5, u6, NULL, NULL, 6, ladderID); - break; - } - else - { - - i7 = i6; - for (++i7; i7 != userMap.end(); ++i7) - { - u7 = i7->second; - if (u7->status != STATUS_WORKING) - continue; - - double matchFitness1 = computeMatchFitness(i1->first, u1, i7->first, u7); - double matchFitness2 = computeMatchFitness(i2->first, u2, i7->first, u7); - double matchFitness3 = computeMatchFitness(i3->first, u3, i7->first, u7); - double matchFitness4 = computeMatchFitness(i4->first, u4, i7->first, u7); - double matchFitness5 = computeMatchFitness(i5->first, u5, i7->first, u7); - double matchFitness6 = computeMatchFitness(i6->first, u6, i7->first, u7); - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - tmp = MapSetUnion(tmp, u3->maps); - tmp = MapSetUnion(tmp, u4->maps); - tmp = MapSetUnion(tmp, u5->maps); - tmp = MapSetUnion(tmp, u6->maps); - tmp = MapSetUnion(tmp, u7->maps); - if (MapSetCount(tmp) && matchFitness1 > fitnessThreshold && matchFitness2 > fitnessThreshold && matchFitness3 > fitnessThreshold && matchFitness4 > fitnessThreshold && matchFitness5 > fitnessThreshold && matchFitness6 > fitnessThreshold) - { - i8 = i7; - for (++i8; i8 != userMap.end(); ++i8) - { - u8 = i8->second; - if (u8->status != STATUS_WORKING) - continue; - - double matchFitness1 = computeMatchFitness(i1->first, u1, i8->first, u8); - double matchFitness2 = computeMatchFitness(i2->first, u2, i8->first, u8); - double matchFitness3 = computeMatchFitness(i3->first, u3, i8->first, u8); - double matchFitness4 = computeMatchFitness(i4->first, u4, i8->first, u8); - double matchFitness5 = computeMatchFitness(i5->first, u5, i8->first, u8); - double matchFitness6 = computeMatchFitness(i6->first, u6, i8->first, u8); - double matchFitness7 = computeMatchFitness(i7->first, u7, i8->first, u8); - MapBitSet tmp = MapSetUnion(u1->maps, u2->maps); - tmp = MapSetUnion(tmp, u3->maps); - tmp = MapSetUnion(tmp, u4->maps); - tmp = MapSetUnion(tmp, u5->maps); - tmp = MapSetUnion(tmp, u6->maps); - tmp = MapSetUnion(tmp, u7->maps); - tmp = MapSetUnion(tmp, u8->maps); - if (MapSetCount(tmp) && matchFitness1 > fitnessThreshold && matchFitness2 > fitnessThreshold && matchFitness3 > fitnessThreshold && matchFitness4 > fitnessThreshold && matchFitness5 > fitnessThreshold && matchFitness6 > fitnessThreshold && matchFitness7 > fitnessThreshold) - { - // match 8 players - sendMatchInfo(i1->first, i2->first, i3->first, i4->first, i5->first, i6->first, i7->first, i8->first, - u1, u2, u3, u4, u5, u6, u7, u8, 8, ladderID); - break; - } - } - } - } - - } - } - } - } - } - - } - } - } - } - } - } - } - } // for i2 - - if (bestUser && numPlayers == 2) - { - // we had a match. send the info. - DBGMSG("Matching " << i1->first << " with " << bestName << ":\n" - "\tmatch fitness: " << bestMatchFitness << "\n" - "\tpoint percentage: " << (1-bestUser->points/(double)u1->points)*100 << "\n" - "\tpoints: " << u1->points << ", " << u2->points << "\n" - "\tping in ms: " << sqrt(1000000 * calcPingDelta(u1, bestUser) / (255*255*2)) << "\n" - "\tprevious attempts: " << u1->widened << ", " << bestUser->widened); - sendMatchInfo(i1->first, bestName, "", "", "", "", "", "", - u1, bestUser, NULL, NULL, NULL, NULL, NULL, NULL, 2, ladderID); - break; - } - } // for i1 - - dumpUsers(); -} - -// return false for possible hack attempt -bool GeneralsMatcher::handleUserWiden(const char *nick) -{ - GeneralsUser *userInfo = findUserInAnyLadder(nick); - if (!userInfo) - { - userInfo = findNonLadderUser(nick); - } - - if (!userInfo) - { - DBGMSG("Got Widen from nick not needing one!"); - peerMessagePlayer(m_peer, nick, "MBOT:CANTSENDWIDENNOW", NormalMessage); - return false; - } - DBGMSG("Widening search for " << nick); - peerMessagePlayer(m_peer, nick, "MBOT:WIDENINGSEARCH", NormalMessage); - - userInfo->widened = true; - return true; -} - -bool GeneralsMatcher::handleUserInfo(const char *nick, const std::string& msg) -{ - DBGMSG("Got user info [" << msg << "] from " << nick); - GeneralsUser *userInfo = removeNonMatchingUser(nick); - if (!userInfo) - { - DBGMSG("Got UserInfo from nick not needing one!"); - peerMessagePlayer(m_peer, nick, "MBOT:CANTSENDCINFONOW", NormalMessage); - return false; - } - DBGMSG("Looking at " << nick << " with user info [" << msg << "]"); - - int ladderID = 0; - unsigned int ladderPassCRC = 0; - - int offset = 0; - while (1) - { - int firstMarker = msg.find_first_of('\\', offset); - if (firstMarker < 0) - break; - int secondMarker = msg.find_first_of('\\', firstMarker + 1); - if (secondMarker < 0) - break; - int thirdMarker = msg.find_first_of('\\', secondMarker + 1); - if (thirdMarker < 0) - break; - std::string k = msg.substr(firstMarker + 1, secondMarker - firstMarker - 1); - std::string v = msg.substr(secondMarker + 1, thirdMarker - secondMarker - 1); - offset = thirdMarker - 1; - - if (k == "Widen") - { - int val = atoi(v.c_str()); - if (val > 0) - userInfo->timeToWiden = time(NULL) + val; - else - userInfo->timeToWiden = 0; - } - else if (k == "LadID") - { - ladderID = atoi(v.c_str()); - } - else if (k == "LadPass") - { - ladderPassCRC = atoi(v.c_str()); - } - else if (k == "PointsMin") - { - userInfo->minPoints = atoi(v.c_str()); - } - else if (k == "PointsMax") - { - userInfo->maxPoints = atoi(v.c_str()); - } - else if (k == "PingMax") - { - userInfo->maxPing = atoi(v.c_str()); - } - else if (k == "DisconMax") - { - userInfo->maxDiscons = atoi(v.c_str()); - } - else if (k == "Maps") - { -#ifdef DEBUG - //int curMaps = userInfo->maps.size(); -#endif - - //DBGMSG("map cur size is " << curMaps); - userInfo->maps.clear(); - if (!v.length()) - { - INFMSG("Bad maps from " << nick << ": [" << v << "]"); - peerMessagePlayer(m_peer, nick, "MBOT:BADMAPS", NormalMessage); - return false; - } - const char *buf = v.c_str(); - int pos = 0; - while (*buf) - { - bool hasMap = (*buf != '0'); - //DBGMSG("Setting map " << pos << " to " << hasMap); - userInfo->maps.push_back( hasMap ); - ++pos; - ++buf; - } - } - else if (k == "NumPlayers") - { - userInfo->numPlayers = atoi(v.c_str()); - if (userInfo->numPlayers != 2 && userInfo->numPlayers != 4 && - userInfo->numPlayers != 6 && userInfo->numPlayers != 8) - { - INFMSG("Bad numPlayers from " << nick << ": [" << userInfo->numPlayers << "]"); - peerMessagePlayer(m_peer, nick, "MBOT:BADCINFO", NormalMessage); - return false; - } - } - else if (k == "IP") - { - userInfo->IP = atoi(v.c_str()); - } - else if (k == "NAT") - { - userInfo->NAT = atoi(v.c_str()); - } - else if (k == "Side") - { - userInfo->country = atoi(v.c_str()); - } - else if (k == "Color") - { - userInfo->color = atoi(v.c_str()); - } - else if (k == "Pings") - { - if (!v.length() || (v.length() % 2)) - { - INFMSG("Bad pings from " << nick << ": [" << v << "]"); - peerMessagePlayer(m_peer, nick, "MBOT:BADPINGS", NormalMessage); - return false; - } - int ping = 0; - const char *buf = v.c_str(); - char buf2[3]; - buf2[2] = '\0'; - // We've already assured that pingStr has non-zero even length. - while (*buf) - { - buf2[0] = *buf++; - buf2[1] = *buf++; - ping = (int)strtol(buf2, NULL, 16); - userInfo->pseudoPing.push_back(ping); - } - } - else if (k == "Points") - { - userInfo->points = max(1, atoi(v.c_str())); - } - else if (k == "Discons") - { - userInfo->discons = atoi(v.c_str()); - } - else - { - INFMSG("Unknown key/value pair in user info [" << k << "]/[" << v << "]"); - peerMessagePlayer(m_peer, nick, "MBOT:BADCINFO", NormalMessage); - return false; - } - } - - std::string s = "MBOT:WORKING "; - - if (ladderID) - { - addUserInLadder(nick, ladderID, userInfo); - s.append(intToString(m_ladders[ladderID].size())); - } - else - { - addNonLadderUser(nick, userInfo); - switch (userInfo->numPlayers) - { - case 2: - s.append(intToString(m_nonLadderUsers1v1.size())); - break; - case 4: - s.append(intToString(m_nonLadderUsers2v2.size())); - break; - case 6: - s.append(intToString(m_nonLadderUsers3v3.size())); - break; - case 8: - s.append(intToString(m_nonLadderUsers4v4.size())); - break; - } - } - - userInfo->status = STATUS_WORKING; - userInfo->matchStart = time(NULL); - peerMessagePlayer(m_peer, nick, s.c_str(), NormalMessage); - - DBGMSG("Player " << nick << " is matching now, ack was [" << s << "]"); - return true; -} - -GeneralsUser* GeneralsMatcher::findUser(const std::string& who) -{ - GeneralsUser *user; - user = findNonLadderUser(who); - if (user) - return user; - user = findNonMatchingUser(who); - if (user) - return user; - user = findUserInAnyLadder(who); - if (user) - return user; - - return NULL; -} - -GeneralsUser* GeneralsMatcher::findUserInAnyLadder(const std::string& who) -{ - for (LadderMap::iterator lIt = m_ladders.begin(); lIt != m_ladders.end(); ++lIt) - { - UserMap::iterator uIt = lIt->second.find(who); - if (uIt != lIt->second.end()) - return uIt->second; - } - return NULL; -} - -GeneralsUser* GeneralsMatcher::findUserInLadder(const std::string& who, int ladderID) -{ - LadderMap::iterator lIt = m_ladders.find(ladderID); - if (lIt == m_ladders.end()) - return NULL; - - UserMap::iterator uIt = lIt->second.find(who); - if (uIt == lIt->second.end()) - return NULL; - - return uIt->second; -} - -GeneralsUser* GeneralsMatcher::findNonLadderUser(const std::string& who) -{ - UserMap::iterator it = m_nonLadderUsers1v1.find(who); - if (it != m_nonLadderUsers1v1.end()) - return it->second; - - it = m_nonLadderUsers2v2.find(who); - if (it != m_nonLadderUsers2v2.end()) - return it->second; - - it = m_nonLadderUsers3v3.find(who); - if (it != m_nonLadderUsers3v3.end()) - return it->second; - - it = m_nonLadderUsers4v4.find(who); - if (it != m_nonLadderUsers4v4.end()) - return it->second; - - return NULL; -} - -GeneralsUser* GeneralsMatcher::findNonMatchingUser(const std::string& who) -{ - UserMap::iterator it = m_nonMatchingUsers.find(who); - if (it == m_nonMatchingUsers.end()) - return NULL; - - return it->second; -} - -void GeneralsMatcher::addUser(const std::string& who) -{ - if (findUser(who)) - { - ERRMSG("Re-adding " << who); - return; - } - - addNonMatchingUser(who, new GeneralsUser); -} - -void GeneralsMatcher::addUserInLadder(const std::string& who, int ladderID, GeneralsUser *user) -{ - m_ladders[ladderID][who] = user; -} - -void GeneralsMatcher::addNonLadderUser(const std::string& who, GeneralsUser *user) -{ - switch (user->numPlayers) - { - case 2: - m_nonLadderUsers1v1[who] = user; - break; - case 4: - m_nonLadderUsers2v2[who] = user; - break; - case 6: - m_nonLadderUsers3v3[who] = user; - break; - case 8: - m_nonLadderUsers4v4[who] = user; - break; - } -} - -void GeneralsMatcher::addNonMatchingUser(const std::string& who, GeneralsUser *user) -{ - m_nonMatchingUsers[who] = user; -} - - -bool GeneralsMatcher::removeUser(const std::string& who) -{ - GeneralsUser *user; - user = removeUserInAnyLadder(who); - if (user) - { - delete user; - return true; - } - user = removeNonLadderUser(who); - if (user) - { - delete user; - return true; - } - user = removeNonMatchingUser(who); - if (user) - { - delete user; - return true; - } - - return false; -} - -GeneralsUser* GeneralsMatcher::removeUserInLadder(const std::string& who, int ladderID) -{ - LadderMap::iterator lIt = m_ladders.find(ladderID); - if (lIt == m_ladders.end()) - return NULL; - - UserMap::iterator uIt = lIt->second.find(who); - if (uIt == lIt->second.end()) - return NULL; - - GeneralsUser *user = uIt->second; - lIt->second.erase(uIt); - return user; -} - -GeneralsUser* GeneralsMatcher::removeUserInAnyLadder(const std::string& who) -{ - for (LadderMap::iterator lIt = m_ladders.begin(); lIt != m_ladders.end(); ++lIt) - { - UserMap::iterator uIt = lIt->second.find(who); - if (uIt != lIt->second.end()) - { - GeneralsUser *user = uIt->second; - lIt->second.erase(uIt); - return user; - } - } - return NULL; -} - -GeneralsUser* GeneralsMatcher::removeNonLadderUser(const std::string& who) -{ - UserMap::iterator it = m_nonLadderUsers1v1.find(who); - if (it != m_nonLadderUsers1v1.end()) - { - GeneralsUser *user = it->second; - m_nonLadderUsers1v1.erase(it); - return user; - } - - it = m_nonLadderUsers2v2.find(who); - if (it != m_nonLadderUsers2v2.end()) - { - GeneralsUser *user = it->second; - m_nonLadderUsers2v2.erase(it); - return user; - } - - it = m_nonLadderUsers3v3.find(who); - if (it != m_nonLadderUsers3v3.end()) - { - GeneralsUser *user = it->second; - m_nonLadderUsers3v3.erase(it); - return user; - } - - it = m_nonLadderUsers4v4.find(who); - if (it != m_nonLadderUsers4v4.end()) - { - GeneralsUser *user = it->second; - m_nonLadderUsers4v4.erase(it); - return user; - } - - return NULL; -} - -GeneralsUser* GeneralsMatcher::removeNonMatchingUser(const std::string& who) -{ - UserMap::iterator it = m_nonMatchingUsers.find(who); - if (it == m_nonMatchingUsers.end()) - return NULL; - - GeneralsUser *user = it->second; - m_nonMatchingUsers.erase(it); - return user; -} - - -void GeneralsMatcher::handleDisconnect( const char *reason ) -{ - ERRMSG("Disconnected"); - done = true; - exit(0); -} - -void GeneralsMatcher::handleRoomMessage( const char *nick, const char *message, MessageType messageType ) -{ - if (messageType == ActionMessage) - { - PARANOIDMSG(nick << " " << message); - } - else - { - PARANOIDMSG("[" << nick << "] " << message); - } -} - -void GeneralsMatcher::handlePlayerMessage( const char *nick, const char *message, MessageType messageType ) -{ - if (messageType == ActionMessage) - { - DBGMSG(nick << " " << message); - } - else - { - DBGMSG("[" << nick << "] " << message); - } - - if (messageType != NormalMessage) - return; - - std::string line = message; - line.append("\\"); - - int offset = 0; - int firstMarker = line.find_first_of('\\', offset); - int secondMarker = line.find_first_of('\\', firstMarker + 1); - if (firstMarker >= 0 && secondMarker >= 0) - { - std::string marker = line.substr(firstMarker + 1, secondMarker - firstMarker - 1); - if (marker == "CINFO") - { - handleUserInfo(nick, line.substr(secondMarker));//, std::string::npos)); - } - else if (marker == "WIDEN") - { - handleUserWiden(nick); - } - else - { - INFMSG("Unknown marker [" << marker << "] in line [" << line << "] from " << nick); - } - } - else - { - INFMSG("Failed to parse line [" << line << "] from " << nick); - } -} - -void GeneralsMatcher::handlePlayerJoined( const char *nick ) -{ - DBGMSG("Player " << nick << " joined"); - addUser(nick); -} - -void GeneralsMatcher::handlePlayerLeft( const char *nick ) -{ - DBGMSG("Player " << nick << " left"); - if (m_nick != nick) - removeUser(nick); -} - -void GeneralsMatcher::handlePlayerChangedNick( const char *oldNick, const char *newNick ) -{ - DBGMSG("Player " << oldNick << " changed nick to " << newNick << " - resetting to non-matching state"); - removeUser(oldNick); - addUser(newNick); -} - -void GeneralsMatcher::handlePlayerEnum( bool success, int gameSpyIndex, const char *nick, int flags ) -{ - if (!nick) - nick = ""; - DBGMSG("PlayerEnum: success=" << success << " index=" << gameSpyIndex << ", nick=" << nick << ", flags=" << flags); - - if (success && gameSpyIndex >= 0 && m_nick != nick) - { - addUser(nick); - } -} - - -// ===================================================================== -// TEST Client Matcher class -// ===================================================================== - -GeneralsClientMatcher::GeneralsClientMatcher() -{ - // Read some values from the config file - int quietTMP = 0; - Global.config.getInt("NOECHO", quietTMP); - if (quietTMP) - quiet = true; - else - quiet = false; -} - -void GeneralsClientMatcher::init(void) -{ - m_baseNick.setFormatted("qmBot%d", time(NULL)); - m_profileID = 0; -} - -void GeneralsClientMatcher::checkMatches(void) -{} - -void GeneralsClientMatcher::handleDisconnect( const char *reason ) -{} -void GeneralsClientMatcher::handleRoomMessage( const char *nick, const char *message, MessageType messageType ) -{} -void GeneralsClientMatcher::handlePlayerMessage( const char *nick, const char *message, MessageType messageType ) -{} -void GeneralsClientMatcher::handlePlayerJoined( const char *nick ) -{} -void GeneralsClientMatcher::handlePlayerLeft( const char *nick ) -{} -void GeneralsClientMatcher::handlePlayerChangedNick( const char *oldNick, const char *newNick ) -{} -void GeneralsClientMatcher::handlePlayerEnum( bool success, int gameSpyIndex, const char *nick, int flags ) -{} - - -// ===================================================================== -// End of File -// ===================================================================== - - diff --git a/Generals/Code/Tools/matchbot/generals.h b/Generals/Code/Tools/matchbot/generals.h deleted file mode 100644 index e0761e110e..0000000000 --- a/Generals/Code/Tools/matchbot/generals.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __GENERALS_H__ -#define __GENERALS_H__ - -#ifdef _WIN32 -#include -#endif -//#include -//#include -//#include -#include "matcher.h" -#include "global.h" - -#include -#include -#include -#include -#include - -typedef std::vector MapBitSet; - -// ===================================================================== -// Users -// ===================================================================== - -// Here are the states a matcher can be in: -typedef enum -{ - STATUS_INVAL = 0, - STATUS_INCHANNEL, // Just entered the channel - STATUS_WORKING, // Sent info, needs to be matched - STATUS_MATCHED, // Been matched, but is still in the channel -} UserStatus; - -class GeneralsUser -{ -public: - GeneralsUser(void); - UserStatus status; - - int points, minPoints, maxPoints; - - int discons, maxDiscons; - - int country; - int color; - - bool widened; - time_t timeToWiden; - time_t matchStart; // when did we request a match? - - // This is a ping to a designated 3rd-party server who just - // responds to pings. The idea is that if the game server is - // behind a firewall, the client will have a 1000ms ping to it, - // even though he might be very close. To combat this, we have - // clients & servers ping some 3rd-party servers & calculate a - // pesudo-ping based on the sum of pings server-->3rd-->client. - std::vector pseudoPing; - int maxPing; - - unsigned int IP; - int NAT; - - MapBitSet maps; - - int numPlayers; -}; - -// ===================================================================== -// Matcher class -// ===================================================================== - -typedef std::map UserMap; -typedef std::map LadderMap; - -class GeneralsMatcher : public MatcherClass -{ -public: - GeneralsMatcher(); - virtual ~GeneralsMatcher() - {} - - virtual void init(void); - virtual void checkMatches(void); - - virtual void handleDisconnect( const char *reason ); - virtual void handleRoomMessage( const char *nick, const char *message, MessageType messageType ); - virtual void handlePlayerMessage( const char *nick, const char *message, MessageType messageType ); - virtual void handlePlayerJoined( const char *nick ); - virtual void handlePlayerLeft( const char *nick ); - virtual void handlePlayerChangedNick( const char *oldNick, const char *newNick ); - virtual void handlePlayerEnum( bool success, int gameSpyIndex, const char *nick, int flags ); - -private: - LadderMap m_ladders; - UserMap m_nonLadderUsers1v1; - UserMap m_nonLadderUsers2v2; - UserMap m_nonLadderUsers3v3; - UserMap m_nonLadderUsers4v4; - UserMap m_nonMatchingUsers; - - double computeMatchFitness(const std::string& i1, const GeneralsUser *u1, const std::string& i2, const GeneralsUser *u2); - - GeneralsUser* findUser(const std::string& who); - GeneralsUser* findUserInLadder(const std::string& who, int ladderID); - GeneralsUser* findUserInAnyLadder(const std::string& who); - GeneralsUser* findNonLadderUser(const std::string& who); - GeneralsUser* findNonMatchingUser(const std::string& who); - - void addUser(const std::string& who); - void addUserInLadder(const std::string& who, int ladderID, GeneralsUser *user); - void addUserInAnyLadder(const std::string& who, GeneralsUser *user); - void addNonLadderUser(const std::string& who, GeneralsUser *user); - void addNonMatchingUser(const std::string& who, GeneralsUser *user); - - bool removeUser(const std::string& who); - GeneralsUser* removeUserInLadder(const std::string& who, int ladderID); - GeneralsUser* removeUserInAnyLadder(const std::string& who); - GeneralsUser* removeNonLadderUser(const std::string& who); - GeneralsUser* removeNonMatchingUser(const std::string& who); - - void checkMatchesInUserMap(UserMap& userMap, int ladderID, int numPlayers, bool showPoolSize); - - void dumpUsers(void); - - void sendMatchInfo(std::string name1, std::string name2, std::string name3, std::string name4, - std::string name5, std::string name6, std::string name7, std::string name8, - GeneralsUser *user1, GeneralsUser *user2, GeneralsUser *user3, GeneralsUser *user4, - GeneralsUser *user5, GeneralsUser *user6, GeneralsUser *user7, GeneralsUser *user8, - int numPlayers, int ladderID); - - // Command handlers for above privmsg commands (offset is the - // offset for the getToken() past the command token) - bool handleUserInfo(const char *nick, const std::string& msg); - bool handleUserWiden(const char *nick); - - // Weights for various matching parameters - int weightLowPing; - int weightAvgPoints; - int totalWeight; - - time_t m_nextPoolSizeAnnouncement; - int m_secondsBetweenPoolSizeAnnouncements; - - //typedef std::vector StringVec; - //StringVec mapFileList; -} -; - -// ===================================================================== -// TEST Client Matcher class -// ===================================================================== - -class GeneralsClientMatcher : public MatcherClass -{ -public: - GeneralsClientMatcher(); - virtual ~GeneralsClientMatcher() - {} - - virtual void init(void); - virtual void checkMatches(void); - - virtual void handleDisconnect( const char *reason ); - virtual void handleRoomMessage( const char *nick, const char *message, MessageType messageType ); - virtual void handlePlayerMessage( const char *nick, const char *message, MessageType messageType ); - virtual void handlePlayerJoined( const char *nick ); - virtual void handlePlayerLeft( const char *nick ); - virtual void handlePlayerChangedNick( const char *oldNick, const char *newNick ); - virtual void handlePlayerEnum( bool success, int gameSpyIndex, const char *nick, int flags ); - -private: -} -; - -#endif /* __GENERALS_H__ */ - diff --git a/Generals/Code/Tools/matchbot/global.cpp b/Generals/Code/Tools/matchbot/global.cpp deleted file mode 100644 index 232cee6310..0000000000 --- a/Generals/Code/Tools/matchbot/global.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include // for FILE ops -#include "global.h" - -GlobalClass Global; - -GlobalClass::GlobalClass(void) -{} - -bool GlobalClass::ReadFile(const char *fname) -{ - FILE *fp; - if ((fp = fopen(fname, "r")) == NULL) - return false; - config.readFile(fp); - fclose(fp); - - return true; -} - -bool GlobalClass::GetString(const Wstring& key, Wstring& val) -{ - val = ""; - config.getString(key, val, "STRINGS"); - if (val == "") - { - val.setFormatted("MISSING:%s", key.get()); - return false; - } - - return true; - -} - diff --git a/Generals/Code/Tools/matchbot/global.h b/Generals/Code/Tools/matchbot/global.h deleted file mode 100644 index 5dc7856dca..0000000000 --- a/Generals/Code/Tools/matchbot/global.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __GLOBAL_H__ -#define __GLOBAL_H__ - -#ifdef _WIN32 -#include -#ifdef IN -#undef IN -#endif -#define IN const -#endif -#include -#include -#include -#include -#include -#include "matcher.h" -#include "rand.h" - -class GlobalClass -{ -public: - GlobalClass(); - - ConfigFile config; - bool ReadFile(const char *fname); - - bool GetString(const Wstring& key, Wstring& val); - - RandClass rnd; -}; - -extern GlobalClass Global; - -// Log rotation functions -void rotateOutput(void); -void rotateParanoid(void); - -#endif - diff --git a/Generals/Code/Tools/matchbot/main.cpp b/Generals/Code/Tools/matchbot/main.cpp deleted file mode 100644 index 0290ac55be..0000000000 --- a/Generals/Code/Tools/matchbot/main.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifdef _WIN32 -#include -#endif -#include -#include -#include - -#ifdef _WIN32 -#include -#else -#include -#include -#endif - -//#define THREADSAFE_HEADER - -#include -#include -#include -#include -#include -#include -#include "global.h" -#include "generals.h" -#include "timezone.h" -#include - -#include -#include "mydebug.h" - -#ifdef _UNIX -using namespace std; -#else -#define sleep(x) Sleep(1000 * (x)) -#endif - -static const char *Program_Usage = "A config filename can be given on the command line (default=matchbot.cfg)\n"; -void logMonitor(void *); -void paranoidLogMonitor(void *); - -OutputDevice * output_device = NULL; -OutputDevice * paranoid_output_device = NULL; - - -void Signal_Quit(int) -{ - INFMSG("Exiting due to signal."); - exit(2); -} - -void Setup_Signals(void) -{ -#ifdef _UNIX - struct sigaction act, oact; - act.sa_handler = Signal_Quit; - sigemptyset(&act.sa_mask); - act.sa_flags = 0; - sigaction(SIGTERM, &act, &oact); - sigaction(SIGINT, &act, &oact); -#endif -} - -int VerifyFileDescriptors(int requested) -{ -#ifdef _UNIX - struct rlimit limit; - if (!getrlimit(_SC_OPEN_MAX, &limit)) - { - INFMSG("Hard limit on file descriptors: " << limit.rlim_max); - if (limit.rlim_max < (unsigned int)requested) - { - ERRMSG("Too many file descriptors requested"); - ERRMSG("Hard Limit: " << limit.rlim_max << ", requested: " << requested); - requested = limit.rlim_max; - } - - limit.rlim_cur = limit.rlim_max; /* make soft limit the max */ - if (setrlimit(_SC_OPEN_MAX, &limit) == -1) - { - ERRMSG("Error setting max file descriptors to " << limit.rlim_cur); - exit(-1); - } - INFMSG("Soft limit on file descriptors: " << limit.rlim_cur); - } - else - { - ERRMSG("Couldn't get limit for _SC_OPEN_MAX"); - exit(-1); - } -#endif - return requested; -} - - - -GeneralsMatcher *s_generalsMatcher = NULL; -GeneralsClientMatcher *s_generalsClientMatcher = NULL; - -int main(int argc, char ** argv) -{ - Wstring config_fname = "matchbot.cfg"; - - // You can specify the config file on the command line - if (argc == 2) - config_fname = argv[1]; - - // Read the config file - FILE *fp; - if ((fp = fopen(config_fname.get(), "r")) == NULL) - { - cerr << "\nCan't open the config file '" << config_fname.get() << "'\n\n"; - cerr << Program_Usage << endl; - exit( -1); - } - fclose(fp); - - Global.ReadFile(config_fname.get()); - - // Setup debugging & logging output - Wstring output_file; - output_file.set("matchbot.log"); - Global.config.getString("OUTPUTFILE", output_file); - if (output_file != "STDOUT") - { - int append = 1; - Global.config.getInt("APPENDTOLOG", append); - if (append) - output_device = new FileD(output_file.get(), "a"); - else - output_device = new FileD(output_file.get(), "w"); - if (!output_device) - { - cerr << "Could not open " << output_file.get() << " for writing!" << endl; - exit( -1); - } - } - else - { - output_device = new StdoutD; - } - MsgManager::setAllStreams(output_device); - DBGMSG("Matching bot started!"); - INFMSG("Matching bot " << argv[0] << " started!"); - - // Setup logging of suspicious activity - Wstring paranoid_output_file; - paranoid_output_file.set("hacks.log"); - Global.config.getString("PARANOIDFILE", paranoid_output_file); - if (paranoid_output_file != "STDOUT") - { - paranoid_output_device = new FileD(paranoid_output_file.get(), "a"); - if (!paranoid_output_device) - { - cerr << "Could not open " << paranoid_output_file.get() << " for writing!" << endl; - exit( -1); - } - } - else - { - paranoid_output_device = new StdoutD; - } - MyMsgManager::setParanoidStream(paranoid_output_device); - DBGMSG("Hack log started!"); - PARANOIDMSG("Hack log started!"); - - Setup_Signals(); - -#ifdef _WINDOWS - // ----- Initialize Winsock ----- - WORD verReq = MAKEWORD(2, 2); - WSADATA wsadata; - - int err = WSAStartup(verReq, &wsadata); - if (err != 0) - { - ERRMSG("Winsock Init failed."); - return 1; - } - - if ((LOBYTE(wsadata.wVersion) != 2) || (HIBYTE(wsadata.wVersion) !=2)) - { - ERRMSG("Winsock DLL is not 2.2"); - WSACleanup(); - ERRMSG("Winsock Init failed."); - return 1; - } - INFMSG("Winsock Init done."); -#endif - - // Check game type & start matcher - Wstring gametype = "unknown"; - Global.config.getString("GAME", gametype); - - // Command-line override for gamemode. - // This is for test suites, so they can use - // the same config file as the corresponding - // matchbot. - const char *s = argv[0] + strlen(argv[0]); - while (s > argv[0] && *s != '/') - --s; - if (*s == '/') - ++s; - Wstring exe = s; - exe.toLower(); - DBGMSG("Executable file is [" << exe.get() << "]"); - - if (gametype == "Generals") - { - DBGMSG("Generals matching behavior"); - s_generalsMatcher = new GeneralsMatcher; - s_generalsMatcher->connectAndLoop(); - } - else if (gametype == "GeneralsClient") - { - DBGMSG("Generals TEST client matching behavior"); - s_generalsClientMatcher = new GeneralsClientMatcher; - s_generalsClientMatcher->connectAndLoop(); - } - else - { - cerr << "\nNo valid GAME entry found!" << endl; - exit( -1); - } - - if (s_generalsMatcher) - delete s_generalsMatcher; - if (s_generalsClientMatcher) - delete s_generalsClientMatcher; - - return 0; -} - -/*----------------------------------------------------------------------+ -| THREAD: logMonitor | -| This thread is spawned once per execution. It will activate after | -| midnight and create a new log file. The old one gets put into the | -| logfiles directory. | -`----------------------------------------------------------------------*/ -void logMonitor(void *) -{ -#ifdef _UNIX - Xtime xtime; - time_t curtime; - //char timebuf[40]; - char filenamebuf[128]; - int delay = -1; - Global.config.getInt("ROTATEDELAY", delay); - DBGMSG("ROTATEDELAY: " << delay); - if (delay == -1) - return ; - while (1) - { - curtime = time(NULL); - // get the number of seconds that have passed since midnight - // of the current day. - curtime -= TimezoneOffset(); - time_t timeofday = curtime % (delay); - if ((timeofday > 0) && (timeofday <= 300)) - { - // We're within 5 minutes of midnight, switch the files. - - DBGMSG("about to switch."); - Wstring logfilename = "matchbot.log"; - Global.config.getString("OUTPUTFILE", logfilename); - Wstring newfilename = "tmp.log"; - Global.config.getString("ROTATEFILE", newfilename); - MsgManager::ReplaceAllStreams((FileD*)output_device, logfilename.get(), newfilename.get()); - Wstring logpath = "logs"; - Global.config.getString("LOGPATH", logpath); - xtime.update(); - sprintf(filenamebuf, "%s/%02d%02d%04d_%02d%02d%02d_log", logpath.get(), xtime.getMonth(), - xtime.getMDay(), xtime.getYear(), xtime.getHour(), xtime.getMinute(), xtime.getSecond()); - rename(newfilename.get(), filenamebuf); - DBGMSG("Normal: Just been switched. " << logfilename.get() << ", " << newfilename.get()); - sleep(60*60*23); // sleep the next 23 hours - } - sleep(300); - } -#endif -} - -void rotateOutput(void) -{ - Xtime xtime; - char filenamebuf[128]; - Wstring logfilename = "matchbot.log"; - Wstring newfilename = "tmp.log"; - Wstring logpath = "logs"; - - DBGMSG("About to switch."); - - Global.config.getString("OUTPUTFILE", logfilename); - Global.config.getString("ROTATEFILE", newfilename); - Global.config.getString("LOGPATH", logpath); - - // This grabs the semaphore, renames the file, and switches the output device - MsgManager::ReplaceAllStreams((FileD*)output_device, logfilename.get(), - newfilename.get()); - - // clean up the tmp filename and move it to the log dir. - sprintf(filenamebuf, "%s/%02d%02d%04d_%02d%02d%02d_log", logpath.get(), - xtime.getMonth(), xtime.getMDay(), xtime.getYear(), xtime.getHour(), - xtime.getMinute(), xtime.getSecond()); -#ifdef _WINDOWS - mkdir(logpath.get()); -#else - mkdir(logpath.get(), 00666); -#endif - rename(newfilename.get(), filenamebuf); - - DBGMSG("Normal: Just been switched. " << logfilename.get() << ", " << - newfilename.get()); -} - -void paranoidLogMonitor(void *) -{ -#ifdef _UNIX - Xtime xtime; - time_t curtime; - //char timebuf[40]; - char filenamebuf[128]; - int delay = -1; - Global.config.getInt("ROTATEDELAY", delay); - PARANOIDMSG("ROTATEDELAY: " << delay); - if (delay == -1) - return ; - while (1) - { - curtime = time(NULL); - // get the number of seconds that have passed since midnight - // of the current day. - curtime -= TimezoneOffset(); - time_t timeofday = curtime % (delay); - if ((timeofday > 0) && (timeofday <= 300)) - { - // We're within 5 minutes of midnight, switch the files. - - PARANOIDMSG("about to switch."); - Wstring logfilename = "matchbot.log"; - Global.config.getString("PARANOIDFILE", logfilename); - Wstring newfilename = "tmp.log"; - Global.config.getString("ROTATEPARANOIDFILE", newfilename); - MyMsgManager::ReplaceAllStreams((FileD*)paranoid_output_device, logfilename.get(), newfilename.get()); - Wstring logpath = "logs"; - Global.config.getString("PARANOIDLOGPATH", logpath); - xtime.update(); - sprintf(filenamebuf, "%s/%02d%02d%04d_%02d%02d%02d_log", logpath.get(), xtime.getMonth(), - xtime.getMDay(), xtime.getYear(), xtime.getHour(), xtime.getMinute(), xtime.getSecond()); - rename(newfilename.get(), filenamebuf); - PARANOIDMSG("Paranoid: Just been switched. " << logfilename.get() << ", " << newfilename.get()); - sleep(60*60*23); // sleep the next 23 hours - } - sleep(300); - } -#endif -} - -void rotateParanoid(void) -{ - Xtime xtime; - char filenamebuf[128]; - Wstring logfilename = "matchbot.log"; - Wstring newfilename = "tmp.log"; - Wstring logpath = "logs"; - - PARANOIDMSG("About to switch."); - - Global.config.getString("PARANOIDFILE", logfilename); - Global.config.getString("ROTATEPARANOIDFILE", newfilename); - Global.config.getString("PARANOIDLOGPATH", logpath); - - // This grabs the semaphore, renames the file, and switches the output device - MyMsgManager::ReplaceAllStreams((FileD*)output_device, logfilename.get(), - newfilename.get()); - - // clean up the tmp filename and move it to the log dir. - sprintf(filenamebuf, "%s/%02d%02d%04d_%02d%02d%02d_log", logpath.get(), - xtime.getMonth(), xtime.getMDay(), xtime.getYear(), xtime.getHour(), - xtime.getMinute(), xtime.getSecond()); -#ifdef _WINDOWS - mkdir(logpath.get()); -#else - mkdir(logpath.get(), 00666); -#endif - rename(newfilename.get(), filenamebuf); - - PARANOIDMSG("Paranoid: Just been switched. " << logfilename.get() << ", " << - newfilename.get()); -} - - diff --git a/Generals/Code/Tools/matchbot/matcher.cpp b/Generals/Code/Tools/matchbot/matcher.cpp deleted file mode 100644 index 2b27968ad9..0000000000 --- a/Generals/Code/Tools/matchbot/matcher.cpp +++ /dev/null @@ -1,421 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "global.h" -#include "matcher.h" -#include "encrypt.h" -#include "timezone.h" -#include "debug.h" - -#ifdef _WINDOWS -#define usleep(x) Sleep((x)/100000) -#endif - -MatcherClass::MatcherClass(void) -{ - m_lastRotation = 0; - m_baseNick = "matcher"; - m_joinSuccess = false; - done = 0; - - m_rotateLogs = false; - quiet = false; -} - -Wstring MatcherClass::getString(const Wstring& key) -{ - Wstring res; - Global.GetString(key, res); - return res; -} - -void logIt(const char *Txt) -{ - // intentionally crash if we can't open it - FILE *fp = fopen("logIt.txt", "w"); - fputs(Txt, fp); - fclose(fp); -} - -void MatcherClass::readLoop(void) -{ - int delay = -1; - Global.config.getInt("ROTATEDELAY", delay); - DBGMSG("ROTATEDELAY: " << delay); - - do - { - static time_t lastLogTime = 0; - time_t now = time(NULL); - if (now > lastLogTime + 300) - { - lastLogTime = now; - INFMSG("still here" << endl); - } - - logIt("peerThink\n"); - peerThink(m_peer); - - logIt("peerIsConnected\n"); - if (peerIsConnected(m_peer)) - { - logIt("checkMatches()\n"); - checkMatches(); - logIt("checkMatches() done\n"); - } - else - done = true; - - msleep(1); - - // rotate logs if it's time - if (delay != -1) - { -#ifdef _UNIX - Xtime xtime; - time_t curtime; - curtime = time(NULL); - // get the number of seconds that have passed since midnight - // of the current day. - curtime -= TimezoneOffset(); - time_t timeofday = curtime % (delay); - if ((timeofday > 0) && (timeofday <= 300)) - { - rotateOutput(); - rotateParanoid(); - } -#endif - } - } - while (!done); - DBGMSG("Bailing out of readLoop!" << endl); - INFMSG("Bailing out of readLoop!" << endl); - ERRMSG("Bailing out of readLoop!" << endl); -} - -///////////////////////////////////////////////////////////////////////////// - -static void DisconnectedCallback ( PEER peer, const char * reason, void * param) -{ - DBGMSG("Disconnected: " << reason); - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handleDisconnect( reason ); -} - -static void RoomMessageCallback ( PEER peer, RoomType roomType, const char * nick, const char * message, MessageType messageType, void * param) -{ - DBGMSG("(PUBLIC) " << nick << ": " << message); - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handleRoomMessage( nick, message, messageType ); -} - -static void PlayerMessageCallback ( PEER peer, const char * nick, const char * message, MessageType messageType, void * param) -{ - DBGMSG("(PRIVATE) " << nick << ": " << message); - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handlePlayerMessage( nick, message, messageType ); -} - -static void PlayerJoinedCallback ( PEER peer, RoomType roomType, const char * nick, void * param) -{ - DBGMSG(nick << " joined the room"); - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handlePlayerJoined( nick ); -} - -static void PlayerLeftCallback ( PEER peer, RoomType roomType, const char * nick, const char * reason, void * param) -{ - DBGMSG(nick << " left the room"); - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handlePlayerLeft( nick ); -} - -static void PlayerChangedNickCallback ( PEER peer, RoomType roomType, const char * oldNick, const char * newNick, void * param) -{ - INFMSG(oldNick << " changed nicks to " << newNick); - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handlePlayerChangedNick( oldNick, newNick ); -} - -static void EnumPlayersCallback ( PEER peer, PEERBool success, RoomType roomType, int index, const char * nick, int flags, void * param) -{ - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handlePlayerEnum( success == PEERTrue, index, nick, flags); -} - -static int s_groupID = 0; -static void ListGroupRoomsCallback ( PEER peer, PEERBool success, int groupID, SBServer server, const char * name, int numWaiting, int maxWaiting, int numGames, int numPlaying, void * param) -{ - if (success && name && !strcasecmp(name, "QuickMatch")) - { - s_groupID = groupID; - } -} - -static void ConnectCallback ( PEER peer, PEERBool success, int failureReason, void * param ) -{ - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handleConnect( success == PEERTrue ); -} - -static void JoinCallback ( PEER peer, PEERBool success, PEERJoinResult result, RoomType roomType, void * param) -{ - MatcherClass *matcher = (MatcherClass *)param; - if (matcher) - matcher->handleJoin( success == PEERTrue ); -} - -static void NickErrorCallback ( PEER peer, int type, const char * badNick, int numSuggestedNicks, const const char ** suggestedNicks, void * param) -{ - ERRMSG("Nick error with " << badNick); - - if(type == PEER_IN_USE) - { - int len = strlen(badNick); - std::string nickStr = badNick; - int newVal = 0; - if (badNick[len-1] == '}' && badNick[len-3] == '{' && isdigit(badNick[len-2])) - { - newVal = badNick[len-2] - '0' + 1; - nickStr.erase(len-3, 3); - } - - nickStr.append("{"); - char tmp[2]; - tmp[0] = '0'+newVal; - tmp[1] = '\0'; - nickStr.append(tmp); - nickStr.append("}"); - DBGMSG("Nickname taken: was "<= 1); - } -} - -void MatcherClass::connectAndLoop(void) -{ - // Game-specific initializations, if neccessary - init(); - - // Check for possible quit from init()-based self-tests - if (done) - return ; - - // Defaults. - //////////// - Wstring title = "gmtest"; - Wstring secretKey = "HA6zkS"; - Wstring serialNo = ""; - m_profileID = 0; - Global.config.getString("Nick", m_baseNick, "LOGIN"); - DBGMSG("base nick is " << m_baseNick.get()); - m_baseNick.toLower(); - Global.config.getString("Title", title, "LOGIN"); - Global.config.getString("SecretKey", secretKey, "LOGIN"); - Global.config.getInt("ProfileID", m_profileID, "LOGIN"); - Global.config.getString("CDKey", serialNo, "LOGIN"); - PEERCallbacks callbacks; - PEERBool pingRooms[NumRooms]; - PEERBool crossPingRooms[NumRooms]; - - // Setup the callbacks. - /////////////////////// - memset(&callbacks, 0, sizeof(PEERCallbacks)); - callbacks.disconnected = DisconnectedCallback; - callbacks.playerChangedNick = PlayerChangedNickCallback; - callbacks.playerJoined = PlayerJoinedCallback; - callbacks.playerLeft = PlayerLeftCallback; - callbacks.roomMessage = RoomMessageCallback; - callbacks.playerMessage = PlayerMessageCallback; - callbacks.param = this; - - // Init. - //////// - m_peer = peerInitialize(&callbacks); - if(!m_peer) - { - ERRMSG("Failed to init peer object" << endl); - return; - } - - // Ping/cross-ping in no room. - ///////////////////////////////// - pingRooms[TitleRoom] = PEERFalse; - pingRooms[GroupRoom] = PEERFalse; - pingRooms[StagingRoom] = PEERFalse; - crossPingRooms[TitleRoom] = PEERFalse; - crossPingRooms[GroupRoom] = PEERFalse; - crossPingRooms[StagingRoom] = PEERFalse; - - // Set the title. - ///////////////// - if(!peerSetTitle(m_peer, title.get(), secretKey.get(), title.get(), secretKey.get(), 0, 30, PEERTrue, pingRooms, crossPingRooms)) - { - peerShutdown(m_peer); - ERRMSG("Failed to set the title" << endl); - return; - } - - // Connect. - /////////// - m_connectSuccess = false; - m_nick = m_baseNick.get(); - peerConnect(m_peer, m_baseNick.get(), m_profileID, NickErrorCallback, ConnectCallback, this, PEERTrue); - if(!m_connectSuccess) - { - peerShutdown(m_peer); - ERRMSG("Failed to connect" << endl); - return; - } - - bool cdOk = false; - peerAuthenticateCDKey(m_peer, serialNo.get(), AuthenticateCDKeyCallback, &cdOk, PEERTrue); - if (!cdOk) - { - peerShutdown(m_peer); - ERRMSG("Failed to auth CDKey " << serialNo.get() << endl); - return; - } - - m_groupID = 0; - peerListGroupRooms(m_peer, NULL, ListGroupRoomsCallback, &m_groupID, PEERTrue); - m_groupID = s_groupID; - - DBGMSG("QuickMatch room is " << m_groupID); - - // Join the title room. - /////////////////////// - peerJoinGroupRoom(m_peer, m_groupID, JoinCallback, this, PEERTrue); - if(!m_joinSuccess) - { - peerDisconnect(m_peer); - peerShutdown(m_peer); - ERRMSG("Failed to join the title room" << endl); - return; - } - - // Connected, so lets do our thing - readLoop(); - - peerDisconnect(m_peer); - peerShutdown(m_peer); -} - diff --git a/Generals/Code/Tools/matchbot/matcher.h b/Generals/Code/Tools/matchbot/matcher.h deleted file mode 100644 index 398ca33d6c..0000000000 --- a/Generals/Code/Tools/matchbot/matcher.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __MATCHER_H__ -#define __MATCHER_H__ - -#ifdef _WIN32 -#include -#endif -#include -#include -#include -#include -#include -#include - -#include - -#include - -class MatcherClass -{ -public: - MatcherClass(); - virtual ~MatcherClass() - {} - - virtual void init(void) - {} - - virtual void checkMatches(void) - {} - - virtual void handleDisconnect( const char *reason ) - {} - virtual void handleRoomMessage( const char *nick, const char *message, MessageType messageType ) - {} - virtual void handlePlayerMessage( const char *nick, const char *message, MessageType messageType ) - {} - virtual void handlePlayerJoined( const char *nick ) - {} - virtual void handlePlayerLeft( const char *nick ) - {} - virtual void handlePlayerChangedNick( const char *oldNick, const char *newNick ) - {} - virtual void handlePlayerEnum( bool success, int gameSpyIndex, const char *nick, int flags ) - {} - - void handleConnect( bool success ); - void handleGroupRoomList( bool success, int groupID, const char *name ); - void handleJoin( bool success ); - void handleNickError( const char *badNick ); - - void connectAndLoop( void ); - -protected: - - Wstring getString(const Wstring& key); - - Wstring m_baseNick; - std::string m_nick; - int m_profileID; - PEER m_peer; - bool m_connectSuccess; - bool m_joinSuccess; - void readLoop( void ); - - int done; // 0=no, neg=quit;error, pos=quit;success - bool quiet; - int m_groupID; - - bool m_rotateLogs; // check for log rotation in this thread? - time_t m_lastRotation; - -}; - -#endif /* __MATCHER_H__ */ - diff --git a/Generals/Code/Tools/matchbot/mydebug.cpp b/Generals/Code/Tools/matchbot/mydebug.cpp deleted file mode 100644 index 4090f27125..0000000000 --- a/Generals/Code/Tools/matchbot/mydebug.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include -#include "mydebug.h" -#include "streamer.h" -#include "odevice.h" - - -// static MyMsgManager *msg_manager=NULL; - -// static int paranoid_enabled=0; -static ostream *paranoid_ostream=NULL; -static Streamer paranoid_streamer; - -// Don't dare touch this semaphore in application code! -#ifdef USE_SEM -Sem4 MyDebugLibSemaphore; -#else -CritSec MyDebugLibSemaphore; -#endif - - -int MyMsgManager::setAllStreams(OutputDevice *device) -{ - if (device==NULL) - return(1); - - MYDEBUGLOCK; - paranoid_streamer.setOutputDevice(device); - delete(paranoid_ostream); - paranoid_ostream=new ostream(¶noid_streamer); - - MYDEBUGUNLOCK; - - return(0); -} - - -int MyMsgManager::setParanoidStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - MYDEBUGLOCK; - paranoid_streamer.setOutputDevice(device); - delete(paranoid_ostream); - paranoid_ostream=new ostream(¶noid_streamer); - MYDEBUGUNLOCK; - - return(0); -} - - - - -ostream *MyMsgManager::paranoidStream(void) -{ - return(paranoid_ostream); -} - - -int MyMsgManager::ReplaceAllStreams(FileD * output_device, const char *device_filename, const char *copy_filename) -{ - MYDEBUGLOCK; - - delete(paranoid_ostream); - - if (output_device != NULL) - { - delete(output_device); - output_device = NULL; - } - - rename(device_filename, copy_filename); - - // FileD new_device(device_filename); - output_device = new FileD(device_filename); - - paranoid_streamer.setOutputDevice(output_device); - paranoid_ostream = new ostream(¶noid_streamer); - - MYDEBUGUNLOCK; - - return(0); -} diff --git a/Generals/Code/Tools/matchbot/mydebug.h b/Generals/Code/Tools/matchbot/mydebug.h deleted file mode 100644 index da38b12fb8..0000000000 --- a/Generals/Code/Tools/matchbot/mydebug.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*****************************************************************************\ -wdebug Neal Kettler - -MT-LEVEL - MT-Safe - -The debugging module is pretty good for debugging and it has some message -printing stuff as well. The basic idea is that you write a class that -inherits from OutputDevice (several are provided) and assign that output -device to a stream. There are seperate streams for debugging, information, -warning, and error messages. Each one can have a seperate output device, -or they can all have the same one. Debugging messages only get compiled -in if your module defines 'DEBUG'. If you don't define debug, then not even -the text of the debugging message gets into the binary. All the other -output streams get printed regardless of whether DEBUG is defined. - -Sample usage: -FileD debug_device("gameres.debug"); // create a file device -MsgManager::setDebugStream(&debug_device); -DBGMSG("This debug message #" << 1 << " you use C++ streams"); - -Note that since these are defines you really don't need to put a semicolon -at the end, and it can be bad in situations like this: - -if (x) - DBGMSG("Stuff is broken"); -else - DBGMSG("Stuff is NOT broken"); - -This won't compile, read the code until you figure it out. Only then -will you be ready to leave grasshopper. - -\*****************************************************************************/ - -#ifndef MYDEBUG_HEADER -#define MYDEBUG_HEADER - -#define USE_SEM - -#include "wstypes.h" - -#include -#include - -#ifdef USE_SEM -#include "sem4.h" -#else -#include "critsec.h" -#endif -#include "odevice.h" -#include "streamer.h" -#include "xtime.h" -#include "timezone.h" // MDC -#include "filed.h" - -// This is needed because the streams return a pointer. Every time you -// change the output device the old stream is deleted, and a new one -// is created. -// MDC: Changed from semaphores to critical sections because Windows doesn't provide -// a good way of doing semaphores (I think) -// MDC: Never mind, they seem to be working now! I'm leaving it in, though, so anyone can -// flip a switch between the two. - -#ifdef USE_SEM -extern Sem4 MyDebugLibSemaphore; -#define MYDEBUGLOCK MyDebugLibSemaphore.Wait() -#define MYDEBUGUNLOCK MyDebugLibSemaphore.Post() -#else -extern CritSec MyDebugLibSemaphore; -#define MYDEBUGLOCK MyDebugLibSemaphore.lock() -#define MYDEBUGUNLOCK MyDebugLibSemaphore.unlock() -#endif - -// Print an information message -#define PARANOIDMSG(X)\ -{\ -char timebuf[40]; \ -Xtime now; \ -now -= TimezoneOffset(); \ -now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ -MYDEBUGLOCK; \ -if (MyMsgManager::paranoidStream()) \ -(*(MyMsgManager::paranoidStream())) << "HACK " << timebuf << " [" << \ -__FILE__ << " " << __LINE__ << "] " << X << endl; \ -MYDEBUGUNLOCK; \ -} - -// Just get a stream to the information device, no extra junk -#define PARANOIDSTREAM(X)\ -{\ -MYDEBUGLOCK; \ -if (MyMsgManager::paranoidStream()) \ -(*(MyMsgManager::paranoidStream())) << X;\ -MYDEBUGUNLOCK; \ -} - - -//#undef MYDEBUGLOCK -//#undef MYDEBUGUNLOCK - -class MyMsgManager -{ -protected: - MyMsgManager(); - -public: - static int setAllStreams(OutputDevice *device); - static int setParanoidStream(OutputDevice *device); - static int ReplaceAllStreams(FileD *output_device, const char *device_filename, const char *copy_filename); - - static void enableParanoid(int flag); - - static ostream *paranoidStream(void); -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/rand.cpp b/Generals/Code/Tools/matchbot/rand.cpp deleted file mode 100644 index 87a6469816..0000000000 --- a/Generals/Code/Tools/matchbot/rand.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "rand.h" -#include - -static const double theMultFactor = 1.0 / (pow(2, 8 * sizeof(unsigned int)) - 1.0); - -RandClass::RandClass(int start) -{ - seed[0] = 0xf22d0e56L; - seed[1] = 0x883126e9L; - seed[2] = 0xc624dd2fL; - seed[3] = 0x702c49cL; - seed[4] = 0x9e353f7dL; - seed[5] = 0x6fdf3b64L; - - unsigned int ax; - - ax = start; /* mov eax,SEED */ - ax += 0xf22d0e56; /* add eax,0f22d0e56h */ - seed[0] = ax; /* mov seed,eax */ - ax += 0x883126e9 - 0xf22d0e56; /* add eax,0883126e9h-0f22d0e56h */ - seed[1] = ax; /* mov seed+4,eax */ - ax += 0xc624dd2f - 0x883126e9; /* add eax,0c624dd2fh-0883126e9h */ - seed[2] = ax; /* mov seed+8,eax */ - ax += 0x0702c49c - 0xc624dd2f; /* add eax,00702c49ch-0c624dd2fh */ - seed[3] = ax; /* mov seed+12,eax */ - ax += 0x9e353f7d - 0x0702c49c; /* add eax,09e353f7dh-00702c49ch */ - seed[4] = ax; /* mov seed+16,eax */ - ax += 0x6fdf3b64 - 0x9e353f7d; /* add eax,06fdf3b64h-09e353f7dh */ - seed[5] = ax; /* mov seed+20,eax */ -} - -// Add with carry. SUM is replaced with A + B + C, C is replaced with 1 if there was a carry, 0 if there wasn't. A carry occurred if the sum is less than one of the inputs. This is addition, so carry can never be more than one. -#define ADC(SUM, A, B, C) SUM = (A) + (B) + (C); C = ((SUM < (A)) || (SUM < (B))) - -unsigned int RandClass::randomValue( void ) -{ - unsigned int ax; - unsigned int c = 0; - - - ADC(ax, seed[5], seed[4], c); /* mov ax,seed+20 */ - /* add ax,seed+16 */ - seed[4] = ax; /* mov seed+8,ax */ - - ADC(ax, ax, seed[3], c); /* adc ax,seed+12 */ - seed[3] = ax; /* mov seed+12,ax */ - - ADC(ax, ax, seed[2], c); /* adc ax,seed+8 */ - seed[2] = ax; /* mov seed+8,ax */ - - ADC(ax, ax, seed[1], c); /* adc ax,seed+4 */ - seed[1] = ax; /* mov seed+4,ax */ - - ADC(ax, ax, seed[0], c); /* adc ax,seed+0 */ - seed[0] = ax; /* mov seed+0,ax */ - - /* Increment seed array, bubbling up the carries. */ - if (!++seed[5]) - { - if (!++seed[4]) - { - if (!++seed[3]) - { - if (!++seed[2]) - { - if (!++seed[1]) - { - ++seed[0]; - ++ax; - } - } - } - } - } - return(ax); -} - - -int RandClass::Int(void) -{ - return (int)randomValue(); -} - -int RandClass::Int(int low, int high) -{ - unsigned int delta = high - low + 1; - int rval; - - if (delta == 0) - return high; - - rval = ((int)(randomValue()%delta)) + low; - - return rval; -} - -double RandClass::Double(void) -{ - return Double(0.0, 1.0); -} - -double RandClass::Double(double low, double high) -{ - double delta = high - low; - double rval; - - if (delta <= 0.0) - return high; - - rval = ((double)(randomValue()) * theMultFactor) * delta + low; - return rval; -} - - diff --git a/Generals/Code/Tools/matchbot/rand.h b/Generals/Code/Tools/matchbot/rand.h deleted file mode 100644 index d5a1f4d691..0000000000 --- a/Generals/Code/Tools/matchbot/rand.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __RAND_H__ -#define __RAND_H__ - -#include - -class RandClass -{ -public: - RandClass(int start = 0); - ~RandClass() - {} - - - int Int(void); - double Double(void); - int Int(int low, int high); - double Double(double low, double high); - -private: - - unsigned int randomValue( void ); - unsigned int seed[6]; - -}; - -#endif /* __RAND_H__ */ - diff --git a/Generals/Code/Tools/matchbot/wlib/arraylist.h b/Generals/Code/Tools/matchbot/wlib/arraylist.h deleted file mode 100644 index efcd3abd65..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/arraylist.h +++ /dev/null @@ -1,709 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: -File Name : arraylist.h -Author : Neal Kettler -Start Date : Jan 19, 1997 -Last Update : Jan 19, 1997 ------------------------------------------------------------------------------- - -Array implementation of a list. Note: There are some freaky C++ memory tricks -going on here. If you think there's a leak, see me before changing it. -The way this works is that it allocates an array to hold 'N' items on the -first list add. It doesn't call the constructors for those 'N' items until -necessary (for efficiency). When an item is added to a slot then a new -class is constructed inside the array element using the placement new operator -and the class's copy constructor. When elements are removed the destructor -is then manually called on this memory location. - -All data added to the list is copied so feel free to delete/destroy/modify -the original after an add. - -You _must_ have a good copy constructor for any classes that you use this template -for! A good copy constructor is one that won't blindly duplicate pointers -that don't belong to them, etc... - -\****************************************************************************/ - -#ifndef ARRAYLIST_HEADER -#define ARRAYLIST_HEADER - -#include -#include -#include -#include -#include -#include - -#include "wstypes.h" - -// -// Usage: ArrayList TheList; -// -template -class ArrayList -{ - public: - ArrayList(); - ArrayList(ArrayList &other); - ~ArrayList(); - - // Remove all entries from the lsit - void clear(void); - - // Add a node after the zero based 'pos' - bit8 add(IN T &node,sint32 pos); - bit8 addTail(IN T &node); - bit8 addHead(IN T &node); - bit8 addSortedAsc(IN T &node); // Ascending - bit8 addSortedDes(IN T &node); // Descending - /*bit8 addNumSortedAsc(IN T &node); // Ascending - bit8 addNumSortedDes(IN T &node); // Descending*/ - - // Remove a node - bit8 remove(OUT T &node,sint32 pos); - bit8 remove(sint32 pos); - bit8 removeHead(OUT T &node); - bit8 removeTail(OUT T &node); - - // Replace one obj with another - bit8 replace(IN T &node, sint32 pos); - - - // Get a node without removing from the list - bit8 get(OUT T &node,sint32 pos) RO; - bit8 getHead(OUT T &node) RO; - bit8 getTail(OUT T &node) RO; - - // Get a pointer to the interally managed copy (careful!) - bit8 getPointer(OUT T **node,sint32 pos) RO; - - // Get the number of entries in the list - sint32 length(void) RO; - - // UNSAFE! for classes, see note below! - bit8 setSize(sint32 newsize, IN T &filler); - - // Print information on the list - void print(FILE *out); - - // assignment operator - ArrayList &operator=(IN ArrayList &other); - - private: - sint32 _sortedLookup(IN T &target, int ascending); - sint32 Entries_; // Number of entries - sint32 Slots_; // Number of available slots - - T *Vector_; // The actual memory where the list is held - - enum - { - INITIAL_SIZE = 10 - }; - - bit8 growVector(void); // Expand the number of slots - bit8 shrinkVector(void); // Reduce the number of slots -}; - - -//Create the empty list -template -ArrayList::ArrayList() -{ - Entries_=0; - Slots_=0; - Vector_=NULL; -} - -// copy constructor -template -ArrayList::ArrayList(ArrayList &other) -{ - Entries_=0; - Slots_=0; - Vector_=NULL; - (*this)=other; -} - -//Free all the memory... -template -ArrayList::~ArrayList() -{ - clear(); // Remove the entries & call destructors on them - - delete[]((uint8*)Vector_); // this will prevent the destructors from - // gettting called on elements not - // containing valid objects. - - //fprintf(stderr,"Arraylist destructor\n"); -} - -// assignment operator -template -ArrayList &ArrayList::operator=(IN ArrayList &other) -{ - T node; - clear(); - for (int i=0; i -void ArrayList::clear() -{ - for (int i=0; i~T(); // Call the destructor manually. Don't try this - // at home kiddies! - } - Entries_=0; -} - -// ************************* UNSAFE UNSAFE UNSAFE ************************* -// Note - Don't call this on any type with a constructor/destructor since this -// is really dumb and just puts a new one of filler in. Well, it's kindof safe -// just be careful. -// It's fine for simple classes like ints though.. -// -// Add/remove entries in a stupid manner... -// -// ************************************************************************** -template -bit8 ArrayList::setSize(sint32 newsize, IN T &filler) -{ - int oldEntries=Entries_; - Entries_ = newsize; - - if (newsize<0) - return(false); - - // Grow the vector as much as we need to - while (newsize > Slots_) - growVector(); - - // Create new objects in the blank holes - for (int i=oldEntries; i -bit8 ArrayList::add(IN T &node,sint32 pos) -{ - if (pos > Entries_) // You can only access one of the end of the vector - pos=Entries_; - if (pos >= Slots_) // If we're at the end, grow the list - growVector(); - if (Entries_ >= Slots_) // enuff space? - growVector(); - - // If we are insering into the middle or front of the list we have to - // slide the old objects forward. - if (pos < Entries_) // If there are elements after the add point - memmove(Vector_+pos+1,Vector_+pos,sizeof(T)*(Entries_-pos)); // move them forward - - //fprintf(stderr,"Placement new to %p\n",(Vector_+pos)); - - // This uses the placement new operator. placement new allows us to - // specify the memory address for the new object. In this case we - // want it at the 'pos' index into our array. - new((void *)(Vector_+pos)) T((T &)node); // Trust me, this isn't a memory leak - Entries_++; // one new entry - return(TRUE); -} - - -// Add to the first node, all others get shifted down one slot -template -bit8 ArrayList::addHead(IN T &node) -{ - return(add(node,0)); -} - - -// Append to the end of the list -template -bit8 ArrayList::addTail(IN T &node) -{ - return(add(node,length())); -} - - -// addSortedX only works (properly) if evrerything else in the list is added -// using addSorted. -template -bit8 ArrayList::addSortedAsc(IN T &node) -{ - sint32 pos = _sortedLookup(node, 1); - return(add(node, pos)); -} - - -// addSortedX only works (properly) if evrerything else in the list is added -// using addSorted. -template -bit8 ArrayList::addSortedDes(IN T &node) -{ - sint32 pos = _sortedLookup(node, 0); - return(add(node, pos)); -} - - -// This is the binary search used by addSorted -template -sint32 ArrayList::_sortedLookup(IN T &target, int ascending) -{ - int low, mid, high; - T* lowtarget; - T* hightarget; - T* midtarget; - - - // Trivial cases - if( Entries_ == 0 ) - return 0; - - low = 0; - high = Entries_ - 1; - while( 1 ) - { - assert( low <= high ); - mid = low + (int)(floor(((double)high - (double)low) / (double)2)); - - getPointer(&lowtarget, low); - getPointer(&hightarget, high); - getPointer(&midtarget, mid); - - // Exact match - if( *midtarget == target ) return mid; - - // Single element - if( high == low ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else - return low + 1; - } - else - { - if( target <= *lowtarget ) - return low + 1; - else - return low; - } - } - - // Two elemsnts - if( (high - low) == 1 ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else if( target <= *hightarget ) - return high; - else - return high + 1; - } - else - { - if( target <= *hightarget ) - return high + 1; - else if( target <= *lowtarget ) - return high; - else - return low; - } - } - - // Sorry, try again... - if( ascending ) - { - if( target < *midtarget ) - high = mid; - else - low = mid; - } - else - { - if( target < *midtarget ) - low = mid; - else - high = mid; - } - } -} - - -/*// addNumSortedX works in much the same way as addSortedX, except that I needed -// it for a very specific thing. I needed a list of strings numerically sorted, -// not alphabetically sorted. Furthermore these strings were composed of numbers -// delimited by underscores. In the interest of keeping it generic, these -// functions take as args a node, a delimiting character, and a count of the -// number of fields to include in a sort. If this is the list of strings: -// -// 55_100, 2_5, 23_32, 98_445, 2_48, 8_88, 2_3, 2_4 -// -// An alphabetical sort is: -// -// 2_3, 2_4, 2_48, 2_5, 55_100, 8_88, 98_445 -// -// But a numerical sort by calling addNumSortedAsc(, "_", 2) will result in: -// -// 2_3, 2_4, 2_5, 2_48, 8_88, 55_100, 98_445 -// -// Yes...now that you mention it I am on crack... -// -template -bit8 ArrayList::addNumSortedAsc(IN T &node, char delim, int fields) -{ - sint32 pos = _numSortedLookup(node, delim, fields, 1); - return(add(node, pos)); -} - - -// See addNumSortedAsc comment above. -template -bit8 ArrayList::addSortedDes(IN T &node, char delim, int fields) -{ - sint32 pos = _sortedLookup(node, delim, fields, 0); - return(add(node, pos)); -} - - -// This is the binary search used by addSorted -template -sint32 ArrayList::_numSortedLookup(IN T &target, char delim, int fields, int ascending) -{ - int low, mid, high; - T* lowtarget; - T* hightarget; - T* midtarget; - - - // Trivial case - if( Entries_ == 0 ) - return 0; - - low = 0; - high = Entries_; - while( 1 ) - { - assert( low <= high ); - mid = low + (int)(floor(((double)high - (double)low) / (double)2)); - - getPointer(&lowtarget, low); - getPointer(&hightarget, high); - getPointer(&midtarget, mid); - - // Exact match - if( *midtarget == target ) return mid; - - // Single element - if( high == low ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else - return low + 1; - } - else - { - if( target <= *lowtarget ) - return low + 1; - else - return low; - } - } - - // Two elemsnts - if( (high - low) == 1 ) - { - if( ascending ) - { - if( target <= *lowtarget ) - return low; - else - return high; - } - else - { - if( target <= *lowtarget ) - return high; - else - return low; - } - } - - // Sorry, try again... - if( ascending ) - { - if( target < *midtarget ) - high = mid; - else - low = mid; - } - else - { - if( target < *midtarget ) - low = mid; - else - high = mid; - } - } -}*/ - - -// -// Delete an item at this index and construct a new one in it's place -// -template -bit8 ArrayList::replace(IN T &node, sint32 pos) -{ - if (Entries_==0) - return(FALSE); - if (pos<0) - pos=0; - if (pos >= Entries_) - pos=Entries_-1; - - (Vector_+pos)->~T(); // Call the destructor manually. Don't try this - // at home kiddies! - - // Now put the replacement object in there... - new((void *)(Vector_+pos)) T(node); // Trust me, this isn't a memory leak - - return(TRUE); -} - - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 ArrayList::remove(sint32 pos) -{ - if (Entries_==0) - return(FALSE); - if (pos<0) - pos=0; - if (pos >= Entries_) - pos=Entries_-1; - - (Vector_+pos)->~T(); // Call the destructor manually. Don't try this - // at home kiddies! - - memmove(Vector_+pos,Vector_+pos+1,sizeof(T)*(Entries_-pos-1)); - - Entries_--; - - // If we're at 33% usage or less, shrink the vector - if ( (Entries_*3) <= Slots_) - shrinkVector(); - - return(TRUE); -} - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 ArrayList::remove(OUT T &node, sint32 pos) -{ - bit8 retval; - retval=get(node,pos); - if (retval==FALSE) - return(FALSE); - return(remove(pos)); -} - - -// Remove the first node of the list -template -bit8 ArrayList::removeHead(OUT T &node) -{ - return(remove(node,0)); -} - - -// Remove the last node of the list -template -bit8 ArrayList::removeTail(OUT T &node) -{ - return(remove(node,Entries_-1)); -} - -// get a pointer to the internally managed object. Try and avoid this, but -// sometimes efficiency requires it... -// get a copy of an item -template -bit8 ArrayList::getPointer(OUT T **node,sint32 pos) RO -{ - if ((pos < 0)||(pos >= Entries_)) - return(FALSE); - *node=&(Vector_[pos]); - return(TRUE); -} - - -// get a copy of an item -template -bit8 ArrayList::get(OUT T &node,sint32 pos) RO -{ - if ((pos < 0)||(pos >= Entries_)) - return(FALSE); - node=Vector_[pos]; - return(TRUE); -} - - -// get a copy of the first node of the list -template -bit8 ArrayList::getHead(OUT T &node) RO -{ - return(get(node,0)); -} - - -// get a copy of the last node -template -bit8 ArrayList::getTail(OUT T &node) RO -{ - return(get(node,Entries_-1)); -} - -// just for debugging -template -void ArrayList::print(FILE *out) -{ - fprintf(out,"--------------------\n"); - //for (int i=0; i -sint32 ArrayList::length(void) RO -{ - return(Entries_); -} - -// Grow the vector by a factor of 2X -template -bit8 ArrayList::growVector(void) -{ - if (Entries_ < Slots_) // Don't grow until we're at 100% usage - return(FALSE); - - int newSlots=Entries_*2; - if(newSlots < INITIAL_SIZE) - newSlots=INITIAL_SIZE; - - //fprintf(stderr,"Growing vector to: %d\n",newSlots); - - // The goofy looking new below prevents operator new from getting called - // unnecessarily. This is severall times faster than allocating all of - // the slots as objects and then calling the assignment operator on them - // when they actually get used. - // - T *newVector=(T *)(new uint8[newSlots * sizeof(T)]); - memset(newVector,0,newSlots * sizeof(T)); // zero just to be safe - - if (Vector_ != NULL) - memcpy(newVector,Vector_,Entries_*sizeof(T)); - - delete[]((uint8 *)Vector_); // Get rid of the old vector without calling - // destructors - - Vector_=newVector; - Slots_=newSlots; - - return(TRUE); -} - - -// Shrink the vector by a factor of 2X -template -bit8 ArrayList::shrinkVector(void) -{ - //fprintf(stderr,"Shrink called\n"); - - // Don't need to shrink until usage goes below 33% - if ( (Entries_*3) > Slots_) - return(FALSE); - - int newSlots=Slots_/2; - if(newSlots < INITIAL_SIZE) // never shrink past initial size - newSlots=INITIAL_SIZE; - - if (newSlots >= Slots_) // don't need to shrink - return(FALSE); - - //fprintf(stderr,"Shrinking vector to: %d\n",newSlots); - - // The goofy looking new below prevents operator new from getting called - // unnecessarily. This is severall times faster than allocating all of - // the slots as objects and then calling the assignment operator on them - // when they actually get used. - // - T *newVector=(T *)(new uint8[newSlots * sizeof(T)]); - - if (Vector_ != NULL) // Vector_ better not be NULL! - memcpy(newVector,Vector_,Entries_*sizeof(T)); - - delete[]((uint8 *)Vector_); // Get rid of the old vector without calling - // destructors - - Vector_=newVector; - Slots_=newSlots; - - return(TRUE); -} - - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/configfile.cpp b/Generals/Code/Tools/matchbot/wlib/configfile.cpp deleted file mode 100644 index b0f9e5a91c..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/configfile.cpp +++ /dev/null @@ -1,490 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : configfile.cpp -Author : Neal Kettler -Start Date : June 9, 1997 -Last Update : June 17, 1997 - - -This class will read in a config file and store the key value pairs for -later access. This is a fairly simple class, the config file is assumed -to be of the form: - -#comment -key = value - -The value can then be retrieved as a string or an integer. The key on -the left is used for retrieval and it must be specified in uppercase -for the 'get' functions. E.g. getString("KEY",valWstring); -\***************************************************************************/ - -#include -#include -#include - -#include "configfile.h" -#include "wdebug.h" - -static uint32 Wstring_Hash(const Wstring &string); -static char *Eat_Spaces(char *string); - -ConfigFile::ConfigFile() : Dictionary_(Wstring_Hash) -{ } - -ConfigFile::~ConfigFile() -{ } - -// Read and parse the config file. The key value pairs will be stored -// for later access by the getString/getInt functions. -bit8 ConfigFile::readFile(FILE *in) -{ - char string[256]; - char sectionname[256]; // section name like '[user parameters]' - Wstring key; - Wstring value; - char *cptr; - - memset(string,0,256); - memset(sectionname,0,256); - sectionList.clear(); - - while (fgets(string,256,in)) - { - cptr=Eat_Spaces(string); - if ((*cptr==0)||(*cptr=='#')) // '#' signals a comment - continue; - - if (*cptr=='[') // new section - { - key=cptr; - key.truncate(']'); // remove after & including the ] - key.cat("]"); // put the ] back - strcpy(sectionname,key.get()); // set the current section name - Wstring wssectionname; - - if (strlen(sectionname)==2) // clear section with a "[]" - { - sectionname[0]=0; - wssectionname.set(""); - } - else - wssectionname.set(sectionname+1); - - wssectionname.truncate(']'); - sectionList.addTail(wssectionname); - - - continue; - } - - if (strchr(cptr,'=')==NULL) // All config entries must have a '=' - continue; - key=cptr; - key.truncate('='); - key.removeSpaces(); // No spaces allowed in the key - key.toUpper(); // make key all caps - - // Add the section name to the end of the key - if (strlen(sectionname)) - key.cat(sectionname); - - cptr=Eat_Spaces(strchr(cptr,'=')+1); // Jump to after the '=' - value=cptr; - value.truncate('\r'); - value.truncate('\n'); - value.truncate('#'); - - // TheSuperHackers @compile xezon 25/03/2025 Re-implement algorithm to avoid writing into string buffer directly. - // Remove trailing spaces - { - const char* valueStr = value.get(); - const uint32 valueLen = value.length(); - uint32 spaceIdx = valueLen; - for (; spaceIdx > 0 && isgraph(valueStr[spaceIdx - 1])==0; --spaceIdx); - if (spaceIdx != valueLen) - value.truncate(spaceIdx); - } - - Critsec_.lock(); - Dictionary_.add(key,value); - Critsec_.unlock(); - } - return(TRUE); -} - - -// -// Enum through the config strings. To start, index & offset should be 0 -// If retval is false you're done, ignore whatever's in key & value. -// -// Section specifies the configfile section. Set to NULL if you don't care. -// -bit8 ConfigFile::enumerate(int &index, int &offset, Wstring &key, Wstring &value, IN char *section) const -{ - int seclen = strlen(section); - while(1) - { - Critsec_.lock(); - if (Dictionary_.iterate(index,offset,key,value)==FALSE) // out of keys? - { - Critsec_.unlock(); - return(FALSE); - } - Critsec_.unlock(); - - if (section==NULL) // no specified section, so any will do... - break; - - if (strlen(section)+2 >= strlen(key.get())) // key should have form: X[section] - continue; - - // Is this key part of our section? - const char *keystr = key.get() + strlen(key.get())-seclen-1; - if (strncmp(keystr,section,strlen(section))==0) - break; - } - key.truncate('['); // remove the section name - return(TRUE); -} - - - -// Get a config entry as a string -bit8 ConfigFile::getString(IN Wstring &_key, Wstring &value, IN char *section) const -{ - Wstring key(_key); - key.toUpper(); - - if (section) // append section name to key - { - key+="["; - key+=section; - key+="]"; - } - - Critsec_.lock(); - bit8 retval=Dictionary_.getValue(key,value); - Critsec_.unlock(); - - if (retval==FALSE) - { - DBGMSG("Config entry missing: "<>24); // ROL 8 - } - return(retval); -} - -static char *Eat_Spaces(char *string) -{ - char *retval=string; - while (isspace(*retval)) - retval++; - return(retval); -} diff --git a/Generals/Code/Tools/matchbot/wlib/configfile.h b/Generals/Code/Tools/matchbot/wlib/configfile.h deleted file mode 100644 index b622f1354e..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/configfile.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : configfile.h -Author : Neal Kettler -Start Date : June 9, 1997 -Last Update : May 13, 1999 -\***************************************************************************/ - -#ifndef CONFIGFILE_HEADER -#define CONFIGFILE_HEADER - -#include "wstypes.h" -#include "dictionary.h" -#include "wstring.h" -#include "critsec.h" -#include "arraylist.h" - -class ConfigFile -{ - public: - ConfigFile(); - ~ConfigFile(); - bit8 readFile(FILE *config); - bit8 getString(IN Wstring &key,OUT Wstring &value, IN char *section=NULL) const; - bit8 getString(IN char *key,OUT Wstring &value, IN char *section=NULL) const; - - bit8 getInt(IN Wstring &key,OUT sint32 &value, IN char *section=NULL) const; - bit8 getInt(IN char *key,OUT sint32 &value, IN char *section=NULL) const; - - bit8 getInt(IN Wstring &key,OUT sint16 &value, IN char *section=NULL) const; - bit8 getInt(IN char *key,OUT sint16 &value, IN char *section=NULL) const; - - // Enumerate through the config lines - bit8 enumerate(int &index, int &offset, Wstring &key, Wstring &value, IN char *section=NULL) const; - - // Manual update of config file - bit8 setString(IN Wstring &key,IN Wstring &value, IN char *section=NULL); - bit8 setString(IN char *key,IN Wstring &value, IN char *section=NULL); - bit8 setInt(IN Wstring &key,IN sint32 &value, IN char *section=NULL); - bit8 setInt(IN char *key,IN sint32 &value, IN char *section=NULL); - bit8 removeEntry(IN Wstring &key, IN char *section=NULL); - bit8 removeEntry(IN char *key, IN char *section=NULL); - bit8 writeFile(FILE *config); // Does not preserve comments, etc - - ArrayList sectionList; // stores the names of all sections - - private: - Dictionary Dictionary_; // stores the mappings from keys - // to value strings - - // The lock is only needed around the immediate access to the dictionary, no writes - // are allowed so you don't need to worry about an outer lock around the enumerate - CritSec Critsec_; // lock around dictionary -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/critsec.cpp b/Generals/Code/Tools/matchbot/wlib/critsec.cpp deleted file mode 100644 index 21b8ced2b7..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/critsec.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "critsec.h" -#include -#include "wlib/wdebug.h" - - - -CritSec::CritSec() -{ -#ifdef _UNIX - pthread_mutex_init(&Mutex_, NULL); - RefCount_ = 0; -#elif defined(_WIN32) - InitializeCriticalSection(&CritSec_); -#endif -} - -CritSec::~CritSec() -{ - #ifdef _UNIX - pthread_mutex_destroy(&Mutex_); - #elif defined(_WIN32) - DeleteCriticalSection(&CritSec_); - #endif -} - -// The "lock" function blocks until the mutex is available. -// Returns 0 on success, error code on error. -// -// A thread that already has a lock will increment a reference count if it calls -// lock again. It must then call unlock() enough times to get the reference to 0. -// -// If refcount is not null you can get the current ref counter after the lock. -// -sint32 CritSec::lock(int *refcount) RO -{ - #ifdef _UNIX - sint32 status; - - // I TRY to get the lock. IF I succeed, OR if I fail because - // I already have the lock, I just increment the reference - // count and return. - if (((status = pthread_mutex_trylock(&Mutex_)) == 0) || - ((status == EBUSY) && (ThreadId_ == pthread_self()))) - { - ThreadId_ = pthread_self(); - RefCount_++; - if (refcount) - *refcount=RefCount_; - return(0); - } - - // Otherwise, I wait for the lock. - if ((status = pthread_mutex_lock(&Mutex_)) == 0) - { - assert(RefCount_ == 0); - ThreadId_ = pthread_self(); - RefCount_++; - } - else - { - ERRMSG("pthread_mutex_lock: " << strerror(errno)); - } - - if (refcount) - *refcount=RefCount_; - - return(status); - #elif defined(_WIN32) - // TOFIX update the refcount - EnterCriticalSection(&CritSec_); - return(0); - #else - #error Must define either _WIN32 or _UNIX - #endif -} - -// The "unlock" function release the critical section. -sint32 CritSec::unlock(void) RO -{ - #ifdef _UNIX - sint32 status = 0; - - assert(RefCount_ >= 0); - if (RefCount_ <= 0) - { - //ERRMSG("unlocking unlocked mutex!"); - return(-1); - } - - ///assert(ThreadId_ == pthread_self()); - if (ThreadId_ != pthread_self()) - { - WRNMSG("tried to unlock a mutex not owned by self"); - return(-1); - } - - if (--RefCount_ == 0) - { - // Set thread id to zero -- we're going to release mutex - ThreadId_ = (pthread_t)0; - - // Unlock the mutex. - if ((status = pthread_mutex_unlock(&Mutex_)) != 0) - ERRMSG("pthread_mutex_lock: " << strerror(errno)); - } - return status; - #elif defined(_WIN32) - LeaveCriticalSection(&CritSec_); - return(0); - #endif -} diff --git a/Generals/Code/Tools/matchbot/wlib/critsec.h b/Generals/Code/Tools/matchbot/wlib/critsec.h deleted file mode 100644 index c25759cf04..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/critsec.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef CRITSEC_HEADER -#define CRITSEC_HEADER - -#include "wstypes.h" -#ifdef _WIN32 - #include - #include -#elif defined(_UNIX) - #include - #include -#endif - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -// -// Critical Section built either on a POSIX Mutex, or a Win32 Critical Section -// -// POSIX version is done by keeping a thread_id and a reference count. Win32 version -// just calls the built in functions. -// -class CritSec -{ - public: - CritSec(); - ~CritSec(); - - sint32 lock(int *refcount=NULL) RO; - sint32 unlock(void) RO; - - protected: - #ifdef _WIN32 - mutable CRITICAL_SECTION CritSec_; - #else - mutable pthread_mutex_t Mutex_; // Mutex lock - mutable pthread_t ThreadId_; // Owner of mutex - mutable int RefCount_; // Reference count - #endif -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/dictionary.h b/Generals/Code/Tools/matchbot/wlib/dictionary.h deleted file mode 100644 index 56e1cc346b..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/dictionary.h +++ /dev/null @@ -1,681 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : dictionary.h -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 - -This template file implements a hash dictionary. A hash dictionary is -used to quickly match a value with a key. This works well for very -large sets of data. A table is constructed that has some power of two -number of pointers in it. Any value to be put in the table has a hashing -function applied to the key. That key/value pair is then put in the -linked list at the slot the hashing function specifies. If everything -is working well, this is much faster than a linked list, but only if -your hashing function is good. -\****************************************************************************/ - - -#ifndef DICTIONARY_HEADER -#define DICTIONARY_HEADER - - -#include -#include -#include -#include -#include - -#include "wstypes.h" - -// Every entry in the hash dictionary must be an instance of the DNode -// template. 'K' and 'V' denote Key and Value. -template -class DNode -{ - public: - K key; - V value; - DNode *hashNext; -}; - -template -class Dictionary -{ - public: - ////////////////Dictionary(uint32 (* hashFn)(K &key)); - - -// Note: I had to put this inside the class definition because VC5 sucks butt - -//Create the empty hash dictionary -Dictionary(uint32 (*hashFn)(const K &key)) : - SHRINK_THRESHOLD(0.20), // When table is only 20% full shrink it - EXPAND_THRESHOLD(0.80), // When table is 80% full grow it - MIN_TABLE_SIZE(128) // must be a power of 2 -{ - log2Size=MIN_TABLE_SIZE; - size=MIN_TABLE_SIZE; - assert(size>=4); - tableBits=0; - while(log2Size) { tableBits++; log2Size>>=1; } - tableBits--; - size=1< **)new DNode* [size]; - assert(table!=NULL); - - memset((void *)table,0,size*sizeof(void *)); - hashFunc=hashFn; -} - - - ~Dictionary(); - - void clear(void); - bit8 add(IN K &key,IN V &value); - bool getValue(IN K &key, OUT V &value) RO; - bool getPointer(IN K &key, OUT V **value) RO; // ptr to internal storage (Careful!) - void print(FILE *out) RO; - uint32 getSize(void) RO; - uint32 getEntries(void) RO; - bit8 contains(IN K &key) RO; - bit8 updateValue(IN K &key,IN V &value); - bit8 remove(IN K &key,OUT V &value); - bit8 remove(IN K &key); - bit8 removeAny(OUT K &key,OUT V &value); - bit8 iterate(INOUT int &index,INOUT int &offset, OUT V &value) RO; - bit8 iterate(INOUT int &index,INOUT int &offset, OUT K &key, OUT V &value) RO; - Dictionary &operator=(Dictionary &other); - - private: - void shrink(void); // halve the number of slots - void expand(void); // double the number of slots - - - DNode **table; // This stores the lists at each slot - - uint32 entries; // number of entries - uint32 size; // size of table - uint32 tableBits; // table is 2^tableBits big - uint32 log2Size; // Junk variable - bit8 keepSize; // If true don't shrink or expand - - uint32 (* hashFunc)(IN K &key); // User provided hash function - uint32 keyHash(IN K &key) RO; // This will reduce to correct range - - - // See initilizer list of constructor for values - const double SHRINK_THRESHOLD; // When table is this % full shrink it - const double EXPAND_THRESHOLD; // When table is this % full grow it - const int MIN_TABLE_SIZE; // must be a power of 2 -}; - - - -//Free all the memory... -template -Dictionary::~Dictionary() -{ - clear(); // Remove the entries - delete[](table); // And the table as well -} - -// Remove all the entries and free the memory -template -void Dictionary::clear() -{ - DNode *temp,*del; - uint32 i; - //free all the data - for (i=0; ihashNext; - delete(del); - } - table[i]=NULL; - } - entries=0; - - while ((getSize()>(uint32)MIN_TABLE_SIZE)&&(keepSize==FALSE)) - shrink(); -} - -template -uint32 Dictionary::keyHash(IN K &key) RO -{ - uint32 retval=hashFunc(key); - retval &= ((1< -void Dictionary::print(FILE *out) RO -{ - DNode *temp; - uint32 i; - - fprintf(out,"--------------------\n"); - for (i=0; ihashNext; - } - fprintf(out,"\n"); - } - fprintf(out,"--------------------\n"); -} - - -template -Dictionary &Dictionary::operator=(Dictionary &other) -{ - _ASSERTE(0); -} - - - -// -// Iterate through all the records. Index is for the table, offset specifies the -// element in the linked list. Set both to 0 and continue calling till false -// is returned. -template -bit8 Dictionary::iterate(INOUT int &index,INOUT int &offset, - OUT V &value) RO -{ - DNode *temp; - - // index out of range - if ((index<0)||(index >= (int)getSize())) - return(FALSE); - - temp=table[index]; - while ((temp==NULL)&&((++index) < (int)getSize())) - { - temp=table[index]; - offset=0; - } - - if (temp==NULL) // no more slots with data - return(FALSE); - - uint32 i=0; - while ((temp!=NULL) && ((int)i < offset)) - { - temp=temp->hashNext; - i++; - } - - if (temp==NULL) // should never happen - return(FALSE); - - value=temp->value; - if (temp->hashNext==NULL) - { - index++; - offset=0; - } - else - offset++; - - return(TRUE); -} - - - - -// -// Iterate through all the records. Index is for the table, offset specifies the -// element in the linked list. Set both to 0 and continue calling till false -// is returned. -template -bit8 Dictionary::iterate(INOUT int &index,INOUT int &offset, - OUT K &key, OUT V &value) RO -{ - DNode *temp; - - // index out of range - if ((index<0)||(index >= (int)getSize())) - return(FALSE); - - temp=table[index]; - while ((temp==NULL)&&((++index) < (int)getSize())) - { - temp=table[index]; - offset=0; - } - - if (temp==NULL) // no more slots with data - return(FALSE); - - uint32 i=0; - while ((temp!=NULL) && ((int)i < offset)) - { - temp=temp->hashNext; - i++; - } - - if (temp==NULL) // should never happen - return(FALSE); - - value=temp->value; - key=temp->key; - if (temp->hashNext==NULL) - { - index++; - offset=0; - } - else - offset++; - - return(TRUE); -} - - - - -// Return the current size of the hash table -template -uint32 Dictionary::getSize(void) RO -{ return(size); } - - -// Return the current number of entries in the table -template -uint32 Dictionary::getEntries(void) RO -{ return(entries); } - - -// Does the Dictionary contain the key? -template -bit8 Dictionary::contains(IN K &key) RO -{ - int offset; - DNode *node; - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - { return(FALSE); } // can't find it - - while(node!=NULL) - { - if ((node->key)==key) - { return(TRUE); } - node=node->hashNext; - } - return(FALSE); -} - - -// Try and update the value of an already existing object -template -bit8 Dictionary::updateValue(IN K &key,IN V &value) -{ - sint32 retval; - - retval=remove(key); - if (retval==FALSE) - return(FALSE); - - add(key,value); - return(TRUE); -} - - -// Add to the dictionary (if key exists, value is updated with the new V) -template -bit8 Dictionary::add(IN K &key,IN V &value) -{ - int offset; - DNode *node,*item,*temp; - float percent; - - item=(DNode *)new DNode; - assert(item!=NULL); - - #ifdef KEY_MEM_OPS - memcpy(&(item->key),&key,sizeof(K)); - #else - item->key=key; - #endif - - #ifdef VALUE_MEM_OPS - memcpy(&(item->value),&value,sizeof(V)); - #else - item->value=value; - #endif - - item->hashNext=NULL; - - //If key already exists, it will be overwritten - remove(key); // Hopefully this will be false... - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - { table[offset]=item; } - else - { - temp=table[offset]; - table[offset]=item; - item->hashNext=temp; - } - - entries++; - percent=(float)entries; - percent/=(float)getSize(); - if (percent>= EXPAND_THRESHOLD ) expand(); - - return(TRUE); -} - -// Remove an item from the dictionary -template -bit8 Dictionary::remove(IN K &key,OUT V &value) -{ - int offset; - DNode *node,*last,*temp; - float percent; - - if (entries==0) - return(FALSE); - - percent=(float)(entries-1); - percent/=(float)getSize(); - - offset=keyHash(key); - node=table[offset]; - - last=node; - if (node==NULL) - return(FALSE); - - //special case table points to thing to delete - - #ifdef KEY_MEM_OPS - if (0==memcmp(&(node->key),&key,sizeof(K))) - #else - if ((node->key)==key) - #endif - { - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - temp=table[offset]->hashNext; - delete(table[offset]); - table[offset]=temp; - entries--; - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); - } - node=node->hashNext; - - bit8 retval=FALSE; // wow, didn't add this for years... (DOH!) - - //Now the case if the thing to delete is not the first - while (node!=NULL) - { - #ifdef KEY_MEM_OPS - if (0==memcmp(&(node->key),&key,sizeof(K))) - #else - if (node->key==key) - #endif - { - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - last->hashNext=node->hashNext; - entries--; - delete(node); - retval=TRUE; // yes, we deleted something - break; - } - last=node; - node=node->hashNext; - } - - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(retval); -} - - -template -bit8 Dictionary::remove(IN K &key) -{ - V temp; - return(remove(key,temp)); -} - - -// Remove some random K/V pair that's in the Dictionary -template -bit8 Dictionary::removeAny(OUT K &key,OUT V &value) -{ - int offset; - DNode *node,*last,*temp; - float percent; - - if (entries==0) - return(FALSE); - - percent=(entries-1); - percent/=(float)getSize(); - - int i; - offset=-1; - for (i=0; i<(int)getSize(); i++) - if (table[i]!=NULL) - { - offset=i; - break; - } - - if (offset==-1) // Nothing there - return(FALSE); - - node=table[offset]; - last=node; - - #ifdef KEY_MEM_OPS - memcpy(&key,&(node->key),sizeof(K)); - #else - key=node->key; - #endif - #ifdef VALUE_MEM_OPS - memcpy(&value,&(node->value),sizeof(V)); - #else - value=node->value; - #endif - - temp=table[offset]->hashNext; - delete(table[offset]); - table[offset]=temp; - entries--; - if (percent <= SHRINK_THRESHOLD) - shrink(); - return(TRUE); -} - - -template -bool Dictionary::getValue(IN K &key,OUT V &value) RO -{ - V *valptr=NULL; - bool retval=getPointer(key,&valptr); - if (retval && valptr) - { - #ifdef VALUE_MEM_OPS - assert(0); - #else - value=*valptr; - #endif - } - return(retval); -} - -// Try and avoid this since you're getting a pointer to the internally -// managed data! -template -bool Dictionary::getPointer(IN K &key,OUT V **valptr) RO -{ - int offset; - DNode *node; - - if (entries==0) - return(FALSE); - - offset=keyHash(key); - - node=table[offset]; - - if (node==NULL) - return(FALSE); - - #ifdef KEY_MEM_OPS - while ((node!=NULL)&&(memcmp(&(node->key),&key,sizeof(K)))) - #else - while ((node!=NULL)&&( ! ((node->key)==key)) ) // odd syntax so you don't - #endif // have to do oper != - { node=node->hashNext; } - - if (node==NULL) - { return(FALSE); } - - *valptr=&(node->value); - - return(TRUE); -} - - -//A note about Shrink and Expand: They are never necessary, they are -//only here to improve performance of the hash table by reducing -//the length of the linked list at each table entry. - -// Shrink the hash table by a factor of 2 (and relocate entries) -template -void Dictionary::shrink(void) -{ - int i; - int oldsize; - uint32 offset; - DNode **oldtable,*temp,*first,*next; - - if ((size<=(uint32)MIN_TABLE_SIZE)||(keepSize==TRUE)) - return; - - //fprintf(stderr,"Shrinking....\n"); - - oldtable=table; - oldsize=size; - size/=2; - tableBits--; - - table=(DNode **)new DNode*[size]; - assert(table!=NULL); - memset((void *)table,0,size*sizeof(void *)); - - for (i=0; ikey); - first=table[offset]; - table[offset]=temp; - next=temp->hashNext; - temp->hashNext=first; - temp=next; - } - } - delete[](oldtable); -} - - -template -void Dictionary::expand(void) -{ - int i; - int oldsize; - uint32 offset; - DNode **oldtable,*temp,*first,*next; - - if (keepSize==TRUE) - return; - - //fprintf(stderr,"Expanding...\n"); - - oldtable=table; - oldsize=size; - size*=2; - tableBits++; - - table=(DNode **)new DNode* [size]; - assert(table!=NULL); - memset((void *)table,0,size*sizeof(void *)); - - for (i=0; ikey); - first=table[offset]; - table[offset]=temp; - next=temp->hashNext; - temp->hashNext=first; - temp=next; - } - } - delete[](oldtable); -} - - -#endif - diff --git a/Generals/Code/Tools/matchbot/wlib/filed.h b/Generals/Code/Tools/matchbot/wlib/filed.h deleted file mode 100644 index ac68d7c705..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/filed.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef FILED_HEADER -#define FILED_HEADER - -#include "odevice.h" - -class FileD : public OutputDevice -{ - public: - FileD(IN char *filename, IN char *mode = "w") - { - out=fopen(filename,mode); - if (out==NULL) - out=fopen("FileDev.out",mode); - } - - virtual ~FileD() - { fclose(out); } - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - fprintf(out,"%s",string); - delete[](string); - fflush(out); - return(len); - } - - FILE *out; -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/linkedlist.h b/Generals/Code/Tools/matchbot/wlib/linkedlist.h deleted file mode 100644 index d546d3e96c..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/linkedlist.h +++ /dev/null @@ -1,495 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: -File Name : linkedlist.h -Author : Neal Kettler -Start Date : June 19, 1997 -Last Update : June 19, 1997 - -Linked list template. This is a fairly standard doubly linked list that -allows insertion and removal at any point in the list. A current pointer -is used to quickly access items when they are examined sequentially. -Copies of the data are stored instead of a pointer to the original. - -If you want to store pointers then the template should be of a pointer type. -\****************************************************************************/ - -#ifndef LINKEDLIST_HEADER -#define LINKEDLIST_HEADER - -#include -#include -#include -#include - -#include "wstypes.h" - -template -class LNode -{ - public: - T Node; - LNode *Next; - LNode *Prev; -}; - -template -class LinkedList -{ - public: - LinkedList(); - LinkedList(LinkedList &other); - ~LinkedList(); - - // Remove all entries from the lsit - void clear(void); - - // Add a node after the zero based 'pos' - bit8 add(IN T &node,sint32 pos, OUT T **newnodeptr=NULL); - bit8 addTail(IN T &node, OUT T **newnodeptr=NULL); - bit8 addHead(IN T &node, OUT T **newnodeptr=NULL); - - // Remove a node - bit8 remove(OUT T &node,sint32 pos); - bit8 remove(sint32 pos); - bit8 removeHead(OUT T &node); - bit8 removeTail(OUT T &node); - - - // Get a node without removing from the list - bit8 get(OUT T &node,sint32 pos); - bit8 getHead(OUT T &node); - bit8 getTail(OUT T &node); - - // Get a pointer to the internally managed data (careful!) - bit8 getPointer(OUT T **node, sint32 pos); - - // Get the number of entries in the list - sint32 length(void); - - // Print information on the list - void print(IN FILE *out); - - // assignment operator - LinkedList &operator=(LinkedList &other); - - private: - sint32 Entries; // Number of entries - LNode *Head; // Head of the list - LNode *Tail; // Tail of the list - - LNode *Current; // Current pointer & index for speed only - sint32 CurIndex; -}; - - -//Create the empty list -template -LinkedList::LinkedList() -{ - Entries=0; - Head=Tail=Current=NULL; - CurIndex=-1; // Not valid when 0 entries -} - -// copy constructor -template -LinkedList::LinkedList(LinkedList &other) -{ - Entries=0; - Head=Tail=Current=NULL; - CurIndex=-1; // Not valid when 0 entries - (*this)=other; -} - -//Free all the memory... -template -LinkedList::~LinkedList() -{ - clear(); // Remove the entries -} - -// assignment operator -template -LinkedList &LinkedList::operator=(LinkedList &other) -{ - T node; - clear(); - for (int i=0; i -void LinkedList::clear() -{ - LNode *temp,*del; - - temp=Head; - while (temp) { - del=temp; - temp=temp->Next; - delete(del); - } - Entries=0; - CurIndex=-1; - Head=Tail=Current=NULL; -} - -// When adding into a position, the new node goes at the zero based slot -// specified by pos. All other nodes get moved one slot down. -template -bit8 LinkedList::add(IN T &node,sint32 pos, OUT T **newnodeptr) -{ - LNode *temp; - LNode *item; - - if (pos<0) - pos=0; - if (pos>Entries) - pos=Entries; - - item=(LNode *)new LNode; - assert(item!=NULL); - item->Node=node; // copy the passed in object - item->Prev=NULL; - item->Next=NULL; - - if (newnodeptr) - *newnodeptr=&(item->Node); - - if ((pos==0)||(pos==Entries)) { // Both cases can be true for a new list! - if (pos==0) { - item->Next=Head; - if (Head) - Head->Prev=item; - Head=item; - } - if (pos==Entries) { - item->Prev=Tail; - if (Tail) - Tail->Next=item; - Tail=item; - } - Entries++; - Current=item; - CurIndex=pos; - return(TRUE); - } - - // If control is here, we know the new node is not an endpoint - - // Check for possible speedup, so we don't have to scan the list - if (pos==CurIndex) { - item->Next=Current; - item->Prev=Current->Prev; - Current->Prev=item; - item->Prev->Next=item; - Current=item; - Entries++; - return(TRUE); - } - // Check the other possible speedup (adding after CurIndex) - if (pos==CurIndex+1) { - item->Next=Current->Next; - item->Prev=Current; - Current->Next=item; - item->Next->Prev=item; - Current=item; - CurIndex++; - Entries++; - return(TRUE); - } - - // If control reaches here we have to scan the whole thing - temp=Head->Next; // Can start at node '1' because head was special cased - for (int i=1; iNext; - assert(temp!=NULL); - } - item->Next=temp; - item->Prev=temp->Prev; - temp->Prev=item; - item->Prev->Next=item; - Current=item; - CurIndex=pos; - Entries++; - - return(TRUE); -} - - -// Add to the first node, all others get shifted down one slot -template -bit8 LinkedList::addHead(IN T &node, OUT T **newnodeptr) -{ - return(add(node,0,newnodeptr)); -} - - -// Append to the end of the list -template -bit8 LinkedList::addTail(IN T &node, OUT T **newnodeptr) -{ - return(add(node,length(),newnodeptr)); -} - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 LinkedList::remove(OUT T &node, sint32 pos) -{ - ////////LNode *temp; - LNode *item; - - if (Entries==0) - return(FALSE); - - if (pos<0) - pos=0; - if (pos>=Entries) - pos=Entries-1; - - if ((pos==0)||(pos==Entries-1)) { // Both can be true for a 1 item list - if (pos==0) { - item=Head; - if (item->Next) - item->Next->Prev=NULL; - Head=item->Next; - node=item->Node; - Current=Head; - CurIndex=0; - } - if (pos==Entries-1) { - item=Tail; - if (item->Prev) - item->Prev->Next=NULL; - Tail=item->Prev; - node=item->Node; - Current=Tail; - CurIndex=Entries-2; - } - delete(item); - Entries--; - - if (Entries==0) { // Super paranoia check - assert(Current==NULL); - assert(CurIndex==-1); - assert(Head==NULL); - assert(Tail==NULL); - } - return(TRUE); - } - // If control is here, we know the target node is not an endpoint - - // Check for possible speedup, so we don't have to scan the list - if (pos==CurIndex) { - item=Current; - item->Prev->Next=item->Next; - item->Next->Prev=item->Prev; - Current=item->Next; - // CurIndex stays the same - node=item->Node; - delete(item); - Entries--; - return(TRUE); - } - - // Check the other possible speedup (removing after CurIndex) - if (pos==CurIndex+1) { - item=Current->Next; - item->Prev->Next=item->Next; - item->Next->Prev=item->Prev; - Current=item->Next; - CurIndex++; - node=item->Node; - delete(item); - Entries--; - return(TRUE); - } - - - // If control reaches here we have to scan the whole thing - item=Head->Next; // Can start at node '1' because head was special cased - for (int i=1; iNext; - assert(item!=NULL); - } - - item->Prev->Next=item->Next; - item->Next->Prev=item->Prev; - Current=item->Next; - CurIndex=pos; - node=item->Node; - delete(item); - Entries--; - - return(TRUE); -} - - - - -// Remove at the zero based index specified by 'pos'. When removing from -// a slot, all others get shifted up by one. -template -bit8 LinkedList::remove(sint32 pos) -{ - T temp_node; - return(remove(temp_node,pos)); -} - - -// Remove the first node of the list -template -bit8 LinkedList::removeHead(OUT T &node) -{ - return(remove(node,0)); -} - - -// Remove the last node of the list -template -bit8 LinkedList::removeTail(OUT T &node) -{ - return(remove(node,Entries-1)); -} - - - -template -bit8 LinkedList::get(OUT T &node, sint32 pos) -{ - T *objptr; - bool retval=getPointer(&objptr,pos); - if (retval && objptr) - node=*objptr; - - return(retval); -} - - -template -bit8 LinkedList::getPointer(OUT T **node,sint32 pos) -{ - if ((node==0)||(Entries==0)) - return(FALSE); - - LNode *item; - - if (pos<0) - { - //pos=0; - return(FALSE); - } - if (pos>=Entries) - { - //pos=Entries-1; - return(FALSE); - } - - if (pos==0) { - *node=&(Head->Node); - return(TRUE); - } else if (pos==Entries-1) { - *node=&(Tail->Node); - return(TRUE); - } - // If control reaches here, we know target is not an endpoint - - // Check for possible speedup, so we don't have to scan the list - if (pos==CurIndex) { - *node=&(Current->Node); - return(TRUE); - } else if (pos==CurIndex+1) { - *node=&(Current->Next->Node); - CurIndex++; - Current=Current->Next; - return(TRUE); - } else if (pos==CurIndex-1) { - *node=&(Current->Prev->Node); - CurIndex--; - Current=Current->Prev; - return(TRUE); - } - - // If control reaches here we have to scan the whole thing - item=Head->Next; // Can start at node '1' because head was special cased - for (int i=1; iNext; - assert(item!=NULL); - } - *node=&(item->Node); - CurIndex=pos; - Current=item; - - return(TRUE); -} - - -// Remove the first node of the list -template -bit8 LinkedList::getHead(OUT T &node) -{ - return(get(node,0)); -} - - -// Remove the last node of the list -template -bit8 LinkedList::getTail(OUT T &node) -{ - return(get(node,Entries-1)); -} - - -template -void LinkedList::print(IN FILE *out) -{ - LNode *temp; - - fprintf(out,"--------------------\n"); - fprintf(out,"Entries = %d\n",length()); - fprintf(out,"H = %8p C = %8p (%d) T = %8p\n",Head,Current,CurIndex,Tail); - - temp=Head; - while (temp) { - fprintf(out," %8p<-((%8p))->%8p \n",temp->Prev,temp,temp->Next); - temp=temp->Next; - } - - fprintf(out,"--------------------\n"); -} - -// Return the current length of the list -template -sint32 LinkedList::length(void) { - return(Entries); -} - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/mboxd.h b/Generals/Code/Tools/matchbot/wlib/mboxd.h deleted file mode 100644 index 4bd1e7f121..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/mboxd.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef MBOXD_HEADER -#define MBOXD_HEADER - -#include "odevice.h" - -class MboxD : public OutputDevice -{ - public: - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - MessageBox(NULL,string,"Debug Message", MB_OK | MB_ICONINFORMATION); - delete[](string); - return(len); - } - -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/monod.cpp b/Generals/Code/Tools/matchbot/wlib/monod.cpp deleted file mode 100644 index 5448e627f1..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/monod.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "monod.h" - -MonoD::MonoD(void) -{ -#ifdef _WIN32 - unsigned long retval; - handle = CreateFile("\\\\.\\MONO", GENERIC_READ|GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - - if (handle != INVALID_HANDLE_VALUE) - { - DeviceIoControl(handle, (DWORD)IOCTL_MONO_CLEAR_SCREEN, NULL, 0, NULL, 0, - &retval,0); - } -#endif -} - -MonoD::~MonoD() -{ - #ifdef _WIN32 - CloseHandle(handle); - handle=NULL; - #endif -} - -int MonoD::print(const char *str, int len) -{ - #ifdef _WIN32 - unsigned long retval; - WriteFile(handle, str, len, &retval, NULL); - ////DeviceIoControl(handle, (DWORD)IOCTL_MONO_PRINT_RAW, (void *)str, len, NULL, 0, - //// &retval,0); - return(len); - #else - for (int i=0; i. -*/ - -#ifndef MONOD_HEADER -#define MONOD_HEADER - - -#include -#include -#include "odevice.h" - -///////////////////////// WIN32 ONLY /////////////////////////////////// - -#ifdef _WIN32 -#include -#include - - -/* -** This is the identifier for the Monochrome Display Driver -*/ -#define FILE_DEVICE_MONO 0x00008000 - -/* -** These are the IOCTL commands supported by the Monochrome Display Driver. -*/ -#define IOCTL_MONO_HELP_SCREEN CTL_CODE(FILE_DEVICE_MONO, 0x800, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_CLEAR_SCREEN CTL_CODE(FILE_DEVICE_MONO, 0x801, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_PRINT_RAW CTL_CODE(FILE_DEVICE_MONO, 0x802, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_CURSOR CTL_CODE(FILE_DEVICE_MONO, 0x803, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SCROLL CTL_CODE(FILE_DEVICE_MONO, 0x804, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_BRING_TO_TOP CTL_CODE(FILE_DEVICE_MONO, 0x805, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_ATTRIBUTE CTL_CODE(FILE_DEVICE_MONO, 0x806, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_PAN CTL_CODE(FILE_DEVICE_MONO, 0x807, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_LOCK CTL_CODE(FILE_DEVICE_MONO, 0x808, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_UNLOCK CTL_CODE(FILE_DEVICE_MONO, 0x809, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_WINDOW CTL_CODE(FILE_DEVICE_MONO, 0x80A, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_RESET_WINDOW CTL_CODE(FILE_DEVICE_MONO, 0x80B, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_SET_FLAG CTL_CODE(FILE_DEVICE_MONO, 0x80C, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_CLEAR_FLAG CTL_CODE(FILE_DEVICE_MONO, 0x80D, METHOD_BUFFERED, FILE_WRITE_DATA) -#define IOCTL_MONO_FILL_ATTRIB CTL_CODE(FILE_DEVICE_MONO, 0x80E, METHOD_BUFFERED, FILE_WRITE_DATA) - -#endif // ifdef _WIN32 - -class MonoD : public OutputDevice -{ - public: - MonoD(); - ~MonoD(); - - virtual int print(const char *str,int len); - - private: - #ifdef _WIN32 - HANDLE handle; - #endif -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/odevice.h b/Generals/Code/Tools/matchbot/wlib/odevice.h deleted file mode 100644 index f04bffaec1..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/odevice.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef ODEVICE_HEADER -#define ODEVICE_HEADER - -// This virtual base class provides an interface for output devices -// that can be used for the debugging package. -class OutputDevice -{ - public: - OutputDevice() {} - virtual ~OutputDevice() {}; - virtual int print(const char *s,int len)=0; -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/sem4.cpp b/Generals/Code/Tools/matchbot/wlib/sem4.cpp deleted file mode 100644 index 9c7f7e42a1..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/sem4.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/******************************************************************************\ -sem4.cpp Neal Kettler - -Simple Posix semaphore class -This is useful because the constructor will automatically call sem_init - and you don't have to worry about it. It also allows for other semaphore - libraries if you don't have posix. -\******************************************************************************/ - -#include "sem4.h" - -#ifdef _REENTRANT - -Sem4::Sem4() -{ -#ifndef _WINDOWS - sem_init(&sem,1,1); -#else - sem = CreateSemaphore(NULL, 1, 1, NULL); -#endif -} - -Sem4::Sem4(uint32 value) -{ -#ifndef _WINDOWS - sem_init(&sem,1,value); -#else - sem = CreateSemaphore(NULL, value, value, NULL); -#endif -} - -Sem4::~Sem4() -{ -#ifndef _WINDOWS - sem_destroy(&sem); -#else - if (sem) CloseHandle(sem); -#endif -} - -sint32 Sem4::Wait(void) const -{ -#ifndef _WINDOWS - return(sem_wait((sem_t *)&sem)); -#else - if (!sem) - return -1; // no semaphore! - - DWORD dwWaitResult = WaitForSingleObject(sem, INFINITE); - switch (dwWaitResult) { - case WAIT_OBJECT_0: // The semaphore object was signaled. - return 0; - break; - case WAIT_TIMEOUT: // Should not happen ;) - return -1; - break; - } - return -1; -#endif -} - -sint32 Sem4::Post(void) const -{ -#ifndef _WINDOWS - return(sem_post((sem_t *)&sem)); -#else - if (!sem) - return -1; - if (!ReleaseSemaphore(sem, 1 ,NULL)) - return -1; - return 0; -#endif -} - -sint32 Sem4::TryWait(void) const -{ -#ifndef _WINDOWS - return(sem_trywait((sem_t *)&sem)); -#else - if (!sem) - return -1; - DWORD dwWaitResult = WaitForSingleObject(sem, 0L); - switch (dwWaitResult) { - case WAIT_OBJECT_0: // The semaphore object was signaled. - return 0; - break; - case WAIT_TIMEOUT: - return -1; - break; - } - return -1; -#endif -} - -sint32 Sem4::GetValue(int *sval) const -{ -#ifndef _WINDOWS - return(sem_getvalue((sem_t *)&sem,sval)); -#else - if (!sem) - return -1; - long prev; - if (!ReleaseSemaphore(sem, 0, &prev)) - return -1; - if (sval) - *sval = prev; - return 0; -#endif -} - -sint32 Sem4::Destroy(void) -{ -#ifndef _WINDOWS - return(sem_destroy(&sem)); -#else - return CloseHandle(sem); -#endif -} - -#else - -/**************************************************************************** -non threaded versions that do nothing -*****************************************************************************/ - -Sem4::Sem4() -{ -} - -Sem4::Sem4(uint32) -{ -} - -Sem4::~Sem4() -{ -} - -sint32 Sem4::Wait(void) const -{ - return(0); -} - -sint32 Sem4::Post(void) const -{ - return(0); -} - -sint32 Sem4::TryWait(void) const -{ - return(0); -} - -sint32 Sem4::GetValue(int *) const -{ - return(0); -} - -sint32 Sem4::Destroy(void) -{ - return(0); -} - -#endif - diff --git a/Generals/Code/Tools/matchbot/wlib/sem4.h b/Generals/Code/Tools/matchbot/wlib/sem4.h deleted file mode 100644 index c96f2f7b78..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/sem4.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef SEM4_HEADER -#define SEM4_HEADER - -#include -#ifndef _WINDOWS -#include -#endif -#include "wstypes.h" - -#ifdef _REENTRANT -#ifndef _WINDOWS -#include -#else -#include -#endif // _WINDOWS -#endif // _REENTRANT - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -class Sem4 -{ - private: - #ifdef _REENTRANT -#ifndef _WINDOWS - sem_t sem; -#else - HANDLE sem; -#endif - #endif - public: - Sem4(); - Sem4(uint32 value); - ~Sem4(); - - sint32 Wait(void) const; - sint32 TryWait(void) const; - sint32 Post(void) const; - sint32 GetValue(int *sval) const; - sint32 Destroy(void); -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/stderrd.h b/Generals/Code/Tools/matchbot/wlib/stderrd.h deleted file mode 100644 index 4559bea747..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/stderrd.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STDERRD_HEADER -#define STDERRD_HEADER - -#include "odevice.h" - -class StderrD : public OutputDevice -{ - public: - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memset(string,0,len+1); - memcpy(string,str,len); - fprintf(stderr,"%s",string); - delete[](string); - return(len); - } -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/stdoutd.h b/Generals/Code/Tools/matchbot/wlib/stdoutd.h deleted file mode 100644 index a3d20fc3c5..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/stdoutd.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STDOUTD_HEADER -#define STDOUTD_HEADER - -#include "odevice.h" - -class StdoutD : public OutputDevice -{ - public: - - virtual int print(const char *str,int len) - { - char *string=new char[len+1]; - memcpy(string,str,len); - string[len]=0; - fprintf(stdout,"%s",string); - fflush(stdout); - delete[](string); - return(len); - } -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/streamer.cpp b/Generals/Code/Tools/matchbot/wlib/streamer.cpp deleted file mode 100644 index b8a8eca1c1..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/streamer.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "streamer.h" -#ifdef _WIN32 - #include -#endif - -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) -#define STREAMER_UNBUFFERED unbuffered() -#else -#define STREAMER_UNBUFFERED 0 -#endif - -Streamer::Streamer() : streambuf(), Output_Device(NULL), Buf(NULL) -{ -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) - int state=unbuffered(); - unbuffered(0); // 0 = buffered, 1 = unbuffered -#else - static_assert(STREAMER_UNBUFFERED==0, "std::streambuf is assumed to be buffered by default"); -#endif -} - -Streamer::~Streamer() -{ - ///////// calling sync seems to cause crashes here on Win32 - //sync(); - ///////// - if (Buf) - delete[] Buf; -} - -int Streamer::setOutputDevice(OutputDevice *device) -{ - Output_Device=device; - return(0); -} - - -// put n chars from string into buffer -int Streamer::xsputn(const char* buf, int size) //implementation of sputn -{ - if (size<=0) // Nothing to do - return(0); - - const unsigned char *ptr=(const unsigned char *)buf; - for (int i=0; i= epptr()) && (sync()==EOF)) - return(EOF); - else { - sputc(c); - if ((STREAMER_UNBUFFERED && c=='\n' || pptr() >= epptr()) - && sync()==EOF) { - return(EOF); - } - return(c); - } -} - -// This is a write only stream, this should never happen -int Streamer::underflow(void) -{ - return(EOF); -} - -int Streamer::doallocate() -{ - if (Buf==NULL) - { - Buf=new char[(2*STREAMER_BUFSIZ)]; // deleted by destructor - memset(Buf,0,2*STREAMER_BUFSIZ); - - // Buffer -#if defined(USING_STLPORT) || (defined(_MSC_VER) && _MSC_VER < 1300) - setb( - Buf, // base pointer - Buf+STREAMER_BUFSIZ, // ebuf pointer (end of buffer); - 0); // 0 = manual deletion of buff -#else - pubsetbuf(Buf, 2*STREAMER_BUFSIZ); -#endif - - // Get area - setg( - Buf, // eback - Buf, // gptr - Buf); // egptr - - Buf+=STREAMER_BUFSIZ; - // Put area - setp(Buf,Buf+STREAMER_BUFSIZ); - return(1); - } - else - return(0); -} - - -int Streamer::sync() -{ - if (pptr()<=pbase()) { - return(0); - } - - int wlen=pptr()-pbase(); - - if (Output_Device) - { - Output_Device->print(pbase(),wlen); - } - - if (STREAMER_UNBUFFERED) { - setp(pbase(),pbase()); - } - else { - setp(pbase(),pbase()+STREAMER_BUFSIZ); - } - return(0); -} diff --git a/Generals/Code/Tools/matchbot/wlib/streamer.h b/Generals/Code/Tools/matchbot/wlib/streamer.h deleted file mode 100644 index 8dce9298f9..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/streamer.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef STREAMER_HEADER -#define STREAMER_HEADER - -#include -#include -#include -#include -#include - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#include "odevice.h" - -#ifndef STREAMER_BUFSIZ -// This limits the number of characters that can be sent to a single 'print' -// call. If your debug message is bigger than this, it will get split over -// multiple 'print' calls. That's usually not a problem. - #define STREAMER_BUFSIZ 2048 -#endif - - -// Provide a streambuf interface for a class that can 'print' -class Streamer : public streambuf -{ - public: - Streamer(); - virtual ~Streamer(); - - int setOutputDevice(OutputDevice *output_device); - - protected: - // Virtual methods from streambuf - int xsputn(const char* s, int n); // buffer some characters - int overflow(int = EOF); // flush buffer and make more room - int underflow(void); // Does nothing - int sync(); - - int doallocate(); // allocate a buffer - - - OutputDevice *Output_Device; - char* Buf; -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/syslogd.cpp b/Generals/Code/Tools/matchbot/wlib/syslogd.cpp deleted file mode 100644 index 7568868b24..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/syslogd.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "syslogd.h" - -SyslogD::SyslogD(char *ident,int logopt,int facility,int _priority) -{ -#ifndef _WINDOWS - openlog(ident,logopt,facility); - priority=_priority; -#endif -} - -int SyslogD::print(const char *str, int len) -{ -#ifndef _WINDOWS - char *temp_str=new char[len+1]; - memset(temp_str,0,len+1); - strncpy(temp_str,str,len); - syslog(priority,temp_str); - delete[](temp_str); -#endif - return(len); -} diff --git a/Generals/Code/Tools/matchbot/wlib/syslogd.h b/Generals/Code/Tools/matchbot/wlib/syslogd.h deleted file mode 100644 index 569f2b1d5b..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/syslogd.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef SYSLOGD_HEADER -#define SYSLOGD_HEADER - -#include -#include -#ifndef _WINDOWS -#include -#endif -#include - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#include "odevice.h" - -// Windows doesn't have a syslog equivalent (does it?), so this class does little there -class SyslogD : public OutputDevice -{ - public: - SyslogD(char *ident,int logopt,int facility,int priority); - virtual int print(const char *str,int len); - - private: - int priority; -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/threadfac.cpp b/Generals/Code/Tools/matchbot/wlib/threadfac.cpp deleted file mode 100644 index 0f42558536..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/threadfac.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#define THREADFAC_CODE - -#include "threadfac.h" - -int Runnable::ThreadCount_ = 0; -CritSec Runnable::CritSec_; // to protect ThreadCount_ - -// MDC: Made all this dependent on _REENTRANT being defined so VC++ doesn't complain on -// single-threaded programs... - - -// -// Note: I chose the following type signature for thread functions -// void function(void *data); -// -// -// Since Win32 & POSIX have different type signatures for the thread entry points -// an intermediate system-dependent function in this file gets called first. -// That function then calls the system independent version. So the system dependent -// version needs 2 Items 1) The address of the _real_ thread func 2) the data -// to pass. We only have 1 argument available, so you figure out the rest... -// -// This is for internal use only -// -struct ThreadInformation -{ - void *startPoint; // The address of the _real_ thread function, or class - void *data; // data to pass to real thread function or class - bit8 destroy; // only applies to classes, should delete after execution? -}; - - - -// -// Start a thread inside a class -// -bit8 ThreadFactory::startThread(Runnable &runable, void *data, bit8 destroy) -{ -#ifdef _REENTRANT - - { - Runnable::CritSec_.lock(); - Runnable::ThreadCount_++; - Runnable::CritSec_.unlock(); - } - - - ThreadInformation *tInfo=new ThreadInformation; - tInfo->startPoint=(void *)&runable; - tInfo->data=data; - tInfo->destroy=destroy; - - #ifdef _WIN32 - // Under windows call _beginthreadex instead of CreateThread so you can - // use all the normal C library stuff. (IMPORTANT!!!) - uint32 handle; - uint32 stup1d; - handle=_beginthreadex(NULL,0, threadClassLauncher, tInfo, 0, &stup1d); - if (handle!=NULL) - return(TRUE); - else - { - { - runable.CritSec_.lock(); - runable.ThreadCount_--; // Ok, so it didn't really start - runable.CritSec_.unlock(); - } - return(FALSE); - } - #else // UNIX - // Setup thread attributes for client threads - int retval; - pthread_attr_t threadAttr; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED); - pthread_attr_setscope(&threadAttr,PTHREAD_SCOPE_SYSTEM); - retval=pthread_create(NULL,&threadAttr, threadClassLauncher, tInfo); - if (retval==0) - return(TRUE); - else - { - { - runable.CritSec_.lock(); - runable.ThreadCount_--; // Ok, so it didn't really start - runable.CritSec_.unlock(); - } - return(FALSE); - } - #endif -#else - return (FALSE); -#endif /* _REENTRANT */ -} - - -// -// Start a thread inside a function -// -bit8 ThreadFactory::startThread(void (*start_func)(void *), void *data) -{ -#ifdef _REENTRANT - ThreadInformation *tInfo=new ThreadInformation; - tInfo->startPoint=start_func; - tInfo->data=data; - - #ifdef _WIN32 - // Under windows call _beginthreadex instead of CreateThread so you can - // use all the normal C library stuff. (IMPORTANT!!!) - uint32 handle; - unsigned temp; - handle=_beginthreadex(NULL,0, threadFuncLauncher, tInfo, 0, &temp); - if (handle!=NULL) - return(TRUE); - return(FALSE); - #else // UNIX - // Setup thread attributes for client threads - int retval; - pthread_attr_t threadAttr; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED); - pthread_attr_setscope(&threadAttr,PTHREAD_SCOPE_SYSTEM); - retval=pthread_create(NULL,&threadAttr, threadFuncLauncher, tInfo); - if (retval==0) - return(TRUE); - else - return(FALSE); - #endif -#else - return(FALSE); -#endif /* REENTRANT */ -} - -#ifdef _WIN32 - unsigned __stdcall threadFuncLauncher(void *temp) -#else // UNIX - void *threadFuncLauncher(void *temp) -#endif -{ - ThreadInformation *tInfo=(ThreadInformation *)temp; - - void (*start_func)(void *); - start_func=(void (*)(void *))tInfo->startPoint; - - void *data=tInfo->data; - delete(tInfo); - - start_func(data); - return(0); -} - -#ifdef _WIN32 - unsigned __stdcall threadClassLauncher(void *temp) -#else // UNIX - void *threadClassLauncher(void *temp) -#endif -{ - ThreadInformation *tInfo=(ThreadInformation *)temp; - - Runnable *thrClass=(Runnable *)tInfo->startPoint; - void *data=tInfo->data; - bit8 destroy=tInfo->destroy; - delete(tInfo); - - thrClass->run(data); - - if (destroy) // May want to free memory after thread finishes - delete(thrClass); - - { - Runnable::CritSec_.lock(); - Runnable::ThreadCount_--; - Runnable::CritSec_.unlock(); - } - - #ifdef _WIN32 - ExitThread(0); // is this really needed? - #endif - return(0); -} - -Runnable::Runnable() -{ } - -Runnable::~Runnable() -{ } - -// Is there a thread running in this class -bit8 Runnable::isRunning(void) -{ - // Don't need to lock a simple assignment - int temp=ThreadCount_; - return((temp>0)?TRUE:FALSE); -} - -// How many threads are running in this class -int Runnable::getThreadCount(void) -{ - // Don't need to lock a simple assignment - int temp=ThreadCount_; - return(temp); -} - -#undef THREADFAC_CODE diff --git a/Generals/Code/Tools/matchbot/wlib/threadfac.h b/Generals/Code/Tools/matchbot/wlib/threadfac.h deleted file mode 100644 index a4edbc3680..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/threadfac.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Platform independent thread creation (Win32 & POSIX) -// - -#ifndef THREADFAC_HEADER -#define THREADFAC_HEADER - -#ifdef _WIN32 - #include -#endif -#include "wstypes.h" -#include - -#ifdef _WIN32 - #include -#else // UNIX - #include -#endif - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#include "critsec.h" - - - -#ifdef THREADFAC_CODE - // This is the fake thread entry point for functions - #ifdef _WIN32 - static unsigned __stdcall threadFuncLauncher(void *temp); - #else // UNIX - static void *threadFuncLauncher(void *temp); - #endif - - // Fake entry point for classes - #ifdef _WIN32 - static unsigned __stdcall threadClassLauncher(void *temp); - #else // UNIX - static void *threadClassLauncher(void *temp); - #endif -#endif - - - - - -// Forward definition of base class for threaded classes -class Runnable; - -// -// Call the static method startThread to begin a new thread. -// -class ThreadFactory -{ - public: - static bit8 startThread(void (*start_func)(void *), void *data); - static bit8 startThread(Runnable &runable, void *data, bit8 destroy=FALSE); -}; - - - -// -// Base class for when you want a thread to execute inside a class -// instead of a function. -// -class Runnable -{ - public: - Runnable(); - virtual ~Runnable(); - - - // ThreadFactory needs to be able to access the private - // IsRunning_ field. - friend class ThreadFactory; - - // So do the threadClassLaunchers - #ifdef _WIN32 - friend static unsigned __stdcall threadClassLauncher(void *temp); - #else // UNIX - friend void *threadClassLauncher(void *temp); - #endif - - virtual void run(void *data)=0; // Thread entry point - - void startThread(void *data,bit8 destroy=FALSE) // nice way to start a thread - { - ThreadFactory::startThread(*this,data,destroy); - }; - - // Is there a thread running in this class? - static bit8 isRunning(void); - - // Get the count of threads running inside this class - static int getThreadCount(); - - - private: - static int ThreadCount_; - static CritSec CritSec_; // to protect ThreadCount_ -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/threadsafe.h b/Generals/Code/Tools/matchbot/wlib/threadsafe.h deleted file mode 100644 index 8a2addac60..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/threadsafe.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// threadsafe.h -// -// If you include this file and call non-threadsafe functions, it'll -// prevent your program from compiling. It's meant to be a slap -// on the wrist in case you forget and call an unsafe function -// from a threadsafe program. -// - -// -// Reminder to self - use sigwait, not signal handlers! -// - -#ifdef _REENTRANT - -#ifndef THREADSAFE_HEADER -#define THREADSAFE_HEADER - -#define strtok ("strtok() is not MT-SAFE!") -#define ascctime ("asctime() is not MT-SAFE!") -// Can't just do ctime, as Windows' objidl.h uses it as a FILETIME thingie -#define ctime(x) ("ctime() is not MT-SAFE!") -#define gmtime ("gmtime() is not MT-SAFE!") -#define localtime ("localtime() is not MT-SAFE!") -#define tzset ("tzset() is not MT-SAFE!") -#define tzsetwall ("tzsetwall() is not MT-SAFE!") -#define readdir ("readdir() is not MT-SAFE!") - -#define rand ("rand() is not MT-SAFE!") -#define srand ("srand() is not MT-SAFE!") -#define random ("random() is not MT-SAFE!") -#define srandom ("srandom() is not MT-SAFE!") - -#define tmpnam ("tmpnam() is not MT-SAFE!") -#define vfork ("vfork() is not MT-SAFE!") - -#define system ("system() is not MT-SAFE!") -#define popen ("popen() is not MT-SAFE!") -#define pclose ("pclose() is not MT-SAFE!") -#define ctermid ("ctermid() is not MT-SAFE!") -#define getlogin ("getlogin() is not MT-SAFE!"); - -#endif // THREADSAFE_HEADER -#endif // _REENTRANT diff --git a/Generals/Code/Tools/matchbot/wlib/timezone.cpp b/Generals/Code/Tools/matchbot/wlib/timezone.cpp deleted file mode 100644 index 6e191ebb17..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/timezone.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "wlib/xtime.h" -#include "timezone.h" - -void GetTimezoneInfo(const char * &timezone_str, int &timezone_offset) { - timezone_str = "Unknown Timezone"; - timezone_offset = 0; -#ifdef _WINDOWS - struct _timeb wintime; - _ftime(&wintime); - - if (wintime.dstflag) { - // Daylight savings time - if (_daylight) { - timezone_str = _tzname[1]; - } - } else { - timezone_str = _tzname[0]; - } - timezone_offset = wintime.timezone * 60; // its in minutes... - -#endif -#ifndef _WINDOWS - struct timeval unixtime; - struct timezone unixtzone; - gettimeofday(&unixtime,&unixtzone); - - struct tm unixtm; - localtime_r(&unixtime.tv_sec, &unixtm); - - if (unixtm.tm_isdst) { - // Daylight savings time - if (daylight) timezone_str = tzname[1]; - timezone_offset = altzone; - } else { - timezone_str = tzname[0]; - timezone_offset = timezone; - } -#endif -} - -const char * TimezoneString(void) { - const char *timezone_str; - int timezone_offset; - GetTimezoneInfo(timezone_str, timezone_offset); - return timezone_str; -} - -int TimezoneOffset(void) { - const char *timezone_str; - int timezone_offset; - GetTimezoneInfo(timezone_str, timezone_offset); - return timezone_offset; -} diff --git a/Generals/Code/Tools/matchbot/wlib/timezone.h b/Generals/Code/Tools/matchbot/wlib/timezone.h deleted file mode 100644 index 95e4c37f38..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/timezone.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -timezone Matthew D. Campbell - -This is just a couple of convenience functions for determining what timezone -we are now in. It even accounts for daylight savings! One caveat is that it -only tells you info about what the daylight savings info is now, not 5 minutes -from now, not 2 hours ago. Oh well. -\****************************************************************************/ - -#ifndef _TIMEZONE_H_ -#define _TIMEZONE_H_ - -// Just fill in both the timezone description and its offset from GMT -void GetTimezoneInfo(const char * &timezone_str, int &timezone_offset); - -// Returns the description of the current timezone (daylight savings included) -const char * TimezoneString(void); - -// Returns the offset from GMT of the current timezone -int TimezoneOffset(void); - -#endif // _TIMEZONE_H_ - diff --git a/Generals/Code/Tools/matchbot/wlib/ustring.h b/Generals/Code/Tools/matchbot/wlib/ustring.h deleted file mode 100644 index 12fee83b68..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/ustring.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef USTRING_HEADER -#define USTRING_HEADER - -#include -#include -#include -#include - -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const - -#define MAX_BYTES_PER_CHAR 1 - -template -class UstringT : public basic_string > -{ - public: - explicit UstringT(int max_charlength) { - set_max_bytelength(max_charlength*MAX_BYTES_PER_CHAR); - } - - UstringT() { max_bytelength=4000; } - - size_t get_max_bytelength(void) { return(max_bytelength); } - void set_max_bytelength(size_t max) { max_bytelength=max; } - - bool operator==(const UstringT &other) - { - const basic_string > *other_basic=&other; - const basic_string > *this_basic=this; - return((*other_basic)==(*this_basic)); - } - - private: - size_t max_bytelength; -}; - -typedef UstringT Ustring; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/wdebug.cpp b/Generals/Code/Tools/matchbot/wlib/wdebug.cpp deleted file mode 100644 index 8e2d14f7e4..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wdebug.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include -#include "wdebug.h" -#include "streamer.h" -#include "odevice.h" - - -static MsgManager *msg_manager=NULL; - -static int debug_enabled=0; -static ostream *debug_ostream=NULL; -static Streamer debug_streamer; - -static int info_enabled=0; -static ostream *info_ostream=NULL; -static Streamer info_streamer; - -static int warn_enabled=0; -static ostream *warn_ostream=NULL; -static Streamer warn_streamer; - -static int error_enabled=0; -static ostream *error_ostream=NULL; -static Streamer error_streamer; - - -// Don't dare touch this semaphore in application code! -#ifdef USE_DEBUG_SEM -Sem4 DebugLibSemaphore; -#else -CritSec DebugLibSemaphore; -#endif - - -int MsgManager::setAllStreams(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - debug_streamer.setOutputDevice(device); - delete(debug_ostream); - debug_ostream=new ostream(&debug_streamer); - - info_streamer.setOutputDevice(device); - delete(info_ostream); - info_ostream=new ostream(&info_streamer); - - warn_streamer.setOutputDevice(device); - delete(warn_ostream); - warn_ostream=new ostream(&warn_streamer); - - error_streamer.setOutputDevice(device); - delete(error_ostream); - error_ostream=new ostream(&error_streamer); - - DEBUGUNLOCK; - - return(0); -} - - -int MsgManager::ReplaceAllStreams(FileD * output_device, IN char *device_filename, IN char *copy_filename) -{ - DebugLibSemaphore.Wait(); - - delete(debug_ostream); - delete(info_ostream); - delete(warn_ostream); - delete(error_ostream); - - if (output_device != NULL) - { - delete(output_device); - output_device = NULL; - } - - rename(device_filename, copy_filename); - -// FileD new_device(device_filename); - output_device = new FileD(device_filename); - - debug_streamer.setOutputDevice(output_device); - debug_ostream = new ostream(&debug_streamer); - - info_streamer.setOutputDevice(output_device); - info_ostream=new ostream(&info_streamer); - - warn_streamer.setOutputDevice(output_device); - warn_ostream = new ostream(&warn_streamer); - - error_streamer.setOutputDevice(output_device); - error_ostream = new ostream(&error_streamer); - - DebugLibSemaphore.Post(); - - return(0); -} - - -int MsgManager::setDebugStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - debug_streamer.setOutputDevice(device); - delete(debug_ostream); - debug_ostream=new ostream(&debug_streamer); - DEBUGUNLOCK; - return(0); -} - -int MsgManager::setInfoStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - info_streamer.setOutputDevice(device); - delete(info_ostream); - info_ostream=new ostream(&info_streamer); - DEBUGUNLOCK; - return(0); -} - -int MsgManager::setWarnStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - warn_streamer.setOutputDevice(device); - delete(warn_ostream); - warn_ostream=new ostream(&warn_streamer); - DEBUGUNLOCK; - return(0); -} - -int MsgManager::setErrorStream(OutputDevice *device) -{ - if (device==NULL) - return(1); - - DEBUGLOCK; - error_streamer.setOutputDevice(device); - delete(error_ostream); - error_ostream=new ostream(&error_streamer); - DEBUGUNLOCK; - return(0); -} - - - -ostream *MsgManager::debugStream(void) -{ - return(debug_ostream); -} - -ostream *MsgManager::infoStream(void) -{ - return(info_ostream); -} - -ostream *MsgManager::warnStream(void) -{ - return(warn_ostream); -} - -ostream *MsgManager::errorStream(void) -{ - return(error_ostream); -} diff --git a/Generals/Code/Tools/matchbot/wlib/wdebug.h b/Generals/Code/Tools/matchbot/wlib/wdebug.h deleted file mode 100644 index a37c9ee75f..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wdebug.h +++ /dev/null @@ -1,314 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*****************************************************************************\ -wdebug Neal Kettler - -MT-LEVEL - MT-Safe - -The debugging module is pretty good for debugging and it has some message -printing stuff as well. The basic idea is that you write a class that -inherits from OutputDevice (several are provided) and assign that output -device to a stream. There are seperate streams for debugging, information, -warning, and error messages. Each one can have a seperate output device, -or they can all have the same one. Debugging messages only get compiled -in if your module defines 'DEBUG'. If you don't define debug, then not even -the text of the debugging message gets into the binary. All the other -output streams get printed regardless of whether DEBUG is defined. - -Sample usage: -FileD debug_device("gameres.debug"); // create a file device -MsgManager::setDebugStream(&debug_device); -DBGMSG("This debug message #" << 1 << " you use C++ streams"); - -Note that since these are defines you really don't need to put a semicolon -at the end, and it can be bad in situations like this: - -if (x) - DBGMSG("Stuff is broken"); -else - DBGMSG("Stuff is NOT broken"); - -This won't compile, read the code until you figure it out. Only then -will you be ready to leave grasshopper. - -\*****************************************************************************/ - -#ifndef WDEBUG_HEADER -#define WDEBUG_HEADER - -#define USE_DEBUG_SEM - -#include "wstypes.h" - -#include -#include - -#if !defined(_WINDOWS) -// Windows headers have a tendency to redefine IN -#ifdef IN -#undef IN -#endif -#define IN const -#endif - -#ifdef USE_DEBUG_SEM -#include "sem4.h" -#else -#include "critsec.h" -#endif -#include "odevice.h" -#include "streamer.h" -#include "xtime.h" -#include "timezone.h" // MDC -#include "filed.h" - -// This is needed because the streams return a pointer. Every time you -// change the output device the old stream is deleted, and a new one -// is created. -// MDC: Added a macro to switch between semaphores & critsecs to debug a -// problem in Win32. - -#ifdef USE_DEBUG_SEM -extern Sem4 DebugLibSemaphore; -#define DEBUGLOCK DebugLibSemaphore.Wait() -#define DEBUGUNLOCK DebugLibSemaphore.Post() -#else -extern CritSec DebugLibSemaphore; -#define DEBUGLOCK DebugLibSemaphore.lock() -#define DEBUGUNLOCK DebugLibSemaphore.unlock() -#endif - -// Print an information message -#define INFMSG(X)\ -{\ - char timebuf[40]; \ - Xtime now; \ - now -= TimezoneOffset(); \ - now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ - DEBUGLOCK; \ - if (MsgManager::infoStream()) \ - (*(MsgManager::infoStream())) << "INF " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ - DEBUGUNLOCK; \ -} - -// Print a warning message -#define WRNMSG(X)\ -{\ - char timebuf[40]; \ - Xtime now; \ - now -= TimezoneOffset(); \ - now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ - DEBUGLOCK; \ - if (MsgManager::warnStream()) \ - (*(MsgManager::warnStream())) << "WRN " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ - DEBUGUNLOCK; \ -} - -// Print an error message -#define ERRMSG(X)\ -{\ - char timebuf[40]; \ - Xtime now; \ - now -= TimezoneOffset(); \ - now.FormatTime(timebuf, "mm/dd/yy hh:mm:ss"); \ - DEBUGLOCK; \ - if (MsgManager::errorStream()) \ - (*(MsgManager::errorStream())) << "ERR " << timebuf << " [" << \ - __FILE__ << " " << __LINE__ << "] " << X << endl; \ - DEBUGUNLOCK; \ -} - - -// Just get a stream to the information device, no extra junk -#define INFSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::infoStream()) \ - (*(MsgManager::infoStream())) << X;\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the warning device, no extra junk -#define WRNSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::warnStream()) \ - (*(MsgManager::warnStream())) << X;\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the error device, no extra junk -#define ERRSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::errorStream()) \ - (*(MsgManager::errorStream())) << X;\ - DEBUGUNLOCK; \ -} - -#ifndef DEBUG - -// No debugging, no debug messages. -// Note that anything enclosed in "DBG()" will NOT get executed -// unless DEBUG is defined. -// They are defined to {} for consistency when DEBUG is defined - -#define DBG(X) -#define DBGSTREAM(X) {} -#define PVAR(v) {} -#define DBGMSG(X) {} -#define VERBOSE(X) {} - -#else // DEBUG _is_ defined - -// Execute only if in debugging mode -#define DBG(X) X - -// In Windows, send a copy to the debugger window -#ifdef _WINDOWS - -// Print a variable -#define PVAR(v) \ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << endl; \ - strstream __s;\ - __s << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << '\n' << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - - -#define DBGMSG(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << endl;\ - strstream __s;\ - __s << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << '\n' << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the debugging device, no extra junk -#define DBGSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << X;\ - strstream __s;\ - __s << X << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - -// Verbosely execute a statement -#define VERBOSE(X)\ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(DebugManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << endl; X \ - strstream __s;\ - __s << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << '\n' << '\0';\ - OutputDebugString(STRSTREAM_CSTR(__s));\ - DEBUGUNLOCK; \ -} - -#else // _WINDOWS - -// Print a variable -#define PVAR(v) \ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##V << " = " << V << endl; \ - DEBUGUNLOCK; \ -} - - -#define DBGMSG(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << "DBG [" << __FILE__ << \ - " " << __LINE__ << "] " << X << endl;\ - DEBUGUNLOCK; \ -} - -// Just get a stream to the debugging device, no extra junk -#define DBGSTREAM(X)\ -{\ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(MsgManager::debugStream())) << X;\ - DEBUGUNLOCK; \ -} - -// Verbosely execute a statement -#define VERBOSE(X)\ -{ \ - DEBUGLOCK; \ - if (MsgManager::debugStream()) \ - (*(DebugManager::debugStream())) << __FILE__ << "[" << __LINE__ << \ - "]: " << ##X << endl; X \ - DEBUGUNLOCK; \ -} -#endif // _WINDOWS - -#endif // DEBUG - -//#undef DEBUGLOCK -//#undef DEBUGUNLOCK - -class MsgManager -{ - protected: - MsgManager(); - - public: - static int setAllStreams(OutputDevice *device); - static int ReplaceAllStreams(FileD *output_device, IN char *device_filename, IN char *copy_filename); - static int setDebugStream(OutputDevice *device); - static int setInfoStream(OutputDevice *device); - static int setWarnStream(OutputDevice *device); - static int setErrorStream(OutputDevice *device); - - static void enableDebug(int flag); - static void enableInfo(int flag); - static void enableWarn(int flag); - static void enableError(int flag); - - static ostream *debugStream(void); - static ostream *infoStream(void); - static ostream *warnStream(void); - static ostream *errorStream(void); -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/wstring.cpp b/Generals/Code/Tools/matchbot/wlib/wstring.cpp deleted file mode 100644 index e7fa32cff3..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wstring.cpp +++ /dev/null @@ -1,597 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : string.cpp -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 - -A fairly typical string class. This string class always copies any input -string to it's own memory (for assignment or construction). -\***************************************************************************/ - -#include -#include -#include -#include -#include - -#include "wstring.h" - -#define PADSIZE 32 // include a little padding on alloc for future growth - -Wstring::Wstring() : str(NULL), strsize(0) -{ } - -Wstring::Wstring(const char *string):str(NULL), strsize(0) -{ set(string); } - -Wstring::Wstring(const Wstring &other):str(NULL), strsize(0) -{ - if (other.str!=NULL) - { - str=new char[strlen(other.str)+PADSIZE+1]; - strsize=strlen(other.str)+PADSIZE+1; - strcpy(str,other.str); - } -} - -Wstring::~Wstring() -{ - clear(); -} - -bool Wstring::operator<(const Wstring &other) const -{ - if (str == NULL && other.str == NULL) - return false; - - if (str == NULL) - return true; - - return ( strcmp(str, other.str) < 0 ); -} - -bit8 Wstring::operator==(const char *other) const -{ - if ((str==NULL)&&(other==NULL)) - return(TRUE); - if(strcmp(str, other) != 0) - return(FALSE); - else - return(TRUE); -} - -bit8 Wstring::operator==(const Wstring &other) const -{ - if((str == NULL) && (other.str == NULL)) - return(TRUE); - - if((str == NULL) || (other.str == NULL)) - return(FALSE); - - if(strcmp(str, other.str) != 0) - return(FALSE); - else - return(TRUE); -} - - -bit8 Wstring::operator!=(const char *other) const -{ - if(strcmp(str, other) != 0) - return(TRUE); - else - return(FALSE); -} - - -bit8 Wstring::operator!=(const Wstring &other) const -{ - if((str == NULL) && (other.str == NULL)) - return(FALSE); - - if((str == NULL) || (other.str == NULL)) - return(TRUE); - - if(strcmp(str, other.str) != 0) - return(TRUE); - else - return(FALSE); -} - - -Wstring &Wstring::operator=(const char *other) -{ - set(other); - return(*this); -} - - -Wstring &Wstring::operator=(const Wstring &other) -{ - if(*this == other) - return(*this); - - set(other.get()); - return(*this); -} - - -bit8 Wstring::cat(const char *s) -{ - uint32 len; - - if (s==NULL) // it's OK to cat nothing - return(TRUE); - - // Determine the length of the resultant string. - len = strlen(s) + 1; - if(str) - len += strlen(str); - - // Space check - strgrow(len); - - strcat(str, s); - - return(TRUE); -} - - -bit8 Wstring::cat(uint32 size, const char *s) -{ - uint32 len; - - // Determine the length of the resultant string. - len = size + 1; - if(str) - len += strlen(str); - - // Allocate memory for the new string. - strgrow(len); - - strncat(str, s, size); - str[len-1]=0; // make sure null term'd - - return(TRUE); -} - -bit8 Wstring::cat(const Wstring &other) -{ - return cat(other.get()); -} - -Wstring &Wstring::operator+=(const char *string) -{ - cat(string); - return(*this); -} - -Wstring &Wstring::operator+=(const Wstring &other) -{ - cat(other.get()); - return(*this); -} - -Wstring Wstring::operator+(const char *string) -{ - Wstring temp = *this; - temp.cat(string); - return(temp); -} - -Wstring Wstring::operator+(const Wstring &s) -{ - Wstring temp = *this; - temp.cat(s); - return(temp); -} - -// -// This function deletes 'count' characters indexed by `pos' from the Wstring. -// If `pos'+'count' is > the length of the array, the last 'count' characters -// of the string are removed. If an error occurs, FALSE is returned. -// Otherwise, TRUE is returned. Note: count has a default value of 1. -// -// -char Wstring::remove(sint32 pos,sint32 count) -{ - //char *s; - sint32 len; - - len = (sint32)strlen(str); - - if(pos+count > len) - pos = len - count; - if (pos < 0) - { - count+=pos; // If they remove before 0, ignore up till beginning - pos=0; - } - if (count<=0) - return(FALSE); - - memmove(str+pos,str+pos+count,len-pos-count+1); - - return(TRUE); -} - -// Remove all instances of a char from the string -bit8 Wstring::removeChar(char c) -{ - int len=0; - char *cptr=NULL; - bit8 removed=FALSE; - - if (str==NULL) - return(FALSE); - - len=strlen(str); - while ((cptr=strchr(str,c)) !=NULL) - { - memmove(cptr,cptr+1,len-1-((int)(cptr-str))); - len--; - str[len]=0; - removed=TRUE; - } - return(removed); -} - -void Wstring::removeSpaces(void) -{ - removeChar(' '); - removeChar('\t'); -} - -void Wstring::clear(void) -{ - if(str) - delete[](str); - strsize=0; - str=NULL; -} - -// This is usually used for raw storage instead of string ops... -void Wstring::setSize(sint32 size) -{ - clear(); - if (size<0) - return; - - str=new char[size]; - strsize=size; - memset(str,0,size); -} - -void Wstring::cellCopy(char *dest, uint32 len) -{ - uint32 i; - - strncpy(dest, str, len); - for(i = (uint32)strlen(str); i < len; i++) - dest[i] = ' '; - dest[len] = 0; -} - -const char *Wstring::get(void) const -{ - if(!str) - return ""; - return str; -} - -char Wstring::get(uint32 index) const -{ - if(index < strlen(str)) - return str[index]; - return(0); -} - -uint32 Wstring::length(void) const -{ - if(str == NULL) - return(0); - return((uint32)strlen(str)); -} - - -// Insert at given position and shift old stuff to right -bit8 Wstring::insert(const char *instring, uint32 pos) -{ - if (str==NULL) - return(set(instring)); - if (pos>strlen(str)) - pos=strlen(str); - - strgrow(strlen(str)+strlen(instring)+1); - memmove(str+pos+strlen(instring),str+pos,strlen(str)-pos+1); - memmove(str+pos,instring,strlen(instring)); - - return(TRUE); -} - -// This function inserts the character specified by `k' into the string at the -// position indexed by `pos'. If `pos' is >= the length of the string, it is -// appended to the string. If an error occurs, FALSE is returned. Otherwise, -// TRUE is returned. -bit8 Wstring::insert(char k, uint32 pos) -{ - char temp[2]; - temp[0]=k; - temp[1]=0; - return(insert(temp,pos)); -} - - -// Joe Howes (05/19/2000): This function inserts commas to nicely format a -// large number (i.e. 1234567890 -> 1,234,567,890). It doesn't really care -// if the string is really a number or not. -bit8 Wstring::beautifyNumber() -{ - int len = length(); - int accum = 3 - (len % 3); - int numcommas = 0; - - - if( accum == 3 ) accum = -1; - for(int i = 0; i < len; i++) - { - if( accum == 3 ) - { - insert(',', i + numcommas); - numcommas++; - } - accum = ( accum == 3 || accum == -1 ) ? 1 : accum + 1; - } - - return(TRUE); -} - - -// This function replaces any occurences of the string pointed to by -// `replaceThis' with the string pointed to by `withThis'. If an error -// occurs, FALSE is returned. Otherwise, TRUE is returned. -bit8 Wstring::replace(const char *replaceThis,const char *withThis) -{ - Wstring dest; - const char *foundStr, *src; - uint32 len; - - src=get(); - while(src && src[0]) - { - foundStr = strstr(src, replaceThis); - if(foundStr) - { - len = (uint32)foundStr - (uint32)src; - if(len) - { - if(!dest.cat(len, src)) - return(FALSE); - } - if(!dest.cat(withThis)) - return(FALSE); - src = foundStr + strlen(replaceThis); - } - else - { - if(!dest.cat(src)) - return(FALSE); - - src=NULL; - } - } - return(set(dest.get())); -} - - -bit8 Wstring::set(const char *s) -{ - //uint32 len; - - strgrow(strlen(s)+1); - strcpy(str,s); - - return(TRUE); -} - - -bit8 Wstring::set(char c, uint32 index) -{ - if(index >= (uint32)strlen(str)) - return FALSE; - - str[index] = c; - - return TRUE; -} - - -char Wstring::set(uint32 size, const char *string) -{ - //uint32 len; - - strgrow(size+1); - strncpy(str,string,size); - str[size]=0; - - return(TRUE); -} - - -// Added by Joe Howes. Takes a printf formatted string and a set of args. -// The expanded string must not exceed 1k or twice the length of the format -// string, whichever is larger. It would probably be better to traverse -// the format string and properly calculate, the length so this will -// work in all cases, but this should be good enough for 99% of Wstring usage. -char Wstring::setFormatted(const char *msg, ...) -{ - if( msg == NULL || strlen(msg) <= 0 ) return FALSE; - - char* string; - va_list args; - int len = (strlen(msg) < 1024) ? 1024 : (strlen(msg)*2); - - string = new char[len]; - va_start(args, msg); - vsprintf(string, msg, args); - va_end(args); - set(string); - delete[] string; - return(TRUE); -} - - -// This function converts all alphabetical characters in the string to lower -// case. -void Wstring::toLower(void) -{ - uint32 i; - int strlength=length(); - - for(i = 0; i < (uint32)strlength; i++) - { - if((str[i] >= 'A') && (str[i] <= 'Z')) - str[i] = (sint8)tolower(str[i]); - } -} - - -// This function converts all alphabetical characters in the string to upper -// case. -void Wstring::toUpper(void) -{ - uint32 i; - int strlength=length(); - - for(i = 0; i < (uint32)strlength; i++) - { - if((str[i] >= 'a') && (str[i] <= 'z')) - str[i] = (sint8)toupper(str[i]); - } -} - - -// This function truncates the string so its length will match the specified -// `len'. If an error occurs, FALSE is returned. Otherwise, TRUE is returned. -bit8 Wstring::truncate(uint32 len) -{ - strgrow(len+1); - str[len]=0; - return(TRUE); -} - -// Truncate the string after the character 'c' (gets rid of 'c' as well) -// Do nothing if 'c' isn't in the string -bit8 Wstring::truncate(char c) -{ - sint32 len; - - if (str==NULL) - return(FALSE); - - char *cptr=strchr(str,c); - if (cptr==NULL) - return(FALSE); - len=(sint32)(cptr-str); - truncate((uint32)len); - return(TRUE); -} - -// Get a token from this string that's seperated by one or more -// chars from the 'delim' string , start at offset & return offset -sint32 Wstring::getToken(int offset,const char *delim,Wstring &out) const -{ - int i; - sint32 start; - sint32 stop; - - if (offset<0) // check for bad input - return(-1); - - for (i=offset; i<(int)length(); i++) { - if(strchr(delim,str[i])==NULL) - break; - } - if (i>=(int)length()) - return(-1); - start=i; - - for (; i<(int)length(); i++) { - if(strchr(delim,str[i])!=NULL) - break; - } - stop=i-1; - out.set(str+start); - out.truncate((uint32)stop-start+1); - return(stop+1); -} - -// Get the first line of text after offset. Lines are terminated by '\r\n' or '\n' -sint32 Wstring::getLine(int offset, Wstring &out) -{ - int i; - sint32 start; - sint32 stop; - - start=i=offset; - if (start >= (sint32)length()) - return(-1); - - for (; i<(int)length(); i++) { - if(strchr("\r\n",str[i])!=NULL) - break; - } - stop=i; - if ((str[stop]=='\r')&&(str[stop+1]=='\n')) - stop++; - - out.set(str+start); - out.truncate((uint32)stop-start+1); - return(stop+1); -} - -// -// Make sure there's AT LEAST length bytes in this string object -// -void Wstring::strgrow(int length) -{ - if (str==NULL) - { - str=new char[length+PADSIZE]; - str[0]=0; - strsize=length+PADSIZE; - return; - } - else if (strsize >= length) // no need to alloc more data - return; - else // bah, gotta grow... - { - char *newstr=new char[length+PADSIZE]; - strsize=length+PADSIZE; - strcpy(newstr,str); - delete[](str); - str=newstr; - return; - } -} diff --git a/Generals/Code/Tools/matchbot/wlib/wstring.h b/Generals/Code/Tools/matchbot/wlib/wstring.h deleted file mode 100644 index 484815c1ba..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wstring.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : main.cpp -Author : Neal Kettler -Start Date : June 1, 1997 -Last Update : June 17, 1997 -\****************************************************************************/ - -#ifndef WSTRING_HEADER -#define WSTRING_HEADER - -#include -#include -#include "wstypes.h" - -class Wstring -{ - public: - Wstring(); - Wstring(const Wstring &other); - Wstring(const char *string); - ~Wstring(); - - void clear(void); - - bit8 cat(const char *string); - bit8 cat(uint32 size,const char *string); - bit8 cat(const Wstring &string); - - void cellCopy(OUT char *dest, uint32 len); - char remove(sint32 pos, sint32 count); - bit8 removeChar(char c); - void removeSpaces(void); - const char *get(void) const; - char get(uint32 index) const; - uint32 length(void) const; - bit8 insert(char c, uint32 pos); - bit8 insert(const char *instring, uint32 pos); - bit8 beautifyNumber(); - bit8 replace(const char *replaceThis,const char *withThis); - char set(const char *str); - char set(uint32 size,const char *str); - bit8 set(char c, uint32 index); - char setFormatted(const char *str, ...); // Added by Joe Howes - void setSize(sint32 bytes); // create an empty string - void toLower(void); - void toUpper(void); - bit8 truncate(uint32 len); - bit8 truncate(char c); // trunc after char c - sint32 getToken(int offset,const char *delim,Wstring &out) const; - sint32 getLine(int offset, Wstring &out); - void strgrow(int length); - - bit8 operator==(const char *other) const; - bit8 operator==(const Wstring &other) const; - bit8 operator!=(const char *other) const; - bit8 operator!=(const Wstring &other) const; - - Wstring &operator=(const char *other); - Wstring &operator=(const Wstring &other); - Wstring &operator+=(const char *other); - Wstring &operator+=(const Wstring &other); - Wstring operator+(const char *other); - Wstring operator+(const Wstring &other); - - bool operator<(const Wstring &other) const; - - private: - char *str; // Pointer to allocated string. - int strsize; // allocated data length -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/wstypes.h b/Generals/Code/Tools/matchbot/wlib/wstypes.h deleted file mode 100644 index dbc5824563..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wstypes.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -* C O N F I D E N T I A L --- W E S T W O O D S T U D I O S * -****************************************************************************** -Project Name: Carpenter (The RedAlert ladder creator) -File Name : wstypes.h -Author : Neal Kettler -Start Date : June 3, 1997 -Last Update : June 17, 1997 - -Standard type definitions for the sake of portability and readability. -\***************************************************************************/ - -#ifndef WSTYPES_HEADER -#define WSTYPES_HEADER - -#ifdef _REENTRANT // reentrant = threaded -// Headers with non threadsafe libs need to come before my hacky -// threadsafe.h otherwise they won't compile - -#include -#ifndef _WINDOWS -#define _POSIX_C_SOURCE 199506L -#define _POSIX_PTHREAD_SEMANTICS -#define __EXTENSIONS__ -#endif -#include -#include -#include -#ifndef _WINDOWS -#include -#include -#include -#else -#include -#include -#endif -#include "threadsafe.h" // enforce threadsafe-only calls -#endif - -#define adelete(X) (delete[](X)) - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - -#ifndef MIN -#define MIN(x,y) (((x)<(y))?(x):(y)) -#endif - -#ifndef MAX -#define MAX(x,y) (((x)>(y))?(x):(y)) -#endif - -#ifndef NULL -#define NULL 0 -#endif - -//These are used for readability purposes mostly, when a method takes a -// pointer or reference these help specify what will happen to the data -// that is sent in. -#ifdef IN -#undef IN -#endif -#define IN const -#define OUT -#define INOUT -#define _IN_ const - -// Used to declare a function or method as const or Read Only -#define RO const - -typedef char bit8; -typedef char sint8; -typedef unsigned char uint8; -typedef signed short int sint16; -typedef unsigned short int uint16; -typedef signed int sint32; -typedef unsigned int uint32; - -typedef float float32; -typedef double float64; - -#define MAX_BIT8 0x1 -#define MAX_UINT32 0xFFFFFFFF -#define MAX_UINT16 0xFFFF -#define MAX_UINT8 0xFF -#define MAX_SINT32 0x7FFFFFFF -#define MAX_SINT16 0x7FFF -#define MAX_SINT8 0x7F - -#ifdef _WINDOWS -#define strncasecmp _strnicmp -#define strcasecmp _stricmp -#endif - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/wtime.cpp b/Generals/Code/Tools/matchbot/wlib/wtime.cpp deleted file mode 100644 index 9843a25d94..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wtime.cpp +++ /dev/null @@ -1,802 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -wtime Neal Kettler -\****************************************************************************/ - -#include -#include "wtime.h" - -static const char *DAYS[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; - -static const char *FULLDAYS[]={"Sunday","Monday","Tuesday","Wednesday","Thursday", - "Friday","Saturday"}; - -static const char *MONTHS[]={"Jan","Feb","Mar","Apr","May","Jun","Jul", - "Aug","Sep","Oct","Nov","Dec"}; - -static const char *FULLMONTHS[]={"January","February","March","April","May","June", - "July","August","September","October","November","December"}; - -// MDC: Windows doesn't provide a localtime_r, so make our own... -#ifdef _WINDOWS -#ifdef _REENTRANT -#include "critsec.h" -static CritSec localtime_critsec; -#undef localtime -_CRTIMP struct tm *localtime(const time_t *clockval); -#endif // _REENTRANT - -static struct tm *localtime_r(const time_t *clockval, struct tm *res) { -#ifdef _REENTRANT - localtime_critsec.lock(); -#endif - struct tm *static_tm = localtime(clockval); - res = (struct tm *)memcpy(res, static_tm, sizeof(tm)); -#ifdef _REENTRANT - localtime_critsec.unlock(); -#endif - return res; -} -#endif // _WINDOWS - -Wtime::Wtime(void) -{ - Update(); -} - -Wtime::Wtime( Wtime &other ) -{ - sign=other.sign; - sec=other.sec; - usec=other.usec; -} - -Wtime::Wtime( uint32 other ) -{ - sign=POSITIVE; - sec=other; - usec=0; -} - -Wtime::~Wtime() -{ -} - -void Wtime::Update(void) -{ - sign=POSITIVE; - #ifdef _WINDOWS - struct _timeb wintime; - _ftime(&wintime); - sec=wintime.time; - usec=(wintime.millitm)*1000; - #endif - #ifndef _WINDOWS - struct timeval unixtime; - struct timezone unixtzone; - gettimeofday(&unixtime,&unixtzone); - sec=unixtime.tv_sec; - usec=unixtime.tv_usec; - #endif -} - - -// Parses a date string that's in modified RFC 1123 format -// Can have a +minutes after the normal time -// eg: Thu, 20 Jun 1996 17:33:49 +100 -// Returns true if successfully parsed, false otherwise -bit8 Wtime::ParseDate(char *in) -{ - int i; - uint32 minOffset; - struct tm t; - char *ptr=in; - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of string - if (*ptr==0) return(FALSE); - t.tm_wday=-1; - for (i=0; i<7; i++) // parse day of week - if (strncmp(ptr,DAYS[i],strlen(DAYS[i]))==0) - t.tm_wday=i; - if (t.tm_wday==-1) - return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to day of month - if (*ptr==0) return(FALSE); - t.tm_mday=atoi(ptr); - while ((!isalpha(*ptr))&&(*ptr!=0)) ptr++; // skip to month - if (*ptr==0) return(FALSE); - t.tm_mon=-1; - for (i=0; i<12; i++) // match month - if (strncmp(ptr,MONTHS[i],strlen(MONTHS[i]))==0) t.tm_mon=i; - if (t.tm_mon==-1) return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(FALSE); - t.tm_year=atoi(ptr); - if (t.tm_year<70) // if they specify a 2 digit year, we'll be nice - t.tm_year+=2000; - else if (t.tm_year<100) - t.tm_year+=1900; - if (t.tm_year>2200) // I doubt my code will be around for another 203 years - return(FALSE); - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to end of year - if (*ptr==0) return(FALSE); - - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of time - if (*ptr==0) return(FALSE); - - t.tm_hour=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_min=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_sec=atoi(ptr); - t.tm_year%=100; // 1996 is stored as 96, not 1996 - t.tm_isdst=-1; // daylight savings info isn't available - - sec=(uint32)(mktime(&t)); - if ((sint32)sec==-1) - return(FALSE); - - - // The next part of the time is OPTIONAL (+minutes) - - // first skip past the seconds - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(TRUE); - - // skip past any spaces - while ((isspace(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr!='+') - { - //printf("\nNOPE ptr was '%s'\n",ptr); - return(TRUE); - } - ptr++; - if (*ptr==0) - { - //printf("\nPTR WAS 0\n"); - return(TRUE); - } - - minOffset=atol(ptr); - //printf("\n\nAdding %d minutes!\n\n",minOffset); - sec+=minOffset*60; // add the minutes as seconds - return(TRUE); -} - - -// This takes the standard Microsoft time formatting string -// make sure the out string is big enough -// An example format would be "mm/dd/yy hh:mm:ss" -// CHANGE: Joe Howes 06/30/99 -// To specify 12-hour format, use "aa" instead of "hh". -// The hours will be 12 hour and the string will be -// appended with " AM" or " PM". -bit8 Wtime::FormatTime(char *out, const char *format) -{ - int lastWasH=0; - int ampmflag = 0; - out[0]=0; - const char *ptr=format; - - if (*ptr=='"') ptr++; // skip past open quote if exists - - while (*ptr!=0) - { - if (lastWasH>0) - lastWasH--; - - if (isspace(*ptr)) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),"%c",*ptr); - ptr+=1; - } - else if (strncmp(ptr,"\"",1)==0) - { - break; - } - else if (strncmp(ptr,":",1)==0) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),":"); - ptr+=1; - } - else if (strncmp(ptr,"/",1)==0) - { - sprintf(out+strlen(out),"/"); - ptr+=1; - } - else if (strncmp(ptr,"c",1)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld %ld:%02ld:%02ld",GetMonth(), - GetMDay(),GetYear()%100,GetHour(),GetMinute(),GetSecond()); - ptr+=1; - } - else if (strncmp(ptr,"dddddd",6)==0) - { - sprintf(out+strlen(out),"%s %02ld, %ld",FULLMONTHS[GetMonth()-1], - GetMDay(),GetYear()); - ptr+=6; - } - else if (strncmp(ptr,"ddddd",5)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld",GetMonth(),GetMDay(), - GetYear()%100); - ptr+=5; - } - else if (strncmp(ptr,"dddd",4)==0) - { - sprintf(out+strlen(out),"%s",FULLDAYS[GetWDay()-1]); - ptr+=4; - } - else if (strncmp(ptr,"ddd",3)==0) - { - sprintf(out+strlen(out),"%s",DAYS[GetWDay()-1]); - ptr+=3; - } - else if (strncmp(ptr,"dd",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetMDay()); - ptr+=2; - } - else if (strncmp(ptr,"d",1)==0) - { - sprintf(out+strlen(out),"%ld",GetMDay()); - ptr+=1; - } - else if (strncmp(ptr,"ww",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetYWeek()); - ptr+=2; - } - else if (strncmp(ptr,"w",1)==0) - { - sprintf(out+strlen(out),"%ld",GetWDay()); - ptr+=1; - } - else if (strncmp(ptr,"mmmm",4)==0) - { - sprintf(out+strlen(out),"%s",FULLMONTHS[GetMonth()-1]); - ptr+=4; - } - else if (strncmp(ptr,"mmm",3)==0) - { - sprintf(out+strlen(out),"%s",MONTHS[GetMonth()-1]); - ptr+=3; - } - else if (strncmp(ptr,"mm",2)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%02ld",GetMinute()); - else - sprintf(out+strlen(out),"%02ld",GetMonth()); - ptr+=2; - } - else if (strncmp(ptr,"m",1)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%ld",GetMinute()); - else - sprintf(out+strlen(out),"%ld",GetMonth()); - ptr+=1; - } - else if (strncmp(ptr,"q",1)==0) - { - sprintf(out+strlen(out),"%ld",((GetMonth()-1)/4)+1); // GetQuarter - ptr+=1; - } - else if (strncmp(ptr,"yyyy",4)==0) - { - sprintf(out+strlen(out),"%ld",GetYear()); - ptr+=4; - } - else if (strncmp(ptr,"yy",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetYear()%100); - ptr+=2; - } - else if (strncmp(ptr,"y",1)==0) - { - sprintf(out+strlen(out),"%ld",GetYDay()); - ptr+=1; - } - else if (strncmp(ptr,"hh",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - } - else if (strncmp(ptr,"h",1)==0) - { - sprintf(out+strlen(out),"%ld",GetHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=1; - } - else if (strncmp(ptr,"nn",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetMinute()); - ptr+=2; - } - else if (strncmp(ptr,"n",1)==0) - { - sprintf(out+strlen(out),"%ld",GetMinute()); - ptr+=1; - } - else if (strncmp(ptr,"ss",2)==0) - { - sprintf(out+strlen(out),"%02ld",GetSecond()); - ptr+=2; - } - else if (strncmp(ptr,"s",1)==0) - { - sprintf(out+strlen(out),"%ld",GetSecond()); - ptr+=1; - } - else if (strncmp(ptr,"ttttt",5)==0) - { - sprintf(out+strlen(out),"%ld:%02ld:%02ld",GetHour(),GetMinute(), - GetSecond()); - ptr+=5; - } - else if (strncmp(ptr,"aa",2)==0) - { - uint32 tmp = (GetHour() <= 12) ? GetHour() : GetHour() - 12; - sprintf(out+strlen(out),"%02ld", tmp); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - ampmflag = 1; - } - else // an unknown char, move to next - ptr++; - } - if(ampmflag) - { - char ampm[4]; - if( GetHour() < 12 ) - strcpy(ampm, " AM"); - else - strcpy(ampm, " PM"); - sprintf(out+strlen(out), "%s", ampm); - } - return(TRUE); -} - - - -// In addition to PrintTime & PrintDate there is the 'Print' function -// which prints both in RFC 1123 format - -void Wtime::PrintTime(FILE *out) const -{ - char string[80]; - PrintTime(string); - fprintf(out,"%s",string); -} - -void Wtime::PrintTime(char *out) const -{ - sprintf(out," %02lu:%02lu:%02lu",GetHour(),GetMinute(),GetSecond()); -} - -void Wtime::PrintDate(FILE *out) const -{ - char string[80]; - PrintDate(string); - fprintf(out,"%s",string); -} - -void Wtime::PrintDate(char *out) const -{ - sprintf(out,"%s, %lu %s %lu",DAYS[GetWDay()-1],GetMDay(),MONTHS[GetMonth()-1], - GetYear()); -} - -uint32 Wtime::GetSec(void) const -{ - return(sec); -} - -uint32 Wtime::GetUsec(void) const -{ - return(usec); -} - -void Wtime::SetSec(uint32 newsec) -{ - sec=newsec; -} - -void Wtime::SetUsec(uint32 newusec) -{ - usec=newusec; -} - -void Wtime::Set(uint32 newsec, uint32 newusec) -{ - sec=newsec; - usec=newusec; -} - -// Get a timeval ptr from a Wtime class -struct timeval *Wtime::GetTimeval(void) -{ - static struct timeval tv; - tv.tv_sec=sec; - tv.tv_usec=usec; - return(&tv); -} - -// Get a timeval ptr from a Wtime class -void Wtime::GetTimevalMT(struct timeval &tv) -{ - tv.tv_sec=sec; - tv.tv_usec=usec; -} - - -uint32 Wtime::GetSecond(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_sec); -} -uint32 Wtime::GetMinute(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_min); -} -uint32 Wtime::GetHour(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_hour); -} -uint32 Wtime::GetMDay(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_mday); -} -uint32 Wtime::GetWDay(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_wday+1); -} -uint32 Wtime::GetYDay(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_yday+1); -} -uint32 Wtime::GetYWeek(void) const -{ - uint32 yweek; - uint32 yday=GetYDay(); - uint32 wday=GetWDay(); - //phase holds the first weekday of the year. If (Jan 1 = Sun) phase = 0 - sint32 phase=((wday-yday)%7); - if (phase<0) phase+=7; - yweek=((yday+phase-1)/7)+1; - return(yweek); -} -uint32 Wtime::GetMonth(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - return(tptr->tm_mon+1); -} - -uint32 Wtime::GetYear(void) const -{ - struct tm t; - struct tm *tptr; - tptr=localtime_r((time_t *)&sec,&t); - if ((tptr->tm_year)>=70) - return((tptr->tm_year)+1900); - else - return((tptr->tm_year)+2000); -} - - -bit8 Wtime::GetSign(void) const -{ - return(sign); -} - -// 1 = *this > other -//-1 = *this < other -// 0 = *this == other -int Wtime::Compare(const Wtime &other) const -{ - if ((sec==other.sec)&&(usec==other.usec)) - return(0); // equal - - else if (sec>other.sec) - return(1); - else if (secother.usec) - return(1); - else - return(-1); -} - - -bit8 Wtime::operator == ( const Wtime &other ) const -{ - bit8 retval=Compare(other); - if (retval==0) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator != ( const Wtime &other ) const -{ - bit8 retval=Compare(other); - if (retval==0) - return(FALSE); - else - return(TRUE); -} - -bit8 Wtime::operator < ( const Wtime &other ) const -{ - int retval=Compare(other); - if (retval==-1) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator > ( const Wtime &other ) const -{ - int retval=Compare(other); - if (retval==1) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator <= ( const Wtime &other ) const -{ - int retval=Compare(other); - if ((retval==-1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - -bit8 Wtime::operator >= ( const Wtime &other ) const -{ - int retval=Compare(other); - if ((retval==1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - - -// None of the operators pay attention to sign -// only the functions that begin with 'Signed' -void Wtime::SignedAdd(const Wtime &other) -{ - Wtime temp; - - if ((sign==POSITIVE)&&(other.sign==POSITIVE)) - { - *this+=other; - sign=POSITIVE; - } - else if ((sign==POSITIVE)&&(other.sign==NEGATIVE)) - { - if (*this>other) - { - *this-=other; - sign=POSITIVE; - } - else - { - temp=other; - temp-=*this; - *this=temp; - sign=NEGATIVE; - } - } - else if ((sign==NEGATIVE)&&(other.sign==POSITIVE)) - { - if (*thisother) - { - *this-=other; - sign=POSITIVE; - } - else - { - temp=other; - temp-=*this; - *this=temp; - sign=NEGATIVE; - } - } - else if ((sign==NEGATIVE)&&(other.sign==NEGATIVE)) - { - if (*this1000000) - { - sec++; - usec-=1000000; - } - return *this; -} - -Wtime &Wtime::operator -= (const Wtime &other) -{ - sint32 temp; - if (Compare(other)==-1) - { - sec=0; // can't handle negative time - usec=0; - return *this; - } - sec-=other.sec; - temp=(sint32)usec; - temp-=(sint32)other.usec; - if (temp<0) - { - sec--; - temp+=1000000; - } - usec=temp; - return *this; -} - -Wtime Wtime::operator - (Wtime &other) -{ - Wtime temp(*this); - temp-=other; - return(temp); -} - -Wtime Wtime::operator + (Wtime &other) -{ - Wtime temp(*this); - temp+=other; - return(temp); -} - - -Wtime &Wtime::operator = (const Wtime &other) -{ - sign=other.sign; - sec=other.sec; - usec=other.usec; - return *this; -} - - -Wtime &Wtime::operator += (const uint32 other) -{ - sec+=other; - return *this; -} - - -Wtime &Wtime::operator -= (const uint32 other) -{ - sec-=other; - return *this; -} - - -Wtime Wtime::operator - (uint32 other) -{ - Wtime temp(*this); - temp-=other; - return(temp); -} - - -Wtime Wtime::operator + (uint32 other) -{ - Wtime temp(*this); - temp+=other; - return(temp); -} - - -Wtime &Wtime::operator = (const uint32 other) -{ - sign=POSITIVE; - sec=other; - usec=0; - return *this; -} diff --git a/Generals/Code/Tools/matchbot/wlib/wtime.h b/Generals/Code/Tools/matchbot/wlib/wtime.h deleted file mode 100644 index 3f0d1cf723..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/wtime.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -wtime Neal Kettler - -\****************************************************************************/ -#ifndef WTIME_HEADER -#define WTIME_HEADER - - -#include -#include -#include -#include - -#ifndef _WINDOWS -#include -#include -#include -#else -#include -#include -#endif - -#include -#include - -#include "wstypes.h" - -class Wtime -{ - public: - - enum - { - POSITIVE=0, - NEGATIVE=1 - }; - - Wtime(); // init to system time - Wtime( Wtime &other ); - Wtime( uint32 other ); - ~Wtime(); - - void Update(); // Update members sec & usec to system time - - - void PrintTime(FILE *out) const; - void PrintTime(char *out) const; - void PrintDate(FILE *out) const; - void PrintDate(char *out) const; - - uint32 GetSec(void) const; // Get member variable 'sec' - uint32 GetUsec(void) const; // Get member variable 'usec' - void SetSec(uint32 newsec); - void SetUsec(uint32 newusec); - void Set(uint32 newsec,uint32 newusec); - bit8 ParseDate(char *in); - bit8 FormatTime(char *out, const char *format); - - struct timeval *GetTimeval(void); - void GetTimevalMT(struct timeval &tv); - - uint32 GetSecond(void) const; // Second (0- 60) (60 is for a leap second) - uint32 GetMinute(void) const; // Minute (0 - 59) - uint32 GetHour(void) const; // Hour (0-23) - uint32 GetMDay(void) const; // Day of Month (1-31) - uint32 GetWDay(void) const; // Day of Week (1-7) - uint32 GetYDay(void) const; // Day of Year (1-366) - uint32 GetMonth(void) const; // Month (1-12) - uint32 GetYWeek(void) const; // Week of Year (1-53) - uint32 GetYear(void) const; // Year (e.g. 1997) - - bit8 GetSign(void) const; // 0 = pos 1 = neg - - int Compare(const Wtime &other) const; - - // comparisons - bit8 operator == ( const Wtime &other ) const; - bit8 operator != ( const Wtime &other ) const; - bit8 operator < ( const Wtime &other ) const; - bit8 operator > ( const Wtime &other ) const; - bit8 operator <= ( const Wtime &other ) const; - bit8 operator >= ( const Wtime &other ) const; - - // assignments - Wtime &operator = (const Wtime &other); - Wtime &operator = (const uint32 other); - - // math - // signed - void SignedAdd(const Wtime &other); - void SignedSubtract(const Wtime &other); - - // unsigned - Wtime &operator += (const Wtime &other); - Wtime &operator -= (const Wtime &other); - Wtime operator + (Wtime &other); - Wtime operator - (Wtime &other); - - Wtime &operator += (const uint32 other); - Wtime &operator -= (const uint32 other); - Wtime operator + (uint32 other); - Wtime operator - (uint32 other); - - protected: - uint32 sec; // seconds since Jan 1, 1970 - uint32 usec; // microseconds (millionths of a second) - bit8 sign; // for time differences 0 = pos 1 = neg -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wlib/xtime.cpp b/Generals/Code/Tools/matchbot/wlib/xtime.cpp deleted file mode 100644 index 28181d6f36..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/xtime.cpp +++ /dev/null @@ -1,1015 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ - -xtime Neal Kettler - -Improved version of the Wtime library (V->W->X...) - -Handles signed times better and dates long -long long after you'll be dead. - -\****************************************************************************/ - -#include -#include -#ifndef _WINDOWS -#include -#endif -#include "xtime.h" - -static const char *DAYS[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; - -static const char *FULLDAYS[]={"Sunday","Monday","Tuesday","Wednesday","Thursday", - "Friday","Saturday"}; - -static const char *MONTHS[]={"Jan","Feb","Mar","Apr","May","Jun","Jul", - "Aug","Sep","Oct","Nov","Dec"}; - -static const char *FULLMONTHS[]={"January","February","March","April","May","June", - "July","August","September","October","November","December"}; - - -#define IS_LEAP(y) ((y) % 4) == 0 && (! ((y) % 100) == 0 || ((y) % 400) == 0) -#define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400) - - -/////////////// Utility functions /////////////////// - -// -// Return the daycount since year 0 for the specified date. -// month = 1-12, day = 1-31 year = 0... -// -static sint32 Get_Day(int month, int day, int year) -{ - time_t days; - - static int DaysAtMonth[] = - {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; - - /* Add up number of straight days + number of leap days + days */ - /* up to the month + the day of month. */ - - days = (year * 365) + (year / 4) - (year / 100) + (year / 400) + - DaysAtMonth[month-1] + day; - - /* If we haven't hit Feb 29, and this is a leap year, we need to */ - /* subtract out the leap day that was added above for this year */ - - if (month < 3 && IS_LEAP(year)) - --days; - return(days); -} - - - -// -// Get the year from a daycount since year 0 -// Also get the daycount since the start of the year -// -// Ayecarumba what a pain in the ass! -// -static bit8 Get_Date_From_Day(sint32 days, OUT sint32 &year, OUT sint32 &yday) -{ - //register long int rem; - register long int y; - //register const unsigned short int *ip; - - if (days <= 365) - { - year=0; - yday=days+1; // 1 based - return(TRUE); - } - - y = 1; - days-=365; - - days--; // zero based - - // - // As far as I can tell there's no non-iteritive way to - // do this... - // - while (days < 0 || days >= (IS_LEAP (y) ? 366 : 365)) - { - /* Guess a corrected year, assuming 365 days per year. */ - long int yg = y + days / 365 - (days % 365 < 0); - - /* Adjust DAYS and Y to match the guessed year. */ - days -= ((yg - y) * 365 - + LEAPS_THRU_END_OF (yg - 1) - - LEAPS_THRU_END_OF (y - 1)); - y = yg; - } - year=y; - yday=days+1; // 1 based - return(TRUE); -} - - -// -// Get the max day of a given month in a given year -// -int Max_Day(int month, int year) -{ - static char dayTable[2][13] = { - {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, - {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} - }; - bit8 isleap=IS_LEAP(year); - return(dayTable[isleap][month]); -} - - - -/********************************************************** -int main(int argc, char *argv[]) -{ - Xtime wtime; - int month,mday,year,hour,minute,second,day; - int i; - int dayoffset; - int yr; - int yday; - int ydaycount; - - wtime.set(719528,0); - -*********************************************** - for (year=0; year<10000; year++) - { - ydaycount=1; - for (month=1; month<=12; month++) - { - for (day=1; day<=Max_Day(month,year); day++) - { - dayoffset=Get_Day(month,day,year); - assert (GetDateFromDay(dayoffset,yr,yday)==TRUE); - - //printf("Yday=%d YdayCount=%d\n",yday,ydaycount); - - if (yr!=year) - { - printf("MO=%d DAY=%d YEAR=%d YR=%d\n",month,day,year,yr); - assert(0); - } - if (yday != ydaycount) - { - printf("MO=%d DAY=%d YEAR=%d YR=%d\n",month,day,year,yr); - printf("Yday=%d YdayCount=%d\n",yday,ydaycount); - assert(0); - } - ydaycount++; - } - } - printf("(%d) ",year); - } -*************************************** - - ///////wtime.addSeconds((60*60*24)-(60*60*8)); - ////////wtime.addSeconds(-(60*60*8)); // timezone delta - - dayoffset=Get_Day(1,1,1970); - printf("DAYOFFSET = %d\n",dayoffset); - - - wtime.getTime(month, mday, year, hour, minute, second); - printf("\n%s %d %d %d:%02d:%02d\n\n", - MONTHS[month-1],mday,year,hour,minute,second); - - struct timeval unixtime; - struct timezone unixtzone; - time_t ttime; - tm tmtime; - - memset(&tmtime,0,sizeof(tmtime)); - ttime=0; - unixtime.tv_sec=0; - unixtime.tv_usec=0; - - //gettimeofday(&unixtime,&unixtzone); - //ttime=time(NULL); - tmtime=*gmtime(&ttime); - - printf("TIME->CTIME = %s\n",ctime(&ttime)); - printf("GTOD->CTIE = %s\n",ctime(&(unixtime.tv_sec))); - printf("TIME->GMT->ASCTIME = %s\n",asctime(&tmtime)); -} -***************************************************************/ - - - -// -// Construct with current clock time -// -Xtime::Xtime(void) -{ - update(); -} - -// -// Copy constructor -// -Xtime::Xtime( Xtime &other ) -{ - day_=other.day_; - msec_=other.msec_; -} - -// -// Set to a time_t (1970-2038) -// -Xtime::Xtime( time_t other ) -{ - day_=719528; // days from year 0 to Jan1, 1970 - // Add seconds from time_t - addSeconds(other); - msec_=0; -} - -Xtime::~Xtime() -{ -} - -// -// Add some number of seconds to the time (seconds can be negative) -// -void Xtime::addSeconds(sint32 seconds) -{ - // Add to day counter first - day_+=(seconds/86400); - msec_+=(seconds % 86400)*1000; - - // Now normalize in case msec is > 1 days worth - normalize(); -} - -// -// If msec is > 1 days worth, adjust the day count -// & decrement the msec counter until OK. -// -void Xtime::normalize(void) -{ - day_+=(msec_/86400000); - msec_%=86400000; - - while (msec_ < 0) - { - day_--; - msec_+=86400000; - } -} - -// -// Update time to hold the current clock time -// (breaks in 2038 :-) -// -void Xtime::update(void) -{ - day_=719528; // day_s from year 0 to Jan1, 1970 - msec_=0; - - #ifdef _WINDOWS - struct _timeb wintime; - _ftime(&wintime); - addSeconds(wintime.time); - msec_+=wintime.millitm; - #endif - #ifndef _WINDOWS - struct timeval unixtime; - struct timezone unixtzone; - gettimeofday(&unixtime,&unixtzone); - addSeconds(unixtime.tv_sec); - msec_+=(unixtime.tv_usec/1000); - #endif - - // Now normalize in case msec is > 1 days worth - normalize(); -} - - -// This takes the standard Microsoft time formatting string -// make sure the out string is big enough -// An example format would be "mm/dd/yy hh:mm:ss" -// CHANGE: Joe Howes 06/30/99 -// To specify 12-hour format, use "aa" instead of "hh". -// The hours will be 12 hour and the string will be -// appended with " AM" or " PM". -bit8 Xtime::FormatTime(char *out, const char *format) -{ - int lastWasH=0; - int ampmflag = 0; - out[0]=0; - const char *ptr=format; - - if (*ptr=='"') ptr++; // skip past open quote if exists - - while (*ptr!=0) - { - if (lastWasH>0) - lastWasH--; - - if (isspace(*ptr)) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),"%c",*ptr); - ptr+=1; - } - else if (strncmp(ptr,"\"",1)==0) - { - break; - } - else if (strncmp(ptr,":",1)==0) - { - if (lastWasH==1) lastWasH=2; - sprintf(out+strlen(out),":"); - ptr+=1; - } - else if (strncmp(ptr,"/",1)==0) - { - sprintf(out+strlen(out),"/"); - ptr+=1; - } - else if (strncmp(ptr,"c",1)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld %ld:%02ld:%02ld",getMonth(), - getMDay(),getYear()%100,getHour(),getMinute(),getSecond()); - ptr+=1; - } - else if (strncmp(ptr,"dddddd",6)==0) - { - sprintf(out+strlen(out),"%s %02ld, %ld",FULLMONTHS[getMonth()-1], - getMDay(),getYear()); - ptr+=6; - } - else if (strncmp(ptr,"ddddd",5)==0) - { - sprintf(out+strlen(out),"%ld/%ld/%02ld",getMonth(),getMDay(), - getYear()%100); - ptr+=5; - } - /*else if (strncmp(ptr,"dddd",4)==0) - { - sprintf(out+strlen(out),"%s",FULLDAYS[getWDay()-1]); - ptr+=4; - } - else if (strncmp(ptr,"ddd",3)==0) - { - sprintf(out+strlen(out),"%s",DAYS[getWDay()-1]); - ptr+=3; - }*/ - else if (strncmp(ptr,"dd",2)==0) - { - sprintf(out+strlen(out),"%02ld",getMDay()); - ptr+=2; - } - else if (strncmp(ptr,"d",1)==0) - { - sprintf(out+strlen(out),"%ld",getMDay()); - ptr+=1; - } - /*else if (strncmp(ptr,"ww",2)==0) - { - sprintf(out+strlen(out),"%02ld",getYWeek()); - ptr+=2; - }*/ - /*else if (strncmp(ptr,"w",1)==0) - { - sprintf(out+strlen(out),"%ld",getWDay()); - ptr+=1; - }*/ - else if (strncmp(ptr,"mmmm",4)==0) - { - sprintf(out+strlen(out),"%s",FULLMONTHS[getMonth()-1]); - ptr+=4; - } - else if (strncmp(ptr,"mmm",3)==0) - { - sprintf(out+strlen(out),"%s",MONTHS[getMonth()-1]); - ptr+=3; - } - else if (strncmp(ptr,"mm",2)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%02ld",getMinute()); - else - sprintf(out+strlen(out),"%02ld",getMonth()); - ptr+=2; - } - else if (strncmp(ptr,"m",1)==0) - { - if (lastWasH==1) - sprintf(out+strlen(out),"%ld",getMinute()); - else - sprintf(out+strlen(out),"%ld",getMonth()); - ptr+=1; - } - else if (strncmp(ptr,"q",1)==0) - { - sprintf(out+strlen(out),"%ld",((getMonth()-1)/4)+1); // GetQuarter - ptr+=1; - } - else if (strncmp(ptr,"yyyy",4)==0) - { - sprintf(out+strlen(out),"%ld",getYear()); - ptr+=4; - } - else if (strncmp(ptr,"yy",2)==0) - { - sprintf(out+strlen(out),"%02ld",getYear()%100); - ptr+=2; - } - /*else if (strncmp(ptr,"y",1)==0) - { - sprintf(out+strlen(out),"%ld",getYDay()); - ptr+=1; - }*/ - else if (strncmp(ptr,"hh",2)==0) - { - sprintf(out+strlen(out),"%02ld",getHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - } - else if (strncmp(ptr,"h",1)==0) - { - sprintf(out+strlen(out),"%ld",getHour()); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=1; - } - else if (strncmp(ptr,"nn",2)==0) - { - sprintf(out+strlen(out),"%02ld",getMinute()); - ptr+=2; - } - else if (strncmp(ptr,"n",1)==0) - { - sprintf(out+strlen(out),"%ld",getMinute()); - ptr+=1; - } - else if (strncmp(ptr,"ss",2)==0) - { - sprintf(out+strlen(out),"%02ld",getSecond()); - ptr+=2; - } - else if (strncmp(ptr,"s",1)==0) - { - sprintf(out+strlen(out),"%ld",getSecond()); - ptr+=1; - } - else if (strncmp(ptr,"ttttt",5)==0) - { - sprintf(out+strlen(out),"%ld:%02ld:%02ld",getHour(),getMinute(), - getSecond()); - ptr+=5; - } - else if (strncmp(ptr,"aa",2)==0) - { - uint32 tmp = (getHour() <= 12) ? getHour() : getHour() - 12; - sprintf(out+strlen(out),"%02ld", tmp); - lastWasH=2; // needs to be 1 after top of loop decs it - ptr+=2; - ampmflag = 1; - } - else // an unknown char, move to next - ptr++; - } - if(ampmflag) - { - char ampm[4]; - if( getHour() < 12 ) - strcpy(ampm, " AM"); - else - strcpy(ampm, " PM"); - sprintf(out+strlen(out), "%s", ampm); - } - return(TRUE); -} - -/************************************** - - REPLACE THIS CRAP - -// Parses a date string that's in modified RFC 1123 format -// Can have a +minutes after the normal time -// eg: Thu, 20 Jun 1996 17:33:49 +100 -// Returns true if successfully parsed, false otherwise -bit8 Xtime::ParseDate(char *in) -{ - int i; - uint32 minOffset; - struct tm t; - char *ptr=in; - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of string - if (*ptr==0) return(FALSE); - t.tm_wday_=-1; - for (i=0; i<7; i++) // parse day_ of week - if (strncmp(ptr,DAYS[i],strlen(DAYS[i]))==0) - t.tm_wday_=i; - if (t.tm_wday_==-1) - return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to day_ of month - if (*ptr==0) return(FALSE); - t.tm_mday_=atoi(ptr); - while ((!isalpha(*ptr))&&(*ptr!=0)) ptr++; // skip to month - if (*ptr==0) return(FALSE); - t.tm_mon=-1; - for (i=0; i<12; i++) // match month - if (strncmp(ptr,MONTHS[i],strlen(MONTHS[i]))==0) t.tm_mon=i; - if (t.tm_mon==-1) return(FALSE); - while ((!isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(FALSE); - t.tm_year=atoi(ptr); - if (t.tm_year<70) // if they specify a 2 digit year, we'll be nice - t.tm_year+=2000; - else if (t.tm_year<100) - t.tm_year+=1900; - if (t.tm_year>2200) // I doubt my code will be around for another 203 years - return(FALSE); - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; // skip to end of year - if (*ptr==0) return(FALSE); - - while ((!isgraph(*ptr))&&(*ptr!=0)) ptr++; // skip to start of time - if (*ptr==0) return(FALSE); - - t.tm_hour=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_min=atoi(ptr); - while ((*ptr!=':')&&(*ptr!=0)) ptr++; - ptr++; // skip past colon - if (*ptr==0) return(FALSE); - t.tm_sec=atoi(ptr); - t.tm_year%=100; // 1996 is stored as 96, not 1996 - t.tm_isdst=-1; // day_light savings info isn't available - - sec=(uint32)(mktime(&t)); - if ((sint32)sec==-1) - return(FALSE); - - - // The next part of the time is OPTIONAL (+minutes) - - // first skip past the seconds - while ((isdigit(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr==0) return(TRUE); - - // skip past any spaces - while ((isspace(*ptr))&&(*ptr!=0)) ptr++; - if (*ptr!='+') - { - //printf("\nNOPE ptr was '%s'\n",ptr); - return(TRUE); - } - ptr++; - if (*ptr==0) - { - //printf("\nPTR WAS 0\n"); - return(TRUE); - } - - minOffset=atol(ptr); - //printf("\n\nAdding %d minutes!\n\n",minOffset); - sec+=minOffset*60; // add the minutes as seconds - return(TRUE); -} - - - -// In addition to PrintTime & PrintDate there is the 'Print' function -// which prints both in RFC 1123 format - -void Xtime::PrintTime(FILE *out) const -{ - char string[80]; - PrintTime(string); - fprintf(out,"%s",string); -} - -void Xtime::PrintTime(char *out) const -{ - sprintf(out," %02lu:%02lu:%02lu",GetHour(),GetMinute(),GetSecond()); -} - -void Xtime::PrintDate(FILE *out) const -{ - char string[80]; - PrintDate(string); - fprintf(out,"%s",string); -} - -void Xtime::PrintDate(char *out) const -{ - sprintf(out,"%s, %lu %s %lu",DAYS[GetWDay()-1],GetMDay(),MONTHS[GetMonth()-1], - GetYear()); -} -********************************************/ - -// Get day_s since year 0 -sint32 Xtime::getDay(void) const -{ - return(day_); -} - -// Get msecs since start of day -sint32 Xtime::getMsec(void) const -{ - return(msec_); -} - -// Set days since year 0 -void Xtime::setDay(sint32 newday) -{ - day_=newday; -} - -// Set msec since start of this day -void Xtime::setMsec(sint32 newmsec) -{ - msec_=newmsec; -} - -// Set both -void Xtime::set(sint32 newday, sint32 newmsec) -{ - day_=newday; - msec_=newmsec; -} - - -// -// Get a timeval ptr from a Xtime class -// May fail if timeval can't hold a year this big or small -// -bit8 Xtime::getTimeval(struct timeval &tv) -{ - // A timeval can only hold dates from 1970-2038 - if ((day_ < 719528) || (day_ >= 719528+24855)) - return(FALSE); - - // Compute seconds since Jan 1, 1970 - uint32 seconds=day_-719528; - seconds*=(60*60*24); - seconds+=(msec_/1000); - - tv.tv_sec=seconds; - tv.tv_usec=(msec_%1000)*1000; - return(TRUE); -} - -// -// Set the time -// -bit8 Xtime::setTime(int month, int mday, int year, int hour, int minute, int second) -{ - day_=Get_Day(month,mday,year); - msec_=(hour*1000*60*60)+(minute*1000*60)+(second*1000); - return(TRUE); -} - - - -int Xtime::getYDay(void) const // Day of Year (1-366) (366 = leap yr) -{ - int year; - sint32 dayofyear; - if (Get_Date_From_Day(day_,year,dayofyear)==FALSE) - return(-1); - return dayofyear; -} - - -// -// Get all the components of the time in the usual normalized format. -// -// Most of the uglyness is in Get_Date_From_Day() -// -bit8 Xtime::getTime(int &month, int &mday, int &year, int &hour, int &minute, int &second) const -{ - int i; - sint32 dayofyear; - if (Get_Date_From_Day(day_,year,dayofyear)==FALSE) - return(FALSE); - - static int DaysAtMonth[2][12] = { - {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}, // normal - {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335} // leap year - }; - - month=0; - - bit8 isleap=IS_LEAP(year); - for (i=0; i<12; i++) - { - if (DaysAtMonth[isleap][i] >= dayofyear) - break; - month=i; - } - month++; // 1 based - - mday=dayofyear-DaysAtMonth[isleap][month-1]; - - // Whew! Now all we have to do is figure out H/M/S from the msec! - hour=(msec_/3600000)%24; // 1000*60*60 - minute=(msec_/60000)%60; // 1000*60 - second=(msec_/ 1000)%60; // 1000 - - return(TRUE); -} - -// -// These are for getting components of the time in the -// standard ranges. Like Day 1-31, Second 0-59, etc... -// -int Xtime::getSecond(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(second); -} -int Xtime::getMinute(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(minute); -} -int Xtime::getHour(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(hour); -} -int Xtime::getMDay(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(mday); -} - -int Xtime::getMonth(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(month); -} - -// based at year 0 (real 0, not 1970) -int Xtime::getYear(void) const -{ - int month,mday,year,hour,minute,second; - getTime(month, mday, year, hour, minute, second); - return(year); -} - - -// -// Set the seconds value (0-59) -// -bit8 Xtime::setSecond(sint32 sec) -{ - sint32 second=(msec_/ 1000)%60; - msec_-=(second*1000); - msec_+=(sec*1000); - return(TRUE); -} - -// -// Set the minutes value (0-59) -// -bit8 Xtime::setMinute(sint32 min) -{ - sint32 minute=(msec_/60000)%60; // 1000*60 - msec_-=(minute*60000); - msec_+=(min*60000); - return(TRUE); -} - -// -// Set the minutes value (0-23) -// -bit8 Xtime::setHour(sint32 hour) -{ - hour=(msec_/3600000)%24; // 1000*60*60 - msec_-=(hour*3600000); - msec_+=(hour*3600000); - return(TRUE); -} - -// -// Set the year value -// Results are undefined if you're moving from Feb 29, to a non leap year -// -bit8 Xtime::setYear(sint32 _year) -{ - // extract the date - int month,mday,year,hour,min,sec; - getTime(month,mday,year,hour,min,sec); - - // modify & rebuild - year=_year; - day_=Get_Day(month,mday,year); - return(TRUE); -} - -// -// Modify the month -// -bit8 Xtime::setMonth(sint32 _month) -{ - // extract the date - int month,mday,year,hour,min,sec; - getTime(month,mday,year,hour,min,sec); - - // modify & rebuild - month=_month; - day_=Get_Day(month,mday,year); - return(TRUE); -} - - -// -// Modify the day of the month -// -bit8 Xtime::setMDay(sint32 _mday) -{ - // extract the date - int month,mday,year,hour,min,sec; - getTime(month,mday,year,hour,min,sec); - - // modify & rebuild - mday=_mday; - day_=Get_Day(month,mday,year); - return(TRUE); -} - - -// -// Compare two times. The time better be normalized -// which it would be unless you've put bad stuff in it! -// -// 1 = *this > other -//-1 = *this < other -// 0 = *this == other -int Xtime::compare(const Xtime &other) const -{ - if ((day_==other.day_)&&(msec_==other.msec_)) - return(0); // equal - - else if (day_>other.day_) - return(1); - else if (day_other.msec_) - return(1); - else - return(-1); -} - - -bit8 Xtime::operator == ( const Xtime &other ) const -{ - bit8 retval=compare(other); - if (retval==0) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator != ( const Xtime &other ) const -{ - bit8 retval=compare(other); - if (retval==0) - return(FALSE); - else - return(TRUE); -} - -bit8 Xtime::operator < ( const Xtime &other ) const -{ - int retval=compare(other); - if (retval==-1) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator > ( const Xtime &other ) const -{ - int retval=compare(other); - if (retval==1) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator <= ( const Xtime &other ) const -{ - int retval=compare(other); - if ((retval==-1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - -bit8 Xtime::operator >= ( const Xtime &other ) const -{ - int retval=compare(other); - if ((retval==1)||(retval==0)) - return(TRUE); - else - return(FALSE); -} - - -Xtime &Xtime::operator += (const Xtime &other) -{ - day_+=other.day_; - msec_+=other.msec_; - normalize(); - return *this; -} - -Xtime &Xtime::operator -= (const Xtime &other) -{ - day_-=other.day_; - msec_-=other.msec_; - normalize(); - return *this; -} - -Xtime Xtime::operator - (Xtime &other) -{ - Xtime temp(*this); - temp-=other; - return(temp); -} - -Xtime Xtime::operator + (Xtime &other) -{ - Xtime temp(*this); - temp+=other; - return(temp); -} - - -Xtime &Xtime::operator = (const Xtime &other) -{ - day_=other.day_; - msec_=other.msec_; - return *this; -} - - -Xtime &Xtime::operator += (const time_t other) -{ - addSeconds(other); - return *this; -} - - -Xtime &Xtime::operator -= (const time_t other) -{ - addSeconds(-((sint32)other)); - return *this; -} - - -Xtime Xtime::operator - (time_t other) -{ - Xtime temp(*this); - temp-=other; - return(temp); -} - - -Xtime Xtime::operator + (time_t other) -{ - Xtime temp(*this); - temp+=other; - return(temp); -} - -Xtime &Xtime::operator = (const time_t other) -{ - msec_=0; - day_=719528; // Jan 1, 1970 - addSeconds(other); - return *this; -} diff --git a/Generals/Code/Tools/matchbot/wlib/xtime.h b/Generals/Code/Tools/matchbot/wlib/xtime.h deleted file mode 100644 index b6210eee2c..0000000000 --- a/Generals/Code/Tools/matchbot/wlib/xtime.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -xtime Neal Kettler - -This is version 2 of the Wtime library (now xtime). It now supports -time storage from the year 0 to well after the sun -will have gone supernova (OK, OK I admit it'll break in the -year 5 Million.) - -The call to update the current time will break in 2038. -Hopefully by then somebody will replace the lame time() -function :-) -\****************************************************************************/ - -#ifndef XTIME_HEADER -#define XTIME_HEADER - - -#include -#include -#include -#include - -#ifndef _WINDOWS -#include -#include -#include -#else -#include -#include -#endif - -#include -#include - -#include "wstypes.h" - -class Xtime -{ - public: - - Xtime(); // init to system time - Xtime( Xtime &other ); - Xtime( time_t other ); // 1970-2038 - ~Xtime(); - - void addSeconds(sint32 seconds); - - bit8 getTime(int &month, int &mday, int &year, int &hour, int &minute, - int &second) const; - - bit8 setTime(int month, int mday, int year, int hour, int minute, - int second); - - void update(); // Update members sec & usec to system time - // This will break after 2038 - -/******** - void PrintTime(FILE *out) const; - void PrintTime(char *out) const; - void PrintDate(FILE *out) const; - void PrintDate(char *out) const; -**********/ - - sint32 getDay(void) const; // Get days since year 0 - sint32 getMsec(void) const; // Get milliseconds into the day - - void setDay(sint32 day); - void setMsec(sint32 msec); - - void set(sint32 newday, sint32 newmsec); - bit8 ParseDate(char *in); - bit8 FormatTime(char *out, const char *format); - - bit8 getTimeval(struct timeval &tv); - - // All of these may return -1 if the time is invalid - int getSecond(void) const; // Second (0-60) (60 is for a leap second) - int getMinute(void) const; // Minute (0-59) - int getHour(void) const; // Hour (0-23) - int getMDay(void) const; // Day of Month (1-31) - int getWDay(void) const; // Day of Week (1-7) - int getYDay(void) const; // Day of Year (1-366) (366 = leap yr) - int getMonth(void) const; // Month (1-12) - int getYWeek(void) const; // Week of Year (1-53) - int getYear(void) const; // Year (e.g. 1997) - - // Modify the time components. Return FALSE if fail - bit8 setSecond(sint32 sec); - bit8 setMinute(sint32 min); - bit8 setHour(sint32 hour); - bit8 setYear(sint32 year); - bit8 setMonth(sint32 month); - bit8 setMDay(sint32 mday); - - void normalize(void); // move msec overflows to the day - - // Compare two times - int compare(const Xtime &other) const; - - // comparisons - bit8 operator == ( const Xtime &other ) const; - bit8 operator != ( const Xtime &other ) const; - bit8 operator < ( const Xtime &other ) const; - bit8 operator > ( const Xtime &other ) const; - bit8 operator <= ( const Xtime &other ) const; - bit8 operator >= ( const Xtime &other ) const; - - // assignments - Xtime &operator = (const Xtime &other); - Xtime &operator = (const time_t other); - - // signed - Xtime &operator += (const Xtime &other); - Xtime &operator -= (const Xtime &other); - Xtime operator + (Xtime &other); - Xtime operator - (Xtime &other); - - Xtime &operator += (const time_t other); - Xtime &operator -= (const time_t other); - Xtime operator + (time_t other); - Xtime operator - (time_t other); - - protected: - sint32 day_; // days since Jan 1, 0 - sint32 msec_; // milliseconds (thousandths of a sec) -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wnet/field.cpp b/Generals/Code/Tools/matchbot/wnet/field.cpp deleted file mode 100644 index 3597370937..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/field.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : FIELD.CPP * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/22/96 * - * * - * Last Update : April 22, 1996 [PWG] * - * * - * Actual member function for the field class. * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#include -#include -#ifndef _WINDOWS -#include -#else -#define Win32_Winsock -#include -#endif -#include "field.h" - - -// private member func -void FieldClass::Clear(void) -{ - delete[](Data); - - strcpy(ID,""); - DataType=0; - Size=0; - Data=NULL; - Next=NULL; -} - - -FieldClass::FieldClass(char *id, char data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, unsigned char data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, short data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, unsigned short data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, long data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, unsigned long data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, char *data) -{ - Data=NULL; - Set(id,data); -} - -FieldClass::FieldClass(char *id, void *data, int length) -{ - Data=NULL; - Set(id,data,length); -} - -void FieldClass::Set(char *id, char data) -{ - FieldClass *Nextsave=Next; - - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_CHAR; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, unsigned char data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_UNSIGNED_CHAR; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, short data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_SHORT; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, unsigned short data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_UNSIGNED_SHORT; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, long data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_LONG; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, unsigned long data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_UNSIGNED_LONG; - Size = sizeof(data); - Data = new char[Size]; - memcpy(Data, &data, Size); - Next = Nextsave; -} - -void FieldClass::Set(char *id, char *data) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_STRING; - Size = (unsigned short)(strlen(data)+1); - Data = new char[Size]; - memcpy(Data, data, Size); - Next = Nextsave; -} - - -void FieldClass::Set(char *id, void *data, int length) -{ - FieldClass *Nextsave=Next; - Clear(); - strncpy(ID, id, sizeof(ID)); - DataType = TYPE_CHUNK; - Size = (unsigned short)length; - Data = new char[Size]; - memcpy(Data, data, Size); - Next = Nextsave; -} - - -FieldClass::~FieldClass() -{ - Clear(); -} - -// Fetch the datatype -int FieldClass::Get_Type(void) -{ - return(DataType); -} - -void *FieldClass::Get_Data(void) -{ -return(Data); -} - -char *FieldClass::Get_ID(void) -{ -return(ID); -} - -/************************************************************************** - * PACKETCLASS::HOST_TO_NET_FIELD -- Converts host field to net format * - * * - * INPUT: FIELD * to the data field we need to convert * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -void FieldClass::Host_To_Net(void) -{ - // - // Before we convert the data type, we should convert the actual data - // sent. - // - switch (DataType) { - case TYPE_CHAR: - case TYPE_UNSIGNED_CHAR: - case TYPE_STRING: - break; - - case TYPE_SHORT: - case TYPE_UNSIGNED_SHORT: - *((unsigned short *)Data) = htons(*((unsigned short *)Data)); - break; - - case TYPE_LONG: - case TYPE_UNSIGNED_LONG: - *((unsigned long *)Data) = htonl(*((unsigned long *)Data)); - break; - - // - // Might be good to insert some type of error message here for unknown - // datatypes -- but will leave that for later. - // - default: - break; - } - // - // Finally convert over the data type and the size of the packet. - // - DataType = htons(DataType); - Size = htons(Size); -} - -/************************************************************************** - * PACKETCLASS::NET_TO_HOST_FIELD -- Converts net field to host format * - * * - * INPUT: FIELD * to the data field we need to convert * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -void FieldClass::Net_To_Host(void) -{ - // - // Finally convert over the data type and the size of the packet. - // - DataType = ntohs(DataType); - Size = ntohs(Size); - - // - // Before we convert the data type, we should convert the actual data - // sent. - // - switch (DataType) { - case TYPE_CHAR: - case TYPE_UNSIGNED_CHAR: - case TYPE_STRING: - break; - - case TYPE_SHORT: - case TYPE_UNSIGNED_SHORT: - *((unsigned short *)Data) = ntohs(*((unsigned short *)Data)); - break; - - case TYPE_LONG: - case TYPE_UNSIGNED_LONG: - *((unsigned long *)Data) = ntohl(*((unsigned long *)Data)); - break; - - // - // Might be good to insert some type of error message here for unknown - // datatypes -- but will leave that for later. - // - default: - break; - } -} - diff --git a/Generals/Code/Tools/matchbot/wnet/field.h b/Generals/Code/Tools/matchbot/wnet/field.h deleted file mode 100644 index 8a58f68f55..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/field.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : FIELD.H * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/22/96 * - * * - * Last Update : April 22, 1996 [PWG] * - * * - * This module takes care of maintaining the field list used to process * - * packets. * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#define FIELD_HEADER_SIZE (sizeof(FieldClass) - (sizeof(void *) * 2)) - -#define TYPE_CHAR 1 -#define TYPE_UNSIGNED_CHAR 2 -#define TYPE_SHORT 3 -#define TYPE_UNSIGNED_SHORT 4 -#define TYPE_LONG 5 -#define TYPE_UNSIGNED_LONG 6 -#define TYPE_STRING 7 -#define TYPE_CHUNK 20 - -class PacketClass; - -class FieldClass -{ - public: - friend PacketClass; - // - // Define constructors to be able to create all the different kinds - // of fields. - // - FieldClass(void) {}; - FieldClass(char *id, char data); - FieldClass(char *id, unsigned char data); - FieldClass(char *id, short data); - FieldClass(char *id, unsigned short data); - FieldClass(char *id, long data); - FieldClass(char *id, unsigned long data); - FieldClass(char *id, char *data); - FieldClass(char *id, void *data, int length); - - ~FieldClass(); - - // Change the field contents - void Set(char *id, char data); - void Set(char *id, unsigned char data); - void Set(char *id, short data); - void Set(char *id, unsigned short data); - void Set(char *id, long data); - void Set(char *id, unsigned long data); - void Set(char *id, char *data); - void Set(char *id, void *data, int length); - - int Get_Type(void); // get the datatype of this field - unsigned short Get_Size(void) { return Size; } - void * Get_Data(void); // get the datatype of this field - char * Get_ID(void); // get the datatype of this field - - void Host_To_Net(void); - void Net_To_Host(void); - - private: - - void Clear(void); // dealloc mem & zero safely - - char ID[4]; // id value of this field - unsigned short DataType; // id of the data type we are using - unsigned short Size; // size of the data portion of this field - char *Data; // pointer to the data portion of this field - FieldClass *Next; // pointer to the next field in the field list -}; - - - diff --git a/Generals/Code/Tools/matchbot/wnet/packet.cpp b/Generals/Code/Tools/matchbot/wnet/packet.cpp deleted file mode 100644 index a2741dbe48..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/packet.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : PACKET.CPP * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/22/96 * - * * - * Last Update : April 24, 1996 [PWG] * - * * - *-------------------------------------------------------------------------* - * Functions: * - * *PacketClass::Find_Field -- Finds a field if it exists in the packets * - * Get_Field -- Find specified name and returns data * - * PacketClass::~PacketClass -- destroys a packet class be freeing list * - * PacketClass::Add_Field -- Adds a FieldClass entry to head of packet li* - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ -#include -#include -#include -#include -#ifndef _WINDOWS -#include -#else -#define Win32_Winsock -#include -#endif - -#include "packet.h" - - -/************************************************************************** - * PACKETCLASS::~PACKETCLASS -- destroys a packet class be freeing list * - * * - * INPUT: none * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/24/1996 PWG : Created. * - *========================================================================*/ -PacketClass::~PacketClass() -{ - FieldClass *current; - FieldClass *next; - - // - // Loop through the entire field list and delete each entry. - // - for (current = Head; current; current = next) { - next = current->Next; - delete(current); - } -} - - -/************************************************************************** - * PACKETCLASS::ADD_FIELD -- Adds a FieldClass entry to head of packet li * - * * - * INPUT: FieldClass * - a properly constructed field class entry. * - * * - * OUTPUT: none * - * * - * HISTORY: * - * 04/24/1996 PWG : Created. * - *========================================================================*/ -void PacketClass::Add_Field(FieldClass *field) -{ - field->Next = Head; - Head = field; -} - -/************************************************************************** - * PACKETCLASS::PACKETCLASS -- Creates a Packet object from a COMMS packe * - * * - * INPUT: * - * * - * OUTPUT: * - * * - * WARNINGS: * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -PacketClass::PacketClass(char *curbuf) -{ - int remaining_size; - // - // Pull the size and packet ID out of the linear packet stream. - // - Size = *((unsigned short *)curbuf); - curbuf += sizeof(unsigned short); - Size = ntohs(Size); - ID = *((short *)curbuf); - curbuf += sizeof(unsigned short); - ID = ntohs(ID); - Head = NULL; - - // - // Calculate the remaining size so that we can loop through the - // packets and extract them. - // - remaining_size = Size - 4; - - // - // Loop through the linear packet until we run out of room and - // create a field for each. - // - while (remaining_size > 0) - { - FieldClass *field = new FieldClass; - - // - // Copy the adjusted header into the buffer and then advance the buffer - // - memcpy(field, curbuf, FIELD_HEADER_SIZE); - curbuf += FIELD_HEADER_SIZE; - remaining_size -= FIELD_HEADER_SIZE; - - // - // Copy the data into the buffer - // - int size = ntohs(field->Size); - field->Data = new char[size]; - memcpy(field->Data, curbuf, size); - curbuf += size; - remaining_size -= size; - - // - // Make sure we allow for the pad bytes. - // - int pad = (4 - (ntohs(field->Size) & 3)) & 3; - curbuf += pad; - remaining_size -= pad; - - // - // Convert the field back to the host format - // - field->Net_To_Host(); - - // - // Finally add the field to the field list in the packet - // structure. - // - Add_Field(field); - } -} - -/************************************************************************** - * CREATE_COMMS_PACKET -- Walks field list creating a packet * - * * - * INPUT: short - the id of the packet so the server can identify it * - * unsigned short & - the size of the packet returned here * - * * - * OUTPUT: void * pointer to the linear packet data * - * * - * WARNINGS: This routine allocates memory that the user is responsible * - * for freeing. * - * * - * HISTORY: * - * 04/22/1996 PWG : Created. * - *========================================================================*/ -char *PacketClass::Create_Comms_Packet(int &size) -{ - FieldClass *current; - - // - // Size starts at four because that is the size of the packet header. - // - size = 4; - - // - // Take a quick spin through and calculate the size of the packet we - // are building. - // - for (current = Head; current; current=current->Next) - { - size += (unsigned short)FIELD_HEADER_SIZE; // add in packet header size - size += current->Size; // add in data size - size += (4 - (size & 3)) & 3; // add in pad value to dword align next packet - } - - // - // Now that we know the size allocate a buffer big enough to hold the - // packet. - // - char *retval = new char[size]; - char *curbuf = retval; - - // - // write the size into the packet header - // - *((unsigned short *)curbuf) = (unsigned short)htons(size); - curbuf += sizeof(unsigned short); - *((short *)curbuf) = htons(ID); - curbuf += sizeof(unsigned short); - - // - // Ok now that the actual header information has been written we need to write out - // field information. - // - for (current = Head; current; current = current->Next) - { - // - // Temporarily convert the packet to net format (this saves alot of - // effort, and seems safe...) - // - current->Host_To_Net(); - - // - // Copy the adjusted header into the buffer and then advance the buffer - // - memcpy(curbuf, current, FIELD_HEADER_SIZE); - curbuf += FIELD_HEADER_SIZE; - - // - // Copy the data into the buffer and then advance the buffer - // - memcpy(curbuf, current->Data, ntohs(current->Size)); - curbuf += ntohs(current->Size); - - // - // Finally take care of any pad bytes by setting them to 0 - // - int pad = (4 - (ntohs(current->Size) & 3)) & 3; - curbuf += pad; - - current->Net_To_Host(); - } - return(retval); -} - - -/************************************************************************** - * PACKETCLASS::FIND_FIELD -- Finds a field if it exists in the packets * - * * - * INPUT: char * - the id of the field we are looking for. * - * * - * OUTPUT: FieldClass * pointer to the field class * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -FieldClass *PacketClass::Find_Field(char *id) -{ - for (FieldClass *current = Head; current; current = current->Next) - { - if ( strncmp(id, current->ID, 4) == 0) - return current; - } - return NULL; -} - -// gks 9/25/2000 -FieldClass *PacketClass::Get_Field_At(int position) -{ - int i = 0; - FieldClass *current = Head; - for (; (current && (i < position)); current = current->Next, i++) { - } - - if (current) return current; - else return NULL; -} - -// gks 9/25/2000 -int PacketClass::Get_Num_Fields() -{ - int i = 0; - - for (FieldClass *current = Head; current; current = current->Next, i++) {} - - return i; - -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * char & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, char &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((char *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * unsigned char & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, unsigned char &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned char *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * short & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, short &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((short *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * unsigned short & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, unsigned short &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned short *)field->Data); - } - return((field) ? true : false); -} - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * long & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, long &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((long *)field->Data); - } - return((field) ? true : false); -} - - - -bit8 PacketClass::Get_Field(char *id, int &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((int *)field->Data); - } - return((field) ? true : false); -} - - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data as a string * - * * - * INPUT: char * - the id of the field that holds the data. * - * char * - the string to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The string is not changed if the field is not found. It * - * is assumed that the string variabled specified by the * - * pointer is large enough to hold the data. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, char *data) -{ - FieldClass *field = Find_Field(id); - if (field) { - strcpy(data, (char *)field->Data); - } - return((field) ? true : false); -} - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * unsigned long & - the reference to store the data into * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 04/23/1996 PWG : Created. * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, unsigned long &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned long *)field->Data); - } - return((field) ? true : false); -} - -bit8 PacketClass::Get_Field(char *id, unsigned &data) -{ - FieldClass *field = Find_Field(id); - if (field) { - data = *((unsigned *)field->Data); - } - return((field) ? true : false); -} - - - -/************************************************************************** - * GET_FIELD -- Find specified name and returns data * - * * - * INPUT: char * - the id of the field that holds the data. * - * void * - the reference to store the data into * - * int - the length of the buffer passed in * - * * - * OUTPUT: true if the field was found, false if it was not. * - * * - * WARNINGS: The data reference is not changed if the field is not * - * found. * - * * - * HISTORY: * - * 6/4/96 4:46PM ST : Created * - *========================================================================*/ -bit8 PacketClass::Get_Field(char *id, void *data, int &length) -{ - FieldClass *field = Find_Field(id); - if (field) { - memcpy (data, field->Data, MIN(field->Size, length)); - length = (int) field->Size; - } - return((field) ? true : false); -} - - -unsigned short PacketClass::Get_Field_Size(char* id) -{ - FieldClass *field = Find_Field(id); - if (field) - return field->Get_Size(); - else - return 0; -} - diff --git a/Generals/Code/Tools/matchbot/wnet/packet.h b/Generals/Code/Tools/matchbot/wnet/packet.h deleted file mode 100644 index 1bd2141833..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/packet.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*************************************************************************** - * * - * Project Name : Westwood Auto Registration App * - * * - * File Name : PACKET.H * - * * - * Programmer : Philip W. Gorrow * - * * - * Start Date : 04/19/96 * - * * - * Last Update : April 19, 1996 [PWG] * - * * - * This header defines the functions for the PacketClass. The packet * - * class is used to create a linked list of field entries which can be * - * converted to a linear packet in a COMMS API compatible format. * - * * - * Packets can be created empty and then have fields added to them or can * - * be created from an existing linear packet. * - * * - *-------------------------------------------------------------------------* - * Functions: * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "field.h" -#include - - -class PacketClass -{ - public: - - PacketClass(short id = 0) - { - Size = 0; - ID = id; - Head = 0; - } - PacketClass(char *cur_buf); - ~PacketClass(); - - // - // This function allows us to add a field to the start of the list. As the field is just - // a big linked list it makes no difference which end we add a member to. - // - void Add_Field(FieldClass *field); - - // - // These conveniance functions allow us to add a field directly to the list without - // having to worry about newing one first. - // - void Add_Field(char *field, char data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, unsigned char data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, short data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, unsigned short data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, long data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, unsigned long data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, char *data) {Add_Field(new FieldClass(field, data));}; - void Add_Field(char *field, void *data, int length) {Add_Field(new FieldClass(field, data, length));}; - - // - // These functions search for a field of a given name in the list and - // return the data via a reference value. - // - FieldClass *Find_Field(char *id); - - bit8 Get_Field(char *id, int &data); - bit8 Get_Field(char *id, char &data); - bit8 Get_Field(char *id, unsigned char &data); - bit8 Get_Field(char *id, short &data); - bit8 Get_Field(char *id, unsigned short &data); - bit8 Get_Field(char *id, long &data); - bit8 Get_Field(char *id, unsigned long &data); - bit8 Get_Field(char *id, unsigned &data); - bit8 Get_Field(char *id, char *data); - bit8 Get_Field(char *id, void *data, int &length); - unsigned short Get_Field_Size(char* id); - - // gks 9/25/2000 - FieldClass *Get_Field_At(int position); - int Get_Num_Fields(); - - char *Create_Comms_Packet(int &size); - - private: - unsigned short Size; - short ID; - FieldClass *Head; - FieldClass *Current; -}; - diff --git a/Generals/Code/Tools/matchbot/wnet/tcp.cpp b/Generals/Code/Tools/matchbot/wnet/tcp.cpp deleted file mode 100644 index 4c26d3231d..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/tcp.cpp +++ /dev/null @@ -1,1242 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -TCP Neal Kettler neal@westwood.com -****************************************************************************** - -A general purpose TCP class that can be used in either CLIENT or -SERVER mode. Note that this uses non-blocking sockets. - -The FD_* macros: - - FD_CLR(int fd, fd_set *set); // clear a single FD - FD_ISSET(int fd, fd_set *set); // check whether a single FD is set - FD_SET(int fd, fd_set *set); // set a single FD - FD_ZERO(fd_set * set); // clear the entire set - -NOTE: The fd_set returned by 'Wait' is static, don't call delete -on it! - - -If you are writing a CLIENT: - The last argument to many functions is an integer whichFD, this is used -only by SERVER mode, so you can omit this argument. Sample Code: - -fd_set *fdSet; -uint8 *buff=new uint8[1024]; -int retval; -TCP tcp(CLIENT); - -tcp.Bind((uint32)0,(uint16)0); // let system pick local IP and a Port for you -tcp.Connect("tango",13); // can connect by name or "10.1.1.10" - // or the integer in host byte order - -fdSet=tcp.Wait(10,0); // wait for UP TO 10 sec and 0 microseconds -if (FD_ISSET(tcp.GetFD(),fdSet)) // Is there something to read? -{ - retval=tcp.Read(buff,1024); // Read something - // Retval will contain the number of - // bytes read, or... - // 0 = remote end closed connection - // -1 = nothing to read - fprintf(stderr,"%s",buff); -} -else - fprintf(stderr,"Nothing was read!\n"); - - -If you are writing a SERVER: - - The structure called 'clientList' contains all the File Descriptors -that have connected to the server. Make sure you look at the FD_* -functions so you can use this sort of structure. When you are writing -a server, you need to specify the 'whichFD' arguments to all the -functions. Sample Code: - -fd_set *fdSet; -uint8 *buff=new uint8[1024]; -int retval; -TCP tcp(SERVER); - -tcp.Bind((uint32)0,(uint16)2121); // You need to bind to a well defined - // port number or nobody will know where - // to connect to. - -while (1) -{ - fdSet=tcp.Wait(-1,-1); // Wait until there is something on the socket - if (FD_ISSET(tcp.GetFD(),fdSet)) // somebody must want a connection - { - retval=tcp.GetConnection(); // Get a connection if somebody's trying - if (retval!=-1) - { - tcp.Write("Hello World!\n",strlen("Hello World!\n"),retval); - tcp.Close(retval); - } - } -} - - -\****************************************************************************/ - - -#include "tcp.h" -#include - -#ifndef _WINDOWS -#include -#define closesocket close -#endif - -// newMode should be either CLIENT or SERVER -TCP::TCP(int new_mode) -{ - mode=CLIENT; - maxFD=0; - fd = -1; - clientCount=0; - if ((new_mode==CLIENT)||(new_mode==SERVER)) - mode=new_mode; - FD_ZERO(&clientList); - connectionState=CLOSED; - inputDelay=5; - outputDelay=5; -} - -// Create a TCP object on a pre-existing socket -TCP::TCP(int new_mode,sint16 socket) -{ - sint32 retval; - - mode=CLIENT; - maxFD= socket; - fd = socket; - clientCount=0; - if ((new_mode==CLIENT)||(new_mode==SERVER)) - mode=new_mode; - FD_ZERO(&clientList); - - inputDelay=5; - outputDelay=5; - - - retval=SetBlocking(FALSE,socket); // set to NB mode - //DBGMSG("Setblocking: "<0)&&(c!=0)) - { - string[i]=c; - if (c=='\n') - return(string); - i++; - } - else if ((retval==0)&&(i==0)) - { - DBGMSG("Remote endpoint closed (1)"); - return(NULL); - } - else if (retval==0) - return(string); - } - return(string); -} - - -// only specify whichFD if this is a server -sint32 TCP::Read(uint8 *msg,uint32 len,sint32 whichFD) -{ - sint32 retval; - //DBGMSG("In read, mode: "<0) - bytes_read+=retval; - // otherwise some error - } - return(bytes_read); -} - - - -// only specify whichFD if this is a server -// Peek at data in system buffer -sint32 TCP::Peek(uint8 *msg,uint32 len,sint32 whichFD) -{ - sint32 retval; - if (mode==CLIENT) - { - retval=recv(fd,(char *)msg,len,MSG_PEEK); - if (retval==0) - Close(); - return(retval); - } - else if (mode==SERVER) - { - if ((whichFD<=maxFD) && (FD_ISSET(whichFD,&clientList))) - { - retval=recv(whichFD,(char *)msg,len,MSG_PEEK); - if (retval==0) - Close(whichFD); - return(retval); - } - else - return(0); // closed - } - return(-1); -} - - -// only specify whichFD if this is a server -// (this is used for non-8 bit clean pipes, you probably don't -// want to use it!) -sint32 TCP::EncapsulatedRead(uint8 *msg,uint32 len,sint32 whichFD) -{ - sint32 retval,bytesRead=0; - uint32 i; - char data; - - if (mode==CLIENT) - whichFD=fd; - else if (mode==SERVER) - { - if ((whichFD>maxFD) || (!FD_ISSET(whichFD,&clientList))) - return(0); - } - else - return(-1); - - for (i=0; i=0; i--) - if (FD_ISSET(i,&clientList)) - { - maxFD=i; - break; - } - } - FD_CLR((uint32)whichFD,&clientList); - clientCount--; - return(closesocket(whichFD)); - } - } - return(-1); -} - - - -// if 'sec' AND 'usec' are -1 then this will sleep until -// there is socket activity - -int TCP::Wait(sint32 sec,sint32 usec,fd_set &returnSet,sint32 whichFD) -{ - fd_set inputSet; - - FD_ZERO(&inputSet); - - if (mode==SERVER) - { - if (whichFD==0) - { - inputSet=clientList; - if (fd > 0) - FD_SET(fd,&inputSet); - } - else if (whichFD > 0) - FD_SET(whichFD,&inputSet); - } - else if (mode==CLIENT) - { - if (whichFD==0) - whichFD=fd; - if (whichFD > 0) - FD_SET(whichFD,&inputSet); - } - - return(Wait(sec,usec,inputSet,returnSet)); -} - -int TCP::Wait(sint32 sec,sint32 usec,fd_set &givenSet,fd_set &returnSet) -{ - Wtime timeout; - Wtime timenow; - Wtime timethen; - fd_set backupSet; - int retval=0,done,givenMax; - bit8 noTimeout=FALSE; - timeval tv; - - returnSet=givenSet; - backupSet=returnSet; - - if ((sec==-1)&&(usec==-1)) - noTimeout=TRUE; - - timeout.SetSec(sec); - timeout.SetUsec(usec); - timethen+=timeout; - - givenMax=maxFD; - for (uint32 i=0; i<(sizeof(fd_set)*8); i++) // i=maxFD+1 - { - if (FD_ISSET(i,&givenSet)) - givenMax=i; - } - - done=0; - while( ! done) - { - if (noTimeout) - retval=select(givenMax+1,&returnSet,0,0,NULL); - else - { - timeout.GetTimevalMT(tv); - retval=select(givenMax+1,&returnSet,0,0,&tv); - } - - if (retval>=0) - done=1; - - else if ((retval==-1)&&(errno==EINTR)) // in case of signal - { - if (noTimeout==FALSE) - { - timenow.Update(); - timeout=timethen-timenow; - } - if ((noTimeout==FALSE)&&(timenow.GetSec()==0)&&(timenow.GetUsec()==0)) - done=1; - else - returnSet=backupSet; - } - else // maybe out of memory? - { - done=1; - } - } - return(retval); -} - - -void TCP::WaitWrite(sint32 whichFD) -{ - fd_set backupSet; - int retval=0,done; - fd_set outputSet; - - if (whichFD==0) - whichFD=fd; - - if (whichFD==-1) - return; - - FD_ZERO(&outputSet); - FD_SET(whichFD,&outputSet); - backupSet=outputSet; - - done=0; - while( ! done) - { - retval=select(maxFD+1,0,&outputSet,0,NULL); - - if (retval>=0) - done=1; - - else if ((retval==-1)&&(errno==EINTR)) // in case of signal - outputSet=backupSet; - else // maybe out of memory? - done=1; - } -} - -// Can a FD be written to? -bit8 TCP::CanWrite(sint32 whichFD) -{ - int retval=0; - fd_set outputSet; - Wtime timeout; - timeval tv; - - timeout.SetSec(0); - timeout.SetUsec(0); - - if (whichFD==0) - whichFD=fd; - - FD_ZERO(&outputSet); - FD_SET(whichFD,&outputSet); - - timeout.GetTimevalMT(tv); - retval=select(whichFD+1,0,&outputSet,0,&tv); - if (retval>0) - return(TRUE); - else - return(FALSE); -} - - -bit8 TCP::Bind(char *Host,uint16 port,bit8 reuseAddr) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( Bind( ntohl(inet_addr(Host)), port,reuseAddr) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - return (0); - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( Bind(ntohl(hostNode->s_addr),port,reuseAddr) ); -} - - -// You must call bind, implicit binding is for sissies -// Well... you can get implicit binding if you pass 0 for either arg - -bit8 TCP::Bind(uint32 IP,uint16 Port,bit8 reuseAddr) -{ - int retval; - int status; - - IP=htonl(IP); - Port=htons(Port); - - addr.sin_family=AF_INET; - addr.sin_port=Port; - addr.sin_addr.s_addr=IP; - fd=socket(AF_INET,SOCK_STREAM,DEFAULT_PROTOCOL); - if (fd==-1) - return(FALSE); - - retval=SetBlocking(FALSE,fd); - if (retval==-1) - ERRMSG("Couldn't set nonblocking mode!"); - - if (reuseAddr==TRUE) - { - uint32 opval; - - #ifdef SO_REUSEPORT -/****************** this may make the socket get garbage data?? - opval=1; - retval=setsockopt(fd,SOL_SOCKET,SO_REUSEPORT,(char *)&opval,sizeof(opval)); - if (retval!=0) - fprintf(stderr,"Could not set socket to SO_REUSEPORT\n"); -**********************/ - #endif - #ifdef SO_REUSEADDR - opval=1; - retval=setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char *)&opval,sizeof(opval)); - if (retval!=0) - fprintf(stderr,"Could not set socket to SO_REUSEADDR\n"); - #endif - } - - retval=bind(fd,(struct sockaddr *)&addr,sizeof(addr)); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - - if (retval==-1) - { - status=GetStatus(); - DBGMSG("Bind failure (" << status << ") IP "<< IP <<" PORT "<< ntohs(Port)); - return(FALSE); - } - myIP=IP; - myPort=Port; - maxFD=fd; - - if (mode==SERVER) - listen(fd,64); //Solaris needs lots of listen slots for some reason - - return(TRUE); -} - - -// This is only for clients - -bit8 TCP::Connect(char *Host,uint16 port) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( Connect( ntohl(inet_addr(Host)), port) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - {ERRMSG("Can't resolve host");return (0);} - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( Connect(ntohl(hostNode->s_addr),port) ); -} - -bit8 TCP::Connect(uint32 IP,uint16 Port) -{ - int tries,result; - struct timeval sleep_time; - struct sockaddr_in serverAddr; - int status; - - IP=htonl(IP); - Port=htons(Port); - - serverAddr.sin_family=AF_INET; - serverAddr.sin_port=Port; - serverAddr.sin_addr.s_addr=IP; - - if (mode!=CLIENT) - {ERRMSG("Can't connect in server mode");return(FALSE);} - - tries=0; - result=-1; - - - // try 10 connects with a greater and greater sleep time after each one - // this can go on for upto 5.4 seconds - while ((tries < 10) && (result == -1)) - { - ClearStatus(); - result = connect(fd,(struct sockaddr *)&serverAddr, sizeof(serverAddr)); - status=GetStatus(); - - #ifdef _WINDOWS - if (result==SOCKET_ERROR) - result=-1; - #endif - - if ((status == ISCONN) && (result == -1)) - { - result = 0; - } - if (result == -1) - { - if ((status!=INPROGRESS)&&(status!=ALREADY)&&(status!=AGAIN)&& - (status!=WOULDBLOCK)) - { - Close(); - Bind(myIP,myPort); - } - tries++; - sleep_time.tv_sec = 0; - sleep_time.tv_usec = (100000*(tries+1)); - #ifdef WIN32 - Sleep((sleep_time.tv_usec)/1000); - #else - select(0, 0, 0, 0, &sleep_time); - #endif - } - } - - if (result == -1) - { - return(FALSE); - } - connectionState=CONNECTED; - return (TRUE); -} - - - -// Asynchronous Connection -bit8 TCP::ConnectAsync(char *Host,uint16 port) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( ConnectAsync( ntohl(inet_addr(Host)), port) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - return (0); - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( ConnectAsync(ntohl(hostNode->s_addr),port) ); -} - -// Asynchronous Connection -bit8 TCP::ConnectAsync(uint32 IP,uint16 Port) -{ - int result; - struct sockaddr_in serverAddr; - int status,connectErrno; - int retval; - - IP=htonl(IP); - Port=htons(Port); - - serverAddr.sin_family=AF_INET; - serverAddr.sin_port=Port; - serverAddr.sin_addr.s_addr=IP; - - if (mode!=CLIENT) - return(FALSE); - - result=-1; - - if (connectionState==CONNECTING) - { - if (IsConnected(fd)) - { - DBGMSG("CONNECTION COMPLETE at point 1"); - connectionState=CONNECTED; - return(TRUE); - } - else - return(TRUE); // Still trying - } - - ClearStatus(); - result = connect(fd,(struct sockaddr *)&serverAddr, sizeof(serverAddr)); - connectErrno=errno; - status=GetStatus(); - - #ifdef _WINDOWS - if (result==SOCKET_ERROR) - { - DBGMSG("Socket error 1 " << status); - result=-1; - } - #endif - - // If we have a bogus FD, try again after closing and re-binding - if ((result==-1)&&((status==BADF)||(status==NOTSOCK)||(status==INVAL))) - { - Close(); - retval=Bind(myIP,myPort); - DBGMSG("BIND = "<maxFD) - maxFD=clientFD; - FD_SET(clientFD,&clientList); - clientCount++; - } - return(clientFD); -} - -sint32 TCP::GetConnection(struct sockaddr *clientAddr) -{ - if (mode!=SERVER) - return(-1); - - sint32 clientFD; - int addrlen=sizeof(struct sockaddr); - - clientFD=accept(fd,(struct sockaddr *)clientAddr,&addrlen); - if (clientFD!=-1) - { - if (clientFD>maxFD) - maxFD=clientFD; - FD_SET(clientFD,&clientList); - clientCount++; - } - return(clientFD); -} - diff --git a/Generals/Code/Tools/matchbot/wnet/tcp.h b/Generals/Code/Tools/matchbot/wnet/tcp.h deleted file mode 100644 index 3f63e4e9d3..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/tcp.h +++ /dev/null @@ -1,199 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/****************************************************************************\ -TCP Neal Kettler neal@westwood.com - -\****************************************************************************/ - -#ifndef TCP_HEADER -#define TCP_HEADER - -#include -#include -#include -#include -#include -#include - -#ifdef _WINDOWS - -#include -#include -#define close _close -#define read _read -#define write _write - -#else //UNIX -#include -#include -#include -#include -#include -#include -#include -#include -#include - -typedef signed int SOCKET; - -#endif - - -#ifdef AIX -#include -#endif - -#define DEFAULT_PROTOCOL 0 - -#include "wlib/wstypes.h" -#include "wlib/wdebug.h" -#include "wlib/wtime.h" - -class TCP -{ - -// DATA --------------- - -private: - int mode; // client or server - sint32 fd; // the primary FD - - uint32 myIP; // after bind myIP & myPort will be - uint16 myPort; // whatever we bound to - - struct sockaddr_in addr; - int maxFD; // value of the biggest FD - int clientCount; // how many clients open - - - sint32 inputDelay; // default delay for semi-blocking reads - sint32 outputDelay; // default delay for semi-blocking writes - - enum ConnectionState - { - CLOSED, - CONNECTING, - CONNECTED - } connectionState; // What state is client FD in - -public: - - enum - { - CLIENT = 1, - SERVER = 2 - }; - - // These defines specify a system independent way to - // get error codes for socket services. - enum - { - OK, // Everything's cool - UNKNOWN, // There was an error of unknown type - ISCONN, // The socket is already connected - INPROGRESS, // The socket is non-blocking and the operation - // isn't done yet - ALREADY, // The socket is already attempting a connection - // but isn't done yet - AGAIN, // Try again. - ADDRINUSE, // Address already in use - ADDRNOTAVAIL, // That address is not available on the remote host - BADF, // Not a valid FD - CONNREFUSED, // Connection was refused - INTR, // Operation was interrupted - NOTSOCK, // FD wasn't a socket - PIPE, // That operation just made a SIGPIPE - WOULDBLOCK, // That operation would block - INVAL, // Invalid - TIMEDOUT // Timeout - }; - - // for client list (if this is a server) - fd_set clientList; - - -// CODE ---------------- - -public: - TCP(int newMode); - TCP(int newMode,sint16 socket); - ~TCP(); - bit8 Bind(uint32 IP,uint16 port,bit8 reuseAddr=FALSE); - bit8 Bind(char *Host,uint16 port,bit8 reuseAddr=FALSE); - - sint32 GetMaxFD(void); - - bit8 Connect(uint32 IP,uint16 port); - bit8 Connect(char *Host,uint16 port); - bit8 ConnectAsync(uint32 IP,uint16 port); - bit8 ConnectAsync(char *Host,uint16 port); - - bit8 IsConnected(sint32 whichFD=0); - - sint32 GetFD(void); - sint32 GetClientCount(void) { return(clientCount); } - - // Get IP or Port of a connected endpoint - uint32 GetRemoteIP(sint32 whichFD=0); - uint16 GetRemotePort(sint32 whichFD=0); - - sint32 GetConnection(void); - sint32 GetConnection(struct sockaddr *clientAddr); - void WaitWrite(sint32 whichFD=0); - bit8 CanWrite(sint32 whichFD=0); - sint32 Write(const uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 WriteNB(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 EncapsulatedWrite(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 WriteString(char *msg,sint32 whichFD=0); - sint32 Printf(sint32 whichFD,const char *format,...); - sint32 Read(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 TimedRead(uint8 *msg,uint32 len,int seconds,sint32 whichFD=0); - sint32 Peek(uint8 *msg,uint32 len,sint32 whichFD=0); - sint32 EncapsulatedRead(uint8 *msg,uint32 len,sint32 whichFD=0); - - char *Gets(char *string,int n,int whichFD=0); - - // Wait on all sockets (or a specified one) - // return when ready for reading (or timeout occurs) - int Wait(sint32 sec,sint32 usec,fd_set &returnSet,sint32 whichFD=0); - int Wait(sint32 sec,sint32 usec,fd_set &inputSet,fd_set &returnSet); - - int GetStatus(void); - void ClearStatus(void); - - //sint32 GetSockStatus(sint32 whichFD=0); - - // give up ownership of the socket without closing it - void DisownSocket(void); - - sint32 Close(sint32 whichFD=0); - sint32 CloseAll(void); // close all sockets (same as close for client) - - sint32 SetBlocking(bit8 block,sint32 whichFD=0); - - // Set default delays for semi-blocking reads & writes - // default input = 5, output = 5 - // this is new and not used everywhere - // - bit8 SetInputDelay(sint32 delay) { inputDelay=delay; return(TRUE); }; - bit8 SetOutputDelay(sint32 delay) { outputDelay=delay; return(TRUE); }; - -}; - -#endif diff --git a/Generals/Code/Tools/matchbot/wnet/udp.cpp b/Generals/Code/Tools/matchbot/wnet/udp.cpp deleted file mode 100644 index afa6d16150..0000000000 --- a/Generals/Code/Tools/matchbot/wnet/udp.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "udp.h" -#include "wlib/wdebug.h" - -UDP::UDP() -{ - fd=0; -} - -UDP::~UDP() -{ -} - -sint32 UDP::Bind(char *Host,uint16 port) -{ - char hostName[100]; - struct hostent *hostStruct; - struct in_addr *hostNode; - - if (isdigit(Host[0])) - return ( Bind( ntohl(inet_addr(Host)), port) ); - - strcpy(hostName, Host); - - hostStruct = gethostbyname(Host); - if (hostStruct == NULL) - return (0); - hostNode = (struct in_addr *) hostStruct->h_addr; - return ( Bind(ntohl(hostNode->s_addr),port) ); -} - -// You must call bind, implicit binding is for sissies -// Well... you can get implicit binding if you pass 0 for either arg -sint32 UDP::Bind(uint32 IP,uint16 Port) -{ - int retval; - int status; - - IP=htonl(IP); - Port=htons(Port); - - addr.sin_family=AF_INET; - addr.sin_port=Port; - addr.sin_addr.s_addr=IP; - fd=socket(AF_INET,SOCK_DGRAM,DEFAULT_PROTOCOL); - #ifdef _WINDOWS - if (fd==SOCKET_ERROR) - fd=-1; - #endif - if (fd==-1) - return(UNKNOWN); - - retval=bind(fd,(struct sockaddr *)&addr,sizeof(addr)); - - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - if (retval==-1) - { - status=GetStatus(); - //CERR("Bind failure (" << status << ") IP " << IP << " PORT " << Port ) - return(status); - } - - int namelen=sizeof(addr); - getsockname(fd, (struct sockaddr *)&addr, &namelen); - - myIP=ntohl(addr.sin_addr.s_addr); - myPort=ntohs(addr.sin_port); - - retval=SetBlocking(FALSE); - if (retval==-1) - fprintf(stderr,"Couldn't set nonblocking mode!\n"); - - return(OK); -} - -bit8 UDP::getLocalAddr(uint32 &ip, uint16 &port) -{ - ip=myIP; - port=myPort; - return(OK); -} - - -// private function -sint32 UDP::SetBlocking(bit8 block) -{ - #ifdef _WINDOWS - unsigned long flag=1; - if (block) - flag=0; - int retval; - retval=ioctlsocket(fd,FIONBIO,&flag); - if (retval==SOCKET_ERROR) - return(UNKNOWN); - else - return(OK); - #else // UNIX - int flags = fcntl(fd, F_GETFL, 0); - if (block==FALSE) // set nonblocking - flags |= O_NONBLOCK; - else // set blocking - flags &= ~(O_NONBLOCK); - - if (fcntl(fd, F_SETFL, flags) < 0) - { - return(UNKNOWN); - } - return(OK); - #endif -} - - -sint32 UDP::Write(uint8 *msg,uint32 len,uint32 IP,uint16 port) -{ - sint32 retval; - struct sockaddr_in to; - - // This happens frequently - if ((IP==0)||(port==0)) return(ADDRNOTAVAIL); - - errno=0; - to.sin_port=htons(port); - to.sin_addr.s_addr=htonl(IP); - to.sin_family=AF_INET; - - ClearStatus(); - retval=sendto(fd,(char *)msg,len,0,(struct sockaddr *)&to,sizeof(to)); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - - return(retval); -} - -sint32 UDP::Read(uint8 *msg,uint32 len,sockaddr_in *from) -{ - sint32 retval; - int alen=sizeof(sockaddr_in); - - if (from!=NULL) - { - retval=recvfrom(fd,(char *)msg,len,0,(struct sockaddr *)from,&alen); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - } - else - { - retval=recvfrom(fd,(char *)msg,len,0,NULL,NULL); - #ifdef _WINDOWS - if (retval==SOCKET_ERROR) - retval=-1; - #endif - } - return(retval); -} - - -void UDP::ClearStatus(void) -{ - #ifndef _WINDOWS - errno=0; - #endif -} - -UDP::sockStat UDP::GetStatus(void) -{ - #ifdef _WINDOWS - int status=WSAGetLastError(); - if (status==0) return(OK); - else if (status==WSAEINTR) return(INTR); - else if (status==WSAEINPROGRESS) return(INPROGRESS); - else if (status==WSAECONNREFUSED) return(CONNREFUSED); - else if (status==WSAEINVAL) return(INVAL); - else if (status==WSAEISCONN) return(ISCONN); - else if (status==WSAENOTSOCK) return(NOTSOCK); - else if (status==WSAETIMEDOUT) return(TIMEDOUT); - else if (status==WSAEALREADY) return(ALREADY); - else if (status==WSAEWOULDBLOCK) return(WOULDBLOCK); - else if (status==WSAEBADF) return(BADF); - else return(UNKNOWN); - #else - int status=errno; - if (status==0) return(OK); - else if (status==EINTR) return(INTR); - else if (status==EINPROGRESS) return(INPROGRESS); - else if (status==ECONNREFUSED) return(CONNREFUSED); - else if (status==EINVAL) return(INVAL); - else if (status==EISCONN) return(ISCONN); - else if (status==ENOTSOCK) return(NOTSOCK); - else if (status==ETIMEDOUT) return(TIMEDOUT); - else if (status==EALREADY) return(ALREADY); - else if (status==EAGAIN) return(AGAIN); - else if (status==EWOULDBLOCK) return(WOULDBLOCK); - else if (status==EBADF) return(BADF); - else return(UNKNOWN); - #endif -} - - - -// -// Wait for net activity on this socket -// -int UDP::Wait(sint32 sec,sint32 usec,fd_set &returnSet) -{ - fd_set inputSet; - - FD_ZERO(&inputSet); - FD_SET(fd,&inputSet); - - return(Wait(sec,usec,inputSet,returnSet)); -} - -// -// Wait for net activity on a list of sockets -// -int UDP::Wait(sint32 sec,sint32 usec,fd_set &givenSet,fd_set &returnSet) -{ - Wtime timeout,timenow,timethen; - fd_set backupSet; - int retval=0,done,givenMax; - bit8 noTimeout=FALSE; - timeval tv; - - returnSet=givenSet; - backupSet=returnSet; - - if ((sec==-1)&&(usec==-1)) - noTimeout=TRUE; - - timeout.SetSec(sec); - timeout.SetUsec(usec); - timethen+=timeout; - - givenMax=fd; - for (uint32 i=0; i<(sizeof(fd_set)*8); i++) // i=maxFD+1 - { - if (FD_ISSET(i,&givenSet)) - givenMax=i; - } - ///DBGMSG("WAIT fd="<. -*/ - -#ifndef UDP_HEADER -#define UDP_HEADER - -#include -#include -#include -#include -#include - -#ifdef _WINDOWS -#include -#include -#define close _close -#define read _read -#define write _write - -#else //UNIX -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -#ifdef AIX -#include -#endif - -#define DEFAULT_PROTOCOL 0 - -#include -#include - -class UDP -{ - // DATA - private: - sint32 fd; - uint32 myIP; - uint16 myPort; - struct sockaddr_in addr; - - // These defines specify a system independent way to - // get error codes for socket services. - enum sockStat - { - OK = 0, // Everything's cool - UNKNOWN = -1, // There was an error of unknown type - ISCONN = -2, // The socket is already connected - INPROGRESS = -3, // The socket is non-blocking and the operation - // isn't done yet - ALREADY = -4, // The socket is already attempting a connection - // but isn't done yet - AGAIN = -5, // Try again. - ADDRINUSE = -6, // Address already in use - ADDRNOTAVAIL = -7, // That address is not available on the remote host - BADF = -8, // Not a valid FD - CONNREFUSED = -9, // Connection was refused - INTR =-10, // Operation was interrupted - NOTSOCK =-11, // FD wasn't a socket - PIPE =-12, // That operation just made a SIGPIPE - WOULDBLOCK =-13, // That operation would block - INVAL =-14, // Invalid - TIMEDOUT =-15 // Timeout - }; - -// CODE - private: - sint32 SetBlocking(bit8 block); - - public: - UDP(); - ~UDP(); - sint32 Bind(uint32 IP,uint16 port); - sint32 Bind(char *Host,uint16 port); - sint32 Write(uint8 *msg,uint32 len,uint32 IP,uint16 port); - sint32 Read(uint8 *msg,uint32 len,sockaddr_in *from); - sockStat GetStatus(void); - void ClearStatus(void); - int Wait(sint32 sec,sint32 usec,fd_set &returnSet); - int Wait(sint32 sec,sint32 usec,fd_set &givenSet,fd_set &returnSet); - - bit8 getLocalAddr(uint32 &ip, uint16 &port); - sint32 getFD(void) { return(fd); } - - bit8 SetInputBuffer(uint32 bytes); - bit8 SetOutputBuffer(uint32 bytes); - int GetInputBuffer(void); - int GetOutputBuffer(void); -}; - -#endif diff --git a/Generals/Code/Tools/textureCompress/CMakeLists.txt b/Generals/Code/Tools/textureCompress/CMakeLists.txt deleted file mode 100644 index f2e67f5014..0000000000 --- a/Generals/Code/Tools/textureCompress/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -set(TEXTURECOMPRESS_SRC - "resource.h" - "textureCompress.cpp" -) - -add_executable(g_texturecompress WIN32) -set_target_properties(g_texturecompress PROPERTIES OUTPUT_NAME texturecompress) - -target_sources(g_texturecompress PRIVATE ${TEXTURECOMPRESS_SRC}) - -target_link_libraries(g_texturecompress PRIVATE - core_config -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(g_texturecompress PRIVATE textureCompress.rc) -endif() diff --git a/Generals/Code/Tools/textureCompress/resource.h b/Generals/Code/Tools/textureCompress/resource.h deleted file mode 100644 index f7ce2bf851..0000000000 --- a/Generals/Code/Tools/textureCompress/resource.h +++ /dev/null @@ -1,16 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by Script1.rc -// -#define IDC_FILENAME 1058 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 112 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1006 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/textureCompress/textureCompress.cpp b/Generals/Code/Tools/textureCompress/textureCompress.cpp deleted file mode 100644 index 029ba62960..0000000000 --- a/Generals/Code/Tools/textureCompress/textureCompress.cpp +++ /dev/null @@ -1,679 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: textureCompress.cpp ////////////////////////////////////////////////////// -// Author: Matthew D. Campbell, Dec 2002 - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#define WIN32_LEAN_AND_MEAN // only bare bones windows stuff wanted -//#include -#include -#include -#include -#include -#include - -#include "resource.h" -#include -#include -#include -#include -#include -#include -#include - -static const char *nodxtPrefix[] = { - "zhca", - "caust", - NULL, -}; - -static const char *nodxtAnywhere[] = { - "userinterface", - "controlbar", - "commandbar", - NULL, -}; - -#define LOG(x) logStuff x -static void logStuff(const char *fmt, ...) -{ - static char buffer[1024]; - va_list va; - va_start( va, fmt ); - _vsnprintf(buffer, 1024, fmt, va ); - buffer[1023] = 0; - va_end( va ); - - puts(buffer); - ::MessageBox(NULL, buffer, "textureCompress", MB_OK); -} - -#ifndef NDEBUG - -class DebugMunkee -{ -public: - DebugMunkee(const char *fname = "debugLog.txt") { m_fp = fopen(fname, "w"); } - ~DebugMunkee() { if (m_fp) fclose(m_fp); m_fp = NULL; } - - FILE *m_fp; -}; - -static DebugMunkee *theDebugMunkee = NULL; - -#define DEBUG_LOG(x) debugLog x -static void debugLog(const char *fmt, ...) -{ - static char buffer[1024]; - va_list va; - va_start( va, fmt ); - _vsnprintf(buffer, 1024, fmt, va ); - buffer[1023] = 0; - va_end( va ); - - OutputDebugString( buffer ); - puts(buffer); - if (theDebugMunkee) - fputs(buffer, theDebugMunkee->m_fp); -} - -#else - -#define DEBUG_LOG(x) {} - -#endif // NDEBUG - - -static void usage(const char *progname) -{ - if (!progname) - progname = "textureCompress"; - LOG (("Usage: %s sourceDir destDir cacheDir outFile dxtOutFile\n", progname)); -} - -class FileInfo -{ -public: - FileInfo() {} - ~FileInfo() {} - - void set( const WIN32_FIND_DATA& info ); - - std::string filename; - time_t creationTime; - time_t accessTime; - time_t modTime; - DWORD attributes; - DWORD filesize; // only care about 32 bits for our purposes - -protected: -}; - -struct FileInfoComparator -{ - bool operator()(const FileInfo& a, const FileInfo& b) const - { - return a.filename < b.filename; - } -}; - -//------------------------------------------------------------------------------------------------- - -typedef std::set FileInfoSet; - -//------------------------------------------------------------------------------------------------- - -class Directory -{ -public: - Directory(const std::string& dirPath); - ~Directory() {} - - FileInfoSet* getFiles( void ); - FileInfoSet* getSubdirs( void ); - -protected: - std::string m_dirPath; - - FileInfoSet m_files; - FileInfoSet m_subdirs; -}; - -//------------------------------------------------------------------------------------------------- - -static void TimetToFileTime( time_t t, FILETIME& ft ) -{ - LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000; - ft.dwLowDateTime = (DWORD) ll; - ft.dwHighDateTime = ll >>32; -} - -static time_t FileTimeToTimet( const FILETIME& ft ) -{ - LONGLONG ll = (ft.dwHighDateTime << 32) + ft.dwLowDateTime - 116444736000000000; - ll /= 10000000; - return (time_t)ll; -} - -//------------------------------------------------------------------------------------------------- - -void FileInfo::set( const WIN32_FIND_DATA& info ) -{ - filename = info.cFileName; - for (int i=0; i= 0; index--) - { - if ((*source != 0) && ((unsigned char)buffer[index] <= 32)) - { - buffer[index] = '\0'; - } - else - { - break; - } - } - } - - return buffer; -} - -//------------------------------------------------------------------------------------------------- -typedef std::set StringSet; - -//------------------------------------------------------------------------------------------------- -void eraseCachedFiles(const std::string& sourceDirName, const std::string& targetDirName, const std::string& cacheDirName, - StringSet& cachedFilesToErase) -{ - StringSet::const_iterator sit; - for (sit = cachedFilesToErase.begin(); sit != cachedFilesToErase.end(); ++sit) - { - std::string src = cacheDirName; - src.append("\\"); - src.append(*sit); - - DEBUG_LOG(("Erasing cached file: %s\n", src.c_str())); - DeleteFile(src.c_str()); - } -} - -//------------------------------------------------------------------------------------------------- -void copyCachedFiles(const std::string& sourceDirName, const std::string& targetDirName, const std::string& cacheDirName, - StringSet& cachedFilesToCopy) -{ - StringSet::const_iterator sit; - for (sit = cachedFilesToCopy.begin(); sit != cachedFilesToCopy.end(); ++sit) - { - std::string src = cacheDirName; - src.append("\\"); - src.append(*sit); - - std::string dest = targetDirName; - dest.append("\\"); - dest.append(*sit); - - DEBUG_LOG(("Copying cached file: %s\n", src.c_str())); - if (_chmod(dest.c_str(), _S_IWRITE | _S_IREAD) == -1) - { - DEBUG_LOG(("Cannot chmod '%s'\n", dest.c_str())); - } - CopyFile(src.c_str(), dest.c_str(), FALSE); - } -} - -//------------------------------------------------------------------------------------------------- -void compressOrigFiles(const std::string& sourceDirName, const std::string& targetDirName, const std::string& cacheDirName, - StringSet& origFilesToCompress, const std::string& dxtOutFname) -{ - char tmpPath[_MAX_PATH] = "C:\\temp\\"; - char tmpFname[_MAX_PATH] = "C:\\temp\\tmp.txt"; - GetTempPath(_MAX_PATH, tmpPath); - GetTempFileName(tmpPath, "tex", 0, tmpFname); - HANDLE h = CreateFile(tmpFname, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); - if (!h) - { - DEBUG_LOG(("Could not create temp file '%s'! Unable to compress textures!\n", tmpFname)); - } - - StringSet::const_iterator sit; - for (sit = origFilesToCompress.begin(); sit != origFilesToCompress.end(); ++sit) - { - std::string tmp = sourceDirName; - tmp.append("\\"); - tmp.append(*sit); - tmp.append("\n"); - DEBUG_LOG(("Compressing file: %s", tmp.c_str())); - DWORD len; - WriteFile(h, tmp.c_str(), tmp.length(), &len, NULL); - } - CloseHandle(h); - - std::string commandLine; - commandLine = "\\projects\\rts\\build\\nvdxt -list "; - commandLine.append(tmpFname); - commandLine.append(" -24 dxt1c -32 dxt5 -full -outdir "); - commandLine.append(cacheDirName); - commandLine.append(" > "); - commandLine.append(dxtOutFname); - - DEBUG_LOG(("Compressing textures with command line of '%s'\n", commandLine.c_str())); - int ret = system(commandLine.c_str()); - DEBUG_LOG(("system(%s) returned %d\n", commandLine.c_str(), ret)); - DeleteFile(tmpFname); - - // now copy compressed file to target dir - for (sit = origFilesToCompress.begin(); sit != origFilesToCompress.end(); ++sit) - { - std::string orig = sourceDirName; - orig.append("\\"); - orig.append(*sit); - - struct stat origStat; - stat( orig.c_str(), &origStat); - - struct _utimbuf utb; - utb.actime = origStat.st_atime; - utb.modtime = origStat.st_mtime; - - std::string src = cacheDirName; - src.append("\\"); - src.append(*sit); - src.replace(src.size()-4, 4, ".dds"); - - _utime(src.c_str(), &utb); - - std::string dest = targetDirName; - dest.append("\\"); - dest.append(*sit); - dest.replace(dest.size()-4, 4, ".dds"); - - DEBUG_LOG(("Copying new file from %s to %s\n", src.c_str(), dest.c_str())); - - if (_chmod(dest.c_str(), _S_IWRITE | _S_IREAD) == -1) - { - DEBUG_LOG(("Cannot chmod '%s'\n", dest.c_str())); - } - BOOL ret = CopyFile(src.c_str(), dest.c_str(), FALSE); - if (!ret) - { - DEBUG_LOG(("Could not copy file!\n")); - } - - _utime(dest.c_str(), &utb); - } -} - -//------------------------------------------------------------------------------------------------- -void copyOrigFiles(const std::string& sourceDirName, const std::string& targetDirName, const std::string& cacheDirName, - StringSet& origFilesToCopy) -{ - StringSet::const_iterator sit; - for (sit = origFilesToCopy.begin(); sit != origFilesToCopy.end(); ++sit) - { - std::string src = sourceDirName; - src.append("\\"); - src.append(*sit); - - std::string dest = targetDirName; - dest.append("\\"); - dest.append(*sit); - - if (_chmod(dest.c_str(), _S_IWRITE | _S_IREAD) == -1) - { - DEBUG_LOG(("Cannot chmod '%s'\n", dest.c_str())); - } - BOOL res = CopyFile(src.c_str(), dest.c_str(), FALSE); - DEBUG_LOG(("Copying file: %s returns %d\n", src.c_str(), res)); - } -} - -//------------------------------------------------------------------------------------------------- -static void scanDir( const std::string& sourceDirName, const std::string& targetDirName, const std::string& cacheDirName, const std::string& dxtOutFname ) -{ - DEBUG_LOG(("Scanning '%s'\n", sourceDirName.c_str())); - Directory sourceDir(sourceDirName); - - DEBUG_LOG(("Scanning '%s'\n", targetDirName.c_str())); - Directory targetDir(targetDirName); - - DEBUG_LOG(("Scanning '%s'\n", cacheDirName.c_str())); - Directory cacheDir(cacheDirName); - - FileInfoSet *sourceFiles = sourceDir.getFiles(); - FileInfoSet *cacheFiles = cacheDir.getFiles(); - FileInfoSet *targetFiles = targetDir.getFiles(); - - StringSet cachedFilesToErase; - StringSet cachedFilesToCopy; - StringSet origFilesToCompress; - StringSet origFilesToCopy; - - DEBUG_LOG(("Emptying targetDir\n")); - for (FileInfoSet::iterator targetIt = targetFiles->begin(); targetIt != targetFiles->end(); ++targetIt) - { - FileInfo f = *targetIt; - std::string fname = f.filename; - f.filename.replace(f.filename.size()-4, 4, ".tga"); - FileInfoSet::iterator fit = sourceFiles->find(f); - if (fit == sourceFiles->end()) - { - // look for pre-existing dds files too - f.filename.replace(f.filename.size()-4, 4, ".dds"); - FileInfoSet::iterator ddsfit = sourceFiles->find(f); - if (ddsfit == sourceFiles->end()) - { - fname.insert(0, "\\"); - fname.insert(0, targetDirName); - DEBUG_LOG(("Deleting now-removed file '%s'\n", fname.c_str())); - DeleteFile(fname.c_str()); - } - } - } - - for (FileInfoSet::iterator cacheIt = cacheFiles->begin(); cacheIt != cacheFiles->end(); ++cacheIt) - { - FileInfo f = *cacheIt; - int len = f.filename.size(); - if (len < 5) - { - cachedFilesToErase.insert(f.filename); - continue; - } - std::string fname = f.filename; - f.filename.replace(len-4, 4, ".tga"); - FileInfoSet::iterator fit = sourceFiles->find(f); - if (fit != sourceFiles->end()) - { - FileInfo sf = *fit; - if (f.modTime < sf.modTime) - { - /** - std::string orig = sourceDirName; - orig.append("\\"); - orig.append(sf.filename); - - struct stat origStat; - stat( orig.c_str(), &origStat); - - struct _utimbuf utb; - utb.actime = origStat.st_atime; - utb.modtime = origStat.st_mtime; - - std::string dest = cacheDirName; - dest.append("\\"); - dest.append(f.filename); - dest.replace(dest.size()-4, 4, ".dds"); - - _utime(dest.c_str(), &utb); - - cachedFilesToCopy.insert(fname); - /**/ - cachedFilesToErase.insert(fname); - } - else - { - f.filename = fname; // back to .dds - FileInfoSet::iterator it = targetFiles->find(f); - if (it == targetFiles->end()) - cachedFilesToCopy.insert(fname); - } - } - else - { - cachedFilesToErase.insert(fname); - } - } - - for (FileInfoSet::iterator sourceIt = sourceFiles->begin(); sourceIt != sourceFiles->end(); ++sourceIt) - { - FileInfo f = *sourceIt; - - std::string fname = f.filename; - const char *s = fname.c_str(); - int index = 0; - const char *check = nodxtPrefix[0]; - bool shouldSkip = false; - while (check) - { - if (fname.find(check) == 0) - { - shouldSkip = true; - break; - } - check = nodxtPrefix[++index]; - } - - index = 0; - check = nodxtAnywhere[0]; - while (check && !shouldSkip) - { - if (fname.find(check) != fname.npos) - { - shouldSkip = true; - break; - } - check = nodxtAnywhere[++index]; - } - - if (!shouldSkip) - { - // check for preexisting .dds files so we can just copy them - if (fname.find(".dds") != fname.npos) - { - shouldSkip = true; - } - } - - if (shouldSkip) - { - origFilesToCopy.insert(s); - } - else - { - int len = f.filename.size(); - f.filename.replace(len-4, 4, ".dds"); - FileInfoSet::iterator fit = cacheFiles->find(f); - if (fit != cacheFiles->end()) - { - FileInfo cf = *fit; - if (cf.modTime < f.modTime) - { - origFilesToCompress.insert(fname); - } - } - else - { - origFilesToCompress.insert(fname); - } - } - } - - // now dump our files - eraseCachedFiles (sourceDirName, targetDirName, cacheDirName, cachedFilesToErase); - copyCachedFiles (sourceDirName, targetDirName, cacheDirName, cachedFilesToCopy); - copyOrigFiles (sourceDirName, targetDirName, cacheDirName, origFilesToCopy); - compressOrigFiles(sourceDirName, targetDirName, cacheDirName, origFilesToCompress, dxtOutFname); -} - -//------------------------------------------------------------------------------------------------- -#define USE_WINMAIN -#ifdef USE_WINMAIN -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR lpCmdLine, - int nCmdShow) -{ - /* - ** Convert WinMain arguments to simple main argc and argv - */ - int argc = 1; - char * argv[20]; - argv[0] = NULL; - - char * token = strtok(lpCmdLine, " "); - while (argc < 20 && token != NULL) - { - argv[argc++] = strtrim(token); - token = strtok(NULL, " "); - } -#else -int main(int argc, const char **argv) -{ -#endif // USE_WINMAIN - - if (argc != 6) - { - usage(argv[0]); - } - else - { - const char *sourceDir = argv[1]; - const char *targetDir = argv[2]; - const char *cacheDir = argv[3]; - -#ifndef NDEBUG - theDebugMunkee = new DebugMunkee(argv[4]); -#endif - - //setUpLoadWindow(); - scanDir(sourceDir, targetDir, cacheDir, argv[5]); - //setLoadWindowText("Writing to file..."); - //printSet( noAlphaChannel, "No Alpha Channel" ); - //printSet( noAlpha, "Not Using Alpha Channel" ); - //printSet( hasAlpha, "Using Alpha Channel" ); - //tearDownLoadWindow(); - -#ifndef NDEBUG - delete theDebugMunkee; - theDebugMunkee = NULL; -#endif - } - - return 0; -} \ No newline at end of file diff --git a/Generals/Code/Tools/timingTest/CMakeLists.txt b/Generals/Code/Tools/timingTest/CMakeLists.txt deleted file mode 100644 index e0c23ec03a..0000000000 --- a/Generals/Code/Tools/timingTest/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -set(TIMINGTEST_SRC - "StdAfx.cpp" - "StdAfx.h" - "timingTest.cpp" -) - -add_executable(g_timingtest WIN32) -set_target_properties(g_timingtest PROPERTIES OUTPUT_NAME timingtest) - -target_sources(g_timingtest PRIVATE ${TIMINGTEST_SRC}) - -target_link_libraries(g_timingtest PRIVATE - core_config - core_utility - winmm -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(g_timingtest PRIVATE /subsystem:console) -endif() diff --git a/Generals/Code/Tools/timingTest/StdAfx.cpp b/Generals/Code/Tools/timingTest/StdAfx.cpp deleted file mode 100644 index 85a2fb45cd..0000000000 --- a/Generals/Code/Tools/timingTest/StdAfx.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.cpp : source file that includes just the standard includes -// timingTest.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "StdAfx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/Generals/Code/Tools/timingTest/StdAfx.h b/Generals/Code/Tools/timingTest/StdAfx.h deleted file mode 100644 index 67b8a1acfd..0000000000 --- a/Generals/Code/Tools/timingTest/StdAfx.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__2E1EE76B_62B6_41EC_9B2E_E7B1677E0D6E__INCLUDED_) -#define AFX_STDAFX_H__2E1EE76B_62B6_41EC_9B2E_E7B1677E0D6E__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -#include - -// TODO: reference additional headers your program requires here - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__2E1EE76B_62B6_41EC_9B2E_E7B1677E0D6E__INCLUDED_) diff --git a/Generals/Code/Tools/timingTest/timingTest.cpp b/Generals/Code/Tools/timingTest/timingTest.cpp deleted file mode 100644 index 3a7b74e153..0000000000 --- a/Generals/Code/Tools/timingTest/timingTest.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// timingTest.cpp : Defines the entry point for the console application. -// - -#include "StdAfx.h" -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#include - -double s_ticksPerSec = 0.0f; -double s_ticksPerMSec = 0.0f; -char buffer[1024]; - -//------------------------------------------------------------------------------------------------- -void GetPrecisionTimer(INT64* t) -{ -#if defined(_MSC_VER) && _MSC_VER < 1300 - // CPUID is needed to force serialization of any previous instructions. - __asm - { - RDTSC - MOV ECX,[t] - MOV [ECX], EAX - MOV [ECX+4], EDX - } -#else - *t = _rdtsc(); -#endif -} - -//------------------------------------------------------------------------------------------------- -void InitPrecisionTimer() -{ - __int64 totalTime = 0; - INT64 TotalTicks = 0; - static int TESTS = 10; - - cout << "Starting tests..." << flush; - - for (int i = 0; i < TESTS; ++i) - { - int TimeStart; - int TimeStop; - INT64 StartTicks; - INT64 EndTicks; - - TimeStart = timeGetTime(); - GetPrecisionTimer(&StartTicks); - for(;;) - { - TimeStop = timeGetTime(); - if ((TimeStop - TimeStart) > 1000) - { - GetPrecisionTimer(&EndTicks); - break; - } - } - - TotalTicks += (EndTicks - StartTicks); - - totalTime += (TimeStop - TimeStart); - } - - cout << "...completed" << endl; - s_ticksPerMSec = 1.0 * TotalTicks / totalTime; - s_ticksPerSec = s_ticksPerMSec * 1000.0f; - - sprintf(buffer, "Ticks per sec: %.2f\n", s_ticksPerSec); - cout << buffer; - sprintf(buffer, "Ticks per msec: %.2f\n", s_ticksPerMSec); - cout << buffer; -} - -int main(int argc, char* argv[]) -{ - INT64 startTime, endTime, totalTime = 0; - InitPrecisionTimer(); - FILE *out = fopen("output.txt", "w"); - cout << "Beginning Looping tests: " << endl; - - const int TESTCOUNT = 60; - - while (1) { - for (int i = 0; i < TESTCOUNT; ++i) { - GetPrecisionTimer(&startTime); - Sleep(5); - GetPrecisionTimer(&endTime); - totalTime += (endTime - startTime); - } - - double avgPerFrame = 1.0 * totalTime / TESTCOUNT; - - sprintf(buffer, "%.8f,\t", avgPerFrame / s_ticksPerMSec ); - fwrite(buffer, strlen(buffer), 1, out); - fflush(out); - cout << buffer << endl; - totalTime = 0; - } - fclose(out); - - return 0; -} - diff --git a/Generals/Code/Tools/versionUpdate/CMakeLists.txt b/Generals/Code/Tools/versionUpdate/CMakeLists.txt deleted file mode 100644 index 694f738b21..0000000000 --- a/Generals/Code/Tools/versionUpdate/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -set(VERSIONUPDATE_SRC - "versionUpdate.cpp" -) - -add_executable(g_versionupdate WIN32) -set_target_properties(g_versionupdate PROPERTIES OUTPUT_NAME versionupdate) - -target_sources(g_versionupdate PRIVATE ${VERSIONUPDATE_SRC}) - -target_link_libraries(g_versionupdate PRIVATE - core_config -) diff --git a/Generals/Code/Tools/versionUpdate/versionUpdate.cpp b/Generals/Code/Tools/versionUpdate/versionUpdate.cpp deleted file mode 100644 index 5cd61e052a..0000000000 --- a/Generals/Code/Tools/versionUpdate/versionUpdate.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: versionUpdate.cpp ////////////////////////////////////////////////////// -// Generals version number class updater -// Author: Matthew D. Campbell, November 2001 - -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -#define WIN32_LEAN_AND_MEAN // only bare bones windows stuff wanted -#include -#include -#include -#include -#include - -// Local defines -#define VERSION_BUILDNUM "VERSION_LOCALBUILDNUM" -#define VERSION_STRING "LOCAL_BUILD_STRING" -#define VERSION_BUILDUSER "VERSION_BUILDUSER" -#define VERSION_BUILDLOC "VERSION_BUILDLOC" -#define FORMAT "#define " VERSION_STRING " \"%d\"\n" -#define COMMENTS "// Do not modify this file by hand. Auto-created and\n// Updated by versionUpdate.\n" -#define NUMFMT "#define %s %d\n" -#define STRFMT "#define %s \"%s\"\n" - -static void writeVersion(char *file, int build) -{ - FILE *filePtr = fopen(file, "w"); - // Clobber the file. Hey, this is a simple program. - if (file) - { - if (filePtr) - { - unsigned long bufSize = UNLEN + 1; - char userName[UNLEN + 1]; - if (!GetUserName(userName, &bufSize)) - { - strcpy(userName, "unknown"); - } - - bufSize = MAX_COMPUTERNAME_LENGTH + 1; - char computerName[MAX_COMPUTERNAME_LENGTH + 1]; - if (!GetComputerName(computerName, &bufSize)) - { - strcpy(computerName, "unknown"); - } - - printf("Build is by %s at %s\n", userName, computerName); - - fprintf(filePtr, COMMENTS); - fprintf(filePtr, FORMAT, build); - fprintf(filePtr, NUMFMT, VERSION_BUILDNUM, build); - fprintf(filePtr, STRFMT, VERSION_BUILDUSER, userName); - fprintf(filePtr, STRFMT, VERSION_BUILDLOC, computerName); - fclose(filePtr); - } - else - { - printf("Cannot write file\n"); - } - } - else - { - printf("No file to write\n"); - } -} - -static void usage(char *progname) -{ - if (progname) - { - printf ("Usage: %s versionfile.h", progname); - } -} - - -// strtrim ==================================================================== -/** Trim leading and trailing whitespace from a character string (in place). */ -//============================================================================= -static char* strtrim(char* buffer) -{ - if (buffer != NULL) { - // Strip leading white space from the string. - char * source = buffer; - while ((*source != 0) && ((unsigned char)*source <= 32)) - { - source++; - } - - if (source != buffer) - { - strcpy(buffer, source); - } - - // Clip trailing white space from the string. - for (int index = strlen(buffer)-1; index >= 0; index--) - { - if ((*source != 0) && ((unsigned char)buffer[index] <= 32)) - { - buffer[index] = '\0'; - } - else - { - break; - } - } - } - - return buffer; -} - -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR lpCmdLine, - int nCmdShow) -{ - /* - ** Convert WinMain arguments to simple main argc and argv - */ - int argc = 1; - char * argv[20]; - argv[0] = NULL; - - char * token = strtok(lpCmdLine, " "); - while (argc < 20 && token != NULL) - { - argv[argc++] = strtrim(token); - token = strtok(NULL, " "); - } - - int build = 0; - - if (argc != 2) - { - usage(argv[0]); - } - else - { - char *target = argv[argc-1]; - FILE *filePtr; - - if (target) { - filePtr = fopen(target, "r+"); - if (filePtr) - { - char buffer[256]; - char *stringPtr = NULL; - - while (!feof(filePtr)) - { - fread(buffer, 256, 1, filePtr); - if ((stringPtr = strstr(buffer, VERSION_STRING)) != NULL) - { - char *ptr; - - // Looking for '#define VERSION "x.y.z"' - ptr = strtok(stringPtr, " "); // The VERSION - ptr = strtok(NULL, "\n"); // The remainder - - if (*ptr == '\"') - { - ptr++; // Inc past the first " - build = atoi(ptr); - fclose(filePtr); - - build++; - - printf ("Local build is %d\n", build); - writeVersion(target, build); - break; - } else - { - printf ("Local build is 0. Oops, didn't find a string of the format: '#define VERSION \"x.y.z\"'"); - } - } // End if if (strstr - } // End of while - } // End of if filePtr - else - { - // Didn't find the file, write a new one - printf ("Local build is %d\n", build); - writeVersion(target, build); - } - } - } - - return 0; -} \ No newline at end of file diff --git a/Generals/Code/Tools/wolSetup/StdAfx.cpp b/Generals/Code/Tools/wolSetup/StdAfx.cpp deleted file mode 100644 index f6eca7fc98..0000000000 --- a/Generals/Code/Tools/wolSetup/StdAfx.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.cpp : source file that includes just the standard includes -// wolSetup.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "StdAfx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/Generals/Code/Tools/wolSetup/StdAfx.h b/Generals/Code/Tools/wolSetup/StdAfx.h deleted file mode 100644 index fa2af0f513..0000000000 --- a/Generals/Code/Tools/wolSetup/StdAfx.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) -#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -#include - - -// TODO: reference additional headers your program requires here - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/chatdefs.h b/Generals/Code/Tools/wolSetup/WOLAPI/chatdefs.h deleted file mode 100644 index f5395c8326..0000000000 --- a/Generals/Code/Tools/wolSetup/WOLAPI/chatdefs.h +++ /dev/null @@ -1,173 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef CHATDEFS_HEADER -#define CHATDEFS_HEADER - -// gks 11/3/1999: version numbers for SetClientVersion -// GMU 01/12/01 : bumped CHAT_VERSION_MINOR to 15 -// BGC 6/7/01: now version 16 -#define CHAT_VERSION_MAJOR 1 -#define CHAT_VERSION_MINOR 16 - -#define CHAT_VERSION ( ( CHAT_VERSION_MAJOR << 16 ) | ( CHAT_VERSION_MINOR ) ) - -// -// Response errors (Sent as arguments to the OnFoo calls) -// - -// Your nick is still logged into chat -#define CHAT_E_NICKINUSE MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 100) -// Your password is incorrect during login -#define CHAT_E_BADPASS MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 101) -// Reference made to non-existant user or channel -#define CHAT_E_NONESUCH MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 102) -// The network layer is down or cannot be initialized for some reason -#define CHAT_E_CON_NETDOWN MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 103) -// Name lookup (e.g DNS) failed for some reason -#define CHAT_E_CON_LOOKUP_FAILED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 104) -// Some fatal error occured with the net connection -#define CHAT_E_CON_ERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 105) -// General request timeout for a request -#define CHAT_E_TIMEOUT MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 106) -// Must patch before continuing -#define CHAT_E_MUSTPATCH MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 107) -// Miscellaneous internal status error -#define CHAT_E_STATUSERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 108) -// Server has returned something we don't recognise -#define CHAT_E_UNKNOWNRESPONSE MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 109) -// Tried to join a channel that has enough players already -#define CHAT_E_CHANNELFULL MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 110) -// Tried to create a channel that already exists -#define CHAT_E_CHANNELEXISTS MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 111) -// Tried to join a channel that does not exist -#define CHAT_E_CHANNELDOESNOTEXIST MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 112) -// Tried to join a channel with the wrong password -#define CHAT_E_BADCHANNELPASSWORD MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 113) -// You've been banned from the server / channel -#define CHAT_E_BANNED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 114) -// You tried to do something that required operator status -#define CHAT_E_NOT_OPER MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 115) -// Your account is disabled -#define CHAT_E_DISABLED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 116) -// Your serial# has been banned -#define CHAT_E_SERIALBANNED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 117) -// Somebody else is using your serial# -#define CHAT_E_SERIALDUP MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 118) - -// New error codes -- gks 1/10/2000 -// Serial number does not exist in the database -#define CHAT_E_SERIALUNKNOWN MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 119) -// Serial number is for a different product -#define CHAT_E_SKUSERIALMISMATCH MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 120) - -// -// Response success codes (non-error arguments passed to the OnFoo callbacks) -// Note: S_OK is the usual success code - -// A network connection is underway -#define CHAT_S_CON_CONNECTING MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 300) -// A network connection is complete -#define CHAT_S_CON_CONNECTED MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 301) -// A network connection is going down -#define CHAT_S_CON_DISCONNECTING MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 302) -// A network connection is closed -#define CHAT_S_CON_DISCONNECTED MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 303) - - -// Find - Nick not in system -#define CHAT_S_FIND_NOTHERE MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 304) -// Find - Not in any channels -#define CHAT_S_FIND_NOCHAN MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 305) -// Find - user has find turned off -#define CHAT_S_FIND_OFF MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 306) - - -// Page - Nick not in system -#define CHAT_S_PAGE_NOTHERE MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 307) -// Page - user has page turned off -#define CHAT_S_PAGE_OFF MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 308) - -// This channel list is only a ping update -#define CHAT_S_PINGLIST MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 315) - - - - - - - -// -// Request errors (returned from the RequestFoo calls) -// - -// You are not connected to the chat server -#define CHAT_E_NOTCONNECTED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 500) -// You are not in a channel -#define CHAT_E_NOCHANNEL MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 501) -// Feature is not implemented -#define CHAT_E_NOTIMPLEMENTED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 502) -// The request was made while while a conflicting request was still pending -#define CHAT_E_PENDINGREQUEST MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 503) -// Invalid parameter passed - usually a NULL pointer -#define CHAT_E_PARAMERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 504) -// Tried to create or join a channel before leaving the previous one -#define CHAT_E_LEAVECHANNEL MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 508) -// Tried to send something to a channel when not a member of any channel -#define CHAT_E_JOINCHANNEL MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 509) -// Tried to join a non-existant channel -#define CHAT_E_UNKNOWNCHANNEL MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 510) - - -// -// Request success codes -// Notes: S_OK is the usual success code - -// -// Channel list filter values -// - -#define CHAT_CHANNEL_LIST_ALL -99999 - -// -// User flags (bit field) -// -// The owner of the current channel -#define CHAT_USER_CHANNELOWNER 0x0001 -// The person with voice (conch shell...) -#define CHAT_USER_VOICE 0x0002 -// Squelched? -#define CHAT_USER_SQUELCHED 0x0004 -// The local user -#define CHAT_USER_MYSELF 0x8000 - -// -// Channel flags (bit field) -// -#define CHAN_MODE_PRIVATE 0x0004 -#define CHAN_MODE_SECRET 0x0008 -#define CHAN_MODE_MODERATED 0x0010 -#define CHAN_MODE_TOPICLIMIT 0x0020 -#define CHAN_MODE_INVITEONLY 0x0040 -#define CHAN_MODE_NOPRIVMSGS 0x0080 -#define CHAN_MODE_KEY 0x0100 -#define CHAN_MODE_BAN 0x0200 -#define CHAN_MODE_LIMIT 0x0400 - - -#endif diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/downloaddefs.h b/Generals/Code/Tools/wolSetup/WOLAPI/downloaddefs.h deleted file mode 100644 index 726dd71e5f..0000000000 --- a/Generals/Code/Tools/wolSetup/WOLAPI/downloaddefs.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef _DOWNLOADDEFS_H -#define _DOWNLOADDEFS_H - -// CDownload statuses - -#define DOWNLOADSTATUS_NONE 0 -#define DOWNLOADSTATUS_GO 1 -#define DOWNLOADSTATUS_CONNECTING 2 -#define DOWNLOADSTATUS_LOGGINGIN 3 -#define DOWNLOADSTATUS_FINDINGFILE 4 -#define DOWNLOADSTATUS_QUERYINGRESUME 5 -#define DOWNLOADSTATUS_DOWNLOADING 6 -#define DOWNLOADSTATUS_DISCONNECTING 7 -#define DOWNLOADSTATUS_DONE 0 - -// CDownload return codes - -#define DOWNLOAD_SUCCEEDED S_OK -#define DOWNLOAD_PARAMERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 1 ) -#define DOWNLOAD_STATUSERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 2 ) -#define DOWNLOAD_NETWORKERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 3 ) -#define DOWNLOAD_FILEERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 4 ) -#define DOWNLOAD_REENTERERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 4 ) - -// CDownloadEvent return codes. - -#define DOWNLOADEVENT_SUCCEEDED S_OK -#define DOWNLOADEVENT_FAILED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 5 ) -#define DOWNLOADEVENT_RESUME S_OK -#define DOWNLOADEVENT_DONOTRESUME MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 6 ) - -// CDownloadEvent error codes for OnError() - -#define DOWNLOADEVENT_NOSUCHSERVER 1 -#define DOWNLOADEVENT_COULDNOTCONNECT 2 -#define DOWNLOADEVENT_LOGINFAILED 3 -#define DOWNLOADEVENT_NOSUCHFILE 4 -#define DOWNLOADEVENT_LOCALFILEOPENFAILED 5 -#define DOWNLOADEVENT_TCPERROR 6 -#define DOWNLOADEVENT_DISCONNECTERROR 7 - -#endif diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/ftpdefs.h b/Generals/Code/Tools/wolSetup/WOLAPI/ftpdefs.h deleted file mode 100644 index 01ee47d67c..0000000000 --- a/Generals/Code/Tools/wolSetup/WOLAPI/ftpdefs.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __FTPDEFS_H_INCLUDED__ -#define __FTPDEFS_H_INCLUDED__ - - -// CFtp return codes. - -#define FTP_SUCCEEDED S_OK -#define FTP_FAILED MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 1 ) -#define FTP_TRYING MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 2 ) - - -#endif diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/netutildefs.h b/Generals/Code/Tools/wolSetup/WOLAPI/netutildefs.h deleted file mode 100644 index b8239dfbc6..0000000000 --- a/Generals/Code/Tools/wolSetup/WOLAPI/netutildefs.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef NETUTILDEFS_HEADER -#define NETUTILDEFS_HEADER - - -#define NETUTIL_E_ERROR MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 100) -#define NETUTIL_E_BUSY MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 101) -#define NETUTIL_E_TIMEOUT MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 102) - -#define NETUTIL_E_INVALIDFIELD MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 256) -#define NETUTIL_E_CANTVERIFY MAKE_HRESULT( SEVERITY_ERROR, FACILITY_ITF, 257) - -#define NETUTIL_S_FINISHED MAKE_HRESULT( SEVERITY_SUCCESS, FACILITY_ITF, 500) - -#endif diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/wolapi.h b/Generals/Code/Tools/wolSetup/WOLAPI/wolapi.h deleted file mode 100644 index e3f253ff1e..0000000000 --- a/Generals/Code/Tools/wolSetup/WOLAPI/wolapi.h +++ /dev/null @@ -1,5492 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* this ALWAYS GENERATED file contains the definitions for the interfaces */ - - -/* File created by MIDL compiler version 5.01.0164 */ -/* at Mon Nov 05 10:28:33 2001 - */ -/* Compiler settings for .\WOLAPI.idl: - Oicf (OptLev=i2), W1, Zp8, env=Win32, ms_ext, c_ext - error checks: allocation ref bounds_check enum stub_data -*/ -//@@MIDL_FILE_HEADING( ) - - -/* verify that the version is high enough to compile this file*/ -#ifndef __REQUIRED_RPCNDR_H_VERSION__ -#define __REQUIRED_RPCNDR_H_VERSION__ 440 -#endif - -#include "rpc.h" -#include "rpcndr.h" - -#ifndef __RPCNDR_H_VERSION__ -#error this stub requires an updated version of -#endif // __RPCNDR_H_VERSION__ - -#ifndef COM_NO_WINDOWS_H -#include "windows.h" -#include "ole2.h" -#endif /*COM_NO_WINDOWS_H*/ - -#ifndef __WOLAPI_h__ -#define __WOLAPI_h__ - -#ifdef __cplusplus -extern "C"{ -#endif - -/* Forward Declarations */ - -#ifndef __IRTPatcher_FWD_DEFINED__ -#define __IRTPatcher_FWD_DEFINED__ -typedef interface IRTPatcher IRTPatcher; -#endif /* __IRTPatcher_FWD_DEFINED__ */ - - -#ifndef __IRTPatcherEvent_FWD_DEFINED__ -#define __IRTPatcherEvent_FWD_DEFINED__ -typedef interface IRTPatcherEvent IRTPatcherEvent; -#endif /* __IRTPatcherEvent_FWD_DEFINED__ */ - - -#ifndef __IChat_FWD_DEFINED__ -#define __IChat_FWD_DEFINED__ -typedef interface IChat IChat; -#endif /* __IChat_FWD_DEFINED__ */ - - -#ifndef __IChatEvent_FWD_DEFINED__ -#define __IChatEvent_FWD_DEFINED__ -typedef interface IChatEvent IChatEvent; -#endif /* __IChatEvent_FWD_DEFINED__ */ - - -#ifndef __IDownload_FWD_DEFINED__ -#define __IDownload_FWD_DEFINED__ -typedef interface IDownload IDownload; -#endif /* __IDownload_FWD_DEFINED__ */ - - -#ifndef __IDownloadEvent_FWD_DEFINED__ -#define __IDownloadEvent_FWD_DEFINED__ -typedef interface IDownloadEvent IDownloadEvent; -#endif /* __IDownloadEvent_FWD_DEFINED__ */ - - -#ifndef __INetUtil_FWD_DEFINED__ -#define __INetUtil_FWD_DEFINED__ -typedef interface INetUtil INetUtil; -#endif /* __INetUtil_FWD_DEFINED__ */ - - -#ifndef __INetUtilEvent_FWD_DEFINED__ -#define __INetUtilEvent_FWD_DEFINED__ -typedef interface INetUtilEvent INetUtilEvent; -#endif /* __INetUtilEvent_FWD_DEFINED__ */ - - -#ifndef __IChat2_FWD_DEFINED__ -#define __IChat2_FWD_DEFINED__ -typedef interface IChat2 IChat2; -#endif /* __IChat2_FWD_DEFINED__ */ - - -#ifndef __IChat2Event_FWD_DEFINED__ -#define __IChat2Event_FWD_DEFINED__ -typedef interface IChat2Event IChat2Event; -#endif /* __IChat2Event_FWD_DEFINED__ */ - - -#ifndef __IIGROptions_FWD_DEFINED__ -#define __IIGROptions_FWD_DEFINED__ -typedef interface IIGROptions IIGROptions; -#endif /* __IIGROptions_FWD_DEFINED__ */ - - -#ifndef __RTPatcher_FWD_DEFINED__ -#define __RTPatcher_FWD_DEFINED__ - -#ifdef __cplusplus -typedef class RTPatcher RTPatcher; -#else -typedef struct RTPatcher RTPatcher; -#endif /* __cplusplus */ - -#endif /* __RTPatcher_FWD_DEFINED__ */ - - -#ifndef __Chat_FWD_DEFINED__ -#define __Chat_FWD_DEFINED__ - -#ifdef __cplusplus -typedef class Chat Chat; -#else -typedef struct Chat Chat; -#endif /* __cplusplus */ - -#endif /* __Chat_FWD_DEFINED__ */ - - -#ifndef __Download_FWD_DEFINED__ -#define __Download_FWD_DEFINED__ - -#ifdef __cplusplus -typedef class Download Download; -#else -typedef struct Download Download; -#endif /* __cplusplus */ - -#endif /* __Download_FWD_DEFINED__ */ - - -#ifndef __IGROptions_FWD_DEFINED__ -#define __IGROptions_FWD_DEFINED__ - -#ifdef __cplusplus -typedef class IGROptions IGROptions; -#else -typedef struct IGROptions IGROptions; -#endif /* __cplusplus */ - -#endif /* __IGROptions_FWD_DEFINED__ */ - - -#ifndef __NetUtil_FWD_DEFINED__ -#define __NetUtil_FWD_DEFINED__ - -#ifdef __cplusplus -typedef class NetUtil NetUtil; -#else -typedef struct NetUtil NetUtil; -#endif /* __cplusplus */ - -#endif /* __NetUtil_FWD_DEFINED__ */ - - -#ifndef __Chat2_FWD_DEFINED__ -#define __Chat2_FWD_DEFINED__ - -#ifdef __cplusplus -typedef class Chat2 Chat2; -#else -typedef struct Chat2 Chat2; -#endif /* __cplusplus */ - -#endif /* __Chat2_FWD_DEFINED__ */ - - -/* header files for imported files */ -#include "oaidl.h" -#include "ocidl.h" - -void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t); -void __RPC_USER MIDL_user_free( void __RPC_FAR * ); - -#ifndef __IRTPatcher_INTERFACE_DEFINED__ -#define __IRTPatcher_INTERFACE_DEFINED__ - -/* interface IRTPatcher */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_IRTPatcher; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("925CDEDE-71B9-11D1-B1C5-006097176556") - IRTPatcher : public IUnknown - { - public: - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ApplyPatch( - /* [string][in] */ LPCSTR destpath, - /* [string][in] */ LPCSTR filename) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PumpMessages( void) = 0; - - }; - -#else /* C style interface */ - - typedef struct IRTPatcherVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IRTPatcher __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IRTPatcher __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IRTPatcher __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ApplyPatch )( - IRTPatcher __RPC_FAR * This, - /* [string][in] */ LPCSTR destpath, - /* [string][in] */ LPCSTR filename); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *PumpMessages )( - IRTPatcher __RPC_FAR * This); - - END_INTERFACE - } IRTPatcherVtbl; - - interface IRTPatcher - { - CONST_VTBL struct IRTPatcherVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IRTPatcher_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IRTPatcher_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IRTPatcher_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IRTPatcher_ApplyPatch(This,destpath,filename) \ - (This)->lpVtbl -> ApplyPatch(This,destpath,filename) - -#define IRTPatcher_PumpMessages(This) \ - (This)->lpVtbl -> PumpMessages(This) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IRTPatcher_ApplyPatch_Proxy( - IRTPatcher __RPC_FAR * This, - /* [string][in] */ LPCSTR destpath, - /* [string][in] */ LPCSTR filename); - - -void __RPC_STUB IRTPatcher_ApplyPatch_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IRTPatcher_PumpMessages_Proxy( - IRTPatcher __RPC_FAR * This); - - -void __RPC_STUB IRTPatcher_PumpMessages_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IRTPatcher_INTERFACE_DEFINED__ */ - - -#ifndef __IRTPatcherEvent_INTERFACE_DEFINED__ -#define __IRTPatcherEvent_INTERFACE_DEFINED__ - -/* interface IRTPatcherEvent */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_IRTPatcherEvent; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("925CDEE3-71B9-11D1-B1C5-006097176556") - IRTPatcherEvent : public IUnknown - { - public: - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnProgress( - /* [in] */ LPCSTR filename, - /* [in] */ int progress) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnTermination( - /* [in] */ BOOL success) = 0; - - }; - -#else /* C style interface */ - - typedef struct IRTPatcherEventVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IRTPatcherEvent __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IRTPatcherEvent __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IRTPatcherEvent __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnProgress )( - IRTPatcherEvent __RPC_FAR * This, - /* [in] */ LPCSTR filename, - /* [in] */ int progress); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnTermination )( - IRTPatcherEvent __RPC_FAR * This, - /* [in] */ BOOL success); - - END_INTERFACE - } IRTPatcherEventVtbl; - - interface IRTPatcherEvent - { - CONST_VTBL struct IRTPatcherEventVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IRTPatcherEvent_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IRTPatcherEvent_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IRTPatcherEvent_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IRTPatcherEvent_OnProgress(This,filename,progress) \ - (This)->lpVtbl -> OnProgress(This,filename,progress) - -#define IRTPatcherEvent_OnTermination(This,success) \ - (This)->lpVtbl -> OnTermination(This,success) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IRTPatcherEvent_OnProgress_Proxy( - IRTPatcherEvent __RPC_FAR * This, - /* [in] */ LPCSTR filename, - /* [in] */ int progress); - - -void __RPC_STUB IRTPatcherEvent_OnProgress_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IRTPatcherEvent_OnTermination_Proxy( - IRTPatcherEvent __RPC_FAR * This, - /* [in] */ BOOL success); - - -void __RPC_STUB IRTPatcherEvent_OnTermination_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IRTPatcherEvent_INTERFACE_DEFINED__ */ - - -#ifndef __IChat_INTERFACE_DEFINED__ -#define __IChat_INTERFACE_DEFINED__ - -/* interface IChat */ -/* [object][unique][helpstring][uuid] */ - -#if defined(_MSC_VER) && _MSC_VER < 1300 -typedef long time_t; -#endif - -typedef -enum Locale - { LOC_UNKNOWN = 0, - LOC_OTHER = LOC_UNKNOWN + 1, - LOC_USA = LOC_OTHER + 1, - LOC_CANADA = LOC_USA + 1, - LOC_UK = LOC_CANADA + 1, - LOC_GERMANY = LOC_UK + 1, - LOC_FRANCE = LOC_GERMANY + 1, - LOC_SPAIN = LOC_FRANCE + 1, - LOC_NETHERLANDS = LOC_SPAIN + 1, - LOC_BELGIUM = LOC_NETHERLANDS + 1, - LOC_AUSTRIA = LOC_BELGIUM + 1, - LOC_SWITZERLAND = LOC_AUSTRIA + 1, - LOC_ITALY = LOC_SWITZERLAND + 1, - LOC_DENMARK = LOC_ITALY + 1, - LOC_SWEDEN = LOC_DENMARK + 1, - LOC_NORWAY = LOC_SWEDEN + 1, - LOC_FINLAND = LOC_NORWAY + 1, - LOC_ISRAEL = LOC_FINLAND + 1, - LOC_SOUTH_AFRICA = LOC_ISRAEL + 1, - LOC_JAPAN = LOC_SOUTH_AFRICA + 1, - LOC_SOUTH_KOREA = LOC_JAPAN + 1, - LOC_CHINA = LOC_SOUTH_KOREA + 1, - LOC_SINGAPORE = LOC_CHINA + 1, - LOC_TAIWAN = LOC_SINGAPORE + 1, - LOC_MALAYSIA = LOC_TAIWAN + 1, - LOC_AUSTRALIA = LOC_MALAYSIA + 1, - LOC_NEW_ZEALAND = LOC_AUSTRALIA + 1, - LOC_BRAZIL = LOC_NEW_ZEALAND + 1, - LOC_THAILAND = LOC_BRAZIL + 1, - LOC_ARGENTINA = LOC_THAILAND + 1, - LOC_PHILIPPINES = LOC_ARGENTINA + 1, - LOC_GREECE = LOC_PHILIPPINES + 1, - LOC_IRELAND = LOC_GREECE + 1, - LOC_POLAND = LOC_IRELAND + 1, - LOC_PORTUGAL = LOC_POLAND + 1, - LOC_MEXICO = LOC_PORTUGAL + 1, - LOC_RUSSIA = LOC_MEXICO + 1, - LOC_TURKEY = LOC_RUSSIA + 1 - } Locale; - -struct Highscore - { - unsigned int sku; - unsigned int wins; - unsigned int losses; - unsigned int points; - unsigned int rank; - unsigned int accomplishments; - struct Highscore __RPC_FAR *next; - unsigned char login_name[ 40 ]; - }; -struct Ladder - { - unsigned int sku; - unsigned int team_no; - unsigned int wins; - unsigned int losses; - unsigned int points; - unsigned int kills; - unsigned int rank; - unsigned int rung; - unsigned int disconnects; - unsigned int team_rung; - unsigned int provisional; - unsigned int last_game_date; - unsigned int win_streak; - unsigned int reserved1; - unsigned int reserved2; - struct Ladder __RPC_FAR *next; - unsigned char login_name[ 40 ]; - Locale locale; - }; -typedef int GroupID; - -struct Server - { - int gametype; - int chattype; - int timezone; - float longitude; - float lattitude; - struct Server __RPC_FAR *next; - unsigned char name[ 71 ]; - unsigned char connlabel[ 5 ]; - unsigned char conndata[ 128 ]; - unsigned char login[ 10 ]; - unsigned char password[ 10 ]; - }; -struct Channel - { - int type; - unsigned int minUsers; - unsigned int maxUsers; - unsigned int currentUsers; - unsigned int official; - unsigned int tournament; - unsigned int ingame; - unsigned int flags; - unsigned long reserved; - unsigned long ipaddr; - int latency; - int hidden; - struct Channel __RPC_FAR *next; - unsigned char name[ 17 ]; - unsigned char topic[ 81 ]; - unsigned char location[ 65 ]; - unsigned char key[ 9 ]; - unsigned char exInfo[ 41 ]; - }; -struct User - { - unsigned int flags; - GroupID group; - unsigned long reserved; - unsigned long reserved2; - unsigned long reserved3; - unsigned long squadID; - unsigned long ipaddr; - unsigned long squad_icon; - struct User __RPC_FAR *next; - unsigned char name[ 10 ]; - unsigned char squadname[ 41 ]; - unsigned char squadabbrev[ 10 ]; - Locale locale; - int team; - }; -struct Group - { - GroupID ident; - int type; - unsigned int members; - struct Group __RPC_FAR *next; - unsigned char name[ 65 ]; - }; -struct Squad - { - unsigned long id; - int sku; - int members; - int color1; - int color2; - int color3; - int icon1; - int icon2; - int icon3; - struct Squad __RPC_FAR *next; - int rank; - int team; - int status; - unsigned char email[ 81 ]; - unsigned char icq[ 17 ]; - unsigned char motto[ 81 ]; - unsigned char url[ 129 ]; - unsigned char name[ 41 ]; - unsigned char abbreviation[ 41 ]; - }; -struct Update - { - unsigned long SKU; - unsigned long version; - int required; - struct Update __RPC_FAR *next; - unsigned char server[ 65 ]; - unsigned char patchpath[ 256 ]; - unsigned char patchfile[ 33 ]; - unsigned char login[ 33 ]; - unsigned char password[ 65 ]; - unsigned char localpath[ 256 ]; - }; -typedef struct Server Server; - -typedef struct Channel Channel; - -typedef struct User User; - -typedef struct Group Group; - -typedef struct Update Update; - -typedef struct Ladder Ladder; - -typedef struct Highscore Highscore; - -typedef struct Squad Squad; - - -EXTERN_C const IID IID_IChat; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("4DD3BAF4-7579-11D1-B1C6-006097176556") - IChat : public IUnknown - { - public: - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PumpMessages( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestServerList( - /* [in] */ unsigned long SKU, - /* [in] */ unsigned long current_version, - /* [in] */ LPCSTR loginname, - /* [in] */ LPCSTR password, - /* [in] */ int timeout) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestConnection( - /* [in] */ Server __RPC_FAR *server, - /* [in] */ int timeout, - int domangle) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelList( - /* [in] */ int channelType, - /* [in] */ int autoping) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelCreate( - /* [in] */ Channel __RPC_FAR *channel) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelJoin( - /* [in] */ Channel __RPC_FAR *channel) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelLeave( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUserList( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPublicMessage( - /* [in] */ LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPrivateMessage( - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestLogout( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPrivateGameOptions( - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR options) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPublicGameOptions( - /* [in] */ LPCSTR options) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPublicAction( - /* [in] */ LPCSTR action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPrivateAction( - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestGameStart( - /* [in] */ User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelTopic( - /* [in] */ LPCSTR topic) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetVersion( - /* [in] */ unsigned long __RPC_FAR *version) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUserKick( - /* [in] */ User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUserIP( - /* [in] */ User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetGametypeInfo( - unsigned int gtype, - int icon_size, - unsigned char __RPC_FAR *__RPC_FAR *bitmap, - int __RPC_FAR *bmp_bytes, - LPCSTR __RPC_FAR *name, - LPCSTR __RPC_FAR *URL) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestFind( - User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPage( - User __RPC_FAR *user, - LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetFindPage( - int findOn, - int pageOn) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetSquelch( - User __RPC_FAR *user, - int squelch) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetSquelch( - User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetChannelFilter( - int channelType) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestGameEnd( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetLangFilter( - int onoff) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelBan( - LPCSTR name, - int ban) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetGametypeList( - LPCSTR __RPC_FAR *list) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetHelpURL( - LPCSTR __RPC_FAR *url) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetProductSKU( - unsigned long SKU) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetNick( - int num, - LPCSTR __RPC_FAR *nick, - LPCSTR __RPC_FAR *pass) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetNick( - int num, - LPCSTR nick, - LPCSTR pass, - int domangle) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetLobbyCount( - int __RPC_FAR *count) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestRawMessage( - LPCSTR ircmsg) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetAttributeValue( - LPCSTR attrib, - LPCSTR __RPC_FAR *value) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetAttributeValue( - LPCSTR attrib, - LPCSTR value) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetChannelExInfo( - LPCSTR info) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE StopAutoping( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestSquadInfo( - unsigned long id) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestSetTeam( - int team) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestSetLocale( - Locale locale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUserLocale( - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUserTeam( - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetNickLocale( - int nicknum, - Locale __RPC_FAR *locale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetNickLocale( - int nicknum, - Locale locale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetLocaleString( - LPCSTR __RPC_FAR *loc_string, - Locale locale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetLocaleCount( - int __RPC_FAR *num) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetClientVersion( - unsigned long version) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetCodepageFilter( - int filter) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestBuddyList( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestBuddyAdd( - User __RPC_FAR *newbuddy) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestBuddyDelete( - User __RPC_FAR *buddy) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPublicUnicodeMessage( - /* [in] */ const unsigned short __RPC_FAR *message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPrivateUnicodeMessage( - /* [in] */ User __RPC_FAR *users, - /* [in] */ const unsigned short __RPC_FAR *message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPublicUnicodeAction( - /* [in] */ const unsigned short __RPC_FAR *action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestPrivateUnicodeAction( - /* [in] */ User __RPC_FAR *users, - /* [in] */ const unsigned short __RPC_FAR *action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUnicodePage( - User __RPC_FAR *user, - const unsigned short __RPC_FAR *message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestSetPlayerCount( - unsigned int currentPlayers, - unsigned int maxPlayers) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestServerTime( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestInsiderStatus( - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestSetLocalIP( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestSquadByName( - LPCSTR name) = 0; - - }; - -#else /* C style interface */ - - typedef struct IChatVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IChat __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IChat __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *PumpMessages )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestServerList )( - IChat __RPC_FAR * This, - /* [in] */ unsigned long SKU, - /* [in] */ unsigned long current_version, - /* [in] */ LPCSTR loginname, - /* [in] */ LPCSTR password, - /* [in] */ int timeout); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestConnection )( - IChat __RPC_FAR * This, - /* [in] */ Server __RPC_FAR *server, - /* [in] */ int timeout, - int domangle); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelList )( - IChat __RPC_FAR * This, - /* [in] */ int channelType, - /* [in] */ int autoping); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelCreate )( - IChat __RPC_FAR * This, - /* [in] */ Channel __RPC_FAR *channel); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelJoin )( - IChat __RPC_FAR * This, - /* [in] */ Channel __RPC_FAR *channel); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelLeave )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUserList )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPublicMessage )( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPrivateMessage )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestLogout )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPrivateGameOptions )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR options); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPublicGameOptions )( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR options); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPublicAction )( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPrivateAction )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestGameStart )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelTopic )( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR topic); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetVersion )( - IChat __RPC_FAR * This, - /* [in] */ unsigned long __RPC_FAR *version); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUserKick )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUserIP )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetGametypeInfo )( - IChat __RPC_FAR * This, - unsigned int gtype, - int icon_size, - unsigned char __RPC_FAR *__RPC_FAR *bitmap, - int __RPC_FAR *bmp_bytes, - LPCSTR __RPC_FAR *name, - LPCSTR __RPC_FAR *URL); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestFind )( - IChat __RPC_FAR * This, - User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPage )( - IChat __RPC_FAR * This, - User __RPC_FAR *user, - LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetFindPage )( - IChat __RPC_FAR * This, - int findOn, - int pageOn); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetSquelch )( - IChat __RPC_FAR * This, - User __RPC_FAR *user, - int squelch); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSquelch )( - IChat __RPC_FAR * This, - User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetChannelFilter )( - IChat __RPC_FAR * This, - int channelType); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestGameEnd )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetLangFilter )( - IChat __RPC_FAR * This, - int onoff); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelBan )( - IChat __RPC_FAR * This, - LPCSTR name, - int ban); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetGametypeList )( - IChat __RPC_FAR * This, - LPCSTR __RPC_FAR *list); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetHelpURL )( - IChat __RPC_FAR * This, - LPCSTR __RPC_FAR *url); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetProductSKU )( - IChat __RPC_FAR * This, - unsigned long SKU); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNick )( - IChat __RPC_FAR * This, - int num, - LPCSTR __RPC_FAR *nick, - LPCSTR __RPC_FAR *pass); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetNick )( - IChat __RPC_FAR * This, - int num, - LPCSTR nick, - LPCSTR pass, - int domangle); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetLobbyCount )( - IChat __RPC_FAR * This, - int __RPC_FAR *count); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestRawMessage )( - IChat __RPC_FAR * This, - LPCSTR ircmsg); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetAttributeValue )( - IChat __RPC_FAR * This, - LPCSTR attrib, - LPCSTR __RPC_FAR *value); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetAttributeValue )( - IChat __RPC_FAR * This, - LPCSTR attrib, - LPCSTR value); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetChannelExInfo )( - IChat __RPC_FAR * This, - LPCSTR info); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *StopAutoping )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestSquadInfo )( - IChat __RPC_FAR * This, - unsigned long id); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestSetTeam )( - IChat __RPC_FAR * This, - int team); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestSetLocale )( - IChat __RPC_FAR * This, - Locale locale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUserLocale )( - IChat __RPC_FAR * This, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUserTeam )( - IChat __RPC_FAR * This, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNickLocale )( - IChat __RPC_FAR * This, - int nicknum, - Locale __RPC_FAR *locale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetNickLocale )( - IChat __RPC_FAR * This, - int nicknum, - Locale locale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetLocaleString )( - IChat __RPC_FAR * This, - LPCSTR __RPC_FAR *loc_string, - Locale locale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetLocaleCount )( - IChat __RPC_FAR * This, - int __RPC_FAR *num); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetClientVersion )( - IChat __RPC_FAR * This, - unsigned long version); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetCodepageFilter )( - IChat __RPC_FAR * This, - int filter); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestBuddyList )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestBuddyAdd )( - IChat __RPC_FAR * This, - User __RPC_FAR *newbuddy); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestBuddyDelete )( - IChat __RPC_FAR * This, - User __RPC_FAR *buddy); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPublicUnicodeMessage )( - IChat __RPC_FAR * This, - /* [in] */ const unsigned short __RPC_FAR *message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPrivateUnicodeMessage )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ const unsigned short __RPC_FAR *message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPublicUnicodeAction )( - IChat __RPC_FAR * This, - /* [in] */ const unsigned short __RPC_FAR *action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPrivateUnicodeAction )( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ const unsigned short __RPC_FAR *action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUnicodePage )( - IChat __RPC_FAR * This, - User __RPC_FAR *user, - const unsigned short __RPC_FAR *message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestSetPlayerCount )( - IChat __RPC_FAR * This, - unsigned int currentPlayers, - unsigned int maxPlayers); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestServerTime )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestInsiderStatus )( - IChat __RPC_FAR * This, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestSetLocalIP )( - IChat __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestSquadByName )( - IChat __RPC_FAR * This, - LPCSTR name); - - END_INTERFACE - } IChatVtbl; - - interface IChat - { - CONST_VTBL struct IChatVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IChat_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IChat_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IChat_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IChat_PumpMessages(This) \ - (This)->lpVtbl -> PumpMessages(This) - -#define IChat_RequestServerList(This,SKU,current_version,loginname,password,timeout) \ - (This)->lpVtbl -> RequestServerList(This,SKU,current_version,loginname,password,timeout) - -#define IChat_RequestConnection(This,server,timeout,domangle) \ - (This)->lpVtbl -> RequestConnection(This,server,timeout,domangle) - -#define IChat_RequestChannelList(This,channelType,autoping) \ - (This)->lpVtbl -> RequestChannelList(This,channelType,autoping) - -#define IChat_RequestChannelCreate(This,channel) \ - (This)->lpVtbl -> RequestChannelCreate(This,channel) - -#define IChat_RequestChannelJoin(This,channel) \ - (This)->lpVtbl -> RequestChannelJoin(This,channel) - -#define IChat_RequestChannelLeave(This) \ - (This)->lpVtbl -> RequestChannelLeave(This) - -#define IChat_RequestUserList(This) \ - (This)->lpVtbl -> RequestUserList(This) - -#define IChat_RequestPublicMessage(This,message) \ - (This)->lpVtbl -> RequestPublicMessage(This,message) - -#define IChat_RequestPrivateMessage(This,users,message) \ - (This)->lpVtbl -> RequestPrivateMessage(This,users,message) - -#define IChat_RequestLogout(This) \ - (This)->lpVtbl -> RequestLogout(This) - -#define IChat_RequestPrivateGameOptions(This,users,options) \ - (This)->lpVtbl -> RequestPrivateGameOptions(This,users,options) - -#define IChat_RequestPublicGameOptions(This,options) \ - (This)->lpVtbl -> RequestPublicGameOptions(This,options) - -#define IChat_RequestPublicAction(This,action) \ - (This)->lpVtbl -> RequestPublicAction(This,action) - -#define IChat_RequestPrivateAction(This,users,action) \ - (This)->lpVtbl -> RequestPrivateAction(This,users,action) - -#define IChat_RequestGameStart(This,users) \ - (This)->lpVtbl -> RequestGameStart(This,users) - -#define IChat_RequestChannelTopic(This,topic) \ - (This)->lpVtbl -> RequestChannelTopic(This,topic) - -#define IChat_GetVersion(This,version) \ - (This)->lpVtbl -> GetVersion(This,version) - -#define IChat_RequestUserKick(This,user) \ - (This)->lpVtbl -> RequestUserKick(This,user) - -#define IChat_RequestUserIP(This,user) \ - (This)->lpVtbl -> RequestUserIP(This,user) - -#define IChat_GetGametypeInfo(This,gtype,icon_size,bitmap,bmp_bytes,name,URL) \ - (This)->lpVtbl -> GetGametypeInfo(This,gtype,icon_size,bitmap,bmp_bytes,name,URL) - -#define IChat_RequestFind(This,user) \ - (This)->lpVtbl -> RequestFind(This,user) - -#define IChat_RequestPage(This,user,message) \ - (This)->lpVtbl -> RequestPage(This,user,message) - -#define IChat_SetFindPage(This,findOn,pageOn) \ - (This)->lpVtbl -> SetFindPage(This,findOn,pageOn) - -#define IChat_SetSquelch(This,user,squelch) \ - (This)->lpVtbl -> SetSquelch(This,user,squelch) - -#define IChat_GetSquelch(This,user) \ - (This)->lpVtbl -> GetSquelch(This,user) - -#define IChat_SetChannelFilter(This,channelType) \ - (This)->lpVtbl -> SetChannelFilter(This,channelType) - -#define IChat_RequestGameEnd(This) \ - (This)->lpVtbl -> RequestGameEnd(This) - -#define IChat_SetLangFilter(This,onoff) \ - (This)->lpVtbl -> SetLangFilter(This,onoff) - -#define IChat_RequestChannelBan(This,name,ban) \ - (This)->lpVtbl -> RequestChannelBan(This,name,ban) - -#define IChat_GetGametypeList(This,list) \ - (This)->lpVtbl -> GetGametypeList(This,list) - -#define IChat_GetHelpURL(This,url) \ - (This)->lpVtbl -> GetHelpURL(This,url) - -#define IChat_SetProductSKU(This,SKU) \ - (This)->lpVtbl -> SetProductSKU(This,SKU) - -#define IChat_GetNick(This,num,nick,pass) \ - (This)->lpVtbl -> GetNick(This,num,nick,pass) - -#define IChat_SetNick(This,num,nick,pass,domangle) \ - (This)->lpVtbl -> SetNick(This,num,nick,pass,domangle) - -#define IChat_GetLobbyCount(This,count) \ - (This)->lpVtbl -> GetLobbyCount(This,count) - -#define IChat_RequestRawMessage(This,ircmsg) \ - (This)->lpVtbl -> RequestRawMessage(This,ircmsg) - -#define IChat_GetAttributeValue(This,attrib,value) \ - (This)->lpVtbl -> GetAttributeValue(This,attrib,value) - -#define IChat_SetAttributeValue(This,attrib,value) \ - (This)->lpVtbl -> SetAttributeValue(This,attrib,value) - -#define IChat_SetChannelExInfo(This,info) \ - (This)->lpVtbl -> SetChannelExInfo(This,info) - -#define IChat_StopAutoping(This) \ - (This)->lpVtbl -> StopAutoping(This) - -#define IChat_RequestSquadInfo(This,id) \ - (This)->lpVtbl -> RequestSquadInfo(This,id) - -#define IChat_RequestSetTeam(This,team) \ - (This)->lpVtbl -> RequestSetTeam(This,team) - -#define IChat_RequestSetLocale(This,locale) \ - (This)->lpVtbl -> RequestSetLocale(This,locale) - -#define IChat_RequestUserLocale(This,users) \ - (This)->lpVtbl -> RequestUserLocale(This,users) - -#define IChat_RequestUserTeam(This,users) \ - (This)->lpVtbl -> RequestUserTeam(This,users) - -#define IChat_GetNickLocale(This,nicknum,locale) \ - (This)->lpVtbl -> GetNickLocale(This,nicknum,locale) - -#define IChat_SetNickLocale(This,nicknum,locale) \ - (This)->lpVtbl -> SetNickLocale(This,nicknum,locale) - -#define IChat_GetLocaleString(This,loc_string,locale) \ - (This)->lpVtbl -> GetLocaleString(This,loc_string,locale) - -#define IChat_GetLocaleCount(This,num) \ - (This)->lpVtbl -> GetLocaleCount(This,num) - -#define IChat_SetClientVersion(This,version) \ - (This)->lpVtbl -> SetClientVersion(This,version) - -#define IChat_SetCodepageFilter(This,filter) \ - (This)->lpVtbl -> SetCodepageFilter(This,filter) - -#define IChat_RequestBuddyList(This) \ - (This)->lpVtbl -> RequestBuddyList(This) - -#define IChat_RequestBuddyAdd(This,newbuddy) \ - (This)->lpVtbl -> RequestBuddyAdd(This,newbuddy) - -#define IChat_RequestBuddyDelete(This,buddy) \ - (This)->lpVtbl -> RequestBuddyDelete(This,buddy) - -#define IChat_RequestPublicUnicodeMessage(This,message) \ - (This)->lpVtbl -> RequestPublicUnicodeMessage(This,message) - -#define IChat_RequestPrivateUnicodeMessage(This,users,message) \ - (This)->lpVtbl -> RequestPrivateUnicodeMessage(This,users,message) - -#define IChat_RequestPublicUnicodeAction(This,action) \ - (This)->lpVtbl -> RequestPublicUnicodeAction(This,action) - -#define IChat_RequestPrivateUnicodeAction(This,users,action) \ - (This)->lpVtbl -> RequestPrivateUnicodeAction(This,users,action) - -#define IChat_RequestUnicodePage(This,user,message) \ - (This)->lpVtbl -> RequestUnicodePage(This,user,message) - -#define IChat_RequestSetPlayerCount(This,currentPlayers,maxPlayers) \ - (This)->lpVtbl -> RequestSetPlayerCount(This,currentPlayers,maxPlayers) - -#define IChat_RequestServerTime(This) \ - (This)->lpVtbl -> RequestServerTime(This) - -#define IChat_RequestInsiderStatus(This,users) \ - (This)->lpVtbl -> RequestInsiderStatus(This,users) - -#define IChat_RequestSetLocalIP(This) \ - (This)->lpVtbl -> RequestSetLocalIP(This) - -#define IChat_RequestSquadByName(This,name) \ - (This)->lpVtbl -> RequestSquadByName(This,name) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_PumpMessages_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_PumpMessages_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestServerList_Proxy( - IChat __RPC_FAR * This, - /* [in] */ unsigned long SKU, - /* [in] */ unsigned long current_version, - /* [in] */ LPCSTR loginname, - /* [in] */ LPCSTR password, - /* [in] */ int timeout); - - -void __RPC_STUB IChat_RequestServerList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestConnection_Proxy( - IChat __RPC_FAR * This, - /* [in] */ Server __RPC_FAR *server, - /* [in] */ int timeout, - int domangle); - - -void __RPC_STUB IChat_RequestConnection_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestChannelList_Proxy( - IChat __RPC_FAR * This, - /* [in] */ int channelType, - /* [in] */ int autoping); - - -void __RPC_STUB IChat_RequestChannelList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestChannelCreate_Proxy( - IChat __RPC_FAR * This, - /* [in] */ Channel __RPC_FAR *channel); - - -void __RPC_STUB IChat_RequestChannelCreate_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestChannelJoin_Proxy( - IChat __RPC_FAR * This, - /* [in] */ Channel __RPC_FAR *channel); - - -void __RPC_STUB IChat_RequestChannelJoin_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestChannelLeave_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestChannelLeave_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestUserList_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestUserList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPublicMessage_Proxy( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR message); - - -void __RPC_STUB IChat_RequestPublicMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPrivateMessage_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR message); - - -void __RPC_STUB IChat_RequestPrivateMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestLogout_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestLogout_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPrivateGameOptions_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR options); - - -void __RPC_STUB IChat_RequestPrivateGameOptions_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPublicGameOptions_Proxy( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR options); - - -void __RPC_STUB IChat_RequestPublicGameOptions_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPublicAction_Proxy( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR action); - - -void __RPC_STUB IChat_RequestPublicAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPrivateAction_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ LPCSTR action); - - -void __RPC_STUB IChat_RequestPrivateAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestGameStart_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users); - - -void __RPC_STUB IChat_RequestGameStart_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestChannelTopic_Proxy( - IChat __RPC_FAR * This, - /* [in] */ LPCSTR topic); - - -void __RPC_STUB IChat_RequestChannelTopic_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetVersion_Proxy( - IChat __RPC_FAR * This, - /* [in] */ unsigned long __RPC_FAR *version); - - -void __RPC_STUB IChat_GetVersion_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestUserKick_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *user); - - -void __RPC_STUB IChat_RequestUserKick_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestUserIP_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *user); - - -void __RPC_STUB IChat_RequestUserIP_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetGametypeInfo_Proxy( - IChat __RPC_FAR * This, - unsigned int gtype, - int icon_size, - unsigned char __RPC_FAR *__RPC_FAR *bitmap, - int __RPC_FAR *bmp_bytes, - LPCSTR __RPC_FAR *name, - LPCSTR __RPC_FAR *URL); - - -void __RPC_STUB IChat_GetGametypeInfo_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestFind_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *user); - - -void __RPC_STUB IChat_RequestFind_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPage_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *user, - LPCSTR message); - - -void __RPC_STUB IChat_RequestPage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetFindPage_Proxy( - IChat __RPC_FAR * This, - int findOn, - int pageOn); - - -void __RPC_STUB IChat_SetFindPage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetSquelch_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *user, - int squelch); - - -void __RPC_STUB IChat_SetSquelch_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetSquelch_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *user); - - -void __RPC_STUB IChat_GetSquelch_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetChannelFilter_Proxy( - IChat __RPC_FAR * This, - int channelType); - - -void __RPC_STUB IChat_SetChannelFilter_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestGameEnd_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestGameEnd_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetLangFilter_Proxy( - IChat __RPC_FAR * This, - int onoff); - - -void __RPC_STUB IChat_SetLangFilter_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestChannelBan_Proxy( - IChat __RPC_FAR * This, - LPCSTR name, - int ban); - - -void __RPC_STUB IChat_RequestChannelBan_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetGametypeList_Proxy( - IChat __RPC_FAR * This, - LPCSTR __RPC_FAR *list); - - -void __RPC_STUB IChat_GetGametypeList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetHelpURL_Proxy( - IChat __RPC_FAR * This, - LPCSTR __RPC_FAR *url); - - -void __RPC_STUB IChat_GetHelpURL_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetProductSKU_Proxy( - IChat __RPC_FAR * This, - unsigned long SKU); - - -void __RPC_STUB IChat_SetProductSKU_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetNick_Proxy( - IChat __RPC_FAR * This, - int num, - LPCSTR __RPC_FAR *nick, - LPCSTR __RPC_FAR *pass); - - -void __RPC_STUB IChat_GetNick_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetNick_Proxy( - IChat __RPC_FAR * This, - int num, - LPCSTR nick, - LPCSTR pass, - int domangle); - - -void __RPC_STUB IChat_SetNick_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetLobbyCount_Proxy( - IChat __RPC_FAR * This, - int __RPC_FAR *count); - - -void __RPC_STUB IChat_GetLobbyCount_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestRawMessage_Proxy( - IChat __RPC_FAR * This, - LPCSTR ircmsg); - - -void __RPC_STUB IChat_RequestRawMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetAttributeValue_Proxy( - IChat __RPC_FAR * This, - LPCSTR attrib, - LPCSTR __RPC_FAR *value); - - -void __RPC_STUB IChat_GetAttributeValue_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetAttributeValue_Proxy( - IChat __RPC_FAR * This, - LPCSTR attrib, - LPCSTR value); - - -void __RPC_STUB IChat_SetAttributeValue_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetChannelExInfo_Proxy( - IChat __RPC_FAR * This, - LPCSTR info); - - -void __RPC_STUB IChat_SetChannelExInfo_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_StopAutoping_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_StopAutoping_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestSquadInfo_Proxy( - IChat __RPC_FAR * This, - unsigned long id); - - -void __RPC_STUB IChat_RequestSquadInfo_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestSetTeam_Proxy( - IChat __RPC_FAR * This, - int team); - - -void __RPC_STUB IChat_RequestSetTeam_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestSetLocale_Proxy( - IChat __RPC_FAR * This, - Locale locale); - - -void __RPC_STUB IChat_RequestSetLocale_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestUserLocale_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *users); - - -void __RPC_STUB IChat_RequestUserLocale_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestUserTeam_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *users); - - -void __RPC_STUB IChat_RequestUserTeam_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetNickLocale_Proxy( - IChat __RPC_FAR * This, - int nicknum, - Locale __RPC_FAR *locale); - - -void __RPC_STUB IChat_GetNickLocale_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetNickLocale_Proxy( - IChat __RPC_FAR * This, - int nicknum, - Locale locale); - - -void __RPC_STUB IChat_SetNickLocale_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetLocaleString_Proxy( - IChat __RPC_FAR * This, - LPCSTR __RPC_FAR *loc_string, - Locale locale); - - -void __RPC_STUB IChat_GetLocaleString_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_GetLocaleCount_Proxy( - IChat __RPC_FAR * This, - int __RPC_FAR *num); - - -void __RPC_STUB IChat_GetLocaleCount_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetClientVersion_Proxy( - IChat __RPC_FAR * This, - unsigned long version); - - -void __RPC_STUB IChat_SetClientVersion_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_SetCodepageFilter_Proxy( - IChat __RPC_FAR * This, - int filter); - - -void __RPC_STUB IChat_SetCodepageFilter_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestBuddyList_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestBuddyList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestBuddyAdd_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *newbuddy); - - -void __RPC_STUB IChat_RequestBuddyAdd_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestBuddyDelete_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *buddy); - - -void __RPC_STUB IChat_RequestBuddyDelete_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPublicUnicodeMessage_Proxy( - IChat __RPC_FAR * This, - /* [in] */ const unsigned short __RPC_FAR *message); - - -void __RPC_STUB IChat_RequestPublicUnicodeMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPrivateUnicodeMessage_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ const unsigned short __RPC_FAR *message); - - -void __RPC_STUB IChat_RequestPrivateUnicodeMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPublicUnicodeAction_Proxy( - IChat __RPC_FAR * This, - /* [in] */ const unsigned short __RPC_FAR *action); - - -void __RPC_STUB IChat_RequestPublicUnicodeAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestPrivateUnicodeAction_Proxy( - IChat __RPC_FAR * This, - /* [in] */ User __RPC_FAR *users, - /* [in] */ const unsigned short __RPC_FAR *action); - - -void __RPC_STUB IChat_RequestPrivateUnicodeAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestUnicodePage_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *user, - const unsigned short __RPC_FAR *message); - - -void __RPC_STUB IChat_RequestUnicodePage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestSetPlayerCount_Proxy( - IChat __RPC_FAR * This, - unsigned int currentPlayers, - unsigned int maxPlayers); - - -void __RPC_STUB IChat_RequestSetPlayerCount_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestServerTime_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestServerTime_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestInsiderStatus_Proxy( - IChat __RPC_FAR * This, - User __RPC_FAR *users); - - -void __RPC_STUB IChat_RequestInsiderStatus_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestSetLocalIP_Proxy( - IChat __RPC_FAR * This); - - -void __RPC_STUB IChat_RequestSetLocalIP_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat_RequestSquadByName_Proxy( - IChat __RPC_FAR * This, - LPCSTR name); - - -void __RPC_STUB IChat_RequestSquadByName_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IChat_INTERFACE_DEFINED__ */ - - -#ifndef __IChatEvent_INTERFACE_DEFINED__ -#define __IChatEvent_INTERFACE_DEFINED__ - -/* interface IChatEvent */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_IChatEvent; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("4DD3BAF6-7579-11D1-B1C6-006097176556") - IChatEvent : public IUnknown - { - public: - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnServerList( - /* [in] */ HRESULT res, - /* [in] */ Server __RPC_FAR *servers) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUpdateList( - /* [in] */ HRESULT res, - /* [in] */ Update __RPC_FAR *updates) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnServerError( - /* [in] */ HRESULT res, - /* [in] */ LPCSTR ircmsg) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnConnection( - /* [in] */ HRESULT res, - /* [in] */ LPCSTR motd) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnMessageOfTheDay( - /* [in] */ HRESULT res, - /* [in] */ LPCSTR motd) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelList( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channels) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelCreate( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelJoin( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelLeave( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelTopic( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ LPCSTR topic) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPrivateAction( - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPublicAction( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - User __RPC_FAR *user, - /* [in] */ LPCSTR action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserList( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPublicMessage( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPrivateMessage( - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnSystemMessage( - /* [in] */ HRESULT res, - /* [in] */ LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnNetStatus( - /* [in] */ HRESULT res) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnLogout( - /* [in] */ HRESULT status, - /* [in] */ User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPrivateGameOptions( - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR options) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPublicGameOptions( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR options) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnGameStart( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *users, - /* [in] */ int gameid) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserKick( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *kicked, - /* [in] */ User __RPC_FAR *kicker) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserIP( - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnFind( - HRESULT res, - Channel __RPC_FAR *chan) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPageSend( - HRESULT res) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPaged( - HRESULT res, - User __RPC_FAR *user, - LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnServerBannedYou( - HRESULT res, - time_t bannedTill) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserFlags( - HRESULT res, - LPCSTR name, - unsigned int flags, - unsigned int mask) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelBan( - HRESULT res, - LPCSTR name, - int banned) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnSquadInfo( - HRESULT res, - unsigned long id, - Squad __RPC_FAR *squad) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserLocale( - HRESULT res, - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserTeam( - HRESULT res, - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnSetLocale( - HRESULT res, - Locale newlocale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnSetTeam( - HRESULT res, - int newteam) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnBuddyList( - HRESULT res, - User __RPC_FAR *buddy_list) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnBuddyAdd( - HRESULT res, - User __RPC_FAR *buddy_added) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnBuddyDelete( - HRESULT res, - User __RPC_FAR *buddy_deleted) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPublicUnicodeMessage( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPrivateUnicodeMessage( - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPrivateUnicodeAction( - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPublicUnicodeAction( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *action) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnPagedUnicode( - HRESULT res, - User __RPC_FAR *user, - const unsigned short __RPC_FAR *message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnServerTime( - HRESULT res, - time_t stime) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnInsiderStatus( - HRESULT res, - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnSetLocalIP( - HRESULT res, - LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelListBegin( - /* [in] */ HRESULT res) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelListEntry( - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelListEnd( - /* [in] */ HRESULT res) = 0; - - }; - -#else /* C style interface */ - - typedef struct IChatEventVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IChatEvent __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IChatEvent __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IChatEvent __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnServerList )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Server __RPC_FAR *servers); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUpdateList )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Update __RPC_FAR *updates); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnServerError )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR ircmsg); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnConnection )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR motd); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnMessageOfTheDay )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR motd); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelList )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channels); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelCreate )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelJoin )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelLeave )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelTopic )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ LPCSTR topic); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPrivateAction )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPublicAction )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - User __RPC_FAR *user, - /* [in] */ LPCSTR action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserList )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPublicMessage )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPrivateMessage )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnSystemMessage )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnNetStatus )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnLogout )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT status, - /* [in] */ User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPrivateGameOptions )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR options); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPublicGameOptions )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR options); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnGameStart )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *users, - /* [in] */ int gameid); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserKick )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *kicked, - /* [in] */ User __RPC_FAR *kicker); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserIP )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnFind )( - IChatEvent __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPageSend )( - IChatEvent __RPC_FAR * This, - HRESULT res); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPaged )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *user, - LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnServerBannedYou )( - IChatEvent __RPC_FAR * This, - HRESULT res, - time_t bannedTill); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserFlags )( - IChatEvent __RPC_FAR * This, - HRESULT res, - LPCSTR name, - unsigned int flags, - unsigned int mask); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelBan )( - IChatEvent __RPC_FAR * This, - HRESULT res, - LPCSTR name, - int banned); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnSquadInfo )( - IChatEvent __RPC_FAR * This, - HRESULT res, - unsigned long id, - Squad __RPC_FAR *squad); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserLocale )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserTeam )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnSetLocale )( - IChatEvent __RPC_FAR * This, - HRESULT res, - Locale newlocale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnSetTeam )( - IChatEvent __RPC_FAR * This, - HRESULT res, - int newteam); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnBuddyList )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *buddy_list); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnBuddyAdd )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *buddy_added); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnBuddyDelete )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *buddy_deleted); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPublicUnicodeMessage )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPrivateUnicodeMessage )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPrivateUnicodeAction )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPublicUnicodeAction )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *action); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPagedUnicode )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *user, - const unsigned short __RPC_FAR *message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnServerTime )( - IChatEvent __RPC_FAR * This, - HRESULT res, - time_t stime); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnInsiderStatus )( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnSetLocalIP )( - IChatEvent __RPC_FAR * This, - HRESULT res, - LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelListBegin )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelListEntry )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelListEnd )( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res); - - END_INTERFACE - } IChatEventVtbl; - - interface IChatEvent - { - CONST_VTBL struct IChatEventVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IChatEvent_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IChatEvent_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IChatEvent_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IChatEvent_OnServerList(This,res,servers) \ - (This)->lpVtbl -> OnServerList(This,res,servers) - -#define IChatEvent_OnUpdateList(This,res,updates) \ - (This)->lpVtbl -> OnUpdateList(This,res,updates) - -#define IChatEvent_OnServerError(This,res,ircmsg) \ - (This)->lpVtbl -> OnServerError(This,res,ircmsg) - -#define IChatEvent_OnConnection(This,res,motd) \ - (This)->lpVtbl -> OnConnection(This,res,motd) - -#define IChatEvent_OnMessageOfTheDay(This,res,motd) \ - (This)->lpVtbl -> OnMessageOfTheDay(This,res,motd) - -#define IChatEvent_OnChannelList(This,res,channels) \ - (This)->lpVtbl -> OnChannelList(This,res,channels) - -#define IChatEvent_OnChannelCreate(This,res,channel) \ - (This)->lpVtbl -> OnChannelCreate(This,res,channel) - -#define IChatEvent_OnChannelJoin(This,res,channel,user) \ - (This)->lpVtbl -> OnChannelJoin(This,res,channel,user) - -#define IChatEvent_OnChannelLeave(This,res,channel,user) \ - (This)->lpVtbl -> OnChannelLeave(This,res,channel,user) - -#define IChatEvent_OnChannelTopic(This,res,channel,topic) \ - (This)->lpVtbl -> OnChannelTopic(This,res,channel,topic) - -#define IChatEvent_OnPrivateAction(This,res,user,action) \ - (This)->lpVtbl -> OnPrivateAction(This,res,user,action) - -#define IChatEvent_OnPublicAction(This,res,channel,user,action) \ - (This)->lpVtbl -> OnPublicAction(This,res,channel,user,action) - -#define IChatEvent_OnUserList(This,res,channel,users) \ - (This)->lpVtbl -> OnUserList(This,res,channel,users) - -#define IChatEvent_OnPublicMessage(This,res,channel,user,message) \ - (This)->lpVtbl -> OnPublicMessage(This,res,channel,user,message) - -#define IChatEvent_OnPrivateMessage(This,res,user,message) \ - (This)->lpVtbl -> OnPrivateMessage(This,res,user,message) - -#define IChatEvent_OnSystemMessage(This,res,message) \ - (This)->lpVtbl -> OnSystemMessage(This,res,message) - -#define IChatEvent_OnNetStatus(This,res) \ - (This)->lpVtbl -> OnNetStatus(This,res) - -#define IChatEvent_OnLogout(This,status,user) \ - (This)->lpVtbl -> OnLogout(This,status,user) - -#define IChatEvent_OnPrivateGameOptions(This,res,user,options) \ - (This)->lpVtbl -> OnPrivateGameOptions(This,res,user,options) - -#define IChatEvent_OnPublicGameOptions(This,res,channel,user,options) \ - (This)->lpVtbl -> OnPublicGameOptions(This,res,channel,user,options) - -#define IChatEvent_OnGameStart(This,res,channel,users,gameid) \ - (This)->lpVtbl -> OnGameStart(This,res,channel,users,gameid) - -#define IChatEvent_OnUserKick(This,res,channel,kicked,kicker) \ - (This)->lpVtbl -> OnUserKick(This,res,channel,kicked,kicker) - -#define IChatEvent_OnUserIP(This,res,user) \ - (This)->lpVtbl -> OnUserIP(This,res,user) - -#define IChatEvent_OnFind(This,res,chan) \ - (This)->lpVtbl -> OnFind(This,res,chan) - -#define IChatEvent_OnPageSend(This,res) \ - (This)->lpVtbl -> OnPageSend(This,res) - -#define IChatEvent_OnPaged(This,res,user,message) \ - (This)->lpVtbl -> OnPaged(This,res,user,message) - -#define IChatEvent_OnServerBannedYou(This,res,bannedTill) \ - (This)->lpVtbl -> OnServerBannedYou(This,res,bannedTill) - -#define IChatEvent_OnUserFlags(This,res,name,flags,mask) \ - (This)->lpVtbl -> OnUserFlags(This,res,name,flags,mask) - -#define IChatEvent_OnChannelBan(This,res,name,banned) \ - (This)->lpVtbl -> OnChannelBan(This,res,name,banned) - -#define IChatEvent_OnSquadInfo(This,res,id,squad) \ - (This)->lpVtbl -> OnSquadInfo(This,res,id,squad) - -#define IChatEvent_OnUserLocale(This,res,users) \ - (This)->lpVtbl -> OnUserLocale(This,res,users) - -#define IChatEvent_OnUserTeam(This,res,users) \ - (This)->lpVtbl -> OnUserTeam(This,res,users) - -#define IChatEvent_OnSetLocale(This,res,newlocale) \ - (This)->lpVtbl -> OnSetLocale(This,res,newlocale) - -#define IChatEvent_OnSetTeam(This,res,newteam) \ - (This)->lpVtbl -> OnSetTeam(This,res,newteam) - -#define IChatEvent_OnBuddyList(This,res,buddy_list) \ - (This)->lpVtbl -> OnBuddyList(This,res,buddy_list) - -#define IChatEvent_OnBuddyAdd(This,res,buddy_added) \ - (This)->lpVtbl -> OnBuddyAdd(This,res,buddy_added) - -#define IChatEvent_OnBuddyDelete(This,res,buddy_deleted) \ - (This)->lpVtbl -> OnBuddyDelete(This,res,buddy_deleted) - -#define IChatEvent_OnPublicUnicodeMessage(This,res,channel,user,message) \ - (This)->lpVtbl -> OnPublicUnicodeMessage(This,res,channel,user,message) - -#define IChatEvent_OnPrivateUnicodeMessage(This,res,user,message) \ - (This)->lpVtbl -> OnPrivateUnicodeMessage(This,res,user,message) - -#define IChatEvent_OnPrivateUnicodeAction(This,res,user,action) \ - (This)->lpVtbl -> OnPrivateUnicodeAction(This,res,user,action) - -#define IChatEvent_OnPublicUnicodeAction(This,res,channel,user,action) \ - (This)->lpVtbl -> OnPublicUnicodeAction(This,res,channel,user,action) - -#define IChatEvent_OnPagedUnicode(This,res,user,message) \ - (This)->lpVtbl -> OnPagedUnicode(This,res,user,message) - -#define IChatEvent_OnServerTime(This,res,stime) \ - (This)->lpVtbl -> OnServerTime(This,res,stime) - -#define IChatEvent_OnInsiderStatus(This,res,users) \ - (This)->lpVtbl -> OnInsiderStatus(This,res,users) - -#define IChatEvent_OnSetLocalIP(This,res,message) \ - (This)->lpVtbl -> OnSetLocalIP(This,res,message) - -#define IChatEvent_OnChannelListBegin(This,res) \ - (This)->lpVtbl -> OnChannelListBegin(This,res) - -#define IChatEvent_OnChannelListEntry(This,res,channel) \ - (This)->lpVtbl -> OnChannelListEntry(This,res,channel) - -#define IChatEvent_OnChannelListEnd(This,res) \ - (This)->lpVtbl -> OnChannelListEnd(This,res) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnServerList_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Server __RPC_FAR *servers); - - -void __RPC_STUB IChatEvent_OnServerList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUpdateList_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Update __RPC_FAR *updates); - - -void __RPC_STUB IChatEvent_OnUpdateList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnServerError_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR ircmsg); - - -void __RPC_STUB IChatEvent_OnServerError_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnConnection_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR motd); - - -void __RPC_STUB IChatEvent_OnConnection_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnMessageOfTheDay_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR motd); - - -void __RPC_STUB IChatEvent_OnMessageOfTheDay_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelList_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channels); - - -void __RPC_STUB IChatEvent_OnChannelList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelCreate_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel); - - -void __RPC_STUB IChatEvent_OnChannelCreate_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelJoin_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user); - - -void __RPC_STUB IChatEvent_OnChannelJoin_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelLeave_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user); - - -void __RPC_STUB IChatEvent_OnChannelLeave_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelTopic_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ LPCSTR topic); - - -void __RPC_STUB IChatEvent_OnChannelTopic_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPrivateAction_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR action); - - -void __RPC_STUB IChatEvent_OnPrivateAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPublicAction_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - User __RPC_FAR *user, - /* [in] */ LPCSTR action); - - -void __RPC_STUB IChatEvent_OnPublicAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUserList_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *users); - - -void __RPC_STUB IChatEvent_OnUserList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPublicMessage_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR message); - - -void __RPC_STUB IChatEvent_OnPublicMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPrivateMessage_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR message); - - -void __RPC_STUB IChatEvent_OnPrivateMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnSystemMessage_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ LPCSTR message); - - -void __RPC_STUB IChatEvent_OnSystemMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnNetStatus_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res); - - -void __RPC_STUB IChatEvent_OnNetStatus_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnLogout_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT status, - /* [in] */ User __RPC_FAR *user); - - -void __RPC_STUB IChatEvent_OnLogout_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPrivateGameOptions_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR options); - - -void __RPC_STUB IChatEvent_OnPrivateGameOptions_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPublicGameOptions_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ LPCSTR options); - - -void __RPC_STUB IChatEvent_OnPublicGameOptions_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnGameStart_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *users, - /* [in] */ int gameid); - - -void __RPC_STUB IChatEvent_OnGameStart_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUserKick_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *kicked, - /* [in] */ User __RPC_FAR *kicker); - - -void __RPC_STUB IChatEvent_OnUserKick_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUserIP_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user); - - -void __RPC_STUB IChatEvent_OnUserIP_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnFind_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan); - - -void __RPC_STUB IChatEvent_OnFind_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPageSend_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res); - - -void __RPC_STUB IChatEvent_OnPageSend_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPaged_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *user, - LPCSTR message); - - -void __RPC_STUB IChatEvent_OnPaged_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnServerBannedYou_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - time_t bannedTill); - - -void __RPC_STUB IChatEvent_OnServerBannedYou_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUserFlags_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - LPCSTR name, - unsigned int flags, - unsigned int mask); - - -void __RPC_STUB IChatEvent_OnUserFlags_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelBan_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - LPCSTR name, - int banned); - - -void __RPC_STUB IChatEvent_OnChannelBan_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnSquadInfo_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - unsigned long id, - Squad __RPC_FAR *squad); - - -void __RPC_STUB IChatEvent_OnSquadInfo_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUserLocale_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *users); - - -void __RPC_STUB IChatEvent_OnUserLocale_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnUserTeam_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *users); - - -void __RPC_STUB IChatEvent_OnUserTeam_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnSetLocale_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - Locale newlocale); - - -void __RPC_STUB IChatEvent_OnSetLocale_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnSetTeam_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - int newteam); - - -void __RPC_STUB IChatEvent_OnSetTeam_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnBuddyList_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *buddy_list); - - -void __RPC_STUB IChatEvent_OnBuddyList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnBuddyAdd_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *buddy_added); - - -void __RPC_STUB IChatEvent_OnBuddyAdd_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnBuddyDelete_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *buddy_deleted); - - -void __RPC_STUB IChatEvent_OnBuddyDelete_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPublicUnicodeMessage_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *message); - - -void __RPC_STUB IChatEvent_OnPublicUnicodeMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPrivateUnicodeMessage_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *message); - - -void __RPC_STUB IChatEvent_OnPrivateUnicodeMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPrivateUnicodeAction_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *action); - - -void __RPC_STUB IChatEvent_OnPrivateUnicodeAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPublicUnicodeAction_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel, - User __RPC_FAR *user, - /* [in] */ const unsigned short __RPC_FAR *action); - - -void __RPC_STUB IChatEvent_OnPublicUnicodeAction_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnPagedUnicode_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *user, - const unsigned short __RPC_FAR *message); - - -void __RPC_STUB IChatEvent_OnPagedUnicode_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnServerTime_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - time_t stime); - - -void __RPC_STUB IChatEvent_OnServerTime_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnInsiderStatus_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *users); - - -void __RPC_STUB IChatEvent_OnInsiderStatus_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnSetLocalIP_Proxy( - IChatEvent __RPC_FAR * This, - HRESULT res, - LPCSTR message); - - -void __RPC_STUB IChatEvent_OnSetLocalIP_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelListBegin_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res); - - -void __RPC_STUB IChatEvent_OnChannelListBegin_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelListEntry_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res, - /* [in] */ Channel __RPC_FAR *channel); - - -void __RPC_STUB IChatEvent_OnChannelListEntry_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChatEvent_OnChannelListEnd_Proxy( - IChatEvent __RPC_FAR * This, - /* [in] */ HRESULT res); - - -void __RPC_STUB IChatEvent_OnChannelListEnd_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IChatEvent_INTERFACE_DEFINED__ */ - - -#ifndef __IDownload_INTERFACE_DEFINED__ -#define __IDownload_INTERFACE_DEFINED__ - -/* interface IDownload */ -/* [unique][helpstring][dual][uuid][object] */ - - -EXTERN_C const IID IID_IDownload; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("0BF5FCEB-9F03-11D1-9DC7-006097C54321") - IDownload : public IUnknown - { - public: - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE DownloadFile( - LPCSTR server, - LPCSTR login, - LPCSTR password, - LPCSTR file, - LPCSTR localfile, - LPCSTR regkey) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Abort( void) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE PumpMessages( void) = 0; - - }; - -#else /* C style interface */ - - typedef struct IDownloadVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IDownload __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IDownload __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IDownload __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DownloadFile )( - IDownload __RPC_FAR * This, - LPCSTR server, - LPCSTR login, - LPCSTR password, - LPCSTR file, - LPCSTR localfile, - LPCSTR regkey); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Abort )( - IDownload __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *PumpMessages )( - IDownload __RPC_FAR * This); - - END_INTERFACE - } IDownloadVtbl; - - interface IDownload - { - CONST_VTBL struct IDownloadVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IDownload_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IDownload_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IDownload_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IDownload_DownloadFile(This,server,login,password,file,localfile,regkey) \ - (This)->lpVtbl -> DownloadFile(This,server,login,password,file,localfile,regkey) - -#define IDownload_Abort(This) \ - (This)->lpVtbl -> Abort(This) - -#define IDownload_PumpMessages(This) \ - (This)->lpVtbl -> PumpMessages(This) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDownload_DownloadFile_Proxy( - IDownload __RPC_FAR * This, - LPCSTR server, - LPCSTR login, - LPCSTR password, - LPCSTR file, - LPCSTR localfile, - LPCSTR regkey); - - -void __RPC_STUB IDownload_DownloadFile_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDownload_Abort_Proxy( - IDownload __RPC_FAR * This); - - -void __RPC_STUB IDownload_Abort_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDownload_PumpMessages_Proxy( - IDownload __RPC_FAR * This); - - -void __RPC_STUB IDownload_PumpMessages_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IDownload_INTERFACE_DEFINED__ */ - - -#ifndef __IDownloadEvent_INTERFACE_DEFINED__ -#define __IDownloadEvent_INTERFACE_DEFINED__ - -/* interface IDownloadEvent */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_IDownloadEvent; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("6869E99D-9FB4-11D1-9DC8-006097C54321") - IDownloadEvent : public IUnknown - { - public: - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnEnd( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnError( - int error) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnProgressUpdate( - int bytesread, - int totalsize, - int timetaken, - int timeleft) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnQueryResume( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnStatusUpdate( - int status) = 0; - - }; - -#else /* C style interface */ - - typedef struct IDownloadEventVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IDownloadEvent __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IDownloadEvent __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IDownloadEvent __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnEnd )( - IDownloadEvent __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnError )( - IDownloadEvent __RPC_FAR * This, - int error); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnProgressUpdate )( - IDownloadEvent __RPC_FAR * This, - int bytesread, - int totalsize, - int timetaken, - int timeleft); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnQueryResume )( - IDownloadEvent __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnStatusUpdate )( - IDownloadEvent __RPC_FAR * This, - int status); - - END_INTERFACE - } IDownloadEventVtbl; - - interface IDownloadEvent - { - CONST_VTBL struct IDownloadEventVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IDownloadEvent_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IDownloadEvent_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IDownloadEvent_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IDownloadEvent_OnEnd(This) \ - (This)->lpVtbl -> OnEnd(This) - -#define IDownloadEvent_OnError(This,error) \ - (This)->lpVtbl -> OnError(This,error) - -#define IDownloadEvent_OnProgressUpdate(This,bytesread,totalsize,timetaken,timeleft) \ - (This)->lpVtbl -> OnProgressUpdate(This,bytesread,totalsize,timetaken,timeleft) - -#define IDownloadEvent_OnQueryResume(This) \ - (This)->lpVtbl -> OnQueryResume(This) - -#define IDownloadEvent_OnStatusUpdate(This,status) \ - (This)->lpVtbl -> OnStatusUpdate(This,status) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDownloadEvent_OnEnd_Proxy( - IDownloadEvent __RPC_FAR * This); - - -void __RPC_STUB IDownloadEvent_OnEnd_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IDownloadEvent_OnError_Proxy( - IDownloadEvent __RPC_FAR * This, - int error); - - -void __RPC_STUB IDownloadEvent_OnError_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IDownloadEvent_OnProgressUpdate_Proxy( - IDownloadEvent __RPC_FAR * This, - int bytesread, - int totalsize, - int timetaken, - int timeleft); - - -void __RPC_STUB IDownloadEvent_OnProgressUpdate_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IDownloadEvent_OnQueryResume_Proxy( - IDownloadEvent __RPC_FAR * This); - - -void __RPC_STUB IDownloadEvent_OnQueryResume_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IDownloadEvent_OnStatusUpdate_Proxy( - IDownloadEvent __RPC_FAR * This, - int status); - - -void __RPC_STUB IDownloadEvent_OnStatusUpdate_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IDownloadEvent_INTERFACE_DEFINED__ */ - - -#ifndef __INetUtil_INTERFACE_DEFINED__ -#define __INetUtil_INTERFACE_DEFINED__ - -/* interface INetUtil */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_INetUtil; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("B832B0AA-A7D3-11D1-97C3-00609706FA0C") - INetUtil : public IUnknown - { - public: - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RequestGameresSend( - LPCSTR host, - int port, - unsigned char __RPC_FAR *data, - int length) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RequestLadderSearch( - LPCSTR host, - int port, - LPCSTR key, - unsigned long SKU, - int team, - int cond, - int sort, - int number, - int leading) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RequestLadderList( - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU, - int team, - int cond, - int sort) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RequestPing( - LPCSTR host, - int timeout, - int __RPC_FAR *handle) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE PumpMessages( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetAvgPing( - unsigned long ip, - int __RPC_FAR *avg) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestNewNick( - LPCSTR nick, - LPCSTR pass, - LPCSTR email, - LPCSTR parentEmail, - int newsletter, - int shareinfo) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestAgeCheck( - int month, - int day, - int year, - LPCSTR email) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestWDTState( - LPCSTR host, - int port, - unsigned char request) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestLocaleLadderList( - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU, - int team, - int cond, - int sort, - Locale locale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestLocaleLadderSearch( - LPCSTR host, - int port, - LPCSTR key, - unsigned long sku, - int team, - int cond, - int sort, - int number, - int leading, - Locale locale) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestHighscore( - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetGameResMD5( - int flag) = 0; - - }; - -#else /* C style interface */ - - typedef struct INetUtilVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - INetUtil __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - INetUtil __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - INetUtil __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestGameresSend )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - unsigned char __RPC_FAR *data, - int length); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestLadderSearch )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR key, - unsigned long SKU, - int team, - int cond, - int sort, - int number, - int leading); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestLadderList )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU, - int team, - int cond, - int sort); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestPing )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int timeout, - int __RPC_FAR *handle); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *PumpMessages )( - INetUtil __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetAvgPing )( - INetUtil __RPC_FAR * This, - unsigned long ip, - int __RPC_FAR *avg); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestNewNick )( - INetUtil __RPC_FAR * This, - LPCSTR nick, - LPCSTR pass, - LPCSTR email, - LPCSTR parentEmail, - int newsletter, - int shareinfo); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestAgeCheck )( - INetUtil __RPC_FAR * This, - int month, - int day, - int year, - LPCSTR email); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestWDTState )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - unsigned char request); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestLocaleLadderList )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU, - int team, - int cond, - int sort, - Locale locale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestLocaleLadderSearch )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR key, - unsigned long sku, - int team, - int cond, - int sort, - int number, - int leading, - Locale locale); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestHighscore )( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetGameResMD5 )( - INetUtil __RPC_FAR * This, - int flag); - - END_INTERFACE - } INetUtilVtbl; - - interface INetUtil - { - CONST_VTBL struct INetUtilVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define INetUtil_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define INetUtil_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define INetUtil_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define INetUtil_RequestGameresSend(This,host,port,data,length) \ - (This)->lpVtbl -> RequestGameresSend(This,host,port,data,length) - -#define INetUtil_RequestLadderSearch(This,host,port,key,SKU,team,cond,sort,number,leading) \ - (This)->lpVtbl -> RequestLadderSearch(This,host,port,key,SKU,team,cond,sort,number,leading) - -#define INetUtil_RequestLadderList(This,host,port,keys,SKU,team,cond,sort) \ - (This)->lpVtbl -> RequestLadderList(This,host,port,keys,SKU,team,cond,sort) - -#define INetUtil_RequestPing(This,host,timeout,handle) \ - (This)->lpVtbl -> RequestPing(This,host,timeout,handle) - -#define INetUtil_PumpMessages(This) \ - (This)->lpVtbl -> PumpMessages(This) - -#define INetUtil_GetAvgPing(This,ip,avg) \ - (This)->lpVtbl -> GetAvgPing(This,ip,avg) - -#define INetUtil_RequestNewNick(This,nick,pass,email,parentEmail,newsletter,shareinfo) \ - (This)->lpVtbl -> RequestNewNick(This,nick,pass,email,parentEmail,newsletter,shareinfo) - -#define INetUtil_RequestAgeCheck(This,month,day,year,email) \ - (This)->lpVtbl -> RequestAgeCheck(This,month,day,year,email) - -#define INetUtil_RequestWDTState(This,host,port,request) \ - (This)->lpVtbl -> RequestWDTState(This,host,port,request) - -#define INetUtil_RequestLocaleLadderList(This,host,port,keys,SKU,team,cond,sort,locale) \ - (This)->lpVtbl -> RequestLocaleLadderList(This,host,port,keys,SKU,team,cond,sort,locale) - -#define INetUtil_RequestLocaleLadderSearch(This,host,port,key,sku,team,cond,sort,number,leading,locale) \ - (This)->lpVtbl -> RequestLocaleLadderSearch(This,host,port,key,sku,team,cond,sort,number,leading,locale) - -#define INetUtil_RequestHighscore(This,host,port,keys,SKU) \ - (This)->lpVtbl -> RequestHighscore(This,host,port,keys,SKU) - -#define INetUtil_SetGameResMD5(This,flag) \ - (This)->lpVtbl -> SetGameResMD5(This,flag) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestGameresSend_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - unsigned char __RPC_FAR *data, - int length); - - -void __RPC_STUB INetUtil_RequestGameresSend_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestLadderSearch_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR key, - unsigned long SKU, - int team, - int cond, - int sort, - int number, - int leading); - - -void __RPC_STUB INetUtil_RequestLadderSearch_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestLadderList_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU, - int team, - int cond, - int sort); - - -void __RPC_STUB INetUtil_RequestLadderList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestPing_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int timeout, - int __RPC_FAR *handle); - - -void __RPC_STUB INetUtil_RequestPing_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtil_PumpMessages_Proxy( - INetUtil __RPC_FAR * This); - - -void __RPC_STUB INetUtil_PumpMessages_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_GetAvgPing_Proxy( - INetUtil __RPC_FAR * This, - unsigned long ip, - int __RPC_FAR *avg); - - -void __RPC_STUB INetUtil_GetAvgPing_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestNewNick_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR nick, - LPCSTR pass, - LPCSTR email, - LPCSTR parentEmail, - int newsletter, - int shareinfo); - - -void __RPC_STUB INetUtil_RequestNewNick_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestAgeCheck_Proxy( - INetUtil __RPC_FAR * This, - int month, - int day, - int year, - LPCSTR email); - - -void __RPC_STUB INetUtil_RequestAgeCheck_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestWDTState_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - unsigned char request); - - -void __RPC_STUB INetUtil_RequestWDTState_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestLocaleLadderList_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU, - int team, - int cond, - int sort, - Locale locale); - - -void __RPC_STUB INetUtil_RequestLocaleLadderList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestLocaleLadderSearch_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR key, - unsigned long sku, - int team, - int cond, - int sort, - int number, - int leading, - Locale locale); - - -void __RPC_STUB INetUtil_RequestLocaleLadderSearch_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_RequestHighscore_Proxy( - INetUtil __RPC_FAR * This, - LPCSTR host, - int port, - LPCSTR keys, - unsigned long SKU); - - -void __RPC_STUB INetUtil_RequestHighscore_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtil_SetGameResMD5_Proxy( - INetUtil __RPC_FAR * This, - int flag); - - -void __RPC_STUB INetUtil_SetGameResMD5_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __INetUtil_INTERFACE_DEFINED__ */ - - -#ifndef __INetUtilEvent_INTERFACE_DEFINED__ -#define __INetUtilEvent_INTERFACE_DEFINED__ - -/* interface INetUtilEvent */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_INetUtilEvent; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("B832B0AC-A7D3-11D1-97C3-00609706FA0C") - INetUtilEvent : public IUnknown - { - public: - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnPing( - HRESULT res, - int time, - unsigned long ip, - int handle) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnLadderList( - HRESULT res, - /* [in] */ Ladder __RPC_FAR *list, - int totalCount, - long timeStamp, - int keyRung) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnGameresSent( - HRESULT res) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnNewNick( - HRESULT res, - LPCSTR message, - LPCSTR nick, - LPCSTR pass) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnAgeCheck( - HRESULT res, - int years, - int consent) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnWDTState( - HRESULT res, - unsigned char __RPC_FAR *state, - int length) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnHighscore( - HRESULT res, - /* [in] */ Highscore __RPC_FAR *list, - int totalCount, - long timeStamp, - int keyRung) = 0; - - }; - -#else /* C style interface */ - - typedef struct INetUtilEventVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - INetUtilEvent __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - INetUtilEvent __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - INetUtilEvent __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnPing )( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - int time, - unsigned long ip, - int handle); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnLadderList )( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - /* [in] */ Ladder __RPC_FAR *list, - int totalCount, - long timeStamp, - int keyRung); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnGameresSent )( - INetUtilEvent __RPC_FAR * This, - HRESULT res); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnNewNick )( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - LPCSTR message, - LPCSTR nick, - LPCSTR pass); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnAgeCheck )( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - int years, - int consent); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnWDTState )( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - unsigned char __RPC_FAR *state, - int length); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnHighscore )( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - /* [in] */ Highscore __RPC_FAR *list, - int totalCount, - long timeStamp, - int keyRung); - - END_INTERFACE - } INetUtilEventVtbl; - - interface INetUtilEvent - { - CONST_VTBL struct INetUtilEventVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define INetUtilEvent_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define INetUtilEvent_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define INetUtilEvent_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define INetUtilEvent_OnPing(This,res,time,ip,handle) \ - (This)->lpVtbl -> OnPing(This,res,time,ip,handle) - -#define INetUtilEvent_OnLadderList(This,res,list,totalCount,timeStamp,keyRung) \ - (This)->lpVtbl -> OnLadderList(This,res,list,totalCount,timeStamp,keyRung) - -#define INetUtilEvent_OnGameresSent(This,res) \ - (This)->lpVtbl -> OnGameresSent(This,res) - -#define INetUtilEvent_OnNewNick(This,res,message,nick,pass) \ - (This)->lpVtbl -> OnNewNick(This,res,message,nick,pass) - -#define INetUtilEvent_OnAgeCheck(This,res,years,consent) \ - (This)->lpVtbl -> OnAgeCheck(This,res,years,consent) - -#define INetUtilEvent_OnWDTState(This,res,state,length) \ - (This)->lpVtbl -> OnWDTState(This,res,state,length) - -#define INetUtilEvent_OnHighscore(This,res,list,totalCount,timeStamp,keyRung) \ - (This)->lpVtbl -> OnHighscore(This,res,list,totalCount,timeStamp,keyRung) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnPing_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - int time, - unsigned long ip, - int handle); - - -void __RPC_STUB INetUtilEvent_OnPing_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnLadderList_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - /* [in] */ Ladder __RPC_FAR *list, - int totalCount, - long timeStamp, - int keyRung); - - -void __RPC_STUB INetUtilEvent_OnLadderList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnGameresSent_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res); - - -void __RPC_STUB INetUtilEvent_OnGameresSent_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnNewNick_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - LPCSTR message, - LPCSTR nick, - LPCSTR pass); - - -void __RPC_STUB INetUtilEvent_OnNewNick_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnAgeCheck_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - int years, - int consent); - - -void __RPC_STUB INetUtilEvent_OnAgeCheck_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnWDTState_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - unsigned char __RPC_FAR *state, - int length); - - -void __RPC_STUB INetUtilEvent_OnWDTState_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE INetUtilEvent_OnHighscore_Proxy( - INetUtilEvent __RPC_FAR * This, - HRESULT res, - /* [in] */ Highscore __RPC_FAR *list, - int totalCount, - long timeStamp, - int keyRung); - - -void __RPC_STUB INetUtilEvent_OnHighscore_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __INetUtilEvent_INTERFACE_DEFINED__ */ - - -#ifndef __IChat2_INTERFACE_DEFINED__ -#define __IChat2_INTERFACE_DEFINED__ - -/* interface IChat2 */ -/* [object][unique][helpstring][uuid] */ - -typedef unsigned long GID; - - -enum GTYPE_ - { SERVER = 0, - CHANNEL = 1, - CLIENT = 2 - }; -typedef enum GTYPE_ GTYPE; - - -enum CHAN_CTYPE_ - { ALLEXIT = 0, - CREATOREXIT = 1, - CLOSEC = 2 - }; -typedef enum CHAN_CTYPE_ CHAN_CTYPE; - - -EXTERN_C const IID IID_IChat2; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("8B938190-EF3F-11D1-9808-00609706FA0C") - IChat2 : public IUnknown - { - public: - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PumpMessages( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestConnection( - Server __RPC_FAR *server, - int timeout) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestMessage( - GID who, - LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetTypeFromGID( - GID id, - GTYPE __RPC_FAR *type) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelList( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelJoin( - LPCSTR name) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelLeave( - Channel __RPC_FAR *chan) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestUserList( - Channel __RPC_FAR *chan) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestLogout( void) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestChannelCreate( - Channel __RPC_FAR *chan) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RequestRawCmd( - LPCSTR cmd) = 0; - - }; - -#else /* C style interface */ - - typedef struct IChat2Vtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IChat2 __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IChat2 __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IChat2 __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *PumpMessages )( - IChat2 __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestConnection )( - IChat2 __RPC_FAR * This, - Server __RPC_FAR *server, - int timeout); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestMessage )( - IChat2 __RPC_FAR * This, - GID who, - LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeFromGID )( - IChat2 __RPC_FAR * This, - GID id, - GTYPE __RPC_FAR *type); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelList )( - IChat2 __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelJoin )( - IChat2 __RPC_FAR * This, - LPCSTR name); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelLeave )( - IChat2 __RPC_FAR * This, - Channel __RPC_FAR *chan); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestUserList )( - IChat2 __RPC_FAR * This, - Channel __RPC_FAR *chan); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestLogout )( - IChat2 __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestChannelCreate )( - IChat2 __RPC_FAR * This, - Channel __RPC_FAR *chan); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RequestRawCmd )( - IChat2 __RPC_FAR * This, - LPCSTR cmd); - - END_INTERFACE - } IChat2Vtbl; - - interface IChat2 - { - CONST_VTBL struct IChat2Vtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IChat2_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IChat2_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IChat2_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IChat2_PumpMessages(This) \ - (This)->lpVtbl -> PumpMessages(This) - -#define IChat2_RequestConnection(This,server,timeout) \ - (This)->lpVtbl -> RequestConnection(This,server,timeout) - -#define IChat2_RequestMessage(This,who,message) \ - (This)->lpVtbl -> RequestMessage(This,who,message) - -#define IChat2_GetTypeFromGID(This,id,type) \ - (This)->lpVtbl -> GetTypeFromGID(This,id,type) - -#define IChat2_RequestChannelList(This) \ - (This)->lpVtbl -> RequestChannelList(This) - -#define IChat2_RequestChannelJoin(This,name) \ - (This)->lpVtbl -> RequestChannelJoin(This,name) - -#define IChat2_RequestChannelLeave(This,chan) \ - (This)->lpVtbl -> RequestChannelLeave(This,chan) - -#define IChat2_RequestUserList(This,chan) \ - (This)->lpVtbl -> RequestUserList(This,chan) - -#define IChat2_RequestLogout(This) \ - (This)->lpVtbl -> RequestLogout(This) - -#define IChat2_RequestChannelCreate(This,chan) \ - (This)->lpVtbl -> RequestChannelCreate(This,chan) - -#define IChat2_RequestRawCmd(This,cmd) \ - (This)->lpVtbl -> RequestRawCmd(This,cmd) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_PumpMessages_Proxy( - IChat2 __RPC_FAR * This); - - -void __RPC_STUB IChat2_PumpMessages_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestConnection_Proxy( - IChat2 __RPC_FAR * This, - Server __RPC_FAR *server, - int timeout); - - -void __RPC_STUB IChat2_RequestConnection_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestMessage_Proxy( - IChat2 __RPC_FAR * This, - GID who, - LPCSTR message); - - -void __RPC_STUB IChat2_RequestMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_GetTypeFromGID_Proxy( - IChat2 __RPC_FAR * This, - GID id, - GTYPE __RPC_FAR *type); - - -void __RPC_STUB IChat2_GetTypeFromGID_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestChannelList_Proxy( - IChat2 __RPC_FAR * This); - - -void __RPC_STUB IChat2_RequestChannelList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestChannelJoin_Proxy( - IChat2 __RPC_FAR * This, - LPCSTR name); - - -void __RPC_STUB IChat2_RequestChannelJoin_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestChannelLeave_Proxy( - IChat2 __RPC_FAR * This, - Channel __RPC_FAR *chan); - - -void __RPC_STUB IChat2_RequestChannelLeave_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestUserList_Proxy( - IChat2 __RPC_FAR * This, - Channel __RPC_FAR *chan); - - -void __RPC_STUB IChat2_RequestUserList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestLogout_Proxy( - IChat2 __RPC_FAR * This); - - -void __RPC_STUB IChat2_RequestLogout_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestChannelCreate_Proxy( - IChat2 __RPC_FAR * This, - Channel __RPC_FAR *chan); - - -void __RPC_STUB IChat2_RequestChannelCreate_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2_RequestRawCmd_Proxy( - IChat2 __RPC_FAR * This, - LPCSTR cmd); - - -void __RPC_STUB IChat2_RequestRawCmd_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IChat2_INTERFACE_DEFINED__ */ - - -#ifndef __IChat2Event_INTERFACE_DEFINED__ -#define __IChat2Event_INTERFACE_DEFINED__ - -/* interface IChat2Event */ -/* [object][unique][helpstring][uuid] */ - - -EXTERN_C const IID IID_IChat2Event; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("8B938192-EF3F-11D1-9808-00609706FA0C") - IChat2Event : public IUnknown - { - public: - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnNetStatus( - HRESULT res) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnMessage( - HRESULT res, - User __RPC_FAR *user, - LPCSTR message) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelList( - HRESULT res, - Channel __RPC_FAR *list) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelJoin( - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnLogin( - HRESULT res) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUserList( - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *users) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelLeave( - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *user) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnChannelCreate( - HRESULT res, - Channel __RPC_FAR *chan) = 0; - - virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnUnknownLine( - HRESULT res, - LPCSTR line) = 0; - - }; - -#else /* C style interface */ - - typedef struct IChat2EventVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IChat2Event __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IChat2Event __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IChat2Event __RPC_FAR * This); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnNetStatus )( - IChat2Event __RPC_FAR * This, - HRESULT res); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnMessage )( - IChat2Event __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *user, - LPCSTR message); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelList )( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *list); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelJoin )( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnLogin )( - IChat2Event __RPC_FAR * This, - HRESULT res); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUserList )( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *users); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelLeave )( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *user); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnChannelCreate )( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan); - - /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnUnknownLine )( - IChat2Event __RPC_FAR * This, - HRESULT res, - LPCSTR line); - - END_INTERFACE - } IChat2EventVtbl; - - interface IChat2Event - { - CONST_VTBL struct IChat2EventVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IChat2Event_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IChat2Event_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IChat2Event_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IChat2Event_OnNetStatus(This,res) \ - (This)->lpVtbl -> OnNetStatus(This,res) - -#define IChat2Event_OnMessage(This,res,user,message) \ - (This)->lpVtbl -> OnMessage(This,res,user,message) - -#define IChat2Event_OnChannelList(This,res,list) \ - (This)->lpVtbl -> OnChannelList(This,res,list) - -#define IChat2Event_OnChannelJoin(This,res,chan,user) \ - (This)->lpVtbl -> OnChannelJoin(This,res,chan,user) - -#define IChat2Event_OnLogin(This,res) \ - (This)->lpVtbl -> OnLogin(This,res) - -#define IChat2Event_OnUserList(This,res,chan,users) \ - (This)->lpVtbl -> OnUserList(This,res,chan,users) - -#define IChat2Event_OnChannelLeave(This,res,chan,user) \ - (This)->lpVtbl -> OnChannelLeave(This,res,chan,user) - -#define IChat2Event_OnChannelCreate(This,res,chan) \ - (This)->lpVtbl -> OnChannelCreate(This,res,chan) - -#define IChat2Event_OnUnknownLine(This,res,line) \ - (This)->lpVtbl -> OnUnknownLine(This,res,line) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnNetStatus_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res); - - -void __RPC_STUB IChat2Event_OnNetStatus_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnMessage_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - User __RPC_FAR *user, - LPCSTR message); - - -void __RPC_STUB IChat2Event_OnMessage_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnChannelList_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *list); - - -void __RPC_STUB IChat2Event_OnChannelList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnChannelJoin_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *user); - - -void __RPC_STUB IChat2Event_OnChannelJoin_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnLogin_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res); - - -void __RPC_STUB IChat2Event_OnLogin_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnUserList_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *users); - - -void __RPC_STUB IChat2Event_OnUserList_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnChannelLeave_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan, - User __RPC_FAR *user); - - -void __RPC_STUB IChat2Event_OnChannelLeave_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnChannelCreate_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - Channel __RPC_FAR *chan); - - -void __RPC_STUB IChat2Event_OnChannelCreate_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring] */ HRESULT STDMETHODCALLTYPE IChat2Event_OnUnknownLine_Proxy( - IChat2Event __RPC_FAR * This, - HRESULT res, - LPCSTR line); - - -void __RPC_STUB IChat2Event_OnUnknownLine_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IChat2Event_INTERFACE_DEFINED__ */ - - -#ifndef __IIGROptions_INTERFACE_DEFINED__ -#define __IIGROptions_INTERFACE_DEFINED__ - -/* interface IIGROptions */ -/* [unique][helpstring][dual][uuid][object] */ - - -EXTERN_C const IID IID_IIGROptions; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("89DD1ECD-0DCA-49d8-8EF3-3375E6D6EE9D") - IIGROptions : public IUnknown - { - public: - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Init( void) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Is_Auto_Login_Allowed( void) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Is_Storing_Nicks_Allowed( void) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Is_Running_Reg_App_Allowed( void) = 0; - - virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Set_Options( - unsigned int options) = 0; - - }; - -#else /* C style interface */ - - typedef struct IIGROptionsVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( - IIGROptions __RPC_FAR * This, - /* [in] */ REFIID riid, - /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( - IIGROptions __RPC_FAR * This); - - ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( - IIGROptions __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Init )( - IIGROptions __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Is_Auto_Login_Allowed )( - IIGROptions __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Is_Storing_Nicks_Allowed )( - IIGROptions __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Is_Running_Reg_App_Allowed )( - IIGROptions __RPC_FAR * This); - - /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Set_Options )( - IIGROptions __RPC_FAR * This, - unsigned int options); - - END_INTERFACE - } IIGROptionsVtbl; - - interface IIGROptions - { - CONST_VTBL struct IIGROptionsVtbl __RPC_FAR *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define IIGROptions_QueryInterface(This,riid,ppvObject) \ - (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) - -#define IIGROptions_AddRef(This) \ - (This)->lpVtbl -> AddRef(This) - -#define IIGROptions_Release(This) \ - (This)->lpVtbl -> Release(This) - - -#define IIGROptions_Init(This) \ - (This)->lpVtbl -> Init(This) - -#define IIGROptions_Is_Auto_Login_Allowed(This) \ - (This)->lpVtbl -> Is_Auto_Login_Allowed(This) - -#define IIGROptions_Is_Storing_Nicks_Allowed(This) \ - (This)->lpVtbl -> Is_Storing_Nicks_Allowed(This) - -#define IIGROptions_Is_Running_Reg_App_Allowed(This) \ - (This)->lpVtbl -> Is_Running_Reg_App_Allowed(This) - -#define IIGROptions_Set_Options(This,options) \ - (This)->lpVtbl -> Set_Options(This,options) - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IIGROptions_Init_Proxy( - IIGROptions __RPC_FAR * This); - - -void __RPC_STUB IIGROptions_Init_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IIGROptions_Is_Auto_Login_Allowed_Proxy( - IIGROptions __RPC_FAR * This); - - -void __RPC_STUB IIGROptions_Is_Auto_Login_Allowed_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IIGROptions_Is_Storing_Nicks_Allowed_Proxy( - IIGROptions __RPC_FAR * This); - - -void __RPC_STUB IIGROptions_Is_Storing_Nicks_Allowed_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IIGROptions_Is_Running_Reg_App_Allowed_Proxy( - IIGROptions __RPC_FAR * This); - - -void __RPC_STUB IIGROptions_Is_Running_Reg_App_Allowed_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - -/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IIGROptions_Set_Options_Proxy( - IIGROptions __RPC_FAR * This, - unsigned int options); - - -void __RPC_STUB IIGROptions_Set_Options_Stub( - IRpcStubBuffer *This, - IRpcChannelBuffer *_pRpcChannelBuffer, - PRPC_MESSAGE _pRpcMessage, - DWORD *_pdwStubPhase); - - - -#endif /* __IIGROptions_INTERFACE_DEFINED__ */ - - - -#ifndef __WOLAPILib_LIBRARY_DEFINED__ -#define __WOLAPILib_LIBRARY_DEFINED__ - -/* library WOLAPILib */ -/* [helpstring][version][uuid] */ - - -EXTERN_C const IID LIBID_WOLAPILib; - -EXTERN_C const CLSID CLSID_RTPatcher; - -#ifdef __cplusplus - -class DECLSPEC_UUID("925CDEDF-71B9-11D1-B1C5-006097176556") -RTPatcher; -#endif - -EXTERN_C const CLSID CLSID_Chat; - -#ifdef __cplusplus - -class DECLSPEC_UUID("4DD3BAF5-7579-11D1-B1C6-006097176556") -Chat; -#endif - -EXTERN_C const CLSID CLSID_Download; - -#ifdef __cplusplus - -class DECLSPEC_UUID("BF6EA206-9E55-11D1-9DC6-006097C54321") -Download; -#endif - -EXTERN_C const CLSID CLSID_IGROptions; - -#ifdef __cplusplus - -class DECLSPEC_UUID("ABF6FC8F-1344-46de-84C9-8371118DC3FF") -IGROptions; -#endif - -EXTERN_C const CLSID CLSID_NetUtil; - -#ifdef __cplusplus - -class DECLSPEC_UUID("B832B0AB-A7D3-11D1-97C3-00609706FA0C") -NetUtil; -#endif - -EXTERN_C const CLSID CLSID_Chat2; - -#ifdef __cplusplus - -class DECLSPEC_UUID("8B938191-EF3F-11D1-9808-00609706FA0C") -Chat2; -#endif -#endif /* __WOLAPILib_LIBRARY_DEFINED__ */ - -/* Additional Prototypes for ALL interfaces */ - -/* end of Additional Prototypes */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Generals/Code/Tools/wolSetup/WOLAPI/wolapi_i.c b/Generals/Code/Tools/wolSetup/WOLAPI/wolapi_i.c deleted file mode 100644 index 691b31aca2..0000000000 --- a/Generals/Code/Tools/wolSetup/WOLAPI/wolapi_i.c +++ /dev/null @@ -1,113 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/* this file contains the actual definitions of */ -/* the IIDs and CLSIDs */ - -/* link this file in with the server and any clients */ - - -/* File created by MIDL compiler version 5.01.0164 */ -/* at Mon Nov 05 10:28:33 2001 - */ -/* Compiler settings for .\WOLAPI.idl: - Oicf (OptLev=i2), W1, Zp8, env=Win32, ms_ext, c_ext - error checks: allocation ref bounds_check enum stub_data -*/ -//@@MIDL_FILE_HEADING( ) -#ifdef __cplusplus -extern "C"{ -#endif - - -#ifndef __IID_DEFINED__ -#define __IID_DEFINED__ - -typedef struct _IID -{ - unsigned long x; - unsigned short s1; - unsigned short s2; - unsigned char c[8]; -} IID; - -#endif // __IID_DEFINED__ - -#ifndef CLSID_DEFINED -#define CLSID_DEFINED -typedef IID CLSID; -#endif // CLSID_DEFINED - -const IID IID_IRTPatcher = {0x925CDEDE,0x71B9,0x11D1,{0xB1,0xC5,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const IID IID_IRTPatcherEvent = {0x925CDEE3,0x71B9,0x11D1,{0xB1,0xC5,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const IID IID_IChat = {0x4DD3BAF4,0x7579,0x11D1,{0xB1,0xC6,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const IID IID_IChatEvent = {0x4DD3BAF6,0x7579,0x11D1,{0xB1,0xC6,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const IID IID_IDownload = {0x0BF5FCEB,0x9F03,0x11D1,{0x9D,0xC7,0x00,0x60,0x97,0xC5,0x43,0x21}}; - - -const IID IID_IDownloadEvent = {0x6869E99D,0x9FB4,0x11D1,{0x9D,0xC8,0x00,0x60,0x97,0xC5,0x43,0x21}}; - - -const IID IID_INetUtil = {0xB832B0AA,0xA7D3,0x11D1,{0x97,0xC3,0x00,0x60,0x97,0x06,0xFA,0x0C}}; - - -const IID IID_INetUtilEvent = {0xB832B0AC,0xA7D3,0x11D1,{0x97,0xC3,0x00,0x60,0x97,0x06,0xFA,0x0C}}; - - -const IID IID_IChat2 = {0x8B938190,0xEF3F,0x11D1,{0x98,0x08,0x00,0x60,0x97,0x06,0xFA,0x0C}}; - - -const IID IID_IChat2Event = {0x8B938192,0xEF3F,0x11D1,{0x98,0x08,0x00,0x60,0x97,0x06,0xFA,0x0C}}; - - -const IID IID_IIGROptions = {0x89DD1ECD,0x0DCA,0x49d8,{0x8E,0xF3,0x33,0x75,0xE6,0xD6,0xEE,0x9D}}; - - -const IID LIBID_WOLAPILib = {0x925CDED1,0x71B9,0x11D1,{0xB1,0xC5,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const CLSID CLSID_RTPatcher = {0x925CDEDF,0x71B9,0x11D1,{0xB1,0xC5,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const CLSID CLSID_Chat = {0x4DD3BAF5,0x7579,0x11D1,{0xB1,0xC6,0x00,0x60,0x97,0x17,0x65,0x56}}; - - -const CLSID CLSID_Download = {0xBF6EA206,0x9E55,0x11D1,{0x9D,0xC6,0x00,0x60,0x97,0xC5,0x43,0x21}}; - - -const CLSID CLSID_IGROptions = {0xABF6FC8F,0x1344,0x46de,{0x84,0xC9,0x83,0x71,0x11,0x8D,0xC3,0xFF}}; - - -const CLSID CLSID_NetUtil = {0xB832B0AB,0xA7D3,0x11D1,{0x97,0xC3,0x00,0x60,0x97,0x06,0xFA,0x0C}}; - - -const CLSID CLSID_Chat2 = {0x8B938191,0xEF3F,0x11D1,{0x98,0x08,0x00,0x60,0x97,0x06,0xFA,0x0C}}; - - -#ifdef __cplusplus -} -#endif - diff --git a/Generals/Code/Tools/wolSetup/resource.h b/Generals/Code/Tools/wolSetup/resource.h deleted file mode 100644 index e805651207..0000000000 --- a/Generals/Code/Tools/wolSetup/resource.h +++ /dev/null @@ -1,33 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by wolSetup.rc -// -#define IDC_MYICON 2 -#define IDI_ICON1 101 -#define IDI_ICON2 102 -#define IDS_APP_TITLE 103 -#define IDD_MAINBOX 103 -#define IDD_GENERALSSETUPBOX 104 -#define IDS_HELLO 106 -#define IDC_WOLSETUP 109 -#define IDC_DEBUG_WOLAPI 1000 -#define IDC_RELEASE_WOLAPI 1001 -#define IDC_UNINSTALL_WOLAPI 1002 -#define IDC_SETUP_GENERALS 1003 -#define IDC_UNINSTALL_GENERALS 1004 -#define IDC_TEXT_WOLDIR 1006 -#define IDC_TEXT_GENERALSDIR 1007 -#define IDC_TEXT_WOLVER 1008 -#define IDC_EDIT_PATH 1009 -#define IDC_EDIT_SERIAL 1011 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 103 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1010 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Generals/Code/Tools/wolSetup/verchk.cpp b/Generals/Code/Tools/wolSetup/verchk.cpp deleted file mode 100644 index fe428a3412..0000000000 --- a/Generals/Code/Tools/wolSetup/verchk.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "verchk.h" -#include "wolSetup.h" -#include -#include -#include - -/** - * Retrieve version information from files version resource. - * - * INPUTS - * Filename - Name of file to retrieve version information for. - * FileInfo - Pointer to VS_FIXEDFILEINFO structure to be filled in. - * - * RESULT - * Success - True if successful in obtaining version information. - */ -bool GetVersionInfo(char* filename, VS_FIXEDFILEINFO* fileInfo) -{ - if (filename == NULL || fileInfo == NULL) - { - return false; - } - - // Get version information from the application - DWORD verHandle; - DWORD verInfoSize = GetFileVersionInfoSize(filename, &verHandle); - - if (verInfoSize) - { - // If we were able to get the information, process it: - HANDLE memHandle = GlobalAlloc(GMEM_MOVEABLE, verInfoSize); - - if (memHandle) - { - LPVOID buffer = GlobalLock(memHandle); - - if (buffer) - { - BOOL success = GetFileVersionInfo(filename, verHandle, verInfoSize, buffer); - - if (success) - { - VS_FIXEDFILEINFO* data; - UINT dataSize = 0; - success = VerQueryValue(buffer, "\\", (LPVOID*) & data, &dataSize); - - if (success && (dataSize == sizeof(VS_FIXEDFILEINFO))) - { - memcpy(fileInfo, data, sizeof(VS_FIXEDFILEINFO)); - return true; - } - } - - GlobalUnlock(memHandle); - } - - GlobalFree(memHandle); - } - } - - return false; -} - -bool loadWolapi( char *filename ) -{ - VS_FIXEDFILEINFO fileInfo; - if (GetVersionInfo(filename, &fileInfo)) - g_wolapiInstalled = false; - - return g_wolapiInstalled; -} diff --git a/Generals/Code/Tools/wolSetup/verchk.h b/Generals/Code/Tools/wolSetup/verchk.h deleted file mode 100644 index fe7e6d68d6..0000000000 --- a/Generals/Code/Tools/wolSetup/verchk.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#ifndef __VERCHK_H__ -#define __VERCHK_H__ - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include - -// Obtain version information from the specified file. -bool GetVersionInfo(char* filename, VS_FIXEDFILEINFO* fileInfo); -bool loadWolapi( char *filename ); - -#endif // __VERCHK_H__ - diff --git a/Generals/Code/Tools/wolSetup/wolInit.cpp b/Generals/Code/Tools/wolSetup/wolInit.cpp deleted file mode 100644 index fa0b8acf69..0000000000 --- a/Generals/Code/Tools/wolSetup/wolInit.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: WOLinit.cpp ////////////////////////////////////////////////////// -// Westwood Online DLL/COM/ initialization/teardown -// Author: Matthew D. Campbell, December 2001 - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include - -#include -extern CComModule _Module; // Required for COM - must be between atlbase.h and atlcom.h. Funky, no? -#include - -#include -#include - -#include "wolSetup.h" -#include "WOLAPI/wolapi.h" - -unsigned long g_wolapiRegistryVersion = 0; -unsigned long g_wolapiRealVersion = 0; -bool g_wolapiInstalled = false; -char g_wolapiRegFilename[MAX_PATH]; -char g_wolapiRealFilename[MAX_PATH]; -char g_generalsFilename[MAX_PATH]; -char g_generalsSerial[1024]; - -#define GENERALS_REG_KEY_TOP "HKEY_LOCAL_MACHINE" ///< Registry base -#define GENERALS_REG_KEY_PATH "SOFTWARE\\Westwood\\Generals" ///< Generals registry key -#define GENERALS_REG_KEY_BOTTOM GENERALS_REG_KEY_PATH "\\" ///< Generals registry key with trailing backslashes -#define GENERALS_REG_KEY_VERSION "Version" ///< Version registry key -#define GENERALS_REG_KEY_SKU "SKU" ///< SKU registry key -#define GENERALS_REG_KEY_NAME "Name" ///< Product name registry key -#define GENERALS_REG_KEY_INSTALLPATH "InstallPath" ///< Install path registry key -#define GENERALS_REG_KEY_SERIAL "Serial" ///< Serial # registry key -#define GENERALS_REG_KEY GENERALS_REG_KEY_TOP "\\" GENERALS_REG_KEY_BOTTOM ///< Full Generals registry path - -#define WOLAPI_REG_KEY_TOP "HKEY_LOCAL_MACHINE" ///< Registry base -#define WOLAPI_REG_KEY_PATH "SOFTWARE\\Westwood\\WOLAPI" ///< WOLAPI registry key -#define WOLAPI_REG_KEY_BOTTOM WOLAPI_REG_KEY_PATH "\\" ///< WOLAPI registry key with trailing backslashes -#define WOLAPI_REG_KEY_VERSION "Version" ///< Version registry key -#define WOLAPI_REG_KEY_INSTALLPATH "InstallPath" ///< Install path registry key -#define WOLAPI_REG_KEY WOLAPI_REG_KEY_TOP "\\" WOLAPI_REG_KEY_BOTTOM ///< Full WOLAPI registry path - -#define DLL_REG_KEY_TOP "HKEY_CLASSES_ROOT" ///< Registry base -#define DLL_REG_KEY_PATH "CLSID\\{18FD6763-F5EA-4fa5-B2A9-668554152FAE}\\InprocServer32" ///< WOLAPI registry key -#define DLL_REG_KEY_BOTTOM DLL_REG_KEY_PATH "\\" ///< WOLAPI registry key with trailing backslashes -#define DLL_REG_KEY_LOCATION "" ///< Version registry key - -void getPathsFromRegistry( void ) -{ - HKEY handle; - unsigned long type; - unsigned long size; - int returnValue; - - size = sizeof(g_generalsFilename); - strcpy(g_generalsFilename, "No install path in registry"); - - if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, GENERALS_REG_KEY_PATH, 0, KEY_ALL_ACCESS, &handle ) == ERROR_SUCCESS) { - - returnValue = RegQueryValueEx(handle, GENERALS_REG_KEY_INSTALLPATH, NULL, &type, (unsigned char *) &g_generalsFilename, &size); - - if (returnValue != ERROR_SUCCESS) - { - strcpy(g_generalsFilename, "No install path in registry"); - } - - RegCloseKey( handle ); - } - - size = sizeof(g_generalsSerial); - strcpy(g_generalsSerial, "0"); - - if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, GENERALS_REG_KEY_PATH, 0, KEY_ALL_ACCESS, &handle ) == ERROR_SUCCESS) { - - returnValue = RegQueryValueEx(handle, GENERALS_REG_KEY_SERIAL, NULL, &type, (unsigned char *) &g_generalsSerial, &size); - - if (returnValue != ERROR_SUCCESS) - { - strcpy(g_generalsSerial, "0"); - } - - RegCloseKey( handle ); - } - - size = sizeof(g_wolapiRegFilename); - strcpy(g_wolapiRegFilename, "No install path in registry"); - g_wolapiInstalled = true; - - if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, WOLAPI_REG_KEY_PATH, 0, KEY_ALL_ACCESS, &handle ) == ERROR_SUCCESS) { - - returnValue = RegQueryValueEx(handle, WOLAPI_REG_KEY_INSTALLPATH, NULL, &type, (unsigned char *) &g_wolapiRegFilename, &size); - - if (returnValue != ERROR_SUCCESS) - { - strcpy(g_wolapiRegFilename, "No install path in registry"); - g_wolapiInstalled = false; - } - - RegCloseKey( handle ); - } - - size = sizeof(g_wolapiRealFilename); - strcpy(g_wolapiRealFilename, "No wolapi.dll installed"); - - if (RegOpenKeyEx( HKEY_CLASSES_ROOT, DLL_REG_KEY_PATH, 0, KEY_ALL_ACCESS, &handle ) == ERROR_SUCCESS) { - - returnValue = RegQueryValueEx(handle, DLL_REG_KEY_LOCATION, NULL, &type, (unsigned char *) &g_wolapiRealFilename, &size); - - if (returnValue != ERROR_SUCCESS) - { - strcpy(g_wolapiRealFilename, "No wolapi.dll installed"); - g_wolapiInstalled = false; - } - - RegCloseKey( handle ); - } -} - -void setupGenerals( const char *genPath, const char *genSerial ) -{ - HKEY handle; - unsigned long type; - unsigned long returnValue; - int size; - char lpClass[] = "REG_NONE"; - - if (RegCreateKeyEx( HKEY_LOCAL_MACHINE, GENERALS_REG_KEY_PATH, 0, lpClass, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &handle, NULL ) == ERROR_SUCCESS) { - - type = REG_SZ; - size = strlen(genPath)+1; - returnValue = RegSetValueEx(handle, GENERALS_REG_KEY_INSTALLPATH, 0, type, (unsigned char *) genPath, size); - - size = strlen(genSerial)+1; - returnValue = RegSetValueEx(handle, GENERALS_REG_KEY_SERIAL, 0, type, (unsigned char *) genSerial, size); - - size = strlen("Generals")+1; - returnValue = RegSetValueEx(handle, GENERALS_REG_KEY_NAME, 0, type, (unsigned char *) "Generals", size); - - type = REG_DWORD; - size = sizeof(DWORD); - unsigned long value = 65536; - returnValue = RegSetValueEx(handle, GENERALS_REG_KEY_VERSION, 0, type, (unsigned char *) &value, size); - value = 12544; - returnValue = RegSetValueEx(handle, GENERALS_REG_KEY_SKU, 0, type, (unsigned char *) &value, size); - - RegCloseKey( handle ); - } - -} - - -/** - * OLEInitializer class - Init and shutdown OLE & COM as a global - * object. Scary, nasty stuff, COM. /me shivers. - */ -class OLEInitializer -{ - public: - OLEInitializer() { OleInitialize(NULL); } - ~OLEInitializer() { OleUninitialize(); } -}; -OLEInitializer g_OLEInitializer; -CComModule _Module; - -IChat *g_pChat = NULL; - -/** - * checkInstalledWolapiVersion inits WOLAPI if possible and gets its version - * number. It also saves off its install path from the registry. - */ -void checkInstalledWolapiVersion( void ) -{ - // Initialize this instance - _Module.Init(NULL, g_hInst); - - // Create the WOLAPI instance - CoCreateInstance(CLSID_Chat, NULL, CLSCTX_INPROC_SERVER, \ - IID_IChat, (void**)&g_pChat); - - if (g_pChat) - { - // Grab versions - g_pChat->GetVersion(&g_wolapiRealVersion); - - // Release everything - g_pChat->Release(); - - g_wolapiInstalled = true; - } - - _Module.Term(); - - // Grab path info from registry - getPathsFromRegistry(); - - return; -} - diff --git a/Generals/Code/Tools/wolSetup/wolSetup.cpp b/Generals/Code/Tools/wolSetup/wolSetup.cpp deleted file mode 100644 index 644d39cfc4..0000000000 --- a/Generals/Code/Tools/wolSetup/wolSetup.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: wolSetup.cpp ////////////////////////////////////////////////////// -// Defines the entry point for the application. -// Author: Matthew D. Campbell, December 2001 - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include -#include - -#include "resource.h" -#include "wolSetup.h" -#include "verchk.h" - -void registerDLL(const char *dllName) -{ - HINSTANCE hLib = LoadLibrary(dllName); - FARPROC lpDllEntryPoint; - - if (hLib < (HINSTANCE)HINSTANCE_ERROR) - { - return; - } - - // Find the entry point. - (FARPROC&)lpDllEntryPoint = GetProcAddress(hLib, - "DllRegisterServer"); - if (lpDllEntryPoint != NULL) - (*lpDllEntryPoint)(); - else - ;//unable to locate entry point -} - - - -HINSTANCE g_hInst = NULL; - -LRESULT CALLBACK MainDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); - -int APIENTRY WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPSTR lpCmdLine, - int nCmdShow) -{ - g_hInst = hInstance; - - checkInstalledWolapiVersion(); - - DialogBox(g_hInst, (LPCTSTR)IDD_MAINBOX, NULL, (DLGPROC)MainDialogProc); - - return 0; -} - - -// Mesage handler for generals setup box. -LRESULT CALLBACK GeneralsSetupDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - SetDlgItemText(hDlg, IDC_EDIT_PATH, g_generalsFilename); - SetDlgItemText(hDlg, IDC_EDIT_SERIAL, g_generalsSerial); - return TRUE; - } - - case WM_COMMAND: - switch(LOWORD(wParam)) - { - case IDOK: - { - char genPath[_MAX_PATH], genSerial[1024]; - GetDlgItemText(hDlg, IDC_EDIT_PATH, genPath, _MAX_PATH); - GetDlgItemText(hDlg, IDC_EDIT_SERIAL, genSerial, 1024); - setupGenerals( genPath, genSerial ); - EndDialog(hDlg, LOWORD(wParam)); - return TRUE; - } - - case IDCANCEL: - { - EndDialog(hDlg, LOWORD(wParam)); - return TRUE; - } - } - break; - } - return FALSE; -} - -void updateDisplay(HWND hDlg) -{ - checkInstalledWolapiVersion(); - if (g_wolapiInstalled) - { - char buf[200]; - sprintf(buf, "%d.%d (%s)", MAJOR(g_wolapiRealVersion), MINOR(g_wolapiRealVersion), g_wolapiRealFilename); - SetDlgItemText(hDlg, IDC_TEXT_WOLVER, buf); - } - else - { - SetDlgItemText(hDlg, IDC_TEXT_WOLVER, "Not installed"); - } - SetDlgItemText(hDlg, IDC_TEXT_WOLDIR, g_wolapiRegFilename); - SetDlgItemText(hDlg, IDC_TEXT_GENERALSDIR, g_generalsFilename); -} - -// Mesage handler for main dialog box. -LRESULT CALLBACK MainDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - updateDisplay(hDlg); - return TRUE; - } - - case WM_COMMAND: - switch(LOWORD(wParam)) - { - case IDOK: - case IDCANCEL: - { - EndDialog(hDlg, LOWORD(wParam)); - return TRUE; - } - case IDC_SETUP_GENERALS: - { - DialogBox(g_hInst, (LPCTSTR)IDD_GENERALSSETUPBOX, hDlg, (DLGPROC)GeneralsSetupDialogProc); - updateDisplay(hDlg); - break; - } - case IDC_UNINSTALL_GENERALS: - { - if (MessageBox(hDlg, "Are you sure you want to delete Generals registry entries?", "Warning!", MB_OKCANCEL) == IDOK) - { - MessageBox(hDlg, "Oops! Can't do that yet!", "Unimplemented", MB_OK); - updateDisplay(hDlg); - } - break; - } - case IDC_DEBUG_WOLAPI: - { - if (g_wolapiInstalled) - { - if (MessageBox(hDlg, "Are you sure you want to overwrite installed WOLAPI?", "Warning!", MB_OKCANCEL) == IDOK) - { - registerDLL("woldbg.dll"); - updateDisplay(hDlg); - } - } - else - { - DialogBox(g_hInst, (LPCTSTR)IDD_GENERALSSETUPBOX, hDlg, (DLGPROC)MainDialogProc); - } - break; - } - case IDC_RELEASE_WOLAPI: - { - if (g_wolapiInstalled) - { - if (MessageBox(hDlg, "Are you sure you want to overwrite installed WOLAPI?", "Warning!", MB_OKCANCEL) == IDOK) - { - registerDLL("wolapi.dll"); - updateDisplay(hDlg); - } - } - else - { - DialogBox(g_hInst, (LPCTSTR)IDD_GENERALSSETUPBOX, hDlg, (DLGPROC)MainDialogProc); - updateDisplay(hDlg); - } - break; - } - case IDC_UNINSTALL_WOLAPI: - { - if (g_wolapiInstalled) - { - MessageBox(hDlg, "Oops! Can't do that yet!", "Unimplemented", MB_OK); - updateDisplay(hDlg); - } - break; - } - } - break; - } - return FALSE; -} - - - diff --git a/Generals/Code/Tools/wolSetup/wolSetup.h b/Generals/Code/Tools/wolSetup/wolSetup.h deleted file mode 100644 index e66901bc5e..0000000000 --- a/Generals/Code/Tools/wolSetup/wolSetup.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: wolSetup.h ////////////////////////////////////////////////////// -// Author: Matthew D. Campbell, December 2001 - -#ifndef __WOLSETUP_H__ -#define __WOLSETUP_H__ - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include - -void checkInstalledWolapiVersion( void ); -void setupGenerals( const char *genPath, const char *genSerial ); - -extern HINSTANCE g_hInst; -extern unsigned long g_wolapiRegistryVersion; -extern unsigned long g_wolapiRealVersion; -extern bool g_wolapiInstalled; -extern char g_wolapiRegFilename[MAX_PATH]; -extern char g_wolapiRealFilename[MAX_PATH]; -extern char g_generalsFilename[MAX_PATH]; -extern char g_generalsSerial[]; - -// TheSuperHackers @todo Check if this should be returning unsigned long. -static int MAJOR(unsigned long x) { return (((x) & 0xffff0000) >> 16); } -static int MINOR(unsigned long x) { return ((x) & 0xffff); } - -#endif // __WOLSETUP_H__ diff --git a/GeneralsMD/CMakeLists.txt b/GeneralsMD/CMakeLists.txt index 0926d07a2e..d7d20ea93a 100644 --- a/GeneralsMD/CMakeLists.txt +++ b/GeneralsMD/CMakeLists.txt @@ -2,15 +2,6 @@ cmake_minimum_required(VERSION 3.25) project(z_generals LANGUAGES C CXX) -# Do we want to build extra SDK stuff or just the game binary? -option(RTS_BUILD_ZEROHOUR_TOOLS "Build tools for Zero Hour" ON) -add_feature_info(ZeroHourTools RTS_BUILD_ZEROHOUR_TOOLS "Build Zero Hour Mod Tools") -option(RTS_BUILD_ZEROHOUR_EXTRAS "Build extra tools/tests for Zero Hour" OFF) -add_feature_info(ZeroHourExtras RTS_BUILD_ZEROHOUR_EXTRAS "Build Zero Hour Extra Tools/Tests") - -# Do we want to build documentation? -option(RTS_BUILD_ZEROHOUR_DOCS "Build documentation for Zero Hour" OFF) -add_feature_info(ZeroHourDocs RTS_BUILD_ZEROHOUR_DOCS "Build Zero Hour Documentation") if (RTS_BUILD_ZEROHOUR_DOCS) find_package(Doxygen REQUIRED) doxygen_add_docs(z_docs Code) diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt index 3133dbe74d..856b64d0b7 100644 --- a/GeneralsMD/Code/CMakeLists.txt +++ b/GeneralsMD/Code/CMakeLists.txt @@ -19,6 +19,10 @@ target_include_directories(zi_libraries_source_wwvegas_ww3d2 INTERFACE "Librarie target_include_directories(zi_libraries_source_wwvegas_wwmath INTERFACE "Libraries/Source/WWVegas/WWMath") target_include_directories(zi_libraries_source_wwvegas_wwsaveload INTERFACE "Libraries/Source/WWVegas/WWSaveLoad") target_include_directories(zi_main INTERFACE "Main") + +target_compile_definitions(zi_always INTERFACE + RTS_ZEROHOUR=1 +) target_link_libraries(zi_always INTERFACE core_utility zi_libraries_include diff --git a/GeneralsMD/Code/GameEngine/CMakeLists.txt b/GeneralsMD/Code/GameEngine/CMakeLists.txt index 4e9ec56354..425eba687a 100644 --- a/GeneralsMD/Code/GameEngine/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngine/CMakeLists.txt @@ -1,1179 +1,1179 @@ -set(GAMEENGINE_SRC - Include/Common/AcademyStats.h - Include/Common/ActionManager.h - Include/Common/ArchiveFile.h - Include/Common/ArchiveFileSystem.h - Include/Common/AsciiString.h - Include/Common/AudioAffect.h - Include/Common/AudioEventInfo.h - Include/Common/AudioEventRTS.h - Include/Common/AudioHandleSpecialValues.h - Include/Common/AudioRandomValue.h - Include/Common/AudioRequest.h - Include/Common/AudioSettings.h - Include/Common/BattleHonors.h - Include/Common/BezFwdIterator.h - Include/Common/BezierSegment.h - Include/Common/BitFlags.h - Include/Common/BitFlagsIO.h - Include/Common/BorderColors.h - Include/Common/BuildAssistant.h - Include/Common/CDManager.h - Include/Common/ClientUpdateModule.h - Include/Common/CommandLine.h - Include/Common/CopyProtection.h - Include/Common/crc.h - Include/Common/CRCDebug.h - Include/Common/CriticalSection.h - Include/Common/CustomMatchPreferences.h - Include/Common/DamageFX.h - Include/Common/DataChunk.h - Include/Common/Debug.h - Include/Common/Dict.h - Include/Common/Directory.h - Include/Common/DisabledTypes.h - Include/Common/DiscreteCircle.h - Include/Common/DrawModule.h - Include/Common/DynamicAudioEventInfo.h - Include/Common/encrypt.h - Include/Common/Energy.h - Include/Common/Errors.h - Include/Common/file.h - Include/Common/FileSystem.h - Include/Common/FunctionLexicon.h - Include/Common/GameAudio.h - Include/Common/GameCommon.h - Include/Common/GameEngine.h - Include/Common/GameLOD.h - Include/Common/GameMemory.h - Include/Common/GameMusic.h - Include/Common/GameSounds.h - Include/Common/GameSpyMiscPreferences.h - Include/Common/GameState.h - Include/Common/GameStateMap.h - Include/Common/GameType.h - Include/Common/Geometry.h - Include/Common/GlobalData.h - Include/Common/Handicap.h - Include/Common/IgnorePreferences.h - Include/Common/INI.h - Include/Common/INIException.h - Include/Common/KindOf.h - Include/Common/LadderPreferences.h - Include/Common/Language.h - Include/Common/LatchRestore.h - Include/Common/List.h - Include/Common/LocalFile.h - Include/Common/LocalFileSystem.h - Include/Common/MapObject.h - Include/Common/MapReaderWriterInfo.h - Include/Common/MessageStream.h - Include/Common/MiniLog.h - Include/Common/MiscAudio.h - Include/Common/MissionStats.h - Include/Common/ModelState.h - Include/Common/Module.h - Include/Common/ModuleFactory.h - Include/Common/Money.h - Include/Common/MultiplayerSettings.h - Include/Common/NameKeyGenerator.h - Include/Common/ObjectStatusTypes.h - Include/Common/OSDisplay.h - Include/Common/Overridable.h - Include/Common/Override.h - Include/Common/PartitionSolver.h - Include/Common/PerfMetrics.h - Include/Common/PerfTimer.h - Include/Common/Player.h - Include/Common/PlayerList.h - Include/Common/PlayerTemplate.h - Include/Common/ProductionPrerequisite.h - Include/Common/QuickmatchPreferences.h - Include/Common/QuotedPrintable.h - Include/Common/Radar.h - Include/Common/RAMFile.h - Include/Common/RandomValue.h - Include/Common/Recorder.h - Include/Common/Registry.h - Include/Common/ResourceGatheringManager.h - Include/Common/Science.h - Include/Common/ScopedMutex.h - Include/Common/ScoreKeeper.h - Include/Common/simpleplayer.h - Include/Common/SkirmishBattleHonors.h - Include/Common/SkirmishPreferences.h - Include/Common/Snapshot.h - Include/Common/SparseMatchFinder.h - Include/Common/SpecialPower.h - Include/Common/SpecialPowerMaskType.h - Include/Common/SpecialPowerType.h - Include/Common/StackDump.h - Include/Common/StateMachine.h - Include/Common/StatsCollector.h - Include/Common/STLTypedefs.h - Include/Common/StreamingArchiveFile.h - Include/Common/SubsystemInterface.h - Include/Common/SystemInfo.h - Include/Common/Team.h - Include/Common/Terrain.h - Include/Common/TerrainTypes.h - Include/Common/Thing.h - Include/Common/ThingFactory.h - Include/Common/ThingSort.h - Include/Common/ThingTemplate.h - Include/Common/TunnelTracker.h - Include/Common/UnicodeString.h - Include/Common/UnitTimings.h - Include/Common/Upgrade.h - Include/Common/urllaunch.h - Include/Common/UserPreferences.h - Include/Common/version.h - Include/Common/WellKnownKeys.h - Include/Common/Xfer.h - Include/Common/XferCRC.h - Include/Common/XferDeepCRC.h - Include/Common/XferLoad.h - Include/Common/XferSave.h - Include/GameClient/Anim2D.h - Include/GameClient/AnimateWindowManager.h - Include/GameClient/CampaignManager.h - Include/GameClient/CDCheck.h - Include/GameClient/ChallengeGenerals.h - Include/GameClient/ClientRandomValue.h - Include/GameClient/Color.h - Include/GameClient/CommandXlat.h - Include/GameClient/ControlBar.h - Include/GameClient/ControlBarResizer.h - Include/GameClient/ControlBarScheme.h - Include/GameClient/Credits.h - Include/GameClient/DebugDisplay.h - Include/GameClient/Diplomacy.h - Include/GameClient/DisconnectMenu.h - Include/GameClient/Display.h - Include/GameClient/DisplayString.h - Include/GameClient/DisplayStringManager.h - Include/GameClient/Drawable.h - Include/GameClient/DrawableInfo.h - Include/GameClient/DrawGroupInfo.h - Include/GameClient/EstablishConnectionsMenu.h - Include/GameClient/Eva.h - Include/GameClient/ExtendedMessageBox.h - Include/GameClient/FontDesc.h - Include/GameClient/FXList.h - Include/GameClient/Gadget.h - Include/GameClient/GadgetCheckBox.h - Include/GameClient/GadgetComboBox.h - Include/GameClient/GadgetListBox.h - Include/GameClient/GadgetProgressBar.h - Include/GameClient/GadgetPushButton.h - Include/GameClient/GadgetRadioButton.h - Include/GameClient/GadgetSlider.h - Include/GameClient/GadgetStaticText.h - Include/GameClient/GadgetTabControl.h - Include/GameClient/GadgetTextEntry.h - Include/GameClient/GameClient.h - Include/GameClient/GameFont.h - Include/GameClient/GameInfoWindow.h - Include/GameClient/GameText.h - Include/GameClient/GameWindow.h - Include/GameClient/GameWindowGlobal.h - Include/GameClient/GameWindowID.h - Include/GameClient/GameWindowManager.h - Include/GameClient/GameWindowTransitions.h - Include/GameClient/GlobalLanguage.h - Include/GameClient/GraphDraw.h - Include/GameClient/GUICallbacks.h - Include/GameClient/GUICommandTranslator.h - Include/GameClient/HeaderTemplate.h - Include/GameClient/HintSpy.h - Include/GameClient/HotKey.h - Include/GameClient/Image.h - Include/GameClient/IMEManager.h - Include/GameClient/InGameUI.h - Include/GameClient/Keyboard.h - Include/GameClient/KeyDefs.h - Include/GameClient/LanguageFilter.h - Include/GameClient/Line2D.h - Include/GameClient/LoadScreen.h - Include/GameClient/LookAtXlat.h - Include/GameClient/MapUtil.h - Include/GameClient/MessageBox.h - Include/GameClient/MetaEvent.h - Include/GameClient/Module/AnimatedParticleSysBoneClientUpdate.h - Include/GameClient/Module/BeaconClientUpdate.h - Include/GameClient/Module/SwayClientUpdate.h - Include/GameClient/Mouse.h - Include/GameClient/ParabolicEase.h - Include/GameClient/ParticleSys.h - Include/GameClient/PlaceEventTranslator.h - Include/GameClient/ProcessAnimateWindow.h - Include/GameClient/RadiusDecal.h - Include/GameClient/RayEffect.h - Include/GameClient/SelectionInfo.h - Include/GameClient/SelectionXlat.h - Include/GameClient/Shadow.h - Include/GameClient/Shell.h - Include/GameClient/ShellHooks.h - Include/GameClient/ShellMenuScheme.h - Include/GameClient/Smudge.h - Include/GameClient/Snow.h - Include/GameClient/Statistics.h - Include/GameClient/TerrainRoads.h - Include/GameClient/TerrainVisual.h - Include/GameClient/VideoPlayer.h - Include/GameClient/View.h - Include/GameClient/Water.h - Include/GameClient/WindowLayout.h - Include/GameClient/WindowVideoManager.h - Include/GameClient/WindowXlat.h - Include/GameClient/WinInstanceData.h - Include/GameLogic/AI.h - Include/GameLogic/AIDock.h - Include/GameLogic/AIGuard.h - Include/GameLogic/AIGuardRetaliate.h - Include/GameLogic/AIPathfind.h - Include/GameLogic/AIPlayer.h - Include/GameLogic/AISkirmishPlayer.h - Include/GameLogic/AIStateMachine.h - Include/GameLogic/AITNGuard.h - Include/GameLogic/Armor.h - Include/GameLogic/ArmorSet.h - Include/GameLogic/CaveSystem.h - Include/GameLogic/CrateSystem.h - Include/GameLogic/Damage.h - Include/GameLogic/ExperienceTracker.h - Include/GameLogic/FiringTracker.h - Include/GameLogic/FPUControl.h - Include/GameLogic/GameLogic.h - Include/GameLogic/GhostObject.h - Include/GameLogic/Locomotor.h - Include/GameLogic/LocomotorSet.h - Include/GameLogic/LogicRandomValue.h - Include/GameLogic/Module/ActiveBody.h - Include/GameLogic/Module/ActiveShroudUpgrade.h - Include/GameLogic/Module/AIUpdate.h - Include/GameLogic/Module/AnimationSteeringUpdate.h - Include/GameLogic/Module/ArmorUpgrade.h - Include/GameLogic/Module/AssaultTransportAIUpdate.h - Include/GameLogic/Module/AssistedTargetingUpdate.h - Include/GameLogic/Module/AutoDepositUpdate.h - Include/GameLogic/Module/AutoFindHealingUpdate.h - Include/GameLogic/Module/AutoHealBehavior.h - Include/GameLogic/Module/BaikonurLaunchPower.h - Include/GameLogic/Module/BaseRegenerateUpdate.h - Include/GameLogic/Module/BattleBusSlowDeathBehavior.h - Include/GameLogic/Module/BattlePlanUpdate.h - Include/GameLogic/Module/BehaviorModule.h - Include/GameLogic/Module/BodyModule.h - Include/GameLogic/Module/BoneFXDamage.h - Include/GameLogic/Module/BoneFXUpdate.h - Include/GameLogic/Module/BridgeBehavior.h - Include/GameLogic/Module/BridgeScaffoldBehavior.h - Include/GameLogic/Module/BridgeTowerBehavior.h - Include/GameLogic/Module/BunkerBusterBehavior.h - Include/GameLogic/Module/CashBountyPower.h - Include/GameLogic/Module/CashHackSpecialPower.h - Include/GameLogic/Module/CaveContain.h - Include/GameLogic/Module/CheckpointUpdate.h - Include/GameLogic/Module/ChinookAIUpdate.h - Include/GameLogic/Module/CleanupAreaPower.h - Include/GameLogic/Module/CleanupHazardUpdate.h - Include/GameLogic/Module/CollideModule.h - Include/GameLogic/Module/CommandButtonHuntUpdate.h - Include/GameLogic/Module/CommandSetUpgrade.h - Include/GameLogic/Module/ContainModule.h - Include/GameLogic/Module/ConvertToCarBombCrateCollide.h - Include/GameLogic/Module/ConvertToHijackedVehicleCrateCollide.h - Include/GameLogic/Module/CostModifierUpgrade.h - Include/GameLogic/Module/CountermeasuresBehavior.h - Include/GameLogic/Module/CrateCollide.h - Include/GameLogic/Module/CreateCrateDie.h - Include/GameLogic/Module/CreateModule.h - Include/GameLogic/Module/CreateObjectDie.h - Include/GameLogic/Module/CrushDie.h - Include/GameLogic/Module/DamageModule.h - Include/GameLogic/Module/DamDie.h - Include/GameLogic/Module/DefaultProductionExitUpdate.h - Include/GameLogic/Module/DefectorSpecialPower.h - Include/GameLogic/Module/DeletionUpdate.h - Include/GameLogic/Module/DeliverPayloadAIUpdate.h - Include/GameLogic/Module/DemoralizeSpecialPower.h - Include/GameLogic/Module/DemoTrapUpdate.h - Include/GameLogic/Module/DeployStyleAIUpdate.h - Include/GameLogic/Module/DestroyDie.h - Include/GameLogic/Module/DestroyModule.h - Include/GameLogic/Module/DieModule.h - Include/GameLogic/Module/DockUpdate.h - Include/GameLogic/Module/DozerAIUpdate.h - Include/GameLogic/Module/DumbProjectileBehavior.h - Include/GameLogic/Module/DynamicGeometryInfoUpdate.h - Include/GameLogic/Module/DynamicShroudClearingRangeUpdate.h - Include/GameLogic/Module/EjectPilotDie.h - Include/GameLogic/Module/EMPUpdate.h - Include/GameLogic/Module/EnemyNearUpdate.h - Include/GameLogic/Module/ExperienceScalarUpgrade.h - Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h - Include/GameLogic/Module/FireSpreadUpdate.h - Include/GameLogic/Module/FirestormDynamicGeometryInfoUpdate.h - Include/GameLogic/Module/FireWeaponCollide.h - Include/GameLogic/Module/FireWeaponPower.h - Include/GameLogic/Module/FireWeaponUpdate.h - Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h - Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h - Include/GameLogic/Module/FlammableUpdate.h - Include/GameLogic/Module/FlightDeckBehavior.h - Include/GameLogic/Module/FloatUpdate.h - Include/GameLogic/Module/FXListDie.h - Include/GameLogic/Module/GarrisonContain.h - Include/GameLogic/Module/GenerateMinefieldBehavior.h - Include/GameLogic/Module/GrantScienceUpgrade.h - Include/GameLogic/Module/GrantStealthBehavior.h - Include/GameLogic/Module/GrantUpgradeCreate.h - Include/GameLogic/Module/HackInternetAIUpdate.h - Include/GameLogic/Module/HealContain.h - Include/GameLogic/Module/HealCrateCollide.h - Include/GameLogic/Module/HeightDieUpdate.h - Include/GameLogic/Module/HelicopterSlowDeathUpdate.h - Include/GameLogic/Module/HelixContain.h - Include/GameLogic/Module/HighlanderBody.h - Include/GameLogic/Module/HijackerUpdate.h - Include/GameLogic/Module/HiveStructureBody.h - Include/GameLogic/Module/HordeUpdate.h - Include/GameLogic/Module/ImmortalBody.h - Include/GameLogic/Module/InactiveBody.h - Include/GameLogic/Module/InstantDeathBehavior.h - Include/GameLogic/Module/InternetHackContain.h - Include/GameLogic/Module/JetAIUpdate.h - Include/GameLogic/Module/JetSlowDeathBehavior.h - Include/GameLogic/Module/KeepObjectDie.h - Include/GameLogic/Module/LaserUpdate.h - Include/GameLogic/Module/LifetimeUpdate.h - Include/GameLogic/Module/LockWeaponCreate.h - Include/GameLogic/Module/LocomotorSetUpgrade.h - Include/GameLogic/Module/MaxHealthUpgrade.h - Include/GameLogic/Module/MinefieldBehavior.h - Include/GameLogic/Module/MissileAIUpdate.h - Include/GameLogic/Module/MissileLauncherBuildingUpdate.h - Include/GameLogic/Module/MobMemberSlavedUpdate.h - Include/GameLogic/Module/MobNexusContain.h - Include/GameLogic/Module/ModelConditionUpgrade.h - Include/GameLogic/Module/MoneyCrateCollide.h - Include/GameLogic/Module/NeutronBlastBehavior.h - Include/GameLogic/Module/NeutronMissileSlowDeathUpdate.h - Include/GameLogic/Module/NeutronMissileUpdate.h - Include/GameLogic/Module/ObjectCreationUpgrade.h - Include/GameLogic/Module/ObjectDefectionHelper.h - Include/GameLogic/Module/ObjectHelper.h - Include/GameLogic/Module/ObjectRepulsorHelper.h - Include/GameLogic/Module/ObjectSMCHelper.h - Include/GameLogic/Module/ObjectWeaponStatusHelper.h - Include/GameLogic/Module/OCLSpecialPower.h - Include/GameLogic/Module/OCLUpdate.h - Include/GameLogic/Module/OpenContain.h - Include/GameLogic/Module/OverchargeBehavior.h - Include/GameLogic/Module/OverlordContain.h - Include/GameLogic/Module/ParachuteContain.h - Include/GameLogic/Module/ParkingPlaceBehavior.h - Include/GameLogic/Module/ParticleUplinkCannonUpdate.h - Include/GameLogic/Module/PassengersFireUpgrade.h - Include/GameLogic/Module/PhysicsUpdate.h - Include/GameLogic/Module/PilotFindVehicleUpdate.h - Include/GameLogic/Module/PointDefenseLaserUpdate.h - Include/GameLogic/Module/PoisonedBehavior.h - Include/GameLogic/Module/PowerPlantUpdate.h - Include/GameLogic/Module/PowerPlantUpgrade.h - Include/GameLogic/Module/POWTruckAIUpdate.h - Include/GameLogic/Module/POWTruckBehavior.h - Include/GameLogic/Module/PreorderCreate.h - Include/GameLogic/Module/PrisonBehavior.h - Include/GameLogic/Module/PrisonDockUpdate.h - Include/GameLogic/Module/ProductionUpdate.h - Include/GameLogic/Module/ProjectileStreamUpdate.h - Include/GameLogic/Module/ProneUpdate.h - Include/GameLogic/Module/PropagandaCenterBehavior.h - Include/GameLogic/Module/PropagandaTowerBehavior.h - Include/GameLogic/Module/QueueProductionExitUpdate.h - Include/GameLogic/Module/RadarUpdate.h - Include/GameLogic/Module/RadarUpgrade.h - Include/GameLogic/Module/RadiusDecalUpdate.h - Include/GameLogic/Module/RailedTransportAIUpdate.h - Include/GameLogic/Module/RailedTransportContain.h - Include/GameLogic/Module/RailedTransportDockUpdate.h - Include/GameLogic/Module/RailroadGuideAIUpdate.h - Include/GameLogic/Module/RebuildHoleBehavior.h - Include/GameLogic/Module/RebuildHoleExposeDie.h - Include/GameLogic/Module/RepairDockUpdate.h - Include/GameLogic/Module/ReplaceObjectUpgrade.h - Include/GameLogic/Module/RiderChangeContain.h - Include/GameLogic/Module/SabotageCommandCenterCrateCollide.h - Include/GameLogic/Module/SabotageFakeBuildingCrateCollide.h - Include/GameLogic/Module/SabotageInternetCenterCrateCollide.h - Include/GameLogic/Module/SabotageMilitaryFactoryCrateCollide.h - Include/GameLogic/Module/SabotagePowerPlantCrateCollide.h - Include/GameLogic/Module/SabotageSuperweaponCrateCollide.h - Include/GameLogic/Module/SabotageSupplyCenterCrateCollide.h - Include/GameLogic/Module/SabotageSupplyDropzoneCrateCollide.h - Include/GameLogic/Module/SalvageCrateCollide.h - Include/GameLogic/Module/ShroudCrateCollide.h - Include/GameLogic/Module/SlavedUpdate.h - Include/GameLogic/Module/SlowDeathBehavior.h - Include/GameLogic/Module/SmartBombTargetHomingUpdate.h - Include/GameLogic/Module/SpawnBehavior.h - Include/GameLogic/Module/SpawnPointProductionExitUpdate.h - Include/GameLogic/Module/SpecialAbility.h - Include/GameLogic/Module/SpecialAbilityUpdate.h - Include/GameLogic/Module/SpecialPowerCompletionDie.h - Include/GameLogic/Module/SpecialPowerCreate.h - Include/GameLogic/Module/SpecialPowerModule.h - Include/GameLogic/Module/SpecialPowerUpdateModule.h - Include/GameLogic/Module/SpectreGunshipDeploymentUpdate.h - Include/GameLogic/Module/SpectreGunshipUpdate.h - Include/GameLogic/Module/SpyVisionSpecialPower.h - Include/GameLogic/Module/SpyVisionUpdate.h - Include/GameLogic/Module/SquishCollide.h - Include/GameLogic/Module/StatusBitsUpgrade.h - Include/GameLogic/Module/StatusDamageHelper.h - Include/GameLogic/Module/StealthDetectorUpdate.h - Include/GameLogic/Module/StealthUpdate.h - Include/GameLogic/Module/StealthUpgrade.h - Include/GameLogic/Module/StickyBombUpdate.h - Include/GameLogic/Module/StructureBody.h - Include/GameLogic/Module/StructureCollapseUpdate.h - Include/GameLogic/Module/StructureToppleUpdate.h - Include/GameLogic/Module/SubdualDamageHelper.h - Include/GameLogic/Module/SubObjectsUpgrade.h - Include/GameLogic/Module/SupplyCenterCreate.h - Include/GameLogic/Module/SupplyCenterDockUpdate.h - Include/GameLogic/Module/SupplyCenterProductionExitUpdate.h - Include/GameLogic/Module/SupplyTruckAIUpdate.h - Include/GameLogic/Module/SupplyWarehouseCreate.h - Include/GameLogic/Module/SupplyWarehouseCripplingBehavior.h - Include/GameLogic/Module/SupplyWarehouseDockUpdate.h - Include/GameLogic/Module/TechBuildingBehavior.h - Include/GameLogic/Module/TempWeaponBonusHelper.h - Include/GameLogic/Module/TensileFormationUpdate.h - Include/GameLogic/Module/ToppleUpdate.h - Include/GameLogic/Module/TransitionDamageFX.h - Include/GameLogic/Module/TransportAIUpdate.h - Include/GameLogic/Module/TransportContain.h - Include/GameLogic/Module/TunnelContain.h - Include/GameLogic/Module/UndeadBody.h - Include/GameLogic/Module/UnitCrateCollide.h - Include/GameLogic/Module/UnpauseSpecialPowerUpgrade.h - Include/GameLogic/Module/UpdateModule.h - Include/GameLogic/Module/UpgradeDie.h - Include/GameLogic/Module/UpgradeModule.h - Include/GameLogic/Module/VeterancyCrateCollide.h - Include/GameLogic/Module/VeterancyGainCreate.h - Include/GameLogic/Module/WanderAIUpdate.h - Include/GameLogic/Module/WaveGuideUpdate.h - Include/GameLogic/Module/WeaponBonusUpdate.h - Include/GameLogic/Module/WeaponBonusUpgrade.h - Include/GameLogic/Module/WeaponSetUpgrade.h - Include/GameLogic/Module/WorkerAIUpdate.h - Include/GameLogic/Object.h - Include/GameLogic/ObjectCreationList.h - Include/GameLogic/ObjectIter.h - Include/GameLogic/ObjectScriptStatusBits.h - Include/GameLogic/ObjectTypes.h - Include/GameLogic/PartitionManager.h - Include/GameLogic/PolygonTrigger.h - Include/GameLogic/Powers.h - Include/GameLogic/RankInfo.h - Include/GameLogic/ScriptActions.h - Include/GameLogic/ScriptConditions.h - Include/GameLogic/ScriptEngine.h - Include/GameLogic/Scripts.h - Include/GameLogic/SidesList.h - Include/GameLogic/Squad.h - Include/GameLogic/TerrainLogic.h - Include/GameLogic/TurretAI.h - Include/GameLogic/VictoryConditions.h - Include/GameLogic/Weapon.h - Include/GameLogic/WeaponBonusConditionFlags.h - Include/GameLogic/WeaponSet.h - Include/GameLogic/WeaponSetFlags.h - Include/GameLogic/WeaponSetType.h - Include/GameLogic/WeaponStatus.h - Include/GameNetwork/Connection.h - Include/GameNetwork/ConnectionManager.h - Include/GameNetwork/DisconnectManager.h - Include/GameNetwork/DownloadManager.h - Include/GameNetwork/FileTransfer.h - Include/GameNetwork/FirewallHelper.h - Include/GameNetwork/FrameData.h - Include/GameNetwork/FrameDataManager.h - Include/GameNetwork/FrameMetrics.h - Include/GameNetwork/GameInfo.h - Include/GameNetwork/GameMessageParser.h - Include/GameNetwork/GameSpy/BuddyDefs.h - Include/GameNetwork/GameSpy/BuddyThread.h - Include/GameNetwork/GameSpy/GameResultsThread.h - Include/GameNetwork/GameSpy/GSConfig.h - Include/GameNetwork/GameSpy/LadderDefs.h - Include/GameNetwork/GameSpy/LobbyUtils.h - Include/GameNetwork/GameSpy/MainMenuUtils.h - Include/GameNetwork/GameSpy/PeerDefs.h - Include/GameNetwork/GameSpy/PeerDefsImplementation.h - Include/GameNetwork/GameSpy/PeerThread.h - Include/GameNetwork/GameSpy/PersistentStorageDefs.h - Include/GameNetwork/GameSpy/PersistentStorageThread.h - Include/GameNetwork/GameSpy/PingThread.h - Include/GameNetwork/GameSpy/StagingRoomGameInfo.h - Include/GameNetwork/GameSpy/ThreadUtils.h - Include/GameNetwork/GameSpyChat.h - Include/GameNetwork/GameSpyGameInfo.h - Include/GameNetwork/GameSpyGP.h - Include/GameNetwork/GameSpyOverlay.h - Include/GameNetwork/GameSpyThread.h - Include/GameNetwork/GUIUtil.h - Include/GameNetwork/IPEnumeration.h - Include/GameNetwork/LANAPI.h - Include/GameNetwork/LANAPICallbacks.h - Include/GameNetwork/LANGameInfo.h - Include/GameNetwork/LANPlayer.h - Include/GameNetwork/NAT.h - Include/GameNetwork/NetCommandList.h - Include/GameNetwork/NetCommandMsg.h - Include/GameNetwork/NetCommandRef.h - Include/GameNetwork/NetCommandWrapperList.h - Include/GameNetwork/NetPacket.h - Include/GameNetwork/NetworkDefs.h - Include/GameNetwork/NetworkInterface.h - Include/GameNetwork/networkutil.h - Include/GameNetwork/RankPointValue.h - Include/GameNetwork/Transport.h - Include/GameNetwork/udp.h - Include/GameNetwork/User.h - Include/GameNetwork/WOLBrowser/FEBDispatch.h - Include/GameNetwork/WOLBrowser/WebBrowser.h - Include/Precompiled/PreRTS.h - Source/Common/Audio/AudioEventRTS.cpp - Source/Common/Audio/AudioRequest.cpp - Source/Common/Audio/DynamicAudioEventInfo.cpp - Source/Common/Audio/GameAudio.cpp - Source/Common/Audio/GameMusic.cpp - Source/Common/Audio/GameSounds.cpp - #Source/Common/Audio/simpleplayer.cpp - #Source/Common/Audio/urllaunch.cpp - Source/Common/Bezier/BezFwdIterator.cpp - Source/Common/Bezier/BezierSegment.cpp - Source/Common/BitFlags.cpp - Source/Common/CommandLine.cpp - Source/Common/crc.cpp - Source/Common/CRCDebug.cpp - Source/Common/DamageFX.cpp - Source/Common/Dict.cpp - Source/Common/DiscreteCircle.cpp - Source/Common/GameEngine.cpp - Source/Common/GameLOD.cpp - Source/Common/GameMain.cpp - Source/Common/GlobalData.cpp - Source/Common/INI/INI.cpp - Source/Common/INI/INIAiData.cpp - Source/Common/INI/INIAnimation.cpp - Source/Common/INI/INIAudioEventInfo.cpp - Source/Common/INI/INICommandButton.cpp - Source/Common/INI/INICommandSet.cpp - Source/Common/INI/INIControlBarScheme.cpp - Source/Common/INI/INICrate.cpp - Source/Common/INI/INIDamageFX.cpp - Source/Common/INI/INIDrawGroupInfo.cpp - Source/Common/INI/INIGameData.cpp - Source/Common/INI/INIMapCache.cpp - Source/Common/INI/INIMapData.cpp - Source/Common/INI/INIMappedImage.cpp - Source/Common/INI/INIMiscAudio.cpp - Source/Common/INI/INIModel.cpp - Source/Common/INI/INIMultiplayer.cpp - Source/Common/INI/INIObject.cpp - Source/Common/INI/INIParticleSys.cpp - Source/Common/INI/INISpecialPower.cpp - Source/Common/INI/INITerrain.cpp - Source/Common/INI/INITerrainBridge.cpp - Source/Common/INI/INITerrainRoad.cpp - Source/Common/INI/INIUpgrade.cpp - Source/Common/INI/INIVideo.cpp - Source/Common/INI/INIWater.cpp - Source/Common/INI/INIWeapon.cpp - Source/Common/INI/INIWebpageURL.cpp - Source/Common/Language.cpp - Source/Common/MessageStream.cpp - Source/Common/MiniLog.cpp - Source/Common/MultiplayerSettings.cpp - Source/Common/NameKeyGenerator.cpp - Source/Common/PartitionSolver.cpp - Source/Common/PerfTimer.cpp - Source/Common/RandomValue.cpp - Source/Common/Recorder.cpp - Source/Common/RTS/AcademyStats.cpp - Source/Common/RTS/ActionManager.cpp - Source/Common/RTS/Energy.cpp - Source/Common/RTS/Handicap.cpp - Source/Common/RTS/MissionStats.cpp - Source/Common/RTS/Money.cpp - Source/Common/RTS/Player.cpp - Source/Common/RTS/PlayerList.cpp - Source/Common/RTS/PlayerTemplate.cpp - Source/Common/RTS/ProductionPrerequisite.cpp - Source/Common/RTS/ResourceGatheringManager.cpp - Source/Common/RTS/Science.cpp - Source/Common/RTS/ScoreKeeper.cpp - Source/Common/RTS/SpecialPower.cpp - Source/Common/RTS/Team.cpp - Source/Common/RTS/TunnelTracker.cpp - Source/Common/SkirmishBattleHonors.cpp - Source/Common/StateMachine.cpp - Source/Common/StatsCollector.cpp - Source/Common/System/ArchiveFile.cpp - Source/Common/System/ArchiveFileSystem.cpp - Source/Common/System/AsciiString.cpp - Source/Common/System/BuildAssistant.cpp - Source/Common/System/CDManager.cpp - Source/Common/System/CopyProtection.cpp - Source/Common/System/CriticalSection.cpp - Source/Common/System/DataChunk.cpp - Source/Common/System/Debug.cpp - Source/Common/System/Directory.cpp - Source/Common/System/DisabledTypes.cpp - Source/Common/System/encrypt.cpp - Source/Common/System/File.cpp - Source/Common/System/FileSystem.cpp - Source/Common/System/FunctionLexicon.cpp - Source/Common/System/GameCommon.cpp - #Source/Common/System/GameMemory.cpp - Source/Common/System/GameType.cpp - Source/Common/System/Geometry.cpp - Source/Common/System/KindOf.cpp - Source/Common/System/List.cpp - Source/Common/System/LocalFile.cpp - Source/Common/System/LocalFileSystem.cpp - #Source/Common/System/MemoryInit.cpp - Source/Common/System/ObjectStatusTypes.cpp - Source/Common/System/QuotedPrintable.cpp - Source/Common/System/Radar.cpp - Source/Common/System/RAMFile.cpp - Source/Common/System/registry.cpp - Source/Common/System/SaveGame/GameState.cpp - Source/Common/System/SaveGame/GameStateMap.cpp - Source/Common/System/Snapshot.cpp - Source/Common/System/StackDump.cpp - Source/Common/System/StreamingArchiveFile.cpp - Source/Common/System/SubsystemInterface.cpp - Source/Common/System/Trig.cpp - Source/Common/System/UnicodeString.cpp - Source/Common/System/Upgrade.cpp - Source/Common/System/Xfer.cpp - Source/Common/System/XferCRC.cpp - Source/Common/System/XferLoad.cpp - Source/Common/System/XferSave.cpp - Source/Common/TerrainTypes.cpp - Source/Common/Thing/DrawModule.cpp - Source/Common/Thing/Module.cpp - Source/Common/Thing/ModuleFactory.cpp - Source/Common/Thing/Thing.cpp - Source/Common/Thing/ThingFactory.cpp - Source/Common/Thing/ThingTemplate.cpp - Source/Common/UserPreferences.cpp - Source/Common/version.cpp - Source/GameClient/Color.cpp - Source/GameClient/Credits.cpp - Source/GameClient/Display.cpp - Source/GameClient/DisplayString.cpp - Source/GameClient/DisplayStringManager.cpp - Source/GameClient/Drawable.cpp - Source/GameClient/Drawable/Update/AnimatedParticleSysBoneClientUpdate.cpp - Source/GameClient/Drawable/Update/BeaconClientUpdate.cpp - Source/GameClient/Drawable/Update/SwayClientUpdate.cpp - Source/GameClient/DrawGroupInfo.cpp - Source/GameClient/Eva.cpp - Source/GameClient/FXList.cpp - Source/GameClient/GameClient.cpp - Source/GameClient/GameClientDispatch.cpp - Source/GameClient/GameText.cpp - Source/GameClient/GlobalLanguage.cpp - Source/GameClient/GraphDraw.cpp - Source/GameClient/GUI/AnimateWindowManager.cpp - Source/GameClient/GUI/ChallengeGenerals.cpp - Source/GameClient/GUI/ControlBar/ControlBar.cpp - Source/GameClient/GUI/ControlBar/ControlBarBeacon.cpp - Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp - Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp - Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp - Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp - Source/GameClient/GUI/ControlBar/ControlBarOCLTimer.cpp - Source/GameClient/GUI/ControlBar/ControlBarPrintPositions.cpp - Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp - Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp - Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp - Source/GameClient/GUI/ControlBar/ControlBarUnderConstruction.cpp - Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp - Source/GameClient/GUI/EstablishConnectionsMenu/EstablishConnectionsMenu.cpp - Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp - Source/GameClient/GUI/Gadget/GadgetComboBox.cpp - Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp - Source/GameClient/GUI/Gadget/GadgetListBox.cpp - Source/GameClient/GUI/Gadget/GadgetProgressBar.cpp - Source/GameClient/GUI/Gadget/GadgetPushButton.cpp - Source/GameClient/GUI/Gadget/GadgetRadioButton.cpp - Source/GameClient/GUI/Gadget/GadgetStaticText.cpp - Source/GameClient/GUI/Gadget/GadgetTabControl.cpp - Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp - Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp - Source/GameClient/GUI/GameFont.cpp - Source/GameClient/GUI/GameWindow.cpp - Source/GameClient/GUI/GameWindowGlobal.cpp - Source/GameClient/GUI/GameWindowManager.cpp - Source/GameClient/GUI/GameWindowManagerScript.cpp - Source/GameClient/GUI/GameWindowTransitions.cpp - Source/GameClient/GUI/GameWindowTransitionsStyles.cpp - Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp - Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp - Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp - Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp - Source/GameClient/GUI/GUICallbacks/GeneralsExpPoints.cpp - Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp - Source/GameClient/GUI/GUICallbacks/InGameChat.cpp - Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp - Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp - Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp - Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp - Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp - Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp - Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp - Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp - Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp - Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp - Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp - Source/GameClient/GUI/GUICallbacks/MessageBox.cpp - Source/GameClient/GUI/GUICallbacks/ReplayControls.cpp - Source/GameClient/GUI/HeaderTemplate.cpp - Source/GameClient/GUI/IMEManager.cpp - Source/GameClient/GUI/LoadScreen.cpp - Source/GameClient/GUI/ProcessAnimateWindow.cpp - Source/GameClient/GUI/Shell/Shell.cpp - Source/GameClient/GUI/Shell/ShellMenuScheme.cpp - Source/GameClient/GUI/WindowLayout.cpp - Source/GameClient/GUI/WindowVideoManager.cpp - Source/GameClient/GUI/WinInstanceData.cpp - Source/GameClient/InGameUI.cpp - Source/GameClient/Input/Keyboard.cpp - Source/GameClient/Input/Mouse.cpp - Source/GameClient/LanguageFilter.cpp - Source/GameClient/Line2D.cpp - Source/GameClient/MapUtil.cpp - Source/GameClient/MessageStream/CommandXlat.cpp - Source/GameClient/MessageStream/GUICommandTranslator.cpp - Source/GameClient/MessageStream/HintSpy.cpp - Source/GameClient/MessageStream/HotKey.cpp - Source/GameClient/MessageStream/LookAtXlat.cpp - Source/GameClient/MessageStream/MetaEvent.cpp - Source/GameClient/MessageStream/PlaceEventTranslator.cpp - Source/GameClient/MessageStream/SelectionXlat.cpp - Source/GameClient/MessageStream/WindowXlat.cpp - Source/GameClient/ParabolicEase.cpp - Source/GameClient/RadiusDecal.cpp - Source/GameClient/SelectionInfo.cpp - Source/GameClient/Snow.cpp - Source/GameClient/Statistics.cpp - Source/GameClient/System/Anim2D.cpp - Source/GameClient/System/CampaignManager.cpp - "Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp" - Source/GameClient/System/DebugDisplay.cpp - Source/GameClient/System/Image.cpp - Source/GameClient/System/ParticleSys.cpp - Source/GameClient/System/RayEffect.cpp - Source/GameClient/System/Smudge.cpp - Source/GameClient/Terrain/TerrainRoads.cpp - Source/GameClient/Terrain/TerrainVisual.cpp - Source/GameClient/VideoPlayer.cpp - Source/GameClient/VideoStream.cpp - Source/GameClient/View.cpp - Source/GameClient/Water.cpp - Source/GameLogic/AI/AI.cpp - Source/GameLogic/AI/AIDock.cpp - Source/GameLogic/AI/AIGroup.cpp - Source/GameLogic/AI/AIGuard.cpp - Source/GameLogic/AI/AIGuardRetaliate.cpp - Source/GameLogic/AI/AIPathfind.cpp - Source/GameLogic/AI/AIPlayer.cpp - Source/GameLogic/AI/AISkirmishPlayer.cpp - Source/GameLogic/AI/AIStates.cpp - Source/GameLogic/AI/AITNGuard.cpp - Source/GameLogic/AI/Squad.cpp - Source/GameLogic/AI/TurretAI.cpp - Source/GameLogic/Map/PolygonTrigger.cpp - Source/GameLogic/Map/SidesList.cpp - Source/GameLogic/Map/TerrainLogic.cpp - Source/GameLogic/Object/Armor.cpp - Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp - Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp - Source/GameLogic/Object/Behavior/BehaviorModule.cpp - Source/GameLogic/Object/Behavior/BridgeBehavior.cpp - Source/GameLogic/Object/Behavior/BridgeScaffoldBehavior.cpp - Source/GameLogic/Object/Behavior/BridgeTowerBehavior.cpp - Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp - Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp - Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp - Source/GameLogic/Object/Behavior/FireWeaponWhenDamagedBehavior.cpp - Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp - Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp - Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp - Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp - Source/GameLogic/Object/Behavior/InstantDeathBehavior.cpp - Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp - Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp - Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp - Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp - Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp - Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp - Source/GameLogic/Object/Behavior/POWTruckBehavior.cpp - Source/GameLogic/Object/Behavior/PrisonBehavior.cpp - Source/GameLogic/Object/Behavior/PropagandaCenterBehavior.cpp - Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp - Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp - Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp - Source/GameLogic/Object/Behavior/SpawnBehavior.cpp - Source/GameLogic/Object/Behavior/SupplyWarehouseCripplingBehavior.cpp - Source/GameLogic/Object/Behavior/TechBuildingBehavior.cpp - Source/GameLogic/Object/Body/ActiveBody.cpp - Source/GameLogic/Object/Body/BodyModule.cpp - Source/GameLogic/Object/Body/HighlanderBody.cpp - Source/GameLogic/Object/Body/HiveStructureBody.cpp - Source/GameLogic/Object/Body/ImmortalBody.cpp - Source/GameLogic/Object/Body/InactiveBody.cpp - Source/GameLogic/Object/Body/StructureBody.cpp - Source/GameLogic/Object/Body/UndeadBody.cpp - Source/GameLogic/Object/Collide/CollideModule.cpp - Source/GameLogic/Object/Collide/CrateCollide/ConvertToCarBombCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/HealCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/MoneyCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/ShroudCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/UnitCrateCollide.cpp - Source/GameLogic/Object/Collide/CrateCollide/VeterancyCrateCollide.cpp - Source/GameLogic/Object/Collide/FireWeaponCollide.cpp - Source/GameLogic/Object/Collide/SquishCollide.cpp - Source/GameLogic/Object/Contain/CaveContain.cpp - Source/GameLogic/Object/Contain/GarrisonContain.cpp - Source/GameLogic/Object/Contain/HealContain.cpp - Source/GameLogic/Object/Contain/HelixContain.cpp - Source/GameLogic/Object/Contain/InternetHackContain.cpp - Source/GameLogic/Object/Contain/MobNexusContain.cpp - Source/GameLogic/Object/Contain/OpenContain.cpp - Source/GameLogic/Object/Contain/OverlordContain.cpp - Source/GameLogic/Object/Contain/ParachuteContain.cpp - Source/GameLogic/Object/Contain/RailedTransportContain.cpp - Source/GameLogic/Object/Contain/RiderChangeContain.cpp - Source/GameLogic/Object/Contain/TransportContain.cpp - Source/GameLogic/Object/Contain/TunnelContain.cpp - Source/GameLogic/Object/Create/CreateModule.cpp - Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp - Source/GameLogic/Object/Create/LockWeaponCreate.cpp - Source/GameLogic/Object/Create/PreorderCreate.cpp - Source/GameLogic/Object/Create/SpecialPowerCreate.cpp - Source/GameLogic/Object/Create/SupplyCenterCreate.cpp - Source/GameLogic/Object/Create/SupplyWarehouseCreate.cpp - Source/GameLogic/Object/Create/VeterancyGainCreate.cpp - Source/GameLogic/Object/Damage/BoneFXDamage.cpp - Source/GameLogic/Object/Damage/DamageModule.cpp - Source/GameLogic/Object/Damage/TransitionDamageFX.cpp - Source/GameLogic/Object/Destroy/DestroyModule.cpp - Source/GameLogic/Object/Die/CreateCrateDie.cpp - Source/GameLogic/Object/Die/CreateObjectDie.cpp - Source/GameLogic/Object/Die/CrushDie.cpp - Source/GameLogic/Object/Die/DamDie.cpp - Source/GameLogic/Object/Die/DestroyDie.cpp - Source/GameLogic/Object/Die/DieModule.cpp - Source/GameLogic/Object/Die/EjectPilotDie.cpp - Source/GameLogic/Object/Die/FXListDie.cpp - Source/GameLogic/Object/Die/KeepObjectDie.cpp - Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp - Source/GameLogic/Object/Die/SpecialPowerCompletionDie.cpp - Source/GameLogic/Object/Die/UpgradeDie.cpp - Source/GameLogic/Object/ExperienceTracker.cpp - Source/GameLogic/Object/FiringTracker.cpp - Source/GameLogic/Object/GhostObject.cpp - Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp - Source/GameLogic/Object/Helper/ObjectHelper.cpp - Source/GameLogic/Object/Helper/ObjectRepulsorHelper.cpp - Source/GameLogic/Object/Helper/ObjectSMCHelper.cpp - Source/GameLogic/Object/Helper/ObjectWeaponStatusHelper.cpp - Source/GameLogic/Object/Helper/StatusDamageHelper.cpp - Source/GameLogic/Object/Helper/SubdualDamageHelper.cpp - Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp - Source/GameLogic/Object/Locomotor.cpp - Source/GameLogic/Object/Object.cpp - Source/GameLogic/Object/ObjectCreationList.cpp - Source/GameLogic/Object/ObjectTypes.cpp - Source/GameLogic/Object/PartitionManager.cpp - Source/GameLogic/Object/SimpleObjectIterator.cpp - Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp - Source/GameLogic/Object/SpecialPower/CashBountyPower.cpp - Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp - Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp - Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp - Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp - Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp - Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp - Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp - Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp - Source/GameLogic/Object/SpecialPower/SpyVisionSpecialPower.cpp - Source/GameLogic/Object/Update/AIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/POWTruckAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/RailedTransportAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cpp - Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp - Source/GameLogic/Object/Update/AnimationSteeringUpdate.cpp - Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp - Source/GameLogic/Object/Update/AutoDepositUpdate.cpp - Source/GameLogic/Object/Update/AutoFindHealingUpdate.cpp - Source/GameLogic/Object/Update/BaseRenerateUpdate.cpp - Source/GameLogic/Object/Update/BattlePlanUpdate.cpp - Source/GameLogic/Object/Update/BoneFXUpdate.cpp - Source/GameLogic/Object/Update/CheckpointUpdate.cpp - Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp - Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp - Source/GameLogic/Object/Update/DeletionUpdate.cpp - Source/GameLogic/Object/Update/DemoTrapUpdate.cpp - Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp - Source/GameLogic/Object/Update/DockUpdate/PrisonDockUpdate.cpp - Source/GameLogic/Object/Update/DockUpdate/RailedTransportDockUpdate.cpp - Source/GameLogic/Object/Update/DockUpdate/RepairDockUpdate.cpp - Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp - Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp - Source/GameLogic/Object/Update/DynamicGeometryInfoUpdate.cpp - Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp - Source/GameLogic/Object/Update/EMPUpdate.cpp - Source/GameLogic/Object/Update/EnemyNearUpdate.cpp - Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp - Source/GameLogic/Object/Update/FireSpreadUpdate.cpp - Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cpp - Source/GameLogic/Object/Update/FireWeaponUpdate.cpp - Source/GameLogic/Object/Update/FlammableUpdate.cpp - Source/GameLogic/Object/Update/FloatUpdate.cpp - Source/GameLogic/Object/Update/HeightDieUpdate.cpp - Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp - Source/GameLogic/Object/Update/HijackerUpdate.cpp - Source/GameLogic/Object/Update/HordeUpdate.cpp - Source/GameLogic/Object/Update/LaserUpdate.cpp - Source/GameLogic/Object/Update/LifetimeUpdate.cpp - Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp - Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp - Source/GameLogic/Object/Update/NeutronMissileSlowDeathUpdate.cpp - Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp - Source/GameLogic/Object/Update/OCLUpdate.cpp - Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp - Source/GameLogic/Object/Update/PhysicsUpdate.cpp - Source/GameLogic/Object/Update/PilotFindVehicleUpdate.cpp - Source/GameLogic/Object/Update/PointDefenseLaserUpdate.cpp - Source/GameLogic/Object/Update/PowerPlantUpdate.cpp - Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp - Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp - Source/GameLogic/Object/Update/ProductionExitUpdate/SpawnPointProductionExitUpdate.cpp - Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp - Source/GameLogic/Object/Update/ProductionUpdate.cpp - Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp - Source/GameLogic/Object/Update/ProneUpdate.cpp - Source/GameLogic/Object/Update/RadarUpdate.cpp - Source/GameLogic/Object/Update/RadiusDecalUpdate.cpp - Source/GameLogic/Object/Update/SlavedUpdate.cpp - Source/GameLogic/Object/Update/SmartBombTargetHomingUpdate.cpp - Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp - Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp - Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp - Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp - Source/GameLogic/Object/Update/SpyVisionUpdate.cpp - Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp - Source/GameLogic/Object/Update/StealthUpdate.cpp - Source/GameLogic/Object/Update/StickyBombUpdate.cpp - Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp - Source/GameLogic/Object/Update/StructureToppleUpdate.cpp - Source/GameLogic/Object/Update/TensileFormationUpdate.cpp - Source/GameLogic/Object/Update/ToppleUpdate.cpp - Source/GameLogic/Object/Update/UpdateModule.cpp - Source/GameLogic/Object/Update/WaveGuideUpdate.cpp - Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp - Source/GameLogic/Object/Upgrade/ActiveShroudUpgrade.cpp - Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp - Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp - Source/GameLogic/Object/Upgrade/CostModifierUpgrade.cpp - Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp - Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp - Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp - Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp - Source/GameLogic/Object/Upgrade/ModelConditionUpgrade.cpp - Source/GameLogic/Object/Upgrade/ObjectCreationUpgrade.cpp - Source/GameLogic/Object/Upgrade/PassengersFireUpgrade.cpp - Source/GameLogic/Object/Upgrade/PowerPlantUpgrade.cpp - Source/GameLogic/Object/Upgrade/RadarUpgrade.cpp - Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cpp - Source/GameLogic/Object/Upgrade/StatusBitsUpgrade.cpp - Source/GameLogic/Object/Upgrade/StealthUpgrade.cpp - Source/GameLogic/Object/Upgrade/SubObjectsUpgrade.cpp - Source/GameLogic/Object/Upgrade/UnpauseSpecialPowerUpgrade.cpp - Source/GameLogic/Object/Upgrade/UpgradeModule.cpp - Source/GameLogic/Object/Upgrade/WeaponBonusUpgrade.cpp - Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp - Source/GameLogic/Object/Weapon.cpp - Source/GameLogic/Object/WeaponSet.cpp - Source/GameLogic/ScriptEngine/ScriptActions.cpp - Source/GameLogic/ScriptEngine/ScriptConditions.cpp - Source/GameLogic/ScriptEngine/ScriptEngine.cpp - Source/GameLogic/ScriptEngine/Scripts.cpp - Source/GameLogic/ScriptEngine/VictoryConditions.cpp - Source/GameLogic/System/CaveSystem.cpp - Source/GameLogic/System/CrateSystem.cpp - Source/GameLogic/System/Damage.cpp - Source/GameLogic/System/GameLogic.cpp - Source/GameLogic/System/GameLogicDispatch.cpp - Source/GameLogic/System/RankInfo.cpp - Source/GameNetwork/Connection.cpp - Source/GameNetwork/ConnectionManager.cpp - Source/GameNetwork/DisconnectManager.cpp - Source/GameNetwork/DownloadManager.cpp - Source/GameNetwork/FileTransfer.cpp - Source/GameNetwork/FirewallHelper.cpp - Source/GameNetwork/FrameData.cpp - Source/GameNetwork/FrameDataManager.cpp - Source/GameNetwork/FrameMetrics.cpp - Source/GameNetwork/GameInfo.cpp - Source/GameNetwork/GameMessageParser.cpp - #Source/GameNetwork/GameSpyChat.cpp - #Source/GameNetwork/GameSpyGameInfo.cpp - #Source/GameNetwork/GameSpyGP.cpp - Source/GameNetwork/GameSpy/Chat.cpp - Source/GameNetwork/GameSpy/GSConfig.cpp - Source/GameNetwork/GameSpy/LadderDefs.cpp - Source/GameNetwork/GameSpy/LobbyUtils.cpp - Source/GameNetwork/GameSpy/MainMenuUtils.cpp - Source/GameNetwork/GameSpy/PeerDefs.cpp - Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp - Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp - Source/GameNetwork/GameSpy/Thread/GameResultsThread.cpp - Source/GameNetwork/GameSpy/Thread/PeerThread.cpp - Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp - Source/GameNetwork/GameSpy/Thread/PingThread.cpp - Source/GameNetwork/GameSpy/Thread/ThreadUtils.cpp - Source/GameNetwork/GameSpyOverlay.cpp - Source/GameNetwork/GUIUtil.cpp - Source/GameNetwork/IPEnumeration.cpp - Source/GameNetwork/LANAPI.cpp - Source/GameNetwork/LANAPICallbacks.cpp - Source/GameNetwork/LANAPIhandlers.cpp - Source/GameNetwork/LANGameInfo.cpp - Source/GameNetwork/NAT.cpp - Source/GameNetwork/NetCommandList.cpp - Source/GameNetwork/NetCommandMsg.cpp - Source/GameNetwork/NetCommandRef.cpp - Source/GameNetwork/NetCommandWrapperList.cpp - Source/GameNetwork/NetMessageStream.cpp - Source/GameNetwork/NetPacket.cpp - Source/GameNetwork/Network.cpp - Source/GameNetwork/NetworkUtil.cpp - Source/GameNetwork/Transport.cpp - Source/GameNetwork/udp.cpp - Source/GameNetwork/User.cpp - Source/GameNetwork/WOLBrowser/WebBrowser.cpp - Source/Precompiled/PreRTS.cpp -) - -if(RTS_GAMEMEMORY_ENABLE) - # Uses the original Game Memory implementation. - list(APPEND GAMEENGINE_SRC - Source/Common/System/GameMemory.cpp - Source/Common/System/MemoryInit.cpp - ) -else() - # Uses the null implementation when disabled. - list(APPEND GAMEENGINE_SRC - Source/Common/System/GameMemoryNull.cpp - Include/Common/GameMemoryNull.h - ) -endif() - - -add_library(z_gameengine STATIC) - -target_sources(z_gameengine PRIVATE ${GAMEENGINE_SRC}) - -target_include_directories(z_gameengine PUBLIC - Include -) - -target_include_directories(z_gameengine PRIVATE - Include/Precompiled -) - -target_link_libraries(z_gameengine PRIVATE - zi_always -) - -target_link_libraries(z_gameengine PUBLIC - d3d8lib - gamespy::gamespy - core_config - core_utility - stlport - core_browserdispatch - core_compression - z_wwvegas -) - -target_compile_definitions(z_gameengine PRIVATE - IG_DEBUG_STACKTRACE -) - -target_precompile_headers(z_gameengine PRIVATE Include/Precompiled/PreRTS.h) +set(GAMEENGINE_SRC + Include/Common/AcademyStats.h + Include/Common/ActionManager.h + Include/Common/ArchiveFile.h + Include/Common/ArchiveFileSystem.h + Include/Common/AsciiString.h + Include/Common/AudioAffect.h + Include/Common/AudioEventInfo.h + Include/Common/AudioEventRTS.h + Include/Common/AudioHandleSpecialValues.h + Include/Common/AudioRandomValue.h + Include/Common/AudioRequest.h + Include/Common/AudioSettings.h + Include/Common/BattleHonors.h + Include/Common/BezFwdIterator.h + Include/Common/BezierSegment.h + Include/Common/BitFlags.h + Include/Common/BitFlagsIO.h + Include/Common/BorderColors.h + Include/Common/BuildAssistant.h + Include/Common/CDManager.h + Include/Common/ClientUpdateModule.h + Include/Common/CommandLine.h + Include/Common/CopyProtection.h + Include/Common/crc.h + Include/Common/CRCDebug.h + Include/Common/CriticalSection.h + Include/Common/CustomMatchPreferences.h + Include/Common/DamageFX.h + Include/Common/DataChunk.h + Include/Common/Debug.h + Include/Common/Dict.h + Include/Common/Directory.h + Include/Common/DisabledTypes.h + Include/Common/DiscreteCircle.h + Include/Common/DrawModule.h + Include/Common/DynamicAudioEventInfo.h + Include/Common/encrypt.h + Include/Common/Energy.h + Include/Common/Errors.h + Include/Common/file.h + Include/Common/FileSystem.h + Include/Common/FunctionLexicon.h + Include/Common/GameAudio.h + Include/Common/GameCommon.h + Include/Common/GameEngine.h + Include/Common/GameLOD.h + Include/Common/GameMemory.h + Include/Common/GameMusic.h + Include/Common/GameSounds.h + Include/Common/GameSpyMiscPreferences.h + Include/Common/GameState.h + Include/Common/GameStateMap.h + Include/Common/GameType.h + Include/Common/Geometry.h + Include/Common/GlobalData.h + Include/Common/Handicap.h + Include/Common/IgnorePreferences.h + Include/Common/INI.h + Include/Common/INIException.h + Include/Common/KindOf.h + Include/Common/LadderPreferences.h + Include/Common/Language.h + Include/Common/LatchRestore.h + Include/Common/List.h + Include/Common/LocalFile.h + Include/Common/LocalFileSystem.h + Include/Common/MapObject.h + Include/Common/MapReaderWriterInfo.h + Include/Common/MessageStream.h + Include/Common/MiniLog.h + Include/Common/MiscAudio.h + Include/Common/MissionStats.h + Include/Common/ModelState.h + Include/Common/Module.h + Include/Common/ModuleFactory.h + Include/Common/Money.h + Include/Common/MultiplayerSettings.h + Include/Common/NameKeyGenerator.h + Include/Common/ObjectStatusTypes.h + Include/Common/OSDisplay.h + Include/Common/Overridable.h + Include/Common/Override.h + Include/Common/PartitionSolver.h + Include/Common/PerfMetrics.h + Include/Common/PerfTimer.h + Include/Common/Player.h + Include/Common/PlayerList.h + Include/Common/PlayerTemplate.h + Include/Common/ProductionPrerequisite.h + Include/Common/QuickmatchPreferences.h + Include/Common/QuotedPrintable.h + Include/Common/Radar.h + Include/Common/RAMFile.h + Include/Common/RandomValue.h + Include/Common/Recorder.h + Include/Common/Registry.h + Include/Common/ResourceGatheringManager.h + Include/Common/Science.h + Include/Common/ScopedMutex.h + Include/Common/ScoreKeeper.h + Include/Common/simpleplayer.h + Include/Common/SkirmishBattleHonors.h + Include/Common/SkirmishPreferences.h + Include/Common/Snapshot.h + Include/Common/SparseMatchFinder.h + Include/Common/SpecialPower.h + Include/Common/SpecialPowerMaskType.h + Include/Common/SpecialPowerType.h + Include/Common/StackDump.h + Include/Common/StateMachine.h + Include/Common/StatsCollector.h + Include/Common/STLTypedefs.h + Include/Common/StreamingArchiveFile.h + Include/Common/SubsystemInterface.h + Include/Common/SystemInfo.h + Include/Common/Team.h + Include/Common/Terrain.h + Include/Common/TerrainTypes.h + Include/Common/Thing.h + Include/Common/ThingFactory.h + Include/Common/ThingSort.h + Include/Common/ThingTemplate.h + Include/Common/TunnelTracker.h + Include/Common/UnicodeString.h + Include/Common/UnitTimings.h + Include/Common/Upgrade.h + Include/Common/urllaunch.h + Include/Common/UserPreferences.h + Include/Common/version.h + Include/Common/WellKnownKeys.h +# Include/Common/Xfer.h +# Include/Common/XferCRC.h +# Include/Common/XferDeepCRC.h +# Include/Common/XferLoad.h +# Include/Common/XferSave.h + Include/GameClient/Anim2D.h + Include/GameClient/AnimateWindowManager.h + Include/GameClient/CampaignManager.h + Include/GameClient/CDCheck.h + Include/GameClient/ChallengeGenerals.h + Include/GameClient/ClientInstance.h + Include/GameClient/ClientRandomValue.h + Include/GameClient/Color.h + Include/GameClient/CommandXlat.h + Include/GameClient/ControlBar.h + Include/GameClient/ControlBarResizer.h + Include/GameClient/ControlBarScheme.h + Include/GameClient/Credits.h + Include/GameClient/DebugDisplay.h + Include/GameClient/Diplomacy.h + Include/GameClient/DisconnectMenu.h + Include/GameClient/Display.h + Include/GameClient/DisplayString.h + Include/GameClient/DisplayStringManager.h + Include/GameClient/Drawable.h + Include/GameClient/DrawableInfo.h + Include/GameClient/DrawGroupInfo.h + Include/GameClient/EstablishConnectionsMenu.h + Include/GameClient/Eva.h + Include/GameClient/ExtendedMessageBox.h + Include/GameClient/FontDesc.h + Include/GameClient/FXList.h + Include/GameClient/Gadget.h + Include/GameClient/GadgetCheckBox.h + Include/GameClient/GadgetComboBox.h + Include/GameClient/GadgetListBox.h + Include/GameClient/GadgetProgressBar.h + Include/GameClient/GadgetPushButton.h + Include/GameClient/GadgetRadioButton.h + Include/GameClient/GadgetSlider.h + Include/GameClient/GadgetStaticText.h + Include/GameClient/GadgetTabControl.h + Include/GameClient/GadgetTextEntry.h + Include/GameClient/GameClient.h + Include/GameClient/GameFont.h + Include/GameClient/GameInfoWindow.h + Include/GameClient/GameText.h + Include/GameClient/GameWindow.h + Include/GameClient/GameWindowGlobal.h + Include/GameClient/GameWindowID.h + Include/GameClient/GameWindowManager.h + Include/GameClient/GameWindowTransitions.h + Include/GameClient/GlobalLanguage.h + Include/GameClient/GraphDraw.h + Include/GameClient/GUICallbacks.h + Include/GameClient/GUICommandTranslator.h + Include/GameClient/HeaderTemplate.h + Include/GameClient/HintSpy.h + Include/GameClient/HotKey.h + Include/GameClient/Image.h + Include/GameClient/IMEManager.h + Include/GameClient/InGameUI.h + Include/GameClient/Keyboard.h + Include/GameClient/KeyDefs.h + Include/GameClient/LanguageFilter.h + Include/GameClient/Line2D.h + Include/GameClient/LoadScreen.h + Include/GameClient/LookAtXlat.h + Include/GameClient/MapUtil.h + Include/GameClient/MessageBox.h + Include/GameClient/MetaEvent.h + Include/GameClient/Module/AnimatedParticleSysBoneClientUpdate.h + Include/GameClient/Module/BeaconClientUpdate.h + Include/GameClient/Module/SwayClientUpdate.h + Include/GameClient/Mouse.h + Include/GameClient/ParabolicEase.h + Include/GameClient/ParticleSys.h + Include/GameClient/PlaceEventTranslator.h + Include/GameClient/ProcessAnimateWindow.h + Include/GameClient/RadiusDecal.h + Include/GameClient/RayEffect.h + Include/GameClient/SelectionInfo.h + Include/GameClient/SelectionXlat.h + Include/GameClient/Shadow.h + Include/GameClient/Shell.h + Include/GameClient/ShellHooks.h + Include/GameClient/ShellMenuScheme.h + Include/GameClient/Smudge.h + Include/GameClient/Snow.h + Include/GameClient/Statistics.h + Include/GameClient/TerrainRoads.h + Include/GameClient/TerrainVisual.h + Include/GameClient/TintStatus.h + Include/GameClient/VideoPlayer.h + Include/GameClient/View.h + Include/GameClient/Water.h + Include/GameClient/WindowLayout.h + Include/GameClient/WindowVideoManager.h + Include/GameClient/WindowXlat.h + Include/GameClient/WinInstanceData.h + Include/GameLogic/AI.h + Include/GameLogic/AIDock.h + Include/GameLogic/AIGuard.h + Include/GameLogic/AIGuardRetaliate.h + Include/GameLogic/AIPathfind.h + Include/GameLogic/AIPlayer.h + Include/GameLogic/AISkirmishPlayer.h + Include/GameLogic/AIStateMachine.h + Include/GameLogic/AITNGuard.h + Include/GameLogic/Armor.h + Include/GameLogic/ArmorSet.h + Include/GameLogic/CaveSystem.h + Include/GameLogic/CrateSystem.h + Include/GameLogic/Damage.h + Include/GameLogic/ExperienceTracker.h + Include/GameLogic/FiringTracker.h + Include/GameLogic/FPUControl.h + Include/GameLogic/GameLogic.h + Include/GameLogic/GhostObject.h + Include/GameLogic/Locomotor.h + Include/GameLogic/LocomotorSet.h + Include/GameLogic/LogicRandomValue.h + Include/GameLogic/Module/ActiveBody.h + Include/GameLogic/Module/ActiveShroudUpgrade.h + Include/GameLogic/Module/AIUpdate.h + Include/GameLogic/Module/AnimationSteeringUpdate.h + Include/GameLogic/Module/ArmorUpgrade.h + Include/GameLogic/Module/AssaultTransportAIUpdate.h + Include/GameLogic/Module/AssistedTargetingUpdate.h + Include/GameLogic/Module/AutoDepositUpdate.h + Include/GameLogic/Module/AutoFindHealingUpdate.h + Include/GameLogic/Module/AutoHealBehavior.h + Include/GameLogic/Module/BaikonurLaunchPower.h + Include/GameLogic/Module/BaseRegenerateUpdate.h + Include/GameLogic/Module/BattleBusSlowDeathBehavior.h + Include/GameLogic/Module/BattlePlanUpdate.h + Include/GameLogic/Module/BehaviorModule.h + Include/GameLogic/Module/BodyModule.h + Include/GameLogic/Module/BoneFXDamage.h + Include/GameLogic/Module/BoneFXUpdate.h + Include/GameLogic/Module/BridgeBehavior.h + Include/GameLogic/Module/BridgeScaffoldBehavior.h + Include/GameLogic/Module/BridgeTowerBehavior.h + Include/GameLogic/Module/BunkerBusterBehavior.h + Include/GameLogic/Module/CashBountyPower.h + Include/GameLogic/Module/CashHackSpecialPower.h + Include/GameLogic/Module/CaveContain.h + Include/GameLogic/Module/CheckpointUpdate.h + Include/GameLogic/Module/ChinookAIUpdate.h + Include/GameLogic/Module/CleanupAreaPower.h + Include/GameLogic/Module/CleanupHazardUpdate.h + Include/GameLogic/Module/CollideModule.h + Include/GameLogic/Module/CommandButtonHuntUpdate.h + Include/GameLogic/Module/CommandSetUpgrade.h + Include/GameLogic/Module/ContainModule.h + Include/GameLogic/Module/ConvertToCarBombCrateCollide.h + Include/GameLogic/Module/ConvertToHijackedVehicleCrateCollide.h + Include/GameLogic/Module/CostModifierUpgrade.h + Include/GameLogic/Module/ProductionTimeModifierUpgrade.h + Include/GameLogic/Module/CountermeasuresBehavior.h + Include/GameLogic/Module/CrateCollide.h + Include/GameLogic/Module/CreateCrateDie.h + Include/GameLogic/Module/CreateModule.h + Include/GameLogic/Module/CreateObjectDie.h + Include/GameLogic/Module/CrushDie.h + Include/GameLogic/Module/DamageModule.h + Include/GameLogic/Module/DamDie.h + Include/GameLogic/Module/DefaultProductionExitUpdate.h + Include/GameLogic/Module/DefectorSpecialPower.h + Include/GameLogic/Module/DeletionUpdate.h + Include/GameLogic/Module/DeliverPayloadAIUpdate.h + Include/GameLogic/Module/DemoralizeSpecialPower.h + Include/GameLogic/Module/DemoTrapUpdate.h + Include/GameLogic/Module/DeployStyleAIUpdate.h + Include/GameLogic/Module/DestroyDie.h + Include/GameLogic/Module/DestroyModule.h + Include/GameLogic/Module/DieModule.h + Include/GameLogic/Module/DockUpdate.h + Include/GameLogic/Module/DozerAIUpdate.h + Include/GameLogic/Module/DumbProjectileBehavior.h + Include/GameLogic/Module/DynamicGeometryInfoUpdate.h + Include/GameLogic/Module/DynamicShroudClearingRangeUpdate.h + Include/GameLogic/Module/EjectPilotDie.h + Include/GameLogic/Module/EMPUpdate.h + Include/GameLogic/Module/EnemyNearUpdate.h + Include/GameLogic/Module/ExperienceScalarUpgrade.h + Include/GameLogic/Module/FireOCLAfterWeaponCooldownUpdate.h + Include/GameLogic/Module/FireSpreadUpdate.h + Include/GameLogic/Module/FirestormDynamicGeometryInfoUpdate.h + Include/GameLogic/Module/FireWeaponCollide.h + Include/GameLogic/Module/FireWeaponPower.h + Include/GameLogic/Module/FireWeaponUpdate.h + Include/GameLogic/Module/FireWeaponWhenDamagedBehavior.h + Include/GameLogic/Module/FireWeaponWhenDeadBehavior.h + Include/GameLogic/Module/FlammableUpdate.h + Include/GameLogic/Module/FlightDeckBehavior.h + Include/GameLogic/Module/FloatUpdate.h + Include/GameLogic/Module/FXListDie.h + Include/GameLogic/Module/GarrisonContain.h + Include/GameLogic/Module/GenerateMinefieldBehavior.h + Include/GameLogic/Module/GrantScienceUpgrade.h + Include/GameLogic/Module/GrantStealthBehavior.h + Include/GameLogic/Module/GrantUpgradeCreate.h + Include/GameLogic/Module/HackInternetAIUpdate.h + Include/GameLogic/Module/HealContain.h + Include/GameLogic/Module/HealCrateCollide.h + Include/GameLogic/Module/HeightDieUpdate.h + Include/GameLogic/Module/HelicopterSlowDeathUpdate.h + Include/GameLogic/Module/HelixContain.h + Include/GameLogic/Module/HighlanderBody.h + Include/GameLogic/Module/HijackerUpdate.h + Include/GameLogic/Module/HiveStructureBody.h + Include/GameLogic/Module/HordeUpdate.h + Include/GameLogic/Module/ImmortalBody.h + Include/GameLogic/Module/InactiveBody.h + Include/GameLogic/Module/InstantDeathBehavior.h + Include/GameLogic/Module/InternetHackContain.h + Include/GameLogic/Module/JetAIUpdate.h + Include/GameLogic/Module/JetSlowDeathBehavior.h + Include/GameLogic/Module/KeepObjectDie.h + Include/GameLogic/Module/LaserUpdate.h + Include/GameLogic/Module/LifetimeUpdate.h + Include/GameLogic/Module/LockWeaponCreate.h + Include/GameLogic/Module/LocomotorSetUpgrade.h + Include/GameLogic/Module/MaxHealthUpgrade.h + Include/GameLogic/Module/MinefieldBehavior.h + Include/GameLogic/Module/MissileAIUpdate.h + Include/GameLogic/Module/MissileLauncherBuildingUpdate.h + Include/GameLogic/Module/MobMemberSlavedUpdate.h + Include/GameLogic/Module/MobNexusContain.h + Include/GameLogic/Module/ModelConditionUpgrade.h + Include/GameLogic/Module/MoneyCrateCollide.h + Include/GameLogic/Module/NeutronBlastBehavior.h + Include/GameLogic/Module/NeutronMissileSlowDeathUpdate.h + Include/GameLogic/Module/NeutronMissileUpdate.h + Include/GameLogic/Module/ObjectCreationUpgrade.h + Include/GameLogic/Module/ObjectDefectionHelper.h + Include/GameLogic/Module/ObjectHelper.h + Include/GameLogic/Module/ObjectRepulsorHelper.h + Include/GameLogic/Module/ObjectSMCHelper.h + Include/GameLogic/Module/ObjectWeaponStatusHelper.h + Include/GameLogic/Module/OCLSpecialPower.h + Include/GameLogic/Module/OCLUpdate.h + Include/GameLogic/Module/OpenContain.h + Include/GameLogic/Module/OverchargeBehavior.h + Include/GameLogic/Module/OverlordContain.h + Include/GameLogic/Module/ParachuteContain.h + Include/GameLogic/Module/ParkingPlaceBehavior.h + Include/GameLogic/Module/ParticleUplinkCannonUpdate.h + Include/GameLogic/Module/PassengersFireUpgrade.h + Include/GameLogic/Module/PhysicsUpdate.h + Include/GameLogic/Module/PilotFindVehicleUpdate.h + Include/GameLogic/Module/PointDefenseLaserUpdate.h + Include/GameLogic/Module/PoisonedBehavior.h + Include/GameLogic/Module/PowerPlantUpdate.h + Include/GameLogic/Module/PowerPlantUpgrade.h + Include/GameLogic/Module/POWTruckAIUpdate.h + Include/GameLogic/Module/POWTruckBehavior.h + Include/GameLogic/Module/PreorderCreate.h + Include/GameLogic/Module/PrisonBehavior.h + Include/GameLogic/Module/PrisonDockUpdate.h + Include/GameLogic/Module/ProductionUpdate.h + Include/GameLogic/Module/ProjectileStreamUpdate.h + Include/GameLogic/Module/ProneUpdate.h + Include/GameLogic/Module/PropagandaCenterBehavior.h + Include/GameLogic/Module/PropagandaTowerBehavior.h + Include/GameLogic/Module/QueueProductionExitUpdate.h + Include/GameLogic/Module/RadarUpdate.h + Include/GameLogic/Module/RadarUpgrade.h + Include/GameLogic/Module/RadiusDecalUpdate.h + Include/GameLogic/Module/RailedTransportAIUpdate.h + Include/GameLogic/Module/RailedTransportContain.h + Include/GameLogic/Module/RailedTransportDockUpdate.h + Include/GameLogic/Module/RailroadGuideAIUpdate.h + Include/GameLogic/Module/RebuildHoleBehavior.h + Include/GameLogic/Module/RebuildHoleExposeDie.h + Include/GameLogic/Module/RepairDockUpdate.h + Include/GameLogic/Module/ReplaceObjectUpgrade.h + Include/GameLogic/Module/RiderChangeContain.h + Include/GameLogic/Module/SabotageCommandCenterCrateCollide.h + Include/GameLogic/Module/SabotageFakeBuildingCrateCollide.h + Include/GameLogic/Module/SabotageInternetCenterCrateCollide.h + Include/GameLogic/Module/SabotageMilitaryFactoryCrateCollide.h + Include/GameLogic/Module/SabotagePowerPlantCrateCollide.h + Include/GameLogic/Module/SabotageSuperweaponCrateCollide.h + Include/GameLogic/Module/SabotageSupplyCenterCrateCollide.h + Include/GameLogic/Module/SabotageSupplyDropzoneCrateCollide.h + Include/GameLogic/Module/SalvageCrateCollide.h + Include/GameLogic/Module/ScatterShotUpdate.h + Include/GameLogic/Module/ShroudCrateCollide.h + Include/GameLogic/Module/SlavedUpdate.h + Include/GameLogic/Module/SlowDeathBehavior.h + Include/GameLogic/Module/SmartBombTargetHomingUpdate.h + Include/GameLogic/Module/SpawnBehavior.h + Include/GameLogic/Module/SpawnPointProductionExitUpdate.h + Include/GameLogic/Module/SpecialAbility.h + Include/GameLogic/Module/SpecialAbilityUpdate.h + Include/GameLogic/Module/SpecialPowerCompletionDie.h + Include/GameLogic/Module/SpecialPowerCreate.h + Include/GameLogic/Module/SpecialPowerModule.h + Include/GameLogic/Module/SpecialPowerUpdateModule.h + Include/GameLogic/Module/SpectreGunshipDeploymentUpdate.h + Include/GameLogic/Module/SpectreGunshipUpdate.h + Include/GameLogic/Module/SpyVisionSpecialPower.h + Include/GameLogic/Module/SpyVisionUpdate.h + Include/GameLogic/Module/SquishCollide.h + Include/GameLogic/Module/StatusBitsUpgrade.h + Include/GameLogic/Module/StatusDamageHelper.h + Include/GameLogic/Module/StealthDetectorUpdate.h + Include/GameLogic/Module/StealthUpdate.h + Include/GameLogic/Module/StealthUpgrade.h + Include/GameLogic/Module/StickyBombUpdate.h + Include/GameLogic/Module/StructureBody.h + Include/GameLogic/Module/StructureCollapseUpdate.h + Include/GameLogic/Module/StructureToppleUpdate.h + Include/GameLogic/Module/SubdualDamageHelper.h + Include/GameLogic/Module/SubObjectsUpgrade.h + Include/GameLogic/Module/SupplyCenterCreate.h + Include/GameLogic/Module/SupplyCenterDockUpdate.h + Include/GameLogic/Module/SupplyCenterProductionExitUpdate.h + Include/GameLogic/Module/SupplyTruckAIUpdate.h + Include/GameLogic/Module/SupplyWarehouseCreate.h + Include/GameLogic/Module/SupplyWarehouseCripplingBehavior.h + Include/GameLogic/Module/SupplyWarehouseDockUpdate.h + Include/GameLogic/Module/TechBuildingBehavior.h + Include/GameLogic/Module/TempWeaponBonusHelper.h + Include/GameLogic/Module/TensileFormationUpdate.h + Include/GameLogic/Module/ToppleUpdate.h + Include/GameLogic/Module/TransitionDamageFX.h + Include/GameLogic/Module/TransportAIUpdate.h + Include/GameLogic/Module/TransportContain.h + Include/GameLogic/Module/TunnelContain.h + Include/GameLogic/Module/UndeadBody.h + Include/GameLogic/Module/UnitCrateCollide.h + Include/GameLogic/Module/UnpauseSpecialPowerUpgrade.h + Include/GameLogic/Module/UpdateModule.h + Include/GameLogic/Module/UpgradeDie.h + Include/GameLogic/Module/UpgradeModule.h + Include/GameLogic/Module/VeterancyCrateCollide.h + Include/GameLogic/Module/VeterancyGainCreate.h + Include/GameLogic/Module/WanderAIUpdate.h + Include/GameLogic/Module/WaveGuideUpdate.h + Include/GameLogic/Module/WeaponBonusUpdate.h + Include/GameLogic/Module/ArmorDamageScalarUpdate.h + Include/GameLogic/Module/WeaponBonusUpgrade.h + Include/GameLogic/Module/WeaponSetUpgrade.h + Include/GameLogic/Module/WorkerAIUpdate.h + Include/GameLogic/Object.h + Include/GameLogic/ObjectCreationList.h + Include/GameLogic/ObjectIter.h + Include/GameLogic/ObjectScriptStatusBits.h + Include/GameLogic/ObjectTypes.h + Include/GameLogic/PartitionManager.h + Include/GameLogic/PolygonTrigger.h + Include/GameLogic/Powers.h + Include/GameLogic/RankInfo.h + Include/GameLogic/ScriptActions.h + Include/GameLogic/ScriptConditions.h + Include/GameLogic/ScriptEngine.h + Include/GameLogic/Scripts.h + Include/GameLogic/SidesList.h + Include/GameLogic/Squad.h + Include/GameLogic/TerrainLogic.h + Include/GameLogic/TurretAI.h + Include/GameLogic/VictoryConditions.h + Include/GameLogic/Weapon.h + Include/GameLogic/WeaponBonusConditionFlags.h + Include/GameLogic/WeaponSet.h + Include/GameLogic/WeaponSetFlags.h + Include/GameLogic/WeaponSetType.h + Include/GameLogic/WeaponStatus.h + Include/GameNetwork/Connection.h + Include/GameNetwork/ConnectionManager.h + Include/GameNetwork/DisconnectManager.h + Include/GameNetwork/DownloadManager.h + Include/GameNetwork/FileTransfer.h + Include/GameNetwork/FirewallHelper.h + Include/GameNetwork/FrameData.h + Include/GameNetwork/FrameDataManager.h + Include/GameNetwork/FrameMetrics.h + Include/GameNetwork/GameInfo.h + Include/GameNetwork/GameMessageParser.h + Include/GameNetwork/GameSpy/BuddyDefs.h + Include/GameNetwork/GameSpy/BuddyThread.h + Include/GameNetwork/GameSpy/GameResultsThread.h + Include/GameNetwork/GameSpy/GSConfig.h + Include/GameNetwork/GameSpy/LadderDefs.h + Include/GameNetwork/GameSpy/LobbyUtils.h + Include/GameNetwork/GameSpy/MainMenuUtils.h + Include/GameNetwork/GameSpy/PeerDefs.h + Include/GameNetwork/GameSpy/PeerDefsImplementation.h + Include/GameNetwork/GameSpy/PeerThread.h + Include/GameNetwork/GameSpy/PersistentStorageDefs.h + Include/GameNetwork/GameSpy/PersistentStorageThread.h + Include/GameNetwork/GameSpy/PingThread.h + Include/GameNetwork/GameSpy/StagingRoomGameInfo.h + Include/GameNetwork/GameSpy/ThreadUtils.h + Include/GameNetwork/GameSpyChat.h + Include/GameNetwork/GameSpyGameInfo.h + Include/GameNetwork/GameSpyGP.h + Include/GameNetwork/GameSpyOverlay.h + Include/GameNetwork/GameSpyThread.h + Include/GameNetwork/GUIUtil.h + Include/GameNetwork/IPEnumeration.h + Include/GameNetwork/LANAPI.h + Include/GameNetwork/LANAPICallbacks.h + Include/GameNetwork/LANGameInfo.h + Include/GameNetwork/LANPlayer.h + Include/GameNetwork/NAT.h + Include/GameNetwork/NetCommandList.h + Include/GameNetwork/NetCommandMsg.h + Include/GameNetwork/NetCommandRef.h + Include/GameNetwork/NetCommandWrapperList.h + Include/GameNetwork/NetPacket.h + Include/GameNetwork/NetworkDefs.h + Include/GameNetwork/NetworkInterface.h + Include/GameNetwork/networkutil.h + Include/GameNetwork/RankPointValue.h + Include/GameNetwork/Transport.h + Include/GameNetwork/udp.h + Include/GameNetwork/User.h + Include/GameNetwork/WOLBrowser/FEBDispatch.h + Include/GameNetwork/WOLBrowser/WebBrowser.h + Include/Precompiled/PreRTS.h + Source/Common/Audio/AudioEventRTS.cpp + Source/Common/Audio/AudioRequest.cpp + Source/Common/Audio/DynamicAudioEventInfo.cpp + Source/Common/Audio/GameAudio.cpp + Source/Common/Audio/GameMusic.cpp + Source/Common/Audio/GameSounds.cpp + #Source/Common/Audio/simpleplayer.cpp + #Source/Common/Audio/urllaunch.cpp + Source/Common/Bezier/BezFwdIterator.cpp + Source/Common/Bezier/BezierSegment.cpp + Source/Common/BitFlags.cpp + Source/Common/CommandLine.cpp + Source/Common/crc.cpp + Source/Common/CRCDebug.cpp + Source/Common/DamageFX.cpp + Source/Common/Dict.cpp + Source/Common/DiscreteCircle.cpp + Source/Common/GameEngine.cpp + Source/Common/GameLOD.cpp + Source/Common/GameMain.cpp + Source/Common/GlobalData.cpp + Source/Common/INI/INI.cpp + Source/Common/INI/INIAiData.cpp + Source/Common/INI/INIAnimation.cpp + Source/Common/INI/INIAudioEventInfo.cpp + Source/Common/INI/INICommandButton.cpp + Source/Common/INI/INICommandSet.cpp + Source/Common/INI/INIControlBarScheme.cpp + Source/Common/INI/INICrate.cpp + Source/Common/INI/INIDamageFX.cpp + Source/Common/INI/INIDrawGroupInfo.cpp + Source/Common/INI/INIGameData.cpp + Source/Common/INI/INIMapCache.cpp + Source/Common/INI/INIMapData.cpp + Source/Common/INI/INIMappedImage.cpp + Source/Common/INI/INIMiscAudio.cpp + Source/Common/INI/INIModel.cpp + Source/Common/INI/INIMultiplayer.cpp + Source/Common/INI/INIObject.cpp + Source/Common/INI/INIParticleSys.cpp + Source/Common/INI/INISpecialPower.cpp + Source/Common/INI/INITerrain.cpp + Source/Common/INI/INITerrainBridge.cpp + Source/Common/INI/INITerrainRoad.cpp + Source/Common/INI/INIUpgrade.cpp + Source/Common/INI/INIVideo.cpp + Source/Common/INI/INIWater.cpp + Source/Common/INI/INIWeapon.cpp + Source/Common/INI/INIWebpageURL.cpp + Source/Common/Language.cpp + Source/Common/MessageStream.cpp + Source/Common/MiniLog.cpp + Source/Common/MultiplayerSettings.cpp + Source/Common/NameKeyGenerator.cpp + Source/Common/PartitionSolver.cpp + Source/Common/PerfTimer.cpp + Source/Common/RandomValue.cpp + Source/Common/Recorder.cpp + Source/Common/RTS/AcademyStats.cpp + Source/Common/RTS/ActionManager.cpp + Source/Common/RTS/Energy.cpp + Source/Common/RTS/Handicap.cpp + Source/Common/RTS/MissionStats.cpp + Source/Common/RTS/Money.cpp + Source/Common/RTS/Player.cpp + Source/Common/RTS/PlayerList.cpp + Source/Common/RTS/PlayerTemplate.cpp + Source/Common/RTS/ProductionPrerequisite.cpp + Source/Common/RTS/ResourceGatheringManager.cpp + Source/Common/RTS/Science.cpp + Source/Common/RTS/ScoreKeeper.cpp + Source/Common/RTS/SpecialPower.cpp + Source/Common/RTS/Team.cpp + Source/Common/RTS/TunnelTracker.cpp + Source/Common/SkirmishBattleHonors.cpp + Source/Common/StateMachine.cpp + Source/Common/StatsCollector.cpp + Source/Common/System/ArchiveFile.cpp + Source/Common/System/ArchiveFileSystem.cpp + Source/Common/System/AsciiString.cpp + Source/Common/System/BuildAssistant.cpp + Source/Common/System/CDManager.cpp + Source/Common/System/CopyProtection.cpp + Source/Common/System/CriticalSection.cpp + Source/Common/System/DataChunk.cpp + Source/Common/System/Debug.cpp + Source/Common/System/Directory.cpp + Source/Common/System/DisabledTypes.cpp + Source/Common/System/encrypt.cpp + Source/Common/System/File.cpp + Source/Common/System/FileSystem.cpp + Source/Common/System/FunctionLexicon.cpp + Source/Common/System/GameCommon.cpp + #Source/Common/System/GameMemory.cpp + Source/Common/System/GameType.cpp + Source/Common/System/Geometry.cpp + Source/Common/System/KindOf.cpp + Source/Common/System/List.cpp + Source/Common/System/LocalFile.cpp + Source/Common/System/LocalFileSystem.cpp + #Source/Common/System/MemoryInit.cpp + Source/Common/System/ObjectStatusTypes.cpp + Source/Common/System/QuotedPrintable.cpp + Source/Common/System/Radar.cpp + Source/Common/System/RAMFile.cpp + Source/Common/System/registry.cpp + Source/Common/System/SaveGame/GameState.cpp + Source/Common/System/SaveGame/GameStateMap.cpp + Source/Common/System/Snapshot.cpp + Source/Common/System/StackDump.cpp + Source/Common/System/StreamingArchiveFile.cpp + Source/Common/System/SubsystemInterface.cpp + Source/Common/System/Trig.cpp + Source/Common/System/UnicodeString.cpp + Source/Common/System/Upgrade.cpp +# Source/Common/System/Xfer.cpp +# Source/Common/System/XferCRC.cpp +# Source/Common/System/XferLoad.cpp +# Source/Common/System/XferSave.cpp + Source/Common/TerrainTypes.cpp + Source/Common/Thing/DrawModule.cpp + Source/Common/Thing/Module.cpp + Source/Common/Thing/ModuleFactory.cpp + Source/Common/Thing/Thing.cpp + Source/Common/Thing/ThingFactory.cpp + Source/Common/Thing/ThingTemplate.cpp + Source/Common/UserPreferences.cpp + Source/Common/version.cpp + Source/GameClient/ClientInstance.cpp + Source/GameClient/Color.cpp + Source/GameClient/Credits.cpp + Source/GameClient/Display.cpp + Source/GameClient/DisplayString.cpp + Source/GameClient/DisplayStringManager.cpp + Source/GameClient/Drawable.cpp + Source/GameClient/Drawable/Update/AnimatedParticleSysBoneClientUpdate.cpp + Source/GameClient/Drawable/Update/BeaconClientUpdate.cpp + Source/GameClient/Drawable/Update/SwayClientUpdate.cpp + Source/GameClient/DrawGroupInfo.cpp + Source/GameClient/Eva.cpp + Source/GameClient/FXList.cpp + Source/GameClient/GameClient.cpp + Source/GameClient/GameClientDispatch.cpp + Source/GameClient/GameText.cpp + Source/GameClient/GlobalLanguage.cpp + Source/GameClient/GraphDraw.cpp + Source/GameClient/GUI/AnimateWindowManager.cpp + Source/GameClient/GUI/ChallengeGenerals.cpp + Source/GameClient/GUI/ControlBar/ControlBar.cpp + Source/GameClient/GUI/ControlBar/ControlBarBeacon.cpp + Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp + Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp + Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp + Source/GameClient/GUI/ControlBar/ControlBarObserver.cpp + Source/GameClient/GUI/ControlBar/ControlBarOCLTimer.cpp + Source/GameClient/GUI/ControlBar/ControlBarPrintPositions.cpp + Source/GameClient/GUI/ControlBar/ControlBarResizer.cpp + Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp + Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp + Source/GameClient/GUI/ControlBar/ControlBarUnderConstruction.cpp + Source/GameClient/GUI/DisconnectMenu/DisconnectMenu.cpp + Source/GameClient/GUI/EstablishConnectionsMenu/EstablishConnectionsMenu.cpp + Source/GameClient/GUI/Gadget/GadgetCheckBox.cpp + Source/GameClient/GUI/Gadget/GadgetComboBox.cpp + Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp + Source/GameClient/GUI/Gadget/GadgetListBox.cpp + Source/GameClient/GUI/Gadget/GadgetProgressBar.cpp + Source/GameClient/GUI/Gadget/GadgetPushButton.cpp + Source/GameClient/GUI/Gadget/GadgetRadioButton.cpp + Source/GameClient/GUI/Gadget/GadgetStaticText.cpp + Source/GameClient/GUI/Gadget/GadgetTabControl.cpp + Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp + Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp + Source/GameClient/GUI/GameFont.cpp + Source/GameClient/GUI/GameWindow.cpp + Source/GameClient/GUI/GameWindowGlobal.cpp + Source/GameClient/GUI/GameWindowManager.cpp + Source/GameClient/GUI/GameWindowManagerScript.cpp + Source/GameClient/GUI/GameWindowTransitions.cpp + Source/GameClient/GUI/GameWindowTransitionsStyles.cpp + Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp + Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp + Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp + Source/GameClient/GUI/GUICallbacks/ExtendedMessageBox.cpp + Source/GameClient/GUI/GUICallbacks/GeneralsExpPoints.cpp + Source/GameClient/GUI/GUICallbacks/IMECandidate.cpp + Source/GameClient/GUI/GUICallbacks/InGameChat.cpp + Source/GameClient/GUI/GUICallbacks/InGamePopupMessage.cpp + Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/DifficultySelect.cpp + Source/GameClient/GUI/GUICallbacks/Menus/DisconnectWindow.cpp + Source/GameClient/GUI/GUICallbacks/Menus/DownloadMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/EstablishConnectionsWindow.cpp + Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp + Source/GameClient/GUI/GUICallbacks/Menus/KeyboardOptionsMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/MapSelectMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp + Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupCommunicator.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupJoinGame.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp + Source/GameClient/GUI/GUICallbacks/Menus/PopupSaveLoad.cpp + Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp + Source/GameClient/GUI/GUICallbacks/Menus/SinglePlayerMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLCustomScoreScreen.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLLadderScreen.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLMessageWindow.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLQMScoreScreen.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLStatusMenu.cpp + Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp + Source/GameClient/GUI/GUICallbacks/MessageBox.cpp + Source/GameClient/GUI/GUICallbacks/ReplayControls.cpp + Source/GameClient/GUI/HeaderTemplate.cpp + Source/GameClient/GUI/IMEManager.cpp + Source/GameClient/GUI/LoadScreen.cpp + Source/GameClient/GUI/ProcessAnimateWindow.cpp + Source/GameClient/GUI/Shell/Shell.cpp + Source/GameClient/GUI/Shell/ShellMenuScheme.cpp + Source/GameClient/GUI/WindowLayout.cpp + Source/GameClient/GUI/WindowVideoManager.cpp + Source/GameClient/GUI/WinInstanceData.cpp + Source/GameClient/InGameUI.cpp + Source/GameClient/Input/Keyboard.cpp + Source/GameClient/Input/Mouse.cpp + Source/GameClient/LanguageFilter.cpp + Source/GameClient/Line2D.cpp + Source/GameClient/MapUtil.cpp + Source/GameClient/MessageStream/CommandXlat.cpp + Source/GameClient/MessageStream/GUICommandTranslator.cpp + Source/GameClient/MessageStream/HintSpy.cpp + Source/GameClient/MessageStream/HotKey.cpp + Source/GameClient/MessageStream/LookAtXlat.cpp + Source/GameClient/MessageStream/MetaEvent.cpp + Source/GameClient/MessageStream/PlaceEventTranslator.cpp + Source/GameClient/MessageStream/SelectionXlat.cpp + Source/GameClient/MessageStream/WindowXlat.cpp + Source/GameClient/ParabolicEase.cpp + Source/GameClient/RadiusDecal.cpp + Source/GameClient/SelectionInfo.cpp + Source/GameClient/Snow.cpp + Source/GameClient/Statistics.cpp + Source/GameClient/System/Anim2D.cpp + Source/GameClient/System/CampaignManager.cpp + "Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp" + Source/GameClient/System/DebugDisplay.cpp + Source/GameClient/System/Image.cpp + Source/GameClient/System/ParticleSys.cpp + Source/GameClient/System/RayEffect.cpp + Source/GameClient/System/Smudge.cpp + Source/GameClient/Terrain/TerrainRoads.cpp + Source/GameClient/Terrain/TerrainVisual.cpp + Source/GameClient/VideoPlayer.cpp + Source/GameClient/VideoStream.cpp + Source/GameClient/View.cpp + Source/GameClient/Water.cpp + Source/GameLogic/AI/AI.cpp + Source/GameLogic/AI/AIDock.cpp + Source/GameLogic/AI/AIGroup.cpp + Source/GameLogic/AI/AIGuard.cpp + Source/GameLogic/AI/AIGuardRetaliate.cpp + Source/GameLogic/AI/AIPathfind.cpp + Source/GameLogic/AI/AIPlayer.cpp + Source/GameLogic/AI/AISkirmishPlayer.cpp + Source/GameLogic/AI/AIStates.cpp + Source/GameLogic/AI/AITNGuard.cpp + Source/GameLogic/AI/Squad.cpp + Source/GameLogic/AI/TurretAI.cpp + Source/GameLogic/Map/PolygonTrigger.cpp + Source/GameLogic/Map/SidesList.cpp + Source/GameLogic/Map/TerrainLogic.cpp + Source/GameLogic/Object/Armor.cpp + Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp + Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp + Source/GameLogic/Object/Behavior/BehaviorModule.cpp + Source/GameLogic/Object/Behavior/BridgeBehavior.cpp + Source/GameLogic/Object/Behavior/BridgeScaffoldBehavior.cpp + Source/GameLogic/Object/Behavior/BridgeTowerBehavior.cpp + Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp + Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp + Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp + Source/GameLogic/Object/Behavior/FireWeaponWhenDamagedBehavior.cpp + Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp + Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp + Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp + Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp + Source/GameLogic/Object/Behavior/InstantDeathBehavior.cpp + Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp + Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp + Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp + Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp + Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp + Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp + Source/GameLogic/Object/Behavior/POWTruckBehavior.cpp + Source/GameLogic/Object/Behavior/PrisonBehavior.cpp + Source/GameLogic/Object/Behavior/PropagandaCenterBehavior.cpp + Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp + Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp + Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp + Source/GameLogic/Object/Behavior/SpawnBehavior.cpp + Source/GameLogic/Object/Behavior/SupplyWarehouseCripplingBehavior.cpp + Source/GameLogic/Object/Behavior/TechBuildingBehavior.cpp + Source/GameLogic/Object/Body/ActiveBody.cpp + Source/GameLogic/Object/Body/BodyModule.cpp + Source/GameLogic/Object/Body/HighlanderBody.cpp + Source/GameLogic/Object/Body/HiveStructureBody.cpp + Source/GameLogic/Object/Body/ImmortalBody.cpp + Source/GameLogic/Object/Body/InactiveBody.cpp + Source/GameLogic/Object/Body/StructureBody.cpp + Source/GameLogic/Object/Body/UndeadBody.cpp + Source/GameLogic/Object/Collide/CollideModule.cpp + Source/GameLogic/Object/Collide/CrateCollide/ConvertToCarBombCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/HealCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/MoneyCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/SalvageCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/ShroudCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/UnitCrateCollide.cpp + Source/GameLogic/Object/Collide/CrateCollide/VeterancyCrateCollide.cpp + Source/GameLogic/Object/Collide/FireWeaponCollide.cpp + Source/GameLogic/Object/Collide/SquishCollide.cpp + Source/GameLogic/Object/Contain/CaveContain.cpp + Source/GameLogic/Object/Contain/GarrisonContain.cpp + Source/GameLogic/Object/Contain/HealContain.cpp + Source/GameLogic/Object/Contain/HelixContain.cpp + Source/GameLogic/Object/Contain/InternetHackContain.cpp + Source/GameLogic/Object/Contain/MobNexusContain.cpp + Source/GameLogic/Object/Contain/OpenContain.cpp + Source/GameLogic/Object/Contain/OverlordContain.cpp + Source/GameLogic/Object/Contain/ParachuteContain.cpp + Source/GameLogic/Object/Contain/RailedTransportContain.cpp + Source/GameLogic/Object/Contain/RiderChangeContain.cpp + Source/GameLogic/Object/Contain/TransportContain.cpp + Source/GameLogic/Object/Contain/TunnelContain.cpp + Source/GameLogic/Object/Create/CreateModule.cpp + Source/GameLogic/Object/Create/GrantUpgradeCreate.cpp + Source/GameLogic/Object/Create/LockWeaponCreate.cpp + Source/GameLogic/Object/Create/PreorderCreate.cpp + Source/GameLogic/Object/Create/SpecialPowerCreate.cpp + Source/GameLogic/Object/Create/SupplyCenterCreate.cpp + Source/GameLogic/Object/Create/SupplyWarehouseCreate.cpp + Source/GameLogic/Object/Create/VeterancyGainCreate.cpp + Source/GameLogic/Object/Damage/BoneFXDamage.cpp + Source/GameLogic/Object/Damage/DamageModule.cpp + Source/GameLogic/Object/Damage/TransitionDamageFX.cpp + Source/GameLogic/Object/Destroy/DestroyModule.cpp + Source/GameLogic/Object/Die/CreateCrateDie.cpp + Source/GameLogic/Object/Die/CreateObjectDie.cpp + Source/GameLogic/Object/Die/CrushDie.cpp + Source/GameLogic/Object/Die/DamDie.cpp + Source/GameLogic/Object/Die/DestroyDie.cpp + Source/GameLogic/Object/Die/DieModule.cpp + Source/GameLogic/Object/Die/EjectPilotDie.cpp + Source/GameLogic/Object/Die/FXListDie.cpp + Source/GameLogic/Object/Die/KeepObjectDie.cpp + Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp + Source/GameLogic/Object/Die/SpecialPowerCompletionDie.cpp + Source/GameLogic/Object/Die/UpgradeDie.cpp + Source/GameLogic/Object/ExperienceTracker.cpp + Source/GameLogic/Object/FiringTracker.cpp + Source/GameLogic/Object/GhostObject.cpp + Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp + Source/GameLogic/Object/Helper/ObjectHelper.cpp + Source/GameLogic/Object/Helper/ObjectRepulsorHelper.cpp + Source/GameLogic/Object/Helper/ObjectSMCHelper.cpp + Source/GameLogic/Object/Helper/ObjectWeaponStatusHelper.cpp + Source/GameLogic/Object/Helper/StatusDamageHelper.cpp + Source/GameLogic/Object/Helper/SubdualDamageHelper.cpp + Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp + Source/GameLogic/Object/Locomotor.cpp + Source/GameLogic/Object/Object.cpp + Source/GameLogic/Object/ObjectCreationList.cpp + Source/GameLogic/Object/ObjectTypes.cpp + Source/GameLogic/Object/PartitionManager.cpp + Source/GameLogic/Object/SimpleObjectIterator.cpp + Source/GameLogic/Object/SpecialPower/BaikonurLaunchPower.cpp + Source/GameLogic/Object/SpecialPower/CashBountyPower.cpp + Source/GameLogic/Object/SpecialPower/CashHackSpecialPower.cpp + Source/GameLogic/Object/SpecialPower/CleanupAreaPower.cpp + Source/GameLogic/Object/SpecialPower/DefectorSpecialPower.cpp + Source/GameLogic/Object/SpecialPower/DemoralizeSpecialPower.cpp + Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp + Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp + Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp + Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp + Source/GameLogic/Object/SpecialPower/SpyVisionSpecialPower.cpp + Source/GameLogic/Object/Update/AIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/POWTruckAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/RailedTransportAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/WanderAIUpdate.cpp + Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp + Source/GameLogic/Object/Update/AnimationSteeringUpdate.cpp + Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp + Source/GameLogic/Object/Update/AutoDepositUpdate.cpp + Source/GameLogic/Object/Update/AutoFindHealingUpdate.cpp + Source/GameLogic/Object/Update/BaseRenerateUpdate.cpp + Source/GameLogic/Object/Update/BattlePlanUpdate.cpp + Source/GameLogic/Object/Update/BoneFXUpdate.cpp + Source/GameLogic/Object/Update/CheckpointUpdate.cpp + Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp + Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp + Source/GameLogic/Object/Update/DeletionUpdate.cpp + Source/GameLogic/Object/Update/DemoTrapUpdate.cpp + Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp + Source/GameLogic/Object/Update/DockUpdate/PrisonDockUpdate.cpp + Source/GameLogic/Object/Update/DockUpdate/RailedTransportDockUpdate.cpp + Source/GameLogic/Object/Update/DockUpdate/RepairDockUpdate.cpp + Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp + Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp + Source/GameLogic/Object/Update/DynamicGeometryInfoUpdate.cpp + Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp + Source/GameLogic/Object/Update/EMPUpdate.cpp + Source/GameLogic/Object/Update/EnemyNearUpdate.cpp + Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp + Source/GameLogic/Object/Update/FireSpreadUpdate.cpp + Source/GameLogic/Object/Update/FirestormDynamicGeometryInfoUpdate.cpp + Source/GameLogic/Object/Update/FireWeaponUpdate.cpp + Source/GameLogic/Object/Update/FlammableUpdate.cpp + Source/GameLogic/Object/Update/FloatUpdate.cpp + Source/GameLogic/Object/Update/HeightDieUpdate.cpp + Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp + Source/GameLogic/Object/Update/HijackerUpdate.cpp + Source/GameLogic/Object/Update/HordeUpdate.cpp + Source/GameLogic/Object/Update/LaserUpdate.cpp + Source/GameLogic/Object/Update/LifetimeUpdate.cpp + Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp + Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp + Source/GameLogic/Object/Update/NeutronMissileSlowDeathUpdate.cpp + Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp + Source/GameLogic/Object/Update/OCLUpdate.cpp + Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp + Source/GameLogic/Object/Update/PhysicsUpdate.cpp + Source/GameLogic/Object/Update/PilotFindVehicleUpdate.cpp + Source/GameLogic/Object/Update/PointDefenseLaserUpdate.cpp + Source/GameLogic/Object/Update/PowerPlantUpdate.cpp + Source/GameLogic/Object/Update/ProductionExitUpdate/DefaultProductionExitUpdate.cpp + Source/GameLogic/Object/Update/ProductionExitUpdate/QueueProductionExitUpdate.cpp + Source/GameLogic/Object/Update/ProductionExitUpdate/SpawnPointProductionExitUpdate.cpp + Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp + Source/GameLogic/Object/Update/ProductionUpdate.cpp + Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp + Source/GameLogic/Object/Update/ProneUpdate.cpp + Source/GameLogic/Object/Update/RadarUpdate.cpp + Source/GameLogic/Object/Update/RadiusDecalUpdate.cpp + Source/GameLogic/Object/Update/ScatterShotUpdate.cpp + Source/GameLogic/Object/Update/SlavedUpdate.cpp + Source/GameLogic/Object/Update/SmartBombTargetHomingUpdate.cpp + Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp + Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp + Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp + Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp + Source/GameLogic/Object/Update/SpyVisionUpdate.cpp + Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp + Source/GameLogic/Object/Update/StealthUpdate.cpp + Source/GameLogic/Object/Update/StickyBombUpdate.cpp + Source/GameLogic/Object/Update/StructureCollapseUpdate.cpp + Source/GameLogic/Object/Update/StructureToppleUpdate.cpp + Source/GameLogic/Object/Update/TensileFormationUpdate.cpp + Source/GameLogic/Object/Update/ToppleUpdate.cpp + Source/GameLogic/Object/Update/UpdateModule.cpp + Source/GameLogic/Object/Update/WaveGuideUpdate.cpp + Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp + Source/GameLogic/Object/Update/ArmorDamageScalarUpdate.cpp + Source/GameLogic/Object/Upgrade/ActiveShroudUpgrade.cpp + Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp + Source/GameLogic/Object/Upgrade/CommandSetUpgrade.cpp + Source/GameLogic/Object/Upgrade/CostModifierUpgrade.cpp + Source/GameLogic/Object/Upgrade/ProductionTimeModifierUpgrade.cpp + Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp + Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp + Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp + Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp + Source/GameLogic/Object/Upgrade/ModelConditionUpgrade.cpp + Source/GameLogic/Object/Upgrade/ObjectCreationUpgrade.cpp + Source/GameLogic/Object/Upgrade/PassengersFireUpgrade.cpp + Source/GameLogic/Object/Upgrade/PowerPlantUpgrade.cpp + Source/GameLogic/Object/Upgrade/RadarUpgrade.cpp + Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cpp + Source/GameLogic/Object/Upgrade/StatusBitsUpgrade.cpp + Source/GameLogic/Object/Upgrade/StealthUpgrade.cpp + Source/GameLogic/Object/Upgrade/SubObjectsUpgrade.cpp + Source/GameLogic/Object/Upgrade/UnpauseSpecialPowerUpgrade.cpp + Source/GameLogic/Object/Upgrade/UpgradeModule.cpp + Source/GameLogic/Object/Upgrade/WeaponBonusUpgrade.cpp + Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp + Source/GameLogic/Object/Weapon.cpp + Source/GameLogic/Object/WeaponSet.cpp + Source/GameLogic/ScriptEngine/ScriptActions.cpp + Source/GameLogic/ScriptEngine/ScriptConditions.cpp + Source/GameLogic/ScriptEngine/ScriptEngine.cpp + Source/GameLogic/ScriptEngine/Scripts.cpp + Source/GameLogic/ScriptEngine/VictoryConditions.cpp + Source/GameLogic/System/CaveSystem.cpp + Source/GameLogic/System/CrateSystem.cpp + Source/GameLogic/System/Damage.cpp + Source/GameLogic/System/GameLogic.cpp + Source/GameLogic/System/GameLogicDispatch.cpp + Source/GameLogic/System/RankInfo.cpp + Source/GameNetwork/Connection.cpp + Source/GameNetwork/ConnectionManager.cpp + Source/GameNetwork/DisconnectManager.cpp + Source/GameNetwork/DownloadManager.cpp + Source/GameNetwork/FileTransfer.cpp + Source/GameNetwork/FirewallHelper.cpp + Source/GameNetwork/FrameData.cpp + Source/GameNetwork/FrameDataManager.cpp + Source/GameNetwork/FrameMetrics.cpp + Source/GameNetwork/GameInfo.cpp + Source/GameNetwork/GameMessageParser.cpp + #Source/GameNetwork/GameSpyChat.cpp + #Source/GameNetwork/GameSpyGameInfo.cpp + #Source/GameNetwork/GameSpyGP.cpp + Source/GameNetwork/GameSpy/Chat.cpp + Source/GameNetwork/GameSpy/GSConfig.cpp + Source/GameNetwork/GameSpy/LadderDefs.cpp + Source/GameNetwork/GameSpy/LobbyUtils.cpp + Source/GameNetwork/GameSpy/MainMenuUtils.cpp + Source/GameNetwork/GameSpy/PeerDefs.cpp + Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp + Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp + Source/GameNetwork/GameSpy/Thread/GameResultsThread.cpp + Source/GameNetwork/GameSpy/Thread/PeerThread.cpp + Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp + Source/GameNetwork/GameSpy/Thread/PingThread.cpp + Source/GameNetwork/GameSpy/Thread/ThreadUtils.cpp + Source/GameNetwork/GameSpyOverlay.cpp + Source/GameNetwork/GUIUtil.cpp + Source/GameNetwork/IPEnumeration.cpp + Source/GameNetwork/LANAPI.cpp + Source/GameNetwork/LANAPICallbacks.cpp + Source/GameNetwork/LANAPIhandlers.cpp + Source/GameNetwork/LANGameInfo.cpp + Source/GameNetwork/NAT.cpp + Source/GameNetwork/NetCommandList.cpp + Source/GameNetwork/NetCommandMsg.cpp + Source/GameNetwork/NetCommandRef.cpp + Source/GameNetwork/NetCommandWrapperList.cpp + Source/GameNetwork/NetMessageStream.cpp + Source/GameNetwork/NetPacket.cpp + Source/GameNetwork/Network.cpp + Source/GameNetwork/NetworkUtil.cpp + Source/GameNetwork/Transport.cpp + Source/GameNetwork/udp.cpp + Source/GameNetwork/User.cpp + Source/GameNetwork/WOLBrowser/WebBrowser.cpp + Source/Precompiled/PreRTS.cpp +) + +if(RTS_GAMEMEMORY_ENABLE) + # Uses the original Game Memory implementation. + list(APPEND GAMEENGINE_SRC + Source/Common/System/GameMemory.cpp + Source/Common/System/MemoryInit.cpp + ) +else() + # Uses the null implementation when disabled. + list(APPEND GAMEENGINE_SRC + Source/Common/System/GameMemoryNull.cpp + Include/Common/GameMemoryNull.h + ) +endif() + + +add_library(z_gameengine STATIC) + +target_sources(z_gameengine PRIVATE ${GAMEENGINE_SRC}) + +target_include_directories(z_gameengine PUBLIC + Include +) + +target_include_directories(z_gameengine PRIVATE + Include/Precompiled +) + +target_link_libraries(z_gameengine PRIVATE + corei_gameengine_private + zi_always +) + +target_link_libraries(z_gameengine PUBLIC + corei_gameengine_public + z_wwvegas +) + +target_precompile_headers(z_gameengine PRIVATE Include/Precompiled/PreRTS.h) diff --git a/GeneralsMD/Code/GameEngine/Include/Common/AsciiString.h b/GeneralsMD/Code/GameEngine/Include/Common/AsciiString.h index 338c83a046..c3c1a8aec3 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/AsciiString.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/AsciiString.h @@ -91,7 +91,7 @@ class AsciiString // add a ctor/dtor, 'cuz they won't ever be called. struct AsciiStringData { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) const char* m_debugptr; // just makes it easier to read in the debugger #endif unsigned short m_refCount; // reference count @@ -101,7 +101,7 @@ class AsciiString inline char* peek() { return (char*)(this+1); } }; - #ifdef _DEBUG + #ifdef RTS_DEBUG void validate() const; #else inline void validate() const { } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h b/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h index 2477dd26fe..a234243ba1 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/CRCDebug.h @@ -68,9 +68,11 @@ void dumpReal(Real r, AsciiString name, AsciiString fname, Int line); void outputCRCDebugLines( void ); + void CRCDebugStartNewGame( void ); void outputCRCDumpLines( void ); void addCRCDebugLine(const char *fmt, ...); + void addCRCDebugLineNoCounter(const char *fmt, ...); void addCRCDumpLine(const char *fmt, ...); void addCRCGenLine(const char *fmt, ...); #define CRCDEBUG_LOG(x) addCRCDebugLine x @@ -97,7 +99,9 @@ extern Bool g_crcModuleDataFromLogic; extern Bool g_keepCRCSaves; - + extern Bool g_saveDebugCRCPerFrame; + extern AsciiString g_saveDebugCRCPerFrameDir; + extern Bool g_logObjectCRCs; #else // DEBUG_CRC diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Debug.h b/GeneralsMD/Code/GameEngine/Include/Common/Debug.h index 2bb44fa954..d1a0b93a6d 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Debug.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Debug.h @@ -50,12 +50,14 @@ class AsciiString; -#if defined(_DEBUG) && defined(_INTERNAL) +#if defined(RTS_DEBUG) && defined(RTS_INTERNAL) #error "Only one at a time of these should ever be defined" #endif #define NO_RELEASE_DEBUG_LOGGING +#define RELEASE_DEBUG_LOGGING 1 + #ifdef RELEASE_DEBUG_LOGGING ///< Creates a DebugLogFile.txt (No I or D) with all the debug log goodness. Good for startup problems. #define ALLOW_DEBUG_UTILS 1 #define DEBUG_LOGGING 1 @@ -69,15 +71,15 @@ class AsciiString; #define TOKEN_IT(a) STRING_IT(,##a) #define MESSAGE(a) message (__FILE__ "(" TOKEN_IT(__LINE__) ") : " a) -// by default, turn on ALLOW_DEBUG_UTILS if _DEBUG is turned on. -#if (defined(_DEBUG) || defined(_INTERNAL)) && !defined(ALLOW_DEBUG_UTILS) && !defined(DISABLE_ALLOW_DEBUG_UTILS) +// by default, turn on ALLOW_DEBUG_UTILS if RTS_DEBUG is turned on. +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) && !defined(ALLOW_DEBUG_UTILS) && !defined(DISABLE_ALLOW_DEBUG_UTILS) #define ALLOW_DEBUG_UTILS 1 #elif defined(DEBUG_LOGGING) || defined(DEBUG_CRASHING) || defined(DEBUG_STACKTRACE) || defined(DEBUG_PROFILE) // TheSuperHackers @tweak also turn on when any of the above options is already set. #define ALLOW_DEBUG_UTILS 1 #endif -// these are predicated on ALLOW_DEBUG_UTILS, not _DEBUG, and allow you to selectively disable +// these are predicated on ALLOW_DEBUG_UTILS, not RTS_DEBUG, and allow you to selectively disable // bits of the debug stuff for special builds. #if defined(ALLOW_DEBUG_UTILS) && !defined(DEBUG_LOGGING) && !defined(DISABLE_DEBUG_LOGGING) #define DEBUG_LOGGING 1 @@ -126,8 +128,8 @@ class AsciiString; DEBUG_FLAG_LOG_TO_FILE = 0x01, DEBUG_FLAG_LOG_TO_CONSOLE = 0x02, DEBUG_FLAG_PREPEND_TIME = 0x04, -#ifdef _INTERNAL - // by default, _INTERNAL builds log to file, but not to console, in the interest +#ifdef RTS_INTERNAL + // by default, RTS_INTERNAL builds log to file, but not to console, in the interest // of speed. want console output? just change this line: DEBUG_FLAGS_DEFAULT = (DEBUG_FLAG_LOG_TO_FILE) #else @@ -154,6 +156,8 @@ class AsciiString; #ifdef DEBUG_LOGGING DEBUG_EXTERN_C void DebugLog(const char *format, ...); + DEBUG_EXTERN_C const char* DebugGetLogFileName(); + DEBUG_EXTERN_C const char* DebugGetLogFileNamePrev(); // This defines a bitmask of log types that we care about, to allow some flexability // in what gets logged. This should be extended to asserts, too, but the assert box diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Dict.h b/GeneralsMD/Code/GameEngine/Include/Common/Dict.h index b2ea09f932..828368340d 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Dict.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Dict.h @@ -320,7 +320,7 @@ class Dict inline DictPair* peek() { return (DictPair*)(this+1); } }; - #ifdef _DEBUG + #ifdef RTS_DEBUG void validate() const; #else inline void validate() const { } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/DrawModule.h b/GeneralsMD/Code/GameEngine/Include/Common/DrawModule.h index cf13e695bb..03ebbc72a0 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/DrawModule.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/DrawModule.h @@ -78,7 +78,7 @@ class DrawModule : public DrawableModule virtual void releaseShadows(void) = 0; ///< frees all shadow resources used by this module - used by Options screen. virtual void allocateShadows(void) = 0; ///< create shadow resources if not already present. Used by Options screen. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void getRenderCost(RenderCost & rc) const { }; ///< estimates the render cost of this draw module #endif @@ -187,6 +187,7 @@ class ObjectDrawInterface virtual void replaceModelConditionState(const ModelConditionFlags& a) = 0; virtual void replaceIndicatorColor(Color color) = 0; virtual Bool handleWeaponFireFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, const Coord3D* victimPos, Real damageRadius) = 0; + virtual Bool handleWeaponPreAttackFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, const Coord3D* victimPos, Real damageRadius) = 0; virtual Int getBarrelCount(WeaponSlotType wslot) const = 0; virtual void setSelectable(Bool selectable) = 0; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h index 64dae03189..49581fb8d4 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h @@ -136,7 +136,7 @@ class AudioManager : public SubsystemInterface public: AudioManager(); virtual ~AudioManager(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void audioDebugDisplay(DebugDisplayInterface *dd, void *userData, FILE *fp = NULL ) = 0; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameCommon.h b/GeneralsMD/Code/GameEngine/Include/Common/GameCommon.h index 3d076603f3..dbbad0424c 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/GameCommon.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/GameCommon.h @@ -60,7 +60,7 @@ #include "Lib/BaseType.h" // ---------------------------------------------------------------------------------------------- -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) #define DUMP_PERF_STATS #else #define NO_DUMP_PERF_STATS @@ -230,6 +230,9 @@ enum CommandSourceType CPP_11(: Int) CMD_FROM_AI, CMD_FROM_DOZER, // Special rare command when the dozer originates a command to attack a mine. Mines are not ai-attackable, and it seems deceitful for the dozer to generate a player or script command. jba. CMD_DEFAULT_SWITCH_WEAPON, // Special case: A weapon that can be chosen -- this is the default case (machine gun vs flashbang). + CMD_SYNC_TO_PRIMARY, // This weapon can only be used when PRIMARY is fired + CMD_SYNC_TO_SECONDARY, // This weapon can only be used when SECONDARY is fired + CMD_SYNC_TO_TERTIARY, // This weapon can only be used when TERTIARY is fired }; ///< the source of a command @@ -493,6 +496,12 @@ inline Real stdAngleDiff(Real a1, Real a2) return normalizeAngle(a1 - a2); } +// normalized angle difference between a1 and a2, respecting negative values and wraparound +inline Real stdAngleDiffMod(Real a1, Real a2) { + return normalizeAngle(nmod(a1 - a2, 2 * PI)); +} + + // ------------------------------------------------------------------------ // NOTE NOTE NOTE: Keep TheRelationShipNames in sync with this enum enum Relationship CPP_11(: Int) diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h b/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h index f26fcd1b25..95c5ff12d0 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/GameMemory.h @@ -53,12 +53,12 @@ #define DISABLE_MEMORYPOOL_CHECKPOINTING 1 #endif -#if (defined(_DEBUG) || defined(_INTERNAL)) && !defined(MEMORYPOOL_DEBUG_CUSTOM_NEW) && !defined(DISABLE_MEMORYPOOL_DEBUG_CUSTOM_NEW) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) && !defined(MEMORYPOOL_DEBUG_CUSTOM_NEW) && !defined(DISABLE_MEMORYPOOL_DEBUG_CUSTOM_NEW) #define MEMORYPOOL_DEBUG_CUSTOM_NEW #endif -//#if (defined(_DEBUG) || defined(_INTERNAL)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) -#if (defined(_DEBUG)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) +//#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) +#if (defined(RTS_DEBUG)) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) #define MEMORYPOOL_DEBUG #endif diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h b/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h index 2f08ff5985..a9c475bbf8 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Geometry.h @@ -67,7 +67,7 @@ static const char *GeometryNames[] = #endif // end DEFINE_GEOMETRY_NAMES //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) enum ExtentModType CPP_11(: Int) { EXTENTMOD_INVALID = 0, @@ -188,7 +188,7 @@ class GeometryInfo : public Snapshot // given an object with this geom, SET how far above the object's canonical position its max z should extend. void setMaxHeightAbovePosition(Real z); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void tweakExtents(ExtentModType extentModType, Real extentModAmount); AsciiString getDescriptiveString() const; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h index e1c0c1547a..2256d749b9 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h @@ -38,6 +38,7 @@ #include "Common/GameMemory.h" #include "Common/SubsystemInterface.h" #include "GameClient/Color.h" +#include "GameClient/TintStatus.h" #include "Common/STLTypedefs.h" #include "Common/GameCommon.h" #include "Common/Money.h" @@ -50,6 +51,7 @@ class INI; class WeaponBonusSet; enum BodyDamageType CPP_11(: Int); enum AIDebugOptions CPP_11(: Int); +//enum DrawableColorTint CPP_11(: Int); // PUBLIC ///////////////////////////////////////////////////////////////////////////////////////// @@ -449,14 +451,14 @@ class GlobalData : public SubsystemInterface Real m_keyboardCameraRotateSpeed; ///< How fast the camera rotates when rotated via keyboard controls. Int m_playStats; ///< Int whether we want to log play stats or not, if <= 0 then we don't log -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) Bool m_specialPowerUsesDelay ; #endif Bool m_TiVOFastMode; ///< When true, the client speeds up the framerate... set by HOTKEY! -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_wireframe; Bool m_stateMachineDebug; Bool m_useCameraConstraints; @@ -520,6 +522,11 @@ class GlobalData : public SubsystemInterface //-allAdvice feature //Bool m_allAdvice; + DrawableColorTint m_colorTintTypes[TINT_STATUS_COUNT]; + Bool m_colorTintTypes2; // [TINT_STATUS_COUNT] ; + + Bool m_useOldMoveSpeed; + // the trailing '\' is included! const AsciiString &getPath_UserData() const { return m_userDataDir; } @@ -545,6 +552,9 @@ class GlobalData : public SubsystemInterface GlobalData& operator=(const GlobalData& that) = default; #endif + static void setColorTintEntry(DrawableColorTint* arr, int index, RGBColor color, RGBColor colorInfantry, UnsignedInt attackFrames, UnsignedInt decayFrames); + static void parseTintStatusType(INI* ini, void* instance, void* store, const void* userData); + }; // singleton diff --git a/GeneralsMD/Code/GameEngine/Include/Common/INI.h b/GeneralsMD/Code/GameEngine/Include/Common/INI.h index 103626dbf1..8d5c22b4bf 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/INI.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/INI.h @@ -184,6 +184,7 @@ class INI // data type parsing (the highest level of what type of thing we're parsing) static void parseObjectDefinition( INI *ini ); static void parseObjectReskinDefinition( INI *ini ); + static void parseObjectExtendDefinition( INI* ini ); static void parseWeaponTemplateDefinition( INI *ini ); static void parseScienceDefinition( INI *ini ); static void parseRankDefinition( INI *ini ); @@ -205,6 +206,7 @@ class INI static void parseWeatherDefinition( INI *ini ); static void parseMappedImageDefinition( INI *ini ); static void parseArmorDefinition( INI *ini ); + static void parseArmorExtendDefinition( INI *ini ); static void parseDamageFXDefinition( INI *ini ); static void parseDrawGroupNumberDefinition( INI *ini ); static void parseTerrainDefinition( INI *ini ); @@ -275,6 +277,7 @@ class INI static void parseAnim2DTemplate( INI *ini, void *instance, void *store, const void *userData ); static void parsePercentToReal( INI *ini, void *instance, void *store, const void* userData ); static void parseRGBColor( INI *ini, void *instance, void *store, const void* userData ); + static void parseRGBColorReal( INI *ini, void *instance, void *store, const void* userData ); static void parseRGBAColorInt( INI *ini, void *instance, void *store, const void* userData ); static void parseColorInt( INI *ini, void *instance, void *store, const void* userData ); static void parseCoord3D( INI *ini, void *instance, void *store, const void* userData ); @@ -289,6 +292,8 @@ class INI static void parseUpgradeTemplate( INI *ini, void *instance, void *store, const void *userData ); static void parseScience( INI *ini, void *instance, void *store, const void *userData ); static void parseScienceVector( INI *ini, void *instance, void *store, const void *userData ); + static void parseWeaponBonusVector( INI *ini, void *instance, void *store, const void *userData ); + static void parseWeaponBonusVectorKeepDefault( INI *ini, void *instance, void *store, const void *userData ); static void parseGameClientRandomVariable( INI* ini, void *instance, void *store, const void* userData ); static void parseBitString8( INI *ini, void *instance, void *store, const void* userData ); static void parseBitString32( INI *ini, void *instance, void *store, const void* userData ); @@ -317,6 +322,8 @@ class INI static void parseVeterancyLevelFlags(INI* ini, void* instance, void* store, const void* userData); static void parseSoundsList( INI* ini, void *instance, void *store, const void* /*userData*/ ); + // like parseIndexList but special handling for NONE to return -2 (EVA_None) + static void parseEvaNameIndexList(INI* ini, void* instance, void* store, const void* userData); /** return the next token. if seps is null (or omitted), the standard seps are used. diff --git a/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h b/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h index ac2d4dc663..14e16a6631 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/MessageStream.h @@ -236,7 +236,7 @@ class GameMessage : public MemoryPoolObject MSG_META_CHAT_EVERYONE, ///< send chat msg to everyone (incl. observers) MSG_META_DIPLOMACY, ///< bring up diplomacy screen MSG_META_OPTIONS, ///< bring up options screen -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) MSG_META_HELP, ///< bring up help screen #endif @@ -298,7 +298,7 @@ class GameMessage : public MemoryPoolObject // META items that are really for debug/demo/development use only... // They do not get built into RELEASE builds. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) MSG_META_DEMO_TOGGLE_BEHIND_BUILDINGS, ///< Toggles showing units behind buildings or not MSG_META_DEMO_TOGGLE_LETTERBOX, ///< enable/disable letterbox mode MSG_META_DEMO_TOGGLE_MESSAGE_TEXT, ///< toggle the text from the UI messages @@ -416,11 +416,11 @@ class GameMessage : public MemoryPoolObject MSG_META_DEBUG_WIN, ///< Instant Win MSG_META_DEMO_TOGGLE_DEBUG_STATS, ///< show/hide the debug stats /// @todo END section to REMOVE (not disable) for release -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) MSG_META_DEMO_TOGGLE_AUDIODEBUG, ///< show/hide the audio debug info -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS MSG_META_DEMO_PERFORM_STATISTICAL_DUMP, ///< dump performance stats for this frame to StatisticsDump.txt #endif//DUMP_PERF_STATS @@ -595,7 +595,7 @@ class GameMessage : public MemoryPoolObject MSG_BEGIN_DEBUG_NETWORK_MESSAGES = 1900, ///< network messages that exist only in debug/internal builds. all grouped separately. -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) // all debug/internal-only messages must go here. MSG_DEBUG_KILL_SELECTION, MSG_DEBUG_HURT_OBJECT, diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ModelState.h b/GeneralsMD/Code/GameEngine/Include/Common/ModelState.h index 856c99d133..6749326ed7 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/ModelState.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/ModelState.h @@ -237,6 +237,17 @@ enum ModelConditionFlagType CPP_11(: Int) MODELCONDITION_USER_2, MODELCONDITION_DISGUISED, + + // --- + // New Weaponsets + MODELCONDITION_WEAPONSET_PLAYER_UPGRADE2, + MODELCONDITION_WEAPONSET_PLAYER_UPGRADE3, + MODELCONDITION_WEAPONSET_PLAYER_UPGRADE4, + + // MODELCONDITION_WEAPONSET_CONTAINED, // for new Garrisoned and Contained weaponsets + // MODELCONDITION_WEAPONSET_GARRISONED, // somewhat obsolote since we are usually not visible when contained. + + // // Note: these values are saved in save files, so you MUST NOT REMOVE OR CHANGE // existing values! diff --git a/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h b/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h index c7a952d1c6..1a1ba1fddb 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/PerfTimer.h @@ -33,7 +33,7 @@ #include "Utility/intrin_compat.h" -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /* NOTE NOTE NOTE: never check this in with this enabled, since there is a nonzero time penalty for running in this mode. Only enable it for local builds for testing purposes! (srj) @@ -155,7 +155,7 @@ void PerfGather::stopTimer() ++m_callCount; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(*m_activeHead != NULL, ("m_activeHead is null, uh oh")); DEBUG_ASSERTCRASH(*m_activeHead == this, ("I am not the active timer, uh oh")); DEBUG_ASSERTCRASH(m_activeHead >= &m_active[0] && m_activeHead <= &m_active[MAX_ACTIVE_STACK-1], ("active under/over flow")); diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h index 1c8ab987d1..05179cd2a3 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h @@ -327,7 +327,7 @@ class Player : public Snapshot void onUpgradeCompleted( const UpgradeTemplate *upgradeTemplate ); ///< An upgrade just finished, do things like tell all objects to recheck UpgradeModules void onUpgradeRemoved(){} ///< An upgrade just got removed, this doesn't do anything now. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /// Prereq disabling cheat key void toggleIgnorePrereqs(){ m_DEMO_ignorePrereqs = !m_DEMO_ignorePrereqs; } Bool ignoresPrereqs() const { return m_DEMO_ignorePrereqs; } @@ -338,7 +338,7 @@ class Player : public Snapshot #endif -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) /// No time building cheat key void toggleInstantBuild(){ m_DEMO_instantBuild = !m_DEMO_instantBuild; } Bool buildsInstantly() const { return m_DEMO_instantBuild; } @@ -386,6 +386,14 @@ class Player : public Snapshot /// Returns production cost change based on typeof (Used for upgrades) Real getProductionCostChangeBasedOnKindOf( KindOfMaskType kindOf ) const; + /// Decrement the ref counter on the typeof production list node + void removeKindOfProductionTimeChange(KindOfMaskType kindOf, Real percent); + /// add type of production cost change (Used for upgrades) + void addKindOfProductionTimeChange(KindOfMaskType kindOf, Real percent); + /// Returns production cost change based on typeof (Used for upgrades) + Real getProductionTimeChangeBasedOnKindOf(KindOfMaskType kindOf) const; + + /** Return bonus or penalty for construction of this thing. */ Real getProductionCostChangePercent( AsciiString buildTemplateName ) const; @@ -802,21 +810,25 @@ class Player : public Snapshot Real m_cashBountyPercent; /// @todo REMOVE (not disable) these cheat keys -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_DEMO_ignorePrereqs; ///< Can I ignore prereq checks? Bool m_DEMO_freeBuild; ///< Can I build everything for no money? #endif -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) Bool m_DEMO_instantBuild; ///< Can I build anything in one frame? #endif ScoreKeeper m_scoreKeeper; ///< The local scorekeeper for this player + // Production Cost modifier typedef std::list KindOfPercentProductionChangeList; typedef KindOfPercentProductionChangeList::iterator KindOfPercentProductionChangeListIt; mutable KindOfPercentProductionChangeList m_kindOfPercentProductionChangeList; + // Production Time modifier (we can re-use the same types) + mutable KindOfPercentProductionChangeList m_kindOfPercentProductionTimeChangeList; + typedef std::list SpecialPowerReadyTimerList; typedef SpecialPowerReadyTimerList::iterator SpecialPowerReadyTimerListIterator; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h b/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h index 4ae303eeda..be8e9c4d01 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Recorder.h @@ -71,7 +71,7 @@ class RecorderClass : public SubsystemInterface { Bool testVersionPlayback(AsciiString filename); ///< Returns if the playback is a valid playback file for this version or not. AsciiString getCurrentReplayFilename( void ); ///< valid during playback only void stopPlayback(); ///< Stops playback. Its fine to call this even if not playing back a file. -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool analyzeReplay( AsciiString filename ); Bool isAnalysisInProgress( void ); #endif diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h b/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h index a123825d0e..3f1f696617 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/SparseMatchFinder.h @@ -36,7 +36,7 @@ #include "Common/BitFlags.h" #include "Common/STLTypedefs.h" -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define SPARSEMATCH_DEBUG #else #undef SPARSEMATCH_DEBUG diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPower.h b/GeneralsMD/Code/GameEngine/Include/Common/SpecialPower.h index 49ccb8c360..bac61e9054 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPower.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/SpecialPower.h @@ -42,6 +42,8 @@ #include "Common/Overridable.h" #include "Common/Override.h" +#include "GameClient/Eva.h" + // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class ObjectCreationList; class Object; @@ -114,6 +116,7 @@ class SpecialPowerTemplate : public Overridable AsciiString getName( void ) const { return getFO()->m_name; } UnsignedInt getID( void ) const { return getFO()->m_id; } SpecialPowerType getSpecialPowerType( void ) const { return getFO()->m_type; } + SpecialPowerType getSpecialPowerBehaviorType( void ) const { return getFO()->m_type_behavior; } UnsignedInt getReloadTime( void ) const { return getFO()->m_reloadTime; } ScienceType getRequiredScience( void ) const { return getFO()->m_requiredScience; } const AudioEventRTS *getInitiateSound( void ) const { return &getFO()->m_initiateSound; } @@ -126,7 +129,16 @@ class SpecialPowerTemplate : public Overridable Real getRadiusCursorRadius() const { return getFO()->m_radiusCursorRadius; } Bool isShortcutPower() const { return getFO()->m_shortcutPower; } AcademyClassificationType getAcademyClassificationType() const { return m_academyClassificationType; } - + EvaMessage getEvaDetectedOwn( void ) const { return getFO()->m_eva_detected_own; } + EvaMessage getEvaDetectedAlly( void ) const { return getFO()->m_eva_detected_ally; } + EvaMessage getEvaDetectedEnemy( void ) const { return getFO()->m_eva_detected_enemy; } + EvaMessage getEvaLaunchedOwn(void) const { return getFO()->m_eva_launched_own; } + EvaMessage getEvaLaunchedAlly(void) const { return getFO()->m_eva_launched_ally; } + EvaMessage getEvaLaunchedEnemy(void) const { return getFO()->m_eva_launched_enemy; } + EvaMessage getEvaReadyOwn(void) const { return getFO()->m_eva_ready_own; } + EvaMessage getEvaReadyAlly(void) const { return getFO()->m_eva_ready_ally; } + EvaMessage getEvaReadyEnemy(void) const { return getFO()->m_eva_ready_enemy; } + private: const SpecialPowerTemplate* getFO() const { return (const SpecialPowerTemplate*)friend_getFinalOverride(); } @@ -147,6 +159,16 @@ class SpecialPowerTemplate : public Overridable Bool m_publicTimer; ///< display a countdown timer for this special power for all to see Bool m_sharedNSync; ///< If true, this is a special that is shared between all of a player's command centers Bool m_shortcutPower; ///< Is this shortcut power capable of being fired by the side panel? + SpecialPowerType m_type_behavior; //< behave like a default special power, used by new ones only + EvaMessage m_eva_detected_own; //< eva event when constructed by self + EvaMessage m_eva_detected_ally; //< eva event when constructed by ally + EvaMessage m_eva_detected_enemy; //< eva event when constructed by enemy + EvaMessage m_eva_launched_own; //< eva event when launched by self + EvaMessage m_eva_launched_ally; //< eva event when launched by ally + EvaMessage m_eva_launched_enemy; //< eva event when launched by enemy + EvaMessage m_eva_ready_own; //< eva event when own ready + EvaMessage m_eva_ready_ally; //< eva event when ally ready + EvaMessage m_eva_ready_enemy; //< eva event when enemy ready static const FieldParse m_specialPowerFieldParse[]; ///< the parse table diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h b/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h index fc59251168..d67e17a017 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h @@ -128,7 +128,16 @@ enum SpecialPowerType CPP_11(: Int) SUPW_SPECIAL_NEUTRON_MISSILE, SPECIAL_BATTLESHIP_BOMBARDMENT, - + + //new constants by OFS + SPECIAL_ION_CANNON, + SPECIAL_CLUSTER_MISSILE, + SPECIAL_SUNSTORM_MISSILE, + SPECIAL_METEOR_STRIKE, + SPECIAL_PUNISHER_CANNON, + SPECIAL_CHEMICAL_MISSILE, + SPECIAL_CHRONOSPHERE, + SPECIALPOWER_COUNT, // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] }; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h index 3644e524cc..e9f994b9c8 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h @@ -30,7 +30,7 @@ #ifndef IG_DEGBUG_STACKTRACE #define IG_DEBUG_STACKTRACE 1 #endif // Unsure about this one -ML 3/25/03 -#if defined(_DEBUG) || defined(_INTERNAL) || defined(IG_DEBUG_STACKTRACE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(IG_DEBUG_STACKTRACE) // Writes a stackdump (provide a callback : gets called per line) // If callback is NULL then will write using OuputDebugString diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h b/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h index cec0d45770..4cd35c9d4f 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/StateMachine.h @@ -46,10 +46,10 @@ class StateMachine; class Object; //#undef STATE_MACHINE_DEBUG -#if defined(_DEBUG) +#if defined(RTS_DEBUG) #define STATE_MACHINE_DEBUG #endif -#if defined(_INTERNAL) +#if defined(RTS_INTERNAL) #define STATE_MACHINE_DEBUG //uncomment to debug state machines in internal. jba. #endif @@ -321,7 +321,7 @@ class StateMachine : public MemoryPoolObject, public Snapshot // StateReturnType internalSetState( StateID newStateID ); ///< for internal use only - change the current state of the machine -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) UnsignedInt peekSleepTill() const { return m_sleepTill; } #endif diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Thing.h b/GeneralsMD/Code/GameEngine/Include/Common/Thing.h index 26f746fcdc..a9590666a4 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Thing.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Thing.h @@ -161,7 +161,7 @@ class Thing : public MemoryPoolObject // since ThingTemplates are shared between many, many Things, the Thing // should never be able to change it. OVERRIDE m_template; ///< reference back to template database -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) AsciiString m_templateName; #endif /* diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ThingFactory.h b/GeneralsMD/Code/GameEngine/Include/Common/ThingFactory.h index 7a05be4829..4d63d44436 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/ThingFactory.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/ThingFactory.h @@ -96,6 +96,8 @@ class ThingFactory : public SubsystemInterface static void parseObjectDefinition( INI* ini, const AsciiString& name, const AsciiString& reskinFrom ); + static void parseObjectExtendDefinition( INI* ini, const AsciiString& name, const AsciiString& extendFrom ); + private: /// free all template databse data diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h b/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h index bb597140fa..b918059d7f 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/ThingTemplate.h @@ -1,785 +1,810 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ThingTemplate.h ////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, April 2001 -// Desc: Thing templates are a 'roadmap' to creating things -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __THINGTEMPLATE_H_ -#define __THINGTEMPLATE_H_ - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Lib/BaseType.h" - -#include "Common/AudioEventRTS.h" -#include "Common/FileSystem.h" -#include "Common/GameCommon.h" -#include "Common/Geometry.h" -#include "Common/KindOf.h" -#include "Common/ModuleFactory.h" -#include "Common/Overridable.h" -#include "Common/ProductionPrerequisite.h" -#include "Common/Science.h" -#include "Common/UnicodeString.h" - -#include "GameLogic/ArmorSet.h" -#include "GameLogic/WeaponSet.h" -#include "Common/STLTypedefs.h" -#include "GameClient/Color.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class AIUpdateModuleData; -class Image; -class Object; -class Drawable; -class ProductionPrerequisite; -struct FieldParse; -class Player; -class INI; -enum RadarPriorityType CPP_11(: Int); -enum ScienceType CPP_11(: Int); -enum EditorSortingType CPP_11(: Int); -enum ShadowType CPP_11(: Int); -class WeaponTemplateSet; -class ArmorTemplateSet; -class FXList; - -// TYPEDEFS FOR FILE ////////////////////////////////////////////////////////////////////////////// -typedef std::map PerUnitSoundMap; -typedef std::map PerUnitFXMap; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//Code renderer handles these states now. -//enum InventoryImageType -//{ -// INV_IMAGE_ENABLED = 0, -// INV_IMAGE_DISABLED, -// INV_IMAGE_HILITE, -// INV_IMAGE_PUSHED, -// -// INV_IMAGE_NUM_IMAGES // keep this last -// -//}; -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -enum -{ - MAX_UPGRADE_CAMEO_UPGRADES = 5 -}; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -enum ThingTemplateAudioType CPP_11(: Int) -{ - TTAUDIO_voiceSelect, ///< Response when unit is selected - TTAUDIO_voiceGroupSelect, ///< Response when a group of this unit is selected - TTAUDIO_voiceSelectElite, ///< Response when unit is selected and elite - TTAUDIO_voiceMove, ///< Response when unit moves - TTAUDIO_voiceAttack, ///< Response when unit is told to attack - TTAUDIO_voiceEnter, ///< Response when unit is told to enter a building - TTAUDIO_voiceFear, ///< Response when unit is under attack - TTAUDIO_voiceCreated, ///< Response when unit is created - TTAUDIO_voiceNearEnemy, ///< Unit is near an enemy - TTAUDIO_voiceTaskUnable, ///< Unit is told to do something impossible - TTAUDIO_voiceTaskComplete, ///< Unit completes a move, or other task indicated - TTAUDIO_voiceMeetEnemy, ///< Unit meets an enemy unit - TTAUDIO_soundMoveStart, ///< Sound when unit starts moving - TTAUDIO_soundMoveStartDamaged, ///< Sound when unit starts moving and is damaged - TTAUDIO_soundMoveLoop, ///< Sound when unit is moving - TTAUDIO_soundMoveLoopDamaged, ///< Sound when unit is moving and is damaged - TTAUDIO_soundAmbient, ///< Ambient sound for unit during normal status. Also the default sound - TTAUDIO_soundAmbientDamaged, ///< Ambient sound for unit if damaged. Corresponds to body info damage - TTAUDIO_soundAmbientReallyDamaged,///< Ambient sound for unit if badly damaged. - TTAUDIO_soundAmbientRubble, ///< Ambient sound for unit if it is currently rubble. (Dam, for instance) - TTAUDIO_soundStealthOn, ///< Sound when unit stealths - TTAUDIO_soundStealthOff, ///< Sound when unit destealths - TTAUDIO_soundCreated, ///< Sound when unit is created - TTAUDIO_soundOnDamaged, ///< Sound when unit enters damaged state - TTAUDIO_soundOnReallyDamaged, ///< Sound when unit enters reallyd damaged state - TTAUDIO_soundEnter, ///< Sound when another unit enters me. - TTAUDIO_soundExit, ///< Sound when another unit exits me. - TTAUDIO_soundPromotedVeteran, ///< Sound when unit gets promoted to Veteran level - TTAUDIO_soundPromotedElite, ///< Sound when unit gets promoted to Elite level - TTAUDIO_soundPromotedHero, ///< Sound when unit gets promoted to Hero level - TTAUDIO_voiceGarrison, ///< Unit is ordered to enter a garrisonable building - TTAUDIO_soundFalling, ///< This sound is actually called on a unit when it is exiting another. - ///< However, there is a soundExit which refers to the container, and this is only used for bombs falling from planes. -#ifdef ALLOW_SURRENDER - TTAUDIO_voiceSurrender, ///< Unit surrenders -#endif - TTAUDIO_voiceDefect, ///< Unit is forced to defect - TTAUDIO_voiceAttackSpecial, ///< Unit is ordered to use a special attack - TTAUDIO_voiceAttackAir, ///< Unit is ordered to attack an airborne unit - TTAUDIO_voiceGuard, ///< Unit is ordered to guard an area - - TTAUDIO_COUNT // keep last! -}; - -class AudioArray -{ -public: - DynamicAudioEventRTS* m_audio[TTAUDIO_COUNT]; - - AudioArray() - { - for (Int i = 0; i < TTAUDIO_COUNT; ++i) - m_audio[i] = NULL; - } - - ~AudioArray() - { - for (Int i = 0; i < TTAUDIO_COUNT; ++i) - if (m_audio[i]) - m_audio[i]->deleteInstance(); - } - - AudioArray(const AudioArray& that) - { - for (Int i = 0; i < TTAUDIO_COUNT; ++i) - { - if (that.m_audio[i]) - m_audio[i] = newInstance(DynamicAudioEventRTS)(*that.m_audio[i]); - else - m_audio[i] = NULL; - } - } - - AudioArray& operator=(const AudioArray& that) - { - if (this != &that) - { - for (Int i = 0; i < TTAUDIO_COUNT; ++i) - { - if (that.m_audio[i]) - { - if (m_audio[i]) - *m_audio[i] = *that.m_audio[i]; - else - m_audio[i] = newInstance(DynamicAudioEventRTS)(*that.m_audio[i]); - } - else - { - m_audio[i] = NULL; - } - } - } - return *this; - } -}; - -//------------------------------------------------------------------------------------------------- -/** Object class type enumeration */ -//------------------------------------------------------------------------------------------------- -enum BuildCompletionType CPP_11(: Int) -{ - BC_INVALID = 0, - BC_APPEARS_AT_RALLY_POINT, ///< unit appears at rally point of its #1 prereq - BC_PLACED_BY_PLAYER, ///< unit must be manually placed by player - - BC_NUM_TYPES // leave this last -}; -#ifdef DEFINE_BUILD_COMPLETION_NAMES -static const char *BuildCompletionNames[] = -{ - "INVALID", - "APPEARS_AT_RALLY_POINT", - "PLACED_BY_PLAYER", - - NULL -}; -#endif // end DEFINE_BUILD_COMPLETION_NAMES - -enum BuildableStatus CPP_11(: Int) -{ - // saved into savegames... do not change or remove values! - BSTATUS_YES = 0, - BSTATUS_IGNORE_PREREQUISITES, - BSTATUS_NO, - BSTATUS_ONLY_BY_AI, - - BSTATUS_NUM_TYPES // leave this last -}; - -#ifdef DEFINE_BUILDABLE_STATUS_NAMES -static const char *BuildableStatusNames[] = -{ - "Yes", - "Ignore_Prerequisites", - "No", - "Only_By_AI", - NULL -}; -#endif // end DEFINE_BUILDABLE_STATUS_NAMES - -//------------------------------------------------------------------------------------------------- -enum ModuleParseMode CPP_11(: Int) -{ - MODULEPARSE_NORMAL, - MODULEPARSE_ADD_REMOVE_REPLACE, - MODULEPARSE_INHERITABLE, - MODULEPARSE_OVERRIDEABLE_BY_LIKE_KIND, - -}; - -//------------------------------------------------------------------------------------------------- -class ModuleInfo -{ -private: - struct Nugget - { - AsciiString first; - AsciiString m_moduleTag; - const ModuleData* second; - Int interfaceMask; - Bool copiedFromDefault; - Bool inheritable; - Bool overrideableByLikeKind; - - Nugget(const AsciiString& n, const AsciiString& moduleTag, const ModuleData* d, Int i, Bool inh, Bool oblk) - : first(n), - m_moduleTag(moduleTag), - second(d), - interfaceMask(i), - copiedFromDefault(false), - inheritable(inh), - overrideableByLikeKind(oblk) - { - } - - }; - std::vector m_info; - -public: - - ModuleInfo() { } - - void addModuleInfo( ThingTemplate *thingTemplate, const AsciiString& name, const AsciiString& moduleTag, const ModuleData* data, Int interfaceMask, Bool inheritable, Bool overrideableByLikeKind = FALSE ); - const ModuleInfo::Nugget *getNuggetWithTag( const AsciiString& tag ) const; - - Int getCount() const - { - return m_info.size(); - } - -#if defined(_DEBUG) || defined(_INTERNAL) - Bool containsPartialName(const char* n) const - { - for (size_t i = 0; i < m_info.size(); i++) - if (strstr(m_info[i].first.str(), n) != NULL) - return true; - return false; - } -#endif - - AsciiString getNthName(size_t i) const - { - if (i >= 0 && i < m_info.size()) - { - return m_info[i].first; - } - return AsciiString::TheEmptyString; - } - - AsciiString getNthTag(size_t i) const - { - if (i >= 0 && i < m_info.size()) - { - return m_info[i].m_moduleTag; - } - return AsciiString::TheEmptyString; - } - - const ModuleData* getNthData(size_t i) const - { - if (i >= 0 && i < m_info.size()) - { - return m_info[i].second; - } - return NULL; - } - - // for use only by ThingTemplate::friend_getAIModuleInfo - ModuleData* friend_getNthData(Int i); - - void clear() - { - m_info.clear(); - } - - void setCopiedFromDefault(Bool v) - { - for (size_t i = 0; i < m_info.size(); i++) - m_info[i].copiedFromDefault = v; - } - - Bool clearModuleDataWithTag(const AsciiString& tagToClear, AsciiString& clearedModuleNameOut); - Bool clearCopiedFromDefaultEntries(Int interfaceMask, const AsciiString &name, const ThingTemplate *fullTemplate ); - Bool clearAiModuleInfo(); -}; - -//------------------------------------------------------------------------------------------------- -/** Definition of a thing template to read from our game data framework */ -//------------------------------------------------------------------------------------------------- -class ThingTemplate : public Overridable -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ThingTemplate, "ThingTemplatePool" ) - -private: - -#if defined(_MSC_VER) && _MSC_VER < 1300 - ThingTemplate(const ThingTemplate& that) : m_geometryInfo(that.m_geometryInfo) - { - DEBUG_CRASH(("This should never be called\n")); - } -#else - ThingTemplate(const ThingTemplate& that) = delete; -#endif - -public: - - - ThingTemplate(); - - // copy the guts of that into this, but preserve this' name, id, and list-links. - void copyFrom(const ThingTemplate* that); - - /// called by ThingFactory after all templates have been loaded. - void resolveNames(); - -#ifdef LOAD_TEST_ASSETS - void initForLTA(const AsciiString& name); - inline AsciiString getLTAName() const { return m_LTAName; } -#endif - - /** - return a unique identifier suitable for identifying this ThingTemplate on machines playing - across the net. this should be considered a Magic Cookie and used only for net traffic or - similar sorts of things. To convert an id back to a ThingTemplate, use ThingFactory::findByID(). - Note that 0 is always an invalid id. NOTE that we are not referencing m_override here - because even though we actually have multiple templates here representing overrides, - we still only conceptually have one template and want to always use one single - pointer for comparisons of templates. However, even if we did reference m_override - the IDs would be the same for each one since every override first *COPIES* data - from the current/parent template data. - */ - UnsignedShort getTemplateID() const { return m_templateID; } - - // note that m_override is not used here, see getTemplateID(), for it is the same reasons - const AsciiString& getName() const { return m_nameString; } ///< return the name of this template - - /// get the display color (used for the editor) - Color getDisplayColor() const { return m_displayColor; } - - /// get the editor sorting - EditorSortingType getEditorSorting() const { return (EditorSortingType)m_editorSorting; } - - /// return true iff the template has the specified kindOf flag set. - inline Bool isKindOf(KindOfType t) const - { - return TEST_KINDOFMASK(m_kindof, t); - } - - /// convenience for doing multiple kindof testing at once. - inline Bool isKindOfMulti(const KindOfMaskType& mustBeSet, const KindOfMaskType& mustBeClear) const - { - return TEST_KINDOFMASK_MULTI(m_kindof, mustBeSet, mustBeClear); - } - - inline Bool isAnyKindOf( const KindOfMaskType& anyKindOf ) const - { - return TEST_KINDOFMASK_ANY(m_kindof, anyKindOf); - } - - /// set the display name - const UnicodeString& getDisplayName() const { return m_displayName; } ///< return display name - - RadarPriorityType getDefaultRadarPriority() const { return (RadarPriorityType)m_radarPriority; } ///< return radar priority from INI - - // note, you should not call this directly; rather, call Object::getTransportSlotCount(). - Int getRawTransportSlotCount() const { return m_transportSlotCount; } - - Real getFenceWidth() const { return m_fenceWidth; } // return fence width - - Real getFenceXOffset() const { return m_fenceXOffset; } // return fence offset - - Bool isBridge() const { return m_isBridge; } // return fence offset - - // Only Object can ask this. Everyone else should ask the Object. In fact, you really should ask the Object everything. - Real friend_calcVisionRange() const { return m_visionRange; } ///< get vision range - Real friend_calcShroudClearingRange() const { return m_shroudClearingRange; } ///< get vision range for Shroud ONLY (Design requested split) - - //This one is okay to check directly... because it doesn't get effected by bonuses. - Real getShroudRevealToAllRange() const { return m_shroudRevealToAllRange; } - - // This function is only for use by the AIUpdateModuleData::parseLocomotorSet function. - AIUpdateModuleData *friend_getAIModuleInfo(void); - - ShadowType getShadowType() const { return (ShadowType)m_shadowType; } - Real getShadowSizeX() const { return m_shadowSizeX; } - Real getShadowSizeY() const { return m_shadowSizeY; } - Real getShadowOffsetX() const { return m_shadowOffsetX; } - Real getShadowOffsetY() const { return m_shadowOffsetY; } - - const AsciiString& getShadowTextureName( void ) const { return m_shadowTextureName; } - UnsignedInt getOcclusionDelay(void) const { return m_occlusionDelay;} - - const ModuleInfo& getBehaviorModuleInfo() const { return m_behaviorModuleInfo; } - const ModuleInfo& getDrawModuleInfo() const { return m_drawModuleInfo; } - const ModuleInfo& getClientUpdateModuleInfo() const { return m_clientUpdateModuleInfo; } - - const Image *getSelectedPortraitImage( void ) const { return m_selectedPortraitImage; } - const Image *getButtonImage( void ) const { return m_buttonImage; } - - //Code renderer handles these states now. - //const AsciiString& getInventoryImageName( InventoryImageType type ) const { return m_inventoryImage[ type ]; } - - Int getSkillPointValue(Int level) const; - - Int getExperienceValue(Int level) const { return m_experienceValues[level]; } - Int getExperienceRequired(Int level) const {return m_experienceRequired[level]; } - Bool isTrainable() const{return m_isTrainable; } - Bool isEnterGuard() const{return m_enterGuard; } - Bool isHijackGuard() const{return m_hijackGuard; } - - const AudioEventRTS *getVoiceSelect() const { return getAudio(TTAUDIO_voiceSelect); } - const AudioEventRTS *getVoiceGroupSelect() const { return getAudio(TTAUDIO_voiceGroupSelect); } - const AudioEventRTS *getVoiceMove() const { return getAudio(TTAUDIO_voiceMove); } - const AudioEventRTS *getVoiceAttack() const { return getAudio(TTAUDIO_voiceAttack); } - const AudioEventRTS *getVoiceEnter() const { return getAudio(TTAUDIO_voiceEnter); } - const AudioEventRTS *getVoiceFear() const { return getAudio(TTAUDIO_voiceFear); } - const AudioEventRTS *getVoiceSelectElite() const { return getAudio(TTAUDIO_voiceSelectElite); } - const AudioEventRTS *getVoiceCreated() const { return getAudio(TTAUDIO_voiceCreated); } - const AudioEventRTS *getVoiceNearEnemy() const { return getAudio(TTAUDIO_voiceNearEnemy); } - const AudioEventRTS *getVoiceTaskUnable() const { return getAudio(TTAUDIO_voiceTaskUnable); } - const AudioEventRTS *getVoiceTaskComplete() const { return getAudio(TTAUDIO_voiceTaskComplete); } - const AudioEventRTS *getVoiceMeetEnemy() const { return getAudio(TTAUDIO_voiceMeetEnemy); } - const AudioEventRTS *getVoiceGarrison() const { return getAudio(TTAUDIO_voiceGarrison); } -#ifdef ALLOW_SURRENDER - const AudioEventRTS *getVoiceSurrender() const { return getAudio(TTAUDIO_voiceSurrender); } -#endif - const AudioEventRTS *getVoiceDefect() const { return getAudio(TTAUDIO_voiceDefect); } - const AudioEventRTS *getVoiceAttackSpecial() const { return getAudio(TTAUDIO_voiceAttackSpecial); } - const AudioEventRTS *getVoiceAttackAir() const { return getAudio(TTAUDIO_voiceAttackAir); } - const AudioEventRTS *getVoiceGuard() const { return getAudio(TTAUDIO_voiceGuard); } - const AudioEventRTS *getSoundMoveStart() const { return getAudio(TTAUDIO_soundMoveStart); } - const AudioEventRTS *getSoundMoveStartDamaged() const { return getAudio(TTAUDIO_soundMoveStartDamaged); } - const AudioEventRTS *getSoundMoveLoop() const { return getAudio(TTAUDIO_soundMoveLoop); } - const AudioEventRTS *getSoundMoveLoopDamaged() const { return getAudio(TTAUDIO_soundMoveLoopDamaged); } - const AudioEventRTS *getSoundAmbient() const { return getAudio(TTAUDIO_soundAmbient); } - const AudioEventRTS *getSoundAmbientDamaged() const { return getAudio(TTAUDIO_soundAmbientDamaged); } - const AudioEventRTS *getSoundAmbientReallyDamaged() const { return getAudio(TTAUDIO_soundAmbientReallyDamaged); } - const AudioEventRTS *getSoundAmbientRubble() const { return getAudio(TTAUDIO_soundAmbientRubble); } - const AudioEventRTS *getSoundStealthOn() const { return getAudio(TTAUDIO_soundStealthOn); } - const AudioEventRTS *getSoundStealthOff() const { return getAudio(TTAUDIO_soundStealthOff); } - const AudioEventRTS *getSoundCreated() const { return getAudio(TTAUDIO_soundCreated); } - const AudioEventRTS *getSoundOnDamaged() const { return getAudio(TTAUDIO_soundOnDamaged); } - const AudioEventRTS *getSoundOnReallyDamaged() const { return getAudio(TTAUDIO_soundOnReallyDamaged); } - const AudioEventRTS *getSoundEnter() const { return getAudio(TTAUDIO_soundEnter); } - const AudioEventRTS *getSoundExit() const { return getAudio(TTAUDIO_soundExit); } - const AudioEventRTS *getSoundPromotedVeteran() const { return getAudio(TTAUDIO_soundPromotedVeteran); } - const AudioEventRTS *getSoundPromotedElite() const { return getAudio(TTAUDIO_soundPromotedElite); } - const AudioEventRTS *getSoundPromotedHero() const { return getAudio(TTAUDIO_soundPromotedHero); } - const AudioEventRTS *getSoundFalling() const { return getAudio(TTAUDIO_soundFalling); } - - Bool hasSoundAmbient() const { return hasAudio(TTAUDIO_soundAmbient); } - - const AudioEventRTS *getPerUnitSound(const AsciiString& soundName) const; - const FXList* getPerUnitFX(const AsciiString& fxName) const; - - UnsignedInt getThreatValue() const { return m_threatValue; } - - //------------------------------------------------------------------------------------------------- - /** If this is not NAMEKEY_INVALID, it indicates that all the templates which return the same name key - * should be counted as the same "type" when looking at getMaxSimultaneousOfType(). For instance, - * a Scud Storm and a Scud Storm rebuild hole will return the same value, so that the player - * can't build another Scud Storm while waiting for the rebuild hole to start rebuilding */ - //------------------------------------------------------------------------------------------------- - NameKeyType getMaxSimultaneousLinkKey() const { return m_maxSimultaneousLinkKey; } - UnsignedInt getMaxSimultaneousOfType() const; - - void validate(); - -// The version that does not take an Object argument is labeled friend for use by WorldBuilder. All game requests -// for CommandSet must use Object::getCommandSetString, as we have two different sources for dynamic answers. - const AsciiString& friend_getCommandSetString() const { return m_commandSetString; } - - const std::vector& getBuildVariations() const { return m_buildVariations; } - - Real getAssetScale() const { return m_assetScale; } ///< return uniform scaling - Real getInstanceScaleFuzziness() const { return m_instanceScaleFuzziness; } ///< return uniform scaling - Real getStructureRubbleHeight() const { return (Real)m_structureRubbleHeight; } ///< return uniform scaling - - /* - NOTE: if you have a Thing, don't call this function; call Thing::getGeometryInfo instead, since - geometry can now vary on a per-object basis. Only call this when you have no Thing around, - and want to get info for the "prototype" (eg, for building new Things)... - */ - const GeometryInfo& getTemplateGeometryInfo() const { return m_geometryInfo; } - - // - // these are intended ONLY for the private use of ThingFactory and do not use - // the m_override pointer, it deals only with templates at the "top" level - // - inline void friend_setTemplateName( const AsciiString& name ) { m_nameString = name; } - inline ThingTemplate *friend_getNextTemplate() const { return m_nextThingTemplate; } - inline void friend_setNextTemplate(ThingTemplate *tmplate) { m_nextThingTemplate = tmplate; } - inline void friend_setTemplateID(UnsignedShort id) { m_templateID = id; } - - Int getEnergyProduction() const { return m_energyProduction; } - Int getEnergyBonus() const { return m_energyBonus; } - - // these are NOT publicly available; you should call calcCostToBuild() or calcTimeToBuild() - // instead, because they will take player handicaps into account. - // Int getBuildCost() const { return m_buildCost; } - - Int getRefundValue() const { return m_refundValue; } - - BuildCompletionType getBuildCompletion() const { return (BuildCompletionType)m_buildCompletion; } - - BuildableStatus getBuildable() const; - - Int getPrereqCount() const { return m_prereqInfo.size(); } - const ProductionPrerequisite *getNthPrereq(Int i) const { return &m_prereqInfo[i]; } - - /** - return the BuildFacilityTemplate, if any. - - if this template needs no build facility, null is returned. - - if the template needs a build facility but the given player doesn't have any in existence, - null will be returned. - - if you pass null for player, we'll return the 'natural' build facility. - */ - const ThingTemplate *getBuildFacilityTemplate( const Player *player ) const; - - Bool isBuildableItem(void) const; - - /// calculate how long (in logic frames) it will take the given player to build this unit - Int calcTimeToBuild( const Player* player) const; - - /// calculate how much money it will take the given player to build this unit - Int calcCostToBuild( const Player* player) const; - - /// Used only by Skirmish AI. Everyone else should call calcCostToBuild. - Int friend_getBuildCost() const { return m_buildCost; } - - const AsciiString& getDefaultOwningSide() const { return m_defaultOwningSide; } - - /// get us the table to parse the fields for thing templates - const FieldParse* getFieldParse() const { return s_objectFieldParseTable; } - const FieldParse* getReskinFieldParse() const { return s_objectReskinFieldParseTable; } - - Bool isBuildFacility() const { return m_isBuildFacility; } - Real getPlacementViewAngle( void ) const { return m_placementViewAngle; } - - Real getFactoryExitWidth() const { return m_factoryExitWidth; } - Real getFactoryExtraBibWidth() const { return m_factoryExtraBibWidth; } - - void setCopiedFromDefault(); - - void setReskinnedFrom(const ThingTemplate* tt) { DEBUG_ASSERTCRASH(m_reskinnedFrom == NULL, ("should be null")); m_reskinnedFrom = tt; } - - Bool isPrerequisite() const { return m_isPrerequisite; } - - const WeaponTemplateSet* findWeaponTemplateSet(const WeaponSetFlags& t) const; - const ArmorTemplateSet* findArmorTemplateSet(const ArmorSetFlags& t) const; - - // returns true iff we have at least one weaponset that contains a weapon. - // returns false if we have no weaponsets, or they are all empty. - Bool canPossiblyHaveAnyWeapon() const; - - Bool isEquivalentTo(const ThingTemplate* tt) const; - - UnsignedByte getCrushableLevel() const { return m_crushableLevel; } - UnsignedByte getCrusherLevel() const { return m_crusherLevel; } - - AsciiString getUpgradeCameoName( Int n)const{ return m_upgradeCameoUpgradeNames[n]; } - - const WeaponTemplateSetVector& getWeaponTemplateSets(void) const {return m_weaponTemplateSets;} - -protected: - - // - // these are NOT publicly available; you should call calcCostToBuild() or calcTimeToBuild() - // instead, because they will take player handicaps into account. - // - Int getBuildCost() const { return m_buildCost; } - Real getBuildTime() const { return m_buildTime; } - const PerUnitSoundMap* getAllPerUnitSounds( void ) const { return &m_perUnitSounds; } - void validateAudio(); - const AudioEventRTS* getAudio(ThingTemplateAudioType t) const { return m_audioarray.m_audio[t] ? &m_audioarray.m_audio[t]->m_event : &s_audioEventNoSound; } - Bool hasAudio(ThingTemplateAudioType t) const { return m_audioarray.m_audio[t] != NULL; } - - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** Table for parsing the object fields */ - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - static void parseArmorTemplateSet( INI* ini, void *instance, void *store, const void* /*userData*/ ); - static void parseWeaponTemplateSet( INI* ini, void *instance, void *store, const void* /*userData*/ ); - static void parsePrerequisites( INI* ini, void *instance, void * /*store*/, const void* /*userData*/ ); - static void parseModuleName(INI* ini, void *instance, void* /*store*/, const void* userData); - static void parseIntList(INI* ini, void *instance, void* store, const void* userData); - - static void parsePerUnitSounds(INI* ini, void *instance, void* store, const void* userData); - static void parsePerUnitFX(INI* ini, void *instance, void* store, const void* userData); - - static void parseAddModule(INI *ini, void *instance, void *store, const void *userData); - static void parseRemoveModule(INI *ini, void *instance, void *store, const void *userData); - static void parseReplaceModule(INI *ini, void *instance, void *store, const void *userData); - static void parseInheritableModule(INI *ini, void *instance, void *store, const void *userData); - static void OverrideableByLikeKind(INI *ini, void *instance, void *store, const void *userData); - - static void parseMaxSimultaneous(INI *ini, void *instance, void *store, const void *userData); - - Bool removeModuleInfo(const AsciiString& moduleToRemove, AsciiString& clearedModuleNameOut); - -private: - static const FieldParse s_objectFieldParseTable[]; ///< the parse table - static const FieldParse s_objectReskinFieldParseTable[]; ///< the parse table - static AudioEventRTS s_audioEventNoSound; - -private: - - // ---- Strings - UnicodeString m_displayName; ///< UI display for onscreen display - AsciiString m_nameString; ///< name of this thing template - AsciiString m_defaultOwningSide; ///< default owning side (owning player is inferred) - AsciiString m_commandSetString; - AsciiString m_selectedPortraitImageName; - AsciiString m_buttonImageName; - AsciiString m_upgradeCameoUpgradeNames[MAX_UPGRADE_CAMEO_UPGRADES]; ///< Use these to find the upgrade images to display on the control bar - AsciiString m_shadowTextureName; ///< name of texture to use for shadow decal - AsciiString m_moduleBeingReplacedName; ///< used only during map.ini loading... name (not tag) of Module being replaced, or empty if not inside ReplaceModule block - AsciiString m_moduleBeingReplacedTag; ///< used only during map.ini loading... tag (not name) of Module being replaced, or empty if not inside ReplaceModule block -#ifdef LOAD_TEST_ASSETS - AsciiString m_LTAName; -#endif - - // ---- Misc Larger-than-int things - GeometryInfo m_geometryInfo; ///< geometry information - KindOfMaskType m_kindof; ///< kindof bits - AudioArray m_audioarray; - ModuleInfo m_behaviorModuleInfo; - ModuleInfo m_drawModuleInfo; - ModuleInfo m_clientUpdateModuleInfo; - - // ---- Misc Arrays-of-things - Int m_skillPointValues[LEVEL_COUNT]; - Int m_experienceValues[LEVEL_COUNT]; ///< How much I am worth at each experience level - Int m_experienceRequired[LEVEL_COUNT]; ///< How many experience points I need for each level - - //Code renderer handles these states now. - //AsciiString m_inventoryImage[ INV_IMAGE_NUM_IMAGES ]; ///< portrait inventory pictures - - // ---- STL-sized things - std::vector m_prereqInfo; ///< the unit Prereqs for this tech - std::vector m_buildVariations; /**< if we build a unit of this type via script or ui, randomly choose one - of these templates instead. (doesn't apply to MapObject-created items) */ - WeaponTemplateSetVector m_weaponTemplateSets; ///< our weaponsets - WeaponTemplateSetFinder m_weaponTemplateSetFinder; ///< helper to allow us to find the best sets, quickly - ArmorTemplateSetVector m_armorTemplateSets; ///< our armorsets - ArmorTemplateSetFinder m_armorTemplateSetFinder; ///< helper to allow us to find the best sets, quickly - PerUnitSoundMap m_perUnitSounds; ///< An additional set of sounds that only apply for this template. - PerUnitFXMap m_perUnitFX; ///< An additional set of fx that only apply for this template. - - // ---- Pointer-sized things - ThingTemplate* m_nextThingTemplate; - const ThingTemplate* m_reskinnedFrom; ///< non NULL if we were generated via a reskin - const Image * m_selectedPortraitImage; /// portrait image when selected (to display in GUI) - const Image * m_buttonImage; - - // ---- Real-sized things - Real m_fenceWidth; ///< Fence width for fence type objects. - Real m_fenceXOffset; ///< Fence X offset for fence type objects. - Real m_visionRange; ///< object "sees" this far around itself - Real m_shroudClearingRange; ///< Since So many things got added to "Seeing" functionality, we need to split this part out. - Real m_shroudRevealToAllRange; ///< When > zero, the shroud gets revealed to all players. - Real m_placementViewAngle; ///< when placing buildings this will be the angle of the building when "floating" at the mouse - Real m_factoryExitWidth; ///< when placing buildings this will be the width of the reserved exit area on the right side. - Real m_factoryExtraBibWidth; ///< when placing buildings this will be the width of the reserved exit area on the right side. - Real m_buildTime; ///< Seconds to build - Real m_assetScale; - Real m_instanceScaleFuzziness; ///< scale randomization tolerance to init for each Drawable instance, - Real m_shadowSizeX; ///< world-space extent of decal shadow texture - Real m_shadowSizeY; ///< world-space extent of decal shadow texture - Real m_shadowOffsetX; ///< world-space offset of decal shadow texture - Real m_shadowOffsetY; ///< world-space offset of decal shadow texture - - // ---- Int-sized things - Int m_energyProduction; ///< how much Energy this takes (negative values produce Energy, rather than consuming it) - Int m_energyBonus; ///< how much extra Energy this produces due to the upgrade - Color m_displayColor; ///< for the editor display color - UnsignedInt m_occlusionDelay; ///< delay after object creation before building occlusion is allowed. - NameKeyType m_maxSimultaneousLinkKey; ///< If this is not NAMEKEY_INVALID, it indicates that all the templates which have the same name key should be counted as the same "type" when looking at getMaxSimultaneousOfType(). - - // ---- Short-sized things - UnsignedShort m_templateID; ///< id for net (etc.) transmission purposes - UnsignedShort m_buildCost; ///< money to build (0 == not buildable) - UnsignedShort m_refundValue; ///< custom resale value, if sold. (0 == use default) - UnsignedShort m_threatValue; ///< Threat map info - UnsignedShort m_maxSimultaneousOfType; ///< max simultaneous of this unit we can have (per player) at one time. (0 == unlimited) - - // ---- Bool-sized things - Bool m_maxSimultaneousDeterminedBySuperweaponRestriction; ///< If true, override value in m_maxSimultaneousOfType with value from GameInfo::getSuperweaponRestriction() - Bool m_isPrerequisite; ///< Is this thing considered in a prerequisite for any other thing? - Bool m_isBridge; ///< True if this model is a bridge. - Bool m_isBuildFacility; ///< is this the build facility for something? (calculated based on other template's prereqs) - Bool m_isTrainable; ///< Whether or not I can even gain experience - Bool m_enterGuard; ///< Whether or not I can enter objects when guarding - Bool m_hijackGuard; ///< Whether or not I can hijack objects when guarding - Bool m_isForbidden; ///< useful when overriding in .ini - Bool m_armorCopiedFromDefault; - Bool m_weaponsCopiedFromDefault; - - // ---- Byte-sized things - Byte m_radarPriority; ///< does object appear on radar, and if so at what priority - Byte m_transportSlotCount; ///< how many "slots" we take in a transport (0 == not transportable) - Byte m_buildable; ///< is this thing buildable at all? - Byte m_buildCompletion; ///< how the units come into the world when build is complete - Byte m_editorSorting; ///< editor sorting type, see EditorSortingType enum - Byte m_structureRubbleHeight; - Byte m_shadowType; ///< settings which determine the type of shadow rendered - Byte m_moduleParsingMode; - UnsignedByte m_crusherLevel; ///< crusher > crushable level to actually crush - UnsignedByte m_crushableLevel; ///< Specifies the level of crushability (must be hit by a crusher greater than this to crush me). - - -}; - -//----------------------------------------------------------------------------- -// Inlining -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Externals -//----------------------------------------------------------------------------- - -#endif // __THINGTEMPLATE_H_ - +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ThingTemplate.h ////////////////////////////////////////////////////////////////////////// +// Author: Colin Day, April 2001 +// Desc: Thing templates are a 'roadmap' to creating things +/////////////////////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __THINGTEMPLATE_H_ +#define __THINGTEMPLATE_H_ + +// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// +#include "Lib/BaseType.h" + +#include "Common/AudioEventRTS.h" +#include "Common/FileSystem.h" +#include "Common/GameCommon.h" +#include "Common/Geometry.h" +#include "Common/KindOf.h" +#include "Common/ModuleFactory.h" +#include "Common/Overridable.h" +#include "Common/ProductionPrerequisite.h" +#include "Common/Science.h" +#include "Common/UnicodeString.h" + +#include "GameLogic/ArmorSet.h" +#include "GameLogic/WeaponSet.h" +#include "Common/STLTypedefs.h" +#include "GameClient/Color.h" + +// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// +class AIUpdateModuleData; +class Image; +class Object; +class Drawable; +class ProductionPrerequisite; +struct FieldParse; +class Player; +class INI; +enum RadarPriorityType CPP_11(: Int); +enum ScienceType CPP_11(: Int); +enum EditorSortingType CPP_11(: Int); +enum ShadowType CPP_11(: Int); +class WeaponTemplateSet; +class ArmorTemplateSet; +class FXList; + +// TYPEDEFS FOR FILE ////////////////////////////////////////////////////////////////////////////// +typedef std::map PerUnitSoundMap; +typedef std::map PerUnitFXMap; + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//Code renderer handles these states now. +//enum InventoryImageType +//{ +// INV_IMAGE_ENABLED = 0, +// INV_IMAGE_DISABLED, +// INV_IMAGE_HILITE, +// INV_IMAGE_PUSHED, +// +// INV_IMAGE_NUM_IMAGES // keep this last +// +//}; +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +enum +{ + MAX_UPGRADE_CAMEO_UPGRADES = 5 +}; + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +enum ThingTemplateAudioType CPP_11(: Int) +{ + TTAUDIO_voiceSelect, ///< Response when unit is selected + TTAUDIO_voiceGroupSelect, ///< Response when a group of this unit is selected + TTAUDIO_voiceSelectElite, ///< Response when unit is selected and elite + TTAUDIO_voiceMove, ///< Response when unit moves + TTAUDIO_voiceAttack, ///< Response when unit is told to attack + TTAUDIO_voiceEnter, ///< Response when unit is told to enter a building + TTAUDIO_voiceFear, ///< Response when unit is under attack + TTAUDIO_voiceCreated, ///< Response when unit is created + TTAUDIO_voiceNearEnemy, ///< Unit is near an enemy + TTAUDIO_voiceTaskUnable, ///< Unit is told to do something impossible + TTAUDIO_voiceTaskComplete, ///< Unit completes a move, or other task indicated + TTAUDIO_voiceMeetEnemy, ///< Unit meets an enemy unit + TTAUDIO_soundMoveStart, ///< Sound when unit starts moving + TTAUDIO_soundMoveStartDamaged, ///< Sound when unit starts moving and is damaged + TTAUDIO_soundMoveLoop, ///< Sound when unit is moving + TTAUDIO_soundMoveLoopDamaged, ///< Sound when unit is moving and is damaged + TTAUDIO_soundAmbient, ///< Ambient sound for unit during normal status. Also the default sound + TTAUDIO_soundAmbientDamaged, ///< Ambient sound for unit if damaged. Corresponds to body info damage + TTAUDIO_soundAmbientReallyDamaged,///< Ambient sound for unit if badly damaged. + TTAUDIO_soundAmbientRubble, ///< Ambient sound for unit if it is currently rubble. (Dam, for instance) + TTAUDIO_soundStealthOn, ///< Sound when unit stealths + TTAUDIO_soundStealthOff, ///< Sound when unit destealths + TTAUDIO_soundCreated, ///< Sound when unit is created + TTAUDIO_soundOnDamaged, ///< Sound when unit enters damaged state + TTAUDIO_soundOnReallyDamaged, ///< Sound when unit enters reallyd damaged state + TTAUDIO_soundEnter, ///< Sound when another unit enters me. + TTAUDIO_soundExit, ///< Sound when another unit exits me. + TTAUDIO_soundPromotedVeteran, ///< Sound when unit gets promoted to Veteran level + TTAUDIO_soundPromotedElite, ///< Sound when unit gets promoted to Elite level + TTAUDIO_soundPromotedHero, ///< Sound when unit gets promoted to Hero level + TTAUDIO_voiceGarrison, ///< Unit is ordered to enter a garrisonable building + TTAUDIO_soundFalling, ///< This sound is actually called on a unit when it is exiting another. + ///< However, there is a soundExit which refers to the container, and this is only used for bombs falling from planes. +#ifdef ALLOW_SURRENDER + TTAUDIO_voiceSurrender, ///< Unit surrenders +#endif + TTAUDIO_voiceDefect, ///< Unit is forced to defect + TTAUDIO_voiceAttackSpecial, ///< Unit is ordered to use a special attack + TTAUDIO_voiceAttackAir, ///< Unit is ordered to attack an airborne unit + TTAUDIO_voiceGuard, ///< Unit is ordered to guard an area + + TTAUDIO_COUNT // keep last! +}; + +class AudioArray +{ +public: + DynamicAudioEventRTS* m_audio[TTAUDIO_COUNT]; + + AudioArray() + { + for (Int i = 0; i < TTAUDIO_COUNT; ++i) + m_audio[i] = NULL; + } + + ~AudioArray() + { + for (Int i = 0; i < TTAUDIO_COUNT; ++i) + if (m_audio[i]) + m_audio[i]->deleteInstance(); + } + + AudioArray(const AudioArray& that) + { + for (Int i = 0; i < TTAUDIO_COUNT; ++i) + { + if (that.m_audio[i]) + m_audio[i] = newInstance(DynamicAudioEventRTS)(*that.m_audio[i]); + else + m_audio[i] = NULL; + } + } + + AudioArray& operator=(const AudioArray& that) + { + if (this != &that) + { + for (Int i = 0; i < TTAUDIO_COUNT; ++i) + { + if (that.m_audio[i]) + { + if (m_audio[i]) + *m_audio[i] = *that.m_audio[i]; + else + m_audio[i] = newInstance(DynamicAudioEventRTS)(*that.m_audio[i]); + } + else + { + m_audio[i] = NULL; + } + } + } + return *this; + } +}; + +//------------------------------------------------------------------------------------------------- +/** Object class type enumeration */ +//------------------------------------------------------------------------------------------------- +enum BuildCompletionType CPP_11(: Int) +{ + BC_INVALID = 0, + BC_APPEARS_AT_RALLY_POINT, ///< unit appears at rally point of its #1 prereq + BC_PLACED_BY_PLAYER, ///< unit must be manually placed by player + + BC_NUM_TYPES // leave this last +}; +#ifdef DEFINE_BUILD_COMPLETION_NAMES +static const char *BuildCompletionNames[] = +{ + "INVALID", + "APPEARS_AT_RALLY_POINT", + "PLACED_BY_PLAYER", + + NULL +}; +#endif // end DEFINE_BUILD_COMPLETION_NAMES + +enum BuildableStatus CPP_11(: Int) +{ + // saved into savegames... do not change or remove values! + BSTATUS_YES = 0, + BSTATUS_IGNORE_PREREQUISITES, + BSTATUS_NO, + BSTATUS_ONLY_BY_AI, + + BSTATUS_NUM_TYPES // leave this last +}; + +#ifdef DEFINE_BUILDABLE_STATUS_NAMES +static const char *BuildableStatusNames[] = +{ + "Yes", + "Ignore_Prerequisites", + "No", + "Only_By_AI", + NULL +}; +#endif // end DEFINE_BUILDABLE_STATUS_NAMES + +enum AmmoPipsStyle CPP_11(: Int) +{ + AMMO_PIPS_DEFAULT = 0, ///< Default style, showing each shot in clip + AMMO_PIPS_BAR, ///< Show percentage bar + AMMO_PIPS_SINGLE, ///< like default, but show a single pip only (full or empty) + + AMMO_PIPS_NUM_TYPES // leave this last +}; +#ifdef DEFINE_AMMO_PIPS_STYLE_NAMES +static const char* AmmoPipsStyleNames[] = +{ + "DEFAULT", + "PERCENTAGE_BAR", + "SINGLE", + + NULL +}; +#endif // end DEFINE_AMMO_PIPS_STYLE_NAMES + +//------------------------------------------------------------------------------------------------- +enum ModuleParseMode CPP_11(: Int) +{ + MODULEPARSE_NORMAL, + MODULEPARSE_ADD_REMOVE_REPLACE, + MODULEPARSE_INHERITABLE, + MODULEPARSE_OVERRIDEABLE_BY_LIKE_KIND, + +}; + +//------------------------------------------------------------------------------------------------- +class ModuleInfo +{ +private: + struct Nugget + { + AsciiString first; + AsciiString m_moduleTag; + const ModuleData* second; + Int interfaceMask; + Bool copiedFromDefault; + Bool inheritable; + Bool overrideableByLikeKind; + + Nugget(const AsciiString& n, const AsciiString& moduleTag, const ModuleData* d, Int i, Bool inh, Bool oblk) + : first(n), + m_moduleTag(moduleTag), + second(d), + interfaceMask(i), + copiedFromDefault(false), + inheritable(inh), + overrideableByLikeKind(oblk) + { + } + + }; + std::vector m_info; + +public: + + ModuleInfo() { } + + void addModuleInfo( ThingTemplate *thingTemplate, const AsciiString& name, const AsciiString& moduleTag, const ModuleData* data, Int interfaceMask, Bool inheritable, Bool overrideableByLikeKind = FALSE ); + const ModuleInfo::Nugget *getNuggetWithTag( const AsciiString& tag ) const; + + Int getCount() const + { + return m_info.size(); + } + +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + Bool containsPartialName(const char* n) const + { + for (size_t i = 0; i < m_info.size(); i++) + if (strstr(m_info[i].first.str(), n) != NULL) + return true; + return false; + } +#endif + + AsciiString getNthName(size_t i) const + { + if (i >= 0 && i < m_info.size()) + { + return m_info[i].first; + } + return AsciiString::TheEmptyString; + } + + AsciiString getNthTag(size_t i) const + { + if (i >= 0 && i < m_info.size()) + { + return m_info[i].m_moduleTag; + } + return AsciiString::TheEmptyString; + } + + const ModuleData* getNthData(size_t i) const + { + if (i >= 0 && i < m_info.size()) + { + return m_info[i].second; + } + return NULL; + } + + // for use only by ThingTemplate::friend_getAIModuleInfo + ModuleData* friend_getNthData(Int i); + + void clear() + { + m_info.clear(); + } + + void setCopiedFromDefault(Bool v) + { + for (size_t i = 0; i < m_info.size(); i++) + m_info[i].copiedFromDefault = v; + } + + Bool clearModuleDataWithTag(const AsciiString& tagToClear, AsciiString& clearedModuleNameOut); + Bool clearCopiedFromDefaultEntries(Int interfaceMask, const AsciiString &name, const ThingTemplate *fullTemplate ); + Bool clearAiModuleInfo(); +}; + +//------------------------------------------------------------------------------------------------- +/** Definition of a thing template to read from our game data framework */ +//------------------------------------------------------------------------------------------------- +class ThingTemplate : public Overridable +{ + + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ThingTemplate, "ThingTemplatePool" ) + +private: + +#if defined(_MSC_VER) && _MSC_VER < 1300 + ThingTemplate(const ThingTemplate& that) : m_geometryInfo(that.m_geometryInfo) + { + DEBUG_CRASH(("This should never be called\n")); + } +#else + ThingTemplate(const ThingTemplate& that) = delete; +#endif + +public: + + + ThingTemplate(); + + // copy the guts of that into this, but preserve this' name, id, and list-links. + void copyFrom(const ThingTemplate* that); + + /// called by ThingFactory after all templates have been loaded. + void resolveNames(); + +#ifdef LOAD_TEST_ASSETS + void initForLTA(const AsciiString& name); + inline AsciiString getLTAName() const { return m_LTAName; } +#endif + + /** + return a unique identifier suitable for identifying this ThingTemplate on machines playing + across the net. this should be considered a Magic Cookie and used only for net traffic or + similar sorts of things. To convert an id back to a ThingTemplate, use ThingFactory::findByID(). + Note that 0 is always an invalid id. NOTE that we are not referencing m_override here + because even though we actually have multiple templates here representing overrides, + we still only conceptually have one template and want to always use one single + pointer for comparisons of templates. However, even if we did reference m_override + the IDs would be the same for each one since every override first *COPIES* data + from the current/parent template data. + */ + UnsignedShort getTemplateID() const { return m_templateID; } + + // note that m_override is not used here, see getTemplateID(), for it is the same reasons + const AsciiString& getName() const { return m_nameString; } ///< return the name of this template + + /// get the display color (used for the editor) + Color getDisplayColor() const { return m_displayColor; } + + /// get the editor sorting + EditorSortingType getEditorSorting() const { return (EditorSortingType)m_editorSorting; } + + /// return true iff the template has the specified kindOf flag set. + inline Bool isKindOf(KindOfType t) const + { + return TEST_KINDOFMASK(m_kindof, t); + } + + /// convenience for doing multiple kindof testing at once. + inline Bool isKindOfMulti(const KindOfMaskType& mustBeSet, const KindOfMaskType& mustBeClear) const + { + return TEST_KINDOFMASK_MULTI(m_kindof, mustBeSet, mustBeClear); + } + + inline Bool isAnyKindOf( const KindOfMaskType& anyKindOf ) const + { + return TEST_KINDOFMASK_ANY(m_kindof, anyKindOf); + } + + /// set the display name + const UnicodeString& getDisplayName() const { return m_displayName; } ///< return display name + + RadarPriorityType getDefaultRadarPriority() const { return (RadarPriorityType)m_radarPriority; } ///< return radar priority from INI + + AmmoPipsStyle getAmmoPipsStyle() const { return (AmmoPipsStyle)m_ammoPipsStyle; } ///< return ammo pips style from ini + + + // note, you should not call this directly; rather, call Object::getTransportSlotCount(). + Int getRawTransportSlotCount() const { return m_transportSlotCount; } + + Real getFenceWidth() const { return m_fenceWidth; } // return fence width + + Real getFenceXOffset() const { return m_fenceXOffset; } // return fence offset + + Bool isBridge() const { return m_isBridge; } // return fence offset + + // Only Object can ask this. Everyone else should ask the Object. In fact, you really should ask the Object everything. + Real friend_calcVisionRange() const { return m_visionRange; } ///< get vision range + Real friend_calcShroudClearingRange() const { return m_shroudClearingRange; } ///< get vision range for Shroud ONLY (Design requested split) + + //This one is okay to check directly... because it doesn't get effected by bonuses. + Real getShroudRevealToAllRange() const { return m_shroudRevealToAllRange; } + + // This function is only for use by the AIUpdateModuleData::parseLocomotorSet function. + AIUpdateModuleData *friend_getAIModuleInfo(void); + + ShadowType getShadowType() const { return (ShadowType)m_shadowType; } + Real getShadowSizeX() const { return m_shadowSizeX; } + Real getShadowSizeY() const { return m_shadowSizeY; } + Real getShadowOffsetX() const { return m_shadowOffsetX; } + Real getShadowOffsetY() const { return m_shadowOffsetY; } + + const AsciiString& getShadowTextureName( void ) const { return m_shadowTextureName; } + UnsignedInt getOcclusionDelay(void) const { return m_occlusionDelay;} + + const ModuleInfo& getBehaviorModuleInfo() const { return m_behaviorModuleInfo; } + const ModuleInfo& getDrawModuleInfo() const { return m_drawModuleInfo; } + const ModuleInfo& getClientUpdateModuleInfo() const { return m_clientUpdateModuleInfo; } + + const Image *getSelectedPortraitImage( void ) const { return m_selectedPortraitImage; } + const Image *getButtonImage( void ) const { return m_buttonImage; } + + //Code renderer handles these states now. + //const AsciiString& getInventoryImageName( InventoryImageType type ) const { return m_inventoryImage[ type ]; } + + Int getSkillPointValue(Int level) const; + + Int getExperienceValue(Int level) const { return m_experienceValues[level]; } + Int getExperienceRequired(Int level) const {return m_experienceRequired[level]; } + Bool isTrainable() const{return m_isTrainable; } + Bool isEnterGuard() const{return m_enterGuard; } + Bool isHijackGuard() const{return m_hijackGuard; } + + const AudioEventRTS *getVoiceSelect() const { return getAudio(TTAUDIO_voiceSelect); } + const AudioEventRTS *getVoiceGroupSelect() const { return getAudio(TTAUDIO_voiceGroupSelect); } + const AudioEventRTS *getVoiceMove() const { return getAudio(TTAUDIO_voiceMove); } + const AudioEventRTS *getVoiceAttack() const { return getAudio(TTAUDIO_voiceAttack); } + const AudioEventRTS *getVoiceEnter() const { return getAudio(TTAUDIO_voiceEnter); } + const AudioEventRTS *getVoiceFear() const { return getAudio(TTAUDIO_voiceFear); } + const AudioEventRTS *getVoiceSelectElite() const { return getAudio(TTAUDIO_voiceSelectElite); } + const AudioEventRTS *getVoiceCreated() const { return getAudio(TTAUDIO_voiceCreated); } + const AudioEventRTS *getVoiceNearEnemy() const { return getAudio(TTAUDIO_voiceNearEnemy); } + const AudioEventRTS *getVoiceTaskUnable() const { return getAudio(TTAUDIO_voiceTaskUnable); } + const AudioEventRTS *getVoiceTaskComplete() const { return getAudio(TTAUDIO_voiceTaskComplete); } + const AudioEventRTS *getVoiceMeetEnemy() const { return getAudio(TTAUDIO_voiceMeetEnemy); } + const AudioEventRTS *getVoiceGarrison() const { return getAudio(TTAUDIO_voiceGarrison); } +#ifdef ALLOW_SURRENDER + const AudioEventRTS *getVoiceSurrender() const { return getAudio(TTAUDIO_voiceSurrender); } +#endif + const AudioEventRTS *getVoiceDefect() const { return getAudio(TTAUDIO_voiceDefect); } + const AudioEventRTS *getVoiceAttackSpecial() const { return getAudio(TTAUDIO_voiceAttackSpecial); } + const AudioEventRTS *getVoiceAttackAir() const { return getAudio(TTAUDIO_voiceAttackAir); } + const AudioEventRTS *getVoiceGuard() const { return getAudio(TTAUDIO_voiceGuard); } + const AudioEventRTS *getSoundMoveStart() const { return getAudio(TTAUDIO_soundMoveStart); } + const AudioEventRTS *getSoundMoveStartDamaged() const { return getAudio(TTAUDIO_soundMoveStartDamaged); } + const AudioEventRTS *getSoundMoveLoop() const { return getAudio(TTAUDIO_soundMoveLoop); } + const AudioEventRTS *getSoundMoveLoopDamaged() const { return getAudio(TTAUDIO_soundMoveLoopDamaged); } + const AudioEventRTS *getSoundAmbient() const { return getAudio(TTAUDIO_soundAmbient); } + const AudioEventRTS *getSoundAmbientDamaged() const { return getAudio(TTAUDIO_soundAmbientDamaged); } + const AudioEventRTS *getSoundAmbientReallyDamaged() const { return getAudio(TTAUDIO_soundAmbientReallyDamaged); } + const AudioEventRTS *getSoundAmbientRubble() const { return getAudio(TTAUDIO_soundAmbientRubble); } + const AudioEventRTS *getSoundStealthOn() const { return getAudio(TTAUDIO_soundStealthOn); } + const AudioEventRTS *getSoundStealthOff() const { return getAudio(TTAUDIO_soundStealthOff); } + const AudioEventRTS *getSoundCreated() const { return getAudio(TTAUDIO_soundCreated); } + const AudioEventRTS *getSoundOnDamaged() const { return getAudio(TTAUDIO_soundOnDamaged); } + const AudioEventRTS *getSoundOnReallyDamaged() const { return getAudio(TTAUDIO_soundOnReallyDamaged); } + const AudioEventRTS *getSoundEnter() const { return getAudio(TTAUDIO_soundEnter); } + const AudioEventRTS *getSoundExit() const { return getAudio(TTAUDIO_soundExit); } + const AudioEventRTS *getSoundPromotedVeteran() const { return getAudio(TTAUDIO_soundPromotedVeteran); } + const AudioEventRTS *getSoundPromotedElite() const { return getAudio(TTAUDIO_soundPromotedElite); } + const AudioEventRTS *getSoundPromotedHero() const { return getAudio(TTAUDIO_soundPromotedHero); } + const AudioEventRTS *getSoundFalling() const { return getAudio(TTAUDIO_soundFalling); } + + Bool hasSoundAmbient() const { return hasAudio(TTAUDIO_soundAmbient); } + + const AudioEventRTS *getPerUnitSound(const AsciiString& soundName) const; + const FXList* getPerUnitFX(const AsciiString& fxName) const; + + UnsignedInt getThreatValue() const { return m_threatValue; } + + //------------------------------------------------------------------------------------------------- + /** If this is not NAMEKEY_INVALID, it indicates that all the templates which return the same name key + * should be counted as the same "type" when looking at getMaxSimultaneousOfType(). For instance, + * a Scud Storm and a Scud Storm rebuild hole will return the same value, so that the player + * can't build another Scud Storm while waiting for the rebuild hole to start rebuilding */ + //------------------------------------------------------------------------------------------------- + NameKeyType getMaxSimultaneousLinkKey() const { return m_maxSimultaneousLinkKey; } + UnsignedInt getMaxSimultaneousOfType() const; + + void validate(); + +// The version that does not take an Object argument is labeled friend for use by WorldBuilder. All game requests +// for CommandSet must use Object::getCommandSetString, as we have two different sources for dynamic answers. + const AsciiString& friend_getCommandSetString() const { return m_commandSetString; } + + const std::vector& getBuildVariations() const { return m_buildVariations; } + + Real getAssetScale() const { return m_assetScale; } ///< return uniform scaling + Real getInstanceScaleFuzziness() const { return m_instanceScaleFuzziness; } ///< return uniform scaling + Real getStructureRubbleHeight() const { return (Real)m_structureRubbleHeight; } ///< return uniform scaling + + /* + NOTE: if you have a Thing, don't call this function; call Thing::getGeometryInfo instead, since + geometry can now vary on a per-object basis. Only call this when you have no Thing around, + and want to get info for the "prototype" (eg, for building new Things)... + */ + const GeometryInfo& getTemplateGeometryInfo() const { return m_geometryInfo; } + + // + // these are intended ONLY for the private use of ThingFactory and do not use + // the m_override pointer, it deals only with templates at the "top" level + // + inline void friend_setTemplateName( const AsciiString& name ) { m_nameString = name; } + inline ThingTemplate *friend_getNextTemplate() const { return m_nextThingTemplate; } + inline void friend_setNextTemplate(ThingTemplate *tmplate) { m_nextThingTemplate = tmplate; } + inline void friend_setTemplateID(UnsignedShort id) { m_templateID = id; } + + Int getEnergyProduction() const { return m_energyProduction; } + Int getEnergyBonus() const { return m_energyBonus; } + + // these are NOT publicly available; you should call calcCostToBuild() or calcTimeToBuild() + // instead, because they will take player handicaps into account. + // Int getBuildCost() const { return m_buildCost; } + + Int getRefundValue() const { return m_refundValue; } + + BuildCompletionType getBuildCompletion() const { return (BuildCompletionType)m_buildCompletion; } + + BuildableStatus getBuildable() const; + + Int getPrereqCount() const { return m_prereqInfo.size(); } + const ProductionPrerequisite *getNthPrereq(Int i) const { return &m_prereqInfo[i]; } + + /** + return the BuildFacilityTemplate, if any. + + if this template needs no build facility, null is returned. + + if the template needs a build facility but the given player doesn't have any in existence, + null will be returned. + + if you pass null for player, we'll return the 'natural' build facility. + */ + const ThingTemplate *getBuildFacilityTemplate( const Player *player ) const; + + Bool isBuildableItem(void) const; + + /// calculate how long (in logic frames) it will take the given player to build this unit + Int calcTimeToBuild( const Player* player) const; + + /// calculate how much money it will take the given player to build this unit + Int calcCostToBuild( const Player* player) const; + + /// Used only by Skirmish AI. Everyone else should call calcCostToBuild. + Int friend_getBuildCost() const { return m_buildCost; } + + const AsciiString& getDefaultOwningSide() const { return m_defaultOwningSide; } + + /// get us the table to parse the fields for thing templates + const FieldParse* getFieldParse() const { return s_objectFieldParseTable; } + const FieldParse* getReskinFieldParse() const { return s_objectReskinFieldParseTable; } + + Bool isBuildFacility() const { return m_isBuildFacility; } + Real getPlacementViewAngle( void ) const { return m_placementViewAngle; } + + Real getFactoryExitWidth() const { return m_factoryExitWidth; } + Real getFactoryExtraBibWidth() const { return m_factoryExtraBibWidth; } + + void setCopiedFromDefault(); + + // Only set non removable modules as copied when using ObjectExtend + void setCopiedFromDefaultExtended(); + + void setReskinnedFrom(const ThingTemplate* tt) { DEBUG_ASSERTCRASH(m_reskinnedFrom == NULL, ("should be null")); m_reskinnedFrom = tt; } + + Bool isPrerequisite() const { return m_isPrerequisite; } + + const WeaponTemplateSet* findWeaponTemplateSet(const WeaponSetFlags& t) const; + const ArmorTemplateSet* findArmorTemplateSet(const ArmorSetFlags& t) const; + + // returns true iff we have at least one weaponset that contains a weapon. + // returns false if we have no weaponsets, or they are all empty. + Bool canPossiblyHaveAnyWeapon() const; + + Bool isEquivalentTo(const ThingTemplate* tt) const; + + UnsignedByte getCrushableLevel() const { return m_crushableLevel; } + UnsignedByte getCrusherLevel() const { return m_crusherLevel; } + + AsciiString getUpgradeCameoName( Int n)const{ return m_upgradeCameoUpgradeNames[n]; } + + const WeaponTemplateSetVector& getWeaponTemplateSets(void) const {return m_weaponTemplateSets;} + +protected: + + // + // these are NOT publicly available; you should call calcCostToBuild() or calcTimeToBuild() + // instead, because they will take player handicaps into account. + // + Int getBuildCost() const { return m_buildCost; } + Real getBuildTime() const { return m_buildTime; } + const PerUnitSoundMap* getAllPerUnitSounds( void ) const { return &m_perUnitSounds; } + void validateAudio(); + const AudioEventRTS* getAudio(ThingTemplateAudioType t) const { return m_audioarray.m_audio[t] ? &m_audioarray.m_audio[t]->m_event : &s_audioEventNoSound; } + Bool hasAudio(ThingTemplateAudioType t) const { return m_audioarray.m_audio[t] != NULL; } + + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + /** Table for parsing the object fields */ + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + static void parseArmorTemplateSet( INI* ini, void *instance, void *store, const void* /*userData*/ ); + static void parseWeaponTemplateSet( INI* ini, void *instance, void *store, const void* /*userData*/ ); + static void parsePrerequisites( INI* ini, void *instance, void * /*store*/, const void* /*userData*/ ); + static void parseModuleName(INI* ini, void *instance, void* /*store*/, const void* userData); + static void parseIntList(INI* ini, void *instance, void* store, const void* userData); + + static void parsePerUnitSounds(INI* ini, void *instance, void* store, const void* userData); + static void parsePerUnitFX(INI* ini, void *instance, void* store, const void* userData); + + static void parseAddModule(INI *ini, void *instance, void *store, const void *userData); + static void parseRemoveModule(INI *ini, void *instance, void *store, const void *userData); + static void parseReplaceModule(INI *ini, void *instance, void *store, const void *userData); + static void parseInheritableModule(INI *ini, void *instance, void *store, const void *userData); + static void OverrideableByLikeKind(INI *ini, void *instance, void *store, const void *userData); + + static void parseMaxSimultaneous(INI *ini, void *instance, void *store, const void *userData); + + Bool removeModuleInfo(const AsciiString& moduleToRemove, AsciiString& clearedModuleNameOut); + +private: + static const FieldParse s_objectFieldParseTable[]; ///< the parse table + static const FieldParse s_objectReskinFieldParseTable[]; ///< the parse table + static AudioEventRTS s_audioEventNoSound; + +private: + + // ---- Strings + UnicodeString m_displayName; ///< UI display for onscreen display + AsciiString m_nameString; ///< name of this thing template + AsciiString m_defaultOwningSide; ///< default owning side (owning player is inferred) + AsciiString m_commandSetString; + AsciiString m_selectedPortraitImageName; + AsciiString m_buttonImageName; + AsciiString m_upgradeCameoUpgradeNames[MAX_UPGRADE_CAMEO_UPGRADES]; ///< Use these to find the upgrade images to display on the control bar + AsciiString m_shadowTextureName; ///< name of texture to use for shadow decal + AsciiString m_moduleBeingReplacedName; ///< used only during map.ini loading... name (not tag) of Module being replaced, or empty if not inside ReplaceModule block + AsciiString m_moduleBeingReplacedTag; ///< used only during map.ini loading... tag (not name) of Module being replaced, or empty if not inside ReplaceModule block +#ifdef LOAD_TEST_ASSETS + AsciiString m_LTAName; +#endif + + // ---- Misc Larger-than-int things + GeometryInfo m_geometryInfo; ///< geometry information + KindOfMaskType m_kindof; ///< kindof bits + AudioArray m_audioarray; + ModuleInfo m_behaviorModuleInfo; + ModuleInfo m_drawModuleInfo; + ModuleInfo m_clientUpdateModuleInfo; + + // ---- Misc Arrays-of-things + Int m_skillPointValues[LEVEL_COUNT]; + Int m_experienceValues[LEVEL_COUNT]; ///< How much I am worth at each experience level + Int m_experienceRequired[LEVEL_COUNT]; ///< How many experience points I need for each level + + //Code renderer handles these states now. + //AsciiString m_inventoryImage[ INV_IMAGE_NUM_IMAGES ]; ///< portrait inventory pictures + + // ---- STL-sized things + std::vector m_prereqInfo; ///< the unit Prereqs for this tech + std::vector m_buildVariations; /**< if we build a unit of this type via script or ui, randomly choose one + of these templates instead. (doesn't apply to MapObject-created items) */ + WeaponTemplateSetVector m_weaponTemplateSets; ///< our weaponsets + WeaponTemplateSetFinder m_weaponTemplateSetFinder; ///< helper to allow us to find the best sets, quickly + ArmorTemplateSetVector m_armorTemplateSets; ///< our armorsets + ArmorTemplateSetFinder m_armorTemplateSetFinder; ///< helper to allow us to find the best sets, quickly + PerUnitSoundMap m_perUnitSounds; ///< An additional set of sounds that only apply for this template. + PerUnitFXMap m_perUnitFX; ///< An additional set of fx that only apply for this template. + + // ---- Pointer-sized things + ThingTemplate* m_nextThingTemplate; + const ThingTemplate* m_reskinnedFrom; ///< non NULL if we were generated via a reskin + const Image * m_selectedPortraitImage; /// portrait image when selected (to display in GUI) + const Image * m_buttonImage; + + // ---- Real-sized things + Real m_fenceWidth; ///< Fence width for fence type objects. + Real m_fenceXOffset; ///< Fence X offset for fence type objects. + Real m_visionRange; ///< object "sees" this far around itself + Real m_shroudClearingRange; ///< Since So many things got added to "Seeing" functionality, we need to split this part out. + Real m_shroudRevealToAllRange; ///< When > zero, the shroud gets revealed to all players. + Real m_placementViewAngle; ///< when placing buildings this will be the angle of the building when "floating" at the mouse + Real m_factoryExitWidth; ///< when placing buildings this will be the width of the reserved exit area on the right side. + Real m_factoryExtraBibWidth; ///< when placing buildings this will be the width of the reserved exit area on the right side. + Real m_buildTime; ///< Seconds to build + Real m_assetScale; + Real m_instanceScaleFuzziness; ///< scale randomization tolerance to init for each Drawable instance, + Real m_shadowSizeX; ///< world-space extent of decal shadow texture + Real m_shadowSizeY; ///< world-space extent of decal shadow texture + Real m_shadowOffsetX; ///< world-space offset of decal shadow texture + Real m_shadowOffsetY; ///< world-space offset of decal shadow texture + + // ---- Int-sized things + Int m_energyProduction; ///< how much Energy this takes (negative values produce Energy, rather than consuming it) + Int m_energyBonus; ///< how much extra Energy this produces due to the upgrade + Color m_displayColor; ///< for the editor display color + UnsignedInt m_occlusionDelay; ///< delay after object creation before building occlusion is allowed. + NameKeyType m_maxSimultaneousLinkKey; ///< If this is not NAMEKEY_INVALID, it indicates that all the templates which have the same name key should be counted as the same "type" when looking at getMaxSimultaneousOfType(). + + // ---- Short-sized things + UnsignedShort m_templateID; ///< id for net (etc.) transmission purposes + UnsignedShort m_buildCost; ///< money to build (0 == not buildable) + UnsignedShort m_refundValue; ///< custom resale value, if sold. (0 == use default) + UnsignedShort m_threatValue; ///< Threat map info + UnsignedShort m_maxSimultaneousOfType; ///< max simultaneous of this unit we can have (per player) at one time. (0 == unlimited) + + // ---- Bool-sized things + Bool m_maxSimultaneousDeterminedBySuperweaponRestriction; ///< If true, override value in m_maxSimultaneousOfType with value from GameInfo::getSuperweaponRestriction() + Bool m_isPrerequisite; ///< Is this thing considered in a prerequisite for any other thing? + Bool m_isBridge; ///< True if this model is a bridge. + Bool m_isBuildFacility; ///< is this the build facility for something? (calculated based on other template's prereqs) + Bool m_isTrainable; ///< Whether or not I can even gain experience + Bool m_enterGuard; ///< Whether or not I can enter objects when guarding + Bool m_hijackGuard; ///< Whether or not I can hijack objects when guarding + Bool m_isForbidden; ///< useful when overriding in .ini + Bool m_armorCopiedFromDefault; + Bool m_weaponsCopiedFromDefault; + + // ---- Byte-sized things + Byte m_radarPriority; ///< does object appear on radar, and if so at what priority + Byte m_transportSlotCount; ///< how many "slots" we take in a transport (0 == not transportable) + Byte m_buildable; ///< is this thing buildable at all? + Byte m_buildCompletion; ///< how the units come into the world when build is complete + Byte m_editorSorting; ///< editor sorting type, see EditorSortingType enum + Byte m_structureRubbleHeight; + Byte m_shadowType; ///< settings which determine the type of shadow rendered + Byte m_moduleParsingMode; + UnsignedByte m_crusherLevel; ///< crusher > crushable level to actually crush + UnsignedByte m_crushableLevel; ///< Specifies the level of crushability (must be hit by a crusher greater than this to crush me). + Byte m_ammoPipsStyle; ///< How ammo pips are displayed for this thing + +}; + +//----------------------------------------------------------------------------- +// Inlining +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Externals +//----------------------------------------------------------------------------- + +#endif // __THINGTEMPLATE_H_ + diff --git a/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h b/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h index b8355391f1..b0ef11bd8f 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h @@ -89,7 +89,7 @@ class UnicodeString // add a ctor/dtor, 'cuz they won't ever be called. struct UnicodeStringData { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) const WideChar* m_debugptr; // just makes it easier to read in the debugger #endif unsigned short m_refCount; // reference count @@ -99,7 +99,7 @@ class UnicodeString inline WideChar* peek() { return (WideChar*)(this+1); } }; - #ifdef _DEBUG + #ifdef RTS_DEBUG void validate() const; #else inline void validate() const { } diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h b/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h index 8a6df4bd51..b9021df3ea 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Upgrade.h @@ -55,7 +55,7 @@ enum UpgradeStatusType CPP_11(: Int) }; //The maximum number of upgrades. -#define UPGRADE_MAX_COUNT 128 +#define UPGRADE_MAX_COUNT 1024 typedef BitFlags UpgradeMaskType; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/crc.h b/GeneralsMD/Code/GameEngine/Include/Common/crc.h index 9e921993d3..1e06be3276 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/crc.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/crc.h @@ -33,7 +33,7 @@ #include "Lib/BaseType.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG //#include "winsock2.h" // for htonl diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ClientInstance.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ClientInstance.h new file mode 100644 index 0000000000..74e7add404 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ClientInstance.h @@ -0,0 +1,47 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ +#include "Lib/BaseType.h" + +namespace rts +{ + +// TheSuperHackers @feature Adds support for launching multiple game clients and keeping track of their instance id. + +class ClientInstance +{ +public: + // Can be called N times, but is initialized just once. + static bool initialize(); + + static bool isInitialized(); + + // Returns the instance index of this game client. Starts at 0. + static UnsignedInt getInstanceIndex(); + + // Returns the instance id of this game client. Starts at 1. + static UnsignedInt getInstanceId(); + + // Returns the instance name of the first game client. + static const char* getFirstInstanceName(); + +private: + static HANDLE s_mutexHandle; + static UnsignedInt s_instanceIndex; +}; + +} // namespace rts diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h index 10b4e187e1..08938bc3d3 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h @@ -1027,7 +1027,7 @@ class ControlBar : public SubsystemInterface Int m_remainingRadarAttackGlowFrames; GameWindow *m_radarAttackGlowWindow; -#if defined( _INTERNAL ) || defined( _DEBUG ) +#if defined( RTS_INTERNAL ) || defined( RTS_DEBUG ) UnsignedInt m_lastFrameMarkedDirty; UnsignedInt m_consecutiveDirtyFrames; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/DebugDisplay.h b/GeneralsMD/Code/GameEngine/Include/GameClient/DebugDisplay.h index b3930688b2..9d1e61c789 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/DebugDisplay.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/DebugDisplay.h @@ -142,7 +142,7 @@ class DebugDisplay : public DebugDisplayInterface // displayers -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern void AudioDebugDisplay( DebugDisplayInterface *debugDisplay, void *userData, FILE *fp ); #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h index b943339792..92775c7e36 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Display.h @@ -92,7 +92,7 @@ class Display : public SubsystemInterface virtual void setGamma(Real gamma, Real bright, Real contrast, Bool calibrate) {}; virtual Bool testMinSpecRequirements(Bool *videoPassed, Bool *cpuPassed, Bool *memPassed,StaticGameLODLevel *idealVideoLevel=NULL, Real *cpuTime=NULL) {*videoPassed=*cpuPassed=*memPassed=true; return true;} virtual void doSmartAssetPurgeAndPreload(const char* usageFileName) = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void dumpAssetUsage(const char* mapname) = 0; #endif @@ -163,7 +163,7 @@ class Display : public SubsystemInterface virtual void clearShroud() = 0; ///< empty the entire shroud virtual void setBorderShroudLevel(UnsignedByte level) = 0; ///, rts::equal_to > DrawablePtrHash; -typedef DrawablePtrHash::iterator DrawablePtrHashIt; +//typedef std::hash_map, rts::equal_to > DrawablePtrHash; +//typedef DrawablePtrHash::iterator DrawablePtrHashIt; + +typedef std::vector DrawablePtrVector; //----------------------------------------------------------------------------- /** The Client message dispatcher, this is the last "translator" on the message @@ -163,7 +165,8 @@ class GameClient : public SubsystemInterface, UnsignedInt m_frame; ///< Simulation frame number from server Drawable *m_drawableList; ///< All of the drawables in the world - DrawablePtrHash m_drawableHash; ///< Used for DrawableID lookups +// DrawablePtrHash m_drawableHash; ///< Used for DrawableID lookups + DrawablePtrVector m_drawableVector; DrawableID m_nextDrawableID; ///< For allocating drawable id's DrawableID allocDrawableID( void ); ///< Returns a new unique drawable id @@ -238,13 +241,18 @@ inline Drawable* GameClient::findDrawableByID( const DrawableID id ) if( id == INVALID_DRAWABLE_ID ) return NULL; - DrawablePtrHashIt it = m_drawableHash.find(id); - if (it == m_drawableHash.end()) { - // no such drawable - return NULL; - } +// DrawablePtrHashIt it = m_drawableHash.find(id); +// if (it == m_drawableHash.end()) { +// // no such drawable +// return NULL; +// } +// +// return (*it).second; + + if( (size_t)id < m_drawableVector.size() ) + return m_drawableVector[(size_t)id]; - return (*it).second; + return NULL; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h index 6ea74f81b4..c0dba2767d 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/InGameUI.h @@ -593,7 +593,7 @@ friend class Drawable; // for selection/deselection transactions Real durationInSeconds, Real zRisePerSecond ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void DEBUG_addFloatingText(const AsciiString& text,const Coord3D * pos, Color color); #endif @@ -613,7 +613,7 @@ friend class Drawable; // for selection/deselection transactions { MOVE_HINT = 0, ATTACK_HINT, -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_HINT, #endif NUM_HINT_TYPES // keep this one last diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h index 663df919af..58a1279f9b 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h @@ -345,7 +345,8 @@ class ParticleSystemInfo : public Snapshot typedef Int Color; - void tintAllColors( Color tintColor ); + void tintAllColors( Color tintColor); + void tintColorsAllFrames( Color tintColor); GameClientRandomVariable m_colorScale; ///< color coefficient @@ -627,6 +628,13 @@ class ParticleSystem : public MemoryPoolObject, // Access to dynamically changing part of a particle system. void setEmissionVolumeSphereRadius( Real newRadius ) { if (m_emissionVolumeType == SPHERE) m_emissionVolume.sphere.radius = newRadius; } void setEmissionVolumeCylinderRadius( Real newRadius ) { if (m_emissionVolumeType == CYLINDER) m_emissionVolume.cylinder.radius = newRadius; } + void setEmissionBoxHalfSize(Real newX, Real newY, Real newZ) { + if (m_emissionVolumeType == BOX) { + m_emissionVolume.box.halfSize.x = newX; + m_emissionVolume.box.halfSize.y = newY; + m_emissionVolume.box.halfSize.z = newZ; + } + } EmissionVolumeType getEmisionVolumeType() const { return m_emissionVolumeType; } ParticlePriorityType getPriority() const { return m_priority; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h b/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h index 526f1a2d15..3970cf3bc3 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h @@ -74,7 +74,7 @@ class SelectionTranslator : public GameMessageTranslator void setDragSelecting(Bool dragSelect); void setLeftMouseButton(Bool state); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) Bool m_HandOfGodSelectionMode; Bool isHandOfGodSelectionMode( void) { return m_HandOfGodSelectionMode; }; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Shadow.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Shadow.h index f2be765967..75c42c21af 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Shadow.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Shadow.h @@ -116,7 +116,7 @@ class Shadow }; - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void getRenderCost(RenderCost & rc) const = 0; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/TintStatus.h b/GeneralsMD/Code/GameEngine/Include/GameClient/TintStatus.h new file mode 100644 index 0000000000..7d84c4b578 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/TintStatus.h @@ -0,0 +1,50 @@ + +#pragma once +#ifndef __TINTSTATUS_H__ +#define __TINTSTATUS_H__ + +// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// +#include "Lib/BaseType.h" +#include "Common/BitFlags.h" +#include "Common/BitFlagsIO.h" + +// Tint status types can now be used via ini; +// Sync with TintStatusFlags::s_bitNameList[] in Drawable.cpp +enum TintStatus CPP_11(: Int) +{ + TINT_STATUS_INVALID = 0, + + TINT_STATUS_DISABLED = 1,///< drawable tint color is deathly dark grey + TINT_STATUS_IRRADIATED, ///< drawable tint color is sickly green + TINT_STATUS_POISONED, ///< drawable tint color is open-sore red + TINT_STATUS_GAINING_SUBDUAL_DAMAGE, ///< When gaining subdual damage, we tint SUBDUAL_DAMAGE_COLOR + TINT_STATUS_FRENZY, ///< When frenzied, we tint FRENZY_COLOR + // New generic entries: + TINT_STATUS_SHIELDED, ///< When shielded, we tint SHIELDED_COLOR + TINT_STATUS_DEMORALIZED, + TINT_STATUS_BOOST, + TINT_STATUS_EXTRA1, + TINT_STATUS_EXTRA2, + TINT_STATUS_EXTRA3, + TINT_STATUS_EXTRA4, + TINT_STATUS_EXTRA5, + TINT_STATUS_EXTRA6, + TINT_STATUS_EXTRA7, + TINT_STATUS_EXTRA8, + + TINT_STATUS_COUNT // Keep this last +}; + +//------------------- +struct DrawableColorTint +{ + RGBColor color; + RGBColor colorInfantry; + UnsignedInt attackFrames; + UnsignedInt decayFrames; +}; + +typedef BitFlags TintStatusFlags; + +// -------- +#endif /* __TINTSTATUS_H__ */ \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h index 339a00ae84..45207ed6ec 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h +++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Water.h @@ -100,9 +100,9 @@ class WaterTransparencySetting : public Overridable m_standingWaterColor.red = 1.0f; m_standingWaterColor.green = 1.0f; m_standingWaterColor.blue = 1.0f; - m_radarColor.red = 140; - m_radarColor.green = 140; - m_radarColor.blue = 255; + m_radarColor.red = 0.55f; + m_radarColor.green = 0.55f; + m_radarColor.blue = 1.0f; m_standingWaterTexture = "TWWater01.tga"; m_additiveBlend = FALSE; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h index c8cb0c8b01..d16d6b0019 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h @@ -336,7 +336,9 @@ static const char *TheCommandSourceMaskNames[] = "FROM_AI", "FROM_DOZER", //don't use this "DEFAULT_SWITCH_WEAPON", //unit will pick this weapon when normal logic fails. - + "SYNC_TO_PRIMARY", //This weapon will be fired whenever PRIMARY is fired + "SYNC_TO_SECONDARY", //This weapon will be fired whenever SECONDARY is fired + "SYNC_TO_TERTIARY", //This weapon will be fired whenever TERTIARY is fired NULL }; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h index 8b783d943d..44d275df88 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h @@ -410,7 +410,7 @@ class PathfindLayer Bool connectsZones(PathfindZoneManager *zm, const LocomotorSet& locomotorSet,Int zone1, Int zone2); Bool isPointOnWall(ObjectID *wallPieces, Int numPieces, const Coord3D *pt); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void doDebugIcons(void) ; #endif protected: @@ -827,7 +827,7 @@ class Pathfinder : PathfindServicesInterface, public Snapshot void checkChangeLayers(PathfindCell *parentCell); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void doDebugIcons(void) ; #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h index c8183eb689..60ba43a5eb 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Armor.h @@ -54,6 +54,8 @@ class ArmorTemplate void clear(); + void copyFrom(const ArmorTemplate* other); + /** This is the real "meat" of the class: given a damage type and amount, adjust the damage and return the amount that should be dealt. @@ -119,6 +121,7 @@ class ArmorStore : public SubsystemInterface } static void parseArmorDefinition(INI* ini); + static void parseArmorExtendDefinition(INI* ini); private: diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h index 54cded619b..32c7715b2c 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ArmorSet.h @@ -53,7 +53,10 @@ enum ArmorSetType CPP_11(: Int) ARMORSET_WEAK_VERSUS_BASEDEFENSES = 4, ARMORSET_SECOND_LIFE = 5, ///< Body Module has marked us as on our second life ARMORSET_CRATE_UPGRADE_ONE, ///< Just like weaponset type from salvage. - ARMORSET_CRATE_UPGRADE_TWO, + ARMORSET_CRATE_UPGRADE_TWO, + ARMORSET_PLAYER_UPGRADE2, + ARMORSET_PLAYER_UPGRADE3, + ARMORSET_PLAYER_UPGRADE4, ARMORSET_COUNT ///< keep last, please }; @@ -87,7 +90,7 @@ class ArmorTemplateSet inline Int getConditionsYesCount() const { return 1; } inline const ArmorSetFlags& getNthConditionsYes(Int i) const { return m_types; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h index 8e3a91003c..4bdd735da2 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ExperienceTracker.h @@ -60,7 +60,9 @@ class ExperienceTracker : public MemoryPoolObject, public Snapshot void setExperienceSink( ObjectID sink ); ///< My experience actually goes to this person (loose couple) Real getExperienceScalar() const { return m_experienceScalar; } + Real getExperienceValueScalar() const { return m_experienceValueScalar; } void setExperienceScalar( Real scalar ) { m_experienceScalar = scalar; } + void setExperienceValueScalar( Real scalar ) { m_experienceValueScalar = scalar; } // --------------- inherited from Snapshot interface -------------- void crc( Xfer *xfer ); @@ -73,6 +75,7 @@ class ExperienceTracker : public MemoryPoolObject, public Snapshot Int m_currentExperience; ///< Number of experience points ObjectID m_experienceSink; ///< ID of object I have pledged my experience point gains to Real m_experienceScalar; ///< Scales any experience gained by this multiplier. + Real m_experienceValueScalar; ///< Scales any experience given by this multiplier. }; #endif \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h index 4e80926166..88be3a9a91 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h @@ -92,9 +92,10 @@ enum /// Function pointers for use by GameLogic callback functions. typedef void (*GameLogicFuncPtr)( Object *obj, void *userData ); -typedef std::hash_map, rts::equal_to > ObjectPtrHash; -typedef ObjectPtrHash::const_iterator ObjectPtrIter; +//typedef std::hash_map, rts::equal_to > ObjectPtrHash; +//typedef ObjectPtrHash::const_iterator ObjectPtrIter; +typedef std::vector ObjectPtrVector; // ------------------------------------------------------------------------------------------------ /** @@ -113,7 +114,7 @@ class GameLogic : public SubsystemInterface, public Snapshot virtual void reset( void ); ///< Reset the logic system virtual void update( void ); ///< update the world -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int getNumberSleepyUpdates() const {return m_sleepyUpdates.size();} //For profiling, so not in Release. #endif void processCommandList( CommandList *list ); ///< process the command list @@ -319,7 +320,8 @@ class GameLogic : public SubsystemInterface, public Snapshot WindowLayout *m_background; Object* m_objList; ///< All of the objects in the world. - ObjectPtrHash m_objHash; ///< Used for ObjectID lookups +// ObjectPtrHash m_objHash; ///< Used for ObjectID lookups + ObjectPtrVector m_objVector; // this is a vector, but is maintained as a priority queue. // never modify it directly; please use the proper access methods. @@ -410,11 +412,15 @@ inline Object* GameLogic::findObjectByID( ObjectID id ) if( id == INVALID_ID ) return NULL; - ObjectPtrHash::iterator it = m_objHash.find(id); - if (it == m_objHash.end()) - return NULL; +// ObjectPtrHash::iterator it = m_objHash.find(id); +// if (it == m_objHash.end()) +// return NULL; +// +// return (*it).second; + if( (size_t)id < m_objVector.size() ) + return m_objVector[(size_t)id]; - return (*it).second; + return NULL; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h index 63c01defa5..791bece902 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h @@ -201,6 +201,9 @@ class AIUpdateModuleData : public UpdateModuleData #ifdef ALLOW_SURRENDER UnsignedInt m_surrenderDuration; ///< when we surrender, how long we stay surrendered. #endif + Real m_attackAngle; + Bool m_useAttackAngle; + Bool m_attackAngleMirrored; AIUpdateModuleData(); @@ -214,6 +217,7 @@ class AIUpdateModuleData : public UpdateModuleData private: static void parseTurret( INI* ini, void *instance, void *store, const void* /*userData*/ ); + static void parseAttackAngle( INI* ini, void *instance, void *store, const void* /*userData*/ ); }; @@ -332,6 +336,10 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface Bool areTurretsLinked() const { return getAIUpdateModuleData()->m_turretsLinked; } + Real getAttackAngle() const { return getAIUpdateModuleData()->m_attackAngle; } + Bool useAttackAngle() const { return getAIUpdateModuleData()->m_useAttackAngle; } + Bool isAttackAngleMirrored() const { return getAIUpdateModuleData()->m_attackAngleMirrored; } + // this is present solely for some transports to override, so that they can land before // allowing people to exit... virtual AIFreeToExitType getAiFreeToExit(const Object* exiter) const { return FREE_TO_EXIT; } @@ -438,6 +446,11 @@ class AIUpdateInterface : public UpdateModule, public AICommandInterface Bool isWeaponSlotOnTurretAndAimingAtTarget(WeaponSlotType wslot, const Object* victim) const; Bool getTurretRotAndPitch(WhichTurretType tur, Real* turretAngle, Real* turretPitch) const; Real getTurretTurnRate(WhichTurretType tur) const; + + Real getMinTurretAngle(WhichTurretType tur) const; + Real getMaxTurretAngle(WhichTurretType tur) const; + Bool hasLimitedTurretAngle(WhichTurretType tur) const; + void setTurretTargetObject(WhichTurretType tur, Object* o, Bool isForceAttacking = FALSE); Object *getTurretTargetObject( WhichTurretType tur, Bool clearDeadTargets = TRUE ); void setTurretTargetPosition(WhichTurretType tur, const Coord3D* pos); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ActiveBody.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ActiveBody.h index 7fff08ac75..ecfa264ae2 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ActiveBody.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ActiveBody.h @@ -128,6 +128,8 @@ class ActiveBody : public BodyModule virtual Bool canBeSubdued() const; virtual void onSubdualChange( Bool isNowSubdued );///< Override this if you want a totally different effect than DISABLED_SUBDUED + virtual void overrideDamageFX(DamageFX* damageFX); + protected: void validateArmorAndDamageFX() const; @@ -162,6 +164,7 @@ class ActiveBody : public BodyModule Bool m_backCrushed; Bool m_lastDamageCleared; Bool m_indestructible; ///< is this object indestructible? + Bool m_damageFXOverride; BodyParticleSystem *m_particleSystems; ///< particle systems created and attached to this object diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorDamageScalarUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorDamageScalarUpdate.h new file mode 100644 index 0000000000..3c5ada3d91 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorDamageScalarUpdate.h @@ -0,0 +1,133 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ArmorDamageScalarUpdate.h ///////////////////////////////////////////////// +//----------------------------------------------------------------------------- +// +// Electronic Arts Pacific. +// +// Confidential Information +// Copyright (C) 2002-2003 - All Rights Reserved +// +//----------------------------------------------------------------------------- +// +// created: March 2025 +// +// Filename: ArmorDamageScalarUpdate.h +// +// author: Andi W +// +// purpose: Apply a temporary multiplier to damage taken to units in an area +// +//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __ARMOR_DAMAGE_SCALAR_UPDATE_H_ +#define __ARMOR_DAMAGE_SCALAR_UPDATE_H_ + +//----------------------------------------------------------------------------- +// SYSTEM INCLUDES //////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// USER INCLUDES ////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +#include "GameLogic/Module/UpdateModule.h" +//----------------------------------------------------------------------------- +// FORWARD REFERENCES ///////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +// enum WeaponBonusConditionType; +class DamageFX; +enum TintStatus CPP_11(: Int); + +//----------------------------------------------------------------------------- +// TYPE DEFINES /////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +class ArmorDamageScalarUpdateModuleData : public UpdateModuleData +{ +public: + + ArmorDamageScalarUpdateModuleData(); + + KindOfMaskType m_allowAffectKindOf; ///< Must be set on target + KindOfMaskType m_forbiddenAffectKindOf; ///< Must be clear on target + Int m_targetsMask; ///< ALLIES, ENEMIES or NEUTRALS + Bool m_isAffectAirborne; ///< Affect Airborne targets + UnsignedInt m_bonusDuration; ///< How long a hit lasts on target + UnsignedInt m_initialDelay; ///< Delay before effect + Real m_bonusRange; ///< How far to affect + Real m_armorDamageScalar; ///< damage (i.e. armor) scalar effect magnitude 1.0 = full damage; < 1.0 = less damage; > 1.0 = more damage + DamageFX* m_damageFx; ///< override the objects damageFX during effect + const ParticleSystemTemplate* m_effectParticleSystem; ///< particles attached to random points of the object + Bool m_scaleParticleCount; ///< scales emission rate of attached particle based on object's size + TintStatus m_tintStatus; ///< tint color to apply + + //Bool m_applyTint; ///< apply SHIELDED color tint on objects + // Real m_sparksPerCubicFoot; ///< just like it sounds + static void buildFieldParse(MultiIniFieldParse& p); +}; + + +//------------------------------------------------------------------------------------------------- +class ArmorDamageScalarUpdate : public UpdateModule +{ + + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ArmorDamageScalarUpdate, "ArmorDamageScalarUpdate" ) + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA(ArmorDamageScalarUpdate, ArmorDamageScalarUpdateModuleData ) + +public: + + ArmorDamageScalarUpdate( Thing *thing, const ModuleData* moduleData ); + // virtual destructor prototype provided by memory pool declaration + + UnsignedInt getDieFrame() { return m_dieFrame; } + + virtual UpdateSleepTime update( void ); + void applyEffect(void); + void removeEffect(void); + + void applyEffectToObject(Object* obj); + void removeEffectFromObject(Object* obj); + + +protected: + + ObjectIDVector m_affectedObjects; + UnsignedInt m_dieFrame; + + Bool m_effectApplied; +}; + + +//----------------------------------------------------------------------------- +// INLINING /////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// EXTERNALS ////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +#endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorUpgrade.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorUpgrade.h index 3accb88943..a62a3244c6 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorUpgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ArmorUpgrade.h @@ -56,21 +56,36 @@ // USER INCLUDES ////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "GameLogic/Module/UpgradeModule.h" +#include "GameLogic/ArmorSet.h" //----------------------------------------------------------------------------- // FORWARD REFERENCES ///////////////////////////////////////////////////////// //----------------------------------------------------------------------------- class Thing; +enum ArmorSetType CPP_11(: Int); -//----------------------------------------------------------------------------- -// TYPE DEFINES /////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +class ArmorUpgradeModuleData : public UpgradeModuleData +{ + +public: + ArmorUpgradeModuleData(void); + + static void buildFieldParse(MultiIniFieldParse& p); + + ArmorSetType m_armorSetFlag; ///< The weaponset flag to set (default = WEAPONSET_PLAYER_UPGRADE) + ArmorSetFlags m_armorSetFlagsToClear; ///< The weaponset flags to clear. This is needed if we want to disable a previous upgrade. + //Bool m_needsParkedAircraft; ///< Aircraft attempting this upgrade needs to be stationary in hangar + +}; +//------------------------------------------------------------------------------------------------- class ArmorUpgrade : public UpgradeModule { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( ArmorUpgrade, "ArmorUpgrade" ) - MAKE_STANDARD_MODULE_MACRO( ArmorUpgrade ); + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( ArmorUpgrade, ArmorUpgradeModuleData); public: diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BodyModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BodyModule.h index 8bf0dbca1a..4493e55148 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BodyModule.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BodyModule.h @@ -180,6 +180,7 @@ class BodyModuleInterface virtual void applyDamageScalar( Real scalar ) = 0; virtual Real getDamageScalar() const = 0; + virtual void overrideDamageFX(DamageFX* damageFX) = 0; /** Change the module's health by the given delta. Note that @@ -279,6 +280,7 @@ class BodyModule : public BehaviorModule, public BodyModuleInterface //Allows outside systems to apply defensive bonuses or penalties (they all stack as a multiplier!) virtual void applyDamageScalar( Real scalar ) { m_damageScalar *= scalar; } virtual Real getDamageScalar() const { return m_damageScalar; } + virtual void overrideDamageFX(DamageFX* damageFX) { } /** Change the module's health by the given delta. Note that diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h index 693a699b2a..88998889e7 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/DumbProjectileBehavior.h @@ -97,6 +97,8 @@ class DumbProjectileBehavior : public UpdateModule, public ProjectileUpdateInter virtual ObjectID projectileGetLauncherID() const { return m_launcherID; } virtual void setFramesTillCountermeasureDiversionOccurs( UnsignedInt frames ) {} virtual void projectileNowJammed() {} + virtual Object* getTargetObject(); + virtual const Coord3D* getTargetPosition(); protected: @@ -120,7 +122,7 @@ class DumbProjectileBehavior : public UpdateModule, public ProjectileUpdateInter Bool m_hasDetonated; ///< Bool calcFlightPath(Bool recalcNumSegments); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void displayFlightPath(); ///< Uses little debug icons in worldspace to show the path chosen when it is decided upon #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ExperienceScalarUpgrade.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ExperienceScalarUpgrade.h index c661dc477f..945677ef27 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ExperienceScalarUpgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ExperienceScalarUpgrade.h @@ -49,7 +49,8 @@ class ExperienceScalarUpgradeModuleData: public UpgradeModuleData static void buildFieldParse(MultiIniFieldParse& p); - Real m_addXPScalar; + Real m_addXPScalar; ///< Additive bonus to scalar for XP this unit gains + Real m_addXPValueScalar; ///< Additive bonus to scalar for XP this unit gives when killed }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h index 027187275e..19fedcdbe6 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/JetAIUpdate.h @@ -35,7 +35,7 @@ #include "GameLogic/AIStateMachine.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -134,6 +134,7 @@ class JetAIUpdate : public AIUpdateInterface void friend_addWaypointToGoalPath( const Coord3D &pos ); AICommandType friend_getPendingCommandType() const; void friend_purgePendingCommand(); + Bool isParkedInHangar() const; protected: diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LaserUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LaserUpdate.h index 8e08e1d1e0..0baefd6e04 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LaserUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LaserUpdate.h @@ -52,6 +52,14 @@ class LaserUpdateModuleData : public ClientUpdateModuleData Real m_punchThroughScalar; ///< If non-zero, length modifier when we used to have a target object and now don't + UnsignedInt m_fadeInDurationFrames; ///< If non-zero, beam fades in over duration + UnsignedInt m_fadeOutDurationFrames; ///< If non-zero, beam fades out over duration (tries to get time from lifetimeUpdate) + UnsignedInt m_widenDurationFrames; ///< If non-zero, beam grows to max size over duration + UnsignedInt m_decayDurationFrames; ///< If non-zero, beam shrinks over duration (tries to get time from lifetimeUpdate) + + Bool m_hasMultiDraw; ///< Enable this to support tracking multiple LaserDraw modules + Bool m_useHouseColor; ///< Enable this to color particles with house color + LaserUpdateModuleData(); static void buildFieldParse(MultiIniFieldParse& p); @@ -84,9 +92,16 @@ class LaserUpdate : public ClientUpdateModule Real getCurrentLaserRadius() const; void setDirty( Bool dirty ) { m_dirty = dirty; } - Bool isDirty() { return m_dirty; } + Bool isDirty() { return m_dirty || getLaserUpdateModuleData()->m_hasMultiDraw; } Real getWidthScale() const { return m_currentWidthScalar; } + Real getAlphaScale() const { return m_currentAlphaScalar; } + + Real getLifeTimeProgress() const; + + Int getPlayerColor() const { return m_hexColor; }; + + void updateContinuousLaser(const Object* parent, const Object* target, const Coord3D* startPos, const Coord3D* endPos); virtual void clientUpdate(); @@ -102,6 +117,9 @@ class LaserUpdate : public ClientUpdateModule DrawableID m_parentID; DrawableID m_targetID; + UnsignedInt m_startFrame; ///< the frame this laser is initialized + UnsignedInt m_dieFrame; ///< the frame this laser is scheduled to die + Bool m_dirty; ParticleSystemID m_particleSystemID; ParticleSystemID m_targetParticleSystemID; @@ -112,7 +130,20 @@ class LaserUpdate : public ClientUpdateModule Real m_currentWidthScalar; UnsignedInt m_decayStartFrame; UnsignedInt m_decayFinishFrame; + + Bool m_fadingIn; + Bool m_fadingOut; + UnsignedInt m_fadeInStartFrame; + UnsignedInt m_fadeInFinishFrame; + Real m_currentAlphaScalar; + UnsignedInt m_fadeOutStartFrame; + UnsignedInt m_fadeOutFinishFrame; + AsciiString m_parentBoneName; + + Int m_hexColor; + + // Bool m_isMultiDraw; }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LifetimeUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LifetimeUpdate.h index 302144f4e8..014a1fbd93 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LifetimeUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LifetimeUpdate.h @@ -75,6 +75,7 @@ class LifetimeUpdate : public UpdateModule // virtual destructor prototype provided by memory pool declaration void setLifetimeRange( UnsignedInt minFrames, UnsignedInt maxFrames ); + void resetLifetime(void); UnsignedInt getDieFrame() const { return m_dieFrame; } virtual UpdateSleepTime update( void ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LocomotorSetUpgrade.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LocomotorSetUpgrade.h index 7c46d12623..a093521ffd 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LocomotorSetUpgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/LocomotorSetUpgrade.h @@ -38,14 +38,24 @@ // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class Thing; -//------------------------------------------------------------------------------------------------- -/** The default die module */ +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +class LocomotorSetUpgradeModuleData : public UpgradeModuleData +{ +public: + + LocomotorSetUpgradeModuleData(void); + + static void buildFieldParse(MultiIniFieldParse& p); + + Bool m_setUpgraded; ///< Enable or Disable upgraded locomotor + //Bool m_needsParkedAircraft; ///< Aircraft attempting this upgrade needs to be stationary in hangar +}; //------------------------------------------------------------------------------------------------- class LocomotorSetUpgrade : public UpgradeModule { - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( LocomotorSetUpgrade, "LocomotorSetUpgrade" ) - MAKE_STANDARD_MODULE_MACRO( LocomotorSetUpgrade ); + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(LocomotorSetUpgrade, "LocomotorSetUpgrade") + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( LocomotorSetUpgrade, LocomotorSetUpgradeModuleData); public: diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MaxHealthUpgrade.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MaxHealthUpgrade.h index c3aebfc167..df080a0de9 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MaxHealthUpgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MaxHealthUpgrade.h @@ -51,6 +51,7 @@ class MaxHealthUpgradeModuleData: public UpgradeModuleData static void buildFieldParse(MultiIniFieldParse& p); Real m_addMaxHealth; + Real m_multiplyMaxHealth; MaxHealthChangeType m_maxHealthChangeType; }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MissileAIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MissileAIUpdate.h index b9bbab54f1..703ce7d1c7 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MissileAIUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/MissileAIUpdate.h @@ -99,6 +99,8 @@ class MissileAIUpdate : public AIUpdateInterface, public ProjectileUpdateInterfa virtual ObjectID projectileGetLauncherID() const { return m_launcherID; } virtual void setFramesTillCountermeasureDiversionOccurs( UnsignedInt frames ); ///< Number of frames till missile diverts to countermeasures. virtual void projectileNowJammed();///< We lose our Object target and scatter to the ground + virtual Object* getTargetObject(); + virtual const Coord3D* getTargetPosition(); virtual Bool processCollision(PhysicsBehavior *physics, Object *other); ///< Returns true if the physics collide should apply the force. Normally not. jba. diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/NeutronMissileUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/NeutronMissileUpdate.h index d3a05b3f00..2d27dbd170 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/NeutronMissileUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/NeutronMissileUpdate.h @@ -106,6 +106,8 @@ class NeutronMissileUpdate : public UpdateModule, virtual const Coord3D *getVelocity() const { return &m_vel; } ///< get current velocity virtual void setFramesTillCountermeasureDiversionOccurs( UnsignedInt frames ) {} virtual void projectileNowJammed() {} + virtual Object* getTargetObject() { return NULL; } + virtual const Coord3D* getTargetPosition(); virtual UpdateSleepTime update(); virtual void onDelete( void ); diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h index 3e3ba8dbd1..cd0fac556b 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/OpenContain.h @@ -42,6 +42,7 @@ #include "GameLogic/Module/UpdateModule.h" #include "GameLogic/Module/DieModule.h" #include "GameLogic/Module/DamageModule.h" +#include "GameLogic/Weapon.h" #include "Common/AudioEventRTS.h" #include "Common/KindOf.h" #include "Common/GameMemory.h" @@ -73,6 +74,8 @@ class OpenContainModuleData : public UpdateModuleData Bool m_allowEnemiesInside; ///< allow enemies inside us Bool m_allowNeutralInside; ///< allow neutral inside us + WeaponBonusConditionTypeVec m_passengerWeaponBonusVec; ///< weaponBonus types granted to passengers + OpenContainModuleData( void ); static void buildFieldParse(MultiIniFieldParse& p); }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h index 766dfba459..4210847940 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h @@ -66,6 +66,7 @@ class PhysicsBehaviorModuleData : public UpdateModuleData Real m_minFallSpeedForDamage; Real m_fallHeightDamageFactor; Real m_pitchRollYawFactor; + Bool m_vehicleCrashAllowAirborne; const WeaponTemplate* m_vehicleCrashesIntoBuildingWeaponTemplate; const WeaponTemplate* m_vehicleCrashesIntoNonBuildingWeaponTemplate; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionTimeModifierUpgrade.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionTimeModifierUpgrade.h new file mode 100644 index 0000000000..594487fe40 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionTimeModifierUpgrade.h @@ -0,0 +1,119 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ProductionTimeModifierUpgrade.h /////////////////////////////////////// +//----------------------------------------------------------------------------- +// +// Electronic Arts Pacific. +// +// Confidential Information +// Copyright (C) 2002 - All Rights Reserved +// +//----------------------------------------------------------------------------- +// +// created: March 2025 +// +// Filename: ProductionTimeModifierUpgrade.h +// +// author: Andi W +// +// purpose: +// +//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __PRODUCTION_TIME_MODIFIER_UPGRADE_H_ +#define __PRODUCTION_TIME_MODIFIER_UPGRADE_H_ + +//----------------------------------------------------------------------------- +// SYSTEM INCLUDES //////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// USER INCLUDES ////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +#include "GameLogic/Module/UpgradeModule.h" +#include "Common/KindOf.h" +//----------------------------------------------------------------------------- +// FORWARD REFERENCES ///////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +class Thing; +class Player; + +//----------------------------------------------------------------------------- +// TYPE DEFINES /////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// INLINING /////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// EXTERNALS ////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +class ProductionTimeModifierUpgradeModuleData : public UpgradeModuleData +{ + +public: + + ProductionTimeModifierUpgradeModuleData( void ); + + static void buildFieldParse(MultiIniFieldParse& p); + + Real m_percentage; + KindOfMaskType m_kindOf; +}; + +//------------------------------------------------------------------------------------------------- +/** The OCL upgrade module */ +//------------------------------------------------------------------------------------------------- +class ProductionTimeModifierUpgrade : public UpgradeModule +{ + + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( ProductionTimeModifierUpgrade, "ProductionTimeModifierUpgrade" ) + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( ProductionTimeModifierUpgrade, ProductionTimeModifierUpgradeModuleData ); + +public: + + ProductionTimeModifierUpgrade( Thing *thing, const ModuleData* moduleData ); + // virtual destructor prototype defined by MemoryPoolObject + + virtual void onDelete( void ); ///< we have some work to do when this module goes away + virtual void onCapture( Player *oldOwner, Player *newOwner ); + +protected: + + virtual void upgradeImplementation( void ); ///< Here's the actual work of Upgrading + virtual Bool isSubObjectsUpgrade() { return false; } + +}; + +#endif // __PRODUCTION_TIME_MODIFIER_UPGRADE_H_ diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ScatterShotUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ScatterShotUpdate.h new file mode 100644 index 0000000000..4a93bf2986 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ScatterShotUpdate.h @@ -0,0 +1,113 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ScatterShotUpdate.h ////////////////////////////////////////////////////////////////////// +// Author: Andi W, April 2025 +// Desc: Projectile Scatter/Airburst module +/////////////////////////////////////////////////////////////////////////////////////////////////// +#pragma once + +#ifndef __SCATTER_SHOT_UPDATE_H_ +#define __SCATTER_SHOT_UPDATE_H_ + +// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// +#include "GameLogic/Module/UpdateModule.h" +#include "GameLogic/Object.h" +#include "GameLogic/Weapon.h" + +class FXList; +enum DeathType; + +//------------------------------------------------------------------------------------------------- +class ScatterShotUpdateModuleData : public UpdateModuleData +{ +public: + const WeaponTemplate* m_weaponTemplate; + UnsignedInt m_numShots; + Real m_targetSearchRadius; + Real m_targetMinRadius; + UnsignedInt m_maxShotsPerTarget; + Bool m_preferSimilarTargets; + Bool m_preferNearestTargets; + Real m_noTargetsScatterRadius; + Bool m_attackGroundWhenNoTargets; + + Real m_triggerDistanceToTarget; + Real m_triggerDistanceFromSource; + Real m_triggerDistancePercent; + UnsignedInt m_triggerLifetime; + Bool m_triggerOnImpact; + Bool m_triggerInstantly; + + Bool m_stayAliveAfterTrigger; + + DeathType m_triggerDeathType; + const FXList* m_scatterFX; + + + ScatterShotUpdateModuleData(); + + static void buildFieldParse(MultiIniFieldParse& p); + +private: + +}; + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +class ScatterShotUpdate : public UpdateModule +{ + + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ScatterShotUpdate, "ScatterShotUpdate") + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA(ScatterShotUpdate, ScatterShotUpdateModuleData) + +public: + + ScatterShotUpdate(Thing* thing, const ModuleData* moduleData); + // virtual destructor prototype provided by memory pool declaration + + virtual UpdateSleepTime update(); + +protected: + + Weapon* m_weapon; + UnsignedInt m_initialDelayFrame; + Bool m_hasTriggered; + Bool m_isInitialized; // are goal pos/obj set + + Coord3D m_goalPos; + Object* m_goalObj; + + Real m_totalTargetDistance; + + void triggerScatterShot(void); + Bool isValidTarget(const Object* victim) const; + +private: + Real getTargetDistance() const; + +}; + +#endif + diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TempWeaponBonusHelper.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TempWeaponBonusHelper.h index a9c62421df..fc9750ad3c 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TempWeaponBonusHelper.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/TempWeaponBonusHelper.h @@ -1,72 +1,75 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: TempWeaponBonusHelper.h //////////////////////////////////////////////////////////////////////// -// Author: Graham Smallwood, June 2003 -// Desc: Object helper - Clears Temporary weapon bonus effects -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __TempWeaponBonusHelper_H_ -#define __TempWeaponBonusHelper_H_ - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "GameLogic/Module/ObjectHelper.h" - -enum WeaponBonusConditionType CPP_11(: Int); - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -class TempWeaponBonusHelperModuleData : public ModuleData -{ - -}; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -class TempWeaponBonusHelper : public ObjectHelper -{ - - MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( TempWeaponBonusHelper, TempWeaponBonusHelperModuleData ) - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(TempWeaponBonusHelper, "TempWeaponBonusHelper" ) - -public: - - TempWeaponBonusHelper( Thing *thing, const ModuleData *modData ); - // virtual destructor prototype provided by memory pool object - - virtual DisabledMaskType getDisabledTypesToProcess() const { return DISABLEDMASK_ALL; } - virtual UpdateSleepTime update(); - - void doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration ); - -protected: - WeaponBonusConditionType m_currentBonus; - UnsignedInt m_frameToRemove; - void clearTempWeaponBonus(); -}; - - -#endif // end __TempWeaponBonusHelper_H_ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: TempWeaponBonusHelper.h //////////////////////////////////////////////////////////////////////// +// Author: Graham Smallwood, June 2003 +// Desc: Object helper - Clears Temporary weapon bonus effects +/////////////////////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __TempWeaponBonusHelper_H_ +#define __TempWeaponBonusHelper_H_ + +// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// +#include "GameLogic/Module/ObjectHelper.h" +#include "GameClient/TintStatus.h" + +enum WeaponBonusConditionType CPP_11(: Int); +// enum TintStatus CPP_11(: Int); + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +class TempWeaponBonusHelperModuleData : public ModuleData +{ + +}; + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +class TempWeaponBonusHelper : public ObjectHelper +{ + + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( TempWeaponBonusHelper, TempWeaponBonusHelperModuleData ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(TempWeaponBonusHelper, "TempWeaponBonusHelper" ) + +public: + + TempWeaponBonusHelper( Thing *thing, const ModuleData *modData ); + // virtual destructor prototype provided by memory pool object + + virtual DisabledMaskType getDisabledTypesToProcess() const { return DISABLEDMASK_ALL; } + virtual UpdateSleepTime update(); + + void doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration, TintStatus tintStatus = TINT_STATUS_INVALID); + +protected: + WeaponBonusConditionType m_currentBonus; + TintStatus m_currentTint; + UnsignedInt m_frameToRemove; + void clearTempWeaponBonus(); +}; + + +#endif // end __TempWeaponBonusHelper_H_ diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h index 47d05a00ba..fc9a42c90f 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/UpdateModule.h @@ -269,6 +269,9 @@ class ProjectileUpdateInterface virtual Bool projectileHandleCollision(Object *other) = 0; virtual void setFramesTillCountermeasureDiversionOccurs( UnsignedInt frames ) = 0; ///< Number of frames till missile diverts to countermeasures. virtual void projectileNowJammed() = 0; + + virtual Object* getTargetObject() = 0; + virtual const Coord3D* getTargetPosition() = 0; }; //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponBonusUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponBonusUpdate.h index bb535c97fb..4e96ce9677 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponBonusUpdate.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponBonusUpdate.h @@ -1,112 +1,115 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: WeaponBonusUpdate.h ///////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Electronic Arts Pacific. -// -// Confidential Information -// Copyright (C) 2002-2003 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// created: July 2003 -// -// Filename: WeaponBonusUpdate.cpp -// -// author: Graham Smallwood -// -// purpose: Like healing in that it can affect just me or people around, -// except this gives a Weapon Bonus instead of health -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#ifndef __WEAPON_BONUS_UPDATE_H_ -#define __WEAPON_BONUS_UPDATE_H_ - -//----------------------------------------------------------------------------- -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// USER INCLUDES ////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -#include "GameLogic/Module/UpdateModule.h" -//----------------------------------------------------------------------------- -// FORWARD REFERENCES ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -enum WeaponBonusConditionType CPP_11(: Int); - -//----------------------------------------------------------------------------- -// TYPE DEFINES /////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -class WeaponBonusUpdateModuleData : public UpdateModuleData -{ -public: - - WeaponBonusUpdateModuleData(); - - KindOfMaskType m_requiredAffectKindOf; ///< Must be set on target - KindOfMaskType m_forbiddenAffectKindOf; ///< Must be clear on target - UnsignedInt m_bonusDuration; ///< How long a hit lasts on target - UnsignedInt m_bonusDelay; ///< How often to pulse - Real m_bonusRange; ///< How far to affect - WeaponBonusConditionType m_bonusConditionType; ///< Status to give - - static void buildFieldParse(MultiIniFieldParse& p); -}; - - -//------------------------------------------------------------------------------------------------- -class WeaponBonusUpdate : public UpdateModule -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( WeaponBonusUpdate, "WeaponBonusUpdate" ) - MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( WeaponBonusUpdate, WeaponBonusUpdateModuleData ) - -public: - - WeaponBonusUpdate( Thing *thing, const ModuleData* moduleData ); - // virtual destructor prototype provided by memory pool declaration - - virtual UpdateSleepTime update( void ); - -protected: - -}; - - -//----------------------------------------------------------------------------- -// INLINING /////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// EXTERNALS ////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -#endif +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: WeaponBonusUpdate.h ///////////////////////////////////////////////// +//----------------------------------------------------------------------------- +// +// Electronic Arts Pacific. +// +// Confidential Information +// Copyright (C) 2002-2003 - All Rights Reserved +// +//----------------------------------------------------------------------------- +// +// created: July 2003 +// +// Filename: WeaponBonusUpdate.cpp +// +// author: Graham Smallwood +// +// purpose: Like healing in that it can affect just me or people around, +// except this gives a Weapon Bonus instead of health +// +//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __WEAPON_BONUS_UPDATE_H_ +#define __WEAPON_BONUS_UPDATE_H_ + +//----------------------------------------------------------------------------- +// SYSTEM INCLUDES //////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// USER INCLUDES ////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +#include "GameLogic/Module/UpdateModule.h" + +//----------------------------------------------------------------------------- +// FORWARD REFERENCES ///////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +enum WeaponBonusConditionType CPP_11(: Int); +enum TintStatus CPP_11(: Int); + +//----------------------------------------------------------------------------- +// TYPE DEFINES /////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +class WeaponBonusUpdateModuleData : public UpdateModuleData +{ +public: + + WeaponBonusUpdateModuleData(); + + KindOfMaskType m_requiredAffectKindOf; ///< Must be set on target + KindOfMaskType m_forbiddenAffectKindOf; ///< Must be clear on target + UnsignedInt m_bonusDuration; ///< How long a hit lasts on target + UnsignedInt m_bonusDelay; ///< How often to pulse + Real m_bonusRange; ///< How far to affect + WeaponBonusConditionType m_bonusConditionType; ///< Status to give + TintStatus m_tintStatus; ///< tint color to apply + + static void buildFieldParse(MultiIniFieldParse& p); +}; + + +//------------------------------------------------------------------------------------------------- +class WeaponBonusUpdate : public UpdateModule +{ + + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( WeaponBonusUpdate, "WeaponBonusUpdate" ) + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA( WeaponBonusUpdate, WeaponBonusUpdateModuleData ) + +public: + + WeaponBonusUpdate( Thing *thing, const ModuleData* moduleData ); + // virtual destructor prototype provided by memory pool declaration + + virtual UpdateSleepTime update( void ); + +protected: + +}; + + +//----------------------------------------------------------------------------- +// INLINING /////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// EXTERNALS ////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +#endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponSetUpgrade.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponSetUpgrade.h index d73612c996..b5a7b90781 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponSetUpgrade.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/WeaponSetUpgrade.h @@ -34,21 +34,42 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "GameLogic/Module/UpgradeModule.h" +#include "GameLogic/WeaponSet.h" + // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class Thing; +//enum ModelConditionFlagType CPP_11(: Int); +enum WeaponSetType CPP_11(: Int); -//------------------------------------------------------------------------------------------------- -/** The default die module */ + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +class WeaponSetUpgradeModuleData : public UpgradeModuleData +{ + +public: + + WeaponSetUpgradeModuleData(void); + + static void buildFieldParse(MultiIniFieldParse& p); + + WeaponSetType m_weaponSetFlag; ///< The weaponset flag to set (default = WEAPONSET_PLAYER_UPGRADE) + WeaponSetFlags m_weaponSetFlagsToClear; ///< The weaponset flags to clear. This is needed if we want to disable a previous upgrade. + Bool m_needsParkedAircraft; ///< Aircraft attempting this upgrade needs to be stationary in hangar + +}; //------------------------------------------------------------------------------------------------- class WeaponSetUpgrade : public UpgradeModule { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( WeaponSetUpgrade, "WeaponSetUpgrade" ) - MAKE_STANDARD_MODULE_MACRO( WeaponSetUpgrade ); + MAKE_STANDARD_MODULE_MACRO_WITH_MODULE_DATA(WeaponSetUpgrade, WeaponSetUpgradeModuleData); public: + virtual Bool wouldUpgrade(UpgradeMaskType keyMask) const; + WeaponSetUpgrade( Thing *thing, const ModuleData* moduleData ); // virtual destructor prototype defined by MemoryPoolObject diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h index f2b2b7b71d..9abdb11701 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h @@ -121,6 +121,7 @@ enum ArmorSetType CPP_11(: Int); enum WeaponStatus CPP_11(: Int); enum RadarPriorityType CPP_11(: Int); enum CanAttackResult CPP_11(: Int); +// enum TintStatus CPP_11(: Int); // For ObjectStatusTypes #include "Common/ObjectStatusTypes.h" @@ -128,6 +129,9 @@ enum CanAttackResult CPP_11(: Int); // For ObjectScriptStatusBit #include "GameLogic/ObjectScriptStatusBits.h" +// For TintStatus +#include "GameClient/TintStatus.h" + //----------------------------------------------------------------------------- // Type Defines //----------------------------------------------------------------------------- @@ -231,7 +235,7 @@ class Object : public Thing, public Snapshot void healCompletely(); ///< Restore max health to this Object void notifySubdualDamage( Real amount );///< At this level, we just pass this on to our helper and do a special tint void doStatusDamage( ObjectStatusTypes status, Real duration );///< At this level, we just pass this on to our helper - void doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration );///< At this level, we just pass this on to our helper + void doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration, TintStatus tintStatus = TINT_STATUS_INVALID );///< At this level, we just pass this on to our helper void scoreTheKill( const Object *victim ); ///< I just killed this object. void onVeterancyLevelChanged( VeterancyLevel oldLevel, VeterancyLevel newLevel, Bool provideFeedback = TRUE ); ///< I just achieved this level right this moment @@ -481,6 +485,7 @@ class Object : public Thing, public Snapshot Weapon* getWeaponInWeaponSlot(WeaponSlotType wslot) const { return m_weaponSet.getWeaponInWeaponSlot(wslot); } UnsignedInt getWeaponInWeaponSlotCommandSourceMask( WeaponSlotType wSlot ) const { return m_weaponSet.getNthCommandSourceMask( wSlot ); } + Bool getWeaponInWeaponSlotSyncedToSlot(WeaponSlotType thisSlot, WeaponSlotType otherSlot) const; // see if this current weapon set's weapons has shared reload times const Bool isReloadTimeShared() const { return m_weaponSet.isSharedReloadTime(); } @@ -492,6 +497,7 @@ class Object : public Thing, public Snapshot void fireCurrentWeapon(Object *target); void fireCurrentWeapon(const Coord3D* pos); void preFireCurrentWeapon( const Object *victim ); + void preFireCurrentWeapon(const Coord3D* pos); UnsignedInt getLastShotFiredFrame() const; ///< Get the frame a shot was last fired on ObjectID getLastVictimID() const; ///< Get the last victim we shot at Weapon* findWaypointFollowingCapableWeapon(); @@ -563,6 +569,7 @@ class Object : public Thing, public Snapshot // note, the !=0 at the end is important, to convert this into a boolean type! (srj) Bool testWeaponBonusCondition(WeaponBonusConditionType wst) const { return (m_weaponBonusCondition & (1 << wst)) != 0; } inline WeaponBonusConditionFlags getWeaponBonusCondition() const { return m_weaponBonusCondition; } + inline void setWeaponBonusConditionFlags(WeaponBonusConditionFlags flags) { m_weaponBonusCondition = flags; } Bool getSingleLogicalBonePosition(const char* boneName, Coord3D* position, Matrix3D* transform) const; Bool getSingleLogicalBonePositionOnTurret(WhichTurretType whichTurret, const char* boneName, Coord3D* position, Matrix3D* transform) const; @@ -800,7 +807,7 @@ class Object : public Thing, public Snapshot // --------- BYTE-SIZED THINGS GO HERE Bool m_isSelectable; Bool m_modulesReady; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_hasDiedAlready; #endif UnsignedByte m_scriptStatus; ///< status as set by scripting, corresponds to ORed ObjectScriptStatusBits @@ -811,12 +818,10 @@ class Object : public Thing, public Snapshot }; // end class Object -#ifdef DEBUG_LOGGING // describe an object as an AsciiString: e.g. "Object 102 (KillerBuggy) [GLARocketBuggy, owned by player 2 (GLAIntroPlayer)]" -AsciiString DescribeObject(const Object *obj); -#endif // DEBUG_LOGGING +AsciiString DebugDescribeObject(const Object *obj); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define DEBUG_OBJECT_ID_EXISTS #else #undef DEBUG_OBJECT_ID_EXISTS diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h index 7438ce9475..ab4f9b54e1 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/PartitionManager.h @@ -354,7 +354,7 @@ class PartitionCell : public Snapshot // not MPO: allocated in an array inline CellAndObjectIntersection *getFirstCoiInCell() { return m_firstCoiInCell; } - #ifdef _DEBUG + #ifdef RTS_DEBUG void validateCoiList(); #endif @@ -596,7 +596,7 @@ class PartitionFilter { public: virtual Bool allow(Object *objOther) = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() = 0; #endif }; @@ -610,7 +610,7 @@ class PartitionFilterIsFlying : public PartitionFilter public: PartitionFilterIsFlying() { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterIsFlying"; } #endif }; @@ -626,7 +626,7 @@ class PartitionFilterWouldCollide : public PartitionFilter public: PartitionFilterWouldCollide(const Coord3D& pos, const GeometryInfo& geom, Real angle, Bool desired); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterWouldCollide"; } #endif }; @@ -642,7 +642,7 @@ class PartitionFilterSamePlayer : public PartitionFilter public: PartitionFilterSamePlayer(const Player *player) : m_player(player) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterSamePlayer"; } #endif }; @@ -668,7 +668,7 @@ class PartitionFilterRelationship : public PartitionFilter }; PartitionFilterRelationship(const Object *obj, Int flags) : m_obj(obj), m_flags(flags) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRelationship"; } #endif }; @@ -685,7 +685,7 @@ class PartitionFilterAcceptOnTeam : public PartitionFilter public: PartitionFilterAcceptOnTeam(const Team *team); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptOnTeam"; } #endif }; @@ -702,7 +702,7 @@ class PartitionFilterAcceptOnSquad : public PartitionFilter public: PartitionFilterAcceptOnSquad(const Squad *squad); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptOnSquad"; } #endif }; @@ -725,7 +725,7 @@ class PartitionFilterLineOfSight : public PartitionFilter public: PartitionFilterLineOfSight(const Object *obj); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLineOfSight"; } #endif }; @@ -743,7 +743,7 @@ class PartitionFilterPossibleToAttack : public PartitionFilter public: PartitionFilterPossibleToAttack(AbleToAttackType t, const Object *obj, CommandSourceType commandSource); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPossibleToAttack"; } #endif }; @@ -761,7 +761,7 @@ class PartitionFilterPossibleToEnter : public PartitionFilter public: PartitionFilterPossibleToEnter(const Object *obj, CommandSourceType commandSource); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPossibleToEnter"; } #endif }; @@ -779,7 +779,7 @@ class PartitionFilterPossibleToHijack : public PartitionFilter public: PartitionFilterPossibleToHijack(const Object *obj, CommandSourceType commandSource); virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPossibleToHijack"; } #endif }; @@ -795,7 +795,7 @@ class PartitionFilterLastAttackedBy : public PartitionFilter public: PartitionFilterLastAttackedBy(Object *obj); virtual Bool allow(Object *other); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLastAttackedBy"; } #endif }; @@ -811,7 +811,7 @@ class PartitionFilterAcceptByObjectStatus : public PartitionFilter public: PartitionFilterAcceptByObjectStatus( ObjectStatusMaskType mustBeSet, ObjectStatusMaskType mustBeClear) : m_mustBeSet(mustBeSet), m_mustBeClear(mustBeClear) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptByObjectStatus"; } #endif }; @@ -831,7 +831,7 @@ class PartitionFilterRejectByObjectStatus : public PartitionFilter { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectByObjectStatus"; } #endif }; @@ -848,7 +848,7 @@ class PartitionFilterStealthedAndUndetected : public PartitionFilter public: PartitionFilterStealthedAndUndetected( const Object *obj, Bool allow ) { m_obj = obj; m_allow = allow; } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterStealthedAndUndetected"; } #endif }; @@ -864,7 +864,7 @@ class PartitionFilterAcceptByKindOf : public PartitionFilter public: PartitionFilterAcceptByKindOf(const KindOfMaskType& mustBeSet, const KindOfMaskType& mustBeClear) : m_mustBeSet(mustBeSet), m_mustBeClear(mustBeClear) { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAcceptByKindOf"; } #endif }; @@ -884,7 +884,7 @@ class PartitionFilterRejectByKindOf : public PartitionFilter { } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectByKindOf"; } #endif }; @@ -901,7 +901,7 @@ class PartitionFilterRejectBehind: public PartitionFilter public: PartitionFilterRejectBehind( Object *obj ); virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectBehind"; } #endif }; @@ -916,7 +916,7 @@ class PartitionFilterAlive : public PartitionFilter PartitionFilterAlive(void) { } protected: virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterAlive"; } #endif }; @@ -934,7 +934,7 @@ class PartitionFilterSameMapStatus : public PartitionFilter PartitionFilterSameMapStatus(const Object *obj) : m_obj(obj) { } protected: virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterSameMapStatus"; } #endif }; @@ -949,7 +949,7 @@ class PartitionFilterOnMap : public PartitionFilter PartitionFilterOnMap() { } protected: virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterOnMap"; } #endif }; @@ -969,7 +969,7 @@ class PartitionFilterRejectBuildings : public PartitionFilter PartitionFilterRejectBuildings(const Object *o); protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRejectBuildings"; } #endif }; @@ -989,7 +989,7 @@ class PartitionFilterInsignificantBuildings : public PartitionFilter m_allowNonBuildings(allowNonBuildings), m_allowInsignificant(allowInsignificant) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterInsignificantBuildings"; } #endif }; @@ -1007,7 +1007,7 @@ class PartitionFilterFreeOfFog : public PartitionFilter m_comparisonIndex(toWhom){} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterFreeOfFog"; } #endif }; @@ -1024,7 +1024,7 @@ class PartitionFilterRepulsor : public PartitionFilter PartitionFilterRepulsor(const Object *o) : m_self(o) { } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterRepulsor"; } #endif }; @@ -1045,7 +1045,7 @@ class PartitionFilterIrregularArea : public PartitionFilter PartitionFilterIrregularArea(Coord3D* area, Int numPointsInArea) : m_area(area), m_numPointsInArea(numPointsInArea) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterIrregularArea"; } #endif }; @@ -1065,7 +1065,7 @@ class PartitionFilterPolygonTrigger : public PartitionFilter PartitionFilterPolygonTrigger(const PolygonTrigger *trigger) : m_trigger(trigger) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPolygonTrigger"; } #endif }; @@ -1085,7 +1085,7 @@ class PartitionFilterPlayer : public PartitionFilter PartitionFilterPlayer(const Player *player, Bool match) : m_player(player), m_match(match) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPlayer"; } #endif }; @@ -1110,7 +1110,7 @@ class PartitionFilterPlayerAffiliation : public PartitionFilter } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterPlayerAffiliation"; } #endif }; @@ -1130,7 +1130,7 @@ class PartitionFilterThing : public PartitionFilter PartitionFilterThing(const ThingTemplate *thing, Bool match) : m_tThing(thing), m_match(match) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterThing"; } #endif }; @@ -1155,7 +1155,7 @@ class PartitionFilterGarrisonable : public PartitionFilter } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterGarrisonable"; } #endif }; @@ -1178,7 +1178,7 @@ class PartitionFilterGarrisonableByPlayer : public PartitionFilter } protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterGarrisonableByPlayer"; } #endif }; @@ -1196,7 +1196,7 @@ class PartitionFilterUnmannedObject : public PartitionFilter PartitionFilterUnmannedObject( Bool match ) : m_match(match) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterUnmannedObject"; } #endif }; @@ -1218,7 +1218,7 @@ class PartitionFilterValidCommandButtonTarget : public PartitionFilter m_source(source), m_commandButton(commandButton), m_match(match), m_commandSource(commandSource) {} protected: virtual Bool allow( Object *other ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterValidCommandButtonTarget"; } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h index d4c0ee960f..38d3e897d6 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScriptEngine.h @@ -50,7 +50,7 @@ class Player; class PolygonTrigger; class ObjectTypes; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL #define SPECIAL_SCRIPT_PROFILING #endif @@ -136,7 +136,7 @@ class AttackPriorityInfo : public Snapshot void setPriority(const ThingTemplate *tThing, Int priority); Int getPriority(const ThingTemplate *tThing) const; AsciiString getName(void) const {return m_name;} -#ifdef _DEBUG +#ifdef RTS_DEBUG void dumpPriorityInfo(void); #endif @@ -353,7 +353,7 @@ class ScriptEngine : public SubsystemInterface, void setEnableVTune(Bool value); Bool getEnableVTune() const; ///End VTUNE -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void debugVictory( void ); //#endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/TurretAI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/TurretAI.h index dc1e387907..2b8af79a8c 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/TurretAI.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/TurretAI.h @@ -239,11 +239,16 @@ class TurretAIData : public MemoryPoolObject Bool m_firesWhileTurning; ///< so the firing state does not instantly expire the turning state Bool m_isAllowsPitch; ///< This type of turret can pitch up and down as well as spin + Real m_minTurretAngle; ///< Minimum turn angle for turret + Real m_maxTurretAngle; ///< Maximum turn angle for turret + Bool m_hasLimitedTurretAngle; ///< this type of turret has limited angles + TurretAIData(); static void buildFieldParse(MultiIniFieldParse& p); static void parseTurretSweep(INI* ini, void *instance, void *store, const void* userData); static void parseTurretSweepSpeed(INI* ini, void *instance, void *store, const void* userData); + static void parseMinMaxAngle(INI* ini, void *instance, void *store, const void* userData); }; EMPTY_DTOR(TurretAIData) @@ -285,6 +290,11 @@ class TurretAI : public MemoryPoolObject, public Snapshot, public NotifyWeaponFi UnsignedInt getMaxIdleScanInterval() const { return m_data->m_maxIdleScanInterval; } UnsignedInt getRecenterTime() const { return m_data->m_recenterTime; } Object* getOwner() { return m_owner; } + + Real getMinTurretAngle() const { return m_data->m_minTurretAngle; } + Real getMaxTurretAngle() const { return m_data->m_maxTurretAngle; } + Real hasLimitedTurretAngle() const { return m_data->m_hasLimitedTurretAngle; } + const Object* getOwner() const { return m_owner; } Bool isOwnersCurWeaponOnTurret() const; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h index 92fbe8a8b8..87eccd5c5e 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h @@ -205,6 +205,7 @@ enum WeaponBonusConditionType CPP_11(: Int) WEAPONBONUSCONDITION_FRENZY_ONE, WEAPONBONUSCONDITION_FRENZY_TWO, WEAPONBONUSCONDITION_FRENZY_THREE, + WEAPONBONUSCONDITION_CONTAINED, WEAPONBONUSCONDITION_COUNT }; @@ -243,11 +244,16 @@ static const char *TheWeaponBonusNames[] = "FRENZY_ONE", "FRENZY_TWO", "FRENZY_THREE", + "CONTAINED", NULL }; #endif + +typedef std::vector WeaponBonusConditionTypeVec; + + // For WeaponBonusConditionFlags // part of detangling #include "GameLogic/WeaponBonusConditionFlags.h" @@ -447,9 +453,13 @@ class WeaponTemplate : public MemoryPoolObject inline const ObjectCreationList* getFireOCL(VeterancyLevel v) const { return m_fireOCLs[v]; } inline const ObjectCreationList* getProjectileDetonationOCL(VeterancyLevel v) const { return m_projectileDetonationOCLs[v]; } inline const ParticleSystemTemplate* getProjectileExhaust(VeterancyLevel v) const { return m_projectileExhausts[v]; } + inline const FXList* getPreAttackFX(VeterancyLevel v) const { return m_preAttackFXs[v]; } + inline UnsignedInt getPreAttackFXDelay() const { return m_preAttackFXDelay; } inline const AudioEventRTS& getFireSound() const { return m_fireSound; } inline UnsignedInt getFireSoundLoopTime() const { return m_fireSoundLoopTime; } + inline UnsignedInt getContinuousLaserLoopTime() const { return m_continuousLaserLoopTime; } + inline UnsignedInt getScatterTargetResetTime() const { return m_scatterTargetResetTime; } inline const std::vector& getScatterTargetsVector() const { return m_scatterTargets; } inline const WeaponBonusSet* getExtraBonus() const { return m_extraBonus; } inline Int getShotsPerBarrel() const { return m_shotsPerBarrel; } @@ -460,12 +470,29 @@ class WeaponTemplate : public MemoryPoolObject inline Bool isPlayFXWhenStealthed() const { return m_playFXWhenStealthed; } inline Bool getDieOnDetonate() const { return m_dieOnDetonate; } + inline Bool isScatterTargetAligned() const { return m_scatterTargetAligned; } + inline Bool isScatterTargetRandom() const { return m_scatterTargetRandom; } + inline Bool isScatterTargetRandomAngle() const { return m_scatterTargetRandomAngle; } + inline Real getScatterTargetMinScalar () const { return m_scatterTargetMinScalar; } + inline Bool isScatterTargetCenteredAtShooter() const { return m_scatterTargetCenteredAtShooter; } + Bool shouldProjectileCollideWith( const Object* projectileLauncher, const Object* projectile, const Object* thingWeCollidedWith, ObjectID intendedVictimID // could be INVALID_ID for a position-shot ) const; + + void createPreAttackFX + ( + const Object* sourceObj, + WeaponSlotType wslot, + Int specificBarrelToUse, + const Object* victimObj, + const Coord3D* victimPos + //const WeaponBonus& bonus, + //Weapon *firingWeapon, + ) const; void postProcessLoad(); @@ -556,6 +583,18 @@ class WeaponTemplate : public MemoryPoolObject ObjectStatusTypes m_damageStatusType; ///< If our damage is Status damage, the status we apply UnsignedInt m_suspendFXDelay; ///< The fx can be suspended for any delay, in frames, then they will execute as normal Bool m_dieOnDetonate; + const FXList* m_preAttackFXs[LEVEL_COUNT]; ///< FX played when preattack starts + UnsignedInt m_preAttackFXDelay; ///< Delay after starting a preattackFX before we can play it again (default = 200 ms) + + UnsignedInt m_continuousLaserLoopTime; ///< time between shots the continuos laser object is kept alive instead of creating a new one + + Bool m_scatterTargetAligned; ///< if the scatter target pattern is aligned to the shooter + Bool m_scatterTargetRandom; ///< if the scatter target pattern is fired in a random order + Bool m_scatterTargetRandomAngle; ///< if the scatter target pattern is randomly aligned + Real m_scatterTargetMinScalar; ///< scale the scatterTarget pattern depending on range + Bool m_scatterTargetCenteredAtShooter; ///< if the scatter target pattern is centered at the shooter + + UnsignedInt m_scatterTargetResetTime; ///< if this much time between shots has passed, we reset the scatter targets mutable HistoricWeaponDamageList m_historicDamage; }; @@ -598,6 +637,8 @@ class Weapon : public MemoryPoolObject, void preFireWeapon( const Object *source, const Object *victim ); + void preFireWeapon(const Object* source, const Coord3D* pos); + //Currently, this function was added to allow a script to force fire a weapon, //and immediately gain control of the weapon that was fired to give it special orders... Object* forceFireWeapon( const Object *source, const Coord3D *pos ); @@ -660,10 +701,13 @@ class Weapon : public MemoryPoolObject, UnsignedInt getLastReloadStartedFrame() const { return m_whenLastReloadStarted; } Real getPercentReadyToFire() const; + UnsignedInt getNextPreAttackFXFrame() const { return m_nextPreAttackFXFrame; } + // do not ever use this unless you are weaponset.cpp void setPossibleNextShotFrame( UnsignedInt frameNum ) { m_whenWeCanFireAgain = frameNum; } void setPreAttackFinishedFrame( UnsignedInt frameNum ) { m_whenPreAttackFinished = frameNum; } void setLastReloadStartedFrame( UnsignedInt frameNum ) { m_whenLastReloadStarted = frameNum; } + void setNextPreAttackFXFrame(UnsignedInt frameNum) { m_nextPreAttackFXFrame = frameNum; } //Transfer the reload times and status from the passed in weapon. void transferNextShotStatsFrom( const Weapon &weapon ); @@ -680,7 +724,9 @@ class Weapon : public MemoryPoolObject, void newProjectileFired( const Object *sourceObj, const Object *projectile, const Object *victimObj, const Coord3D *victimPos );///getLaserName().isNotEmpty(); } - void createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos ); + // void createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos ); + ObjectID createLaser(const Object* sourceObj, const Object* victimObj, const Coord3D* victimPos); //now returns the object ID + void handleContinuousLaser(const Object* sourceObj, const Object* victimObj, const Coord3D* victimPos); inline const WeaponTemplate* getTemplate() const { return m_template; } inline WeaponSlotType getWeaponSlot() const { return m_wslot; } @@ -701,6 +747,7 @@ class Weapon : public MemoryPoolObject, inline UnsignedInt getAutoReloadWhenIdleFrames() const { return m_template->getAutoReloadWhenIdleFrames(); } inline const AudioEventRTS& getFireSound() const { return m_template->getFireSound(); } inline UnsignedInt getFireSoundLoopTime() const { return m_template->getFireSoundLoopTime(); } + inline UnsignedInt getContinuousLaserLoopTime() const { return m_template->getContinuousLaserLoopTime(); } inline DamageType getDamageType() const { return m_template->getDamageType(); } inline DeathType getDeathType() const { return m_template->getDeathType(); } inline Real getContinueAttackRange() const { return m_template->getContinueAttackRange(); } @@ -736,6 +783,9 @@ class Weapon : public MemoryPoolObject, Bool isClearGoalFiringLineOfSightTerrain(const Object* source, const Coord3D& goalPos, const Object* victim) const; Bool isClearGoalFiringLineOfSightTerrain(const Object* source, const Coord3D& goalPos, const Coord3D& victimPos) const; + ObjectID setBonusRefObjID(void) { return m_bonusRefObjID; } + void setBonusRefObjID(ObjectID id) { m_bonusRefObjID = id; } + static void calcProjectileLaunchPosition( const Object* launcher, WeaponSlotType wslot, @@ -803,6 +853,10 @@ class Weapon : public MemoryPoolObject, std::vector m_scatterTargetsUnused; ///< A running memory of which targets I've used, so I can shoot them all at random Bool m_pitchLimited; Bool m_leechWeaponRangeActive; ///< This weapon has unlimited range until attack state is aborted! + Real m_scatterTargetsAngle; ///< Random angle chosen for scatterTarget pattern + UnsignedInt m_nextPreAttackFXFrame; ///< the frame when we are next allowed to play a preAttackFX + ObjectID m_continuousLaserID; ///< the object that is tracking our continuous laser if we have one. + ObjectID m_bonusRefObjID; ///< for weapons fired from projectiles, we compute the bonus from the original source object instead. // setter function for status that should not be used outside this class void setStatus( WeaponStatus status) { m_status = status; } diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h index bba5c76aaf..6b6fc75a88 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSet.h @@ -103,6 +103,11 @@ static const ModelConditionFlagType TheWeaponSetTypeToModelConditionTypeMap[WEAP /*WEAPONSET_RIDER6*/ MODELCONDITION_RIDER6, /*WEAPONSET_RIDER7*/ MODELCONDITION_RIDER7, /*WEAPONSET_RIDER8*/ MODELCONDITION_RIDER8, + /*WEAPONSET_PLAYER_UPGRADE2*/ MODELCONDITION_WEAPONSET_PLAYER_UPGRADE2, + /*WEAPONSET_PLAYER_UPGRADE3*/ MODELCONDITION_WEAPONSET_PLAYER_UPGRADE3, + /*WEAPONSET_PLAYER_UPGRADE4*/ MODELCONDITION_WEAPONSET_PLAYER_UPGRADE4, + /*WEAPONSET_GARRISONED*/ MODELCONDITION_INVALID, //No actual conditionstates needed for Garrisoned and contained + /*WEAPONSET_CONTAINED*/ MODELCONDITION_INVALID }; #endif @@ -131,6 +136,7 @@ class WeaponTemplateSet KindOfMaskType m_preferredAgainst[WEAPONSLOT_COUNT]; Bool m_isReloadTimeShared; Bool m_isWeaponLockSharedAcrossSets; ///< A weapon set so similar that it is safe to hold locks across + Bool m_isWeaponReloadSharedAcrossSets; ///< Keep current ammo count and reload progress between sets static void parseWeapon(INI* ini, void *instance, void *store, const void* userData); static void parseAutoChoose(INI* ini, void *instance, void *store, const void* userData); @@ -150,6 +156,7 @@ class WeaponTemplateSet Bool testWeaponSetFlag( WeaponSetType wst ) const; Bool isSharedReloadTime( void ) const { return m_isReloadTimeShared; } Bool isWeaponLockSharedAcrossSets() const {return m_isWeaponLockSharedAcrossSets; } + Bool isWeaponReloadSharedAcrossSets() const { return m_isWeaponReloadSharedAcrossSets; } Bool hasAnyWeapons() const; inline const WeaponTemplate* getNth(WeaponSlotType n) const { return m_template[n]; } @@ -158,7 +165,7 @@ class WeaponTemplateSet inline Int getConditionsYesCount() const { return 1; } inline const WeaponSetFlags& getNthConditionsYes(Int i) const { return m_types; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline AsciiString getDescription() const { return AsciiString("ArmorTemplateSet"); } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSetType.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSetType.h index 91c60ed3a4..34fa3f1861 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSetType.h +++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/WeaponSetType.h @@ -58,6 +58,12 @@ enum WeaponSetType CPP_11(: Int) WEAPONSET_RIDER6, WEAPONSET_RIDER7, WEAPONSET_RIDER8, + WEAPONSET_PLAYER_UPGRADE2, // New sets to support multiple weapon upgrades + WEAPONSET_PLAYER_UPGRADE3, + WEAPONSET_PLAYER_UPGRADE4, + + WEAPONSET_GARRISONED, + WEAPONSET_CONTAINED, WEAPONSET_COUNT ///< keep last, please }; diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h index d90005e271..4aa162d038 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h +++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Connection.h @@ -79,7 +79,7 @@ class Connection : public MemoryPoolObject void setQuitting( void ); Bool isQuitting( void ) { return m_isQuitting; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void debugPrintCommands(); #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h index 83f0aa4252..5ab892aa12 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h +++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/ConnectionManager.h @@ -140,7 +140,7 @@ class ConnectionManager Int getAverageFPS( void ); Int getSlotAverageFPS(Int slot); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void debugPrintConnectionCommands(); #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h index 7865dc5b35..e2ac808c52 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h +++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetCommandRef.h @@ -31,7 +31,7 @@ #include "GameNetwork/NetCommandMsg.h" #include "Common/GameMemory.h" -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) // #define DEBUG_NETCOMMANDREF #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h index 01244de2bb..be121ba002 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h +++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkDefs.h @@ -99,7 +99,7 @@ struct TransportMessage }; #pragma pack(pop) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #pragma pack(push, 1) struct DelayedTransportMessage { diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkInterface.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkInterface.h index 2ca8b36ced..07983545cf 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkInterface.h +++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/NetworkInterface.h @@ -120,7 +120,7 @@ class NetworkInterface : public SubsystemInterface virtual Int getExecutionFrame() = 0; ///< Returns the next valid frame for simultaneous command execution. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void toggleNetworkOn( void ) = 0; ///< toggle whether or not to send network traffic. #endif diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h index b61e381423..4a1eddb765 100644 --- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h +++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Transport.h @@ -76,7 +76,7 @@ class Transport //: public MemoryPoolObject TransportMessage m_outBuffer[MAX_MESSAGES]; TransportMessage m_inBuffer[MAX_MESSAGES]; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DelayedTransportMessage m_delayedInBuffer[MAX_MESSAGES]; #endif diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp index dc5edcfbcf..3f9d2937bb 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp @@ -57,7 +57,7 @@ #include "GameClient/Drawable.h" // For getPosition #include "GameClient/GameClient.h" // For getDrawableByID -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp index b1858359ef..2f50c15f9e 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp @@ -71,7 +71,7 @@ #include "WWMath/matrix3d.h" /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif @@ -248,7 +248,7 @@ void AudioManager::init() break; } // We loop infinitely on the splash screen if we don't allow breaking out of this loop. -//#if !defined( _DEBUG ) && !defined( _INTERNAL ) +//#if !defined( RTS_DEBUG ) && !defined( RTS_INTERNAL ) else { // Display the warning. diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameMusic.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameMusic.cpp index 423c27527f..5eb664302c 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameMusic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameMusic.cpp @@ -52,7 +52,7 @@ #include "Common/GameAudio.h" #include "Common/INI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameSounds.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameSounds.cpp index c9f5ab3c2c..361a752e59 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameSounds.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameSounds.cpp @@ -56,7 +56,7 @@ #include "GameLogic/PartitionManager.h" /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/GeneralsMD/Code/GameEngine/Source/Common/BitFlags.cpp b/GeneralsMD/Code/GameEngine/Source/Common/BitFlags.cpp index fad98759a8..ef8b2a3ffe 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/BitFlags.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/BitFlags.cpp @@ -170,6 +170,11 @@ const char* ModelConditionFlags::s_bitNameList[] = "USER_2", "DISGUISED", + + // New Weaponsets + "WEAPONSET_PLAYER_UPGRADE2", + "WEAPONSET_PLAYER_UPGRADE3", + "WEAPONSET_PLAYER_UPGRADE4", NULL }; @@ -184,6 +189,9 @@ const char* ArmorSetFlags::s_bitNameList[] = "SECOND_LIFE", "CRATE_UPGRADE_ONE", "CRATE_UPGRADE_TWO", + "PLAYER_UPGRADE2", + "PLAYER_UPGRADE3", + "PLAYER_UPGRADE4", NULL }; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CRCDebug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CRCDebug.cpp index 46c781f656..47cbd241b1 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/CRCDebug.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/CRCDebug.cpp @@ -28,11 +28,12 @@ #include "Common/CRCDebug.h" #include "Common/Debug.h" #include "Common/PerfTimer.h" +#include "Common/LocalFileSystem.h" #include "GameClient/InGameUI.h" #include "GameNetwork/IPEnumeration.h" #include -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -41,11 +42,12 @@ #ifdef DEBUG_CRC static const Int MaxStrings = 64000; +static const Int MaxStringLen = 1024; -static char DebugStrings[MaxStrings][1024]; +static char DebugStrings[MaxStrings][MaxStringLen]; static Int nextDebugString = 0; static Int numDebugStrings = 0; -//static char DumpStrings[MaxStrings][1024]; +//static char DumpStrings[MaxStrings][MaxStringLen]; //static Int nextDumpString = 0; //static Int numDumpStrings = 0; @@ -91,12 +93,8 @@ CRCVerification::~CRCVerification() #endif } -static Bool dumped = FALSE; void outputCRCDebugLines( void ) { - if (dumped) - return; - dumped = TRUE; IPEnumeration ips; AsciiString fname; fname.format("crcDebug%s.txt", ips.getMachineName().str()); @@ -116,6 +114,62 @@ void outputCRCDebugLines( void ) if (fp) fclose(fp); } +Int lastCRCDebugFrame = 0; +Int lastCRCDebugIndex = 0; +extern Bool inCRCGen; + +void CRCDebugStartNewGame() +{ + if (TheGameLogic->isInShellGame()) + return; + if (g_saveDebugCRCPerFrame) + { + // Create folder for frame data, if it doesn't exist yet. + CreateDirectory(g_saveDebugCRCPerFrameDir.str(), NULL); + + // Delete existing files + FilenameList files; + AsciiString dir = g_saveDebugCRCPerFrameDir; + dir.concat("/"); + TheLocalFileSystem->getFileListInDirectory(dir.str(), "", "DebugFrame_*.txt", files, FALSE); + FilenameList::iterator it; + for (it = files.begin(); it != files.end(); ++it) + { + DeleteFile(it->str()); + } + } + nextDebugString = 0; + numDebugStrings = 0; + lastCRCDebugFrame = 0; + lastCRCDebugIndex = 0; +} + +static void outputCRCDebugLinesPerFrame() +{ + if (!g_saveDebugCRCPerFrame || numDebugStrings == 0) + return; + AsciiString fname; + fname.format("%s/DebugFrame_%06d.txt", g_saveDebugCRCPerFrameDir.str(), lastCRCDebugFrame); + FILE *fp = fopen(fname.str(), "wt"); + int start = 0; + int end = nextDebugString; + if (numDebugStrings >= MaxStrings) + start = nextDebugString - MaxStrings; + nextDebugString = 0; + numDebugStrings = 0; + if (!fp) + return; + + for (Int i=start; iisInGameLogicUpdate()*/) + if (TheGameLogic == NULL || !(IS_FRAME_OK_TO_LOG)) return; - if (IS_FRAME_OK_TO_LOG) + if (lastCRCDebugFrame != TheGameLogic->getFrame()) { + outputCRCDebugLinesPerFrame(); + lastCRCDebugFrame = TheGameLogic->getFrame(); + lastCRCDebugIndex = 0; + } - if (lastCRCDebugFrame != TheGameLogic->getFrame()) - { - lastCRCDebugFrame = TheGameLogic->getFrame(); - lastCRCDebugIndex = 0; - } - - sprintf(DebugStrings[nextDebugString], "%d:%d ", TheGameLogic->getFrame(), lastCRCDebugIndex++); - //DebugStrings[nextDebugString][0] = 0; - Int len = strlen(DebugStrings[nextDebugString]); + if (count) + sprintf(DebugStrings[nextDebugString], "%d:%05d ", TheGameLogic->getFrame(), lastCRCDebugIndex++); + else + DebugStrings[nextDebugString][0] = 0; + Int len = strlen(DebugStrings[nextDebugString]); - va_list va; - va_start( va, fmt ); - _vsnprintf(DebugStrings[nextDebugString]+len, 1024-len, fmt, va ); - DebugStrings[nextDebugString][1023] = 0; - va_end( va ); + _vsnprintf(DebugStrings[nextDebugString]+len, MaxStringLen-len, fmt, args); + DebugStrings[nextDebugString][MaxStringLen-1] = 0; - char *tmp = DebugStrings[nextDebugString]; - while (tmp && *tmp) + char *tmp = DebugStrings[nextDebugString]; + while (tmp && *tmp) + { + if (*tmp == '\r' || *tmp == '\n') { - if (*tmp == '\r' || *tmp == '\n') - { - *tmp = ' '; - } - ++tmp; + *tmp = ' '; } + ++tmp; + } + + //DEBUG_LOG(("%s\n", DebugStrings[nextDebugString])); - //DEBUG_LOG(("%s\n", DebugStrings[nextDebugString])); + ++nextDebugString; + ++numDebugStrings; + if (nextDebugString == MaxStrings) + nextDebugString = 0; +} - ++nextDebugString; - ++numDebugStrings; - if (nextDebugString == MaxStrings) - nextDebugString = 0; +void addCRCDebugLine(const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + addCRCDebugLineInternal(true, fmt, args); + va_end(args); +} - } +void addCRCDebugLineNoCounter(const char *fmt, ...) +{ + // TheSuperHackers @feature helmutbuhler 04/09/2025 + // This version doesn't increase the lastCRCDebugIndex counter + // and can be used for logging lines that don't necessarily match up on all peers. + // (Otherwise the numbers would no longer match up and the diff would be very difficult to read) + va_list args; + va_start(args, fmt); + addCRCDebugLineInternal(false, fmt, args); + va_end(args); } void addCRCGenLine(const char *fmt, ...) { - if (dumped || !(IS_FRAME_OK_TO_LOG)) + if (!(IS_FRAME_OK_TO_LOG)) return; - static char buf[1024]; + static char buf[MaxStringLen]; va_list va; va_start( va, fmt ); - _vsnprintf(buf, 1024, fmt, va ); + _vsnprintf(buf, MaxStringLen, fmt, va ); va_end( va ); - buf[1023] = 0; + buf[MaxStringLen-1] = 0; addCRCDebugLine("%s", buf); //DEBUG_LOG(("%s", buf)); @@ -205,8 +271,8 @@ void addCRCDumpLine(const char *fmt, ...) /* va_list va; va_start( va, fmt ); - _vsnprintf(DumpStrings[nextDumpString], 1024, fmt, va ); - DumpStrings[nextDumpString][1023] = 0; + _vsnprintf(DumpStrings[nextDumpString], MaxStringLen, fmt, va ); + DumpStrings[nextDumpString][MaxStringLen-1] = 0; va_end( va ); ++nextDumpString; @@ -218,9 +284,6 @@ void addCRCDumpLine(const char *fmt, ...) void dumpVector3(const Vector3 *v, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); @@ -231,9 +294,6 @@ void dumpVector3(const Vector3 *v, AsciiString name, AsciiString fname, Int line void dumpCoord3D(const Coord3D *c, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); @@ -244,9 +304,6 @@ void dumpCoord3D(const Coord3D *c, AsciiString name, AsciiString fname, Int line void dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); @@ -260,9 +317,6 @@ void dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int li void dumpReal(Real r, AsciiString name, AsciiString fname, Int line) { - if (dumped) - return; - if (!(IS_FRAME_OK_TO_LOG)) return; fname.toLower(); fname = getFname(fname); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp index 5e855e2c03..e687854dcd 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp @@ -34,7 +34,7 @@ #include "GameClient/GameText.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -49,6 +49,8 @@ extern Int DX8Wrapper_PreserveFPU; Int TheCRCFirstFrameToLog = -1; UnsignedInt TheCRCLastFrameToLog = 0xffffffff; Bool g_keepCRCSaves = FALSE; +Bool g_saveDebugCRCPerFrame = FALSE; +AsciiString g_saveDebugCRCPerFrameDir; Bool g_crcModuleDataFromLogic = FALSE; Bool g_crcModuleDataFromClient = FALSE; Bool g_verifyClientCRC = FALSE; // verify that GameLogic CRC doesn't change from client @@ -56,7 +58,7 @@ Bool g_clientDeepCRC = FALSE; Bool g_logObjectCRCs = FALSE; #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern Bool g_useStringFile; #endif @@ -161,7 +163,8 @@ Int parseFPUPreserve(char *args[], int argc) return 2; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + //============================================================================= //============================================================================= Int parseUseCSF(char *args[], int) @@ -202,6 +205,7 @@ Int parseNoMilCap(char *args[], int) } return 1; } +#endif // RTS_DEBUG || RTS_INTERNAL //============================================================================= //============================================================================= @@ -239,6 +243,22 @@ Int parseKeepCRCSave(char *args[], int argc) return 1; } +//============================================================================= +//============================================================================= +Int parseSaveDebugCRCPerFrame(char* args[], int argc) +{ +#ifdef DEBUG_CRC + if (argc > 1) + { + g_saveDebugCRCPerFrame = TRUE; + g_saveDebugCRCPerFrameDir = args[1]; + if (TheCRCFirstFrameToLog == -1) + TheCRCFirstFrameToLog = 0; + } +#endif + return 2; +} + //============================================================================= //============================================================================= Int parseCRCLogicModuleData(char *args[], int argc) @@ -328,6 +348,8 @@ Int parseNoDraw(char *args[], int argc) return 1; } +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + //============================================================================= //============================================================================= Int parseLogToConsole(char *args[], int) @@ -338,7 +360,7 @@ Int parseLogToConsole(char *args[], int) return 1; } -#endif // _DEBUG || _INTERNAL +#endif // RTS_DEBUG || RTS_INTERNAL //============================================================================= //============================================================================= @@ -414,7 +436,7 @@ Int parseYRes(char *args[], int num) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= //============================================================================= Int parseLatencyAverage(char *args[], int num) @@ -597,7 +619,7 @@ Int parseMunkee(char *args[], int) } return 1; } -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseScriptDebug(char *args[], int) { @@ -631,7 +653,7 @@ Int parseBuildMapCache(char *args[], int) } -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) Int parsePreload( char *args[], int num ) { if( TheWritableGlobalData ) @@ -641,7 +663,7 @@ Int parsePreload( char *args[], int num ) #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseDisplayDebug(char *args[], int) { if (TheWritableGlobalData) @@ -693,7 +715,7 @@ Int parseVTune ( char *args[], int num ) } /// end stuff for VTUNE -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= //============================================================================= @@ -707,7 +729,7 @@ Int parseNoFX(char *args[], int) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseNoShroud(char *args[], int) { if (TheWritableGlobalData) @@ -736,7 +758,7 @@ Int parseNoMoveCamera(char *args[], int) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseNoCinematic(char *args[], int) { if (TheWritableGlobalData) @@ -777,7 +799,7 @@ Int parseNoShaders(char *args[], int) return 1; } -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) Int parseNoLogo(char *args[], int) { if (TheWritableGlobalData) @@ -828,7 +850,7 @@ Int parseWinCursors(char *args[], int num) Int parseQuickStart( char *args[], int num ) { -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) parseNoLogo( args, num ); #else //Kris: Patch 1.01 -- Allow release builds to skip the sizzle video, but still force the EA logo to show up. @@ -849,7 +871,7 @@ Int parseConstantDebug( char *args[], int num ) return 1; } -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) Int parseExtraLogging( char *args[], int num ) { if (TheWritableGlobalData) @@ -882,7 +904,7 @@ Int parseShowTeamDot( char *args[], int num ) } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseSelectAll( char *args[], int num ) { if( TheWritableGlobalData ) @@ -950,7 +972,7 @@ Int parseDemoLoadScreen(char *args[], int num) return 1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseSaveStats(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -962,7 +984,7 @@ Int parseSaveStats(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseSaveAllStats(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -975,7 +997,7 @@ Int parseSaveAllStats(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseLocalMOTD(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -987,7 +1009,7 @@ Int parseLocalMOTD(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseCameraDebug(char *args[], int num) { if (TheWritableGlobalData) @@ -998,7 +1020,7 @@ Int parseCameraDebug(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int parseBenchmark(char *args[], int num) { if (TheWritableGlobalData && num > 1) @@ -1010,7 +1032,7 @@ Int parseBenchmark(char *args[], int num) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #ifdef DUMP_PERF_STATS Int parseStats(char *args[], int num) { @@ -1183,7 +1205,7 @@ static CommandLineParam params[] = { "-noshaders", parseNoShaders }, { "-quickstart", parseQuickStart }, -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) { "-noaudio", parseNoAudio }, { "-map", parseMapName }, { "-nomusic", parseNoMusic }, @@ -1198,17 +1220,58 @@ static CommandLineParam params[] = { "-localMOTD", parseLocalMOTD }, { "-UseCSF", parseUseCSF }, { "-NoInputDisable", parseNoInputDisable }, +#endif +#ifdef DEBUG_CRC + // TheSuperHackers @info helmutbuhler 04/09/2025 + // The following arguments are useful for CRC debugging. + // Note that you need to have a debug or internal configuration build in order to use this. + // Release configuration also works if RELEASE_DEBUG_LOGGING is defined in Debug.h + // Also note that all players need to play in the same configuration, otherwise mismatch will + // occur almost immediately. + // Try this if you want to play the game and have useful debug information in case mismatch occurs: + // -ignoreAsserts -DebugCRCFromFrame 0 -VerifyClientCRC -LogObjectCRCs -NetCRCInterval 1 + // After mismatch occurs, you can examine the logfile and also reproduce the crc from the replay with this (and diff that with the log): + // -ignoreAsserts -DebugCRCFromFrame xxx -LogObjectCRCs -SaveDebugCRCPerFrame crc + + // After which frame to log crc logging. Call with 0 to log all frames and with -1 to log none (default). { "-DebugCRCFromFrame", parseDebugCRCFromFrame }, + + // Last frame to log { "-DebugCRCUntilFrame", parseDebugCRCUntilFrame }, + + // Save data involving CRC calculation to a binary file. (This isn't that useful.) { "-KeepCRCSaves", parseKeepCRCSave }, + + // TheSuperHackers @feature helmutbuhler 04/09/2025 + // Store CRC Debug Logging into a separate file for each frame. + // Pass the foldername after this where those files are to be stored. + // This is useful for replay analysis. + // Note that the passed folder is deleted if it already exists for every started game. + { "-SaveDebugCRCPerFrame", parseSaveDebugCRCPerFrame }, + { "-CRCLogicModuleData", parseCRCLogicModuleData }, { "-CRCClientModuleData", parseCRCClientModuleData }, - { "-ClientDeepCRC", parseClientDeepCRC }, + + // Verify that Game Logic CRC doesn't change during client update. + // Client update is only for visuals and not supposed to change the crc. + // (This is implemented using CRCVerification class in GameEngine::update) { "-VerifyClientCRC", parseVerifyClientCRC }, + + // Write out binary crc data pre and post client update to "clientPre.crc" and "clientPost.crc" + { "-ClientDeepCRC", parseClientDeepCRC }, + + // Log CRC of Objects and Weapons (See Object::crc and Weapon::crc) { "-LogObjectCRCs", parseLogObjectCRCs }, - { "-saveAllStats", parseSaveAllStats }, + + // Number of frames between each CRC check between all players in multiplayer games + // (if not all crcs are equal, mismatch occurs). { "-NetCRCInterval", parseNetCRCInterval }, + + // Number of frames between each CRC that is written to replay files in singleplayer games. { "-ReplayCRCInterval", parseReplayCRCInterval }, +#endif +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) + { "-saveAllStats", parseSaveAllStats }, { "-noDraw", parseNoDraw }, { "-nomilcap", parseNoMilCap }, { "-nofade", parseNoFade }, @@ -1284,7 +1347,7 @@ static CommandLineParam params[] = //-allAdvice feature //{ "-allAdvice", parseAllAdvice }, -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) { "-preload", parsePreload }, #endif diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Dict.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Dict.cpp index 94d87f9453..a8985d5086 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Dict.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Dict.cpp @@ -107,7 +107,7 @@ void Dict::DictPair::setNameAndType(NameKeyType key, Dict::DataType type) } // ----------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void Dict::validate() const { if (!m_data) return; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp index afd0e0c42a..9e79d39979 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp @@ -108,7 +108,7 @@ #include "Common/version.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -258,9 +258,9 @@ void GameEngine::init( int argc, char *argv[] ) if (TheVersion) { DEBUG_LOG(("================================================================================\n")); - #if defined _DEBUG + #if defined RTS_DEBUG const char *buildType = "Debug"; - #elif defined _INTERNAL + #elif defined RTS_INTERNAL const char *buildType = "Internal"; #else const char *buildType = "Release"; @@ -372,7 +372,7 @@ void GameEngine::init( int argc, char *argv[] ) - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // If we're in Debug or Internal, load the Debug info as well. ini.load( AsciiString( "Data\\INI\\GameDataDebug.ini" ), INI_LOAD_OVERWRITE, NULL ); #endif @@ -524,7 +524,7 @@ void GameEngine::init( int argc, char *argv[] ) fname.format("Data\\%s\\CommandMap.ini", GetRegistryLanguage().str()); initSubsystem(TheMetaMap,"TheMetaMap", MSGNEW("GameEngineSubsystem") MetaMap(), NULL, fname.str(), "Data\\INI\\CommandMap.ini"); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ini.load("Data\\INI\\CommandMapDebug.ini", INI_LOAD_MULTIFILE, NULL); #endif @@ -575,33 +575,6 @@ void GameEngine::init( int argc, char *argv[] ) // load music dialog will still cause the game to quit. // m_quitting = FALSE; - // for fingerprinting, we need to ensure the presence of these files - - -#if !defined(_INTERNAL) && !defined(_DEBUG) - AsciiString dirName; - dirName = TheArchiveFileSystem->getArchiveFilenameForFile("generalsbzh.sec"); - - if (dirName.compareNoCase("genseczh.big") != 0) - { - DEBUG_LOG(("generalsbzh.sec was not found in genseczh.big - it was in '%s'\n", dirName.str())); - m_quitting = TRUE; - } - - dirName = TheArchiveFileSystem->getArchiveFilenameForFile("generalsazh.sec"); - const char *noPath = dirName.reverseFind('\\'); - if (noPath) { - dirName = noPath + 1; - } - - if (dirName.compareNoCase("musiczh.big") != 0) - { - DEBUG_LOG(("generalsazh.sec was not found in musiczh.big - it was in '%s'\n", dirName.str())); - m_quitting = TRUE; - } -#endif - - // initialize the MapCache TheMapCache = MSGNEW("GameEngineSubsystem") MapCache; TheMapCache->updateCache(); @@ -790,7 +763,7 @@ void GameEngine::execute( void ) { DWORD prevTime = timeGetTime(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DWORD startTime = timeGetTime() / 1000; #endif @@ -807,7 +780,7 @@ void GameEngine::execute( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) { // enter only if in benchmark mode if (TheGlobalData->m_benchmarkTimer > 0) @@ -865,7 +838,7 @@ void GameEngine::execute( void ) // I'm disabling this in internal because many people need alt-tab capability. If you happen to be // doing performance tuning, please just change this on your local system. -MDC - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ::Sleep(1); // give everyone else a tiny time slice. #endif diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp index fcc5765b06..725c75fc8e 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp @@ -41,7 +41,7 @@ #define DEFINE_PARTICLE_SYSTEM_NAMES #include "GameClient/ParticleSys.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp index fa65dc5407..7858544a4b 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp @@ -53,6 +53,7 @@ #include "GameClient/Color.h" #include "GameClient/TerrainVisual.h" +#include "GameClient/TintStatus.h" #include "GameNetwork/FirewallHelper.h" @@ -62,6 +63,24 @@ GlobalData* TheWritableGlobalData = NULL; ///< The global data singleton //------------------------------------------------------------------------------------------------- GlobalData* GlobalData::m_theOriginal = NULL; + + +//------------------------------------------------------------------------------------------------- +/*static*/ void GlobalData::parseTintStatusType(INI* ini, void* instance, void* store, const void* userData) +{ + TintStatus tintType = (TintStatus)INI::scanIndexList(ini->getNextToken(), TintStatusFlags::getBitNames()); + + DrawableColorTint* colorTintTypes = (DrawableColorTint*)(store); + DrawableColorTint* tintEntry = &colorTintTypes[tintType]; + + INI::parseRGBColorReal(ini, instance, &tintEntry->color, NULL); + INI::parseRGBColorReal(ini, instance, &tintEntry->colorInfantry, NULL); + + INI::parseUnsignedInt(ini, instance, &tintEntry->attackFrames, NULL); + INI::parseUnsignedInt(ini, instance, &tintEntry->decayFrames, NULL); +} + + /////////////////////////////////////////////////////////////////////////////////////////////////// // PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -488,7 +507,7 @@ GlobalData* GlobalData::m_theOriginal = NULL; { "KeyboardCameraRotateSpeed", INI::parseReal, NULL, offsetof( GlobalData, m_keyboardCameraRotateSpeed ) }, { "PlayStats", INI::parseInt, NULL, offsetof( GlobalData, m_playStats ) }, -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) { "DisableCameraFade", INI::parseBool, NULL, offsetof( GlobalData, m_disableCameraFade ) }, { "DisableScriptedInputDisabling", INI::parseBool, NULL, offsetof( GlobalData, m_disableScriptedInputDisabling ) }, { "DisableMilitaryCaption", INI::parseBool, NULL, offsetof( GlobalData, m_disableMilitaryCaption ) }, @@ -522,11 +541,24 @@ GlobalData* GlobalData::m_theOriginal = NULL; { "ExtraLogging", INI::parseBool, NULL, offsetof( GlobalData, m_extraLogging ) }, #endif + { "UseVanillaDiagonalMoveSpeed", INI::parseBool, NULL, offsetof(GlobalData, m_useOldMoveSpeed) }, + { "TintStatus", GlobalData::parseTintStatusType, NULL, offsetof(GlobalData, m_colorTintTypes) }, { NULL, NULL, NULL, 0 } // keep this last }; + +// Helper function +/*static*/ void GlobalData::setColorTintEntry(DrawableColorTint* arr, int index, RGBColor color, RGBColor colorInfantry, UnsignedInt attackFrames, UnsignedInt decayFrames) +{ + arr[index].color = color; + arr[index].colorInfantry = colorInfantry; + arr[index].attackFrames = attackFrames; + arr[index].decayFrames = decayFrames; +} + + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- GlobalData::GlobalData() @@ -543,12 +575,12 @@ GlobalData::GlobalData() m_theOriginal = this; m_next = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) m_specialPowerUsesDelay = TRUE; #endif m_TiVOFastMode = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_wireframe = 0; m_stateMachineDebug = FALSE; m_useCameraConstraints = TRUE; @@ -1089,6 +1121,36 @@ GlobalData::GlobalData() m_clientRetaliationModeEnabled = TRUE; //On by default. + m_useOldMoveSpeed = FALSE; //Fix is enabled by default + + // -------------------------------------------------------------------------- + // INIT TINT STATUS TYPES: + + //old consts for reference. Do not use this outside initialization here. + // const RGBColor SICKLY_GREEN_POISONED_COLOR = {-1.0f, 1.0f, -1.0f}; + const RGBColor DARK_GRAY_DISABLED_COLOR = {-0.5f, -0.5f, -0.5f}; + // const RGBColor RED_IRRADIATED_COLOR = { 1.0f, -1.0f, -1.0f}; + const RGBColor SUBDUAL_DAMAGE_COLOR = {-0.2f, -0.2f, 0.8f}; + const RGBColor FRENZY_COLOR = { 0.2f, -0.2f, -0.2f}; + const RGBColor FRENZY_COLOR_INFANTRY = { 0.0f, -0.7f, -0.7f}; + + setColorTintEntry(m_colorTintTypes, TINT_STATUS_DISABLED, DARK_GRAY_DISABLED_COLOR, DARK_GRAY_DISABLED_COLOR, 30, 30 ); + // setColorTintEntry(m_colorTintTypes, TINT_STATUS_IRRADIATED, RED_IRRADIATED_COLOR, RED_IRRADIATED_COLOR, 30, 30 ); + // setColorTintEntry(m_colorTintTypes, TINT_STATUS_POISONED, SICKLY_GREEN_POISONED_COLOR, SICKLY_GREEN_POISONED_COLOR, 30, 30 ); + setColorTintEntry(m_colorTintTypes, TINT_STATUS_GAINING_SUBDUAL_DAMAGE, SUBDUAL_DAMAGE_COLOR, SUBDUAL_DAMAGE_COLOR, 150, 150 ); + setColorTintEntry(m_colorTintTypes, TINT_STATUS_FRENZY, FRENZY_COLOR, FRENZY_COLOR_INFANTRY, 30, 30); + + + for (i = 0; i < TINT_STATUS_COUNT; i++) { + DrawableColorTint tc = m_colorTintTypes[i]; + + DEBUG_LOG((">> GLOBAL_DATA: m_colorTintTypes[%d] = {(%f, %f, %f), (%f, %f, %f), %d, %d}\n", + i, tc.color.red, tc.color.green, tc.color.blue, tc.colorInfantry.red, tc.colorInfantry.green, tc.colorInfantry.blue, + tc.attackFrames, tc.decayFrames)); + } + // ------------------------------------------------------------------------------ + + } // end GlobalData diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp index 9e89441e2b..10d236cb77 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INI.cpp @@ -30,6 +30,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine #define DEFINE_DEATH_NAMES +#define DEFINE_WEAPONBONUSCONDITION_NAMES #include "Common/INI.h" #include "Common/INIException.h" @@ -59,7 +60,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -86,6 +87,7 @@ static const BlockParse theTypeTable[] = { "AIData", INI::parseAIDataDefinition }, { "Animation", INI::parseAnim2DDefinition }, { "Armor", INI::parseArmorDefinition }, + { "ArmorExtend", INI::parseArmorExtendDefinition }, { "AudioEvent", INI::parseAudioEventDefinition }, { "AudioSettings", INI::parseAudioSettingsDefinition }, { "Bridge", INI::parseTerrainBridgeDefinition }, @@ -122,6 +124,7 @@ static const BlockParse theTypeTable[] = { "Object", INI::parseObjectDefinition }, { "ObjectCreationList", INI::parseObjectCreationListDefinition }, { "ObjectReskin", INI::parseObjectReskinDefinition }, + { "ObjectExtend", INI::parseObjectExtendDefinition }, { "ParticleSystem", INI::parseParticleSystemDefinition }, { "PlayerTemplate", INI::parsePlayerTemplateDefinition }, { "Road", INI::parseTerrainRoadDefinition }, @@ -711,6 +714,40 @@ void INI::parseAsciiStringVectorAppend( INI* ini, void * /*instance*/, void *sto } } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +/* static */void INI::parseWeaponBonusVector( INI *ini, void * /*instance*/, void *store, const void *userData ) +{ + WeaponBonusConditionTypeVec* asv = (WeaponBonusConditionTypeVec*)store; + asv->clear(); + for (const char *token = ini->getNextTokenOrNull(); token != NULL; token = ini->getNextTokenOrNull()) + { + if (stricmp(token, "None") == 0) + { + asv->clear(); + return; + } + asv->push_back((WeaponBonusConditionType)INI::scanIndexList(token, TheWeaponBonusNames)); + } +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +/* static */void INI::parseWeaponBonusVectorKeepDefault(INI* ini, void* /*instance*/, void* store, const void* userData) +{ + WeaponBonusConditionTypeVec* asv = (WeaponBonusConditionTypeVec*)store; + // asv->clear(); + for (const char* token = ini->getNextTokenOrNull(); token != NULL; token = ini->getNextTokenOrNull()) + { + if (stricmp(token, "None") == 0) + { + asv->clear(); + return; + } + asv->push_back((WeaponBonusConditionType)INI::scanIndexList(token, TheWeaponBonusNames)); + } +} + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- AsciiString INI::getNextQuotedAsciiString() @@ -996,6 +1033,36 @@ void INI::parseRGBColor( INI* ini, void * /*instance*/, void *store, const void* } + +//------------------------------------------------------------------------------------------------- +/** Parse a color in the form of + * + * RGB_COLOR = R:0.5 G:0.3 B:0.6 + * and store in "RGBColor" structure pointed to by 'store' + * Negative numbers, and values greater 1 are allowed! */ + //------------------------------------------------------------------------------------------------- +void INI::parseRGBColorReal(INI* ini, void* /*instance*/, void* store, const void* /*userData*/) +{ + const char* names[3] = { "R", "G", "B" }; + Real colors[3]; + for (Int i = 0; i < 3; i++) + { + colors[i] = scanReal(ini->getNextSubToken(names[i])); + //if (colors[i] < -255) + // throw INI_INVALID_DATA; + //if (colors[i] > 255) + // throw INI_INVALID_DATA; + } + + // assign the color components to the "RGBColor" pointer at 'store' + RGBColor* theColor = (RGBColor*)store; + theColor->red = colors[0]; + theColor->green = colors[1]; + theColor->blue = colors[2]; + +} + + //------------------------------------------------------------------------------------------------- /** Parse a color in the form of * @@ -1435,6 +1502,22 @@ void INI::parseLookupList( INI* ini, void * /*instance*/, void *store, const voi *(Int *)store = scanLookupList(ini->getNextToken(), lookupList); } +//------------------------------------------------------------------------------------------------- +/** Special Handling for None = -2 (Eva_NONE), otherwise like parseIndexList **/ +//------------------------------------------------------------------------------------------------- +void INI::parseEvaNameIndexList(INI* ini, void* /*instance*/, void* store, const void* userData) +{ + const char* token = ini->getNextToken(); + if (stricmp(token, "None") == 0) { + *(Int*)store = -2; + } + else { + //like parseIndexList + ConstCharPtrArray nameList = (ConstCharPtrArray)userData; + *(Int*)store = scanIndexList(token, nameList); + } +} + /////////////////////////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMapCache.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMapCache.cpp index 8c0f376ff8..1cad0961cf 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMapCache.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIMapCache.cpp @@ -39,7 +39,7 @@ #include "Common/WellKnownKeys.h" #include "Common/QuotedPrintable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIObject.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIObject.cpp index d6d6f5c795..d3e68b2023 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIObject.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIObject.cpp @@ -58,4 +58,14 @@ void INI::parseObjectReskinDefinition( INI* ini ) ThingFactory::parseObjectDefinition(ini, name, reskinFrom); } +//------------------------------------------------------------------------------------------------- +/** Parse Object with extends entry */ +//------------------------------------------------------------------------------------------------- +void INI::parseObjectExtendDefinition(INI* ini) +{ + AsciiString name = ini->getNextToken(); + AsciiString extendFrom = ini->getNextToken(); + ThingFactory::parseObjectExtendDefinition(ini, name, extendFrom); +} + diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp index 09fd9d2e90..b529e9e844 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INIWebpageURL.cpp @@ -34,7 +34,7 @@ #include "Common/Registry.h" #include "GameNetwork/WOLBrowser/WebBrowser.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp b/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp index fc2c79dc6c..692195a75e 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/MessageStream.cpp @@ -42,7 +42,7 @@ CommandList *TheCommandList = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -347,7 +347,7 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_META_CHAT_EVERYONE) CHECK_IF(MSG_META_DIPLOMACY) CHECK_IF(MSG_META_OPTIONS) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CHECK_IF(MSG_META_HELP) #endif CHECK_IF(MSG_META_TOGGLE_LOWER_DETAILS) @@ -405,7 +405,7 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_META_TOGGLE_FAST_FORWARD_REPLAY) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CHECK_IF(MSG_META_DEMO_TOGGLE_BEHIND_BUILDINGS) CHECK_IF(MSG_META_DEMO_TOGGLE_LETTERBOX) CHECK_IF(MSG_META_DEMO_TOGGLE_MESSAGE_TEXT) @@ -518,12 +518,12 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_META_DEBUG_SLEEPY_UPDATE_PERFORMANCE) CHECK_IF(MSG_META_DEBUG_WIN) CHECK_IF(MSG_META_DEMO_TOGGLE_DEBUG_STATS) -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) CHECK_IF(MSG_META_DEMO_TOGGLE_AUDIODEBUG) -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS CHECK_IF(MSG_META_DEMO_PERFORM_STATISTICAL_DUMP) #endif//DUMP_PERF_STATS @@ -666,7 +666,7 @@ AsciiString GameMessage::getCommandTypeAsAsciiString(GameMessage::Type t) CHECK_IF(MSG_SELF_DESTRUCT) CHECK_IF(MSG_CREATE_FORMATION) CHECK_IF(MSG_LOGIC_CRC) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CHECK_IF(MSG_DEBUG_KILL_SELECTION) CHECK_IF(MSG_DEBUG_HURT_OBJECT) CHECK_IF(MSG_DEBUG_KILL_OBJECT) @@ -999,7 +999,7 @@ void MessageStream::removeTranslator( TranslatorID id ) // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool isInvalidDebugCommand( GameMessage::Type t ) { @@ -1087,7 +1087,7 @@ void MessageStream::propagateMessages( void ) for( msg=m_firstMessage; msg; msg=next ) { if (ss->m_translator -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) && !isInvalidDebugCommand(msg->getType()) #endif ) diff --git a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp index 9488b5bf0d..c171f6bbda 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/NameKeyGenerator.cpp @@ -145,7 +145,7 @@ NameKeyType NameKeyGenerator::nameToKey(const char* nameString) NameKeyType result = b->m_key; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // reality-check to be sure our hasher isn't going bad. const Int maxThresh = 3; Int numOverThresh = 0; @@ -193,7 +193,7 @@ NameKeyType NameKeyGenerator::nameToLowercaseKey(const char* nameString) NameKeyType result = b->m_key; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // reality-check to be sure our hasher isn't going bad. const Int maxThresh = 3; Int numOverThresh = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp index 0d4fcec12f..2888170991 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp @@ -40,7 +40,7 @@ __forceinline void ProfileGetTime(__int64 &t) t = _rdtsc(); } -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -597,7 +597,7 @@ void PerfTimer::outputInfo( void ) return; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) double totalTimeInMS = 1000.0 * m_runningTime / s_ticksPerSec; double avgTimePerFrame = totalTimeInMS / (m_lastFrame - m_startFrame + 1); double avgTimePerCall = totalTimeInMS / m_callCount; @@ -635,7 +635,7 @@ void PerfTimer::outputInfo( void ) //------------------------------------------------------------------------------------------------- void PerfTimer::showMetrics( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) double totalTimeInMS = 1000.0 * m_runningTime / s_ticksPerSec; double avgTimePerFrame = totalTimeInMS / (m_lastFrame - m_startFrame + 1); double avgTimePerCall = totalTimeInMS / m_callCount; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp index a355425300..693e54666d 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/AcademyStats.cpp @@ -62,7 +62,7 @@ #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp index eb27ba747f..db8f2d3189 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp @@ -64,7 +64,7 @@ #include "GameLogic/ExperienceTracker.h"//LORENZEN -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1471,6 +1471,16 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 SpecialPowerModuleInterface *mod = obj->getSpecialPowerModule( spTemplate ); if( mod ) { + + //use a behaviortype for custom sp + SpecialPowerType behaviorType = spTemplate->getSpecialPowerType(); + if (behaviorType >= SPECIAL_ION_CANNON) { //first custom SP + behaviorType = spTemplate->getSpecialPowerBehaviorType(); + if (behaviorType == SPECIAL_INVALID) { + behaviorType == SPECIAL_NEUTRON_MISSILE; // Default to behave like neutron missile, common behavior + } + } + if (checkSourceRequirements) { if( mod->getPercentReady() < 1.0f ) @@ -1481,7 +1491,7 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 } // First check terrain type, if it is cared about. Don't return a true, since there are more checks. - switch( spTemplate->getSpecialPowerType() ) + switch(behaviorType) { case SPECIAL_PARADROP_AMERICA: case INFA_SPECIAL_PARADROP_AMERICA: @@ -1494,7 +1504,7 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 } // Last check is shroudedness, if it is cared about - switch( spTemplate->getSpecialPowerType() ) + switch(behaviorType) { case SPECIAL_DAISY_CUTTER: case AIRF_SPECIAL_DAISY_CUTTER: @@ -1609,11 +1619,21 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * } } + + //use a behaviortype for custom sp + SpecialPowerType behaviorType = spTemplate->getSpecialPowerType(); + if (behaviorType >= SPECIAL_ION_CANNON) { //first custom SP + behaviorType = spTemplate->getSpecialPowerBehaviorType(); + if (behaviorType == SPECIAL_INVALID) { + behaviorType == SPECIAL_NEUTRON_MISSILE; // Default to behave like neutron missile, common behavior + } + } + // if the target is in the shroud, we can't do anything if (isObjectShroudedForAction(obj, target, commandSource)) return FALSE; - switch( spTemplate->getSpecialPowerType() ) + switch(behaviorType) { case SPECIAL_CASH_BOUNTY: return false; @@ -1812,11 +1832,11 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * //We also don't want to allow a unit that can place timed charges on a building to be able to place //remote charges (or vice-versa). So we're going to look for the other special ability update and //reject if the other one has it planted... - if( spTemplate->getSpecialPowerType() == SPECIAL_REMOTE_CHARGES ) + if( behaviorType == SPECIAL_REMOTE_CHARGES ) { spUpdate = obj->findSpecialAbilityUpdate( SPECIAL_TIMED_CHARGES ); } - else if( spTemplate->getSpecialPowerType() == SPECIAL_TIMED_CHARGES ) + else if( behaviorType == SPECIAL_TIMED_CHARGES ) { spUpdate = obj->findSpecialAbilityUpdate( SPECIAL_REMOTE_CHARGES ); } @@ -1864,7 +1884,16 @@ Bool ActionManager::canDoSpecialPower( const Object *obj, const SpecialPowerTemp } } - switch( spTemplate->getSpecialPowerType() ) + //use a behaviortype for custom sp + SpecialPowerType behaviorType = spTemplate->getSpecialPowerType(); + if (behaviorType >= SPECIAL_ION_CANNON) { //first custom SP + behaviorType = spTemplate->getSpecialPowerBehaviorType(); + if (behaviorType == SPECIAL_INVALID) { + behaviorType == SPECIAL_NEUTRON_MISSILE; // Default to behave like neutron missile, common behavior + } + } + + switch( behaviorType ) { case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: case SPECIAL_TANKHUNTER_TNT_ATTACK: diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp index 53ec362923..4b2eb27110 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp @@ -53,7 +53,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp index f77407cc36..1861869fa1 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -101,7 +101,7 @@ #include "GameNetwork/GameInfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -431,12 +431,12 @@ void Player::init(const PlayerTemplate* pt) m_unitsShouldHunt = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_DEMO_ignorePrereqs = FALSE; m_DEMO_freeBuild = FALSE; #endif -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) m_DEMO_instantBuild = FALSE; #endif @@ -516,6 +516,15 @@ void Player::init(const PlayerTemplate* pt) tof->deleteInstance(); } + it = m_kindOfPercentProductionTimeChangeList.begin(); + while (it != m_kindOfPercentProductionTimeChangeList.end()) + { + KindOfPercentProductionChange* tof = *it; + it = m_kindOfPercentProductionTimeChangeList.erase(it); + if (tof) + tof->deleteInstance(); + } + getAcademyStats()->init( this ); //Always off at the beginning of a game! Only GameLogic::update has @@ -1292,7 +1301,7 @@ static void doFindSpecialPowerSourceObject( Object *obj, void *userData ) { UnsignedInt readyFrame = spmInterface->getReadyFrame(); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) // Everything is ready if timers are debug off'd if( ! TheGlobalData->m_specialPowerUsesDelay ) readyFrame = 0; @@ -1349,7 +1358,7 @@ static void doCountSpecialPowersReady( Object *obj, void *userData ) UnsignedInt readyFrame = spmInterface->getReadyFrame(); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) // Everything is ready if timers are debug off'd if( ! TheGlobalData->m_specialPowerUsesDelay ) readyFrame = 0; @@ -1652,6 +1661,10 @@ void Player::preTeamDestroy( const Team *team ) // ai notification callback if( m_ai ) m_ai->aiPreTeamDestroy( team ); + + // TheSuperHackers @bugfix Mauller/Xezon 03/05/2025 Clear the default team to prevent dangling pointer usage + if( m_defaultTeam == team ) + m_defaultTeam = NULL; } // preTeamDestroy //------------------------------------------------------------------------------------------------- @@ -1662,10 +1675,26 @@ void Player::onStructureCreated( Object *builder, Object *structure ) } // end onStructureCreated + +const SpecialPowerTemplate* findSpecialPowerWithEvaDetected(const Object* structure) { + for (BehaviorModule** m = structure->getBehaviorModules(); *m; ++m) + { + SpecialPowerModuleInterface* sp = (*m)->getSpecialPower(); + if (!sp) + continue; + + if (sp->getSpecialPowerTemplate()->getEvaDetectedEnemy() > EVA_FIRST || sp->getSpecialPowerTemplate()->getEvaDetectedAlly() > EVA_FIRST || sp->getSpecialPowerTemplate()->getEvaDetectedOwn() > EVA_FIRST) { + //Specialpower has an eva, return + return sp->getSpecialPowerTemplate(); + } + } + return NULL; +} + //------------------------------------------------------------------------------------------------- /// a structure that was under construction has become completed //------------------------------------------------------------------------------------------------- -void Player::onStructureConstructionComplete( Object *builder, Object *structure, Bool isRebuild ) +void Player::onStructureConstructionComplete(Object* builder, Object* structure, Bool isRebuild) { // When a a structure is completed, it becomes "real" as far as scripting is // concerned. jba. @@ -1685,70 +1714,99 @@ void Player::onStructureConstructionComplete( Object *builder, Object *structure structure->friend_adjustPowerForPlayer(TRUE); // ai notification callback - if( m_ai ) - m_ai->onStructureProduced( builder, structure ); + if (m_ai) + m_ai->onStructureProduced(builder, structure); // the GUI needs to re-evaluate the information being displayed to the user now - if( TheControlBar ) + if (TheControlBar) TheControlBar->markUIDirty(); - + // This object may require us to play some EVA sounds. - Player *localPlayer = ThePlayerList->getLocalPlayer(); + Player* localPlayer = ThePlayerList->getLocalPlayer(); - if( structure->hasSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON ) || - structure->hasSpecialPower( SUPW_SPECIAL_PARTICLE_UPLINK_CANNON ) || - structure->hasSpecialPower( LAZR_SPECIAL_PARTICLE_UPLINK_CANNON ) ) - { - if ( localPlayer == structure->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ParticleCannon); - } - else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) - { - // Note: treating NEUTRAL as ally. Is this correct? - TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ParticleCannon); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ParticleCannon); - } - } + //Check if structure has a specialPower with new custom eva sounds + const SpecialPowerTemplate* specialPowerTemp = findSpecialPowerWithEvaDetected(structure); + if (specialPowerTemp != NULL) { + // Check if SpecialPower eva event instead of hardcoded stuff + bool isOwn = localPlayer == structure->getControllingPlayer(); + bool isAlly = localPlayer->getRelationship(structure->getTeam()) != ENEMIES; + bool isEnemy = !isOwn && !isAlly; - if( structure->hasSpecialPower( SPECIAL_NEUTRON_MISSILE ) || - structure->hasSpecialPower( NUKE_SPECIAL_NEUTRON_MISSILE ) || - structure->hasSpecialPower( SUPW_SPECIAL_NEUTRON_MISSILE ) ) - { - if ( localPlayer == structure->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_Nuke); - } - else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) - { - // Note: treating NEUTRAL as ally. Is this correct? - TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_Nuke); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_Nuke); - } - } - - if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) - { - if ( localPlayer == structure->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ScudStorm); - } - else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) - { - // Note: treating NEUTRAL as ally. Is this correct? - TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ScudStorm); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ScudStorm); - } - } + //Check SpecialPower Eva + EvaMessage eva = EVA_Invalid; + + if (isOwn) { + eva = specialPowerTemp->getEvaDetectedOwn(); + } + else if (isAlly) { + eva = specialPowerTemp->getEvaDetectedAlly(); + } + else if (isEnemy) { + eva = specialPowerTemp->getEvaDetectedEnemy(); + } + + if (eva > EVA_FIRST) { + TheEva->setShouldPlay(eva); + } + + } + else { + //Do default hardcoded check + if (structure->hasSpecialPower(SPECIAL_PARTICLE_UPLINK_CANNON) || + structure->hasSpecialPower(SUPW_SPECIAL_PARTICLE_UPLINK_CANNON) || + structure->hasSpecialPower(LAZR_SPECIAL_PARTICLE_UPLINK_CANNON)) + { + if (localPlayer == structure->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ParticleCannon); + } + else if (localPlayer->getRelationship(structure->getTeam()) != ENEMIES) + { + // Note: treating NEUTRAL as ally. Is this correct? + TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ParticleCannon); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ParticleCannon); + } + } + + if (structure->hasSpecialPower(SPECIAL_NEUTRON_MISSILE) || + structure->hasSpecialPower(NUKE_SPECIAL_NEUTRON_MISSILE) || + structure->hasSpecialPower(SUPW_SPECIAL_NEUTRON_MISSILE)) + { + if (localPlayer == structure->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_Nuke); + } + else if (localPlayer->getRelationship(structure->getTeam()) != ENEMIES) + { + // Note: treating NEUTRAL as ally. Is this correct? + TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_Nuke); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_Nuke); + } + } + + if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) + { + if (localPlayer == structure->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ScudStorm); + } + else if (localPlayer->getRelationship(structure->getTeam()) != ENEMIES) + { + // Note: treating NEUTRAL as ally. Is this correct? + TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ScudStorm); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ScudStorm); + } + } + } } // end onStructureConstructionComplete //============================================================================= @@ -2502,7 +2560,15 @@ Bool Player::addSkillPointsForKill(const Object* killer, const Object* victim) return false; Int victimLevel = victim->getVeterancyLevel(); + Int skillValue = victim->getTemplate()->getSkillPointValue(victimLevel); + + //New: We can now upgrade XP value, so we check the XP tracker for a scalar + const ExperienceTracker* xpTracker = victim->getExperienceTracker(); + if (xpTracker) + { + skillValue *= xpTracker->getExperienceValueScalar(); + } return addSkillPoints(skillValue); } @@ -2939,7 +3005,7 @@ Bool Player::canBuild(const ThingTemplate *tmplate) const prereqsOK = false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (ignoresPrereqs()) prereqsOK = true; #endif @@ -3891,6 +3957,78 @@ Real Player::getProductionCostChangeBasedOnKindOf( KindOfMaskType kindOf ) const return (start); } +//------------------------------------------------------------------------------------------------- +/** addKindOfProductionTimeChange adds a production change to the typeof list */ +//------------------------------------------------------------------------------------------------- +void Player::addKindOfProductionTimeChange(KindOfMaskType kindOf, Real percent) +{ + KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionTimeChangeList.begin(); + while (it != m_kindOfPercentProductionTimeChangeList.end()) + { + + KindOfPercentProductionChange* tof = *it; + if (tof->m_percent == percent && tof->m_kindOf == kindOf) + { + tof->m_ref++; + return; + } + ++it; + } + + KindOfPercentProductionChange* newTof = newInstance(KindOfPercentProductionChange); + newTof->m_kindOf = kindOf; + newTof->m_percent = percent; + newTof->m_ref = 1; + m_kindOfPercentProductionTimeChangeList.push_back(newTof); + +} + +//------------------------------------------------------------------------------------------------- +/** removeKindOfProductionTimeChange adds a production change to the typeof list */ +//------------------------------------------------------------------------------------------------- +void Player::removeKindOfProductionTimeChange(KindOfMaskType kindOf, Real percent) +{ + KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionTimeChangeList.begin(); + while (it != m_kindOfPercentProductionTimeChangeList.end()) + { + + KindOfPercentProductionChange* tof = *it; + if (tof->m_percent == percent && tof->m_kindOf == kindOf) + { + tof->m_ref--; + if (tof->m_ref == 0) + { + m_kindOfPercentProductionTimeChangeList.erase(it); + if (tof) + tof->deleteInstance(); + } + return; + } + ++it; + } + DEBUG_ASSERTCRASH(FALSE, ("removeKindOfProductionTimeChange was called with kindOf=%d and percent=%f. We could not find the entry in the list with these variables. CLH.", kindOf, percent)); +} + +//------------------------------------------------------------------------------------------------- +/** getProductionTimeChangeBasedOnKindOf gets the time percentage change based off of Kindof Mask */ +//------------------------------------------------------------------------------------------------- +Real Player::getProductionTimeChangeBasedOnKindOf(KindOfMaskType kindOf) const +{ + Real start = 1.0f; + KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionTimeChangeList.begin(); + while (it != m_kindOfPercentProductionTimeChangeList.end()) + { + + KindOfPercentProductionChange* tof = *it; + if (TEST_KINDOFMASK_MULTI(kindOf, tof->m_kindOf, KINDOFMASK_NONE)) + { + start *= (1 + tof->m_percent); + } + ++it; + } + return (start); +} + //------------------------------------------------------------------------------------------------- /** setAttackedBy */ //------------------------------------------------------------------------------------------------- @@ -4358,7 +4496,7 @@ void Player::xfer( Xfer *xfer ) // score keeper xfer->xferSnapshot( &m_scoreKeeper ); - // size of and data for kindof percent production change list + // size of and data for kindof percent production COST change list UnsignedShort percentProductionChangeCount = m_kindOfPercentProductionChangeList.size(); xfer->xferUnsignedShort( &percentProductionChangeCount ); KindOfPercentProductionChange *entry; @@ -4418,6 +4556,66 @@ void Player::xfer( Xfer *xfer ) } // end else, load + // size of and data for kindof percent production TIME change list + UnsignedShort percentProductionTimeChangeCount = m_kindOfPercentProductionTimeChangeList.size(); + xfer->xferUnsignedShort(&percentProductionTimeChangeCount); + entry = NULL; + if (xfer->getXferMode() == XFER_SAVE) + { + KindOfPercentProductionChangeListIt it; + + // save each item + for (it = m_kindOfPercentProductionTimeChangeList.begin(); + it != m_kindOfPercentProductionTimeChangeList.end(); + ++it) + { + + // get entry data + entry = *it; + + // kind of mask type + entry->m_kindOf.xfer(xfer); + + // percent + xfer->xferReal(&entry->m_percent); + + // ref + xfer->xferUnsignedInt(&entry->m_ref); + + } // end for + + } // end if, save + else + { + + // sanity, list must be empty right now + if (m_kindOfPercentProductionTimeChangeList.size() != 0) + { + + DEBUG_CRASH(("Player::xfer - m_kindOfPercentProductionTimeChangeList should be empty but is not\n")); + throw SC_INVALID_DATA; + + } // end if + + // read each entry + for (UnsignedInt i = 0; i < percentProductionTimeChangeCount; ++i) + { + + // allocate new entry + entry = newInstance(KindOfPercentProductionChange); + + // read data + entry->m_kindOf.xfer(xfer); + xfer->xferReal(&entry->m_percent); + xfer->xferUnsignedInt(&entry->m_ref); + + // put at end of list + m_kindOfPercentProductionTimeChangeList.push_back(entry); + + } // end for i + + } // end else, load + diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerList.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerList.cpp index 1aedae13c2..365d18d862 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerList.cpp @@ -54,13 +54,13 @@ #include "Common/Team.h" #include "Common/WellKnownKeys.h" #include "Common/Xfer.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #include "GameLogic/Object.h" #endif #include "GameLogic/SidesList.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp index efc8dc729d..14f18ef9b7 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp @@ -53,7 +53,7 @@ #include "Common/Science.h" #include "GameClient/Image.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -333,12 +333,12 @@ const PlayerTemplate* PlayerTemplateStore::findPlayerTemplate(NameKeyType nameke namekey = g0; // end ugly, hokey code to quietly load old maps... - #ifdef _DEBUG + #ifdef RTS_DEBUG AsciiString nn = KEYNAME(namekey); #endif for (PlayerTemplateVector::const_iterator it = m_playerTemplates.begin(); it != m_playerTemplates.end(); ++it) { - #ifdef _DEBUG + #ifdef RTS_DEBUG AsciiString n = KEYNAME((*it).getNameKey()); #endif if ((*it).getNameKey() == namekey) diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index 95fe341369..c2606e4130 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -52,7 +52,7 @@ #include "GameClient/Drawable.h" #include "GameClient/GameText.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp index 084275c9c3..1d13b91d1a 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp @@ -35,7 +35,7 @@ ScienceStore* TheScienceStore = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp index 53a59a0c93..33bedf7594 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp @@ -37,7 +37,7 @@ #include "GameLogic/Object.h" #include "Common/BitFlagsIO.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -133,6 +133,15 @@ const char* SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_BATTLESHIP_BOMBARDMENT", + //new constants by OFS + "SPECIAL_ION_CANNON", + "SPECIAL_CLUSTER_MISSILE", + "SPECIAL_SUNSTORM_MISSILE", + "SPECIAL_METEOR_STRIKE", + "SPECIAL_PUNISHER_CANNON", + "SPECIAL_CHEMICAL_MISSILE", + "SPECIAL_CHRONOSPHERE", + NULL }; @@ -207,6 +216,17 @@ void SpecialPowerStore::parseSpecialPowerDefinition( INI *ini ) { "RadiusCursorRadius", INI::parseReal, NULL, offsetof( SpecialPowerTemplate, m_radiusCursorRadius ) }, { "ShortcutPower", INI::parseBool, NULL, offsetof( SpecialPowerTemplate, m_shortcutPower ) }, { "AcademyClassify", INI::parseIndexList, TheAcademyClassificationTypeNames, offsetof( SpecialPowerTemplate, m_academyClassificationType ) }, + { "BehaviorEnum", INI::parseIndexList, SpecialPowerMaskType::getBitNames(), offsetof(SpecialPowerTemplate, m_type_behavior) }, + { "EvaDetectedOwn", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_detected_own) }, + { "EvaDetectedAlly", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_detected_ally) }, + { "EvaDetectedEnemy", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_detected_enemy) }, + { "EvaLaunchedOwn", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_launched_own) }, + { "EvaLaunchedAlly", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_launched_ally) }, + { "EvaLaunchedEnemy", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_launched_enemy) }, + { "EvaReadyOwn", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_ready_own) }, + { "EvaReadyAlly", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_ready_ally) }, + { "EvaReadyEnemy", INI::parseEvaNameIndexList, TheEvaMessageNames, offsetof(SpecialPowerTemplate, m_eva_ready_enemy) }, + { NULL, NULL, NULL, 0 } // keep this last }; @@ -226,6 +246,16 @@ SpecialPowerTemplate::SpecialPowerTemplate() m_viewObjectRange = 0; m_radiusCursorRadius = 0; m_shortcutPower = FALSE; + m_type_behavior = SPECIAL_INVALID; + m_eva_detected_own = EVA_Invalid; + m_eva_detected_ally = EVA_Invalid; + m_eva_detected_enemy = EVA_Invalid; + m_eva_launched_own = EVA_Invalid; + m_eva_launched_ally = EVA_Invalid; + m_eva_launched_enemy = EVA_Invalid; + m_eva_ready_own = EVA_Invalid; + m_eva_ready_ally = EVA_Invalid; + m_eva_ready_enemy = EVA_Invalid; } // end SpecialPowerTemplate diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp index d2ce15c424..c79953d229 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp @@ -51,7 +51,7 @@ #include "GameLogic/ScriptActions.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp index 289eb1f10a..eb5f09c6ad 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomValue.cpp @@ -37,7 +37,7 @@ //#define DETERMINISTIC // to allow repetition for debugging -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp index 46ebcaa78e..0959ca9015 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp @@ -30,6 +30,7 @@ #include "Common/Player.h" #include "Common/GlobalData.h" #include "Common/GameEngine.h" +#include "GameClient/ClientInstance.h" #include "GameClient/GameWindow.h" #include "GameClient/GameWindowManager.h" #include "GameClient/InGameUI.h" @@ -45,7 +46,7 @@ #include "Common/CRCDebug.h" #include "Common/version.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -56,10 +57,17 @@ Int REPLAY_CRC_INTERVAL = 100; const char *replayExtention = ".rep"; const char *lastReplayFileName = "00000000"; // a name the user is unlikely to ever type, but won't cause panic & confusion +// TheSuperHackers @tweak helmutbuhler 25/04/2025 +// The replay header contains two time fields; startTime and endTime of type time_t. +// time_t is 32 bit wide on VC6, but on newer compilers it is 64 bit wide. +// In order to remain compatible we need to load and save time values with 32 bits. +// Note that this will overflow on January 18, 2038. @todo Upgrade to 64 bits when we break compatibility. +typedef int32_t replay_time_t; + static time_t startTime; static const UnsignedInt startTimeOffset = 6; -static const UnsignedInt endTimeOffset = startTimeOffset + sizeof(time_t); -static const UnsignedInt framesOffset = endTimeOffset + sizeof(time_t); +static const UnsignedInt endTimeOffset = startTimeOffset + sizeof(replay_time_t); +static const UnsignedInt framesOffset = endTimeOffset + sizeof(replay_time_t); static const UnsignedInt desyncOffset = framesOffset + sizeof(UnsignedInt); static const UnsignedInt quitEarlyOffset = desyncOffset + sizeof(Bool); static const UnsignedInt disconOffset = quitEarlyOffset + sizeof(Bool); @@ -75,7 +83,8 @@ void RecorderClass::logGameStart(AsciiString options) if (!fseek(m_file, startTimeOffset, SEEK_SET)) { // save off start time - fwrite(&startTime, sizeof(time_t), 1, m_file); + replay_time_t tmp = (replay_time_t)startTime; + fwrite(&tmp, sizeof(replay_time_t), 1, m_file); } // move back to end of stream #ifdef DEBUG_CRASHING @@ -84,7 +93,7 @@ void RecorderClass::logGameStart(AsciiString options) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheNetwork && TheGlobalData->m_saveStats) { //if (TheLAN) @@ -145,7 +154,7 @@ void RecorderClass::logPlayerDisconnect(UnicodeString player, Int slot) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { unsigned long bufSize = MAX_COMPUTERNAME_LENGTH + 1; @@ -190,7 +199,7 @@ void RecorderClass::logCRCMismatch( void ) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { m_wasDesync = TRUE; @@ -229,7 +238,8 @@ void RecorderClass::logGameEnd( void ) if (!fseek(m_file, endTimeOffset, SEEK_SET)) { // save off end time - fwrite(&t, sizeof(time_t), 1, m_file); + replay_time_t tmp = (replay_time_t)t; + fwrite(&tmp, sizeof(replay_time_t), 1, m_file); } // move to appropriate offset if (!fseek(m_file, framesOffset, SEEK_SET)) @@ -244,7 +254,7 @@ void RecorderClass::logGameEnd( void ) fseek(m_file, fileSize, SEEK_SET); DEBUG_ASSERTCRASH(res == 0, ("Could not seek to end of file!")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheNetwork && TheGlobalData->m_saveStats) { //if (TheLAN) @@ -273,22 +283,9 @@ void RecorderClass::logGameEnd( void ) #endif } -#ifdef DEBUG_LOGGING - #if defined(_INTERNAL) - #define DEBUG_FILE_NAME "DebugLogFileI.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevI.txt" - #elif defined(_DEBUG) - #define DEBUG_FILE_NAME "DebugLogFileD.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevD.txt" - #else - #define DEBUG_FILE_NAME "DebugLogFile.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrev.txt" - #endif -#endif - void RecorderClass::cleanUpReplayFile( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { char fname[_MAX_PATH+1]; @@ -298,14 +295,19 @@ void RecorderClass::cleanUpReplayFile( void ) AsciiString oldFname; oldFname.format("%s%s", getReplayDir().str(), m_fileName.str()); CopyFile(oldFname.str(), fname, TRUE); -#ifdef DEBUG_FILE_NAME + +#ifdef DEBUG_LOGGING + const char* logFileName = DebugGetLogFileName(); + if (logFileName[0] == '\0') + return; + AsciiString debugFname = fname; debugFname.removeLastChar(); debugFname.removeLastChar(); debugFname.removeLastChar(); debugFname.concat("txt"); UnsignedInt fileSize = 0; - FILE *fp = fopen(DEBUG_FILE_NAME, "rb"); + FILE *fp = fopen(logFileName, "rb"); if (fp) { fseek(fp, 0, SEEK_END); @@ -318,13 +320,13 @@ void RecorderClass::cleanUpReplayFile( void ) const int MAX_DEBUG_SIZE = 65536; if (fileSize <= MAX_DEBUG_SIZE || TheGlobalData->m_saveAllStats) { - DEBUG_LOG(("Using CopyFile to copy %s\n", DEBUG_FILE_NAME)); - CopyFile(DEBUG_FILE_NAME, debugFname.str(), TRUE); + DEBUG_LOG(("Using CopyFile to copy %s\n", logFileName)); + CopyFile(logFileName, debugFname.str(), TRUE); } else { - DEBUG_LOG(("manual copy of %s\n", DEBUG_FILE_NAME)); - FILE *ifp = fopen(DEBUG_FILE_NAME, "rb"); + DEBUG_LOG(("manual copy of %s\n", logFileName)); + FILE *ifp = fopen(logFileName, "rb"); FILE *ofp = fopen(debugFname.str(), "wb"); if (ifp && ofp) { @@ -348,7 +350,7 @@ void RecorderClass::cleanUpReplayFile( void ) ofp = NULL; } } -#endif // DEBUG_FILE_NAME +#endif // DEBUG_LOGGING } #endif } @@ -557,9 +559,9 @@ void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, In // // **** if this changes, change the LAN code above **** // - time_t t = 0; - fwrite(&t, sizeof(time_t), 1, m_file); // reserve space for start time - fwrite(&t, sizeof(time_t), 1, m_file); // reserve space for end time + replay_time_t t = 0; + fwrite(&t, sizeof(replay_time_t), 1, m_file); // reserve space for start time + fwrite(&t, sizeof(replay_time_t), 1, m_file); // reserve space for end time UnsignedInt frames = 0; fwrite(&frames, sizeof(UnsignedInt), 1, m_file); // reserve space for duration in frames @@ -836,8 +838,11 @@ Bool RecorderClass::readReplayHeader(ReplayHeader& header) } // read in some stats - fread(&header.startTime, sizeof(time_t), 1, m_file); - fread(&header.endTime, sizeof(time_t), 1, m_file); + replay_time_t tmp; + fread(&tmp, sizeof(replay_time_t), 1, m_file); + header.startTime = tmp; + fread(&tmp, sizeof(replay_time_t), 1, m_file); + header.endTime = tmp; fread(&header.frameDuration, sizeof(UnsignedInt), 1, m_file); @@ -902,7 +907,7 @@ Bool RecorderClass::readReplayHeader(ReplayHeader& header) return TRUE; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool RecorderClass::analyzeReplay( AsciiString filename ) { m_doingAnalysis = TRUE; @@ -1099,8 +1104,8 @@ Bool RecorderClass::playbackFile(AsciiString filename) { return FALSE; } -#ifdef DEBUG_LOGGING +#ifdef DEBUG_CRASHING Bool versionStringDiff = header.versionString != TheVersion->getUnicodeVersion(); Bool versionTimeStringDiff = header.versionTimeString != TheVersion->getUnicodeBuildTime(); Bool versionNumberDiff = header.versionNumber != TheVersion->getVersionNumber(); @@ -1112,15 +1117,20 @@ Bool RecorderClass::playbackFile(AsciiString filename) AsciiString tempStr; if (exeDifferent) { + // TheSuperHackers @fix helmutbuhler 05/05/2025 No longer attempts to print unicode as ascii + // via a call to AsciiString::format with %ls format. It does not work with non-ascii characters. + UnicodeString tempStrWide; debugString = "EXE is different:\n"; if (versionStringDiff) { - tempStr.format(" Version [%ls] vs [%ls]\n", TheVersion->getUnicodeVersion().str(), header.versionString.str()); + tempStrWide.format(L" Version [%s] vs [%s]\n", TheVersion->getUnicodeVersion().str(), header.versionString.str()); + tempStr.translate(tempStrWide); debugString.concat(tempStr); } if (versionTimeStringDiff) { - tempStr.format(" Build Time [%ls] vs [%ls]\n", TheVersion->getUnicodeBuildTime().str(), header.versionTimeString.str()); + tempStrWide.format(L" Build Time [%s] vs [%s]\n", TheVersion->getUnicodeBuildTime().str(), header.versionTimeString.str()); + tempStr.translate(tempStrWide); debugString.concat(tempStr); } if (versionNumberDiff) @@ -1535,7 +1545,7 @@ AsciiString RecorderClass::getReplayExtention() { */ AsciiString RecorderClass::getLastReplayFileName() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheNetwork && TheGlobalData->m_saveStats) { GameInfo *game = NULL; @@ -1596,7 +1606,17 @@ AsciiString RecorderClass::getLastReplayFileName() } } #endif - return AsciiString(lastReplayFileName); + + AsciiString filename; + if (rts::ClientInstance::getInstanceId() > 1u) + { + filename.format("%s_Instance%.2u", lastReplayFileName, rts::ClientInstance::getInstanceId()); + } + else + { + filename = lastReplayFileName; + } + return filename; } /** diff --git a/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp index cf79a8f029..d98c866f36 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/StateMachine.cpp @@ -37,7 +37,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) @@ -839,7 +839,7 @@ void StateMachine::xfer( Xfer *xfer ) } Bool snapshotAllStates = false; -#ifdef _DEBUG +#ifdef RTS_DEBUG //snapshotAllStates = true; #endif xfer->xferBool(&snapshotAllStates); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp b/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp index 5b52442bcb..646e5b30a1 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/StatsCollector.cpp @@ -108,7 +108,7 @@ void StatsCollector::reset( void ) { // make sure we have a stats Dir. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { AsciiString playtestDir = TheGlobalData->m_baseStatsDir; @@ -254,7 +254,7 @@ void StatsCollector::writeFileEnd( void ) fprintf(f, "===================================================\n"); fprintf(f, "* Times are in Game Seconds which are based off of frames. Current fps is set to %d\n", LOGICFRAMES_PER_SECOND); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_benchmarkTimer > 0) { fprintf(f, "\n*** BENCHMARK MODE STATS ***\n"); @@ -322,7 +322,7 @@ void StatsCollector::createFileName( void ) name.removeLastChar(); // m name.removeLastChar(); // . m_statsFileName.clear(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_saveStats) { m_statsFileName.set(TheGlobalData->m_baseStatsDir); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp index 70c34153a8..c0513d6370 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/ArchiveFileSystem.cpp @@ -51,7 +51,7 @@ #include "Common/AsciiString.h" #include "Common/PerfTimer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp index 3da480fc6d..bae77bb02f 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp @@ -89,7 +89,7 @@ void AsciiString::freeBytes(void) } // ----------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void AsciiString::validate() const { if (!m_data) return; @@ -142,7 +142,7 @@ void AsciiString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveData AsciiStringData* newData = (AsciiStringData*)TheDynamicMemoryAllocator->allocateBytesDoNotZero(actualBytes, "STR_AsciiString::ensureUniqueBufferOfSize"); newData->m_refCount = 1; newData->m_numCharsAllocated = (actualBytes - sizeof(AsciiStringData))/sizeof(char); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) newData->m_debugptr = newData->peek(); // just makes it easier to read in the debugger #endif @@ -284,12 +284,7 @@ void AsciiString::format(const char* format, ...) // ----------------------------------------------------- void AsciiString::format_va(const AsciiString& format, va_list args) { - validate(); - char buf[MAX_FORMAT_BUF_LEN]; - if (_vsnprintf(buf, sizeof(buf)/sizeof(char)-1, format.str(), args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + format_va(format.str(), args); } // ----------------------------------------------------- @@ -297,10 +292,16 @@ void AsciiString::format_va(const char* format, va_list args) { validate(); char buf[MAX_FORMAT_BUF_LEN]; - if (_vsnprintf(buf, sizeof(buf)/sizeof(char)-1, format, args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + const int result = _vsnprintf(buf, sizeof(buf)/sizeof(char)-1, format, args); + if (result >= 0) + { + set(buf); + validate(); + } + else + { + DEBUG_ASSERTCRASH(false, ("AsciiString::format_va failed with code:%d format:\"%s\"", result, format)); + } } // ----------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp index cb8bd1b3e0..bdcd8c8bff 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp @@ -59,7 +59,7 @@ // PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// BuildAssistant *TheBuildAssistant = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/CopyProtection.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/CopyProtection.cpp index 9de7673fbe..3dc61948f2 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/CopyProtection.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/CopyProtection.cpp @@ -50,7 +50,7 @@ static const char* const protectGUID = "7BEB9006-CC19-4aca-913A-C870A88DE01A"; // Generals Protect GUID */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool skipProtection(void) { //return FALSE; @@ -79,7 +79,7 @@ Bool CopyProtect::isLauncherRunning(void) } DEBUG_LOG(("result was %d\n", (int)isRunning)); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (skipProtection()) { DEBUG_LOG(("DevStudio is running - forcing to TRUE\n")); @@ -95,7 +95,7 @@ Bool CopyProtect::notifyLauncher(void) { DEBUG_LOG(("COPYPROTECTION - Notify launcher\n")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (skipProtection()) { DEBUG_LOG(("DevStudio is running - skipping notifyLauncher()\n")); @@ -207,7 +207,7 @@ Bool CopyProtect::validate(void) "Play the \"Command & Conquer: Generals\" Multiplayer Test.") == 0); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (skipProtection()) { DEBUG_LOG(("DevStudio is running - forcing to TRUE\n")); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp index 7ea25e354b..7b2e1c76e3 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp @@ -46,14 +46,23 @@ #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -// USER INCLUDES +// USER INCLUDES + +// TheSuperHackers @feature helmutbuhler 04/10/2025 +// Uncomment this to show normal logging stuff in the crc logging. +// This can be helpful for context, but can also clutter diffs because normal logs aren't necessarily +// deterministic or the same on all peers in multiplayer games. +//#define INCLUDE_DEBUG_LOG_IN_CRC_LOG + #define DEBUG_THREADSAFE #ifdef DEBUG_THREADSAFE #include "Common/CriticalSection.h" #endif #include "Common/Debug.h" +#include "Common/CRCDebug.h" #include "Common/SystemInfo.h" #include "Common/UnicodeString.h" +#include "GameClient/ClientInstance.h" #include "GameClient/GameText.h" #include "GameClient/Keyboard.h" #include "GameClient/Mouse.h" @@ -67,7 +76,7 @@ extern HWND ApplicationHWnd; extern const char *gAppPrefix; /// So WB can have a different log file name. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // this should ALWAYS be present #pragma optimize("", off) #endif @@ -78,15 +87,15 @@ extern const char *gAppPrefix; /// So WB can have a different log file name. #ifdef DEBUG_LOGGING -#if defined(_INTERNAL) - #define DEBUG_FILE_NAME "DebugLogFileI.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevI.txt" -#elif defined(_DEBUG) - #define DEBUG_FILE_NAME "DebugLogFileD.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevD.txt" +#if defined(RTS_INTERNAL) + #define DEBUG_FILE_NAME "DebugLogFileI" + #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevI" +#elif defined(RTS_DEBUG) + #define DEBUG_FILE_NAME "DebugLogFileD" + #define DEBUG_FILE_NAME_PREV "DebugLogFilePrevD" #else - #define DEBUG_FILE_NAME "DebugLogFile.txt" - #define DEBUG_FILE_NAME_PREV "DebugLogFilePrev.txt" + #define DEBUG_FILE_NAME "DebugLogFile" + #define DEBUG_FILE_NAME_PREV "DebugLogFilePrev" #endif #endif @@ -98,8 +107,12 @@ extern const char *gAppPrefix; /// So WB can have a different log file name. // ---------------------------------------------------------------------------- // PRIVATE DATA // ---------------------------------------------------------------------------- +// TheSuperHackers @info Must not use static RAII types when set in DebugInit, +// because DebugInit can be called during static module initialization before the main function is called. #ifdef DEBUG_LOGGING static FILE *theLogFile = NULL; +static char theLogFileName[ _MAX_PATH ]; +static char theLogFileNamePrev[ _MAX_PATH ]; #endif #define LARGE_BUFFER 8192 static char theBuffer[ LARGE_BUFFER ]; // make it big to avoid weird overflow bugs in debug mode @@ -237,6 +250,10 @@ static void doLogOutput(const char *buffer) { ::OutputDebugString(buffer); } + +#ifdef INCLUDE_DEBUG_LOG_IN_CRC_LOG + addCRCDebugLineNoCounter("%s", buffer); +#endif } #endif @@ -348,6 +365,11 @@ void DebugInit(int flags) #ifdef DEBUG_LOGGING + // TheSuperHackers @info Debug initialization can happen very early. + // Therefore, initialize the client instance now. + if (!rts::ClientInstance::initialize()) + return; + char dirbuf[ _MAX_PATH ]; ::GetModuleFileName( NULL, dirbuf, sizeof( dirbuf ) ); char *pEnd = dirbuf + strlen( dirbuf ); @@ -361,22 +383,26 @@ void DebugInit(int flags) pEnd--; } - char prevbuf[ _MAX_PATH ]; - char curbuf[ _MAX_PATH ]; - - strcpy(prevbuf, dirbuf); - strcat(prevbuf, gAppPrefix); - strcat(prevbuf, DEBUG_FILE_NAME_PREV); - strcpy(curbuf, dirbuf); - strcat(curbuf, gAppPrefix); - strcat(curbuf, DEBUG_FILE_NAME); - - remove(prevbuf); - rename(curbuf, prevbuf); - theLogFile = fopen(curbuf, "w"); + strcpy(theLogFileNamePrev, dirbuf); + strcat(theLogFileNamePrev, gAppPrefix); + strcat(theLogFileNamePrev, DEBUG_FILE_NAME_PREV); + if (rts::ClientInstance::getInstanceId() > 1u) + sprintf(theLogFileNamePrev + strlen(theLogFileNamePrev), "_Instance%.2u", rts::ClientInstance::getInstanceId()); + strcat(theLogFileNamePrev, ".txt"); + + strcpy(theLogFileName, dirbuf); + strcat(theLogFileName, gAppPrefix); + strcat(theLogFileName, DEBUG_FILE_NAME); + if (rts::ClientInstance::getInstanceId() > 1u) + sprintf(theLogFileName + strlen(theLogFileName), "_Instance%.2u", rts::ClientInstance::getInstanceId()); + strcat(theLogFileName, ".txt"); + + remove(theLogFileNamePrev); + rename(theLogFileName, theLogFileNamePrev); + theLogFile = fopen(theLogFileName, "w"); if (theLogFile != NULL) { - DebugLog("Log %s opened: %s\n", curbuf, getCurrentTimeString()); + DebugLog("Log %s opened: %s\n", theLogFileName, getCurrentTimeString()); } #endif } @@ -413,6 +439,17 @@ void DebugLog(const char *format, ...) whackFunnyCharacters(theBuffer); doLogOutput(theBuffer); } + +const char* DebugGetLogFileName() +{ + return theLogFileName; +} + +const char* DebugGetLogFileNamePrev() +{ + return theLogFileNamePrev; +} + #endif // ---------------------------------------------------------------------------- @@ -665,7 +702,7 @@ void ReleaseCrash(const char *reason) ShowWindow(ApplicationHWnd, SW_HIDE); } } -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // /* static */ char buff[8192]; // not so static so we can be threadsafe // _snprintf(buff, 8192, "Sorry, a serious error occurred. (%s)", reason);/ // buff[8191] = 0; @@ -710,7 +747,7 @@ void ReleaseCrash(const char *reason) ShowWindow(ApplicationHWnd, SW_HIDE); } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /* static */ char buff[8192]; // not so static so we can be threadsafe _snprintf(buff, 8192, "Sorry, a serious error occurred. (%s)", reason); buff[8191] = 0; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/GameCommon.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/GameCommon.cpp index 1535089371..257aa4e760 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/GameCommon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/GameCommon.cpp @@ -64,3 +64,5 @@ Real normalizeAngle(Real angle) return angle; } + + diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp index f34d17d8b4..b2b65f15a7 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/GameMemory.cpp @@ -64,7 +64,7 @@ DECLARE_PERF_TIMER(MemoryPoolDebugging) DECLARE_PERF_TIMER(MemoryPoolInitFilling) #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -115,7 +115,7 @@ DECLARE_PERF_TIMER(MemoryPoolInitFilling) }; // in debug mode (but not internal), save stacktraces too - #if !defined(MEMORYPOOL_CHECKPOINTING) && defined(MEMORYPOOL_STACKTRACE) && defined(_DEBUG) + #if !defined(MEMORYPOOL_CHECKPOINTING) && defined(MEMORYPOOL_STACKTRACE) && defined(RTS_DEBUG) #define MEMORYPOOL_SINGLEBLOCK_GETS_STACKTRACE #endif @@ -2248,7 +2248,7 @@ void *DynamicMemoryAllocator::allocateBytesDoNotZeroImplementation(Int numBytes #endif #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // check alignment if (unsigned(result)&3) throw ERROR_OUT_OF_MEMORY; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Geometry.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Geometry.cpp index 2ed9c2de8a..40e048563d 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Geometry.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Geometry.cpp @@ -36,7 +36,7 @@ #include "Common/RandomValue.h" #include "Common/Xfer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -518,7 +518,7 @@ void GeometryInfo::calcBoundingStuff() }; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= void GeometryInfo::tweakExtents(ExtentModType extentModType, Real extentModAmount) { @@ -542,7 +542,7 @@ void GeometryInfo::tweakExtents(ExtentModType extentModType, Real extentModAmoun } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //============================================================================= AsciiString GeometryInfo::getDescriptiveString() const { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/LocalFile.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/LocalFile.cpp index d9b927203c..1869125368 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/LocalFile.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/LocalFile.cpp @@ -61,7 +61,7 @@ #include "Common/PerfTimer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp index 27f04f3478..3e2cccaac3 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/MemoryInit.cpp @@ -49,7 +49,7 @@ #include "Lib/BaseType.h" #include "Common/GameMemory.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -211,6 +211,7 @@ static PoolSizeRec sizes[] = { "GarrisonContain", 256, 32 }, { "HealCrateCollide", 32, 32 }, { "HeightDieUpdate", 32, 32 }, + { "ScatterShotUpdate", 128, 64 }, { "FireWeaponWhenDamagedBehavior", 32, 32 }, { "FireWeaponWhenDeadBehavior", 128, 64 }, { "GenerateMinefieldBehavior", 32, 32 }, @@ -272,6 +273,7 @@ static PoolSizeRec sizes[] = { "AnimationSteeringUpdate", 1024, 32 }, { "SupplyWarehouseCripplingBehavior", 16, 16 }, { "CostModifierUpgrade", 32, 32 }, + { "ProductionTimeModifierUpgrade", 32, 32 }, { "CashBountyPower", 32, 32 }, { "CleanupAreaPower", 32, 32 }, { "ObjectCreationUpgrade", 196, 32 }, @@ -346,6 +348,7 @@ static PoolSizeRec sizes[] = { "ChinookAIUpdate", 32, 32 }, { "WanderAIUpdate", 32, 32 }, { "WaveGuideUpdate", 16, 16 }, + { "ArmorDamageScalarUpdate", 256, 32 }, { "WeaponBonusUpgrade", 512, 128 }, { "WeaponSetUpgrade", 512, 128 }, { "ArmorUpgrade", 512, 128 }, @@ -556,6 +559,7 @@ static PoolSizeRec sizes[] = { "AttackPriorityInfo", 32, 32 }, { "SequentialScript", 32, 32 }, { "Win32LocalFile", 1024, 256 }, + { "StdLocalFile", 1024, 256 }, { "RAMFile", 32, 32 }, { "BattlePlanBonuses", 32, 32 }, { "KindOfPercentProductionChange", 32, 32 }, diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Radar.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Radar.cpp index 1b792fabbf..d91290c3ec 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Radar.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Radar.cpp @@ -53,7 +53,7 @@ #include "GameLogic/Module/ContainModule.h" #include "GameLogic/Module/StealthUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp index b902fa2cc2..05418b7659 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp @@ -59,7 +59,7 @@ #include "GameLogic/SidesList.h" #include "GameLogic/TerrainLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp index 56429990ed..a5edd698a2 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameStateMap.cpp @@ -45,7 +45,7 @@ // GLOBALS //////////////////////////////////////////////////////////////////////////////////////// GameStateMap *TheGameStateMap = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp index 9846ca3eb5..a0ed36025f 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp @@ -24,7 +24,7 @@ #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#if defined(_DEBUG) || defined(_INTERNAL) || defined(IG_DEBUG_STACKTRACE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(IG_DEBUG_STACKTRACE) #pragma pack(push, 8) diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp index c0f5fdf459..ad6b39ea2e 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SubsystemInterface.cpp @@ -29,7 +29,7 @@ #include "Common/SubsystemInterface.h" #include "Common/Xfer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp index a1e7273c68..6115baae1d 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp @@ -46,7 +46,7 @@ #include "Common/CriticalSection.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -57,7 +57,7 @@ /*static*/ UnicodeString UnicodeString::TheEmptyString; // ----------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void UnicodeString::validate() const { if (!m_data) return; @@ -102,7 +102,7 @@ void UnicodeString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveDa UnicodeStringData* newData = (UnicodeStringData*)TheDynamicMemoryAllocator->allocateBytesDoNotZero(actualBytes, "STR_UnicodeString::ensureUniqueBufferOfSize"); newData->m_refCount = 1; newData->m_numCharsAllocated = (actualBytes - sizeof(UnicodeStringData))/sizeof(WideChar); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) newData->m_debugptr = newData->peek(); // just makes it easier to read in the debugger #endif @@ -308,12 +308,7 @@ void UnicodeString::format(const WideChar* format, ...) // ----------------------------------------------------- void UnicodeString::format_va(const UnicodeString& format, va_list args) { - validate(); - WideChar buf[MAX_FORMAT_BUF_LEN]; - if (_vsnwprintf(buf, sizeof(buf)/sizeof(WideChar)-1, format.str(), args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + format_va(format.str(), args); } // ----------------------------------------------------- @@ -321,10 +316,16 @@ void UnicodeString::format_va(const WideChar* format, va_list args) { validate(); WideChar buf[MAX_FORMAT_BUF_LEN]; - if (_vsnwprintf(buf, sizeof(buf)/sizeof(WideChar)-1, format, args) < 0) - throw ERROR_OUT_OF_MEMORY; - set(buf); - validate(); + const int result = _vsnwprintf(buf, sizeof(buf)/sizeof(WideChar)-1, format, args); + if (result >= 0) + { + set(buf); + validate(); + } + else + { + DEBUG_ASSERTCRASH(false, ("UnicodeString::format_va failed with code:%d", result)); + } } //----------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp index 40d1953a0f..ea13059b79 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Upgrade.cpp @@ -156,7 +156,7 @@ UpgradeTemplate::~UpgradeTemplate( void ) //------------------------------------------------------------------------------------------------- Int UpgradeTemplate::calcTimeToBuild( Player *player ) const { -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) if( player->buildsInstantly() ) { return 1; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp index 960f21e163..d82ce18e08 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp @@ -30,7 +30,7 @@ #include "Common/Registry.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp index 1e9e44be0d..9932109bcb 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/Module.cpp @@ -47,7 +47,7 @@ #include "GameLogic/Module/UpdateModule.h" #include "GameLogic/Module/UpgradeModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp index 6cd5852a24..83a6ff4b14 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp @@ -128,6 +128,7 @@ #include "GameLogic/Module/AssaultTransportAIUpdate.h" #include "GameLogic/Module/HeightDieUpdate.h" #include "GameLogic/Module/HordeUpdate.h" +#include "GameLogic/Module/ScatterShotUpdate.h" #include "GameLogic/Module/JetAIUpdate.h" #include "GameLogic/Module/LaserUpdate.h" #include "GameLogic/Module/PointDefenseLaserUpdate.h" @@ -186,6 +187,7 @@ #include "GameLogic/Module/WanderAIUpdate.h" #include "GameLogic/Module/WaveGuideUpdate.h" #include "GameLogic/Module/WeaponBonusUpdate.h" +#include "GameLogic/Module/ArmorDamageScalarUpdate.h" #include "GameLogic/Module/WorkerAIUpdate.h" #include "GameLogic/Module/PowerPlantUpdate.h" #include "GameLogic/Module/CheckpointUpdate.h" @@ -211,6 +213,7 @@ #include "GameLogic/Module/WeaponSetUpgrade.h" #include "GameLogic/Module/WeaponBonusUpgrade.h" #include "GameLogic/Module/CostModifierUpgrade.h" +#include "GameLogic/Module/ProductionTimeModifierUpgrade.h" #include "GameLogic/Module/ExperienceScalarUpgrade.h" #include "GameLogic/Module/MaxHealthUpgrade.h" @@ -286,7 +289,7 @@ ModuleFactory *TheModuleFactory = NULL; ///< the module factory singleton // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -407,6 +410,7 @@ void ModuleFactory::init( void ) addModule( LeafletDropBehavior ); addModule( AutoDepositUpdate ); addModule( WeaponBonusUpdate ); + addModule( ArmorDamageScalarUpdate ); addModule( MissileAIUpdate ); addModule( NeutronMissileUpdate ); addModule( FireSpreadUpdate ); @@ -415,6 +419,7 @@ void ModuleFactory::init( void ) addModule( FloatUpdate ); addModule( TensileFormationUpdate ); addModule( HeightDieUpdate ); + addModule( ScatterShotUpdate ); addModule( ChinookAIUpdate ); addModule( JetAIUpdate ); addModule( AIUpdateInterface ); @@ -476,6 +481,7 @@ void ModuleFactory::init( void ) // upgrade modules addModule( CostModifierUpgrade ); + addModule( ProductionTimeModifierUpgrade ); addModule( ActiveShroudUpgrade ); addModule( ArmorUpgrade ); addModule( CommandSetUpgrade ); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/Thing.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/Thing.cpp index c3e8bfcec6..bc0f65c456 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/Thing.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/Thing.cpp @@ -46,7 +46,7 @@ #include "Lib/trig.h" #include "GameLogic/TerrainLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -68,7 +68,7 @@ Thing::Thing( const ThingTemplate *thingTemplate ) } // end if m_template = thingTemplate; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_templateName = thingTemplate->getName(); #endif m_transform.Make_Identity(); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp index ca78bd807a..e3635d30d4 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp @@ -48,7 +48,7 @@ #include "GameClient/Drawable.h" #include "Common/INI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -366,7 +366,7 @@ Drawable *ThingFactory::newDrawable(const ThingTemplate *tmplate, DrawableStatus } // end newDrawableByType -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString TheThingTemplateBeingParsedName; #endif @@ -375,7 +375,7 @@ AsciiString TheThingTemplateBeingParsedName; //------------------------------------------------------------------------------------------------- /*static*/ void ThingFactory::parseObjectDefinition( INI* ini, const AsciiString& name, const AsciiString& reskinFrom ) { -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) TheThingTemplateBeingParsedName = name; #endif @@ -434,7 +434,73 @@ AsciiString TheThingTemplateBeingParsedName; thingTemplate->resolveNames(); } -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) + TheThingTemplateBeingParsedName.clear(); +#endif +} + +void ThingFactory::parseObjectExtendDefinition(INI* ini, const AsciiString& name, const AsciiString& extendFrom) +{ +#if defined(_DEBUG) || defined(_INTERNAL) + TheThingTemplateBeingParsedName = name; +#endif + + if (extendFrom.isEmpty()) { + DEBUG_CRASH(("ObjectExtend must specify an Object to extend from (%s).\n", name.str())); + } + + // find existing item if present + ThingTemplate* thingTemplate = TheThingFactory->findTemplateInternal(name, FALSE); + if (!thingTemplate) + { + // no item is present, create a new one + thingTemplate = TheThingFactory->newTemplate(name); + if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES) + { + // This ThingTemplate is actually an override, so we will mark it as such so that it properly + // gets deleted on ::reset(). + thingTemplate->markAsOverride(); + } + } + else if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES) + { + //Holy crap, this sucks to debug!!! + //If you have two different objects, the previous code would simply + //allow you to define multiple objects with the same name, and just + //nuke the old one with the new one. So, I (KM) have added this + //assert to notify in case of two same-name objects. + DEBUG_CRASH(("[LINE: %d in '%s'] Duplicate factionunit %s found!", ini->getLineNum(), ini->getFilename().str(), name.str())); + } + else + { + thingTemplate = TheThingFactory->newOverride(thingTemplate); + } + + + const ThingTemplate* extendTmpl = TheThingFactory->findTemplate(extendFrom); + if (extendTmpl) + { + thingTemplate->copyFrom(extendTmpl); + thingTemplate->setCopiedFromDefaultExtended(); + //thingTemplate->setReskinnedFrom(extendTmpl); + + ini->initFromINI(thingTemplate, thingTemplate->getFieldParse()); + } + else + { + DEBUG_CRASH(("ObjectExtend must come after the original Object (%s, %s).\n", extendFrom.str(), name.str())); + throw INI_INVALID_DATA; + } + + + thingTemplate->validate(); + + if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES) + { + thingTemplate->resolveNames(); + } + +#if defined(_DEBUG) || defined(_INTERNAL) TheThingTemplateBeingParsedName.clear(); #endif } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp index 93fc07e60e..ced3df12cc 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp @@ -37,6 +37,7 @@ #define DEFINE_EDITOR_SORTING_NAMES // for EditorSortingNames[] #define DEFINE_RADAR_PRIORITY_NAMES // for RadarPriorityNames[] #define DEFINE_BUILDABLE_STATUS_NAMES // for BuildableStatusNames[] +#define DEFINE_AMMO_PIPS_STYLE_NAMES // for AmmoPipsStyleNames[] #include "Common/DamageFX.h" #include "Common/GameAudio.h" @@ -72,7 +73,7 @@ #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -249,7 +250,7 @@ const FieldParse ThingTemplate::s_objectFieldParseTable[] = { "MaxSimultaneousLinkKey", NameKeyGenerator::parseStringAsNameKeyType, NULL, offsetof(ThingTemplate, m_maxSimultaneousLinkKey ) }, { "CrusherLevel", INI::parseUnsignedByte, NULL, offsetof( ThingTemplate, m_crusherLevel ) }, { "CrushableLevel", INI::parseUnsignedByte, NULL, offsetof( ThingTemplate, m_crushableLevel ) }, - + { "AmmoPipsStyle", INI::parseByteSizedIndexList, AmmoPipsStyleNames, offsetof(ThingTemplate, m_ammoPipsStyle) }, { 0, 0, 0, 0 } // keep this last }; @@ -309,7 +310,7 @@ void ModuleInfo::addModuleInfo(ThingTemplate *thingTemplate, // there must be a module tag present, and it must be unique across all module infos // for this thing template // -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // get module info const Nugget *nugget; @@ -908,7 +909,7 @@ void ThingTemplate::parseArmorTemplateSet( INI* ini, void *instance, void * /*st ArmorTemplateSet ws; ws.parseArmorTemplateSet(ini); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES) { for (ArmorTemplateSetVector::const_iterator it = self->m_armorTemplateSets.begin(); it != self->m_armorTemplateSets.end(); ++it) @@ -936,7 +937,7 @@ void ThingTemplate::parseWeaponTemplateSet( INI* ini, void *instance, void * /*s WeaponTemplateSet ws; ws.parseWeaponTemplateSet(ini, self); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES) { for (WeaponTemplateSetVector::const_iterator it = self->m_weaponTemplateSets.begin(); it != self->m_weaponTemplateSets.end(); ++it) @@ -1047,6 +1048,7 @@ ThingTemplate::ThingTemplate() : m_crusherLevel = 0; //Unspecified, this object is unable to crush anything! m_crushableLevel = 255; //Unspecified, this object is unable to be crushed by anything! + m_ammoPipsStyle = AMMO_PIPS_DEFAULT; } //------------------------------------------------------------------------------------------------- @@ -1068,7 +1070,7 @@ AIUpdateModuleData *ThingTemplate::friend_getAIModuleInfo(void) //------------------------------------------------------------------------------------------------- void ThingTemplate::validateAudio() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define AUDIO_TEST(y) \ if (!get##y()->getEventName().isEmpty() && get##y()->getEventName().compareNoCase("NoSound") != 0) { \ @@ -1158,7 +1160,7 @@ void ThingTemplate::validate() validateAudio(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (getName() == "DefaultThingTemplate") return; @@ -1242,6 +1244,18 @@ void ThingTemplate::setCopiedFromDefault() m_clientUpdateModuleInfo.setCopiedFromDefault(true); } +//------------------------------------------------------------------------------------------------- +void ThingTemplate::setCopiedFromDefaultExtended() +{ + //only set weapons and armors as copied, so they get cleared when defining new ones as they + // cannot be removed with RemoveModule + m_armorCopiedFromDefault = true; + m_weaponsCopiedFromDefault = true; + //m_behaviorModuleInfo.setCopiedFromDefault(true); + //m_drawModuleInfo.setCopiedFromDefault(true); + //m_clientUpdateModuleInfo.setCopiedFromDefault(true); +} + //------------------------------------------------------------------------------------------------- ThingTemplate::~ThingTemplate() { @@ -1552,9 +1566,10 @@ Int ThingTemplate::calcTimeToBuild( const Player* player) const buildTime *= player->getHandicap()->getHandicap(Handicap::BUILDTIME, this); Real factionModifier = 1 + player->getProductionTimeChangePercent( getName() ); + factionModifier *= player->getProductionTimeChangeBasedOnKindOf(m_kindof); buildTime *= factionModifier; -#if defined (_DEBUG) || defined (_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined (RTS_DEBUG) || defined (RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) if( player->buildsInstantly() ) { buildTime = 1; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp b/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp index 0bebce1fe7..1d488c1d38 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/UserPreferences.cpp @@ -51,7 +51,7 @@ #include "GameClient/ChallengeGenerals.h" #include "GameNetwork/GameSpy/PeerDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/Common/crc.cpp b/GeneralsMD/Code/GameEngine/Source/Common/crc.cpp index 0ab310e098..ddf54fff93 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/crc.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/crc.cpp @@ -28,7 +28,7 @@ #include "Common/crc.h" #include "Common/Debug.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG void CRC::addCRC( UnsignedByte val ) { diff --git a/GeneralsMD/Code/GameEngine/Source/Common/version.cpp b/GeneralsMD/Code/GameEngine/Source/Common/version.cpp index 8d3df755f2..923b7a204c 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/version.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/version.cpp @@ -41,7 +41,7 @@ Version::Version() m_localBuildNum = 0; m_buildUser = AsciiString("somebody"); m_buildLocation = AsciiString("somewhere"); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL m_showFullVersion = TRUE; #else m_showFullVersion = FALSE; @@ -70,15 +70,15 @@ UnsignedInt Version::getVersionNumber( void ) AsciiString Version::getAsciiVersion( void ) { AsciiString version; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (m_localBuildNum) version.format("%d.%d.%d.%d%c%c", m_major, m_minor, m_buildNum, m_localBuildNum, m_buildUser.getCharAt(0), m_buildUser.getCharAt(1)); else version.format("%d.%d.%d", m_major, m_minor, m_buildNum); -#else // defined _DEBUG || defined _INTERNAL +#else // defined RTS_DEBUG || defined RTS_INTERNAL version.format("%d.%d", m_major, m_minor); -#endif // defined _DEBUG || defined _INTERNAL +#endif // defined RTS_DEBUG || defined RTS_INTERNAL return version; } @@ -87,21 +87,21 @@ UnicodeString Version::getUnicodeVersion( void ) { UnicodeString version; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (!m_localBuildNum) version.format(TheGameText->fetch("Version:Format3").str(), m_major, m_minor, m_buildNum); else version.format(TheGameText->fetch("Version:Format4").str(), m_major, m_minor, m_buildNum, m_localBuildNum, m_buildUser.getCharAt(0), m_buildUser.getCharAt(1)); -#else // defined _DEBUG || defined _INTERNAL +#else // defined RTS_DEBUG || defined RTS_INTERNAL version.format(TheGameText->fetch("Version:Format2").str(), m_major, m_minor); -#endif // defined _DEBUG || defined _INTERNAL +#endif // defined RTS_DEBUG || defined RTS_INTERNAL -#ifdef _DEBUG +#ifdef RTS_DEBUG version.concat(UnicodeString(L" Debug")); #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL version.concat(UnicodeString(L" Internal")); #endif @@ -118,11 +118,11 @@ UnicodeString Version::getFullUnicodeVersion( void ) version.format(TheGameText->fetch("Version:Format4").str(), m_major, m_minor, m_buildNum, m_localBuildNum, m_buildUser.getCharAt(0), m_buildUser.getCharAt(1)); -#ifdef _DEBUG +#ifdef RTS_DEBUG version.concat(UnicodeString(L" Debug")); #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL version.concat(UnicodeString(L" Internal")); #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/ClientInstance.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/ClientInstance.cpp new file mode 100644 index 0000000000..5b142a256c --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/ClientInstance.cpp @@ -0,0 +1,99 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ +#include "PreRTS.h" +#include "GameClient/ClientInstance.h" + +#define GENERALS_GUID "685EAFF2-3216-4265-B047-251C5F4B82F3" + +namespace rts +{ +HANDLE ClientInstance::s_mutexHandle = NULL; +UnsignedInt ClientInstance::s_instanceIndex = 0; + +bool ClientInstance::initialize() +{ + if (isInitialized()) + { + return true; + } + + // Create a mutex with a unique name to Generals in order to determine if our app is already running. + // WARNING: DO NOT use this number for any other application except Generals. + while (true) + { +#ifdef RTS_MULTI_INSTANCE + std::string guidStr = getFirstInstanceName(); + if (s_instanceIndex > 0u) + { + char idStr[33]; + itoa(s_instanceIndex, idStr, 10); + guidStr.push_back('-'); + guidStr.append(idStr); + } + s_mutexHandle = CreateMutex(NULL, FALSE, guidStr.c_str()); + if (GetLastError() == ERROR_ALREADY_EXISTS) + { + if (s_mutexHandle != NULL) + { + CloseHandle(s_mutexHandle); + s_mutexHandle = NULL; + } + // Try again with a new instance. + ++s_instanceIndex; + continue; + } +#else + s_mutexHandle = CreateMutex(NULL, FALSE, getFirstInstanceName()); + if (GetLastError() == ERROR_ALREADY_EXISTS) + { + if (s_mutexHandle != NULL) + { + CloseHandle(s_mutexHandle); + s_mutexHandle = NULL; + } + return false; + } +#endif + break; + } + + return true; +} + +bool ClientInstance::isInitialized() +{ + return s_mutexHandle != NULL; +} + +UnsignedInt ClientInstance::getInstanceIndex() +{ + DEBUG_ASSERTLOG(!isInitialized(), ("ClientInstance::isInitialized() failed")); + return s_instanceIndex; +} + +UnsignedInt ClientInstance::getInstanceId() +{ + return getInstanceIndex() + 1; +} + +const char* ClientInstance::getFirstInstanceName() +{ + return GENERALS_GUID; +} + +} // namespace rts diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Color.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Color.cpp index 24aac3d228..70d20e99e5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Color.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Color.cpp @@ -79,7 +79,7 @@ /** Get the RGB color comonents of a color */ //============================================================================= -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp index e770fbae3d..afe800967a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp @@ -56,7 +56,7 @@ #include "GameClient/Display.h" #include "GameClient/GameText.h" #include "GameClient/GlobalLanguage.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp index b0f514e246..e91de9272f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp @@ -76,13 +76,14 @@ #include "GameClient/LanguageFilter.h" #include "GameClient/Shadow.h" #include "GameClient/GameText.h" +#include "GameClient/TintStatus.h" //#define KRIS_BRUTAL_HACK_FOR_AIRCRAFT_CARRIER_DEBUGGING #ifdef KRIS_BRUTAL_HACK_FOR_AIRCRAFT_CARRIER_DEBUGGING #include "GameLogic/Module/ParkingPlaceBehavior.h" #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -115,6 +116,29 @@ static const char *TheDrawableIconNames[] = }; +// ----- +const char* TintStatusFlags::s_bitNameList[] = +{ + "NONE", + "DISABLED", + "IRRADIATED", + "POISONED", + "GAINING_SUBDUAL_DAMAGE", + "FRENZY", + "SHIELDED", + "DEMORALIZED", + "BOOST", + "EXTRA1", + "EXTRA2", + "EXTRA3", + "EXTRA4", + "EXTRA5", + "EXTRA6", + "EXTRA7", + "EXTRA8", + NULL +}; + /** * Returns a special DynamicAudioEventInfo which can be used to mark a sound as "no sound". * E.g. if m_customSoundAmbientInfo equals the value returned from this function, we @@ -135,8 +159,6 @@ static DynamicAudioEventInfo * getNoSoundMarker() return marker; } - - // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ DrawableIconInfo::DrawableIconInfo() @@ -247,12 +269,17 @@ static DrawableIconType drawableIconNameToIndex( const char *iconName ) const UnsignedInt HEALING_ICON_DISPLAY_TIME = LOGICFRAMES_PER_SECOND * 3; const UnsignedInt DEFAULT_HEAL_ICON_WIDTH = 32; const UnsignedInt DEFAULT_HEAL_ICON_HEIGHT = 32; -const RGBColor SICKLY_GREEN_POISONED_COLOR = {-1.0f, 1.0f, -1.0f}; -const RGBColor DARK_GRAY_DISABLED_COLOR = {-0.5f, -0.5f, -0.5f}; -const RGBColor RED_IRRADIATED_COLOR = { 1.0f, -1.0f, -1.0f}; -const RGBColor SUBDUAL_DAMAGE_COLOR = {-0.2f, -0.2f, 0.8f}; -const RGBColor FRENZY_COLOR = { 0.2f, -0.2f, -0.2f}; -const RGBColor FRENZY_COLOR_INFANTRY = { 0.0f, -0.7f, -0.7f}; + +//Note: These constants are now obsolete and are only here for reference. +//const RGBColor SICKLY_GREEN_POISONED_COLOR = {-1.0f, 1.0f, -1.0f}; +//const RGBColor DARK_GRAY_DISABLED_COLOR = {-0.5f, -0.5f, -0.5f}; +//const RGBColor RED_IRRADIATED_COLOR = { 1.0f, -1.0f, -1.0f}; +//const RGBColor SUBDUAL_DAMAGE_COLOR = {-0.2f, -0.2f, 0.8f}; +//const RGBColor FRENZY_COLOR = { 0.2f, -0.2f, -0.2f}; +//const RGBColor FRENZY_COLOR_INFANTRY = { 0.0f, -0.7f, -0.7f}; +//const RGBColor SHIELDED_COLOR = { -0.1f, -0.2f, -0.2f}; +// --- + const Int MAX_ENABLED_MODULES = 16; // ------------------------------------------------------------------------------------------------ @@ -434,8 +461,8 @@ Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatus statusBit m_object = NULL; // tintStatusTracking - m_tintStatus = 0; - m_prevTintStatus = 0; + // m_tintStatus = 0; + // m_prevTintStatus = 0; #ifdef DIRTY_CONDITION_FLAGS m_isModelDirty = true; @@ -1253,47 +1280,84 @@ void Drawable::updateDrawable( void ) // we'll use an ifelseif ladder since we are scanning bits if( m_prevTintStatus != m_tintStatus )// edge test { - if ( testTintStatus( TINT_STATUS_DISABLED ) ) - { - if (m_colorTintEnvelope == NULL) - m_colorTintEnvelope = newInstance(TintEnvelope); - m_colorTintEnvelope->play( &DARK_GRAY_DISABLED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); + + bool hasStatus = false; + + // New: Check the global list + for (int i = 0; i < TINT_STATUS_COUNT; i++) { + + TintStatus tintStatus = (TintStatus)i; + + if (testTintStatus(tintStatus)) { + if (m_colorTintEnvelope == NULL) + m_colorTintEnvelope = newInstance(TintEnvelope); + + DrawableColorTint tintColor = TheGlobalData->m_colorTintTypes[i]; + + m_colorTintEnvelope->play( + isKindOf(KINDOF_INFANTRY) ? &tintColor.colorInfantry : &tintColor.color, + tintColor.attackFrames, tintColor.decayFrames, SUSTAIN_INDEFINITELY); + + hasStatus = true; + break; + } } - else if( testTintStatus(TINT_STATUS_GAINING_SUBDUAL_DAMAGE) ) - { - // Disabled has precendence, so it goes first + + if (!hasStatus) { + // NO TINTING SHOULD BE PRESENT if (m_colorTintEnvelope == NULL) m_colorTintEnvelope = newInstance(TintEnvelope); - m_colorTintEnvelope->play( &SUBDUAL_DAMAGE_COLOR, 150, 150, SUSTAIN_INDEFINITELY); + m_colorTintEnvelope->release(); // head on back to normal, now } - else if( testTintStatus(TINT_STATUS_FRENZY) ) - { - // Disabled has precendence, so it goes first - if (m_colorTintEnvelope == NULL) - m_colorTintEnvelope = newInstance(TintEnvelope); - m_colorTintEnvelope->play( isKindOf( KINDOF_INFANTRY) ? &FRENZY_COLOR_INFANTRY:&FRENZY_COLOR, 30, 30, SUSTAIN_INDEFINITELY); - - } -// else if ( testTintStatus( TINT_STATUS_POISONED) ) +// if ( testTintStatus( TINT_STATUS_DISABLED ) ) // { // if (m_colorTintEnvelope == NULL) // m_colorTintEnvelope = newInstance(TintEnvelope); -// m_colorTintEnvelope->play( &SICKLY_GREEN_POISONED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); +// m_colorTintEnvelope->play( &DARK_GRAY_DISABLED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); // } -// else if ( testTintStatus( TINT_STATUS_IRRADIATED) ) +// else if( testTintStatus(TINT_STATUS_GAINING_SUBDUAL_DAMAGE) ) // { +// // Disabled has precendence, so it goes first // if (m_colorTintEnvelope == NULL) // m_colorTintEnvelope = newInstance(TintEnvelope); -// m_colorTintEnvelope->play( &RED_IRRADIATED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); +// m_colorTintEnvelope->play( &SUBDUAL_DAMAGE_COLOR, 150, 150, SUSTAIN_INDEFINITELY); +// } +// else if (testTintStatus(TINT_STATUS_FRENZY)) +// { +// // Disabled has precendence, so it goes first +// if (m_colorTintEnvelope == NULL) +// m_colorTintEnvelope = newInstance(TintEnvelope); +// +// m_colorTintEnvelope->play(isKindOf(KINDOF_INFANTRY) ? &FRENZY_COLOR_INFANTRY : &FRENZY_COLOR, 30, 30, SUSTAIN_INDEFINITELY); +// } +// else if (testTintStatus(TINT_STATUS_SHIELDED)) +// { +// // Disabled has precendence, so it goes first +// if (m_colorTintEnvelope == NULL) +// m_colorTintEnvelope = newInstance(TintEnvelope); +// +// m_colorTintEnvelope->play( &SHIELDED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); +// } +//// else if ( testTintStatus( TINT_STATUS_POISONED) ) +//// { +//// if (m_colorTintEnvelope == NULL) +//// m_colorTintEnvelope = newInstance(TintEnvelope); +//// m_colorTintEnvelope->play( &SICKLY_GREEN_POISONED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); +//// } +//// else if ( testTintStatus( TINT_STATUS_IRRADIATED) ) +//// { +//// if (m_colorTintEnvelope == NULL) +//// m_colorTintEnvelope = newInstance(TintEnvelope); +//// m_colorTintEnvelope->play( &RED_IRRADIATED_COLOR, 30, 30, SUSTAIN_INDEFINITELY); +//// } +// else +// { +// // NO TINTING SHOULD BE PRESENT +// if (m_colorTintEnvelope == NULL) +// m_colorTintEnvelope = newInstance(TintEnvelope); +// m_colorTintEnvelope->release(); // head on back to normal, now // } - else - { - // NO TINTING SHOULD BE PRESENT - if (m_colorTintEnvelope == NULL) - m_colorTintEnvelope = newInstance(TintEnvelope); - m_colorTintEnvelope->release(); // head on back to normal, now - } } @@ -2527,7 +2591,7 @@ const AudioEventRTS& Drawable::getAmbientSoundByDamage(BodyDamageType dt) //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void Drawable::validatePos() const { const Coord3D* ourPos = getPosition(); @@ -2655,7 +2719,7 @@ void Drawable::draw( View *view ) -#ifdef _DEBUG +#ifdef RTS_DEBUG validatePos(); #endif @@ -2884,54 +2948,124 @@ void Drawable::drawEmoticon( const IRegion2D *healthBarRegion ) // ------------------------------------------------------------------------------------------------ void Drawable::drawAmmo( const IRegion2D *healthBarRegion ) { - const Object *obj = getObject(); + if (!healthBarRegion) + return; + + const Object* obj = getObject(); if (!( - TheGlobalData->m_showObjectHealth && - (isSelected() || (TheInGameUI && (TheInGameUI->getMousedOverDrawableID() == getID()))) && - obj->getControllingPlayer() == ThePlayerList->getLocalPlayer() - )) + TheGlobalData->m_showObjectHealth && + (isSelected() || (TheInGameUI && (TheInGameUI->getMousedOverDrawableID() == getID()))) && + obj->getControllingPlayer() == ThePlayerList->getLocalPlayer() + )) return; - Int numTotal; - Int numFull; + Int numTotal; // getClipSize(); + Int numFull; // getRemainingAmmo(); if (!obj->getAmmoPipShowingInfo(numTotal, numFull)) return; - if (!s_fullAmmo || !s_emptyAmmo) - return; + AmmoPipsStyle pipsStyle = obj->getTemplate()->getAmmoPipsStyle(); + switch (pipsStyle) + { + case AMMO_PIPS_DEFAULT: + case AMMO_PIPS_SINGLE: + { + if (!s_fullAmmo || !s_emptyAmmo) + return; - #ifdef SCALE_ICONS_WITH_ZOOM_ML - Real scale = TheGlobalData->m_ammoPipScaleFactor / CLAMP_ICON_ZOOM_FACTOR( TheTacticalView->getZoom() ); + Real scale = TheGlobalData->m_ammoPipScaleFactor / CLAMP_ICON_ZOOM_FACTOR(TheTacticalView->getZoom()); #else - Real scale = 1.0f; + Real scale = 1.0f; #endif - Int boxWidth = REAL_TO_INT(s_emptyAmmo->getImageWidth() * scale); - Int boxHeight = REAL_TO_INT(s_emptyAmmo->getImageHeight() * scale); - const Int SPACING = 1; - //Int totalWidth = (boxWidth+SPACING)*numTotal; + Int boxWidth = REAL_TO_INT(s_emptyAmmo->getImageWidth() * scale); + Int boxHeight = REAL_TO_INT(s_emptyAmmo->getImageHeight() * scale); + const Int SPACING = 1; + //Int totalWidth = (boxWidth+SPACING)*numTotal; - ICoord2D screenCenter; - Coord3D pos = *obj->getPosition(); - pos.x += TheGlobalData->m_ammoPipWorldOffset.x; - pos.y += TheGlobalData->m_ammoPipWorldOffset.y; - pos.z += TheGlobalData->m_ammoPipWorldOffset.z + obj->getGeometryInfo().getMaxHeightAbovePosition(); - if( !TheTacticalView->worldToScreen( &pos, &screenCenter ) ) + ICoord2D screenCenter; + Coord3D pos = *obj->getPosition(); + pos.x += TheGlobalData->m_ammoPipWorldOffset.x; + pos.y += TheGlobalData->m_ammoPipWorldOffset.y; + pos.z += TheGlobalData->m_ammoPipWorldOffset.z + obj->getGeometryInfo().getMaxHeightAbovePosition(); + if (!TheTacticalView->worldToScreen(&pos, &screenCenter)) + return; + + Real bounding = obj->getGeometryInfo().getBoundingSphereRadius() * scale; + //Int posx = screenCenter.x + REAL_TO_INT(TheGlobalData->m_ammoPipScreenOffset.x*bounding) - totalWidth; + //**CHANGING CODE: Left justify with health bar min + Int posx = healthBarRegion->lo.x; + Int posy = screenCenter.y + REAL_TO_INT(TheGlobalData->m_ammoPipScreenOffset.y * bounding); + + // Draw only one pip, either full or empty + if (pipsStyle == AMMO_PIPS_SINGLE) { + if (numTotal <= 0) return; + + Real ammoRatio = (Real)numFull / (Real)numTotal; + + if (numFull == numTotal) { // Full + TheDisplay->drawImage(s_fullAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight); + } + else if (numFull == 0) { // Empty + TheDisplay->drawImage(s_emptyAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight); + } + else { // partial + // Color color = GameMakeColor(255 * ammoRatio, 255 * ammoRatio, 255 * ammoRatio, 255); + Color color = GameMakeColor(255, 255, 255, 255 * ammoRatio); + TheDisplay->drawImage(s_emptyAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight); + TheDisplay->drawImage(s_fullAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight, color); + } + } + else { // Default style + for (Int i = 0; i < numTotal; ++i) + { + TheDisplay->drawImage(i < numFull ? s_fullAmmo : s_emptyAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight); + posx += boxWidth + SPACING; + } + } + + return; - Real bounding = obj->getGeometryInfo().getBoundingSphereRadius() * scale; - //Int posx = screenCenter.x + REAL_TO_INT(TheGlobalData->m_ammoPipScreenOffset.x*bounding) - totalWidth; - //**CHANGING CODE: Left justify with health bar min - Int posx = healthBarRegion->lo.x; - Int posy = screenCenter.y + REAL_TO_INT(TheGlobalData->m_ammoPipScreenOffset.y*bounding); - for (Int i = 0; i < numTotal; ++i) + } + case AMMO_PIPS_BAR: { - TheDisplay->drawImage(i < numFull ? s_fullAmmo : s_emptyAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight); - posx += boxWidth + SPACING; + if (numTotal <= 0) return; + + Color color, outlineColor; + + color = GameMakeColor(255, 255, 0, 255); // yellow bar + outlineColor = GameMakeColor(0, 0, 0, 255); // black outline + + Real ammoRatio = (Real)numFull / (Real)numTotal; + + Real healthBoxWidth = healthBarRegion->hi.x - healthBarRegion->lo.x; + + Real healthBoxHeight = max(3, healthBarRegion->hi.y - healthBarRegion->lo.y) * 1.5f; + Real healthBoxOutlineSize = 1.0f; + + Real yOffset = 5; + + // draw the health (actually ammo) box outline + TheDisplay->drawOpenRect(healthBarRegion->lo.x, healthBarRegion->lo.y + yOffset, healthBoxWidth, healthBoxHeight, + healthBoxOutlineSize, outlineColor); + + if (numFull > 0) { + + // draw a filled bar for the ammo count + TheDisplay->drawFillRect(healthBarRegion->lo.x + 1, healthBarRegion->lo.y + yOffset + 1, + (healthBoxWidth - 2) * ammoRatio, healthBoxHeight - 2, + color); + } + + + return; } + } + } // ------------------------------------------------------------------------------------------------ @@ -4262,6 +4396,32 @@ Bool Drawable::handleWeaponFireFX(WeaponSlotType wslot, Int specificBarrelToUse, return false; } +//------------------------------------------------------------------------------------------------- +Bool Drawable::handleWeaponPreAttackFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, Real recoilAmount, Real recoilAngle, const Coord3D* victimPos, Real damageRadius) +{ + if (recoilAmount != 0.0f) + { + // adjust recoil from absolute to relative. + if (getObject()) + recoilAngle -= getObject()->getOrientation(); + // flip direction 180 degrees. + recoilAngle += PI; + if (m_locoInfo) + { + m_locoInfo->m_accelerationPitchRate += recoilAmount * Cos(recoilAngle); + m_locoInfo->m_accelerationRollRate += recoilAmount * Sin(recoilAngle); + } + } + + for (DrawModule** dm = getDrawModules(); *dm; ++dm) + { + ObjectDrawInterface* di = (*dm)->getObjectDrawInterface(); + if (di && di->handleWeaponPreAttackFX(wslot, specificBarrelToUse, fxl, weaponSpeed, victimPos, damageRadius)) + return true; + } + return false; +} + //------------------------------------------------------------------------------------------------- Int Drawable::getBarrelCount(WeaponSlotType wslot) const { @@ -5083,10 +5243,12 @@ void Drawable::xfer( Xfer *xfer ) xfer->xferUnsignedInt( &m_status ); // tint status - xfer->xferUnsignedInt( &m_tintStatus ); + //xfer->xferUnsignedInt( &m_tintStatus ); + m_tintStatus.xfer(xfer); // prev tint status - xfer->xferUnsignedInt( &m_prevTintStatus ); + //xfer->xferUnsignedInt( &m_prevTintStatus ); + m_prevTintStatus.xfer(xfer); // fading mode xfer->xferUser( &m_fadeMode, sizeof( FadingMode ) ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp index a589130d88..f3eadcbe85 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/SwayClientUpdate.cpp @@ -43,7 +43,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp index 4721b0e348..2bfe8c64d1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Eva.cpp @@ -31,7 +31,7 @@ #include "Common/PlayerList.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -93,7 +93,79 @@ const char *TheEvaMessageNames[] = "SUPERWEAPONLAUNCHED_OWN_SNEAK_ATTACK", "SUPERWEAPONLAUNCHED_ALLY_SNEAK_ATTACK", "SUPERWEAPONLAUNCHED_ENEMY_SNEAK_ATTACK", - + + // New constants added by OFS + + "SUPERWEAPONDETECTED_OWN_ION_CANNON", + "SUPERWEAPONDETECTED_ALLY_ION_CANNON", + "SUPERWEAPONDETECTED_ENEMY_ION_CANNON", + "SUPERWEAPONLAUNCHED_OWN_ION_CANNON", + "SUPERWEAPONLAUNCHED_ALLY_ION_CANNON", + "SUPERWEAPONLAUNCHED_ENEMY_ION_CANNON", + "SUPERWEAPONREADY_OWN_ION_CANNON", + "SUPERWEAPONREADY_ALLY_ION_CANNON", + "SUPERWEAPONREADY_ENEMY_ION_CANNON", + + "SUPERWEAPONDETECTED_OWN_CLUSTER_MISSILE", + "SUPERWEAPONDETECTED_ALLY_CLUSTER_MISSILE", + "SUPERWEAPONDETECTED_ENEMY_CLUSTER_MISSILE", + "SUPERWEAPONLAUNCHED_OWN_CLUSTER_MISSILE", + "SUPERWEAPONLAUNCHED_ALLY_CLUSTER_MISSILE", + "SUPERWEAPONLAUNCHED_ENEMY_CLUSTER_MISSILE", + "SUPERWEAPONREADY_OWN_CLUSTER_MISSILE", + "SUPERWEAPONREADY_ALLY_CLUSTER_MISSILE", + "SUPERWEAPONREADY_ENEMY_CLUSTER_MISSILE", + + "SUPERWEAPONDETECTED_OWN_SUNSTORM_MISSILE", + "SUPERWEAPONDETECTED_ALLY_SUNSTORM_MISSILE", + "SUPERWEAPONDETECTED_ENEMY_SUNSTORM_MISSILE", + "SUPERWEAPONLAUNCHED_OWN_SUNSTORM_MISSILE", + "SUPERWEAPONLAUNCHED_ALLY_SUNSTORM_MISSILE", + "SUPERWEAPONLAUNCHED_ENEMY_SUNSTORM_MISSILE", + "SUPERWEAPONREADY_OWN_SUNSTORM_MISSILE", + "SUPERWEAPONREADY_ALLY_SUNSTORM_MISSILE", + "SUPERWEAPONREADY_ENEMY_SUNSTORM_MISSILE", + + "SUPERWEAPONDETECTED_OWN_METEOR_STRIKE", + "SUPERWEAPONDETECTED_ALLY_METEOR_STRIKE", + "SUPERWEAPONDETECTED_ENEMY_METEOR_STRIKE", + "SUPERWEAPONLAUNCHED_OWN_METEOR_STRIKE", + "SUPERWEAPONLAUNCHED_ALLY_METEOR_STRIKE", + "SUPERWEAPONLAUNCHED_ENEMY_METEOR_STRIKE", + "SUPERWEAPONREADY_OWN_METEOR_STRIKE", + "SUPERWEAPONREADY_ALLY_METEOR_STRIKE", + "SUPERWEAPONREADY_ENEMY_METEOR_STRIKE", + + "SUPERWEAPONDETECTED_OWN_PUNISHER_CANNON", + "SUPERWEAPONDETECTED_ALLY_PUNISHER_CANNON", + "SUPERWEAPONDETECTED_ENEMY_PUNISHER_CANNON", + "SUPERWEAPONLAUNCHED_OWN_PUNISHER_CANNON", + "SUPERWEAPONLAUNCHED_ALLY_PUNISHER_CANNON", + "SUPERWEAPONLAUNCHED_ENEMY_PUNISHER_CANNON", + "SUPERWEAPONREADY_OWN_PUNISHER_CANNON", + "SUPERWEAPONREADY_ALLY_PUNISHER_CANNON", + "SUPERWEAPONREADY_ENEMY_PUNISHER_CANNON", + + "SUPERWEAPONDETECTED_OWN_CHEMICAL_MISSILE", + "SUPERWEAPONDETECTED_ALLY_CHEMICAL_MISSILE", + "SUPERWEAPONDETECTED_ENEMY_CHEMICAL_MISSILE", + "SUPERWEAPONLAUNCHED_OWN_CHEMICAL_MISSILE", + "SUPERWEAPONLAUNCHED_ALLY_CHEMICAL_MISSILE", + "SUPERWEAPONLAUNCHED_ENEMY_CHEMICAL_MISSILE", + "SUPERWEAPONREADY_OWN_CHEMICAL_MISSILE", + "SUPERWEAPONREADY_ALLY_CHEMICAL_MISSILE", + "SUPERWEAPONREADY_ENEMY_CHEMICAL_MISSILE", + + "SUPERWEAPONDETECTED_OWN_CHRONOSPHERE", + "SUPERWEAPONDETECTED_ALLY_CHRONOSPHERE", + "SUPERWEAPONDETECTED_ENEMY_CHRONOSPHERE", + "SUPERWEAPONLAUNCHED_OWN_CHRONOSPHERE", + "SUPERWEAPONLAUNCHED_ALLY_CHRONOSPHERE", + "SUPERWEAPONLAUNCHED_ENEMY_CHRONOSPHERE", + "SUPERWEAPONREADY_OWN_CHRONOSPHERE", + "SUPERWEAPONREADY_ALLY_CHRONOSPHERE", + "SUPERWEAPONREADY_ENEMY_CHRONOSPHERE", + //**************************************************************************** //Kris: Don't forget to add another handler below -- it's ghey-ly implemented. //**************************************************************************** @@ -156,6 +228,69 @@ const ShouldPlayFunc Eva::s_shouldPlayFuncs[] = Eva::shouldPlayGenericHandler, Eva::shouldPlayGenericHandler, Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, + Eva::shouldPlayGenericHandler, Eva::shouldPlayGenericHandler, NULL, }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp index 8bd434dfc5..11f67db386 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/FXList.cpp @@ -54,7 +54,7 @@ // PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp index 3a74a4a319..b788f33492 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ChallengeGenerals.cpp @@ -31,7 +31,7 @@ #include "GameClient/ChallengeGenerals.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp index 4d9a8774fa..663491e05c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp @@ -83,7 +83,7 @@ #include "GameNetwork/GameInfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -139,7 +139,7 @@ void ControlBar::markUIDirty( void ) { m_UIDirty = TRUE; -#if defined( _INTERNAL ) || defined( _DEBUG ) +#if defined( RTS_INTERNAL ) || defined( RTS_DEBUG ) UnsignedInt now = TheGameLogic->getFrame(); if( now == m_lastFrameMarkedDirty ) { @@ -961,7 +961,7 @@ ControlBar::ControlBar( void ) m_remainingRadarAttackGlowFrames = 0; m_radarAttackGlowWindow = NULL; -#if defined( _INTERNAL ) || defined( _DEBUG ) +#if defined( RTS_INTERNAL ) || defined( RTS_DEBUG ) m_lastFrameMarkedDirty = 0; m_consecutiveDirtyFrames = 0; #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp index aaf3fd215a..b5759c34bc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp @@ -42,6 +42,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Module/BattlePlanUpdate.h" #include "GameLogic/Module/DozerAIUpdate.h" +#include "GameLogic/Module/JetAIUpdate.h" #include "GameLogic/Module/OverchargeBehavior.h" #include "GameLogic/Module/ProductionUpdate.h" #include "GameLogic/Module/SpecialPowerModule.h" @@ -60,7 +61,7 @@ #include "GameClient/GameWindowManager.h" #include "GameClient/GadgetPushButton.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -207,9 +208,6 @@ void ControlBar::doTransportInventoryUI( Object *transport, const CommandSet *co m_commandWindows[ i ]->winHide( FALSE ); m_commandWindows[ i ]->winEnable( FALSE ); - -///////// poopy - //Clear any potential veterancy rank, or else we'll see it when it's empty! GadgetButtonDrawOverlayImage( m_commandWindows[ i ], NULL ); @@ -1061,11 +1059,19 @@ CommandAvailability ControlBar::getCommandAvailability( const CommandButton *com if( BitIsSet( command->getOptions(), MUST_BE_STOPPED ) ) { - //This button can only be activated when the unit isn't moving! + // This button can only be activated when the unit isn't moving! + // Jets can be idle while in the air, so we need to do more checks AIUpdateInterface *ai = obj->getAI(); - if( ai && ai->isMoving() ) - { - return COMMAND_RESTRICTED; + if( ai ) { + JetAIUpdate* jetAI = ai->getJetAIUpdate(); + if (jetAI) { + if (!jetAI->isParkedInHangar()) { + return COMMAND_RESTRICTED; + } + } + else if (ai->isMoving()) { + return COMMAND_RESTRICTED; + } } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp index d898043ffc..27ea05cb72 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommandProcessing.cpp @@ -56,7 +56,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ProductionUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp index 598ecf0c50..daa7176c15 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarMultiSelect.cpp @@ -40,7 +40,7 @@ #include "GameClient/InGameUI.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp index 2d8ea77453..22e49b08fe 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp @@ -62,7 +62,7 @@ #include "GameClient/Image.h" #include "GameClient/GameWindowManager.h" #include "GameClient/GadgetPushButton.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp index ebf57a867a..0afb55edf6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarStructureInventory.cpp @@ -44,7 +44,7 @@ #include "GameClient/GadgetPushButton.h" #include "GameClient/HotKey.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp index f54463db74..dcddb56f4b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarPopupDescription.cpp @@ -93,7 +93,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp index 2f29ed4e25..217c38ccb6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Diplomacy.cpp @@ -57,7 +57,7 @@ #include "GameNetwork/GameSpy/BuddyDefs.h" #include "GameNetwork/GameSpy/PeerDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp index a05402fdba..7d3c2d6898 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ChallengeMenu.cpp @@ -55,7 +55,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp index b1bc00c8c6..afb9fb5eb3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/CreditsMenu.cpp @@ -47,7 +47,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp index 9923c809b4..ebbcd496b2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/GameInfoWindow.cpp @@ -44,7 +44,7 @@ #include "GameNetwork/GameInfo.h" #include "GameNetwork/LANAPI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp index bdf136bf30..a2da56d65a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp @@ -60,7 +60,7 @@ #include "GameClient/GameText.h" #include "GameNetwork/GUIUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp index 1e60028998..6c589f39b6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanMapSelectMenu.cpp @@ -44,7 +44,7 @@ #include "GameClient/MapUtil.h" #include "GameNetwork/GUIUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp index c0e1bd51bd..f507410f4d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp @@ -78,7 +78,7 @@ //for accessing the InGameUI #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -101,7 +101,7 @@ enum static Bool raiseMessageBoxes = TRUE; static Bool campaignSelected = FALSE; -#if defined _DEBUG || defined _INTERNAL || defined _PROFILE +#if defined RTS_DEBUG || defined RTS_INTERNAL || defined RTS_PROFILE static NameKeyType campaignID = NAMEKEY_INVALID; static GameWindow *buttonCampaign = NULL; #ifdef TEST_COMPRESSION @@ -554,7 +554,7 @@ void MainMenuInit( WindowLayout *layout, void *userData ) showSelectiveButtons(SHOW_NONE); // Set up the version number -#if defined _DEBUG || defined _INTERNAL || defined _PROFILE +#if defined RTS_DEBUG || defined RTS_INTERNAL || defined RTS_PROFILE WinInstanceData instData; #ifdef TEST_COMPRESSION instData.init(); @@ -1309,7 +1309,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, if(buttonPushed) break; -#if defined _DEBUG || defined _INTERNAL || defined _PROFILE +#if defined RTS_DEBUG || defined RTS_INTERNAL || defined RTS_PROFILE if( control == buttonCampaign ) { buttonPushed = TRUE; @@ -1509,10 +1509,10 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, } // end else if else if( controlID == worldBuilderID ) { -#if defined _DEBUG +#if defined RTS_DEBUG if(_spawnl(_P_NOWAIT,"WorldBuilderD.exe","WorldBuilderD.exe", NULL) < 0) MessageBoxOk(TheGameText->fetch("GUI:WorldBuilder"), TheGameText->fetch("GUI:WorldBuilderLoadFailed"),NULL); -#elif defined _INTERNAL +#elif defined RTS_INTERNAL if(_spawnl(_P_NOWAIT,"WorldBuilderI.exe","WorldBuilderI.exe", NULL) < 0) MessageBoxOk(TheGameText->fetch("GUI:WorldBuilder"), TheGameText->fetch("GUI:WorldBuilderLoadFailed"),NULL); #else @@ -1527,7 +1527,7 @@ WindowMsgHandledType MainMenuSystem( GameWindow *window, UnsignedInt msg, else if( controlID == exitID ) { // If we ever want to add a dialog before we exit out of the game, uncomment this line and kill the quitCallback() line below. -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //Added By Sadullah Nader //Changed the preprocessing code to normal code diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp index 124e5389c6..5a39d2b626 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/NetworkDirectConnect.cpp @@ -50,7 +50,7 @@ #include "GameNetwork/LANAPI.h" #include "GameNetwork/LANAPICallbacks.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp index 208a87dbaf..fa5dd193b6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp @@ -75,7 +75,7 @@ // This is for non-RC builds only!!! #define VERBOSE_VERSION L"Release" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp index 31c85f4f1e..efd7235e58 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupHostGame.cpp @@ -100,7 +100,7 @@ static GameWindow *textEntryGamePassword = NULL; static GameWindow *checkBoxLimitArmies = NULL; static GameWindow *checkBoxUseStats = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp index 6fbc351447..35079a15d1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupLadderSelect.cpp @@ -68,7 +68,7 @@ //#include "GameNetwork/GameSpy/PeerThread.h" #include "GameNetwork/GameSpyOverlay.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp index c86e3865a1..60fdf4da2f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupPlayerInfo.cpp @@ -60,7 +60,7 @@ #include "WWDownload/Registry.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp index 30e8c58580..b583f3ea71 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/PopupReplay.cpp @@ -59,7 +59,7 @@ #include "GameClient/Shell.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp index df4920b5b7..0a226e3040 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/QuitMenu.cpp @@ -53,7 +53,7 @@ #include "GameClient/DisconnectMenu.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp index f0166d2441..ed85fa7902 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ReplayMenu.cpp @@ -48,7 +48,7 @@ #include "GameClient/GameText.h" #include "GameClient/GameWindowTransitions.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -75,7 +75,7 @@ static Int initialGadgetDelay = 2; static Bool justEntered = FALSE; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL static GameWindow *buttonAnalyzeReplay = NULL; #endif @@ -181,7 +181,10 @@ void PopulateReplayFileListbox(GameWindow *listbox) const MapMetaData *md = TheMapCache->findMap(info.getMap()); if (!md) { - mapStr.translate(info.getMap()); + // TheSuperHackers @bugfix helmutbuhler 08/03/2025 Just use the filename. + // Displaying a long map path string would break the map list gui. + const char* filename = info.getMap().reverseFind('\\'); + mapStr.translate(filename ? filename + 1 : info.getMap()); } else { @@ -291,7 +294,7 @@ void ReplayMenuInit( WindowLayout *layout, void *userData ) GadgetListBoxReset(listboxReplayFiles); PopulateReplayFileListbox(listboxReplayFiles); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL WinInstanceData instData; instData.init(); BitSet( instData.m_style, GWS_PUSH_BUTTON | GWS_MOUSE_TRACK ); @@ -512,7 +515,7 @@ WindowMsgHandledType ReplayMenuSystem( GameWindow *window, UnsignedInt msg, GameWindow *control = (GameWindow *)mData1; Int controlID = control->winGetWindowId(); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if( controlID == buttonAnalyzeReplay->winGetWindowId() ) { if(listboxReplayFiles) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp index 0fa6d09f85..97a2751f75 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/ScoreScreen.cpp @@ -101,7 +101,7 @@ #include "GameClient/InGameUI.h" #include "GameClient/ChallengeGenerals.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp index b9aac9e512..deed879d81 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp @@ -69,7 +69,7 @@ #include "GameNetwork/IPEnumeration.h" #include "WWDownload/Registry.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -466,7 +466,7 @@ static MessageBoxReturnType cancelStartBecauseOfNoCD( void *userData ) Bool IsFirstCDPresent(void) { -#if !defined(_INTERNAL) && !defined(_DEBUG) +#if !defined(RTS_INTERNAL) && !defined(RTS_DEBUG) return TheFileSystem->areMusicFilesOnCD(); #else return TRUE; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp index ff9afd41fd..a1a9b8d9be 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLBuddyOverlay.cpp @@ -57,7 +57,7 @@ // PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp index 0da8930603..f7a0059a1b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp @@ -67,7 +67,7 @@ void WOLDisplaySlotList( void ); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -77,7 +77,7 @@ extern std::list TheLobbyQueuedUTMs; extern void MapSelectorTooltip(GameWindow *window, WinInstanceData *instData, UnsignedInt mouse); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern Bool g_debugSlots; void slotListDebugLog(const char *fmt, ...) { @@ -1960,7 +1960,7 @@ void WOLGameSetupMenuUpdate( WindowLayout * layout, void *userData) case PeerResponse::PEERRESPONSE_ROOMUTM: { sawImportantMessage = TRUE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (g_debugSlots) { DEBUG_LOG(("About to process a room UTM. Command is '%s', command options is '%s'\n", @@ -2524,7 +2524,7 @@ Bool handleGameSetupSlashCommands(UnicodeString uText) TheGameSpyInfo->sendChat(UnicodeString(uText.str()+4), TRUE, NULL); return TRUE; // was a slash command } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) else if (token == "slots") { g_debugSlots = !g_debugSlots; @@ -2538,7 +2538,7 @@ Bool handleGameSetupSlashCommands(UnicodeString uText) TheGameSpyPeerMessageQueue->addRequest( req ); return TRUE; } -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) return FALSE; // not a slash command } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp index a8490ad6c3..760fbb362c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLobbyMenu.cpp @@ -70,7 +70,7 @@ #include "GameNetwork/GameSpy/LobbyUtils.h" #include "GameNetwork/RankPointValue.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -133,7 +133,7 @@ static Int groupRoomToJoin = 0; static Int initialGadgetDelay = 2; static Bool justEntered = FALSE; -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) Bool g_fakeCRC = FALSE; Bool g_debugSlots = FALSE; #endif @@ -202,7 +202,7 @@ Bool handleLobbySlashCommands(UnicodeString uText) return TRUE; // was a slash command } */ -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) else if (token == "fakecrc") { g_fakeCRC = !g_fakeCRC; @@ -1571,7 +1571,7 @@ WindowMsgHandledType WOLLobbyMenuSystem( GameWindow *window, UnsignedInt msg, { // bad crc. don't go. DEBUG_LOG(("WOLLobbyMenuSystem - CRC mismatch with the game I'm trying to join. My CRC's - EXE:0x%08X INI:0x%08X Their CRC's - EXE:0x%08x INI:0x%08x\n", TheGlobalData->m_exeCRC, TheGlobalData->m_iniCRC, roomToJoin->getExeCRC(), roomToJoin->getIniCRC())); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_netMinPlayers) { GSMessageBoxOk(TheGameText->fetch("GUI:JoinFailedDefault"), TheGameText->fetch("GUI:JoinFailedCRCMismatch")); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp index 5da99177a7..522a354c93 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLocaleSelectPopup.cpp @@ -48,7 +48,7 @@ #include "GameNetwork/GameSpy/PersistentStorageDefs.h" #include "GameNetwork/GameSpy/PersistentStorageThread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp index 93d53e0043..689a41b288 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLLoginMenu.cpp @@ -68,7 +68,7 @@ #include "GameNetwork/WOLBrowser/WebBrowser.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp index 8d3dca851e..ae27048b6b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLMapSelectMenu.cpp @@ -44,7 +44,7 @@ #include "GameClient/MapUtil.h" #include "GameNetwork/GUIUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp index 51a149941f..e281adc384 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLQuickMatchMenu.cpp @@ -66,7 +66,7 @@ #include "GameNetwork/GameSpy/PersistentStorageThread.h" #include "GameNetwork/RankPointValue.h" #include "GameNetwork/GameSpy/LadderDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp index 3f71929f26..202139339f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLWelcomeMenu.cpp @@ -69,7 +69,7 @@ #include "GameNetwork/GameSpy/MainMenuUtils.h" #include "GameNetwork/WOLBrowser/WebBrowser.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp index 3866451a9d..665fa2ca81 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetHorizontalSlider.cpp @@ -67,7 +67,7 @@ /////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp index 6d33152c55..17d9b65619 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp @@ -63,7 +63,7 @@ #include "GameClient/GameWindowGlobal.h" #include "GameClient/Keyboard.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp index 0dd85bc3e7..2e39eb0d3a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp @@ -54,7 +54,7 @@ #include "GameClient/GameWindowManager.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp index 04824f1963..4e7c3c12a6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp @@ -57,7 +57,7 @@ // DEFINES //////////////////////////////////////////////////////////////////// // PRIVATE TYPES ////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp index 6c24dd661c..71168137cf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetVerticalSlider.cpp @@ -66,7 +66,7 @@ /////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp index 6c673defee..f612ac7533 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp @@ -61,7 +61,7 @@ #include "GameClient/GadgetStaticText.h" #include "GameClient/Mouse.h" #include "GameClient/SelectionXlat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp index 93c40ade6f..4be961bc34 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp @@ -61,7 +61,7 @@ UnsignedInt WindowLayoutCurrentVersion = 2; /////////////////////////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp index 006be86fc1..71a803aa5c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp @@ -72,7 +72,7 @@ #include "GameClient/GameText.h" #include "GameClient/HeaderTemplate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp index 72d1fb152f..d09f45fcc1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitions.cpp @@ -47,7 +47,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp index 3da8f36617..61ee3319f9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowTransitionsStyles.cpp @@ -47,7 +47,7 @@ // SYSTEM INCLUDES //////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp index 00a52d3f65..bfde39d203 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/HeaderTemplate.cpp @@ -60,7 +60,7 @@ #include "GameClient/HeaderTemplate.h" #include "GameClient/GameFont.h" #include "GameClient/GlobalLanguage.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp index a56dec0baf..08ab7b231a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp @@ -61,7 +61,7 @@ #include "GameClient/Color.h" #include "Common/NameKeyGenerator.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp index 91b2f6eb2f..21d3c892af 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/LoadScreen.cpp @@ -90,7 +90,7 @@ // DEFINES //////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp index 4fb7455338..47039e76a5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp @@ -47,7 +47,7 @@ // PUBLIC DATA //////////////////////////////////////////////////////////////////////////////////// Shell *TheShell = NULL; ///< the shell singleton definition -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -460,7 +460,7 @@ void Shell::showShell( Bool runInit ) if (!TheGlobalData->m_shellMapOn && m_screenCount == 0) { -#ifdef _PROFILE +#ifdef RTS_PROFILE Profile::StopRange("init"); #endif //else diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp index 21632e84bd..bd63f3d13a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/WindowLayout.cpp @@ -33,7 +33,7 @@ #include "GameClient/WindowLayout.h" #include "GameClient/Shell.h" #include "GameClient/GameWindowManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp index 178189044c..ee53c2779e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp @@ -83,7 +83,7 @@ #include "GameLogic/GhostObject.h" #include "GameLogic/Object.h" #include "GameLogic/ScriptEngine.h" // For TheScriptEngine - jkmcd -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -450,12 +450,11 @@ void GameClient::init( void ) void GameClient::reset( void ) { Drawable *draw, *nextDraw; - m_drawableHash.clear(); -#if USING_STLPORT - m_drawableHash.resize(DRAWABLE_HASH_SIZE); -#else - m_drawableHash.reserve(DRAWABLE_HASH_SIZE); -#endif +// m_drawableHash.clear(); +// m_drawableHash.resize(DRAWABLE_HASH_SIZE); + + m_drawableVector.clear(); + m_drawableVector.resize(DRAWABLE_HASH_SIZE, NULL); // need to reset the in game UI to clear drawables before they are destroyed TheInGameUI->reset(); @@ -479,6 +478,9 @@ void GameClient::reset( void ) // clear any drawable TOC we might have m_drawableTOC.clear(); + // TheSuperHackers @fix Mauller 13/04/2025 Reset the drawable id so it does not keep growing over the lifetime of the game. + m_nextDrawableID = (DrawableID)1; + } // end reset /** ----------------------------------------------------------------------------------------------- @@ -656,7 +658,7 @@ void GameClient::update( void ) if (!freezeTime) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) #else if (true) @@ -687,7 +689,7 @@ void GameClient::update( void ) while (draw) { // update() could free the Drawable, so go ahead and grab 'next' Drawable* next = draw->getNextDrawable(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) #else if (true) @@ -724,7 +726,7 @@ void GameClient::update( void ) } } -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) // need to draw the first frame, then don't draw again until TheGlobalData->m_noDraw if (TheGlobalData->m_noDraw > TheGameLogic->getFrame() && TheGameLogic->getFrame() > 0) { @@ -863,7 +865,12 @@ void GameClient::addDrawableToLookupTable(Drawable *draw ) return; // add to lookup - m_drawableHash[ draw->getID() ] = draw; +// m_drawableHash[ draw->getID() ] = draw; + DrawableID newID = draw->getID(); + while( newID >= m_drawableVector.size() ) // Fail case is hella rare, so faster to double up on size() call + m_drawableVector.resize(m_drawableVector.size() * 2, NULL); + + m_drawableVector[ newID ] = draw; } // end addDrawableToLookupTable @@ -874,11 +881,13 @@ void GameClient::removeDrawableFromLookupTable( Drawable *draw ) { // sanity - if( draw == NULL ) + // TheSuperHackers @fix Mauller/Xezon 24/04/2025 Prevent out of range access to vector lookup table + if( draw == NULL || static_cast(draw->getID()) >= m_drawableVector.size() ) return; // remove from table - m_drawableHash.erase( draw->getID() ); +// m_drawableHash.erase( draw->getID() ); + m_drawableVector[ draw->getID() ] = NULL; } // end removeDrawableFromLookupTable diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp index 2a1688c6a7..17fd2e9d65 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameText.cpp @@ -48,6 +48,7 @@ #include "GameClient/GameText.h" #include "Common/Language.h" #include "Common/Registry.h" +#include "GameClient/ClientInstance.h" #include "GameClient/LanguageFilter.h" #include "Common/Debug.h" #include "Common/UnicodeString.h" @@ -57,7 +58,7 @@ #include "Common/FileSystem.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -68,7 +69,7 @@ // Externals //---------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool g_useStringFile = TRUE; #endif @@ -167,7 +168,7 @@ class GameTextManager : public GameTextInterface StringInfo *m_stringInfo; StringLookUp *m_stringLUT; Bool m_initialized; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_jabberWockie; Bool m_munkee; #endif @@ -248,7 +249,7 @@ GameTextManager::GameTextManager() m_stringLUT(NULL), m_initialized(FALSE), m_noStringList(NULL), -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_jabberWockie(FALSE), m_munkee(FALSE), m_useStringFile(g_useStringFile), @@ -301,7 +302,7 @@ void GameTextManager::init( void ) m_initialized = TRUE; m_maxLabelLen = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if(TheGlobalData) { m_jabberWockie = TheGlobalData->m_jabberOn; @@ -370,6 +371,14 @@ void GameTextManager::init( void ) qsort( m_stringLUT, m_textCount, sizeof(StringLookUp), compareLUT ); UnicodeString ourName = fetch("GUI:Command&ConquerGenerals"); + + if (rts::ClientInstance::getInstanceId() > 1u) + { + UnicodeString s; + s.format(L"Instance:%.2u - %s", rts::ClientInstance::getInstanceId(), ourName.str()); + ourName = s; + } + AsciiString ourNameA; ourNameA.translate(ourName); //get ASCII version for Win 9x @@ -695,7 +704,7 @@ void GameTextManager::translateCopy( WideChar *outbuf, Char *inbuf ) { Int slash = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if ( m_jabberWockie ) { static Char buffer[MAX_UITEXT_LENGTH*2]; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp index 1fa290fa39..344670c9d5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp @@ -90,7 +90,7 @@ #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2222,7 +2222,7 @@ void InGameUI::createGarrisonHint( const GameMessage *msg ) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define AI_DEBUG_TOOLTIPS 1 #ifdef AI_DEBUG_TOOLTIPS @@ -2231,7 +2231,7 @@ void InGameUI::createGarrisonHint( const GameMessage *msg ) #include "GameLogic/AIPathfind.h" #endif // AI_DEBUG_TOOLTIPS -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------------------------------- /** Details of what is mouse hovered over right now are in this message. Terrain might result @@ -2307,7 +2307,7 @@ void InGameUI::createMouseoverHint( const GameMessage *msg ) else m_mousedOverDrawableID = draw->getID(); -#if defined(_DEBUG) || defined(_INTERNAL) //Extra hacky, sorry, but I need to use this in constantdebug report +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //Extra hacky, sorry, but I need to use this in constantdebug report if ( TheGlobalData->m_constantDebugUpdate == TRUE ) m_mousedOverDrawableID = draw->getID(); #endif @@ -2533,7 +2533,7 @@ void InGameUI::createCommandHint( const GameMessage *msg ) { const Object* obj = draw->getObject(); Int localPlayerIndex = ThePlayerList ? ThePlayerList->getLocalPlayer()->getPlayerIndex() : 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ObjectShroudStatus ss = (!obj || !TheGlobalData->m_shroudOn) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); #else ObjectShroudStatus ss = (!obj) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); @@ -3583,54 +3583,81 @@ void InGameUI::postDraw( void ) Player *localPlayer = ThePlayerList->getLocalPlayer(); - if( type == SPECIAL_PARTICLE_UPLINK_CANNON || type == SUPW_SPECIAL_PARTICLE_UPLINK_CANNON || type == LAZR_SPECIAL_PARTICLE_UPLINK_CANNON ) - { - if ( localPlayer == owningObject->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponReady_Own_ParticleCannon); - } - else if ( localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponReady_Ally_ParticleCannon); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponReady_Enemy_ParticleCannon); - } - } - else if( type == SPECIAL_NEUTRON_MISSILE || type == NUKE_SPECIAL_NEUTRON_MISSILE || type == SUPW_SPECIAL_NEUTRON_MISSILE ) - { - if ( localPlayer == owningObject->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponReady_Own_Nuke); - } - else if ( localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponReady_Ally_Nuke); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponReady_Enemy_Nuke); - } - } - else if (type == SPECIAL_SCUD_STORM) - { - if ( localPlayer == owningObject->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponReady_Own_ScudStorm); - } - else if ( localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponReady_Ally_ScudStorm); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponReady_Enemy_ScudStorm); - } - } + // Check if SpecialPower eva event instead of hardcoded stuff + bool isOwn = localPlayer == owningObject->getControllingPlayer(); + bool isAlly = localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES; + bool isEnemy = !isOwn && !isAlly; + bool isDefault = type < SPECIAL_ION_CANNON; // first new Special Power + + //Check SpecialPower Eva + const SpecialPowerTemplate* specialPowerTemp = module->getSpecialPowerTemplate(); + EvaMessage eva = EVA_Invalid; + + if (isOwn) { + eva = specialPowerTemp->getEvaReadyOwn(); + } + else if (isAlly) { + eva = specialPowerTemp->getEvaReadyAlly(); + } + else if (isEnemy) { + eva = specialPowerTemp->getEvaReadyEnemy(); + } + + if (eva > EVA_FIRST) { + TheEva->setShouldPlay(eva); + } + else if (eva == EVA_Invalid && isDefault) { + //DO the hardcoded vanilla stuff + + if (type == SPECIAL_PARTICLE_UPLINK_CANNON || type == SUPW_SPECIAL_PARTICLE_UPLINK_CANNON || type == LAZR_SPECIAL_PARTICLE_UPLINK_CANNON) + { + if (localPlayer == owningObject->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponReady_Own_ParticleCannon); + } + else if (localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponReady_Ally_ParticleCannon); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponReady_Enemy_ParticleCannon); + } + } + else if (type == SPECIAL_NEUTRON_MISSILE || type == NUKE_SPECIAL_NEUTRON_MISSILE || type == SUPW_SPECIAL_NEUTRON_MISSILE) + { + if (localPlayer == owningObject->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponReady_Own_Nuke); + } + else if (localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponReady_Ally_Nuke); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponReady_Enemy_Nuke); + } + } + else if (type == SPECIAL_SCUD_STORM) + { + if (localPlayer == owningObject->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponReady_Own_ScudStorm); + } + else if (localPlayer->getRelationship(owningObject->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponReady_Ally_ScudStorm); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponReady_Enemy_ScudStorm); + } + } + } } info->m_evaReadyPlayed = true; } @@ -5001,7 +5028,7 @@ void InGameUI::addFloatingText(const UnicodeString& text,const Coord3D *pos, Col //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline Bool isClose(Real a, Real b) { return fabs(a-b) <= 1.0f; } inline Bool isClose(const Coord3D& a, const Coord3D& b) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp index a69c8755ff..22abf438fc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp @@ -47,7 +47,7 @@ #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp index e27fe0d7cf..b7fabb01f3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/LanguageFilter.cpp @@ -29,7 +29,7 @@ #include "Common/FileSystem.h" #include "Common/file.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp index 4ecbe7f72c..fa1dca801a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MapUtil.cpp @@ -61,7 +61,7 @@ #include "GameNetwork/GameInfo.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -467,7 +467,7 @@ void MapCache::updateCache( void ) writeCacheINI( TRUE ); } loadStandardMaps(); // we shall overwrite info from matching user maps to prevent munkees from getting rowdy :) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheLocalFileSystem->doesFileExist(getMapDir().str())) { // only create the map cache file if "Maps" exist @@ -506,7 +506,7 @@ void MapCache::loadStandardMaps(void) INI ini; AsciiString fname; fname.format("%s\\%s", getMapDir().str(), m_mapCacheName); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) File *fp = TheFileSystem->openFile(fname.str(), File::READ); if (fp != NULL) { @@ -514,7 +514,7 @@ void MapCache::loadStandardMaps(void) fp = NULL; #endif ini.load( fname, INI_LOAD_OVERWRITE, NULL ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } #endif } diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp index 02fd3145c3..149c1e3110 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp @@ -86,7 +86,7 @@ #include "GameNetwork/GameSpyOverlay.h" #include "GameNetwork/GameSpy/BuddyThread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -97,7 +97,7 @@ #define dont_ALLOW_ALT_F4 -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /*non-static*/ Real TheSkateDistOverride = 0.0f; void countObjects(Object *obj, void *userData) @@ -2349,7 +2349,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage return DESTROY_MESSAGE; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ExtentModType extentModType = EXTENTMOD_INVALID; Real extentModAmount = 0.0f; #endif @@ -3016,7 +3016,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEPLOY: - #ifdef _DEBUG + #ifdef RTS_DEBUG DEBUG_ASSERTCRASH(FALSE, ("unimplemented meta command MSG_META_DEPLOY !")); #endif /// @todo srj implement me @@ -3025,7 +3025,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_FOLLOW: - #ifdef _DEBUG + #ifdef RTS_DEBUG DEBUG_ASSERTCRASH(FALSE, ("unimplemented meta command MSG_META_FOLLOW !")); #endif /// @todo srj implement me @@ -3814,7 +3814,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //------------------------------------------------------------------------------- DEMO MESSAGES -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------- BEGIN DEMO MESSAGES //------------------------------------------------------------------------- BEGIN DEMO MESSAGES //------------------------------------------------------------------------- BEGIN DEMO MESSAGES @@ -5127,11 +5127,11 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage //--------------------------------------------------------------------------- END DEMO MESSAGES //--------------------------------------------------------------------------- END DEMO MESSAGES //--------------------------------------------------------------------------- END DEMO MESSAGES -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------DEMO MESSAGES //----------------------------------------------------------------------------------------- -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) case GameMessage::MSG_META_DEMO_TOGGLE_AUDIODEBUG: { if (TheDisplay->getDebugDisplayCallback() == AudioDebugDisplay) @@ -5142,7 +5142,7 @@ GameMessageDisposition CommandTranslator::translateGameMessage(const GameMessage break; } -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS //------------------------------------------------------------------------DEMO MESSAGES diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp index a1d656d9e7..8ca58a23fc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/GUICommandTranslator.cpp @@ -47,7 +47,7 @@ #include "GameClient/GUICommandTranslator.h" #include "GameClient/CommandXlat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp index ccd835bfc7..4259d3f53b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp @@ -336,7 +336,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage m_anchor = msg->getArgument( 0 )->pixel; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // adjust the field of view if (m_isChangingFOV) { @@ -494,7 +494,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage } // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_BEGIN_ADJUST_PITCH: { DEBUG_ASSERTCRASH(!m_isPitching, ("hmm, mismatched m_isPitching")); @@ -502,10 +502,10 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage disp = DESTROY_MESSAGE; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_END_ADJUST_PITCH: { DEBUG_ASSERTCRASH(m_isPitching, ("hmm, mismatched m_isPitching")); @@ -513,16 +513,16 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage disp = DESTROY_MESSAGE; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_DESHROUD: { ThePartitionManager->revealMapForPlayerPermanently( ThePlayerList->getLocalPlayer()->getPlayerIndex() ); break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ #if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) @@ -537,7 +537,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage #endif // #if defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_ENSHROUD: { // Need to first undo the permanent Look laid down by DEMO_DESHROUD, then blast a shroud dollop. @@ -545,10 +545,10 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage ThePartitionManager->shroudMapForPlayer( ThePlayerList->getLocalPlayer()->getPlayerIndex() ); break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_BEGIN_ADJUST_FOV: { //DEBUG_ASSERTCRASH(!m_isChangingFOV, ("hmm, mismatched m_isChangingFOV")); @@ -556,17 +556,17 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage m_anchor = m_currentPos; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_END_ADJUST_FOV: { // DEBUG_ASSERTCRASH(m_isChangingFOV, ("hmm, mismatched m_isChangingFOV")); m_isChangingFOV = false; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_SAVE_VIEW1: @@ -610,7 +610,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage } //----------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) case GameMessage::MSG_META_DEMO_LOCK_CAMERA_TO_PLANES: { Drawable *first = NULL; @@ -671,7 +671,7 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage disp = DESTROY_MESSAGE; break; } -#endif // #if defined(_DEBUG) || defined(_INTERNAL) +#endif // #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } // end switch diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp index 557cc39166..5f7f65ee35 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/MetaEvent.cpp @@ -62,7 +62,7 @@ MetaMap *TheMetaMap = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -208,7 +208,7 @@ static const LookupListRec GameMessageMetaTypeNames[] = #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) { "HELP", GameMessage::MSG_META_HELP }, { "DEMO_TOGGLE_BEHIND_BUILDINGS", GameMessage::MSG_META_DEMO_TOGGLE_BEHIND_BUILDINGS }, @@ -333,12 +333,12 @@ static const LookupListRec GameMessageMetaTypeNames[] = { "DEBUG_OBJECT_ID_PERFORMANCE", GameMessage::MSG_META_DEBUG_OBJECT_ID_PERFORMANCE }, { "DEBUG_DRAWABLE_ID_PERFORMANCE", GameMessage::MSG_META_DEBUG_DRAWABLE_ID_PERFORMANCE }, { "DEBUG_SLEEPY_UPDATE_PERFORMANCE", GameMessage::MSG_META_DEBUG_SLEEPY_UPDATE_PERFORMANCE }, -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) -#if defined(_INTERNAL) || defined(_DEBUG) +#if defined(RTS_INTERNAL) || defined(RTS_DEBUG) { "DEMO_TOGGLE_AUDIODEBUG", GameMessage::MSG_META_DEMO_TOGGLE_AUDIODEBUG }, -#endif//defined(_INTERNAL) || defined(_DEBUG) +#endif//defined(RTS_INTERNAL) || defined(RTS_DEBUG) #ifdef DUMP_PERF_STATS { "DEMO_PERFORM_STATISTICAL_DUMP", GameMessage::MSG_META_DEMO_PERFORM_STATISTICAL_DUMP }, #endif//DUMP_PERF_STATS diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp index 64b40aabe2..16ba5e79e6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp @@ -46,7 +46,7 @@ #include "GameLogic/Module/ProductionUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp index 2ef2f2bfa5..a5dbb81428 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp @@ -56,7 +56,7 @@ #include "GameClient/SelectionXlat.h" #include "GameClient/TerrainVisual.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -67,11 +67,11 @@ //----------------------------------------------------------------------------- // Lorenzen changed this to a member of SelectionTranslator, providing external access // name ly in rebuildholeexposedie, where we decide whether to create GLA Holes when hand-of-Godding -//#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) //static Bool TheHandOfGodSelectionMode = false; //#endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) static Bool TheHurtSelectionMode = false; static Bool TheDebugSelectionMode = false; #endif @@ -284,7 +284,7 @@ SelectionTranslator::SelectionTranslator() TheSelectionTranslator = this; -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) m_HandOfGodSelectionMode = FALSE; #endif } @@ -835,7 +835,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (m_HandOfGodSelectionMode && draw) @@ -1283,7 +1283,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEMO_TOGGLE_HAND_OF_GOD_MODE: { @@ -1311,7 +1311,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEMO_TOGGLE_HURT_ME_MODE: { @@ -1325,7 +1325,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessa } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //----------------------------------------------------------------------------------------- case GameMessage::MSG_META_DEMO_DEBUG_SELECTION: { diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp index 06f705ac15..cce35480d4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp @@ -55,7 +55,7 @@ #include "GameClient/Shell.h" #include "GameClient/Display.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -75,7 +75,7 @@ // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats extern ICoord2D TheMousePos; #endif @@ -236,7 +236,7 @@ GameMessageDisposition WindowTranslator::translateGameMessage(const GameMessage { // all window events have the position of the mouse as arg 0 ICoord2D mousePos = msg->getArgument( 0 )->pixel; -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats TheMousePos.x = mousePos.x; TheMousePos.y = mousePos.y; #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/ParabolicEase.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/ParabolicEase.cpp index 32873a1eb8..b393145d45 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/ParabolicEase.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/ParabolicEase.cpp @@ -26,11 +26,11 @@ #include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine #include "GameClient/ParabolicEase.h" // ============================================================================ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... // #pragma optimize("", off) // #pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") -#endif // _INTERNAL +#endif // RTS_INTERNAL // ============================================================================ namespace { // ============================================================================ diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp index bf700306d7..c0ffe556a0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/RadiusDecal.cpp @@ -36,7 +36,7 @@ #include "GameClient/Shadow.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp index 4a0d4eeb0f..dba71ac691 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/SelectionInfo.cpp @@ -39,7 +39,7 @@ #include "GameClient/Drawable.h" #include "GameClient/KeyDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -344,7 +344,7 @@ void translatePickTypesToKindof(UnsignedInt pickTypes, KindOfMaskType& outMask) Bool addDrawableToList( Drawable *draw, void *userData ) { PickDrawableStruct *pds = (PickDrawableStruct *) userData; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_allowUnselectableSelection) { pds->drawableListToFill->push_back(draw); return TRUE; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp index 7ffadd629d..e2617586b6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Snow.cpp @@ -31,7 +31,7 @@ #include "GameClient/Snow.h" #include "GameClient/View.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -99,6 +99,13 @@ SnowManager::~SnowManager() { delete [] m_startingHeights; m_startingHeights=NULL; + + // TheSuperHackers @fix Mauller 13/04/2025 Delete the instance of the weather settings + if (TheWeatherSetting) + { + ((WeatherSetting*)TheWeatherSetting.getNonOverloadedPointer())->deleteInstance(); + TheWeatherSetting=NULL; + } } OVERRIDE TheWeatherSetting = NULL; diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp index 7c4a8c0117..81337f99ae 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Anim2D.cpp @@ -38,7 +38,7 @@ #include "GameClient/Image.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp index 22869a2497..f4a1c81ffb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/CampaignManager.cpp @@ -66,7 +66,7 @@ CampaignManager *TheCampaignManager = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp index 9b14ec6bbd..ee540455da 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Debug Displayers/AudioDebugDisplay.cpp @@ -105,7 +105,7 @@ static void printFunc( char *text ) // AudioDebugDisplay //============================================================================ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void AudioDebugDisplay ( DebugDisplayInterface *dd, void *, FILE *fp = NULL ) { TheAudio->audioDebugDisplay( dd, NULL, fp ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp index 351cd79157..a3ad171e9d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp @@ -49,7 +49,7 @@ #include "GameLogic/Object.h" #include "GameLogic/TerrainLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -760,7 +760,6 @@ ParticleSystemInfo::ParticleSystemInfo() } - void ParticleSystemInfo::tintAllColors( Color tintColor ) { RGBColor rgb; @@ -769,6 +768,7 @@ void ParticleSystemInfo::tintAllColors( Color tintColor ) //This tints all but the first colorKey!!! for (int key = 1; key < MAX_KEYFRAMES; ++key ) { + // AW: Isn't this wrong? rgb.red is already float m_colorKey[ key ].color.red *= (Real)(rgb.red ) / 255.0f; m_colorKey[ key ].color.green *= (Real)(rgb.green) / 255.0f; m_colorKey[ key ].color.blue *= (Real)(rgb.blue ) / 255.0f; @@ -776,6 +776,21 @@ void ParticleSystemInfo::tintAllColors( Color tintColor ) } // end loadPostProcess +// ---------------- +void ParticleSystemInfo::tintColorsAllFrames(Color tintColor) +{ + RGBColor rgb; + rgb.setFromInt(tintColor); + + //This tints all but the first colorKey!!! + for (int key = 0; key < MAX_KEYFRAMES; key++) + { + m_colorKey[key].color.red *= rgb.red; + m_colorKey[key].color.green *= rgb.green; + m_colorKey[key].color.blue *= rgb.blue; + } + +} // ------------------------------------------------------------------------------------------------ /** CRC */ diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Smudge.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Smudge.cpp index a41e6535c0..436a83da99 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/Smudge.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/Smudge.cpp @@ -30,7 +30,7 @@ #include "PreRTS.h" // This must go first in EVERY cpp file int the Game #include "GameClient/Smudge.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp index 7f17d08bd6..71c8db29ec 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Terrain/TerrainVisual.cpp @@ -32,7 +32,7 @@ #include "GameClient/TerrainVisual.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp index 49869635b1..681d46f0a4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp @@ -47,7 +47,7 @@ extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -527,7 +527,7 @@ class PartitionFilterLiveMapEnemies : public PartitionFilter return true; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLiveMapEnemies"; } #endif }; @@ -557,7 +557,7 @@ class PartitionFilterWithinAttackRange : public PartitionFilter return false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterWithinAttackRange"; } #endif }; @@ -863,7 +863,7 @@ Real AI::getAdjustedVisionRangeForObject(const Object *object, Int factorsToCons } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { // ICK. This really nasty statement is used so that we only initialize this color once. diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp index 95a499c52b..018f14a760 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp @@ -56,7 +56,7 @@ #include "GameLogic/Module/SpecialPowerUpdateModule.h" #include "GameLogic/ObjectIter.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -2162,6 +2162,9 @@ void AIGroup::groupAttackObjectPrivate( Bool forced, Object *victim, Int maxShot for( ContainedItemsList::const_iterator it = items->begin(); it != items->end(); ++it ) { Object* garrisonedMember = *it; + + if (!contain->isPassengerAllowedToFire(garrisonedMember->getID())) continue; + CanAttackResult result = garrisonedMember->getAbleToAttackSpecificObject( forced ? ATTACK_NEW_TARGET_FORCED : ATTACK_NEW_TARGET, victim, cmdSource ); if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING ) { @@ -2250,6 +2253,9 @@ void AIGroup::groupAttackPosition( const Coord3D *pos, Int maxShotsToFire, Comma for( ContainedItemsList::const_iterator it = items->begin(); it != items->end(); ++it ) { Object* garrisonedMember = *it; + + if (!contain->isPassengerAllowedToFire(garrisonedMember->getID())) continue; + CanAttackResult result = garrisonedMember->getAbleToUseWeaponAgainstTarget( ATTACK_NEW_TARGET, NULL, &attackPos, cmdSource ) ; if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp index 92fb98901e..283ea006f3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp @@ -55,7 +55,7 @@ const Real CLOSE_ENOUGH = (25.0f); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp index 50e86eb640..578019f13b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuardRetaliate.cpp @@ -54,7 +54,7 @@ const Real CLOSE_ENOUGH = (25.0f); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp index a8c54678a4..802a7c88d9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp @@ -52,6 +52,7 @@ #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. +#include "Utility/CppMacros.h" #define no_INTENSE_DEBUG @@ -70,7 +71,7 @@ //------------------------------------------------------------------------------------------------- -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -357,7 +358,7 @@ void Path::xfer( Xfer *xfer ) xfer->xferBool(&m_blockedByAlly); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI == AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -760,7 +761,7 @@ void Path::computePointOnPath( ClosestPointOnPathInfo& out ) { - CRCDEBUG_LOG(("Path::computePointOnPath() fzor %s\n", DescribeObject(obj).str())); + CRCDEBUG_LOG(("Path::computePointOnPath() for %s\n", DebugDescribeObject(obj).str())); out.layer = LAYER_GROUND; out.posOnPath.zero(); @@ -2641,7 +2642,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye // // DEBUG_ASSERTCRASH(map[i][j].getZone() != 0, ("Cleared the zone.")); // } // } - register UnsignedInt maxZone = m_maxZone; + REGISTER UnsignedInt maxZone = m_maxZone; j=globalBounds.lo.y; while( j <= globalBounds.hi.y ) { @@ -2754,7 +2755,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye //FLATTEN HIERARCHICAL ZONES { i = 1; - register Int zone; + REGISTER Int zone; while ( i < maxZone ) { // Flatten hierarchical zones. zone = m_hierarchicalZones[i]; @@ -2797,7 +2798,7 @@ void PathfindZoneManager::calculateZones( PathfindCell **map, PathfindLayer laye #endif #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI == AI_DEBUG_ZONES) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -2942,7 +2943,7 @@ void PathfindZoneManager::updateZonesForModify(PathfindCell **map, PathfindLayer //DEBUG_LOG(("Time to update zones %f, cells %d\n", timeToUpdate, (globalBounds.hi.x-globalBounds.lo.x)*(globalBounds.hi.y-globalBounds.lo.y))); #endif #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_ZONES) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -3266,7 +3267,7 @@ Bool PathfindLayer::isUnused(void) /** * Draws debug cell info. */ -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void PathfindLayer::doDebugIcons(void) { if (isUnused()) return; extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -4031,6 +4032,8 @@ void Pathfinder::classifyFence( Object *obj, Bool insert ) IRegion2D cellBounds; cellBounds.lo.x = REAL_TO_INT_FLOOR((pos->x + 0.5f)/PATHFIND_CELL_SIZE_F); cellBounds.lo.y = REAL_TO_INT_FLOOR((pos->y + 0.5f)/PATHFIND_CELL_SIZE_F); + cellBounds.hi.x = REAL_TO_INT_CEIL((pos->x + 0.5f)/PATHFIND_CELL_SIZE_F); + cellBounds.hi.y = REAL_TO_INT_CEIL((pos->y + 0.5f)/PATHFIND_CELL_SIZE_F); Bool didAnything = false; for (Int iy = 0; iy < numStepsY; ++iy, tl_x += ydx, tl_y += ydy) @@ -4694,7 +4697,7 @@ void Pathfinder::debugShowSearch( Bool pathFound ) if (!TheGlobalData->m_debugAI) { return; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); // show all explored cells for debugging @@ -4820,7 +4823,7 @@ void Pathfinder::cleanOpenAndClosedLists(void) { m_closedList = NULL; } m_cumulativeCellsAllocated += count; -//#ifdef _DEBUG +//#ifdef RTS_DEBUG #if 0 // Check for dangling cells. for( int j=0; j<=m_extent.hi.y; j++ ) @@ -5686,7 +5689,7 @@ Bool Pathfinder::queueForPath(ObjectID id) return true; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL void Pathfinder::doDebugIcons(void) { const Int FRAMES_TO_SHOW_OBSTACLES = 100; extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -5956,7 +5959,7 @@ void Pathfinder::processPathfindQueue(void) #endif #endif } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL doDebugIcons(); #endif @@ -6657,7 +6660,7 @@ Path *Pathfinder::internalFindPath( Object *obj, const LocomotorSet& locomotorSe } // failure - goal cannot be reached -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL #ifdef INTENSE_DEBUG DEBUG_LOG(("internal find path FAILURE...\n")); #endif @@ -6805,7 +6808,7 @@ Path *Pathfinder::buildGroundPath(Bool isCrusher, const Coord3D *fromPos, Pathfi path->optimizeGroundPath( isCrusher, pathDiameter ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -6869,7 +6872,7 @@ Path *Pathfinder::buildHierachicalPath( const Coord3D *fromPos, PathfindCell *go } } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -7145,7 +7148,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from, DEBUG_LOG((" time %d msec %d cells", (::GetTickCount()-startTimeMS), cellCount)); DEBUG_LOG((" SUCCESS\n")); #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool show = TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS; if (show) debugShowSearch(true); @@ -7190,7 +7193,7 @@ Path *Pathfinder::findGroundPath( const Coord3D *from, const Int adjacent[5] = {0, 1, 2, 3, 0}; Bool neighborFlags[8] = {false, false, false, false, false, false, false}; - UnsignedInt newCostSoFar; + UnsignedInt newCostSoFar = 0; for( int i=0; im_debugAI) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -7695,7 +7698,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu m_isTunneling = false; // construct and return path Path *path = buildHierachicalPath( from, goalCell ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL Bool show = TheGlobalData->m_debugAI==AI_DEBUG_PATHS; show |= (TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS); if (show) { @@ -7730,7 +7733,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu return path; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL #if 0 Bool show = TheGlobalData->m_debugAI==AI_DEBUG_PATHS; show |= (TheGlobalData->m_debugAI==AI_DEBUG_GROUND_PATHS); @@ -7897,7 +7900,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu m_isTunneling = false; // construct and return path Path *path = buildHierachicalPath( from, closestCell ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL #if 0 if (TheGlobalData->m_debugAI) { @@ -7931,7 +7934,7 @@ Path *Pathfinder::internal_findHierarchicalPath( Bool isHuman, const LocomotorSu } // failure - goal cannot be reached -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -8400,7 +8403,7 @@ Bool Pathfinder::pathDestination( Object *obj, const LocomotorSet& locomotorSet } } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (closestCell) { debugShowSearch(true); *dest = closestPos; @@ -8955,7 +8958,7 @@ Path *Pathfinder::findClosestPath( Object *obj, const LocomotorSet& locomotorSet DEBUG_LOG(("Pathfind(findClosestPath) failed from (%f,%f) to (%f,%f), original valid %d --", from->x, from->y, to->x, to->y, valid)); DEBUG_LOG(("Unit '%s', time %f\n", obj->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); #endif -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) debugShowSearch(false); #endif @@ -9003,7 +9006,7 @@ Path *Pathfinder::buildActualPath( const Object *obj, LocomotorSurfaceTypeMask a // cleanup the path by checking line of sight path->optimize(obj, acceptableSurfaces, blocked); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI==AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -10363,7 +10366,7 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj, } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL debugShowSearch(true); #endif @@ -10439,7 +10442,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet // until goal is found. // -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); if (TheGlobalData->m_debugAI) { @@ -10462,7 +10465,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet info.radius = radius; info.considerTransient = blocked; info.acceptableSurfaces = locomotorSet.getValidSurfaces(); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) { RGBColor color; color.setFromInt(0); @@ -10550,7 +10553,7 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet DEBUG_LOG(("patchPath Pathfind failed -- ")); DEBUG_LOG(("Unit '%s', time %f\n", obj->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI) { debugShowSearch(true); } @@ -10600,7 +10603,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot } */ if (m_isMapReady == false) return NULL; // Should always be ok. -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Int startTimeMS = ::GetTickCount(); #endif @@ -10790,7 +10793,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot #endif if (show) debugShowSearch(true); - #if defined _DEBUG || defined _INTERNAL + #if defined RTS_DEBUG || defined RTS_INTERNAL //DEBUG_LOG(("Attack path took %d cells, %f sec\n", cellCount, (::GetTickCount()-startTimeMS)/1000.0f)); #endif // put parent cell onto closed list - its evaluation is finished @@ -10904,7 +10907,7 @@ Path *Pathfinder::findAttackPath( const Object *obj, const LocomotorSet& locomot cleanOpenAndClosedLists(); return path; } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL DEBUG_LOG(("%d (%d cells)", TheGameLogic->getFrame(), cellCount)); DEBUG_LOG(("Attack Pathfind failed from (%f,%f) to (%f,%f) -- \n", from->x, from->y, victim->getPosition()->x, victim->getPosition()->y)); DEBUG_LOG(("Unit '%s', attacking '%s' time %f\n", obj->getTemplate()->getName().str(), victim->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); @@ -10927,7 +10930,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor { //CRCDEBUG_LOG(("Pathfinder::findSafePath()\n")); if (m_isMapReady == false) return NULL; // Should always be ok. -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Int startTimeMS = ::GetTickCount(); #endif @@ -11034,7 +11037,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor #endif if (show) debugShowSearch(true); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL //DEBUG_LOG(("Attack path took %d cells, %f sec\n", cellCount, (::GetTickCount()-startTimeMS)/1000.0f)); #endif // construct and return path @@ -11065,7 +11068,7 @@ Path *Pathfinder::findSafePath( const Object *obj, const LocomotorSet& locomotor TheScriptEngine->AppendDebugMessage("Overflowed Safe path", false); #endif #if 0 -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL DEBUG_LOG(("%d (%d cells)", TheGameLogic->getFrame(), cellCount)); DEBUG_LOG(("Attack Pathfind failed from (%f,%f) to (%f,%f) -- \n", from->x, from->y, victim->getPosition()->x, victim->getPosition()->y)); DEBUG_LOG(("Unit '%s', attacking '%s' time %f\n", obj->getTemplate()->getName().str(), victim->getTemplate()->getName().str(), (::GetTickCount()-startTimeMS)/1000.0f)); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp index caedafac01..2ac34ad03f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp @@ -62,7 +62,7 @@ #include "GameLogic/Module/SupplyWarehouseDockUpdate.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -633,7 +633,7 @@ Object *AIPlayer::buildStructureWithDozer(const ThingTemplate *bldgPlan, BuildLi -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (TheGlobalData->m_debugAI == AI_DEBUG_PATHS) { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); @@ -1048,7 +1048,13 @@ Bool AIPlayer::isLocationSafe(const Coord3D *pos, const ThingTemplate *tthing ) void AIPlayer::onUnitProduced( Object *factory, Object *unit ) { Bool found = false; + // TheSuperHackers @fix Mauller 26/04/2025 Fixes uninitialized variable. + // To keep retail compatibility this needs to remain uninitialized in VS6 builds. +#if defined(_MSC_VER) && _MSC_VER < 1300 Bool supplyTruck; +#else + Bool supplyTruck = false; +#endif // factory could be NULL at the start of the game. if (factory == NULL) { @@ -2598,7 +2604,7 @@ void AIPlayer::recruitSpecificAITeam(TeamPrototype *teamProto, Real recruitRadiu AIUpdateInterface *ai = unit->getAIUpdateInterface(); if (ai) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Coord3D pos = *unit->getPosition(); Coord3D to = teamProto->getTemplateInfo()->m_homeLocation; DEBUG_LOG(("Moving unit from %f,%f to %f,%f\n", pos.x, pos.y , to.x, to.y )); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp index 53f33d2f1b..b629a1519c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp @@ -56,7 +56,7 @@ #include "GameLogic/Module/ProductionUpdate.h" #include "GameClient/TerrainVisual.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -810,7 +810,7 @@ void AISkirmishPlayer::recruitSpecificAITeam(TeamPrototype *teamProto, Real recr AIUpdateInterface *ai = unit->getAIUpdateInterface(); if (ai) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Coord3D pos = *unit->getPosition(); Coord3D to = teamProto->getTemplateInfo()->m_homeLocation; DEBUG_LOG(("Moving unit from %f,%f to %f,%f\n", pos.x, pos.y , to.x, to.y )); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp index 5bd89527fa..eceebc1324 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp @@ -69,7 +69,7 @@ #include "GameLogic/Module/PhysicsUpdate.h" #include "GameLogic/Module/StealthUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -858,7 +858,7 @@ AsciiString AIStateMachine::getCurrentStateName(void) const StateReturnType AIStateMachine::updateStateMachine() { //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) Bool idle = getOwner()->getAI()->isIdle(); if( !idle && TheGlobalData->m_extraLogging ) DEBUG_LOG( ("%d - %s::update() start - %s", TheGameLogic->getFrame(), getCurrentStateName().str(), getOwner()->getTemplate()->getName().str() ) ); @@ -878,7 +878,7 @@ StateReturnType AIStateMachine::updateStateMachine() if (status==STATE_CONTINUE) { //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( !idle && TheGlobalData->m_extraLogging ) DEBUG_LOG( (" - RETURN EARLY STATE_CONTINUE\n") ); #endif @@ -892,7 +892,7 @@ StateReturnType AIStateMachine::updateStateMachine() StateReturnType retType = StateMachine::updateStateMachine(); //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) AsciiString result; if( TheGlobalData->m_extraLogging ) { @@ -5005,10 +5005,14 @@ StateReturnType AIAttackAimAtTargetState::onEnter() StateReturnType AIAttackAimAtTargetState::update() { + // contained by AIAttackState, so no separate timer Object* source = getMachineOwner(); AIUpdateInterface* sourceAI = source->getAI(); + + // DEBUG_LOG((">>> attackAngle = %f, useAttackAngle = %d, mirrored = %d, canTurnInPlace = %d\n", sourceAI->getAttackAngle() * 180 / PI, sourceAI->useAttackAngle(), sourceAI->isAttackAngleMirrored(), m_canTurnInPlace)); + if (!source->hasAnyWeapon()) return STATE_FAILURE; @@ -5030,10 +5034,35 @@ StateReturnType AIAttackAimAtTargetState::update() { sourceAI->setTurretTargetPosition(tur, getMachineGoalPosition()); } + // If we have limited Turret Angle, we need to turn until we are in range + if (sourceAI->hasLimitedTurretAngle(tur)) { + Real relAngle = m_isAttackingObject ? + ThePartitionManager->getRelativeAngle2D(source, victim) : + ThePartitionManager->getRelativeAngle2D(source, getMachineGoalPosition()); + Real maxAngle = sourceAI->getMaxTurretAngle(tur); + Real minAngle = sourceAI->getMinTurretAngle(tur); + if (maxAngle < minAngle) { // This might be a backwards facing configuration + maxAngle = nmod(maxAngle, 2.0 * PI); + relAngle = nmod(relAngle, 2.0 * PI); + } + + // DEBUG_LOG((">>> (hasLimited) relAngle = %f, minAngle = %f, maxAngle = %f.\n", relAngle * 180 / PI, minAngle * 180 / PI, maxAngle * 180 / PI)); + + if ((relAngle < maxAngle) && (relAngle > minAngle)) { + // If the target is inside our maximum turret angle, we can continue + return STATE_CONTINUE; + } + else { + Locomotor* curLoco = sourceAI->getCurLocomotor(); + if (!curLoco) + return STATE_FAILURE; + } + + } // if we have a turret, but it is incapable of turning, turn ourself. // (gotta do this for units like the Comanche, which have fake "turrets" // solely to allow for attacking-on-the-move...) - if (sourceAI->getTurretTurnRate(tur) != 0.0f) + else if (sourceAI->getTurretTurnRate(tur) != 0.0f) { // The Body can never return Success if the weapon is on the turret, or else we end // up shooting the current weapon (which is on the turret) in the wrong direction. @@ -5063,19 +5092,107 @@ StateReturnType AIAttackAimAtTargetState::update() aimDelta = REL_THRESH; } - //DEBUG_LOG(("AIM: desired %f, actual %f, delta %f, aimDelta %f, goalpos %f %f\n",rad2deg(obj->getOrientation() + relAngle),rad2deg(obj->getOrientation()),rad2deg(relAngle),rad2deg(aimDelta),victim->getPosition()->x,victim->getPosition()->y)); - if (m_canTurnInPlace) - { - if (fabs(relAngle) > aimDelta) + if (sourceAI->hasLimitedTurretAngle(tur) && !sourceAI->useAttackAngle()) { + Real maxAngle = sourceAI->getMaxTurretAngle(tur) + aimDelta; + Real minAngle = sourceAI->getMinTurretAngle(tur) - aimDelta; + if (maxAngle < minAngle) { // This might be a backwards facing configuration + maxAngle = nmod(maxAngle, 2.0 * PI); + relAngle = nmod(relAngle, 2.0 * PI); + } + + if (m_canTurnInPlace) { - Real desiredAngle = source->getOrientation() + relAngle; - sourceAI->setLocomotorGoalOrientation(desiredAngle); - m_setLocomotor = true; + // if out of turret turn range: + if (relAngle > maxAngle || relAngle < minAngle) { + + // if (fabs(relAngle - maxAngle) < fabs(relAngle - minAngle)) + if (fabs(stdAngleDiffMod(relAngle, maxAngle)) < fabs(stdAngleDiffMod(relAngle, minAngle))) + { + Real desiredAngle = source->getOrientation() + relAngle - maxAngle + REL_THRESH * 2; + desiredAngle = normalizeAngle(desiredAngle); + //DEBUG_LOG((">>> AIStates: relAngle = %f, aimDelta = %f, minAngle = %f, maxAngle = %f, desiredAngle = %f.\n", + // relAngle / PI * 180.0, aimDelta / PI * 180.0, minAngle / PI * 180.0, maxAngle / PI * 180.0, desiredAngle / PI * 180.0)); + + sourceAI->setLocomotorGoalOrientation(desiredAngle); + m_setLocomotor = true; + } + else { + Real desiredAngle = source->getOrientation() + relAngle - minAngle - REL_THRESH * 2; + desiredAngle = normalizeAngle(desiredAngle); + DEBUG_LOG((">>> AIStates: relAngle = %f, aimDelta = %f, minAngle = %f, maxAngle = %f, desiredAngle = %f.\n", + relAngle / PI * 180.0, aimDelta / PI * 180.0, minAngle / PI * 180.0, maxAngle / PI * 180.0, desiredAngle / PI * 180.0)); + + + sourceAI->setLocomotorGoalOrientation(desiredAngle); + m_setLocomotor = true; + } + } + } + + /*if (m_canTurnInPlace) + { + if (relAngle < aimDeltaNeg) + { + Real desiredAngle = source->getOrientation() + relAngle - aimDeltaNeg - REL_THRESH - attackAngle; + desiredAngle = normalizeAngle(desiredAngle); + DEBUG_LOG((">>> AIStates: relAngle = %f, aimDelta = %f, aimDeltaNeg = %f, desiredAngle = %f.\n", + relAngle / PI * 180.0, aimDelta / PI * 180.0, aimDeltaNeg / PI * 180.0, desiredAngle / PI * 180.0)); + + sourceAI->setLocomotorGoalOrientation(desiredAngle); + m_setLocomotor = true; + } + else if (relAngle > aimDelta) { + Real desiredAngle = source->getOrientation() + relAngle - aimDelta + REL_THRESH - attackAngle; + desiredAngle = normalizeAngle(desiredAngle); + DEBUG_LOG((">>> AIStates: relAngle = %f, aimDelta = %f, aimDeltaNeg = %f, desiredAngle = %f.\n", + relAngle /PI * 180.0, aimDelta / PI * 180.0, aimDeltaNeg / PI * 180.0, desiredAngle / PI * 180.0)); + + + sourceAI->setLocomotorGoalOrientation(desiredAngle); + m_setLocomotor = true; + } + }*/ + else + { + sourceAI->setLocomotorGoalPositionExplicit(m_isAttackingObject ? *victim->getPosition() : *getMachineGoalPosition()); } } - else - { - sourceAI->setLocomotorGoalPositionExplicit(m_isAttackingObject ? *victim->getPosition() : *getMachineGoalPosition()); + else { + + // DEBUG_LOG((">>> (2) attackAngle = %f, useAttackAngle = %d, mirrored = %d, canTurnInPlace = %d\n", sourceAI->getAttackAngle() * 180 / PI, sourceAI->useAttackAngle(), sourceAI->isAttackAngleMirrored(), m_canTurnInPlace)); + + + // Check preferredAttackAngle + if (sourceAI->useAttackAngle()) { + Real attackAngle = sourceAI->getAttackAngle(); + + if (sourceAI->isAttackAngleMirrored()) { + + // check which side is closer + if (fabs(stdAngleDiffMod(relAngle, attackAngle)) > fabs(stdAngleDiffMod(relAngle, attackAngle + PI))) { + attackAngle = attackAngle + PI; + } + } + + relAngle -= attackAngle; + relAngle = normalizeAngle(relAngle); + } + + + //DEBUG_LOG(("AIM: desired %f, actual %f, delta %f, aimDelta %f, goalpos %f %f\n",rad2deg(obj->getOrientation() + relAngle),rad2deg(obj->getOrientation()),rad2deg(relAngle),rad2deg(aimDelta),victim->getPosition()->x,victim->getPosition()->y)); + if (m_canTurnInPlace) + { + if (fabs(relAngle) > aimDelta) + { + Real desiredAngle = source->getOrientation() + relAngle; + sourceAI->setLocomotorGoalOrientation(desiredAngle); + m_setLocomotor = true; + } + } + else + { + sourceAI->setLocomotorGoalPositionExplicit(m_isAttackingObject ? *victim->getPosition() : *getMachineGoalPosition()); + } } if (fabs(relAngle) < aimDelta /*&& !m_preAttackFrames*/ ) @@ -5181,7 +5298,18 @@ StateReturnType AIAttackFireWeaponState::onEnter() } obj->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_IS_FIRING_WEAPON ) ); - obj->preFireCurrentWeapon( getMachineGoalObject() ); + if (victim) { + obj->preFireCurrentWeapon(victim); + } + else { + const Coord3D* pos = getMachineGoalPosition(); + if (pos) { + obj->preFireCurrentWeapon(pos); + } + else { + obj->preFireCurrentWeapon(victim); + } + } return STATE_CONTINUE; } @@ -5236,10 +5364,10 @@ StateReturnType AIAttackFireWeaponState::update() if (m_att->isAttackingObject()) { - // Since it is very late in the project, and there is no call for such code... - // there is currently no support here for linked turrets, as regards Attacking Objects (victims) - // If the concept of linked turrets is further developed then God help you, and put more code right here - // that lookl like the //LINKED TURRETS// block, below + // Since it is very late in the project, and there is no call for such code... + // there is currently no support here for linked turrets, as regards Attacking Objects (victims) + // If the concept of linked turrets is further developed then God help you, and put more code right here + // that lookl like the //LINKED TURRETS// block, below obj->fireCurrentWeapon(victim); @@ -5250,19 +5378,19 @@ StateReturnType AIAttackFireWeaponState::update() //to transfer attackers (AIUpdateInterface::transferAttack), it is unable to modify our current victim in our attack state //machine. When we move immediately to the aim state in the same frame as the transfer (after this call in fact), the victim //was still pointing to the building and not the hole we transferred to. This code fixes that. - if( victim != obj->getAI()->getCurrentVictim() ) + if (victim != obj->getAI()->getCurrentVictim()) { - getMachine()->setGoalObject( obj->getAI()->getCurrentVictim() ); + getMachine()->setGoalObject(obj->getAI()->getCurrentVictim()); } // clear this, just in case. - obj->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_IGNORING_STEALTH ) ); + obj->clearStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_IGNORING_STEALTH)); Real continueRange = weapon->getContinueAttackRange(); if ( continueRange > 0.0f && - victim && + victim && (victim->isDestroyed() || victim->isEffectivelyDead() || (victim->isKindOf(KINDOF_MINE) && victim->testStatus(OBJECT_STATUS_MASKED))) - ) + ) { const Coord3D* originalVictimPos = m_att ? m_att->getOriginalVictimPos() : NULL; if (originalVictimPos) @@ -5272,12 +5400,12 @@ StateReturnType AIAttackFireWeaponState::update() // but not if they were ordered by ai. AIUpdateInterface* ai = obj->getAI(); CommandSourceType lastCmdSource = ai ? ai->getLastCommandSource() : CMD_FROM_AI; - PartitionFilterSamePlayer filterPlayer( victim->getControllingPlayer() ); + PartitionFilterSamePlayer filterPlayer(victim->getControllingPlayer()); PartitionFilterSameMapStatus filterMapStatus(obj); PartitionFilterPossibleToAttack filterAttack(ATTACK_NEW_TARGET, obj, lastCmdSource); - PartitionFilter *filters[] = { &filterAttack, &filterPlayer, &filterMapStatus, NULL }; + PartitionFilter* filters[] = { &filterAttack, &filterPlayer, &filterMapStatus, NULL }; // note that we look around originalVictimPos, *not* the current victim's pos. - victim = ThePartitionManager->getClosestObject( originalVictimPos, continueRange, FROM_CENTER_2D, filters );// could be null. this is ok. + victim = ThePartitionManager->getClosestObject(originalVictimPos, continueRange, FROM_CENTER_2D, filters);// could be null. this is ok. if (victim) { getMachine()->setGoalObject(victim); @@ -5288,27 +5416,53 @@ StateReturnType AIAttackFireWeaponState::update() } else { - - if( getMachineOwner()->getAI()->areTurretsLinked() ) //LINKED TURRETS - {// it doesn;t matter which weapon slot is locked, current or whatever - for ( Int slot = PRIMARY_WEAPON; slot < WEAPONSLOT_COUNT ; slot++ ) - {// were firing with all barrels - Weapon *weapon = obj->getWeaponInWeaponSlot( (WeaponSlotType)slot ); - if ( weapon ) - { - if ( weapon->fireWeapon(obj, getMachineGoalPosition()) ) //fire() returns 'reloaded' - obj->releaseWeaponLock(LOCKED_TEMPORARILY);// unlock, 'cause we're loaded - - obj->notifyFiringTrackerShotFired(weapon, INVALID_ID); - } - } - } - else - obj->fireCurrentWeapon(getMachineGoalPosition()); + + if (getMachineOwner()->getAI()->areTurretsLinked()) //LINKED TURRETS + {// it doesn;t matter which weapon slot is locked, current or whatever + for (Int slot = PRIMARY_WEAPON; slot < WEAPONSLOT_COUNT; slot++) + {// were firing with all barrels + Weapon* weapon = obj->getWeaponInWeaponSlot((WeaponSlotType)slot); + if (weapon) + { + if (weapon->fireWeapon(obj, getMachineGoalPosition())) //fire() returns 'reloaded' + obj->releaseWeaponLock(LOCKED_TEMPORARILY);// unlock, 'cause we're loaded + + obj->notifyFiringTrackerShotFired(weapon, INVALID_ID); + } + } + } + else + obj->fireCurrentWeapon(getMachineGoalPosition()); // clear this, just in case. - obj->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_IGNORING_STEALTH ) ); + obj->clearStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_IGNORING_STEALTH)); } + + // Synced weapon Slots: + for (Int slot = PRIMARY_WEAPON; slot < WEAPONSLOT_COUNT; slot++) + { + // check this slot if the weapon should be synced to the currently fired slot + if (slot == wslot || !obj->getWeaponInWeaponSlotSyncedToSlot((WeaponSlotType)slot, wslot)) { + // DEBUG_LOG((">> Skipping slot %d.\n", slot)); + continue; + } + + // DEBUG_LOG((">> Slot %d is synced. Prepare to fire weapon.\n", slot)); + + // Yes, we are firing this weapon! + Weapon* weapon = obj->getWeaponInWeaponSlot((WeaponSlotType)slot); + if (weapon) + { + if (weapon->fireWeapon(obj, getMachineGoalPosition())) { //fire() returns 'reloaded' + obj->releaseWeaponLock(LOCKED_TEMPORARILY);// unlock, 'cause we're loaded + // DEBUG_LOG((">> On firing Weapon in slot %d: fire synced weapon slot %d. Shot Fired!\n", wslot, slot)); + } + + obj->notifyFiringTrackerShotFired(weapon, INVALID_ID); + } + } + + m_att->notifyFired(); return STATE_SUCCESS; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp index efc7db9eff..d92fd8faae 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp @@ -55,7 +55,7 @@ const Real CLOSE_ENOUGH = (25.0f); -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp index 6b47190596..8ed94f20e6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/Squad.cpp @@ -48,7 +48,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp index 19b6170ebf..2d061cb017 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/TurretAI.cpp @@ -47,7 +47,7 @@ const UnsignedInt WAIT_INDEFINITELY = 0xffffffff; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -201,6 +201,10 @@ TurretAIData::TurretAIData() m_initiallyDisabled = false; m_firesWhileTurning = FALSE; m_isAllowsPitch = false; + + m_minTurretAngle = 0.0; + m_maxTurretAngle = 0.0; + m_hasLimitedTurretAngle = false; } //------------------------------------------------------------------------------------------------- @@ -232,6 +236,16 @@ void TurretAIData::parseTurretSweepSpeed(INI* ini, void *instance, void * /*stor INI::parseReal( ini, instance, &self->m_turretSweepSpeedModifier[wslot], NULL ); } + +//------------------------------------------------------------------------------------------------- +/*static*/ void TurretAIData::parseMinMaxAngle(INI* ini, void* instance, void* store, const void* userData) +{ + INI::parseAngleReal(ini, instance, store, userData); + TurretAIData* self = (TurretAIData*)instance; + self->m_hasLimitedTurretAngle = TRUE; +} + + //---------------------------------------------------------------------------------------------------------- void TurretAIData::buildFieldParse(MultiIniFieldParse& p) { @@ -258,6 +272,9 @@ void TurretAIData::buildFieldParse(MultiIniFieldParse& p) { "RecenterTime", INI::parseDurationUnsignedInt, NULL, offsetof( TurretAIData, m_recenterTime ) }, { "InitiallyDisabled", INI::parseBool, NULL, offsetof( TurretAIData, m_initiallyDisabled ) }, { "FiresWhileTurning", INI::parseBool, NULL, offsetof( TurretAIData, m_firesWhileTurning ) }, + { "MinTurretAngle", TurretAIData::parseMinMaxAngle, NULL, offsetof(TurretAIData, m_minTurretAngle) }, + { "MaxTurretAngle", TurretAIData::parseMinMaxAngle, NULL, offsetof(TurretAIData, m_maxTurretAngle) }, + // { "TurretAngleLimited", INI::parseBool, NULL, offsetof(TurretAIData, m_hasLimitedTurretAngle) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); @@ -308,7 +325,7 @@ TurretAI::TurretAI(Object* owner, const TurretAIData* data, WhichTurretType tur) m_angle = getNaturalTurretAngle(); m_pitch = getNaturalTurretPitch(); -#ifdef _DEBUG +#ifdef RTS_DEBUG char smbuf[256]; sprintf(smbuf, "TurretStateMachine for tur %08lx slot %d",this,tur); const char* smname = smbuf; @@ -397,7 +414,65 @@ Bool TurretAI::friend_turnTowardsAngle(Real desiredAngle, Real rateModifier, Rea Real origAngle = getTurretAngle(); Real actualAngle = origAngle; Real turnRate = getTurnRate() * rateModifier; - Real angleDiff = normalizeAngle(desiredAngle - actualAngle); + // Real angleDiff = normalizeAngle(desiredAngle - actualAngle); + Real angleDiff = stdAngleDiffMod(desiredAngle, actualAngle); + + // --- + if (hasLimitedTurretAngle()) { + Real minAngle = getMinTurretAngle(); + Real maxAngle = getMaxTurretAngle(); + + if (maxAngle < minAngle) { // This might be a backwards facing configuration + maxAngle = nmod(maxAngle, 2.0 * PI); + desiredAngle = nmod(desiredAngle, 2.0 * PI); + } + + //DEBUG_LOG((">>> TurretAI::friend_turnTowardsAngle: minAngle = %f, maxAngle = %f, desiredAngle = %f, angleDiff = %f.\n", + // minAngle / PI * 180.0, maxAngle / PI * 180.0, desiredAngle / PI * 180.0, angleDiff / PI * 180.0)); + + bool isWithinLimit = true; + if ((desiredAngle > maxAngle)) { + desiredAngle = maxAngle; + // desiredAngle = getNaturalTurretAngle(); + isWithinLimit = false; + } + else if (desiredAngle < minAngle) { + desiredAngle = minAngle; + // desiredAngle = getNaturalTurretAngle(); + isWithinLimit = false; + } + if (!isWithinLimit) { + // angleDiff = normalizeAngle(desiredAngle - actualAngle); + angleDiff = stdAngleDiffMod(desiredAngle, actualAngle); + // Are we close enough to the desired angle to just snap there? + if (fabs(angleDiff) < turnRate) + { + // we are centered + actualAngle = desiredAngle; + + getOwner()->clearModelConditionState(MODELCONDITION_TURRET_ROTATE); + } + else + { + if (angleDiff > 0) + actualAngle += turnRate; + else + actualAngle -= turnRate; + + getOwner()->setModelConditionState(MODELCONDITION_TURRET_ROTATE); + m_playRotSound = true; + } + + m_angle = normalizeAngle(actualAngle); + + if (m_angle != origAngle) + getOwner()->reactToTurretChange(m_whichTurret, origAngle, m_pitch); + + return false; + } + } + // ----- + desiredAngle = normalizeAngle(desiredAngle); // Are we close enough to the desired angle to just snap there? if (fabs(angleDiff) < turnRate) @@ -423,7 +498,10 @@ Bool TurretAI::friend_turnTowardsAngle(Real desiredAngle, Real rateModifier, Rea if( m_angle != origAngle ) getOwner()->reactToTurretChange( m_whichTurret, origAngle, m_pitch ); - Bool aligned = fabs(m_angle - desiredAngle) <= relThresh; + // Bool aligned = fabs(m_angle - desiredAngle) <= relThresh; + Bool aligned = fabs(stdAngleDiffMod(m_angle, desiredAngle)) <= relThresh; + + // DEBUG_LOG((">>> TurretAI::friend_turnTowardsAngle: aligned = %d, actualAngle = %f, m_angle = %f, desiredAngle = %f, relThresh = %f\n", aligned, actualAngle * PI / 180.0, m_angle * PI / 180.0, desiredAngle * PI / 180.0, relThresh * PI / 180.0)); return aligned; } @@ -689,7 +767,7 @@ UpdateSleepTime TurretAI::updateTurretAI() { USE_PERF_TIMER(TurretAI) -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(!m_enabled || m_turretStateMachine->peekSleepTill() == 0 || m_turretStateMachine->peekSleepTill() >= m_sleepUntil, ("Turret Machine is less sleepy than turret")); @@ -748,7 +826,7 @@ UpdateSleepTime TurretAI::updateTurretAI() m_sleepUntil = now + subMachineSleep; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(!m_enabled || m_turretStateMachine->peekSleepTill() == 0 || m_turretStateMachine->peekSleepTill() >= m_sleepUntil, ("Turret Machine is less sleepy than turret")); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp index 45cf9f7ad3..ce0111a34e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp @@ -204,7 +204,7 @@ Bool PolygonTrigger::ParsePolygonTriggersDataChunk(DataChunkInput &file, DataChu // before water areas existed, so create a default one. PolygonTrigger *pTrig = newInstance(PolygonTrigger)(4); pTrig->setWaterArea(true); -#ifdef _DEBUG +#ifdef RTS_DEBUG pTrig->setTriggerName("AutoAddedWaterAreaTrigger"); #endif pTrig->m_triggerID = maxTriggerId++; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp index c18e65726f..27f96ef64d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp @@ -59,7 +59,7 @@ #include "WWMath/plane.h" #include "WWMath/tri.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp index e038fca959..3b66ecaafc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp @@ -63,6 +63,13 @@ void ArmorTemplate::clear() } } +void ArmorTemplate::copyFrom(const ArmorTemplate* other) { + for (int i = 0; i < DAMAGE_NUM_TYPES; i++) + { + m_damageCoefficient[i] = other->m_damageCoefficient[i]; + } +} + //------------------------------------------------------------------------------------------------- Real ArmorTemplate::adjustDamage(DamageType t, Real damage) const { @@ -145,9 +152,39 @@ const ArmorTemplate* ArmorStore::findArmorTemplate(AsciiString name) const ini->initFromINI(&armorTmpl, myFieldParse); } +//------------------------------------------------------------------------------------------------- +/*static */ void ArmorStore::parseArmorExtendDefinition(INI* ini) +{ + static const FieldParse myFieldParse[] = + { + { "Armor", ArmorTemplate::parseArmorCoefficients, NULL, 0 } + }; + + const char* new_armor_name = ini->getNextToken(); + + const char* parent = ini->getNextToken(); + const ArmorTemplate* parentTemplate = TheArmorStore->findArmorTemplate(parent); + if (parentTemplate == NULL) { + DEBUG_CRASH(("ArmorExtend must extend a previously defined Armor (%s).\n", parent)); + throw INI_INVALID_DATA; + } + + NameKeyType key = TheNameKeyGenerator->nameToKey(new_armor_name); + ArmorTemplate& armorTmpl = TheArmorStore->m_armorTemplates[key]; + armorTmpl.clear(); + armorTmpl.copyFrom(parentTemplate); + + ini->initFromINI(&armorTmpl, myFieldParse); +} + //------------------------------------------------------------------------------------------------- /*static*/ void INI::parseArmorDefinition(INI *ini) { ArmorStore::parseArmorDefinition(ini); } +//------------------------------------------------------------------------------------------------- +/*static*/ void INI::parseArmorExtendDefinition(INI* ini) +{ + ArmorStore::parseArmorExtendDefinition(ini); +} diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp index 5ecaa53177..eea116b7cb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp @@ -44,7 +44,7 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp index 8a6d560f45..611956e342 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BattleBusSlowDeathBehavior.cpp @@ -44,7 +44,7 @@ #include "GameLogic/Module/ContainModule.h" #include "GameLogic/Module/PhysicsUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp index f6dba4a4a5..504c233b34 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/BunkerBusterBehavior.cpp @@ -41,7 +41,7 @@ #include "GameClient/TerrainVisual.h"//Seismic simulations! -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp index 59c75a5fee..b9e27755a7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/CountermeasuresBehavior.cpp @@ -47,7 +47,7 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp index b7e1252d73..91de76b64d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/DumbProjectileBehavior.cpp @@ -46,7 +46,7 @@ #include "GameLogic/Module/PhysicsUpdate.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -454,7 +454,7 @@ Bool DumbProjectileBehavior::calcFlightPath(Bool recalcNumSegments) flightCurve.getSegmentPoints( m_flightPathSegments, &m_flightPath ); DEBUG_ASSERTCRASH(m_flightPathSegments == m_flightPath.size(), ("m_flightPathSegments mismatch")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_debugProjectilePath ) displayFlightPath(); #endif @@ -490,7 +490,7 @@ Bool DumbProjectileBehavior::projectileHandleCollision( Object *other ) const ContainedItemsList* items = contain->getContainedItemsList(); if (items) { - for (ContainedItemsList::const_iterator it = items->begin(); *it != NULL && numKilled < d->m_garrisonHitKillCount; ) + for (ContainedItemsList::const_iterator it = items->begin(); it != items->end() && numKilled < d->m_garrisonHitKillCount; ) { Object* thingToKill = *it++; if (!thingToKill->isEffectivelyDead() && thingToKill->isKindOfMulti(d->m_garrisonHitKillKindof, d->m_garrisonHitKillKindofNot)) @@ -698,10 +698,21 @@ UpdateSleepTime DumbProjectileBehavior::update() return UPDATE_SLEEP_NONE;//This no longer flys with physics, so it needs to not sleep } +// ------------------------------------------------------------------------------------------------ +const Coord3D* DumbProjectileBehavior::getTargetPosition() +{ + return &m_flightPathEnd; +} +// ------------------------------------------------------------------------------------------------ +Object* DumbProjectileBehavior::getTargetObject() +{ + return TheGameLogic->findObjectByID(m_victimID); +} + // ------------------------------------------------------------------------------------------------ /** displayFlightPath for debugging */ // ------------------------------------------------------------------------------------------------ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void DumbProjectileBehavior::displayFlightPath() { extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp index 554e9252be..5663782e46 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FireWeaponWhenDeadBehavior.cpp @@ -49,7 +49,7 @@ #include "GameLogic/Weapon.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp index cf51674a87..f76a5fb1a2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/FlightDeckBehavior.cpp @@ -52,7 +52,7 @@ #include "GameLogic/Module/JetAIUpdate.h" #include "GameLogic/Module/ProductionUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp index 8f872c932c..e3477ea5dc 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GenerateMinefieldBehavior.cpp @@ -54,7 +54,7 @@ #include "GameLogic/Weapon.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp index 69c4c55a5b..04ce8fb6c1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/GrantStealthBehavior.cpp @@ -46,7 +46,7 @@ #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp index 02cbd9ce52..24dd381036 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/JetSlowDeathBehavior.cpp @@ -43,7 +43,7 @@ #include "GameLogic/Object.h" #include "GameLogic/ObjectCreationList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp index 2467fba870..e8cea87c86 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/MinefieldBehavior.cpp @@ -45,7 +45,7 @@ #include "GameLogic/Module/AutoHealBehavior.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp index 3ce9d7d454..c87632b390 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/NeutonBlastBehavior.cpp @@ -40,7 +40,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp index 3b19802821..a9a1d5d830 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/OverchargeBehavior.cpp @@ -43,7 +43,7 @@ #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp index 4228b823c7..e2a0990b2d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/ParkingPlaceBehavior.cpp @@ -44,7 +44,7 @@ #include "GameLogic/TerrainLogic.h" #include "Common/Team.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp index 2fa223f66a..8dcfa01097 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PoisonedBehavior.cpp @@ -37,7 +37,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp index 844ed36ed8..2692a16ad2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/PropagandaTowerBehavior.cpp @@ -44,7 +44,7 @@ #include "GameLogic/Module/BodyModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp index 54b01c3fdb..4c2129e5e5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/RebuildHoleBehavior.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Module/RebuildHoleBehavior.h" #include "GameLogic/Module/StickyBombUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp index dd0d2128e1..144afc9480 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SlowDeathBehavior.cpp @@ -51,7 +51,7 @@ #include "GameLogic/Weapon.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp index e1413c7acc..0c18aae37d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp @@ -49,7 +49,7 @@ #define NONE_SPAWNED_YET (0xffffffff) -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp index 91fbf834c1..093ba428bf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/ActiveBody.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/DieModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -173,7 +173,8 @@ ActiveBody::ActiveBody( Thing *thing, const ModuleData* moduleData ) : m_lastDamageCleared(false), m_particleSystems(NULL), m_currentSubdualDamage(0), - m_indestructible(false) + m_indestructible(false), + m_damageFXOverride(false) { m_currentHealth = getActiveBodyModuleData()->m_initialHealth; m_prevHealth = getActiveBodyModuleData()->m_initialHealth; @@ -278,7 +279,7 @@ void ActiveBody::validateArmorAndDamageFX() const { m_curArmor.clear(); } - m_curDamageFX = set->getDamageFX(); + if (!m_damageFXOverride) m_curDamageFX = set->getDamageFX(); // Only set this if override is cleared m_curArmorSet = set; } } @@ -1514,6 +1515,28 @@ void ActiveBody::setAflame( Bool ) updateBodyParticleSystems(); } +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +void ActiveBody::overrideDamageFX(DamageFX* damageFX) +{ + if (damageFX != NULL) { + m_curDamageFX = damageFX; + m_damageFXOverride = true; + } + else { + m_curDamageFX = NULL; + m_damageFXOverride = false; + + // Restore DamageFX from current armorset + const ArmorTemplateSet* set = getObject()->getTemplate()->findArmorTemplateSet(m_curArmorSetFlags); + if (set) + { + m_curDamageFX = set->getDamageFX(); + } + } + DEBUG_LOG((">>>ActiveBody: overrideDamageFX - new m_curDamageFX = %d, m_damageFXOverride = %d\n", + m_curDamageFX, m_damageFXOverride)); +} // ------------------------------------------------------------------------------------------------ /** CRC */ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp index 243c166cce..4783437ea5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/ConvertToHijackedVehicleCrateCollide.cpp @@ -56,7 +56,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/Module/DozerAIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp index 3985be20c5..0be6e01aa8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/CrateCollide.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp index 4e58388056..5f40cfa6b8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageCommandCenterCrateCollide.cpp @@ -62,7 +62,7 @@ #include "GameLogic/Module/SpecialPowerModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp index 88cae38e61..1e93289966 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageFakeBuilding.cpp @@ -57,7 +57,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/Module/DozerAIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp index 1dae7b5adf..f590b1b2e5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageInternetCenterCrateCollide.cpp @@ -63,7 +63,7 @@ #include "GameLogic/Module/SpyVisionUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp index e66f274e3c..f779d2db2f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageMilitaryFactoryCrateCollide.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/SabotageMilitaryFactoryCrateCollide.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp index 6de804bc49..69e0c5fa1c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotagePowerPlantCrateCollide.cpp @@ -57,7 +57,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/Module/DozerAIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp index d156fa12b4..5963eb4859 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSuperweaponCrateCollide.cpp @@ -62,7 +62,7 @@ #include "GameLogic/Module/SpecialPowerModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp index 460fe97aa0..62d4ff2676 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyCenterCrateCollide.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/SabotageSupplyCenterCrateCollide.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp index 71f955f499..741f35a488 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/SabotageSupplyDropzoneCrateCollide.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/SabotageSupplyDropzoneCrateCollide.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp index a700551e1c..e98f4c249b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/SquishCollide.cpp @@ -41,7 +41,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp index 4b69792e68..ece1d3e3ab 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/GarrisonContain.cpp @@ -48,13 +48,14 @@ #include "GameLogic/Module/BodyModule.h" #include "GameLogic/PartitionManager.h" #include "GameLogic/Weapon.h" +#include "GameLogic/WeaponSetType.h" #include "GameClient/Drawable.h" #include "GameClient/GameClient.h" #include "GameClient/InGameUI.h" #include "GameClient/View.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif @@ -80,6 +81,9 @@ GarrisonContainModuleData::GarrisonContainModuleData( void ) m_isEnclosingContainer = TRUE; ///< a sensible default for a garrison container... few exceptions, firebase is one m_initialRoster.count = 0; + + m_passengerWeaponBonusVec.push_back(WEAPONBONUSCONDITION_GARRISONED); + } // end if //----------------------------------------------------------------------------- @@ -283,7 +287,7 @@ Bool GarrisonContain::calcBestGarrisonPosition( Coord3D *sourcePos, const Coord3 if( !sourcePos || !targetPos ) return FALSE; -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("calcBestGarrisonPosition... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -317,7 +321,7 @@ Bool GarrisonContain::attemptBestFirePointPosition( Object *source, Weapon *weap return FALSE; } -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("calcBestGarrisonPosition... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -357,7 +361,7 @@ Bool GarrisonContain::attemptBestFirePointPosition( Object *source, Weapon *weap { return FALSE; } -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("calcBestGarrisonPosition... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -398,7 +402,7 @@ void GarrisonContain::putObjectAtBestGarrisonPoint( Object *obj, Object *target, if( obj == NULL || (target == NULL && targetPos == NULL) ) return; -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("calcBestGarrisonPosition... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -433,7 +437,7 @@ void GarrisonContain::removeObjectFromGarrisonPoint( Object *obj, Int index ) if ( ! isEnclosingContainerFor(obj) ) return;// since I am not enclosed, I am not at a garrison point! -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("calcBestGarrisonPosition... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -587,7 +591,7 @@ Bool GarrisonContain::isValidContainerFor(const Object* obj, Bool checkCapacity) // ------------------------------------------------------------------------------------------------ void GarrisonContain::removeInvalidObjectsFromGarrisonPoints( void ) { -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("removeinvalidobjFromGarrisonPoint... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -638,7 +642,7 @@ void GarrisonContain::addValidObjectsToGarrisonPoints( void ) { -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("addvalidobjtoGarrisonPoint... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -833,7 +837,7 @@ void GarrisonContain::updateEffects( void ) { -#if defined __DEBUG || defined _INTERNAL +#if defined __DEBUG || defined RTS_INTERNAL const GarrisonContainModuleData *modData = getGarrisonContainModuleData(); DEBUG_ASSERTCRASH(modData->m_isEnclosingContainer, ("updateeffects... SHOULD NOT GET HERE, since this container is non-enclosing") ); #endif @@ -1626,7 +1630,8 @@ void GarrisonContain::onContaining( Object *obj, Bool wasSelected ) structure->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_CAN_ATTACK ) ); // give the object a garrisoned version of its weapon - obj->setWeaponBonusCondition( WEAPONBONUSCONDITION_GARRISONED ); + // obj->setWeaponBonusCondition( WEAPONBONUSCONDITION_GARRISONED ); + obj->setWeaponSetFlag(WEAPONSET_GARRISONED); // put the object in the center of the building if (isEnclosingContainerFor( obj )) @@ -1667,6 +1672,7 @@ void GarrisonContain::onRemoving( Object *obj ) } // give the object back a regular weapon obj->clearWeaponBonusCondition( WEAPONBONUSCONDITION_GARRISONED ); + obj->clearWeaponSetFlag(WEAPONSET_GARRISONED); // object is no longer held inside a garrisoned building obj->clearDisabled( DISABLED_HELD ); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp index ebbfafa0b6..48e4c1eddb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp @@ -47,7 +47,7 @@ #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -135,16 +135,17 @@ UpdateSleepTime HelixContain::update() void HelixContain::redeployOccupants( void ) { - Coord3D firePos = *getObject()->getPosition(); - firePos.z += 8; - - - for (ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); ++it) - { - Object* rider = *it; - if (rider) - rider->setPosition( &firePos ); - } + // Removed by AndiW: This restores proper firebones, if the parent vehicle model has them + + // Coord3D firePos = *getObject()->getPosition(); + // firePos.z += 8; + // for (ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); ++it) + // { + // Object* rider = *it; + // if (rider) + // rider->setPosition( &firePos ); + // } + OpenContain::redeployOccupants(); } @@ -395,8 +396,8 @@ void HelixContain::onContaining( Object *obj, Bool wasSelected ) TransportContain::onContaining( obj, wasSelected ); // give the object a garrisoned version of its weapon - obj->setWeaponBonusCondition( WEAPONBONUSCONDITION_GARRISONED ); - obj->setDisabled( DISABLED_HELD ); + // obj->setWeaponBonusCondition( WEAPONBONUSCONDITION_GARRISONED ); + obj->setDisabled( DISABLED_HELD ); if ( obj->isKindOf( KINDOF_PORTABLE_STRUCTURE ) && getObject()->testStatus( OBJECT_STATUS_STEALTHED ) ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/InternetHackContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/InternetHackContain.cpp index 81d43234fc..809eaba357 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/InternetHackContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/InternetHackContain.cpp @@ -35,7 +35,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp index 0407b838b5..c6fd0e1c30 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp @@ -57,7 +57,7 @@ #include "GameLogic/PartitionManager.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -110,6 +110,7 @@ OpenContainModuleData::OpenContainModuleData( void ) { "AllowAlliesInside", INI::parseBool, NULL, offsetof( OpenContainModuleData, m_allowAlliesInside ) }, { "AllowEnemiesInside", INI::parseBool, NULL, offsetof( OpenContainModuleData, m_allowEnemiesInside ) }, { "AllowNeutralInside", INI::parseBool, NULL, offsetof( OpenContainModuleData, m_allowNeutralInside ) }, + { "PassengerWeaponBonusList", INI::parseWeaponBonusVectorKeepDefault, NULL, offsetof(OpenContainModuleData, m_passengerWeaponBonusVec) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); @@ -157,6 +158,11 @@ OpenContain::OpenContain( Thing *thing, const ModuleData* moduleData ) : UpdateM m_firePoints[ i ].Make_Identity(); } // end for i + //DEBUG_LOG(("OpenContain(): ('%s') m_passengerWeaponBonusVec:\n", getObject()->getTemplate()->getName().str())); + //const OpenContainModuleData* d = getOpenContainModuleData(); + //for (i = 0; i < d->m_passengerWeaponBonusVec.size(); i++) { + // DEBUG_LOG(("-- (%d)\n", d->m_passengerWeaponBonusVec[i])); + //} } // ------------------------------------------------------------------------------------------------ @@ -306,7 +312,7 @@ void OpenContain::addToContain( Object *rider ) wasSelected = TRUE; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( !isValidContainerFor( rider, false ) ) { Object *reportObject = rider; @@ -631,7 +637,7 @@ void OpenContain::removeFromContainViaIterator( ContainedItemsList::iterator it, { /* - #ifdef _DEBUG + #ifdef RTS_DEBUG TheInGameUI->message( UnicodeString( L"'%S(%d)' no longer contains '%S(%d)'" ), getObject()->getTemplate()->getName().str(), getObject()->getID(), @@ -738,6 +744,12 @@ void OpenContain::scatterToNearbyPosition(Object* rider) //------------------------------------------------------------------------------------------------- void OpenContain::onContaining( Object *rider, Bool wasSelected ) { + + const OpenContainModuleData* d = getOpenContainModuleData(); + for (Int i = 0; i < d->m_passengerWeaponBonusVec.size(); i++) { + rider->setWeaponBonusCondition(d->m_passengerWeaponBonusVec[i]); + } + // Play audio if( m_loadSoundsEnabled ) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp index e0537f3ac1..cc744ad4a6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OverlordContain.cpp @@ -47,7 +47,7 @@ #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp index 024dee7969..1a75a22778 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/ParachuteContain.cpp @@ -50,7 +50,7 @@ const Real NO_START_Z = 1e10; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp index 664f7d21f4..5d4764906f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/RiderChangeContain.cpp @@ -55,7 +55,7 @@ #include "GameLogic/Module/RiderChangeContain.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp index 04bf7ddadb..638f25f210 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TransportContain.cpp @@ -45,8 +45,9 @@ #include "GameLogic/Module/TransportContain.h" #include "GameLogic/Object.h" #include "GameLogic/Weapon.h" +#include "GameLogic/WeaponSetType.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -77,6 +78,8 @@ TransportContainModuleData::TransportContainModuleData() // m_allowInsideKindOf = MAKE_KINDOF_MASK( KINDOF_INFANTRY ); + m_passengerWeaponBonusVec.push_back(WEAPONBONUSCONDITION_CONTAINED); + } // ------------------------------------------------------------------------------------------------ @@ -306,6 +309,12 @@ void TransportContain::onContaining( Object *rider, Bool wasSelected ) } // end if + + // give the object a contained version of its weapon + // rider->setWeaponBonusCondition(WEAPONBONUSCONDITION_CONTAINED); + rider->setWeaponSetFlag(WEAPONSET_CONTAINED); + + if ( getTransportContainModuleData()->m_armedRidersUpgradeWeaponSet ) letRidersUpgradeWeaponSet(); @@ -336,6 +345,10 @@ void TransportContain::onRemoving( Object *rider ) const TransportContainModuleData* d = getTransportContainModuleData(); + // give the object back a regular weapon + rider->clearWeaponBonusCondition(WEAPONBONUSCONDITION_CONTAINED); + rider->clearWeaponSetFlag(WEAPONSET_CONTAINED); + if (!d->m_exitBone.isEmpty()) { Drawable* draw = getObject()->getDrawable(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp index 02d73af63b..b5402ba312 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp @@ -43,7 +43,7 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp index c9654788a3..ac0334f4d2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Create/PreorderCreate.cpp @@ -35,7 +35,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/PreorderCreate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp index 4763a3e3c7..84dc17cd12 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/CreateObjectDie.cpp @@ -39,7 +39,7 @@ #include "GameLogic/ObjectCreationList.h" #include "GameLogic/Module/BodyModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp index 5d8b38c58f..8881c5a2f4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DestroyDie.cpp @@ -35,7 +35,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Module/DestroyDie.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp index c2a6372867..2dcea456b2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/DieModule.cpp @@ -38,7 +38,7 @@ #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp index 8a928eb82a..6e9e22ca83 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Die/RebuildHoleExposeDie.cpp @@ -46,7 +46,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameClient/SelectionXlat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -107,7 +107,7 @@ void RebuildHoleExposeDie::onDie( const DamageInfo *damageInfo ) return; -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) if(TheSelectionTranslator->isHandOfGodSelectionMode()) { if ( getObject()->isKindOf( KINDOF_STRUCTURE ) ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp index f9ae823843..1e02b892c8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ExperienceTracker.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -48,6 +48,7 @@ ExperienceTracker::ExperienceTracker(Object *parent) : m_currentLevel(LEVEL_REGULAR), m_experienceSink(INVALID_ID), m_experienceScalar( 1.0f ), + m_experienceValueScalar(1.0f ), m_currentExperience(0) // Added By Sadullah Nader { } @@ -64,7 +65,7 @@ Int ExperienceTracker::getExperienceValue( const Object* killer ) const if( killer->getRelationship( m_parent ) == ALLIES ) return 0; - return m_parent->getTemplate()->getExperienceValue(m_currentLevel); + return m_parent->getTemplate()->getExperienceValue(m_currentLevel) * m_experienceValueScalar; } //------------------------------------------------------------------------------------------------- @@ -266,6 +267,9 @@ void ExperienceTracker::xfer( Xfer *xfer ) // experience scalar xfer->xferReal( &m_experienceScalar ); + // experience value scalar + xfer->xferReal(&m_experienceValueScalar); + } // end xfer //----------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp index 4457981c63..e620b587fd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp index c8f77f4d82..1206b9f14f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/GhostObject.cpp @@ -42,7 +42,10 @@ GhostObject::GhostObject(void): //Added By Sadullah Nader //Initializations missing and needed m_parentAngle(0.0f), -m_parentGeometryIsSmall(0.0f), +// TheSuperHackers @bugfix tomsons26 26/04/2025 Change initialization of m_parentGeometryIsSmall from 0.0f. +// Assigning a float to a bool results in the compiler using a random 1 byte value to assign to the bool. +// @todo Change initialization to 'false' when applicable. +m_parentGeometryIsSmall(true), m_parentGeometryMajorRadius(0.0f), m_parentGeometryminorRadius(0.0f), m_parentObject(NULL), diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp index e4007fed44..c80618523d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectDefectionHelper.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ObjectDefectionHelper.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp index 0d7713bd8e..3e66caac25 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/ObjectHelper.cpp @@ -34,7 +34,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ObjectHelper.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp index 9c5aed4858..da076c98ba 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Helper/TempWeaponBonusHelper.cpp @@ -43,6 +43,7 @@ TempWeaponBonusHelper::TempWeaponBonusHelper( Thing *thing, const ModuleData *modData ) : ObjectHelper( thing, modData ) { m_currentBonus = WEAPONBONUSCONDITION_INVALID; + m_currentTint = TINT_STATUS_INVALID; m_frameToRemove = 0; setWakeFrame(getObject(), UPDATE_SLEEP_FOREVER); @@ -75,18 +76,23 @@ void TempWeaponBonusHelper::clearTempWeaponBonus() m_currentBonus = WEAPONBONUSCONDITION_INVALID; m_frameToRemove = 0; - if( getObject()->getDrawable() ) - { - getObject()->getDrawable()->clearTintStatus(TINT_STATUS_FRENZY); -// if (getObject()->isKindOf(KINDOF_INFANTRY)) -// getObject()->getDrawable()->setSecondMaterialPassOpacity( 0.0f ); - } + if (getObject()->getDrawable()) + { + if (m_currentTint > TINT_STATUS_INVALID && m_currentTint < TINT_STATUS_COUNT) { + getObject()->getDrawable()->clearTintStatus(m_currentTint); + m_currentTint = TINT_STATUS_INVALID; + } + + // getObject()->getDrawable()->clearTintStatus(TINT_STATUS_FRENZY); + // if (getObject()->isKindOf(KINDOF_INFANTRY)) + // getObject()->getDrawable()->setSecondMaterialPassOpacity( 0.0f ); + } } } // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -void TempWeaponBonusHelper::doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration ) +void TempWeaponBonusHelper::doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration, TintStatus tintStatus) { // Clear any different status we may have. Re-getting the same status will just reset the timer if( m_currentBonus != status ) @@ -96,12 +102,18 @@ void TempWeaponBonusHelper::doTempWeaponBonus( WeaponBonusConditionType status, m_currentBonus = status; m_frameToRemove = TheGameLogic->getFrame() + duration; - if( getObject()->getDrawable() ) - { - getObject()->getDrawable()->setTintStatus(TINT_STATUS_FRENZY); -// if (getObject()->isKindOf(KINDOF_INFANTRY)) -// getObject()->getDrawable()->setSecondMaterialPassOpacity( 1.0f ); - } + if (getObject()->getDrawable()) + { + if (tintStatus > TINT_STATUS_INVALID && tintStatus < TINT_STATUS_COUNT) { + getObject()->getDrawable()->setTintStatus(tintStatus); + m_currentTint = tintStatus; + } + + // getObject()->getDrawable()->setTintStatus(TINT_STATUS_FRENZY); + + // if (getObject()->isKindOf(KINDOF_INFANTRY)) + // getObject()->getDrawable()->setSecondMaterialPassOpacity( 1.0f ); + } setWakeFrame( getObject(), UPDATE_SLEEP(duration) ); } @@ -134,6 +146,7 @@ void TempWeaponBonusHelper::xfer( Xfer *xfer ) ObjectHelper::xfer( xfer ); xfer->xferUser( &m_currentBonus, sizeof(WeaponBonusConditionType) );// an enum + xfer->xferUser( &m_currentTint, sizeof(TintStatus) );// an enum xfer->xferUnsignedInt( &m_frameToRemove ); } // end xfer diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp index 563437edce..984973e1b1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp @@ -46,7 +46,7 @@ #include "GameLogic/Module/BodyModule.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 2d375390a6..853f82ffd9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -33,6 +33,7 @@ #include "Common/BitFlagsIO.h" #include "Common/BuildAssistant.h" #include "Common/Dict.h" +#include "Common/GameCommon.h" #include "Common/GameEngine.h" #include "Common/GameState.h" #include "Common/ModuleFactory.h" @@ -111,7 +112,7 @@ #include "Common/AudioEventInfo.h" #include "Common/DynamicAudioEventInfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -152,8 +153,7 @@ extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBCo //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#ifdef DEBUG_LOGGING -AsciiString DescribeObject(const Object *obj) +AsciiString DebugDescribeObject(const Object *obj) { if (!obj) return ""; @@ -177,7 +177,6 @@ AsciiString DescribeObject(const Object *obj) return ret; } -#endif // DEBUG_LOGGING //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- @@ -224,7 +223,7 @@ Object::Object( const ThingTemplate *tt, const ObjectStatusMaskType &objectStatu m_visionSpiedMask (PLAYERMASK_NONE), m_numTriggerAreasActive(0) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_hasDiedAlready = false; #endif //Modules have not been created yet! @@ -571,7 +570,7 @@ void Object::initObject() // Kris -- All missiles must be projectiles! This is the perfect place to assert them! // srj: yes, but only in debug... -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( !isKindOf( KINDOF_PROJECTILE ) ) { if( isKindOf( KINDOF_SMALL_MISSILE ) || isKindOf( KINDOF_BALLISTIC_MISSILE ) ) @@ -1260,6 +1259,28 @@ UnsignedInt Object::getMostPercentReadyToFireAnyWeapon() const return m_weaponSet.getMostPercentReadyToFireAnyWeapon(); } +//============================================================================= +Bool Object::getWeaponInWeaponSlotSyncedToSlot(WeaponSlotType thisSlot, WeaponSlotType otherSlot) const +{ + CommandSourceMask mask = getWeaponInWeaponSlotCommandSourceMask(thisSlot); + + //Bool value0a = mask & (1 << CMD_SYNC_TO_PRIMARY); + //Bool value0b = (otherSlot == PRIMARY_WEAPON); + //Bool value1a = mask & (1 << CMD_SYNC_TO_SECONDARY); + //Bool value1b = (otherSlot == SECONDARY_WEAPON); + //Bool value2a = mask & (1 << CMD_SYNC_TO_TERTIARY); + //Bool value2b = (otherSlot == TERTIARY_WEAPON); + + //DEBUG_LOG(("- getWeaponInWeaponSlotSyncedToSlot (thisSlot=%d, otherSlot=%d): mask = %d --> value0 = %d/%d, value1 = %d/%d, value2 = %d/%d.\n", + // thisSlot, otherSlot, static_cast(mask), value0a, value0b, value1a, value1b, value2a, value2b)); + + return ((Int)mask >= 0) && + ((mask & (1 << CMD_SYNC_TO_PRIMARY) && otherSlot == PRIMARY_WEAPON) || + (mask & (1 << CMD_SYNC_TO_SECONDARY) && otherSlot == SECONDARY_WEAPON) || + (mask & (1 << CMD_SYNC_TO_TERTIARY) && otherSlot == TERTIARY_WEAPON)); + +} + //============================================================================= Bool Object::hasWeaponToDealDamageType(DamageType typeToDeal) const { @@ -1539,6 +1560,21 @@ void Object::preFireCurrentWeapon( const Object *victim ) } } +//============================================================================= +void Object::preFireCurrentWeapon(const Coord3D* pos) +{ + Weapon* weapon = m_weaponSet.getCurWeapon(); + + //If we are going to be capable of firing our weapon NEXT frame, set the pre-attack + //up now. This gets called by AIAttackFireWeaponState::onEnter().. but the update happens + //next frame. + if (weapon && TheGameLogic->getFrame() + 1 >= weapon->getPossibleNextShotFrame()) + { + weapon->preFireWeapon(this, pos); + friend_setUndetectedDefector(FALSE);// My secret is out + } +} + // ============================================================================ /** Using the firing tracker, return the frame a shot was last fired on */ // ============================================================================ @@ -2628,7 +2664,7 @@ void Object::setTriggerAreaFlagsForChangeInPosition() if (m_team) m_team->setEnteredExited(); TheGameLogic->updateObjectsChangedTriggerAreas(); -#ifdef _DEBUG +#ifdef RTS_DEBUG //TheScriptEngine->AppendDebugMessage("Object exited.", false); #endif } @@ -2663,7 +2699,7 @@ void Object::setTriggerAreaFlagsForChangeInPosition() m_team->setEnteredExited(); TheGameLogic->updateObjectsChangedTriggerAreas(); ++m_numTriggerAreasActive; -#ifdef _DEBUG +#ifdef RTS_DEBUG //TheScriptEngine->AppendDebugMessage("Object entered.", false); #endif } @@ -3884,10 +3920,6 @@ void Object::onDisabledEdge(Bool becomingDisabled) //------------------------------------------------------------------------------------------------- void Object::crc( Xfer *xfer ) { - // This is evil - we cast the const Matrix3D * to a Matrix3D * because the XferCRC class must use - // the same interface as the XferLoad class for save game restore. This only works because - // XferCRC does not modify its data. - #ifdef DEBUG_CRC // g_logObjectCRCs = TRUE; // Bool g_logAllObjects = TRUE; @@ -3896,7 +3928,7 @@ void Object::crc( Xfer *xfer ) Bool doLogging = g_logObjectCRCs /* && getControllingPlayer()->getPlayerType() == PLAYER_HUMAN */; if (doLogging) { - tmp.format("CRC of Object %d (%s), owned by player %d, ", m_id, getTemplate()->getName().str(), getControllingPlayer()->getPlayerIndex()); + tmp.format("CRC of Object %d (%s), owned by player %d, team: %d, ", m_id, getTemplate()->getName().str(), getControllingPlayer()->getPlayerIndex(), this->getTeam() ? this->getTeam()->getID() : TEAM_ID_INVALID); logString.concat(tmp); } #endif // DEBUG_CRC @@ -3910,6 +3942,9 @@ void Object::crc( Xfer *xfer ) } #endif // DEBUG_CRC + // This is evil - we cast the const Matrix3D * to a Matrix3D * because the XferCRC class must use + // the same interface as the XferLoad class for save game restore. This only works because + // XferCRC does not modify its data. xfer->xferUser((Matrix3D *)getTransformMatrix(), sizeof(Matrix3D)); #ifdef DEBUG_CRC if (doLogging) @@ -3924,25 +3959,6 @@ void Object::crc( Xfer *xfer ) #endif // DEBUG_CRC -#ifdef DEBUG_CRC - if (doLogging) - { - const Matrix3D *mtx = getTransformMatrix(); - CRCDEBUG_LOG(("CRC of Object %d (%s), owned by player %d, ", m_id, getTemplate()->getName().str(), getControllingPlayer()->getPlayerIndex())); - DUMPMATRIX3D(mtx); - } -#endif // DEBUG_CRC - - - - - - - - - - - xfer->xferUser(&m_id, sizeof(m_id)); #ifdef DEBUG_CRC if (doLogging) @@ -4408,7 +4424,7 @@ void Object::xfer( Xfer *xfer ) //m_body; //m_ai; //m_physics; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //m_hasDiedAlready; #endif @@ -4574,7 +4590,7 @@ void Object::onDie( DamageInfo *damageInfo ) checkAndDetonateBoobyTrap(NULL);// Already dying, so no need to handle death case of explosion -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) DEBUG_ASSERTCRASH(m_hasDiedAlready == false, ("Object::onDie has been called multiple times. This is invalid. jkmcd")); m_hasDiedAlready = true; #endif @@ -5124,7 +5140,7 @@ void Object::unshroud() //------------------------------------------------------------------------------------------------- Real Object::getVisionRange() const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { Vector3 pos(m_visionRange, 0, 0); @@ -5160,7 +5176,7 @@ Real Object::getShroudClearingRange() const shroudClearingRange = getGeometryInfo().getBoundingCircleRadius(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { Vector3 pos(shroudClearingRange, 0, 0); @@ -5217,7 +5233,7 @@ void Object::setShroudClearingRange( Real newShroudClearingRange ) //------------------------------------------------------------------------------------------------- Real Object::getShroudRange() const { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugVisibility) { Vector3 pos(m_shroudRange, 0, 0); @@ -5285,10 +5301,10 @@ void Object::doStatusDamage( ObjectStatusTypes status, Real duration ) } //------------------------------------------------------------------------------------------------- -void Object::doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration ) +void Object::doTempWeaponBonus( WeaponBonusConditionType status, UnsignedInt duration, TintStatus tintStatus) { if(m_tempWeaponBonusHelper) - m_tempWeaponBonusHelper->doTempWeaponBonus(status, duration); + m_tempWeaponBonusHelper->doTempWeaponBonus(status, duration, tintStatus); } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp index be6b1ad224..c7a5ad2709 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp @@ -73,7 +73,7 @@ #include "Common/CRCDebug.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -754,6 +754,8 @@ class GenericObjectCreationNugget : public ObjectCreationNugget m_minLODRequired(STATIC_GAME_LOD_LOW), m_ignorePrimaryObstacle(false), m_inheritsVeterancy(false), + m_inheritsWeaponBonus(false), + m_experienceSink(false), m_diesOnBadLand(FALSE), m_skipIfSignificantlyAirborne(false), m_invulnerableTime(0), @@ -874,6 +876,8 @@ class GenericObjectCreationNugget : public ObjectCreationNugget { "MinHealth", INI::parsePercentToReal, NULL, offsetof(GenericObjectCreationNugget, m_minHealth) }, { "MaxHealth", INI::parsePercentToReal, NULL, offsetof(GenericObjectCreationNugget, m_maxHealth) }, { "RequiresLivePlayer", INI::parseBool, NULL, offsetof(GenericObjectCreationNugget, m_requiresLivePlayer) }, + { "InheritsWeaponBonus", INI::parseBool, NULL, offsetof(GenericObjectCreationNugget, m_inheritsWeaponBonus) }, + { "ExperienceSinkForCaller", INI::parseBool, NULL, offsetof(GenericObjectCreationNugget, m_experienceSink) }, { 0, 0, 0, 0 } }; @@ -1029,6 +1033,14 @@ class GenericObjectCreationNugget : public ObjectCreationNugget TheScriptEngine->transferObjectName( sourceObj->getName(), obj ); } + if (m_experienceSink && sourceObj) { + obj->getExperienceTracker()->setExperienceSink(sourceObj->getID()); + } + + if (m_inheritsWeaponBonus && sourceObj) { + obj->setWeaponBonusConditionFlags(sourceObj->getWeaponBonusCondition()); + } + if ( m_invulnerableTime > 0 ) { obj->goInvulnerable( m_invulnerableTime ); @@ -1482,6 +1494,8 @@ class GenericObjectCreationNugget : public ObjectCreationNugget Int m_objectCount; // how many objects will there be? AudioEventRTS m_bounceSound; Bool m_requiresLivePlayer; + Bool m_experienceSink; + Bool m_inheritsWeaponBonus; Bool m_containInsideSourceObject; ///< The created stuff will be added to the Conatin module of the SourceObject Bool m_preserveLayer; Bool m_nameAreObjects; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp index c049d77060..b6eb3df7af 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp @@ -79,7 +79,7 @@ #include "GameClient/Line2D.h" #include "GameClient/ControlBar.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG //#include "GameClient/InGameUI.h" // for debugHints #include "Common/PlayerList.h" #endif @@ -96,7 +96,7 @@ UnsignedInt s_gcoPerfFrame = 0xffffffff; #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1492,7 +1492,7 @@ void PartitionCell::getCellCenterPos(Real& x, Real& y) } //----------------------------------------------------------------------------- -#ifdef _DEBUG +#ifdef RTS_DEBUG void PartitionCell::validateCoiList() { CellAndObjectIntersection *nextCoi = 0, *prevCoi = 0; @@ -2138,7 +2138,7 @@ void PartitionData::invalidateShroudedStatusForAllPlayers() } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) static AsciiString theObjName; #endif @@ -2152,7 +2152,7 @@ Int PartitionData::calcMaxCoiForShape(GeometryType geom, Real majorRadius, Real //M Lorenzen 8/26/03 // if (isSmall) // { -// #if defined(_DEBUG) || defined(_INTERNAL) +// #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // Int chk = calcMaxCoiForShape(geom, majorRadius, minorRadius, false); // DEBUG_ASSERTCRASH(chk <= 4, ("Small objects should be <= 4 cells, but I calced %s as %d\n",theObjName.str(),chk)); // #endif @@ -2193,7 +2193,7 @@ Int PartitionData::calcMaxCoiForObject() Real majorRadius = obj->getGeometryInfo().getMajorRadius(); Real minorRadius = obj->getGeometryInfo().getMinorRadius(); Bool isSmall = obj->getGeometryInfo().getIsSmall(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) theObjName = obj->getTemplate()->getName(); #endif return calcMaxCoiForShape(geom, majorRadius, minorRadius, isSmall); @@ -2695,7 +2695,7 @@ void PartitionManager::shutdown() m_updatedSinceLastReset = false; ThePartitionManager->removeAllDirtyModules(); -#ifdef _DEBUG +#ifdef RTS_DEBUG // the above *should* remove all the touched cells (via unRegisterObject), but let's check: DEBUG_ASSERTCRASH( m_moduleList == NULL, ("hmm, modules left over")); PartitionData *mod, *nextMod; @@ -2779,7 +2779,7 @@ void PartitionManager::update() processPendingUndoShroudRevealQueue(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugThreatMap) { if (TheGameLogic->getFrame() % TheGlobalData->m_debugThreatMapTileDuration) @@ -2839,7 +2839,7 @@ void PartitionManager::update() } } } -#endif // defined(_DEBUG) || defined(_INTERNAL) +#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) } // end update //------------------------------------------------------------------------------ @@ -3194,7 +3194,7 @@ void PartitionManager::calcRadiusVec() } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Int total = 0; for (Int i = 0; i <= m_maxGcoRadius; ++i) { @@ -3236,7 +3236,7 @@ Object *PartitionManager::getClosestObjects( GetPrecisionTimer(&startTime64); #endif -#ifdef _DEBUG +#ifdef RTS_DEBUG static Int theEntrancyCount = 0; DEBUG_ASSERTCRASH(theEntrancyCount == 0, ("sorry, this routine is not reentrant")); ++theEntrancyCount; @@ -3439,7 +3439,7 @@ Object *PartitionManager::getClosestObjects( *closestDistArg = (Real)sqrtf(closestDistSqr); } -#ifdef _DEBUG +#ifdef RTS_DEBUG --theEntrancyCount; #endif #ifdef DUMP_PERF_STATS @@ -5376,7 +5376,7 @@ Bool PartitionFilterPossibleToAttack::allow(Object *objOther) // objOther is guaranteed to be non-null, so we don't need to check (srj) // we should have already filtered out isAbleToAttack! -#ifdef _DEBUG +#ifdef RTS_DEBUG // disable this assert for INTERNAL builds (srj) DEBUG_ASSERTCRASH(m_obj && m_obj->isAbleToAttack(), ("if the object is unable to attack at all, you should filter that out ahead of time!")); #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp index 18d376892c..f52ccc7d2c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/FireWeaponPower.cpp @@ -57,7 +57,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/Module/FireWeaponPower.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp index 5d2933e91d..18857c33e7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/OCLSpecialPower.cpp @@ -44,7 +44,7 @@ // MODULE DATA //////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp index 39979386b9..6a37a750b6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialAbility.cpp @@ -39,7 +39,7 @@ /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp index b1220f83c6..06c9f9e463 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp @@ -54,7 +54,7 @@ #include "GameClient/ControlBar.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -288,7 +288,7 @@ Bool SpecialPowerModule::isModuleForPower( const SpecialPowerTemplate *specialPo //------------------------------------------------------------------------------------------------- Bool SpecialPowerModule::isReady() const { -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) // this is a cheat ... remove this for release! if( TheGlobalData->m_specialPowerUsesDelay == FALSE ) return TRUE; @@ -326,7 +326,7 @@ Real SpecialPowerModule::getPercentReady() const return 0.99999f; } -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) if( TheGlobalData->m_specialPowerUsesDelay == FALSE ) return 1.0f; #endif @@ -388,7 +388,7 @@ Bool SpecialPowerModule::isScriptOnly() const //------------------------------------------------------------------------------------------------- void SpecialPowerModule::startPowerRecharge() { -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) // this is a cheat ... remove this for release! if( TheGlobalData->m_specialPowerUsesDelay == FALSE ) return; @@ -544,96 +544,122 @@ void SpecialPowerModule::aboutToDoSpecialPower( const Coord3D *location ) Player *localPlayer = ThePlayerList->getLocalPlayer(); - // Only play the EVA sounds if this is not the local player, and the local player doesn't consider the - // person an enemy. - // Kris: Actually, all players need to hear these warnings. - // Ian: But now there are different Eva messages depending on who launched - //if (localPlayer != getObject()->getControllingPlayer() && localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) - { - if( type == SPECIAL_PARTICLE_UPLINK_CANNON || type == SUPW_SPECIAL_PARTICLE_UPLINK_CANNON || type == LAZR_SPECIAL_PARTICLE_UPLINK_CANNON ) - { - if ( localPlayer == getObject()->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_ParticleCannon); - } - else if ( localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_ParticleCannon); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_ParticleCannon); - } - } - else if( type == SPECIAL_NEUTRON_MISSILE || type == NUKE_SPECIAL_NEUTRON_MISSILE || type == SUPW_SPECIAL_NEUTRON_MISSILE ) - { - if ( localPlayer == getObject()->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_Nuke); - } - else if ( localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_Nuke); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_Nuke); - } - } - else if (type == SPECIAL_SCUD_STORM) - { - if ( localPlayer == getObject()->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_ScudStorm); - } - else if ( localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_ScudStorm); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_ScudStorm); - } - } - else if (type == SPECIAL_GPS_SCRAMBLER || type == SLTH_SPECIAL_GPS_SCRAMBLER ) - { - // This is Ghetto. Voices should be ini lines in the special power entry. You shouldn't have to - // add to an enum to get a new voice - if ( localPlayer == getObject()->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_GPS_Scrambler); - } - else if ( localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_GPS_Scrambler); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_GPS_Scrambler); - } - } - else if (type == SPECIAL_SNEAK_ATTACK) - { - if ( localPlayer == getObject()->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_Sneak_Attack); - } - else if ( localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES ) - { - // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_Sneak_Attack); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_Sneak_Attack); - } - } - } - + // Check if SpecialPower eva event instead of hardcoded stuff + bool isOwn = localPlayer == getObject()->getControllingPlayer(); + bool isAlly = localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES; + bool isEnemy = !isOwn && !isAlly; + bool isDefault = type < SPECIAL_ION_CANNON; // first new Special Power + + //Check SpecialPower Eva + const SpecialPowerTemplate* specialPowerTemp = getSpecialPowerModuleData()->m_specialPowerTemplate; + EvaMessage eva = EVA_Invalid; + + if (isOwn) { + eva = specialPowerTemp->getEvaLaunchedOwn(); + } + else if (isAlly) { + eva = specialPowerTemp->getEvaLaunchedAlly(); + } + else if (isEnemy) { + eva = specialPowerTemp->getEvaLaunchedEnemy(); + } + + if (eva > EVA_FIRST) { + TheEva->setShouldPlay(eva); + } + else if (eva == EVA_Invalid && isDefault) { + //Do the old hardcoded stuff for undefined default powers + + // Only play the EVA sounds if this is not the local player, and the local player doesn't consider the + // person an enemy. + // Kris: Actually, all players need to hear these warnings. + // Ian: But now there are different Eva messages depending on who launched + //if (localPlayer != getObject()->getControllingPlayer() && localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) + { + if (type == SPECIAL_PARTICLE_UPLINK_CANNON || type == SUPW_SPECIAL_PARTICLE_UPLINK_CANNON || type == LAZR_SPECIAL_PARTICLE_UPLINK_CANNON) + { + if (localPlayer == getObject()->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_ParticleCannon); + } + else if (localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_ParticleCannon); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_ParticleCannon); + } + } + else if (type == SPECIAL_NEUTRON_MISSILE || type == NUKE_SPECIAL_NEUTRON_MISSILE || type == SUPW_SPECIAL_NEUTRON_MISSILE) + { + if (localPlayer == getObject()->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_Nuke); + } + else if (localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_Nuke); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_Nuke); + } + } + else if (type == SPECIAL_SCUD_STORM) + { + if (localPlayer == getObject()->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_ScudStorm); + } + else if (localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_ScudStorm); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_ScudStorm); + } + } + else if (type == SPECIAL_GPS_SCRAMBLER || type == SLTH_SPECIAL_GPS_SCRAMBLER) + { + // This is Ghetto. Voices should be ini lines in the special power entry. You shouldn't have to + // add to an enum to get a new voice + if (localPlayer == getObject()->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_GPS_Scrambler); + } + else if (localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_GPS_Scrambler); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_GPS_Scrambler); + } + } + else if (type == SPECIAL_SNEAK_ATTACK) + { + if (localPlayer == getObject()->getControllingPlayer()) + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Own_Sneak_Attack); + } + else if (localPlayer->getRelationship(getObject()->getTeam()) != ENEMIES) + { + // Note: counting relationship NEUTRAL as ally. Not sure if this makes a difference??? + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Ally_Sneak_Attack); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponLaunched_Enemy_Sneak_Attack); + } + } + } + } // get module data const SpecialPowerModuleData *modData = getSpecialPowerModuleData(); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp index 8e744bf8ac..0c32d8d969 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp @@ -73,7 +73,7 @@ #define SLEEPY_AI -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -91,8 +91,11 @@ AIUpdateModuleData::AIUpdateModuleData() m_surrenderDuration = LOGICFRAMES_PER_SECOND * 120; #endif - m_forbidPlayerCommands = FALSE; + m_forbidPlayerCommands = FALSE; m_turretsLinked = FALSE; + m_attackAngle = 0.0f; + m_useAttackAngle = FALSE; + m_attackAngleMirrored = FALSE; } //------------------------------------------------------------------------------------------------- @@ -140,13 +143,41 @@ const LocomotorTemplateVector* AIUpdateModuleData::findLocomotorTemplateVector(L #ifdef ALLOW_SURRENDER { "SurrenderDuration", INI::parseDurationUnsignedInt, NULL, offsetof(AIUpdateModuleData, m_surrenderDuration) }, #endif - { "ForbidPlayerCommands", INI::parseBool, NULL, offsetof(AIUpdateModuleData, m_forbidPlayerCommands) }, - { "TurretsLinked", INI::parseBool, NULL, offsetof( AIUpdateModuleData, m_turretsLinked ) }, + { "ForbidPlayerCommands", INI::parseBool, NULL, offsetof(AIUpdateModuleData, m_forbidPlayerCommands) }, + { "TurretsLinked", INI::parseBool, NULL, offsetof(AIUpdateModuleData, m_turretsLinked) }, + { "PreferredAttackAngle", AIUpdateModuleData::parseAttackAngle, NULL, offsetof(AIUpdateModuleData, m_attackAngle) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); } +//------------------------------------------------------------------------------------------------- +/*static*/ void AIUpdateModuleData::parseAttackAngle(INI* ini, void* instance, void* store, const void* /*userData*/) +{ + AIUpdateModuleData* self = (AIUpdateModuleData*)instance; + + const char* token = ini->getNextToken(); + + // Disable if None (not really needed actually) + if (stricmp(token, "None") == 0) { + // self->m_useAttackAngle = FALSE; + return; + } + + // Parse Angle and store in m_attackAngle + const Real RADS_PER_DEGREE = PI / 180.0f; + *(Real*)store = INI::scanReal(token) * RADS_PER_DEGREE; + + self->m_useAttackAngle = TRUE; + + // Check for Mirrored keyword + token = ini->getNextTokenOrNull(); + if (token != NULL && stricmp(token, "MIRRORED") == 0) { + self->m_attackAngleMirrored = TRUE; + } +} + + //------------------------------------------------------------------------------------------------- /*static*/ void AIUpdateModuleData::parseTurret(INI* ini, void *instance, void * store, const void* /*userData*/) { @@ -766,6 +797,28 @@ Real AIUpdateInterface::getTurretTurnRate(WhichTurretType tur) const 0.0f; } +//============================================================================= +Bool AIUpdateInterface::hasLimitedTurretAngle(WhichTurretType tur) const +{ + return (tur != TURRET_INVALID && m_turretAI[tur] != NULL) && m_turretAI[tur]->hasLimitedTurretAngle(); +} + +//============================================================================= +Real AIUpdateInterface::getMinTurretAngle(WhichTurretType tur) const +{ + return (tur != TURRET_INVALID && m_turretAI[tur] != NULL) ? + m_turretAI[tur]->getMinTurretAngle() : + 0.0f; +} + +//============================================================================= +Real AIUpdateInterface::getMaxTurretAngle(WhichTurretType tur) const +{ + return (tur != TURRET_INVALID && m_turretAI[tur] != NULL) ? + m_turretAI[tur]->getMaxTurretAngle() : + 0.0f; +} + //============================================================================= WhichTurretType AIUpdateInterface::getWhichTurretForCurWeapon() const { @@ -800,7 +853,7 @@ Real AIUpdateInterface::getCurLocomotorSpeed() const if (m_curLocomotor != NULL) return m_curLocomotor->getMaxSpeedForCondition(getObject()->getBodyModule()->getDamageState()); - DEBUG_LOG(("no current locomotor!")); + // DEBUG_LOG(("no current locomotor!")); return 0.0f; } @@ -2205,7 +2258,7 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void ) // obstacles, and follow the intermediate path points. ClosestPointOnPathInfo info; CRCDEBUG_LOG(("AIUpdateInterface::doLocomotor() - calling computePointOnPath() for %s\n", - DescribeObject(getObject()).str())); + DebugDescribeObject(getObject()).str())); getPath()->computePointOnPath(getObject(), m_locomotorSet, *getObject()->getPosition(), info); onPathDistToGoal = info.distAlongPath; goalPos = info.posOnPath; @@ -2332,7 +2385,7 @@ void AIUpdateInterface::setLocomotorGoalPositionExplicit(const Coord3D& newPos) { m_locomotorGoalType = POSITION_EXPLICIT; m_locomotorGoalData = newPos; -#ifdef _DEBUG +#ifdef RTS_DEBUG if (_isnan(m_locomotorGoalData.x) || _isnan(m_locomotorGoalData.y) || _isnan(m_locomotorGoalData.z)) { DEBUG_CRASH(("NAN in setLocomotorGoalPositionExplicit")); @@ -2345,7 +2398,7 @@ void AIUpdateInterface::setLocomotorGoalOrientation(Real angle) { m_locomotorGoalType = ANGLE; m_locomotorGoalData.x = angle; -#ifdef _DEBUG +#ifdef RTS_DEBUG if (_isnan(m_locomotorGoalData.x) || _isnan(m_locomotorGoalData.y) || _isnan(m_locomotorGoalData.z)) { DEBUG_CRASH(("NAN in setLocomotorGoalOrientation")); @@ -3507,6 +3560,9 @@ void AIUpdateInterface::privateAttackTeam( const Team *team, Int maxShotsToFire, */ void AIUpdateInterface::privateAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) { + //DEBUG_LOG(("AIUpdateInterface::privateAttackPosition: Order %s to fire at pos, type = %d\n", + // getObject()->getTemplate()->getName().str(), cmdSource)); + //Resetting the locomotor here was initially added for scripting purposes. It has been moved //to the responsibility of the script to reset the locomotor before moving. This is needed because //other systems (like the battle drone) change the locomotor based on what it's trying to do, and @@ -4721,43 +4777,48 @@ void AIUpdateInterface::evaluateMoraleBonus( void ) #ifdef ALLOW_DEMORALIZE // if we are are not demoralized we can have horde and nationalism effects - if( demoralized == FALSE ) + if (demoralized == FALSE) #endif { #ifdef ALLOW_DEMORALIZE // demoralized - us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_DEMORALIZED ); + us->clearWeaponBonusCondition(WEAPONBONUSCONDITION_DEMORALIZED); #endif - + //Lorenzen temporarily disabled, since it fights with the horde buff //Drawable *draw = us->getDrawable(); //if ( draw && !us->isKindOf( KINDOF_PORTABLE_STRUCTURE ) ) // draw->setTerrainDecal(TERRAIN_DECAL_NONE); // horde - if( horde ) + if (horde) { - us->setWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE ); + us->setWeaponBonusCondition(WEAPONBONUSCONDITION_HORDE); + } // end if - else - us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_HORDE ); + else { + us->clearWeaponBonusCondition(WEAPONBONUSCONDITION_HORDE); + } // nationalism - if( nationalism ) - { - us->setWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM ); - // fanaticism - if ( fanaticism ) - us->setWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM );// FOR THE NEW GC INFANTRY GENERAL - else - us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM ); - } - else - us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_NATIONALISM ); - + if (horde && nationalism) + { + us->setWeaponBonusCondition(WEAPONBONUSCONDITION_NATIONALISM); + } + else { + us->clearWeaponBonusCondition(WEAPONBONUSCONDITION_NATIONALISM); + } + // fanaticism + if (horde && fanaticism) + { + us->setWeaponBonusCondition(WEAPONBONUSCONDITION_FANATICISM);// FOR THE NEW GC INFANTRY GENERAL + } + else { + us->clearWeaponBonusCondition( WEAPONBONUSCONDITION_FANATICISM ); + } } // end if #ifdef ALLOW_DEMORALIZE diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp index a71d860940..193419c929 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/AssaultTransportAIUpdate.cpp @@ -43,7 +43,7 @@ #include "GameLogic/PartitionManager.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp index 87e4cf2ae8..197e57765c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp @@ -1,1677 +1,1677 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// ChinookAIUpdate.cpp ////////// - -#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine - -#define DEFINE_VETERANCY_NAMES // for TheVeterancyNames[] - -#include "Common/ActionManager.h" -#include "Common/DrawModule.h" -#include "Common/GameState.h" -#include "Common/GlobalData.h" -#include "Common/RandomValue.h" -#include "Common/Team.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "Common/Xfer.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "GameClient/Drawable.h" -#include "GameClient/GameClient.h" -#include "GameClient/ParticleSys.h" -#include "GameLogic/AIPathfind.h" -#include "GameLogic/Locomotor.h" -#include "GameLogic/Module/ContainModule.h" -#include "GameLogic/Module/ChinookAIUpdate.h" -#include "GameLogic/Module/PhysicsUpdate.h" -#include "GameLogic/PartitionManager.h" - -const Real BIGNUM = 99999.0f; - -#ifdef _INTERNAL -// for occasional debugging... -//#pragma optimize("", off) -//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") -#endif - -//------------------------------------------------------------------------------------------------- -enum ChinookAIStateType CPP_11(: Int) -{ - // note that these must be distinct (numerically) from AIStateType. ick. - ChinookAIStateType_FIRST = 1000, - - TAKING_OFF, - LANDING, - - MOVE_TO_AND_LAND, - - MOVE_TO_AND_EVAC, - LAND_AND_EVAC, - EVAC_AND_TAKEOFF, - - MOVE_TO_AND_EVAC_AND_EXIT, - LAND_AND_EVAC_AND_EXIT, - EVAC_AND_EXIT, - TAKEOFF_AND_EXIT, - HEAD_OFF_MAP, - - MOVE_TO_COMBAT_DROP, - DO_COMBAT_DROP, - MOVE_TO_AND_EVAC_AND_EXIT_INIT -}; - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -static Real calcDistSqr(const Coord3D& a, const Coord3D& b) -{ - return sqr(a.x-b.x) + sqr(a.y-b.y) + sqr(a.z-b.z); -} - -//------------------------------------------------------------------------------------------------- -static Object* getPotentialRappeller(Object* obj) -{ - const ContainedItemsList* items = obj->getContain() ? obj->getContain()->getContainedItemsList() : NULL; - if (items) - { - for (ContainedItemsList::const_iterator it = items->begin(); it != items->end(); ++it ) - { - Object* rider = *it; - if (rider->isKindOf(KINDOF_CAN_RAPPEL)) - { - return rider; - } - } - } - return NULL; -} - -//---------------------------------------------------------------------------------------------------------- -class ChinookEvacuateState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookEvacuateState, "ChinookEvacuateState") -protected: - // snapshot interface STUBBED - no member vars to save. jba. - virtual void crc( Xfer *xfer ){}; - virtual void xfer( Xfer *xfer ){}; - virtual void loadPostProcess(){}; -public: - ChinookEvacuateState( StateMachine *machine ) : State( machine, "ChinookEvacuateState" ) { } - - StateReturnType onEnter() - { - Object* obj = getMachineOwner(); - if( obj->getContain() ) - { - obj->getContain()->removeAllContained(FALSE); - } - obj->getTeam()->setActive(); // why? I don't know. - return STATE_SUCCESS; - } - - virtual StateReturnType update() - { - return STATE_SUCCESS; - } -}; -EMPTY_DTOR(ChinookEvacuateState) - -//------------------------------------------------------------------------------------------------- -class ChinookHeadOffMapState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookHeadOffMapState, "ChinookHeadOffMapState") - //I'm outta here -protected: - // snapshot interface STUBBED - no member vars to save. jba. - virtual void crc( Xfer *xfer ){}; - virtual void xfer( Xfer *xfer ){}; - virtual void loadPostProcess(){}; -public: - ChinookHeadOffMapState( StateMachine *machine ) : State( machine, "ChinookHeadOffMapState" ) {} - - StateReturnType onEnter() // Give move order out of town - { - Object *owner = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)owner->getAIUpdateInterface(); - - owner->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_RIDER8 ) ); - ai->aiMoveToPosition( ai->getOriginalPosition(), CMD_FROM_AI ); - ai->getCurLocomotor()->setAllowInvalidPosition(true); - - return STATE_CONTINUE; - } - - StateReturnType update() - { - Object *owner = getMachineOwner(); - - Region3D mapRegion; - TheTerrainLogic->getExtentIncludingBorder( &mapRegion ); - if( !mapRegion.isInRegionNoZ( owner->getPosition() ) ) - { - TheGameLogic->destroyObject(owner); - return STATE_SUCCESS; - } - - return STATE_CONTINUE; - } - - void onExit() - { - Object *owner = getMachineOwner(); - owner->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_RIDER8 ) ); - } -}; -EMPTY_DTOR(ChinookHeadOffMapState) - -//------------------------------------------------------------------------------------------------- -class ChinookTakeoffOrLandingState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookTakeoffOrLandingState, "ChinookTakeoffOrLandingState") -private: - Coord3D m_destLoc; - Bool m_landing; - -protected: - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty - } - - virtual void xfer( Xfer *xfer ) - { - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - xfer->xferCoord3D(&m_destLoc); - xfer->xferBool(&m_landing); - } - - virtual void loadPostProcess() - { - // empty - } - -public: - ChinookTakeoffOrLandingState( StateMachine *machine, Bool landing ) : m_landing(landing), State( machine, "ChinookTakeoffOrLandingState" ) - { - m_destLoc.zero(); - } - - virtual StateReturnType onEnter() - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - - ai->friend_setFlightStatus(m_landing ? CHINOOK_LANDING : CHINOOK_TAKING_OFF); - - if( m_landing ) - { - // A chinook given transport duty loses his supplies. - while( ai->loseOneBox() ); - } - - // kill any drift... - obj->getPhysics()->scrubVelocity2D(0); - - ai->chooseLocomotorSet(LOCOMOTORSET_NORMAL); - Locomotor* loco = ai->getCurLocomotor(); - loco->setUsePreciseZPos(true); - loco->setUltraAccurate(true); - - m_destLoc = *obj->getPosition(); - const Bool onlyHealthyBridges = true; // ignore dead bridges. - PathfindLayerEnum layerAtDest = TheTerrainLogic->getHighestLayerForDestination(&m_destLoc, onlyHealthyBridges); - m_destLoc.z = TheTerrainLogic->getLayerHeight(m_destLoc.x, m_destLoc.y, layerAtDest); - if (m_landing) - { - Coord3D tmp; - FindPositionOptions options; - options.maxRadius = obj->getGeometryInfo().getBoundingCircleRadius() * 100.0f; - if (ThePartitionManager->findPositionAround(&m_destLoc, &options, &tmp)) - { - m_destLoc = tmp; - TheAI->pathfinder()->adjustToLandingDestination(obj, &m_destLoc); - } - // recalc, since it may have changed. note that findPositionAround() will ALWAYS - // return a position on the ground proper, so if our initial search start pos was - // above a bridge, this will put us below the bridge, which would be unfortunate. - // so recheck to be sure. (note that the partitionmgr is 2d-only, so if it sez that - // the position on the ground at that xy is clear, it will be clear for both the - // ground proper and the bridge itself.) also note: don't call objectInteractsWithBridgeLayer(), - // since it assumes that things that aren't close in z shouldn't interact. - tmp = m_destLoc; - tmp.z = obj->getPosition()->z; - layerAtDest = TheTerrainLogic->getHighestLayerForDestination(&tmp, onlyHealthyBridges); - m_destLoc.z = TheTerrainLogic->getLayerHeight(m_destLoc.x, m_destLoc.y, layerAtDest); - obj->setLayer(layerAtDest); - } - else - { - m_destLoc.z += loco->getPreferredHeight(); - obj->setLayer(LAYER_GROUND); - } - - return STATE_CONTINUE; - } - - virtual StateReturnType update() - { - Object* obj = getMachineOwner(); - if (obj->isEffectivelyDead()) - return STATE_FAILURE; - - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - - ai->setLocomotorGoalPositionExplicit(m_destLoc); - - const Real THRESH = 3.0f; - const Real THRESH_SQR = THRESH*THRESH; - if (calcDistSqr(*obj->getPosition(), m_destLoc) <= THRESH_SQR) - return STATE_SUCCESS; - - return STATE_CONTINUE; - } - - virtual void onExit( StateExitType status ) - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - - ai->friend_setFlightStatus(m_landing ? CHINOOK_LANDED : CHINOOK_FLYING); - - // Paranoia checks - sometimes onExit is called when we are - // shutting down, and not all pieces are valid. CurLocomotor - // is definitely null in some cases. jba. - Locomotor* loco = ai->getCurLocomotor(); - if (loco) - { - loco->setUsePreciseZPos(false); - loco->setUltraAccurate(false); - // don't restore lift if dead -- this may fight with JetSlowDeathBehavior! - if (!obj->isEffectivelyDead()) - loco->setMaxLift(BIGNUM); - } - - if (m_landing) - { - ai->chooseLocomotorSet(LOCOMOTORSET_TAXIING); - } - else - { - // when takeoff is complete, always go back to layer-ground, rather than - // some bridge layer. - obj->setLayer(LAYER_GROUND); - } - - - } - -}; -EMPTY_DTOR(ChinookTakeoffOrLandingState) - -//------------------------------------------------------------------------------------------------- -class ChinookCombatDropState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookCombatDropState, "ChinookCombatDropState") - -private: - - struct RopeInfo - { - Drawable* ropeDrawable; - DrawableID ropeID; // used only during save-load process - Matrix3D dropStartMtx; - Real ropeSpeed; - Real ropeLen; - Real ropeLenMax; - UnsignedInt nextDropTime; - std::list rappellerIDs; - }; - std::vector m_ropes; - - void removeDoneRappellers() - { - for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) - { - for (std::list::iterator oit = it->rappellerIDs.begin(); oit != it->rappellerIDs.end(); ) - { - Object* rappeller = TheGameLogic->findObjectByID(*oit); - if (rappeller == NULL || rappeller->isEffectivelyDead() || !rappeller->isAboveTerrain()) - { - oit = it->rappellerIDs.erase(oit); - } - else - { - ++oit; - } - } - } - } - - static void initRopeParms(Drawable* rope, Real length, Real width, const RGBColor& color, Real wobbleLen, Real wobbleAmp, Real wobbleRate) - { - RopeDrawInterface* tdi = NULL; - for (DrawModule** d = rope->getDrawModules(); *d; ++d) - { - if ((tdi = (*d)->getRopeDrawInterface()) != NULL) - { - tdi->initRopeParms(length, width, color, wobbleLen, wobbleAmp, wobbleRate); - } - } - } - - static void setRopeCurLen(Drawable* rope, Real length) - { - RopeDrawInterface* tdi = NULL; - for (DrawModule** d = rope->getDrawModules(); *d; ++d) - { - if ((tdi = (*d)->getRopeDrawInterface()) != NULL) - { - tdi->setRopeCurLen(length); - } - } - } - - static void setRopeSpeed(Drawable* rope, Real curSpeed, Real maxSpeed, Real accel) - { - RopeDrawInterface* tdi = NULL; - for (DrawModule** d = rope->getDrawModules(); *d; ++d) - { - if ((tdi = (*d)->getRopeDrawInterface()) != NULL) - { - tdi->setRopeSpeed(curSpeed, maxSpeed, accel); - } - } - } - -protected: - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty - } - - virtual void xfer( Xfer *xfer ) - { - // version - const XferVersion currentVersion = 2; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - Int numRopes = m_ropes.size(); - xfer->xferInt(&numRopes); - - if (version >= 2) - { - if (xfer->getXferMode() == XFER_LOAD) - { - if (!m_ropes.empty()) - { - DEBUG_CRASH(( "ChinookCombatDropState - ropes should be empty\n" )); - throw SC_INVALID_DATA; - } - m_ropes.resize(numRopes); - } - - for (Int i = 0; i < numRopes; ++i) - { - RopeInfo info; - if (xfer->getXferMode() == XFER_SAVE) - { - info = m_ropes[i]; - // always overwrite this, since it's probably stale - info.ropeID = info.ropeDrawable ? info.ropeDrawable->getID() : INVALID_DRAWABLE_ID; - } - xfer->xferDrawableID(&info.ropeID); - xfer->xferMatrix3D(&info.dropStartMtx); - xfer->xferReal(&info.ropeSpeed); - xfer->xferReal(&info.ropeLen); - xfer->xferReal(&info.ropeLenMax); - xfer->xferUnsignedInt(&info.nextDropTime); - xfer->xferSTLObjectIDList(&info.rappellerIDs); - if (xfer->getXferMode() == XFER_LOAD) - { - info.ropeDrawable = NULL; // filled in via loadPostProcess - m_ropes[i] = info; - } - } - } - } - - virtual void loadPostProcess() - { - for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) - { - it->ropeDrawable = TheGameClient->findDrawableByID(it->ropeID); - // always nuke this, since we're done with it till we save/load again - it->ropeID = INVALID_DRAWABLE_ID; - } - } - -public: - ChinookCombatDropState( StateMachine *machine ): State( machine, "ChinookCombatDropState" ) { } - - // -------------- - virtual StateReturnType onEnter() - { - Object* obj = getMachineOwner(); - Drawable* draw = obj->getDrawable(); - if (draw == NULL) - return STATE_FAILURE; - - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - const ChinookAIUpdateModuleData* d = ai->friend_getData(); - - obj->setDisabled( DISABLED_HELD ); - ai->friend_setFlightStatus(CHINOOK_DOING_COMBAT_DROP); - - // A chinook given combat drop duty also loses his supplies. - while( ai->loseOneBox() ); - - UnsignedInt now = TheGameLogic->getFrame(); - - const ThingTemplate* ropeTmpl = TheThingFactory->findTemplate(d->m_ropeName); - - const Int MAX_BONES = 32; - Coord3D ropePos[MAX_BONES]; - Matrix3D dropMtx[MAX_BONES]; - - Int ropeCount = draw->getPristineBonePositions("RopeStart", 1, ropePos, NULL, MAX_BONES); - Int dropCount = draw->getPristineBonePositions("RopeEnd", 1, NULL, dropMtx, MAX_BONES); - - Int numRopes = d->m_numRopes; - if (numRopes > ropeCount) numRopes = ropeCount; - if (numRopes > dropCount) numRopes = dropCount; - if (numRopes <= 0) - return STATE_FAILURE; - - m_ropes.clear(); - for (Int i = 0; i < numRopes; ++i) - { - RopeInfo info; - - obj->convertBonePosToWorldPos( NULL, &dropMtx[i], NULL, &info.dropStartMtx ); - - info.ropeDrawable = ropeTmpl ? TheThingFactory->newDrawable(ropeTmpl) : NULL; - if (info.ropeDrawable) - { - obj->convertBonePosToWorldPos( &ropePos[i], NULL, &ropePos[i], NULL ); - info.ropeDrawable->setPosition(&ropePos[i]); - info.ropeSpeed = 0.0f; - info.ropeLen = 1.0f; - - const Bool onlyHealthyBridges = true; // ignore dead bridges. - PathfindLayerEnum layerAtDest = TheTerrainLogic->getHighestLayerForDestination(&ropePos[i], onlyHealthyBridges); - - info.ropeLenMax = ropePos[i].z - TheTerrainLogic->getLayerHeight(ropePos[i].x, ropePos[i].y, layerAtDest) - d->m_ropeFinalHeight; - - initRopeParms(info.ropeDrawable, info.ropeLenMax, d->m_ropeWidth, d->m_ropeColor, d->m_ropeWobbleLen, d->m_ropeWobbleAmp, d->m_ropeWobbleRate); - } - - info.nextDropTime = now + GameLogicRandomValue(d->m_perRopeDelayMin, d->m_perRopeDelayMax) - d->m_perRopeDelayMin; - info.rappellerIDs.clear(); - - m_ropes.push_back(info); - } - - return STATE_CONTINUE; - } - - // -------------- - virtual StateReturnType update() - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - const ChinookAIUpdateModuleData* d = ai->friend_getData(); - - if (obj->isEffectivelyDead()) - { - return STATE_FAILURE; - } - - // first, eliminate "done" rappellers - removeDoneRappellers(); - - UnsignedInt now = TheGameLogic->getFrame(); - - // ok, now check each rope: if it's empty, or we're at the next drop time, spawn a new rappeller - Int numRopesInUse = 0; - for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) - { - if (it->ropeLen < it->ropeLenMax) - { - it->ropeSpeed += fabs(TheGlobalData->m_gravity); - if (it->ropeSpeed > d->m_ropeDropSpeed) - it->ropeSpeed = d->m_ropeDropSpeed; - it->ropeLen += it->ropeSpeed; - setRopeCurLen(it->ropeDrawable, it->ropeLen); - if (d->m_waitForRopesToDrop) - { - // can't use this rope till it's dropped all the way - ++it->nextDropTime; - continue; - } - } - - if (now >= it->nextDropTime) - { - Object* rappeller = getPotentialRappeller(obj); - if (rappeller != NULL) - { - ExitInterface *exitInterface = obj->getObjectExitInterface(); - ExitDoorType exitDoor = exitInterface ? exitInterface->reserveDoorForExit(rappeller->getTemplate(), rappeller) : DOOR_NONE_AVAILABLE; - if(exitDoor != DOOR_NONE_AVAILABLE) - { - exitInterface->exitObjectViaDoor(rappeller, exitDoor); - } - else - { - DEBUG_CRASH(("rappeller is not free to exit... what?")); - } - - rappeller->setTransformMatrix(&it->dropStartMtx); - - AIUpdateInterface* rappellerAI = rappeller ? rappeller->getAIUpdateInterface() : NULL; - if (rappellerAI) - { - rappellerAI->setDesiredSpeed(d->m_rappelSpeed); - rappellerAI->aiRappelInto(getMachineGoalObject(), *getMachineGoalPosition(), CMD_FROM_AI); - } - - it->rappellerIDs.push_back(rappeller->getID()); - - it->nextDropTime = now + GameLogicRandomValue(d->m_perRopeDelayMin, d->m_perRopeDelayMax); - } - } - - if (!it->rappellerIDs.empty()) - { - ++numRopesInUse; - } - } - - if (numRopesInUse == 0 && getPotentialRappeller(obj) == NULL) - { - // we're done! - return STATE_SUCCESS; - } - - return STATE_CONTINUE; - } - - // -------------- - virtual void onExit( StateExitType status ) - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - const ChinookAIUpdateModuleData* d = ai->friend_getData(); - - obj->clearDisabled( DISABLED_HELD ); - ai->friend_setFlightStatus(CHINOOK_FLYING); - - if (obj->isEffectivelyDead()) - { - // oops. drop the rangers. - for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) - { - for (std::list::iterator oit = it->rappellerIDs.begin(); oit != it->rappellerIDs.end(); ++oit) - { - Object* rappeller = TheGameLogic->findObjectByID(*oit); - AIUpdateInterface* rappellerAI = rappeller ? rappeller->getAIUpdateInterface() : NULL; - if (rappellerAI != NULL) - { - rappellerAI->aiIdle(CMD_FROM_AI); - } - } - } - } - - UnsignedInt now = TheGameLogic->getFrame(); - for (Int i = 0; i < m_ropes.size(); ++i) - { - if (m_ropes[i].ropeDrawable) - { - const UnsignedInt ROPE_EXPIRATION_TIME = LOGICFRAMES_PER_SECOND * 5; - const Real initialSpeed = TheGlobalData->m_gravity * 30; // give it a little kick - setRopeSpeed(m_ropes[i].ropeDrawable, initialSpeed, d->m_ropeDropSpeed, TheGlobalData->m_gravity); - m_ropes[i].ropeDrawable->setExpirationDate(now + ROPE_EXPIRATION_TIME); - m_ropes[i].ropeDrawable = NULL; // we're done with it, so null it so we won't save it - } - } - - m_ropes.clear(); - } - -}; -EMPTY_DTOR(ChinookCombatDropState) - -//----------------------------------------------------------------------------------------------------------- -/** - * Move to the GoalPosition, or GoalObject. - */ -class ChinookMoveToBldgState : public AIMoveToState -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookMoveToBldgState, "ChinookMoveToBldgState") -private: - Real m_oldPreferredHeight; - Real m_newPreferredHeight; - Real m_destZ; -protected: - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty - } - - virtual void xfer( Xfer *xfer ) - { - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - xfer->xferReal(&m_oldPreferredHeight); - xfer->xferReal(&m_newPreferredHeight); - xfer->xferReal(&m_destZ); - } - - virtual void loadPostProcess() - { - // empty - } - -public: - ChinookMoveToBldgState( StateMachine *machine ): AIMoveToState( machine ) { } - - virtual StateReturnType onEnter() - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - const ChinookAIUpdateModuleData* d = ai->friend_getData(); - Locomotor* loco = ai->getCurLocomotor(); - loco->setUltraAccurate(true); - m_oldPreferredHeight = loco->getPreferredHeight(); - m_newPreferredHeight = m_oldPreferredHeight; - - const Coord3D* destPos; - Object* bldg = getMachineGoalObject(); - if (bldg != NULL && !bldg->isEffectivelyDead() && bldg->isKindOf(KINDOF_STRUCTURE)) - { - destPos = bldg->getPosition(); - m_newPreferredHeight = bldg->getGeometryInfo().getMaxHeightAbovePosition() + d->m_minDropHeight; - if (m_newPreferredHeight < m_oldPreferredHeight) - m_newPreferredHeight = m_oldPreferredHeight; - } - else - { - destPos = getMachineGoalPosition(); - } - - loco->setPreferredHeight(m_newPreferredHeight); - - m_destZ = TheTerrainLogic->getGroundHeight(destPos->x, destPos->y) + m_newPreferredHeight; - - return AIMoveToState::onEnter(); - } - - virtual StateReturnType update() - { - Object* obj = getMachineOwner(); - - // the normal moveto state will bail when 2d pos matches; we need z, too - StateReturnType status = AIMoveToState::update(); - - const Real THRESH = 3.0f; - if (status != STATE_CONTINUE && fabs(obj->getPosition()->z - m_destZ) > THRESH) - status = STATE_CONTINUE; - - return status; - } - - virtual void onExit( StateExitType status ) - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - Locomotor* loco = ai->getCurLocomotor(); - loco->setPreferredHeight(m_oldPreferredHeight); - loco->setUltraAccurate(false); - AIMoveToState::onExit(status); - } - -}; -EMPTY_DTOR(ChinookMoveToBldgState) - -//----------------------------------------------------------------------------------------------------------- -/** - * Store the original position we are assigned to for exit. - */ -class ChinookRecordCreationState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookRecordCreationState, "ChinookRecordCreationState") -protected: - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty - } - - virtual void xfer( Xfer *xfer ) - { - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - } - - virtual void loadPostProcess() - { - // empty - } - -public: - ChinookRecordCreationState( StateMachine *machine ): State( machine, "ChinookRecordCreationState" ) { } - - virtual StateReturnType onEnter() - { - Object* obj = getMachineOwner(); - ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); - if( ai ) - { - ai->recordOriginalPosition( *obj->getPosition() ); - } - return STATE_SUCCESS; - } - - virtual StateReturnType update() - { - return STATE_SUCCESS; - } - -}; -EMPTY_DTOR(ChinookRecordCreationState) - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -class ChinookAIStateMachine : public AIStateMachine -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( ChinookAIStateMachine, "ChinookAIStateMachine" ); - -public: - ChinookAIStateMachine( Object *owner, AsciiString name ); - -}; - -//------------------------------------------------------------------------------------------------- -ChinookAIStateMachine::ChinookAIStateMachine(Object *owner, AsciiString name) : AIStateMachine(owner, name) -{ - defineState( TAKING_OFF, newInstance(ChinookTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE ); - defineState( LANDING, newInstance(ChinookTakeoffOrLandingState)( this, true ), AI_IDLE, AI_IDLE ); - defineState( MOVE_TO_COMBAT_DROP, newInstance(ChinookMoveToBldgState)( this ), DO_COMBAT_DROP, AI_IDLE ); - defineState( DO_COMBAT_DROP, newInstance(ChinookCombatDropState)( this ), AI_IDLE, AI_IDLE ); - - defineState( MOVE_TO_AND_LAND, newInstance(AIMoveToState)( this ), LANDING, AI_IDLE ); - - defineState( MOVE_TO_AND_EVAC, newInstance(AIMoveToState)( this ), LAND_AND_EVAC, AI_IDLE ); - defineState( LAND_AND_EVAC, newInstance(ChinookTakeoffOrLandingState)( this, true ), EVAC_AND_TAKEOFF, AI_IDLE ); - defineState( EVAC_AND_TAKEOFF, newInstance(ChinookEvacuateState)( this ), TAKING_OFF, AI_IDLE ); - - defineState( MOVE_TO_AND_EVAC_AND_EXIT_INIT, newInstance(ChinookRecordCreationState)( this ), MOVE_TO_AND_EVAC_AND_EXIT, AI_IDLE ); - defineState( MOVE_TO_AND_EVAC_AND_EXIT, newInstance(AIMoveToState)( this ), LAND_AND_EVAC_AND_EXIT, AI_IDLE ); - defineState( LAND_AND_EVAC_AND_EXIT, newInstance(ChinookTakeoffOrLandingState)( this, true ), EVAC_AND_EXIT, AI_IDLE ); - defineState( EVAC_AND_EXIT, newInstance(ChinookEvacuateState)( this ), TAKEOFF_AND_EXIT, AI_IDLE ); - defineState( TAKEOFF_AND_EXIT, newInstance(ChinookTakeoffOrLandingState)( this, false ), HEAD_OFF_MAP, AI_IDLE ); - defineState( HEAD_OFF_MAP, newInstance(ChinookHeadOffMapState)( this ), AI_IDLE, AI_IDLE ); -} - -//------------------------------------------------------------------------------------------------- -ChinookAIStateMachine::~ChinookAIStateMachine() -{ -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -ChinookAIUpdateModuleData::ChinookAIUpdateModuleData() -{ - m_numRopes = 4; - m_ropeWidth = 0.5f; - m_ropeColor.red = 0.9f; - m_ropeColor.green = 0.8f; - m_ropeColor.blue = 0.7f; - m_perRopeDelayMin = 0x7fffffff; - m_perRopeDelayMax = 0x7fffffff; - m_ropeName = "GenericRope"; - m_waitForRopesToDrop = true; - m_minDropHeight = 30.0f; - m_ropeFinalHeight = 0.0f; - m_ropeDropSpeed = 1e10f; // um, fast. - m_rappelSpeed = fabs(TheGlobalData->m_gravity) * LOGICFRAMES_PER_SECOND * 0.5f; - m_ropeWobbleLen = 10.0f; - m_ropeWobbleAmp = 1.0f; - m_ropeWobbleRate = 0.1f; - m_rotorWashParticleSystem.clear(); - m_upgradedSupplyBoost = 0; -} - -//------------------------------------------------------------------------------------------------- -/*static*/ void ChinookAIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) -{ - SupplyTruckAIUpdateModuleData::buildFieldParse(p); - - static const FieldParse dataFieldParse[] = - { - { "RappelSpeed", INI::parseVelocityReal, 0, offsetof(ChinookAIUpdateModuleData, m_rappelSpeed) }, - { "RopeDropSpeed", INI::parseVelocityReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeDropSpeed) }, - { "RopeName", INI::parseAsciiString, 0, offsetof(ChinookAIUpdateModuleData, m_ropeName) }, - { "RopeFinalHeight", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeFinalHeight) }, - { "RopeWidth", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWidth) }, - { "RopeWobbleLen", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWobbleLen) }, - { "RopeWobbleAmplitude", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWobbleAmp) }, - { "RopeWobbleRate", INI::parseAngularVelocityReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWobbleRate) }, - { "RopeColor", INI::parseRGBColor, 0, offsetof(ChinookAIUpdateModuleData, m_ropeColor) }, - { "NumRopes", INI::parseUnsignedInt, 0, offsetof(ChinookAIUpdateModuleData, m_numRopes) }, - { "PerRopeDelayMin", INI::parseDurationUnsignedInt, 0, offsetof(ChinookAIUpdateModuleData, m_perRopeDelayMin) }, - { "PerRopeDelayMax", INI::parseDurationUnsignedInt, 0, offsetof(ChinookAIUpdateModuleData, m_perRopeDelayMax) }, - { "MinDropHeight", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_minDropHeight) }, - { "WaitForRopesToDrop", INI::parseBool, 0, offsetof(ChinookAIUpdateModuleData, m_waitForRopesToDrop) }, - { "RotorWashParticleSystem", INI::parseAsciiString, NULL, offsetof( ChinookAIUpdateModuleData, m_rotorWashParticleSystem ) }, - { "UpgradedSupplyBoost", INI::parseInt, NULL, offsetof( ChinookAIUpdateModuleData, m_upgradedSupplyBoost) }, - - { 0, 0, 0, 0 } - }; - p.add(dataFieldParse); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -AIStateMachine* ChinookAIUpdate::makeStateMachine() -{ - return newInstance(ChinookAIStateMachine)( getObject(), "ChinookAIStateMachine"); -} - -//------------------------------------------------------------------------------------------------- -ChinookAIUpdate::ChinookAIUpdate( Thing *thing, const ModuleData* moduleData ) : SupplyTruckAIUpdate( thing, moduleData ) -{ - m_hasPendingCommand = false; - m_flightStatus = CHINOOK_FLYING; // yep, that's right, even if we start "on ground" - m_airfieldForHealing = INVALID_ID; - m_originalPos.zero(); -} - -//------------------------------------------------------------------------------------------------- -ChinookAIUpdate::~ChinookAIUpdate() -{ - -} - -//------------------------------------------------------------------------------------------------- -static ParkingPlaceBehaviorInterface* getPP(ObjectID id) -{ - Object* airfield = TheGameLogic->findObjectByID( id ); - if (airfield == NULL || airfield->isEffectivelyDead() || !airfield->isKindOf(KINDOF_FS_AIRFIELD)) - return NULL; - - ParkingPlaceBehaviorInterface* pp = NULL; - for (BehaviorModule** i = airfield->getBehaviorModules(); *i; ++i) - { - if ((pp = (*i)->getParkingPlaceBehaviorInterface()) != NULL) - break; - } - - return pp; -} - -//------------------------------------------------------------------------------------------------- -void ChinookAIUpdate::setAirfieldForHealing(ObjectID id) -{ - // make sure we de-register with current one, if any - if (m_airfieldForHealing != INVALID_ID && m_airfieldForHealing != id) - { - ParkingPlaceBehaviorInterface* pp = getPP(m_airfieldForHealing); - if (pp != NULL) - { - pp->setHealee(getObject(), false); - } - } - m_airfieldForHealing = id; -} - -//------------------------------------------------------------------------------------------------- -Bool ChinookAIUpdate::isIdle() const -{ - // we need to do this because we enter an idle state briefly between takeoff/landing in these cases, - // but scripting relies on us never claiming to be "idle"... - if (m_hasPendingCommand) - return false; - - Bool result = SupplyTruckAIUpdate::isIdle(); - - if (result && m_flightStatus == CHINOOK_LANDED) - { - // ditto: if we are waiting to disgorge some folks, we aren't 'idle' - ContainModuleInterface* contain = getObject()->getContain(); - if (contain && contain->hasObjectsWantingToEnterOrExit()) - result = false; - } - - return result; -} - -//------------------------------------------------------------------------------------------------- -Bool ChinookAIUpdate::isCurrentlyFerryingSupplies() const -{ - return SupplyTruckAIUpdate::isCurrentlyFerryingSupplies(); -} - -//------------------------------------------------------------------------------------------------- -Bool ChinookAIUpdate::isAvailableForSupplying() const -{ - if (!SupplyTruckAIUpdate::isAvailableForSupplying()) - return false; - - ContainModuleInterface* contain = getObject()->getContain(); - if( !contain || contain->hasObjectsWantingToEnterOrExit() || contain->getContainCount() || contain->isSpecialOverlordStyleContainer()) - return false; - - return true; -} - -//------------------------------------------------------------------------------------------------- -Bool ChinookAIUpdate::isAllowedToAdjustDestination() const -{ - if (m_flightStatus == CHINOOK_LANDED) - return false; - - if( getCurLocomotor()->isInvalidPositionAllowed() ) - { - return FALSE; - } - - return SupplyTruckAIUpdate::isAllowedToAdjustDestination(); -} - -//------------------------------------------------------------------------------------------------- -ObjectID ChinookAIUpdate::getBuildingToNotPathAround() const -{ - if (getAIStateType() == MOVE_TO_COMBAT_DROP || getAIStateType() == DO_COMBAT_DROP) - { - const Object* goalObj = getStateMachine()->getGoalObject(); - if (goalObj) - return goalObj->getID(); - } - - return INVALID_ID; -} - -//------------------------------------------------------------------------------------------------- -AIFreeToExitType ChinookAIUpdate::getAiFreeToExit(const Object* exiter) const -{ - if (m_flightStatus == CHINOOK_LANDED - || (m_flightStatus == CHINOOK_DOING_COMBAT_DROP && exiter->isKindOf(KINDOF_CAN_RAPPEL))) - return FREE_TO_EXIT; - - return WAIT_TO_EXIT; -} - -//------------------------------------------------------------------------------------------------- -Bool ChinookAIUpdate::chooseLocomotorSet(LocomotorSetType wst) -{ - if (m_flightStatus == CHINOOK_LANDED) - wst = LOCOMOTORSET_TAXIING; - return SupplyTruckAIUpdate::chooseLocomotorSet(wst); -} - -//------------------------------------------------------------------------------------------------- -UpdateSleepTime ChinookAIUpdate::update() -{ - ParkingPlaceBehaviorInterface* pp = getPP(m_airfieldForHealing); - if (pp != NULL) - { - if (m_flightStatus == CHINOOK_LANDED && - !m_hasPendingCommand && - getObject()->getBodyModule()->getHealth() == getObject()->getBodyModule()->getMaxHealth()) - { - // we're completely healed, so take off again - pp->setHealee(getObject(), false); - setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); - } - else - { - pp->setHealee(getObject(), m_flightStatus == CHINOOK_LANDED); - } - } - else - { - setAirfieldForHealing(INVALID_ID); - } - - - - // have to call our parent's isIdle, because we override it to never return true - // when we have a pending command... - ContainModuleInterface* contain = getObject()->getContain(); - if( contain ) - { - if (SupplyTruckAIUpdate::isIdle()) - { - Bool waitingToEnterOrExit = contain->hasObjectsWantingToEnterOrExit(); - if (m_hasPendingCommand) - { - AICommandParms parms(AICMD_MOVE_TO_POSITION, CMD_FROM_AI); // values don't matter, will be wiped by next line - m_pendingCommand.reconstitute(parms); - m_hasPendingCommand = false; - aiDoCommand(&parms); - } - else if (waitingToEnterOrExit && m_flightStatus != CHINOOK_LANDED) - { - setMyState(LANDING, NULL, NULL, CMD_FROM_AI); - } - else if (!waitingToEnterOrExit && m_flightStatus == CHINOOK_LANDED && m_airfieldForHealing == INVALID_ID) - { - setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); - } - } - - - if ( TheGameLogic->getFrame()%10 == 1 ) - { - Object *victim = getCurrentVictim(); - if ( victim ) - { - // privateAttackObject( victim, 9999, CMD_FROM_AI ); - - //If we are attacking something, lets make sure our passengers follow suit - if ( contain->isPassengerAllowedToFire() ) - { - const ContainedItemsList *passengerList = contain->getContainedItemsList(); - ContainedItemsList::const_iterator passengerIterator; - passengerIterator = passengerList->begin(); - - while( passengerIterator != passengerList->end() ) - { - Object *passenger = *passengerIterator; - //Advance to the next iterator - passengerIterator++; - - AIUpdateInterface *passengerAI = passenger->getAIUpdateInterface(); - if( passengerAI && (passengerAI->getCurrentVictim() == NULL) ) - { - passengerAI->aiAttackObject( victim, 999, CMD_FROM_AI ); - } - } - } - - } - } - - - - - } - - - - - // Just a handy spot to handle that groovy client effect of the rotor wash - if ( getObject()->getShroudedStatus( ThePlayerList->getLocalPlayer()->getPlayerIndex()) == OBJECTSHROUD_CLEAR ) - { - if ( m_flightStatus == CHINOOK_LANDING || m_flightStatus == CHINOOK_TAKING_OFF || m_flightStatus == CHINOOK_LANDED ) - { - Coord3D pos = *getObject()->getPosition(); - Real chopperElevation = pos.z; - pos.z = TheTerrainLogic->getGroundHeight( pos.x, pos.y ) + 3.0f; - chopperElevation -= pos.z; - - if ( GameClientRandomValueReal( 0.0f, chopperElevation ) < 5.0f ) - { - const ParticleSystemTemplate *tmp = TheParticleSystemManager->findTemplate( getChinookAIUpdateModuleData()->m_rotorWashParticleSystem ); - ParticleSystem *system; - if( tmp ) - { - system = TheParticleSystemManager->createParticleSystem( tmp ); - if( system ) - { - system->setPosition( &pos ); - } - } - } - - } - } - - - - - return SupplyTruckAIUpdate::update(); -} - -//------------------------------------------------------------------------------------------------- -void ChinookAIUpdate::setMyState( StateID cmd, Object* target, const Coord3D* pos, CommandSourceType cmdSource ) -{ - getStateMachine()->clear(); - getStateMachine()->setGoalObject( target ); - setGoalPositionClipped(pos, cmdSource); // yeah, null is ok here. - setLastCommandSource( cmdSource ); - getStateMachine()->setState( cmd ); -} - -//---------------------------------------------------------------------------------------- -/** - * Get repaired at the repair depot - */ -void ChinookAIUpdate::privateGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) -{ - // we are already landing. just ignore it. - if (m_flightStatus == CHINOOK_LANDING || m_flightStatus == CHINOOK_LANDED) - return; - - // sanity, if we can't get repaired from here get out of here - if( TheActionManager->canGetRepairedAt( getObject(), repairDepot, cmdSource ) == FALSE ) - return; - - setAirfieldForHealing(repairDepot->getID()); - - Coord3D pos = *repairDepot->getPosition(); - Coord3D tmp; - FindPositionOptions options; - options.maxRadius = repairDepot->getGeometryInfo().getBoundingCircleRadius() * 100.0f; - if (ThePartitionManager->findPositionAround(&pos, &options, &tmp)) - pos = tmp; - - setMyState(MOVE_TO_AND_LAND, NULL, &pos, cmdSource); - -} - -//------------------------------------------------------------------------------------------------- -void ChinookAIUpdate::privateCombatDrop( Object* target, const Coord3D& pos, CommandSourceType cmdSource ) -{ - - // - // when there is a target present, we must verify that we can logically do the action when - // we get commands from players (we'll assume AI knows what its doing) - // - if( target != NULL && cmdSource == CMD_FROM_PLAYER && - TheActionManager->canEnterObject( getObject(), target, cmdSource, COMBATDROP_INTO ) == FALSE ) - return; - - Coord3D localPos = pos; - if (target == NULL) - { - // if target is null, we are dropping at a pos, not into a bldg. - // in this case, ensure there is no structure at the pos... this can happen - // if you combat-drop into a spot in the fog-of-war. - Coord3D tmp; - FindPositionOptions options; - options.maxRadius = getObject()->getGeometryInfo().getBoundingCircleRadius() * 100.0f; - if (ThePartitionManager->findPositionAround(&localPos, &options, &tmp)) - { - localPos = tmp; - } - } - - // start the combat drop process - setMyState(MOVE_TO_COMBAT_DROP, target, &localPos, cmdSource); - -} - -//------------------------------------------------------------------------------------------------- -void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms) -{ - // this gets reset every time a command is issued. - setAirfieldForHealing(INVALID_ID); - - if (!isAllowedToRespondToAiCommands(parms)) - return; - - if (m_flightStatus == CHINOOK_TAKING_OFF || - m_flightStatus == CHINOOK_LANDING || - m_flightStatus == CHINOOK_DOING_COMBAT_DROP) - { - // have to wait for takeoff or landing (or rappel) to complete, just store the sucker. - m_pendingCommand.store(*parms); - m_hasPendingCommand = true; - return; - } - - Bool passItThru = true; - switch (parms->m_cmd) - { - case AICMD_IDLE: - case AICMD_BUSY: - case AICMD_FOLLOW_EXITPRODUCTION_PATH: - { - // don't need (or want) to take off for these... - // just pass it thru. - } - break; - - case AICMD_MOVE_TO_POSITION_AND_EVACUATE: - case AICMD_MOVE_TO_POSITION_AND_EVACUATE_AND_EXIT: - { - const Real THRESH = 3.0f; - const Real THRESH_SQR = THRESH*THRESH; - if (calcDistSqr(*getObject()->getPosition(), parms->m_pos) > THRESH_SQR && - m_flightStatus == CHINOOK_LANDED) - { - // gotta take off first! - m_pendingCommand.store(*parms); - m_hasPendingCommand = true; - - setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); - passItThru = false; - } - else - { - // do this INSTEAD of the standard stuff - setMyState( - (parms->m_cmd == AICMD_MOVE_TO_POSITION_AND_EVACUATE) ? MOVE_TO_AND_EVAC : MOVE_TO_AND_EVAC_AND_EXIT_INIT, - NULL, &parms->m_pos, CMD_FROM_AI); - passItThru = false; - } - } - break; - - case AICMD_EXIT: - case AICMD_EVACUATE: - { - if (m_flightStatus != CHINOOK_LANDED) - { - // gotta land first! - m_pendingCommand.store(*parms); - m_hasPendingCommand = true; - - setMyState(LANDING, NULL, NULL, CMD_FROM_AI); - passItThru = false; - } - } - break; - - default: - { - if (m_flightStatus != CHINOOK_FLYING) - { - // gotta take off first! - m_pendingCommand.store(*parms); - m_hasPendingCommand = true; - - setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); - passItThru = false; - } - } - break; - } - - if (passItThru) - { - m_hasPendingCommand = false; - SupplyTruckAIUpdate::aiDoCommand(parms); - } -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void ChinookAIUpdate::crc( Xfer *xfer ) -{ - SupplyTruckAIUpdate::crc(xfer); -} // end crc - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void ChinookAIUpdate::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 2; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - // extend base class - SupplyTruckAIUpdate::xfer(xfer); - - xfer->xferBool(&m_hasPendingCommand); - if (m_hasPendingCommand) { - m_pendingCommand.doXfer(xfer); - } - xfer->xferUser(&m_flightStatus, sizeof(m_flightStatus)); - xfer->xferObjectID(&m_airfieldForHealing); - - if( version >= 2 ) - { - xfer->xferCoord3D( &m_originalPos ); - } - -} // end xfer - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void ChinookAIUpdate::loadPostProcess( void ) -{ - SupplyTruckAIUpdate::loadPostProcess(); -} // end loadPostProcess - - - - - -//---------------------------------------------------------------------------------------- -/** - * Enter idle state. - */ -void ChinookAIUpdate::privateIdle(CommandSourceType cmdSource) -{ - - // Just an extra step, here, before extending idle to parent classes. - // Living in you own privateIdle-ho. - ContainModuleInterface* contain = getObject()->getContain(); - if( contain != NULL ) - { - Object *rider = (Object*)contain->friend_getRider(); - if ( rider ) - { - AIUpdateInterface *riderAI = rider->getAIUpdateInterface(); - if( riderAI ) - riderAI->aiIdle( cmdSource ); - } - } - - SupplyTruckAIUpdate::privateIdle( cmdSource ); - -} - - -//------------------------------------------------------------------------------------------------- -/** - * Attack given object - */ -void ChinookAIUpdate::privateAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) -{ - - if ( ! getObject()->isKindOf( KINDOF_CAN_ATTACK ) ) - return; - - ContainModuleInterface* contain = getObject()->getContain(); - if( contain != NULL ) - { - // As an extension of the normal attack, I may want to tell my passengers to attack - // too, but only if this is a direct command. (As opposed to a passive aquire) - if( (cmdSource == CMD_FROM_PLAYER || cmdSource == CMD_FROM_SCRIPT) ) - { - //if ( contain->isPassengerAllowedToFire() )//moved to below - { - const ContainedItemsList *passengerList = contain->getContainedItemsList(); - ContainedItemsList::const_iterator passengerIterator; - passengerIterator = passengerList->begin(); - - while( passengerIterator != passengerList->end() ) - { - Object *passenger = *passengerIterator; - //Advance to the next iterator - passengerIterator++; - - - if ( ! contain->isPassengerAllowedToFire( passenger->getID() ) ) - continue; - - if ( ! passenger->isKindOf( KINDOF_INFANTRY )) - continue; - - // If I am an overlord with a gattling upgrade, I do not tell it to fire if it is disabled - if ( passenger->isKindOf( KINDOF_PORTABLE_STRUCTURE ) ) - { - if( passenger->isDisabledByType( DISABLED_HACKED ) - || passenger->isDisabledByType( DISABLED_EMP ) - || passenger->isDisabledByType( DISABLED_SUBDUED ) - || passenger->isDisabledByType( DISABLED_PARALYZED) ) - continue; - } - - AIUpdateInterface *passengerAI = passenger->getAIUpdateInterface(); - if( passengerAI ) - { - passengerAI->aiAttackObject( victim, maxShotsToFire, cmdSource ); - } - } - - } - - private___TellPortableStructureToAttackWithMe( victim, maxShotsToFire, cmdSource ); - - } - } - - AIUpdateInterface::privateAttackObject( victim, maxShotsToFire, cmdSource ); -} - - - -void ChinookAIUpdate::private___TellPortableStructureToAttackWithMe( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) -{ - ContainModuleInterface* contain = getObject()->getContain(); - if( contain != NULL ) - { - //--------- THE GATTLING UPGRADE OR THE GUYS IN THE BUNKER_NOT_A_BUNKER------------- - Object *rider = (Object*)contain->friend_getRider(); - if ( rider - && rider->isKindOf( KINDOF_PORTABLE_STRUCTURE ) - && !rider->isDisabledByType( DISABLED_HACKED ) - && !rider->isDisabledByType( DISABLED_EMP ) - && !rider->isDisabledByType( DISABLED_SUBDUED ) - && !rider->isDisabledByType( DISABLED_PARALYZED) ) - { - AIUpdateInterface *riderAI = rider->getAIUpdateInterface(); - if( riderAI ) - { - riderAI->aiAttackObject( victim, maxShotsToFire, cmdSource ); - } - } - } -} - - -//------------------------------------------------------------------------------------------------- -/** - * Attack given object - */ -void ChinookAIUpdate::privateForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) -{ - - if ( ! getObject()->isKindOf( KINDOF_CAN_ATTACK ) ) - return; - - ContainModuleInterface* contain = getObject()->getContain(); - if( contain != NULL ) - { - // As an extension of the normal attack, I may want to tell my passengers to attack - // too, but only if this is a direct command. (As opposed to a passive aquire) - if( (cmdSource == CMD_FROM_PLAYER || cmdSource == CMD_FROM_SCRIPT) ) - { -// if ( contain->isPassengerAllowedToFire() ) - { - const ContainedItemsList *passengerList = contain->getContainedItemsList(); - ContainedItemsList::const_iterator passengerIterator; - passengerIterator = passengerList->begin(); - - while( passengerIterator != passengerList->end() ) - { - Object *passenger = *passengerIterator; - //Advance to the next iterator - passengerIterator++; - - if ( ! contain->isPassengerAllowedToFire( passenger->getID() ) ) - continue; - - if ( ! passenger->isKindOf( KINDOF_INFANTRY )) - continue; - - // If I am an overlord with a gattling upgrade, I do not tell it to fire if it is disabled - if ( passenger->isKindOf( KINDOF_PORTABLE_STRUCTURE ) ) - { - if( passenger->isDisabledByType( DISABLED_HACKED ) - || passenger->isDisabledByType( DISABLED_EMP ) - || passenger->isDisabledByType( DISABLED_SUBDUED ) - || passenger->isDisabledByType( DISABLED_PARALYZED) ) - continue; - } - - AIUpdateInterface *passengerAI = passenger->getAIUpdateInterface(); - if( passengerAI ) - { - passengerAI->aiForceAttackObject( victim, maxShotsToFire, cmdSource ); - } - - } - } - - - //--------- THE GATTLING UPGRADE OR THE GUYS IN THE BUNKER_NOT_A_BUNKER------------- - Object *rider = (Object*)contain->friend_getRider(); - if ( rider - && rider->isKindOf( KINDOF_PORTABLE_STRUCTURE ) - && !rider->isDisabledByType( DISABLED_HACKED ) - && !rider->isDisabledByType( DISABLED_EMP ) - && !rider->isDisabledByType( DISABLED_SUBDUED ) - && !rider->isDisabledByType( DISABLED_PARALYZED) ) - { - AIUpdateInterface *riderAI = rider->getAIUpdateInterface(); - if( riderAI ) - { - riderAI->aiForceAttackObject( victim, maxShotsToFire, cmdSource ); - } - } - - } - } - - AIUpdateInterface::privateForceAttackObject( victim, maxShotsToFire, cmdSource ); -} - -//------------------------------------------------------------------------------------------------- -/** - * Attack given position - */ -void ChinookAIUpdate::privateAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) -{ - - if ( ! getObject()->isKindOf( KINDOF_CAN_ATTACK ) ) - return; - - ContainModuleInterface* contain = getObject()->getContain(); - if( contain != NULL ) - { - // As an extension of the normal attack, I may want to tell my passengers to attack - // too, but only if this is a direct command. (As opposed to a passive aquire) - if( (cmdSource == CMD_FROM_PLAYER || cmdSource == CMD_FROM_SCRIPT) ) - { - - //if ( contain->isPassengerAllowedToFire() ) - { - const ContainedItemsList *passengerList = contain->getContainedItemsList(); - ContainedItemsList::const_iterator passengerIterator; - passengerIterator = passengerList->begin(); - - while( passengerIterator != passengerList->end() ) - { - Object *passenger = *passengerIterator; - //Advance to the next iterator - passengerIterator++; - - if ( ! contain->isPassengerAllowedToFire( passenger->getID() ) ) - continue; - - if ( ! passenger->isKindOf( KINDOF_INFANTRY )) - continue; - - // If I am an overlord with a gattling upgrade, I do not tell it ti fire if it is disabled - if ( passenger->isKindOf( KINDOF_PORTABLE_STRUCTURE ) ) - { - if( passenger->isDisabledByType( DISABLED_HACKED ) - || passenger->isDisabledByType( DISABLED_EMP) - || passenger->isDisabledByType( DISABLED_SUBDUED) - || passenger->isDisabledByType( DISABLED_PARALYZED) ) - continue; - } - - AIUpdateInterface *passengerAI = passenger->getAIUpdateInterface(); - if( passengerAI ) - { - passengerAI->aiAttackPosition( pos, maxShotsToFire, cmdSource ); - } - - } - } - - //--------- THE GATTLING UPGRADE OR THE GUYS IN THE BUNKER_NOT_A_BUNKER------------- - Object *rider = (Object*)contain->friend_getRider(); - if ( rider - && rider->isKindOf( KINDOF_PORTABLE_STRUCTURE ) - && !rider->isDisabledByType( DISABLED_HACKED ) - && !rider->isDisabledByType( DISABLED_EMP ) - && !rider->isDisabledByType( DISABLED_SUBDUED ) - && !rider->isDisabledByType( DISABLED_PARALYZED) ) - { - AIUpdateInterface *riderAI = rider->getAIUpdateInterface(); - if( riderAI ) - { - riderAI->aiAttackPosition( pos, maxShotsToFire, cmdSource ); - } - } - } - } - - AIUpdateInterface::privateAttackPosition( pos, maxShotsToFire, cmdSource ); -} - -//------------------------------------------------------------------------------------------------ -Int ChinookAIUpdate::getUpgradedSupplyBoost() const -{ - Player *player = getObject()->getControllingPlayer(); - static const UpgradeTemplate *supplyLinesTemplate = TheUpgradeCenter->findUpgrade( "Upgrade_AmericaSupplyLines" ); - - if (player && supplyLinesTemplate && player->hasUpgradeComplete(supplyLinesTemplate)) - return getChinookAIUpdateModuleData()->m_upgradedSupplyBoost; - else - return 0; -} +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// ChinookAIUpdate.cpp ////////// + +#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine + +#define DEFINE_VETERANCY_NAMES // for TheVeterancyNames[] + +#include "Common/ActionManager.h" +#include "Common/DrawModule.h" +#include "Common/GameState.h" +#include "Common/GlobalData.h" +#include "Common/RandomValue.h" +#include "Common/Team.h" +#include "Common/ThingFactory.h" +#include "Common/ThingTemplate.h" +#include "Common/Xfer.h" +#include "Common/Player.h" +#include "Common/PlayerList.h" +#include "GameClient/Drawable.h" +#include "GameClient/GameClient.h" +#include "GameClient/ParticleSys.h" +#include "GameLogic/AIPathfind.h" +#include "GameLogic/Locomotor.h" +#include "GameLogic/Module/ContainModule.h" +#include "GameLogic/Module/ChinookAIUpdate.h" +#include "GameLogic/Module/PhysicsUpdate.h" +#include "GameLogic/PartitionManager.h" + +const Real BIGNUM = 99999.0f; + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + +//------------------------------------------------------------------------------------------------- +enum ChinookAIStateType CPP_11(: Int) +{ + // note that these must be distinct (numerically) from AIStateType. ick. + ChinookAIStateType_FIRST = 1000, + + TAKING_OFF, + LANDING, + + MOVE_TO_AND_LAND, + + MOVE_TO_AND_EVAC, + LAND_AND_EVAC, + EVAC_AND_TAKEOFF, + + MOVE_TO_AND_EVAC_AND_EXIT, + LAND_AND_EVAC_AND_EXIT, + EVAC_AND_EXIT, + TAKEOFF_AND_EXIT, + HEAD_OFF_MAP, + + MOVE_TO_COMBAT_DROP, + DO_COMBAT_DROP, + MOVE_TO_AND_EVAC_AND_EXIT_INIT +}; + + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +static Real calcDistSqr(const Coord3D& a, const Coord3D& b) +{ + return sqr(a.x-b.x) + sqr(a.y-b.y) + sqr(a.z-b.z); +} + +//------------------------------------------------------------------------------------------------- +static Object* getPotentialRappeller(Object* obj) +{ + const ContainedItemsList* items = obj->getContain() ? obj->getContain()->getContainedItemsList() : NULL; + if (items) + { + for (ContainedItemsList::const_iterator it = items->begin(); it != items->end(); ++it ) + { + Object* rider = *it; + if (rider->isKindOf(KINDOF_CAN_RAPPEL)) + { + return rider; + } + } + } + return NULL; +} + +//---------------------------------------------------------------------------------------------------------- +class ChinookEvacuateState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookEvacuateState, "ChinookEvacuateState") +protected: + // snapshot interface STUBBED - no member vars to save. jba. + virtual void crc( Xfer *xfer ){}; + virtual void xfer( Xfer *xfer ){}; + virtual void loadPostProcess(){}; +public: + ChinookEvacuateState( StateMachine *machine ) : State( machine, "ChinookEvacuateState" ) { } + + StateReturnType onEnter() + { + Object* obj = getMachineOwner(); + if( obj->getContain() ) + { + obj->getContain()->removeAllContained(FALSE); + } + obj->getTeam()->setActive(); // why? I don't know. + return STATE_SUCCESS; + } + + virtual StateReturnType update() + { + return STATE_SUCCESS; + } +}; +EMPTY_DTOR(ChinookEvacuateState) + +//------------------------------------------------------------------------------------------------- +class ChinookHeadOffMapState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookHeadOffMapState, "ChinookHeadOffMapState") + //I'm outta here +protected: + // snapshot interface STUBBED - no member vars to save. jba. + virtual void crc( Xfer *xfer ){}; + virtual void xfer( Xfer *xfer ){}; + virtual void loadPostProcess(){}; +public: + ChinookHeadOffMapState( StateMachine *machine ) : State( machine, "ChinookHeadOffMapState" ) {} + + StateReturnType onEnter() // Give move order out of town + { + Object *owner = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)owner->getAIUpdateInterface(); + + owner->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_RIDER8 ) ); + ai->aiMoveToPosition( ai->getOriginalPosition(), CMD_FROM_AI ); + ai->getCurLocomotor()->setAllowInvalidPosition(true); + + return STATE_CONTINUE; + } + + StateReturnType update() + { + Object *owner = getMachineOwner(); + + Region3D mapRegion; + TheTerrainLogic->getExtentIncludingBorder( &mapRegion ); + if( !mapRegion.isInRegionNoZ( owner->getPosition() ) ) + { + TheGameLogic->destroyObject(owner); + return STATE_SUCCESS; + } + + return STATE_CONTINUE; + } + + void onExit() + { + Object *owner = getMachineOwner(); + owner->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_RIDER8 ) ); + } +}; +EMPTY_DTOR(ChinookHeadOffMapState) + +//------------------------------------------------------------------------------------------------- +class ChinookTakeoffOrLandingState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookTakeoffOrLandingState, "ChinookTakeoffOrLandingState") +private: + Coord3D m_destLoc; + Bool m_landing; + +protected: + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty + } + + virtual void xfer( Xfer *xfer ) + { + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + xfer->xferCoord3D(&m_destLoc); + xfer->xferBool(&m_landing); + } + + virtual void loadPostProcess() + { + // empty + } + +public: + ChinookTakeoffOrLandingState( StateMachine *machine, Bool landing ) : m_landing(landing), State( machine, "ChinookTakeoffOrLandingState" ) + { + m_destLoc.zero(); + } + + virtual StateReturnType onEnter() + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + + ai->friend_setFlightStatus(m_landing ? CHINOOK_LANDING : CHINOOK_TAKING_OFF); + + if( m_landing ) + { + // A chinook given transport duty loses his supplies. + while( ai->loseOneBox() ); + } + + // kill any drift... + obj->getPhysics()->scrubVelocity2D(0); + + ai->chooseLocomotorSet(LOCOMOTORSET_NORMAL); + Locomotor* loco = ai->getCurLocomotor(); + loco->setUsePreciseZPos(true); + loco->setUltraAccurate(true); + + m_destLoc = *obj->getPosition(); + const Bool onlyHealthyBridges = true; // ignore dead bridges. + PathfindLayerEnum layerAtDest = TheTerrainLogic->getHighestLayerForDestination(&m_destLoc, onlyHealthyBridges); + m_destLoc.z = TheTerrainLogic->getLayerHeight(m_destLoc.x, m_destLoc.y, layerAtDest); + if (m_landing) + { + Coord3D tmp; + FindPositionOptions options; + options.maxRadius = obj->getGeometryInfo().getBoundingCircleRadius() * 100.0f; + if (ThePartitionManager->findPositionAround(&m_destLoc, &options, &tmp)) + { + m_destLoc = tmp; + TheAI->pathfinder()->adjustToLandingDestination(obj, &m_destLoc); + } + // recalc, since it may have changed. note that findPositionAround() will ALWAYS + // return a position on the ground proper, so if our initial search start pos was + // above a bridge, this will put us below the bridge, which would be unfortunate. + // so recheck to be sure. (note that the partitionmgr is 2d-only, so if it sez that + // the position on the ground at that xy is clear, it will be clear for both the + // ground proper and the bridge itself.) also note: don't call objectInteractsWithBridgeLayer(), + // since it assumes that things that aren't close in z shouldn't interact. + tmp = m_destLoc; + tmp.z = obj->getPosition()->z; + layerAtDest = TheTerrainLogic->getHighestLayerForDestination(&tmp, onlyHealthyBridges); + m_destLoc.z = TheTerrainLogic->getLayerHeight(m_destLoc.x, m_destLoc.y, layerAtDest); + obj->setLayer(layerAtDest); + } + else + { + m_destLoc.z += loco->getPreferredHeight(); + obj->setLayer(LAYER_GROUND); + } + + return STATE_CONTINUE; + } + + virtual StateReturnType update() + { + Object* obj = getMachineOwner(); + if (obj->isEffectivelyDead()) + return STATE_FAILURE; + + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + + ai->setLocomotorGoalPositionExplicit(m_destLoc); + + const Real THRESH = 3.0f; + const Real THRESH_SQR = THRESH*THRESH; + if (calcDistSqr(*obj->getPosition(), m_destLoc) <= THRESH_SQR) + return STATE_SUCCESS; + + return STATE_CONTINUE; + } + + virtual void onExit( StateExitType status ) + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + + ai->friend_setFlightStatus(m_landing ? CHINOOK_LANDED : CHINOOK_FLYING); + + // Paranoia checks - sometimes onExit is called when we are + // shutting down, and not all pieces are valid. CurLocomotor + // is definitely null in some cases. jba. + Locomotor* loco = ai->getCurLocomotor(); + if (loco) + { + loco->setUsePreciseZPos(false); + loco->setUltraAccurate(false); + // don't restore lift if dead -- this may fight with JetSlowDeathBehavior! + if (!obj->isEffectivelyDead()) + loco->setMaxLift(BIGNUM); + } + + if (m_landing) + { + ai->chooseLocomotorSet(LOCOMOTORSET_TAXIING); + } + else + { + // when takeoff is complete, always go back to layer-ground, rather than + // some bridge layer. + obj->setLayer(LAYER_GROUND); + } + + + } + +}; +EMPTY_DTOR(ChinookTakeoffOrLandingState) + +//------------------------------------------------------------------------------------------------- +class ChinookCombatDropState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookCombatDropState, "ChinookCombatDropState") + +private: + + struct RopeInfo + { + Drawable* ropeDrawable; + DrawableID ropeID; // used only during save-load process + Matrix3D dropStartMtx; + Real ropeSpeed; + Real ropeLen; + Real ropeLenMax; + UnsignedInt nextDropTime; + std::list rappellerIDs; + }; + std::vector m_ropes; + + void removeDoneRappellers() + { + for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) + { + for (std::list::iterator oit = it->rappellerIDs.begin(); oit != it->rappellerIDs.end(); ) + { + Object* rappeller = TheGameLogic->findObjectByID(*oit); + if (rappeller == NULL || rappeller->isEffectivelyDead() || !rappeller->isAboveTerrain()) + { + oit = it->rappellerIDs.erase(oit); + } + else + { + ++oit; + } + } + } + } + + static void initRopeParms(Drawable* rope, Real length, Real width, const RGBColor& color, Real wobbleLen, Real wobbleAmp, Real wobbleRate) + { + RopeDrawInterface* tdi = NULL; + for (DrawModule** d = rope->getDrawModules(); *d; ++d) + { + if ((tdi = (*d)->getRopeDrawInterface()) != NULL) + { + tdi->initRopeParms(length, width, color, wobbleLen, wobbleAmp, wobbleRate); + } + } + } + + static void setRopeCurLen(Drawable* rope, Real length) + { + RopeDrawInterface* tdi = NULL; + for (DrawModule** d = rope->getDrawModules(); *d; ++d) + { + if ((tdi = (*d)->getRopeDrawInterface()) != NULL) + { + tdi->setRopeCurLen(length); + } + } + } + + static void setRopeSpeed(Drawable* rope, Real curSpeed, Real maxSpeed, Real accel) + { + RopeDrawInterface* tdi = NULL; + for (DrawModule** d = rope->getDrawModules(); *d; ++d) + { + if ((tdi = (*d)->getRopeDrawInterface()) != NULL) + { + tdi->setRopeSpeed(curSpeed, maxSpeed, accel); + } + } + } + +protected: + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty + } + + virtual void xfer( Xfer *xfer ) + { + // version + const XferVersion currentVersion = 2; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + Int numRopes = m_ropes.size(); + xfer->xferInt(&numRopes); + + if (version >= 2) + { + if (xfer->getXferMode() == XFER_LOAD) + { + if (!m_ropes.empty()) + { + DEBUG_CRASH(( "ChinookCombatDropState - ropes should be empty\n" )); + throw SC_INVALID_DATA; + } + m_ropes.resize(numRopes); + } + + for (Int i = 0; i < numRopes; ++i) + { + RopeInfo info; + if (xfer->getXferMode() == XFER_SAVE) + { + info = m_ropes[i]; + // always overwrite this, since it's probably stale + info.ropeID = info.ropeDrawable ? info.ropeDrawable->getID() : INVALID_DRAWABLE_ID; + } + xfer->xferDrawableID(&info.ropeID); + xfer->xferMatrix3D(&info.dropStartMtx); + xfer->xferReal(&info.ropeSpeed); + xfer->xferReal(&info.ropeLen); + xfer->xferReal(&info.ropeLenMax); + xfer->xferUnsignedInt(&info.nextDropTime); + xfer->xferSTLObjectIDList(&info.rappellerIDs); + if (xfer->getXferMode() == XFER_LOAD) + { + info.ropeDrawable = NULL; // filled in via loadPostProcess + m_ropes[i] = info; + } + } + } + } + + virtual void loadPostProcess() + { + for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) + { + it->ropeDrawable = TheGameClient->findDrawableByID(it->ropeID); + // always nuke this, since we're done with it till we save/load again + it->ropeID = INVALID_DRAWABLE_ID; + } + } + +public: + ChinookCombatDropState( StateMachine *machine ): State( machine, "ChinookCombatDropState" ) { } + + // -------------- + virtual StateReturnType onEnter() + { + Object* obj = getMachineOwner(); + Drawable* draw = obj->getDrawable(); + if (draw == NULL) + return STATE_FAILURE; + + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + const ChinookAIUpdateModuleData* d = ai->friend_getData(); + + obj->setDisabled( DISABLED_HELD ); + ai->friend_setFlightStatus(CHINOOK_DOING_COMBAT_DROP); + + // A chinook given combat drop duty also loses his supplies. + while( ai->loseOneBox() ); + + UnsignedInt now = TheGameLogic->getFrame(); + + const ThingTemplate* ropeTmpl = TheThingFactory->findTemplate(d->m_ropeName); + + const Int MAX_BONES = 32; + Coord3D ropePos[MAX_BONES]; + Matrix3D dropMtx[MAX_BONES]; + + Int ropeCount = draw->getPristineBonePositions("RopeStart", 1, ropePos, NULL, MAX_BONES); + Int dropCount = draw->getPristineBonePositions("RopeEnd", 1, NULL, dropMtx, MAX_BONES); + + Int numRopes = d->m_numRopes; + if (numRopes > ropeCount) numRopes = ropeCount; + if (numRopes > dropCount) numRopes = dropCount; + if (numRopes <= 0) + return STATE_FAILURE; + + m_ropes.clear(); + for (Int i = 0; i < numRopes; ++i) + { + RopeInfo info; + + obj->convertBonePosToWorldPos( NULL, &dropMtx[i], NULL, &info.dropStartMtx ); + + info.ropeDrawable = ropeTmpl ? TheThingFactory->newDrawable(ropeTmpl) : NULL; + if (info.ropeDrawable) + { + obj->convertBonePosToWorldPos( &ropePos[i], NULL, &ropePos[i], NULL ); + info.ropeDrawable->setPosition(&ropePos[i]); + info.ropeSpeed = 0.0f; + info.ropeLen = 1.0f; + + const Bool onlyHealthyBridges = true; // ignore dead bridges. + PathfindLayerEnum layerAtDest = TheTerrainLogic->getHighestLayerForDestination(&ropePos[i], onlyHealthyBridges); + + info.ropeLenMax = ropePos[i].z - TheTerrainLogic->getLayerHeight(ropePos[i].x, ropePos[i].y, layerAtDest) - d->m_ropeFinalHeight; + + initRopeParms(info.ropeDrawable, info.ropeLenMax, d->m_ropeWidth, d->m_ropeColor, d->m_ropeWobbleLen, d->m_ropeWobbleAmp, d->m_ropeWobbleRate); + } + + info.nextDropTime = now + GameLogicRandomValue(d->m_perRopeDelayMin, d->m_perRopeDelayMax) - d->m_perRopeDelayMin; + info.rappellerIDs.clear(); + + m_ropes.push_back(info); + } + + return STATE_CONTINUE; + } + + // -------------- + virtual StateReturnType update() + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + const ChinookAIUpdateModuleData* d = ai->friend_getData(); + + if (obj->isEffectivelyDead()) + { + return STATE_FAILURE; + } + + // first, eliminate "done" rappellers + removeDoneRappellers(); + + UnsignedInt now = TheGameLogic->getFrame(); + + // ok, now check each rope: if it's empty, or we're at the next drop time, spawn a new rappeller + Int numRopesInUse = 0; + for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) + { + if (it->ropeLen < it->ropeLenMax) + { + it->ropeSpeed += fabs(TheGlobalData->m_gravity); + if (it->ropeSpeed > d->m_ropeDropSpeed) + it->ropeSpeed = d->m_ropeDropSpeed; + it->ropeLen += it->ropeSpeed; + setRopeCurLen(it->ropeDrawable, it->ropeLen); + if (d->m_waitForRopesToDrop) + { + // can't use this rope till it's dropped all the way + ++it->nextDropTime; + continue; + } + } + + if (now >= it->nextDropTime) + { + Object* rappeller = getPotentialRappeller(obj); + if (rappeller != NULL) + { + ExitInterface *exitInterface = obj->getObjectExitInterface(); + ExitDoorType exitDoor = exitInterface ? exitInterface->reserveDoorForExit(rappeller->getTemplate(), rappeller) : DOOR_NONE_AVAILABLE; + if(exitDoor != DOOR_NONE_AVAILABLE) + { + exitInterface->exitObjectViaDoor(rappeller, exitDoor); + } + else + { + DEBUG_CRASH(("rappeller is not free to exit... what?")); + } + + rappeller->setTransformMatrix(&it->dropStartMtx); + + AIUpdateInterface* rappellerAI = rappeller ? rappeller->getAIUpdateInterface() : NULL; + if (rappellerAI) + { + rappellerAI->setDesiredSpeed(d->m_rappelSpeed); + rappellerAI->aiRappelInto(getMachineGoalObject(), *getMachineGoalPosition(), CMD_FROM_AI); + } + + it->rappellerIDs.push_back(rappeller->getID()); + + it->nextDropTime = now + GameLogicRandomValue(d->m_perRopeDelayMin, d->m_perRopeDelayMax); + } + } + + if (!it->rappellerIDs.empty()) + { + ++numRopesInUse; + } + } + + if (numRopesInUse == 0 && getPotentialRappeller(obj) == NULL) + { + // we're done! + return STATE_SUCCESS; + } + + return STATE_CONTINUE; + } + + // -------------- + virtual void onExit( StateExitType status ) + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + const ChinookAIUpdateModuleData* d = ai->friend_getData(); + + obj->clearDisabled( DISABLED_HELD ); + ai->friend_setFlightStatus(CHINOOK_FLYING); + + if (obj->isEffectivelyDead()) + { + // oops. drop the rangers. + for (std::vector::iterator it = m_ropes.begin(); it != m_ropes.end(); ++it) + { + for (std::list::iterator oit = it->rappellerIDs.begin(); oit != it->rappellerIDs.end(); ++oit) + { + Object* rappeller = TheGameLogic->findObjectByID(*oit); + AIUpdateInterface* rappellerAI = rappeller ? rappeller->getAIUpdateInterface() : NULL; + if (rappellerAI != NULL) + { + rappellerAI->aiIdle(CMD_FROM_AI); + } + } + } + } + + UnsignedInt now = TheGameLogic->getFrame(); + for (Int i = 0; i < m_ropes.size(); ++i) + { + if (m_ropes[i].ropeDrawable) + { + const UnsignedInt ROPE_EXPIRATION_TIME = LOGICFRAMES_PER_SECOND * 5; + const Real initialSpeed = TheGlobalData->m_gravity * 30; // give it a little kick + setRopeSpeed(m_ropes[i].ropeDrawable, initialSpeed, d->m_ropeDropSpeed, TheGlobalData->m_gravity); + m_ropes[i].ropeDrawable->setExpirationDate(now + ROPE_EXPIRATION_TIME); + m_ropes[i].ropeDrawable = NULL; // we're done with it, so null it so we won't save it + } + } + + m_ropes.clear(); + } + +}; +EMPTY_DTOR(ChinookCombatDropState) + +//----------------------------------------------------------------------------------------------------------- +/** + * Move to the GoalPosition, or GoalObject. + */ +class ChinookMoveToBldgState : public AIMoveToState +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookMoveToBldgState, "ChinookMoveToBldgState") +private: + Real m_oldPreferredHeight; + Real m_newPreferredHeight; + Real m_destZ; +protected: + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty + } + + virtual void xfer( Xfer *xfer ) + { + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + xfer->xferReal(&m_oldPreferredHeight); + xfer->xferReal(&m_newPreferredHeight); + xfer->xferReal(&m_destZ); + } + + virtual void loadPostProcess() + { + // empty + } + +public: + ChinookMoveToBldgState( StateMachine *machine ): AIMoveToState( machine ) { } + + virtual StateReturnType onEnter() + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + const ChinookAIUpdateModuleData* d = ai->friend_getData(); + Locomotor* loco = ai->getCurLocomotor(); + loco->setUltraAccurate(true); + m_oldPreferredHeight = loco->getPreferredHeight(); + m_newPreferredHeight = m_oldPreferredHeight; + + const Coord3D* destPos; + Object* bldg = getMachineGoalObject(); + if (bldg != NULL && !bldg->isEffectivelyDead() && bldg->isKindOf(KINDOF_STRUCTURE)) + { + destPos = bldg->getPosition(); + m_newPreferredHeight = bldg->getGeometryInfo().getMaxHeightAbovePosition() + d->m_minDropHeight; + if (m_newPreferredHeight < m_oldPreferredHeight) + m_newPreferredHeight = m_oldPreferredHeight; + } + else + { + destPos = getMachineGoalPosition(); + } + + loco->setPreferredHeight(m_newPreferredHeight); + + m_destZ = TheTerrainLogic->getGroundHeight(destPos->x, destPos->y) + m_newPreferredHeight; + + return AIMoveToState::onEnter(); + } + + virtual StateReturnType update() + { + Object* obj = getMachineOwner(); + + // the normal moveto state will bail when 2d pos matches; we need z, too + StateReturnType status = AIMoveToState::update(); + + const Real THRESH = 3.0f; + if (status != STATE_CONTINUE && fabs(obj->getPosition()->z - m_destZ) > THRESH) + status = STATE_CONTINUE; + + return status; + } + + virtual void onExit( StateExitType status ) + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + Locomotor* loco = ai->getCurLocomotor(); + loco->setPreferredHeight(m_oldPreferredHeight); + loco->setUltraAccurate(false); + AIMoveToState::onExit(status); + } + +}; +EMPTY_DTOR(ChinookMoveToBldgState) + +//----------------------------------------------------------------------------------------------------------- +/** + * Store the original position we are assigned to for exit. + */ +class ChinookRecordCreationState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ChinookRecordCreationState, "ChinookRecordCreationState") +protected: + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty + } + + virtual void xfer( Xfer *xfer ) + { + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + } + + virtual void loadPostProcess() + { + // empty + } + +public: + ChinookRecordCreationState( StateMachine *machine ): State( machine, "ChinookRecordCreationState" ) { } + + virtual StateReturnType onEnter() + { + Object* obj = getMachineOwner(); + ChinookAIUpdate* ai = (ChinookAIUpdate*)obj->getAIUpdateInterface(); + if( ai ) + { + ai->recordOriginalPosition( *obj->getPosition() ); + } + return STATE_SUCCESS; + } + + virtual StateReturnType update() + { + return STATE_SUCCESS; + } + +}; +EMPTY_DTOR(ChinookRecordCreationState) + + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +class ChinookAIStateMachine : public AIStateMachine +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( ChinookAIStateMachine, "ChinookAIStateMachine" ); + +public: + ChinookAIStateMachine( Object *owner, AsciiString name ); + +}; + +//------------------------------------------------------------------------------------------------- +ChinookAIStateMachine::ChinookAIStateMachine(Object *owner, AsciiString name) : AIStateMachine(owner, name) +{ + defineState( TAKING_OFF, newInstance(ChinookTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE ); + defineState( LANDING, newInstance(ChinookTakeoffOrLandingState)( this, true ), AI_IDLE, AI_IDLE ); + defineState( MOVE_TO_COMBAT_DROP, newInstance(ChinookMoveToBldgState)( this ), DO_COMBAT_DROP, AI_IDLE ); + defineState( DO_COMBAT_DROP, newInstance(ChinookCombatDropState)( this ), AI_IDLE, AI_IDLE ); + + defineState( MOVE_TO_AND_LAND, newInstance(AIMoveToState)( this ), LANDING, AI_IDLE ); + + defineState( MOVE_TO_AND_EVAC, newInstance(AIMoveToState)( this ), LAND_AND_EVAC, AI_IDLE ); + defineState( LAND_AND_EVAC, newInstance(ChinookTakeoffOrLandingState)( this, true ), EVAC_AND_TAKEOFF, AI_IDLE ); + defineState( EVAC_AND_TAKEOFF, newInstance(ChinookEvacuateState)( this ), TAKING_OFF, AI_IDLE ); + + defineState( MOVE_TO_AND_EVAC_AND_EXIT_INIT, newInstance(ChinookRecordCreationState)( this ), MOVE_TO_AND_EVAC_AND_EXIT, AI_IDLE ); + defineState( MOVE_TO_AND_EVAC_AND_EXIT, newInstance(AIMoveToState)( this ), LAND_AND_EVAC_AND_EXIT, AI_IDLE ); + defineState( LAND_AND_EVAC_AND_EXIT, newInstance(ChinookTakeoffOrLandingState)( this, true ), EVAC_AND_EXIT, AI_IDLE ); + defineState( EVAC_AND_EXIT, newInstance(ChinookEvacuateState)( this ), TAKEOFF_AND_EXIT, AI_IDLE ); + defineState( TAKEOFF_AND_EXIT, newInstance(ChinookTakeoffOrLandingState)( this, false ), HEAD_OFF_MAP, AI_IDLE ); + defineState( HEAD_OFF_MAP, newInstance(ChinookHeadOffMapState)( this ), AI_IDLE, AI_IDLE ); +} + +//------------------------------------------------------------------------------------------------- +ChinookAIStateMachine::~ChinookAIStateMachine() +{ +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +ChinookAIUpdateModuleData::ChinookAIUpdateModuleData() +{ + m_numRopes = 4; + m_ropeWidth = 0.5f; + m_ropeColor.red = 0.9f; + m_ropeColor.green = 0.8f; + m_ropeColor.blue = 0.7f; + m_perRopeDelayMin = 0x7fffffff; + m_perRopeDelayMax = 0x7fffffff; + m_ropeName = "GenericRope"; + m_waitForRopesToDrop = true; + m_minDropHeight = 30.0f; + m_ropeFinalHeight = 0.0f; + m_ropeDropSpeed = 1e10f; // um, fast. + m_rappelSpeed = fabs(TheGlobalData->m_gravity) * LOGICFRAMES_PER_SECOND * 0.5f; + m_ropeWobbleLen = 10.0f; + m_ropeWobbleAmp = 1.0f; + m_ropeWobbleRate = 0.1f; + m_rotorWashParticleSystem.clear(); + m_upgradedSupplyBoost = 0; +} + +//------------------------------------------------------------------------------------------------- +/*static*/ void ChinookAIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + SupplyTruckAIUpdateModuleData::buildFieldParse(p); + + static const FieldParse dataFieldParse[] = + { + { "RappelSpeed", INI::parseVelocityReal, 0, offsetof(ChinookAIUpdateModuleData, m_rappelSpeed) }, + { "RopeDropSpeed", INI::parseVelocityReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeDropSpeed) }, + { "RopeName", INI::parseAsciiString, 0, offsetof(ChinookAIUpdateModuleData, m_ropeName) }, + { "RopeFinalHeight", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeFinalHeight) }, + { "RopeWidth", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWidth) }, + { "RopeWobbleLen", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWobbleLen) }, + { "RopeWobbleAmplitude", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWobbleAmp) }, + { "RopeWobbleRate", INI::parseAngularVelocityReal, 0, offsetof(ChinookAIUpdateModuleData, m_ropeWobbleRate) }, + { "RopeColor", INI::parseRGBColor, 0, offsetof(ChinookAIUpdateModuleData, m_ropeColor) }, + { "NumRopes", INI::parseUnsignedInt, 0, offsetof(ChinookAIUpdateModuleData, m_numRopes) }, + { "PerRopeDelayMin", INI::parseDurationUnsignedInt, 0, offsetof(ChinookAIUpdateModuleData, m_perRopeDelayMin) }, + { "PerRopeDelayMax", INI::parseDurationUnsignedInt, 0, offsetof(ChinookAIUpdateModuleData, m_perRopeDelayMax) }, + { "MinDropHeight", INI::parseReal, 0, offsetof(ChinookAIUpdateModuleData, m_minDropHeight) }, + { "WaitForRopesToDrop", INI::parseBool, 0, offsetof(ChinookAIUpdateModuleData, m_waitForRopesToDrop) }, + { "RotorWashParticleSystem", INI::parseAsciiString, NULL, offsetof( ChinookAIUpdateModuleData, m_rotorWashParticleSystem ) }, + { "UpgradedSupplyBoost", INI::parseInt, NULL, offsetof( ChinookAIUpdateModuleData, m_upgradedSupplyBoost) }, + + { 0, 0, 0, 0 } + }; + p.add(dataFieldParse); +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +AIStateMachine* ChinookAIUpdate::makeStateMachine() +{ + return newInstance(ChinookAIStateMachine)( getObject(), "ChinookAIStateMachine"); +} + +//------------------------------------------------------------------------------------------------- +ChinookAIUpdate::ChinookAIUpdate( Thing *thing, const ModuleData* moduleData ) : SupplyTruckAIUpdate( thing, moduleData ) +{ + m_hasPendingCommand = false; + m_flightStatus = CHINOOK_FLYING; // yep, that's right, even if we start "on ground" + m_airfieldForHealing = INVALID_ID; + m_originalPos.zero(); +} + +//------------------------------------------------------------------------------------------------- +ChinookAIUpdate::~ChinookAIUpdate() +{ + +} + +//------------------------------------------------------------------------------------------------- +static ParkingPlaceBehaviorInterface* getPP(ObjectID id) +{ + Object* airfield = TheGameLogic->findObjectByID( id ); + if (airfield == NULL || airfield->isEffectivelyDead() || !airfield->isKindOf(KINDOF_FS_AIRFIELD)) + return NULL; + + ParkingPlaceBehaviorInterface* pp = NULL; + for (BehaviorModule** i = airfield->getBehaviorModules(); *i; ++i) + { + if ((pp = (*i)->getParkingPlaceBehaviorInterface()) != NULL) + break; + } + + return pp; +} + +//------------------------------------------------------------------------------------------------- +void ChinookAIUpdate::setAirfieldForHealing(ObjectID id) +{ + // make sure we de-register with current one, if any + if (m_airfieldForHealing != INVALID_ID && m_airfieldForHealing != id) + { + ParkingPlaceBehaviorInterface* pp = getPP(m_airfieldForHealing); + if (pp != NULL) + { + pp->setHealee(getObject(), false); + } + } + m_airfieldForHealing = id; +} + +//------------------------------------------------------------------------------------------------- +Bool ChinookAIUpdate::isIdle() const +{ + // we need to do this because we enter an idle state briefly between takeoff/landing in these cases, + // but scripting relies on us never claiming to be "idle"... + if (m_hasPendingCommand) + return false; + + Bool result = SupplyTruckAIUpdate::isIdle(); + + if (result && m_flightStatus == CHINOOK_LANDED) + { + // ditto: if we are waiting to disgorge some folks, we aren't 'idle' + ContainModuleInterface* contain = getObject()->getContain(); + if (contain && contain->hasObjectsWantingToEnterOrExit()) + result = false; + } + + return result; +} + +//------------------------------------------------------------------------------------------------- +Bool ChinookAIUpdate::isCurrentlyFerryingSupplies() const +{ + return SupplyTruckAIUpdate::isCurrentlyFerryingSupplies(); +} + +//------------------------------------------------------------------------------------------------- +Bool ChinookAIUpdate::isAvailableForSupplying() const +{ + if (!SupplyTruckAIUpdate::isAvailableForSupplying()) + return false; + + ContainModuleInterface* contain = getObject()->getContain(); + if( !contain || contain->hasObjectsWantingToEnterOrExit() || contain->getContainCount() || contain->isSpecialOverlordStyleContainer()) + return false; + + return true; +} + +//------------------------------------------------------------------------------------------------- +Bool ChinookAIUpdate::isAllowedToAdjustDestination() const +{ + if (m_flightStatus == CHINOOK_LANDED) + return false; + + if( getCurLocomotor()->isInvalidPositionAllowed() ) + { + return FALSE; + } + + return SupplyTruckAIUpdate::isAllowedToAdjustDestination(); +} + +//------------------------------------------------------------------------------------------------- +ObjectID ChinookAIUpdate::getBuildingToNotPathAround() const +{ + if (getAIStateType() == MOVE_TO_COMBAT_DROP || getAIStateType() == DO_COMBAT_DROP) + { + const Object* goalObj = getStateMachine()->getGoalObject(); + if (goalObj) + return goalObj->getID(); + } + + return INVALID_ID; +} + +//------------------------------------------------------------------------------------------------- +AIFreeToExitType ChinookAIUpdate::getAiFreeToExit(const Object* exiter) const +{ + if (m_flightStatus == CHINOOK_LANDED + || (m_flightStatus == CHINOOK_DOING_COMBAT_DROP && exiter->isKindOf(KINDOF_CAN_RAPPEL))) + return FREE_TO_EXIT; + + return WAIT_TO_EXIT; +} + +//------------------------------------------------------------------------------------------------- +Bool ChinookAIUpdate::chooseLocomotorSet(LocomotorSetType wst) +{ + if (m_flightStatus == CHINOOK_LANDED) + wst = LOCOMOTORSET_TAXIING; + return SupplyTruckAIUpdate::chooseLocomotorSet(wst); +} + +//------------------------------------------------------------------------------------------------- +UpdateSleepTime ChinookAIUpdate::update() +{ + ParkingPlaceBehaviorInterface* pp = getPP(m_airfieldForHealing); + if (pp != NULL) + { + if (m_flightStatus == CHINOOK_LANDED && + !m_hasPendingCommand && + getObject()->getBodyModule()->getHealth() == getObject()->getBodyModule()->getMaxHealth()) + { + // we're completely healed, so take off again + pp->setHealee(getObject(), false); + setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); + } + else + { + pp->setHealee(getObject(), m_flightStatus == CHINOOK_LANDED); + } + } + else + { + setAirfieldForHealing(INVALID_ID); + } + + + + // have to call our parent's isIdle, because we override it to never return true + // when we have a pending command... + ContainModuleInterface* contain = getObject()->getContain(); + if( contain ) + { + if (SupplyTruckAIUpdate::isIdle()) + { + Bool waitingToEnterOrExit = contain->hasObjectsWantingToEnterOrExit(); + if (m_hasPendingCommand) + { + AICommandParms parms(AICMD_MOVE_TO_POSITION, CMD_FROM_AI); // values don't matter, will be wiped by next line + m_pendingCommand.reconstitute(parms); + m_hasPendingCommand = false; + aiDoCommand(&parms); + } + else if (waitingToEnterOrExit && m_flightStatus != CHINOOK_LANDED) + { + setMyState(LANDING, NULL, NULL, CMD_FROM_AI); + } + else if (!waitingToEnterOrExit && m_flightStatus == CHINOOK_LANDED && m_airfieldForHealing == INVALID_ID) + { + setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); + } + } + + + if ( TheGameLogic->getFrame()%10 == 1 ) + { + Object *victim = getCurrentVictim(); + if ( victim ) + { + // privateAttackObject( victim, 9999, CMD_FROM_AI ); + + //If we are attacking something, lets make sure our passengers follow suit + if ( contain->isPassengerAllowedToFire() ) + { + const ContainedItemsList *passengerList = contain->getContainedItemsList(); + ContainedItemsList::const_iterator passengerIterator; + passengerIterator = passengerList->begin(); + + while( passengerIterator != passengerList->end() ) + { + Object *passenger = *passengerIterator; + //Advance to the next iterator + passengerIterator++; + + AIUpdateInterface *passengerAI = passenger->getAIUpdateInterface(); + if( passengerAI && (passengerAI->getCurrentVictim() == NULL) ) + { + passengerAI->aiAttackObject( victim, 999, CMD_FROM_AI ); + } + } + } + + } + } + + + + + } + + + + + // Just a handy spot to handle that groovy client effect of the rotor wash + if ( getObject()->getShroudedStatus( ThePlayerList->getLocalPlayer()->getPlayerIndex()) == OBJECTSHROUD_CLEAR ) + { + if ( m_flightStatus == CHINOOK_LANDING || m_flightStatus == CHINOOK_TAKING_OFF || m_flightStatus == CHINOOK_LANDED ) + { + Coord3D pos = *getObject()->getPosition(); + Real chopperElevation = pos.z; + pos.z = TheTerrainLogic->getGroundHeight( pos.x, pos.y ) + 3.0f; + chopperElevation -= pos.z; + + if ( GameClientRandomValueReal( 0.0f, chopperElevation ) < 5.0f ) + { + const ParticleSystemTemplate *tmp = TheParticleSystemManager->findTemplate( getChinookAIUpdateModuleData()->m_rotorWashParticleSystem ); + ParticleSystem *system; + if( tmp ) + { + system = TheParticleSystemManager->createParticleSystem( tmp ); + if( system ) + { + system->setPosition( &pos ); + } + } + } + + } + } + + + + + return SupplyTruckAIUpdate::update(); +} + +//------------------------------------------------------------------------------------------------- +void ChinookAIUpdate::setMyState( StateID cmd, Object* target, const Coord3D* pos, CommandSourceType cmdSource ) +{ + getStateMachine()->clear(); + getStateMachine()->setGoalObject( target ); + setGoalPositionClipped(pos, cmdSource); // yeah, null is ok here. + setLastCommandSource( cmdSource ); + getStateMachine()->setState( cmd ); +} + +//---------------------------------------------------------------------------------------- +/** + * Get repaired at the repair depot + */ +void ChinookAIUpdate::privateGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) +{ + // we are already landing. just ignore it. + if (m_flightStatus == CHINOOK_LANDING || m_flightStatus == CHINOOK_LANDED) + return; + + // sanity, if we can't get repaired from here get out of here + if( TheActionManager->canGetRepairedAt( getObject(), repairDepot, cmdSource ) == FALSE ) + return; + + setAirfieldForHealing(repairDepot->getID()); + + Coord3D pos = *repairDepot->getPosition(); + Coord3D tmp; + FindPositionOptions options; + options.maxRadius = repairDepot->getGeometryInfo().getBoundingCircleRadius() * 100.0f; + if (ThePartitionManager->findPositionAround(&pos, &options, &tmp)) + pos = tmp; + + setMyState(MOVE_TO_AND_LAND, NULL, &pos, cmdSource); + +} + +//------------------------------------------------------------------------------------------------- +void ChinookAIUpdate::privateCombatDrop( Object* target, const Coord3D& pos, CommandSourceType cmdSource ) +{ + + // + // when there is a target present, we must verify that we can logically do the action when + // we get commands from players (we'll assume AI knows what its doing) + // + if( target != NULL && cmdSource == CMD_FROM_PLAYER && + TheActionManager->canEnterObject( getObject(), target, cmdSource, COMBATDROP_INTO ) == FALSE ) + return; + + Coord3D localPos = pos; + if (target == NULL) + { + // if target is null, we are dropping at a pos, not into a bldg. + // in this case, ensure there is no structure at the pos... this can happen + // if you combat-drop into a spot in the fog-of-war. + Coord3D tmp; + FindPositionOptions options; + options.maxRadius = getObject()->getGeometryInfo().getBoundingCircleRadius() * 100.0f; + if (ThePartitionManager->findPositionAround(&localPos, &options, &tmp)) + { + localPos = tmp; + } + } + + // start the combat drop process + setMyState(MOVE_TO_COMBAT_DROP, target, &localPos, cmdSource); + +} + +//------------------------------------------------------------------------------------------------- +void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms) +{ + // this gets reset every time a command is issued. + setAirfieldForHealing(INVALID_ID); + + if (!isAllowedToRespondToAiCommands(parms)) + return; + + if (m_flightStatus == CHINOOK_TAKING_OFF || + m_flightStatus == CHINOOK_LANDING || + m_flightStatus == CHINOOK_DOING_COMBAT_DROP) + { + // have to wait for takeoff or landing (or rappel) to complete, just store the sucker. + m_pendingCommand.store(*parms); + m_hasPendingCommand = true; + return; + } + + Bool passItThru = true; + switch (parms->m_cmd) + { + case AICMD_IDLE: + case AICMD_BUSY: + case AICMD_FOLLOW_EXITPRODUCTION_PATH: + { + // don't need (or want) to take off for these... + // just pass it thru. + } + break; + + case AICMD_MOVE_TO_POSITION_AND_EVACUATE: + case AICMD_MOVE_TO_POSITION_AND_EVACUATE_AND_EXIT: + { + const Real THRESH = 3.0f; + const Real THRESH_SQR = THRESH*THRESH; + if (calcDistSqr(*getObject()->getPosition(), parms->m_pos) > THRESH_SQR && + m_flightStatus == CHINOOK_LANDED) + { + // gotta take off first! + m_pendingCommand.store(*parms); + m_hasPendingCommand = true; + + setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); + passItThru = false; + } + else + { + // do this INSTEAD of the standard stuff + setMyState( + (parms->m_cmd == AICMD_MOVE_TO_POSITION_AND_EVACUATE) ? MOVE_TO_AND_EVAC : MOVE_TO_AND_EVAC_AND_EXIT_INIT, + NULL, &parms->m_pos, CMD_FROM_AI); + passItThru = false; + } + } + break; + + case AICMD_EXIT: + case AICMD_EVACUATE: + { + if (m_flightStatus != CHINOOK_LANDED) + { + // gotta land first! + m_pendingCommand.store(*parms); + m_hasPendingCommand = true; + + setMyState(LANDING, NULL, NULL, CMD_FROM_AI); + passItThru = false; + } + } + break; + + default: + { + if (m_flightStatus != CHINOOK_FLYING) + { + // gotta take off first! + m_pendingCommand.store(*parms); + m_hasPendingCommand = true; + + setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI); + passItThru = false; + } + } + break; + } + + if (passItThru) + { + m_hasPendingCommand = false; + SupplyTruckAIUpdate::aiDoCommand(parms); + } +} + +// ------------------------------------------------------------------------------------------------ +/** CRC */ +// ------------------------------------------------------------------------------------------------ +void ChinookAIUpdate::crc( Xfer *xfer ) +{ + SupplyTruckAIUpdate::crc(xfer); +} // end crc + +// ------------------------------------------------------------------------------------------------ +/** Xfer method + * Version Info: + * 1: Initial version */ +// ------------------------------------------------------------------------------------------------ +void ChinookAIUpdate::xfer( Xfer *xfer ) +{ + + // version + XferVersion currentVersion = 2; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + // extend base class + SupplyTruckAIUpdate::xfer(xfer); + + xfer->xferBool(&m_hasPendingCommand); + if (m_hasPendingCommand) { + m_pendingCommand.doXfer(xfer); + } + xfer->xferUser(&m_flightStatus, sizeof(m_flightStatus)); + xfer->xferObjectID(&m_airfieldForHealing); + + if( version >= 2 ) + { + xfer->xferCoord3D( &m_originalPos ); + } + +} // end xfer + +// ------------------------------------------------------------------------------------------------ +/** Load post process */ +// ------------------------------------------------------------------------------------------------ +void ChinookAIUpdate::loadPostProcess( void ) +{ + SupplyTruckAIUpdate::loadPostProcess(); +} // end loadPostProcess + + + + + +//---------------------------------------------------------------------------------------- +/** + * Enter idle state. + */ +void ChinookAIUpdate::privateIdle(CommandSourceType cmdSource) +{ + + // Just an extra step, here, before extending idle to parent classes. + // Living in you own privateIdle-ho. + ContainModuleInterface* contain = getObject()->getContain(); + if (contain != NULL) + { + Object* rider = (Object*)contain->friend_getRider(); + if (rider) + { + AIUpdateInterface* riderAI = rider->getAIUpdateInterface(); + if (riderAI) + riderAI->aiIdle(cmdSource); + } + } + + SupplyTruckAIUpdate::privateIdle( cmdSource ); + +} + + +//------------------------------------------------------------------------------------------------- +/** + * Attack given object + */ +void ChinookAIUpdate::privateAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) +{ + + if (!getObject()->isKindOf(KINDOF_CAN_ATTACK)) + return; + + ContainModuleInterface* contain = getObject()->getContain(); + if (contain != NULL) + { + // As an extension of the normal attack, I may want to tell my passengers to attack + // too, but only if this is a direct command. (As opposed to a passive aquire) + if ((cmdSource == CMD_FROM_PLAYER || cmdSource == CMD_FROM_SCRIPT)) + { + //if ( contain->isPassengerAllowedToFire() )//moved to below + { + const ContainedItemsList* passengerList = contain->getContainedItemsList(); + ContainedItemsList::const_iterator passengerIterator; + passengerIterator = passengerList->begin(); + + while (passengerIterator != passengerList->end()) + { + Object* passenger = *passengerIterator; + //Advance to the next iterator + passengerIterator++; + + + if (!contain->isPassengerAllowedToFire(passenger->getID())) + continue; + + if (!passenger->isKindOf(KINDOF_INFANTRY)) + continue; + + // If I am an overlord with a gattling upgrade, I do not tell it to fire if it is disabled + if (passenger->isKindOf(KINDOF_PORTABLE_STRUCTURE)) + { + if (passenger->isDisabledByType(DISABLED_HACKED) + || passenger->isDisabledByType(DISABLED_EMP) + || passenger->isDisabledByType(DISABLED_SUBDUED) + || passenger->isDisabledByType(DISABLED_PARALYZED)) + continue; + } + + AIUpdateInterface* passengerAI = passenger->getAIUpdateInterface(); + if (passengerAI) + { + passengerAI->aiAttackObject(victim, maxShotsToFire, cmdSource); + } + } + + } + + private___TellPortableStructureToAttackWithMe(victim, maxShotsToFire, cmdSource); + + } + } + + AIUpdateInterface::privateAttackObject( victim, maxShotsToFire, cmdSource ); +} + + + +void ChinookAIUpdate::private___TellPortableStructureToAttackWithMe( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) +{ + ContainModuleInterface* contain = getObject()->getContain(); + if (contain != NULL) + { + //--------- THE GATTLING UPGRADE OR THE GUYS IN THE BUNKER_NOT_A_BUNKER------------- + Object* rider = (Object*)contain->friend_getRider(); + if (rider + && rider->isKindOf(KINDOF_PORTABLE_STRUCTURE) + && !rider->isDisabledByType(DISABLED_HACKED) + && !rider->isDisabledByType(DISABLED_EMP) + && !rider->isDisabledByType(DISABLED_SUBDUED) + && !rider->isDisabledByType(DISABLED_PARALYZED)) + { + AIUpdateInterface* riderAI = rider->getAIUpdateInterface(); + if (riderAI) + { + riderAI->aiAttackObject(victim, maxShotsToFire, cmdSource); + } + } + } +} + + +//------------------------------------------------------------------------------------------------- +/** + * Attack given object + */ +void ChinookAIUpdate::privateForceAttackObject( Object *victim, Int maxShotsToFire, CommandSourceType cmdSource ) +{ + + if (!getObject()->isKindOf(KINDOF_CAN_ATTACK)) + return; + + ContainModuleInterface* contain = getObject()->getContain(); + if (contain != NULL) + { + // As an extension of the normal attack, I may want to tell my passengers to attack + // too, but only if this is a direct command. (As opposed to a passive aquire) + if ((cmdSource == CMD_FROM_PLAYER || cmdSource == CMD_FROM_SCRIPT)) + { + // if ( contain->isPassengerAllowedToFire() ) + { + const ContainedItemsList* passengerList = contain->getContainedItemsList(); + ContainedItemsList::const_iterator passengerIterator; + passengerIterator = passengerList->begin(); + + while (passengerIterator != passengerList->end()) + { + Object* passenger = *passengerIterator; + //Advance to the next iterator + passengerIterator++; + + if (!contain->isPassengerAllowedToFire(passenger->getID())) + continue; + + if (!passenger->isKindOf(KINDOF_INFANTRY)) + continue; + + // If I am an overlord with a gattling upgrade, I do not tell it to fire if it is disabled + if (passenger->isKindOf(KINDOF_PORTABLE_STRUCTURE)) + { + if (passenger->isDisabledByType(DISABLED_HACKED) + || passenger->isDisabledByType(DISABLED_EMP) + || passenger->isDisabledByType(DISABLED_SUBDUED) + || passenger->isDisabledByType(DISABLED_PARALYZED)) + continue; + } + + AIUpdateInterface* passengerAI = passenger->getAIUpdateInterface(); + if (passengerAI) + { + passengerAI->aiForceAttackObject(victim, maxShotsToFire, cmdSource); + } + + } + } + + + //--------- THE GATTLING UPGRADE OR THE GUYS IN THE BUNKER_NOT_A_BUNKER------------- + Object* rider = (Object*)contain->friend_getRider(); + if (rider + && rider->isKindOf(KINDOF_PORTABLE_STRUCTURE) + && !rider->isDisabledByType(DISABLED_HACKED) + && !rider->isDisabledByType(DISABLED_EMP) + && !rider->isDisabledByType(DISABLED_SUBDUED) + && !rider->isDisabledByType(DISABLED_PARALYZED)) + { + AIUpdateInterface* riderAI = rider->getAIUpdateInterface(); + if (riderAI) + { + riderAI->aiForceAttackObject(victim, maxShotsToFire, cmdSource); + } + } + + } + } + + AIUpdateInterface::privateForceAttackObject(victim, maxShotsToFire, cmdSource); +} + +//------------------------------------------------------------------------------------------------- +/** + * Attack given position + */ +void ChinookAIUpdate::privateAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource ) +{ + + if (!getObject()->isKindOf(KINDOF_CAN_ATTACK)) + return; + + ContainModuleInterface* contain = getObject()->getContain(); + if (contain != NULL) + { + // As an extension of the normal attack, I may want to tell my passengers to attack + // too, but only if this is a direct command. (As opposed to a passive aquire) + if ((cmdSource == CMD_FROM_PLAYER || cmdSource == CMD_FROM_SCRIPT)) + { + + //if ( contain->isPassengerAllowedToFire() ) + { + const ContainedItemsList* passengerList = contain->getContainedItemsList(); + ContainedItemsList::const_iterator passengerIterator; + passengerIterator = passengerList->begin(); + + while (passengerIterator != passengerList->end()) + { + Object* passenger = *passengerIterator; + //Advance to the next iterator + passengerIterator++; + + if (!contain->isPassengerAllowedToFire(passenger->getID())) + continue; + + if (!passenger->isKindOf(KINDOF_INFANTRY)) + continue; + + // If I am an overlord with a gattling upgrade, I do not tell it ti fire if it is disabled + if (passenger->isKindOf(KINDOF_PORTABLE_STRUCTURE)) + { + if (passenger->isDisabledByType(DISABLED_HACKED) + || passenger->isDisabledByType(DISABLED_EMP) + || passenger->isDisabledByType(DISABLED_SUBDUED) + || passenger->isDisabledByType(DISABLED_PARALYZED)) + continue; + } + + AIUpdateInterface* passengerAI = passenger->getAIUpdateInterface(); + if (passengerAI) + { + passengerAI->aiAttackPosition(pos, maxShotsToFire, cmdSource); + } + + } + } + + //--------- THE GATTLING UPGRADE OR THE GUYS IN THE BUNKER_NOT_A_BUNKER------------- + Object* rider = (Object*)contain->friend_getRider(); + if (rider + && rider->isKindOf(KINDOF_PORTABLE_STRUCTURE) + && !rider->isDisabledByType(DISABLED_HACKED) + && !rider->isDisabledByType(DISABLED_EMP) + && !rider->isDisabledByType(DISABLED_SUBDUED) + && !rider->isDisabledByType(DISABLED_PARALYZED)) + { + AIUpdateInterface* riderAI = rider->getAIUpdateInterface(); + if (riderAI) + { + riderAI->aiAttackPosition(pos, maxShotsToFire, cmdSource); + } + } + } + } + + AIUpdateInterface::privateAttackPosition(pos, maxShotsToFire, cmdSource); +} + +//------------------------------------------------------------------------------------------------ +Int ChinookAIUpdate::getUpgradedSupplyBoost() const +{ + Player *player = getObject()->getControllingPlayer(); + static const UpgradeTemplate *supplyLinesTemplate = TheUpgradeCenter->findUpgrade( "Upgrade_AmericaSupplyLines" ); + + if (player && supplyLinesTemplate && player->hasUpgradeComplete(supplyLinesTemplate)) + return getChinookAIUpdateModuleData()->m_upgradedSupplyBoost; + else + return 0; +} diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp index c1ff533cce..cda98a568b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeliverPayloadAIUpdate.cpp @@ -50,7 +50,7 @@ #include "GameLogic/Weapon.h" #include "GameLogic/WeaponSet.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -305,7 +305,7 @@ void DeliverPayloadAIUpdate::deliverPayload( // must make the state machine AFTER initing the other stuff, since it may inquire of its values... m_deliverPayloadStateMachine = newInstance(DeliverPayloadStateMachine)( getObject() ); m_deliverPayloadStateMachine->initDefaultState(); -#ifdef _DEBUG +#ifdef RTS_DEBUG m_deliverPayloadStateMachine->setName("DeliverPayloadSpecificAI"); #endif } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp index 854656f9a0..3fff2db660 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DeployStyleAIUpdate.cpp @@ -46,7 +46,7 @@ #include "GameLogic/Module/DeployStyleAIUpdate.h" #include "GameLogic/Module/PhysicsUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp index 73a26555e5..75b9646dd0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp @@ -55,7 +55,7 @@ #include "GameLogic/Module/DozerAIUpdate.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp index f98c482922..6b3bed3c47 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/HackInternetAIUpdate.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Object.h" //#include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -164,7 +164,7 @@ void HackInternetAIUpdate::hackInternet() // must make the state machine AFTER initing the other stuff, since it may inquire of its values... //m_hackInternetStateMachine = newInstance(HackInternetStateMachine)( getObject() ); //m_hackInternetStateMachine->initDefaultState(); -#ifdef _DEBUG +#ifdef RTS_DEBUG //m_hackInternetStateMachine->setName("HackInternetSpecificAI"); #endif getStateMachine()->setState(UNPACKING); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp index cddafdbb49..e84bbe419f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp @@ -1,2629 +1,2655 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// JetAIUpdate.cpp ////////// - -#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine - -#define DEFINE_LOCOMOTORSET_NAMES - -#include "Common/ActionManager.h" -#include "Common/GlobalData.h" -#include "Common/MiscAudio.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "GameClient/Drawable.h" -#include "GameClient/GameClient.h" -#include "GameLogic/ExperienceTracker.h" -#include "GameLogic/Locomotor.h" -#include "GameLogic/Module/BodyModule.h" -#include "GameLogic/Module/CountermeasuresBehavior.h" -#include "GameLogic/Module/JetAIUpdate.h" -#include "GameLogic/Module/ParkingPlaceBehavior.h" -#include "GameLogic/Module/PhysicsUpdate.h" -#include "GameLogic/Object.h" -#include "GameLogic/AIPathfind.h" -#include "GameLogic/PartitionManager.h" -#include "GameLogic/Weapon.h" - -const Real BIGNUM = 99999.0f; - -#ifdef _INTERNAL -// for occasional debugging... -//#pragma optimize("", off) -//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") -#endif - -//------------------------------------------------------------------------------------------------- -enum TaxiType CPP_11(: Int) -{ - FROM_HANGAR, - FROM_PARKING, - TO_PARKING -}; - -//------------------------------------------------------------------------------------------------- -enum JetAIStateType CPP_11(: Int) -{ - // note that these must be distinct (numerically) from AIStateType. ick. - JETAISTATETYPE_FIRST = 1000, - - TAXI_FROM_HANGAR, - TAKING_OFF_AWAIT_CLEARANCE, - TAXI_TO_TAKEOFF, - PAUSE_BEFORE_TAKEOFF, - TAKING_OFF, - LANDING_AWAIT_CLEARANCE, - LANDING, - TAXI_FROM_LANDING, - ORIENT_FOR_PARKING_PLACE, - RELOAD_AMMO, - RETURNING_FOR_LANDING, - RETURN_TO_DEAD_AIRFIELD, - CIRCLING_DEAD_AIRFIELD, - - JETAISTATETYPE_LAST -}; - - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::getFlag( FlagType f ) const -{ - return (m_flags & (1<getWeaponInWeaponSlot((WeaponSlotType)i); - if (weapon == NULL || weapon->getReloadType() != RETURN_TO_BASE_TO_RELOAD) - continue; - ++specials; - if (weapon->getStatus() == OUT_OF_AMMO) - ++out; - } - return specials > 0 && out == specials; -} - -//------------------------------------------------------------------------------------------------- -static ParkingPlaceBehaviorInterface* getPP(ObjectID id, Object** airfieldPP = NULL) -{ - if (airfieldPP) - *airfieldPP = NULL; - - Object* airfield = TheGameLogic->findObjectByID( id ); - if (airfield == NULL || airfield->isEffectivelyDead() || !airfield->isKindOf(KINDOF_FS_AIRFIELD) || airfield->testStatus(OBJECT_STATUS_SOLD)) - return NULL; - - if (airfieldPP) - *airfieldPP = airfield; - - ParkingPlaceBehaviorInterface* pp = NULL; - for (BehaviorModule** i = airfield->getBehaviorModules(); *i; ++i) - { - if ((pp = (*i)->getParkingPlaceBehaviorInterface()) != NULL) - break; - } - - return pp; -} - -//------------------------------------------------------------------------------------------------- -class PartitionFilterHasParkingPlace : public PartitionFilter -{ -private: - ObjectID m_id; -public: - PartitionFilterHasParkingPlace(ObjectID id) : m_id(id) { } -protected: -#if defined(_DEBUG) || defined(_INTERNAL) - virtual const char* debugGetName() { return "PartitionFilterHasParkingPlace"; } -#endif - virtual Bool allow(Object *objOther) - { - ParkingPlaceBehaviorInterface* pp = getPP(objOther->getID()); - if (pp != NULL && pp->reserveSpace(m_id, 0.0f, NULL)) - return true; - return false; - } -}; - -//------------------------------------------------------------------------------------------------- -static Object* findSuitableAirfield(Object* jet) -{ - PartitionFilterAcceptByKindOf filterKind(MAKE_KINDOF_MASK(KINDOF_FS_AIRFIELD), KINDOFMASK_NONE); - PartitionFilterRejectByObjectStatus filterStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_UNDER_CONSTRUCTION ), OBJECT_STATUS_MASK_NONE ); - PartitionFilterRejectByObjectStatus filterStatusTwo( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_SOLD ), OBJECT_STATUS_MASK_NONE ); // Independent to make it an OR - PartitionFilterRelationship filterTeam(jet, PartitionFilterRelationship::ALLOW_ALLIES); - PartitionFilterAlive filterAlive; - PartitionFilterSameMapStatus filterMapStatus(jet); - PartitionFilterHasParkingPlace filterPP(jet->getID()); - - PartitionFilter *filters[16]; - Int numFilters = 0; - filters[numFilters++] = &filterKind; - filters[numFilters++] = &filterStatus; - filters[numFilters++] = &filterStatusTwo; - filters[numFilters++] = &filterTeam; - filters[numFilters++] = &filterAlive; - filters[numFilters++] = &filterPP; - filters[numFilters++] = &filterMapStatus; - filters[numFilters] = NULL; - - return ThePartitionManager->getClosestObject( jet, HUGE_DIST, FROM_CENTER_2D, filters ); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -/* - Success: we have runway clearance - Failure: no runway clearance -*/ -class JetAwaitingRunwayState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetAwaitingRunwayState, "JetAwaitingRunwayState") -protected: - // snapshot interface STUBBED. - virtual void crc( Xfer *xfer ){}; - virtual void xfer( Xfer *xfer ){XferVersion cv = 1; XferVersion v = cv; xfer->xferVersion( &v, cv );} - virtual void loadPostProcess(){}; -private: - const Bool m_landing; - -public: - JetAwaitingRunwayState( StateMachine *machine, Bool landing ) : m_landing(landing), State( machine, "JetAwaitingRunwayState") { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - jetAI->friend_setTakeoffInProgress(!m_landing); - jetAI->friend_setLandingInProgress(m_landing); - jetAI->friend_setAllowCircling(true); - return STATE_CONTINUE; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp == NULL) - { - // no producer? just skip this step. - return STATE_SUCCESS; - } - - // gotta reserve a space in order to reserve a runway - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), NULL)) - { - DEBUG_ASSERTCRASH(m_landing, ("hmm, this should never happen for taking-off things")); - return STATE_FAILURE; - } - - if (pp->reserveRunway(jet->getID(), m_landing)) - { - return STATE_SUCCESS; - } - else if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) && !m_landing ) - { - //If we're trying to take off an aircraft carrier and fail to reserve a - //runway, it's because we need to be at the front of the carrier queue. - //Therefore, we need to move forward whenever possible until we are in - //the front. - Coord3D bestPos; - if( pp->calcBestParkingAssignment( jet->getID(), &bestPos ) ) - { - jetAI->friend_setTaxiInProgress(true); - jetAI->friend_setAllowAirLoco(false); - jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING); - - jetAI->destroyPath(); - Path *movePath; - movePath = newInstance(Path); - Coord3D pos = *jet->getPosition(); - movePath->prependNode( &pos, LAYER_GROUND ); - movePath->markOptimized(); - movePath->appendNode( &bestPos, LAYER_GROUND ); - - TheAI->pathfinder()->setDebugPath(movePath); - - jetAI->friend_setPath( movePath ); - DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco")); - jetAI->getCurLocomotor()->setUsePreciseZPos(true); - jetAI->getCurLocomotor()->setUltraAccurate(true); - jetAI->getCurLocomotor()->setAllowInvalidPosition(true); - jetAI->ignoreObstacleID(jet->getProducerID()); - } - } - - // can't get a runway? gotta wait. - jetAI->setLocomotorGoalNone(); - return STATE_CONTINUE; - } - - virtual void onExit(StateExitType status) - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if (jetAI) - { - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - jetAI->friend_setAllowCircling(false); - } - } - -}; -EMPTY_DTOR(JetAwaitingRunwayState) - -//------------------------------------------------------------------------------------------------- -/* - Success: a new suitable airfield has appeared - Failure: shouldn't normally happen -*/ -class JetOrHeliCirclingDeadAirfieldState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliCirclingDeadAirfieldState, "JetOrHeliCirclingDeadAirfieldState") -protected: - // snapshot interface STUBBED. - // The state will check immediately after a load game, but I think that's ok. jba. - virtual void crc( Xfer *xfer ){}; - virtual void xfer( Xfer *xfer ){XferVersion cv = 1; XferVersion v = cv; xfer->xferVersion( &v, cv );} - virtual void loadPostProcess(){}; - -private: - Int m_checkAirfield; - - enum - { - // only recheck for new airfields every second or so - HOW_OFTEN_TO_CHECK = LOGICFRAMES_PER_SECOND - }; - -public: - JetOrHeliCirclingDeadAirfieldState( StateMachine *machine ) : - State( machine, "JetOrHeliCirclingDeadAirfieldState"), - m_checkAirfield(0) { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - { - return STATE_FAILURE; - } - - // obscure case: if the jet wasn't spawned, but just placed directly on the map, - // it might not have an owning airfield, and it might be trying to return - // simply due to being idle, not out of ammo. so check and don't die in that - // case, but just punt back out to idle. - if (!jetAI->isOutOfSpecialReloadAmmo() && jet->getProducerID() == INVALID_ID) - { - return STATE_FAILURE; - } - - // just stay where we are. - jetAI->setLocomotorGoalNone(); - - m_checkAirfield = HOW_OFTEN_TO_CHECK; - - //Play the "low fuel" voice whenever the craft is circling above the airfield. - AudioEventRTS soundToPlay = *jet->getTemplate()->getPerUnitSound( "VoiceLowFuel" ); - soundToPlay.setObjectID( jet->getID() ); - TheAudio->addAudioEvent( &soundToPlay ); - - return STATE_CONTINUE; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - { - return STATE_FAILURE; - } - - // just stay where we are. - jetAI->setLocomotorGoalNone(); - - Real damageRate = jetAI->friend_getOutOfAmmoDamagePerSecond(); - if (damageRate > 0) - { - // convert to damage/sec to damage/frame - damageRate *= SECONDS_PER_LOGICFRAME_REAL; - // since it's a percentage, multiply times the max health - damageRate *= jet->getBodyModule()->getMaxHealth(); - - DamageInfo damageInfo; - damageInfo.in.m_damageType = DAMAGE_UNRESISTABLE; - damageInfo.in.m_deathType = DEATH_NORMAL; - damageInfo.in.m_sourceID = INVALID_ID; - damageInfo.in.m_amount = damageRate; - jet->attemptDamage( &damageInfo ); - } - - if (--m_checkAirfield <= 0) - { - m_checkAirfield = HOW_OFTEN_TO_CHECK; - Object* airfield = findSuitableAirfield( jet ); - if (airfield) - { - jet->setProducer(airfield); - return STATE_SUCCESS; - } - } - - return STATE_CONTINUE; - } - -}; -EMPTY_DTOR(JetOrHeliCirclingDeadAirfieldState) - -//------------------------------------------------------------------------------------------------- -/* - Success: we returned to the dead-airfield location - Failure: shouldn't normally happen -*/ -class JetOrHeliReturningToDeadAirfieldState : public AIInternalMoveToState -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliReturningToDeadAirfieldState, "JetOrHeliReturningToDeadAirfieldState") -public: - JetOrHeliReturningToDeadAirfieldState( StateMachine *machine ) : AIInternalMoveToState( machine, "JetOrHeliReturningToDeadAirfieldState") { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - { - return STATE_FAILURE; - } - - setAdjustsDestination(true); - m_goalPosition = *jetAI->friend_getProducerLocation(); - - return AIInternalMoveToState::onEnter(); - } - -}; -EMPTY_DTOR(JetOrHeliReturningToDeadAirfieldState) - -//------------------------------------------------------------------------------------------------- -// This solution uses the -// http://www.faqs.org/faqs/graphics/algorithms-faq/ -// Subject 1.03 -static Bool intersectInfiniteLine2D -( - Real ax, Real ay, Real ao, - Real cx, Real cy, Real co, - Real& ix, Real& iy -) -{ - Real bx = ax + Cos(ao); - Real by = ay + Sin(ao); - Real dx = cx + Cos(co); - Real dy = cy + Sin(co); - - Real denom = ((bx - ax) * (dy - cy) - (by - ay) * (dx - cx)); - if (denom == 0.0f) - { - // the lines are parallel. - return false; - } - - // The lines intersect. - Real r = ((ay - cy) * (dx - cx) - (ax - cx) * (dy - cy) ) / denom; - ix = ax + r * (bx - ax); - iy = ay + r * (by - ay); - return true; -} - -//------------------------------------------------------------------------------------------------- -/* - Success: we are on the ground at the runway start - Failure: we are unable to get on the ground -*/ -class JetOrHeliTaxiState : public AIMoveOutOfTheWayState -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliTaxiState, "JetOrHeliTaxiState") -private: - TaxiType m_taxiMode; -public: - JetOrHeliTaxiState( StateMachine *machine, TaxiType m ) : m_taxiMode(m), AIMoveOutOfTheWayState( machine ) { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - jetAI->setCanPathThroughUnits(true); - jetAI->friend_setTakeoffInProgress(m_taxiMode != TO_PARKING); - jetAI->friend_setLandingInProgress(m_taxiMode == TO_PARKING); - jetAI->friend_setTaxiInProgress(true); - - if( m_taxiMode == TO_PARKING ) - { - //Instantly reload flares. - CountermeasuresBehaviorInterface *cbi = jet->getCountermeasuresBehaviorInterface(); - if( cbi ) - { - cbi->reloadCountermeasures(); - } - } - - jetAI->friend_setAllowAirLoco(false); - jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING); - DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco")); - - Object* airfield; - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID(), &airfield); - if (pp == NULL) - return STATE_SUCCESS; // no airfield? just skip this step. - - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) - return STATE_FAILURE; // full? - - Coord3D intermedPt; - Bool intermed = false; - Real orient = atan2(ppinfo.runwayPrep.y - ppinfo.parkingSpace.y, ppinfo.runwayPrep.x - ppinfo.parkingSpace.x); - if (fabs(stdAngleDiff(orient, ppinfo.parkingOrientation)) > PI/128) - { - intermedPt.z = (ppinfo.parkingSpace.z + ppinfo.runwayPrep.z) * 0.5f; - intermed = intersectInfiniteLine2D( - ppinfo.parkingSpace.x, ppinfo.parkingSpace.y, ppinfo.parkingOrientation, - ppinfo.runwayPrep.x, ppinfo.runwayPrep.y, ppinfo.parkingOrientation + PI/2, - intermedPt.x, intermedPt.y); - } - - jetAI->destroyPath(); - Path *movePath; - movePath = newInstance(Path); - Coord3D pos = *jet->getPosition(); - movePath->prependNode( &pos, LAYER_GROUND ); - movePath->markOptimized(); - - if (m_taxiMode == TO_PARKING) - { - if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) - { - //We're on an aircraft carrier. - const std::vector *pTaxiLocations = pp->getTaxiLocations( jet->getID() ); - if( pTaxiLocations ) - { - std::vector::const_iterator it; - for( it = pTaxiLocations->begin(); it != pTaxiLocations->end(); it++ ) - { - movePath->appendNode( &(*it), LAYER_GROUND ); - } - } - - //We just landed... see if we can get a better space forward so we don't stop and pause - //at our initially assigned spot. - Coord3D pos; - pp->calcBestParkingAssignment( jet->getID(), &pos ); - - movePath->appendNode( &pos, LAYER_GROUND ); - } - else - { - //We're on a normal airfield - movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); - if (intermed) - movePath->appendNode( &intermedPt, LAYER_GROUND ); - movePath->appendNode( &ppinfo.parkingSpace, LAYER_GROUND ); - } - } - else if (m_taxiMode == FROM_PARKING) - { - if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) - { - if( !(ppinfo.runwayStart == ppinfo.runwayPrep) ) - { - movePath->appendNode( &ppinfo.runwayStart, LAYER_GROUND ); - } - } - else - { - if (intermed) - movePath->appendNode( &intermedPt, LAYER_GROUND ); - movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); - movePath->appendNode( &ppinfo.runwayStart, LAYER_GROUND ); - } - } - else if (m_taxiMode == FROM_HANGAR) - { - if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) - { - //Aircraft carrier - if( jet->testStatus( OBJECT_STATUS_REASSIGN_PARKING ) ) - { - //This status means we are being reassigned a parking space. We're not actually moving from the - //hangar. So simply move to the new parking spot which was just switched from under us in - //FlightDeckBehavior::update() - jet->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_REASSIGN_PARKING ) ); - movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); - } - else - { - const std::vector *pCreationLocations = pp->getCreationLocations( jet->getID() ); - if( !pCreationLocations ) - { - DEBUG_CRASH( ("No creation locations specified for runway for JetAIBehavior -- taxiing from hanger (Kris).") ); - return STATE_FAILURE; - } - std::vector::const_iterator it; - Bool firstNode = TRUE; - for( it = pCreationLocations->begin(); it != pCreationLocations->end(); it++ ) - { - if( firstNode ) - { - //Skip the first node because it's the creation location. - firstNode = FALSE; - continue; - } - movePath->appendNode( &(*it), LAYER_GROUND ); - } - movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); - } - } - else - { - //Airfield - movePath->appendNode( &ppinfo.parkingSpace, LAYER_GROUND ); - } - } - - m_waitingForPath = FALSE; - TheAI->pathfinder()->setDebugPath(movePath); - - setAdjustsDestination(false); // precision is necessary - - jetAI->friend_setPath( movePath ); - DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco")); - jetAI->getCurLocomotor()->setUsePreciseZPos(true); - jetAI->getCurLocomotor()->setUltraAccurate(true); - jetAI->getCurLocomotor()->setAllowInvalidPosition(true); - jetAI->ignoreObstacleID(jet->getProducerID()); - - StateReturnType ret = AIMoveOutOfTheWayState::onEnter(); - return ret; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - if( m_taxiMode == TO_PARKING || m_taxiMode == FROM_HANGAR ) - { - //Keep checking to see if there is a better spot as it moves forward. If we find a better spot, then - //append the position to our move. - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - Coord3D bestPos; - Int oldIndex, newIndex; - // Check pp for null, as it is possible for your airfield to get destroyed while taxiing.jba [8/27/2003] - if( pp!=NULL && pp->calcBestParkingAssignment( jet->getID(), &bestPos, &oldIndex, &newIndex ) ) - { - Path *path = jetAI->friend_getPath(); - if( path ) - { - path->appendNode( &bestPos, LAYER_GROUND ); - } - } - } - - return AIMoveOutOfTheWayState::update(); - } - - virtual void onExit( StateExitType status ) - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if (jetAI) - { - jetAI->getCurLocomotor()->setUsePreciseZPos(false); - jetAI->getCurLocomotor()->setUltraAccurate(false); - jetAI->getCurLocomotor()->setAllowInvalidPosition(false); - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - jetAI->friend_setTaxiInProgress(false); - jetAI->setCanPathThroughUnits(false); - } - - AIMoveOutOfTheWayState::onExit(status); - } - -}; -EMPTY_DTOR(JetOrHeliTaxiState) - -//------------------------------------------------------------------------------------------------- -/* - Success: we are on the ground at the runway start - Failure: we are unable to get on the ground -*/ -class JetTakeoffOrLandingState : public AIFollowPathState -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetTakeoffOrLandingState, "JetTakeoffOrLandingState") -private: - Real m_maxLift; - Real m_maxSpeed; -#ifdef CIRCLE_FOR_LANDING - Coord3D m_circleForLandingPos; -#endif - Bool m_landing; - Bool m_landingSoundPlayed; - -public: - JetTakeoffOrLandingState( StateMachine *machine, Bool landing ) : m_landing(landing), AIFollowPathState( machine, "JetTakeoffOrLandingState" ) { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if (!jetAI) - return STATE_FAILURE; - - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - jetAI->friend_setTakeoffInProgress(!m_landing); - jetAI->friend_setLandingInProgress(m_landing); - jetAI->friend_setAllowAirLoco(true); - jetAI->chooseLocomotorSet(LOCOMOTORSET_NORMAL); - Locomotor* loco = jetAI->getCurLocomotor(); - DEBUG_ASSERTCRASH(loco, ("no loco")); - loco->setMaxLift(BIGNUM); - BodyDamageType bdt = jet->getBodyModule()->getDamageState(); - m_maxLift = loco->getMaxLift(bdt); - m_maxSpeed = loco->getMaxSpeedForCondition(bdt); - m_landingSoundPlayed = FALSE; - if (m_landing) - { - loco->setMaxSpeed(loco->getMinSpeed()); - } - else - { - loco->setMaxLift(0); - } - loco->setUsePreciseZPos(true); - loco->setUltraAccurate(true); - jetAI->ignoreObstacleID(jet->getProducerID()); - - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp == NULL) - return STATE_SUCCESS; // no airfield? just skip this step - - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) - { - // it's full. - return STATE_FAILURE; - } - - // only check this for landing; we might have already given up the reservation to the guy behind us for takeoff - if (m_landing) - { - if (!pp->reserveRunway(jet->getID(), m_landing)) - { - DEBUG_CRASH(("we should never get to this state unless we have a runway available")); - return STATE_FAILURE; - } - } - - std::vector path; - if (m_landing) - { -#ifdef CIRCLE_FOR_LANDING - m_circleForLandingPos = ppinfo.runwayApproach; - m_circleForLandingPos.z = (ppinfo.runwayEnd.z + ppinfo.runwayApproach.z)*0.5f; -#else - path.push_back(ppinfo.runwayApproach); -#endif - if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) - { - //Assigned to an aircraft carrier which has separate landing strips. - path.push_back( ppinfo.runwayLandingStart ); - path.push_back( ppinfo.runwayLandingEnd ); - } - else - { - //Assigned to an airstrip -- land the same way we took off but in reverse. - path.push_back(ppinfo.runwayEnd); - path.push_back(ppinfo.runwayStart); - } - } - else - { - ppinfo.runwayEnd.z = ppinfo.runwayApproach.z; - path.push_back(ppinfo.runwayEnd); - path.push_back(ppinfo.runwayExit); - } - - setAdjustsDestination(false); // precision is necessary - setAdjustFinalDestination(false); // especially at the endpoint! - - jetAI->friend_setGoalPath( &path ); - - StateReturnType ret = AIFollowPathState::onEnter(); - - return ret; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - if (m_landing) - { -#ifdef CIRCLE_FOR_LANDING - if (jet->getPosition()->z > m_circleForLandingPos.z) - { - const Real THRESH = 4.0f; - jetAI->getCurLocomotor()->setAltitudeChangeThresholdForCircling(THRESH); - jetAI->setLocomotorGoalPositionExplicit(m_circleForLandingPos); - return STATE_CONTINUE; - } - else -#endif - { - jetAI->getCurLocomotor()->setMaxLift(BIGNUM); -#ifdef CIRCLE_FOR_LANDING - jetAI->getCurLocomotor()->setAltitudeChangeThresholdForCircling(0); -#endif - } - - if( !m_landingSoundPlayed ) - { - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - Real zPos = jet->getPosition()->z; - Real zSlop = 0.25f; - PathfindLayerEnum layer = TheTerrainLogic->getHighestLayerForDestination( jet->getPosition() ); - Real groundZ = TheTerrainLogic->getLayerHeight( jet->getPosition()->x, jet->getPosition()->y, layer ); - if( pp ) - { - groundZ += pp->getLandingDeckHeightOffset(); - } - - if( zPos - zSlop <= groundZ ) - { - m_landingSoundPlayed = TRUE; - AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_aircraftWheelScreech; - soundToPlay.setPosition( jet->getPosition() ); - TheAudio->addAudioEvent( &soundToPlay ); - } - } - } - else - { - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp) - pp->transferRunwayReservationToNextInLineForTakeoff(jet->getID()); - - //Calculate the distance of the jet from the end of the runway as a ratio from the start. - //As it approaches the end of the runway, the plane will gain more lift, even if it's already - //going quickly. Using speed for lift is bad in the case of the aircraft carrier, because - //we don't want it to take off quickly. - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - pp->calcPPInfo( jet->getID(), &ppinfo ); - Coord3D vector = ppinfo.runwayEnd; - vector.sub( jet->getPosition() ); - Real dist = vector.length(); - - Real ratio = 1.0f - (dist / ppinfo.runwayTakeoffDist); - ratio *= ratio; //dampen it.... - if (ratio < 0.0f) ratio = 0.0f; - if (ratio > 1.0f) ratio = 1.0f; - jetAI->getCurLocomotor()->setMaxLift(m_maxLift * ratio); - } - - StateReturnType ret = AIFollowPathState::update(); - return ret; - } - - virtual void onExit( StateExitType status ) - { - AIFollowPathState::onExit(status); - - // just in case. - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return; - - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - jetAI->friend_enableAfterburners(false); - - // Paranoia checks - sometimes onExit is called when we are - // shutting down, and not all pieces are valid. CurLocomotor - // is definitely null in some cases. jba. - Locomotor* loco = jetAI->getCurLocomotor(); - if (loco) - { - loco->setUsePreciseZPos(false); - loco->setUltraAccurate(false); - // don't restore lift if dead -- this may fight with JetSlowDeathBehavior! - if (!jet->isEffectivelyDead()) - loco->setMaxLift(BIGNUM); -#ifdef CIRCLE_FOR_LANDING - loco->setAltitudeChangeThresholdForCircling(0); -#endif - } - jetAI->ignoreObstacleID(INVALID_ID); - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (!m_landing) - { - if (pp && !jetAI->friend_keepsParkingSpaceWhenAirborne()) - pp->releaseSpace(jet->getID()); - } - if (pp) - pp->releaseRunway(jet->getID()); - } -}; -EMPTY_DTOR(JetTakeoffOrLandingState) - -//------------------------------------------------------------------------------------------------- -static Real calcDistSqr(const Coord3D& a, const Coord3D& b) -{ - return sqr(a.x-b.x) + sqr(a.y-b.y) + sqr(a.z-b.z); -} - -//------------------------------------------------------------------------------------------------- -/* - Success: we are on the ground at the runway start - Failure: we are unable to get on the ground -*/ -class HeliTakeoffOrLandingState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(HeliTakeoffOrLandingState, "HeliTakeoffOrLandingState") -protected: - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty. jba. - } - - virtual void xfer( Xfer *xfer ) - { - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // set on create. xfer->xferBool(&m_landing); - xfer->xferCoord3D(&m_path[0]); - xfer->xferCoord3D(&m_path[1]); - xfer->xferInt(&m_index); - xfer->xferCoord3D(&m_parkingLoc); - xfer->xferReal(&m_parkingOrientation); - } - virtual void loadPostProcess() - { - // empty. jba. - } - -private: - Coord3D m_path[2]; - Int m_index; - Coord3D m_parkingLoc; - Real m_parkingOrientation; - Bool m_landing; -public: - HeliTakeoffOrLandingState( StateMachine *machine, Bool landing ) : m_landing(landing), - State( machine, "HeliTakeoffOrLandingState" ), m_index(0) - { - m_parkingLoc.zero(); - } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - jetAI->friend_setTakeoffInProgress(!m_landing); - jetAI->friend_setLandingInProgress(m_landing); - jetAI->friend_setAllowAirLoco(true); - jetAI->chooseLocomotorSet(LOCOMOTORSET_NORMAL); - - Locomotor* loco = jetAI->getCurLocomotor(); - DEBUG_ASSERTCRASH(loco, ("no loco")); - loco->setUsePreciseZPos(true); - loco->setUltraAccurate(true); - jetAI->ignoreObstacleID(jet->getProducerID()); - - Object* airfield; - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID(), &airfield); - if (pp == NULL) - return STATE_SUCCESS; // no airfield? just skip this step - - Coord3D landingApproach; - if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) - { - if (m_landing) - { - m_parkingLoc = jetAI->friend_getLandingPosForHelipadStuff(); - m_parkingOrientation = jet->getOrientation(); - } - else - { - m_parkingOrientation = jet->getOrientation(); - m_parkingLoc = *jet->getPosition(); - } - landingApproach = m_parkingLoc; - landingApproach.z += pp->getApproachHeight() + pp->getLandingDeckHeightOffset(); - } - else - { - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) - return STATE_FAILURE; - m_parkingLoc = ppinfo.parkingSpace; - m_parkingOrientation = ppinfo.parkingOrientation; - landingApproach = m_parkingLoc; - landingApproach.z += (ppinfo.runwayApproach.z - ppinfo.runwayEnd.z); - } - - if (m_landing) - { - m_path[0] = landingApproach; - m_path[1] = m_parkingLoc; - } - else - { - m_path[0] = m_parkingLoc; - m_path[1] = landingApproach; - m_path[1].z = landingApproach.z; - } - m_index = 0; - - return STATE_CONTINUE; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - -// I have disabled this because it is no longer necessary and is a bit funky lookin' (srj) -#ifdef NOT_IN_USE - // magically position it correctly. - jet->getPhysics()->scrubVelocity2D(0); - Coord3D hoverloc = m_path[m_index]; - hoverloc.z = jet->getPosition()->z; -#if 1 - Coord3D pos = *jet->getPosition(); - Real dx = hoverloc.x - pos.x; - Real dy = hoverloc.y - pos.y; - Real dSqr = dx*dx+dy*dy; - const Real DARN_CLOSE = 0.25f; - if (dSqr < DARN_CLOSE) - { - jet->setPosition(&hoverloc); - } - else - { - Real dist = sqrtf(dSqr); - if (dist<1) dist = 1; - pos.x += PATHFIND_CELL_SIZE_F*dx/(dist*LOGICFRAMES_PER_SECOND); - pos.y += PATHFIND_CELL_SIZE_F*dy/(dist*LOGICFRAMES_PER_SECOND); - jet->setPosition(&pos); - } -#else - jet->setPosition(&hoverloc); -#endif - jet->setOrientation(m_parkingOrientation); -#endif - - if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) || !m_landing) - { - TheAI->pathfinder()->adjustDestination(jet, jetAI->getLocomotorSet(), &m_path[m_index]); - TheAI->pathfinder()->updateGoal(jet, &m_path[m_index], LAYER_GROUND); - } - - jetAI->setLocomotorGoalPositionExplicit(m_path[m_index]); - - const Real THRESH = 3.0f; - const Real THRESH_SQR = THRESH*THRESH; - const Coord3D* a = jet->getPosition(); - const Coord3D* b = &m_path[m_index]; - Real distSqr = calcDistSqr(*a, *b); - if (distSqr <= THRESH_SQR) - ++m_index; - - if (m_index >= 2) - return STATE_SUCCESS; - - return STATE_CONTINUE; - } - - virtual void onExit( StateExitType status ) - { - // just in case. - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return; - - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - - // Paranoia checks - sometimes onExit is called when we are - // shutting down, and not all pieces are valid. CurLocomotor - // is definitely null in some cases. jba. - Locomotor* loco = jetAI->getCurLocomotor(); - if (loco) - { - loco->setUsePreciseZPos(false); - loco->setUltraAccurate(false); - // don't restore lift if dead -- this may fight with JetSlowDeathBehavior! - if (!jet->isEffectivelyDead()) - loco->setMaxLift(BIGNUM); - } - - jetAI->ignoreObstacleID(INVALID_ID); - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (m_landing) - { - jetAI->friend_setAllowAirLoco(false); - jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING); - } - else - { - if (pp && !jetAI->friend_keepsParkingSpaceWhenAirborne()) - pp->releaseSpace(jet->getID()); - } - } - -}; -EMPTY_DTOR(HeliTakeoffOrLandingState) - -//------------------------------------------------------------------------------------------------- -class JetOrHeliParkOrientState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliParkOrientState, "JetOrHeliParkOrientState") -protected: - // snapshot interface STUBBED. - virtual void crc( Xfer *xfer ){}; - virtual void xfer( Xfer *xfer ){XferVersion cv = 1; XferVersion v = cv; xfer->xferVersion( &v, cv );} - virtual void loadPostProcess(){}; - -public: - JetOrHeliParkOrientState( StateMachine *machine ) : State( machine, "JetOrHeliParkOrientState") { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) - { - return STATE_SUCCESS; - } - - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(true); - - jetAI->ignoreObstacleID(jet->getProducerID()); - return STATE_CONTINUE; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - { - return STATE_FAILURE; - } - - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp == NULL) - return STATE_FAILURE; - - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) - return STATE_FAILURE; - - const Real THRESH = 0.001f; - if (fabs(stdAngleDiff(jet->getOrientation(), ppinfo.parkingOrientation)) <= THRESH) - return STATE_SUCCESS; - - // magically position it correctly. - jet->getPhysics()->scrubVelocity2D(0); - Coord3D hoverloc = ppinfo.parkingSpace; - if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) - { - hoverloc = ppinfo.runwayPrep; - } - - hoverloc.z = jet->getPosition()->z; - jet->setPosition(&hoverloc); - - jetAI->setLocomotorGoalOrientation(ppinfo.parkingOrientation); - - return STATE_CONTINUE; - } - - virtual void onExit( StateExitType status ) - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return; - - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - jetAI->ignoreObstacleID(INVALID_ID); - } -}; -EMPTY_DTOR(JetOrHeliParkOrientState) - -//------------------------------------------------------------------------------------------------- -class JetPauseBeforeTakeoffState : public AIFaceState -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetPauseBeforeTakeoffState, "JetPauseBeforeTakeoffState") -protected: - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty. jba. - } - - virtual void xfer( Xfer *xfer ) - { - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // set on create. xfer->xferBool(&m_landing); - xfer->xferUnsignedInt(&m_when); - xfer->xferUnsignedInt(&m_whenTransfer); - xfer->xferBool(&m_afterburners); - xfer->xferBool(&m_resetTimer); - xfer->xferObjectID(&m_waitedForTaxiID); - } - virtual void loadPostProcess() - { - // empty. jba. - } - -private: - UnsignedInt m_when; - UnsignedInt m_whenTransfer; - ObjectID m_waitedForTaxiID; - Bool m_resetTimer; - Bool m_afterburners; - - Bool findWaiter() - { - Object* jet = getMachineOwner(); - ParkingPlaceBehaviorInterface* pp = getPP(getMachineOwner()->getProducerID()); - if (pp) - { - Int count = pp->getRunwayCount(); - for (Int i = 0; i < count; ++i) - { - Object* otherJet = TheGameLogic->findObjectByID( pp->getRunwayReservation( i, RESERVATION_TAKEOFF ) ); - if (otherJet == NULL || otherJet == jet) - continue; - - AIUpdateInterface* ai = otherJet->getAIUpdateInterface(); - if (ai == NULL) - continue; - - if (ai->getCurrentStateID() == TAXI_TO_TAKEOFF) - { - if (m_waitedForTaxiID == INVALID_ID) - { - m_waitedForTaxiID = otherJet->getID(); - } - return true; - } - } - } - return false; - } - -public: - JetPauseBeforeTakeoffState( StateMachine *machine ) : - AIFaceState(machine, false), - m_when(0), - m_whenTransfer(0), - m_waitedForTaxiID(INVALID_ID), - m_resetTimer(false), - m_afterburners(false) - { - // nothing - } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - jetAI->friend_setTakeoffInProgress(true); - jetAI->friend_setLandingInProgress(false); - - m_when = 0; - m_whenTransfer = 0; - m_waitedForTaxiID = INVALID_ID; - m_resetTimer = false; - m_afterburners = false; - - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp == NULL) - return STATE_SUCCESS; // no airfield? just skip this step. - - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) - return STATE_SUCCESS; // full? - - getMachine()->setGoalPosition(&ppinfo.runwayEnd); - - return AIFaceState::onEnter(); - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if (jet->isEffectivelyDead()) - return STATE_FAILURE; - - // always call this. - StateReturnType superStatus = AIFaceState::update(); - - if (findWaiter()) - return STATE_CONTINUE; - - UnsignedInt now = TheGameLogic->getFrame(); - if (!m_resetTimer) - { - // we had to wait, but now everyone else is ready, so restart our countdown. - m_when = now + jetAI->friend_getTakeoffPause(); - if (m_waitedForTaxiID == INVALID_ID) - { - m_waitedForTaxiID = jet->getID(); // just so we don't pick up anyone else - m_whenTransfer = now + 1; - } - else - { - m_whenTransfer = now + 2; // 2 seems odd, but is correct - } - m_resetTimer = true; - } - - if (!m_afterburners) - { - jetAI->friend_enableAfterburners(true); - m_afterburners = true; - } - - DEBUG_ASSERTCRASH(m_when != 0, ("hmm")); - DEBUG_ASSERTCRASH(m_whenTransfer != 0, ("hmm")); - - // once we start the final wait, release the runways for guys behind us, so they can start taxiing - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp && now >= m_whenTransfer) - { - pp->transferRunwayReservationToNextInLineForTakeoff(jet->getID()); - } - - if (now >= m_when) - return superStatus; - - return STATE_CONTINUE; - } - - virtual void onExit(StateExitType status) - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - AIFaceState::onExit(status); - } - -}; -EMPTY_DTOR(JetPauseBeforeTakeoffState) - -//------------------------------------------------------------------------------------------------- -class JetOrHeliReloadAmmoState : public State -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliReloadAmmoState, "JetOrHeliReloadAmmoState") -private: - UnsignedInt m_reloadTime; - UnsignedInt m_reloadDoneFrame; - -protected: - - // snapshot interface - virtual void crc( Xfer *xfer ) - { - // empty. jba. - } - - virtual void xfer( Xfer *xfer ) - { - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // set on create. xfer->xferBool(&m_landing); - xfer->xferUnsignedInt(&m_reloadTime); - xfer->xferUnsignedInt(&m_reloadDoneFrame); - } - virtual void loadPostProcess() - { - // empty. jba. - } - -public: - JetOrHeliReloadAmmoState( StateMachine *machine ) : State( machine, "JetOrHeliReloadAmmoState") { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - if( !jetAI ) - return STATE_FAILURE; - - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - jetAI->friend_setUseSpecialReturnLoco(false); - - m_reloadTime = 0; - for (Int i = 0; i < WEAPONSLOT_COUNT; ++i) - { - const Weapon* w = jet->getWeaponInWeaponSlot((WeaponSlotType)i); - if (w == NULL) - continue; - - Int remaining = w->getRemainingAmmo(); - Int clipSize = w->getClipSize(); - Int rt = w->getClipReloadTime(jet); - if (clipSize > 0) - { - // bias by amount empty. - Int needed = clipSize - remaining; - rt = (rt * needed) / clipSize; - } - if (rt > m_reloadTime) - m_reloadTime = rt; - } - - if (m_reloadTime < 1) - m_reloadTime = 1; - m_reloadDoneFrame = m_reloadTime + TheGameLogic->getFrame(); - return STATE_CONTINUE; - } - - virtual StateReturnType update() - { - Object* jet = getMachineOwner(); - UnsignedInt now = TheGameLogic->getFrame(); - Bool allDone = true; - for (Int i = 0; i < WEAPONSLOT_COUNT; ++i) - { - Weapon* w = jet->getWeaponInWeaponSlot((WeaponSlotType)i); - if (w == NULL) - continue; - - if (now >= m_reloadDoneFrame) - w->setClipPercentFull(1.0f, false); - else - w->setClipPercentFull((Real)(m_reloadTime - (m_reloadDoneFrame - now)) / m_reloadTime, false); - - if (w->getRemainingAmmo() != w->getClipSize()) - allDone = false; - } - - if (allDone) - return STATE_SUCCESS; - - return STATE_CONTINUE; - } - - virtual void onExit(StateExitType status) - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - jetAI->friend_setTakeoffInProgress(false); - jetAI->friend_setLandingInProgress(false); - } - -}; -EMPTY_DTOR(JetOrHeliReloadAmmoState) - -//------------------------------------------------------------------------------------------------- -/* - Success: we are close enough to a friendly airfield to land - Failure: we are unable to get close enough to a friendly airfield to land -*/ -class JetOrHeliReturnForLandingState : public AIInternalMoveToState -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliReturnForLandingState, "JetOrHeliReturnForLandingState") -public: - JetOrHeliReturnForLandingState( StateMachine *machine ) : AIInternalMoveToState( machine, "JetOrHeliReturnForLandingState") { } - - virtual StateReturnType onEnter() - { - Object* jet = getMachineOwner(); - JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); - - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (pp == NULL) - { - // nuke the producer id, since it's dead - jet->setProducer(NULL); - - Object* airfield = findSuitableAirfield( jet ); - pp = airfield ? getPP(airfield->getID()) : NULL; - if (airfield && pp) - { - jet->setProducer(airfield); - } - else - { - return STATE_FAILURE; - } - } - - if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) - { - m_goalPosition = jetAI->friend_getLandingPosForHelipadStuff(); - } - else - { - ParkingPlaceBehaviorInterface::PPInfo ppinfo; - if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) - return STATE_FAILURE; - - m_goalPosition = jetAI->friend_needsRunway() ? ppinfo.runwayApproach : ppinfo.parkingSpace; - } - setAdjustsDestination(false); // precision is necessary - - return AIInternalMoveToState::onEnter(); - } -}; -EMPTY_DTOR(JetOrHeliReturnForLandingState) - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -class JetAIStateMachine : public AIStateMachine -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( JetAIStateMachine, "JetAIStateMachine" ); - -public: - JetAIStateMachine( Object *owner, AsciiString name ); - -}; - -//------------------------------------------------------------------------------------------------- -JetAIStateMachine::JetAIStateMachine(Object *owner, AsciiString name) : AIStateMachine(owner, name) -{ - defineState( RETURNING_FOR_LANDING, newInstance(JetOrHeliReturnForLandingState)( this ), LANDING_AWAIT_CLEARANCE, RETURN_TO_DEAD_AIRFIELD ); - defineState( TAKING_OFF_AWAIT_CLEARANCE, newInstance(JetAwaitingRunwayState)( this, false ), TAXI_TO_TAKEOFF, AI_IDLE ); - defineState( TAXI_TO_TAKEOFF, newInstance(JetOrHeliTaxiState)( this, FROM_PARKING ), PAUSE_BEFORE_TAKEOFF, AI_IDLE ); - defineState( PAUSE_BEFORE_TAKEOFF, newInstance(JetPauseBeforeTakeoffState)( this ), TAKING_OFF, AI_IDLE ); - defineState( TAKING_OFF, newInstance(JetTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE ); - defineState( LANDING_AWAIT_CLEARANCE, newInstance(JetAwaitingRunwayState)( this, true ), LANDING, AI_IDLE ); - defineState( LANDING, newInstance(JetTakeoffOrLandingState)( this, true ), TAXI_FROM_LANDING, AI_IDLE ); - defineState( TAXI_FROM_LANDING, newInstance(JetOrHeliTaxiState)( this, TO_PARKING ), ORIENT_FOR_PARKING_PLACE, AI_IDLE ); - defineState( TAXI_FROM_HANGAR, newInstance(JetOrHeliTaxiState)( this, FROM_HANGAR ), ORIENT_FOR_PARKING_PLACE, AI_IDLE ); - defineState( ORIENT_FOR_PARKING_PLACE, newInstance(JetOrHeliParkOrientState)( this ), RELOAD_AMMO, AI_IDLE ); - defineState( RELOAD_AMMO, newInstance(JetOrHeliReloadAmmoState)( this ), AI_IDLE, AI_IDLE ); - defineState( RETURN_TO_DEAD_AIRFIELD, newInstance(JetOrHeliReturningToDeadAirfieldState)( this ), CIRCLING_DEAD_AIRFIELD, RETURN_TO_DEAD_AIRFIELD ); - defineState( CIRCLING_DEAD_AIRFIELD, newInstance(JetOrHeliCirclingDeadAirfieldState)( this ), AI_IDLE, AI_IDLE ); -} - -//------------------------------------------------------------------------------------------------- -JetAIStateMachine::~JetAIStateMachine() -{ -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -class HeliAIStateMachine : public AIStateMachine -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( HeliAIStateMachine, "HeliAIStateMachine" ); - -public: - HeliAIStateMachine( Object *owner, AsciiString name ); - -}; - -//------------------------------------------------------------------------------------------------- -HeliAIStateMachine::HeliAIStateMachine(Object *owner, AsciiString name) : AIStateMachine(owner, name) -{ - defineState( RETURNING_FOR_LANDING, newInstance(JetOrHeliReturnForLandingState)( this ), LANDING_AWAIT_CLEARANCE, RETURN_TO_DEAD_AIRFIELD ); - defineState( TAKING_OFF_AWAIT_CLEARANCE, newInstance(SuccessState)( this ), TAKING_OFF, AI_IDLE ); - defineState( TAKING_OFF, newInstance(HeliTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE ); - defineState( LANDING_AWAIT_CLEARANCE, newInstance(SuccessState)( this ), ORIENT_FOR_PARKING_PLACE, AI_IDLE ); - defineState( ORIENT_FOR_PARKING_PLACE, newInstance(JetOrHeliParkOrientState)( this ), LANDING, AI_IDLE ); - defineState( LANDING, newInstance(HeliTakeoffOrLandingState)( this, true ), RELOAD_AMMO, AI_IDLE ); - defineState( RELOAD_AMMO, newInstance(JetOrHeliReloadAmmoState)( this ), AI_IDLE, AI_IDLE ); - defineState( RETURN_TO_DEAD_AIRFIELD, newInstance(JetOrHeliReturningToDeadAirfieldState)( this ), CIRCLING_DEAD_AIRFIELD, RETURN_TO_DEAD_AIRFIELD ); - defineState( CIRCLING_DEAD_AIRFIELD, newInstance(JetOrHeliCirclingDeadAirfieldState)( this ), AI_IDLE, AI_IDLE ); - defineState( TAXI_FROM_HANGAR, newInstance(JetOrHeliTaxiState)( this, FROM_HANGAR ), AI_IDLE, AI_IDLE ); -} - -//------------------------------------------------------------------------------------------------- -HeliAIStateMachine::~HeliAIStateMachine() -{ -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -JetAIUpdateModuleData::JetAIUpdateModuleData() -{ - m_outOfAmmoDamagePerSecond = 0; - m_needsRunway = true; - m_keepsParkingSpaceWhenAirborne = true; - m_takeoffDistForMaxLift = 0.0f; - m_minHeight = 0.0f; - m_parkingOffset = 0.0f; - m_sneakyOffsetWhenAttacking = 0.0f; - m_takeoffPause = 0; - m_attackingLoco = LOCOMOTORSET_NORMAL; - m_returningLoco = LOCOMOTORSET_NORMAL; - m_attackLocoPersistTime = 0; - m_attackersMissPersistTime = 0; - m_lockonTime = 0; - m_lockonCursor.clear(); - m_lockonInitialDist = 100; - m_lockonFreq = 0.5; - m_lockonAngleSpin = 720; - m_returnToBaseIdleTime = 0; -} - -//------------------------------------------------------------------------------------------------- -/*static*/ void JetAIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) -{ - AIUpdateModuleData::buildFieldParse(p); - - static const FieldParse dataFieldParse[] = - { - { "OutOfAmmoDamagePerSecond", INI::parsePercentToReal, NULL, offsetof( JetAIUpdateModuleData, m_outOfAmmoDamagePerSecond ) }, - { "NeedsRunway", INI::parseBool, NULL, offsetof( JetAIUpdateModuleData, m_needsRunway ) }, - { "KeepsParkingSpaceWhenAirborne",INI::parseBool, NULL, offsetof( JetAIUpdateModuleData, m_keepsParkingSpaceWhenAirborne ) }, - { "TakeoffDistForMaxLift", INI::parsePercentToReal, NULL, offsetof( JetAIUpdateModuleData, m_takeoffDistForMaxLift ) }, - { "TakeoffPause", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_takeoffPause ) }, - { "MinHeight", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_minHeight ) }, - { "ParkingOffset", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_parkingOffset ) }, - { "SneakyOffsetWhenAttacking", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_sneakyOffsetWhenAttacking ) }, - { "AttackLocomotorType", INI::parseIndexList, TheLocomotorSetNames, offsetof( JetAIUpdateModuleData, m_attackingLoco ) }, - { "AttackLocomotorPersistTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_attackLocoPersistTime ) }, - { "AttackersMissPersistTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_attackersMissPersistTime ) }, - { "ReturnForAmmoLocomotorType", INI::parseIndexList, TheLocomotorSetNames, offsetof( JetAIUpdateModuleData, m_returningLoco ) }, - { "LockonTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_lockonTime ) }, - { "LockonCursor", INI::parseAsciiString, NULL, offsetof( JetAIUpdateModuleData, m_lockonCursor ) }, - { "LockonInitialDist", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_lockonInitialDist ) }, - { "LockonFreq", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_lockonFreq ) }, - { "LockonAngleSpin", INI::parseAngleReal, NULL, offsetof( JetAIUpdateModuleData, m_lockonAngleSpin ) }, - { "LockonBlinky", INI::parseBool, NULL, offsetof( JetAIUpdateModuleData, m_lockonBlinky ) }, - { "ReturnToBaseIdleTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_returnToBaseIdleTime ) }, - { 0, 0, 0, 0 } - }; - p.add(dataFieldParse); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -AIStateMachine* JetAIUpdate::makeStateMachine() -{ - if (getJetAIUpdateModuleData()->m_needsRunway) - return newInstance(JetAIStateMachine)( getObject(), "JetAIStateMachine"); - else - return newInstance(HeliAIStateMachine)( getObject(), "HeliAIStateMachine"); -} - -//------------------------------------------------------------------------------------------------- -JetAIUpdate::JetAIUpdate( Thing *thing, const ModuleData* moduleData ) : AIUpdateInterface( thing, moduleData ) -{ - m_flags = 0; - m_afterburnerSound = *(getObject()->getTemplate()->getPerUnitSound("Afterburner")); - m_afterburnerSound.setObjectID(getObject()->getID()); - m_attackLocoExpireFrame = 0; - m_attackersMissExpireFrame = 0; - m_untargetableExpireFrame = 0; - m_returnToBaseFrame = 0; - m_lockonDrawable = NULL; - m_landingPosForHelipadStuff.zero(); - - //Added By Sadullah Nader - //Initializations missing and needed - m_producerLocation.zero(); - // - m_enginesOn = TRUE; -} - -//------------------------------------------------------------------------------------------------- -JetAIUpdate::~JetAIUpdate() -{ - if (m_lockonDrawable) - { - TheGameClient->destroyDrawable(m_lockonDrawable); - m_lockonDrawable = NULL; - } -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::isIdle() const -{ - // we need to do this because we enter an idle state briefly between takeoff/landing in these cases, - // but scripting relies on us never claiming to be "idle"... - if (getFlag(HAS_PENDING_COMMAND)) - return false; - - return AIUpdateInterface::isIdle(); -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::isReloading() const -{ - StateID stateID = getStateMachine()->getCurrentStateID(); - if( stateID == RELOAD_AMMO ) - { - return TRUE; - } - return FALSE; -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::isTaxiingToParking() const -{ - StateID stateID = getStateMachine()->getCurrentStateID(); - switch( stateID ) - { - case TAXI_FROM_HANGAR: - case TAXI_FROM_LANDING: - case ORIENT_FOR_PARKING_PLACE: - case RELOAD_AMMO: - case TAKING_OFF_AWAIT_CLEARANCE: - case TAXI_TO_TAKEOFF: - case PAUSE_BEFORE_TAKEOFF: - case TAKING_OFF: - return TRUE; - } - return FALSE; -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::onObjectCreated() -{ - AIUpdateInterface::onObjectCreated(); - friend_setAllowAirLoco(false); - chooseLocomotorSet(LOCOMOTORSET_TAXIING); -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::onDelete() -{ - AIUpdateInterface::onDelete(); - ParkingPlaceBehaviorInterface* pp = getPP(getObject()->getProducerID()); - if (pp) - pp->releaseSpace(getObject()->getID()); -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::getProducerLocation() -{ - if (getFlag(HAS_PRODUCER_LOCATION)) - return; - - Object* jet = getObject(); - Object* airfield = TheGameLogic->findObjectByID( jet->getProducerID() ); - if (airfield == NULL) - m_producerLocation = *jet->getPosition(); - else - m_producerLocation = *airfield->getPosition(); - - /* - if we aren't allowed to fly, then we should be parked (or at least taxiing), - which implies we have a parking place reserved. If we don't, it's probably - because we were directly spawned via script (or directly placed on the map). - So, check to see if we have no parking place, and if not, quietly enable flight. - */ - ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); - if (!pp || !pp->hasReservedSpace(jet->getID())) - { - friend_setAllowAirLoco(true); - chooseLocomotorSet(LOCOMOTORSET_NORMAL); - } - else - { - friend_setAllowAirLoco(false); - chooseLocomotorSet(LOCOMOTORSET_TAXIING); - } - - setFlag(HAS_PRODUCER_LOCATION, true); - -} - -//------------------------------------------------------------------------------------------------- -UpdateSleepTime JetAIUpdate::update() -{ - const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); - - getProducerLocation(); - - Object* jet = getObject(); - - ParkingPlaceBehaviorInterface* pp = getPP(getObject()->getProducerID()); - - // If idle & out of ammo, return - // have to call our parent's isIdle, because we override it to never return true - // when we have a pending command... - UnsignedInt now = TheGameLogic->getFrame(); - - // srj sez: not 100% sure on this. calling RELOAD_AMMO "idle" allows us to get healed while reloading, - // but might have other side effects we didn't want. if this does prove to cause a bug, be sure - // that jets (and ESPECIALLY comanches) are still getting healed at airfields. - if (AIUpdateInterface::isIdle() || getStateMachine()->getCurrentStateID() == RELOAD_AMMO) - { - if (pp != NULL) - { - if (!getFlag(ALLOW_AIR_LOCO) && - !getFlag(HAS_PENDING_COMMAND) && - jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) && - jet->getBodyModule()->getHealth() == jet->getBodyModule()->getMaxHealth()) - { - // we're completely healed, so take off again - pp->setHealee(jet, false); - friend_setAllowAirLoco(true); - getStateMachine()->clear(); - setLastCommandSource( CMD_FROM_AI ); - getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE ); - } - else - { - pp->setHealee(jet, !getFlag(ALLOW_AIR_LOCO)); - } - } - - // note that we might still have weapons with ammo, but still be forced to return to reload. - if (isOutOfSpecialReloadAmmo() && getFlag(ALLOW_AIR_LOCO)) - { - m_returnToBaseFrame = 0; - - // this is really a "just-in-case" to ensure the targeter list doesn't spin out of control (srj) - pruneDeadTargeters(); - - setFlag(USE_SPECIAL_RETURN_LOCO, true); - setLastCommandSource( CMD_FROM_AI ); - getStateMachine()->setState(RETURNING_FOR_LANDING); - } - else if (getFlag(HAS_PENDING_COMMAND) - // srj sez: if we are reloading ammo, wait will we are done before processing the pending command. - && getStateMachine()->getCurrentStateID() != RELOAD_AMMO) - { - m_returnToBaseFrame = 0; - - AICommandParms parms(AICMD_MOVE_TO_POSITION, CMD_FROM_AI); // values don't matter, will be wiped by next line - m_mostRecentCommand.reconstitute(parms); - setFlag(HAS_PENDING_COMMAND, false); - - aiDoCommand(&parms); - } - else if (m_returnToBaseFrame != 0 && now >= m_returnToBaseFrame && getFlag(ALLOW_AIR_LOCO)) - { - m_returnToBaseFrame = 0; - DEBUG_ASSERTCRASH(isOutOfSpecialReloadAmmo() == false, ("Hmm, this seems unlikely -- isOutOfSpecialReloadAmmo()==false")); - setFlag(USE_SPECIAL_RETURN_LOCO, false); - setLastCommandSource( CMD_FROM_AI ); - getStateMachine()->setState(RETURNING_FOR_LANDING); - } - else if (m_returnToBaseFrame == 0 && d->m_returnToBaseIdleTime > 0 && getFlag(ALLOW_AIR_LOCO)) - { - m_returnToBaseFrame = now + d->m_returnToBaseIdleTime; - } - } - else - { - if (pp != NULL) - { - pp->setHealee(getObject(), false); - } - m_returnToBaseFrame = 0; - if (getFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD) && - isOutOfSpecialReloadAmmo() && getFlag(ALLOW_AIR_LOCO)) - { - setFlag(USE_SPECIAL_RETURN_LOCO, true); - setFlag(HAS_PENDING_COMMAND, true); - setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, false); - setLastCommandSource( CMD_FROM_AI ); - getStateMachine()->setState(RETURNING_FOR_LANDING); - } - } - - Real minHeight = friend_getMinHeight(); - if( pp ) - { - minHeight += pp->getLandingDeckHeightOffset(); - } - - Drawable* draw = jet->getDrawable(); - if (draw != NULL) - { - StateID id = getStateMachine()->getCurrentStateID(); - Bool needToCheckMinHeight = (id >= JETAISTATETYPE_FIRST && id <= JETAISTATETYPE_LAST) || - !jet->isAboveTerrain() || - !getFlag(ALLOW_AIR_LOCO); - if( needToCheckMinHeight || jet->getStatusBits().test( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) - { - Real ht = jet->isAboveTerrain() ? jet->getHeightAboveTerrain() : 0; - if (ht < minHeight) - { - Matrix3D tmp(1); - tmp.Set_Z_Translation(minHeight - ht); - draw->setInstanceMatrix(&tmp); - } - else - { - draw->setInstanceMatrix(NULL); - } - } - else - { - draw->setInstanceMatrix(NULL); - } - } - - PhysicsBehavior* physics = jet->getPhysics(); - if (physics->getVelocityMagnitude() > 0 && getFlag(ALLOW_AIR_LOCO)) - jet->setModelConditionState(MODELCONDITION_JETEXHAUST); - else - jet->clearModelConditionState(MODELCONDITION_JETEXHAUST); - - if (jet->testStatus(OBJECT_STATUS_IS_ATTACKING)) - { - m_attackLocoExpireFrame = now + d->m_attackLocoPersistTime; - m_attackersMissExpireFrame = now + d->m_attackersMissPersistTime; - } - else - { - if (m_attackLocoExpireFrame != 0 && now >= m_attackLocoExpireFrame) - { - m_attackLocoExpireFrame = 0; - } - if (m_attackersMissExpireFrame != 0 && now >= m_attackersMissExpireFrame) - { - m_attackersMissExpireFrame = 0; - } - } - - if (m_untargetableExpireFrame != 0 && now >= m_untargetableExpireFrame) - { - m_untargetableExpireFrame = 0; - } - - positionLockon(); - - if (m_attackLocoExpireFrame != 0) - { - chooseLocomotorSet(d->m_attackingLoco); - } - else if (getFlag(USE_SPECIAL_RETURN_LOCO)) - { - chooseLocomotorSet(d->m_returningLoco); - } - - - if( !jet->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) ) - { - Drawable *draw = jet->getDrawable(); - if( draw ) - { - if( getFlag(TAKEOFF_IN_PROGRESS) - || getFlag(LANDING_IN_PROGRESS) - || getObject()->isSignificantlyAboveTerrain() - || isMoving() - || isWaitingForPath() ) - { - if( !m_enginesOn ) - { - //We just started moving, therefore turn on the engines! - draw->enableAmbientSound( TRUE ); - m_enginesOn = TRUE; - } - } - else if( m_enginesOn ) - { - //We're no longer moving, so turn off the engines! - draw->enableAmbientSound( FALSE ); - m_enginesOn = FALSE; - } - } - } - - - /*UpdateSleepTime ret =*/ AIUpdateInterface::update(); - //return (mine < ret) ? mine : ret; - /// @todo srj -- someday, make sleepy. for now, must not sleep. - return UPDATE_SLEEP_NONE; -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::chooseLocomotorSet(LocomotorSetType wst) -{ - const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); - if (!getFlag(ALLOW_AIR_LOCO)) - { - wst = LOCOMOTORSET_TAXIING; - } - else if (m_attackLocoExpireFrame != 0) - { - wst = d->m_attackingLoco; - } - else if (getFlag(USE_SPECIAL_RETURN_LOCO)) - { - wst = d->m_returningLoco; - } - return AIUpdateInterface::chooseLocomotorSet(wst); -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::setLocomotorGoalNone() -{ - if ((getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS)) - && getFlag(ALLOW_AIR_LOCO) && !getFlag(ALLOW_CIRCLING)) - { - Object* jet = getObject(); - Coord3D desiredPos = *jet->getPosition(); - const Coord3D* dir = jet->getUnitDirectionVector2D(); - desiredPos.x += dir->x * 1000.0f; - desiredPos.y += dir->y * 1000.0f; - setLocomotorGoalPositionExplicit(desiredPos); - } - else - { - AIUpdateInterface::setLocomotorGoalNone(); - } -} - -//---------------------------------------------------------------------------------------- -Bool JetAIUpdate::getSneakyTargetingOffset(Coord3D* offset) const -{ - if (m_attackersMissExpireFrame != 0 && TheGameLogic->getFrame() < m_attackersMissExpireFrame) - { - if (offset) - { - const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); - const Object* jet = getObject(); - const Coord3D* dir = jet->getUnitDirectionVector2D(); - offset->x = dir->x * d->m_sneakyOffsetWhenAttacking; - offset->y = dir->y * d->m_sneakyOffsetWhenAttacking; - offset->z = 0.0f; - } - return true; - } - else - { - return false; - } -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::pruneDeadTargeters() -{ - if (!m_targetedBy.empty()) - { - for (std::list::iterator it = m_targetedBy.begin(); it != m_targetedBy.end(); /* empty */ ) - { - if (TheGameLogic->findObjectByID(*it) == NULL) - { - it = m_targetedBy.erase(it); - } - else - { - ++it; - } - } - } -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::positionLockon() -{ - if (!m_lockonDrawable) - return; - - if (m_untargetableExpireFrame == 0) - { - TheGameClient->destroyDrawable(m_lockonDrawable); - m_lockonDrawable = NULL; - return; - } - - const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); - UnsignedInt now = TheGameLogic->getFrame(); - UnsignedInt remaining = m_untargetableExpireFrame - now; - UnsignedInt elapsed = d->m_lockonTime - remaining; - - Coord3D pos = *getObject()->getPosition(); - Real frac = (Real)remaining / (Real)d->m_lockonTime; - Real finalDist = getObject()->getGeometryInfo().getBoundingCircleRadius(); - Real dist = finalDist + (d->m_lockonInitialDist - finalDist) * frac; - Real angle = d->m_lockonAngleSpin * frac; - - pos.x += Cos(angle) * dist; - pos.y += Sin(angle) * dist; - // pos.z is untouched - - m_lockonDrawable->setPosition(&pos); - Real dx = getObject()->getPosition()->x - pos.x; - Real dy = getObject()->getPosition()->y - pos.y; - if (dx || dy) - m_lockonDrawable->setOrientation(atan2(dy, dx)); - - // the Gaussian sum, to avoid keeping a running total: - // - // 1+2+3+...n = n*(n+1)/2 - // - Real elapsedTimeSumPrev = 0.5f * (elapsed-1) * (elapsed); - Real elapsedTimeSumCurr = elapsedTimeSumPrev + elapsed; - Real factor = d->m_lockonFreq / d->m_lockonTime; - Bool lastPhase = ((Int)(factor * elapsedTimeSumPrev) & 1) != 0; - Bool thisPhase = ((Int)(factor * elapsedTimeSumCurr) & 1) != 0; - - if (lastPhase && (!thisPhase)) - { - AudioEventRTS lockonSound = TheAudio->getMiscAudio()->m_lockonTickSound; - lockonSound.setObjectID(getObject()->getID()); - TheAudio->addAudioEvent(&lockonSound); - if (d->m_lockonBlinky) - m_lockonDrawable->setDrawableHidden(false); - } - else - { - if (d->m_lockonBlinky) - m_lockonDrawable->setDrawableHidden(true); - } -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::buildLockonDrawableIfNecessary() -{ - if (m_untargetableExpireFrame == 0) - return; - - const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); - if (d->m_lockonCursor.isNotEmpty() && m_lockonDrawable == NULL) - { - const ThingTemplate* tt = TheThingFactory->findTemplate(d->m_lockonCursor); - if (tt) - { - m_lockonDrawable = TheThingFactory->newDrawable(tt); - } - } - positionLockon(); -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::addTargeter(ObjectID id, Bool add) -{ - const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); - UnsignedInt lockonTime = d->m_lockonTime; - if (lockonTime != 0) - { - std::list::iterator it = std::find(m_targetedBy.begin(), m_targetedBy.end(), id); - if (add) - { - if (it == m_targetedBy.end()) - { - m_targetedBy.push_back(id); - if (m_untargetableExpireFrame == 0 && m_targetedBy.size() == 1) - { - m_untargetableExpireFrame = TheGameLogic->getFrame() + lockonTime; - buildLockonDrawableIfNecessary(); - } - } - } - else - { - if (it != m_targetedBy.end()) - { - m_targetedBy.erase(it); - if (m_targetedBy.empty()) - { - m_untargetableExpireFrame = 0; - } - } - } - } -} - -//---------------------------------------------------------------------------------------- -Bool JetAIUpdate::isTemporarilyPreventingAimSuccess() const -{ - return m_untargetableExpireFrame != 0 && (TheGameLogic->getFrame() < m_untargetableExpireFrame); -} - -//---------------------------------------------------------------------------------------- -Bool JetAIUpdate::isAllowedToMoveAwayFromUnit() const -{ - // parked (or landing) units don't get to do this. - if (!getFlag(ALLOW_AIR_LOCO) || getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS)) - return false; - - return AIUpdateInterface::isAllowedToMoveAwayFromUnit(); -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::isDoingGroundMovement(void) const -{ - // srj per jba: Air units should never be doing ground movement, even when taxiing... - // (exception: see getTreatAsAircraftForLocoDistToGoal) - return false; -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::getTreatAsAircraftForLocoDistToGoal() const -{ - // exception to isDoingGroundMovement: should never treat as aircraft for dist-to-goal when taxiing. - if (getFlag(TAXI_IN_PROGRESS)) - { - return false; - } - else - { - return AIUpdateInterface::getTreatAsAircraftForLocoDistToGoal(); - } -} - -//---------------------------------------------------------------------------------------- -/** - * Follow the path defined by the given array of points - */ -void JetAIUpdate::privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) -{ - if (exitProduction) - { - getStateMachine()->clear(); - if( ignoreObject ) - ignoreObstacle( ignoreObject ); - setLastCommandSource( cmdSource ); - if (getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) - getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE ); - else - getStateMachine()->setState( TAXI_FROM_HANGAR ); - } - else - { - AIUpdateInterface::privateFollowPath(path, ignoreObject, cmdSource, exitProduction); - } -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::privateFollowPathAppend( const Coord3D *pos, CommandSourceType cmdSource ) -{ - // nothing yet... might need to override. not sure. (srj) - AIUpdateInterface::privateFollowPathAppend(pos, cmdSource); -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::doLandingCommand(Object *airfield, CommandSourceType cmdSource) -{ - if (getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) - { - m_landingPosForHelipadStuff = *airfield->getPosition(); - - Coord3D tmp; - FindPositionOptions options; - options.maxRadius = airfield->getGeometryInfo().getBoundingCircleRadius() * 10.0f; - if (ThePartitionManager->findPositionAround(&m_landingPosForHelipadStuff, &options, &tmp)) - m_landingPosForHelipadStuff = tmp; - } - - for (BehaviorModule** i = airfield->getBehaviorModules(); *i; ++i) - { - ParkingPlaceBehaviorInterface* pp = (*i)->getParkingPlaceBehaviorInterface(); - if (pp == NULL) - continue; - - if (getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) || - pp->reserveSpace(getObject()->getID(), friend_getParkingOffset(), NULL)) - { - // if we had a space at another airfield, release it - ParkingPlaceBehaviorInterface* oldPP = getPP(getObject()->getProducerID()); - if (oldPP != NULL && oldPP != pp) - { - oldPP->releaseSpace(getObject()->getID()); - } - - getObject()->setProducer(airfield); - DEBUG_ASSERTCRASH(isOutOfSpecialReloadAmmo() == false, ("Hmm, this seems unlikely -- isOutOfSpecialReloadAmmo()==false")); - setFlag(USE_SPECIAL_RETURN_LOCO, false); - setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, false); - setLastCommandSource( cmdSource ); - getStateMachine()->setState(RETURNING_FOR_LANDING); - return; - } - } -} - -//---------------------------------------------------------------------------------------- -void JetAIUpdate::notifyVictimIsDead() -{ - if (getJetAIUpdateModuleData()->m_needsRunway) - m_returnToBaseFrame = TheGameLogic->getFrame(); -} - -//---------------------------------------------------------------------------------------- -/** - * Enter the given object - */ -void JetAIUpdate::privateEnter( Object *objectToEnter, CommandSourceType cmdSource ) -{ - // we are already landing. just ignore it. - if (getFlag(LANDING_IN_PROGRESS)) - return; - - if( !TheActionManager->canEnterObject( getObject(), objectToEnter, cmdSource, DONT_CHECK_CAPACITY ) ) - return; - - doLandingCommand(objectToEnter, cmdSource); -} - -//---------------------------------------------------------------------------------------- -/** - * Get repaired at the repair depot - */ -void JetAIUpdate::privateGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) -{ - // we are already landing. just ignore it. - if (getFlag(LANDING_IN_PROGRESS)) - return; - - // sanity, if we can't get repaired from here get out of here - if( TheActionManager->canGetRepairedAt( getObject(), repairDepot, cmdSource ) == FALSE ) - return; - - // dock with the repair depot - doLandingCommand( repairDepot, cmdSource ); - -} - -//------------------------------------------------------------------------------------------------- -Bool JetAIUpdate::isParkedAt(const Object* obj) const -{ - if (!getFlag(ALLOW_AIR_LOCO) && - !getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) && - obj != NULL) - { - Object* airfield; - ParkingPlaceBehaviorInterface* pp = getPP(getObject()->getProducerID(), &airfield); - if (pp != NULL && airfield != NULL && airfield == obj) - { - return true; - } - } - - return false; -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::aiDoCommand(const AICommandParms* parms) -{ - // call this from aiDoCommand as well as update, because this can - // be called before update ever is... if the unit is placed on a map, - // and a script tells it to do something with a condition of TRUE! - getProducerLocation(); - - if (!isAllowedToRespondToAiCommands(parms)) - return; - - // note that we always store this, even if nothing will be "pending". - m_mostRecentCommand.store(*parms); - - if (getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS)) - { - // have to wait for takeoff or landing to complete, just store the sucker - setFlag(HAS_PENDING_COMMAND, true); - return; - } - else if (parms->m_cmd == AICMD_IDLE && getStateMachine()->getCurrentStateID() == RELOAD_AMMO) - { - // uber-special-case... if we are told to idle, but are reloading ammo, ignore it for now, - // since we're already doing "nothing" and responding to this will cease our reload... - // don't just return, tho, in case we were (say) reloading during a guard stint. - setFlag(HAS_PENDING_COMMAND, true); - return; - } - else if( parms->m_cmd == AICMD_IDLE && getObject()->isAirborneTarget() && !getObject()->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) ) - { - getStateMachine()->clear(); - setLastCommandSource( CMD_FROM_AI ); - getStateMachine()->setState( RETURNING_FOR_LANDING ); - return; - } - else if (!getFlag(ALLOW_AIR_LOCO)) - { - switch (parms->m_cmd) - { - case AICMD_IDLE: - case AICMD_BUSY: - case AICMD_FOLLOW_EXITPRODUCTION_PATH: - // don't need (or want) to take off for these - break; - - case AICMD_ENTER: - case AICMD_GET_REPAIRED: - - // if we're already parked at the airfield in question, just ignore. - if (isParkedAt(parms->m_obj)) - return; - - // else fall thru to the default case! - - default: - { - // nuke any existing pending cmd - m_mostRecentCommand.store(*parms); - setFlag(HAS_PENDING_COMMAND, true); - - getStateMachine()->clear(); - setLastCommandSource( CMD_FROM_AI ); - getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE ); - - return; - } - } - } - - switch (parms->m_cmd) - { - case AICMD_GUARD_POSITION: - case AICMD_GUARD_OBJECT: - case AICMD_GUARD_AREA: - case AICMD_HUNT: - case AICMD_GUARD_RETALIATE: - setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, true); - break; - default: - setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, false); - break; - } - - setFlag(HAS_PENDING_COMMAND, false); - AIUpdateInterface::aiDoCommand(parms); -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::friend_setAllowAirLoco(Bool allowAirLoco) -{ - setFlag(ALLOW_AIR_LOCO, allowAirLoco); -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::friend_enableAfterburners(Bool v) -{ - Object* jet = getObject(); - if (v) - { - jet->setModelConditionState(MODELCONDITION_JETAFTERBURNER); - if (!m_afterburnerSound.isCurrentlyPlaying()) - { - m_afterburnerSound.setObjectID(jet->getID()); - m_afterburnerSound.setPlayingHandle(TheAudio->addAudioEvent(&m_afterburnerSound)); - } - } - else - { - jet->clearModelConditionState(MODELCONDITION_JETAFTERBURNER); - if (m_afterburnerSound.isCurrentlyPlaying()) - { - TheAudio->removeAudioEvent(m_afterburnerSound.getPlayingHandle()); - } - } -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::friend_addWaypointToGoalPath( const Coord3D &bestPos ) -{ - privateFollowPathAppend( &bestPos, CMD_FROM_AI ); -} - -//------------------------------------------------------------------------------------------------- -AICommandType JetAIUpdate::friend_getPendingCommandType() const -{ - if( getFlag( HAS_PENDING_COMMAND ) ) - { - return m_mostRecentCommand.getCommandType(); - } - return AICMD_NO_COMMAND; -} - -//------------------------------------------------------------------------------------------------- -void JetAIUpdate::friend_purgePendingCommand() -{ - setFlag(HAS_PENDING_COMMAND, false); -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void JetAIUpdate::crc( Xfer *xfer ) -{ - // extend base class - AIUpdateInterface::crc(xfer); -} // end crc - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void JetAIUpdate::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 2; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // extend base class - AIUpdateInterface::xfer(xfer); - - - xfer->xferCoord3D(&m_producerLocation); - m_mostRecentCommand.doXfer(xfer); - xfer->xferUnsignedInt(&m_attackLocoExpireFrame); - xfer->xferUnsignedInt(&m_attackersMissExpireFrame); - xfer->xferUnsignedInt(&m_returnToBaseFrame); - xfer->xferSTLObjectIDList(&m_targetedBy); - - xfer->xferUnsignedInt(&m_untargetableExpireFrame); - - // Set on create. - //AudioEventRTS m_afterburnerSound; ///< Sound when afterburners on - - AsciiString drawName; - if (m_lockonDrawable) { - drawName = m_lockonDrawable->getTemplate()->getName(); - } - xfer->xferAsciiString(&drawName); - if (drawName.isNotEmpty() && m_lockonDrawable==NULL) - { - const ThingTemplate* tt = TheThingFactory->findTemplate(drawName); - if (tt) - { - m_lockonDrawable = TheThingFactory->newDrawable(tt); - } - } - xfer->xferInt(&m_flags); - - if( version >= 2 ) - { - xfer->xferBool( &m_enginesOn ); - } - else - { - //We don't have to be accurate -- this is a patch. - if( getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS) || getObject()->isSignificantlyAboveTerrain() || getObject()->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) ) - { - m_enginesOn = TRUE; - } - else - { - m_enginesOn = FALSE; - } - } - -} // end xfer - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void JetAIUpdate::loadPostProcess( void ) -{ - //When drawables are created, so are their ambient sounds. After loading, only turn off the - //ambient sound if the engine is off. - if( !m_enginesOn ) - { - Drawable *draw = getObject()->getDrawable(); - if( draw ) - { - draw->stopAmbientSound(); - } - } - - // extend base class - AIUpdateInterface::loadPostProcess(); -} // end loadPostProcess +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// JetAIUpdate.cpp ////////// + +#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine + +#define DEFINE_LOCOMOTORSET_NAMES + +#include "Common/ActionManager.h" +#include "Common/GlobalData.h" +#include "Common/MiscAudio.h" +#include "Common/ThingFactory.h" +#include "Common/ThingTemplate.h" +#include "GameClient/Drawable.h" +#include "GameClient/GameClient.h" +#include "GameLogic/ExperienceTracker.h" +#include "GameLogic/Locomotor.h" +#include "GameLogic/Module/BodyModule.h" +#include "GameLogic/Module/CountermeasuresBehavior.h" +#include "GameLogic/Module/JetAIUpdate.h" +#include "GameLogic/Module/ParkingPlaceBehavior.h" +#include "GameLogic/Module/PhysicsUpdate.h" +#include "GameLogic/Object.h" +#include "GameLogic/AIPathfind.h" +#include "GameLogic/PartitionManager.h" +#include "GameLogic/Weapon.h" + +const Real BIGNUM = 99999.0f; + +#ifdef RTS_INTERNAL +// for occasional debugging... +//#pragma optimize("", off) +//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") +#endif + +//------------------------------------------------------------------------------------------------- +enum TaxiType CPP_11(: Int) +{ + FROM_HANGAR, + FROM_PARKING, + TO_PARKING +}; + +//------------------------------------------------------------------------------------------------- +enum JetAIStateType CPP_11(: Int) +{ + // note that these must be distinct (numerically) from AIStateType. ick. + JETAISTATETYPE_FIRST = 1000, + + TAXI_FROM_HANGAR, + TAKING_OFF_AWAIT_CLEARANCE, + TAXI_TO_TAKEOFF, + PAUSE_BEFORE_TAKEOFF, + TAKING_OFF, + LANDING_AWAIT_CLEARANCE, + LANDING, + TAXI_FROM_LANDING, + ORIENT_FOR_PARKING_PLACE, + RELOAD_AMMO, + RETURNING_FOR_LANDING, + RETURN_TO_DEAD_AIRFIELD, + CIRCLING_DEAD_AIRFIELD, + + JETAISTATETYPE_LAST +}; + + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::getFlag( FlagType f ) const +{ + return (m_flags & (1<getWeaponInWeaponSlot((WeaponSlotType)i); + if (weapon == NULL || weapon->getReloadType() != RETURN_TO_BASE_TO_RELOAD) + continue; + ++specials; + if (weapon->getStatus() == OUT_OF_AMMO) + ++out; + } + return specials > 0 && out == specials; +} + +//------------------------------------------------------------------------------------------------- +static ParkingPlaceBehaviorInterface* getPP(ObjectID id, Object** airfieldPP = NULL) +{ + if (airfieldPP) + *airfieldPP = NULL; + + Object* airfield = TheGameLogic->findObjectByID( id ); + if (airfield == NULL || airfield->isEffectivelyDead() || !airfield->isKindOf(KINDOF_FS_AIRFIELD) || airfield->testStatus(OBJECT_STATUS_SOLD)) + return NULL; + + if (airfieldPP) + *airfieldPP = airfield; + + ParkingPlaceBehaviorInterface* pp = NULL; + for (BehaviorModule** i = airfield->getBehaviorModules(); *i; ++i) + { + if ((pp = (*i)->getParkingPlaceBehaviorInterface()) != NULL) + break; + } + + return pp; +} + +//------------------------------------------------------------------------------------------------- +class PartitionFilterHasParkingPlace : public PartitionFilter +{ +private: + ObjectID m_id; +public: + PartitionFilterHasParkingPlace(ObjectID id) : m_id(id) { } +protected: +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) + virtual const char* debugGetName() { return "PartitionFilterHasParkingPlace"; } +#endif + virtual Bool allow(Object *objOther) + { + ParkingPlaceBehaviorInterface* pp = getPP(objOther->getID()); + if (pp != NULL && pp->reserveSpace(m_id, 0.0f, NULL)) + return true; + return false; + } +}; + +//------------------------------------------------------------------------------------------------- +static Object* findSuitableAirfield(Object* jet) +{ + PartitionFilterAcceptByKindOf filterKind(MAKE_KINDOF_MASK(KINDOF_FS_AIRFIELD), KINDOFMASK_NONE); + PartitionFilterRejectByObjectStatus filterStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_UNDER_CONSTRUCTION ), OBJECT_STATUS_MASK_NONE ); + PartitionFilterRejectByObjectStatus filterStatusTwo( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_SOLD ), OBJECT_STATUS_MASK_NONE ); // Independent to make it an OR + PartitionFilterRelationship filterTeam(jet, PartitionFilterRelationship::ALLOW_ALLIES); + PartitionFilterAlive filterAlive; + PartitionFilterSameMapStatus filterMapStatus(jet); + PartitionFilterHasParkingPlace filterPP(jet->getID()); + + PartitionFilter *filters[16]; + Int numFilters = 0; + filters[numFilters++] = &filterKind; + filters[numFilters++] = &filterStatus; + filters[numFilters++] = &filterStatusTwo; + filters[numFilters++] = &filterTeam; + filters[numFilters++] = &filterAlive; + filters[numFilters++] = &filterPP; + filters[numFilters++] = &filterMapStatus; + filters[numFilters] = NULL; + + return ThePartitionManager->getClosestObject( jet, HUGE_DIST, FROM_CENTER_2D, filters ); +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +/* + Success: we have runway clearance + Failure: no runway clearance +*/ +class JetAwaitingRunwayState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetAwaitingRunwayState, "JetAwaitingRunwayState") +protected: + // snapshot interface STUBBED. + virtual void crc( Xfer *xfer ){}; + virtual void xfer( Xfer *xfer ){XferVersion cv = 1; XferVersion v = cv; xfer->xferVersion( &v, cv );} + virtual void loadPostProcess(){}; +private: + const Bool m_landing; + +public: + JetAwaitingRunwayState( StateMachine *machine, Bool landing ) : m_landing(landing), State( machine, "JetAwaitingRunwayState") { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + jetAI->friend_setTakeoffInProgress(!m_landing); + jetAI->friend_setLandingInProgress(m_landing); + jetAI->friend_setAllowCircling(true); + return STATE_CONTINUE; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp == NULL) + { + // no producer? just skip this step. + return STATE_SUCCESS; + } + + // gotta reserve a space in order to reserve a runway + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), NULL)) + { + DEBUG_ASSERTCRASH(m_landing, ("hmm, this should never happen for taking-off things")); + return STATE_FAILURE; + } + + if (pp->reserveRunway(jet->getID(), m_landing)) + { + return STATE_SUCCESS; + } + else if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) && !m_landing ) + { + //If we're trying to take off an aircraft carrier and fail to reserve a + //runway, it's because we need to be at the front of the carrier queue. + //Therefore, we need to move forward whenever possible until we are in + //the front. + Coord3D bestPos; + if( pp->calcBestParkingAssignment( jet->getID(), &bestPos ) ) + { + jetAI->friend_setTaxiInProgress(true); + jetAI->friend_setAllowAirLoco(false); + jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING); + + jetAI->destroyPath(); + Path *movePath; + movePath = newInstance(Path); + Coord3D pos = *jet->getPosition(); + movePath->prependNode( &pos, LAYER_GROUND ); + movePath->markOptimized(); + movePath->appendNode( &bestPos, LAYER_GROUND ); + + TheAI->pathfinder()->setDebugPath(movePath); + + jetAI->friend_setPath( movePath ); + DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco")); + jetAI->getCurLocomotor()->setUsePreciseZPos(true); + jetAI->getCurLocomotor()->setUltraAccurate(true); + jetAI->getCurLocomotor()->setAllowInvalidPosition(true); + jetAI->ignoreObstacleID(jet->getProducerID()); + } + } + + // can't get a runway? gotta wait. + jetAI->setLocomotorGoalNone(); + return STATE_CONTINUE; + } + + virtual void onExit(StateExitType status) + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if (jetAI) + { + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + jetAI->friend_setAllowCircling(false); + } + } + +}; +EMPTY_DTOR(JetAwaitingRunwayState) + +//------------------------------------------------------------------------------------------------- +/* + Success: a new suitable airfield has appeared + Failure: shouldn't normally happen +*/ +class JetOrHeliCirclingDeadAirfieldState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliCirclingDeadAirfieldState, "JetOrHeliCirclingDeadAirfieldState") +protected: + // snapshot interface STUBBED. + // The state will check immediately after a load game, but I think that's ok. jba. + virtual void crc( Xfer *xfer ){}; + virtual void xfer( Xfer *xfer ){XferVersion cv = 1; XferVersion v = cv; xfer->xferVersion( &v, cv );} + virtual void loadPostProcess(){}; + +private: + Int m_checkAirfield; + + enum + { + // only recheck for new airfields every second or so + HOW_OFTEN_TO_CHECK = LOGICFRAMES_PER_SECOND + }; + +public: + JetOrHeliCirclingDeadAirfieldState( StateMachine *machine ) : + State( machine, "JetOrHeliCirclingDeadAirfieldState"), + m_checkAirfield(0) { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + { + return STATE_FAILURE; + } + + // obscure case: if the jet wasn't spawned, but just placed directly on the map, + // it might not have an owning airfield, and it might be trying to return + // simply due to being idle, not out of ammo. so check and don't die in that + // case, but just punt back out to idle. + if (!jetAI->isOutOfSpecialReloadAmmo() && jet->getProducerID() == INVALID_ID) + { + return STATE_FAILURE; + } + + // just stay where we are. + jetAI->setLocomotorGoalNone(); + + m_checkAirfield = HOW_OFTEN_TO_CHECK; + + //Play the "low fuel" voice whenever the craft is circling above the airfield. + AudioEventRTS soundToPlay = *jet->getTemplate()->getPerUnitSound( "VoiceLowFuel" ); + soundToPlay.setObjectID( jet->getID() ); + TheAudio->addAudioEvent( &soundToPlay ); + + return STATE_CONTINUE; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + { + return STATE_FAILURE; + } + + // just stay where we are. + jetAI->setLocomotorGoalNone(); + + Real damageRate = jetAI->friend_getOutOfAmmoDamagePerSecond(); + if (damageRate > 0) + { + // convert to damage/sec to damage/frame + damageRate *= SECONDS_PER_LOGICFRAME_REAL; + // since it's a percentage, multiply times the max health + damageRate *= jet->getBodyModule()->getMaxHealth(); + + DamageInfo damageInfo; + damageInfo.in.m_damageType = DAMAGE_UNRESISTABLE; + damageInfo.in.m_deathType = DEATH_NORMAL; + damageInfo.in.m_sourceID = INVALID_ID; + damageInfo.in.m_amount = damageRate; + jet->attemptDamage( &damageInfo ); + } + + if (--m_checkAirfield <= 0) + { + m_checkAirfield = HOW_OFTEN_TO_CHECK; + Object* airfield = findSuitableAirfield( jet ); + if (airfield) + { + jet->setProducer(airfield); + return STATE_SUCCESS; + } + } + + return STATE_CONTINUE; + } + +}; +EMPTY_DTOR(JetOrHeliCirclingDeadAirfieldState) + +//------------------------------------------------------------------------------------------------- +/* + Success: we returned to the dead-airfield location + Failure: shouldn't normally happen +*/ +class JetOrHeliReturningToDeadAirfieldState : public AIInternalMoveToState +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliReturningToDeadAirfieldState, "JetOrHeliReturningToDeadAirfieldState") +public: + JetOrHeliReturningToDeadAirfieldState( StateMachine *machine ) : AIInternalMoveToState( machine, "JetOrHeliReturningToDeadAirfieldState") { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + { + return STATE_FAILURE; + } + + setAdjustsDestination(true); + m_goalPosition = *jetAI->friend_getProducerLocation(); + + return AIInternalMoveToState::onEnter(); + } + +}; +EMPTY_DTOR(JetOrHeliReturningToDeadAirfieldState) + +//------------------------------------------------------------------------------------------------- +// This solution uses the +// http://www.faqs.org/faqs/graphics/algorithms-faq/ +// Subject 1.03 +static Bool intersectInfiniteLine2D +( + Real ax, Real ay, Real ao, + Real cx, Real cy, Real co, + Real& ix, Real& iy +) +{ + Real bx = ax + Cos(ao); + Real by = ay + Sin(ao); + Real dx = cx + Cos(co); + Real dy = cy + Sin(co); + + Real denom = ((bx - ax) * (dy - cy) - (by - ay) * (dx - cx)); + if (denom == 0.0f) + { + // the lines are parallel. + return false; + } + + // The lines intersect. + Real r = ((ay - cy) * (dx - cx) - (ax - cx) * (dy - cy) ) / denom; + ix = ax + r * (bx - ax); + iy = ay + r * (by - ay); + return true; +} + +//------------------------------------------------------------------------------------------------- +/* + Success: we are on the ground at the runway start + Failure: we are unable to get on the ground +*/ +class JetOrHeliTaxiState : public AIMoveOutOfTheWayState +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliTaxiState, "JetOrHeliTaxiState") +private: + TaxiType m_taxiMode; +public: + JetOrHeliTaxiState( StateMachine *machine, TaxiType m ) : m_taxiMode(m), AIMoveOutOfTheWayState( machine ) { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + jetAI->setCanPathThroughUnits(true); + jetAI->friend_setTakeoffInProgress(m_taxiMode != TO_PARKING); + jetAI->friend_setLandingInProgress(m_taxiMode == TO_PARKING); + jetAI->friend_setTaxiInProgress(true); + + if( m_taxiMode == TO_PARKING ) + { + //Instantly reload flares. + CountermeasuresBehaviorInterface *cbi = jet->getCountermeasuresBehaviorInterface(); + if( cbi ) + { + cbi->reloadCountermeasures(); + } + } + + jetAI->friend_setAllowAirLoco(false); + jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING); + DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco")); + + Object* airfield; + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID(), &airfield); + if (pp == NULL) + return STATE_SUCCESS; // no airfield? just skip this step. + + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) + return STATE_FAILURE; // full? + + Coord3D intermedPt; + Bool intermed = false; + Real orient = atan2(ppinfo.runwayPrep.y - ppinfo.parkingSpace.y, ppinfo.runwayPrep.x - ppinfo.parkingSpace.x); + + + if (fabs(stdAngleDiff(orient, ppinfo.parkingOrientation)) > PI/128) + { + intermedPt.z = (ppinfo.parkingSpace.z + ppinfo.runwayPrep.z) * 0.5f; + intermed = intersectInfiniteLine2D( + ppinfo.parkingSpace.x, ppinfo.parkingSpace.y, ppinfo.parkingOrientation, + ppinfo.runwayPrep.x, ppinfo.runwayPrep.y, ppinfo.parkingOrientation + PI/2, + intermedPt.x, intermedPt.y); + } + + jetAI->destroyPath(); + Path *movePath; + movePath = newInstance(Path); + Coord3D pos = *jet->getPosition(); + movePath->prependNode( &pos, LAYER_GROUND ); + movePath->markOptimized(); + + if (m_taxiMode == TO_PARKING) + { + if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) + { + //We're on an aircraft carrier. + const std::vector *pTaxiLocations = pp->getTaxiLocations( jet->getID() ); + if( pTaxiLocations ) + { + std::vector::const_iterator it; + for( it = pTaxiLocations->begin(); it != pTaxiLocations->end(); it++ ) + { + movePath->appendNode( &(*it), LAYER_GROUND ); + } + } + + //We just landed... see if we can get a better space forward so we don't stop and pause + //at our initially assigned spot. + Coord3D pos; + pp->calcBestParkingAssignment( jet->getID(), &pos ); + + movePath->appendNode( &pos, LAYER_GROUND ); + } + else + { + //We're on a normal airfield + movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); + if (intermed) + movePath->appendNode( &intermedPt, LAYER_GROUND ); + movePath->appendNode( &ppinfo.parkingSpace, LAYER_GROUND ); + } + } + else if (m_taxiMode == FROM_PARKING) + { + if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) + { + if( !(ppinfo.runwayStart == ppinfo.runwayPrep) ) + { + movePath->appendNode( &ppinfo.runwayStart, LAYER_GROUND ); + } + } + else + { + if (intermed) + movePath->appendNode( &intermedPt, LAYER_GROUND ); + movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); + movePath->appendNode( &ppinfo.runwayStart, LAYER_GROUND ); + } + } + else if (m_taxiMode == FROM_HANGAR) + { + if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) + { + //Aircraft carrier + if( jet->testStatus( OBJECT_STATUS_REASSIGN_PARKING ) ) + { + //This status means we are being reassigned a parking space. We're not actually moving from the + //hangar. So simply move to the new parking spot which was just switched from under us in + //FlightDeckBehavior::update() + jet->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_REASSIGN_PARKING ) ); + movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); + } + else + { + const std::vector *pCreationLocations = pp->getCreationLocations( jet->getID() ); + if( !pCreationLocations ) + { + DEBUG_CRASH( ("No creation locations specified for runway for JetAIBehavior -- taxiing from hanger (Kris).") ); + return STATE_FAILURE; + } + std::vector::const_iterator it; + Bool firstNode = TRUE; + for( it = pCreationLocations->begin(); it != pCreationLocations->end(); it++ ) + { + if( firstNode ) + { + //Skip the first node because it's the creation location. + firstNode = FALSE; + continue; + } + movePath->appendNode( &(*it), LAYER_GROUND ); + } + movePath->appendNode( &ppinfo.runwayPrep, LAYER_GROUND ); + } + } + else + { + //Airfield + movePath->appendNode( &ppinfo.parkingSpace, LAYER_GROUND ); + } + } + + m_waitingForPath = FALSE; + TheAI->pathfinder()->setDebugPath(movePath); + + setAdjustsDestination(false); // precision is necessary + + jetAI->friend_setPath( movePath ); + DEBUG_ASSERTCRASH(jetAI->getCurLocomotor(), ("no loco")); + jetAI->getCurLocomotor()->setUsePreciseZPos(true); + jetAI->getCurLocomotor()->setUltraAccurate(true); + jetAI->getCurLocomotor()->setAllowInvalidPosition(true); + jetAI->ignoreObstacleID(jet->getProducerID()); + + StateReturnType ret = AIMoveOutOfTheWayState::onEnter(); + return ret; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + if( m_taxiMode == TO_PARKING || m_taxiMode == FROM_HANGAR ) + { + //Keep checking to see if there is a better spot as it moves forward. If we find a better spot, then + //append the position to our move. + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + Coord3D bestPos; + Int oldIndex, newIndex; + // Check pp for null, as it is possible for your airfield to get destroyed while taxiing.jba [8/27/2003] + if( pp!=NULL && pp->calcBestParkingAssignment( jet->getID(), &bestPos, &oldIndex, &newIndex ) ) + { + Path *path = jetAI->friend_getPath(); + if( path ) + { + path->appendNode( &bestPos, LAYER_GROUND ); + } + } + } + + return AIMoveOutOfTheWayState::update(); + } + + virtual void onExit( StateExitType status ) + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if (jetAI) + { + jetAI->getCurLocomotor()->setUsePreciseZPos(false); + jetAI->getCurLocomotor()->setUltraAccurate(false); + jetAI->getCurLocomotor()->setAllowInvalidPosition(false); + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + jetAI->friend_setTaxiInProgress(false); + jetAI->setCanPathThroughUnits(false); + } + + AIMoveOutOfTheWayState::onExit(status); + } + +}; +EMPTY_DTOR(JetOrHeliTaxiState) + +//------------------------------------------------------------------------------------------------- +/* + Success: we are on the ground at the runway start + Failure: we are unable to get on the ground +*/ +class JetTakeoffOrLandingState : public AIFollowPathState +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetTakeoffOrLandingState, "JetTakeoffOrLandingState") +private: + Real m_maxLift; + Real m_maxSpeed; +#ifdef CIRCLE_FOR_LANDING + Coord3D m_circleForLandingPos; +#endif + Bool m_landing; + Bool m_landingSoundPlayed; + +public: + JetTakeoffOrLandingState( StateMachine *machine, Bool landing ) : m_landing(landing), AIFollowPathState( machine, "JetTakeoffOrLandingState" ) { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if (!jetAI) + return STATE_FAILURE; + + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + jetAI->friend_setTakeoffInProgress(!m_landing); + jetAI->friend_setLandingInProgress(m_landing); + jetAI->friend_setAllowAirLoco(true); + jetAI->chooseLocomotorSet(LOCOMOTORSET_NORMAL); + Locomotor* loco = jetAI->getCurLocomotor(); + DEBUG_ASSERTCRASH(loco, ("no loco")); + loco->setMaxLift(BIGNUM); + BodyDamageType bdt = jet->getBodyModule()->getDamageState(); + m_maxLift = loco->getMaxLift(bdt); + m_maxSpeed = loco->getMaxSpeedForCondition(bdt); + m_landingSoundPlayed = FALSE; + if (m_landing) + { + loco->setMaxSpeed(loco->getMinSpeed()); + } + else + { + loco->setMaxLift(0); + } + loco->setUsePreciseZPos(true); + loco->setUltraAccurate(true); + jetAI->ignoreObstacleID(jet->getProducerID()); + + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp == NULL) + return STATE_SUCCESS; // no airfield? just skip this step + + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) + { + // it's full. + return STATE_FAILURE; + } + + // only check this for landing; we might have already given up the reservation to the guy behind us for takeoff + if (m_landing) + { + if (!pp->reserveRunway(jet->getID(), m_landing)) + { + DEBUG_CRASH(("we should never get to this state unless we have a runway available")); + return STATE_FAILURE; + } + } + + std::vector path; + if (m_landing) + { +#ifdef CIRCLE_FOR_LANDING + m_circleForLandingPos = ppinfo.runwayApproach; + m_circleForLandingPos.z = (ppinfo.runwayEnd.z + ppinfo.runwayApproach.z)*0.5f; +#else + path.push_back(ppinfo.runwayApproach); +#endif + if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) + { + //Assigned to an aircraft carrier which has separate landing strips. + path.push_back( ppinfo.runwayLandingStart ); + path.push_back( ppinfo.runwayLandingEnd ); + } + else + { + //Assigned to an airstrip -- land the same way we took off but in reverse. + path.push_back(ppinfo.runwayEnd); + path.push_back(ppinfo.runwayStart); + } + } + else + { + ppinfo.runwayEnd.z = ppinfo.runwayApproach.z; + path.push_back(ppinfo.runwayEnd); + path.push_back(ppinfo.runwayExit); + } + + setAdjustsDestination(false); // precision is necessary + setAdjustFinalDestination(false); // especially at the endpoint! + + jetAI->friend_setGoalPath( &path ); + + StateReturnType ret = AIFollowPathState::onEnter(); + + return ret; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + if (m_landing) + { +#ifdef CIRCLE_FOR_LANDING + if (jet->getPosition()->z > m_circleForLandingPos.z) + { + const Real THRESH = 4.0f; + jetAI->getCurLocomotor()->setAltitudeChangeThresholdForCircling(THRESH); + jetAI->setLocomotorGoalPositionExplicit(m_circleForLandingPos); + return STATE_CONTINUE; + } + else +#endif + { + jetAI->getCurLocomotor()->setMaxLift(BIGNUM); +#ifdef CIRCLE_FOR_LANDING + jetAI->getCurLocomotor()->setAltitudeChangeThresholdForCircling(0); +#endif + } + + if( !m_landingSoundPlayed ) + { + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + Real zPos = jet->getPosition()->z; + Real zSlop = 0.25f; + PathfindLayerEnum layer = TheTerrainLogic->getHighestLayerForDestination( jet->getPosition() ); + Real groundZ = TheTerrainLogic->getLayerHeight( jet->getPosition()->x, jet->getPosition()->y, layer ); + if( pp ) + { + groundZ += pp->getLandingDeckHeightOffset(); + } + + if( zPos - zSlop <= groundZ ) + { + m_landingSoundPlayed = TRUE; + AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_aircraftWheelScreech; + soundToPlay.setPosition( jet->getPosition() ); + TheAudio->addAudioEvent( &soundToPlay ); + } + } + } + else + { + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp) + pp->transferRunwayReservationToNextInLineForTakeoff(jet->getID()); + + //Calculate the distance of the jet from the end of the runway as a ratio from the start. + //As it approaches the end of the runway, the plane will gain more lift, even if it's already + //going quickly. Using speed for lift is bad in the case of the aircraft carrier, because + //we don't want it to take off quickly. + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + pp->calcPPInfo( jet->getID(), &ppinfo ); + Coord3D vector = ppinfo.runwayEnd; + vector.sub( jet->getPosition() ); + Real dist = vector.length(); + + Real ratio = 1.0f - (dist / ppinfo.runwayTakeoffDist); + ratio *= ratio; //dampen it.... + if (ratio < 0.0f) ratio = 0.0f; + if (ratio > 1.0f) ratio = 1.0f; + jetAI->getCurLocomotor()->setMaxLift(m_maxLift * ratio); + } + + StateReturnType ret = AIFollowPathState::update(); + return ret; + } + + virtual void onExit( StateExitType status ) + { + AIFollowPathState::onExit(status); + + // just in case. + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return; + + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + jetAI->friend_enableAfterburners(false); + + // Paranoia checks - sometimes onExit is called when we are + // shutting down, and not all pieces are valid. CurLocomotor + // is definitely null in some cases. jba. + Locomotor* loco = jetAI->getCurLocomotor(); + if (loco) + { + loco->setUsePreciseZPos(false); + loco->setUltraAccurate(false); + // don't restore lift if dead -- this may fight with JetSlowDeathBehavior! + if (!jet->isEffectivelyDead()) + loco->setMaxLift(BIGNUM); +#ifdef CIRCLE_FOR_LANDING + loco->setAltitudeChangeThresholdForCircling(0); +#endif + } + jetAI->ignoreObstacleID(INVALID_ID); + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (!m_landing) + { + if (pp && !jetAI->friend_keepsParkingSpaceWhenAirborne()) + pp->releaseSpace(jet->getID()); + } + if (pp) + pp->releaseRunway(jet->getID()); + } +}; +EMPTY_DTOR(JetTakeoffOrLandingState) + +//------------------------------------------------------------------------------------------------- +static Real calcDistSqr(const Coord3D& a, const Coord3D& b) +{ + return sqr(a.x-b.x) + sqr(a.y-b.y) + sqr(a.z-b.z); +} + +//------------------------------------------------------------------------------------------------- +/* + Success: we are on the ground at the runway start + Failure: we are unable to get on the ground +*/ +class HeliTakeoffOrLandingState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(HeliTakeoffOrLandingState, "HeliTakeoffOrLandingState") +protected: + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty. jba. + } + + virtual void xfer( Xfer *xfer ) + { + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + // set on create. xfer->xferBool(&m_landing); + xfer->xferCoord3D(&m_path[0]); + xfer->xferCoord3D(&m_path[1]); + xfer->xferInt(&m_index); + xfer->xferCoord3D(&m_parkingLoc); + xfer->xferReal(&m_parkingOrientation); + } + virtual void loadPostProcess() + { + // empty. jba. + } + +private: + Coord3D m_path[2]; + Int m_index; + Coord3D m_parkingLoc; + Real m_parkingOrientation; + Bool m_landing; +public: + HeliTakeoffOrLandingState( StateMachine *machine, Bool landing ) : m_landing(landing), + State( machine, "HeliTakeoffOrLandingState" ), m_index(0) + { + m_parkingLoc.zero(); + } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + jetAI->friend_setTakeoffInProgress(!m_landing); + jetAI->friend_setLandingInProgress(m_landing); + jetAI->friend_setAllowAirLoco(true); + jetAI->chooseLocomotorSet(LOCOMOTORSET_NORMAL); + + Locomotor* loco = jetAI->getCurLocomotor(); + DEBUG_ASSERTCRASH(loco, ("no loco")); + loco->setUsePreciseZPos(true); + loco->setUltraAccurate(true); + jetAI->ignoreObstacleID(jet->getProducerID()); + + Object* airfield; + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID(), &airfield); + if (pp == NULL) + return STATE_SUCCESS; // no airfield? just skip this step + + Coord3D landingApproach; + if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) + { + if (m_landing) + { + m_parkingLoc = jetAI->friend_getLandingPosForHelipadStuff(); + m_parkingOrientation = jet->getOrientation(); + } + else + { + m_parkingOrientation = jet->getOrientation(); + m_parkingLoc = *jet->getPosition(); + } + landingApproach = m_parkingLoc; + landingApproach.z += pp->getApproachHeight() + pp->getLandingDeckHeightOffset(); + } + else + { + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) + return STATE_FAILURE; + m_parkingLoc = ppinfo.parkingSpace; + m_parkingOrientation = ppinfo.parkingOrientation; + landingApproach = m_parkingLoc; + landingApproach.z += (ppinfo.runwayApproach.z - ppinfo.runwayEnd.z); + } + + if (m_landing) + { + m_path[0] = landingApproach; + m_path[1] = m_parkingLoc; + } + else + { + m_path[0] = m_parkingLoc; + m_path[1] = landingApproach; + m_path[1].z = landingApproach.z; + } + m_index = 0; + + return STATE_CONTINUE; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + +// I have disabled this because it is no longer necessary and is a bit funky lookin' (srj) +#ifdef NOT_IN_USE + // magically position it correctly. + jet->getPhysics()->scrubVelocity2D(0); + Coord3D hoverloc = m_path[m_index]; + hoverloc.z = jet->getPosition()->z; +#if 1 + Coord3D pos = *jet->getPosition(); + Real dx = hoverloc.x - pos.x; + Real dy = hoverloc.y - pos.y; + Real dSqr = dx*dx+dy*dy; + const Real DARN_CLOSE = 0.25f; + if (dSqr < DARN_CLOSE) + { + jet->setPosition(&hoverloc); + } + else + { + Real dist = sqrtf(dSqr); + if (dist<1) dist = 1; + pos.x += PATHFIND_CELL_SIZE_F*dx/(dist*LOGICFRAMES_PER_SECOND); + pos.y += PATHFIND_CELL_SIZE_F*dy/(dist*LOGICFRAMES_PER_SECOND); + jet->setPosition(&pos); + } +#else + jet->setPosition(&hoverloc); +#endif + jet->setOrientation(m_parkingOrientation); +#endif + + if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) || !m_landing) + { + TheAI->pathfinder()->adjustDestination(jet, jetAI->getLocomotorSet(), &m_path[m_index]); + TheAI->pathfinder()->updateGoal(jet, &m_path[m_index], LAYER_GROUND); + } + + jetAI->setLocomotorGoalPositionExplicit(m_path[m_index]); + + const Real THRESH = 3.0f; + const Real THRESH_SQR = THRESH*THRESH; + const Coord3D* a = jet->getPosition(); + const Coord3D* b = &m_path[m_index]; + Real distSqr = calcDistSqr(*a, *b); + if (distSqr <= THRESH_SQR) + ++m_index; + + if (m_index >= 2) + return STATE_SUCCESS; + + return STATE_CONTINUE; + } + + virtual void onExit( StateExitType status ) + { + // just in case. + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return; + + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + + // Paranoia checks - sometimes onExit is called when we are + // shutting down, and not all pieces are valid. CurLocomotor + // is definitely null in some cases. jba. + Locomotor* loco = jetAI->getCurLocomotor(); + if (loco) + { + loco->setUsePreciseZPos(false); + loco->setUltraAccurate(false); + // don't restore lift if dead -- this may fight with JetSlowDeathBehavior! + if (!jet->isEffectivelyDead()) + loco->setMaxLift(BIGNUM); + } + + jetAI->ignoreObstacleID(INVALID_ID); + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (m_landing) + { + jetAI->friend_setAllowAirLoco(false); + jetAI->chooseLocomotorSet(LOCOMOTORSET_TAXIING); + } + else + { + if (pp && !jetAI->friend_keepsParkingSpaceWhenAirborne()) + pp->releaseSpace(jet->getID()); + } + } + +}; +EMPTY_DTOR(HeliTakeoffOrLandingState) + +//------------------------------------------------------------------------------------------------- +class JetOrHeliParkOrientState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliParkOrientState, "JetOrHeliParkOrientState") +protected: + // snapshot interface STUBBED. + virtual void crc( Xfer *xfer ){}; + virtual void xfer( Xfer *xfer ){XferVersion cv = 1; XferVersion v = cv; xfer->xferVersion( &v, cv );} + virtual void loadPostProcess(){}; + +public: + JetOrHeliParkOrientState( StateMachine *machine ) : State( machine, "JetOrHeliParkOrientState") { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) + { + return STATE_SUCCESS; + } + + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(true); + + jetAI->ignoreObstacleID(jet->getProducerID()); + return STATE_CONTINUE; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + { + return STATE_FAILURE; + } + + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp == NULL) + return STATE_FAILURE; + + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) + return STATE_FAILURE; + + const Real THRESH = 0.001f; + if (fabs(stdAngleDiff(jet->getOrientation(), ppinfo.parkingOrientation)) <= THRESH) + return STATE_SUCCESS; + + // magically position it correctly. + jet->getPhysics()->scrubVelocity2D(0); + Coord3D hoverloc = ppinfo.parkingSpace; + if( jet->testStatus( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) + { + hoverloc = ppinfo.runwayPrep; + } + + hoverloc.z = jet->getPosition()->z; + jet->setPosition(&hoverloc); + + jetAI->setLocomotorGoalOrientation(ppinfo.parkingOrientation); + + return STATE_CONTINUE; + } + + virtual void onExit( StateExitType status ) + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return; + + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + jetAI->ignoreObstacleID(INVALID_ID); + } +}; +EMPTY_DTOR(JetOrHeliParkOrientState) + +//------------------------------------------------------------------------------------------------- +class JetPauseBeforeTakeoffState : public AIFaceState +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetPauseBeforeTakeoffState, "JetPauseBeforeTakeoffState") +protected: + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty. jba. + } + + virtual void xfer( Xfer *xfer ) + { + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + // set on create. xfer->xferBool(&m_landing); + xfer->xferUnsignedInt(&m_when); + xfer->xferUnsignedInt(&m_whenTransfer); + xfer->xferBool(&m_afterburners); + xfer->xferBool(&m_resetTimer); + xfer->xferObjectID(&m_waitedForTaxiID); + } + virtual void loadPostProcess() + { + // empty. jba. + } + +private: + UnsignedInt m_when; + UnsignedInt m_whenTransfer; + ObjectID m_waitedForTaxiID; + Bool m_resetTimer; + Bool m_afterburners; + + Bool findWaiter() + { + Object* jet = getMachineOwner(); + ParkingPlaceBehaviorInterface* pp = getPP(getMachineOwner()->getProducerID()); + if (pp) + { + Int count = pp->getRunwayCount(); + for (Int i = 0; i < count; ++i) + { + Object* otherJet = TheGameLogic->findObjectByID( pp->getRunwayReservation( i, RESERVATION_TAKEOFF ) ); + if (otherJet == NULL || otherJet == jet) + continue; + + AIUpdateInterface* ai = otherJet->getAIUpdateInterface(); + if (ai == NULL) + continue; + + if (ai->getCurrentStateID() == TAXI_TO_TAKEOFF) + { + if (m_waitedForTaxiID == INVALID_ID) + { + m_waitedForTaxiID = otherJet->getID(); + } + return true; + } + } + } + return false; + } + +public: + JetPauseBeforeTakeoffState( StateMachine *machine ) : + AIFaceState(machine, false), + m_when(0), + m_whenTransfer(0), + m_waitedForTaxiID(INVALID_ID), + m_resetTimer(false), + m_afterburners(false) + { + // nothing + } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + jetAI->friend_setTakeoffInProgress(true); + jetAI->friend_setLandingInProgress(false); + + m_when = 0; + m_whenTransfer = 0; + m_waitedForTaxiID = INVALID_ID; + m_resetTimer = false; + m_afterburners = false; + + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp == NULL) + return STATE_SUCCESS; // no airfield? just skip this step. + + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) + return STATE_SUCCESS; // full? + + getMachine()->setGoalPosition(&ppinfo.runwayEnd); + + return AIFaceState::onEnter(); + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if (jet->isEffectivelyDead()) + return STATE_FAILURE; + + // always call this. + StateReturnType superStatus = AIFaceState::update(); + + if (findWaiter()) + return STATE_CONTINUE; + + UnsignedInt now = TheGameLogic->getFrame(); + if (!m_resetTimer) + { + // we had to wait, but now everyone else is ready, so restart our countdown. + m_when = now + jetAI->friend_getTakeoffPause(); + if (m_waitedForTaxiID == INVALID_ID) + { + m_waitedForTaxiID = jet->getID(); // just so we don't pick up anyone else + m_whenTransfer = now + 1; + } + else + { + m_whenTransfer = now + 2; // 2 seems odd, but is correct + } + m_resetTimer = true; + } + + if (!m_afterburners) + { + jetAI->friend_enableAfterburners(true); + m_afterburners = true; + } + + DEBUG_ASSERTCRASH(m_when != 0, ("hmm")); + DEBUG_ASSERTCRASH(m_whenTransfer != 0, ("hmm")); + + // once we start the final wait, release the runways for guys behind us, so they can start taxiing + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp && now >= m_whenTransfer) + { + pp->transferRunwayReservationToNextInLineForTakeoff(jet->getID()); + } + + if (now >= m_when) + return superStatus; + + return STATE_CONTINUE; + } + + virtual void onExit(StateExitType status) + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + AIFaceState::onExit(status); + } + +}; +EMPTY_DTOR(JetPauseBeforeTakeoffState) + +//------------------------------------------------------------------------------------------------- +class JetOrHeliReloadAmmoState : public State +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliReloadAmmoState, "JetOrHeliReloadAmmoState") +private: + UnsignedInt m_reloadTime; + UnsignedInt m_reloadDoneFrame; + +protected: + + // snapshot interface + virtual void crc( Xfer *xfer ) + { + // empty. jba. + } + + virtual void xfer( Xfer *xfer ) + { + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + // set on create. xfer->xferBool(&m_landing); + xfer->xferUnsignedInt(&m_reloadTime); + xfer->xferUnsignedInt(&m_reloadDoneFrame); + } + virtual void loadPostProcess() + { + // empty. jba. + } + +public: + JetOrHeliReloadAmmoState( StateMachine *machine ) : State( machine, "JetOrHeliReloadAmmoState") { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + if( !jetAI ) + return STATE_FAILURE; + + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + jetAI->friend_setUseSpecialReturnLoco(false); + + // AW: Workaround for VTOL aircraft rotating towards 0 degrees on reloading. + if (!jetAI->friend_needsRunway()) { + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + if ((pp) && pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) { + // DEBUG_LOG((">> JetOrHeliReloadAmmoState - onEnter - parkingOrientation = %f.\n", ppinfo.parkingOrientation)); + jetAI->setLocomotorGoalOrientation(ppinfo.parkingOrientation); + } + } + + m_reloadTime = 0; + for (Int i = 0; i < WEAPONSLOT_COUNT; ++i) + { + const Weapon* w = jet->getWeaponInWeaponSlot((WeaponSlotType)i); + if (w == NULL) + continue; + + Int remaining = w->getRemainingAmmo(); + Int clipSize = w->getClipSize(); + Int rt = w->getClipReloadTime(jet); + if (clipSize > 0) + { + // bias by amount empty. + Int needed = clipSize - remaining; + rt = (rt * needed) / clipSize; + } + if (rt > m_reloadTime) + m_reloadTime = rt; + } + + if (m_reloadTime < 1) + m_reloadTime = 1; + m_reloadDoneFrame = m_reloadTime + TheGameLogic->getFrame(); + return STATE_CONTINUE; + } + + virtual StateReturnType update() + { + Object* jet = getMachineOwner(); + + UnsignedInt now = TheGameLogic->getFrame(); + Bool allDone = true; + for (Int i = 0; i < WEAPONSLOT_COUNT; ++i) + { + Weapon* w = jet->getWeaponInWeaponSlot((WeaponSlotType)i); + if (w == NULL) + continue; + + if (now >= m_reloadDoneFrame) + w->setClipPercentFull(1.0f, false); + else + w->setClipPercentFull((Real)(m_reloadTime - (m_reloadDoneFrame - now)) / m_reloadTime, false); + + if (w->getRemainingAmmo() != w->getClipSize()) + allDone = false; + } + + if (allDone) + return STATE_SUCCESS; + + return STATE_CONTINUE; + } + + virtual void onExit(StateExitType status) + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + jetAI->friend_setTakeoffInProgress(false); + jetAI->friend_setLandingInProgress(false); + } + +}; +EMPTY_DTOR(JetOrHeliReloadAmmoState) + +//------------------------------------------------------------------------------------------------- +/* + Success: we are close enough to a friendly airfield to land + Failure: we are unable to get close enough to a friendly airfield to land +*/ +class JetOrHeliReturnForLandingState : public AIInternalMoveToState +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(JetOrHeliReturnForLandingState, "JetOrHeliReturnForLandingState") +public: + JetOrHeliReturnForLandingState( StateMachine *machine ) : AIInternalMoveToState( machine, "JetOrHeliReturnForLandingState") { } + + virtual StateReturnType onEnter() + { + Object* jet = getMachineOwner(); + JetAIUpdate* jetAI = (JetAIUpdate*)jet->getAIUpdateInterface(); + + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (pp == NULL) + { + // nuke the producer id, since it's dead + jet->setProducer(NULL); + + Object* airfield = findSuitableAirfield( jet ); + pp = airfield ? getPP(airfield->getID()) : NULL; + if (airfield && pp) + { + jet->setProducer(airfield); + } + else + { + return STATE_FAILURE; + } + } + + if (jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) + { + m_goalPosition = jetAI->friend_getLandingPosForHelipadStuff(); + } + else + { + ParkingPlaceBehaviorInterface::PPInfo ppinfo; + if (!pp->reserveSpace(jet->getID(), jetAI->friend_getParkingOffset(), &ppinfo)) + return STATE_FAILURE; + + m_goalPosition = jetAI->friend_needsRunway() ? ppinfo.runwayApproach : ppinfo.parkingSpace; + } + setAdjustsDestination(false); // precision is necessary + + return AIInternalMoveToState::onEnter(); + } +}; +EMPTY_DTOR(JetOrHeliReturnForLandingState) + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +class JetAIStateMachine : public AIStateMachine +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( JetAIStateMachine, "JetAIStateMachine" ); + +public: + JetAIStateMachine( Object *owner, AsciiString name ); + +}; + +//------------------------------------------------------------------------------------------------- +JetAIStateMachine::JetAIStateMachine(Object *owner, AsciiString name) : AIStateMachine(owner, name) +{ + defineState( RETURNING_FOR_LANDING, newInstance(JetOrHeliReturnForLandingState)( this ), LANDING_AWAIT_CLEARANCE, RETURN_TO_DEAD_AIRFIELD ); + defineState( TAKING_OFF_AWAIT_CLEARANCE, newInstance(JetAwaitingRunwayState)( this, false ), TAXI_TO_TAKEOFF, AI_IDLE ); + defineState( TAXI_TO_TAKEOFF, newInstance(JetOrHeliTaxiState)( this, FROM_PARKING ), PAUSE_BEFORE_TAKEOFF, AI_IDLE ); + defineState( PAUSE_BEFORE_TAKEOFF, newInstance(JetPauseBeforeTakeoffState)( this ), TAKING_OFF, AI_IDLE ); + defineState( TAKING_OFF, newInstance(JetTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE ); + defineState( LANDING_AWAIT_CLEARANCE, newInstance(JetAwaitingRunwayState)( this, true ), LANDING, AI_IDLE ); + defineState( LANDING, newInstance(JetTakeoffOrLandingState)( this, true ), TAXI_FROM_LANDING, AI_IDLE ); + defineState( TAXI_FROM_LANDING, newInstance(JetOrHeliTaxiState)( this, TO_PARKING ), ORIENT_FOR_PARKING_PLACE, AI_IDLE ); + defineState( TAXI_FROM_HANGAR, newInstance(JetOrHeliTaxiState)( this, FROM_HANGAR ), ORIENT_FOR_PARKING_PLACE, AI_IDLE ); + defineState( ORIENT_FOR_PARKING_PLACE, newInstance(JetOrHeliParkOrientState)( this ), RELOAD_AMMO, AI_IDLE ); + defineState( RELOAD_AMMO, newInstance(JetOrHeliReloadAmmoState)( this ), AI_IDLE, AI_IDLE ); + defineState( RETURN_TO_DEAD_AIRFIELD, newInstance(JetOrHeliReturningToDeadAirfieldState)( this ), CIRCLING_DEAD_AIRFIELD, RETURN_TO_DEAD_AIRFIELD ); + defineState( CIRCLING_DEAD_AIRFIELD, newInstance(JetOrHeliCirclingDeadAirfieldState)( this ), AI_IDLE, AI_IDLE ); +} + +//------------------------------------------------------------------------------------------------- +JetAIStateMachine::~JetAIStateMachine() +{ +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +class HeliAIStateMachine : public AIStateMachine +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( HeliAIStateMachine, "HeliAIStateMachine" ); + +public: + HeliAIStateMachine( Object *owner, AsciiString name ); + +}; + +//------------------------------------------------------------------------------------------------- +HeliAIStateMachine::HeliAIStateMachine(Object *owner, AsciiString name) : AIStateMachine(owner, name) +{ + defineState( RETURNING_FOR_LANDING, newInstance(JetOrHeliReturnForLandingState)( this ), LANDING_AWAIT_CLEARANCE, RETURN_TO_DEAD_AIRFIELD ); + defineState( TAKING_OFF_AWAIT_CLEARANCE, newInstance(SuccessState)( this ), TAKING_OFF, AI_IDLE ); + defineState( TAKING_OFF, newInstance(HeliTakeoffOrLandingState)( this, false ), AI_IDLE, AI_IDLE ); + defineState( LANDING_AWAIT_CLEARANCE, newInstance(SuccessState)( this ), ORIENT_FOR_PARKING_PLACE, AI_IDLE ); + defineState( ORIENT_FOR_PARKING_PLACE, newInstance(JetOrHeliParkOrientState)( this ), LANDING, AI_IDLE ); + defineState( LANDING, newInstance(HeliTakeoffOrLandingState)( this, true ), RELOAD_AMMO, AI_IDLE ); + defineState( RELOAD_AMMO, newInstance(JetOrHeliReloadAmmoState)( this ), AI_IDLE, AI_IDLE ); + defineState( RETURN_TO_DEAD_AIRFIELD, newInstance(JetOrHeliReturningToDeadAirfieldState)( this ), CIRCLING_DEAD_AIRFIELD, RETURN_TO_DEAD_AIRFIELD ); + defineState( CIRCLING_DEAD_AIRFIELD, newInstance(JetOrHeliCirclingDeadAirfieldState)( this ), AI_IDLE, AI_IDLE ); + defineState( TAXI_FROM_HANGAR, newInstance(JetOrHeliTaxiState)( this, FROM_HANGAR ), AI_IDLE, AI_IDLE ); +} + +//------------------------------------------------------------------------------------------------- +HeliAIStateMachine::~HeliAIStateMachine() +{ +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +JetAIUpdateModuleData::JetAIUpdateModuleData() +{ + m_outOfAmmoDamagePerSecond = 0; + m_needsRunway = true; + m_keepsParkingSpaceWhenAirborne = true; + m_takeoffDistForMaxLift = 0.0f; + m_minHeight = 0.0f; + m_parkingOffset = 0.0f; + m_sneakyOffsetWhenAttacking = 0.0f; + m_takeoffPause = 0; + m_attackingLoco = LOCOMOTORSET_NORMAL; + m_returningLoco = LOCOMOTORSET_NORMAL; + m_attackLocoPersistTime = 0; + m_attackersMissPersistTime = 0; + m_lockonTime = 0; + m_lockonCursor.clear(); + m_lockonInitialDist = 100; + m_lockonFreq = 0.5; + m_lockonAngleSpin = 720; + m_returnToBaseIdleTime = 0; +} + +//------------------------------------------------------------------------------------------------- +/*static*/ void JetAIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + AIUpdateModuleData::buildFieldParse(p); + + static const FieldParse dataFieldParse[] = + { + { "OutOfAmmoDamagePerSecond", INI::parsePercentToReal, NULL, offsetof( JetAIUpdateModuleData, m_outOfAmmoDamagePerSecond ) }, + { "NeedsRunway", INI::parseBool, NULL, offsetof( JetAIUpdateModuleData, m_needsRunway ) }, + { "KeepsParkingSpaceWhenAirborne",INI::parseBool, NULL, offsetof( JetAIUpdateModuleData, m_keepsParkingSpaceWhenAirborne ) }, + { "TakeoffDistForMaxLift", INI::parsePercentToReal, NULL, offsetof( JetAIUpdateModuleData, m_takeoffDistForMaxLift ) }, + { "TakeoffPause", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_takeoffPause ) }, + { "MinHeight", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_minHeight ) }, + { "ParkingOffset", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_parkingOffset ) }, + { "SneakyOffsetWhenAttacking", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_sneakyOffsetWhenAttacking ) }, + { "AttackLocomotorType", INI::parseIndexList, TheLocomotorSetNames, offsetof( JetAIUpdateModuleData, m_attackingLoco ) }, + { "AttackLocomotorPersistTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_attackLocoPersistTime ) }, + { "AttackersMissPersistTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_attackersMissPersistTime ) }, + { "ReturnForAmmoLocomotorType", INI::parseIndexList, TheLocomotorSetNames, offsetof( JetAIUpdateModuleData, m_returningLoco ) }, + { "LockonTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_lockonTime ) }, + { "LockonCursor", INI::parseAsciiString, NULL, offsetof( JetAIUpdateModuleData, m_lockonCursor ) }, + { "LockonInitialDist", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_lockonInitialDist ) }, + { "LockonFreq", INI::parseReal, NULL, offsetof( JetAIUpdateModuleData, m_lockonFreq ) }, + { "LockonAngleSpin", INI::parseAngleReal, NULL, offsetof( JetAIUpdateModuleData, m_lockonAngleSpin ) }, + { "LockonBlinky", INI::parseBool, NULL, offsetof( JetAIUpdateModuleData, m_lockonBlinky ) }, + { "ReturnToBaseIdleTime", INI::parseDurationUnsignedInt, NULL, offsetof( JetAIUpdateModuleData, m_returnToBaseIdleTime ) }, + { 0, 0, 0, 0 } + }; + p.add(dataFieldParse); +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +AIStateMachine* JetAIUpdate::makeStateMachine() +{ + if (getJetAIUpdateModuleData()->m_needsRunway) + return newInstance(JetAIStateMachine)( getObject(), "JetAIStateMachine"); + else + return newInstance(HeliAIStateMachine)( getObject(), "HeliAIStateMachine"); +} + +//------------------------------------------------------------------------------------------------- +JetAIUpdate::JetAIUpdate( Thing *thing, const ModuleData* moduleData ) : AIUpdateInterface( thing, moduleData ) +{ + m_flags = 0; + m_afterburnerSound = *(getObject()->getTemplate()->getPerUnitSound("Afterburner")); + m_afterburnerSound.setObjectID(getObject()->getID()); + m_attackLocoExpireFrame = 0; + m_attackersMissExpireFrame = 0; + m_untargetableExpireFrame = 0; + m_returnToBaseFrame = 0; + m_lockonDrawable = NULL; + m_landingPosForHelipadStuff.zero(); + + //Added By Sadullah Nader + //Initializations missing and needed + m_producerLocation.zero(); + // + m_enginesOn = TRUE; +} + +//------------------------------------------------------------------------------------------------- +JetAIUpdate::~JetAIUpdate() +{ + if (m_lockonDrawable) + { + TheGameClient->destroyDrawable(m_lockonDrawable); + m_lockonDrawable = NULL; + } +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::isIdle() const +{ + // we need to do this because we enter an idle state briefly between takeoff/landing in these cases, + // but scripting relies on us never claiming to be "idle"... + if (getFlag(HAS_PENDING_COMMAND)) + return false; + + return AIUpdateInterface::isIdle(); +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::isReloading() const +{ + StateID stateID = getStateMachine()->getCurrentStateID(); + if( stateID == RELOAD_AMMO ) + { + return TRUE; + } + return FALSE; +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::isTaxiingToParking() const +{ + StateID stateID = getStateMachine()->getCurrentStateID(); + switch( stateID ) + { + case TAXI_FROM_HANGAR: + case TAXI_FROM_LANDING: + case ORIENT_FOR_PARKING_PLACE: + case RELOAD_AMMO: + case TAKING_OFF_AWAIT_CLEARANCE: + case TAXI_TO_TAKEOFF: + case PAUSE_BEFORE_TAKEOFF: + case TAKING_OFF: + return TRUE; + } + return FALSE; +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::onObjectCreated() +{ + AIUpdateInterface::onObjectCreated(); + friend_setAllowAirLoco(false); + chooseLocomotorSet(LOCOMOTORSET_TAXIING); +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::onDelete() +{ + AIUpdateInterface::onDelete(); + ParkingPlaceBehaviorInterface* pp = getPP(getObject()->getProducerID()); + if (pp) + pp->releaseSpace(getObject()->getID()); +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::getProducerLocation() +{ + if (getFlag(HAS_PRODUCER_LOCATION)) + return; + + Object* jet = getObject(); + Object* airfield = TheGameLogic->findObjectByID( jet->getProducerID() ); + if (airfield == NULL) + m_producerLocation = *jet->getPosition(); + else + m_producerLocation = *airfield->getPosition(); + + /* + if we aren't allowed to fly, then we should be parked (or at least taxiing), + which implies we have a parking place reserved. If we don't, it's probably + because we were directly spawned via script (or directly placed on the map). + So, check to see if we have no parking place, and if not, quietly enable flight. + */ + ParkingPlaceBehaviorInterface* pp = getPP(jet->getProducerID()); + if (!pp || !pp->hasReservedSpace(jet->getID())) + { + friend_setAllowAirLoco(true); + chooseLocomotorSet(LOCOMOTORSET_NORMAL); + } + else + { + friend_setAllowAirLoco(false); + chooseLocomotorSet(LOCOMOTORSET_TAXIING); + } + + setFlag(HAS_PRODUCER_LOCATION, true); + +} + +//------------------------------------------------------------------------------------------------- +UpdateSleepTime JetAIUpdate::update() +{ + const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); + + getProducerLocation(); + + Object* jet = getObject(); + + ParkingPlaceBehaviorInterface* pp = getPP(getObject()->getProducerID()); + + // If idle & out of ammo, return + // have to call our parent's isIdle, because we override it to never return true + // when we have a pending command... + UnsignedInt now = TheGameLogic->getFrame(); + + // srj sez: not 100% sure on this. calling RELOAD_AMMO "idle" allows us to get healed while reloading, + // but might have other side effects we didn't want. if this does prove to cause a bug, be sure + // that jets (and ESPECIALLY comanches) are still getting healed at airfields. + if (AIUpdateInterface::isIdle() || getStateMachine()->getCurrentStateID() == RELOAD_AMMO) + { + if (pp != NULL) + { + if (!getFlag(ALLOW_AIR_LOCO) && + !getFlag(HAS_PENDING_COMMAND) && + jet->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) && + jet->getBodyModule()->getHealth() == jet->getBodyModule()->getMaxHealth()) + { + // we're completely healed, so take off again + pp->setHealee(jet, false); + friend_setAllowAirLoco(true); + getStateMachine()->clear(); + setLastCommandSource( CMD_FROM_AI ); + getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE ); + } + else + { + pp->setHealee(jet, !getFlag(ALLOW_AIR_LOCO)); + } + } + + // note that we might still have weapons with ammo, but still be forced to return to reload. + if (isOutOfSpecialReloadAmmo() && getFlag(ALLOW_AIR_LOCO)) + { + m_returnToBaseFrame = 0; + + // this is really a "just-in-case" to ensure the targeter list doesn't spin out of control (srj) + pruneDeadTargeters(); + + setFlag(USE_SPECIAL_RETURN_LOCO, true); + setLastCommandSource( CMD_FROM_AI ); + getStateMachine()->setState(RETURNING_FOR_LANDING); + } + else if (getFlag(HAS_PENDING_COMMAND) + // srj sez: if we are reloading ammo, wait will we are done before processing the pending command. + && getStateMachine()->getCurrentStateID() != RELOAD_AMMO) + { + m_returnToBaseFrame = 0; + + AICommandParms parms(AICMD_MOVE_TO_POSITION, CMD_FROM_AI); // values don't matter, will be wiped by next line + m_mostRecentCommand.reconstitute(parms); + setFlag(HAS_PENDING_COMMAND, false); + + aiDoCommand(&parms); + } + else if (m_returnToBaseFrame != 0 && now >= m_returnToBaseFrame && getFlag(ALLOW_AIR_LOCO)) + { + m_returnToBaseFrame = 0; + DEBUG_ASSERTCRASH(isOutOfSpecialReloadAmmo() == false, ("Hmm, this seems unlikely -- isOutOfSpecialReloadAmmo()==false")); + setFlag(USE_SPECIAL_RETURN_LOCO, false); + setLastCommandSource( CMD_FROM_AI ); + getStateMachine()->setState(RETURNING_FOR_LANDING); + } + else if (m_returnToBaseFrame == 0 && d->m_returnToBaseIdleTime > 0 && getFlag(ALLOW_AIR_LOCO)) + { + m_returnToBaseFrame = now + d->m_returnToBaseIdleTime; + } + } + else + { + if (pp != NULL) + { + pp->setHealee(getObject(), false); + } + m_returnToBaseFrame = 0; + if (getFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD) && + isOutOfSpecialReloadAmmo() && getFlag(ALLOW_AIR_LOCO)) + { + setFlag(USE_SPECIAL_RETURN_LOCO, true); + setFlag(HAS_PENDING_COMMAND, true); + setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, false); + setLastCommandSource( CMD_FROM_AI ); + getStateMachine()->setState(RETURNING_FOR_LANDING); + } + } + + Real minHeight = friend_getMinHeight(); + if( pp ) + { + minHeight += pp->getLandingDeckHeightOffset(); + } + + Drawable* draw = jet->getDrawable(); + if (draw != NULL) + { + StateID id = getStateMachine()->getCurrentStateID(); + Bool needToCheckMinHeight = (id >= JETAISTATETYPE_FIRST && id <= JETAISTATETYPE_LAST) || + !jet->isAboveTerrain() || + !getFlag(ALLOW_AIR_LOCO); + if( needToCheckMinHeight || jet->getStatusBits().test( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) ) + { + Real ht = jet->isAboveTerrain() ? jet->getHeightAboveTerrain() : 0; + if (ht < minHeight) + { + Matrix3D tmp(1); + tmp.Set_Z_Translation(minHeight - ht); + draw->setInstanceMatrix(&tmp); + } + else + { + draw->setInstanceMatrix(NULL); + } + } + else + { + draw->setInstanceMatrix(NULL); + } + } + + PhysicsBehavior* physics = jet->getPhysics(); + if (physics->getVelocityMagnitude() > 0 && getFlag(ALLOW_AIR_LOCO)) + jet->setModelConditionState(MODELCONDITION_JETEXHAUST); + else + jet->clearModelConditionState(MODELCONDITION_JETEXHAUST); + + if (jet->testStatus(OBJECT_STATUS_IS_ATTACKING)) + { + m_attackLocoExpireFrame = now + d->m_attackLocoPersistTime; + m_attackersMissExpireFrame = now + d->m_attackersMissPersistTime; + } + else + { + if (m_attackLocoExpireFrame != 0 && now >= m_attackLocoExpireFrame) + { + m_attackLocoExpireFrame = 0; + } + if (m_attackersMissExpireFrame != 0 && now >= m_attackersMissExpireFrame) + { + m_attackersMissExpireFrame = 0; + } + } + + if (m_untargetableExpireFrame != 0 && now >= m_untargetableExpireFrame) + { + m_untargetableExpireFrame = 0; + } + + positionLockon(); + + if (m_attackLocoExpireFrame != 0) + { + chooseLocomotorSet(d->m_attackingLoco); + } + else if (getFlag(USE_SPECIAL_RETURN_LOCO)) + { + chooseLocomotorSet(d->m_returningLoco); + } + + + if( !jet->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) ) + { + Drawable *draw = jet->getDrawable(); + if( draw ) + { + if( getFlag(TAKEOFF_IN_PROGRESS) + || getFlag(LANDING_IN_PROGRESS) + || getObject()->isSignificantlyAboveTerrain() + || isMoving() + || isWaitingForPath() ) + { + if( !m_enginesOn ) + { + //We just started moving, therefore turn on the engines! + draw->enableAmbientSound( TRUE ); + m_enginesOn = TRUE; + } + } + else if( m_enginesOn ) + { + //We're no longer moving, so turn off the engines! + draw->enableAmbientSound( FALSE ); + m_enginesOn = FALSE; + } + } + } + + + /*UpdateSleepTime ret =*/ AIUpdateInterface::update(); + //return (mine < ret) ? mine : ret; + /// @todo srj -- someday, make sleepy. for now, must not sleep. + return UPDATE_SLEEP_NONE; +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::chooseLocomotorSet(LocomotorSetType wst) +{ + const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); + if (!getFlag(ALLOW_AIR_LOCO)) + { + wst = LOCOMOTORSET_TAXIING; + } + else if (m_attackLocoExpireFrame != 0) + { + wst = d->m_attackingLoco; + } + else if (getFlag(USE_SPECIAL_RETURN_LOCO)) + { + wst = d->m_returningLoco; + } + return AIUpdateInterface::chooseLocomotorSet(wst); +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::setLocomotorGoalNone() +{ + if ((getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS)) + && getFlag(ALLOW_AIR_LOCO) && !getFlag(ALLOW_CIRCLING)) + { + Object* jet = getObject(); + Coord3D desiredPos = *jet->getPosition(); + const Coord3D* dir = jet->getUnitDirectionVector2D(); + desiredPos.x += dir->x * 1000.0f; + desiredPos.y += dir->y * 1000.0f; + setLocomotorGoalPositionExplicit(desiredPos); + } + else + { + AIUpdateInterface::setLocomotorGoalNone(); + } +} + +//---------------------------------------------------------------------------------------- +Bool JetAIUpdate::getSneakyTargetingOffset(Coord3D* offset) const +{ + if (m_attackersMissExpireFrame != 0 && TheGameLogic->getFrame() < m_attackersMissExpireFrame) + { + if (offset) + { + const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); + const Object* jet = getObject(); + const Coord3D* dir = jet->getUnitDirectionVector2D(); + offset->x = dir->x * d->m_sneakyOffsetWhenAttacking; + offset->y = dir->y * d->m_sneakyOffsetWhenAttacking; + offset->z = 0.0f; + } + return true; + } + else + { + return false; + } +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::pruneDeadTargeters() +{ + if (!m_targetedBy.empty()) + { + for (std::list::iterator it = m_targetedBy.begin(); it != m_targetedBy.end(); /* empty */ ) + { + if (TheGameLogic->findObjectByID(*it) == NULL) + { + it = m_targetedBy.erase(it); + } + else + { + ++it; + } + } + } +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::positionLockon() +{ + if (!m_lockonDrawable) + return; + + if (m_untargetableExpireFrame == 0) + { + TheGameClient->destroyDrawable(m_lockonDrawable); + m_lockonDrawable = NULL; + return; + } + + const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); + UnsignedInt now = TheGameLogic->getFrame(); + UnsignedInt remaining = m_untargetableExpireFrame - now; + UnsignedInt elapsed = d->m_lockonTime - remaining; + + Coord3D pos = *getObject()->getPosition(); + Real frac = (Real)remaining / (Real)d->m_lockonTime; + Real finalDist = getObject()->getGeometryInfo().getBoundingCircleRadius(); + Real dist = finalDist + (d->m_lockonInitialDist - finalDist) * frac; + Real angle = d->m_lockonAngleSpin * frac; + + pos.x += Cos(angle) * dist; + pos.y += Sin(angle) * dist; + // pos.z is untouched + + m_lockonDrawable->setPosition(&pos); + Real dx = getObject()->getPosition()->x - pos.x; + Real dy = getObject()->getPosition()->y - pos.y; + if (dx || dy) + m_lockonDrawable->setOrientation(atan2(dy, dx)); + + // the Gaussian sum, to avoid keeping a running total: + // + // 1+2+3+...n = n*(n+1)/2 + // + Real elapsedTimeSumPrev = 0.5f * (elapsed-1) * (elapsed); + Real elapsedTimeSumCurr = elapsedTimeSumPrev + elapsed; + Real factor = d->m_lockonFreq / d->m_lockonTime; + Bool lastPhase = ((Int)(factor * elapsedTimeSumPrev) & 1) != 0; + Bool thisPhase = ((Int)(factor * elapsedTimeSumCurr) & 1) != 0; + + if (lastPhase && (!thisPhase)) + { + AudioEventRTS lockonSound = TheAudio->getMiscAudio()->m_lockonTickSound; + lockonSound.setObjectID(getObject()->getID()); + TheAudio->addAudioEvent(&lockonSound); + if (d->m_lockonBlinky) + m_lockonDrawable->setDrawableHidden(false); + } + else + { + if (d->m_lockonBlinky) + m_lockonDrawable->setDrawableHidden(true); + } +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::buildLockonDrawableIfNecessary() +{ + if (m_untargetableExpireFrame == 0) + return; + + const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); + if (d->m_lockonCursor.isNotEmpty() && m_lockonDrawable == NULL) + { + const ThingTemplate* tt = TheThingFactory->findTemplate(d->m_lockonCursor); + if (tt) + { + m_lockonDrawable = TheThingFactory->newDrawable(tt); + } + } + positionLockon(); +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::addTargeter(ObjectID id, Bool add) +{ + const JetAIUpdateModuleData* d = getJetAIUpdateModuleData(); + UnsignedInt lockonTime = d->m_lockonTime; + if (lockonTime != 0) + { + std::list::iterator it = std::find(m_targetedBy.begin(), m_targetedBy.end(), id); + if (add) + { + if (it == m_targetedBy.end()) + { + m_targetedBy.push_back(id); + if (m_untargetableExpireFrame == 0 && m_targetedBy.size() == 1) + { + m_untargetableExpireFrame = TheGameLogic->getFrame() + lockonTime; + buildLockonDrawableIfNecessary(); + } + } + } + else + { + if (it != m_targetedBy.end()) + { + m_targetedBy.erase(it); + if (m_targetedBy.empty()) + { + m_untargetableExpireFrame = 0; + } + } + } + } +} + +//---------------------------------------------------------------------------------------- +Bool JetAIUpdate::isTemporarilyPreventingAimSuccess() const +{ + return m_untargetableExpireFrame != 0 && (TheGameLogic->getFrame() < m_untargetableExpireFrame); +} + +//---------------------------------------------------------------------------------------- +Bool JetAIUpdate::isAllowedToMoveAwayFromUnit() const +{ + // parked (or landing) units don't get to do this. + if (!getFlag(ALLOW_AIR_LOCO) || getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS)) + return false; + + return AIUpdateInterface::isAllowedToMoveAwayFromUnit(); +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::isDoingGroundMovement(void) const +{ + // srj per jba: Air units should never be doing ground movement, even when taxiing... + // (exception: see getTreatAsAircraftForLocoDistToGoal) + return false; +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::getTreatAsAircraftForLocoDistToGoal() const +{ + // exception to isDoingGroundMovement: should never treat as aircraft for dist-to-goal when taxiing. + if (getFlag(TAXI_IN_PROGRESS)) + { + return false; + } + else + { + return AIUpdateInterface::getTreatAsAircraftForLocoDistToGoal(); + } +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::isParkedInHangar() const +{ + // We do not check if the Aircraft actually needs a runway/hangar here, + // so we can ignore those cases earlier already + return isReloading() || !(getFlag(TAKEOFF_IN_PROGRESS) + || getFlag(LANDING_IN_PROGRESS) + || getObject()->isSignificantlyAboveTerrain() + || isMoving() + || isWaitingForPath()); +} + +//---------------------------------------------------------------------------------------- +/** + * Follow the path defined by the given array of points + */ +void JetAIUpdate::privateFollowPath( const std::vector* path, Object *ignoreObject, CommandSourceType cmdSource, Bool exitProduction ) +{ + if (exitProduction) + { + getStateMachine()->clear(); + if( ignoreObject ) + ignoreObstacle( ignoreObject ); + setLastCommandSource( cmdSource ); + if (getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) + getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE ); + else + getStateMachine()->setState( TAXI_FROM_HANGAR ); + } + else + { + AIUpdateInterface::privateFollowPath(path, ignoreObject, cmdSource, exitProduction); + } +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::privateFollowPathAppend( const Coord3D *pos, CommandSourceType cmdSource ) +{ + // nothing yet... might need to override. not sure. (srj) + AIUpdateInterface::privateFollowPathAppend(pos, cmdSource); +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::doLandingCommand(Object *airfield, CommandSourceType cmdSource) +{ + if (getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD)) + { + m_landingPosForHelipadStuff = *airfield->getPosition(); + + Coord3D tmp; + FindPositionOptions options; + options.maxRadius = airfield->getGeometryInfo().getBoundingCircleRadius() * 10.0f; + if (ThePartitionManager->findPositionAround(&m_landingPosForHelipadStuff, &options, &tmp)) + m_landingPosForHelipadStuff = tmp; + } + + for (BehaviorModule** i = airfield->getBehaviorModules(); *i; ++i) + { + ParkingPlaceBehaviorInterface* pp = (*i)->getParkingPlaceBehaviorInterface(); + if (pp == NULL) + continue; + + if (getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) || + pp->reserveSpace(getObject()->getID(), friend_getParkingOffset(), NULL)) + { + // if we had a space at another airfield, release it + ParkingPlaceBehaviorInterface* oldPP = getPP(getObject()->getProducerID()); + if (oldPP != NULL && oldPP != pp) + { + oldPP->releaseSpace(getObject()->getID()); + } + + getObject()->setProducer(airfield); + DEBUG_ASSERTCRASH(isOutOfSpecialReloadAmmo() == false, ("Hmm, this seems unlikely -- isOutOfSpecialReloadAmmo()==false")); + setFlag(USE_SPECIAL_RETURN_LOCO, false); + setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, false); + setLastCommandSource( cmdSource ); + getStateMachine()->setState(RETURNING_FOR_LANDING); + return; + } + } +} + +//---------------------------------------------------------------------------------------- +void JetAIUpdate::notifyVictimIsDead() +{ + if (getJetAIUpdateModuleData()->m_needsRunway) + m_returnToBaseFrame = TheGameLogic->getFrame(); +} + +//---------------------------------------------------------------------------------------- +/** + * Enter the given object + */ +void JetAIUpdate::privateEnter( Object *objectToEnter, CommandSourceType cmdSource ) +{ + // we are already landing. just ignore it. + if (getFlag(LANDING_IN_PROGRESS)) + return; + + if( !TheActionManager->canEnterObject( getObject(), objectToEnter, cmdSource, DONT_CHECK_CAPACITY ) ) + return; + + doLandingCommand(objectToEnter, cmdSource); +} + +//---------------------------------------------------------------------------------------- +/** + * Get repaired at the repair depot + */ +void JetAIUpdate::privateGetRepaired( Object *repairDepot, CommandSourceType cmdSource ) +{ + // we are already landing. just ignore it. + if (getFlag(LANDING_IN_PROGRESS)) + return; + + // sanity, if we can't get repaired from here get out of here + if( TheActionManager->canGetRepairedAt( getObject(), repairDepot, cmdSource ) == FALSE ) + return; + + // dock with the repair depot + doLandingCommand( repairDepot, cmdSource ); + +} + +//------------------------------------------------------------------------------------------------- +Bool JetAIUpdate::isParkedAt(const Object* obj) const +{ + if (!getFlag(ALLOW_AIR_LOCO) && + !getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) && + obj != NULL) + { + Object* airfield; + ParkingPlaceBehaviorInterface* pp = getPP(getObject()->getProducerID(), &airfield); + if (pp != NULL && airfield != NULL && airfield == obj) + { + return true; + } + } + + return false; +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::aiDoCommand(const AICommandParms* parms) +{ + // call this from aiDoCommand as well as update, because this can + // be called before update ever is... if the unit is placed on a map, + // and a script tells it to do something with a condition of TRUE! + getProducerLocation(); + + if (!isAllowedToRespondToAiCommands(parms)) + return; + + // note that we always store this, even if nothing will be "pending". + m_mostRecentCommand.store(*parms); + + if (getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS)) + { + // have to wait for takeoff or landing to complete, just store the sucker + setFlag(HAS_PENDING_COMMAND, true); + return; + } + else if (parms->m_cmd == AICMD_IDLE && getStateMachine()->getCurrentStateID() == RELOAD_AMMO) + { + // uber-special-case... if we are told to idle, but are reloading ammo, ignore it for now, + // since we're already doing "nothing" and responding to this will cease our reload... + // don't just return, tho, in case we were (say) reloading during a guard stint. + setFlag(HAS_PENDING_COMMAND, true); + return; + } + else if( parms->m_cmd == AICMD_IDLE && getObject()->isAirborneTarget() && !getObject()->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) ) + { + getStateMachine()->clear(); + setLastCommandSource( CMD_FROM_AI ); + getStateMachine()->setState( RETURNING_FOR_LANDING ); + return; + } + else if (!getFlag(ALLOW_AIR_LOCO)) + { + switch (parms->m_cmd) + { + case AICMD_IDLE: + case AICMD_BUSY: + case AICMD_FOLLOW_EXITPRODUCTION_PATH: + // don't need (or want) to take off for these + break; + + case AICMD_ENTER: + case AICMD_GET_REPAIRED: + + // if we're already parked at the airfield in question, just ignore. + if (isParkedAt(parms->m_obj)) + return; + + // else fall thru to the default case! + + default: + { + // nuke any existing pending cmd + m_mostRecentCommand.store(*parms); + setFlag(HAS_PENDING_COMMAND, true); + + getStateMachine()->clear(); + setLastCommandSource( CMD_FROM_AI ); + getStateMachine()->setState( TAKING_OFF_AWAIT_CLEARANCE ); + + return; + } + } + } + + switch (parms->m_cmd) + { + case AICMD_GUARD_POSITION: + case AICMD_GUARD_OBJECT: + case AICMD_GUARD_AREA: + case AICMD_HUNT: + case AICMD_GUARD_RETALIATE: + setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, true); + break; + default: + setFlag(ALLOW_INTERRUPT_AND_RESUME_OF_CUR_STATE_FOR_RELOAD, false); + break; + } + + setFlag(HAS_PENDING_COMMAND, false); + AIUpdateInterface::aiDoCommand(parms); +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::friend_setAllowAirLoco(Bool allowAirLoco) +{ + setFlag(ALLOW_AIR_LOCO, allowAirLoco); +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::friend_enableAfterburners(Bool v) +{ + Object* jet = getObject(); + if (v) + { + jet->setModelConditionState(MODELCONDITION_JETAFTERBURNER); + if (!m_afterburnerSound.isCurrentlyPlaying()) + { + m_afterburnerSound.setObjectID(jet->getID()); + m_afterburnerSound.setPlayingHandle(TheAudio->addAudioEvent(&m_afterburnerSound)); + } + } + else + { + jet->clearModelConditionState(MODELCONDITION_JETAFTERBURNER); + if (m_afterburnerSound.isCurrentlyPlaying()) + { + TheAudio->removeAudioEvent(m_afterburnerSound.getPlayingHandle()); + } + } +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::friend_addWaypointToGoalPath( const Coord3D &bestPos ) +{ + privateFollowPathAppend( &bestPos, CMD_FROM_AI ); +} + +//------------------------------------------------------------------------------------------------- +AICommandType JetAIUpdate::friend_getPendingCommandType() const +{ + if( getFlag( HAS_PENDING_COMMAND ) ) + { + return m_mostRecentCommand.getCommandType(); + } + return AICMD_NO_COMMAND; +} + +//------------------------------------------------------------------------------------------------- +void JetAIUpdate::friend_purgePendingCommand() +{ + setFlag(HAS_PENDING_COMMAND, false); +} + +// ------------------------------------------------------------------------------------------------ +/** CRC */ +// ------------------------------------------------------------------------------------------------ +void JetAIUpdate::crc( Xfer *xfer ) +{ + // extend base class + AIUpdateInterface::crc(xfer); +} // end crc + +// ------------------------------------------------------------------------------------------------ +/** Xfer method + * Version Info: + * 1: Initial version */ +// ------------------------------------------------------------------------------------------------ +void JetAIUpdate::xfer( Xfer *xfer ) +{ + + // version + XferVersion currentVersion = 2; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + // extend base class + AIUpdateInterface::xfer(xfer); + + + xfer->xferCoord3D(&m_producerLocation); + m_mostRecentCommand.doXfer(xfer); + xfer->xferUnsignedInt(&m_attackLocoExpireFrame); + xfer->xferUnsignedInt(&m_attackersMissExpireFrame); + xfer->xferUnsignedInt(&m_returnToBaseFrame); + xfer->xferSTLObjectIDList(&m_targetedBy); + + xfer->xferUnsignedInt(&m_untargetableExpireFrame); + + // Set on create. + //AudioEventRTS m_afterburnerSound; ///< Sound when afterburners on + + AsciiString drawName; + if (m_lockonDrawable) { + drawName = m_lockonDrawable->getTemplate()->getName(); + } + xfer->xferAsciiString(&drawName); + if (drawName.isNotEmpty() && m_lockonDrawable==NULL) + { + const ThingTemplate* tt = TheThingFactory->findTemplate(drawName); + if (tt) + { + m_lockonDrawable = TheThingFactory->newDrawable(tt); + } + } + xfer->xferInt(&m_flags); + + if( version >= 2 ) + { + xfer->xferBool( &m_enginesOn ); + } + else + { + //We don't have to be accurate -- this is a patch. + if( getFlag(TAKEOFF_IN_PROGRESS) || getFlag(LANDING_IN_PROGRESS) || getObject()->isSignificantlyAboveTerrain() || getObject()->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) ) + { + m_enginesOn = TRUE; + } + else + { + m_enginesOn = FALSE; + } + } + +} // end xfer + +// ------------------------------------------------------------------------------------------------ +/** Load post process */ +// ------------------------------------------------------------------------------------------------ +void JetAIUpdate::loadPostProcess( void ) +{ + //When drawables are created, so are their ambient sounds. After loading, only turn off the + //ambient sound if the engine is off. + if( !m_enginesOn ) + { + Drawable *draw = getObject()->getDrawable(); + if( draw ) + { + draw->stopAmbientSound(); + } + } + + // extend base class + AIUpdateInterface::loadPostProcess(); +} // end loadPostProcess diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp index 4da9001972..5f2bd0ef9b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp @@ -52,7 +52,7 @@ const Real BIGNUM = 99999.0f; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -348,7 +348,7 @@ Bool MissileAIUpdate::projectileHandleCollision( Object *other ) const ContainedItemsList* items = contain->getContainedItemsList(); if (items) { - for (ContainedItemsList::const_iterator it = items->begin(); *it != NULL && numKilled < d->m_garrisonHitKillCount; ) + for (ContainedItemsList::const_iterator it = items->begin(); it != items->end() && numKilled < d->m_garrisonHitKillCount; ) { Object* thingToKill = *it++; if (!thingToKill->isEffectivelyDead() && thingToKill->isKindOfMulti(d->m_garrisonHitKillKindof, d->m_garrisonHitKillKindofNot)) @@ -832,6 +832,17 @@ void MissileAIUpdate::projectileNowJammed() m_victimID = INVALID_ID; } +// ------------------------------------------------------------------------------------------------ +const Coord3D* MissileAIUpdate::getTargetPosition() +{ + return getGoalPosition(); +} +// ------------------------------------------------------------------------------------------------ +Object* MissileAIUpdate::getTargetObject() +{ + return getGoalObject(); +} + // ------------------------------------------------------------------------------------------------ /** CRC */ // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp index d58d9ed446..b6d70d045a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp @@ -60,7 +60,7 @@ static const Int INVALID_PATH = -1; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -907,7 +907,7 @@ class PartitionFilterIsValidCarriage : public PartitionFilter PartitionFilterIsValidCarriage(Object* obj, const RailroadBehaviorModuleData* data) : m_obj(obj), m_data(data) { } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterIsValidCarriage"; } #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp index 1657deb133..decf07816f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/SupplyTruckAIUpdate.cpp @@ -41,13 +41,13 @@ #include "GameClient/Drawable.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) #define NO_DEBUG_SUPPLY_STATE #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp index 319dd25262..33093b8667 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/TransportAIUpdate.cpp @@ -36,7 +36,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp index 06c80f4a61..f8244caaf1 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp @@ -62,7 +62,7 @@ #include "GameLogic/Module/WorkerAIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -206,7 +206,7 @@ void WorkerAIUpdate::createMachines( void ) m_workerMachine->initDefaultState();// this has to wait until all three are in place since // an immediate transition check will ask questions of the machines. -//#ifdef _DEBUG +//#ifdef RTS_DEBUG // m_workerMachine->setDebugOutput(TRUE); // m_dozerMachine->setDebugOutput(TRUE); // m_supplyTruckStateMachine->setDebugOutput(TRUE); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ArmorDamageScalarUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ArmorDamageScalarUpdate.cpp new file mode 100644 index 0000000000..f542bf64fc --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ArmorDamageScalarUpdate.cpp @@ -0,0 +1,368 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ArmorDamageScalarUpdate.cpp ///////////////////////////////////////////////// +//----------------------------------------------------------------------------- +// +// Electronic Arts Pacific. +// +// Confidential Information +// Copyright (C) 2002-2003 - All Rights Reserved +// +//----------------------------------------------------------------------------- +// +// created: March 2025 +// +// Filename: ArmorDamageScalarUpdate.cpp +// +// author: Andi W +// +// purpose: Apply a temporary multiplier to damage taken to units in an area +// +//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +// SYSTEM INCLUDES //////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// USER INCLUDES ////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine + +#include "GameLogic/Module/ArmorDamageScalarUpdate.h" + +// #define DEFINE_WEAPONBONUSCONDITION_NAMES + +#include "Common/ThingTemplate.h" +#include "Common/DamageFX.h" +#include "GameLogic/Module/ContainModule.h" +#include "GameLogic/Module/BodyModule.h" +#include "GameLogic/GameLogic.h" +#include "GameLogic/Object.h" +#include "GameLogic/PartitionManager.h" +#include "GameLogic/Weapon.h" +#include "GameClient/Drawable.h" +#include "GameClient/ParticleSys.h" +#include "GameClient/TintStatus.h" + +//----------------------------------------------------------------------------- +ArmorDamageScalarUpdateModuleData::ArmorDamageScalarUpdateModuleData() +{ + m_allowAffectKindOf.clear(); + m_forbiddenAffectKindOf.clear(); + m_targetsMask = 0; + m_isAffectAirborne = true; + m_bonusDuration = 0; + m_initialDelay = 0; + m_bonusRange = 0; + m_armorDamageScalar = 1.0f; + m_damageFx = NULL; + m_effectParticleSystem = NULL; + m_scaleParticleCount = false; + m_tintStatus = TINT_STATUS_INVALID; + //m_applyTint = false; + // m_sparksPerCubicFoot = 0.001f; +} + +//----------------------------------------------------------------------------- +void ArmorDamageScalarUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + UpdateModuleData::buildFieldParse(p); + static const FieldParse dataFieldParse[] = + { + { "AllowedAffectKindOf", KindOfMaskType::parseFromINI, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_allowAffectKindOf) }, + { "ForbiddenAffectKindOf", KindOfMaskType::parseFromINI, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_forbiddenAffectKindOf ) }, + { "AffectsTargets", INI::parseBitString32, TheWeaponAffectsMaskNames, offsetof(ArmorDamageScalarUpdateModuleData, m_targetsMask) }, + { "AffectAirborne", INI::parseBool, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_isAffectAirborne) }, + { "BonusDuration", INI::parseDurationUnsignedInt, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_bonusDuration ) }, + { "BonusRange", INI::parseReal, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_bonusRange ) }, + { "InitialDelay", INI::parseDurationUnsignedInt, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_initialDelay) }, + { "ArmorDamageScalar", INI::parseReal, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_armorDamageScalar) }, + { "OverrideDamageFX", INI::parseDamageFX, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_damageFx) }, + { "EffectParticleSystem", INI::parseParticleSystemTemplate, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_effectParticleSystem) }, + { "ScaleParticleSystem", INI::parseBool, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_scaleParticleCount) }, + { "TintStatusType", TintStatusFlags::parseSingleBitFromINI, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_tintStatus) }, + //{ "ApplyColorTint", INI::parseBool, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_applyTint)}, + //{ "ParticlesPerCubicFoot", INI::parseReal, NULL, offsetof(ArmorDamageScalarUpdateModuleData, m_sparksPerCubicFoot) }, + { 0, 0, 0, 0 } + }; + p.add(dataFieldParse); +} + +//----------------------------------------------------------------------------- +// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +ArmorDamageScalarUpdate::ArmorDamageScalarUpdate( Thing *thing, const ModuleData* moduleData ) : UpdateModule( thing, moduleData ) +{ + m_effectApplied = FALSE; + + m_affectedObjects.clear(); + m_dieFrame = 0; + + const ArmorDamageScalarUpdateModuleData* d = getArmorDamageScalarUpdateModuleData(); + if (d->m_initialDelay > 0) { + setWakeFrame(getObject(), UPDATE_SLEEP(d->m_initialDelay)); + } + else { + setWakeFrame(getObject(), UPDATE_SLEEP_NONE); + } +} +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ArmorDamageScalarUpdate::~ArmorDamageScalarUpdate( void ) +{ + removeEffect(); +} + + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +UpdateSleepTime ArmorDamageScalarUpdate::update(void) +{ + if (!m_effectApplied) { + applyEffect(); + const ArmorDamageScalarUpdateModuleData* d = getArmorDamageScalarUpdateModuleData(); + Int delay = d->m_bonusDuration; + m_dieFrame = TheGameLogic->getFrame() + delay; + return UPDATE_SLEEP(delay); + } + else { + removeEffect(); + // We get deleted after the effect is over + TheGameLogic->destroyObject(getObject()); + return UPDATE_SLEEP_FOREVER; + } +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- + +void ArmorDamageScalarUpdate::applyEffect(void) { + + if (m_effectApplied) return; + + m_effectApplied = TRUE; + const ArmorDamageScalarUpdateModuleData * data = getArmorDamageScalarUpdateModuleData(); + Object *me = getObject(); + + Int targetFlags = 0; + if (data->m_targetsMask & WEAPON_AFFECTS_ALLIES) targetFlags |= PartitionFilterRelationship::ALLOW_ALLIES; + if (data->m_targetsMask & WEAPON_AFFECTS_ENEMIES) targetFlags |= PartitionFilterRelationship::ALLOW_ENEMIES; + if (data->m_targetsMask & WEAPON_AFFECTS_NEUTRALS) targetFlags |= PartitionFilterRelationship::ALLOW_NEUTRAL; + + PartitionFilterRelationship relationship( me, targetFlags); + PartitionFilterSameMapStatus filterMapStatus(me); + PartitionFilterAlive filterAlive; + + // Leaving this here commented out to show that I need to reach valid contents of invalid transports. + // So these checks are on an individual basis, not in the Partition query + // PartitionFilterAcceptByKindOf filterKindof(data->m_requiredAffectKindOf,data->m_forbiddenAffectKindOf); + PartitionFilter *filters[] = { &relationship, &filterAlive, &filterMapStatus, NULL }; + + // scan objects in our region + ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( me->getPosition(), + data->m_bonusRange, + FROM_CENTER_2D, + filters ); + MemoryPoolObjectHolder hold( iter ); + + for( Object *currentObj = iter->first(); currentObj != NULL; currentObj = iter->next() ) + { + if (data->m_isAffectAirborne || (!currentObj->isKindOf(KINDOF_AIRCRAFT) && !currentObj->isAirborneTarget())) { + + if (currentObj->isAnyKindOf(data->m_allowAffectKindOf) && !currentObj->isAnyKindOf(data->m_forbiddenAffectKindOf)) + { + applyEffectToObject(currentObj); + m_affectedObjects.push_back(currentObj->getID()); + } + + // TODO: get contained objects and apply effect + //if( currentObj->getContain() ) + //{ + // currentObj->getContain()->iterateContained(containIteratingDoArmorDamageScalar, &armorDamageScalarData, FALSE); + //} + + } + } +} + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +void ArmorDamageScalarUpdate::removeEffect(void) { + + if (!m_effectApplied) return; + + m_effectApplied = FALSE; + + for (ObjectIDVectorIterator it = m_affectedObjects.begin(); it != m_affectedObjects.end(); ) { + Object* obj = TheGameLogic->findObjectByID(*it); + if (obj) { + if (!obj->isEffectivelyDead()) { + removeEffectFromObject(obj); + } + } + + it = m_affectedObjects.erase(it); + } +} + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ + +void ArmorDamageScalarUpdate::applyEffectToObject(Object *obj) { + const ArmorDamageScalarUpdateModuleData* data = getArmorDamageScalarUpdateModuleData(); + BodyModuleInterface* body = obj->getBodyModule(); + body->applyDamageScalar(__max(data->m_armorDamageScalar, 0.01f)); + + + //DEBUG_LOG((">>>ADSU: apply scalar '%f' to obj '%s' - new scalar = '%f' \n", + // data->m_armorDamageScalar, obj->getTemplate()->getName().str(), body->getDamageScalar())); + + // Apply Particle System + Drawable* drw = obj->getDrawable(); + if (drw) + { + if (data->m_tintStatus > TINT_STATUS_INVALID && data->m_tintStatus < TINT_STATUS_COUNT) + { + drw->setTintStatus(data->m_tintStatus); + } + + const ParticleSystemTemplate* tmp = data->m_effectParticleSystem; + if (tmp) + { + ParticleSystem* sys = TheParticleSystemManager->createParticleSystem(tmp); + + if (sys) + { + sys->attachToObject(obj); + sys->setSystemLifetime(data->m_bonusDuration); + + if (data->m_scaleParticleCount) { + // Scale particle count based on size + Real x = obj->getGeometryInfo().getMajorRadius(); + Real y = obj->getGeometryInfo().getMinorRadius(); + Real z = obj->getGeometryInfo().getMaxHeightAbovePosition() * 0.5; + sys->setEmissionBoxHalfSize(x, y, z); + Real size = x * y; + sys->setBurstCountMultiplier(MAX(1.0, sqrt(size * 0.02f))); // these are somewhat tweaked right now + sys->setBurstDelayMultiplier(MIN(5.0, sqrt(500.0f / size))); + + //DEBUG_LOG((">>>ADSU: attach particles to %s: with size (%f, %f, %f) countMultiplier = %f, delayMultiplier = %f \n", + // obj->getTemplate()->getName().str(), x, y, z, sys->getBurstCountMultiplier(), sys->getBurstDelayMultiplier())); + } + + //DEBUG_LOG((">>>ADSU: spawned particle system with lifetime '%d'.\n", + // data->m_bonusDuration)); + } + } + } + + // Apply DamageFX + + if (data->m_damageFx) { + body->overrideDamageFX(data->m_damageFx); + } + +} +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +void ArmorDamageScalarUpdate::removeEffectFromObject(Object* obj) { + const ArmorDamageScalarUpdateModuleData* data = getArmorDamageScalarUpdateModuleData(); + BodyModuleInterface* body = obj->getBodyModule(); + Real scalar = 1.0f / __max(data->m_armorDamageScalar, 0.01f); + body->applyDamageScalar(scalar); + + //DEBUG_LOG((">>>ADSU: apply (=remove) scalar '%f' to obj '%s' - new scalar = '%f' \n", + // scalar, obj->getTemplate()->getName().str(), body->getDamageScalar())); + + if (data->m_damageFx) { + body->overrideDamageFX(NULL); + } + + Drawable* drw = obj->getDrawable(); + + if (data->m_tintStatus > TINT_STATUS_INVALID && data->m_tintStatus < TINT_STATUS_COUNT) + { + drw->clearTintStatus(data->m_tintStatus); + } + +} + +// ------------------------------------------------------------------------------------------------ +/** CRC */ +// ------------------------------------------------------------------------------------------------ +void ArmorDamageScalarUpdate::crc( Xfer *xfer ) +{ + + // extend base class + UpdateModule::crc( xfer ); + +} // end crc + +// ------------------------------------------------------------------------------------------------ +/** Xfer method + * Version Info: + * 1: Initial version */ +// ------------------------------------------------------------------------------------------------ +void ArmorDamageScalarUpdate::xfer( Xfer *xfer ) +{ + + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + // extend base class + UpdateModule::xfer( xfer ); + + // affected objects + Int vectorSize = m_affectedObjects.size(); + xfer->xferInt(&vectorSize); + m_affectedObjects.resize(vectorSize); + for (Int vectorIndex = 0; vectorIndex < vectorSize; ++vectorIndex) + { + xfer->xferObjectID(&m_affectedObjects[vectorIndex]); + } + + // die frame + xfer->xferUnsignedInt(&m_dieFrame); + + // effect applied + xfer->xferBool(&m_effectApplied); + + +} // end xfer + +// ------------------------------------------------------------------------------------------------ +/** Load post process */ +// ------------------------------------------------------------------------------------------------ +void ArmorDamageScalarUpdate::loadPostProcess( void ) +{ + + // extend base class + UpdateModule::loadPostProcess(); + +} // end loadPostProcess diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp index 012fca881b..c5c7b65013 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AssistedTargetingUpdate.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Module/LaserUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp index fc11e6a043..88dadb8472 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/BattlePlanUpdate.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/Module/StealthDetectorUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp index b983748537..8e5f84d865 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CleanupHazardUpdate.cpp @@ -46,7 +46,7 @@ #include "GameLogic/WeaponSet.h" #include "GameLogic/Module/AIUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp index 84dff87f71..9c9422fcfb 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/CommandButtonHuntUpdate.cpp @@ -52,7 +52,7 @@ #include "GameLogic/Module/SpecialPowerModule.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp index 4564a9bdb6..6261c61fe7 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DeletionUpdate.cpp @@ -59,7 +59,7 @@ DeletionUpdate::~DeletionUpdate( void ) void DeletionUpdate::setLifetimeRange( UnsignedInt minFrames, UnsignedInt maxFrames ) { -#if defined _DEBUG && defined CRISS_CROSS_GEOMETRY +#if defined RTS_DEBUG && defined CRISS_CROSS_GEOMETRY setWakeFrame(getObject(), UPDATE_SLEEP(2)); #else UnsignedInt delay = calcSleepDelay(minFrames, maxFrames); @@ -82,7 +82,7 @@ UnsignedInt DeletionUpdate::calcSleepDelay(UnsignedInt minFrames, UnsignedInt ma UpdateSleepTime DeletionUpdate::update( void ) { // Destroy (NOT kill) if time is up -#if defined _DEBUG && defined CRISS_CROSS_GEOMETRY +#if defined RTS_DEBUG && defined CRISS_CROSS_GEOMETRY Object *obj = getObject(); if (obj) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp index b3571f6463..75a770a214 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp @@ -510,7 +510,9 @@ void DockUpdate::loadDockPositions() if( m_numberApproachPositions != DYNAMIC_APPROACH_VECTOR_FLAG ) { // Dynamic means no bones - Coord3D approachBones[DEFAULT_APPROACH_VECTOR_SIZE]; + // TheSuperHackers @fix helmutbuhler 19/04/2025 Zero initialize array to prevent uninitialized memory reads. + // Important: the entire target vector is used for serialization and crc and must not contain random data. + Coord3D approachBones[DEFAULT_APPROACH_VECTOR_SIZE] = {0}; m_numberApproachPositionBones = myDrawable->getPristineBonePositions( "DockWaiting", 1, approachBones, NULL, m_numberApproachPositions); if( m_numberApproachPositions == m_approachPositions.size() )//safeguard: will always be true { diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp index 36a22de319..8cf7600af4 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyCenterDockUpdate.cpp @@ -37,7 +37,7 @@ #include "GameClient/InGameUI.h" #include "GameClient/GameText.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp index a4401324ce..a96848cc68 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/SupplyWarehouseDockUpdate.cpp @@ -38,7 +38,7 @@ #include "GameLogic/PartitionManager.h" #include "GameLogic/AIPathfind.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp index 6645735369..8f26958d6c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DynamicShroudClearingRangeUpdate.cpp @@ -37,7 +37,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp index ec97804814..89ba4e2022 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/EMPUpdate.cpp @@ -50,7 +50,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp index 44bcecc6ea..0cf18532c8 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireOCLAfterWeaponCooldownUpdate.cpp @@ -51,7 +51,7 @@ #include "GameLogic/Module/AIUpdate.h" #include "GameLogic/Module/BodyModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp index 6ae3e34d4e..e645bd874e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireSpreadUpdate.cpp @@ -51,7 +51,7 @@ class PartitionFilterFlammable : public PartitionFilter PartitionFilterFlammable(){ } virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterFlammable"; } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp index b242dd1f6a..679b479896 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FireWeaponUpdate.cpp @@ -37,7 +37,7 @@ #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp index 261723aa9e..05bf0b0bce 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/FloatUpdate.cpp @@ -40,7 +40,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp index e9dba36d5d..e9c7ea6ae9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HeightDieUpdate.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Module/HeightDieUpdate.h" #include "GameLogic/Module/PhysicsUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp index fb0c9777ad..03d590984a 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp @@ -55,7 +55,7 @@ /////////////////////////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp index bdcb9e9e2d..0dca314a71 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp @@ -47,7 +47,7 @@ //------------------------------------------------------------------------------------------------- -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -79,7 +79,7 @@ class PartitionFilterHordeMember : public PartitionFilter PartitionFilterHordeMember(Object* obj, const HordeUpdateModuleData* data) : m_obj(obj), m_data(data) { } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterHordeMember"; } #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp index 190b4843d2..5ba5678489 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp @@ -30,6 +30,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine +#include "Common/GlobalData.h" #include "Common/Player.h" #include "Common/PlayerList.h" #include "Common/Xfer.h" @@ -41,9 +42,10 @@ #include "GameLogic/Object.h" #include "GameLogic/GameLogic.h" // For frame number #include "GameLogic/Module/LaserUpdate.h" +#include "GameLogic/Module/LifetimeUpdate.h" // for beam lifetime #include "WWMath/vector3.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -54,6 +56,12 @@ LaserUpdateModuleData::LaserUpdateModuleData() { m_punchThroughScalar = 0.0f; + m_fadeInDurationFrames = 0; + m_fadeOutDurationFrames = 0; + m_widenDurationFrames = 0; + m_decayDurationFrames = 0; + m_hasMultiDraw = FALSE; + m_useHouseColor = FALSE; } //------------------------------------------------------------------------------------------------- @@ -66,6 +74,12 @@ LaserUpdateModuleData::LaserUpdateModuleData() { "MuzzleParticleSystem", INI::parseAsciiString, NULL, offsetof( LaserUpdateModuleData, m_particleSystemName ) }, { "TargetParticleSystem", INI::parseAsciiString, NULL, offsetof( LaserUpdateModuleData, m_targetParticleSystemName ) }, { "PunchThroughScalar", INI::parseReal, NULL, offsetof( LaserUpdateModuleData, m_punchThroughScalar ) }, + { "BeamFadeInDuration", INI::parseDurationUnsignedInt, NULL, offsetof(LaserUpdateModuleData, m_fadeInDurationFrames) }, + { "BeamFadeOutDuration", INI::parseDurationUnsignedInt, NULL, offsetof(LaserUpdateModuleData, m_fadeOutDurationFrames) }, + { "BeamGrowDuration", INI::parseDurationUnsignedInt, NULL, offsetof(LaserUpdateModuleData, m_widenDurationFrames) }, + { "BeamShrinkDuration", INI::parseDurationUnsignedInt, NULL, offsetof(LaserUpdateModuleData, m_decayDurationFrames) }, + { "UseMultiLaserDraw", INI::parseBool, NULL, offsetof(LaserUpdateModuleData, m_hasMultiDraw) }, + { "UseHouseColoredParticles", INI::parseBool, NULL, offsetof(LaserUpdateModuleData, m_useHouseColor) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); @@ -90,9 +104,22 @@ LaserUpdate::LaserUpdate( Thing *thing, const ModuleData* moduleData ) : ClientU m_decaying = false; m_decayStartFrame = 0; m_decayFinishFrame = 0; + + m_fadingIn = false; + m_fadeInStartFrame = 0; + m_fadeInFinishFrame = 0; + m_currentAlphaScalar = 1.0f; + m_fadingOut = false; + m_fadeOutStartFrame = 0; + m_fadeOutFinishFrame = 0; + m_parentID = INVALID_DRAWABLE_ID; m_targetID = INVALID_DRAWABLE_ID; m_parentBoneName.clear(); + + m_hexColor = 0; + + // m_isMultiDraw = FALSE; } //------------------------------------------------------------------------------------------------- @@ -143,6 +170,16 @@ void LaserUpdate::updateStartPos() m_startPos.x = startPosMatrix.Get_X_Translation(); m_startPos.y = startPosMatrix.Get_Y_Translation(); m_startPos.z = startPosMatrix.Get_Z_Translation(); + + // Update ParticleSystem Position + if (m_particleSystemID) + { + ParticleSystem* system = TheParticleSystemManager->findParticleSystem(m_particleSystemID); + if (system) + { + system->setPosition(&m_startPos); + } + } } else { @@ -202,9 +239,12 @@ void LaserUpdate::clientUpdate( void ) updateStartPos(); updateEndPos(); + UnsignedInt now = TheGameLogic->getFrame(); + if (m_decayStartFrame > 0 && now > m_decayStartFrame) + m_decaying = true; + if( m_decaying ) { - UnsignedInt now = TheGameLogic->getFrame(); m_currentWidthScalar = 1.0f - (Real)(now - m_decayStartFrame) / (Real)(m_decayFinishFrame - m_decayStartFrame); m_dirty = true; if( m_currentWidthScalar <= 0.0f ) @@ -219,7 +259,6 @@ void LaserUpdate::clientUpdate( void ) else if( m_widening ) { //We need to resize our laser width based on the growth ratio completed. - UnsignedInt now = TheGameLogic->getFrame(); m_currentWidthScalar = (Real)(now - m_widenStartFrame) / (Real)(m_widenFinishFrame - m_widenStartFrame); m_dirty = true; if( m_currentWidthScalar >= 1.0f ) @@ -228,6 +267,32 @@ void LaserUpdate::clientUpdate( void ) m_widening = false; } } + + if (m_fadeOutStartFrame > 0 && now > m_fadeOutStartFrame) + m_fadingOut = true; + + if (m_fadingOut) + { + m_currentAlphaScalar = 1.0f - (Real)(now - m_fadeOutStartFrame) / (Real)(m_fadeOutFinishFrame - m_fadeOutStartFrame); + m_dirty = true; + if (m_currentAlphaScalar <= 0.0f) + { + m_currentAlphaScalar = 0.0f; + return; + } + } + else if (m_fadingIn) + { + //We need to resize our laser width based on the growth ratio completed. + m_currentAlphaScalar = (Real)(now - m_fadeInStartFrame) / (Real)(m_fadeInFinishFrame - m_fadeInStartFrame); + m_dirty = true; + if (m_currentAlphaScalar >= 1.0f) + { + m_currentAlphaScalar = 1.0f; + m_fadingIn = false; + } + } + return; } @@ -246,8 +311,10 @@ void LaserUpdate::setDecayFrames( UnsignedInt decayFrames ) //------------------------------------------------------------------------------------------------- void LaserUpdate::initLaser( const Object *parent, const Object *target, const Coord3D *startPos, const Coord3D *endPos, AsciiString parentBoneName, Int sizeDeltaFrames ) { + m_startFrame = TheGameLogic->getFrame(); const LaserUpdateModuleData *data = getLaserUpdateModuleData(); ParticleSystem *system; + // ParticleCannon logic if( sizeDeltaFrames > 0 ) { m_widening = true; @@ -263,6 +330,51 @@ void LaserUpdate::initLaser( const Object *parent, const Object *target, const C m_currentWidthScalar = 1.0f; } + // Try to get beam lifetime + Drawable* draw = getDrawable(); + if (draw) { + Object* obj = draw->getObject(); + if (obj) { + static NameKeyType key_LifetimeUpdate = NAMEKEY("LifetimeUpdate"); + LifetimeUpdate* update = (LifetimeUpdate*)obj->findUpdateModule(key_LifetimeUpdate); + if (update) { + m_dieFrame = update->getDieFrame(); + } + + //if (m_useHouseColor) { + if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) + m_hexColor = obj->getNightIndicatorColor(); + else + m_hexColor = obj->getIndicatorColor(); + + //} + } + } + + // Set up Fade/Widen from module data + if (data->m_widenDurationFrames > 0) { + m_widening = true; + m_widenStartFrame = TheGameLogic->getFrame(); + m_widenFinishFrame = m_widenStartFrame + data->m_widenDurationFrames; + m_currentWidthScalar = 0.0f; + } + if (data->m_fadeInDurationFrames > 0) { + m_fadingIn = true; + m_fadeInStartFrame = TheGameLogic->getFrame(); + m_fadeInFinishFrame = m_fadeInStartFrame + data->m_fadeInDurationFrames; + m_currentAlphaScalar = 0.0f; + } + if (m_dieFrame > 0) { + if (data->m_decayDurationFrames > 0) { + m_decayFinishFrame = m_dieFrame; + m_decayStartFrame = m_decayFinishFrame - data->m_decayDurationFrames; + } + if (data->m_fadeOutDurationFrames > 0) { + m_fadeOutFinishFrame = m_dieFrame; + m_fadeOutStartFrame = m_fadeOutFinishFrame - data->m_fadeOutDurationFrames; + } + } + // Write down the bone name override m_parentBoneName = parentBoneName; @@ -327,6 +439,9 @@ void LaserUpdate::initLaser( const Object *parent, const Object *target, const C if( system ) { m_particleSystemID = system->getSystemID(); + if (data->m_useHouseColor) { + system->tintColorsAllFrames(m_hexColor); + } } } } @@ -341,6 +456,9 @@ void LaserUpdate::initLaser( const Object *parent, const Object *target, const C if( system ) { m_targetParticleSystemID = system->getSystemID(); + if (data->m_useHouseColor) { + system->tintColorsAllFrames(m_hexColor); + } } } } @@ -383,14 +501,135 @@ void LaserUpdate::initLaser( const Object *parent, const Object *target, const C posToUse = *parent->getPosition(); } - Drawable *draw = getDrawable(); + // Drawable *draw = getDrawable(); if( draw ) { + // When initializing the laser, keep track if it has multiple draw modules. + // Update: This is a very special case, makes more sense to set it in INI, rather than check it every time + /* int numDraws = 0; + LaserDrawInterface* ldi = NULL; + for (DrawModule** d = draw->getDrawModules(); *d; ++d) + { + ldi = (*d)->getLaserDrawInterface(); + if (ldi) + { + numDraws++; + } + } + if (numDraws > 1) { + m_isMultiDraw = TRUE; + }*/ + draw->setPosition( &posToUse ); } m_dirty = true; } +//------------------------------------------------------------------------------------------------- +void LaserUpdate::updateContinuousLaser(const Object* parent, const Object* target, const Coord3D* startPos, const Coord3D* endPos) +{ + m_startFrame = TheGameLogic->getFrame(); + const LaserUpdateModuleData* data = getLaserUpdateModuleData(); + ParticleSystem* system; + + // Try to get beam lifetime (assuming it was updated before callin this function) + Drawable* draw = getDrawable(); + if (draw) { + Object* obj = draw->getObject(); + if (obj) { + static NameKeyType key_LifetimeUpdate = NAMEKEY("LifetimeUpdate"); + LifetimeUpdate* update = (LifetimeUpdate*)obj->findUpdateModule(key_LifetimeUpdate); + if (update) { + m_dieFrame = update->getDieFrame(); + } + } + } + + // Update fadeOut/Decay frames + if (m_dieFrame > 0) { + if (data->m_decayDurationFrames > 0) { + m_decayFinishFrame = m_dieFrame; + m_decayStartFrame = m_decayFinishFrame - data->m_decayDurationFrames; + } + if (data->m_fadeOutDurationFrames > 0) { + m_fadeOutFinishFrame = m_dieFrame; + m_fadeOutStartFrame = m_fadeOutFinishFrame - data->m_fadeOutDurationFrames; + } + } + + if (target && !endPos) + { + // If a target object, use it (unless we override it!) + if (target->getDrawable()) + m_targetID = target->getDrawable()->getID(); + + m_endPos = *target->getPosition(); + } + else if (endPos) + { + // just use what they gave, no override here + m_endPos = *endPos; + } + else + { + // if they gave nothing, then we are screwed + TheGameClient->destroyDrawable(getDrawable()); + return; + } + + //Adjust the position of any existing particle system. + //PLEASE NOTE You cannot check an ID for NULL. This should be a check against INVALID_PARTICLE_SYSTEM_ID. Can't change it on the last day without a bug though. + if (m_particleSystemID) + { + system = TheParticleSystemManager->findParticleSystem(m_particleSystemID); + if (system) + { + system->setPosition(&m_startPos); + } + } + + //PLEASE NOTE You cannot check an ID for NULL. This should be a check against INVALID_PARTICLE_SYSTEM_ID. Can't change it on the last day without a bug though. + if (m_targetParticleSystemID) + { + system = TheParticleSystemManager->findParticleSystem(m_targetParticleSystemID); + if (system) + { + system->setPosition(&m_endPos); + } + } + + //Important! Set the laser position to the average of both points or else + //it probably won't get rendered!!! + // And as a client update, we cannot set the logic position. + Coord3D posToUse; + if (parent == NULL) + { + posToUse.set(startPos); + posToUse.add(endPos); + posToUse.scale(0.5); + } + else + { + posToUse = *parent->getPosition(); + } + + // Drawable *draw = getDrawable(); + if (draw) + { + draw->setPosition(&posToUse); + } + + m_dirty = true; +} +//------------------------------------------------------------------------------------------------ + +Real LaserUpdate::getLifeTimeProgress() const +{ + if (m_startFrame > 0 && m_dieFrame > 0) { + return (Real)(TheGameLogic->getFrame() - m_startFrame) / (Real)(m_dieFrame - m_startFrame); + } + return 0.0f; +} //------------------------------------------------------------------------------------------------- Real LaserUpdate::getCurrentLaserRadius() const @@ -454,6 +693,12 @@ void LaserUpdate::xfer( Xfer *xfer ) // target particle system id xfer->xferUser( &m_targetParticleSystemID, sizeof( ParticleSystemID ) ); + // start frame + xfer->xferUnsignedInt(&m_startFrame); + + // die frame + xfer->xferUnsignedInt(&m_dieFrame); + // widening xfer->xferBool( &m_widening ); @@ -475,11 +720,37 @@ void LaserUpdate::xfer( Xfer *xfer ) // decay finish frame xfer->xferUnsignedInt( &m_decayFinishFrame ); + // fadingIn + xfer->xferBool(&m_fadingIn); + + // fadingOut + xfer->xferBool(&m_fadingOut); + + // fade in start frame + xfer->xferUnsignedInt(&m_fadeInStartFrame); + + // fade in finish frame + xfer->xferUnsignedInt(&m_fadeInFinishFrame); + + // current alpha scalar + xfer->xferReal(&m_currentAlphaScalar); + + // fade out start frame + xfer->xferUnsignedInt(&m_fadeOutStartFrame); + + // fade out finish frame + xfer->xferUnsignedInt(&m_fadeOutFinishFrame); + xfer->xferDrawableID(&m_parentID); xfer->xferDrawableID(&m_targetID); xfer->xferAsciiString(&m_parentBoneName); + xfer->xferInt(&m_hexColor); + + // multi draw + // xfer->xferBool(&m_isMultiDraw); + } // end xfer // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp index 34e05d6a4b..e0f187d97d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LifetimeUpdate.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Module/LifetimeUpdate.h" #include "GameLogic/Object.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -78,6 +78,15 @@ void LifetimeUpdate::setLifetimeRange( UnsignedInt minFrames, UnsignedInt maxFra setWakeFrame(getObject(), UPDATE_SLEEP(delay)); } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void LifetimeUpdate::resetLifetime(void) +{ + const LifetimeUpdateModuleData* d = getLifetimeUpdateModuleData(); + UnsignedInt delay = delay = calcSleepDelay(d->m_minFrames, d->m_maxFrames); + setWakeFrame(getObject(), UPDATE_SLEEP(delay)); +} + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- UnsignedInt LifetimeUpdate::calcSleepDelay(UnsignedInt minFrames, UnsignedInt maxFrames) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp index 5a0c4cb02d..e8a349afa5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MissileLauncherBuildingUpdate.cpp @@ -42,7 +42,7 @@ #include "GameClient/Drawable.h" #include "GameClient/FXList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -186,7 +186,7 @@ void MissileLauncherBuildingUpdate::switchToState(DoorStateType dst) TheAudio->removeAudioEvent(m_openIdleAudio.getPlayingHandle()); } break; -#ifdef _DEBUG +#ifdef RTS_DEBUG default: DEBUG_CRASH(("unknown state")); break; @@ -211,7 +211,7 @@ Bool MissileLauncherBuildingUpdate::initiateIntentToDoSpecialPower( const Specia return FALSE; } -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) DEBUG_ASSERTCRASH(!TheGlobalData->m_specialPowerUsesDelay || m_doorState == DOOR_OPEN, ("door is not fully open when specialpower is fired!")); #endif @@ -258,7 +258,7 @@ UpdateSleepTime MissileLauncherBuildingUpdate::update( void ) switchToState(m_timeoutState); } -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) DEBUG_ASSERTCRASH(!TheGlobalData->m_specialPowerUsesDelay || !(m_specialPowerModule->isReady() && m_doorState != DOOR_OPEN), ("door is not fully open when specialpower is ready!")); #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp index 014c051599..6b07341869 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/MobMemberSlavedUpdate.cpp @@ -55,7 +55,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp index 144bf3c435..18fa210da2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/NeutronMissileUpdate.cpp @@ -528,7 +528,12 @@ UpdateSleepTime NeutronMissileUpdate::update( void ) } return UPDATE_SLEEP_NONE; } - +// ------------------------------------------------------------------------------------------------ +const Coord3D* NeutronMissileUpdate::getTargetPosition() +{ + const Coord3D* constPos = &m_targetPos; + return constPos; +} // ------------------------------------------------------------------------------------------------ /** CRC */ // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp index ea56a2e4da..68c2716aee 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ParticleUplinkCannonUpdate.cpp @@ -58,7 +58,7 @@ #include "GameLogic/Module/LaserUpdate.h" #include "GameLogic/Module/ActiveBody.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -942,7 +942,8 @@ void ParticleUplinkCannonUpdate::createGroundToOrbitLaser( UnsignedInt growthFra if( beam ) { TheGameClient->destroyDrawable( beam ); - m_orbitToTargetBeamID = INVALID_DRAWABLE_ID; + // TheSuperHackers @fix helmutbuhler 19/04/2025 Invalidate the relevant drawable ID. + m_groundToOrbitBeamID = INVALID_DRAWABLE_ID; } if( data->m_particleBeamLaserName.isNotEmpty() ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp index 343a23aee9..371fee36fd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PhysicsUpdate.cpp @@ -71,7 +71,7 @@ const Int MOTIVE_FRAMES = LOGICFRAMES_PER_SECOND / 3; #define SLEEPY_PHYSICS -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -140,6 +140,7 @@ PhysicsBehaviorModuleData::PhysicsBehaviorModuleData() m_pitchRollYawFactor = 2.0f; m_vehicleCrashesIntoBuildingWeaponTemplate = TheWeaponStore->findWeaponTemplate("VehicleCrashesIntoBuildingWeapon"); m_vehicleCrashesIntoNonBuildingWeaponTemplate = TheWeaponStore->findWeaponTemplate("VehicleCrashesIntoNonBuildingWeapon"); + m_vehicleCrashAllowAirborne = FALSE; } @@ -190,7 +191,7 @@ static void parseFrictionPerSec( INI* ini, void * /*instance*/, void *store, con { "VehicleCrashesIntoBuildingWeaponTemplate", INI::parseWeaponTemplate, NULL, offsetof(PhysicsBehaviorModuleData, m_vehicleCrashesIntoBuildingWeaponTemplate) }, { "VehicleCrashesIntoNonBuildingWeaponTemplate", INI::parseWeaponTemplate, NULL, offsetof(PhysicsBehaviorModuleData, m_vehicleCrashesIntoNonBuildingWeaponTemplate) }, - + { "VehicleCrashWeaponAllowAirborne", INI::parseBool, NULL, offsetof(PhysicsBehaviorModuleData, m_vehicleCrashAllowAirborne) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); @@ -963,21 +964,32 @@ Real PhysicsBehavior::getVelocityMagnitude() const Real PhysicsBehavior::getForwardSpeed2D() const { const Coord3D *dir = getObject()->getUnitDirectionVector2D(); - Real vx = m_vel.x * dir->x; Real vy = m_vel.y * dir->y; - Real dot = vx + vy; - Real speedSquared = vx*vx + vy*vy; -// DEBUG_ASSERTCRASH( speedSquared != 0, ("zero speedSquared will overflow sqrtf()!") );// lorenzen... sanity check - - Real speed = (Real)sqrtf( speedSquared ); + if (TheGlobalData->m_useOldMoveSpeed) { + + Real speedSquared = vx * vx + vy * vy; + // DEBUG_ASSERTCRASH( speedSquared != 0, ("zero speedSquared will overflow sqrtf()!") );// lorenzen... sanity check + + Real speed = (Real)sqrtf(speedSquared); + + if (dot >= 0.0f) + return speed; + + return -speed; + } + else { + //Note: using fixes from https://github.com/TheSuperHackers/GeneralsGameCode/issues/123#issuecomment-2827246587 - if (dot >= 0.0f) - return speed; + //Return the speed of the unit - Magnitude of the velocity is the speed + if (dot >= 0.0f) + return (Real)sqrtf(sqr(m_vel.x) + sqr(m_vel.y)); - return -speed; + //Negative dot product means the unit is moving in reverse + return -(Real)sqrtf(sqr(m_vel.x) + sqr(m_vel.y)); + } } //------------------------------------------------------------------------------------------------- @@ -988,19 +1000,29 @@ Real PhysicsBehavior::getForwardSpeed2D() const Real PhysicsBehavior::getForwardSpeed3D() const { Vector3 dir = getObject()->getTransformMatrix()->Get_X_Vector(); - Real vx = m_vel.x * dir.X; Real vy = m_vel.y * dir.Y; Real vz = m_vel.z * dir.Z; - Real dot = vx + vy + vz; - Real speed = (Real)sqrtf( vx*vx + vy*vy + vz*vz ); + if (TheGlobalData->m_useOldMoveSpeed) { + Real speed = (Real)sqrtf(vx * vx + vy * vy + vz * vz); + + if (dot >= 0.0f) + return speed; - if (dot >= 0.0f) - return speed; + return -speed; + } + else { + //Note: using fixes from https://github.com/TheSuperHackers/GeneralsGameCode/issues/123#issuecomment-2827246587 + + //Return the speed of the unit - Magnitude of the velocity is the speed + if (dot >= 0.0f) + return (Real)sqrtf(sqr(m_vel.x) + sqr(m_vel.y) + sqr(m_vel.z)); - return -speed; + //Negative dot product means the unit is moving in reverse + return -(Real)sqrtf(sqr(m_vel.x) + sqr(m_vel.y) + sqr(m_vel.z)); + } } //------------------------------------------------------------------------------------------------- @@ -1391,8 +1413,15 @@ void PhysicsBehavior::onCollide( Object *other, const Coord3D *loc, const Coord3 else { // fall into a nonbuilding -- whatever. if we're a vehicle, quietly do a little damage. - if (obj->isKindOf(KINDOF_VEHICLE)) + if (obj->isKindOf(KINDOF_VEHICLE) && (!other->isAirborneTarget() || getPhysicsBehaviorModuleData()->m_vehicleCrashAllowAirborne)) { + //DEBUG_LOG(( + // ">>> PhysicsUpdate - fire vehicleCrashesIntoNonBuildingWeapon; obj = %s (%d); other = %s (%d).\n", + // obj->getTemplate()->getName().str(), + // obj->getID(), + // other->getTemplate()->getName().str(), + // other->getID() + // )); TheWeaponStore->createAndFireTempWeapon(getPhysicsBehaviorModuleData()->m_vehicleCrashesIntoNonBuildingWeaponTemplate, obj, obj->getPosition()); } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp index 727f3b8675..26559bea17 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/PowerPlantUpdate.cpp @@ -38,7 +38,7 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/PowerPlantUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp index ef71b17c41..d93a370a60 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionExitUpdate/SupplyCenterProductionExitUpdate.cpp @@ -42,7 +42,7 @@ #include "GameLogic/Object.h" //#include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp index 7fe0250941..662d651266 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp @@ -55,7 +55,7 @@ #include "GameLogic/Object.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -218,6 +218,8 @@ ProductionUpdate::~ProductionUpdate( void ) production = m_productionQueue; removeFromProductionQueue( production ); + // TheSuperHackers @fix Mauller 13/04/2025 Delete instance of production item + production->deleteInstance(); } // end while diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp index 37aaaedc70..b16859b14f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProjectileStreamUpdate.cpp @@ -36,7 +36,7 @@ #include "GameLogic/Module/ProjectileStreamUpdate.h" #include "WWMath/vector3.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ScatterShotUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ScatterShotUpdate.cpp new file mode 100644 index 0000000000..702acfc1b8 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ScatterShotUpdate.cpp @@ -0,0 +1,621 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ScatterShotUpdate.cpp //////////////////////////////////////////////////////////////////// +// Author: Andi W, April 2025 +// Desc: Projectile Scatter/Airburst module +/////////////////////////////////////////////////////////////////////////////////////////////////// + +// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// +#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine + +#define DEFINE_DEATH_NAMES + +#include "Common/Xfer.h" +#include "Common/PlayerList.h" +#include "Common/Player.h" +#include "GameLogic/Object.h" +#include "GameLogic/Damage.h" +#include "GameLogic/Module/ScatterShotUpdate.h" +#include "GameLogic/Module/ContainModule.h" +#include "GameLogic/Module/StealthUpdate.h" +#include "GameLogic/WeaponStatus.h" +#include "GameLogic/GameLogic.h" +#include "GameLogic/PartitionManager.h" +#include "GameLogic/WeaponSet.h" +#include "GameLogic/TerrainLogic.h" +#include "GameClient/FXList.h" + +//------------------------------------------------------------------------------------------------- +ScatterShotUpdateModuleData::ScatterShotUpdateModuleData() +{ + m_weaponTemplate = NULL; + m_numShots = 0; + m_targetSearchRadius = 0; + m_targetMinRadius = 0; + m_maxShotsPerTarget = 0; + m_preferSimilarTargets = false; + m_preferNearestTargets = false; + m_attackGroundWhenNoTargets = true; + m_noTargetsScatterRadius = 0; + + m_triggerDistanceToTarget = 0; + //m_triggerDistanceFromSource = 0; + m_triggerDistancePercent = 0; + m_triggerLifetime = 0; + m_triggerOnImpact = false; + m_triggerInstantly = false; + m_stayAliveAfterTrigger = false; + + m_triggerDeathType = DEATH_NORMAL; + m_scatterFX = NULL; +} + + +//------------------------------------------------------------------------------------------------- +/*static*/ void ScatterShotUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + UpdateModuleData::buildFieldParse(p); + + static const FieldParse dataFieldParse[] = + { + { "Weapon", INI::parseWeaponTemplate, NULL, offsetof(ScatterShotUpdateModuleData, m_weaponTemplate) }, + { "NumShots", INI::parseUnsignedInt, NULL, offsetof(ScatterShotUpdateModuleData, m_numShots) }, + { "TargetSearchRadius", INI::parseReal, NULL, offsetof(ScatterShotUpdateModuleData, m_targetSearchRadius) }, + { "TargetMinRadius", INI::parseReal, NULL, offsetof(ScatterShotUpdateModuleData, m_targetMinRadius) }, + { "MaxShotsPerTarget", INI::parseUnsignedInt, NULL, offsetof(ScatterShotUpdateModuleData, m_maxShotsPerTarget) }, + { "PreferSimilarTargets", INI::parseBool, NULL, offsetof(ScatterShotUpdateModuleData, m_preferSimilarTargets) }, + { "PreferNearestTargets", INI::parseBool, NULL, offsetof(ScatterShotUpdateModuleData, m_preferNearestTargets) }, + { "NoTargetsScatterRadius", INI::parseReal, NULL, offsetof(ScatterShotUpdateModuleData, m_noTargetsScatterRadius) }, + { "AttackGroundWhenNoTargets", INI::parseBool, NULL, offsetof(ScatterShotUpdateModuleData, m_attackGroundWhenNoTargets) }, + + { "TriggerDistanceToTarget", INI::parseReal, NULL, offsetof(ScatterShotUpdateModuleData, m_triggerDistanceToTarget) }, + //{ "TriggerDistanceFromSource", INI::parseReal, NULL, offsetof(ScatterShotUpdateModuleData, m_triggerDistanceFromSource) }, + { "TriggerDistancePercent", INI::parsePercentToReal, NULL, offsetof(ScatterShotUpdateModuleData, m_triggerDistancePercent) }, + { "TriggerLifetime", INI::parseDurationUnsignedInt, NULL, offsetof(ScatterShotUpdateModuleData, m_triggerLifetime) }, + { "TriggerOnImpact", INI::parseBool, NULL, offsetof(ScatterShotUpdateModuleData, m_triggerOnImpact) }, + { "TriggerInstantly", INI::parseBool, NULL, offsetof(ScatterShotUpdateModuleData, m_triggerInstantly) }, + { "StayAliveAfterTrigger", INI::parseBool, NULL, offsetof(ScatterShotUpdateModuleData, m_stayAliveAfterTrigger) }, + + { "TriggeredDeathType", INI::parseIndexList, TheDeathNames, offsetof(ScatterShotUpdateModuleData, m_triggerDeathType) }, + { "ScatterFX", INI::parseFXList, NULL, offsetof(ScatterShotUpdateModuleData, m_scatterFX) }, + + //{ "InitialDelay", INI::parseDurationUnsignedInt, NULL, offsetof(ScatterShotUpdateModuleData, m_initialDelayFrames) }, + //{ "ExclusiveWeaponDelay", INI::parseDurationUnsignedInt, NULL, offsetof(ScatterShotUpdateModuleData, m_exclusiveWeaponDelay) }, + { 0, 0, 0, 0 } + }; + p.add(dataFieldParse); +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ScatterShotUpdate::ScatterShotUpdate(Thing* thing, const ModuleData* moduleData) : + UpdateModule(thing, moduleData), + m_weapon(NULL) +{ + const ScatterShotUpdateModuleData* data = getScatterShotUpdateModuleData(); + + const WeaponTemplate* tmpl = data->m_weaponTemplate; + if (tmpl) + { + m_weapon = TheWeaponStore->allocateNewWeapon(tmpl, PRIMARY_WEAPON); + m_weapon->loadAmmoNow(getObject()); + } + + m_goalObj = NULL; + //m_goalPos.clear(); + + m_totalTargetDistance = 0; + + m_hasTriggered = false; + m_isInitialized = false; + +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ScatterShotUpdate::~ScatterShotUpdate(void) +{ + if (m_weapon) + m_weapon->deleteInstance(); + m_goalObj = NULL; +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +UpdateSleepTime ScatterShotUpdate::update(void) +{ + // DEBUG_LOG((">>> SSU Update 1\n")); + const ScatterShotUpdateModuleData* data = getScatterShotUpdateModuleData(); + + if (!m_isInitialized) { + ProjectileUpdateInterface* pui = NULL; + for (BehaviorModule** u = getObject()->getBehaviorModules(); *u; ++u) + { + if ((pui = (*u)->getProjectileUpdateInterface()) != NULL) + break; + } + if (pui) { + if (pui->projectileGetLauncherID() != 0 && pui->projectileIsArmed()) { + const Coord3D* pos = pui->getTargetPosition(); + m_goalPos.x = pos->x; + m_goalPos.y = pos->y; + m_goalPos.z = pos->z; + + m_goalObj = pui->getTargetObject(); + + //m_weapon->setBonusRefObjID(pui->projectileGetLauncherID()); + + // We propagate the Weapon bonus from the launcher to the projectile + Object* launcher = NULL; + ObjectID launcherID = pui->projectileGetLauncherID(); + if (launcherID != INVALID_ID) { + launcher = TheGameLogic->findObjectByID(launcherID); + } + if (launcher) { + // Copy weapon bonus flags from the launcher to this projectile + WeaponBonusConditionFlags bonusFlags = launcher->getWeaponBonusCondition(); + getObject()->setWeaponBonusConditionFlags(bonusFlags); + } + if (data->m_triggerDistancePercent > 0) { + m_totalTargetDistance = getTargetDistance(); + } + } + else { + // We are not launched yet. + return UPDATE_SLEEP_NONE; + } + } // We are not a projectile at all. We scatter in place + else { + const Coord3D* pos = getObject()->getPosition(); + m_goalPos.x = pos->x; + m_goalPos.y = pos->y; + m_goalPos.z = pos->z; + } + + if (data->m_triggerLifetime > 0) { + m_initialDelayFrame = TheGameLogic->getFrame() + data->m_triggerLifetime; + } + + m_isInitialized = true; + } + + if (m_hasTriggered) { + // DEBUG_LOG((">>> SSU Update 2 - hasTriggered\n")); + return UPDATE_SLEEP_FOREVER; + } + + // Instant Trigger + if (data->m_triggerInstantly) { + triggerScatterShot(); + return UPDATE_SLEEP_NONE; + } + + // Lifetime Trigger + if (data->m_triggerLifetime > 0 && TheGameLogic->getFrame() >= m_initialDelayFrame) { + /*DEBUG_LOG((">>> SSU Update - lifetimeTrigger: m_triggerLifetime = %d, now = %d, m_initialDelayFrame = %d.\n", + data->m_triggerLifetime, TheGameLogic->getFrame(), m_initialDelayFrame));*/ + triggerScatterShot(); + return UPDATE_SLEEP_NONE; + } + + // Distance to target Trigger + if (data->m_triggerDistancePercent > 0 || data->m_triggerDistanceToTarget > 0) { + + Real targetDistance = getTargetDistance(); + + if (data->m_triggerDistanceToTarget > 0 && targetDistance < data->m_triggerDistanceToTarget) { + triggerScatterShot(); + + // DEBUG_LOG((">>> SSU Update - after triggerScatterShot\n")); + + return UPDATE_SLEEP_NONE; + } + + if (data->m_triggerDistancePercent > 0 && + m_totalTargetDistance > 0 && + (targetDistance / m_totalTargetDistance) > data->m_triggerDistancePercent) { + triggerScatterShot(); + return UPDATE_SLEEP_NONE; + } + + } + + // Note: Disabled; I don't think this is a use case at all + // Distance from source Trigger + //if (data->m_triggerDistanceFromSource > 0) { + //} + + return UPDATE_SLEEP_NONE; +} + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ + +void ScatterShotUpdate::triggerScatterShot(void) +{ + // DEBUG_LOG((">>> SSU - triggerScatterShot 1\n")); + m_hasTriggered = TRUE; + + const ScatterShotUpdateModuleData* data = getScatterShotUpdateModuleData(); + + const Coord3D* pos; + if (m_goalObj != NULL) { + pos = m_goalObj->getPosition(); + } + else { + pos = &m_goalPos; + } + + FXList::doFXObj(data->m_scatterFX, getObject()); + + // Just check this when looping + // + //if (!(m_weapon->getTemplate()->getAntiMask() & WEAPON_ANTI_GROUND)) { + // PartitionFilterRejectByObjectStatus filterStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_AIRBORNE_TARGET), OBJECT_STATUS_MASK_NONE); + // filters[numFilters++] = &filterStatus; + //} + //if (!(m_weapon->getTemplate()->getAntiMask() & WEAPON_ANTI_AIRBORNE_VEHICLE)) { + // else { + // PartitionFilterRejectByObjectStatus filterStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_AIRBORNE_TARGET), OBJECT_STATUS_MASK_NONE); + // } + //} + + //Prefer similar targets + + int shotsLeft = data->m_numShots; + int shotsLeftPerTarget = data->m_maxShotsPerTarget; + + // DEBUG_LOG((">>> SSU - triggerScatterShot 2\n")); + + //WeaponSet weaponSet(m_weapon); + + // DEBUG_LOG((">>> SSU - triggerScatterShot 3\n")); + + // We always try to fire at the Original weapon's target first + bool mainTargetShot = FALSE; + if (shotsLeftPerTarget > 0 && shotsLeft > 0 && data->m_targetMinRadius <= 0) { + if ((m_goalObj) && isValidTarget(m_goalObj)) { + // DEBUG_LOG((">>> SSU - fireWeapon at target Obj\n")); + m_weapon->fireWeapon(getObject(), m_goalObj); + // Bool status = m_weapon->fireWeapon(getObject(), m_goalObj); + // DEBUG_LOG((">>> SSU - fireWeapon success = %s\n", status ? "true" : "false")); + //m_weapon->loadAmmoNow(getObject()); + //weaponSet.reloadAllAmmo(getObject(), true); + shotsLeft--; + mainTargetShot = TRUE; + } + } + + // If we have shots left (and shots per target), look for targets in range + if (shotsLeftPerTarget > 0 && shotsLeft > 0 && data->m_targetSearchRadius > 0) { + IterOrderType orderType = ITER_FASTEST; + if (data->m_preferNearestTargets) orderType = ITER_SORTED_NEAR_TO_FAR; + + PartitionFilterRelationship relationship(getObject(), PartitionFilterRelationship::ALLOW_ENEMIES); + PartitionFilterSameMapStatus filterMapStatus(getObject()); + PartitionFilterAlive filterAlive; + + PartitionFilter* filters[8]; + Int numFilters = 0; + filters[numFilters++] = &relationship; + filters[numFilters++] = &filterAlive; + filters[numFilters++] = &filterMapStatus; + // if preferSimilar is set, we either get ONLY AIR, or ONLY GROUND targets + if (data->m_preferSimilarTargets && m_goalObj != NULL) { + if (m_goalObj->isAirborneTarget()) { + PartitionFilterAcceptByObjectStatus filterStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_AIRBORNE_TARGET), OBJECT_STATUS_MASK_NONE); + filters[numFilters++] = &filterStatus; + } + else { + PartitionFilterRejectByObjectStatus filterStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_AIRBORNE_TARGET), OBJECT_STATUS_MASK_NONE); + filters[numFilters++] = &filterStatus; + } + } + filters[numFilters] = NULL; + + ObjectIterator* iter = ThePartitionManager->iterateObjectsInRange( + pos, data->m_targetSearchRadius, + FROM_CENTER_3D, filters, orderType); //2D or 3D search radius?? + + // Iterate over targets + while (shotsLeftPerTarget > 0 && shotsLeft > 0) { + + for (Object* obj = iter->first(); obj; obj = iter->next()) + { + if (shotsLeft == 0) break; + + if (obj == m_goalObj && mainTargetShot) continue; + + if (data->m_targetMinRadius > 0 && sqrt(ThePartitionManager->getDistanceSquared(getObject(), obj->getPosition(), FROM_CENTER_3D)) <= data->m_targetMinRadius) continue; + + if (isValidTarget(obj)) { + // DEBUG_LOG((">>> SSU - fireWeapon at target Obj\n")); + m_weapon->fireWeapon(getObject(), obj); + // Bool status = m_weapon->fireWeapon(getObject(), obj); + // DEBUG_LOG((">>> SSU - fireWeapon success = %s\n", status ? "true" : "false")); + //m_weapon->loadAmmoNow(getObject()); + //weaponSet.reloadAllAmmo(getObject(), true); + shotsLeft--; + } + } + mainTargetShot = FALSE; // We only care in the first run + shotsLeftPerTarget--; + } + } + + // DEBUG_LOG((">>> SSU - triggerScatterShot 4\n")); + + // Each leftover shot is fired randomly to the ground + while (shotsLeft > 0) { + Coord3D targetPos; + targetPos.x = pos->x; + targetPos.y = pos->y; + + Real scatterRadius = GameLogicRandomValueReal(data->m_targetMinRadius, data->m_noTargetsScatterRadius); + Real scatterAngleRadian = GameLogicRandomValueReal(0, 2 * PI); + + Coord3D firingOffset; + firingOffset.zero(); + firingOffset.x = scatterRadius * Cos(scatterAngleRadian); + firingOffset.y = scatterRadius * Sin(scatterAngleRadian); + + targetPos.x += firingOffset.x; + targetPos.y += firingOffset.y; + targetPos.z = TheTerrainLogic->getGroundHeight(targetPos.x, targetPos.y); + + const Coord3D* constTargetPos = &targetPos; + + //DEBUG_LOG((">>> SSU - fireWeapon at position\n")); + m_weapon->fireWeapon(getObject(), constTargetPos); + //Bool status = m_weapon->fireWeapon(getObject(), constTargetPos); + //DEBUG_LOG((">>> SSU - fireWeapon success = %s\n", status ? "true" : "false")); + //m_weapon->loadAmmoNow(getObject()); + //weaponSet.reloadAllAmmo(getObject(), true); + shotsLeft--; + } + + // DEBUG_LOG((">>> SSU - triggerScatterShot 5\n")); + + // kill the object after scattering + if (!data->m_stayAliveAfterTrigger) { + getObject()->kill(DAMAGE_UNRESISTABLE, data->m_triggerDeathType); + } + + //if (m_weapon) { + // m_weapon->deleteInstance(); + // m_weapon = NULL; + //} + + + // DEBUG_LOG((">>> SSU - triggerScatterShot 6\n")); + + //m_weapon->forceFireWeapon(getObject(), getObject()->getPosition()); + +} + +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ +Real ScatterShotUpdate::getTargetDistance(void) const { + Coord3D goal; + Coord3D pos = *getObject()->getPosition(); + if (m_goalObj != NULL) { + goal = *m_goalObj->getPosition(); + } + else { + goal = m_goalPos; + } + Coord3D delta; + delta.x = pos.x - goal.x; + delta.y = pos.y - goal.y; + delta.z = pos.z - goal.z; + return delta.length(); +} + +//------------------------------------------------------------------------------------------------- +// Copied from WeaponSet.cpp +//------------------------------------------------------------------------------------------------- +static Int getVictimAntiMask(const Object* victim) +{ + if (victim->isKindOf(KINDOF_SMALL_MISSILE)) + { + //All missiles are also projectiles! + return WEAPON_ANTI_SMALL_MISSILE; + } + else if (victim->isKindOf(KINDOF_BALLISTIC_MISSILE)) + { + return WEAPON_ANTI_BALLISTIC_MISSILE; + } + else if (victim->isKindOf(KINDOF_PROJECTILE)) + { + return WEAPON_ANTI_PROJECTILE; + } + else if (victim->isKindOf(KINDOF_MINE) || victim->isKindOf(KINDOF_DEMOTRAP)) + { + return WEAPON_ANTI_MINE | WEAPON_ANTI_GROUND; + } + else if (victim->isAirborneTarget()) + { + if (victim->isKindOf(KINDOF_VEHICLE)) + { + return WEAPON_ANTI_AIRBORNE_VEHICLE; + } + else if (victim->isKindOf(KINDOF_INFANTRY)) + { + return WEAPON_ANTI_AIRBORNE_INFANTRY; + } + else if (victim->isKindOf(KINDOF_PARACHUTE)) + { + return WEAPON_ANTI_PARACHUTE; + } + else if (!victim->isKindOf(KINDOF_UNATTACKABLE)) + { + DEBUG_CRASH(("Object %s is being targetted as airborne, but is not infantry, nor vehicle. Is this legit? -- tell Kris", victim->getTemplate()->getName().str())); + } + return 0; + } + else + { + return WEAPON_ANTI_GROUND; + } +} +// ------------------------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------------------------ + +Bool ScatterShotUpdate::isValidTarget(const Object* victim) const +{ + const Object* source = getObject(); + // basic sanity checks. + if (!source || + !victim || + source->isEffectivelyDead() || + victim->isEffectivelyDead() || + source->isDestroyed() || + victim->isDestroyed() || + victim == source) + return FALSE; + + if (victim->testStatus(OBJECT_STATUS_MASKED)) + return FALSE; + + if (victim->isKindOf(KINDOF_UNATTACKABLE)) + return FALSE; + + // this object is not currently auto-acquireable + if (victim->testStatus(OBJECT_STATUS_NO_ATTACK_FROM_AI)) + return FALSE; + + Bool allowStealthToPreventAttacks = TRUE; + // If an object is stealthed and hasn't been detected yet, then it is not a valid target to fire + // on. + if (allowStealthToPreventAttacks && + victim->testStatus(OBJECT_STATUS_STEALTHED) && + !victim->testStatus(OBJECT_STATUS_DETECTED)) + { + if (!victim->isKindOf(KINDOF_DISGUISER)) + { + return FALSE;; + } + else + { + //Exception case -- don't return false if we are a bomb truck disguised as an enemy vehicle. + StealthUpdate* update = victim->getStealth(); + if (update && update->isDisguised()) + { + Player* ourPlayer = source->getControllingPlayer(); + Player* otherPlayer = ThePlayerList->getNthPlayer(update->getDisguisedPlayerIndex()); + if (ourPlayer && otherPlayer) + { + if (ourPlayer->getRelationship(otherPlayer->getDefaultTeam()) != ENEMIES) + { + //Our stealthed & undetected object is disguised as a unit not perceived to be our enemy. + return FALSE;; + } + } + } + } + } + + // if the victim is contained within an enclosing container, it cannot be attacked directly + const Object* victimsContainer = victim->getContainedBy(); + if (victimsContainer != NULL && victimsContainer->getContain()->isEnclosingContainerFor(victim) == TRUE) + { + return FALSE; + } + + if (!(m_weapon->getAntiMask() & getVictimAntiMask(victim))) { + return FALSE; + } + + return TRUE; +} + +// ------------------------------------------------------------------------------------------------ +/** CRC */ +// ------------------------------------------------------------------------------------------------ +void ScatterShotUpdate::crc(Xfer* xfer) +{ + // extend base class + UpdateModule::crc(xfer); + +} // end crc + +// ------------------------------------------------------------------------------------------------ +/** Xfer method + * Version Info: + * 1: Initial version */ + // ------------------------------------------------------------------------------------------------ +void ScatterShotUpdate::xfer(Xfer* xfer) +{ + + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion(&version, currentVersion); + + // extend base class + UpdateModule::xfer(xfer); + + // weapon + xfer->xferSnapshot(m_weapon); + + // lifetime + xfer->xferUnsignedInt(&m_initialDelayFrame); + + // has triggered + xfer->xferBool(&m_hasTriggered); + + //is initialized + xfer->xferBool(&m_isInitialized); + + // target pos + xfer->xferCoord3D(&m_goalPos); + + // target distance + xfer->xferReal(&m_totalTargetDistance); + + // target obj + if (xfer->getXferMode() == XFER_SAVE) + { + ObjectID targetID = m_goalObj->getID(); + xfer->xferObjectID(&targetID); + } + else { + ObjectID targetID; + xfer->xferObjectID(&targetID); + m_goalObj = TheGameLogic->findObjectByID(targetID); + } + +} // end xfer + +// ------------------------------------------------------------------------------------------------ +/** Load post process */ +// ------------------------------------------------------------------------------------------------ +void ScatterShotUpdate::loadPostProcess(void) +{ + + // extend base class + UpdateModule::loadPostProcess(); + +} // end loadPostProcess diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp index a7a746d8c8..a675a77114 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SlavedUpdate.cpp @@ -50,7 +50,7 @@ #include "GameLogic/Module/SlavedUpdate.h" #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp index 2d40598f6f..4b69015a86 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialAbilityUpdate.cpp @@ -64,7 +64,7 @@ #include "GameLogic/Module/StealthUpdate.h" #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp index 8fd32c036e..38af989400 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpecialPowerUpdateModule.cpp @@ -41,7 +41,7 @@ #include "GameLogic/Module/SpecialPowerUpdateModule.h" #include "GameLogic/Module/SpecialPowerModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp index 006d6d0634..0e89592bf6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipDeploymentUpdate.cpp @@ -63,7 +63,7 @@ #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -144,118 +144,119 @@ void SpectreGunshipDeploymentUpdate::onObjectCreated() //------------------------------------------------------------------------------------------------- Bool SpectreGunshipDeploymentUpdate::initiateIntentToDoSpecialPower(const SpecialPowerTemplate *specialPowerTemplate, const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ) { - const SpectreGunshipDeploymentUpdateModuleData *data = getSpectreGunshipDeploymentUpdateModuleData(); + const SpectreGunshipDeploymentUpdateModuleData* data = getSpectreGunshipDeploymentUpdateModuleData(); - if( m_specialPowerModule->getSpecialPowerTemplate() != specialPowerTemplate ) + if (m_specialPowerModule->getSpecialPowerTemplate() != specialPowerTemplate) { //Check to make sure our modules are connected. return FALSE; } -// getObject()->getControllingPlayer()->getAcademyStats()->recordSpecialPowerUsed( specialPowerTemplate ); - - if( !BitIsSet( commandOptions, COMMAND_FIRED_BY_SCRIPT ) ) + // getObject()->getControllingPlayer()->getAcademyStats()->recordSpecialPowerUsed( specialPowerTemplate ); + + if (!BitIsSet(commandOptions, COMMAND_FIRED_BY_SCRIPT)) { -/******CHANGE*******/ m_initialTargetPosition.set( targetPos ); + /******CHANGE*******/ m_initialTargetPosition.set(targetPos); } else { UnsignedInt now = TheGameLogic->getFrame(); - m_specialPowerModule->setReadyFrame( now ); -/******CHANGE*******/ m_initialTargetPosition.set( targetPos ); -// setLogicalStatus( GUNSHIPDEPLOY_STATUS_INSERTING ); + m_specialPowerModule->setReadyFrame(now); + /******CHANGE*******/ m_initialTargetPosition.set(targetPos); + // setLogicalStatus( GUNSHIPDEPLOY_STATUS_INSERTING ); } - Object *newGunship = TheGameLogic->findObjectByID( m_gunshipID ); - const ThingTemplate *gunshipTemplate = TheThingFactory->findTemplate( data->m_gunshipTemplateName ); - if( newGunship != NULL ) - { -// disengageAndDepartAO( newGunship ); - m_gunshipID = INVALID_ID; - newGunship = NULL; - } - - - // Lets make a gunship, since we have none. + Object* newGunship = TheGameLogic->findObjectByID(m_gunshipID); + const ThingTemplate* gunshipTemplate = TheThingFactory->findTemplate(data->m_gunshipTemplateName); + if (newGunship != NULL) { - newGunship = TheThingFactory->newObject( gunshipTemplate, getObject()->getTeam() ); - } - - DEBUG_ASSERTCRASH( newGunship, ("SpecterGunshipUpdate failed to find or create a gunship object")); - if ( newGunship ) - { - //PRODUCER - newGunship->setProducer( getObject() ); - - //POSITION - Coord3D creationCoord; - switch (data->m_createLoc) - { - case CREATE_GUNSHIP_AT_EDGE_NEAR_SOURCE: - creationCoord = TheTerrainLogic->findClosestEdgePoint( getObject()->getPosition() ); - break; - case CREATE_GUNSHIP_AT_EDGE_FARTHEST_FROM_SOURCE: - creationCoord = TheTerrainLogic->findFarthestEdgePoint( getObject()->getPosition() ); - break; - case CREATE_GUNSHIP_AT_EDGE_NEAR_TARGET: - creationCoord = TheTerrainLogic->findClosestEdgePoint(targetPos); - break; - case CREATE_GUNSHIP_AT_EDGE_FARTHEST_FROM_TARGET: - default: - creationCoord = TheTerrainLogic->findFarthestEdgePoint(targetPos); - break; - } - - - - - // HERE WE NEED TO CREATE THE POINT FURTHER OFF THE MAP SO WE CANT SEE THE LAME HOVER AND ACCELLERATE BEHAVIOR - Coord3D deltaToCreationPoint = m_initialTargetPosition; - deltaToCreationPoint.sub( &creationCoord ); - Real distanceFromTarget = deltaToCreationPoint.length(); - deltaToCreationPoint.normalize(); - deltaToCreationPoint.x *= ( distanceFromTarget + data->m_gunshipOrbitRadius ); - deltaToCreationPoint.y *= ( distanceFromTarget + data->m_gunshipOrbitRadius ); - creationCoord.x = m_initialTargetPosition.x - deltaToCreationPoint.x; - creationCoord.y = m_initialTargetPosition.y - deltaToCreationPoint.y; - - Real preferredElevation = newGunship->getAI()->getCurLocomotor()->getPreferredHeight(); - creationCoord.z = preferredElevation; - newGunship->setPosition( &creationCoord ); - - //ORIENTATION - Real orient = atan2( m_initialTargetPosition.y - creationCoord.y, m_initialTargetPosition.x - creationCoord.x); - newGunship->setOrientation( orient ); - - // ID - m_gunshipID = newGunship->getID(); - - // FIRE THE SPECIAL POWER OF THE GUNSHIP - SpecialPowerModuleInterface *shipSPMInterface = newGunship->getSpecialPowerModule( specialPowerTemplate ); - if( shipSPMInterface ) - { - SpecialPowerModule *spModule = (SpecialPowerModule*)shipSPMInterface; - spModule->markSpecialPowerTriggered( &m_initialTargetPosition ); - spModule->doSpecialPowerAtLocation( &m_initialTargetPosition, INVALID_ANGLE, commandOptions ); - - } - - // MAKE THE GUNSHIP SELECTED - - TheGameLogic->selectObject( newGunship, TRUE, getObject()->getControllingPlayer()->getPlayerMask(), TRUE ); - - - } - - - SpecialPowerModuleInterface *spmInterface = getObject()->getSpecialPowerModule( specialPowerTemplate ); - if( spmInterface ) + // disengageAndDepartAO( newGunship ); + m_gunshipID = INVALID_ID; + newGunship = NULL; + } + + + // Lets make a gunship, since we have none. { - SpecialPowerModule *spModule = (SpecialPowerModule*)spmInterface; - spModule->markSpecialPowerTriggered( &m_initialTargetPosition ); + newGunship = TheThingFactory->newObject(gunshipTemplate, getObject()->getTeam()); } - - return TRUE; + + DEBUG_ASSERTCRASH(newGunship, ("SpecterGunshipUpdate failed to find or create a gunship object")); + if (newGunship) + { + //PRODUCER + newGunship->setProducer(getObject()); + + //POSITION + Coord3D creationCoord; + switch (data->m_createLoc) + { + case CREATE_GUNSHIP_AT_EDGE_NEAR_SOURCE: + creationCoord = TheTerrainLogic->findClosestEdgePoint(getObject()->getPosition()); + break; + case CREATE_GUNSHIP_AT_EDGE_FARTHEST_FROM_SOURCE: + creationCoord = TheTerrainLogic->findFarthestEdgePoint(getObject()->getPosition()); + break; + case CREATE_GUNSHIP_AT_EDGE_NEAR_TARGET: + creationCoord = TheTerrainLogic->findClosestEdgePoint(targetPos); + break; + case CREATE_GUNSHIP_AT_EDGE_FARTHEST_FROM_TARGET: + default: + creationCoord = TheTerrainLogic->findFarthestEdgePoint(targetPos); + break; + } + + + + + // HERE WE NEED TO CREATE THE POINT FURTHER OFF THE MAP SO WE CANT SEE THE LAME HOVER AND ACCELLERATE BEHAVIOR + Coord3D deltaToCreationPoint = m_initialTargetPosition; + deltaToCreationPoint.sub(&creationCoord); + Real distanceFromTarget = deltaToCreationPoint.length(); + deltaToCreationPoint.normalize(); + deltaToCreationPoint.x *= (distanceFromTarget + data->m_gunshipOrbitRadius); + deltaToCreationPoint.y *= (distanceFromTarget + data->m_gunshipOrbitRadius); + creationCoord.x = m_initialTargetPosition.x - deltaToCreationPoint.x; + creationCoord.y = m_initialTargetPosition.y - deltaToCreationPoint.y; + + Real preferredElevation = newGunship->getAI()->getCurLocomotor()->getPreferredHeight(); + creationCoord.z = preferredElevation; + newGunship->setPosition(&creationCoord); + + //ORIENTATION + Real orient = atan2(m_initialTargetPosition.y - creationCoord.y, m_initialTargetPosition.x - creationCoord.x); + newGunship->setOrientation(orient); + + // ID + m_gunshipID = newGunship->getID(); + + // FIRE THE SPECIAL POWER OF THE GUNSHIP + SpecialPowerModuleInterface* shipSPMInterface = newGunship->getSpecialPowerModule(specialPowerTemplate); + if (shipSPMInterface) + { + SpecialPowerModule* spModule = (SpecialPowerModule*)shipSPMInterface; + spModule->markSpecialPowerTriggered(&m_initialTargetPosition); + spModule->doSpecialPowerAtLocation(&m_initialTargetPosition, INVALID_ANGLE, commandOptions); + + } + + // MAKE THE GUNSHIP SELECTED (Update: Now only for the local player) + + // TheGameLogic->selectObject(newGunship, TRUE, getObject()->getControllingPlayer()->getPlayerMask(), TRUE); + TheGameLogic->selectObject(newGunship, TRUE, getObject()->getControllingPlayer()->getPlayerMask(), getObject()->isLocallyControlled()); + + + } + + + SpecialPowerModuleInterface* spmInterface = getObject()->getSpecialPowerModule(specialPowerTemplate); + if (spmInterface) + { + SpecialPowerModule* spModule = (SpecialPowerModule*)spmInterface; + spModule->markSpecialPowerTriggered(&m_initialTargetPosition); + } + + return TRUE; } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp index 76881b7ede..48aa5f3c64 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp @@ -64,7 +64,7 @@ #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -344,7 +344,7 @@ class PartitionFilterLiveMapEnemies : public PartitionFilter return true; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterLiveMapEnemies"; } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpyVisionUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpyVisionUpdate.cpp index 7b487f7c51..e9f5effa2b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpyVisionUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpyVisionUpdate.cpp @@ -38,7 +38,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Module/SpyVisionUpdate.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp index b03784bbb9..d4e4180989 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp @@ -51,7 +51,7 @@ #include "Common/PlayerList.h" #include "Common/Player.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -121,7 +121,7 @@ class PartitionFilterStealthedOrStealthGarrisoned : public PartitionFilter virtual Bool allow(Object *objOther); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterStealthedOrStealthGarrisoned"; } #endif }; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp index 260f86224c..1b36389eea 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp @@ -60,7 +60,7 @@ #include "GameLogic/Module/SpawnBehavior.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -672,6 +672,10 @@ UpdateSleepTime StealthUpdate::update( void ) { //Switch models at the halfway point changeVisualDisguise(); + + // TheSuperHackers @fix Skyaero 06/05/2025 obtain the new drawable + draw = getObject()->getDrawable(); + m_disguiseHalfpointReached = true; } //Opacity ranges from full to none at midpoint and full again at the end @@ -1055,7 +1059,9 @@ void StealthUpdate::changeVisualDisguise() const ThingTemplate *tTemplate = self->getTemplate(); - TheThingFactory->newDrawable( tTemplate ); + // TheSuperHackers @fix helmutbuhler 13/04/2025 Fixes missing pointer assignment for the new drawable. + // This originally caused no runtime crash because the new drawable is allocated at the same address as the previously deleted drawable via the MemoryPoolBlob. + draw = TheThingFactory->newDrawable( tTemplate ); if( draw ) { TheGameLogic->bindObjectAndDrawable(self, draw); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp index 5e9ed3f1f0..ad36ca66f3 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StructureToppleUpdate.cpp @@ -48,7 +48,7 @@ #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp index a9574d3e57..62b45d402b 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/TensileFormationUpdate.cpp @@ -47,7 +47,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -76,7 +76,7 @@ class PartitionFilterTensileFormationMember : public PartitionFilter public: PartitionFilterTensileFormationMember( Object* obj ) : m_obj( obj ) { } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual const char* debugGetName() { return "PartitionFilterTensileFormationMember"; } #endif virtual Bool allow( Object *objOther ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp index e8b3118572..25e01dea46 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/UpdateModule.cpp @@ -33,7 +33,7 @@ #include "GameLogic/GameLogic.h" #include "GameLogic/Module/UpdateModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -116,7 +116,7 @@ void UpdateModule::xfer( Xfer *xfer ) // extend base class BehaviorModule::xfer( xfer ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) /* this is a fix for the following scenario: diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp index dcc43dadbd..4fd6799cd0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/WeaponBonusUpdate.cpp @@ -61,6 +61,7 @@ #include "GameLogic/Object.h" #include "GameLogic/PartitionManager.h" #include "GameLogic/Weapon.h" +#include "GameClient/TintStatus.h" //----------------------------------------------------------------------------- WeaponBonusUpdateModuleData::WeaponBonusUpdateModuleData() @@ -71,6 +72,7 @@ WeaponBonusUpdateModuleData::WeaponBonusUpdateModuleData() m_bonusDelay = 0; m_bonusRange = 0; m_bonusConditionType = WEAPONBONUSCONDITION_INVALID; + m_tintStatus = TINT_STATUS_FRENZY; } //----------------------------------------------------------------------------- @@ -85,6 +87,7 @@ void WeaponBonusUpdateModuleData::buildFieldParse(MultiIniFieldParse& p) { "BonusDelay", INI::parseDurationUnsignedInt, NULL, offsetof( WeaponBonusUpdateModuleData, m_bonusDelay ) }, { "BonusRange", INI::parseReal, NULL, offsetof( WeaponBonusUpdateModuleData, m_bonusRange ) }, { "BonusConditionType", INI::parseIndexList, TheWeaponBonusNames, offsetof( WeaponBonusUpdateModuleData, m_bonusConditionType ) }, + { "TintStatusType", TintStatusFlags::parseSingleBitFromINI, NULL, offsetof( WeaponBonusUpdateModuleData, m_tintStatus ) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); @@ -112,13 +115,14 @@ struct tempWeaponBonusData // Hey Steven, bite me! hahahaha _Lowercase_ since UnsignedInt m_duration; KindOfMaskType m_requiredMask; KindOfMaskType m_forbiddenMask; + TintStatus m_tintStatus; }; void containIteratingDoTempWeaponBonus( Object *passenger, void *voidData) { tempWeaponBonusData *data = (tempWeaponBonusData *)voidData; if( passenger->isKindOfMulti(data->m_requiredMask, data->m_forbiddenMask) ) - passenger->doTempWeaponBonus(data->m_type, data->m_duration); + passenger->doTempWeaponBonus(data->m_type, data->m_duration, data->m_tintStatus); } //------------------------------------------------------------------------------------------------- @@ -148,12 +152,14 @@ UpdateSleepTime WeaponBonusUpdate::update( void ) weaponBonusData.m_duration = data->m_bonusDuration; weaponBonusData.m_requiredMask = data->m_requiredAffectKindOf; weaponBonusData.m_forbiddenMask = data->m_forbiddenAffectKindOf; + weaponBonusData.m_tintStatus = data->m_tintStatus; + for( Object *currentObj = iter->first(); currentObj != NULL; currentObj = iter->next() ) { if( currentObj->isKindOfMulti(data->m_requiredAffectKindOf, data->m_forbiddenAffectKindOf) ) { - currentObj->doTempWeaponBonus(data->m_bonusConditionType, data->m_bonusDuration); + currentObj->doTempWeaponBonus(data->m_bonusConditionType, data->m_bonusDuration, data->m_tintStatus); } if( currentObj->getContain() ) diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp index 3a30858711..b0c158ae45 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ArmorUpgrade.cpp @@ -58,17 +58,33 @@ #include "GameLogic/Object.h" #include "GameLogic/Module/ArmorUpgrade.h" #include "GameLogic/Module/BodyModule.h" -//----------------------------------------------------------------------------- -// DEFINES //////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ArmorUpgradeModuleData::ArmorUpgradeModuleData(void) +{ + m_armorSetFlag = ARMORSET_PLAYER_UPGRADE; + //m_needsParkedAircraft = FALSE; +} -//----------------------------------------------------------------------------- -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void ArmorUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + + UpgradeModuleData::buildFieldParse(p); + + static const FieldParse dataFieldParse[] = + { + { "ArmorSetFlag", INI::parseIndexList, ArmorSetFlags::getBitNames(),offsetof(ArmorUpgradeModuleData, m_armorSetFlag) }, + { "ArmorSetFlagsToClear", ArmorSetFlags::parseFromINI, NULL, offsetof(ArmorUpgradeModuleData, m_armorSetFlagsToClear) }, + //{ "NeedsParkedAircraft", INI::parseBool, NULL, offsetof(ArmorUpgradeModuleData, m_needsParkedAircraft) }, + { 0, 0, 0, 0 } + }; + + p.add(dataFieldParse); + +} // end buildFieldParse //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- @@ -88,19 +104,46 @@ void ArmorUpgrade::upgradeImplementation( ) { // Very simple; just need to flag the Object as having the player upgrade, and the WeaponSet chooser // will do the work of picking the right one from ini. This comment is as long as the code. - // STILL IN PROGRESS + + DEBUG_LOG(("ArmorUpgrade::upgradeImplementation 0\n")); + + const ArmorUpgradeModuleData* data = getArmorUpgradeModuleData(); + Object *obj = getObject(); if( !obj ) return; + DEBUG_LOG(("ArmorUpgrade::upgradeImplementation 1\n")); + BodyModuleInterface* body = obj->getBodyModule(); - if ( body ) - body->setArmorSetFlag( ARMORSET_PLAYER_UPGRADE ); + if (body) { + body->setArmorSetFlag(data->m_armorSetFlag); + + DEBUG_LOG(("ArmorUpgrade::upgradeImplementation 2 - flagsToClear = %d\n", data->m_armorSetFlagsToClear)); + + if (data->m_armorSetFlagsToClear.any()) { + // We loop over each armorset type and see if we have it set. + // Andi: Not sure if this is cleaner solution than storing an array of flags. + for (int i = 0; i < ARMORSET_COUNT; i++) { + ArmorSetType type = (ArmorSetType)i; + if (data->m_armorSetFlagsToClear.test(type)) { + body->clearArmorSetFlag(type); + // obj->clearWeaponSetFlag(type); + } + } + } + } // Unique case for AMERICA to test for upgrade to set flag if(isTriggeredBy("Upgrade_AmericaChemicalSuits")) { - obj->getDrawable()->setTerrainDecal(TERRAIN_DECAL_CHEMSUIT); + Drawable* draw = obj->getDrawable(); + if (draw) { + draw->setTerrainDecal(TERRAIN_DECAL_CHEMSUIT); + } + /*else { + DEBUG_LOG(("ArmorUpgrade::upgradeImplementation 3b - no draw?.\n")); + }*/ } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp index 5b8fb098fe..d7bbed5143 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ExperienceScalarUpgrade.cpp @@ -40,6 +40,7 @@ ExperienceScalarUpgradeModuleData::ExperienceScalarUpgradeModuleData( void ) { m_addXPScalar = 0.0f; + m_addXPValueScalar = 0.0f; } //------------------------------------------------------------------------------------------------- @@ -52,6 +53,7 @@ void ExperienceScalarUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p) static const FieldParse dataFieldParse[] = { { "AddXPScalar", INI::parseReal, NULL, offsetof( ExperienceScalarUpgradeModuleData, m_addXPScalar ) }, + { "AddXPValueScalar", INI::parseReal, NULL, offsetof( ExperienceScalarUpgradeModuleData, m_addXPValueScalar ) }, { 0, 0, 0, 0 } }; @@ -83,6 +85,7 @@ void ExperienceScalarUpgrade::upgradeImplementation( ) if( xpTracker ) { xpTracker->setExperienceScalar( xpTracker->getExperienceScalar() + data->m_addXPScalar ); + xpTracker->setExperienceValueScalar( xpTracker->getExperienceValueScalar() + data->m_addXPValueScalar ); } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp index ea410a4969..c55c8b9723 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/GrantScienceUpgrade.cpp @@ -52,7 +52,7 @@ #include "GameLogic/Module/GrantScienceUpgrade.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp index 23dad7fd2b..3dd166bb8e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/LocomotorSetUpgrade.cpp @@ -35,6 +35,34 @@ #include "GameLogic/Module/LocomotorSetUpgrade.h" #include "GameLogic/Module/AIUpdate.h" + + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +LocomotorSetUpgradeModuleData::LocomotorSetUpgradeModuleData(void) +{ + m_setUpgraded = TRUE; + // m_needsParkedAircraft = FALSE; +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void LocomotorSetUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + + UpgradeModuleData::buildFieldParse(p); + + static const FieldParse dataFieldParse[] = + { + { "EnableUpgrade", INI::parseBool, NULL, offsetof(LocomotorSetUpgradeModuleData, m_setUpgraded) }, + //{ "NeedsParkedAircraft", INI::parseBool, NULL, offsetof(WeaponSetUpgradeModuleData, m_needsParkedAircraft) }, + { 0, 0, 0, 0 } + }; + + p.add(dataFieldParse); + +} // end buildFieldParse + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- LocomotorSetUpgrade::LocomotorSetUpgrade( Thing *thing, const ModuleData* moduleData ) : UpgradeModule( thing, moduleData ) @@ -51,9 +79,10 @@ LocomotorSetUpgrade::~LocomotorSetUpgrade( void ) //------------------------------------------------------------------------------------------------- void LocomotorSetUpgrade::upgradeImplementation( ) { + const LocomotorSetUpgradeModuleData* data = getLocomotorSetUpgradeModuleData(); AIUpdateInterface* ai = getObject()->getAIUpdateInterface(); if (ai) - ai->setLocomotorUpgrade(true); + ai->setLocomotorUpgrade(data->m_setUpgraded); } // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp index 59015144ea..73aa8c224d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp @@ -42,6 +42,7 @@ MaxHealthUpgradeModuleData::MaxHealthUpgradeModuleData( void ) { m_addMaxHealth = 0.0f; + m_multiplyMaxHealth = 1.0f; m_maxHealthChangeType = SAME_CURRENTHEALTH; } @@ -55,6 +56,7 @@ void MaxHealthUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p) static const FieldParse dataFieldParse[] = { { "AddMaxHealth", INI::parseReal, NULL, offsetof( MaxHealthUpgradeModuleData, m_addMaxHealth ) }, + { "MultiplyMaxHealth", INI::parseReal, NULL, offsetof( MaxHealthUpgradeModuleData, m_multiplyMaxHealth ) }, { "ChangeType", INI::parseIndexList, TheMaxHealthChangeTypeNames, offsetof( MaxHealthUpgradeModuleData, m_maxHealthChangeType ) }, { 0, 0, 0, 0 } }; @@ -87,7 +89,10 @@ void MaxHealthUpgrade::upgradeImplementation( ) BodyModuleInterface *body = obj->getBodyModule(); if( body ) { - body->setMaxHealth( body->getMaxHealth() + data->m_addMaxHealth, data->m_maxHealthChangeType ); + Real newVal = (body->getMaxHealth() * data->m_multiplyMaxHealth) + data->m_addMaxHealth; + // DEBUG_LOG(("MaxHealthUpgrade::upgradeImplementation - newVal: (%f * %f) + %f = %f.\n", + // body->getMaxHealth(), data->m_multiplyMaxHealth, data->m_addMaxHealth, newVal)); + body->setMaxHealth( newVal, data->m_maxHealthChangeType ); } } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ProductionTimeModifierUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ProductionTimeModifierUpgrade.cpp new file mode 100644 index 0000000000..ba30a45c20 --- /dev/null +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ProductionTimeModifierUpgrade.cpp @@ -0,0 +1,213 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +// FILE: ProductionTimeModifierUpgrade.cpp ///////////////////////////////////// +//----------------------------------------------------------------------------- +// +// Electronic Arts Pacific. +// +// Confidential Information +// Copyright (C) 2002 - All Rights Reserved +// +//----------------------------------------------------------------------------- +// +// created: March 2025 +// +// Filename: ProductionTimeModifierUpgrade.cpp +// +// author: Andi W +// +// purpose: Upgrade that modifies the production time by a certain percentage +// +//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +// SYSTEM INCLUDES //////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// USER INCLUDES ////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- +#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine + +#include "Common/player.h" +#include "Common/Xfer.h" +#include "GameLogic/Module/ProductionTimeModifierUpgrade.h" +#include "GameLogic/Object.h" +#include "Common/BitFlagsIO.h" +//----------------------------------------------------------------------------- +// DEFINES //////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------- + + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ProductionTimeModifierUpgradeModuleData::ProductionTimeModifierUpgradeModuleData( void ) +{ + + m_kindOf = KINDOFMASK_NONE; + m_percentage = 0; + +} // end ProductionTimeModifierUpgradeModuleData + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +/* static */ void ProductionTimeModifierUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + UpgradeModuleData::buildFieldParse( p ); + + static const FieldParse dataFieldParse[] = + { + { "EffectKindOf", KindOfMaskType::parseFromINI, NULL, offsetof(ProductionTimeModifierUpgradeModuleData, m_kindOf ) }, + { "Percentage", INI::parsePercentToReal, NULL, offsetof(ProductionTimeModifierUpgradeModuleData, m_percentage ) }, + { 0, 0, 0, 0 } + }; + p.add(dataFieldParse); + +} // end buildFieldParse + +/////////////////////////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////////// + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ProductionTimeModifierUpgrade::ProductionTimeModifierUpgrade( Thing *thing, const ModuleData* moduleData ) : + UpgradeModule( thing, moduleData ) +{ + +} // end ProductionTimeModifierUpgrade + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +ProductionTimeModifierUpgrade::~ProductionTimeModifierUpgrade( void ) +{ + +} // end ~ProductionTimeModifierUpgrade + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void ProductionTimeModifierUpgrade::onDelete( void ) +{ + + // if we haven't been upgraded there is nothing to clean up + if( isAlreadyUpgraded() == FALSE ) + return; + + // remove the radar from the player + Player *player = getObject()->getControllingPlayer(); + if( player ) + player->removeKindOfProductionTimeChange(getProductionTimeModifierUpgradeModuleData()->m_kindOf, getProductionTimeModifierUpgradeModuleData()->m_percentage ); + + // this upgrade module is now "not upgraded" + setUpgradeExecuted(FALSE); + +} // end onDelete + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void ProductionTimeModifierUpgrade::onCapture( Player *oldOwner, Player *newOwner ) +{ + + // do nothing if we haven't upgraded yet + if( isAlreadyUpgraded() == FALSE ) + return; + + // remove radar from old player and add to new player + if( oldOwner ) + { + + oldOwner->removeKindOfProductionTimeChange(getProductionTimeModifierUpgradeModuleData()->m_kindOf, getProductionTimeModifierUpgradeModuleData()->m_percentage ); + setUpgradeExecuted(FALSE); + + } // end if + if( newOwner ) + { + + newOwner->addKindOfProductionTimeChange(getProductionTimeModifierUpgradeModuleData()->m_kindOf, getProductionTimeModifierUpgradeModuleData()->m_percentage ); + setUpgradeExecuted(TRUE); + + } // end if + +} // end onCapture + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void ProductionTimeModifierUpgrade::upgradeImplementation( void ) +{ + Player *player = getObject()->getControllingPlayer(); + + // update the player with another TypeOfProductionTimeChange + player->addKindOfProductionTimeChange(getProductionTimeModifierUpgradeModuleData()->m_kindOf, getProductionTimeModifierUpgradeModuleData()->m_percentage ); + +} // end upgradeImplementation + +// ------------------------------------------------------------------------------------------------ +/** CRC */ +// ------------------------------------------------------------------------------------------------ +void ProductionTimeModifierUpgrade::crc( Xfer *xfer ) +{ + + // extend base class + UpgradeModule::crc( xfer ); + +} // end crc + +// ------------------------------------------------------------------------------------------------ +/** Xfer method + * Version Info: + * 1: Initial version */ +// ------------------------------------------------------------------------------------------------ +void ProductionTimeModifierUpgrade::xfer( Xfer *xfer ) +{ + + // version + XferVersion currentVersion = 1; + XferVersion version = currentVersion; + xfer->xferVersion( &version, currentVersion ); + + // extend base class + UpgradeModule::xfer( xfer ); + +} // end xfer + +// ------------------------------------------------------------------------------------------------ +/** Load post process */ +// ------------------------------------------------------------------------------------------------ +void ProductionTimeModifierUpgrade::loadPostProcess( void ) +{ + + // extend base class + UpgradeModule::loadPostProcess(); + +} // end loadPostProcess diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp index 1f309d0fef..7661c675f9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/UpgradeModule.cpp @@ -32,7 +32,7 @@ #include "Common/Xfer.h" #include "GameLogic/Module/UpgradeModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp index 07076cfc49..a2a68a5ca6 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/WeaponSetUpgrade.cpp @@ -33,6 +33,36 @@ #include "Common/Xfer.h" #include "GameLogic/Object.h" #include "GameLogic/Module/WeaponSetUpgrade.h" +#include "GameLogic/Module/JetAIUpdate.h" + + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +WeaponSetUpgradeModuleData::WeaponSetUpgradeModuleData(void) +{ + m_weaponSetFlag = WEAPONSET_PLAYER_UPGRADE; + // m_weaponSetFlagsToClear = WEAPONSET_COUNT; // = undefined; + m_needsParkedAircraft = FALSE; +} + +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +void WeaponSetUpgradeModuleData::buildFieldParse(MultiIniFieldParse& p) +{ + + UpgradeModuleData::buildFieldParse(p); + + static const FieldParse dataFieldParse[] = + { + { "WeaponSetFlag", INI::parseIndexList, WeaponSetFlags::getBitNames(),offsetof(WeaponSetUpgradeModuleData, m_weaponSetFlag) }, + { "WeaponSetFlagsToClear", WeaponSetFlags::parseFromINI, NULL, offsetof(WeaponSetUpgradeModuleData, m_weaponSetFlagsToClear) }, + { "NeedsParkedAircraft", INI::parseBool, NULL, offsetof(WeaponSetUpgradeModuleData, m_needsParkedAircraft) }, + { 0, 0, 0, 0 } + }; + + p.add(dataFieldParse); + +} // end buildFieldParse //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- @@ -46,14 +76,57 @@ WeaponSetUpgrade::~WeaponSetUpgrade( void ) { } +//------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------- +Bool WeaponSetUpgrade::wouldUpgrade(UpgradeMaskType keyMask) const +{ + if (UpgradeMux::wouldUpgrade(keyMask)) { + + // Check additional conditions + const WeaponSetUpgradeModuleData* data = getWeaponSetUpgradeModuleData(); + + if (data->m_needsParkedAircraft) { + const AIUpdateInterface* ai = getObject()->getAI(); + if (ai) { + const JetAIUpdate* jetAI = ai->getJetAIUpdate(); + if ((jetAI) && jetAI->isParkedInHangar()){ + return TRUE; + } + } + } + else { + return TRUE; + } + } + + //We can't upgrade! + return FALSE; +} + //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- void WeaponSetUpgrade::upgradeImplementation( ) { // Very simple; just need to flag the Object as having the player upgrade, and the WeaponSet chooser - // will do the work of picking the right one from ini. This comment is as long as the code. + // will do the work of picking the right one from ini. This comment is as long as the code. Update: not anymore ;) + const WeaponSetUpgradeModuleData* data = getWeaponSetUpgradeModuleData(); + Object *obj = getObject(); - obj->setWeaponSetFlag( WEAPONSET_PLAYER_UPGRADE ); + obj->setWeaponSetFlag(data->m_weaponSetFlag); + + /*DEBUG_LOG((">>> WSU: m_weaponSetFlagsToClear = %d\n", + data->m_weaponSetFlag));*/ + + if (data->m_weaponSetFlagsToClear.any()) { + // We loop over each weaponset type and see if we have it set. + // Andi: Not sure if this is cleaner solution than storing an array of flags. + for (int i = 0; i < WEAPONSET_COUNT; i++) { + WeaponSetType type = (WeaponSetType)i; + if (data->m_weaponSetFlagsToClear.test(type)) { + obj->clearWeaponSetFlag(type); + } + } + } } // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp index 0f22d5b3a7..7c0745fbb2 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp @@ -74,6 +74,7 @@ #include "GameLogic/Module/AssistedTargetingUpdate.h" #include "GameLogic/Module/ProjectileStreamUpdate.h" #include "GameLogic/Module/PhysicsUpdate.h" +#include "GameLogic/Module/LifetimeUpdate.h" #include "GameLogic/TerrainLogic.h" #define RATIONALIZE_ATTACK_RANGE @@ -85,7 +86,7 @@ const DistanceCalculationType ATTACK_RANGE_CALC_TYPE = FROM_BOUNDINGSPHERE_3D; #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -243,6 +244,16 @@ const FieldParse WeaponTemplate::TheWeaponTemplateFieldParseTable[] = { "ContinueAttackRange", INI::parseReal, NULL, offsetof(WeaponTemplate, m_continueAttackRange) }, { "SuspendFXDelay", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_suspendFXDelay) }, { "MissileCallsOnDie", INI::parseBool, NULL, offsetof(WeaponTemplate, m_dieOnDetonate) }, + { "ScatterTargetAligned", INI::parseBool, NULL, offsetof(WeaponTemplate, m_scatterTargetAligned) }, + { "ScatterTargetRandomOrder", INI::parseBool, NULL, offsetof(WeaponTemplate, m_scatterTargetRandom) }, + { "ScatterTargetRandomAngle", INI::parseBool, NULL, offsetof(WeaponTemplate, m_scatterTargetRandomAngle) }, + { "ScatterTargetMinScalar", INI::parseReal, NULL, offsetof(WeaponTemplate, m_scatterTargetMinScalar) }, + { "ScatterTargetCenteredAtShooter", INI::parseBool, NULL, offsetof(WeaponTemplate, m_scatterTargetCenteredAtShooter) }, + { "ScatterTargetResetTime", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_scatterTargetResetTime) }, + { "PreAttackFX", parseAllVetLevelsFXList, NULL, offsetof(WeaponTemplate, m_preAttackFXs) }, + { "VeterancyPreAttackFX", parsePerVetLevelFXList, NULL, offsetof(WeaponTemplate, m_preAttackFXs) }, + { "PreAttackFXDelay", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_preAttackFXDelay) }, + { "ContinuousLaserLoopTime", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_continuousLaserLoopTime) }, { NULL, NULL, NULL, 0 } // keep this last }; @@ -306,6 +317,7 @@ WeaponTemplate::WeaponTemplate() : m_nextTemplate(NULL) m_minDelayBetweenShots = 0; m_maxDelayBetweenShots = 0; m_fireSoundLoopTime = 0; + m_continuousLaserLoopTime = 0; m_extraBonus = NULL; m_shotsPerBarrel = 1; m_antiMask = WEAPON_ANTI_GROUND; // but not air or projectile. @@ -327,6 +339,13 @@ WeaponTemplate::WeaponTemplate() : m_nextTemplate(NULL) m_damageStatusType = OBJECT_STATUS_NONE; m_suspendFXDelay = 0; m_dieOnDetonate = FALSE; + m_scatterTargetAligned = FALSE; + m_scatterTargetRandom = TRUE; + m_scatterTargetRandomAngle = FALSE; + m_scatterTargetMinScalar = 0; + m_scatterTargetCenteredAtShooter = FALSE; + m_scatterTargetResetTime = 0; + m_preAttackFXDelay = 6; // Non-Zero default! 6 frames = 200ms. This should be a good base value to avoid spamming } //------------------------------------------------------------------------------------------------- @@ -776,7 +795,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate { //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) AsciiString targetStr; if( TheGlobalData->m_extraLogging ) { @@ -799,7 +818,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate if (sourceObj == NULL || (victimObj == NULL && victimPos == NULL)) { //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( TheGlobalData->m_extraLogging ) DEBUG_LOG( ("FAIL 1 (sourceObj %d == NULL || (victimObj %d == NULL && victimPos %d == NULL)\n", sourceObj != 0, victimObj != 0, victimPos != 0) ); #endif @@ -878,7 +897,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate //DEBUG_ASSERTCRASH(distSqr < 5*5 || distSqr < attackRangeSqr*1.2f, ("*** victim is out of range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(attackRangeSqr))); //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( TheGlobalData->m_extraLogging ) DEBUG_LOG( ("FAIL 2 (distSqr %.2f > attackRangeSqr %.2f)\n", distSqr, attackRangeSqr ) ); #endif @@ -900,7 +919,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate DEBUG_ASSERTCRASH(distSqr > minAttackRangeSqr*0.8f, ("*** victim is closer than min attack range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(minAttackRangeSqr))); //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( TheGlobalData->m_extraLogging ) DEBUG_LOG( ("FAIL 3 (distSqr %.2f< minAttackRangeSqr %.2f - 0.5f && !isProjectileDetonation %d)\n", distSqr, minAttackRangeSqr, isProjectileDetonation ) ); #endif @@ -1041,14 +1060,49 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate { projectileDestination.set( victimObj->getPosition() ); } - firingWeapon->createLaser( sourceObj, victimObj, &projectileDestination ); + if (firingWeapon->getContinuousLaserLoopTime() > 0) + firingWeapon->handleContinuousLaser(sourceObj, victimObj, &projectileDestination); + else + firingWeapon->createLaser(sourceObj, victimObj, &projectileDestination); } else { //We are missing our intended target, so now we want to aim at the ground at the projectile offset. damageID = INVALID_ID; - firingWeapon->createLaser( sourceObj, NULL, &projectileDestination ); + if (firingWeapon->getContinuousLaserLoopTime() > 0) + firingWeapon->handleContinuousLaser(sourceObj, NULL, &projectileDestination); + else + firingWeapon->createLaser(sourceObj, NULL, &projectileDestination); } + + // Handle Detonation OCL + Coord3D targetPos; // We need a better position to match the visual laser; + targetPos.set(&projectileDestination); + if (victimObj && !victimObj->isKindOf(KINDOF_PROJECTILE) && !victimObj->isAirborneTarget()) + { + //Targets are positioned on the ground, so raise the beam up so we're not shooting their feet. + //Projectiles are a different story, target their exact position. + targetPos.z += 10.0f; + } + + VeterancyLevel vet = sourceObj->getVeterancyLevel(); + const ObjectCreationList* detOCL = getProjectileDetonationOCL(vet); + Real laserAngle = atan2(v.y, v.x); //TODO: check if this should be inverted + if (detOCL) { + //TODO: should we consider a proper 3D matrix? + ObjectCreationList::create(detOCL, sourceObj, &targetPos, NULL, laserAngle); + } + // Handle Detonation FX + const FXList* fx = getProjectileDetonateFX(vet); + if (fx != NULL) { + Matrix3D laserMtx; + Vector3 pos(sourcePos->x, sourcePos->y, sourcePos->z); + Vector3 dir(v.x, v.y, v.z); + dir.Normalize(); //This is fantastically crucial for calling buildTransformMatrix!!!!! + laserMtx.buildTransformMatrix(pos, dir); + FXList::doFXPos(fx, &targetPos, &laserMtx, 0.0f, NULL, getPrimaryDamageRadius(bonus)); + } + if( inflictDamage ) { dealDamageInternal( sourceID, damageID, &projectileDestination, bonus, isProjectileDetonation ); @@ -1067,7 +1121,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate } //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( TheGlobalData->m_extraLogging ) DEBUG_LOG( ("EARLY 4 (delayed damage applied now)\n") ); #endif @@ -1088,7 +1142,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate } //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( TheGlobalData->m_extraLogging ) DEBUG_LOG( ("EARLY 5 (delaying damage applied until frame %d)\n", when ) ); #endif @@ -1179,7 +1233,7 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate } //-extraLogging - #if (defined(_DEBUG) || defined(_INTERNAL)) + #if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) if( TheGlobalData->m_extraLogging ) DEBUG_LOG( ("DONE\n") ); #endif @@ -1188,7 +1242,55 @@ UnsignedInt WeaponTemplate::fireWeaponTemplate return 0; } } +//------------------- +void WeaponTemplate::createPreAttackFX +( + const Object* sourceObj, + WeaponSlotType wslot, + Int specificBarrelToUse, + const Object* victimObj, + const Coord3D* victimPos + //const WeaponBonus& bonus, + //Weapon *firingWeapon, +) const +{ + // PLAY PRE ATTACK FX + VeterancyLevel v = sourceObj->getVeterancyLevel(); + const FXList* fx = getPreAttackFX(v); + if (fx) { + Coord3D targetPos; + if (victimObj) + { + victimObj->getGeometryInfo().getCenterPosition(*victimObj->getPosition(), targetPos); + } + else if (victimPos) + { + targetPos.set(victimPos); + } + + /*DEBUG_LOG((">>> INFO - creating PRE_ATTACK FX for '%s' with victim '%s' and pos '(%f, %f, %f)' \n", + sourceObj->getTemplate()->getName().str(), + victimObj ? victimObj->getTemplate()->getName().str() : "None", + targetPos.x, targetPos.y, targetPos.z));*/ + + Bool handled = false; + handled = sourceObj->getDrawable()->handleWeaponPreAttackFX(wslot, + specificBarrelToUse, + fx, + getWeaponSpeed(), + 0.0f, //TODO: Enable recoil stats if we want to have PreAttack specific recoil amount + 0.0f, + &targetPos, + 0.0f + ); + if (handled == false && fx != NULL) + { + const Coord3D* where = isContactWeapon() ? &targetPos : sourceObj->getDrawable()->getPosition(); + FXList::doFXPos(fx, where, sourceObj->getDrawable()->getTransformMatrix(), getWeaponSpeed(), &targetPos, 0.0f); + } + } +} //------------------------------------------------------------------------------------------------- void WeaponTemplate::trimOldHistoricDamage() const { @@ -1731,7 +1833,7 @@ void WeaponStore::postProcessLoad() if (weapon->m_projectileName.isNone()) weapon->m_projectileName.clear(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!weapon->getFireSound().getEventName().isEmpty() && weapon->getFireSound().getEventName().compareNoCase("NoSound") != 0) { DEBUG_ASSERTCRASH(TheAudio->isValidAudioEvent(&weapon->getFireSound()), ("Invalid FireSound %s in Weapon '%s'.", weapon->getFireSound().getEventName().str(), weapon->getName().str())); @@ -1764,6 +1866,10 @@ Weapon::Weapon(const WeaponTemplate* tmpl, WeaponSlotType wslot) m_numShotsForCurBarrel = m_template->getShotsPerBarrel(); m_lastFireFrame = 0; m_suspendFXFrame = TheGameLogic->getFrame() + m_template->getSuspendFXDelay(); + m_scatterTargetsAngle = 0; + m_nextPreAttackFXFrame = 0; + m_continuousLaserID = INVALID_ID; + m_bonusRefObjID = INVALID_ID; } //------------------------------------------------------------------------------------------------- @@ -1785,6 +1891,9 @@ Weapon::Weapon(const Weapon& that) this->m_numShotsForCurBarrel = m_template->getShotsPerBarrel(); this->m_lastFireFrame = 0; this->m_suspendFXFrame = that.getSuspendFXFrame(); + this->m_nextPreAttackFXFrame = 0; + this->m_continuousLaserID = INVALID_ID; + this->m_bonusRefObjID = INVALID_ID; } //------------------------------------------------------------------------------------------------- @@ -1808,6 +1917,8 @@ Weapon& Weapon::operator=(const Weapon& that) this->m_suspendFXFrame = that.getSuspendFXFrame(); this->m_numShotsForCurBarrel = m_template->getShotsPerBarrel(); this->m_projectileStreamID = INVALID_ID; + this->m_nextPreAttackFXFrame = 0; + this->m_continuousLaserID = INVALID_ID; } return *this; } @@ -1817,18 +1928,43 @@ Weapon::~Weapon() { } +//------------------------------------------------------------------------------------------------- +// DEBUG +static void debug_printWeaponBonus(WeaponBonus* bonus, AsciiString name) { + const char* bonusNames[] = { + "DAMAGE", + "RADIUS", + "RANGE", + "RATE_OF_FIRE", + "PRE_ATTACK" + }; + DEBUG_LOG((">>> Weapon bonus for '%s':\n", name.str())); + for (int i = 0; i < 5; i++) { + DEBUG_LOG((">>> -- '%s' : %f\n", bonusNames[i], bonus->getField(static_cast(i)))); + } +} + //------------------------------------------------------------------------------------------------- void Weapon::computeBonus(const Object *source, WeaponBonusConditionFlags extraBonusFlags, WeaponBonus& bonus) const { + // TODO: Do we need this eventually? + const Object* bonusRefObj = NULL; + if (m_bonusRefObjID != INVALID_ID) { + bonusRefObj = TheGameLogic->findObjectByID(m_bonusRefObjID); + } + else { + bonusRefObj = source; + } + bonus.clear(); - WeaponBonusConditionFlags flags = source->getWeaponBonusCondition(); + WeaponBonusConditionFlags flags = bonusRefObj->getWeaponBonusCondition(); //CRCDEBUG_LOG(("Weapon::computeBonus() - flags are %X for %s\n", flags, DescribeObject(source).str())); flags |= extraBonusFlags; - if( source->getContainedBy() ) + if (bonusRefObj->getContainedBy()) { // We may be able to add in our container's flags - const ContainModuleInterface *theirContain = source->getContainedBy()->getContain(); + const ContainModuleInterface *theirContain = bonusRefObj->getContainedBy()->getContain(); if( theirContain && theirContain->isWeaponBonusPassedToPassengers() ) flags |= theirContain->getWeaponBonusPassedToPassengers(); } @@ -1892,8 +2028,12 @@ void Weapon::rebuildScatterTargets() if (scatterTargetsCount) { // When I reload, I need to rebuild the list of ScatterTargets to shoot at. - for (Int targetIndex = 0; targetIndex < scatterTargetsCount; targetIndex++) - m_scatterTargetsUnused.push_back( targetIndex ); + for (Int targetIndex = scatterTargetsCount - 1; targetIndex >= 0; targetIndex--) + m_scatterTargetsUnused.push_back(targetIndex); + + if (m_template->isScatterTargetRandomAngle()) { + m_scatterTargetsAngle = GameLogicRandomValueReal(0, PI * 2); + } } } @@ -2439,18 +2579,18 @@ void Weapon::newProjectileFired(const Object *sourceObj, const Object *projectil } //------------------------------------------------------------------------------------------------- -void Weapon::createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos ) +ObjectID Weapon::createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos ) { const ThingTemplate* pst = TheThingFactory->findTemplate(m_template->getLaserName()); if( !pst ) { DEBUG_CRASH( ("Weapon::createLaser(). %s could not find template for its laser %s.", sourceObj->getTemplate()->getName().str(), m_template->getLaserName().str() ) ); - return; + return INVALID_ID; } Object* laser = TheThingFactory->newObject( pst, sourceObj->getControllingPlayer()->getDefaultTeam() ); if( laser == NULL ) - return; + return INVALID_ID; // Give it a good basis in reality to ensure it can draw when on screen. laser->setPosition(sourceObj->getPosition()); @@ -2473,8 +2613,58 @@ void Weapon::createLaser( const Object *sourceObj, const Object *victimObj, cons update->initLaser( sourceObj, victimObj, sourceObj->getPosition(), &pos, m_template->getLaserBoneName() ); } } + + return laser->getID(); +} +//------------------------------------------------------------------------------------------------- +void Weapon::handleContinuousLaser(const Object* sourceObj, const Object* victimObj, const Coord3D* victimPos) +{ + UnsignedInt frameNow = TheGameLogic->getFrame(); + Object* continuousLaser = TheGameLogic->findObjectByID(m_continuousLaserID); + + if (m_lastFireFrame + m_template->getContinuousLaserLoopTime() < frameNow || + continuousLaser == NULL) { + // We are outside the loop time, or the laser doesn't exist -> create a new laser + ObjectID laserId = createLaser(sourceObj, victimObj, victimPos); + continuousLaser = TheGameLogic->findObjectByID(laserId); + if (continuousLaser == NULL) { + return; + } + m_continuousLaserID = laserId; + return; + } + + // We have an existing laser + continuousLaser->setPosition(sourceObj->getPosition()); + + //Check for laser update + Drawable* draw = continuousLaser->getDrawable(); + if (draw) + { + // Try to update lifetime of the laser + static NameKeyType key_LifetimeUpdate = NAMEKEY("LifetimeUpdate"); + LifetimeUpdate* lt_update = (LifetimeUpdate*)continuousLaser->findUpdateModule(key_LifetimeUpdate); + if (lt_update) { + lt_update->resetLifetime(); + } + + static NameKeyType key_LaserUpdate = NAMEKEY("LaserUpdate"); + LaserUpdate* update = (LaserUpdate*)draw->findClientUpdateModule(key_LaserUpdate); + if (update) + { + Coord3D pos = *victimPos; + if (victimObj && !victimObj->isKindOf(KINDOF_PROJECTILE) && !victimObj->isAirborneTarget()) + { + //Targets are positioned on the ground, so raise the beam up so we're not shooting their feet. + //Projectiles are a different story, target their exact position. + pos.z += 10.0f; + } + update->updateContinuousLaser(sourceObj, victimObj, sourceObj->getPosition(), &pos); + } + } } +//------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // return true if we auto-reloaded our clip after firing. //DECLARE_PERF_TIMER(fireWeapon) @@ -2587,6 +2777,8 @@ Bool Weapon::privateFireWeapon( WeaponBonus bonus; computeBonus(sourceObj, extraBonusFlags, bonus); + // debug_printWeaponBonus(&bonus, m_template->getName()); + DEBUG_ASSERTCRASH(getStatus() != OUT_OF_AMMO, ("Hmm, firing weapon that is OUT_OF_AMMO")); DEBUG_ASSERTCRASH(getStatus() == READY_TO_FIRE, ("Hmm, Weapon is firing more often than should be possible")); DEBUG_ASSERTCRASH(m_ammoInClip > 0, ("Hmm, firing an empty weapon")); @@ -2605,32 +2797,84 @@ Bool Weapon::privateFireWeapon( m_numShotsForCurBarrel = m_template->getShotsPerBarrel(); } - if( m_scatterTargetsUnused.size() ) + if( m_scatterTargetsUnused.size() && !isProjectileDetonation) { + // If we haven't fired for this long: reset the scatter targets. + if (m_template->getScatterTargetResetTime() > 0) { + UnsignedInt frameNow = TheGameLogic->getFrame(); + if (m_lastFireFrame + m_template->getScatterTargetResetTime() < frameNow) { + rebuildScatterTargets(); + } + } + + // If I have a set scatter pattern, I need to offset the target by a random pick from that pattern if( victimObj ) { victimPos = victimObj->getPosition(); victimObj = NULL; } - Coord3D targetPos = *victimPos; // need to copy, as this pointer is actually inside somebody potentially - Int randomPick = GameLogicRandomValue( 0, m_scatterTargetsUnused.size() - 1 ); - Int targetIndex = m_scatterTargetsUnused[randomPick]; + Coord3D targetPos = *victimPos; // need to copy, as this pointer is actually inside somebody potentially + + Int targetIndex = 0; + if (m_template->isScatterTargetRandom()) { + Int randomPick = GameLogicRandomValue(0, m_scatterTargetsUnused.size() - 1); + targetIndex = m_scatterTargetsUnused[randomPick]; + // To erase from a vector, put the last on the one you used and pop the back. + m_scatterTargetsUnused[randomPick] = m_scatterTargetsUnused.back(); + m_scatterTargetsUnused.pop_back(); + } + else { + //We actually pick from the back of the the order of targets + targetIndex = m_scatterTargetsUnused[m_scatterTargetsUnused.size() - 1]; + m_scatterTargetsUnused.pop_back(); + } Real scatterTargetScalar = getScatterTargetScalar();// essentially a radius, but operates only on this scatterTarget table Coord2D scatterOffset = m_template->getScatterTargetsVector().at( targetIndex ); + // Scale scatter target based on range + if (Real minScale = m_template->getScatterTargetMinScalar() > 0) { + Real minRange = m_template->getMinimumAttackRange(); + Real maxRange = m_template->getUnmodifiedAttackRange(); + Real range = sqrt(ThePartitionManager->getDistanceSquared(sourceObj, victimPos, FROM_CENTER_2D)); + Real rangeRatio = (range - minRange) / (maxRange - minRange); + scatterTargetScalar = (rangeRatio * (scatterTargetScalar - minScale)) + minScale; + // DEBUG_LOG((">>> Weapon: Range = %f, RangeRatio = %f, TargetScalar = %f\n", range, rangeRatio, scatterTargetScalar)); + } + scatterOffset.x *= scatterTargetScalar; scatterOffset.y *= scatterTargetScalar; + // New: align scatter pattern to shooter, and/or use a random angle + if (m_template->isScatterTargetAligned() || m_scatterTargetsAngle != 0.0f) { + // DEBUG_LOG((">>> Weapon: m_scatterTargetsAngle = %f\n", m_scatterTargetsAngle)); + + const Coord3D srcPos = *sourceObj->getPosition(); + + Real angle = m_scatterTargetsAngle; + if (m_template->isScatterTargetAligned()) { + angle += atan2(targetPos.y - srcPos.y, targetPos.x - srcPos.x); + // angle += atan2(srcPos.y - targetPos.y, srcPos.x - targetPos.x); + } + + Real cosA = Cos(angle); + Real sinA = Sin(angle); + Real scatterOffsetRotX = scatterOffset.x * cosA - scatterOffset.y * sinA; + Real scatterOffsetRotY = scatterOffset.x * sinA + scatterOffset.y * cosA; + scatterOffset.x = scatterOffsetRotX; + scatterOffset.y = scatterOffsetRotY; + } + + if (m_template->isScatterTargetCenteredAtShooter()) { + targetPos = *sourceObj->getPosition(); + } + targetPos.x += scatterOffset.x; targetPos.y += scatterOffset.y; targetPos.z = TheTerrainLogic->getGroundHeight(targetPos.x, targetPos.y); - // To erase from a vector, put the last on the one you used and pop the back. - m_scatterTargetsUnused[randomPick] = m_scatterTargetsUnused.back(); - m_scatterTargetsUnused.pop_back(); m_template->fireWeaponTemplate(sourceObj, m_wslot, m_curBarrel, victimObj, &targetPos, bonus, isProjectileDetonation, ignoreRanges, this, projectileID, inflictDamage ); } else @@ -2700,14 +2944,69 @@ Bool Weapon::privateFireWeapon( //------------------------------------------------------------------------------------------------- void Weapon::preFireWeapon( const Object *source, const Object *victim ) { - Int delay = getPreAttackDelay( source, victim ); - if( delay > 0 ) + Int delay = getPreAttackDelay(source, victim); + if (delay > 0) + { + Bool allowFX = TheGameLogic->getFrame() > getNextPreAttackFXFrame(); + + setStatus(PRE_ATTACK); + setPreAttackFinishedFrame(TheGameLogic->getFrame() + delay); + if (m_template->isLeechRangeWeapon()) + { + setLeechRangeActive(TRUE); + } + + if (allowFX) { + + // Fix currentBarrel + Int curBarrel = m_curBarrel; + Int barrelCount = source->getDrawable()->getBarrelCount(m_wslot); + + if (curBarrel >= barrelCount) + { + curBarrel = 0; + } + + getTemplate()->createPreAttackFX(source, m_wslot, curBarrel, victim, NULL); + // Add delay to avoid spamming the FX + if (m_template->getPreAttackFXDelay() > 0) { + setNextPreAttackFXFrame(TheGameLogic->getFrame() + m_template->getPreAttackFXDelay()); + } + } + } +} + +//------------------------------------------------------------------------------------------------- +// Same as above but with target location instead of object +void Weapon::preFireWeapon(const Object* source, const Coord3D* pos) +{ + Int delay = getPreAttackDelay(source, NULL); + if (delay > 0) { - setStatus( PRE_ATTACK ); - setPreAttackFinishedFrame( TheGameLogic->getFrame() + delay ); - if( m_template->isLeechRangeWeapon() ) + Bool allowFX = TheGameLogic->getFrame() > getNextPreAttackFXFrame(); + + setStatus(PRE_ATTACK); + setPreAttackFinishedFrame(TheGameLogic->getFrame() + delay); + if (m_template->isLeechRangeWeapon()) { - setLeechRangeActive( TRUE ); + setLeechRangeActive(TRUE); + } + + if (allowFX) { + // Fix currentBarrel + Int curBarrel = m_curBarrel; + Int barrelCount = source->getDrawable()->getBarrelCount(m_wslot); + + if (curBarrel >= barrelCount) + { + curBarrel = 0; + } + + getTemplate()->createPreAttackFX(source, m_wslot, curBarrel, NULL, pos); + // Add delay to avoid spamming the FX + if (m_template->getPreAttackFXDelay() > 0) { + setNextPreAttackFXFrame(TheGameLogic->getFrame() + m_template->getPreAttackFXDelay()); + } } } } @@ -3003,7 +3302,7 @@ void Weapon::processRequestAssistance( const Object *requestingObject, Object *v #endif } -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // Real muzzleHeight = attachTransform.Get_Z_Translation(); // DEBUG_ASSERTCRASH( muzzleHeight > 0.001f, ("YOUR TURRET HAS A VERY LOW PROJECTILE LAUNCH POSITION, BUT FOUND A VALID BONE. DID YOU PICK THE WRONG ONE? %s", launcher->getTemplate()->getName().str())); //#endif @@ -3226,6 +3525,16 @@ void Weapon::crc( Xfer *xfer ) } #endif // DEBUG_CRC + // m_nextPreAttackFXFrame + xfer->xferUnsignedInt(&m_nextPreAttackFXFrame); +#ifdef DEBUG_CRC + if (doLogging) + { + tmp.format("m_nextPreAttackFXFrame %d ", m_nextPreAttackFXFrame); + logString.concat(tmp); + } +#endif // DEBUG_CRC + // when last reload started xfer->xferUnsignedInt( &m_whenLastReloadStarted ); #ifdef DEBUG_CRC @@ -3347,6 +3656,28 @@ void Weapon::crc( Xfer *xfer ) } #endif // DEBUG_CRC + // scatter targets random angle + xfer->xferReal(&m_scatterTargetsAngle); +#ifdef DEBUG_CRC + if (doLogging) + { + tmp.format("m_scatterTargetsAngle %d ", m_scatterTargetsAngle); + logString.concat(tmp); + } +#endif // DEBUG_CRC + + + // continuous laser object + xfer->xferObjectID(&m_continuousLaserID); +#ifdef DEBUG_CRC + if (doLogging) + { + tmp.format("m_continuousLaserID %d ", m_continuousLaserID); + logString.concat(tmp); + } +#endif // DEBUG_CRC + + #ifdef DEBUG_CRC if (doLogging) @@ -3355,6 +3686,7 @@ void Weapon::crc( Xfer *xfer ) } #endif // DEBUG_CRC + } // end crc // ------------------------------------------------------------------------------------------------ @@ -3396,6 +3728,9 @@ void Weapon::xfer( Xfer *xfer ) // wehn pre attack finished xfer->xferUnsignedInt( &m_whenPreAttackFinished ); + // when next preAttack FX + xfer->xferUnsignedInt( &m_nextPreAttackFXFrame); + // when last reload started xfer->xferUnsignedInt( &m_whenLastReloadStarted ); @@ -3463,6 +3798,13 @@ void Weapon::xfer( Xfer *xfer ) // leech weapon range active xfer->xferBool( &m_leechWeaponRangeActive ); + // scatter targets random angle + xfer->xferReal( &m_scatterTargetsAngle ); + + // continuous laser object + xfer->xferObjectID(&m_continuousLaserID); + + } // end xfer // ------------------------------------------------------------------------------------------------ @@ -3478,6 +3820,15 @@ void Weapon::loadPostProcess( void ) m_projectileStreamID = INVALID_ID; } } + + if (m_continuousLaserID != INVALID_ID) + { + Object* continuousLaser = TheGameLogic->findObjectByID(m_continuousLaserID); + if (continuousLaser == NULL) + { + m_continuousLaserID = INVALID_ID; + } + } } //------------------------------------------------------------------------------------------------- diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp index 771c8a87ef..5fe77f7e2d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp @@ -53,7 +53,7 @@ #include "GameLogic/Weapon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -82,6 +82,13 @@ const char* WeaponSetFlags::s_bitNameList[] = "WEAPON_RIDER6", "WEAPON_RIDER7", "WEAPON_RIDER8", + // New Weaponsets + "PLAYER_UPGRADE2", + "PLAYER_UPGRADE3", + "PLAYER_UPGRADE4", + + "GARRISONED", + "CONTAINED", NULL }; @@ -103,6 +110,7 @@ void WeaponTemplateSet::clear() { m_isReloadTimeShared = false; m_isWeaponLockSharedAcrossSets = FALSE; + m_isWeaponReloadSharedAcrossSets = FALSE; m_types.clear(); for (int i = 0; i < WEAPONSLOT_COUNT; ++i) { @@ -158,6 +166,7 @@ void WeaponTemplateSet::parseWeaponTemplateSet( INI* ini, const ThingTemplate* t { "PreferredAgainst", WeaponTemplateSet::parsePreferredAgainst, NULL, 0 }, { "ShareWeaponReloadTime", INI::parseBool, NULL, offsetof( WeaponTemplateSet, m_isReloadTimeShared ) }, { "WeaponLockSharedAcrossSets", INI::parseBool, NULL, offsetof( WeaponTemplateSet, m_isWeaponLockSharedAcrossSets ) }, + { "WeaponReloadSharedAcrossSets", INI::parseBool, NULL, offsetof(WeaponTemplateSet, m_isWeaponReloadSharedAcrossSets) }, { 0, 0, 0, 0 } }; @@ -313,30 +322,63 @@ void WeaponSet::updateWeaponSet(const Object* obj) m_totalDamageTypeMask.clear(); m_hasPitchLimit = false; m_hasDamageWeapon = false; - for (Int i = WEAPONSLOT_COUNT - 1; i >= PRIMARY_WEAPON ; --i) + for (Int i = WEAPONSLOT_COUNT - 1; i >= PRIMARY_WEAPON; --i) { - if (m_weapons[i] != NULL) - { - m_weapons[i]->deleteInstance(); - m_weapons[i] = NULL; + if (set->isWeaponReloadSharedAcrossSets() && (m_weapons[i] != NULL)) { //This is a bit of redundant code, but it keeps it cleaner overall. + + Weapon* prevWeapon = m_weapons[i]; + + if (set->getNth((WeaponSlotType)i)) + { + m_weapons[i] = TheWeaponStore->allocateNewWeapon(set->getNth((WeaponSlotType)i), (WeaponSlotType)i); + + Real clipPercentage = prevWeapon->getClipSize() > 0 ? (Real)(prevWeapon->getRemainingAmmo()) / (Real)(prevWeapon->getClipSize()) : 0.0f; + + m_weapons[i]->transferNextShotStatsFrom(*prevWeapon); + m_weapons[i]->setClipPercentFull(clipPercentage, false); + + m_filledWeaponSlotMask |= (1 << i); + m_totalAntiMask |= m_weapons[i]->getAntiMask(); + m_totalDamageTypeMask.set(m_weapons[i]->getDamageType()); + if (m_weapons[i]->isPitchLimited()) + m_hasPitchLimit = true; + if (m_weapons[i]->isDamageWeapon()) + m_hasDamageWeapon = true; + } + else { + m_weapons[i] = NULL; + } + + if (prevWeapon != NULL) + { + prevWeapon->deleteInstance(); + prevWeapon = NULL; + } } + else { // Regular old behaviour + if (m_weapons[i] != NULL) + { + m_weapons[i]->deleteInstance(); + m_weapons[i] = NULL; + } - if (set->getNth((WeaponSlotType)i)) - { - m_weapons[i] = TheWeaponStore->allocateNewWeapon(set->getNth((WeaponSlotType)i), (WeaponSlotType)i); - m_weapons[i]->loadAmmoNow(obj); // start 'em all with full clips. - m_filledWeaponSlotMask |= (1 << i); - m_totalAntiMask |= m_weapons[i]->getAntiMask(); - m_totalDamageTypeMask.set(m_weapons[i]->getDamageType()); - if (m_weapons[i]->isPitchLimited()) - m_hasPitchLimit = true; - if (m_weapons[i]->isDamageWeapon()) - m_hasDamageWeapon = true; - - // no, do NOT do this; always start with the cur weapon being primary, even if there is no primary - // weapon. this is by design, to allow us to have units that have only "spell" weapons and no - // "normal" weapons. (srj) - // m_curWeapon = (WeaponSlotType)i; + if (set->getNth((WeaponSlotType)i)) + { + m_weapons[i] = TheWeaponStore->allocateNewWeapon(set->getNth((WeaponSlotType)i), (WeaponSlotType)i); + m_weapons[i]->loadAmmoNow(obj); // start 'em all with full clips. + m_filledWeaponSlotMask |= (1 << i); + m_totalAntiMask |= m_weapons[i]->getAntiMask(); + m_totalDamageTypeMask.set(m_weapons[i]->getDamageType()); + if (m_weapons[i]->isPitchLimited()) + m_hasPitchLimit = true; + if (m_weapons[i]->isDamageWeapon()) + m_hasDamageWeapon = true; + + // no, do NOT do this; always start with the cur weapon being primary, even if there is no primary + // weapon. this is by design, to allow us to have units that have only "spell" weapons and no + // "normal" weapons. (srj) + // m_curWeapon = (WeaponSlotType)i; + } } } m_curWeaponTemplateSet = set; diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp index 5c4f05b4c4..8504ee780c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp @@ -86,7 +86,7 @@ #include "GameLogic/VictoryConditions.h" #include "GameLogic/AIPathfind.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -3200,7 +3200,7 @@ void ScriptActions::doMergeTeamIntoTeam(const AsciiString& teamSrcName, const As //------------------------------------------------------------------------------------------------- void ScriptActions::doDisableInput() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_disableScriptedInputDisabling) #endif { @@ -3852,7 +3852,7 @@ void ScriptActions::doUnfreezeTime(void) //------------------------------------------------------------------------------------------------- void ScriptActions::doMilitaryCaption(const AsciiString& briefing, Int duration) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_disableMilitaryCaption) duration = 1; #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp index 845bfcb1b3..a5eb1386ba 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptConditions.cpp @@ -61,7 +61,7 @@ #include "GameLogic/Scripts.h" #include "GameLogic/VictoryConditions.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp index 9ebd1bbc2e..3b76b555ea 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptEngine.cpp @@ -57,7 +57,7 @@ #include "GameLogic/ScriptEngine.h" #include "GameLogic/SidesList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -105,7 +105,7 @@ Bool st_particleSystemNeedsStopping = FALSE; ///< Set along with st_particleSyst #define FORMAT_STRING_LEADING_STRING "%s%.2f" // That's it for particle editor -#if defined(_INTERNAL) +#if defined(RTS_INTERNAL) #define DO_VTUNE_STUFF #endif @@ -194,7 +194,7 @@ Int AttackPriorityInfo::getPriority(const ThingTemplate *tThing) const return priority; } -#ifdef _DEBUG +#ifdef RTS_DEBUG /** Dump the info. */ //------------------------------------------------------------------------------------------------- void AttackPriorityInfo::dumpPriorityInfo(void) @@ -5615,7 +5615,7 @@ void ScriptEngine::update( void ) _adjustVariable(m_flags[k].name.str(), m_flags[k].value); } } -#ifdef _DEBUG +#ifdef RTS_DEBUG if (TheGameLogic->getFrame()==0) { for (i=0; im_disableCameraFade) { m_fade = FADE_NONE; @@ -9332,7 +9332,7 @@ void ScriptEngine::loadPostProcess( void ) } // end loadPostProcess -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void ScriptEngine::debugVictory( void ) { ScriptAction *action = newInstance(ScriptAction)(ScriptAction::VICTORY); diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp index 4f5181a68d..9a04a12b44 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/Scripts.cpp @@ -67,7 +67,7 @@ #include "GameLogic/Module/ContainModule.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp index eafb55b7ec..babe8b88b5 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp @@ -52,7 +52,7 @@ #include "GameNetwork/GameInfo.h" #include "GameNetwork/NetworkDefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp index daa32cb045..74718ca7bf 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp @@ -130,7 +130,7 @@ extern void externalAddTree(Coord3D location, Real scale, Real angle, AsciiStrin #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -436,22 +436,20 @@ void GameLogic::reset( void ) m_thingTemplateBuildableOverrides.clear(); m_controlBarOverrides.clear(); - // destroy all objects - // TheSuperHackers @info xezon 10/04/2025 Objects need to be destroyed before clearing the object vector. - destroyAllObjectsImmediate(); - // set the hash to be rather large. We need to optimize this value later. - m_objHash.clear(); -#if USING_STLPORT - m_objHash.resize(OBJ_HASH_SIZE); -#else - m_objHash.reserve(OBJ_HASH_SIZE); -#endif +// m_objHash.clear(); +// m_objHash.resize(OBJ_HASH_SIZE); + m_objVector.clear(); + m_objVector.resize(OBJ_HASH_SIZE, NULL); + m_gamePaused = FALSE; m_inputEnabledMemory = TRUE; m_mouseVisibleMemory = TRUE; setFPMode(); + // destroy all objects + destroyAllObjectsImmediate(); + m_nextObjID = (ObjectID)1; m_frameObjectsChangedTriggerAreas = 0; @@ -1114,6 +1112,15 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) GetPrecisionTimer(&startTime64); #endif + // reset the frame counter + m_frame = 0; + +#ifdef DEBUG_CRC + // TheSuperHackers @info helmutbuhler 04/09/2025 + // Let CRC Logger know that a new game was started. + CRCDebugStartNewGame(); +#endif + setLoadingMap( TRUE ); if( loadingSaveGame == FALSE ) @@ -1286,8 +1293,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame ) if(m_loadScreen) updateLoadProgress(LOAD_PROGRESS_POST_PARTICLE_INI_LOAD); - // reset the frame counter - m_frame = 0; + DEBUG_ASSERTCRASH(m_frame == 0, ("framecounter expected to be 0 here\n")); // before loading the map, load the map.ini file in the same directory. loadMapINI( TheGlobalData->m_mapName ); @@ -2550,7 +2556,7 @@ void GameLogic::processCommandList( CommandList *list ) for( msg = list->getFirstMessage(); msg; msg = msg->next() ) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(msg != NULL && msg != (GameMessage*)0xdeadbeef, ("bad msg")); #endif logicMessageDispatcher( msg, NULL ); @@ -3594,11 +3600,11 @@ void GameLogic::update( void ) Total_Load_3D_Assets=0; #endif -#ifdef _PROFILE +#ifdef RTS_PROFILE Profile::StartRange("map_load"); #endif startNewGame( FALSE ); -#ifdef _PROFILE +#ifdef RTS_PROFILE Profile::StopRange("map_load"); #endif m_startNewGame = FALSE; @@ -3657,7 +3663,7 @@ void GameLogic::update( void ) Bool generateForMP = (isMPGameOrReplay && (m_frame % TheGameInfo->getCRCInterval()) == 0); #ifdef DEBUG_CRC Bool generateForSolo = isSoloGameOrReplay && ((m_frame && (m_frame%100 == 0)) || - (getFrame() > TheCRCFirstFrameToLog && getFrame() < TheCRCLastFrameToLog && ((m_frame % REPLAY_CRC_INTERVAL) == 0))); + (getFrame() >= TheCRCFirstFrameToLog && getFrame() < TheCRCLastFrameToLog && ((m_frame % REPLAY_CRC_INTERVAL) == 0))); #else Bool generateForSolo = isSoloGameOrReplay && ((m_frame % REPLAY_CRC_INTERVAL) == 0); #endif // DEBUG_CRC @@ -3670,14 +3676,14 @@ void GameLogic::update( void ) GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_LOGIC_CRC ); msg->appendIntegerArgument( m_CRC ); msg->appendBooleanArgument( (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK) ); // playback CRC - //DEBUG_LOG(("Appended CRC of %8.8X on frame %d\n", m_CRC, m_frame)); + DEBUG_LOG(("Appended CRC on frame %d: %8.8X\n", m_frame, m_CRC)); } else { GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_LOGIC_CRC ); msg->appendIntegerArgument( m_CRC ); msg->appendBooleanArgument( (TheRecorder && TheRecorder->getMode() == RECORDERMODETYPE_PLAYBACK) ); // playback CRC - //DEBUG_LOG(("Appended Playback CRC of %8.8X on frame %d\n", m_CRC, m_frame)); + DEBUG_LOG(("Appended Playback CRC on frame %d: %8.8X\n", m_frame, m_CRC)); } } @@ -3860,7 +3866,12 @@ void GameLogic::addObjectToLookupTable( Object *obj ) return; // add to lookup - m_objHash[ obj->getID() ] = obj; +// m_objHash[ obj->getID() ] = obj; + ObjectID newID = obj->getID(); + while( newID >= m_objVector.size() ) // Fail case is hella rare, so faster to double up on size() call + m_objVector.resize(m_objVector.size() * 2, NULL); + + m_objVector[ newID ] = obj; } // end addObjectToLookupTable @@ -3871,11 +3882,13 @@ void GameLogic::removeObjectFromLookupTable( Object *obj ) { // sanity - if( obj == NULL ) + // TheSuperHackers @fix Mauller/Xezon 24/04/2025 Prevent out of range access to vector lookup table + if( obj == NULL || static_cast(obj->getID()) >= m_objVector.size() ) return; // remove from lookup table - m_objHash.erase( obj->getID() ); +// m_objHash.erase( obj->getID() ); + m_objVector[ obj->getID() ] = NULL; } // end removeObjectFromLookupTable @@ -4027,6 +4040,12 @@ UnsignedInt GameLogic::getCRC( Int mode, AsciiString deepCRCFileName ) { AsciiString crcName; #ifdef DEBUG_CRC + // TheSuperHackers @info helmutbuhler 04/09/2025 + // This allows you to save the binary data that is involved in the crc calculation + // to a binary file per frame. + // This was apparently used early in development and isn't that useful, because diffing + // that binary data is very difficult. The CRC logging is much easier to diff and also more + // granular than this because it can capture changes between two frames. if (isInGameLogicUpdate() && g_keepCRCSaves && m_frame < 5) { xferCRC = NEW XferDeepCRC; @@ -4249,7 +4268,6 @@ void GameLogic::setGamePaused( Bool paused, Bool pauseMusic ) while( drawable ) { drawable->startAmbientSound(); - TheAudio->stopAllAmbientsBy( drawable ); drawable = drawable->getNextDrawable(); } #endif diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp index 2434afa6e6..18d7ab1c73 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp @@ -86,7 +86,7 @@ #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -351,7 +351,7 @@ void GameLogic::prepareNewGame( Int gameMode, GameDifficulty diff, Int rankPoint //------------------------------------------------------------------------------------------------- void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(msg != NULL && msg != (GameMessage*)0xdeadbeef, ("bad msg")); #endif @@ -452,7 +452,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) case GameMessage::MSG_CLEAR_GAME_DATA: { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheDisplay && TheGlobalData->m_dumpAssetUsage) TheDisplay->dumpAssetUsage(TheGlobalData->m_mapName.str()); #endif @@ -914,7 +914,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) break; } -#if defined(_DEBUG) || defined(_INTERNAL) || defined (_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined (_ALLOW_DEBUG_CHEATS_IN_RELEASE) //--------------------------------------------------------------------------------------------- case GameMessage::MSG_DEBUG_KILL_SELECTION: { @@ -1945,13 +1945,13 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, void *userData ) if (thisPlayer->isLocalPlayer()) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // don't even put this in release, cause someone might hack it. if (!TheDebugIgnoreSyncErrors) { #endif m_shouldValidateCRCs = TRUE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } #endif } diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp index 6b38d73d4f..5d447aff82 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/RankInfo.cpp @@ -35,7 +35,7 @@ RankInfoStore* TheRankInfoStore = NULL; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp index c1ec639ecc..7b8b4e1f69 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp @@ -206,14 +206,14 @@ void Connection::sendNetCommandMsg(NetCommandMsg *msg, UnsignedByte relay) { if (ref != NULL) { /* -#if ((defined(_DEBUG)) || (defined(_INTERNAL))) +#if ((defined(RTS_DEBUG)) || (defined(RTS_INTERNAL))) if (msg->getNetCommandType() == NETCOMMANDTYPE_GAMECOMMAND) { DEBUG_LOG(("Connection::sendNetCommandMsg - added game command %d to net command list for frame %d.\n", msg->getID(), msg->getExecutionFrame())); } else if (msg->getNetCommandType() == NETCOMMANDTYPE_FRAMEINFO) { DEBUG_LOG(("Connection::sendNetCommandMsg - added frame info for frame %d\n", msg->getExecutionFrame())); } -#endif // _DEBUG || _INTERNAL +#endif // RTS_DEBUG || RTS_INTERNAL */ ref->setRelay(relay); @@ -371,7 +371,7 @@ NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte ori return NULL; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool doDebug = FALSE; if (temp->getCommand()->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) { doDebug = TRUE; @@ -384,7 +384,7 @@ NetCommandRef * Connection::processAck(UnsignedShort commandID, UnsignedByte ori m_averageLatency += lat / CONNECTION_LATENCY_HISTORY_LENGTH; m_latencies[index] = lat; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug == TRUE) { DEBUG_LOG(("Connection::processAck - disconnect frame command %d found, removing from command list.\n", commandID)); } @@ -411,7 +411,7 @@ void Connection::doRetryMetrics() { } } -#if defined(_DEBUG) || (_INTERNAL) +#if defined(RTS_DEBUG) || (RTS_INTERNAL) void Connection::debugPrintCommands() { NetCommandRef *ref = m_netCommandList->getFirstMessage(); while (ref != NULL) { diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp index 173769766f..99d4050512 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/ConnectionManager.cpp @@ -53,7 +53,7 @@ #include "GameClient/DisconnectMenu.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -682,7 +682,7 @@ void ConnectionManager::processChat(NetChatCommandMsg *msg) void ConnectionManager::processFile(NetFileCommandMsg *msg) { -#ifdef _INTERNAL +#ifdef RTS_INTERNAL UnicodeString log; log.format(L"Saw file transfer: '%hs' of %d bytes from %d", msg->getPortableFilename().str(), msg->getFileLength(), msg->getPlayerID()); DEBUG_LOG(("%ls\n", log.str())); @@ -827,14 +827,14 @@ void ConnectionManager::processFrameInfo(NetFrameCommandMsg *msg) { * it doesn't keep resending it. */ void ConnectionManager::processAckStage1(NetCommandMsg *msg) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool doDebug = (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) ? TRUE : FALSE; #endif UnsignedByte playerID = msg->getPlayerID(); NetCommandRef *ref = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug == TRUE) { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::processAck - processing ack for command %d from player %d\n", ((NetAckStage1CommandMsg *)msg)->getCommandID(), playerID)); } @@ -1035,7 +1035,7 @@ void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) { } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool doDebug = (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) ? TRUE : FALSE; #endif @@ -1045,7 +1045,7 @@ void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) { ackmsg = bothmsg; commandID = bothmsg->getCommandID(); originalPlayerID = bothmsg->getOriginalPlayerID(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug) { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::ackCommand - doing ack both for command %d from player %d\n", bothmsg->getCommandID(), bothmsg->getOriginalPlayerID())); } @@ -1055,7 +1055,7 @@ void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) { ackmsg = stage1msg; commandID = stage1msg->getCommandID(); originalPlayerID = stage1msg->getOriginalPlayerID(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (doDebug) { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::ackCommand - doing ack stage 1 for command %d from player %d\n", stage1msg->getCommandID(), stage1msg->getOriginalPlayerID())); } @@ -1554,7 +1554,7 @@ Int commandsReadyDebugSpewage = 0; */ Bool ConnectionManager::allCommandsReady(UnsignedInt frame, Bool justTesting /* = FALSE */) { Bool retval = TRUE; - FrameDataReturnType frameRetVal; + FrameDataReturnType frameRetVal = FRAMEDATA_NOTREADY; // retval = FALSE; // ****for testing purposes only!!!!!!**** Int i = 0; for (; (i < MAX_SLOTS) && retval; ++i) { @@ -2315,7 +2315,7 @@ Int ConnectionManager::getSlotAverageFPS(Int slot) { return m_fpsAverages[slot]; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void ConnectionManager::debugPrintConnectionCommands() { DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::debugPrintConnectionCommands - begin commands\n")); for (Int i = 0; i < MAX_SLOTS; ++i) { @@ -2347,7 +2347,7 @@ void ConnectionManager::notifyOthersOfCurrentFrame(Int frame) { msg->detach(); DEBUG_LOG_LEVEL(DEBUG_LEVEL_NET, ("ConnectionManager::notifyOthersOfCurrentFrame - start screen on debug stuff\n")); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) debugPrintConnectionCommands(); #endif } diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp index 386ecf20f4..cf8c7d85f9 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/DisconnectManager.cpp @@ -35,7 +35,7 @@ #include "GameNetwork/GameSpy/PingThread.h" #include "GameNetwork/GameSpy/GSConfig.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp index 87d0ee08cf..a1dcdaa455 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp @@ -56,7 +56,7 @@ #include "GameNetwork/NetworkDefs.h" #include "GameNetwork/GameSpy/GSConfig.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp index a1f2da82d6..6ecd086d4f 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp @@ -46,7 +46,7 @@ #include "GameNetwork/LANAPICallbacks.h" // for acceptTrueColor, etc #include "GameClient/ChallengeGenerals.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp index 4896328827..bec5b86d85 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameInfo.cpp @@ -45,7 +45,7 @@ #include "GameNetwork/LANAPICallbacks.h" // for testing packet size #include "strtok_r.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp index 3cc5c3ca6a..2d3523931e 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Chat.cpp @@ -37,7 +37,7 @@ #include "GameNetwork/GameSpy/PeerDefsImplementation.h" #include "GameNetwork/GameSpy/PeerThread.h" #include "GameClient/InGameUI.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp index 0bb8649f5f..1fed5139ca 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/GSConfig.cpp @@ -36,7 +36,7 @@ #include "GameNetwork/GameSpy/GSConfig.h" #include "GameNetwork/RankPointValue.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp index a8cdb7859a..eea0e80313 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LadderDefs.cpp @@ -39,7 +39,7 @@ #include "GameClient/GameText.h" #include "GameClient/MapUtil.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp index d1ef80fcbb..10b11d0d8d 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/LobbyUtils.cpp @@ -62,7 +62,7 @@ #include "Common/STLTypedefs.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp index 3ddc944245..2fbbf1803c 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/MainMenuUtils.cpp @@ -54,7 +54,7 @@ #include "WWDownload/Registry.h" #include "WWDownload/urlBuilder.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp index c4a94f92fc..f7802eae71 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/PeerDefs.cpp @@ -46,7 +46,7 @@ #include "GameNetwork/RankPointValue.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp index 848b3f6320..00d345f7ba 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/StagingRoomGameInfo.cpp @@ -48,7 +48,7 @@ #include "GameNetwork/NAT.h" #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -584,7 +584,7 @@ void GameSpyStagingRoom::startGame(Int gameID) } } -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (numHumans < 2) { launchGame(); @@ -592,7 +592,7 @@ void GameSpyStagingRoom::startGame(Int gameID) TheGameSpyInfo->leaveStagingRoom(); } else -//#endif // defined(_DEBUG) || defined(_INTERNAL) +//#endif // defined(RTS_DEBUG) || defined(RTS_INTERNAL) { TheNAT = NEW NAT(); TheNAT->attachSlotList(m_slot, getLocalSlotNum(), m_localIP); diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp index 3fbec0117c..669d7b1388 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/BuddyThread.cpp @@ -41,7 +41,7 @@ #include "mutex.h" #include "thread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -545,7 +545,7 @@ void BuddyThreadClass::connectCallback( GPConnection *con, GPConnectResponseArg DEBUG_LOG(("Buddy connect: trying chat connect\n")); PeerRequest req; req.peerRequestType = PeerRequest::PEERREQUEST_LOGIN; - req.nick = m_nick.c_str(); + req.nick = m_nick; req.password = m_pass; req.email = m_email; req.login.profileID = arg->profile; diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp index bad4c6c738..ed88e177df 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PeerThread.cpp @@ -48,7 +48,7 @@ #include "Common/MiniLog.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -84,7 +84,7 @@ static LogClass s_stateChangedLog("StateChanged.txt"); // -MDC 2/14/2003 #define USE_BROADCAST_KEYS -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp index cd11b9e1b2..f06528d9fd 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpy/Thread/PersistentStorageThread.cpp @@ -42,7 +42,7 @@ #include "Common/StackDump.h" #include "Common/SubsystemInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp index 23d9be07b6..1aeda9e891 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GameSpyChat.cpp @@ -135,7 +135,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo case L'r': case L'R': remainder.nextToken(&token); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL if (token.compareNoCase(L"raw") == 0) { // Send raw IRC commands (Ascii only) @@ -149,7 +149,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo } #endif break; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL case L'k': case L'K': remainder.nextToken(&token); @@ -194,7 +194,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo } return true; // show it anyway } -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL else if (token.compareNoCase(L"oper") == 0) { // Send raw IRC oper command @@ -245,7 +245,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo return true; // show it anyway } break; -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL case L'c': case L'C': remainder.nextToken(&token); @@ -262,7 +262,7 @@ static Bool handleSlashCommands( UnicodeString message, Bool isAction, GameWindo return true; // show it anyway } break; -#endif // _DEBUG || defined _INTERNAL +#endif // RTS_DEBUG || defined RTS_INTERNAL } } */ diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp index 4ee3eea8e6..e468f89829 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPI.cpp @@ -38,7 +38,7 @@ #include "Common/UserPreferences.h" #include "GameLogic/GameLogic.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -263,7 +263,7 @@ AsciiString GetMessageTypeString(UnsignedInt type) void LANAPI::checkMOTD( void ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_useLocalMOTD) { // for a playtest, let's log some play statistics, eh? diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp index fef5e4935e..bc575d36d0 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPICallbacks.cpp @@ -50,7 +50,7 @@ LANAPI *TheLAN = NULL; extern Bool LANbuttonPushed; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp index 6bee1500e7..b3a625d028 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp @@ -232,7 +232,7 @@ void LANAPI::handleRequestJoin( LANMessage *msg, UnsignedInt senderIP ) Bool canJoin = true; // see if the CRCs match -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_netMinPlayers > 0) { #endif /* if (msg->GameToJoin.iniCRC != TheGlobalData->m_iniCRC || @@ -248,10 +248,12 @@ void LANAPI::handleRequestJoin( LANMessage *msg, UnsignedInt senderIP ) canJoin = false; } */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) } #endif +// TheSuperHackers @tweak Disables the duplicate serial check +#if 0 // check for a duplicate serial AsciiString s; for (player = 0; canJoin && player m_playersToDisconnect; GameWindow *m_messageWindow; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) Bool m_networkOn; #endif }; @@ -279,7 +279,7 @@ Network::Network() m_conMgr = NULL; m_messageWindow = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_networkOn = TRUE; #endif } @@ -362,7 +362,7 @@ void Network::init() DEBUG_LOG(("FRAMES_TO_KEEP = %d\n", FRAMES_TO_KEEP)); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_networkOn = TRUE; #endif @@ -380,7 +380,8 @@ void Network::setSawCRCMismatch( void ) TheRecorder->logCRCMismatch(); // dump GameLogic random seed - DEBUG_LOG(("GameLogic frame = %d\n", TheGameLogic->getFrame())); + DEBUG_LOG(("Latest frame for mismatch = %d GameLogic frame = %d\n", + TheGameLogic->getFrame()-m_runAhead-1, TheGameLogic->getFrame())); DEBUG_LOG(("GetGameLogicRandomSeedCRC() = %d\n", GetGameLogicRandomSeedCRC())); // dump CRCs @@ -691,7 +692,7 @@ void Network::update( void ) // m_frameDataReady = FALSE; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (m_networkOn == FALSE) { return; } @@ -725,7 +726,7 @@ void Network::update( void ) void Network::liteupdate() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (m_networkOn == FALSE) { return; } @@ -749,7 +750,7 @@ void Network::endOfGameCheck() { DEBUG_LOG(("Network::endOfGameCheck - about to show the shell\n")); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) else { m_conMgr->debugPrintConnectionCommands(); } @@ -1015,7 +1016,7 @@ Int Network::getSlotAverageFPS(Int slot) { return -1; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void Network::toggleNetworkOn() { if (m_networkOn == TRUE) { m_networkOn = FALSE; diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp index 5e453847d4..28e8d06949 100644 --- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp +++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Transport.cpp @@ -29,7 +29,7 @@ #include "GameNetwork/Transport.h" #include "GameNetwork/NetworkInterface.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -136,7 +136,7 @@ Bool Transport::init( UnsignedInt ip, UnsignedShort port ) { m_outBuffer[i].length = 0; m_inBuffer[i].length = 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_delayedInBuffer[i].message.length = 0; #endif } @@ -154,7 +154,7 @@ Bool Transport::init( UnsignedInt ip, UnsignedShort port ) m_port = port; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_latencyAverage > 0 || TheGlobalData->m_latencyNoise) m_useLatency = true; @@ -249,7 +249,7 @@ Bool Transport::doSend() { } } // for (i=0; iRead(buf, MAX_MESSAGE_LEN, &from)) > 0 ) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // Packet loss simulation if (m_usePacketLoss) { @@ -332,7 +332,7 @@ Bool Transport::doRecv() for (int i=0; i SetAsciiString; typedef SetAsciiString::iterator SetAsciiStringIt; SetAsciiString m_allEventsLoaded; diff --git a/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdBIGFile.h b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdBIGFile.h new file mode 100644 index 0000000000..9880a541fa --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdBIGFile.h @@ -0,0 +1,58 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +/////// StdBIGFile.h //////////////////////////////////// +// Stephan Vedder, April 2025 +/////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __STDBIGFILE_H +#define __STDBIGFILE_H + +#include "Common/ArchiveFile.h" +#include "Common/AsciiString.h" +#include "Common/List.h" + +class StdBIGFile : public ArchiveFile +{ + public: + StdBIGFile(); + virtual ~StdBIGFile(); + + virtual Bool getFileInfo(const AsciiString& filename, FileInfo *fileInfo) const; ///< fill in the fileInfo struct with info about the requested file. + virtual File* openFile( const Char *filename, Int access = 0 );///< Open the specified file within the BIG file + virtual void closeAllFiles( void ); ///< Close all file opened in this BIG file + virtual AsciiString getName( void ); ///< Returns the name of the BIG file + virtual AsciiString getPath( void ); ///< Returns full path and name of BIG file + virtual void setSearchPriority( Int new_priority ); ///< Set this BIG file's search priority + virtual void close( void ); ///< Close this BIG file + + protected: + + AsciiString m_name; ///< BIG file name + AsciiString m_path; ///< BIG file path +}; + +#endif // __STDBIGFILE_H \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdBIGFileSystem.h b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdBIGFileSystem.h new file mode 100644 index 0000000000..3181e5308d --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdBIGFileSystem.h @@ -0,0 +1,60 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +//////// StdBIGFileSystem.h /////////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __STDBIGFILESYSTEM_H +#define __STDBIGFILESYSTEM_H + +#include "Common/ArchiveFileSystem.h" + +class StdBIGFileSystem : public ArchiveFileSystem +{ +public: + StdBIGFileSystem(); + virtual ~StdBIGFileSystem(); + + virtual void init( void ); + virtual void update( void ); + virtual void reset( void ); + virtual void postProcessLoad( void ); + + // ArchiveFile operations + virtual void closeAllArchiveFiles( void ); ///< Close all Archivefiles currently open + + // File operations + virtual ArchiveFile * openArchiveFile(const Char *filename); + virtual void closeArchiveFile(const Char *filename); + virtual void closeAllFiles( void ); ///< Close all files associated with ArchiveFiles + + virtual Bool loadBigFilesFromDirectory(AsciiString dir, AsciiString fileMask, Bool overwrite = FALSE); +protected: + +}; + +#endif // __STDBIGFILESYSTEM_H \ No newline at end of file diff --git a/Generals/Code/Tools/WW3D/pluglib/BITTYPE.H b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdLocalFile.h similarity index 51% rename from Generals/Code/Tools/WW3D/pluglib/BITTYPE.H rename to GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdLocalFile.h index 4188157216..5937be9359 100644 --- a/Generals/Code/Tools/WW3D/pluglib/BITTYPE.H +++ b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdLocalFile.h @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals(tm) +** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify @@ -16,31 +16,31 @@ ** along with this program. If not, see . */ -/***************************************************************** -* -* Project: 3DTEST1 (3d Test Program) -* -* File: bittype.h -* -* Start Date: Dec 18, 1996 -* -* Programmer: Greg Hjelstrom -* -*****************************************************************/ +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// -#ifndef BITTYPE_H -#define BITTYPE_H +///// StdLocalFile.h /////////////////////////// +// Stephan Vedder, April 2025 +////////////////////////////////////////////////// -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned long uint32; +#pragma once -typedef signed char sint8; -typedef signed short sint16; -typedef signed long sint32; +#ifndef __STDLOCALFILE_H +#define __STDLOCALFILE_H -typedef float float32; -typedef double float64; +#include "Common/LocalFile.h" +class StdLocalFile : public LocalFile +{ + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(StdLocalFile, "StdLocalFile") +public: + StdLocalFile(); + //virtual ~StdLocalFile(); -#endif //BITTYPE_H \ No newline at end of file +protected: +}; + +#endif // __STDLOCALFILE_H \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdLocalFileSystem.h b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdLocalFileSystem.h new file mode 100644 index 0000000000..3008120f68 --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Include/StdDevice/Common/StdLocalFileSystem.h @@ -0,0 +1,56 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +///// StdLocalFileSystem.h ////////////////////////////////// +// Stephan Vedder, April 2025 +/////////////////////////////////////////////////////////////// + +#pragma once + +#ifndef __STDLOCALFILESYSTEM_H +#define __STDLOCALFILESYSTEM_H +#include "Common/LocalFileSystem.h" + +class StdLocalFileSystem : public LocalFileSystem +{ +public: + StdLocalFileSystem(); + virtual ~StdLocalFileSystem(); + + virtual void init(); + virtual void reset(); + virtual void update(); + + virtual File * openFile(const Char *filename, Int access = 0); ///< open the given file. + virtual Bool doesFileExist(const Char *filename) const; ///< does the given file exist? + + virtual void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList &filenameList, Bool searchSubdirectories) const; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. + virtual Bool getFileInfo(const AsciiString& filename, FileInfo *fileInfo) const; + + virtual Bool createDirectory(AsciiString directory); + +protected: +}; + +#endif // __STDLOCALFILESYSTEM_H \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Include/VideoDevice/FFmpeg/FFmpegFile.h b/GeneralsMD/Code/GameEngineDevice/Include/VideoDevice/FFmpeg/FFmpegFile.h new file mode 100644 index 0000000000..cf060b69ef --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Include/VideoDevice/FFmpeg/FFmpegFile.h @@ -0,0 +1,97 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +//////// FFmpegFile.h /////////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////// + +#pragma once + +#include + +#include +#include + +struct AVFormatContext; +struct AVIOContext; +struct AVCodec; +struct AVCodecContext; +struct AVFrame; +struct AVPacket; +struct File; + +using FFmpegFrameCallback = std::function; + +class FFmpegFile +{ +public: + FFmpegFile(); + // The constructur takes ownership of the file + explicit FFmpegFile(File *file); + ~FFmpegFile(); + + Bool open(File *file); + void close(); + void setFrameCallback(FFmpegFrameCallback callback) { m_frameCallback = callback; } + void setUserData(void *user_data) { m_userData = user_data; } + // Read & decode a packet from the container. Note that we could/should split this step + Bool decodePacket(); + void seekFrame(int frame_idx); + Bool hasAudio() const; + + // Audio specific + Int getSizeForSamples(Int numSamples) const; + Int getNumChannels() const; + Int getSampleRate() const; + Int getBytesPerSample() const; + + // Video specific + Int getWidth() const; + Int getHeight() const; + Int getNumFrames() const; + Int getCurrentFrame() const; + Int getPixelFormat() const; + UnsignedInt getFrameTime() const; + +private: + struct FFmpegStream + { + AVCodecContext *codec_ctx = nullptr; + const AVCodec *codec = nullptr; + Int stream_idx = -1; + Int stream_type = -1; + AVFrame *frame = nullptr; + }; + + static Int readPacket(void *opaque, UnsignedByte *buf, Int buf_size); + const FFmpegStream *findMatch(int type) const; + + FFmpegFrameCallback m_frameCallback = nullptr; ///< Callback for frame processing + AVFormatContext *m_fmtCtx = nullptr; ///< Format context for AVFormat + AVIOContext *m_avioCtx = nullptr; ///< IO context for AVFormat + AVPacket *m_packet = nullptr; ///< Current packet + std::vector m_streams; ///< List of streams in the file + File *m_file = nullptr; ///< File handle for the file + void *m_userData = nullptr; ///< User data for the callback +}; \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Include/VideoDevice/FFmpeg/FFmpegVideoPlayer.h b/GeneralsMD/Code/GameEngineDevice/Include/VideoDevice/FFmpeg/FFmpegVideoPlayer.h new file mode 100644 index 0000000000..9488f63ef2 --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Include/VideoDevice/FFmpeg/FFmpegVideoPlayer.h @@ -0,0 +1,137 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +//////// FFmpegVideoPlayer.h /////////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////// + +#pragma once + +#ifndef __VIDEODEVICE_FFMPEGDEVICE_H_ +#define __VIDEODEVICE_FFMPEGDEVICE_H_ + + +//---------------------------------------------------------------------------- +// Includes +//---------------------------------------------------------------------------- + +#include "GameClient/VideoPlayer.h" + +//---------------------------------------------------------------------------- +// Forward References +//---------------------------------------------------------------------------- + +class FFmpegFile; +struct AVFrame; +struct SwsContext; + +//---------------------------------------------------------------------------- +// Type Defines +//---------------------------------------------------------------------------- + +//=============================== +// FFmpegVideoStream +//=============================== + +class FFmpegVideoStream : public VideoStream +{ + friend class FFmpegVideoPlayer; + + protected: + Bool m_good = true; ///< Is the stream valid + Bool m_gotFrame = false; ///< Is the frame ready to be displayed + AVFrame *m_frame = nullptr; ///< Current frame + SwsContext *m_swsContext = nullptr;///< SWSContext for scaling + FFmpegFile *m_ffmpegFile; ///< The AVUI abstraction ///< Bink streaming handle; + Char *m_memFile; ///< Pointer to memory resident file + UnsignedInt64 m_startTime = 0; ///< Time the stream started + UnsignedByte * m_audioBuffer = nullptr;///< Audio buffer for the stream + + FFmpegVideoStream(FFmpegFile* file); ///< only BinkVideoPlayer can create these + virtual ~FFmpegVideoStream(); + + static void onFrame(AVFrame *frame, int stream_idx, int stream_type, void *user_data); + public: + + virtual void update( void ); ///< Update bink stream + + virtual Bool isFrameReady( void ); ///< Is the frame ready to be displayed + virtual void frameDecompress( void ); ///< Render current frame in to buffer + virtual void frameRender( VideoBuffer *buffer ); ///< Render current frame in to buffer + virtual void frameNext( void ); ///< Advance to next frame + virtual Int frameIndex( void ); ///< Returns zero based index of current frame + virtual Int frameCount( void ); ///< Returns the total number of frames in the stream + virtual void frameGoto( Int index ); ///< Go to the spcified frame index + virtual Int height( void ); ///< Return the height of the video + virtual Int width( void ); ///< Return the width of the video + + +}; + +//=============================== +// FFmpegVideoPlayer +//=============================== +/** + * FFmpeg video playback code. + */ +//=============================== + +class FFmpegVideoPlayer : public VideoPlayer +{ + + protected: + + VideoStreamInterface* createStream( File* file ); + + public: + + // subsytem requirements + virtual void init( void ); ///< Initialize video playback code + virtual void reset( void ); ///< Reset video playback + virtual void update( void ); ///< Services all audio tasks. Should be called frequently + + virtual void deinit( void ); ///< Close down player + + + FFmpegVideoPlayer(); + ~FFmpegVideoPlayer(); + + // service + virtual void loseFocus( void ); ///< Should be called when application loses focus + virtual void regainFocus( void ); ///< Should be called when application regains focus + + virtual VideoStreamInterface* open( AsciiString movieTitle ); ///< Open video file for playback + virtual VideoStreamInterface* load( AsciiString movieTitle ); ///< Load video file in to memory for playback + + virtual void notifyVideoPlayerOfNewProvider( Bool nowHasValid ); + virtual void initializeBinkWithMiles( void ); +}; + + +//---------------------------------------------------------------------------- +// Inlining +//---------------------------------------------------------------------------- + + +#endif // __VIDEODEVICE_FFMPEGDEVICE_H_ \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h index 2dbc25047d..2d9a94f6f2 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DLaserDraw.h @@ -58,6 +58,10 @@ class W3DLaserDrawModuleData : public ModuleData Real m_arcHeight; Real m_segmentOverlapRatio; Real m_tilingScalar; + UnsignedInt m_gridColumns; + UnsignedInt m_gridColumnsTotal; + Bool m_useHouseColorInner; + Bool m_useHouseColorOuter; W3DLaserDrawModuleData(); ~W3DLaserDrawModuleData(); @@ -98,6 +102,8 @@ class W3DLaserDraw : public DrawModule, public LaserDrawInterface Real m_textureAspectRatio; ///< aspect ratio of texture Bool m_selfDirty; // not saved + Int m_hexColor; ///< player house color + }; #endif // __W3DLASERDRAW_H_ diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h index 0dba1661be..59fcef32c1 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h @@ -176,7 +176,7 @@ struct ModelConditionInfo Int m_fxBone; ///< the FX bone for this barrel (zero == no bone) Int m_muzzleFlashBone; ///< the muzzle-flash subobj bone for this barrel (zero == none) Matrix3D m_projectileOffsetMtx; ///< where the projectile fires from -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString m_muzzleFlashBoneName; #endif @@ -191,7 +191,7 @@ struct ModelConditionInfo m_fxBone = 0; m_muzzleFlashBone = 0; m_projectileOffsetMtx.Make_Identity(); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) m_muzzleFlashBoneName.clear(); #endif } @@ -200,7 +200,7 @@ struct ModelConditionInfo }; typedef std::vector WeaponBarrelInfoVec; -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString m_description; #endif std::vector m_conditionsYesVec; @@ -249,7 +249,7 @@ struct ModelConditionInfo inline Int getConditionsYesCount() const { DEBUG_ASSERTCRASH(m_conditionsYesVec.size() > 0, ("empty m_conditionsYesVec.size(), see srj")); return m_conditionsYesVec.size(); } inline const ModelConditionFlags& getNthConditionsYes(Int i) const { return m_conditionsYesVec[i]; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) inline AsciiString getDescription() const { return m_description; } #endif @@ -357,7 +357,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual void releaseShadows(void); ///< frees all shadow resources used by this module - used by Options screen. virtual void allocateShadows(void); ///< create shadow resources if not already present. Used by Options screen. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void getRenderCost(RenderCost & rc) const; ///< estimates the render cost of this draw module void getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) const; #endif @@ -385,6 +385,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface virtual void replaceModelConditionState(const ModelConditionFlags& c); virtual void replaceIndicatorColor(Color color); virtual Bool handleWeaponFireFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, const Coord3D* victimPos, Real damageRadius); + virtual Bool handleWeaponPreAttackFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, const Coord3D* victimPos, Real damageRadius); virtual Int getBarrelCount(WeaponSlotType wslot) const; virtual void setSelectable(Bool selectable); // Change the selectability of the model. @@ -520,7 +521,7 @@ class W3DModelDraw : public DrawModule, public ObjectDrawInterface void adjustAnimSpeedToMovementSpeed(); static void hideAllMuzzleFlashes(const ModelConditionInfo* state, RenderObjClass* renderObject); void hideAllHeadlights(Bool hide); -#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test. +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //art wants to see buildings without flags as a test. void hideGarrisonFlags(Bool hide); #endif }; diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h index ca9bbf46fc..06e4823276 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DAssetManager.h @@ -54,7 +54,6 @@ class Vector3; class VertexMaterialClass; -class GrannyAnimManagerClass; class W3DAssetManager: public WW3DAssetManager { @@ -108,8 +107,6 @@ class W3DAssetManager: public WW3DAssetManager int replaceHLODTexture(RenderObjClass *robj, TextureClass *oldTex, TextureClass *newTex); int replaceMeshTexture(RenderObjClass *robj, TextureClass *oldTex, TextureClass *newTex); - GrannyAnimManagerClass *m_GrannyAnimManager; - //'E&B' customizations /* virtual RenderObjClass * Create_Render_Obj(const char * name, float scale, const Vector3 &hsv_shift); TextureClass * Get_Texture_With_HSV_Shift(const char * filename, const Vector3 &hsv_shift, TextureClass::MipCountType mip_level_count = TextureClass::MIP_LEVELS_ALL); diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h index 1ab4599b87..6bc1242cf6 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDebugIcons.h @@ -33,7 +33,7 @@ #include "vertmaterial.h" #include "Lib/BaseType.h" -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL struct DebugIcon; // /// W3DDebugIcons: Draws huge numbers of debug icons for pathfinding quickly. @@ -76,6 +76,6 @@ class W3DDebugIcons : public RenderObjClass public: static void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color); }; -#endif // _DEBUG or _INTERNAL +#endif // RTS_DEBUG or RTS_INTERNAL #endif // end __W3D_DEBUG_ICONS_H_ diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h index a0df6bc1ce..132596da91 100644 --- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h +++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DDisplay.h @@ -71,7 +71,7 @@ class W3DDisplay : public Display virtual void getDisplayModeDescription(Int modeIndex, Int *xres, Int *yres, Int *bitDepth); ///removeShadow(this);} ///m_preloadReport) { @@ -127,7 +127,7 @@ AudioHandle MilesAudioManager::addAudioEvent( const AudioEventRTS *eventToAdd ) } #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------------------------------- void MilesAudioManager::audioDebugDisplay(DebugDisplayInterface *dd, void *, FILE *fp ) { @@ -446,7 +446,7 @@ void MilesAudioManager::init() AudioManager::init(); #ifdef INTENSE_DEBUG DEBUG_LOG(("Sound has temporarily been disabled in debug builds only. jkmcd\n")); - // for now, _DEBUG builds only should have no sound. ask jkmcd or srj about this. + // for now, RTS_DEBUG builds only should have no sound. ask jkmcd or srj about this. return; #endif @@ -467,7 +467,7 @@ void MilesAudioManager::postProcessLoad() //------------------------------------------------------------------------------------------------- void MilesAudioManager::reset() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) dumpAllAssetsUsed(); m_allEventsLoaded.clear(); #endif @@ -3064,7 +3064,7 @@ void AILCALLBACK setStreamCompleted( HSTREAM streamCompleted ) //------------------------------------------------------------------------------------------------- U32 AILCALLBACK streamingFileOpen(char const *fileName, U32 *file_handle) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (sizeof(U32) != sizeof(File*)) { RELEASE_CRASH(("streamingFileOpen - This function requires work in order to compile on non 32-bit platforms.\n")); } @@ -3324,7 +3324,7 @@ Bool AudioFileCache::freeEnoughSpaceForSample(const OpenAudioFile& sampleThatNee } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //------------------------------------------------------------------------------------------------- void MilesAudioManager::dumpAllAssetsUsed() { diff --git a/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdBIGFile.cpp b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdBIGFile.cpp new file mode 100644 index 0000000000..9515af78c1 --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdBIGFile.cpp @@ -0,0 +1,165 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +////// StdBIGFile.cpp ///////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////////// + +#include "Common/LocalFile.h" +#include "Common/LocalFileSystem.h" +#include "Common/RAMFile.h" +#include "Common/StreamingArchiveFile.h" +#include "Common/GameMemory.h" +#include "Common/PerfTimer.h" +#include "StdDevice/Common/StdBIGFile.h" + +//============================================================================ +// StdBIGFile::StdBIGFile +//============================================================================ + +StdBIGFile::StdBIGFile() +{ + +} + +//============================================================================ +// StdBIGFile::~StdBIGFile +//============================================================================ + +StdBIGFile::~StdBIGFile() +{ + +} + +//============================================================================ +// StdBIGFile::openFile +//============================================================================ + +File* StdBIGFile::openFile( const Char *filename, Int access ) +{ + const ArchivedFileInfo *fileInfo = getArchivedFileInfo(AsciiString(filename)); + + if (fileInfo == NULL) { + return NULL; + } + + RAMFile *ramFile = NULL; + + if (BitIsSet(access, File::STREAMING)) + ramFile = newInstance( StreamingArchiveFile ); + else + ramFile = newInstance( RAMFile ); + + ramFile->deleteOnClose(); + if (ramFile->openFromArchive(m_file, fileInfo->m_filename, fileInfo->m_offset, fileInfo->m_size) == FALSE) { + ramFile->close(); + ramFile = NULL; + return NULL; + } + + if ((access & File::WRITE) == 0) { + // requesting read only access. Just return the RAM file. + return ramFile; + } + + // whoever is opening this file wants write access, so copy the file to the local disk + // and return that file pointer. + + File *localFile = TheLocalFileSystem->openFile(filename, access); + if (localFile != NULL) { + ramFile->copyDataToFile(localFile); + } + + ramFile->close(); + ramFile = NULL; + + return localFile; +} + +//============================================================================ +// StdBIGFile::closeAllFiles +//============================================================================ + +void StdBIGFile::closeAllFiles( void ) +{ + +} + +//============================================================================ +// StdBIGFile::getName +//============================================================================ + +AsciiString StdBIGFile::getName( void ) +{ + return m_name; +} + +//============================================================================ +// StdBIGFile::getPath +//============================================================================ + +AsciiString StdBIGFile::getPath( void ) +{ + return m_path; +} + +//============================================================================ +// StdBIGFile::setSearchPriority +//============================================================================ + +void StdBIGFile::setSearchPriority( Int new_priority ) +{ + +} + +//============================================================================ +// StdBIGFile::close +//============================================================================ + +void StdBIGFile::close( void ) +{ + +} + +//============================================================================ +// StdBIGFile::getFileInfo +//============================================================================ + +Bool StdBIGFile::getFileInfo(const AsciiString& filename, FileInfo *fileInfo) const +{ + const ArchivedFileInfo *tempFileInfo = getArchivedFileInfo(filename); + + if (tempFileInfo == NULL) { + return FALSE; + } + + TheLocalFileSystem->getFileInfo(AsciiString(m_file->getName()), fileInfo); + + // fill in the size info. Since the size can't be bigger than a JUNK file, the high Int will always be 0. + fileInfo->sizeHigh = 0; + fileInfo->sizeLow = tempFileInfo->m_size; + + return TRUE; +} + diff --git a/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp new file mode 100644 index 0000000000..76a6ffb0df --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdBIGFileSystem.cpp @@ -0,0 +1,230 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +//////// StdBIGFileSystem.h /////////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////////////////// + +#include "Common/AudioAffect.h" +#include "Common/ArchiveFile.h" +#include "Common/ArchiveFileSystem.h" +#include "Common/File.h" +#include "Common/GameAudio.h" +#include "Common/GameMemory.h" +#include "Common/LocalFileSystem.h" +#include "StdDevice/Common/StdBIGFile.h" +#include "StdDevice/Common/StdBIGFileSystem.h" +#include "Common/Registry.h" +#include "Utility/endian_compat.h" + +static const char *BIGFileIdentifier = "BIGF"; + +StdBIGFileSystem::StdBIGFileSystem() : ArchiveFileSystem() { +} + +StdBIGFileSystem::~StdBIGFileSystem() { +} + +void StdBIGFileSystem::init() { + DEBUG_ASSERTCRASH(TheLocalFileSystem != NULL, ("TheLocalFileSystem must be initialized before TheArchiveFileSystem.")); + if (TheLocalFileSystem == NULL) { + return; + } + + loadBigFilesFromDirectory("", "*.big"); + + // load original Generals assets + AsciiString installPath; + GetStringFromGeneralsRegistry("", "InstallPath", installPath ); + //@todo this will need to be ramped up to a crash for release +#ifndef RTS_INTERNAL + // had to make this non-internal only, otherwise we can't autobuild + // GeneralsZH... + DEBUG_ASSERTCRASH(installPath != "", ("Be 1337! Go install Generals!")); +#endif + if (installPath!="") + loadBigFilesFromDirectory(installPath, "*.big"); +} + +void StdBIGFileSystem::reset() { +} + +void StdBIGFileSystem::update() { +} + +void StdBIGFileSystem::postProcessLoad() { +} + +ArchiveFile * StdBIGFileSystem::openArchiveFile(const Char *filename) { + File *fp = TheLocalFileSystem->openFile(filename, File::READ | File::BINARY); + AsciiString archiveFileName; + archiveFileName = filename; + archiveFileName.toLower(); + Int archiveFileSize = 0; + Int numLittleFiles = 0; + + ArchiveFile *archiveFile = NEW StdBIGFile; + + DEBUG_LOG(("StdBIGFileSystem::openArchiveFile - opening BIG file %s\n", filename)); + + if (fp == NULL) { + DEBUG_CRASH(("Could not open archive file %s for parsing", filename)); + return NULL; + } + + AsciiString asciibuf; + char buffer[_MAX_PATH]; + fp->read(buffer, 4); // read the "BIG" at the beginning of the file. + buffer[4] = 0; + if (strcmp(buffer, BIGFileIdentifier) != 0) { + DEBUG_CRASH(("Error reading BIG file identifier in file %s", filename)); + fp->close(); + fp = NULL; + return NULL; + } + + // read in the file size. + fp->read(&archiveFileSize, 4); + + DEBUG_LOG(("StdBIGFileSystem::openArchiveFile - size of archive file is %d bytes\n", archiveFileSize)); + +// char t; + + // read in the number of files contained in this BIG file. + // change the order of the bytes cause the file size is in reverse byte order for some reason. + fp->read(&numLittleFiles, 4); + numLittleFiles = betoh(numLittleFiles); + + DEBUG_LOG(("StdBIGFileSystem::openArchiveFile - %d are contained in archive\n", numLittleFiles)); +// for (Int i = 0; i < 2; ++i) { +// t = buffer[i]; +// buffer[i] = buffer[(4-i)-1]; +// buffer[(4-i)-1] = t; +// } + + // seek to the beginning of the directory listing. + fp->seek(0x10, File::START); + // read in each directory listing. + ArchivedFileInfo *fileInfo = NEW ArchivedFileInfo; + + for (Int i = 0; i < numLittleFiles; ++i) { + Int filesize = 0; + Int fileOffset = 0; + fp->read(&fileOffset, 4); + fp->read(&filesize, 4); + + filesize = betoh(filesize); + fileOffset = betoh(fileOffset); + + fileInfo->m_archiveFilename = archiveFileName; + fileInfo->m_offset = fileOffset; + fileInfo->m_size = filesize; + + // read in the path name of the file. + Int pathIndex = -1; + do { + ++pathIndex; + fp->read(buffer + pathIndex, 1); + } while (buffer[pathIndex] != 0); + + Int filenameIndex = pathIndex; + while ((filenameIndex >= 0) && (buffer[filenameIndex] != '\\') && (buffer[filenameIndex] != '/')) { + --filenameIndex; + } + + fileInfo->m_filename = (char *)(buffer + filenameIndex + 1); + fileInfo->m_filename.toLower(); + buffer[filenameIndex + 1] = 0; + + AsciiString path; + path = buffer; + + AsciiString debugpath; + debugpath = path; + debugpath.concat(fileInfo->m_filename); +// DEBUG_LOG(("StdBIGFileSystem::openArchiveFile - adding file %s to archive file %s, file number %d\n", debugpath.str(), fileInfo->m_archiveFilename.str(), i)); + + archiveFile->addFile(path, fileInfo); + } + + archiveFile->attachFile(fp); + + delete fileInfo; + fileInfo = NULL; + + // leave fp open as the archive file will be using it. + + return archiveFile; +} + +void StdBIGFileSystem::closeArchiveFile(const Char *filename) { + // Need to close the specified big file + ArchiveFileMap::iterator it = m_archiveFileMap.find(filename); + if (it == m_archiveFileMap.end()) { + return; + } + + if (stricmp(filename, MUSIC_BIG) == 0) { + // Stop the current audio + TheAudio->stopAudio(AudioAffect_Music); + + // No need to turn off other audio, as the lookups will just fail. + } + DEBUG_ASSERTCRASH(stricmp(filename, MUSIC_BIG) == 0, ("Attempting to close Archive file '%s', need to add code to handle its shutdown correctly.", filename)); + + // may need to do some other processing here first. + + delete (it->second); + m_archiveFileMap.erase(it); +} + +void StdBIGFileSystem::closeAllArchiveFiles() { +} + +void StdBIGFileSystem::closeAllFiles() { +} + +Bool StdBIGFileSystem::loadBigFilesFromDirectory(AsciiString dir, AsciiString fileMask, Bool overwrite) { + + FilenameList filenameList; + TheLocalFileSystem->getFileListInDirectory(dir, AsciiString(""), fileMask, filenameList, TRUE); + + Bool actuallyAdded = FALSE; + FilenameListIter it = filenameList.begin(); + while (it != filenameList.end()) { + ArchiveFile *archiveFile = openArchiveFile((*it).str()); + + if (archiveFile != NULL) { + DEBUG_LOG(("StdBIGFileSystem::loadBigFilesFromDirectory - loading %s into the directory tree.\n", (*it).str())); + loadIntoDirectoryTree(archiveFile, *it, overwrite); + m_archiveFileMap[(*it)] = archiveFile; + DEBUG_LOG(("StdBIGFileSystem::loadBigFilesFromDirectory - %s inserted into the archive file map.\n", (*it).str())); + actuallyAdded = TRUE; + } + + it++; + } + + return actuallyAdded; +} diff --git a/Generals/Code/Tools/Autorun/leanAndMeanAutorun.h b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdLocalFile.cpp similarity index 57% rename from Generals/Code/Tools/Autorun/leanAndMeanAutorun.h rename to GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdLocalFile.cpp index 94fc5fede6..70caa3430e 100644 --- a/Generals/Code/Tools/Autorun/leanAndMeanAutorun.h +++ b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdLocalFile.cpp @@ -1,5 +1,5 @@ /* -** Command & Conquer Generals(tm) +** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify @@ -16,16 +16,20 @@ ** along with this program. If not, see . */ -// FILE: leanAndMeanAutorun.h ///////////////////////////////////////////////////////////////////// -// Author: Mark Lorenzen, January 2003! -// Description: Classes extracted from GameEngine for use in autorun without having to link the game to autorun -/////////////////////////////////////////////////////////////////////////////////////////////////// -#pragma once +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// -#ifndef __LEANANDMEANAUTORUN_H_ -#define __LEANANDMEANAUTORUN_H_ +//////// StdLocalFile.cpp /////////////////////////// +// Stephan Vedder, April 2025 +/////////////////////////////////////////////////////// +#include "StdDevice/Common/StdLocalFile.h" -#define LEAN_AND_MEAN +StdLocalFile::StdLocalFile() : LocalFile() { +} -#endif //__LEANANDMEANAUTORUN_H_ \ No newline at end of file +StdLocalFile::~StdLocalFile() { +} diff --git a/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp new file mode 100644 index 0000000000..e3525d2c88 --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Source/StdDevice/Common/StdLocalFileSystem.cpp @@ -0,0 +1,341 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 Electronic Arts Inc. +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +///////// StdLocalFileSystem.cpp ///////////////////////// +// Stephan Vedder, April 2025 +//////////////////////////////////////////////////////////// + +#include "Common/AsciiString.h" +#include "Common/GameMemory.h" +#include "Common/PerfTimer.h" +#include "StdDevice/Common/StdLocalFileSystem.h" +#include "StdDevice/Common/StdLocalFile.h" + +#include + +StdLocalFileSystem::StdLocalFileSystem() : LocalFileSystem() +{ +} + +StdLocalFileSystem::~StdLocalFileSystem() { +} + +//DECLARE_PERF_TIMER(StdLocalFileSystem_openFile) +static std::filesystem::path fixFilenameFromWindowsPath(const Char *filename, Int access) +{ + std::string fixedFilename(filename); + +#ifndef _WIN32 + // Replace backslashes with forward slashes on unix + std::replace(fixedFilename.begin(), fixedFilename.end(), '\\', '/'); +#endif + + // Convert the filename to a std::filesystem::path and pass that + std::filesystem::path path(std::move(fixedFilename)); + +#ifndef _WIN32 + // check if the file exists to see if fixup is required + // if it's not found try to match disregarding case sensitivity + // For cases where a write is happening, we should check if the parent path exists, if so, let it through, since the file may not exist yet. + std::error_code ec; + if (!std::filesystem::exists(path, ec) && + ((!(access & File::WRITE)) || ((access & File::WRITE) && !std::filesystem::exists(path.parent_path(), ec)))) + { + // Traverse path to try and match case-insensitively + std::filesystem::path parent = path.parent_path(); + + std::filesystem::path pathFixed; + std::filesystem::path pathCurrent; + for (auto& p : path) + { + std::filesystem::path pathFixedPart; + if (pathCurrent.empty()) + { + // Load the first part of the path + pathFixed /= p; + pathCurrent /= p; + continue; + } + + if (std::filesystem::exists(pathCurrent / p, ec)) + { + pathFixedPart = p; + } + else if (std::filesystem::exists(pathFixed / p, ec)) + { + pathFixedPart = p; + } + else + { + // Check if the subpath exists using case-insensitive comparison + for (auto& entry : std::filesystem::directory_iterator(pathFixed, ec)) + { + if (strcasecmp(entry.path().filename().string().c_str(), p.string().c_str()) == 0) + { + pathFixedPart = entry.path().filename(); + break; + } + } + } + + if (pathFixedPart.empty()) + { + // Required to allow creation of new files + if (!(access & File::WRITE)) + { + DEBUG_LOG(("StdLocalFileSystem::fixFilenameFromWindowsPath - Error finding file %s\n", filename.string().c_str())); + DEBUG_LOG(("StdLocalFileSystem::fixFilenameFromWindowsPath - Got so far %s\n", pathCurrent.string().c_str())); + + return std::filesystem::path(); + } + + // Use the last known good path + pathFixed = p; + } + + // Copy of the current path to mirror the current depth + pathFixed /= pathFixedPart; + pathCurrent /= p; + } + path = pathFixed; + } +#endif + + return path; +} + +File * StdLocalFileSystem::openFile(const Char *filename, Int access /* = 0 */) +{ + //USE_PERF_TIMER(StdLocalFileSystem_openFile) + + // sanity check + if (strlen(filename) <= 0) { + return NULL; + } + + std::filesystem::path path = fixFilenameFromWindowsPath(filename, access); + + if (path.empty()) { + return NULL; + } + + if (access & File::WRITE) { + // if opening the file for writing, we need to make sure the directory is there + // before we try to create the file. + std::filesystem::path dir = path.parent_path(); + std::error_code ec; + if (!std::filesystem::exists(dir, ec) || ec) { + if(!std::filesystem::create_directories(dir, ec) || ec) { + DEBUG_LOG(("StdLocalFileSystem::openFile - Error creating directory %s\n", dir.string().c_str())); + return NULL; + } + } + } + + StdLocalFile *file = newInstance( StdLocalFile ); + + if (file->open(path.string().c_str(), access) == FALSE) { + file->close(); + file->deleteInstance(); + file = NULL; + } else { + file->deleteOnClose(); + } + +// this will also need to play nice with the STREAMING type that I added, if we ever enable this + +// srj sez: this speeds up INI loading, but makes BIG files unusable. +// don't enable it without further tweaking. +// +// unless you like running really slowly. +// if (!(access&File::WRITE)) { +// // Return a ramfile. +// RAMFile *ramFile = newInstance( RAMFile ); +// if (ramFile->open(file)) { +// file->close(); // is deleteonclose, so should delete. +// ramFile->deleteOnClose(); +// return ramFile; +// } else { +// ramFile->close(); +// ramFile->deleteInstance(); +// } +// } + + return file; +} + +void StdLocalFileSystem::update() +{ +} + +void StdLocalFileSystem::init() +{ +} + +void StdLocalFileSystem::reset() +{ +} + +//DECLARE_PERF_TIMER(StdLocalFileSystem_doesFileExist) +Bool StdLocalFileSystem::doesFileExist(const Char *filename) const +{ + std::filesystem::path path = fixFilenameFromWindowsPath(filename, 0); + if(path.empty()) { + return FALSE; + } + + std::error_code ec; + return std::filesystem::exists(path, ec); +} + +void StdLocalFileSystem::getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList & filenameList, Bool searchSubdirectories) const +{ + + char search[_MAX_PATH]; + AsciiString asciisearch; + asciisearch = originalDirectory; + asciisearch.concat(currentDirectory); + auto searchExt = std::filesystem::path(searchName.str()).extension(); + if (asciisearch.isEmpty()) { + asciisearch = "."; + } + + std::string fixedDirectory(asciisearch.str()); + +#ifndef _WIN32 + // Replace backslashes with forward slashes on unix + std::replace(fixedDirectory.begin(), fixedDirectory.end(), '\\', '/'); +#endif + + strcpy(search, fixedDirectory.c_str()); + + Bool done = FALSE; + std::error_code ec; + + auto iter = std::filesystem::directory_iterator(search, ec); + // The default iterator constructor creates an end iterator + done = iter == std::filesystem::directory_iterator(); + + if (ec) { + DEBUG_LOG(("StdLocalFileSystem::getFileListInDirectory - Error opening directory %s\n", search)); + return; + } + + while (!done) { + std::string filenameStr = iter->path().filename().string(); + if (!iter->is_directory() && iter->path().extension() == searchExt && + (strcmp(filenameStr.c_str(), ".") && strcmp(filenameStr.c_str(), ".."))) { + // if we haven't already, add this filename to the list. + // a stl set should only allow one copy of each filename + AsciiString newFilename = iter->path().string().c_str(); + if (filenameList.find(newFilename) == filenameList.end()) { + filenameList.insert(newFilename); + } + } + + iter++; + done = iter == std::filesystem::directory_iterator(); + } + + if (searchSubdirectories) { + auto iter = std::filesystem::directory_iterator(fixedDirectory, ec); + + if (ec) { + DEBUG_LOG(("StdLocalFileSystem::getFileListInDirectory - Error opening subdirectory %s\n", fixedDirectory)); + return; + } + + // The default iterator constructor creates an end iterator + done = iter == std::filesystem::directory_iterator(); + + while (!done) { + std::string filenameStr = iter->path().filename().string(); + if(iter->is_directory() && + (strcmp(filenameStr.c_str(), ".") && strcmp(filenameStr.c_str(), ".."))) { + AsciiString tempsearchstr(filenameStr.c_str()); + + // recursively add files in subdirectories if required. + getFileListInDirectory(tempsearchstr, originalDirectory, searchName, filenameList, searchSubdirectories); + } + + iter++; + done = iter == std::filesystem::directory_iterator(); + } + } +} + +Bool StdLocalFileSystem::getFileInfo(const AsciiString& filename, FileInfo *fileInfo) const +{ + std::filesystem::path path = fixFilenameFromWindowsPath(filename.str(), 0); + + if(path.empty()) { + return FALSE; + } + + std::error_code ec; + auto file_size = std::filesystem::file_size(path, ec); + if (ec) + { + return FALSE; + } + + auto write_time = std::filesystem::last_write_time(path, ec); + if (ec) + { + return FALSE; + } + + // TODO: fix this to be win compatible (time since 1601) + auto time = write_time.time_since_epoch().count(); + fileInfo->timestampHigh = time >> 32; + fileInfo->timestampLow = time & UINT32_MAX; + fileInfo->sizeHigh = file_size >> 32; + fileInfo->sizeLow = file_size & UINT32_MAX; + + return TRUE; +} + +Bool StdLocalFileSystem::createDirectory(AsciiString directory) +{ + bool result = FALSE; + + std::string fixedDirectory(directory.str()); + +#ifndef _WIN32 + // Replace backslashes with forward slashes on unix + std::replace(fixedDirectory.begin(), fixedDirectory.end(), '\\', '/'); +#endif + + if ((fixedDirectory.length() > 0) && (fixedDirectory.length() < _MAX_DIR)) { + // Convert to host path + std::filesystem::path path(std::move(fixedDirectory)); + + std::error_code ec; + result = std::filesystem::create_directory(path, ec); + if (ec) { + result = FALSE; + } + } + return result; +} diff --git a/GeneralsMD/Code/GameEngineDevice/Source/VideoDevice/FFmpeg/FFmpegFile.cpp b/GeneralsMD/Code/GameEngineDevice/Source/VideoDevice/FFmpeg/FFmpegFile.cpp new file mode 100644 index 0000000000..e3033dc7b6 --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Source/VideoDevice/FFmpeg/FFmpegFile.cpp @@ -0,0 +1,373 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +//////// FFmpegFile.cpp /////////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////// + +#include "VideoDevice/FFmpeg/FFmpegFile.h" +#include "Common/File.h" + +extern "C" { +#include +#include +} + + +FFmpegFile::FFmpegFile() {} + +FFmpegFile::FFmpegFile(File *file) +{ + open(file); +} + +FFmpegFile::~FFmpegFile() +{ + close(); +} + +Bool FFmpegFile::open(File *file) +{ + DEBUG_ASSERTCRASH(m_file == nullptr, ("already open")); + DEBUG_ASSERTCRASH(file != nullptr, ("null file pointer")); +#if LOGGING_LEVEL != LOGLEVEL_NONE + av_log_set_level(AV_LOG_INFO); +#endif + +// This is required for FFmpeg older than 4.0 -> deprecated afterwards though +#if LIBAVFORMAT_VERSION_MAJOR < 58 + av_register_all(); +#endif + + m_file = file; + + // FFmpeg setup + m_fmtCtx = avformat_alloc_context(); + if (!m_fmtCtx) { + DEBUG_LOG(("Failed to alloc AVFormatContext")); + close(); + return false; + } + + constexpr size_t avio_ctx_buffer_size = 0x10000; + uint8_t *buffer = static_cast(av_malloc(avio_ctx_buffer_size)); + if (buffer == nullptr) { + DEBUG_LOG(("Failed to alloc AVIOContextBuffer")); + close(); + return false; + } + + m_avioCtx = avio_alloc_context(buffer, avio_ctx_buffer_size, 0, file, &readPacket, nullptr, nullptr); + if (m_avioCtx == nullptr) { + DEBUG_LOG(("Failed to alloc AVIOContext")); + close(); + return false; + } + + m_fmtCtx->pb = m_avioCtx; + m_fmtCtx->flags |= AVFMT_FLAG_CUSTOM_IO; + + int result = avformat_open_input(&m_fmtCtx, nullptr, nullptr, nullptr); + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'avformat_open_input': %s", error_buffer)); + close(); + return false; + } + + result = avformat_find_stream_info(m_fmtCtx, nullptr); + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'avformat_find_stream_info': %s", error_buffer)); + close(); + return false; + } + + m_streams.resize(m_fmtCtx->nb_streams); + for (unsigned int stream_idx = 0; stream_idx < m_fmtCtx->nb_streams; stream_idx++) { + AVStream *av_stream = m_fmtCtx->streams[stream_idx]; + const AVCodec *input_codec = avcodec_find_decoder(av_stream->codecpar->codec_id); + if (input_codec == nullptr) { + DEBUG_LOG(("Codec not supported: '%s'", avcodec_get_name(av_stream->codecpar->codec_id))); + close(); + return false; + } + + AVCodecContext *codec_ctx = avcodec_alloc_context3(input_codec); + if (codec_ctx == nullptr) { + DEBUG_LOG(("Could not allocate codec context")); + close(); + return false; + } + + result = avcodec_parameters_to_context(codec_ctx, av_stream->codecpar); + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'avcodec_parameters_to_context': %s", error_buffer)); + close(); + return false; + } + + result = avcodec_open2(codec_ctx, input_codec, nullptr); + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'avcodec_open2': %s", error_buffer)); + close(); + return false; + } + + FFmpegStream &output_stream = m_streams[stream_idx]; + output_stream.codec_ctx = codec_ctx; + output_stream.codec = input_codec; + output_stream.stream_type = input_codec->type; + output_stream.stream_idx = stream_idx; + output_stream.frame = av_frame_alloc(); + } + + m_packet = av_packet_alloc(); + + return true; +} + +/** + * Read an FFmpeg packet from file + */ +int FFmpegFile::readPacket(void *opaque, uint8_t *buf, int buf_size) +{ + File *file = static_cast(opaque); + const int read = file->read(buf, buf_size); + + // Streaming protocol requires us to return real errors - when we read less equal 0 we're at EOF + if (read <= 0) + return AVERROR_EOF; + + return read; +} + +/** + * close all the open FFmpeg handles for an open file. + */ +void FFmpegFile::close() +{ + if (m_fmtCtx != nullptr) { + avformat_close_input(&m_fmtCtx); + } + + for (auto &stream : m_streams) { + if (stream.codec_ctx != nullptr) { + avcodec_free_context(&stream.codec_ctx); + av_frame_free(&stream.frame); + } + } + m_streams.clear(); + + if (m_avioCtx != nullptr) { + av_freep(&m_avioCtx->buffer); + avio_context_free(&m_avioCtx); + } + + if (m_packet != nullptr) { + av_packet_free(&m_packet); + } + + if (m_file != nullptr) { + m_file->close(); + m_file = nullptr; + } +} + +Bool FFmpegFile::decodePacket() +{ + DEBUG_ASSERTCRASH(m_fmtCtx != nullptr, ("null format context")); + DEBUG_ASSERTCRASH(m_packet != nullptr, ("null packet pointer")); + + int result = av_read_frame(m_fmtCtx, m_packet); + if (result == AVERROR_EOF) + return false; + + const int stream_idx = m_packet->stream_index; + DEBUG_ASSERTCRASH(m_streams.size() > stream_idx, ("stream index out of bounds")); + + auto &stream = m_streams[stream_idx]; + AVCodecContext *codec_ctx = stream.codec_ctx; + result = avcodec_send_packet(codec_ctx, m_packet); + // Check if we need more data + if (result == AVERROR(EAGAIN)) + return true; + + // Handle any other errors + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'avcodec_send_packet': %s", error_buffer)); + return false; + } + av_packet_unref(m_packet); + + // Get all frames in this packet + while (result >= 0) { + result = avcodec_receive_frame(codec_ctx, stream.frame); + + // Check if we need more data + if (result == AVERROR(EAGAIN)) + return true; + + // Handle any other errors + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'avcodec_receive_frame': %s", error_buffer)); + return false; + } + + if (m_frameCallback != nullptr) { + m_frameCallback(stream.frame, stream_idx, stream.stream_type, m_userData); + } + } + + return true; +} + +void FFmpegFile::seekFrame(int frame_idx) +{ + // Note: not tested, since not used ingame + for (const auto &stream : m_streams) { + Int64 timestamp = av_q2d(m_fmtCtx->streams[stream.stream_idx]->time_base) * frame_idx + * av_q2d(m_fmtCtx->streams[stream.stream_idx]->avg_frame_rate); + int result = av_seek_frame(m_fmtCtx, stream.stream_idx, timestamp, AVSEEK_FLAG_ANY); + if (result < 0) { + char error_buffer[1024]; + av_strerror(result, error_buffer, sizeof(error_buffer)); + DEBUG_LOG(("Failed 'av_seek_frame': %s", error_buffer)); + } + } +} + +Bool FFmpegFile::hasAudio() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_AUDIO); + return stream != nullptr; +} + +const FFmpegFile::FFmpegStream *FFmpegFile::findMatch(Int type) const +{ + for (auto &stream : m_streams) { + if (stream.stream_type == type) + return &stream; + } + + return nullptr; +} + +Int FFmpegFile::getNumChannels() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_AUDIO); + if (stream == nullptr) + return 0; + + return stream->codec_ctx->ch_layout.nb_channels; +} + +Int FFmpegFile::getSampleRate() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_AUDIO); + if (stream == nullptr) + return 0; + + return stream->codec_ctx->sample_rate; +} + +Int FFmpegFile::getBytesPerSample() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_AUDIO); + if (stream == nullptr) + return 0; + + return av_get_bytes_per_sample(stream->codec_ctx->sample_fmt); +} + +Int FFmpegFile::getSizeForSamples(Int numSamples) const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_AUDIO); + if (stream == nullptr) + return 0; + + return av_samples_get_buffer_size(nullptr, stream->codec_ctx->ch_layout.nb_channels, numSamples, stream->codec_ctx->sample_fmt, 1); +} + +Int FFmpegFile::getHeight() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_VIDEO); + if (stream == nullptr) + return 0; + + return stream->codec_ctx->height; +} + +Int FFmpegFile::getWidth() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_VIDEO); + if (stream == nullptr) + return 0; + + return stream->codec_ctx->width; +} + +Int FFmpegFile::getNumFrames() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_VIDEO); + if (m_fmtCtx == nullptr || stream == nullptr || m_fmtCtx->streams[stream->stream_idx] == nullptr) + return 0; + + return (m_fmtCtx->duration / (double)AV_TIME_BASE) * av_q2d(m_fmtCtx->streams[stream->stream_idx]->avg_frame_rate); +} + +Int FFmpegFile::getCurrentFrame() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_VIDEO); + if (stream == nullptr) + return 0; + return stream->codec_ctx->frame_num; +} + +Int FFmpegFile::getPixelFormat() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_VIDEO); + if (stream == nullptr) + return AV_PIX_FMT_NONE; + + return stream->codec_ctx->pix_fmt; +} + +UnsignedInt FFmpegFile::getFrameTime() const +{ + const FFmpegStream *stream = findMatch(AVMEDIA_TYPE_VIDEO); + if (stream == nullptr) + return 0u; + return 1000u / av_q2d(m_fmtCtx->streams[stream->stream_idx]->avg_frame_rate); +} \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Source/VideoDevice/FFmpeg/FFmpegVideoPlayer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/VideoDevice/FFmpeg/FFmpegVideoPlayer.cpp new file mode 100644 index 0000000000..345ce39d73 --- /dev/null +++ b/GeneralsMD/Code/GameEngineDevice/Source/VideoDevice/FFmpeg/FFmpegVideoPlayer.cpp @@ -0,0 +1,547 @@ +/* +** Command & Conquer Generals Zero Hour(tm) +** Copyright 2025 TheSuperHackers +** +** This program 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. +** +** This program 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 this program. If not, see . +*/ + +//////////////////////////////////////////////////////////////////////////////// +// // +// (c) 2001-2003 Electronic Arts Inc. // +// // +//////////////////////////////////////////////////////////////////////////////// + +//////// FFmpegVideoPlayer.cpp /////////////////////////// +// Stephan Vedder, April 2025 +///////////////////////////////////////////////// + +//---------------------------------------------------------------------------- +// Includes +//---------------------------------------------------------------------------- + +#include "Lib/BaseType.h" +#include "VideoDevice/FFmpeg/FFmpegVideoPlayer.h" +#include "Common/AudioAffect.h" +#include "Common/GameAudio.h" +#include "Common/GameMemory.h" +#include "Common/GlobalData.h" +#include "Common/Registry.h" +#include "Common/FileSystem.h" + +#include "VideoDevice/FFmpeg/FFmpegFile.h" + +extern "C" { + #include + #include +} + +#ifdef RTS_HAS_OPENAL +#include "OpenALAudioDevice/OpenALAudioManager.h" +#include "OpenALAudioDevice/OpenALAudioStream.h" +#endif + +#include + +//---------------------------------------------------------------------------- +// Externals +//---------------------------------------------------------------------------- + + + +//---------------------------------------------------------------------------- +// Defines +//---------------------------------------------------------------------------- +#define VIDEO_LANG_PATH_FORMAT "Data/%s/Movies/%s.%s" +#define VIDEO_PATH "Data\\Movies" +#define VIDEO_EXT "bik" + + + +//---------------------------------------------------------------------------- +// Private Types +//---------------------------------------------------------------------------- + + + +//---------------------------------------------------------------------------- +// Private Data +//---------------------------------------------------------------------------- + + + +//---------------------------------------------------------------------------- +// Public Data +//---------------------------------------------------------------------------- + + + +//---------------------------------------------------------------------------- +// Private Prototypes +//---------------------------------------------------------------------------- + + + +//---------------------------------------------------------------------------- +// Private Functions +//---------------------------------------------------------------------------- + + + +//---------------------------------------------------------------------------- +// Public Functions +//---------------------------------------------------------------------------- + + +//============================================================================ +// FFmpegVideoPlayer::FFmpegVideoPlayer +//============================================================================ + +FFmpegVideoPlayer::FFmpegVideoPlayer() +{ + +} + +//============================================================================ +// FFmpegVideoPlayer::~FFmpegVideoPlayer +//============================================================================ + +FFmpegVideoPlayer::~FFmpegVideoPlayer() +{ + deinit(); +} + +//============================================================================ +// FFmpegVideoPlayer::init +//============================================================================ + +void FFmpegVideoPlayer::init( void ) +{ + // Need to load the stuff from the ini file. + VideoPlayer::init(); + + initializeBinkWithMiles(); +} + +//============================================================================ +// FFmpegVideoPlayer::deinit +//============================================================================ + +void FFmpegVideoPlayer::deinit( void ) +{ + TheAudio->releaseHandleForBink(); + VideoPlayer::deinit(); +} + +//============================================================================ +// FFmpegVideoPlayer::reset +//============================================================================ + +void FFmpegVideoPlayer::reset( void ) +{ + VideoPlayer::reset(); +} + +//============================================================================ +// FFmpegVideoPlayer::update +//============================================================================ + +void FFmpegVideoPlayer::update( void ) +{ + VideoPlayer::update(); + +} + +//============================================================================ +// FFmpegVideoPlayer::loseFocus +//============================================================================ + +void FFmpegVideoPlayer::loseFocus( void ) +{ + VideoPlayer::loseFocus(); +} + +//============================================================================ +// FFmpegVideoPlayer::regainFocus +//============================================================================ + +void FFmpegVideoPlayer::regainFocus( void ) +{ + VideoPlayer::regainFocus(); +} + +//============================================================================ +// FFmpegVideoPlayer::createStream +//============================================================================ + +VideoStreamInterface* FFmpegVideoPlayer::createStream( File* file ) +{ + + if ( file == nullptr ) + { + return nullptr; + } + + FFmpegFile* ffmpegHandle = NEW FFmpegFile(); + if(!ffmpegHandle->open(file)) + { + delete ffmpegHandle; + return nullptr; + } + + FFmpegVideoStream *stream = NEW FFmpegVideoStream(ffmpegHandle); + + if ( stream ) + { + + stream->m_next = m_firstStream; + stream->m_player = this; + m_firstStream = stream; + + // never let volume go to 0, as Bink will interpret that as "play at full volume". + Int mod = (Int) ((TheAudio->getVolume(AudioAffect_Speech) * 0.8f) * 100) + 1; + [[maybe_unused]] Int volume = (32768 * mod) / 100; + DEBUG_LOG(("FFmpegVideoPlayer::createStream() - About to set volume (%g -> %d -> %d\n", + TheAudio->getVolume(AudioAffect_Speech), mod, volume)); + //BinkSetVolume( stream->m_handle,0, volume); + DEBUG_LOG(("FFmpegVideoPlayer::createStream() - set volume\n")); + } + + return stream; +} + +//============================================================================ +// FFmpegVideoPlayer::open +//============================================================================ + +VideoStreamInterface* FFmpegVideoPlayer::open( AsciiString movieTitle ) +{ + VideoStreamInterface* stream = nullptr; + + const Video* pVideo = getVideo(movieTitle); + if (pVideo) { + DEBUG_LOG(("FFmpegVideoPlayer::createStream() - About to open bink file\n")); + + if (TheGlobalData->m_modDir.isNotEmpty()) + { + char filePath[ _MAX_PATH ]; + sprintf( filePath, "%s%s\\%s.%s", TheGlobalData->m_modDir.str(), VIDEO_PATH, pVideo->m_filename.str(), VIDEO_EXT ); + File* file = TheFileSystem->openFile(filePath); + DEBUG_ASSERTLOG(!file, ("opened bink file %s\n", filePath)); + if (file) + { + return createStream( file ); + } + } + + char localizedFilePath[ _MAX_PATH ]; + sprintf( localizedFilePath, VIDEO_LANG_PATH_FORMAT, GetRegistryLanguage().str(), pVideo->m_filename.str(), VIDEO_EXT ); + File* file = TheFileSystem->openFile(localizedFilePath); + DEBUG_ASSERTLOG(!file, ("opened localized bink file %s\n", localizedFilePath)); + if (!file) + { + char filePath[ _MAX_PATH ]; + sprintf( filePath, "%s\\%s.%s", VIDEO_PATH, pVideo->m_filename.str(), VIDEO_EXT ); + file = TheFileSystem->openFile(filePath); + DEBUG_ASSERTLOG(!file, ("opened bink file %s\n", filePath)); + } + + DEBUG_LOG(("FFmpegVideoPlayer::createStream() - About to create stream\n")); + stream = createStream( file ); + } + + return stream; +} + +//============================================================================ +// FFmpegVideoPlayer::load +//============================================================================ + +VideoStreamInterface* FFmpegVideoPlayer::load( AsciiString movieTitle ) +{ + return open(movieTitle); // load() used to have the same body as open(), so I'm combining them. Munkee. +} + +//============================================================================ +//============================================================================ +void FFmpegVideoPlayer::notifyVideoPlayerOfNewProvider( Bool nowHasValid ) +{ + if (!nowHasValid) { + TheAudio->releaseHandleForBink(); + //BinkSetSoundTrack(0, 0); + } else { + initializeBinkWithMiles(); + } +} + +//============================================================================ +//============================================================================ +void FFmpegVideoPlayer::initializeBinkWithMiles() +{ + Int retVal = 0; + void *driver = TheAudio->getHandleForBink(); + + if ( driver ) + { + //retVal = BinkSoundUseDirectSound(driver); + } + if( !driver || retVal == 0) + { + //BinkSetSoundTrack ( 0,0 ); + } +} + +//============================================================================ +// FFmpegVideoStream::FFmpegVideoStream +//============================================================================ + +FFmpegVideoStream::FFmpegVideoStream(FFmpegFile* file) +: m_ffmpegFile(file) +{ + m_ffmpegFile->setFrameCallback(onFrame); + m_ffmpegFile->setUserData(this); + +#ifdef RTS_USE_OPENAL + // Release the audio handle if it's already in use + OpenALAudioStream* audioStream = (OpenALAudioStream*)TheAudio->getHandleForBink(); + audioStream->reset(); +#endif + + // Decode until we have our first video frame + while (m_good && m_gotFrame == false) + m_good = m_ffmpegFile->decodePacket(); + + #ifdef RTS_USE_OPENAL + // Start audio playback + audioStream->play(); +#endif + + m_startTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} + +//============================================================================ +// FFmpegVideoStream::~FFmpegVideoStream +//============================================================================ + +FFmpegVideoStream::~FFmpegVideoStream() +{ + av_freep(&m_audioBuffer); + av_frame_free(&m_frame); + sws_freeContext(m_swsContext); + delete m_ffmpegFile; +} + +void FFmpegVideoStream::onFrame(AVFrame *frame, int stream_idx, int stream_type, void *user_data) +{ + FFmpegVideoStream *videoStream = static_cast(user_data); + if (stream_type == AVMEDIA_TYPE_VIDEO) { + av_frame_free(&videoStream->m_frame); + videoStream->m_frame = av_frame_clone(frame); + videoStream->m_gotFrame = true; + } +#ifdef RTS_USE_OPENAL + else if (stream_type == AVMEDIA_TYPE_AUDIO) { + OpenALAudioStream* audioStream = (OpenALAudioStream*)TheAudio->getHandleForBink(); + audioStream->update(); + AVSampleFormat sampleFmt = static_cast(frame->format); + const int bytesPerSample = av_get_bytes_per_sample(sampleFmt); + const int frameSize = av_samples_get_buffer_size(nullptr, frame->ch_layout.nb_channels, frame->nb_samples, sampleFmt, 1); + uint8_t* frameData = frame->data[0]; + // The format is planar - convert it to interleaved + if (av_sample_fmt_is_planar(sampleFmt)) + { + videoStream->m_audioBuffer = static_cast(av_realloc(videoStream->m_audioBuffer, frameSize)); + if (videoStream->m_audioBuffer == nullptr) + { + DEBUG_LOG(("Failed to allocate audio buffer")); + return; + } + + // Write the samples into our audio buffer + for (int sample_idx = 0; sample_idx < frame->nb_samples; sample_idx++) + { + int byte_offset = sample_idx * bytesPerSample; + for (int channel_idx = 0; channel_idx < frame->ch_layout.nb_channels; channel_idx++) + { + uint8_t* dst = &videoStream->m_audioBuffer[byte_offset * frame->ch_layout.nb_channels + channel_idx * bytesPerSample]; + uint8_t* src = &frame->data[channel_idx][byte_offset]; + memcpy(dst, src, bytesPerSample); + } + } + frameData = videoStream->m_audioBuffer; + } + + ALenum format = OpenALAudioManager::getALFormat(frame->ch_layout.nb_channels, bytesPerSample * 8); + audioStream->bufferData(frameData, frameSize, format, frame->sample_rate); + } +#endif +} + + +//============================================================================ +// FFmpegVideoStream::update +//============================================================================ + +void FFmpegVideoStream::update( void ) +{ +#ifdef RTS_USE_OPENAL + // Start audio playback + OpenALAudioStream* audioStream = (OpenALAudioStream*)TheAudio->getHandleForBink(); + audioStream->play(); +#endif + //BinkWait( m_handle ); +} + +//============================================================================ +// FFmpegVideoStream::isFrameReady +//============================================================================ + +Bool FFmpegVideoStream::isFrameReady( void ) +{ + uint64_t time = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + bool ready = (time - m_startTime) >= m_ffmpegFile->getFrameTime() * frameIndex(); + return ready; + + //return !BinkWait( m_handle ); +} + +//============================================================================ +// FFmpegVideoStream::frameDecompress +//============================================================================ + +void FFmpegVideoStream::frameDecompress( void ) +{ + //BinkDoFrame( m_handle ); +} + +//============================================================================ +// FFmpegVideoStream::frameRender +//============================================================================ + +void FFmpegVideoStream::frameRender( VideoBuffer *buffer ) +{ + if (buffer == nullptr) { + return; + } + + if (m_frame == nullptr) { + return; + } + + if (m_frame->data == nullptr) { + return; + } + + AVPixelFormat dst_pix_fmt; + + switch (buffer->format()) { + case VideoBuffer::TYPE_R8G8B8: + dst_pix_fmt = AV_PIX_FMT_RGB24; + break; + case VideoBuffer::TYPE_X8R8G8B8: + dst_pix_fmt = AV_PIX_FMT_BGR0; + break; + case VideoBuffer::TYPE_R5G6B5: + dst_pix_fmt = AV_PIX_FMT_RGB565; + break; + case VideoBuffer::TYPE_X1R5G5B5: + dst_pix_fmt = AV_PIX_FMT_RGB555; + break; + default: + return; + } + + m_swsContext = sws_getCachedContext(m_swsContext, + width(), + height(), + static_cast(m_frame->format), + buffer->width(), + buffer->height(), + dst_pix_fmt, + SWS_BICUBIC, + nullptr, + nullptr, + nullptr); + + uint8_t *buffer_data = static_cast(buffer->lock()); + if (buffer_data == nullptr) { + DEBUG_LOG(("Failed to lock videobuffer")); + return; + } + + int dst_strides[] = { (int)buffer->pitch() }; + uint8_t *dst_data[] = { buffer_data }; + [[maybe_unused]] int result = + sws_scale(m_swsContext, m_frame->data, m_frame->linesize, 0, height(), dst_data, dst_strides); + DEBUG_ASSERTLOG(result >= 0, ("Failed to scale frame")); + buffer->unlock(); +} + +//============================================================================ +// FFmpegVideoStream::frameNext +//============================================================================ + +void FFmpegVideoStream::frameNext( void ) +{ + m_gotFrame = false; + // Decode until we have our next video frame + while (m_good && m_gotFrame == false) + m_good = m_ffmpegFile->decodePacket(); +} + +//============================================================================ +// FFmpegVideoStream::frameIndex +//============================================================================ + +Int FFmpegVideoStream::frameIndex( void ) +{ + return m_ffmpegFile->getCurrentFrame(); +} + +//============================================================================ +// FFmpegVideoStream::totalFrames +//============================================================================ + +Int FFmpegVideoStream::frameCount( void ) +{ + return m_ffmpegFile->getNumFrames(); +} + +//============================================================================ +// FFmpegVideoStream::frameGoto +//============================================================================ + +void FFmpegVideoStream::frameGoto( Int index ) +{ + m_ffmpegFile->seekFrame(index); +} + +//============================================================================ +// VideoStream::height +//============================================================================ + +Int FFmpegVideoStream::height( void ) +{ + return m_ffmpegFile->getHeight(); +} + +//============================================================================ +// VideoStream::width +//============================================================================ + +Int FFmpegVideoStream::width( void ) +{ + return m_ffmpegFile->getWidth(); +} + + diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp index 51ba67de2e..0224d2210a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/Common/System/W3DRadar.cpp @@ -53,7 +53,7 @@ #include "WW3D2/texture.h" #include "WW3D2/dx8caps.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1255,7 +1255,7 @@ void W3DRadar::buildTerrainTexture( TerrainLogic *terrain ) //------------------------------------------------------------------------------------------------- void W3DRadar::clearShroud() { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_shroudOn) return; #endif @@ -1275,7 +1275,7 @@ void W3DRadar::clearShroud() //------------------------------------------------------------------------------------------------- void W3DRadar::setShroudLevel(Int shroudX, Int shroudY, CellShroudStatus setting) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_shroudOn) return; #endif @@ -1412,7 +1412,7 @@ void W3DRadar::draw( Int pixelX, Int pixelY, Int width, Int height ) TheDisplay->drawImage( m_overlayImage, ul.x, ul.y, lr.x, lr.y ); // draw the shroud image -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_shroudOn ) #else if (true) diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp index dfa2d339bd..ba8add5ebb 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp @@ -97,7 +97,7 @@ #include "W3DDevice/GameClient/W3DSmudge.h" #include "W3DDevice/GameClient/W3DSnow.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -313,7 +313,7 @@ BaseHeightMapRenderObjClass::BaseHeightMapRenderObjClass(void) m_scorchTexture = NULL; clearAllScorches(); #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) m_shroud = NEW W3DShroud; else @@ -1896,7 +1896,7 @@ void BaseHeightMapRenderObjClass::allocateScorchBuffers(void) m_scorchesInBuffer = 0; // If we just allocated the buffers, we got no scorches in the buffer. m_curNumScorchVertices=0; m_curNumScorchIndices=0; -#ifdef _DEBUG +#ifdef RTS_DEBUG Vector3 loc(4*MAP_XY_FACTOR,4*MAP_XY_FACTOR,0); addScorch(loc, 1*MAP_XY_FACTOR, SCORCH_1); loc.Y += 10*MAP_XY_FACTOR; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp index 1b9f4fe947..1eb1a59e42 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDependencyModelDraw.cpp @@ -40,7 +40,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp index 7306011ab8..12beb5569a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DLaserDraw.cpp @@ -31,6 +31,7 @@ // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// #include +#include "Common/GlobalData.h" #include "Common/Thing.h" #include "Common/ThingTemplate.h" #include "Common/Xfer.h" @@ -52,7 +53,7 @@ #include "WW3D2/assetmgr.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -75,6 +76,10 @@ W3DLaserDrawModuleData::W3DLaserDrawModuleData() m_arcHeight = 0.0f; m_segmentOverlapRatio = 0.0f; m_tilingScalar = 1.0f; + m_gridColumnsTotal = 1; + m_gridColumns = 1; + m_useHouseColorOuter = FALSE; + m_useHouseColorInner = FALSE; } //------------------------------------------------------------------------------------------------- @@ -105,6 +110,10 @@ void W3DLaserDrawModuleData::buildFieldParse(MultiIniFieldParse& p) { "ArcHeight", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_arcHeight ) }, { "SegmentOverlapRatio", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_segmentOverlapRatio ) }, { "TilingScalar", INI::parseReal, NULL, offsetof( W3DLaserDrawModuleData, m_tilingScalar ) }, + { "TextureGridTotalColumns", INI::parseUnsignedInt, NULL, offsetof(W3DLaserDrawModuleData, m_gridColumnsTotal) }, + { "TextureGridColumns", INI::parseUnsignedInt, NULL, offsetof(W3DLaserDrawModuleData, m_gridColumns) }, + { "UseHouseColorOuter", INI::parseBool, NULL, offsetof(W3DLaserDrawModuleData, m_useHouseColorOuter) }, + { "UseHouseColorInner", INI::parseBool, NULL, offsetof(W3DLaserDrawModuleData, m_useHouseColorInner) }, { 0, 0, 0, 0 } }; p.add(dataFieldParse); @@ -113,34 +122,64 @@ void W3DLaserDrawModuleData::buildFieldParse(MultiIniFieldParse& p) //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -W3DLaserDraw::W3DLaserDraw( Thing *thing, const ModuleData* moduleData ) : - DrawModule( thing, moduleData ), +W3DLaserDraw::W3DLaserDraw(Thing* thing, const ModuleData* moduleData) : + DrawModule(thing, moduleData), m_line3D(NULL), m_texture(NULL), m_textureAspectRatio(1.0f), - m_selfDirty(TRUE) + m_selfDirty(TRUE), + m_hexColor(0) { - Vector3 dummyPos1( 0.0f, 0.0f, 0.0f ); - Vector3 dummyPos2( 1.0f, 1.0f, 1.0f ); + Vector3 dummyPos1(0.0f, 0.0f, 0.0f); + Vector3 dummyPos2(1.0f, 1.0f, 1.0f); Int i; - const W3DLaserDrawModuleData *data = getW3DLaserDrawModuleData(); + const W3DLaserDrawModuleData* data = getW3DLaserDrawModuleData(); - m_texture = WW3DAssetManager::Get_Instance()->Get_Texture( data->m_textureName.str() ); + m_texture = WW3DAssetManager::Get_Instance()->Get_Texture(data->m_textureName.str()); if (m_texture) { if (!m_texture->Is_Initialized()) m_texture->Init(); //make sure texture is actually loaded before accessing surface. - SurfaceClass::SurfaceDescription surfaceDesc; + SurfaceClass::SurfaceDescription surfaceDesc; m_texture->Get_Level_Description(surfaceDesc); - m_textureAspectRatio = (Real)surfaceDesc.Width/(Real)surfaceDesc.Height; + m_textureAspectRatio = (Real)surfaceDesc.Width / (Real)surfaceDesc.Height; } //Get the color components for calculation purposes. Real innerRed, innerGreen, innerBlue, innerAlpha, outerRed, outerGreen, outerBlue, outerAlpha; - GameGetColorComponentsReal( data->m_innerColor, &innerRed, &innerGreen, &innerBlue, &innerAlpha ); - GameGetColorComponentsReal( data->m_outerColor, &outerRed, &outerGreen, &outerBlue, &outerAlpha ); + GameGetColorComponentsReal(data->m_innerColor, &innerRed, &innerGreen, &innerBlue, &innerAlpha); + GameGetColorComponentsReal(data->m_outerColor, &outerRed, &outerGreen, &outerBlue, &outerAlpha); + + //DEBUG_LOG(("LaserDraw (Constructor): INIT 1\n")); + + ////Get the updatemodule that drives it... + //Drawable* draw = getDrawable(); + //if (draw) { + // static NameKeyType key_LaserUpdate = NAMEKEY("LaserUpdate"); + // LaserUpdate* update = (LaserUpdate*)draw->findClientUpdateModule(key_LaserUpdate); + // if (update) { + + // if (m_hexColor <= 0) { + // m_hexColor = update->getPlayerColor(); + // } + + // // handleHouseColor(&innerRed, &innerGreen, &innerBlue, &outerRed, &outerGreen, &outerBlue); + // handleHouseColor(innerRed, innerGreen, innerBlue, outerRed, outerGreen, outerBlue); + + // DEBUG_LOG(("LaserDraw (Constructor): AppliedHousecolor: Inner RGB = %f, %f, %f -- Outer RGB = %f, %f, %f\n", innerRed, innerGreen, innerBlue, outerRed, outerGreen, outerBlue)); + + // } + // else { + // // DEBUG_ASSERTCRASH(0, ("W3DLaserDraw::doDrawModule() expects its owner drawable %s to have a ClientUpdate = LaserUpdate module.", draw->getTemplate()->getName().str())); + // DEBUG_LOG(("W3DLaserDraw::(Constructor) expects its owner drawable %s to have a ClientUpdate = LaserUpdate module.", draw->getTemplate()->getName().str())); + // return; + // } + //} + //else { + // DEBUG_LOG(("W3DLaserDraw::(Constructor) Draw is null\n")); + //} //Make sure our beams range between 1 and the maximum cap. #ifdef I_WANT_TO_BE_FIRED @@ -201,7 +240,13 @@ W3DLaserDraw::W3DLaserDraw( Thing *thing, const ModuleData* moduleData ) : line->Set_UV_Offset_Rate( Vector2(0.0f, data->m_scrollRate) ); //amount to scroll texture on each draw if( m_texture ) { - line->Set_Texture_Mapping_Mode(SegLineRendererClass::TILED_TEXTURE_MAP); //this tiles the texture across the line + if (data->m_gridColumnsTotal > 1) { + line->Set_Texture_Mapping_Mode(SegLineRendererClass::GRID_TILED_TEXTURE_MAP); //allows animated U coordinates + line->Set_U_Scale(1.0f / (Real)(data->m_gridColumnsTotal)); + } + else { + line->Set_Texture_Mapping_Mode(SegLineRendererClass::TILED_TEXTURE_MAP); //this tiles the texture across the line + } } // add to scene @@ -237,6 +282,8 @@ W3DLaserDraw::~W3DLaserDraw( void ) } // end for i delete [] m_line3D; + // TheSuperHackers @fix Mauller 11/03/2025 Free reference counted material + REF_PTR_RELEASE(m_texture); } //------------------------------------------------------------------------------------------------- @@ -268,10 +315,58 @@ void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx) if (update->isDirty() || m_selfDirty) { update->setDirty(false); - m_selfDirty = false; + + m_hexColor = update->getPlayerColor(); + // DEBUG_LOG(("LaserDraw (doDrawModule 2): m_hexColor = %d\n", m_hexColor)); + + + // Texture animation + float u_offset = 0; + if (data->m_gridColumnsTotal > 1) { + float prog = update->getLifeTimeProgress(); + int currentFrame = (int)(data->m_gridColumns * prog); + if (currentFrame == data->m_gridColumns) + currentFrame = data->m_gridColumns - 1; + + u_offset = (1.0f / (float)data->m_gridColumnsTotal) * (float)currentFrame; + + // We stay dirty if we want to animate the beam + m_selfDirty = true; + } + else { + m_selfDirty = false; + } Vector3 laserPoints[ 2 ]; + + //Get the color components for calculation purposes. + Real innerRed, innerGreen, innerBlue, innerAlpha, outerRed, outerGreen, outerBlue, outerAlpha; + GameGetColorComponentsReal(data->m_innerColor, &innerRed, &innerGreen, &innerBlue, &innerAlpha); + GameGetColorComponentsReal(data->m_outerColor, &outerRed, &outerGreen, &outerBlue, &outerAlpha); + + bool updateColor = false; + RGBColor houseColor; + if ((data->m_useHouseColorInner || data->m_useHouseColorOuter)) { + houseColor.setFromInt(m_hexColor); + + if (data->m_useHouseColorInner) { + innerRed *= houseColor.red; + innerGreen *= houseColor.green; + innerBlue *= houseColor.blue; + } + if (data->m_useHouseColorOuter) { + outerRed *= houseColor.red; + outerGreen *= houseColor.green; + outerBlue *= houseColor.blue; + } + + updateColor = true; + } + + // DEBUG_LOG(("LaserDraw (doDrawModule): AppliedHousecolor: Inner RGB = %f, %f, %f -- Outer RGB = %f, %f, %f\n", innerRed, innerGreen, innerBlue, outerRed, outerGreen, outerBlue)); + + for( int segment = 0; segment < data->m_segments; segment++ ) { if( data->m_arcHeight > 0.0f && data->m_segments > 1 ) @@ -371,20 +466,26 @@ void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx) } //Get the color components for calculation purposes. - Real innerRed, innerGreen, innerBlue, innerAlpha, outerRed, outerGreen, outerBlue, outerAlpha; - GameGetColorComponentsReal( data->m_innerColor, &innerRed, &innerGreen, &innerBlue, &innerAlpha ); - GameGetColorComponentsReal( data->m_outerColor, &outerRed, &outerGreen, &outerBlue, &outerAlpha ); + //Real innerRed, innerGreen, innerBlue, innerAlpha, outerRed, outerGreen, outerBlue, outerAlpha; + //GameGetColorComponentsReal(data->m_innerColor, &innerRed, &innerGreen, &innerBlue, &innerAlpha); + //GameGetColorComponentsReal(data->m_outerColor, &outerRed, &outerGreen, &outerBlue, &outerAlpha); for( Int i = data->m_numBeams - 1; i >= 0; i-- ) { - Real alpha, width; + Real red, green, blue, alpha, width; int index = segment * data->m_numBeams + i; if( data->m_numBeams == 1 ) { width = data->m_innerBeamWidth * update->getWidthScale(); - alpha = innerAlpha; + alpha = innerAlpha * update->getAlphaScale(); + + if (updateColor) { + red = innerRed * innerAlpha; + green = innerGreen * innerAlpha; + blue = innerBlue * innerAlpha; + } } else { @@ -393,9 +494,17 @@ void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx) //0.2 means min value + 20% of the diff between min and max Real scale = i / ( data->m_numBeams - 1.0f); Real ultimateScale = update->getWidthScale(); + Real ultimateAlpha = update->getAlphaScale(); width = (data->m_innerBeamWidth + scale * (data->m_outerBeamWidth - data->m_innerBeamWidth)); width *= ultimateScale; alpha = innerAlpha + scale * (outerAlpha - innerAlpha); + alpha *= ultimateAlpha; + + if (updateColor) { + red = innerRed + scale * (outerRed - innerRed) * innerAlpha; + green = innerGreen + scale * (outerGreen - innerGreen) * innerAlpha; + blue = innerBlue + scale * (outerBlue - innerBlue) * innerAlpha; + } } @@ -414,8 +523,34 @@ void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx) m_line3D[ index ]->Set_Texture_Tile_Factor( tileFactor ); //number of times to tile texture across each segment } + if (u_offset > 0) { + Vector2 uvoffset = m_line3D[index]->Get_Current_UV_Offset(); + uvoffset.U = u_offset; + m_line3D[index]->Set_Current_UV_Offset(uvoffset); + } + + if (updateColor) { + m_line3D[index]->Set_Color(Vector3(red, green, blue)); + } + m_line3D[ index ]->Set_Width( width ); m_line3D[ index ]->Set_Points( 2, &laserPoints[0] ); + + + //-- + //if ((data->m_useHouseColorInner || data->m_useHouseColorOuter)) { //&& m_hexColor > 0) { + + // RGBColor myHouseColor; + // myHouseColor.setFromInt(m_hexColor); + + // Vector3 color; + // m_line3D[index]->Get_Color(color); + // color.X *= myHouseColor.red; + // color.Y *= myHouseColor.green; + // color.Z *= myHouseColor.blue; + + // m_line3D[index]->Set_Color(color); + //} } } } @@ -423,6 +558,7 @@ void W3DLaserDraw::doDrawModule(const Matrix3D* transformMtx) return; } + // ------------------------------------------------------------------------------------------------ /** CRC */ // ------------------------------------------------------------------------------------------------ diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp index 59f2b8f778..fead45dcb7 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp @@ -68,7 +68,7 @@ #include "WW3D2/meshmdl.h" #include "Common/BitFlagsIO.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -85,7 +85,7 @@ static inline Bool isValidTimeToCalcLogicStuff() //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(DEBUG_CRC) && (defined(_DEBUG) || defined(_INTERNAL)) +#if defined(DEBUG_CRC) && (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) #include class LogClass { @@ -205,11 +205,11 @@ LogClass BonePosLog("bonePositions.txt"); //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) extern AsciiString TheThingTemplateBeingParsedName; #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) extern Real TheSkateDistOverride; #endif @@ -476,7 +476,7 @@ static Bool findSingleSubObj(RenderObjClass* robj, const AsciiString& boneName, if (test == childObject) { boneIndex = robj->Get_Sub_Object_Bone_Index(0, subObj); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) test->Release_Ref(); test = robj->Get_Sub_Object_On_Bone(0, boneIndex); DEBUG_ASSERTCRASH(test != NULL && test == childObject, ("*** ASSET ERROR: Hmm, bone problem")); @@ -743,7 +743,7 @@ void ModelConditionInfo::validateWeaponBarrelInfo() const // since this class has no idea which object it refers to, it must assume that the projectilelaunchbonename // is required if the fxBoneName is specified // this is not always true, since some weapons have no launched projectiles, hence the caveat in the assert message -//#if defined(_DEBUG) || defined(_INTERNAL) +//#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // if ( // ( m_modelName.startsWith("UV") || m_modelName.startsWith("NV") || m_modelName.startsWith("AV") || // m_modelName.startsWith("uv") || m_modelName.startsWith("nv") || m_modelName.startsWith("av") @@ -773,7 +773,7 @@ void ModelConditionInfo::validateWeaponBarrelInfo() const { sprintf(buffer, "%s%02d", mfName.str(), i); findPristineBone(NAMEKEY(buffer), &info.m_muzzleFlashBone); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) if (info.m_muzzleFlashBone) info.m_muzzleFlashBoneName = buffer; #endif @@ -821,7 +821,7 @@ void ModelConditionInfo::validateWeaponBarrelInfo() const if (!mfName.isEmpty()) findPristineBone(NAMEKEY(mfName), &info.m_muzzleFlashBone); -#if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) if (info.m_muzzleFlashBone) info.m_muzzleFlashBoneName = mfName; #endif @@ -986,7 +986,7 @@ void ModelConditionInfo::loadAnimations() const void ModelConditionInfo::clear() { int i; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_description.clear(); #endif m_conditionsYesVec.clear(); @@ -1482,7 +1482,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void info.m_conditionsYesVec.clear(); info.m_conditionsYesVec.push_back(blankConditions); - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) info.m_description.clear(); info.m_description.concat(TheThingTemplateBeingParsedName); info.m_description.concat(" DEFAULT"); @@ -1513,7 +1513,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void } info.m_transitionSig = buildTransitionSig(firstKey, secondKey); - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) info.m_description.clear(); info.m_description.concat(TheThingTemplateBeingParsedName); info.m_description.concat(" TRANSITION: "); @@ -1537,7 +1537,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void ModelConditionFlags conditionsYes; - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) AsciiString description; conditionsYes.parse(ini, &description); @@ -1589,7 +1589,7 @@ void W3DModelDrawModuleData::parseConditionState(INI* ini, void *instance, void // } ModelConditionFlags conditionsYes; - #if defined(_DEBUG) || defined(_INTERNAL) || defined(DEBUG_CRASHING) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(DEBUG_CRASHING) AsciiString description; conditionsYes.parse(ini, &description); @@ -1889,18 +1889,18 @@ void W3DModelDraw::setShadowsEnabled(Bool enable) } /**collect some stats about the rendering cost of this draw module */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DModelDraw::getRenderCost(RenderCost & rc) const { getRenderCostRecursive(rc,m_renderObject); if (m_shadow) m_shadow->getRenderCost(rc); } -#endif //_DEBUG || _INTERNAL +#endif //RTS_DEBUG || RTS_INTERNAL /**recurse through sub-objs to collect stats about the rendering cost of this draw module */ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DModelDraw::getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) const { if (robj == NULL) return; @@ -1937,7 +1937,7 @@ void W3DModelDraw::getRenderCostRecursive(RenderCost & rc,RenderObjClass * robj) } } } -#endif //_DEBUG || _INTERNAL +#endif //RTS_DEBUG || RTS_INTERNAL //------------------------------------------------------------------------------------------------- void W3DModelDraw::setFullyObscuredByShroud(Bool fullyObscured) @@ -2262,7 +2262,7 @@ Real W3DModelDraw::getCurAnimDistanceCovered() const if (m_curState != NULL && m_whichAnimInCurState >= 0) { const W3DAnimationInfo& animInfo = m_curState->m_animations[m_whichAnimInCurState]; - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheSkateDistOverride != 0.0f) return TheSkateDistOverride; #endif @@ -2822,7 +2822,7 @@ void W3DModelDraw::nukeCurrentRender(Matrix3D* xform) } //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test. +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //art wants to see buildings without flags as a test. void W3DModelDraw::hideGarrisonFlags(Bool hide) { if (!m_renderObject) @@ -3048,7 +3048,7 @@ void W3DModelDraw::setModelState(const ModelConditionInfo* newState) rebuildWeaponRecoilInfo(newState); doHideShowSubObjs(&newState->m_hideShowVec); -#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test. +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //art wants to see buildings without flags as a test. if (TheGlobalData->m_hideGarrisonFlags && draw->isKindOf(KINDOF_STRUCTURE)) hideGarrisonFlags(TRUE); #endif @@ -3277,7 +3277,7 @@ Bool W3DModelDraw::getProjectileLaunchOffset( //BONEPOS_LOG(("can't find best info\n")); return false; } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) CRCDEBUG_LOG(("W3DModelDraw::getProjectileLaunchOffset() for %s\n", stateToUse->getDescription().str())); #endif @@ -3774,6 +3774,72 @@ Bool W3DModelDraw::handleWeaponFireFX(WeaponSlotType wslot, Int specificBarrelTo return handled; } + +//------------------------------------------------------------------------------------------------- +Bool W3DModelDraw::handleWeaponPreAttackFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, const Coord3D* victimPos, Real damageRadius) +{ + //Note: This is mostly a copy of handleWeaponFireFX + + //DEBUG_LOG((">>> handleWeaponPreAttackFX - Slot: %d, Barrel: %d, Pos: '(%f, %f, %f)' \n", + // (Int)wslot, + // specificBarrelToUse, + // victimPos->x, victimPos->y, victimPos->z)); + + if (!m_curState || !(m_curState->m_validStuff & ModelConditionInfo::BARRELS_VALID)) + return false; + + const ModelConditionInfo::WeaponBarrelInfoVec& wbvec = m_curState->m_weaponBarrelInfoVec[wslot]; + if (wbvec.empty()) + { + return false; + } + + Bool handled = false; + + if (specificBarrelToUse < 0 || specificBarrelToUse > wbvec.size()) + specificBarrelToUse = 0; + + const ModelConditionInfo::WeaponBarrelInfo& info = wbvec[specificBarrelToUse]; + + if (fxl) + { + if (info.m_fxBone && m_renderObject) + { + const Object* logicObject = getDrawable()->getObject(); + /*DEBUG_LOG((">>> handleWeaponPreAttackFX - 1.5 - m_renderObject= '%s' \n", + m_renderObject ? "Not Null" : "Null"));*/ + if (!m_renderObject->Is_Hidden() || (logicObject == NULL)) + { + // I can ask the drawable's bone position if I am not hidden (if I have no object I have no choice) + Matrix3D mtx = m_renderObject->Get_Bone_Transform(info.m_fxBone); + Coord3D pos; + pos.x = mtx.Get_X_Translation(); + pos.y = mtx.Get_Y_Translation(); + pos.z = mtx.Get_Z_Translation(); + FXList::doFXPos(fxl, &pos, &mtx, weaponSpeed, victimPos, damageRadius); + } + else + { + // Else, I should just use my logic position for the effect placement. + // Things in transports regularly fire from inside (hidden), so this is not weird. + const Matrix3D* mtx; + Coord3D pos; + mtx = logicObject->getTransformMatrix(); + pos = *(logicObject->getPosition()); + FXList::doFXPos(fxl, &pos, mtx, weaponSpeed, victimPos, damageRadius); + } + + handled = true; + } + else + { + DEBUG_LOG(("*** no FXBone found for a non-null FXL\n")); + } + } + + return handled; +} + //------------------------------------------------------------------------------------------------- void W3DModelDraw::setAnimationLoopDuration(UnsignedInt numFrames) { @@ -4298,7 +4364,7 @@ void W3DModelDrawModuleData::xfer( Xfer *x ) { ModelConditionInfo *info = &(*it); x->xferByte(&(info->m_validStuff)); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) x->xferAsciiString(&(info->m_description)); #endif if (info->m_validStuff) diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordAircraftDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordAircraftDraw.cpp index 0da2a1db91..a49e6631ee 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordAircraftDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordAircraftDraw.cpp @@ -42,7 +42,7 @@ #include "W3DDevice/GameClient/Module/W3DOverlordAircraftDraw.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp index 8604a4b492..be666be04e 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DPropDraw.cpp @@ -38,7 +38,7 @@ #include "W3DDevice/GameClient/Module/W3DPropDraw.h" #include "W3DDevice/GameClient/BaseHeightMap.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp index d4684d871c..50d3ba8eb0 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DRopeDraw.cpp @@ -44,7 +44,7 @@ #include "W3DDevice/GameClient/W3DScene.h" #include "Common/GameState.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp index 80c3739265..269a56b033 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DTankDraw.cpp @@ -47,7 +47,7 @@ #include "W3DDevice/GameClient/Module/W3DTankDraw.h" #include "WW3D2/matinfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -163,6 +163,9 @@ void W3DTankDraw::createEmitters( void ) //------------------------------------------------------------------------------------------------- W3DTankDraw::~W3DTankDraw() { + // TheSuperHackers @fix Mauller 16/04/2025 Delete particle systems + tossEmitters(); + for (Int i=0; ifindImageByName("GenExpBarTop1"); static const Image *beginBar = TheMappedImageCollection->findImageByName("GenExpBarBottom1"); static const Image *centerBar = TheMappedImageCollection->findImageByName("GenExpBar1"); - Int progress; - progress = ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) /(player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown()); + Int progress = 0; + Int skillPointsRequired = player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown(); + + // TheSuperHackers @bugfix Mauller 04/05/2025 Prevent possible division by zero + if ( skillPointsRequired > 0) + { + progress = ( ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) / skillPointsRequired ); + } if(progress <= 0) return; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp index 2ed8d69146..4a7b754d58 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DHorizontalSlider.cpp @@ -68,7 +68,7 @@ /////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp index 824d99c11e..6d7a7a048e 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DPushButton.cpp @@ -58,7 +58,7 @@ #include "W3DDevice/GameClient/W3DGadget.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp index e46adac0e4..7f779a841d 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DStaticText.cpp @@ -70,7 +70,7 @@ /////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp index bb6c082756..a81880fdd7 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DTextEntry.cpp @@ -53,7 +53,7 @@ #include "W3DDevice/GameClient/W3DGadget.h" #include "W3DDevice/GameClient/W3DDisplay.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp index 484431e66c..95bd772b47 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp @@ -96,7 +96,7 @@ #include "Common/PerfTimer.h" #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -179,7 +179,7 @@ UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX #else Real shadeR, shadeG, shadeB; Int diffuse = vbMirror->diffuse; -#ifdef _DEBUG +#ifdef RTS_DEBUG //vbMirror->diffuse += 30; // Shows which vertexes are geting touched by dynamic light. debug only. #endif @@ -272,7 +272,7 @@ Int HeightMapRenderObjClass::getXWithOrigin(Int x) x -= m_originX; if (x<0) x+= m_x-1; if (x>= m_x-1) x-=m_x-1; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH (x>=0, ("X out of range.")); DEBUG_ASSERTCRASH (x= m_y-1) y-=m_y-1; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH (y>=0, ("Y out of range.")); DEBUG_ASSERTCRASH (y= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH); #endif @@ -583,7 +583,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *d if (m_vertexBufferTiles && m_map) { -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(x0 >= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH); #endif @@ -730,7 +730,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVB if (m_vertexBufferTiles && m_map) { -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(x0 >= originX && y0 >= originY && x1>x0 && y1>y0 && x1<=originX+VERTEX_BUFFER_TILE_LENGTH && y1<=originY+VERTEX_BUFFER_TILE_LENGTH); #endif @@ -1017,7 +1017,7 @@ The vertex coordinates and texture coordinates, as well as static lighting are u */ Int HeightMapRenderObjClass::updateBlock(Int x0, Int y0, Int x1, Int y1, WorldHeightMap *pMap, RefRenderObjListIterator *pLightsIterator) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(x0>=0, ("HeightMapRenderObjClass::UpdateBlock parameters extend beyond left edge.")); DEBUG_ASSERTCRASH(y0>=0, ("HeightMapRenderObjClass::UpdateBlock parameters extend beyond bottom edge.")); DEBUG_ASSERTCRASH(x1m_useShadowDecals && m_isEnabled && !m_isInvisibleEnabled) diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp index 90647da5e2..fa2c309db0 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp @@ -62,7 +62,7 @@ #include "wwshade/shdsubmesh.h" #endif -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -850,43 +850,6 @@ Int W3DShadowGeometry::initFromMesh(RenderObjClass *robj) Int W3DShadowGeometry::init(RenderObjClass *robj) { return TRUE; -// m_robj=robj; -/* //code to deal with granny - don't think we'll use shadow volumes on these!? - granny_file *fileInfo=robj->getPrototype().m_file; - - for (Int modelIndex=0; modelIndexModelCount; modelIndex++) - { - granny_model *sourceModel = fileInfo->Models[modelIndex]; - if (stricmp(sourceModel->Name,"AABOX") == 0) - { //found a collision box, copy out data - int MeshCount = sourceModel->MeshBindingCount; - if (MeshCount==1) - { - granny_mesh *sourceMesh = sourceModel->MeshBindings[0].Mesh; - granny_pn33_vertex *Vertices = (granny_pn33_vertex *)sourceMesh->PrimaryVertexData->Vertices; - Vector3 points[24]; - - assert (sourceMesh->PrimaryVertexData->VertexCount <= 24); - - for (Int boxVertex=0; boxVertexPrimaryVertexData->VertexCount; boxVertex++) - { points[boxVertex].Set(Vertices[boxVertex].Position[0], - Vertices[boxVertex].Position[1], - Vertices[boxVertex].Position[2]); - } - box.Init(points,sourceMesh->PrimaryVertexData->VertexCount); - } - } - else - { //mesh is part of model - int meshCount = sourceModel->MeshBindingCount; - for (Int meshIndex=0; meshIndexMeshBindings[meshIndex].Mesh; - if (sourceMesh->PrimaryVertexData) - vertexCount+=sourceMesh->PrimaryVertexData->VertexCount; - } - } - }*/ } /////////////////////////////////////////////////////////////////////////////// @@ -1314,7 +1277,7 @@ void W3DVolumetricShadow::updateOptimalExtrusionPadding(void) // getRenderCost ============================================================ // Returns number of draw calls for this shadow. // ============================================================================ -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DVolumetricShadow::getRenderCost(RenderCost & rc) const { Int drawCount = 0; @@ -4088,7 +4051,7 @@ int W3DShadowGeometryManager::Load_Geom(RenderObjClass *robj, const char *name) } /* -** Iterator converter from HashableClass to GrannyAnimClass +** Iterator converter from HashableClass to W3DShadowGeometry */ W3DShadowGeometry * W3DShadowGeometryManagerIterator::Get_Current_Geom( void ) { diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp index 710138c451..6e2a4c0b61 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp @@ -112,7 +112,7 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) Int tilesPerRow = surface_desc.Width/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); tilesPerRow *= 2; // Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#ifdef _DEBUG +#ifdef RTS_DEBUG //DEBUG_ASSERTCRASH(tilesPerRow*numRows >= htMap->m_numBitmapTiles, ("Too many tiles.")); DEBUG_ASSERTCRASH((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow, ("Bitmap too small.")); #endif @@ -232,7 +232,7 @@ int TerrainTextureClass::update(WorldHeightMap *htMap) Int tilesPerRow = surface_desc.Width/(2*TILE_PIXEL_EXTENT+TILE_OFFSET); tilesPerRow *= 2; Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#ifdef _DEBUG +#ifdef RTS_DEBUG assert(tilesPerRow*numRows >= htMap->m_numBitmapTiles); assert((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow); #endif diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp index dd79e49b62..01a5038249 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp @@ -70,7 +70,7 @@ #include "Common/GlobalData.h" #include "Common/GameCommon.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -151,17 +151,11 @@ RenderObjClass * W3DPrototypeClass::Create(void) //--------------------------------------------------------------------- W3DAssetManager::W3DAssetManager(void) { -#ifdef INCLUDE_GRANNY_IN_BUILD - m_GrannyAnimManager = NEW GrannyAnimManagerClass; -#endif } //--------------------------------------------------------------------- W3DAssetManager::~W3DAssetManager(void) { -#ifdef INCLUDE_GRANNY_IN_BUILD - delete m_GrannyAnimManager; -#endif } #ifdef DUMP_PERF_STATS @@ -245,7 +239,7 @@ TextureClass *W3DAssetManager::Get_Texture( // extern std::vector preloadTextureNamesGlobalHack; // preloadTextureNamesGlobalHack.push_back(tex->Get_Texture_Name()); // } -#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) if (TheGlobalData->m_preloadReport) { //loading a new asset and app is requesting a log of all loaded assets. @@ -730,12 +724,6 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( GetPrecisionTimer(&startTime64); #endif -#ifdef INCLUDE_GRANNY_IN_BUILD - Bool isGranny = false; - char *pext=strrchr(name,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); -#endif Bool reallyscale = (WWMath::Fabs(scale - ident_scale) > scale_epsilon); Bool reallycolor = (color & 0xFFFFFF) != 0; //black is not a valid color and assumes no custom coloring. Bool reallytexture = (oldTexture != NULL && newTexture != NULL); @@ -757,12 +745,6 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( // see if we got a cached version RenderObjClass *rendobj = NULL; -#ifdef INCLUDE_GRANNY_IN_BUILD - if (isGranny) - { //Granny objects share the same prototype since they allow instance scaling. - strcpy(newname,name); //use same name for all granny objects at any scale. - } -#endif Set_WW3D_Load_On_Demand(false); // munged name will never be found in a file. rendobj = WW3DAssetManager::Create_Render_Obj(newname); if (rendobj) @@ -770,11 +752,6 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( //when we need to save this render object to a file. Used during saving //of fog of war ghost objects. rendobj->Set_ObjectColor(color); -#ifdef INCLUDE_GRANNY_IN_BUILD - if (isGranny) - ///@todo Granny objects are realtime scaled - fix to scale like W3D. - rendobj->Set_ObjectScale(scale); -#endif Set_WW3D_Load_On_Demand(true); // Auto Load. #ifdef DUMP_PERF_STATS @@ -797,16 +774,11 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( { // If we didn't find one, try to load on demand char filename [MAX_PATH]; - const char *mesh_name = ::strchr (name, '.'); + const char *mesh_name = strchr (name, '.'); if (mesh_name != NULL) { - ::lstrcpyn(filename, name, ((int)mesh_name) - ((int)name) + 1); -#ifdef INCLUDE_GRANNY_IN_BUILD - if (isGranny) - ::lstrcat(filename, ".gr2"); - else -#endif - ::lstrcat(filename, ".w3d"); + lstrcpyn(filename, name, ((int)mesh_name) - ((int)name) + 1); + lstrcat(filename, ".w3d"); } else { sprintf( filename, "%s.w3d", name); } @@ -815,15 +787,7 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( if ( Load_3D_Assets( filename ) == false ) { StringClass new_filename = StringClass("..\\") + filename; - if (Load_3D_Assets( new_filename ) == false) - { -#ifdef INCLUDE_GRANNY_IN_BUILD - char *mesh_name = ::strchr (filename, '.'); - ::lstrcpyn (mesh_name, ".gr2",5); - Load_3D_Assets( filename ); - isGranny=true; -#endif - } + Load_3D_Assets(new_filename); } proto = Find_Prototype(name); // try again @@ -853,35 +817,23 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj( #endif return NULL; } -#ifdef INCLUDE_GRANNY_IN_BUILD - if (!isGranny) -#endif - { - if (reallyscale) - rendobj->Scale(scale); //this also makes it unique - Make_Unique(rendobj,reallyscale,reallycolor); + if (reallyscale) + rendobj->Scale(scale); //this also makes it unique - if (reallytexture) - { - TextureClass *oldTex = Get_Texture(oldTexture); - TextureClass *newTex = Get_Texture(newTexture); - replaceAssetTexture(rendobj,oldTex,newTex); - REF_PTR_RELEASE(newTex); - REF_PTR_RELEASE(oldTex); - } + Make_Unique(rendobj,reallyscale,reallycolor); - if (reallycolor) - Recolor_Asset(rendobj,color); - } -#ifdef INCLUDE_GRANNY_IN_BUILD - else + if (reallytexture) { - ///@todo Granny objects are realtime scaled - fix to scale like W3D. - rendobj->Set_ObjectScale(scale); - return rendobj; + TextureClass *oldTex = Get_Texture(oldTexture); + TextureClass *newTex = Get_Texture(newTexture); + replaceAssetTexture(rendobj,oldTex,newTex); + REF_PTR_RELEASE(newTex); + REF_PTR_RELEASE(oldTex); } -#endif + + if (reallycolor) + Recolor_Asset(rendobj,color); W3DPrototypeClass *w3dproto = newInstance(W3DPrototypeClass)(rendobj, newname); rendobj->Release_Ref(); @@ -1018,14 +970,6 @@ bool W3DAssetManager::Load_3D_Assets( const char * filename ) GetPrecisionTimer(&startTime64); #endif -#ifdef INCLUDE_GRANNY_IN_BUILD - Bool isGranny = false; - char *pext=strrchr(filename,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); - if (!isGranny) -#endif - // Try to find an existing prototype char basename[512]; strcpy(basename, filename); @@ -1047,7 +991,7 @@ bool W3DAssetManager::Load_3D_Assets( const char * filename ) bool result = WW3DAssetManager::Load_3D_Assets(filename); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (result && TheGlobalData->m_preloadReport) { //loading a new asset and app is requesting a log of all loaded assets. @@ -1070,40 +1014,6 @@ bool W3DAssetManager::Load_3D_Assets( const char * filename ) #endif return result; -#ifdef INCLUDE_GRANNY_IN_BUILD - //Loading assets for Granny File - PrototypeClass * newproto = NULL; - newproto = _GrannyLoader.Load_W3D(filename); - /* - ** Now, see if the prototype that we loaded has a duplicate - ** name with any of our currently loaded prototypes (can't have that!) - */ - if (newproto != NULL) { - if (!Render_Obj_Exists(newproto->Get_Name())) { - /* - ** Add the new, unique prototype to our list - */ - Add_Prototype(newproto); - } else { - /* - ** Warn the user about a name collision with this prototype - ** and dump it - */ - WWDEBUG_SAY(("Render Object Name Collision: %s\r\n",newproto->Get_Name())); - delete newproto; - newproto = NULL; - return false; - } - } else { - /* - ** Warn user that a prototype was not generated from this - ** chunk type - */ - WWDEBUG_SAY(("Could not generate Granny prototype! File = %d\r\n",filename)); - return false; - } - return true; -#endif } #ifdef DUMP_PERF_STATS @@ -1121,47 +1031,17 @@ HAnimClass * W3DAssetManager::Get_HAnim(const char * name) #endif WWPROFILE( "WW3DAssetManager::Get_HAnim" ); -#ifdef INCLUDE_GRANNY_IN_BUILD - Bool isGranny = false; - char *pext=strrchr(name,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); - if (!isGranny) -#endif - { - HAnimClass *anim=WW3DAssetManager::Get_HAnim(name); //we only do custom granny processing. + HAnimClass *anim=WW3DAssetManager::Get_HAnim(name); #ifdef DUMP_PERF_STATS - if (HAnim_Recursions == 1) - { - GetPrecisionTimer(&endTime64); - Total_Get_HAnim_Time += endTime64-startTime64; - } - HAnim_Recursions--; -#endif - return anim; - } - -#ifdef INCLUDE_GRANNY_IN_BUILD - // Try to find the hanim - HAnimClass * anim = m_GrannyAnimManager->Get_Anim(name); - if (WW3D_Load_On_Demand && anim == NULL) { // If we didn't find it, try to load on demand - if ( !m_GrannyAnimManager->Is_Missing( name ) ) { // if this is NOT a known missing anim - - // If we can't find it, try the parent directory - if ( m_GrannyAnimManager->Load_Anim(name) == 1 ) { - StringClass new_filename = StringClass("..\\") + name; - m_GrannyAnimManager->Load_Anim( new_filename ); - } - - anim = m_GrannyAnimManager->Get_Anim(name); // Try again - if (anim == NULL) { -// WWDEBUG_SAY(("WARNING: Animation %s not found!\n", name)); - m_GrannyAnimManager->Register_Missing( name ); // This is now a KNOWN missing anim - } - } + if (HAnim_Recursions == 1) + { + GetPrecisionTimer(&endTime64); + Total_Get_HAnim_Time += endTime64-startTime64; } - return anim; + HAnim_Recursions--; #endif + return anim; + } //--------------------------------------------------------------------- @@ -1447,11 +1327,6 @@ static inline void Munge_Texture_Name(char *newname, const char *oldname, const RenderObjClass * W3DAssetManager::Create_Render_Obj(const char * name,float scale, const Vector3 &hsv_shift) { Bool isGranny = false; -#ifdef INCLUDE_GRANNY_IN_BUILD - char *pext=strrchr(name,'.'); //find file extension - if (pext) - isGranny=(strnicmp(pext,".GR2",4) == 0); -#endif Bool reallyscale = (WWMath::Fabs(scale - ident_scale) > scale_epsilon); Bool reallyhsv_shift = (WWMath::Fabs(hsv_shift.X - ident_HSV.X) > H_epsilon || WWMath::Fabs(hsv_shift.Y - ident_HSV.Y) > S_epsilon || WWMath::Fabs(hsv_shift.Z - ident_HSV.Z) > V_epsilon); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp index 47e34b969a..df141f96c9 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DBridgeBuffer.cpp @@ -72,7 +72,7 @@ #include "WW3D2/meshmdl.h" #include "WW3D2/scene.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1157,7 +1157,7 @@ void W3DBridgeBuffer::drawBridges(CameraClass * camera, Bool wireframe, TextureC DX8Wrapper::Set_Index_Buffer(m_indexBridge,0); DX8Wrapper::Set_Vertex_Buffer(m_vertexBridge); DX8Wrapper::Set_Shader(detailAlphaShader); -#ifdef _DEBUG +#ifdef RTS_DEBUG //DX8Wrapper::Set_Shader(detailShader); // shows alpha clipping. #endif diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DCustomEdging.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DCustomEdging.cpp index 1b23d386ce..d5d22ec686 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DCustomEdging.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DCustomEdging.cpp @@ -358,7 +358,7 @@ void W3DCustomEdging::drawEdging(WorldHeightMap *pMap, Int minX, Int maxX, Int m DX8Wrapper::Set_Index_Buffer(m_indexEdging,0); DX8Wrapper::Set_Vertex_Buffer(m_vertexEdging); DX8Wrapper::Set_Shader(detailAlphaTestShader); -#ifdef _DEBUG +#ifdef RTS_DEBUG //DX8Wrapper::Set_Shader(detailShader); // shows clipping. #endif diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDebugIcons.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDebugIcons.cpp index 5cb1e99495..5449d1968a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDebugIcons.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDebugIcons.cpp @@ -53,7 +53,7 @@ #include "Common/MapObject.h" #include "WW3D2/dx8wrapper.h" -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Texturing, no zbuffer, disabled zbuffer write, primary gradient, alpha blending #define SC_OPAQUE ( SHADE_CNST(ShaderClass::PASS_ALWAYS, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \ @@ -312,4 +312,4 @@ void W3DDebugIcons::Render(RenderInfoClass & rinfo) } } -#endif // _DEBUG or _INTERNAL \ No newline at end of file +#endif // RTS_DEBUG or RTS_INTERNAL \ No newline at end of file diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp index f551296241..7b5a8bddc7 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp @@ -109,7 +109,7 @@ static void drawFramerateBar(void); #include "WinMain.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -322,7 +322,7 @@ void StatDumpClass::dumpStats( Bool brief, Bool flagSpikes ) fprintf( m_fp, "\n" ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if ( ! beBrief ) { TheAudio->audioDebugDisplay( NULL, NULL, m_fp ); @@ -401,7 +401,7 @@ W3DDisplay::W3DDisplay() m_2DScene = NULL; m_3DInterfaceScene = NULL; m_averageFPS = TheGlobalData->m_framesPerSecondLimit; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_timerAtCumuFPSStart = 0; #endif for (i=0; ifreeDisplayString(m_displayStrings[i]); + // TheSuperHackers @fix Mauller/Tomsons26 28/04/2025 Free benchmark display string + if( m_benchmarkDisplayString ) { + TheDisplayStringManager->freeDisplayString(m_benchmarkDisplayString); + } + // delete 2D renderer if( m_2DRender ) { @@ -685,7 +692,7 @@ void W3DDisplay::init( void ) // create our 3D scene m_3DScene =NEW_REF( RTS3DScene, () ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_wireframe ) m_3DScene->Set_Polygon_Mode( SceneClass::LINE ); #endif @@ -884,7 +891,7 @@ void W3DDisplay::updateAverageFPS(void) Int64 freq64 = getPerformanceCounterFrequency(); Int64 time64 = getPerformanceCounter(); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGameLogic->getFrame() == START_CUMU_FRAME) { m_timerAtCumuFPSStart = time64; @@ -926,7 +933,7 @@ void W3DDisplay::updateAverageFPS(void) lastUpdateTime64 = time64; } -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats ICoord2D TheMousePos; #endif @@ -1020,7 +1027,7 @@ void W3DDisplay::gatherDebugStats( void ) double ms = 1000.0f/fps; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) double cumuTime = ((double)(time64 - m_timerAtCumuFPSStart) / (double)(freq64)); if (cumuTime < 0.0) cumuTime = 0.0; Int numFrames = (Int)TheGameLogic->getFrame() - (Int)START_CUMU_FRAME; @@ -1191,7 +1198,7 @@ void W3DDisplay::gatherDebugStats( void ) if (debugD3D) { unibuffer.concat(L", DEBUG D3D"); } -#ifdef _DEBUG +#ifdef RTS_DEBUG unibuffer.concat(L", DEBUG app"); #endif @@ -1318,7 +1325,7 @@ void W3DDisplay::gatherDebugStats( void ) } Object *object = NULL; -#if defined(_DEBUG) || defined(_INTERNAL) //debug hack to view object under mouse stats +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //debug hack to view object under mouse stats Drawable *draw = TheTacticalView->pickDrawable(&TheMousePos, FALSE, (PickType)0xffffffff ); #else Drawable *draw = TheGameClient->findDrawableByID( TheInGameUI->getMousedOverDrawableID() ); @@ -1446,7 +1453,7 @@ void W3DDisplay::gatherDebugStats( void ) // (gth) compute some stats about the rendering cost of this drawable -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) RenderCost rcost; for (DrawModule** dm = draw->getDrawModules(); *dm; ++dm) { @@ -1578,7 +1585,7 @@ void W3DDisplay::calculateTerrainLOD( void ) TerrainLOD goodLOD = TERRAIN_LOD_MIN; TerrainLOD curLOD = TERRAIN_LOD_AUTOMATIC; Int count = 0; -#ifdef _DEBUG +#ifdef RTS_DEBUG // just go to TERRAIN_LOD_NO_WATER, mirror off. TheWritableGlobalData->m_terrainLOD = TERRAIN_LOD_NO_WATER; m_3DScene->drawTerrainOnly(false); @@ -1638,7 +1645,7 @@ void W3DDisplay::calculateTerrainLOD( void ) TheWritableGlobalData->m_terrainLOD = goodLOD; m_3DScene->drawTerrainOnly(false); TheTerrainRenderObject->adjustTerrainLOD(0); -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTCRASH(count<10, ("calculateTerrainLOD") ); #endif @@ -1715,7 +1722,7 @@ void W3DDisplay::draw( void ) // compute debug statistics for display later if ( m_debugDisplayCallback == StatDebugDisplay -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) || TheGlobalData->m_benchmarkTimer > 0 #endif ) @@ -1958,7 +1965,7 @@ void W3DDisplay::draw( void ) drawCurrentDebugDisplay(); } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_benchmarkTimer > 0) { drawFPSStats(); @@ -1966,7 +1973,7 @@ void W3DDisplay::draw( void ) #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_debugShowGraphicalFramerate) { drawFramerateBar(); @@ -3126,7 +3133,7 @@ void W3DDisplay::toggleMovieCapture(void) } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) static FILE *AssetDumpFile=NULL; @@ -3279,7 +3286,7 @@ void W3DDisplay::doSmartAssetPurgeAndPreload(const char* usageFileName) //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) void W3DDisplay::dumpAssetUsage(const char* mapname) { if (!m_assetManager || !mapname || !*mapname) diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp index 29913c1b31..7a10894cc7 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplayString.cpp @@ -56,7 +56,7 @@ #include "GameClient/GlobalLanguage.h" // DEFINES //////////////////////////////////////////////////////////////////// -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp index ea8bb6bff2..bab5a2fe37 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DFileSystem.cpp @@ -425,7 +425,7 @@ int GameFileClass::Size(void) //------------------------------------------------------------------------------------------------- int GameFileClass::Write(void const *buffer, Int len) { -#ifdef _DEBUG +#ifdef RTS_DEBUG #endif return(0); } diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp index 747512e025..0e4f181a4b 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp @@ -52,14 +52,14 @@ #include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba. -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif -#ifdef _DEBUG +#ifdef RTS_DEBUG #include "W3DDevice/GameClient/HeightMap.h" #include "WW3D2/dx8indexbuffer.h" #include "WW3D2/dx8vertexbuffer.h" @@ -259,7 +259,7 @@ void DebugHintObject::Render(RenderInfoClass & rinfo) DX8Wrapper::Draw_Triangles( 0, 1, 0, 3); } } -#endif // _DEBUG +#endif // RTS_DEBUG /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp index 50bf713e16..c1fcfce3e3 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cpp @@ -47,7 +47,7 @@ #include "mutex.h" #include "thread.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp index 98d67104ad..f040861e94 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp @@ -36,7 +36,7 @@ #include "W3DDevice/GameClient/W3DSnow.h" #include "WW3D2/camera.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp index d0da9dbec0..670f1fc9ba 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp @@ -64,7 +64,7 @@ #include "W3DDevice/GameClient/BaseHeightMap.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp index cd5e5927e6..b9760e0419 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cpp @@ -70,7 +70,7 @@ static const Real TEE_WIDTH_ADJUSTMENT = 1.03f; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -710,7 +710,7 @@ void W3DRoadBuffer::loadFloat4PtSection(RoadSegment *pRoad, Vector2 loc, V = Vector2::Dot_Product(roadNormal, curVector); U = Vector2::Dot_Product(roadVector, curVector); Int diffuse = 0; - #ifdef _DEBUG + #ifdef RTS_DEBUG //diffuse &= 0xFFFF00FF; // strip out green. #endif vb[numRoadVertices].u1 = uOffset+U/(uScale*4); @@ -992,7 +992,7 @@ void W3DRoadBuffer::loadLit4PtSection(RoadSegment *pRoad, UnsignedShort *ib, Ver shadeB*=255; diffuse=REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((int)255 << 24); - #ifdef _DEBUG + #ifdef RTS_DEBUG //diffuse &= 0xFFFF00FF; // strip out green. #endif vb[m_curNumRoadVertices].u1 = info.uOffset+U/(info.scale*4); @@ -1370,7 +1370,7 @@ void W3DRoadBuffer::loadRoadSegment(UnsignedShort *ib, VertexFormatXYZDUV1 *vb, void W3DRoadBuffer::moveRoadSegTo(Int fromNdx, Int toNdx) { if (fromNdx<0 || fromNdx>=m_numRoads || toNdx<0 || toNdx>=m_numRoads) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_LOG(("bad moveRoadSegTo\n")); #endif return; @@ -1403,7 +1403,7 @@ void W3DRoadBuffer::checkLinkBefore(Int ndx) } Vector2 loc2 = m_roads[ndx].m_pt2.loc; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[ndx].m_pt1.loc == m_roads[ndx+1].m_pt2.loc, ("Bad link\n")); if (ndx>0) { DEBUG_ASSERTLOG(m_roads[ndx].m_pt2.loc != m_roads[ndx-1].m_pt1.loc, ("Bad Link\n")); @@ -1420,7 +1420,7 @@ void W3DRoadBuffer::checkLinkBefore(Int ndx) Int checkNdx = endOfCurSeg+1; while (checkNdx < m_numRoads) { if (m_roads[checkNdx].m_pt1.loc == loc2) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[checkNdx].m_pt1.count==1, ("Bad count\n")); #endif moveRoadSegTo(checkNdx, ndx); @@ -1428,7 +1428,7 @@ void W3DRoadBuffer::checkLinkBefore(Int ndx) if (m_roads[ndx].m_pt2.count != 1) return; endOfCurSeg++; } else if (m_roads[checkNdx].m_pt2.loc == loc2) { -#ifdef _DEBUG +#ifdef RTS_DEBUG if (m_roads[checkNdx].m_pt2.count!=1) { ::OutputDebugString("fooey.\n"); } @@ -1465,14 +1465,14 @@ void W3DRoadBuffer::checkLinkAfter(Int ndx) } Vector2 loc1 = m_roads[ndx].m_pt1.loc; -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[ndx].m_pt2.loc == m_roads[ndx-1].m_pt1.loc, ("Bad link\n")); #endif Int checkNdx = ndx+1; while (checkNdx < m_numRoads && ndx < m_numRoads-1) { if (m_roads[checkNdx].m_pt2.loc == loc1) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[checkNdx].m_pt2.count==1, ("Bad count\n")); #endif ndx++; @@ -1480,7 +1480,7 @@ void W3DRoadBuffer::checkLinkAfter(Int ndx) loc1 = m_roads[ndx].m_pt1.loc; if (m_roads[ndx].m_pt1.count != 1) return; } else if (m_roads[checkNdx].m_pt1.loc == loc1) { -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(m_roads[checkNdx].m_pt1.count==1, ("Wrong m_pt1.count.\n")); if ( m_roads[checkNdx].m_pt1.count!=1) { ::OutputDebugString("Wrong m_pt1.count.\n"); @@ -1603,7 +1603,7 @@ void W3DRoadBuffer::addMapObjects() } if (pMapObj->getFlag(FLAG_ROAD_POINT1)) { pMapObj2 = pMapObj->getNext(); -#ifdef _DEBUG +#ifdef RTS_DEBUG DEBUG_ASSERTLOG(pMapObj2 && pMapObj2->getFlag(FLAG_ROAD_POINT2), ("Bad Flag\n")); #endif if (pMapObj2==NULL) break; @@ -3343,7 +3343,7 @@ void W3DRoadBuffer::drawRoads(CameraClass * camera, TextureClass *cloudTexture, } else { m_roadTypes[i].applyTexture(); } - #ifdef _DEBUG + #ifdef RTS_DEBUG //DX8Wrapper::Set_Shader(detailShader); // shows clipping. #endif for (Int pass=0; pass < devicePasses; pass++) diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp index 315df93aef..95153b513e 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp @@ -64,7 +64,7 @@ #include "WW3D2/colorspace.h" #include "WW3D2/shdlib.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -105,7 +105,7 @@ RTS3DScene::RTS3DScene() m_scratchLight = NEW_REF( LightClass, (LightClass::DIRECTIONAL) ); // REF_PTR_SET(m_globalLight[lightIndex], pLight); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_shroudOn) m_shroudMaterialPass = NEW_REF(W3DShroudMaterialPassClass,()); else @@ -790,7 +790,7 @@ void RTS3DScene::renderOneObject(RenderInfoClass &rinfo, RenderObjClass *robj, I if (drawInfo) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (!TheGlobalData->m_shroudOn) ss = OBJECTSHROUD_CLEAR; #endif @@ -1173,16 +1173,6 @@ void RTS3DScene::Customized_Render( RenderInfoClass &rinfo ) renderOneObject(rinfo, robj, localPlayerIndex); } } - -#ifdef INCLUDE_GRANNY_IN_BUILD - if (TheGrannyRenderObjSystem) - { //we only want to update granny animations once per frame, so only queue - //them up if this is not a mirror pass. - if (!ShaderClass::Is_Backface_Culling_Inverted()) - TheGrannyRenderObjSystem->queueUpdate(); - TheGrannyRenderObjSystem->Flush(); - } -#endif //Tell shadow manager to render shadows at the end of this frame //Don't draw shadows if there is no terrain present. diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp index 862d7ae22b..db70397bc3 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp @@ -75,7 +75,7 @@ #include "Common/GameLOD.h" #include "benchmark.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -1218,7 +1218,7 @@ Int ShroudTextureShader::set(Int stage) if (stage == 0) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaSpriteShader); else diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp index 7ae8ca361b..d250b5f27c 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShroud.cpp @@ -42,7 +42,7 @@ #include "Common/GlobalData.h" #include "GameLogic/PartitionManager.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -160,7 +160,7 @@ void W3DShroud::init(WorldHeightMap *pMap, Real worldCellSizeX, Real worldCellSi memset(m_finalFogData,0,srcWidth*srcHeight); #endif -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) m_pSrcTexture = DX8Wrapper::_Create_DX8_Surface(srcWidth,srcHeight, WW3D_FORMAT_A4R4G4B4); else @@ -184,7 +184,7 @@ void W3DShroud::init(WorldHeightMap *pMap, Real worldCellSizeX, Real worldCellSi //clear entire texture to black memset(m_srcTextureData,0,m_srcTexturePitch*srcHeight); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) fillShroudData(TheGlobalData->m_shroudAlpha); //initialize shroud to a known value #endif @@ -238,7 +238,7 @@ Bool W3DShroud::ReAcquireResources(void) // Create destination texture (stored in video memory). // Since we control the video memory copy, we can do partial updates more efficiently. Or do shift blits. -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) m_pDstTexture = MSGNEW("TextureClass") TextureClass(m_dstTextureWidth,m_dstTextureHeight,WW3D_FORMAT_A4R4G4B4,MIP_LEVELS_1, TextureClass::POOL_DEFAULT); else @@ -270,7 +270,7 @@ W3DShroudLevel W3DShroud::getShroudLevel(Int x, Int y) { UnsignedShort pixel=*(UnsignedShort *)((Byte *)m_srcTextureData + x*2 + y*m_srcTexturePitch); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) //in this mode, alpha channel holds intensity return (W3DShroudLevel)((1.0f-((Real)(pixel >> 12)/15.0f))*255.0f); @@ -295,7 +295,7 @@ void W3DShroud::setShroudLevel(Int x, Int y, W3DShroudLevel level, Bool textureO if (level < TheGlobalData->m_shroudAlpha) level = TheGlobalData->m_shroudAlpha; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn) { ///@todo: optimize this case if we end up using fog shroud. @@ -360,7 +360,7 @@ void W3DShroud::fillShroudData(W3DShroudLevel level) if (level < TheGlobalData->m_shroudAlpha) level = TheGlobalData->m_shroudAlpha; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //convert value to pixel format if (TheGlobalData && TheGlobalData->m_fogOfWarOn) { @@ -423,7 +423,7 @@ void W3DShroud::fillBorderShroudData(W3DShroudLevel level, SurfaceClass* pDestSu if (level < TheGlobalData->m_shroudAlpha) level = TheGlobalData->m_shroudAlpha; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) //convert value to pixel format if (TheGlobalData && TheGlobalData->m_fogOfWarOn) { @@ -531,7 +531,7 @@ void W3DShroud::render(CameraClass *cam) if (DX8Wrapper::_Get_D3D_Device8() && (DX8Wrapper::_Get_D3D_Device8()->TestCooperativeLevel()) != D3D_OK) return; //device not ready to render anything -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData && TheGlobalData->m_fogOfWarOn != m_drawFogOfWar) { //fog state has changed since last time shroud system was initialized @@ -591,7 +591,7 @@ void W3DShroud::render(CameraClass *cam) { for (Int x=0; xm_fogOfWarOn) { dataDest[x]=((TheGlobalData->m_shroudColor.getAsInt()>>4)&0xf) | (((TheGlobalData->m_shroudColor.getAsInt()>>12)&0xf)<<4) | (((TheGlobalData->m_shroudColor.getAsInt()>>20)&0xf)<<8) | ((((255-(dataSrc[x] & 0xff))>>4)&0xf)<<12); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp index 99b5b67ba1..819efc37a4 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSmudge.cpp @@ -41,7 +41,7 @@ #include "WW3D2/camera.h" #include "WW3D2/sortingrenderer.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp index 644d9fa114..55ee8317ce 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DSnow.cpp @@ -27,7 +27,7 @@ #include "WW3D2/assetmgr.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp index c876a684f9..a680cc9c80 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainBackground.cpp @@ -59,7 +59,7 @@ #include "WW3D2/dx8renderer.h" #include "WW3D2/camera.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp index 00b19f1275..83f44e0b60 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp @@ -60,7 +60,7 @@ #include "GameLogic/Object.h" #include "GameClient/Drawable.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp index ec2be7658e..0204f68aae 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp @@ -197,14 +197,6 @@ W3DTerrainVisual::~W3DTerrainVisual() TheTerrainTracksRenderObjClassSystem=NULL; } -#ifdef INCLUDE_GRANNY_IN_BUILD - if (TheGrannyRenderObjSystem) - { - delete TheGrannyRenderObjSystem; - TheGrannyRenderObjSystem=NULL; - } -#endif - if (TheW3DShadowManager) { delete TheW3DShadowManager; @@ -244,11 +236,6 @@ void W3DTerrainVisual::init( void ) TheTerrainTracksRenderObjClassSystem = NEW TerrainTracksRenderObjClassSystem; TheTerrainTracksRenderObjClassSystem->init(W3DDisplay::m_3DScene); -#ifdef INCLUDE_GRANNY_IN_BUILD - // initialize Granny model drawing system - TheGrannyRenderObjSystem = NEW GrannyRenderObjSystem; -#endif - // initialize object shadow drawing system TheW3DShadowManager = NEW W3DShadowManager; TheW3DShadowManager->init(); @@ -670,7 +657,7 @@ Bool W3DTerrainVisual::load( AsciiString filename ) // add our terrain render object to the scene W3DDisplay::m_3DScene->Add_Render_Object( m_terrainRenderObject ); -#if defined _DEBUG || defined _INTERNAL +#if defined RTS_DEBUG || defined RTS_INTERNAL // Icon drawing utility object for pathfinding. W3DDebugIcons *icons = NEW W3DDebugIcons; W3DDisplay::m_3DScene->Add_Render_Object( icons ); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp index 445032a157..cd6f25f14b 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp @@ -88,7 +88,7 @@ enum #include "WW3D2/meshmdl.h" #include "d3dx8tex.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -146,7 +146,7 @@ int W3DTreeBuffer::W3DTreeTextureClass::update(W3DTreeBuffer *buffer) Int tilePixelExtent = TILE_PIXEL_EXTENT; // Int numRows = surface_desc.Height/(tilePixelExtent+TILE_OFFSET); -#ifdef _DEBUG +#ifdef RTS_DEBUG //DASSERT_MSG(tilesPerRow*numRows >= htMap->m_numBitmapTiles,Debug::Format ("Too many tiles.")); //DEBUG_ASSERTCRASH((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow, ("Bitmap too small.")); #endif diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp index 906ebb2c1a..ac7bbe9792 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp @@ -96,7 +96,7 @@ #include "WinMain.h" /** @todo Remove this, it's only here because we are using timeGetTime, but we can remove that when we have our own timer */ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -585,7 +585,7 @@ void W3DView::setCameraTransform( void ) } m_3DCamera->Set_Clip_Planes(nearZ, farZ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if (TheGlobalData->m_useCameraConstraints) #endif { @@ -608,7 +608,7 @@ void W3DView::setCameraTransform( void ) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_3DCamera->Set_View_Plane( m_FOV, -1 ); #endif @@ -726,7 +726,7 @@ static void drawTerrainNormal( Drawable *draw, void *userData ) } } -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // ------------------------------------------------------------------------------------------------ // Draw a crude circle. Appears on top of any world geometry // ------------------------------------------------------------------------------------------------ @@ -992,7 +992,7 @@ static void drawablePostDraw( Drawable *draw, void *userData ) Object* obj = draw->getObject(); Int localPlayerIndex = ThePlayerList ? ThePlayerList->getLocalPlayer()->getPlayerIndex() : 0; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ObjectShroudStatus ss = (!obj || !TheGlobalData->m_shroudOn) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); #else ObjectShroudStatus ss = (!obj) ? OBJECTSHROUD_CLEAR : obj->getShroudedStatus(localPlayerIndex); @@ -1010,7 +1010,7 @@ static void drawablePostDraw( Drawable *draw, void *userData ) draw->drawIconUI(); //} -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // debug collision extents if( TheGlobalData->m_showCollisionExtents ) drawDrawableExtents( draw, userData ); @@ -1687,7 +1687,7 @@ void W3DView::draw( void ) } // end if, show debug AI -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) if( TheGlobalData->m_debugCamera ) { UnsignedInt c = 0xaaffffff; @@ -2006,7 +2006,7 @@ void W3DView::setFieldOfView( Real angle ) { View::setFieldOfView( angle ); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // this is only for testing, and recalculating the // camera every frame is wasteful setCameraTransform(); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp index d7e9c4731f..1bd414c0d0 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3dWaypointBuffer.cpp @@ -86,7 +86,7 @@ -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp index 3858f4b11e..54d42e58e5 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp @@ -66,7 +66,7 @@ #include "W3DDevice/GameClient/W3DCustomScene.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp index fd73bd0160..56c560560b 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp @@ -54,7 +54,7 @@ #include "Common/file.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp index 0af9735af9..8dd1de1519 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp @@ -50,7 +50,7 @@ #include "WW3D2/matinfo.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp index 8682b13c2d..f174eb245b 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DTerrainLogic.cpp @@ -41,7 +41,7 @@ #include "GameLogic/AI.h" #include "GameLogic/AIPathfind.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp index 87843cdebc..8ba95f2adb 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32BIGFileSystem.cpp @@ -26,7 +26,6 @@ // Bryan Cleveland, August 2002 ///////////////////////////////////////////////////////////// -#include #include "Common/AudioAffect.h" #include "Common/ArchiveFile.h" #include "Common/ArchiveFileSystem.h" @@ -37,8 +36,9 @@ #include "Win32Device/Common/Win32BIGFile.h" #include "Win32Device/Common/Win32BIGFileSystem.h" #include "Common/Registry.h" +#include "Utility/endian_compat.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -64,7 +64,7 @@ void Win32BIGFileSystem::init() { AsciiString installPath; GetStringFromGeneralsRegistry("", "InstallPath", installPath ); //@todo this will need to be ramped up to a crash for release -#ifndef _INTERNAL +#ifndef RTS_INTERNAL // had to make this non-internal only, otherwise we can't autobuild // GeneralsZH... DEBUG_ASSERTCRASH(installPath != "", ("Be 1337! Go install Generals!")); @@ -90,8 +90,6 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { Int archiveFileSize = 0; Int numLittleFiles = 0; - ArchiveFile *archiveFile = NEW Win32BIGFile; - DEBUG_LOG(("Win32BIGFileSystem::openArchiveFile - opening BIG file %s\n", filename)); if (fp == NULL) { @@ -120,7 +118,7 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { // read in the number of files contained in this BIG file. // change the order of the bytes cause the file size is in reverse byte order for some reason. fp->read(&numLittleFiles, 4); - numLittleFiles = ntohl(numLittleFiles); + numLittleFiles = betoh(numLittleFiles); DEBUG_LOG(("Win32BIGFileSystem::openArchiveFile - %d are contained in archive\n", numLittleFiles)); // for (Int i = 0; i < 2; ++i) { @@ -133,6 +131,8 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { fp->seek(0x10, File::START); // read in each directory listing. ArchivedFileInfo *fileInfo = NEW ArchivedFileInfo; + // TheSuperHackers @fix Mauller 23/04/2025 Create new file handle when necessary to prevent memory leak + ArchiveFile *archiveFile = NEW Win32BIGFile; for (Int i = 0; i < numLittleFiles; ++i) { Int filesize = 0; @@ -140,8 +140,8 @@ ArchiveFile * Win32BIGFileSystem::openArchiveFile(const Char *filename) { fp->read(&fileOffset, 4); fp->read(&filesize, 4); - filesize = ntohl(filesize); - fileOffset = ntohl(fileOffset); + filesize = betoh(filesize); + fileOffset = betoh(fileOffset); fileInfo->m_archiveFilename = archiveFileName; fileInfo->m_offset = fileOffset; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp index 19b78e8770..e1f00f7334 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32LocalFileSystem.cpp @@ -45,7 +45,6 @@ Win32LocalFileSystem::~Win32LocalFileSystem() { File * Win32LocalFileSystem::openFile(const Char *filename, Int access /* = 0 */) { //USE_PERF_TIMER(Win32LocalFileSystem_openFile) - Win32LocalFile *file = newInstance( Win32LocalFile ); // sanity check if (strlen(filename) <= 0) { @@ -69,6 +68,9 @@ File * Win32LocalFileSystem::openFile(const Char *filename, Int access /* = 0 */ } } + // TheSuperHackers @fix Mauller 21/04/2025 Create new file handle when necessary to prevent memory leak + Win32LocalFile *file = newInstance( Win32LocalFile ); + if (file->open(filename, access) == FALSE) { file->close(); file->deleteInstance(); diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp index 7cf7edc55d..811d8c8847 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32OSDisplay.cpp @@ -37,7 +37,7 @@ #include "Common/UnicodeString.h" #include "GameClient/GameText.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") #endif diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp index a3f95d7641..6611376deb 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32DIKeyboard.cpp @@ -49,37 +49,37 @@ struct ErrorLookup }; static ErrorLookup errorLookup[] = { -{ DIERR_ACQUIRED, "DIERR_ACQUIRED" }, -{ DIERR_ALREADYINITIALIZED, "DIERR_ALREADYINITIALIZED" }, -{ DIERR_BADDRIVERVER, "DIERR_BADDRIVERVER" }, -{ DIERR_BETADIRECTINPUTVERSION, "DIERR_BETADIRECTINPUTVERSION" }, -{ DIERR_DEVICEFULL, "DIERR_DEVICEFULL" }, -{ DIERR_DEVICENOTREG, "DIERR_DEVICENOTREG" }, -{ DIERR_EFFECTPLAYING, "DIERR_EFFECTPLAYING" }, -{ DIERR_GENERIC, "DIERR_GENERIC" }, -{ DIERR_HANDLEEXISTS, "DIERR_HANDLEEXISTS" }, -{ DIERR_HASEFFECTS, "DIERR_HASEFFECTS" }, -{ DIERR_INCOMPLETEEFFECT, "DIERR_INCOMPLETEEFFECT" }, -{ DIERR_INPUTLOST, "DIERR_INPUTLOST" }, -{ DIERR_INVALIDPARAM, "DIERR_INVALIDPARAM" }, -{ DIERR_MAPFILEFAIL, "DIERR_MAPFILEFAIL" }, -{ DIERR_MOREDATA, "DIERR_MOREDATA" }, -{ DIERR_NOAGGREGATION, "DIERR_NOAGGREGATION" }, -{ DIERR_NOINTERFACE, "DIERR_NOINTERFACE" }, -{ DIERR_NOTACQUIRED, "DIERR_NOTACQUIRED" }, -{ DIERR_NOTBUFFERED, "DIERR_NOTBUFFERED" }, -{ DIERR_NOTDOWNLOADED, "DIERR_NOTDOWNLOADED" }, -{ DIERR_NOTEXCLUSIVEACQUIRED, "DIERR_NOTEXCLUSIVEACQUIRED" }, -{ DIERR_NOTFOUND, "DIERR_NOTFOUND" }, -{ DIERR_NOTINITIALIZED, "DIERR_NOTINITIALIZED" }, -{ DIERR_OBJECTNOTFOUND, "DIERR_OBJECTNOTFOUND" }, -{ DIERR_OLDDIRECTINPUTVERSION, "DIERR_OLDDIRECTINPUTVERSION" }, -{ DIERR_OTHERAPPHASPRIO, "DIERR_OTHERAPPHASPRIO" }, -{ DIERR_OUTOFMEMORY, "DIERR_OUTOFMEMORY" }, -{ DIERR_READONLY, "DIERR_READONLY" }, -{ DIERR_REPORTFULL, "DIERR_REPORTFULL" }, -{ DIERR_UNPLUGGED, "DIERR_UNPLUGGED" }, -{ DIERR_UNSUPPORTED, "DIERR_UNSUPPORTED" }, +{ (HRESULT)DIERR_ACQUIRED, "DIERR_ACQUIRED" }, +{ (HRESULT)DIERR_ALREADYINITIALIZED, "DIERR_ALREADYINITIALIZED" }, +{ (HRESULT)DIERR_BADDRIVERVER, "DIERR_BADDRIVERVER" }, +{ (HRESULT)DIERR_BETADIRECTINPUTVERSION, "DIERR_BETADIRECTINPUTVERSION" }, +{ (HRESULT)DIERR_DEVICEFULL, "DIERR_DEVICEFULL" }, +{ (HRESULT)DIERR_DEVICENOTREG, "DIERR_DEVICENOTREG" }, +{ (HRESULT)DIERR_EFFECTPLAYING, "DIERR_EFFECTPLAYING" }, +{ (HRESULT)DIERR_GENERIC, "DIERR_GENERIC" }, +{ (HRESULT)DIERR_HANDLEEXISTS, "DIERR_HANDLEEXISTS" }, +{ (HRESULT)DIERR_HASEFFECTS, "DIERR_HASEFFECTS" }, +{ (HRESULT)DIERR_INCOMPLETEEFFECT, "DIERR_INCOMPLETEEFFECT" }, +{ (HRESULT)DIERR_INPUTLOST, "DIERR_INPUTLOST" }, +{ (HRESULT)DIERR_INVALIDPARAM, "DIERR_INVALIDPARAM" }, +{ (HRESULT)DIERR_MAPFILEFAIL, "DIERR_MAPFILEFAIL" }, +{ (HRESULT)DIERR_MOREDATA, "DIERR_MOREDATA" }, +{ (HRESULT)DIERR_NOAGGREGATION, "DIERR_NOAGGREGATION" }, +{ (HRESULT)DIERR_NOINTERFACE, "DIERR_NOINTERFACE" }, +{ (HRESULT)DIERR_NOTACQUIRED, "DIERR_NOTACQUIRED" }, +{ (HRESULT)DIERR_NOTBUFFERED, "DIERR_NOTBUFFERED" }, +{ (HRESULT)DIERR_NOTDOWNLOADED, "DIERR_NOTDOWNLOADED" }, +{ (HRESULT)DIERR_NOTEXCLUSIVEACQUIRED, "DIERR_NOTEXCLUSIVEACQUIRED" }, +{ (HRESULT)DIERR_NOTFOUND, "DIERR_NOTFOUND" }, +{ (HRESULT)DIERR_NOTINITIALIZED, "DIERR_NOTINITIALIZED" }, +{ (HRESULT)DIERR_OBJECTNOTFOUND, "DIERR_OBJECTNOTFOUND" }, +{ (HRESULT)DIERR_OLDDIRECTINPUTVERSION, "DIERR_OLDDIRECTINPUTVERSION" }, +{ (HRESULT)DIERR_OTHERAPPHASPRIO, "DIERR_OTHERAPPHASPRIO" }, +{ (HRESULT)DIERR_OUTOFMEMORY, "DIERR_OUTOFMEMORY" }, +{ (HRESULT)DIERR_READONLY, "DIERR_READONLY" }, +{ (HRESULT)DIERR_REPORTFULL, "DIERR_REPORTFULL" }, +{ (HRESULT)DIERR_UNPLUGGED, "DIERR_UNPLUGGED" }, +{ (HRESULT)DIERR_UNSUPPORTED, "DIERR_UNSUPPORTED" }, { 0, NULL } }; diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp index 87bf13a05b..5a5c91cd7a 100644 --- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp +++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/GameClient/Win32Mouse.cpp @@ -37,7 +37,7 @@ #include "Win32Device/GameClient/Win32Mouse.h" #include "WinMain.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Libraries/CMakeLists.txt b/GeneralsMD/Code/Libraries/CMakeLists.txt index 175b35d827..7021b720f4 100644 --- a/GeneralsMD/Code/Libraries/CMakeLists.txt +++ b/GeneralsMD/Code/Libraries/CMakeLists.txt @@ -1,8 +1,2 @@ # WW common libraries decended from earliest C&C games add_subdirectory(Source/WWVegas) - -# profiling library -add_subdirectory(Source/profile) - -# debugging library -add_subdirectory(Source/debug) diff --git a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h index d48c714115..f06481c775 100644 --- a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h +++ b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h @@ -406,4 +406,9 @@ struct RGBAColorInt }; +// Modulo function working with negative values, required for angles +inline Real nmod(Real x, Real y) { + return fmod(fmod(x, y) + y, y); +} + #endif // _BASE_TYPE_H_ diff --git a/GeneralsMD/Code/Libraries/Source/Benchmark/benchmark.h b/GeneralsMD/Code/Libraries/Source/Benchmark/benchmark.h deleted file mode 100644 index 75006be40c..0000000000 --- a/GeneralsMD/Code/Libraries/Source/Benchmark/benchmark.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -** Command & Conquer Generals(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#pragma once - -#ifndef __BENCHMARK_H__ -#define __BENCHMARK_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -int RunBenchmark(int argc, char *argv[], float *floatResult, float *intResult, float *memResult); - -#ifdef __cplusplus -} -#endif - -#endif \ No newline at end of file diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/CMakeLists.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/CMakeLists.txt index 11dafc467f..427c2c4512 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/CMakeLists.txt +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/CMakeLists.txt @@ -1,33 +1,21 @@ # Interface libraries to set common defines and includes, avoid duplication later add_library(z_wwcommon INTERFACE) -target_compile_definitions(z_wwcommon INTERFACE - #NOMINMAX - WIN32_LEAN_AND_MEAN -) - target_link_libraries(z_wwcommon INTERFACE - d3d8lib core_config core_utility core_wwcommon + d3d8lib milesstub stlport ) target_include_directories(z_wwcommon INTERFACE - . + ${CMAKE_CURRENT_SOURCE_DIR} WW3D2 - WWAudio - WWMath - WWSaveLoad - Wwutil ) add_subdirectory(WWAudio) -add_subdirectory(WWMath) -add_subdirectory(Wwutil) -add_subdirectory(WWSaveLoad) add_subdirectory(WW3D2) add_subdirectory(WWDownload) @@ -35,19 +23,12 @@ add_subdirectory(WWDownload) add_library(z_wwvegas INTERFACE) target_include_directories(z_wwvegas INTERFACE - . + ${CMAKE_CURRENT_SOURCE_DIR} WW3D2 - WWDownload - WWMath - WWSaveLoad - Wwutil ) target_link_libraries(z_wwvegas INTERFACE core_wwvegas z_ww3d2 z_wwdownload - z_wwmath - z_wwsaveload - z_wwutil ) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt index 4973d7c73c..b1a9848837 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/CMakeLists.txt @@ -1,58 +1,57 @@ -# Set source files set(WW3D2_SRC - aabtree.cpp - aabtree.h + #aabtree.cpp + #aabtree.h aabtreebuilder.cpp aabtreebuilder.h - agg_def.cpp - agg_def.h - animatedsoundmgr.cpp - animatedsoundmgr.h + #agg_def.cpp + #agg_def.h + #animatedsoundmgr.cpp + #animatedsoundmgr.h animobj.cpp animobj.h assetmgr.cpp assetmgr.h - assetstatus.cpp - assetstatus.h - bitmaphandler.cpp - bitmaphandler.h + #assetstatus.cpp + #assetstatus.h + #bitmaphandler.cpp + #bitmaphandler.h bmp2d.cpp bmp2d.h boxrobj.cpp boxrobj.h - bwrender.cpp - bwrender.h + #bwrender.cpp + #bwrender.h camera.cpp camera.h #classid.h - collect.cpp - collect.h - colorspace.h - coltest.cpp - coltest.h - coltype.h - composite.cpp - composite.h + #collect.cpp + #collect.h + #colorspace.h + #coltest.cpp + #coltest.h + #coltype.h + #composite.cpp + #composite.h dazzle.cpp dazzle.h ddsfile.cpp ddsfile.h decalmsh.cpp decalmsh.h - decalsys.cpp - decalsys.h - distlod.cpp - distlod.h - dllist.h + #decalsys.cpp + #decalsys.h + #distlod.cpp + #distlod.h + #dllist.h dx8caps.cpp dx8caps.h dx8fvf.cpp dx8fvf.h dx8indexbuffer.cpp dx8indexbuffer.h - dx8list.h - dx8polygonrenderer.cpp - dx8polygonrenderer.h + #dx8list.h + #dx8polygonrenderer.cpp + #dx8polygonrenderer.h dx8renderer.cpp dx8renderer.h dx8rendererdebugger.cpp @@ -61,54 +60,54 @@ set(WW3D2_SRC dx8texman.h dx8vertexbuffer.cpp dx8vertexbuffer.h - dx8webbrowser.cpp - dx8webbrowser.h + #dx8webbrowser.cpp + #dx8webbrowser.h dx8wrapper.cpp dx8wrapper.h - dynamesh.cpp - dynamesh.h - font3d.cpp - font3d.h - formconv.cpp - formconv.h - FramGrab.cpp - framgrab.h - hanim.cpp - hanim.h + #dynamesh.cpp + #dynamesh.h + #font3d.cpp + #font3d.h + #formconv.cpp + #formconv.h + #FramGrab.cpp + #framgrab.h + #hanim.cpp + #hanim.h hanimmgr.cpp hanimmgr.h - hcanim.cpp - hcanim.h + #hcanim.cpp + #hcanim.h hlod.cpp hlod.h - hmdldef.cpp - hmdldef.H + #hmdldef.cpp + #hmdldef.H hmorphanim.cpp hmorphanim.h hrawanim.cpp hrawanim.h - htree.cpp - htree.h + #htree.cpp + #htree.h htreemgr.cpp htreemgr.h - intersec.cpp - intersec.h - intersec.inl - inttest.h - layer.cpp - layer.h + #intersec.cpp + #intersec.h + #intersec.inl + #inttest.h + #layer.cpp + #layer.h light.cpp light.h lightenvironment.cpp lightenvironment.h - line3d.cpp - line3d.h + #line3d.cpp + #line3d.h linegrp.cpp linegrp.h mapper.cpp mapper.h - matinfo.cpp - matinfo.h + #matinfo.cpp + #matinfo.h matpass.cpp matpass.h matrixmapper.cpp @@ -117,8 +116,8 @@ set(WW3D2_SRC mesh.h meshbuild.cpp meshbuild.h - meshdam.cpp - meshdam.h + #meshdam.cpp + #meshdam.h meshgeometry.cpp meshgeometry.h meshmatdesc.cpp @@ -126,10 +125,10 @@ set(WW3D2_SRC meshmdl.cpp meshmdl.h meshmdlio.cpp - metalmap.cpp - metalmap.h - missingtexture.cpp - missingtexture.h + #metalmap.cpp + #metalmap.h + #missingtexture.cpp + #missingtexture.h motchan.cpp motchan.h nullrobj.cpp @@ -140,71 +139,71 @@ set(WW3D2_SRC part_emt.h part_ldr.cpp part_ldr.h - pivot.cpp - pivot.h - pointgr.cpp - pointgr.h - polyinfo.cpp - polyinfo.h - predlod.cpp - predlod.h - prim_anim.cpp - prim_anim.h - projector.cpp - projector.h - proto.cpp - proto.h - proxy.h - rddesc.h + #pivot.cpp + #pivot.h + #pointgr.cpp + #pointgr.h + #polyinfo.cpp + #polyinfo.h + #predlod.cpp + #predlod.h + #prim_anim.cpp + #prim_anim.h + #projector.cpp + #projector.h + #proto.cpp + #proto.h + #proxy.h + #rddesc.h render2d.cpp render2d.h - render2dsentence.cpp - render2dsentence.h - renderobjectrecycler.cpp - renderobjectrecycler.h - rendobj.cpp - rendobj.h + #render2dsentence.cpp + #render2dsentence.h + #renderobjectrecycler.cpp + #renderobjectrecycler.h + #rendobj.cpp + #rendobj.h rinfo.cpp rinfo.h - ringobj.cpp - ringobj.h - robjlist.h + #ringobj.cpp + #ringobj.h + #robjlist.h scene.cpp scene.h - segline.cpp - segline.h - seglinerenderer.cpp - seglinerenderer.h + #segline.cpp + #segline.h + #seglinerenderer.cpp + #seglinerenderer.h shader.cpp shader.h - shattersystem.cpp - shattersystem.h + #shattersystem.cpp + #shattersystem.h shdlib.h - snappts.cpp - snapPts.h + #snappts.cpp + #snapPts.h sortingrenderer.cpp sortingrenderer.h - soundlibrarybridge.h - soundrobj.cpp - soundrobj.h - sphereobj.cpp - sphereobj.h - static_sort_list.cpp - static_sort_list.h - statistics.cpp - statistics.h - streak.cpp - streak.h - streakRender.cpp - streakRender.h - stripoptimizer.cpp - stripoptimizer.h - surfaceclass.cpp - surfaceclass.h + #soundlibrarybridge.h + #soundrobj.cpp + #soundrobj.h + #sphereobj.cpp + #sphereobj.h + #static_sort_list.cpp + #static_sort_list.h + #statistics.cpp + #statistics.h + #streak.cpp + #streak.h + #streakRender.cpp + #streakRender.h + #stripoptimizer.cpp + #stripoptimizer.h + #surfaceclass.cpp + #surfaceclass.h texproject.cpp texproject.h #textdraw.cpp - textdraw.h + #textdraw.h texture.cpp texture.h texturefilter.cpp @@ -215,38 +214,31 @@ set(WW3D2_SRC texturethumbnail.h vertmaterial.cpp vertmaterial.h - visrasterizer.cpp - visrasterizer.h - w3d_dep.cpp - w3d_dep.h + #visrasterizer.cpp + #visrasterizer.h + #w3d_dep.cpp + #w3d_dep.h w3d_file.h - w3d_obsolete.h - w3d_util.cpp - w3d_util.h - w3derr.h - w3dexclusionlist.cpp - w3dexclusionlist.h + #w3d_obsolete.h + #w3d_util.cpp + #w3d_util.h + #w3derr.h + #w3dexclusionlist.cpp + #w3dexclusionlist.h ww3d.cpp ww3d.h - ww3dformat.cpp - ww3dformat.h - ww3dids.h - ww3dtrig.h + #ww3dformat.cpp + #ww3dformat.h + #ww3dids.h + #ww3dtrig.h ) -# Targets to build. add_library(z_ww3d2 STATIC) set_target_properties(z_ww3d2 PROPERTIES OUTPUT_NAME ww3d2) target_sources(z_ww3d2 PRIVATE ${WW3D2_SRC}) -if (NOT IS_VS6_BUILD) - target_link_libraries(z_ww3d2 PUBLIC - comsuppw - ) -endif() - target_link_libraries(z_ww3d2 PRIVATE - core_browserengine + corei_ww3d2 z_wwcommon ) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt deleted file mode 100644 index c4cf6aca72..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8 Rationalizations.txt +++ /dev/null @@ -1,25 +0,0 @@ -This document is going to be a place to put descriptions of our reasoning for any "confusing" design decisions made during the conversion to DX8. - -TODO: WRITE PROPER DESCRIPTIONS FOR ALL OF THE FOLLOWING!!! - -Lighting --------- -The user has two choices regarding lighting. SimpleSceneClass will just install the first four LightClasses -into DX8 and let them affect all objects. Otherwise, you need to implement a SceneClass which wraps each -top-level render object and associates a LightEnvironmentClass with it. In your 'Customized_Render' function -you need to update each object's LightEnvironment object from the lights around it. - -Mesh Rendering System ---------------------- -Grouped by FVF format and material settings. Many meshes can share a single VB and IB... - -MeshModel Sharing ------------------ -It would be nice if MeshClass just Add_Ref'd the same mesh model whenever we re-use a mesh. The problems with -this are: -- the transform which is used during deffered rendering and during decal rendering -- instance specific light environment pointer is in the mesh model class -- lots of other stuff <-- FILL THIS IN! - - - diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt deleted file mode 100644 index 31d3ab71d0..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8 Status.txt +++ /dev/null @@ -1,274 +0,0 @@ - - -Now we've got WW3D up and running with the skeleton app. Here is a somewhat more detailed/organized -list of what is left to do: - -LIMITATIONS/POTENTIAL PROBLEMS: -- Skins need to use a limited set of rendering features? -- Polys going into the alpha system must use a limited set of rendering features. -- Additional procedural material passes cannot be applied to alpha blended meshes (no multi-pass alpha) -- Meshes only get two vertex color arrays. Their vertex materials must be configured properly to enable them. -- HY: Simplescene supports only four global lights -- HY: WW3D Spoltlights have an approximate inverse linear attentuation instead of max linear attentuation - - -UPDATED TODO LIST: -agg_def: - - Texture replacement feature needs to be implemented -assetmgr: - - Texture cache, - - Dazzle loader, -bmp2d - - works. Code for setting aspect ratio was added but not used due to legacy - HY -boxrobj - - Alpha blending support needed - - Vis rendering code needed -camera - - *** CameraClass projection convention changed to -1Apply() and the state is being tracked by the shader class. -Materials have been converted to Material->Apply() which calls Mapper->Apply() - -Now, some big issues we need to think about are (in no particular order): - -SOME GOALS - Maintain as many existing class interfaces as we can so that our apps don't have much re-coding! - Input data is existing W3D files, no format changes or new tools! (for now anyway :-) - Incorporate the ideas in Jani's DX8 code, grouping small meshes together in larger VBs, etc - -GERD Replacement - our new low-level rendering interface needs to be the replacement for everywhere we are using the GERD. It needs to supply all of the features that we are using in the GERD currently while allowing us to use Jani's mesh optimizations. There is a lot to think about here and almost everything depends on us doing this right. It also might need to serve as an abstraction layer so that I can implement a software VIS-renderer behind it. -SOLUTION: No GERD replacement, no abstraction layer. DX8Wrapper will be a thin insulation layer though. - -VIS - I'll have to re-implement the rendering code for VIS. It will be a 32bit, solid fill, zbuffering software rasterizer. Not too hard but still a bit of work. Needs to be done in a way that all render objects can be rendered through it easily. -SOLUTION: Vis rendering will branch at the render object level to a new custom vis rasterizer possibly based on the bw shadow code - -TEXTURES - there are many features in the textures system, the "file cache", background loading, LOD, tga loading, global texture reduction factor, etc. -SOLUTION: Naty is working on this system. - -MESHMODEL - I think we'll need to do some load-time conversion of all of our mesh-models into a form similar to Jani's dx8 mesh code. More thought needs to be put into this. - -ALPHA SORTING - This issue becomes especially complex when you think about mixing different types of render objects. This issue will influence how we design the low level rendering interface. -SOLUTION: There will be a custom alpha sorting/rendering system. RenderObjects will be allowed to talk to either DX8 or this system. - -UNIX - It looks like Neal has put some effort into making ww3d compile under Unix. We will probably make life very difficult for him if there are DX8 calls all over the place :-) -SOLUTION: UNIX version of E&B will not use WW3D2. It only needs collision detection so we'll implement a custom solution. - - -Optimizations: -============== -* Currently we search a linear list for textures with the same name every time we ask -the asset manager for a new texture. We should probably use the hashtable template -for this instead. -* The VectorProcessorClass stuff is completely unoptimized - we might want to -optimize this in future. - - -********* NEW STUFF ************ -DX8 Features which we currently do not support and might want to in future: -* Different modes than clamp and wrap - DX8 exposes all kinds of cool modes like mirror, mirror once - do we expose these in our tools? How well are they supported in hardware? If they are not universally supported then we probably don't want to expose them... -* Cube and volume textures - support via inheriting from shared base class with TextureClass? -* Anisotropic filtering: currently trilinear is enabled in the TextureClass but not in our tools. There are issues to think about for both trilinear and anisotropic like: not all hardware supports it, some hardware supports it if there is just one texture but not otherwise, or with a slowdown etc. - this is probably not something we want the artist to specify directly: perhaps the artist can mark those meshes which would benefit from "advanced filtering", and we turn it on selectively depending on hardware? - -We can do fancy texture matrix operations "for free" now. (Only on Hardware T&L cards!) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt deleted file mode 100644 index 667390d83f..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/DX8ToolModifications.txt +++ /dev/null @@ -1,7 +0,0 @@ - -- Detect skins that are using materials that are too complex (max of two uv channels, one pass???) -- Remove Translucency from max plugin -- Editor has to resolve all of the cases where it is rendering to secondary windows -- VIS system needs a new z-buffering software renderer -- WWConfig needs to be updated -- Classic environment mapper and env mapper are the same thing now... diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT deleted file mode 100644 index 80736705e7..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/MAPPERS.TXT +++ /dev/null @@ -1,148 +0,0 @@ -MAPPER_NAME -Description: -What the mapper does -Params: -What to type in the argument space - = (type) -e.g. if it says -UPerSec=(float) 0.0; -it means you have to type in -UPerSec=1.0; -to get your U coordinate scrolling at one unit per second and it has to be a float. If you don't type anything the -default value is 0.0. - -Types: -(float) - any real number -(int) - any integer -(bool) - either TRUE or FALSE - - -LINEAR_OFFSET -Description: -Makes the texture scroll at the speed specified -Params: -UPerSec=(float) 0.0; -VPerSec=(float) 0.0; -UScale=(float) 1.0; -VScale=(float) 1.0; - -CLASSIC_ENVIRONMENT -Description: -Uses the Normals to look up the environment map - -ENVIRONMENT -Description: -Uses the Reflection direction to look up the environment map - -SCREEN -Description: -Projects takes the screen coordinate as the UV coordinate -Params: -UScale=(float) 1.0f; -VScale=(float) 1.0f; - -SILHOUETTE -Description: Obsolete, not supported - -SCALE -Description: -Scales the UV coordinates. Useful for detail mapping. -Params: -UScale=(float) 1.0f; -VScale=(float) 1.0f; - -GRID -Description: -Given a texture that is divided up in to a grid, it animates the texture by looking -up the texture from the topleft to the bottom right, going left to right and then -top to bottom (the same way you would read English text). The texture map must be divided -up evenly. -Params: -FPS=(float) 1.0f; The frames per second -Log2Width=(int) 1; So 0=width 1, 1=width 2, 2=width 4. The default means animate using a texture divided up into quarters. -Last=(int) GridWidth*GridWidth; The last frame to use - -ROTATE -Description: -Rotates a texture map counterclockwise about a specified center then scales the texture -Params: -Speed=(float) 0.1f; In Hertz. 1 = 1 rotate per second -UCenter=(float) 0.0f; -VCenter=(float) 0.0f; -UScale=(float) 1.0; -VScale=(float) 1.0; - -SINE_LINEAR_OFFSET -Description: -Moves the texture map in the shape of a Lissajous figure. -Params: -UAmp=(float) 1.0f; -UFreq=(float) 1.0f; -UPhase=(float) 0.0f; -VAmp=(float) 1.0f; -VFreq=(float) 1.0f; -VPhase=(float) 0.0f; - -STEP_LINEAR_OFFSET -Description: -Similar to Linear Offset but moves stuff around in discrete steps -Params: -UStep=(float) 0.0f; -VStep=(float) 0.0f; -SPS=(float) 0.0f; Steps per second - -ZIGZAG_LINEAR_OFFSET -Description: -Similar to Linear Offset but reverses direction periodically. -Params: -UPerSec=(float) 0.0f; -VPerSec=(float) 0.0f; -Period=(float) 0.0f; Time it takes to make a zigzag in seconds - -WS_CLASSIC_ENVIRONMENT -Description: -World space normal environment map - -WS_ENVIRONMENT -Description: -World space reflection environment map - -GRID_CLASSIC_ENVIRONMENT -Description: -Animated normal environment map - -GRID_ENVIRONMENT -Description: -Animated reflection environtment map - -RANDOM -Description: Randomly rotates and translates a texture with linear offset -FPS=(float) 0.0f; Frames per second -UPerSec=(float) 0.0; -VPerSec=(float) 0.0; - -EDGE -Description: Uses the Z-coordinate of the reflection or normal vector to access the U coordinate -The V-coordinate is linear offset -VPerSec=(float) 0.0 -UseReflect=FALSE -VStart=(float) 0.0 - -BUMPENV -Description: Sets up and possibly animates the bump matrix, also has the LinearOffset features -NOTE: even if you don't want to animate the bump matrix, you should use this mapper -so that the matrix gets set up with the identity settings. -BumpRotation = (float) 0.1f; In Hertz. 1 = 1 rotate per second (DEFAULT = 0.0) -BumpScale = scale factor applied to the bumps (DEFAULT = 1.0) -UPerSec=(float) 0.0; -VPerSec=(float) 0.0; -UScale=(float) 1.0; -VScale=(float) 1.0; - - ------------ -TODO: --the ability to affect the period of the zigzag in only one direction (V) while the other (U) continues to offset undisturbed in the original linear fashion. --groovy scaling --scale random --random mapper random time \ No newline at end of file diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt deleted file mode 100644 index a32b04ea68..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RenderObjectGuide.txt +++ /dev/null @@ -1,25 +0,0 @@ -HY 2/14/01 Created. - -Polygons are rendered via: -A. The Mesh packet renderer -B. Render object's render method -C. Alpha sorting pipeline - -NB. Shaders and Vertex Mateirals have presets that you can use to set state - -Guidelines for B type polygons: - -1. Always set the World matrix -2. Always use a Shader (Shader.Apply()) -3. Always use a VertexMaterial (VertexMaterial.Apply()) -4. If there is a Texture, use Texture.Apply() - -For any other render state, save the initial state, set your state, render then -restore the original state. - -e.g. save the VIEW matrix if you're nuking it, then restore it after you're done. - -Guidelines for C type polygons: - -1. All vertices submitted must be in View Coordinates -2. All states submitted must be entirely contained in Shader,VertexMaterial & Texture \ No newline at end of file diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga deleted file mode 100644 index 7cd0b7a2cf..0000000000 Binary files a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/AddProjectorGradient.tga and /dev/null differ diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI deleted file mode 100644 index 1b7afe4e28..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/Dazzle.INI +++ /dev/null @@ -1,161 +0,0 @@ -;--------------------------------------------------------------------------------------------------------------------- -; -; DAZZLE.INI - -; This file is a sample DAZZLE.INI file, indicating how to set up dazzles and lens -; flares for an application. PLEASE USE THIS FOR REFERENCE ONLY. You should consult the -; asset manager of your project in order to find the location of the actual DAZZLE.INI -; file that is specific to your project. -; -; PLEASE NOTE: some of the tools and library code assume that the dazzle type 'DEFAULT' -; exists and is the first dazzle type. -; -; -; DAZZLE DEFINITION PARAMETERS: -;------------------------------- -; After the dot product between the camera direction and the camera space location of the light source, -; we do a power to Halopow for the halo size and power to DazzlePow for the dazzle size. Halo/DazzleArea -; defines the angle where the values are valid, so any angle beyond HaloArea/DazzleArea results the halo or -; dazzle being scaled to zero. The angles are re-scaled from normalized angle scale of (-1.0...1.0) -; only HaloArea/DazzleArea defined part is used. -; -; HaloIntensityPow - 1.0 would be linear fadeout, smaller than that will steepen the curve (smaller hotspot) -; HaloSizePow - 1.0 would be linear fadeout, smaller than that will steepen the curve (smaller hotspot) -; DazzleIntensityPow -; DazzleSizePow -; HaloArea -; DazzleArea - Something like 0.05 is a good starting point for a dazzle... -; HaloScaleX - X scale factor for the halo -; HaloScaleY - Y scale factor for the halo -; DazzleScaleX - X scale factor for the dazzle -; DazzleScaleY - Y scale factor for the dazzle -; HaloIntensity - base intensity of the halo -; DazzleIntensity - base intensity of the dazzle -; -; Direction area defines the maximum difference between the light direction and the eyespace location, -; so the dazzle can only be seen if the camera is inside the light cone. Value 0.0 means dazzle is not -; directional, it can be seen from any direction. Halo is not affected. Dazzle direction defines the light -; direction vector. -; -; DazzleDirectionArea - Something like 0.5 might be a good test value -; DazzleDirection - direction vector (gth - we should lock this paramter to 0,0,1) -; FadeoutStart - distance in meters where the halo and dazzle start to fade out -; FadeoutEnd - distance in meters where the halo and dazzle are completely faded out -; SizeOptimizationLimit- NOT FINISHED -; HistoryWeight - The weight of history for the intensities. The history weight is per millisecond, -; so if you want to have any real history, values higher than 0.95 are recommended -; (don't use value of 1.0 or anything higher!) -; DazzleTextureName - texture filename for the dazzle -; HaloTextureName - texture filename for the halo -; UseCameraTranslation - If false, camera matrix's translation term isn't used. If translation isn't used -; the dazzle is treated as always visible, scene graph visibility is not used. -; HaloColor - color of the halo -; DazzleColor - color of the dazzle -; -; DazzleTestColor - Dazzle test color could be white in many cases but if the level has a lot of -; white then another color can be defined. -; LensflareName - Dazzle can use a lensflare by defining a name of lensflare in the ini -; -; -; LENSFLARE DEFINITION PARAMETERS: -;---------------------------------- -; -; TextureName - Texture to be used by the lensflare -; FlareCount - The number of flare sprites in lensflare. The FlareLocation, FlareSize and FlareColor -; paremeters are procedural, the names are produced based on this parameter. If -; FlareCount is 3, there exists FlareLocation1, FlareLocation2 and FlareLocation3... And so on. -; FlareLocation - 1D-locations of the flares. 0.0 means the location of the center of the screen and -; 1.0 means the location of the lightsource. The values can be smaller than zero and -; larger than 1.0. -; FlareSize - Normalized flare sizes -; FlareColor - Colors for each flare sprite -; FlareUV - Uv coordinates (as there can be only one texture used, but one may want multiple images). -; The values is a 4-float vector: start_u, start_v, end_u, end_v. -; -;--------------------------------------------------------------------------------------------------------------------- - - -[Dazzles_List] -0=DEFAULT -1=SUN - -[Lensflares_List] -0=SUN_LENSFLARE - - -;========================================== DAZZLE DEFINITIONS ==================== - -[DEFAULT] -HaloIntensity=1.0 -HaloIntensityPow=0.95 -HaloSizePow=0.95 -HaloArea=1.0 -HaloScaleX=0.2 -HaloScaleY=0.2 -DazzleArea=0.05 -DazzleDirectionArea=0 -DazzleDirection=0,1,1 -DazzleSizePow=0.9 -DazzleIntensityPow=0.9 -DazzleIntensity=50 -DazzleScaleX=1.0 -DazzleScaleY=1.0 -FadeoutStart=30.0 -FadeoutEnd=40.0 -SizeOptimizationLimit=0.05 -HistoryWeight=0.975 -UseCameraTranslation=1 -HaloTextureName=SunHalo.tga -DazzleTextureName=SunDazzle.tga -DazzleColor=1,1,1 -HaloColor=1,1,1 -DazzleTestColor=1,1,1 - -[SUN] -HaloSizePow=1.0 -HaloIntensityPow=1.0 -HaloArea=1.0 -HaloScaleX=0.25 -HaloScaleY=0.25 -DazzleArea=0.04 -DazzleDirectionArea=0 -DazzleDirection=0,1,1 -DazzleSizePow=1.0 -DazzleIntensityPow=1.0 -DazzleIntensity=1.0 -DazzleScaleX=4.0 -DazzleScaleY=4.0 -FadeoutStart=20.0 -FadeoutEnd=30.0 -SizeOptimizationLimit=0.05 -HistoryWeight=0.1 -UseCameraTranslation=0 -HaloTextureName=SunHalo.tga -DazzleTextureName=SunDazzle.tga -DazzleColor=1.0,1.0,1.0 -LensflareName=SUN_LENSFLARE - - -;========================================== LENSFLARE DEFINITIONS ================= - -[SUN_LENSFLARE] -TextureName=SunLensFlare.tga -FlareCount=6 -FlareLocation1=1.3 -FlareLocation2=0.4 -FlareLocation3=-0.1 -FlareLocation4=-0.6 -FlareLocation5=-0.9 -FlareLocation6=-1.2 -FlareSize1=0.06 -FlareSize2=0.04 -FlareSize3=0.03 -FlareSize4=0.15 -FlareSize5=0.20 -FlareSize6=0.30 -FlareUV1=0.000,0.000,0.118,0.238 -FlareUV2=0.134,0.048,0.204,0.190 -FlareUV3=0.228,0.079,0.276,0.175 -FlareUV4=0.000,0.619,0.165,1.000 -FlareUV5=0.181,0.365,0.488,1.000 -FlareUV6=0.496,0.000,1.000,1.000 diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga deleted file mode 100644 index 02e9f132ba..0000000000 Binary files a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/MultProjectorGradient.tga and /dev/null differ diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl deleted file mode 100644 index b6119c8fe5..0000000000 Binary files a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterAVel.tbl and /dev/null differ diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d deleted file mode 100644 index c5d41cd022..0000000000 Binary files a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterPlanes0.w3d and /dev/null differ diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl deleted file mode 100644 index 58368bc445..0000000000 Binary files a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/ShatterVel.tbl and /dev/null differ diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga deleted file mode 100644 index 974d3a232d..0000000000 Binary files a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/RequiredAssets/w3d_missing_texture.tga and /dev/null differ diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/State Management.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/State Management.txt deleted file mode 100644 index 67f5e84b6a..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/State Management.txt +++ /dev/null @@ -1,173 +0,0 @@ -State Management Responsibilities - -Key: -G - Global -DX8W - DX8 Wrapper -LE - Wrapper::Set Light Environment -DX8R - DX8 Renderer (affects meshes only) -Shader - ShaderClass -VM - VertexMaterial -Map - Mapper (part of VertexMaterial) -Texture - TextureClass -WW3D - -_D3DRENDERSTATETYPE { -ZENABLE = 7, -FILLMODE = 8, WW3D -SHADEMODE = 9, -LINEPATTERN = 10, -ZWRITEENABLE = 14, Shader -ALPHATESTENABLE = 15, Shader -LASTPIXEL = 16, -SRCBLEND = 19, Shader -DESTBLEND = 20, Shader -CULLMODE = 22, Shader -ZFUNC = 23, Shader -ALPHAREF = 24, Shader -ALPHAFUNC = 25, Shader -DITHERENABLE = 26, G -ALPHABLENDENABLE = 27, Shader -FOGENABLE = 28, Shader -SPECULARENABLE = 29, Shader -ZVISIBLE = 30, -FOGCOLOR = 34, Shader -FOGTABLEMODE = 35, G -FOGSTART = 36, Scene -FOGEND = 37, Scene -FOGDENSITY = 38, -EDGEANTIALIAS = 40, -ZBIAS = 47, G (set to zero after device is initted) -RANGEFOGENABLE = 48, G - -STENCILENABLE = 52, -STENCILFAIL = 53, -STENCILZFAIL = 54, -STENCILPASS = 55, -STENCILFUNC = 56, -STENCILREF = 57, -STENCILMASK = 58, -STENCILWRITEMASK = 59, -TEXTUREFACTOR = 60, - -WRAP0 = 128, -WRAP1 = 129, -WRAP2 = 130, -WRAP3 = 131, -WRAP4 = 132, -WRAP5 = 133, -WRAP6 = 134, -WRAP7 = 135, -CLIPPING = 136, -LIGHTING = 137, VM -AMBIENT = 139, LE -FOGVERTEXMODE = 140, G -COLORVERTEX = 141, G -LOCALVIEWER = 142, -NORMALIZENORMALS = 143, -DIFFUSEMATERIALSOURCE = 145, VM -SPECULARMATERIALSOURCE = 146, G -AMBIENTMATERIALSOURCE = 147, VM, set to same setting as diffuse material source -EMISSIVEMATERIALSOURCE = 148, VM -VERTEXBLEND = 151, -CLIPPLANEENABLE = 152, - -SOFTWAREVERTEXPROCESSING = 153, G - -POINTSIZE = 154, -POINTSIZE_MIN = 155, -POINTSPRITEENABLE = 156, - -POINTSCALEENABLE = 157, -POINTSCALE_A = 158, -POINTSCALE_B = 159, -POINTSCALE_C = 160, - -MULTISAMPLEANTIALIAS = 161, -MULTISAMPLEMASK = 162, - -PATCHEDGESTYLE = 163, -PATCHSEGMENTS = 164, - -DEBUGMONITORTOKEN = 165, -POINTSIZE_MAX = 166, -INDEXEDVERTEXBLENDENABLE = 167, -COLORWRITEENABLE = 168, -TWEENFACTOR = 170, -BLENDOP = 171, - -FORCE_DWORD = 0x7fffffff -} D3DRENDERSTATETYPE; - -_D3DTEXTURESTAGESTATETYPE { -COLOROP = 1, Shader stages 0,1 only -COLORARG1 = 2, Shader stages 0,1 only -COLORARG2 = 3, Shader stages 0,1 only -ALPHAOP = 4, Shader stages 0,1 only -ALPHAARG1 = 5, Shader stages 0,1 only -ALPHAARG2 = 6, Shader stages 0,1 only -BUMPENVMAT00 = 7, -BUMPENVMAT01 = 8, -BUMPENVMAT10 = 9, -BUMPENVMAT11 = 10, -TEXCOORDINDEX = 11, DX8R, Map -ADDRESSU = 13, Texture -ADDRESSV = 14, Texture -BORDERCOLOR = 15, -MAGFILTER = 16, Texture -MINFILTER = 17, Texture -MIPFILTER = 18, Texture -MIPMAPLODBIAS = 19, -MAXMIPLEVEL = 20, -MAXANISOTROPY = 21, -BUMPENVLSCALE = 22, -BUMPENVLOFFSET = 23, -TEXTURETRANSFORMFLAGS = 24, Map -ADDRESSW = 25, -COLORARG0 = 26, -ALPHAARG0 = 27, -RESULTARG = 28, - -FORCE_DWORD = 0x7fffffff -} D3DTEXTURESTAGESTATETYPE; - -Variables - -_D3DTRANSFORMSTATETYPE { - D3DTS_VIEW = 2, Pointgroup (restores), Camera - D3DTS_PROJECTION = 3, Camera - D3DTS_TEXTURE0 = 16, - D3DTS_TEXTURE1 = 17, - D3DTS_TEXTURE2 = 18, - D3DTS_TEXTURE3 = 19, - D3DTS_TEXTURE4 = 20, - D3DTS_TEXTURE5 = 21, - D3DTS_TEXTURE6 = 22, - D3DTS_TEXTURE7 = 23, - - D3DTS_FORCE_DWORD = 0x7fffffff - - D3DTS_WORLDMATRIX(0) = box, pointgroup, camera -} D3DTRANSFORMSTATETYPE; - -Clip Planes = -Clip Status = -Current Texture Palette = -Cursor Position = -Cursor Properties = -Gamma Ramp = -Indices = DX8W -Light = LE -Material = VM -Palette Entries = -Pixel Shader = -Pixel Shader Const = -Render Target = -Stream Source = DX8W -Texture = DX8W -WORLD Transform = box, DX8R, pointgr -VIEW Transform = pointgr -PROJECTION Transform = camera -TEXTURE Transform = Map -Vertex Shader = DX8W -Vertex Shader Const = -Viewport = Camera, WW3D \ No newline at end of file diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp deleted file mode 100644 index 1f024c6fb0..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#include "assetstatus.h" -#include "hashtemplate.h" -#include "wwstring.h" -#include "RAWFILE.H" - -AssetStatusClass AssetStatusClass::Instance; - -const char* ReportCategoryNames[AssetStatusClass::REPORT_COUNT]={ - "LOAD_ON_DEMAND_ROBJ", - "LOAD_ON_DEMAND_HANIM", - "LOAD_ON_DEMAND_HTREE", - "MISSING_ROBJ", - "MISSING_HANIM", - "MISSING_HTREE" -}; - -AssetStatusClass::AssetStatusClass() - : - Reporting (true), - LoadOnDemandReporting(false) -{ -} - -AssetStatusClass::~AssetStatusClass() -{ -#ifdef WWDEBUG - if (Reporting) { - StringClass report("Load-on-demand and missing assets report\r\n\r\n"); - for (int i=0;i ite(ReportHashTables[i]); - for (ite.First();!ite.Is_Done();ite.Next()) { - report+=ite.Peek_Key(); - int count=ite.Peek_Value(); - if (count>1) { - StringClass tmp(0,true); - tmp.Format("\t(reported %d times)",count); - report+=tmp; - } - report+="\r\n"; - } - report+="\r\n"; - } - if (report.Get_Length()) { - RawFileClass raw_log_file("asset_report.txt"); - raw_log_file.Create(); - raw_log_file.Open(RawFileClass::WRITE); - raw_log_file.Write(report,report.Get_Length()); - raw_log_file.Close(); - } - } -#endif -} - -void AssetStatusClass::Add_To_Report(int index, const char* name) -{ - StringClass lower_case_name(name,true); - _strlwr(lower_case_name.Peek_Buffer()); - // This is a bit slow - two accesses to the same member, but currently there's no better way to do it. - int count=ReportHashTables[index].Get(lower_case_name); - count++; - ReportHashTables[index].Set_Value(lower_case_name,count); -} - -void AssetStatusClass::Report_Load_On_Demand_RObj(const char* name) -{ - if (LoadOnDemandReporting) Add_To_Report(REPORT_LOAD_ON_DEMAND_ROBJ,name); -} - -void AssetStatusClass::Report_Load_On_Demand_HAnim(const char* name) -{ - if (LoadOnDemandReporting) Add_To_Report(REPORT_LOAD_ON_DEMAND_HANIM,name); -} - -void AssetStatusClass::Report_Load_On_Demand_HTree(const char* name) -{ - if (LoadOnDemandReporting) Add_To_Report(REPORT_LOAD_ON_DEMAND_HTREE,name); -} - -void AssetStatusClass::Report_Missing_RObj(const char* name) -{ - Add_To_Report(REPORT_MISSING_ROBJ,name); -} - -void AssetStatusClass::Report_Missing_HAnim(const char* name) -{ - Add_To_Report(REPORT_MISSING_HANIM,name); -} - -void AssetStatusClass::Report_Missing_HTree(const char* name) -{ - Add_To_Report(REPORT_MISSING_HTREE,name); -} - diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.h deleted file mode 100644 index 0e7cb183ad..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/assetstatus.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -#if defined(_MSC_VER) -#pragma once -#endif - -#ifndef WW3D_ASSET_STATUS_H -#define WW3D_ASSET_STATUS_H - -#include "always.h" -#include "hashtemplate.h" - -class AssetStatusClass -{ -public: - enum { - REPORT_LOAD_ON_DEMAND_ROBJ, - REPORT_LOAD_ON_DEMAND_HANIM, - REPORT_LOAD_ON_DEMAND_HTREE, - REPORT_MISSING_ROBJ, - REPORT_MISSING_HANIM, - REPORT_MISSING_HTREE, - REPORT_COUNT - }; - - AssetStatusClass(); - ~AssetStatusClass(); - - void Enable_Reporting(bool enable) { Reporting=enable; } - void Enable_Load_On_Demand_Reporting(bool enable) { LoadOnDemandReporting=enable; } - - void Report_Load_On_Demand_RObj(const char* name); - void Report_Load_On_Demand_HAnim(const char* name); - void Report_Load_On_Demand_HTree(const char* name); - - void Report_Missing_RObj(const char* name); - void Report_Missing_HAnim(const char* name); - void Report_Missing_HTree(const char* name); - - static AssetStatusClass* Peek_Instance() { return &Instance; } - -private: - bool Reporting; - bool LoadOnDemandReporting; - static AssetStatusClass Instance; - HashTemplateClass ReportHashTables[REPORT_COUNT]; - - void Add_To_Report(int index, const char* name); - -}; - -#endif diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp index ff99c6eb58..7ea6d67194 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dazzle.cpp @@ -305,7 +305,7 @@ const Vector2 DazzleINIClass::Get_Vector2(char const *section, char const *entry INIEntry * entryptr = Find_Entry(section, entry); if (entryptr && entryptr->Value != NULL) { Vector2 ret; - if ( sscanf( entryptr->Value, "%f,%f", &ret[0], &ret[1], &ret[2] ) == 2 ) { + if ( sscanf( entryptr->Value, "%f,%f", &ret[0], &ret[1] ) == 2 ) { return ret; } } diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp index 531552433c..5d8b9876b0 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp @@ -106,8 +106,6 @@ MeshModelClass::MeshModelClass(const MeshModelClass & that) : MeshModelClass::~MeshModelClass(void) { -// WWDEBUG_SAY(("Note: Mesh %s was never used\n",Get_Name())); - TheDX8MeshRenderer.Unregister_Mesh_Type(this); Reset(0,0,0); REF_PTR_RELEASE(MatInfo); diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp index a7c4d92f8a..691ad41492 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp @@ -50,7 +50,7 @@ #include #include -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... // #pragma optimize("", off) // #pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp index 890b880c41..89d5e0d82e 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.cpp @@ -31,11 +31,8 @@ static DLListClass ThumbnailManagerList; static ThumbnailManagerClass* GlobalThumbnailManager; -static bool message_box_displayed=false; bool ThumbnailManagerClass::CreateThumbnailIfNotFound=false; -const char* ThumbFileHeader="THU6"; - static void Create_Hash_Name(StringClass& name, const StringClass& thumb_name) { name=thumb_name; @@ -258,250 +255,21 @@ ThumbnailClass::~ThumbnailClass() Manager->Remove_From_Hash(this); } -void ThumbnailManagerClass::Create_Thumbnails() -{ -#if 0 - SimpleFileFactoryClass ff; -// ff.Set_Sub_Directory("Data\\"); - ff.Set_Sub_Directory("..\\data\\client\\mixfiles\\"); - - MixFileFactoryClass mix(MixFileName, &ff); - FileFactoryClass* old_file_factory=_TheFileFactory; - _TheFileFactory=&mix; - if (mix.Is_Valid()) { - DynamicVectorClass list; - list.Set_Growth_Step (1000); - mix.Build_Filename_List(list); - for (int i=0;iPeek_Thumbnail_Instance(tex_name); - if (g_thumb) { - delete g_thumb; - } - } - } - } - } - _TheFileFactory=old_file_factory; -#endif -} - -void ThumbnailManagerClass::Load() -{ - WWASSERT(!ThumbnailMemory); - - // If the thumbnail hash table file is available, init hash table -#if 0 // don't do thumbnail file. - DateTime=0; - SimpleFileFactoryClass ff; - ff.Set_Sub_Directory("..\\data\\client\\mixfiles\\"); - FileClass* thumb_file=ff.Get_File(ThumbnailFileName); - - if (thumb_file->Is_Available()) { - thumb_file->Open(FileClass::READ); - - DateTime=thumb_file->Get_Date_Time(); - - char tmp[4]; - thumb_file->Read(tmp,4); - if (tmp[0]==ThumbFileHeader[0] && - tmp[1]==ThumbFileHeader[1] && - tmp[2]==ThumbFileHeader[2] && - tmp[3]==ThumbFileHeader[3]) { - - int total_thumb_count; - int total_header_length; - int total_data_length; - thumb_file->Read(&total_thumb_count,sizeof(int)); - thumb_file->Read(&total_header_length,sizeof(int)); - thumb_file->Read(&total_data_length,sizeof(int)); - if (total_thumb_count) { - WWASSERT(total_data_length && total_header_length); - ThumbnailMemory=W3DNEWARRAY unsigned char[total_data_length]; - // Load thumbs - for (int i=0;iRead(&date_time,sizeof(unsigned long)); - thumb_file->Read(&offset,sizeof(int)); - thumb_file->Read(&width,sizeof(int)); - thumb_file->Read(&height,sizeof(int)); - thumb_file->Read(&original_width,sizeof(int)); - thumb_file->Read(&original_height,sizeof(int)); - thumb_file->Read(&original_mip_level_count,sizeof(int)); - thumb_file->Read(&original_format,sizeof(int)); - thumb_file->Read(&name_len,sizeof(int)); - WWASSERT(name_len<255); - thumb_file->Read(name,name_len); - name[name_len]='\0'; - - // If per-texture time stamp test is enabled, thumbnail is only used if its time stamp - // matches the texture's time stamp. - bool valid=true; - if (Is_Per_Texture_Time_Stamp_Used()) { - file_auto_ptr texture_file(_TheFileFactory, name); - if (texture_file->Is_Available()) { - texture_file->Open(); - if (texture_file->Get_Date_Time()!=date_time) { - valid=false; - } - texture_file->Close(); - } - else { - valid=false; - } - } - - if (valid) { - W3DNEW ThumbnailClass( - this, - name, - ThumbnailMemory+offset-total_header_length, - width, - height, - original_width, - original_height, - original_mip_level_count, - original_format, - false, - date_time); - } - } - thumb_file->Read(ThumbnailMemory,total_data_length); - } - } - thumb_file->Close(); - } - Changed=false; - ff.Return_File(thumb_file); -#endif -} - -void ThumbnailManagerClass::Save(bool force) -{ - // Save only if changed - if (!Changed && !force) return; - Changed=false; - - // If the thumbnail hash table was modified, save it to disk -#if 0 // don't write thumbnails. jba. - - HashTemplateIterator ite(ThumbnailHash); - int total_header_length=0; - int total_data_length=0; - int total_thumb_count=0; - total_header_length+=4; // header - total_header_length+=4; // thumb count - total_header_length+=4; // header size - total_header_length+=4; // data length - - for (ite.First();!ite.Is_Done();ite.Next()) { - ThumbnailClass* thumb=ite.Peek_Value(); - total_header_length+=4; // per-thumb date-time - total_header_length+=4; // int bitmap offset - total_header_length+=4; // int bitmap width - total_header_length+=4; // int bitmap height - total_header_length+=4; // int original bitmap width - total_header_length+=4; // int original bitmap height - total_header_length+=4; // int original mip level count - total_header_length+=4; // int original format - total_header_length+=4; // int name string length - - total_header_length+=strlen(thumb->Get_Name()); - total_data_length+=thumb->Get_Width()*thumb->Get_Height()*2; - total_thumb_count++; - } - int offset=total_header_length; - - SimpleFileFactoryClass ff; - ff.Set_Sub_Directory("..\\data\\client\\mixfiles\\"); - FileClass* thumb_file=ff.Get_File(ThumbnailFileName); -// file_auto_ptr thumb_file(_TheWritingFileFactory, ThumbnailFileName); - - if (thumb_file->Is_Available()) { - thumb_file->Delete(); - } - thumb_file->Create(); - thumb_file->Open(FileClass::WRITE); - - thumb_file->Write(ThumbFileHeader,4); - thumb_file->Write(&total_thumb_count,sizeof(int)); - thumb_file->Write(&total_header_length,sizeof(int)); - thumb_file->Write(&total_data_length,sizeof(int)); - - // Save names and offsets - for (ite.First();!ite.Is_Done();ite.Next()) { - ThumbnailClass* thumb=ite.Peek_Value(); - const char* name=thumb->Get_Name(); - int name_len=strlen(name); - int width=thumb->Get_Width(); - int height=thumb->Get_Height(); - int original_width=thumb->Get_Original_Texture_Width(); - int original_height=thumb->Get_Original_Texture_Height(); - int original_mip_level_count=thumb->Get_Original_Texture_Mip_Level_Count(); - WW3DFormat original_format=thumb->Get_Original_Texture_Format(); - unsigned long date_time=thumb->Get_Date_Time(); - - thumb_file->Write(&date_time,sizeof(unsigned long)); - thumb_file->Write(&offset,sizeof(int)); - thumb_file->Write(&width,sizeof(int)); - thumb_file->Write(&height,sizeof(int)); - thumb_file->Write(&original_width,sizeof(int)); - thumb_file->Write(&original_height,sizeof(int)); - thumb_file->Write(&original_mip_level_count,sizeof(int)); - thumb_file->Write(&original_format,sizeof(int)); - thumb_file->Write(&name_len,sizeof(int)); - thumb_file->Write(name,name_len); - offset+=width*height*2; - } - - // Save bitmaps - offset=total_header_length; - for (ite.First();!ite.Is_Done();ite.Next()) { - ThumbnailClass* thumb=ite.Peek_Value(); - int width=thumb->Get_Width(); - int height=thumb->Get_Height(); - thumb_file->Write(thumb->Peek_Bitmap(),width*height*2); - } - if (DateTime) thumb_file->Set_Date_Time(DateTime); - thumb_file->Close(); - ff.Return_File(thumb_file); -#endif -} - // ---------------------------------------------------------------------------- -ThumbnailManagerClass::ThumbnailManagerClass(const char* thumbnail_filename, const char* mix_filename) +ThumbnailManagerClass::ThumbnailManagerClass(const char* thumbnail_filename) : ThumbnailMemory(NULL), ThumbnailFileName(thumbnail_filename), - MixFileName(mix_filename), PerTextureTimeStampUsed(false), Changed(false), DateTime(0) { - Load(); } // ---------------------------------------------------------------------------- ThumbnailManagerClass::~ThumbnailManagerClass() { - Save(); HashTemplateIterator ite(ThumbnailHash); ite.First(); while (!ite.Is_Done()) { @@ -528,7 +296,7 @@ ThumbnailManagerClass* ThumbnailManagerClass::Peek_Thumbnail_Manager(const char* } // ---------------------------------------------------------------------------- -void ThumbnailManagerClass::Add_Thumbnail_Manager(const char* thumbnail_filename, const char* mix_filename) +void ThumbnailManagerClass::Add_Thumbnail_Manager(const char* thumbnail_filename) { // First loop over all thumbnail managers to see if we already have this one created. This isn't // supposed to be called often at all and there are usually just couple managers alive, @@ -540,11 +308,8 @@ void ThumbnailManagerClass::Add_Thumbnail_Manager(const char* thumbnail_filename ThumbnailManagerClass* man=Peek_Thumbnail_Manager(thumbnail_filename); if (man) return; - // Always update thumbnail files when they're out of date - Update_Thumbnail_File(mix_filename,false); - // Not found, create and add to the list. - man=new ThumbnailManagerClass(thumbnail_filename,mix_filename); + man=new ThumbnailManagerClass(thumbnail_filename); ThumbnailManagerList.Add_Tail(man); } // ---------------------------------------------------------------------------- @@ -627,131 +392,10 @@ void ThumbnailManagerClass::Remove_From_Hash(ThumbnailClass* thumb) ThumbnailHash.Remove(hash_name); } -void ThumbnailManagerClass::Update_Thumbnail_File(const char* mix_file_name,bool display_message_box) -{ - if (!mix_file_name) return; - - SimpleFileFactoryClass ff; - ff.Set_Sub_Directory("..\\data\\client\\mixfiles\\"); - - StringClass thumb_file_name(mix_file_name,true); - int len=thumb_file_name.Get_Length(); - WWASSERT(len>4); - thumb_file_name[len-3]='t'; - thumb_file_name[len-2]='h'; - thumb_file_name[len-1]='6'; - FileClass* mix_file=ff.Get_File(mix_file_name); - FileClass* thumb_file=ff.Get_File(thumb_file_name); - - WWASSERT(mix_file && thumb_file); - - // If mix file isn't found but thumb file is, delete the obsolete thumb file - mix_file->Open(FileClass::READ); - thumb_file->Open(FileClass::READ); //|FileClass::WRITE); Changed this to READ only since we never use the handle for writing and it may cause contention amongst slave servers ST - 12/14/2001 8:26PM - if (!mix_file->Is_Available()) { - if (thumb_file->Is_Available()) { - thumb_file->Delete(); - } - mix_file->Close(); - thumb_file->Close(); - ff.Return_File(mix_file); - ff.Return_File(thumb_file); - return; - } - - unsigned long mix_date_time=mix_file->Get_Date_Time(); - if (thumb_file->Is_Available()) { - unsigned long thumb_date_time=thumb_file->Get_Date_Time(); - if (mix_date_time!=thumb_date_time) { - thumb_file->Delete(); - } - // Read header to make sure the thumb file is of correct version. - char tmp[4]; - thumb_file->Read(tmp,4); - if (tmp[0]!=ThumbFileHeader[0] || - tmp[1]!=ThumbFileHeader[1] || - tmp[2]!=ThumbFileHeader[2] || - tmp[3]!=ThumbFileHeader[3]) { - thumb_file->Delete(); - } - } - - if (thumb_file->Is_Available()) { - mix_file->Close(); - thumb_file->Close(); - ff.Return_File(mix_file); - ff.Return_File(thumb_file); - return; - } - - if (display_message_box && !message_box_displayed) { - message_box_displayed=true; - ::MessageBox(NULL, - "Some or all texture thumbnails need to be updated.\n" - "This will take a while. The update will only be done once\n" - "each time a mix file changes and thumb database hasn't been\n" - "updated.", - "Updating texture thumbnails", - MB_OK); - } - - // we don't currently have a thumbnail file (either we just deleted it or it never existed, we don't care) - // so we must create one now. - ThumbnailManagerClass* manager=new ThumbnailManagerClass(thumb_file_name, mix_file_name); - manager->DateTime=mix_date_time; // Set the datetime to mixfile's datetime. - manager->Create_Thumbnails(); - manager->Save(true); - delete manager; - - // close files and return pointers - mix_file->Close(); - thumb_file->Close(); - ff.Return_File(mix_file); - ff.Return_File(thumb_file); -} - -// Verify that up-to-date thumbnails exist for all textures -void ThumbnailManagerClass::Pre_Init(bool display_message_box) -{ - WWASSERT(!ThumbnailManagerList.Head()); - - // Collect all mix file names - DynamicVectorClass mix_names; - - char cur_dir[256]; - GetCurrentDirectory(sizeof(cur_dir),cur_dir); - StringClass new_dir(cur_dir,true); - new_dir+="\\Data"; - SetCurrentDirectory(new_dir); - - WIN32_FIND_DATA find_data; - HANDLE handle=FindFirstFile("*.mix",&find_data); - if (handle!=INVALID_HANDLE_VALUE) { - for (;;) { - if (!(find_data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) { - mix_names.Add(find_data.cFileName); - } - if (!FindNextFile(handle,&find_data)) { - FindClose(handle); - break; - } - } - } - SetCurrentDirectory(cur_dir); - - // First generate thumbnails for always.dat - Update_Thumbnail_File("always.dat",display_message_box); - - // Then loop over all .mix files - for (int i=0;iEnable_Per_Texture_Time_Stamp(true); } diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h index cd48db52f2..6efa782afd 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texturethumbnail.h @@ -94,28 +94,22 @@ class ThumbnailManagerClass : public DLNodeClass static bool CreateThumbnailIfNotFound; bool PerTextureTimeStampUsed; StringClass ThumbnailFileName; - StringClass MixFileName; HashTemplateClass ThumbnailHash; unsigned char* ThumbnailMemory; bool Changed; unsigned long DateTime; - ThumbnailManagerClass(const char* thumbnail_filename, const char* mix_file_name); + ThumbnailManagerClass(const char* thumbnail_filename); ~ThumbnailManagerClass(); void Remove_From_Hash(ThumbnailClass* thumb); void Insert_To_Hash(ThumbnailClass* thumb); ThumbnailClass* Get_From_Hash(const StringClass& name); - void Create_Thumbnails(); - static void Update_Thumbnail_File(const char* mix_file_name, bool display_message_box); - - void Load(); - void Save(bool force=false); public: ThumbnailClass* Peek_Thumbnail_Instance(const StringClass& name); - static void Add_Thumbnail_Manager(const char* thumbnail_filename, const char* mix_file_name); + static void Add_Thumbnail_Manager(const char* thumbnail_filename); static void Remove_Thumbnail_Manager(const char* thumbnail_filename); static ThumbnailManagerClass* Peek_Thumbnail_Manager(const char* thumbnail_filename); @@ -127,7 +121,6 @@ class ThumbnailManagerClass : public DLNodeClass bool Is_Per_Texture_Time_Stamp_Used() const { return PerTextureTimeStampUsed; } void Enable_Per_Texture_Time_Stamp(bool enable) { PerTextureTimeStampUsed=enable; } - static void Pre_Init(bool display_message_box); static void Init(); static void Deinit(); }; diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h index 26243a2b04..e7e3f642b8 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/w3d_file.h @@ -315,6 +315,11 @@ April 5, 2025 Added W3D_CHUNK_FX_SHADERS and subchunks, which were added in BFME2. These chunks are used to define usage of a specific shader and pass params. +April 21, 2025 + + Added W3D_CHUNK_VERTEX_TANGENT and W3D_CHUNK_VERTEX_BINORMAL chunks. These are used to define + normal mapping information for a mesh. They were added in BFME2. + ********************************************************************************/ @@ -397,6 +402,9 @@ enum { W3D_CHUNK_DEFORM_KEYFRAME =0x0000005A, // a keyframe of deform information in the set W3D_CHUNK_DEFORM_DATA =0x0000005B, // deform information about a single vertex + W3D_CHUNK_VERTEX_TANGENTS = 0x00000060, // array of tangents (array of W3dVectorStruct's) + W3D_CHUNK_VERTEX_BINORMALS = 0x00000061, // array of binormals (array of W3dVectorStruct's) + W3D_CHUNK_PS2_SHADERS =0x00000080, // Shader info specific to the Playstation 2. W3D_CHUNK_AABTREE =0x00000090, // Axis-Aligned Box Tree for hierarchical polygon culling diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt index a216c6a567..074502aa28 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWAudio/CMakeLists.txt @@ -1,54 +1,7 @@ -set(WWAUDIO_SRC - "AABTreeSoundCullClass.h" - "AudibleSound.cpp" - "AudibleSound.h" - "AudioEvents.h" - "AudioSaveLoad.cpp" - "AudioSaveLoad.h" - "FilteredSound.cpp" - "FilteredSound.h" - "Listener.cpp" - "Listener.h" - "listenerhandle.cpp" - "listenerhandle.h" - "LogicalListener.cpp" - "LogicalListener.h" - "LogicalSound.cpp" - "LogicalSound.h" - "PriorityVector.h" - "sound2dhandle.cpp" - "sound2dhandle.h" - "Sound3D.cpp" - "Sound3D.h" - "sound3dhandle.cpp" - "sound3dhandle.h" - "SoundBuffer.cpp" - "SoundBuffer.h" - "SoundChunkIDs.h" - "SoundCullObj.h" - "soundhandle.cpp" - "soundhandle.h" - "SoundPseudo3D.cpp" - "SoundPseudo3D.h" - "SoundScene.cpp" - "SoundScene.h" - "SoundSceneObj.cpp" - "SoundSceneObj.h" - "soundstreamhandle.cpp" - "soundstreamhandle.h" - "Threads.cpp" - "Threads.h" - "Utils.cpp" - "Utils.h" - "WWAudio.cpp" - "WWAudio.h" -) - add_library(z_wwaudio STATIC) set_target_properties(z_wwaudio PROPERTIES OUTPUT_NAME wwaudio) -target_sources(z_wwaudio PRIVATE ${WWAUDIO_SRC}) - target_link_libraries(z_wwaudio PRIVATE + corei_wwaudio z_wwcommon -) \ No newline at end of file +) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt index c3e3507c21..df1e5ef920 100644 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt +++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDownload/CMakeLists.txt @@ -1,25 +1,8 @@ -# Set source files -set(WWDOWNLOAD_SRC - Download.cpp - Download.h - DownloadDebug.h - downloaddefs.h - FTP.CPP - ftp.h - ftpdefs.h - registry.cpp - Registry.h - urlBuilder.cpp - urlBuilder.h -) - -# Targets to build. add_library(z_wwdownload STATIC) set_target_properties(z_wwdownload PROPERTIES OUTPUT_NAME wwdownload) -target_sources(z_wwdownload PRIVATE ${WWDOWNLOAD_SRC}) - target_link_libraries(z_wwdownload PRIVATE - z_wwcommon + corei_wwdownload + zi_always zi_gameengine_include ) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/CMakeLists.txt b/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/CMakeLists.txt deleted file mode 100644 index 79fad0aab6..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Set source files -set(WWUTIL_SRC - mathutil.cpp - mathutil.h - miscutil.cpp - miscutil.h -) - -# Targets to build. -add_library(z_wwutil STATIC) -set_target_properties(z_wwutil PROPERTIES OUTPUT_NAME wwutil) - -target_link_libraries(z_wwutil PRIVATE - z_wwcommon -) - -target_sources(z_wwutil PRIVATE ${WWUTIL_SRC}) diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/mathutil.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/mathutil.cpp deleted file mode 100644 index be69602f7f..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/mathutil.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: mathutil.cpp -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: -// -//----------------------------------------------------------------------------- -#include "mathutil.h" // I WANNA BE FIRST! - -#include -#include -#include "wwmath.h" -#include "miscutil.h" -#include "wwdebug.h" - -const double cMathUtil::PI_1 = 3.1415927; -const double cMathUtil::PI_2 = 1.5707963; - -//----------------------------------------------------------------------------- -// -// Returns a unit vector -// -void cMathUtil::Angle_To_Vector(double angle, double & dx, double & dy) -{ - WWASSERT(angle > -WWMATH_EPSILON && angle < 360.0 + WWMATH_EPSILON); - - double angleRadians; - - if (angle >= 0 && angle < 90) { - angleRadians = angle * PI_1 / 180.0; - dx = WWMath::Sin(angleRadians); - dy = WWMath::Cos(angleRadians); - } else if (angle >= 90 && angle < 180) { - angleRadians = (angle - 90) * PI_1 / 180.0; - dx = WWMath::Cos(angleRadians); - dy = -WWMath::Sin(angleRadians); - } else if (angle >= 180 && angle < 270) { - angleRadians = (angle - 180) * PI_1 / 180.0; - dx = -WWMath::Sin(angleRadians); - dy = -WWMath::Cos(angleRadians); - } else { - angleRadians = (angle - 270) * PI_1 / 180.0; - dx = -WWMath::Cos(angleRadians); - dy = WWMath::Sin(angleRadians); - } - - double len; - len = ::sqrt(dx * dx + dy * dy); - WWASSERT(::fabs(len - 1) < 0.0005); - - // - // Correction for Irish nature of windows y coords - // - dy *= -1; -} - -//----------------------------------------------------------------------------- -void cMathUtil::Vector_To_Angle(double dx, double dy, double & angle) -{ - double theta; - - if (dx == 0 && dy == 0) { - theta = 0; - } - - if (dx == 0) { - if (dy <= 0) { - theta = 0; - } else { - theta = PI_1; - } - } else { - theta = WWMath::Atan(-dy / dx); - if (dx < 0) { - theta += PI_1; - } - theta += 3 * PI_2; - if (theta >= 2 * PI_1) { - theta -= 2 * PI_1; - } - theta = 2 * PI_1 - theta; - if (theta == 2 * PI_1) { - theta = 0; - } - } - - angle = theta * 180.0 / PI_1; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Simple_Distance(double x1, double y1, double x2, double y2) -{ - double dx = x2 - x1; - double dy = y2 - y1; - return(::sqrt(dx * dx + dy * dy)); -} - -//----------------------------------------------------------------------------- -int cMathUtil::Round(double arg) -{ - //return (int)(arg + 0.5); - - if (arg > MISCUTIL_EPSILON) { - return (int) (arg + 0.5f); - } else if (arg < -MISCUTIL_EPSILON) { - return (int) (arg - 0.5f); - } else { - return 0; - } -} - -//----------------------------------------------------------------------------- -void cMathUtil::Rotate_Vector(double & vx, double & vy, double angle) -{ - double angle_radians = angle * PI_1 / 180.0; - - double vx1 = vx; - double vy1 = vy; - - vx = vx1 * ::WWMath::Cos(angle_radians) - vy1 * ::WWMath::Sin(angle_radians); - vy = vx1 * ::WWMath::Sin(angle_radians) + vy1 * ::WWMath::Cos(angle_radians); -} - - - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Uniform_Pdf_Double(double lower, double upper) -{ - WWASSERT(upper - lower > -MISCUTIL_EPSILON); - - double x = lower + ::rand() / (double) RAND_MAX * (upper - lower); - - WWASSERT(x - lower > -MISCUTIL_EPSILON && upper - x > -MISCUTIL_EPSILON); - - return x; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Normalized_Uniform_Pdf_Double() -{ - return Get_Uniform_Pdf_Double(0, 1); -} - -//----------------------------------------------------------------------------- -int cMathUtil::Get_Uniform_Pdf_Int(int lower, int upper) -{ - WWASSERT(lower <= upper); - int x = lower + ::rand() % (upper - lower + 1); - - WWASSERT(x >= lower && upper >= x); - - return x; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Hat_Pdf_Double(double lower, double upper) -{ - WWASSERT(upper - lower > -MISCUTIL_EPSILON); - - double x; - - if (::fabs(upper - lower) < MISCUTIL_EPSILON) { - x = lower; - } else { - - double dx = (upper - lower) / 2.0f; - double dy = 1 / dx; - double m = dy / dx; - double c = -m * lower; - - x = Get_Uniform_Pdf_Double(lower, lower + dx); - double y = Get_Uniform_Pdf_Double(0, dy); - - if (y > m * x + c) { - x += dx; - } - } - - WWASSERT(x - lower > -MISCUTIL_EPSILON && upper - x > -MISCUTIL_EPSILON); - - return x; -} - -//----------------------------------------------------------------------------- -double cMathUtil::Get_Normalized_Hat_Pdf_Double() -{ - return Get_Hat_Pdf_Double(0, 1); -} - -//----------------------------------------------------------------------------- -int cMathUtil::Get_Hat_Pdf_Int(int lower, int upper) -{ - return Round(Get_Hat_Pdf_Double(lower, upper)); -} - - - - - - - - - - - diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/mathutil.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/mathutil.h deleted file mode 100644 index 70c2b65543..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/mathutil.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: mathutil.h -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: static -// -//----------------------------------------------------------------------------- -#if defined(_MSV_VER) -#pragma once -#endif - -#ifndef MATHUTIL_H -#define MATHUTIL_H - -class cMathUtil -{ - public: - static void Angle_To_Vector(double angle, double & dx, double & dy); - static void Vector_To_Angle(double dx, double dy, double & angle); - static double Simple_Distance(double x1, double y1, double x2, double y2); - static int Round(double arg); - static void Rotate_Vector(double & vx, double & vy, double angle); - - // - // Random numbers generated according to simple - // Probability Density Functions - // - static double Get_Uniform_Pdf_Double(double lower, double upper); - static double Get_Normalized_Uniform_Pdf_Double(); - static int Get_Uniform_Pdf_Int(int lower, int upper); - static double Get_Hat_Pdf_Double(double lower, double upper); - static double Get_Normalized_Hat_Pdf_Double(); - static int Get_Hat_Pdf_Int(int lower, int upper); - - static const double PI_1; - static const double PI_2; -}; - -#endif // MATHUTIL_H \ No newline at end of file diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/miscutil.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/miscutil.cpp deleted file mode 100644 index 8f244326bc..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/miscutil.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: miscutil.cpp -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: -// -//----------------------------------------------------------------------------- -#include "miscutil.h" // I WANNA BE FIRST! - -#include - -#include "RAWFILE.H" -#include "wwdebug.h" -#include "win.h" -#include "mmsys.h" -#include "ffactory.h" - -// -// cMiscUtil statics -// - -//--------------------------------------------------------------------------- -LPCSTR cMiscUtil::Get_Text_Time(void) -{ - // - // Returns a pointer to an internal statically allocated buffer... - // Subsequent time operations will destroy the contents of that buffer. - // Note: BoundsChecker reports 2 memory leaks in ctime here. - // - - time_t time_now = ::time(NULL); - char * time_str = ::ctime(&time_now); - time_str[::strlen(time_str) - 1] = 0; // remove \n - return time_str; -} - -//--------------------------------------------------------------------------- -void cMiscUtil::Seconds_To_Hms(float seconds, int & h, int & m, int & s) -{ - WWASSERT(seconds >= 0); - - h = (int) (seconds / 3600); - seconds -= h * 3600; - m = (int) (seconds / 60); - seconds -= m * 60; - s = (int) seconds; - - WWASSERT(h >= 0); - WWASSERT(m >= 0 && m < 60); - WWASSERT(s >= 0 && s < 60); - - //WWASSERT(fabs((h * 3600 + m * 60 + s) / 60) - mins < WWMATH_EPSILON); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_String_Same(LPCSTR str1, LPCSTR str2) -{ - WWASSERT(str1 != NULL); - WWASSERT(str2 != NULL); - - return(::stricmp(str1, str2) == 0); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_String_Different(LPCSTR str1, LPCSTR str2) -{ - WWASSERT(str1 != NULL); - WWASSERT(str2 != NULL); - - return(::stricmp(str1, str2) != 0); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::File_Exists(LPCSTR filename) -{ -#if 0 - WWASSERT(filename != NULL); - - WIN32_FIND_DATA find_info; - HANDLE file_handle = ::FindFirstFile(filename, &find_info); - - if (file_handle != INVALID_HANDLE_VALUE) { - ::FindClose(file_handle); - return true; - } else { - return false; - } -#else - FileClass * file = _TheFileFactory->Get_File( filename ); - if ( file && file->Is_Available() ) { - return true; - } - _TheFileFactory->Return_File( file ); - return false; -#endif -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::File_Is_Read_Only(LPCSTR filename) -{ - WWASSERT(filename != NULL); - - DWORD attributes = ::GetFileAttributes(filename); - return ((attributes != 0xFFFFFFFF) && (attributes & FILE_ATTRIBUTE_READONLY)); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Alphabetic(char c) -{ - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Numeric(char c) -{ - return (c >= '0' && c <= '9'); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Alphanumeric(char c) -{ - return Is_Alphabetic(c) || Is_Numeric(c); -} - -//----------------------------------------------------------------------------- -bool cMiscUtil::Is_Whitespace(char c) -{ - return c == ' ' || c == '\t'; -} - -//----------------------------------------------------------------------------- -void cMiscUtil::Trim_Trailing_Whitespace(char * text) -{ - WWASSERT(text != NULL); - - int length = ::strlen(text); - while (length > 0 && Is_Whitespace(text[length - 1])) { - text[--length] = 0; - } -} - -//----------------------------------------------------------------------------- -void cMiscUtil::Get_File_Id_String(LPCSTR filename, StringClass & str) -{ - WWASSERT(filename != NULL); - -// WWDEBUG_SAY(("cMiscUtil::Get_File_Id_String for %s\n", filename)); - - // - // Get size - // - RawFileClass file(filename); - int filesize = file.Size(); - //WWASSERT(filesize > 0); - if (filesize <= 0) - { - WWDEBUG_SAY(("Error: cMiscUtil::Get_File_Id_String for %s: filesize = %d\n", - filename, filesize)); - //W3D_DIE; - } - file.Close(); - - // - // Note... this timedatestamp is not present for all file types... - // - IMAGE_FILE_HEADER header = {0}; - extern bool Get_Image_File_Header(LPCSTR filename, IMAGE_FILE_HEADER *file_header); - /* - bool success; - success = Get_Image_File_Header(filename, &header); - WWASSERT(success); - */ - Get_Image_File_Header(filename, &header); - int time_date_stamp = header.TimeDateStamp; - - char working_filename[500]; - strcpy(working_filename, filename); - ::strupr(working_filename); - - // - // Strip path off filename - // - char * p_start = &working_filename[strlen(working_filename)]; - int num_chars = 1; - while (p_start > working_filename && *(p_start - 1) != '\\') { - p_start--; - num_chars++; - } - ::memmove(working_filename, p_start, num_chars); - - // - // Put all this data into a string - // - str.Format("%s %d %d", working_filename, filesize, time_date_stamp); - - //WWDEBUG_SAY(("File id string: %s\n", str)); -} - -//----------------------------------------------------------------------------- -void cMiscUtil::Remove_File(LPCSTR filename) -{ - WWASSERT(filename != NULL); - - ::DeleteFile(filename); -} - - - - - - - - - - - - - - - - - -/* -#define SIZE_OF_NT_SIGNATURE sizeof(DWORD) -#define PEFHDROFFSET(a) ((LPVOID)((BYTE *)a + \ - ((PIMAGE_DOS_HEADER)a)->e_lfanew + SIZE_OF_NT_SIGNATURE)) -*/ - -/* -int cMiscUtil::Get_Exe_Key(void) -{ - // - // Get exe name - // - char filename[500]; - int succeeded; - succeeded = ::GetModuleFileName(NULL, filename, sizeof(filename)); - ::strupr(filename); - WWASSERT(succeeded); - - // - // Get size - // - RawFileClass file(filename); - int filesize = file.Size(); - WWASSERT(filesize > 0); - file.Close(); - - // - // Strip path off filename - // - char * p_start = &filename[strlen(filename)]; - int num_chars = 1; - while (*(p_start - 1) != '\\') { - p_start--; - num_chars++; - } - ::memmove(filename, p_start, num_chars); - - // - // Pull a time/date stamp out of the exe header - // - PIMAGE_FILE_HEADER p_header = (PIMAGE_FILE_HEADER) PEFHDROFFSET(ProgramInstance); - WWASSERT(p_header != NULL); - int time_date_stamp = p_header->TimeDateStamp; - - // - // Put all this data into a string - // - char id_string[500]; - ::sprintf(id_string, "%s %d %d", filename, filesize, time_date_stamp); - WWDEBUG_SAY(("File id string: %s\n", id_string)); - - // - // return the crc of that string as the key - // - return CRCEngine()(id_string, strlen(id_string)); -} -*/ - -//#include -//#include "verchk.h" - -/* -//----------------------------------------------------------------------------- -int cMiscUtil::Get_Exe_Key(void) -{ - // - // Get exe name - // - char filename[500]; - int succeeded; - succeeded = ::GetModuleFileName(NULL, filename, sizeof(filename)); - ::strupr(filename); - WWASSERT(succeeded); - - StringClass string; - Get_File_Id_String(filename, string); - - // - // return the crc of that string as the key - // - return CRCEngine()(string, strlen(string)); -} -*/ - -//#include "crc.h" diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/miscutil.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/miscutil.h deleted file mode 100644 index b2e91449f6..0000000000 --- a/GeneralsMD/Code/Libraries/Source/WWVegas/Wwutil/miscutil.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// -// Filename: miscutil.h -// Project: wwutil -// Author: Tom Spencer-Smith -// Date: June 1998 -// Description: -// -//----------------------------------------------------------------------------- -#if defined(_MSV_VER) -#pragma once -#endif - -#ifndef MISCUTIL_H -#define MISCUTIL_H - -#ifndef ALWAYS_H - #include "always.h" -#endif - -#include "bittype.h" -#include "wwstring.h" - -const float MISCUTIL_EPSILON = 0.0001f; - -class cMiscUtil -{ - public: - static LPCSTR Get_Text_Time(void); - static void Seconds_To_Hms(float seconds, int & h, int & m, int & s); - static bool Is_String_Same(LPCSTR str1, LPCSTR str2); - static bool Is_String_Different(LPCSTR str1, LPCSTR str2); - static void Get_File_Id_String(LPCSTR filename, StringClass & str); - static bool File_Exists(LPCSTR filename); - static bool File_Is_Read_Only(LPCSTR filename); - static bool Is_Alphabetic(char c); - static bool Is_Numeric(char c); - static bool Is_Alphanumeric(char c); - static bool Is_Whitespace(char c); - static void Trim_Trailing_Whitespace(char * text); - static void Remove_File(LPCSTR filename); - - private: -}; - - -#endif // MISCUTIL_H - - - - - - //static int Get_Exe_Key(void); diff --git a/GeneralsMD/Code/Libraries/Source/template.cpp b/GeneralsMD/Code/Libraries/Source/template.cpp deleted file mode 100644 index 84860fabcf..0000000000 --- a/GeneralsMD/Code/Libraries/Source/template.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: -// -// Module: -// -// File name: .cpp -// -// Created: -// -//---------------------------------------------------------------------------- - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Externals -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Defines -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Types -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Data -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Prototypes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Private Functions -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Public Functions -//---------------------------------------------------------------------------- - - - -//================================================================= -// Function Header -//================================================================= -/** - * Description - */ -//================================================================= - diff --git a/GeneralsMD/Code/Libraries/Source/template.h b/GeneralsMD/Code/Libraries/Source/template.h deleted file mode 100644 index 010a1e244f..0000000000 --- a/GeneralsMD/Code/Libraries/Source/template.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -//---------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//---------------------------------------------------------------------------- -// -// Project: -// -// Module: -// -// File name: .h -// -// Created: -// -//---------------------------------------------------------------------------- - -#pragma once - -#ifndef $label -#define $label - - -//---------------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Forward References -//---------------------------------------------------------------------------- - - - -//---------------------------------------------------------------------------- -// Type Defines -//---------------------------------------------------------------------------- - -//=============================== -// ClassName -//=============================== -/** - * Description - */ -//=============================== - - - - -//---------------------------------------------------------------------------- -// Inlining -//---------------------------------------------------------------------------- - - - -#endif // $label diff --git a/GeneralsMD/Code/Main/CMakeLists.txt b/GeneralsMD/Code/Main/CMakeLists.txt index 1fa597dc7e..81bed3898b 100644 --- a/GeneralsMD/Code/Main/CMakeLists.txt +++ b/GeneralsMD/Code/Main/CMakeLists.txt @@ -10,6 +10,8 @@ endif() target_link_libraries(z_generals PRIVATE binkstub comctl32 + core_debug + core_profile d3d8 d3dx8 dbghelplib @@ -20,10 +22,8 @@ target_link_libraries(z_generals PRIVATE safedisc vfw32 winmm - z_debug z_gameengine z_gameenginedevice - z_profile zi_always ) @@ -50,7 +50,7 @@ file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/BuildVersion.h target_link_options(z_generals PRIVATE "/NODEFAULTLIB:libci.lib") target_include_directories(z_generals PRIVATE - . + ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) diff --git a/GeneralsMD/Code/Main/WinMain.cpp b/GeneralsMD/Code/Main/WinMain.cpp index ca0ffcf603..7f7e450e61 100644 --- a/GeneralsMD/Code/Main/WinMain.cpp +++ b/GeneralsMD/Code/Main/WinMain.cpp @@ -30,6 +30,13 @@ // /////////////////////////////////////////////////////////////////////////////// +//this block is needed to get the IsDebuggerPresent() method through windows.h +#if _DEBUG +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x500 // Use 0x0500 for Windows 2000 +#endif +#endif + // SYSTEM INCLUDES //////////////////////////////////////////////////////////// #define WIN32_LEAN_AND_MEAN // only bare bones windows stuff wanted #include @@ -54,6 +61,7 @@ #include "Common/MessageStream.h" #include "Common/Registry.h" #include "Common/Team.h" +#include "GameClient/ClientInstance.h" #include "GameClient/InGameUI.h" #include "GameClient/GameClient.h" #include "GameLogic/GameLogic.h" ///< @todo for demo, remove @@ -69,7 +77,7 @@ #include -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") @@ -86,8 +94,6 @@ const Char *g_strFile = "data\\Generals.str"; const Char *g_csfFile = "data\\%s\\Generals.csf"; const char *gAppPrefix = ""; /// So WB can have a different debug log file name. -static HANDLE GeneralsMutex = NULL; -#define GENERALS_GUID "685EAFF2-3216-4265-B047-251C5F4B82F3" #define DEFAULT_XRESOLUTION 800 #define DEFAULT_YRESOLUTION 600 @@ -766,7 +772,7 @@ void munkeeFunc(void) void checkProtection(void) { -#ifdef _INTERNAL +#ifdef RTS_INTERNAL __try { munkeeFunc(); @@ -831,6 +837,26 @@ char *nextParam(char *newSource, const char *seps) return first; } +// Function to wait for debugger attachment +// Relies only on and MSVC compiler intrinsic __debugbreak +void WaitForDebugger() +{ +#ifdef _DEBUG // Only include this code in debug builds + // Loop until a debugger is attached. + // This loop will consume minimal CPU due to the Sleep call. + while (!IsDebuggerPresent()) // IsDebuggerPresent() is in (via WinBase.h usually) + { + Sleep(100); // Sleep() is in (via SynchAPI.h or WinBase.h) + } + + // Once the debugger is attached, IsDebuggerPresent() returns true, + // the loop exits, and we break into the debugger. + __debugbreak(); // MSVC Compiler Intrinsic to cause a breakpoint. + // This is often more robust than DebugBreak() as it doesn't + // rely on a specific SDK header for DebugBreak() itself. +#endif // _DEBUG +} + // Necessary to allow memory managers and such to have useful critical sections static CriticalSection critSec1, critSec2, critSec3, critSec4, critSec5; @@ -840,9 +866,12 @@ static CriticalSection critSec1, critSec2, critSec3, critSec4, critSec5; Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, Int nCmdShow ) { +#ifdef _DEBUG + WaitForDebugger(); //in debug build, wait for debugger attachment +#endif checkProtection(); -#ifdef _PROFILE +#ifdef RTS_PROFILE Profile::StartRange("init"); #endif @@ -912,7 +941,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, return 0; } - #ifdef _DEBUG + #ifdef RTS_DEBUG // Turn on Memory heap tracking int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tmpFlag |= (_CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF); @@ -928,7 +957,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, // Force "splash image" to be loaded from a file, not a resource so same exe can be used in different localizations. -#if defined _DEBUG || defined _INTERNAL || defined _PROFILE +#if defined RTS_DEBUG || defined RTS_INTERNAL || defined RTS_PROFILE // check both localized directory and root dir char filePath[_MAX_PATH]; @@ -988,23 +1017,16 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, #endif - //Create a mutex with a unique name to Generals in order to determine if - //our app is already running. - //WARNING: DO NOT use this number for any other application except Generals. - GeneralsMutex = CreateMutex(NULL, FALSE, GENERALS_GUID); - if (GetLastError() == ERROR_ALREADY_EXISTS) + // TheSuperHackers @refactor The instance mutex now lives in its own class. + + if (!rts::ClientInstance::initialize()) { - HWND ccwindow = FindWindow(GENERALS_GUID, NULL); + HWND ccwindow = FindWindow(rts::ClientInstance::getFirstInstanceName(), NULL); if (ccwindow) { SetForegroundWindow(ccwindow); ShowWindow(ccwindow, SW_RESTORE); } - if (GeneralsMutex != NULL) - { - CloseHandle(GeneralsMutex); - GeneralsMutex = NULL; - } DEBUG_LOG(("Generals is already running...Bail!\n")); delete TheVersion; @@ -1013,7 +1035,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, DEBUG_SHUTDOWN(); return 0; } - DEBUG_LOG(("Create GeneralsMutex okay.\n")); + DEBUG_LOG(("Create Generals Mutex okay.\n")); #ifdef DO_COPY_PROTECTION if (!CopyProtect::notifyLauncher()) @@ -1043,7 +1065,7 @@ Int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, #ifdef MEMORYPOOL_DEBUG TheMemoryPoolFactory->debugMemoryReport(REPORT_POOLINFO | REPORT_POOL_OVERFLOW | REPORT_SIMPLE_LEAKS, 0, 0); #endif - #if defined(_DEBUG) || defined(_INTERNAL) + #if defined(RTS_DEBUG) || defined(RTS_INTERNAL) TheMemoryPoolFactory->memoryPoolUsageReport("AAAMemStats"); #endif diff --git a/GeneralsMD/Code/Tools/Autorun/ARButton_Reg.bmp b/GeneralsMD/Code/Tools/Autorun/ARButton_Reg.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/ARButton_Reg.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/ARButton_Sel.bmp b/GeneralsMD/Code/Tools/Autorun/ARButton_Sel.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/ARButton_Sel.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/AutoRun_Frn.bmp b/GeneralsMD/Code/Tools/Autorun/AutoRun_Frn.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/AutoRun_Frn.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/AutoRun_Ger.bmp b/GeneralsMD/Code/Tools/Autorun/AutoRun_Ger.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/AutoRun_Ger.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/Autorun.ICO b/GeneralsMD/Code/Tools/Autorun/Autorun.ICO deleted file mode 100644 index b261881cd7..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/Autorun.ICO and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/Autorun_BG.bmp b/GeneralsMD/Code/Tools/Autorun/Autorun_BG.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/Autorun_BG.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/Bullet.bmp b/GeneralsMD/Code/Tools/Autorun/Bullet.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/Bullet.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/CDCNTRL.CPP b/GeneralsMD/Code/Tools/Autorun/CDCNTRL.CPP deleted file mode 100644 index 82906f01de..0000000000 --- a/GeneralsMD/Code/Tools/Autorun/CDCNTRL.CPP +++ /dev/null @@ -1,1116 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -/*********************************************************************************************** - *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** - *********************************************************************************************** - * * - * Project Name : Command & Conquer * - * * - * $Archive:: /Renegade Setup/Autorun/CDCNTRL.CPP $* - * * - * $Author:: Maria_l $* - * * - * $Modtime:: 10/18/01 5:33p $* - * * - * $Revision:: 5 $* - * * - *---------------------------------------------------------------------------------------------* - * Functions: * - * * - * CDControlClass::Auto_Eject_Volume -- Eject the removable media * - * CDControlClass::Auto_Eject_Volume_95 -- Eject the specified CD drive * - * CDControlClass::CDControlClass -- Class constructor * - * CDControlClass::Close_Removable_Volume -- Close the handle to a removable volume * - * CDControlClass::Close_VWin32 -- Closes the handle opened by Open_VWin32. * - * CDControlClass::Dismount_Volume -- Dismount the given volume * - * CDControlClass::Eject_CD -- Force the CD drive to eject * - * CDControlClass::Eject_CD_Win95 -- Eject the cd in the given drive * - * CDControlClass::Force_CD_Eject -- Ppen the CD tray on the given drive * - * CDControlClass::Lock_CD_Drive -- Lock the CD tray and prevent ejection * - * CDControlClass::Lock_CD_Drive_95 -- Prevent the user from ejecting the cd in the given driv* - * CDControlClass::Lock_CD_Tray -- Prevent CD ejection on the specified drive * - * CDControlClass::Lock_Logical_Volume -- Take a lock on a logical volume * - * CDControlClass::Lock_Volume -- Prevent access by other threads to a given volume * - * CDControlClass::Lock_Volume_95 -- Locks removable media so that it can't be ejected * - * CDControlClass::Open_Removable_Volume -- Fetch a handle to a removable drive * - * CDControlClass::Open_VWin32 -- Opens a handle to VWIN32 to issue low-level disk I/O * - * CDControlClass::Prevent_Removal_Of_Volume -- Disable the eject button on the given drive * - * CDControlClass::Unlock_CD_Drive -- Unlock the CD tray and allow ejection * - * CDControlClass::Unlock_CD_Drive_95 -- Allow the user to eject the cd in the given drive * - * CDControlClass::Unlock_CD_Tray -- Allow CD ejection on the specified drive * - * CDControlClass::Unlock_Logical_Volume -- Unlocks a logical volume * - * CDControlClass::Unlock_Volume -- Allow access by other threads to a given volume * - * CDControlClass::Unlock_Volume_95 -- Unlocks removable media so that it can be ejected * - * CDControlClass::~CDControlClass -- Class destructor * - * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - -#include "assert.h" -#include "CDCNTRL.H" -#include "WinFix.H" -#include "Wnd_File.h" -#pragma warning(disable : 4201) -#include -#include -#include - - -CDControlClass CDControl; - - -void Last_Error_Text ( LPCTSTR szPrefix, HRESULT hr ); - - -/*********************************************************************************************** - * CDControlClass::CDControlClass -- Class constructor * - * * - * INPUT: Nothing * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 2:03AM ST : Created * - *=============================================================================================*/ -CDControlClass::CDControlClass(void) -{ -} - - -/*********************************************************************************************** - * CDControlClass::~CDControlClass -- Class destructor * - * * - * INPUT: Nothing * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 2:03AM ST : Created * - *=============================================================================================*/ -CDControlClass::~CDControlClass(void) -{ -} - -/*********************************************************************************************** - * CDControlClass::Force_CD_Eject -- Ppen the CD tray on the given drive * - * * - * INPUT: Drive number (0=a, 1=b etc) * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 1:17AM ST : Created * - *=============================================================================================*/ -void CDControlClass::Force_CD_Eject(int drive) -{ - if ( WinVersion.Is_Win9x() ) { - Eject_CD_Win95(drive); - }else{ - Eject_CD(drive); - } -} - -/*********************************************************************************************** - * CDControlClass::Lock_CD_Tray -- Prevent CD ejection on the specified drive * - * * - * INPUT: drive number (0=a: etc) * - * * - * OUTPUT: true if locked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 1:56AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Lock_CD_Tray (int drive) -{ - if ( WinVersion.Is_Win9x() ) { - return (Lock_CD_Drive_95(drive)); - }else{ - return (Lock_CD_Drive(drive)); - } -} - -/*********************************************************************************************** - * CDControlClass::Unlock_CD_Tray -- Allow CD ejection on the specified drive * - * * - * INPUT: drive number (0=a: etc) * - * * - * OUTPUT: true if unlocked OK * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 1:57AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Unlock_CD_Tray (int drive) -{ - if ( WinVersion.Is_Win9x() ) { - return (Unlock_CD_Drive_95(drive)); - }else{ - return (Unlock_CD_Drive(drive)); - } -} - -/*********************************************************************************************** - * CDControlClass::Open_Removable_Volume -- Fetch a handle to a removable drive * - * * - * INPUT: Nothing * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:25PM ST : Created * - *=============================================================================================*/ -HANDLE CDControlClass::Open_Removable_Volume( char drive ) -{ - assert (WinVersion.Is_WinNT()); - - HANDLE volume; - unsigned drivetype; - char volume_name[8]; - char rootname[5]; - unsigned long access_flags; - - /*---------------------------------------------------------------------------------------- - ** Get the drive type to ensure that this is a removable volume. - */ - _stprintf (rootname, _TEXT( "%c:\\" ), drive + 'A'); - drivetype = GetDriveType( rootname ); - - switch( drivetype ) { - - case DRIVE_REMOVABLE: - access_flags = GENERIC_READ | GENERIC_WRITE; - break; - - case DRIVE_CDROM: - access_flags = GENERIC_READ; - break; - - default: -// DebugString ("Attempt to open non-removable volume for locking or ejection\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("Attempt to open non-removable volume for locking or ejection" )); - return( INVALID_HANDLE_VALUE ); - } - - /*---------------------------------------------------------------------------------------- - ** Get a handle to the volume. - */ - _stprintf( volume_name, _TEXT( "\\\\.\\%c:" ), drive + 'A' ); - volume = CreateFile( volume_name, access_flags, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); - -// assert (volume != INVALID_HANDLE_VALUE); - - if ( volume == INVALID_HANDLE_VALUE ) { -// DebugString ("Unable to open drive %c: for ejection\n", drive + 'A'); - Msg( __LINE__, TEXT(__FILE__), TEXT("Unable to open drive %c: for ejection"), drive + 'A' - 1 ); - } - return( volume ); -} - -/*********************************************************************************************** - * CDControlClass::Close_Removable_Volume -- Close the handle to a removable volume * - * * - * INPUT: HANDLE of volume to close * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:27PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Close_Removable_Volume(HANDLE volume) -{ - assert (WinVersion.Is_WinNT()); - return ((CloseHandle(volume)) ? true : false); -} - -/*********************************************************************************************** - * CDControlClass::Lock_Volume -- Prevent access by other threads to a given volume * - * * - * INPUT: HANDLE to volume * - * * - * OUTPUT: true if locked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:29PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Lock_Volume( HANDLE volume ) -{ - assert( WinVersion.Is_WinNT( )); - - unsigned long bytes_returned = 0; - unsigned long sleep_amount = LOCK_TIMEOUT / LOCK_RETRIES; - - /* - ** Do this in a loop until a timeout period has expired - */ - for ( int trycount = 0; trycount < LOCK_RETRIES; trycount++ ) { - - if ( DeviceIoControl( volume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL )) { - return( true ); - } -// Msg( __LINE__, TEXT(__FILE__), TEXT("DeviceIoControl failed to lock volume. Error %d - %s"), GetLastError(), Last_Error_Text()); - Last_Error_Text( _TEXT( "DeviceIoControl failed to lock volume." ), GetLastError()); -// Sleep( sleep_amount ); - Sleep( LOCK_TIMEOUT ); - } - return( false ); -} - -/*********************************************************************************************** - * CDControlClass::Unlock_Volume -- Allow access by other threads to a given volume * - * * - * INPUT: HANDLE to volume * - * * - * OUTPUT: true if unlocked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:29PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Unlock_Volume(HANDLE volume) -{ - assert( WinVersion.Is_WinNT()); - - unsigned long bytes_returned; - unsigned long sleep_amount = LOCK_TIMEOUT / LOCK_RETRIES; - - /* - ** Do this in a loop until a timeout period has expired - */ - for ( int trycount = 0; trycount < LOCK_RETRIES; trycount++ ) { - - if ( DeviceIoControl( volume, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL )) return( true ); -// DebugString ("DeviceIoControl failed to unlock volume. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to unlock volume. Error %d - %s", GetLastError(), Last_Error_Text()); - Last_Error_Text( _TEXT( "DeviceIoControl failed to unlock volume." ), GetLastError()); -// Sleep( sleep_amount ); - Sleep( LOCK_TIMEOUT ); - } - return( false ); -} - -/*********************************************************************************************** - * CDControlClass::Dismount_Volume -- Dismount the given volume * - * * - * INPUT: HANDLE of volume to dismount * - * * - * OUTPUT: true if volume dismounted OK * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:31PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Dismount_Volume(HANDLE volume) -{ - assert( WinVersion.Is_WinNT()); - - unsigned long bytes_returned; - bool result = ((DeviceIoControl( volume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL)) ? true : false ); - - if (result == false) { -// DebugString ("DeviceIoControl failed to dismount volume. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to dismount volume. Error %d - %s", GetLastError(), Last_Error_Text()); - Last_Error_Text( _TEXT( "DeviceIoControl failed to dismount volume." ), GetLastError()); - } - return( result ); -} - -/*********************************************************************************************** - * CDControlClass::Prevent_Removal_Of_Volume -- Disable the eject button on the given drive * - * * - * INPUT: HANDLE of volume to enable/disable * - * true to prevent removal. false to allow it. * - * * - * OUTPUT: true if status changed OK * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:32PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Prevent_Removal_Of_Volume( HANDLE volume, bool prevent ) -{ - assert( WinVersion.Is_WinNT()); - - unsigned long bytes_returned; - PREVENT_MEDIA_REMOVAL pmrbuffer; - - pmrbuffer.PreventMediaRemoval = prevent; - - bool result = ((DeviceIoControl( volume, IOCTL_STORAGE_MEDIA_REMOVAL, &pmrbuffer, sizeof(PREVENT_MEDIA_REMOVAL), NULL, 0, &bytes_returned, NULL)) ? true : false); - - if (result == false) { -// DebugString ("DeviceIoControl failed to prevent media removal. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to prevent media removal. Error %d - %s", GetLastError(), Last_Error_Text()); - Last_Error_Text( _TEXT( "DeviceIoControl failed to prevent media removal." ), GetLastError()); - } - return( result ); -} - -/*********************************************************************************************** - * CDControlClass::Auto_Eject_Volume -- Eject the removable media * - * * - * INPUT: HANDLE of volume to eject * - * * - * OUTPUT: true if ejection occured * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:34PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Auto_Eject_Volume(HANDLE volume) -{ - assert (WinVersion.Is_WinNT()); - unsigned long bytes_returned; - bool result = ((DeviceIoControl( volume, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &bytes_returned, NULL)) ? true : false); - - if (result == false) { -// DebugString ("DeviceIoControl failed to eject media. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to eject media. Error %d - %s", GetLastError(), Last_Error_Text()); - Last_Error_Text( TEXT("DeviceIoControl failed to eject media."), GetLastError()); - } - return (result); -} - -/*********************************************************************************************** - * CDControlClass::Eject_CD -- Force the CD drive to eject * - * * - * INPUT: drive number * - * * - * OUTPUT: true if ejected * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/16/99 11:35PM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Eject_CD(char drive) -{ - assert (WinVersion.Is_WinNT()); - HANDLE volume; - bool ejected = false; - - volume = Open_Removable_Volume(drive); - - if (volume == INVALID_HANDLE_VALUE) return (false); - - /* - ** Lock and dismount the volume. - */ - if (Lock_Volume(volume) && Dismount_Volume(volume)) { - - /* - ** Set prevent removal to false and eject the volume. - */ - if (Prevent_Removal_Of_Volume(volume, false) && Auto_Eject_Volume(volume)) { - ejected = true; - } - } - - /* - ** Close the volume so other processes can use the drive. - */ - Close_Removable_Volume(volume); - - return (ejected); -} - -/*********************************************************************************************** - * CDControlClass::Lock_CD_Drive -- Lock the CD tray and prevent ejection * - * * - * INPUT: drive number * - * * - * OUTPUT: true if locked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:11AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Lock_CD_Drive(char drive) -{ - assert (WinVersion.Is_WinNT()); - HANDLE volume; - bool retval = false; - - volume = Open_Removable_Volume(drive); - - if (volume == INVALID_HANDLE_VALUE) return (false); - - /* - ** Lock the volume. - */ - if (Lock_Volume(volume)) { - - /* - ** Set prevent removal to false - */ - if (Prevent_Removal_Of_Volume(volume, true)) { - retval = true; - } - } - - /* - ** Close the volume so other processes can use the drive. - */ - Unlock_Volume(volume); - Close_Removable_Volume(volume); - - return (true); -} - -/*********************************************************************************************** - * CDControlClass::Unlock_CD_Drive -- Unlock the CD tray and allow ejection * - * * - * INPUT: drive number * - * * - * OUTPUT: true if unlocked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:11AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Unlock_CD_Drive(char drive) -{ - assert (WinVersion.Is_WinNT()); - HANDLE volume; - bool retval = false; - - volume = Open_Removable_Volume(drive); - - if (volume == INVALID_HANDLE_VALUE) return (false); - - /* - ** Lock the volume. - */ - if (Lock_Volume(volume)) { - - /* - ** Set prevent removal to false - */ - if (Prevent_Removal_Of_Volume(volume, false)) { - retval = true; - } - } - - /* - ** Close the volume so other processes can use the drive. - */ - Unlock_Volume(volume); - Close_Removable_Volume(volume); - - return (true); -} - -/*********************************************************************************************** - * CDControlClass::Eject_CD_Win95 -- Eject the cd in the given drive * - * * - * INPUT: drive. 0=a etc. * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 1:04AM ST : Created * - *=============================================================================================*/ -void CDControlClass::Eject_CD_Win95 (char drive) -{ - assert (WinVersion.Is_Win9x()); - HANDLE vwin32 = INVALID_HANDLE_VALUE; - - drive++; - vwin32 = Open_VWin32 (); - assert (vwin32 != INVALID_HANDLE_VALUE); - - /* - ** Make sure no other applications are using the drive. - */ - bool drive_locked = Lock_Logical_Volume (vwin32, drive, 0, 0); -// assert (drive_locked); - if (!drive_locked) { -// DebugString("Unable to lock volume %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Unable to lock volume %c: "), 'A' + drive - 1 ); - return; - } - - /* - ** Make sure there is no software lock keeping the media in the drive. - */ - if (!Unlock_Volume_95 (vwin32, drive)) { -// DebugString("Could not unlock media from drive %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Could not unlock media from drive %c: "), 'A' + drive - 1 ); - Unlock_Logical_Volume (vwin32, drive); - return; - } - - /* - ** Eject! - */ - if (!Auto_Eject_Volume_95 (vwin32, drive)) { -// DebugString("Could not eject media from drive %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Could not eject media from drive %c: "), 'A' + drive - 1 ); - } - - Unlock_Logical_Volume (vwin32, drive); - Close_VWin32 (vwin32); -} - -/*********************************************************************************************** - * CDControlClass::Lock_CD_Drive_95 -- Prevent the user from ejecting the cd in the given drive* - * * - * INPUT: drive. 0=a etc. * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 1:04AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Lock_CD_Drive_95 (char drive) -{ -// DebugString ("CDControlClass::Lock_CD_Drive_95\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("CDControlClass::Lock_CD_Drive_95." )); - - bool retval = true; - assert (WinVersion.Is_Win9x()); - HANDLE vwin32 = INVALID_HANDLE_VALUE; - -// DebugString ("Preventing ejection on CD drive %c\n", drive + 'A'); - Msg( __LINE__, TEXT(__FILE__), TEXT("Preventing ejection on CD drive %c: "), 'A' + drive -1 ); - - drive++; - vwin32 = Open_VWin32(); - assert (vwin32 != INVALID_HANDLE_VALUE); - - /* - ** Make sure no other applications are using the drive. - */ -// DebugString ("About to lock logical volume to enable exclusive access\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("About to lock logical volume to enable exclusive access." )); - - bool drive_locked = Lock_Logical_Volume (vwin32, drive, 0, 0); -// assert (drive_locked); - if (!drive_locked) { -// DebugString("Unable to lock volume %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Unable to lock volume %c:"), 'A' + drive - 1 ); - return(false); - } -// DebugString ("Volume locked OK\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("Volume locked OK." )); - - /* - ** Lock the tray in the closed position. - */ -// DebugString ("About to prevent CD tray ejection\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("About to prevent CD tray ejection." )); - - if (!Lock_Volume_95 (vwin32, drive)) { -// DebugString("Could not lock CD tray in drive %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Could not lock CD tray in drive %c:"), 'A' + drive - 1 ); - retval = false; - }else{ -// DebugString ("CD tray ejection disabled OK\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("CD tray ejection disabled OK." )); - } - - Unlock_Logical_Volume (vwin32, drive); - Close_VWin32 (vwin32); - -// DebugString ("CDControlClass::Lock_CD_Drive_95 returning %s\n", retval ? "true" : "false"); - Msg( __LINE__, TEXT(__FILE__), TEXT("CDControlClass::Lock_CD_Drive_95 returning %s."), retval ? "true" : "false" ); - - return (retval); -} - -/*********************************************************************************************** - * CDControlClass::Unlock_CD_Drive_95 -- Allow the user to eject the cd in the given drive * - * * - * INPUT: drive. 0=a etc. * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 1:04AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Unlock_CD_Drive_95 (char drive) -{ -// DebugString ("CDControlClass::Unlock_CD_Drive_95\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("CDControlClass::Unlock_CD_Drive_95 returning %s." )); - - bool retval = true; - assert (WinVersion.Is_Win9x()); - HANDLE vwin32 = INVALID_HANDLE_VALUE; - -// DebugString ("Allowing ejection on CD drive %c\n", drive + 'A'); - Msg( __LINE__, TEXT(__FILE__), TEXT("Allowing ejection on CD drive %c."), drive + 'A' - 1 ); - - drive++; - vwin32 = Open_VWin32(); - assert (vwin32 != INVALID_HANDLE_VALUE); - - /* - ** Make sure no other applications are using the drive. - */ -// DebugString ("About to lock logical volume to enable exclusive access\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("About to lock logical volume to enable exclusive access." )); - - bool drive_locked = Lock_Logical_Volume (vwin32, drive, 0, 0); -// assert (drive_locked); - if (!drive_locked) { -// DebugString("Unable to lock volume %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Unable to lock volume %c:."), 'A' + drive - 1 ); - return(false); - } -// DebugString ("Volume locked OK\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("Volume locked OK." )); - - /* - ** Unlock the tray to allow ejection. - */ -// DebugString ("About to allow CD tray ejection\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("About to allow CD tray ejection." )); - - if (!Unlock_Volume_95 (vwin32, drive)) { -// DebugString("Could not unlock CD tray in drive %c:\n", 'A' + drive - 1); - Msg( __LINE__, TEXT(__FILE__), TEXT("Could not unlock CD tray in drive %c:"), 'A' + drive - 1 ); - retval = false; - }else{ -// DebugString ("CD tray ejection enabled OK\n"); - Msg( __LINE__, TEXT(__FILE__), TEXT("CD tray ejection enabled OK." )); - } - - Unlock_Logical_Volume (vwin32, drive); - Close_VWin32 (vwin32); - -// DebugString ("CDControlClass::Unlock_CD_Drive_95 returning %s\n", retval ? "true" : "false"); - Msg( __LINE__, TEXT(__FILE__), TEXT("CDControlClass::Unlock_CD_Drive_95 returning %s."), retval ? "true" : "false" ); - return (retval); -} - -/*********************************************************************************************** - * CDControlClass::Unlock_Volume_95 -- Unlocks removable media so that it can be ejected * - * * - * INPUT: Handle to VWIN32 * - * drive to unlock (DOS format) * - * * - * OUTPUT: true if unlocked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:19AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Unlock_Volume_95 (HANDLE vwin32, char drive) -{ - assert (WinVersion.Is_Win9x()); - DIOC_REGISTERS regs = {0}; - PARAMBLOCK unlock_params = {0}; - bool result; - unsigned long cb; - - /* - ** First, check the lock status. This way, we'll know the number of pending locks we must unlock. - */ - unlock_params.bOperation = 2; // return lock/unlock status - - regs.reg_EAX = 0x440D; - regs.reg_EBX = drive; - regs.reg_ECX = MAKEWORD(0x48, 0x08); - regs.reg_EDX = (unsigned long)&unlock_params; - - result = (DeviceIoControl (vwin32, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &cb, 0)) ? true : false; - - if (result) { - - /* - ** DeviceIoControl succeeded. Now see if the unlock succeeded. It - ** succeeded if the carry flag is not set, or if the carry flag is - ** set but EAX is 0x01 or 0xB0. - ** - ** It failed if the carry flag is set and EAX is not 0x01 or 0xB0. - ** - ** If the carry flag is clear, then unlock succeeded. However, you - ** don't need to set fResult because it is already TRUE when you get - ** in here. - */ - if (regs.reg_Flags & CARRY_FLAG) { - result = (regs.reg_EAX == 0xB0) || (regs.reg_EAX == 0x01); - } - - } else { -// DebugString ("DeviceIoControl failed to perform DOS IO control function. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to perform DOS IO control function. Error %d - %s.", GetLastError(), Last_Error_Text() ); - Last_Error_Text( TEXT("DeviceIoControl failed to perform DOS IO control function.."), GetLastError()); - } - - if (!result) return (false); - - /* - ** Now we have to unlock the media for every time it was locked. This gets us a lock count of - ** 0 and totally unlocked media. - */ - for (int i = 0; i < unlock_params.bNumLocks; ++i) { - unlock_params.bOperation = 1; // unlock the media - regs.reg_EAX = 0x440D; - regs.reg_EBX = drive; - regs.reg_ECX = MAKEWORD(0x48, 0x08); // LOCK/UNLOCK - regs.reg_EDX = (unsigned long)&unlock_params; - - result = (DeviceIoControl (vwin32, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &cb, 0)) ? true : false; - if (result == false) { -// DebugString ("DeviceIoControl failed to perform DOS IO control function. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to perform DOS IO control function. Error %d - %s.", GetLastError(), Last_Error_Text() ); - Last_Error_Text( TEXT("DeviceIoControl failed to perform DOS IO control function.."), GetLastError()); - } - - /* - ** See if DeviceIoControl and the lock succeeded - */ - result = result && !(regs.reg_Flags & CARRY_FLAG); - if (!result) break; - } - return (result); -} - -/*********************************************************************************************** - * CDControlClass::Lock_Volume_95 -- Locks removable media so that it can't be ejected * - * * - * INPUT: Handle to VWIN32 * - * drive to lock (DOS format) * - * * - * OUTPUT: true if unlocked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:19AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Lock_Volume_95 (HANDLE vwin32, char drive) -{ - assert (WinVersion.Is_Win9x()); - DIOC_REGISTERS regs = {0}; - PARAMBLOCK unlock_params = {0}; - bool result; - unsigned long cb; - - /* - ** Bring the lock count down to 0. - */ - Unlock_Volume_95(vwin32, drive); - - /* - ** Increment the lock count. - */ - unlock_params.bOperation = 0; // lock the media - regs.reg_EAX = 0x440D; - regs.reg_EBX = drive; - regs.reg_ECX = MAKEWORD(0x48, 0x08); // LOCK/UNLOCK - regs.reg_EDX = (unsigned long)&unlock_params; - - result = (DeviceIoControl (vwin32, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &cb, 0)) ? true : false; - if (result == false) { -// DebugString ("DeviceIoControl failed to perform DOS IO control function. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to perform DOS IO control function. Error %d - %s.", GetLastError(), Last_Error_Text() ); - Last_Error_Text( TEXT("DeviceIoControl failed to perform DOS IO control function."), GetLastError()); - } - - /* - ** See if DeviceIoControl and the lock succeeded - */ - result = result && !(regs.reg_Flags & CARRY_FLAG); - return (result); -} - -/*********************************************************************************************** - * CDControlClass::Auto_Eject_Volume_95 -- Eject the specified CD drive * - * * - * INPUT: Handle to VWIN32 * - * Drive number (DOS format) * - * * - * OUTPUT: True if ejected * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:24AM ST : Created * - *=============================================================================================*/ -bool CDControlClass::Auto_Eject_Volume_95 (HANDLE vwin32, char drive) -{ - assert (WinVersion.Is_Win9x()); - DIOC_REGISTERS regs = {0}; - bool result; - unsigned long cb; - - regs.reg_EAX = 0x440D; - regs.reg_EBX = drive; - regs.reg_ECX = MAKEWORD(0x49, 0x08); //EJECT - - result = (DeviceIoControl (vwin32, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &cb, 0)) ? true : false; - if (result == false) { -// DebugString ("DeviceIoControl failed to perform DOS IO control function. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to perform DOS IO control function. Error %d - %s.", GetLastError(), Last_Error_Text() ); - Last_Error_Text( TEXT("DeviceIoControl failed to perform DOS IO control function."), GetLastError()); - } - - /* - ** See if we ejected OK - */ - result = result && !(regs.reg_Flags & CARRY_FLAG); - - return (result); -} - -/*********************************************************************************************** - * CDControlClass::Open_VWin32 -- Opens a handle to VWIN32 to issue low-level disk I/O * - * * - * INPUT: Nothing * - * * - * OUTPUT: HANDLE to VWin32 * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:26AM ST : Created * - *=============================================================================================*/ -HANDLE WINAPI CDControlClass::Open_VWin32 (void) -{ - assert (WinVersion.Is_Win9x()); - HANDLE result = CreateFile ( TEXT("\\\\.\\vwin32"), 0, 0, NULL, 0, FILE_FLAG_DELETE_ON_CLOSE, NULL); - assert (result != INVALID_HANDLE_VALUE); - return (result); -} - -/*********************************************************************************************** - * CDControlClass::Close_VWin32 -- Closes the handle opened by Open_VWin32. * - * * - * INPUT: Handle to VWin32 * - * * - * OUTPUT: Nothing * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:26AM ST : Created * - *=============================================================================================*/ -bool WINAPI CDControlClass::Close_VWin32 (HANDLE vwin32) -{ - assert (WinVersion.Is_Win9x()); - return ((CloseHandle (vwin32)) ? true : false); -} - -/*********************************************************************************************** - * CDControlClass::Lock_Logical_Volume -- Take a lock on a logical volume * - * * - * INPUT: Handle to VWin32 * - * drive number (DOS format) * - * lock level * - * permissions * - * * - * OUTPUT: true if locked * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 2/17/99 0:33AM ST : Created * - *=============================================================================================*/ -bool WINAPI CDControlClass::Lock_Logical_Volume (HANDLE vwin32, char drive, char lock_level, short permissions) -{ - assert (WinVersion.Is_Win9x()); - bool result; - DIOC_REGISTERS regs = {0}; - char device_cat; // can be either 0x48 or 0x08 - unsigned long cb; - - /* - ** lock_level - ** Can be 0, 1, 2, or 3. Level 0 is an exclusive lock that can only - ** be taken when there are no open files on the specified drive. - ** Levels 1 through 3 form a hierarchy where 1 must be taken before - ** 2, which must be taken before 3. - ** - ** permissions - ** Specifies how the lock will affect file operations when lock levels - ** 1 through 3 are taken. Also specifies whether a formatting lock - ** should be taken after a level 0 lock. - */ - - /* - ** Try first with device category 0x48 for FAT32 volumes. If it - ** doesn't work, try again with device category 0x08. If that - ** doesn't work, then the lock failed. - */ - device_cat = 0; - - do { - if (device_cat == 0) { - device_cat = 0x48; - }else{ - device_cat = 0x08; - } - - /* - ** Set up the parameters for the call. - */ - regs.reg_EAX = 0x440D; - regs.reg_EBX = MAKEWORD(drive, lock_level); - regs.reg_ECX = MAKEWORD(0x4A, device_cat); - regs.reg_EDX = permissions; - - result = (DeviceIoControl (vwin32, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &cb, 0)) ? true : false; - if (result == false) { -// DebugString ("DeviceIoControl failed to perform DOS IO control function. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to perform DOS IO control function. Error %d - %s.", GetLastError(), Last_Error_Text() ); - Last_Error_Text( TEXT("DeviceIoControl failed to perform DOS IO control function."), GetLastError()); - } - result = result && !(regs.reg_Flags & CARRY_FLAG); - - } while (result == false && device_cat != 0x08); - - return (result); -} - -/*********************************************************************************************** - * CDControlClass::Unlock_Logical_Volume -- Unlocks a logical volume * - * * - * INPUT: Handle to VWin32 * - * drive number (DOS format) * - * * - * OUTPUT: true if unlocked * - * * - * WARNINGS: None * - * * - * Must be called the same number of times as LockLogicalVolume() to * - * completely unlock a volume. * - * * - * Only the lock owner can unlock a volume. * - * * - * HISTORY: * - * 2/17/99 0:39AM ST : Created * - *=============================================================================================*/ -bool WINAPI CDControlClass::Unlock_Logical_Volume (HANDLE vwin32, char drive) -{ - assert (WinVersion.Is_Win9x()); - bool result; - DIOC_REGISTERS regs = {0}; - char device_cat; // can be either 0x48 or 0x08 - unsigned long cb; - - /* - ** Try first with device category 0x48 for FAT32 volumes. If it - ** doesn't work, try again with device category 0x08. If that - ** doesn't work, then the unlock failed. - */ - device_cat = 0; - - do { - if (device_cat == 0) { - device_cat = 0x48; - }else{ - device_cat = 0x08; - } - - /* - ** Set up the parameters for the call. - */ - regs.reg_EAX = 0x440D; - regs.reg_EBX = drive; - regs.reg_ECX = MAKEWORD(0x6A, device_cat); - - result = (DeviceIoControl (vwin32, VWIN32_DIOC_DOS_IOCTL, ®s, sizeof(regs), ®s, sizeof(regs), &cb, 0)) ? true : false; - if (result == false) { -// DebugString ("DeviceIoControl failed to perform DOS IO control function. Error %d - %s\n", GetLastError(), Last_Error_Text()); -// Msg( __LINE__, __FILE__, "DeviceIoControl failed to perform DOS IO control function. Error %d - %s.", GetLastError(), Last_Error_Text()); - Last_Error_Text( TEXT("DeviceIoControl failed to perform DOS IO control function."), GetLastError()); - } - result = result && !(regs.reg_Flags & CARRY_FLAG); - - } while (result == false && device_cat != 0x08); - - return (result); -} - -/************************************************************************************************ - * Last_Error_Text -- Display error messages based on FormatMessage() and GetLastError(). * - * * - * INPUT: LPSTR - title. * - * HRESULT - last error message. * - * * - * OUTPUT: None * - * * - * WARNINGS: None * - * * - * HISTORY: * - * 6/24/99 4:44PM MML : Created * - *==============================================================================================*/ - -void Last_Error_Text ( LPCTSTR szPrefix, HRESULT hr ) -{ - LPVOID szMessage; - char szDisplay[1000]; - - if ( hr == S_OK ) { - _stprintf( szDisplay, TEXT("%s"), szPrefix ); -// MessageBox( NULL, szDisplay, TEXT("Msg"),0 ); - return; - } - - if ( HRESULT_FACILITY( hr ) == FACILITY_WIN32 ) { - hr = HRESULT_CODE( hr ); - } - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - hr, - MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), - (LPTSTR)&szMessage, - 0, - NULL ); - - _stprintf( szDisplay, TEXT( "%s: %s(%lx)" ), szPrefix, szMessage, hr ); - - Msg( __LINE__, TEXT(__FILE__), TEXT("GetLastError: %s"), szDisplay ); -// MessageBox( NULL, szDisplay, TEXT( "GetLastError" ), MB_OK ); - - LocalFree( szMessage ); - -} - - - - diff --git a/GeneralsMD/Code/Tools/Autorun/CMakeLists.txt b/GeneralsMD/Code/Tools/Autorun/CMakeLists.txt index 351c79219a..f8a71ea661 100644 --- a/GeneralsMD/Code/Tools/Autorun/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/Autorun/CMakeLists.txt @@ -1,67 +1,10 @@ -set(AUTORUN_SRC - "ARGS.CPP" - "ARGS.H" - "autorun.cpp" - "autorun.h" - "CallbackHook.h" - "CDCNTRL.CPP" - "CDCNTRL.H" - "DrawButton.cpp" - "DrawButton.h" - "EZGIMEX.cpp" - "GameText.cpp" - "GameText.h" - "GETCD.CPP" - "GetCD.h" - "gimex.h" - "IGR.cpp" - "IGR.h" - "Jsupport.cpp" - "JSUPPORT.H" - "leanAndMeanAutorun.h" - "Locale_API.cpp" - "Locale_API.h" - "locale.cpp" - "locale.h" - "POINT.h" - "RECT.h" - "resource.h" - "TTFont.cpp" - "TTFont.h" - "Utils.cpp" - "Utils.h" - "ViewHTML.cpp" - "ViewHTML.h" - "WinFix.CPP" - "WinFix.H" - "Wnd_file.cpp" - "Wnd_File.h" - "WSYS_File.cpp" - "WSYS_file.h" - "WSYS_FileSystem.cpp" - "WSYS_FileSystem.h" - "WSYS_RAMFile.cpp" - "WSYS_RAMFile.h" - "WSYS_StdFile.cpp" - "WSYS_StdFile.h" - "WSYS_StdFileSystem.cpp" - "WSYS_StdFileSystem.h" -) - macro(setup_autorun appname) add_executable(${appname} WIN32) - target_sources(${appname} PRIVATE ${AUTORUN_SRC}) - target_link_libraries(${appname} PRIVATE - core_config - winmm + corei_autorun zi_always ) - - if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(${appname} PRIVATE AUTORUN.RC) - endif() endmacro() setup_autorun(z_autorun_en) diff --git a/GeneralsMD/Code/Tools/Autorun/License French.bmp b/GeneralsMD/Code/Tools/Autorun/License French.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/License French.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/License French2.bmp b/GeneralsMD/Code/Tools/Autorun/License French2.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/License French2.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/License German.bmp b/GeneralsMD/Code/Tools/Autorun/License German.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/License German.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/License German2.bmp b/GeneralsMD/Code/Tools/Autorun/License German2.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/License German2.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/License USA.bmp b/GeneralsMD/Code/Tools/Autorun/License USA.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/License USA.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/License USA2.bmp b/GeneralsMD/Code/Tools/Autorun/License USA2.bmp deleted file mode 100644 index 2582aa9571..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/License USA2.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Autorun/arrow.cur b/GeneralsMD/Code/Tools/Autorun/arrow.cur deleted file mode 100644 index 3d012fff7e..0000000000 Binary files a/GeneralsMD/Code/Tools/Autorun/arrow.cur and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/BABYLON.XLT b/GeneralsMD/Code/Tools/Babylon/BABYLON.XLT deleted file mode 100644 index 6ff3dbf62a..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/BABYLON.XLT and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/bitmap1.bmp b/GeneralsMD/Code/Tools/Babylon/res/bitmap1.bmp deleted file mode 100644 index 3c0c2bc9f3..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/bitmap1.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/noxstring.ico b/GeneralsMD/Code/Tools/Babylon/res/noxstring.ico deleted file mode 100644 index 92531c01d7..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/noxstring.ico and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/noxstring.rc2 b/GeneralsMD/Code/Tools/Babylon/res/noxstring.rc2 deleted file mode 100644 index 6abd7126cb..0000000000 --- a/GeneralsMD/Code/Tools/Babylon/res/noxstring.rc2 +++ /dev/null @@ -1,13 +0,0 @@ -// -// NOXSTRING.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/Tools/Babylon/res/pause.bmp b/GeneralsMD/Code/Tools/Babylon/res/pause.bmp deleted file mode 100644 index 2c0f5b9658..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/pause.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/paused.bmp b/GeneralsMD/Code/Tools/Babylon/res/paused.bmp deleted file mode 100644 index aeb344abda..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/paused.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/playd.bmp b/GeneralsMD/Code/Tools/Babylon/res/playd.bmp deleted file mode 100644 index 53565fdf2f..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/playd.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/playu.bmp b/GeneralsMD/Code/Tools/Babylon/res/playu.bmp deleted file mode 100644 index d41825bb0c..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/playu.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/res/stop.bmp b/GeneralsMD/Code/Tools/Babylon/res/stop.bmp deleted file mode 100644 index 3a1294796a..0000000000 Binary files a/GeneralsMD/Code/Tools/Babylon/res/stop.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/Babylon/resource.hm b/GeneralsMD/Code/Tools/Babylon/resource.hm deleted file mode 100644 index a81ca514f1..0000000000 --- a/GeneralsMD/Code/Tools/Babylon/resource.hm +++ /dev/null @@ -1,5 +0,0 @@ -// Microsoft Developer Studio generated Help ID include file. -// Used by noxstring.rc -// -#define HIDC_PROGRESS1 0x806603ec // IDD_NOXSTRING_DIALOG -#define HIDC_STATUS 0x806603ee // IDD_NOXSTRING_DIALOG diff --git a/GeneralsMD/Code/Tools/CMakeLists.txt b/GeneralsMD/Code/Tools/CMakeLists.txt index 2b47c6323d..b5d2b2a878 100644 --- a/GeneralsMD/Code/Tools/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/CMakeLists.txt @@ -2,7 +2,6 @@ # Build useful tool binaries. if(RTS_BUILD_ZEROHOUR_TOOLS) - add_subdirectory(DebugWindow) add_subdirectory(GUIEdit) add_subdirectory(ImagePacker) add_subdirectory(MapCacheBuilder) @@ -14,18 +13,7 @@ endif() # Build less useful tool/test binaries. if(RTS_BUILD_ZEROHOUR_EXTRAS) - add_subdirectory(assetcull) add_subdirectory(Autorun) - add_subdirectory(Babylon) - add_subdirectory(buildVersionUpdate) - add_subdirectory(CRCDiff) add_subdirectory(Launcher) - add_subdirectory(mangler) - add_subdirectory(matchbot) add_subdirectory(PATCHGET) - add_subdirectory(textureCompress) - add_subdirectory(timingTest) - add_subdirectory(versionUpdate) - add_subdirectory(wolSetup) - add_subdirectory(WW3D) endif() diff --git a/GeneralsMD/Code/Tools/CRCDiff/CMakeLists.txt b/GeneralsMD/Code/Tools/CRCDiff/CMakeLists.txt deleted file mode 100644 index cc2dcbd0c9..0000000000 --- a/GeneralsMD/Code/Tools/CRCDiff/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -set(CRCDIFF_SRC - "CRCDiff.cpp" - "debug.cpp" - "debug.h" - "expander.cpp" - "expander.h" - "KVPair.cpp" - "KVPair.h" - "misc.h" -) - -add_executable(z_crcdiff WIN32) -set_target_properties(z_crcdiff PROPERTIES OUTPUT_NAME crcdiff) - -target_sources(z_crcdiff PRIVATE ${CRCDIFF_SRC}) - -target_link_libraries(z_crcdiff PRIVATE - core_config - core_utility - stlport -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(z_crcdiff PRIVATE /subsystem:console) -endif() diff --git a/GeneralsMD/Code/Tools/CRCDiff/bottom.html b/GeneralsMD/Code/Tools/CRCDiff/bottom.html deleted file mode 100644 index ed4a92524f..0000000000 --- a/GeneralsMD/Code/Tools/CRCDiff/bottom.html +++ /dev/null @@ -1,5 +0,0 @@ - -
- Last - - diff --git a/GeneralsMD/Code/Tools/CRCDiff/row.html b/GeneralsMD/Code/Tools/CRCDiff/row.html deleted file mode 100644 index f15a581ebb..0000000000 --- a/GeneralsMD/Code/Tools/CRCDiff/row.html +++ /dev/null @@ -1,8 +0,0 @@ - - ((LEFTLINE)) - Prev - Top - Bottom - Next - ((RIGHTLINE)) - diff --git a/GeneralsMD/Code/Tools/CRCDiff/style.css b/GeneralsMD/Code/Tools/CRCDiff/style.css deleted file mode 100644 index c3e056c89c..0000000000 --- a/GeneralsMD/Code/Tools/CRCDiff/style.css +++ /dev/null @@ -1,5 +0,0 @@ -td {font-family:monospace; font-size:x-small} -td.leftHistory {color:blue} -td.rightHistory {color:blue} -td.leftDiff {color:red} -td.rightDiff {color:red} diff --git a/GeneralsMD/Code/Tools/CRCDiff/top.html b/GeneralsMD/Code/Tools/CRCDiff/top.html deleted file mode 100644 index eca9252fcd..0000000000 --- a/GeneralsMD/Code/Tools/CRCDiff/top.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - Top - First -
- diff --git a/GeneralsMD/Code/Tools/DebugWindow/CMakeLists.txt b/GeneralsMD/Code/Tools/DebugWindow/CMakeLists.txt deleted file mode 100644 index 5a98e87d8c..0000000000 --- a/GeneralsMD/Code/Tools/DebugWindow/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -set(DEBUGWINDOW_SRC - "DebugWindow.cpp" - "DebugWindow.h" - "DebugWindowDialog.cpp" - "DebugWindowDialog.h" - "DebugWindowExport.h" - "StdAfx.cpp" - "StdAfx.h" -) - -add_library(z_debugwindow SHARED) -set_target_properties(z_debugwindow PROPERTIES OUTPUT_NAME debugwindow) - -target_sources(z_debugwindow PRIVATE ${DEBUGWINDOW_SRC}) - -target_link_libraries(z_debugwindow PRIVATE - core_config -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_compile_definitions(z_debugwindow PRIVATE _AFXDLL) - target_sources(z_debugwindow PRIVATE - DebugWindow.rc - DebugWindow.def - ) - set_target_properties(z_debugwindow PROPERTIES OUTPUT_NAME DebugWindow) -else() - set_target_properties(z_debugwindow PROPERTIES OUTPUT_NAME debugwindow) -endif() diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.def b/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.def deleted file mode 100644 index 1a14c937ee..0000000000 --- a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.def +++ /dev/null @@ -1,6 +0,0 @@ -; DebugWindow.def : Declares the module parameters for the DLL. - -LIBRARY "DebugWindow" -DESCRIPTION 'DebugWindow Windows Dynamic Link Library' - -EXPORTS diff --git a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.rc b/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.rc deleted file mode 100644 index 7722908f21..0000000000 --- a/GeneralsMD/Code/Tools/DebugWindow/DebugWindow.rc +++ /dev/null @@ -1,177 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "#define _AFX_NO_SPLITTER_RESOURCES\r\n" - "#define _AFX_NO_OLE_RESOURCES\r\n" - "#define _AFX_NO_TRACKER_RESOURCES\r\n" - "#define _AFX_NO_PROPERTY_RESOURCES\r\n" - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "#ifdef _WIN32\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#endif //_WIN32\r\n" - "#include ""res\\DebugWindow.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#include ""afxres.rc"" // Standard components\r\n" - "#endif\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "DebugWindow DLL\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "DebugWindow\0" - VALUE "LegalCopyright", "Copyright (C) 2002\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "DebugWindow.DLL\0" - VALUE "ProductName", "DebugWindow Dynamic Link Library\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_DebugWindow DIALOG DISCARDABLE 0, 0, 210, 404 -STYLE DS_MODALFRAME | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Dialog" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Step",IDC_Step,81,7,50,14 - DEFPUSHBUTTON "Step 10",IDC_StepTen,153,7,50,14 - EDITTEXT IDC_Variables,7,43,196,99,ES_MULTILINE | ES_AUTOVSCROLL | - ES_AUTOHSCROLL | ES_READONLY | WS_VSCROLL - EDITTEXT IDC_Messages,7,154,196,247,ES_MULTILINE | ES_AUTOVSCROLL | - ES_READONLY | WS_VSCROLL - LTEXT "Variables",IDC_Variables_Text,7,32,30,8 - LTEXT "Messages",IDC_Messages_Text,7,144,33,8 - DEFPUSHBUTTON "Clear",IDC_ClearWindows,153,26,50,14 - CONTROL "Run Fast (10 X) ",IDC_RUN_FAST,"Button",BS_AUTOCHECKBOX | - BS_PUSHLIKE | WS_TABSTOP,81,26,54,14 - CONTROL "Pause",IDC_Pause,"Button",BS_AUTOCHECKBOX | BS_PUSHLIKE | - WS_TABSTOP,7,7,50,14 - LTEXT "0",IDC_FrameNumber,29,22,44,8 - LTEXT "Frame",IDC_STATIC,7,22,20,8 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_DebugWindow, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 203 - TOPMARGIN, 7 - BOTTOMMARGIN, 397 - END -END -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#define _AFX_NO_SPLITTER_RESOURCES -#define _AFX_NO_OLE_RESOURCES -#define _AFX_NO_TRACKER_RESOURCES -#define _AFX_NO_PROPERTY_RESOURCES - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE 9, 1 -#pragma code_page(1252) -#endif //_WIN32 -#include "res\DebugWindow.rc2" // non-Microsoft Visual C++ edited resources -#include "afxres.rc" // Standard components -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/GeneralsMD/Code/Tools/DebugWindow/post-build.bat b/GeneralsMD/Code/Tools/DebugWindow/post-build.bat deleted file mode 100644 index 9f13c3e38d..0000000000 --- a/GeneralsMD/Code/Tools/DebugWindow/post-build.bat +++ /dev/null @@ -1 +0,0 @@ -@copy debug\debugWindow.dll ..\..\..\Run \ No newline at end of file diff --git a/GeneralsMD/Code/Tools/DebugWindow/res/DebugWindow.rc2 b/GeneralsMD/Code/Tools/DebugWindow/res/DebugWindow.rc2 deleted file mode 100644 index a9778297b9..0000000000 --- a/GeneralsMD/Code/Tools/DebugWindow/res/DebugWindow.rc2 +++ /dev/null @@ -1,13 +0,0 @@ -// -// DEBUGWINDOW.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// diff --git a/GeneralsMD/Code/Tools/GUIEdit/CMakeLists.txt b/GeneralsMD/Code/Tools/GUIEdit/CMakeLists.txt index fcf9a75cc0..e401d8d335 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/GUIEdit/CMakeLists.txt @@ -48,16 +48,16 @@ target_include_directories(z_guiedit PRIVATE target_link_libraries(z_guiedit PRIVATE benchmark comctl32 + core_debug + core_profile d3d8lib dbghelplib imm32 stlport vfw32 winmm - z_debug z_gameengine z_gameenginedevice - z_profile z_wwvegas zi_always ) diff --git a/GeneralsMD/Code/Tools/GUIEdit/Include/GUIEditDisplay.h b/GeneralsMD/Code/Tools/GUIEdit/Include/GUIEditDisplay.h index 14153d61c1..bcae0e79f2 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Include/GUIEditDisplay.h +++ b/GeneralsMD/Code/Tools/GUIEdit/Include/GUIEditDisplay.h @@ -117,11 +117,11 @@ class GUIEditDisplay : public Display virtual void preloadTextureAssets( AsciiString texture ) {} virtual void toggleLetterBox(void) {} virtual void enableLetterBox(Bool enable) {} -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void dumpModelAssets(const char *path) {} #endif virtual void doSmartAssetPurgeAndPreload(const char* usageFileName) {} -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) virtual void dumpAssetUsage(const char* mapname) {} #endif diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp index f4b7cf7521..8230c16bb1 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/Dialog Procedures/ListboxProperties.cpp @@ -600,9 +600,8 @@ static LRESULT CALLBACK listboxPropertiesCallback( HWND hWndDialog, if(newColumns > 1) { - char *percentages = new char[60]; - char *token; - GetDlgItemText(hWndDialog,EDIT_COLUMN_PERCENT,percentages,200); + Char percentages[200]; + GetDlgItemText(hWndDialog,EDIT_COLUMN_PERCENT,percentages,sizeof(percentages)); if(strlen(percentages) == 0) { MessageBox(NULL,"You have specified a column amount greater then 1, please enter the same about of percentages","whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); @@ -612,7 +611,7 @@ static LRESULT CALLBACK listboxPropertiesCallback( HWND hWndDialog, Int *newPercentages = new Int[newColumns]; Int i = 0; Int total = 0; - token = strtok( percentages, "," ); + Char *token = strtok( percentages, "," ); while( token != NULL ) { newPercentages[i] = atoi(token); @@ -621,23 +620,26 @@ static LRESULT CALLBACK listboxPropertiesCallback( HWND hWndDialog, i++; if(i > newColumns && token) { - Char *whoopsMsg = new char[250]; + Char whoopsMsg[250]; sprintf(whoopsMsg,"You have Specified %d columns but I have read in more then that for the percentages, please double check your data", newColumns); MessageBox(NULL, whoopsMsg,"Whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); + delete[] newPercentages; return 0; } else if( i < newColumns && !token ) { - Char *whoopsMsg = new char[250]; + Char whoopsMsg[250]; sprintf(whoopsMsg,"You have Specified %d columns but I have read in only %d for the percentages, please double check your data", newColumns, i ); MessageBox(NULL, whoopsMsg,"Whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); + delete[] newPercentages; return 0; } else if((total > 100 ) || (total < 100 && !token )) { - Char *whoopsMsg = new char[250]; - sprintf(whoopsMsg,"Please Double check to make sure your percentages add up to 100.", newColumns, i - 1); + Char whoopsMsg[250]; + sprintf(whoopsMsg,"Please Double check to make sure your percentages add up to 100."); MessageBox(NULL, whoopsMsg,"Whoops",MB_OK | MB_ICONSTOP | MB_APPLMODAL); + delete[] newPercentages; return 0; } } @@ -941,8 +943,8 @@ HWND InitListboxPropertiesDialog( GameWindow *window ) SetDlgItemInt( dialog, EDIT_NUM_COLUMNS, listData->columns, FALSE ); if(listData->columns > 1) { - char *percentages = new char[60]; - char *tempStr = new char[60]; + Char percentages[200]; + Char tempStr[33]; sprintf(percentages,"%d",listData->columnWidthPercentage[0]); for(Int i = 1; i < listData->columns; i++ ) { diff --git a/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp b/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp index 0552abde55..ecd0a9eed1 100644 --- a/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp +++ b/GeneralsMD/Code/Tools/GUIEdit/Source/LayoutScheme.cpp @@ -2349,33 +2349,44 @@ Bool LayoutScheme::loadScheme( char *filename ) // write header Int version; - fscanf( fp, "Window Layout Scheme: Version '%d'\n", &version ); - if( version != SCHEME_VERSION ) + if (fscanf( fp, "Window Layout Scheme: Version '%d'\n", &version ) == 1) { + if( version != SCHEME_VERSION ) + { - DEBUG_LOG(( "loadScheme: Old layout file version '%d'\n", version )); - MessageBox( TheEditor->getWindowHandle(), - "Old layout version, cannot open.", "Old File", MB_OK ); - return FALSE; + DEBUG_LOG(( "loadScheme: Old layout file version '%d'\n", version )); + MessageBox( TheEditor->getWindowHandle(), + "Old layout version, cannot open.", "Old File", MB_OK ); + return FALSE; - } // end if + } // end if + } // default text colors - fscanf( fp, "Enabled Text: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_enabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); - fscanf( fp, "Enabled Text Border: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_enabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); - - fscanf( fp, "Disabled Text: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_disabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); - fscanf( fp, "Disabled Text Border: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_disabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); - - fscanf( fp, "Hilite Text: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_hiliteText.color = GameMakeColor( colorR, colorG, colorB, colorA ); - fscanf( fp, "Hilite Text Border: (%d,%d,%d,%d)\n", &colorR, &colorG, &colorB, &colorA ); - m_hiliteText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); - + if (fscanf( fp, "Enabled Text: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_enabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Enabled Text Border: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_enabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Disabled Text: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_disabledText.color = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Disabled Text Border: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_disabledText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Hilite Text: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_hiliteText.color = GameMakeColor( colorR, colorG, colorB, colorA ); + } + if (fscanf( fp, "Hilite Text Border: (%hhu,%hhu,%hhu,%hhu)\n", &colorR, &colorG, &colorB, &colorA ) == 4) + { + m_hiliteText.borderColor = GameMakeColor( colorR, colorG, colorB, colorA ); + } // default font char fontBuffer[ 256 ]; Int size, bold; @@ -2399,33 +2410,36 @@ Bool LayoutScheme::loadScheme( char *filename ) c = fgetc( fp ); // the end quite itself // read the size and bold data elements - fscanf( fp, " Size: %d Bold: %d\n", &size, &bold ); - - // set the font - m_font = TheFontLibrary->getFont( AsciiString(fontBuffer), size, bold ); + if(fscanf( fp, " Size: %i Bold: %i\n", &size, &bold ) == 2) + { + // set the font + m_font = TheFontLibrary->getFont( AsciiString(fontBuffer), size, bold ); + } // all the data for all the states Int numStates, state; char imageBuffer[ 128 ]; - fscanf( fp, "Number of states: %d\n", &numStates ); - for( Int i = 0; i < numStates; i++ ) + if (fscanf( fp, "Number of states: %i\n", &numStates ) == 1) { + for( Int i = 0; i < numStates; i++ ) + { - // read all the data - fscanf( fp, "%d: Image: %s Color: (%d,%d,%d,%d) Border: (%d,%d,%d,%d)\n", - &state, imageBuffer, &colorR, &colorG, &colorB, &colorA, - &bColorR, &bColorG, &bColorB, &bColorA ); - - // sanity - assert( state == i ); - - // store the info - storeImageAndColor( (StateIdentifier)state, - TheMappedImageCollection->findImageByName( AsciiString( imageBuffer ) ), - GameMakeColor( colorR, colorG, colorB, colorA ), - GameMakeColor( bColorR, bColorG, bColorB, bColorA ) ); - - } // end for i + // read all the data + if( fscanf( fp, "%d: Image: %s Color: (%hhu,%hhu,%hhu,%hhu) Border: (%hhu,%hhu,%hhu,%hhu)\n", + &state, imageBuffer, &colorR, &colorG, &colorB, &colorA, + &bColorR, &bColorG, &bColorB, &bColorA ) == 10) + { + // sanity + assert( state == i ); + + // store the info + storeImageAndColor( (StateIdentifier)state, + TheMappedImageCollection->findImageByName( AsciiString( imageBuffer ) ), + GameMakeColor( colorR, colorG, colorB, colorA ), + GameMakeColor( bColorR, bColorG, bColorB, bColorA ) ); + } + } // end for i + } // close the file fclose( fp ); diff --git a/GeneralsMD/Code/Tools/ImagePacker/CMakeLists.txt b/GeneralsMD/Code/Tools/ImagePacker/CMakeLists.txt index c7affb096a..ae76437d9f 100644 --- a/GeneralsMD/Code/Tools/ImagePacker/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/ImagePacker/CMakeLists.txt @@ -1,45 +1,9 @@ -set(IMAGEPACKER_SRC - "Include/ImageDirectory.h" - "Include/ImageInfo.h" - "Include/ImagePacker.h" - "Include/TexturePage.h" - "Include/WindowProc.h" - "Include/WinMain.h" - "Source/ImageInfo.cpp" - "Source/ImagePacker.cpp" - "Source/TexturePage.cpp" - "Source/WinMain.cpp" - "Source/Window Procedures/DirectorySelect.cpp" - "Source/Window Procedures/ImageErrorProc.cpp" - "Source/Window Procedures/ImagePackerProc.cpp" - "Source/Window Procedures/PageErrorProc.cpp" - "Source/Window Procedures/PreviewProc.cpp" -) - add_executable(z_imagepacker WIN32) set_target_properties(z_imagepacker PROPERTIES OUTPUT_NAME imagepacker) -target_sources(z_imagepacker PRIVATE ${IMAGEPACKER_SRC}) - -target_include_directories(z_imagepacker PRIVATE - Include - Resource -) - target_link_libraries(z_imagepacker PRIVATE - benchmark - comctl32 - dbghelplib - imm32 - vfw32 - winmm - z_debug + corei_imagepacker z_gameengine z_gameenginedevice - z_profile zi_always ) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(z_imagepacker PRIVATE Resource/ImagePacker.rc) -endif() diff --git a/GeneralsMD/Code/Tools/ImagePacker/Resource/ImagePacker.rc b/GeneralsMD/Code/Tools/ImagePacker/Resource/ImagePacker.rc deleted file mode 100644 index 51db3eb58e..0000000000 --- a/GeneralsMD/Code/Tools/ImagePacker/Resource/ImagePacker.rc +++ /dev/null @@ -1,214 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IMAGE_PACKER_DIALOG DIALOG DISCARDABLE 0, 0, 408, 313 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Image Packer" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Start",BUTTON_START,20,224,50,32 - PUSHBUTTON "Exit",BUTTON_EXIT,80,224,50,32 - LISTBOX LIST_FOLDERS,154,136,232,84,LBS_SORT | LBS_MULTIPLESEL | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | - WS_TABSTOP - GROUPBOX "Folders Containing Source Images",IDC_STATIC,148,84,244, - 144 - GROUPBOX "",IDC_STATIC,4,4,396,304 - GROUPBOX "Output Image Size",IDC_STATIC,12,84,128,108 - CONTROL "128 x 128",RADIO_128X128,"Button",BS_AUTORADIOBUTTON,20, - 99,47,10 - CONTROL "256 x 256",RADIO_256X256,"Button",BS_AUTORADIOBUTTON,20, - 111,47,10 - CONTROL "512 x 512",RADIO_512X512,"Button",BS_AUTORADIOBUTTON,20, - 123,47,10 - CONTROL "Other",RADIO_TARGET_OTHER,"Button",BS_AUTORADIOBUTTON, - 20,135,33,10 - EDITTEXT EDIT_WIDTH,36,148,24,14,ES_CENTER | ES_AUTOHSCROLL | - ES_NUMBER | WS_DISABLED - EDITTEXT EDIT_HEIGHT,72,148,24,14,ES_CENTER | ES_AUTOHSCROLL | - ES_NUMBER | WS_DISABLED - CTEXT "x",STATIC_X,60,148,12,12,SS_CENTERIMAGE | WS_DISABLED - PUSHBUTTON "Add Folder(s)",BUTTON_ADD_FOLDER,196,100,70,14 - PUSHBUTTON "Remove Folder(s)",BUTTON_REMOVE_FOLDER,276,100,72,14 - EDITTEXT EDIT_FILENAME,12,30,128,14,ES_AUTOHSCROLL - LTEXT "Output File Base Name:",IDC_STATIC,12,20,124,8, - SS_CENTERIMAGE - CONTROL "Use Sub-folders",CHECK_USE_SUB_FOLDERS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,156,120,66,10 - LTEXT "Status",STATIC_STATUS,12,288,380,12,SS_CENTERIMAGE | - SS_SUNKEN - PUSHBUTTON "Open Preview",BUTTON_PREVIEW,176,244,68,14 - GROUPBOX "Preview",IDC_STATIC,148,232,244,52 - PUSHBUTTON "<- Prev",BUTTON_PREVIOUS,264,244,50,14 - PUSHBUTTON "Next ->",BUTTON_NEXT,316,244,50,14 - EDITTEXT EDIT_GUTTER,176,57,40,14,ES_CENTER | ES_AUTOHSCROLL | - ES_NUMBER | WS_DISABLED - LTEXT "Pixels Between Packed Images",STATIC_GAP_INFO,220,57, - 128,12,SS_CENTERIMAGE | WS_DISABLED - CONTROL "Output Alpha Channel",CHECK_ALPHA,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,12,68,128,10 - CONTROL "Show Texture In Preview",CHECK_BITMAP_PREVIEW,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,176,264,112,10 - CONTROL "Create INI Mapped Image File",CHECK_INI,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,12,52,128,10 - CONTROL "Compress Final Texture Pages",CHECK_COMPRESS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,20,172,116,10 - GROUPBOX "Gap Method",IDC_STATIC,148,12,244,68 - CONTROL "Extend RGB at Image Edges (All Sides, NO Alpha)", - CHECK_GAP_EXTEND_RGB,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,156,28,174,10 - CONTROL "Transparent Gap (Right and Bottom Only)", - CHECK_GAP_GUTTER,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, - 156,44,146,10 -END - -IMAGE_ERRORS DIALOG DISCARDABLE 0, 0, 252, 257 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Processing Errors" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Proceed Anyway",BUTTON_PROCEED,44,232,72,14 - LISTBOX LIST_IMAGES,4,20,244,200,LBS_SORT | LBS_NOINTEGRALHEIGHT | - LBS_NOSEL | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP - LTEXT "The following images cannot be processed. Proceed anyway?", - IDC_STATIC,4,4,236,12 - DEFPUSHBUTTON "Cancel Build",BUTTON_CANCEL,136,232,72,14 -END - -PAGE_ERRORS DIALOG DISCARDABLE 0, 0, 256, 257 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Texture Page Errors" -FONT 8, "MS Sans Serif" -BEGIN - LISTBOX LIST_PAGES,4,20,244,200,LBS_SORT | LBS_NOINTEGRALHEIGHT | - LBS_NOSEL | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP - LTEXT "The following texture pages could not be generated and were ignored", - IDC_STATIC,4,4,236,12 - PUSHBUTTON "OK",IDOK,104,232,50,14 -END - -DIRECTORY_SELECT_DIALOG DIALOG DISCARDABLE 0, 0, 192, 261 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Select Directory" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Add Directory",BUTTON_ADD,28,8,63,14,WS_DISABLED - PUSHBUTTON "Cancel",BUTTON_CANCEL,100,8,63,14 - LISTBOX LIST_DIR,4,80,184,176,LBS_SORT | LBS_MULTIPLESEL | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | - WS_TABSTOP - LTEXT "Current Dir",STATIC_CURRENT_DIR,4,36,184,24,SS_SUNKEN - COMBOBOX COMBO_DRIVE,28,64,48,180,CBS_DROPDOWNLIST | CBS_SORT | - WS_VSCROLL | WS_TABSTOP - LTEXT "Drive",IDC_STATIC,4,64,20,12,SS_CENTERIMAGE -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IMAGE_PACKER_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 401 - TOPMARGIN, 7 - BOTTOMMARGIN, 306 - END - - IMAGE_ERRORS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 245 - TOPMARGIN, 7 - BOTTOMMARGIN, 250 - END - - PAGE_ERRORS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 249 - TOPMARGIN, 7 - BOTTOMMARGIN, 250 - END - - DIRECTORY_SELECT_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 185 - TOPMARGIN, 7 - BOTTOMMARGIN, 254 - END -END -#endif // APSTUDIO_INVOKED - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/GeneralsMD/Code/Tools/Launcher/CMakeLists.txt b/GeneralsMD/Code/Tools/Launcher/CMakeLists.txt index 2641b3c841..bd2928b21b 100644 --- a/GeneralsMD/Code/Tools/Launcher/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/Launcher/CMakeLists.txt @@ -1,75 +1,9 @@ add_subdirectory(DatGen) -set(LAUNCHER_SRC - "BFISH.CPP" - "BFISH.H" - "configfile.cpp" - "configfile.h" - "dialog.cpp" - "dialog.h" - "dictionary.h" - "filed.h" - "findpatch.cpp" - "findpatch.h" - "loadbmp.cpp" - "loadbmp.h" - "main.cpp" - "monod.cpp" - "monod.h" - "odevice.h" - "patch.cpp" - "patch.h" - "process.cpp" - "process.h" - "Protect.cpp" - "Protect.h" - "resource.h" - "streamer.cpp" - "streamer.h" - "wdebug.cpp" - "wdebug.h" - "winblows.cpp" - "winblows.h" - "wstring.cpp" - "wstring.h" - "wstypes.h" - "Toolkit/Debug/DebugPrint.cpp" - "Toolkit/Debug/DebugPrint.h" - "Toolkit/Storage/File.cpp" - "Toolkit/Storage/File.h" - "Toolkit/Storage/Rights.h" - "Toolkit/Storage/Stream.h" - "Toolkit/Support/RefCounted.h" - "Toolkit/Support/RefPtr.h" - "Toolkit/Support/StringConvert.cpp" - "Toolkit/Support/StringConvert.h" - "Toolkit/Support/UString.cpp" - "Toolkit/Support/UString.h" - "Toolkit/Support/UTypes.h" - "Toolkit/Support/Visualc.h" -) - add_executable(z_launcher WIN32) set_target_properties(z_launcher PROPERTIES OUTPUT_NAME launcher) -target_sources(z_launcher PRIVATE ${LAUNCHER_SRC}) - -target_include_directories(z_launcher PRIVATE - Toolkit -) - -target_compile_definitions(z_launcher PRIVATE - USE_NOTEPAD - $<$:USE_GAMEDIR_FROM_LCF> -) - target_link_libraries(z_launcher PRIVATE - comctl32 - core_config - core_utility - safedisc + corei_launcher + zi_always ) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(z_launcher PRIVATE launcher1.rc) -endif() diff --git a/GeneralsMD/Code/Tools/Launcher/DatGen/CMakeLists.txt b/GeneralsMD/Code/Tools/Launcher/DatGen/CMakeLists.txt index 69b17ab2a2..752f47f613 100644 --- a/GeneralsMD/Code/Tools/Launcher/DatGen/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/Launcher/DatGen/CMakeLists.txt @@ -1,22 +1,7 @@ -set(DATGEN_SRC - "DatGen.cpp" - "../BFISH.CPP" - "../BFISH.H" - "../Toolkit/Debug/DebugPrint.cpp" - "../Toolkit/Debug/DebugPrint.h" -) - add_executable(z_datgen WIN32) set_target_properties(z_datgen PROPERTIES OUTPUT_NAME datgen) -target_include_directories(z_datgen PRIVATE - ../ - ../Toolkit -) - target_link_libraries(z_datgen PRIVATE - core_config - safedisc + corei_datgen + zi_always ) - -target_sources(z_datgen PRIVATE ${DATGEN_SRC}) diff --git a/GeneralsMD/Code/Tools/Launcher/launcher1.rc b/GeneralsMD/Code/Tools/Launcher/launcher1.rc deleted file mode 100644 index 0cb9126c88..0000000000 --- a/GeneralsMD/Code/Tools/Launcher/launcher1.rc +++ /dev/null @@ -1,151 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_PATCHPROGRESS DIALOG DISCARDABLE 0, 0, 243, 126 -STYLE DS_MODALFRAME | DS_SETFOREGROUND | WS_MINIMIZEBOX | WS_POPUP | - WS_CAPTION | WS_SYSMENU -CAPTION "Patching" -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "",IDC_SPLASH,"Static",SS_GRAYRECT | SS_SUNKEN,7,7,229, - 70 - GROUPBOX "File",IDC_CAPTION,7,78,229,22 - CONTROL "Progress1",IDC_PROGRESS2,"msctls_progress32",WS_BORDER, - 7,105,229,13 - CONTROL "",IDC_FILENAME,"Static",SS_LEFTNOWORDWRAP | - SS_CENTERIMAGE | WS_GROUP,13,85,217,13 -END - -IDD_CHANGELOG DIALOG DISCARDABLE 0, 0, 332, 204 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Update Information" -FONT 10, "Lucida Console" -BEGIN - EDITTEXT IDC_TEXT,5,5,322,178,ES_MULTILINE | ES_AUTOHSCROLL | - ES_READONLY | WS_VSCROLL | WS_HSCROLL - PUSHBUTTON "OK",IDOK,128,185,76,14 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_PATCHPROGRESS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 236 - TOPMARGIN, 7 - BOTTOMMARGIN, 119 - END - - IDD_CHANGELOG, DIALOG - BEGIN - LEFTMARGIN, 5 - RIGHTMARGIN, 327 - TOPMARGIN, 5 - BOTTOMMARGIN, 199 - END -END -#endif // APSTUDIO_INVOKED - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_GENERALS ICON DISCARDABLE "Generals.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_SYS_RESTART "Your computer needs to be restarted to continue the patch. Press OK to continue." - IDS_SYS_RESTART_TITLE "About to restart" - IDS_WEBPATCH "You need to download a patch from our website.\rWhen you press OK, your browser will automatically open to the download page." - IDS_WEBPATCH_TITLE "Web Patch" - IDS_FILE_X_OF_Y "File (%d of %d)" - IDS_MUST_RESTART "You must restart your computer now." - IDS_RUNONCE_ERR "Could not set the patch to run on system reboot!\rYou must exit the game and run %s to complete the patch." - IDS_ERROR "Error" - IDS_ERR_MISSING_FILE "Error: Couldn't find file: %s" - IDS_BAD_LIBRARY "A required DLL is corrupt." - IDS_ERR_PATCH "Patch error. Existing game files may have been modified. You should re-install the game from the CD." -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/GeneralsMD/Code/Tools/MapCacheBuilder/CMakeLists.txt b/GeneralsMD/Code/Tools/MapCacheBuilder/CMakeLists.txt index 9cc87d6c99..feeca7af1a 100644 --- a/GeneralsMD/Code/Tools/MapCacheBuilder/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/MapCacheBuilder/CMakeLists.txt @@ -1,32 +1,9 @@ -set(MAPCACHEBUILDER_SRC - "Include/WinMain.h" - "Resource/Resource.h" - "Source/WinMain.cpp" -) - add_executable(z_mapcachebuilder WIN32) set_target_properties(z_mapcachebuilder PROPERTIES OUTPUT_NAME mapcachebuilder) -target_sources(z_mapcachebuilder PRIVATE ${MAPCACHEBUILDER_SRC}) - -target_include_directories(z_mapcachebuilder PRIVATE - Include - Resource -) -# target_link_libraries(z_mapcachebuilder PRIVATE - comctl32 - dbghelplib - imm32 - vfw32 - winmm - z_debug + corei_mapcachebuilder z_gameengine z_gameenginedevice - z_profile zi_always ) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(z_mapcachebuilder PRIVATE Resource/MapCacheBuilder.rc) -endif() diff --git a/GeneralsMD/Code/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc b/GeneralsMD/Code/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc deleted file mode 100644 index 51db3eb58e..0000000000 --- a/GeneralsMD/Code/Tools/MapCacheBuilder/Resource/MapCacheBuilder.rc +++ /dev/null @@ -1,214 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IMAGE_PACKER_DIALOG DIALOG DISCARDABLE 0, 0, 408, 313 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Image Packer" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Start",BUTTON_START,20,224,50,32 - PUSHBUTTON "Exit",BUTTON_EXIT,80,224,50,32 - LISTBOX LIST_FOLDERS,154,136,232,84,LBS_SORT | LBS_MULTIPLESEL | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | - WS_TABSTOP - GROUPBOX "Folders Containing Source Images",IDC_STATIC,148,84,244, - 144 - GROUPBOX "",IDC_STATIC,4,4,396,304 - GROUPBOX "Output Image Size",IDC_STATIC,12,84,128,108 - CONTROL "128 x 128",RADIO_128X128,"Button",BS_AUTORADIOBUTTON,20, - 99,47,10 - CONTROL "256 x 256",RADIO_256X256,"Button",BS_AUTORADIOBUTTON,20, - 111,47,10 - CONTROL "512 x 512",RADIO_512X512,"Button",BS_AUTORADIOBUTTON,20, - 123,47,10 - CONTROL "Other",RADIO_TARGET_OTHER,"Button",BS_AUTORADIOBUTTON, - 20,135,33,10 - EDITTEXT EDIT_WIDTH,36,148,24,14,ES_CENTER | ES_AUTOHSCROLL | - ES_NUMBER | WS_DISABLED - EDITTEXT EDIT_HEIGHT,72,148,24,14,ES_CENTER | ES_AUTOHSCROLL | - ES_NUMBER | WS_DISABLED - CTEXT "x",STATIC_X,60,148,12,12,SS_CENTERIMAGE | WS_DISABLED - PUSHBUTTON "Add Folder(s)",BUTTON_ADD_FOLDER,196,100,70,14 - PUSHBUTTON "Remove Folder(s)",BUTTON_REMOVE_FOLDER,276,100,72,14 - EDITTEXT EDIT_FILENAME,12,30,128,14,ES_AUTOHSCROLL - LTEXT "Output File Base Name:",IDC_STATIC,12,20,124,8, - SS_CENTERIMAGE - CONTROL "Use Sub-folders",CHECK_USE_SUB_FOLDERS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,156,120,66,10 - LTEXT "Status",STATIC_STATUS,12,288,380,12,SS_CENTERIMAGE | - SS_SUNKEN - PUSHBUTTON "Open Preview",BUTTON_PREVIEW,176,244,68,14 - GROUPBOX "Preview",IDC_STATIC,148,232,244,52 - PUSHBUTTON "<- Prev",BUTTON_PREVIOUS,264,244,50,14 - PUSHBUTTON "Next ->",BUTTON_NEXT,316,244,50,14 - EDITTEXT EDIT_GUTTER,176,57,40,14,ES_CENTER | ES_AUTOHSCROLL | - ES_NUMBER | WS_DISABLED - LTEXT "Pixels Between Packed Images",STATIC_GAP_INFO,220,57, - 128,12,SS_CENTERIMAGE | WS_DISABLED - CONTROL "Output Alpha Channel",CHECK_ALPHA,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,12,68,128,10 - CONTROL "Show Texture In Preview",CHECK_BITMAP_PREVIEW,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,176,264,112,10 - CONTROL "Create INI Mapped Image File",CHECK_INI,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,12,52,128,10 - CONTROL "Compress Final Texture Pages",CHECK_COMPRESS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,20,172,116,10 - GROUPBOX "Gap Method",IDC_STATIC,148,12,244,68 - CONTROL "Extend RGB at Image Edges (All Sides, NO Alpha)", - CHECK_GAP_EXTEND_RGB,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,156,28,174,10 - CONTROL "Transparent Gap (Right and Bottom Only)", - CHECK_GAP_GUTTER,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, - 156,44,146,10 -END - -IMAGE_ERRORS DIALOG DISCARDABLE 0, 0, 252, 257 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Processing Errors" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Proceed Anyway",BUTTON_PROCEED,44,232,72,14 - LISTBOX LIST_IMAGES,4,20,244,200,LBS_SORT | LBS_NOINTEGRALHEIGHT | - LBS_NOSEL | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP - LTEXT "The following images cannot be processed. Proceed anyway?", - IDC_STATIC,4,4,236,12 - DEFPUSHBUTTON "Cancel Build",BUTTON_CANCEL,136,232,72,14 -END - -PAGE_ERRORS DIALOG DISCARDABLE 0, 0, 256, 257 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Texture Page Errors" -FONT 8, "MS Sans Serif" -BEGIN - LISTBOX LIST_PAGES,4,20,244,200,LBS_SORT | LBS_NOINTEGRALHEIGHT | - LBS_NOSEL | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP - LTEXT "The following texture pages could not be generated and were ignored", - IDC_STATIC,4,4,236,12 - PUSHBUTTON "OK",IDOK,104,232,50,14 -END - -DIRECTORY_SELECT_DIALOG DIALOG DISCARDABLE 0, 0, 192, 261 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Select Directory" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Add Directory",BUTTON_ADD,28,8,63,14,WS_DISABLED - PUSHBUTTON "Cancel",BUTTON_CANCEL,100,8,63,14 - LISTBOX LIST_DIR,4,80,184,176,LBS_SORT | LBS_MULTIPLESEL | - LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | - WS_TABSTOP - LTEXT "Current Dir",STATIC_CURRENT_DIR,4,36,184,24,SS_SUNKEN - COMBOBOX COMBO_DRIVE,28,64,48,180,CBS_DROPDOWNLIST | CBS_SORT | - WS_VSCROLL | WS_TABSTOP - LTEXT "Drive",IDC_STATIC,4,64,20,12,SS_CENTERIMAGE -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IMAGE_PACKER_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 401 - TOPMARGIN, 7 - BOTTOMMARGIN, 306 - END - - IMAGE_ERRORS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 245 - TOPMARGIN, 7 - BOTTOMMARGIN, 250 - END - - PAGE_ERRORS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 249 - TOPMARGIN, 7 - BOTTOMMARGIN, 250 - END - - DIRECTORY_SELECT_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 185 - TOPMARGIN, 7 - BOTTOMMARGIN, 254 - END -END -#endif // APSTUDIO_INVOKED - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/GeneralsMD/Code/Tools/PATCHGET/CMakeLists.txt b/GeneralsMD/Code/Tools/PATCHGET/CMakeLists.txt index 9d4f2dde50..4175db4b52 100644 --- a/GeneralsMD/Code/Tools/PATCHGET/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/PATCHGET/CMakeLists.txt @@ -1,47 +1,13 @@ -set(PATCHGET_SRC - "CHATAPI.CPP" - "CHATAPI.H" - "COMINIT.CPP" - "COMINIT.H" - "debug.cpp" - "debug.h" - "DownloadManager.cpp" - "DownloadManager.h" - "PROCESS.CPP" - "PROCESS.H" - "registry.cpp" - "Registry.h" - "RESOURCE.H" - "WINBLOWS.CPP" - "WINBLOWS.H" - "WSTYPES.H" -) - macro(setup_patchgrabber appname) add_executable(${appname} WIN32) - target_sources(${appname} PRIVATE ${PATCHGET_SRC}) + target_link_libraries(${appname} PRIVATE - comctl32 - dbghelplib - gamespy::gamespy - imm32 - vfw32 - winmm - z_debug + corei_patchgrabber z_gameengine z_gameenginedevice - z_profile z_wwvegas zi_always ) - - target_compile_definitions(${appname} PRIVATE - $<$:DEBUG_CRASHING> - ) - - if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(${appname} PRIVATE SCRIPT1.RC) - endif() endmacro() setup_patchgrabber(z_patchgrabber_en) diff --git a/GeneralsMD/Code/Tools/PATCHGET/Generals.ico b/GeneralsMD/Code/Tools/PATCHGET/Generals.ico deleted file mode 100644 index 9112002400..0000000000 Binary files a/GeneralsMD/Code/Tools/PATCHGET/Generals.ico and /dev/null differ diff --git a/GeneralsMD/Code/Tools/PATCHGET/GeneralsEnglish.bmp b/GeneralsMD/Code/Tools/PATCHGET/GeneralsEnglish.bmp deleted file mode 100644 index b26c0eb8cd..0000000000 Binary files a/GeneralsMD/Code/Tools/PATCHGET/GeneralsEnglish.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/PATCHGET/GeneralsFrench.bmp b/GeneralsMD/Code/Tools/PATCHGET/GeneralsFrench.bmp deleted file mode 100644 index b26c0eb8cd..0000000000 Binary files a/GeneralsMD/Code/Tools/PATCHGET/GeneralsFrench.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/PATCHGET/GeneralsGerman.bmp b/GeneralsMD/Code/Tools/PATCHGET/GeneralsGerman.bmp deleted file mode 100644 index b26c0eb8cd..0000000000 Binary files a/GeneralsMD/Code/Tools/PATCHGET/GeneralsGerman.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/PATCHGET/SCRIPT1.RC b/GeneralsMD/Code/Tools/PATCHGET/SCRIPT1.RC deleted file mode 100644 index 70f78550b1..0000000000 --- a/GeneralsMD/Code/Tools/PATCHGET/SCRIPT1.RC +++ /dev/null @@ -1,669 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_CONNECTING DIALOG DISCARDABLE 0, 0, 117, 20 -STYLE DS_ABSALIGN | DS_CENTER | WS_POPUP | WS_THICKFRAME -FONT 18, "MS Sans Serif" -BEGIN - CTEXT "Verbinde mit EA",IDC_STATIC,12,4,93,12,SS_CENTERIMAGE -END - -IDD_DOWNLOAD_DIALOG DIALOG DISCARDABLE 0, 0, 290, 143 -STYLE DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Downloading Patch" -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "Cancel",IDC_DLABORT,113,122,63,14 - LTEXT "",IDC_TIMEREM,158,83,125,11 - LTEXT "",IDC_BYTESLEFT,7,83,119,11 - CONTROL "Progress1",IDC_PROGRESS,"msctls_progress32",WS_BORDER,7, - 99,276,16 - CONTROL 103,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE | - SS_SUNKEN,30,7,229,70 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_CONNECTING, DIALOG - BEGIN - LEFTMARGIN, 5 - RIGHTMARGIN, 112 - TOPMARGIN, 4 - BOTTOMMARGIN, 16 - END - - IDD_DOWNLOAD_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 283 - TOPMARGIN, 7 - BOTTOMMARGIN, 136 - END -END -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040704b0" - BEGIN - VALUE "Comments", "\0" - VALUE "CompanyName", "Electronic Arts\0" - VALUE "FileDescription", "patchgrabber\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "patchgrabber\0" - VALUE "LegalCopyright", "Copyright © 2002\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "patchgrabber.exe\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "Electronic Arts patchgrabber\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x407, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_BITMAP BITMAP DISCARDABLE "GeneralsGerman.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ICON1 ICON DISCARDABLE "Generals.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - TXT_ABORT_DOWNLOAD "Sind Sie sicher, daß Sie das Download abbrechen möchten?" - TXT_ABORT "Abbrechen" - TXT_TIME_REMAIN "Verbleibende Zeit: %d:%02d" - TXT_BYTES_READ "Gelesene Bytes: %d von %d" - TXT_BPS "Bytes pro Sekunde: %d" - TXT_CANT_CONTACT "Verbindung zum Electronic Arts-Update-Server konnte nicht hergestellt werden." - TXT_ERROR "Fehler" - TXT_AN_UPGRADE_AVAILABLE "Ein Upgrade ist verfügbar." - TXT_DOWNLOAD_NOW "Möchten Sie es jetzt herunterladen?" - TXT_DOWNLOADING_FILE "Datei %d von %d wird heruntergeladen ..." - TXT_NONE """""" - TXT_UPGRADE_AVAILABLE "Upgrade verfügbar" - TXT_NO_PATCHES "Für dieses Produkt gibt es z.Z. kein Patch." - TXT_AUTO_UPDATE "Auto-Update:" - TXT_CONNECTING "Verbinde ..." -END - -STRINGTABLE DISCARDABLE -BEGIN - TXT_INSTALL_PROBLEM "Das Spiel ist nicht korrekt installiert. Möglicherweise müssen Sie erneut installieren." - TXT_TITLE "Electronic Arts Auto-Patch" - TXT_REGNOW "Möchten Sie sich bei Generals Online registrieren?" -END - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_CONNECTING DIALOG DISCARDABLE 0, 0, 117, 21 -STYLE DS_ABSALIGN | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | - WS_THICKFRAME -FONT 18, "MS Sans Serif" -BEGIN - CTEXT "Connecting to EA",IDC_STATIC,5,4,107,13,SS_CENTERIMAGE -END - -IDD_DOWNLOAD_DIALOG DIALOG DISCARDABLE 0, 0, 290, 143 -STYLE DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Downloading Patch" -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "Cancel",IDC_DLABORT,113,122,63,14 - LTEXT "",IDC_TIMEREM,158,83,125,11 - LTEXT "",IDC_BYTESLEFT,7,83,119,11 - CONTROL "Progress1",IDC_PROGRESS,"msctls_progress32",WS_BORDER,7, - 99,276,16 - CONTROL 103,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE | - SS_SUNKEN,30,7,229,70 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_CONNECTING, DIALOG - BEGIN - LEFTMARGIN, 5 - RIGHTMARGIN, 112 - TOPMARGIN, 4 - BOTTOMMARGIN, 17 - END - - IDD_DOWNLOAD_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 283 - TOPMARGIN, 7 - BOTTOMMARGIN, 136 - END -END -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "\0" - VALUE "CompanyName", "Electronic Arts\0" - VALUE "FileDescription", "patchgrabber\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "patchgrabber\0" - VALUE "LegalCopyright", "Copyright © 2002\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "patchgrabber.exe\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "Electronic Arts patchgrabber\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_BITMAP BITMAP DISCARDABLE "GeneralsEnglish.bmp" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ICON1 ICON DISCARDABLE "Generals.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - TXT_ABORT_DOWNLOAD "Are you sure you want to abort the download?" - TXT_ABORT "Abort" - TXT_TIME_REMAIN "Time Remaining: %d:%02d" - TXT_BYTES_READ "Bytes Read: %d of %d" - TXT_BPS "Bytes Per Second: %d" - TXT_CANT_CONTACT "Unable to contact the Electronic Arts update server." - TXT_ERROR "Error" - TXT_AN_UPGRADE_AVAILABLE "There is an upgrade available." - TXT_DOWNLOAD_NOW "Would you like to download it now?" - TXT_DOWNLOADING_FILE "Downloading file %d of %d..." - TXT_NONE """""" - TXT_UPGRADE_AVAILABLE "Upgrade Available" - TXT_NO_PATCHES "There aren't any patches for this product right now." - TXT_AUTO_UPDATE "Auto-Update:" - TXT_CONNECTING "Connecting..." -END - -STRINGTABLE DISCARDABLE -BEGIN - TXT_INSTALL_PROBLEM "The game does not appear to be installed properly. You may need to re-install." - TXT_TITLE "Electronic Arts Auto-Patch" - TXT_REGNOW "Would you like to register with Generals Online?" - FTP_StatusIdle "Idle" - FTP_UnknownError "Unknown Error" - FTP_NoSuchServer "Server not found" - FTP_CouldNotConnect "Could not connect" - FTP_LoginFailed "Login failed" - FTP_NoSuchFile "File not found" - FTP_LocalFileOpenFailed "Could not write the file to disk" - FTP_TCPError "Network Error" - FTP_DisconnectError "Connection to server was lost." - FTP_StatusNone "Idle" - FTP_StatusConnecting "Connecting..." - FTP_StatusLoggingIn "Logging in..." -END - -STRINGTABLE DISCARDABLE -BEGIN - FTP_StatusFindingFile "Finding file..." - FTP_StatusQueryingResume "Attempting to resume download..." - FTP_StatusDownloading "Downloading..." - FTP_StatusFinishing "Finishing..." - FTP_StatusDone "Done." - FTP_StatusDisconnecting "Disconnecting..." -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// French (France) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA) -#ifdef _WIN32 -LANGUAGE LANG_FRENCH, SUBLANG_FRENCH -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_CONNECTING DIALOG DISCARDABLE 0, 0, 117, 20 -STYLE DS_ABSALIGN | DS_CENTER | WS_POPUP | WS_THICKFRAME -FONT 18, "MS Sans Serif" -BEGIN - CTEXT "Connexion à EA",IDC_STATIC,12,4,93,12,SS_CENTERIMAGE -END - -IDD_DOWNLOAD_DIALOG DIALOG DISCARDABLE 0, 0, 290, 143 -STYLE DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Downloading Patch" -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "Cancel",IDC_DLABORT,113,122,63,14 - LTEXT "",IDC_TIMEREM,158,83,125,11 - LTEXT "",IDC_BYTESLEFT,7,83,119,11 - CONTROL "Progress1",IDC_PROGRESS,"msctls_progress32",WS_BORDER,7, - 99,276,16 - CONTROL 103,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE | - SS_SUNKEN,30,7,229,70 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_CONNECTING, DIALOG - BEGIN - LEFTMARGIN, 5 - RIGHTMARGIN, 112 - TOPMARGIN, 4 - BOTTOMMARGIN, 16 - END - - IDD_DOWNLOAD_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 283 - TOPMARGIN, 7 - BOTTOMMARGIN, 136 - END -END -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040c04b0" - BEGIN - VALUE "Comments", "\0" - VALUE "CompanyName", "Electronic Arts\0" - VALUE "FileDescription", "patchgrabber\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "patchgrabber\0" - VALUE "LegalCopyright", "Copyright © 2002\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "patchgrabber.exe\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "Electronic Arts patchgrabber\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x40c, 1200 - END -END - -#endif // !_MAC - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_BITMAP BITMAP DISCARDABLE "GeneralsFrench.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ICON1 ICON DISCARDABLE "Generals.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - TXT_ABORT_DOWNLOAD "Confirmer abandon du téléchargement ?" - TXT_ABORT "Abandon" - TXT_TIME_REMAIN "Temps restant : %d:%02d" - TXT_BYTES_READ "Octets lus : %d sur %d" - TXT_BPS "Octets/seconde : %d" - TXT_CANT_CONTACT "La connexion au serveur de mise à jour de Electronic Arts a échoué." - TXT_ERROR "Erreur" - TXT_AN_UPGRADE_AVAILABLE "Une mise à jour est disponible." - TXT_DOWNLOAD_NOW "Voulez-vous la télécharger maintenant ?" - TXT_DOWNLOADING_FILE "Téléchargement du fichier %d sur %d..." - TXT_NONE """""" - TXT_UPGRADE_AVAILABLE "Mise à jour disponible" - TXT_NO_PATCHES "Aucun patch n'est disponible pour ce produit." - TXT_AUTO_UPDATE "Mise à jour automatique :" - TXT_CONNECTING "Connexion..." -END - -STRINGTABLE DISCARDABLE -BEGIN - TXT_INSTALL_PROBLEM "L'installation du jeu a échoué. Il est préférable de recommencer l'opération." - TXT_TITLE "Patch automatique de Electronic Arts" - TXT_REGNOW "Voulez-vous vous inscrire à Generals Online ?" -END - -#endif // French (France) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// Spanish (Modern) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ESN) -#ifdef _WIN32 -LANGUAGE LANG_SPANISH, SUBLANG_SPANISH_MODERN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_CONNECTING DIALOG DISCARDABLE 0, 0, 117, 20 -STYLE DS_ABSALIGN | DS_CENTER | WS_POPUP | WS_THICKFRAME -FONT 18, "MS Sans Serif" -BEGIN - CTEXT "Connectando con EA",IDD_CONNECTING,12,4,93,12, - SS_CENTERIMAGE -END - -IDD_DOWNLOAD_DIALOG DIALOG DISCARDABLE 0, 0, 290, 143 -STYLE DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Descargando Parche" -FONT 8, "MS Sans Serif" -BEGIN - PUSHBUTTON "Cancelar",IDC_DLABORT,113,122,63,14 - LTEXT "",IDC_TIMEREM,158,83,125,11 - LTEXT "",IDC_BYTESLEFT,7,83,119,11 - CONTROL "Progress1",IDC_PROGRESS,"msctls_progress32",WS_BORDER,7, - 99,276,16 - CONTROL 103,IDC_STATIC,"Static",SS_BITMAP | SS_REALSIZEIMAGE | - SS_SUNKEN,30,7,229,70 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_CONNECTING, DIALOG - BEGIN - LEFTMARGIN, 5 - RIGHTMARGIN, 112 - TOPMARGIN, 4 - BOTTOMMARGIN, 16 - END - - IDD_DOWNLOAD_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 283 - TOPMARGIN, 7 - BOTTOMMARGIN, 136 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_BITMAP BITMAP DISCARDABLE "GeneralsEnglish.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ICON1 ICON DISCARDABLE "Generals.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - TXT_ABORT_DOWNLOAD "¿Seguro que quieres abortar la descarga?" - TXT_ABORT "Abortar" - TXT_TIME_REMAIN "Tiempo Restante: %d:%02d" - TXT_BYTES_READ "Bytes Leídos: %d of %d" - TXT_BPS "Bytes Por Segundo: %d" - TXT_CANT_CONTACT "No se puede contactar con el servidor de actualizaciones de Electronic Arts." - TXT_ERROR "Error" - TXT_AN_UPGRADE_AVAILABLE "Hay una actualización disponible." - TXT_DOWNLOAD_NOW "¿Quieres descargarla ahora?" - TXT_DOWNLOADING_FILE "Descargando el archivo %d de %d..." - TXT_NONE """""" - TXT_UPGRADE_AVAILABLE "Actualización Disponible" - TXT_NO_PATCHES "No hay parches disponibles para este producto." - TXT_AUTO_UPDATE "Auto-Actualización:" - TXT_CONNECTING "Conectando..." -END - -STRINGTABLE DISCARDABLE -BEGIN - TXT_INSTALL_PROBLEM "El juego parece no estar correctamente instalado. Puedes necesitar reinstalarlo." - TXT_TITLE "Auto-Parche Electronic Arts" - TXT_REGNOW "¿Quieres registrarte a través de Generals Online?" -END - -#endif // Spanish (Modern) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/GeneralsMD/Code/Tools/PATCHGET/debug.cpp b/GeneralsMD/Code/Tools/PATCHGET/debug.cpp deleted file mode 100644 index 48bf7b9566..0000000000 --- a/GeneralsMD/Code/Tools/PATCHGET/debug.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* -** Command & Conquer Generals Zero Hour(tm) -** Copyright 2025 Electronic Arts Inc. -** -** This program 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. -** -** This program 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 this program. If not, see . -*/ - -// FILE: debug.cpp //////////////////////////////////////////////////////// -// Minmal debug info -// Author: Matthew D. Campbell, Sept 2002 - -#include -#include "debug.h" -#include -#include - -namespace patchget -{ - -char* TheCurrentIgnoreCrashPtr; - -#define LARGE_BUFFER 8192 -static char theBuffer[ LARGE_BUFFER ]; // make it big to avoid weird overflow bugs in debug mode - -static int doCrashBox(const char *buffer, bool logResult) -{ - int result; - - result = ::MessageBox(NULL, buffer, "Assertion Failure", MB_ABORTRETRYIGNORE|MB_APPLMODAL|MB_ICONWARNING); - - switch(result) - { - case IDABORT: -#ifdef DEBUG_LOGGING - if (logResult) - DebugLog("[Abort]\n"); -#endif - _exit(1); - break; - case IDRETRY: -#ifdef DEBUG_LOGGING - if (logResult) - DebugLog("[Retry]\n"); -#endif - ::DebugBreak(); - break; - case IDIGNORE: -#ifdef DEBUG_LOGGING - // do nothing, just keep going - if (logResult) - DebugLog("[Ignore]\n"); -#endif - break; - } - return result; -} - -#if defined(DEBUG) || defined(DEBUG_LOGGING) - -void DebugLog(const char *fmt, ...) -{ - va_list va; - va_start( va, fmt ); - _vsnprintf(theBuffer, LARGE_BUFFER, fmt, va ); - theBuffer[LARGE_BUFFER-1] = 0; - va_end( va ); - - OutputDebugString(theBuffer); - printf( "%s", theBuffer ); -} - -#endif // defined(DEBUG) || defined(DEBUG_LOGGING) - -#ifdef DEBUG_CRASHING - -void DebugCrash(const char *format, ...) -{ - theBuffer[0] = 0; - strcat(theBuffer, "ASSERTION FAILURE: "); - - va_list arg; - va_start(arg, format); - vsprintf(theBuffer + strlen(theBuffer), format, arg); - va_end(arg); - - if (strlen(theBuffer) >= sizeof(theBuffer)) - ::MessageBox(NULL, "String too long for debug buffers", "", MB_OK|MB_APPLMODAL); - - OutputDebugString(theBuffer); - printf( "%s", theBuffer ); - - strcat(theBuffer, "\n\nAbort->exception; Retry->debugger; Ignore->continue\n"); - - int result = doCrashBox(theBuffer, true); - - if (result == IDIGNORE && TheCurrentIgnoreCrashPtr != NULL) - { - int yn; - yn = ::MessageBox(NULL, "Ignore this crash from now on?", "", MB_YESNO|MB_APPLMODAL); - if (yn == IDYES) - *TheCurrentIgnoreCrashPtr = 1; - } -} - -#endif - -} // namespace patchget diff --git a/GeneralsMD/Code/Tools/ParticleEditor/CMakeLists.txt b/GeneralsMD/Code/Tools/ParticleEditor/CMakeLists.txt index 1d3d7aa0b9..0b410f3470 100644 --- a/GeneralsMD/Code/Tools/ParticleEditor/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/ParticleEditor/CMakeLists.txt @@ -37,6 +37,8 @@ target_include_directories(z_particleeditor PRIVATE ) target_link_libraries(z_particleeditor PRIVATE + core_debug + core_profile corei_libraries_source_wwvegas corei_libraries_source_wwvegas_wwlib d3d8lib @@ -46,8 +48,6 @@ target_link_libraries(z_particleeditor PRIVATE stlport vfw32 winmm - z_debug - z_profile zi_gameengine_include zi_always zi_libraries_source_wwvegas diff --git a/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.cpp b/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.cpp index 90838557f0..7a57812b62 100644 --- a/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.cpp +++ b/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.cpp @@ -23,7 +23,7 @@ #include "ParticleEditor.h" #include "ParticleEditorDialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.rc b/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.rc index 95c73af067..8010aaa685 100644 --- a/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.rc +++ b/GeneralsMD/Code/Tools/ParticleEditor/ParticleEditor.rc @@ -69,7 +69,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/W3DView/CMakeLists.txt b/GeneralsMD/Code/Tools/W3DView/CMakeLists.txt index fd2cd5f630..7225e63bd5 100644 --- a/GeneralsMD/Code/Tools/W3DView/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/W3DView/CMakeLists.txt @@ -1,190 +1,26 @@ -set(W3DVIEW_SRC - "AddToLineupDialog.cpp" - "AddToLineupDialog.h" - "AdvancedAnimSheet.cpp" - "AdvancedAnimSheet.h" - "AggregateNameDialog.cpp" - "AggregateNameDialog.h" - "AmbientLightDialog.cpp" - "AmbientLightDialog.h" - "AnimatedSoundOptionsDialog.cpp" - "AnimatedSoundOptionsDialog.h" - "AnimationPropPage.cpp" - "AnimationPropPage.h" - "AnimationSpeed.cpp" - "AnimationSpeed.h" - "AnimMixingPage.cpp" - "AnimMixingPage.h" - "AnimReportPage.cpp" - "AnimReportPage.h" - "AssetInfo.cpp" - "AssetInfo.h" - "AssetPropertySheet.cpp" - "AssetPropertySheet.h" - "AssetTypes.h" - "BackgroundBMPDialog.cpp" - "BackgroundBMPDialog.h" - "BackgroundColorDialog.cpp" - "BackgroundColorDialog.h" - "BackgroundObjectDialog.cpp" - "BackgroundObjectDialog.h" - "BoneMgrDialog.cpp" - "BoneMgrDialog.h" - "CameraDistanceDialog.cpp" - "CameraDistanceDialog.h" - "CameraSettingsDialog.cpp" - "CameraSettingsDialog.h" - "ColorBar.cpp" - "ColorBar.h" - "ColorPicker.cpp" - "ColorPicker.h" - "ColorPickerDialogClass.cpp" - "ColorPickerDialogClass.h" - "ColorSelectionDialog.cpp" - "ColorSelectionDialog.h" - "ColorUtils.cpp" - "ColorUtils.h" - "DataTreeView.cpp" - "DataTreeView.h" - "DeviceSelectionDialog.cpp" - "DeviceSelectionDialog.h" - "DialogToolbar.cpp" - "DialogToolbar.h" - "DirectoryDialog.cpp" - "DirectoryDialog.h" - "EditLODDialog.cpp" - "EditLODDialog.h" - "EmitterColorPropPage.cpp" - "EmitterColorPropPage.h" - "EmitterFramePropPage.cpp" - "EmitterFramePropPage.h" - "EmitterGeneralPropPage.cpp" - "EmitterGeneralPropPage.h" - "EmitterInstanceList.cpp" - "EmitterInstanceList.h" - "EmitterLineGroupPropPage.cpp" - "EmitterLineGroupPropPage.h" - "EmitterLinePropPage.cpp" - "EmitterLinePropPage.h" - "EmitterParticlePropPage.cpp" - "EmitterParticlePropPage.h" - "EmitterPhysicsPropPage.cpp" - "EmitterPhysicsPropPage.h" - "EmitterPropertySheet.cpp" - "EmitterPropertySheet.h" - "EmitterRotationPropPage.cpp" - "EmitterRotationPropPage.h" - "EmitterSizePropPage.cpp" - "EmitterSizePropPage.h" - "EmitterUserPropPage.cpp" - "EmitterUserPropPage.h" - "GammaDialog.cpp" - "GammaDialog.h" - "Globals.cpp" - "Globals.h" - "GraphicView.cpp" - "GraphicView.h" - "HierarchyPropPage.cpp" - "HierarchyPropPage.h" - "LODDefs.h" - "MainFrm.cpp" - "MainFrm.h" - "MeshPropPage.cpp" - "MeshPropPage.h" - "OpacitySettingsDialog.cpp" - "OpacitySettingsDialog.h" - "OpacityVectorDialog.cpp" - "OpacityVectorDialog.h" - "ParticleBlurTimeKeyDialog.cpp" - "ParticleBlurTimeKeyDialog.h" - "ParticleFrameKeyDialog.cpp" - "ParticleFrameKeyDialog.h" - "ParticleRotationKeyDialog.cpp" - "ParticleRotationKeyDialog.h" - "ParticleSizeDialog.cpp" - "ParticleSizeDialog.h" - "PlaySoundDialog.cpp" - "PlaySoundDialog.h" - "ResolutionDialog.cpp" - "ResolutionDialog.h" - "resource.h" - "RestrictedFileDialog.cpp" - "RestrictedFileDialog.h" - "RingColorPropPage.cpp" - "RingColorPropPage.h" - "RingGeneralPropPage.cpp" - "RingGeneralPropPage.h" - "RingPropertySheet.cpp" - "RingPropertySheet.h" - "RingSizePropPage.cpp" - "RingSizePropPage.h" - "SaveSettingsDialog.cpp" - "SaveSettingsDialog.h" - "ScaleDialog.cpp" - "ScaleDialog.h" - "SceneLightDialog.cpp" - "SceneLightDialog.h" - "ScreenCursor.cpp" - "ScreenCursor.h" - "SoundEditDialog.cpp" - "SoundEditDialog.h" - "SphereColorPropPage.cpp" - "SphereColorPropPage.h" - "SphereGeneralPropPage.cpp" - "SphereGeneralPropPage.h" - "SpherePropertySheet.cpp" - "SpherePropertySheet.h" - "SphereSizePropPage.cpp" - "SphereSizePropPage.h" - #"SphereUtils.cpp" # Unused and does not compile - #"SphereUtils.h" # Unused and does not compile - "StdAfx.cpp" - "StdAfx.h" - #"TextureMgrDialog.cpp" # Unused - #"TextureMgrDialog.h" # Unused - "TexturePathDialog.cpp" - "TexturePathDialog.h" - #"TextureSettingsDialog.cpp" # Unused - #"TextureSettingsDialog.h" # Unused - "Toolbar.cpp" - "Toolbar.h" - "Utils.cpp" - "Utils.h" - "Vector3RndCombo.cpp" - "Vector3RndCombo.H" - "ViewerAssetMgr.cpp" - "ViewerAssetMgr.h" - "ViewerScene.cpp" - "ViewerScene.h" - "VolumeRandomDialog.cpp" - "VolumeRandomDialog.h" - "W3DView.cpp" - "W3DView.h" - "W3DViewDoc.cpp" - "W3DViewDoc.h" - "W3DViewView.cpp" - "W3DViewView.h" -) - add_executable(z_w3dview WIN32) -target_sources(z_w3dview PRIVATE ${W3DVIEW_SRC}) - target_link_libraries(z_w3dview PRIVATE + core_config + core_utility + core_wwstub # avoid linking GameEngine + corei_w3dview # this interface gets the source files for the tool + d3d8 + d3d8lib + d3dx8 dbghelplib imm32 + milesstub Version vfw32 winmm z_wwaudio - z_wwcommon - z_gameenginedevice + z_wwvegas ) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") target_compile_definitions(z_w3dview PRIVATE _AFXDLL) - target_sources(z_w3dview PRIVATE W3DView.rc) - set_target_properties(z_w3dview PROPERTIES OUTPUT_NAME W3DView) + set_target_properties(z_w3dview PROPERTIES OUTPUT_NAME W3DViewZH) else() - set_target_properties(z_w3dview PROPERTIES OUTPUT_NAME w3dview) + set_target_properties(z_w3dview PROPERTIES OUTPUT_NAME w3dviewzh) endif() diff --git a/GeneralsMD/Code/Tools/WW3D/CMakeLists.txt b/GeneralsMD/Code/Tools/WW3D/CMakeLists.txt deleted file mode 100644 index 1e5b20b0a7..0000000000 --- a/GeneralsMD/Code/Tools/WW3D/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -if (TARGET maxsdk) - add_subdirectory(pluglib) - add_subdirectory(max2w3d) -endif() diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/DISK12.ICO b/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/DISK12.ICO deleted file mode 100644 index 8b21b36843..0000000000 Binary files a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/DISK12.ICO and /dev/null differ diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/one.bmp b/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/one.bmp deleted file mode 100644 index 12f4663906..0000000000 Binary files a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/one.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/orig.ico b/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/orig.ico deleted file mode 100644 index 7c1adf6f27..0000000000 Binary files a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/orig.ico and /dev/null differ diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/orig1.ico b/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/orig1.ico deleted file mode 100644 index c724f99592..0000000000 Binary files a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/orig1.ico and /dev/null differ diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/two.bmp b/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/two.bmp deleted file mode 100644 index 45f8fd4032..0000000000 Binary files a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/two.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/ww3d.bmp b/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/ww3d.bmp deleted file mode 100644 index d63e18ff6f..0000000000 Binary files a/GeneralsMD/Code/Tools/WW3D/max2w3d/Res/ww3d.bmp and /dev/null differ diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/changes.txt b/GeneralsMD/Code/Tools/WW3D/max2w3d/changes.txt deleted file mode 100644 index c148797992..0000000000 --- a/GeneralsMD/Code/Tools/WW3D/max2w3d/changes.txt +++ /dev/null @@ -1,412 +0,0 @@ -Version 1.0.4.70: August 22, 2001 -Greg: - Added BumpEnv mapper - - Added NPatch enable flag for meshes (in the w3dtools command panel) -Ian: - Added BumpEnv setting to the shader (in primary gradient) - -Version 1.0.4.69: January 4, 2001 -Greg: - Modified the "bone picker" that the WWSkin space warp uses to allow Max bones to - be used. - -Version 1.0.4.68: December 7, 2000 -Andre: - Added a Static Sort Level parameter to the Surface Properties rollup page of the - material editor. This parameter must be the same across all materials assigned to - one mesh, and is enforced on export. The value is written out as part of the mesh - header to which the material is assigned. - -Version 1.0.4.67: December 6, 2000 -Greg: - Added 'Vehicle' collision bit. This will allow us to create meshes which constrain vehicles - to certain parts of a level without constraining characters or projectiles. - -Version 1.0.4.66: November 7, 2000 -Greg: - Disabled the "optimize meshes" feature because recent developments in the run-time code - seem to have made it un-necessary (and possibly even undesireable due to the extra mesh overhead) - The main reason for disabling the feature is that the automatic nature of it makes some of - our processes harder to debug. Mesh names are lost so the artist has no way of figuring out - which mesh is causing problems when one of the other tools complains about something. - - modified the mesh export code to reject meshes that are using multi-pass transparent materials. - - fixed error message boxes so they pop on top of all windows (they were appearing behind the log window) - -Version 1.0.4.65: October 31, 2000 -Greg: - Finished code re-organization. - - Pat provided new UI for the main export dialog - - Fixed the "smooth across meshes" feature - - Added the export log window. - -Version 1.0.4.64: October 20, 2000 -Greg: - Fixed a bug in the name editing dialog in the W3D utility panel - - Modified the VAlpha behavior so that only the *last* pass with alpha blending - gets the vertex alpha (instead of all passes with alpha blending) - - Added the Aggregate geometry type. This lets you request external - W3D objects to be attached to bones in your model. - - Added preliminary mesh optimization features. During the export, meshes can be split - into single-material meshes and then meshes which use the same materials - can be combined into larger meshes. - -Version 1.0.4.63: October 19, 2000 -Greg: Re-organized the entire DoExport function. - - First I unified all of the code to go through the "DoOriginBasedExport" - code by using the scene root as the origin when there were no user-defined - origins. - - Re-organized the Export_Geometry function to use a new abstract - class: GeometryExporTaskClass which encapsulates a lot of code that was - cut-and-pasted many times through the w3dexp.cpp module. - - Broke several classes and functions out of w3dexp.cpp into their own - modules. - - Modified/Cleaned HierarchySaveClass and MeshConnections class. - -Version 1.0.4.62: October 11, 2000 -Greg: Re-organised the W3DUtility plugin. Moved several dialog boxes - used by it into their own modules and created a modeless dialog - containing the w3d settings that can be left up when the user - is not in Max's utility panel. - -Version 1.0.4.61: September 26, 2000 -Greg: Added copying of the dazzle app data structure to the MaxScript - extensions. - -Version 1.0.4.60: September 22, 2000 -Greg: Added dazzle exporting to the plugin. Modified MeshConnnections - class and the w3d file format so that HModels are exported in a - slightly simpler manner and so that they can support dazzles. The - "auxiliary" header for hmodels is now obsolete. - -Version 1.0.4.59: September 18, 2000 -Greg: Modified the code so that collections are exported even when no - meshes or other render objects are present. This is used to create - collections of proxy objects for the renegade level editor. Also - modified the "origin" export code to support exporting collections - with origins. - -Version 1.0.4.58: August 25, 2000 -Greg: Fixed a crash bug that happens if you create a PS2 material. The - bug was caused by the modifications to the texture pane to replace - the NoMipMap and Resize buttons with a single NoLOD button. For some - reason, the PS2 material uses a separate dialog template for its - texture pane which is the same as the dialog template for the - normal material. Since the PS2 version of the template was not updated, - the code would crash when initializing the NoLOD button. - -Version 1.0.4.57: August 18, 2000 -Andre: Fixed the loading of version 4 ParameterBlocks so that the value - for Stage1MappingType is correct. - -Version 1.0.4.56: August 16,2000 -Greg: Removed the texture flags and buttons for No-Mipmapping and enable - resizing. These are all lumped into the setting for No-LOD now. - The GameMtl still has the entries in its parameter block for - No-Mipmapping and Resize and I use the No-Mipmap setting to set - the initial state of the No-LOD flag... This also required a flag - in GameMtl indicating that the conversion had been done. Ug... :-) - -Version 1.0.4.55: August 6, 2000 -Greg: Added new colliison type: camera. In renegade we have some physically - collideable meshes which the camera should not collide with so I had - to make a separate flag for camera collision. When the appdata chunk - is first converted to the new version, the camera collision flag is - set to the same setting as the current state of physical collision. - - Added light-glare geometry type. This currently only exports the - position of the pivot point of the max object. It will be used to - indicate where there should be fancy light glare effects in the level - - Added NoLOD option to textures in the W3D material. This setting will - be used on textures which should not scale down even when texture - reduction is being used. - - Fixed serious bug in the parameter block description for the W3D - material plugin (GameMtl.cpp) - -Version 1.0.4.54: July 13, 2000 -Greg: Fixed a bug related to user-defined origins not working when they - are rotate or moved from 0,0,0. - -Version 1.0.4.53: July 12, 2000 -Andre: Added support for a different mappers on stage 0/1 of the Vertex - Material. Added support for the new silhouette mapper type. - These changes can be found in the VertexMaterial panel in the - W3d material editor. - -Version 1.0.4.52: May 30, 2000 -Greg: Added support for Max's multiple mapping channels. This can be - found in the VertexMaterial panel in the W3d material editor. - -Version 1.0.4.51: May 22, 2000 -Greg: Added AABTree exporting so that we don't have to generate AABTrees - at run-time. This is controlled by the "Optimize Collision Detection" - checkbox on the exporter options dialog box. - Added prefix and suffix features to the naming tool. - Added detatch vertices feature to the skin modifier. - -Version 1.0.4.50: May 8, 2000 -Andre: Added a new MAX Script extension: wwInputBox - This is a generic way of getting user input in a Windows-like - manner (as opposed to typing it in the Listener window as - MAX wants to force you to do). - -Version 1.0.4.49: May 2, 2000 -Greg: Fixed a bug in vchannel.cpp. Was writing out garbage animation - channels which would crash wdump. - -Version 1.0.4.48: May 1, 2000 -Greg: Changed the way skins are exported so that their vertices are - sorted with respect to the bone they are attached to. Also - made it so vertices are secondarily sorted by vertex material - (this means that non-skinned meshes will sort by vertex - material only.) - -Version 1.0.4.47: April 19 2000 -Greg: Added a new geometry option for "shatterable" objects. Wrote - a new W3DAppData2Struct which replaces the old AppData1Struct. - Whenever the old format app data is encountered, a new one - is created to replace it. This new app data chunk has more - space in it for future expansion. - Also fixed a crash bug in the skin modifier related to deleting - bones from the space warp. - -Version 1.0.4.46: March 28, 2000 -Greg: Added "Transform Nodes" to the collection export. We already had - "Placeholder" objects which were signified by a '~' after the - name. Now we have "Transform Nodes" which are signified by a '*' - after the name. Transform Nodes instruct one of the Renegade tools - to merge another W3D collection into the file at a given transform. - The purpose was to allow us to lightmap certain building interiors - only once and then merge them into many levels... - -Version 1.0.4.45: March 8, 2000 -Andre: Changed the Is_Origin() test to check for hidden nodes. If a - node is hidden, it will not be accepted as an origin. This - means that hiding an LOD prevents it from being exported (as - you would expect). - -Version unchanged: early March -Andre: Fixed a couple of crash bugs related to animation exporting. - -Version 1.0.4.43: February 29, 2000 -Greg: Fixed a bug which caused all meshes marked to cast shadows to - not get texture coordinates. - Fixed meshsave.cpp to detect and properly handle mirrored meshes. - -Version 1.0.4.42: January 24, 2000 -Lytle: Added Playstation 2 material support, including converting W3D - materials to PS2 materials. Added support for vertex colors and - vertex alpha to exist concurrently. - -Version 1.0.4.41: January 13, 2000 -Andre: Fixed a nasty memory overwriting bug in MeshConnectionsClass - that only reared its head under very unique circumstances. - It was a copy/paste bug that would lead to writing a W3D - file with incorrect data. It would manifest itself by crashing - the viewer (and potentially the game engines) when trying to - load the file. - -Version 1.0.4.40: December 16, 1999 -Ian: Added 'Export Utilites' group to W3D Utility panel and added a - 'Export with Std Mtls' button to this group. This button will - first convert all W3D materials in the scene to standard - materials, then call the export feature, then, after export, - convert materials back to W3D materials. The purpose of this - utility is to make it possible to export W3D material attributes - to third party file formats (eg. Lightscape Preparation files). - -Version 1.0.4.39: November 15, 1999 -Andre: Changed the mesh LOD naming convention so that we use numbers - that correspond to the LOD number (highest-to-lowest) instead - of letters that went from lowest-to-highest. - -Version 1.0.4.38: November 12, 1999 -Greg: Updated MeshConnections class and the hmodel chunk definitions - in w3d_file class to not treat shadow meshes as a different type - of mesh. - -Version 1.0.4.37: November 11, 1999 -Greg: Removed the GEOMETRY_TYPE_SHADOW settings and UI. Added a - EXPORT_CAST_SHADOW flag. This basically means that rather than - shadow casting being a completely different "type" of mesh it - is now an option on any mesh. This required some tweaking - of the AppData structure we're saving and to the w3dutil code. - -Version 1.0.4.35: November 3, 1999 -Andre: Exposed another script extension, called "wwDuplicateSkinWSM". - This extension allows the SceneSetup script to copy bone - information from the base object's skin WSM to the LODs. - Meshes are still unaffected, since the artist will be munging - the meshes to reduce their poly counts. - -Version 1.0.4.34: November 2, 1999 -Andre: Exposed two new script extensions, named "wwCopySkinInfo" and - "wwFindSkinNode". These extensions allow the SceneSetup script - to copy the skin/vertex/bone binding information from the base - model to the LOD and Damage models. - -Version 1.0.4.33: October 18, 1999 -Andre: Merged WWScript.dlx into the exporter, so now WWScript is - unnessesary and should be deleted. The code in that DLX was - ported from MFC to Win32 code during the merge. GetW3DAppData0 - and GetW3DAppData1 are no longer exported from the DLE. - -Version 1.0.4.32: October 11, 1999 -Andre: Correct NULL object handling was implemented when exporting HLODs. - NULL object chunks are only written when using the old-style LOD - setup (one per file), otherwise the name "NULL" is put in the HLOD - and no NULL object chunk is written. - -Version 1.0.4.31: October 5, 1999 -Andre: Fixed a bug in MeshBuilder where a division by zero occurred if the - extents of a triangle was zero in one dimension. - -Version 1.0.4.30: October 1, 1999 -Andre: - Added support for the "suppressPrompts" flag during export. If - Max passes in a TRUE value, we will go with the previous export - settings instead of showing the export options dialog. This makes - non-interactive batch exporting possible. - - Moved W3dExportOptionsStruct from w3ddlg.h to w3dutil.h so that - WWScript can access it easily. - -Version 1.0.4.29: September 27, 1999 -Andre: - Fixed a skin bug that occurred in LOD exporting when a vertex in a - skin was not bound to a bone (it would be exported in unmodified - coordinates, creating a "pop"). - - Strip off any trailing ".%d" or "." from a name in Set_W3D_Name - (as opposed to just ".%d"). - - If the artist sets up damage animations, then the animation on - the base model is no longer exported. (non-damage animations should - still be created in separate files) - - Exporting 2 more symbols from the DLL (GetW3DAppData0 and - GetW3DAppData1). These functions are used by the MAXScript extension - DLL (WWScript.dlx) to copy AppData from one node to another. - -Version 1.0.4.28: September 23, 1999 -Andre: Fixed a bug in LOD exporting when the base object wasn't centered - at the origin. Added support for placing damage models in the scene. - Renamed "Generate LOD extensions" to "Generate extensions" since - the same extensions are used for damage. Added a "Damage Region" - spinner to the W3D Tools panel. With this spinner you can mark - bones as being part of a given damage region (0 to 15, -1 means - not part of a damage region). - -Version 1.0.4.27: September 17, 1999 -Greg: Added degenerate triangle removal to MeshBuilderClass. - -Version 1.0.4.26: September 17, 1999 -Andre: Modified the exporting code to allow artists to define all LODs of - an object in one MAX file. The old way of creating LODs is still - supported so that old art assets are still usable. Added a - "Generate LOD extensions" button to the W3D Tools panel to make - the Origin naming convention less painful. - -Version 1.0.4.25: August 21, 1999 -Greg: Fixed a bug in Export_Geometry. While exporting skins, one line of - code was referring to the list of normal meshes rather than the list - of skins. When you do an export with only a skin and no meshes, this - causes an access violation. - -Version 1.0.4.24: July 27, 1999 -Greg: Changed the Hide/Unhide by W3D type buttons into "Select by W3D Type" - buttons. This should be more useable. Also, added select alpha meshes, - select physical, projectile and vis collision meshes. - Added a material naming tool. - -Version 1.0.4.23: July 9, 1999 -Pat: Changed the default behavior of the collection naming tool to - be 'affect selected' rather than 'affect all' - -Version 1.0.4.22: July 7, 1999 -Pat: The export code doesn't export the DCG array if all vertex colors - are white (1, 1, 1), however this was a problem when using the - new Mesh Deformer, so I added a check during export to see if - the Deformer was modifying vertex colors. Also modified the - hierarchy export code so it will resize its internal array if - the number of nodes is greater than 512. - -Version 1.0.4.21: July 1, 1999 -Pat: Added code to optimze the between-mesh smoothing and added a new - button to the export dialog that allows the user to turn this - smoothing feature on/off. Also added displacement maps to the - W3D material, however due to a bug in the NURBS Mesher modifier, - we decided not to expose the functionality in UI at this time. - -Version 1.0.4.20: June 24, 1999 -Pat: Added code to apply smoothing groups over mesh boundaries. More - work was done on the obj-space mesh deform modifier including save/load, - export, undo, and vertex-alpha support. We fixed a bug where the ErrorClass - object that was used during exception handling was using and freeing a - previously freed pointer. Added a new panel to the material types for - Commando surface types. - -Version 1.0.4.19: June 14, 1999 -Greg: Added the VAlpha checkbox to the W3D utility panel. Checking this - causes the exporter to convert vertex colors into alpha values and put - them in all passes that are using alpha blending. This might be a temporary - solution; I'm thinking we need to extend the Utility panel (and the AppData - structure that we are saving) to allow for more flexible control over vertex - alpha, vertex color, etc. - -Version 1.0.4.18: May 27, 1999 -Greg: Fixed a bug in the code which handles loading a hierarchy tree from another - W3D file. Made the W3D utility panel support multiple selection. -Pat: Added the initial mesh deform object space modifier. Currently doesn't - export the data. - -Version 1.0.4.17: April 9, 1999 -Greg: Fixed a bug related to exporting a mesh with zero vertices. Exporter will - throw an exception which pops up a message box indicating the name of the - mesh. Made the collision boxes behave the same way as meshes when one is - exported with geometry only - it takes on the name of the file. Whew this - part of the exporter code is getting uuuuuugly... - -Version 1.0.4.16: April 6, 1999 -Greg: Fixed a bug related to the storing of the default export options. If the - user exported a model which uses the hierarchy from another model and then - moves the Max file, the next export would crash Max when the exporter couldn't - find the w3d file which contains the hierarchy. - -Version 1.0.4.15: Mar 18, 1999 -Greg: Fixed a bug in the AABox export. Was using the wrong coordinate system for - the box. AABoxes actually seem to be of very limited use. Possibly only - useful as an approximation of a cylinder centered at 0,0,0 in object space - (but moved anywhere on the z-axis) and only for objects that *only* rotate - about the z-axis. (characters) Ug. - -Version 1.0.4.14: Mar 16, 1999 -Greg: Made meshes that are marked as AABox or OBBox export a W3D_CHUNK_BOX instead - of a mesh. The runtime engine can test collision with a box in about the same - amount of time it takes to check a single triangle... so one box is much faster - than a 12 triangle mesh :) These boxes are only for collision detection so - they only export a color, no other rendering information. - -Version 1.0.4.13: Mar 11, 1999 -Greg: Fixed a bug in the collection exporter. Needed to put the entire name - of the render object into the sub object chunk. - -Version 1.0.4.12: Mar 10, 1999 -Naty: Fixed minor bug with start/end animation frames in export dialog. - -Version 1.0.4.11: Mar 4, 1999 -Naty: Added "Camera Oriented" mesh type (and changed the camera aligned button - to read "Camera Parallel"). Export options are now saved in the MAX file - (hierarchy file paths are saved in a relative form). - -Version 1,0,4,10: Mar 3, 1999 -Greg: Modified so that collections are not exported when there is only a single - mesh and forced that mesh to use the name of the file. - Changed w3d_file.h so that meshes have a "container name" instead of - a "hierarchy model name" and set the container name when a collection is exported - -Version 1,0,4,9: Mar 3, 1999 -Naty: New Shader (took out colormaks, fogfunc, new dialog and preset system) - Added alphatest support, added Linear offset mapper and mapper argument - string support - -Version 1,0,4,8: Feb 9, 1999 -Greg: Added the ZNormals option for forcing the normals of a mesh to be 0,0,1 - -Version 1,0,4,7: Feb 8, 1999 -Greg: Fixed 2 bugs in the skin code. Added code to scan the materials used - by a mesh and discard un-used ones. -Naty: Added 'Alpha-Bitmap' button to the texture dialog, added new shader presets - -Version 1,0,4,8: Feb 15, 1999 -Greg: Improved the strip generation algorithm. Now actually turns a cube into 6 - strips instead of 12 individual triangles. Still needs work though... - - diff --git a/GeneralsMD/Code/Tools/WW3D/max2w3d/max2w3d.def b/GeneralsMD/Code/Tools/WW3D/max2w3d/max2w3d.def deleted file mode 100644 index 3a9fe01775..0000000000 --- a/GeneralsMD/Code/Tools/WW3D/max2w3d/max2w3d.def +++ /dev/null @@ -1,10 +0,0 @@ -LIBRARY max2w3d -EXPORTS - LibDescription @1 - LibNumberClasses @2 - LibClassDesc @3 - LibVersion @4 - GetW3DAppData0 @5 - GetW3DAppData1 @6 -SECTIONS - .data READ WRITE diff --git a/GeneralsMD/Code/Tools/WorldBuilder/CMakeLists.txt b/GeneralsMD/Code/Tools/WorldBuilder/CMakeLists.txt index 00b13d3d4c..d984b45440 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/WorldBuilder/CMakeLists.txt @@ -204,22 +204,22 @@ add_executable(z_worldbuilder WIN32) target_sources(z_worldbuilder PRIVATE ${WORLDBUILDER_SRC}) target_include_directories(z_worldbuilder PRIVATE - . + ${CMAKE_CURRENT_SOURCE_DIR} include res ) target_link_libraries(z_worldbuilder PRIVATE + core_debug + core_profile d3d8lib dbghelplib imm32 vfw32 winmm core_browserdispatch - z_debug z_gameengine z_gameenginedevice - z_profile zi_gameengine_include zi_gameenginedevice_include zi_always diff --git a/GeneralsMD/Code/Tools/WorldBuilder/include/MainFrm.h b/GeneralsMD/Code/Tools/WorldBuilder/include/MainFrm.h index a2e5a0383b..506cc13885 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/include/MainFrm.h +++ b/GeneralsMD/Code/Tools/WorldBuilder/include/MainFrm.h @@ -80,7 +80,7 @@ class CMainFrame : public CFrameWnd // Implementation public: virtual ~CMainFrame(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h b/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h index 578796e269..dfbca52496 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h +++ b/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderDoc.h @@ -170,7 +170,7 @@ class CWorldBuilderDoc : public CDocument // Implementation public: virtual ~CWorldBuilderDoc(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderView.h b/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderView.h index 89c6e8e498..fc5c740577 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderView.h +++ b/GeneralsMD/Code/Tools/WorldBuilder/include/WorldBuilderView.h @@ -60,7 +60,7 @@ class CWorldBuilderView : public WbView // Implementation public: virtual ~CWorldBuilderView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/include/wbview.h b/GeneralsMD/Code/Tools/WorldBuilder/include/wbview.h index ddd2e208b1..ab047e5b61 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/include/wbview.h +++ b/GeneralsMD/Code/Tools/WorldBuilder/include/wbview.h @@ -171,7 +171,7 @@ class WbView : public CView // Implementation protected: virtual ~WbView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/include/wbview3d.h b/GeneralsMD/Code/Tools/WorldBuilder/include/wbview3d.h index b77ef29fce..65e9057d12 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/include/wbview3d.h +++ b/GeneralsMD/Code/Tools/WorldBuilder/include/wbview3d.h @@ -86,7 +86,7 @@ class WbView3d : public WbView, public DX8_CleanupHook // Implementation protected: virtual ~WbView3d(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/res/WorldBuilder.rc b/GeneralsMD/Code/Tools/WorldBuilder/res/WorldBuilder.rc index 5b32414f71..ef28eed189 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/res/WorldBuilder.rc +++ b/GeneralsMD/Code/Tools/WorldBuilder/res/WorldBuilder.rc @@ -1878,7 +1878,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 0,8,0,0 PRODUCTVERSION 0,8,0,0 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/DrawObject.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/DrawObject.cpp index 12673aef94..d835153f7f 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/DrawObject.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/DrawObject.cpp @@ -59,7 +59,7 @@ #include "GameLogic/Weapon.h" #include "Common/AudioEventInfo.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define NO_INTENSE_DEBUG 1 #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/EditAction.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/EditAction.cpp index 1cd2f2c0a3..d34968b370 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/EditAction.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/EditAction.cpp @@ -25,7 +25,7 @@ #include "EditParameter.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/EditCondition.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/EditCondition.cpp index 9fda6f1bfb..e74a8dd121 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/EditCondition.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/EditCondition.cpp @@ -25,7 +25,7 @@ #include "EditParameter.h" #include "GameLogic/ScriptEngine.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/EditParameter.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/EditParameter.cpp index 4d19b1757f..cedf8e96a8 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/EditParameter.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/EditParameter.cpp @@ -64,7 +64,7 @@ #include "W3DDevice/GameClient/W3DGameFont.h" #include "W3DDevice/GameClient/HeightMap.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/EulaDialog.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/EulaDialog.cpp index 549891c499..06ed2faa3f 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/EulaDialog.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/EulaDialog.cpp @@ -23,7 +23,7 @@ #include "WorldBuilder.h" #include "euladialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/MainFrm.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/MainFrm.cpp index ea5fd635c9..ecfa71b739 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/MainFrm.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/MainFrm.cpp @@ -447,7 +447,7 @@ void CMainFrame::onEditScripts() ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); @@ -458,7 +458,7 @@ void CMainFrame::Dump(CDumpContext& dc) const CFrameWnd::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectTool.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectTool.cpp index 7136711487..e31d253efd 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectTool.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/ObjectTool.cpp @@ -70,7 +70,7 @@ Real ObjectTool::calcAngle(Coord3D downPt, Coord3D curPt, WbView* pView) if (dx<0) angle = PI-angle; } if (angle > PI) angle -= 2*PI; -#ifdef _DEBUG +#ifdef RTS_DEBUG CString buf; buf.Format("Angle %f rad, %d degrees\n", angle, (int)(angle*180/PI)); ::OutputDebugString(buf); diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/OpenMap.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/OpenMap.cpp index 20ec448637..04a0746c3c 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/OpenMap.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/OpenMap.cpp @@ -33,7 +33,7 @@ OpenMap::OpenMap(TOpenMapInfo *pInfo, CWnd* pParent /*=NULL*/) m_pInfo(pInfo) { m_pInfo->browse = false; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_usingSystemDir = ::AfxGetApp()->GetProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", TRUE); #else m_usingSystemDir = FALSE; @@ -110,7 +110,7 @@ void OpenMap::OnOK() void OpenMap::populateMapListbox( Bool systemMaps ) { m_usingSystemDir = systemMaps; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ::AfxGetApp()->WriteProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", m_usingSystemDir); #endif @@ -190,7 +190,7 @@ BOOL OpenMap::OnInitDialog() if (pUserMaps != NULL) pUserMaps->SetCheck( !m_usingSystemDir ); -#if !defined(_DEBUG) && !defined(_INTERNAL) +#if !defined(RTS_DEBUG) && !defined(RTS_INTERNAL) if (pSystemMaps) pSystemMaps->ShowWindow( FALSE ); if (pUserMaps) diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/SaveMap.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/SaveMap.cpp index 02b02cf7dc..c1856e5a0f 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/SaveMap.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/SaveMap.cpp @@ -32,7 +32,7 @@ SaveMap::SaveMap(TSaveMapInfo *pInfo, CWnd* pParent /*=NULL*/) : CDialog(SaveMap::IDD, pParent), m_pInfo(pInfo) { -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) m_pInfo->usingSystemDir = m_usingSystemDir = ::AfxGetApp()->GetProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", TRUE); #else m_pInfo->usingSystemDir = m_usingSystemDir = FALSE; @@ -121,7 +121,7 @@ void SaveMap::OnBrowse() void SaveMap::populateMapListbox( Bool systemMaps ) { m_pInfo->usingSystemDir = m_usingSystemDir = systemMaps; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ::AfxGetApp()->WriteProfileInt(MAP_OPENSAVE_PANEL_SECTION, "UseSystemDir", m_usingSystemDir); #endif @@ -225,7 +225,7 @@ BOOL SaveMap::OnInitDialog() if (pUserMaps != NULL) pUserMaps->SetCheck( !m_usingSystemDir ); -#if !defined(_DEBUG) && !defined(_INTERNAL) +#if !defined(RTS_DEBUG) && !defined(RTS_INTERNAL) if (pSystemMaps) pSystemMaps->ShowWindow( FALSE ); if (pUserMaps) diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp index 63d4b4a69d..2b1086da51 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptDialog.cpp @@ -42,7 +42,7 @@ #include "WaypointOptions.h" #include "Common/UnicodeString.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptProperties.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptProperties.cpp index d3400fd0af..fcba96f790 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptProperties.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/ScriptProperties.cpp @@ -24,7 +24,7 @@ #include "ScriptProperties.h" #include "GameLogic/Scripts.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma message("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp index 6a493df133..52bb0e80c7 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WHeightMapEdit.cpp @@ -43,7 +43,7 @@ #include "Common/DataChunk.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -394,7 +394,7 @@ void WorldHeightMapEdit::loadBaseImages(void) { /// @todo - take this out when we are done evaluating terrain textures. -#if (defined(_DEBUG) || defined(_INTERNAL)) +#if (defined(RTS_DEBUG) || defined(RTS_INTERNAL)) loadDirectoryOfImages("..\\TestArt\\TestTerrain"); #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp index 4bf49d2bab..d9c1aa9476 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilder.cpp @@ -83,7 +83,7 @@ #include "Win32Device/Common/Win32LocalFileSystem.h" #include "Win32Device/Common/Win32BIGFileSystem.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -272,7 +272,7 @@ CWorldBuilderApp::~CWorldBuilderApp() BOOL CWorldBuilderApp::InitInstance() { -//#ifdef _RELEASE +//#ifdef RTS_RELEASE EulaDialog eulaDialog; if( eulaDialog.DoModal() == IDCANCEL ) { @@ -295,11 +295,11 @@ BOOL CWorldBuilderApp::InitInstance() DEBUG_LOG(("starting Worldbuilder.\n")); -#ifdef _INTERNAL - DEBUG_LOG(("_INTERNAL defined.\n")); +#ifdef RTS_INTERNAL + DEBUG_LOG(("RTS_INTERNAL defined.\n")); #endif -#ifdef _DEBUG - DEBUG_LOG(("_DEBUG defined.\n")); +#ifdef RTS_DEBUG + DEBUG_LOG(("RTS_DEBUG defined.\n")); #endif initMemoryManager(); #ifdef MEMORYPOOL_CHECKPOINTING @@ -352,7 +352,7 @@ BOOL CWorldBuilderApp::InitInstance() initSubsystem(TheWritableGlobalData, new GlobalData(), "Data\\INI\\Default\\GameData.ini", "Data\\INI\\GameData.ini"); -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) ini.load( AsciiString( "Data\\INI\\GameDataDebug.ini" ), INI_LOAD_MULTIFILE, NULL ); #endif @@ -360,7 +360,7 @@ BOOL CWorldBuilderApp::InitInstance() TheWritableGlobalData->m_debugIgnoreAsserts = false; #endif -#if defined(_INTERNAL) +#if defined(RTS_INTERNAL) // leave on asserts for a while. jba. [4/15/2003] TheWritableGlobalData->m_debugIgnoreAsserts = true; #endif DEBUG_LOG(("TheWritableGlobalData %x\n", TheWritableGlobalData)); @@ -433,7 +433,7 @@ BOOL CWorldBuilderApp::InitInstance() DEBUG_ASSERTCRASH(!TheGlobalData->m_useHalfHeightMap, ("TheGlobalData->m_useHalfHeightMap : Don't use this setting in WB.")); TheWritableGlobalData->m_useHalfHeightMap = false; -#if defined(_DEBUG) || defined(_INTERNAL) +#if defined(RTS_DEBUG) || defined(RTS_INTERNAL) // WB never uses the shroud. TheWritableGlobalData->m_shroudOn = FALSE; #endif diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp index ffd6518760..3f695dbdeb 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderDoc.cpp @@ -59,7 +59,7 @@ #include "WorldBuilderView.h" #include "MapPreview.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -910,7 +910,7 @@ void CWorldBuilderDoc::autoSave(void) ///////////////////////////////////////////////////////////////////////////// // CWorldBuilderDoc diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWorldBuilderDoc::AssertValid() const { CDocument::AssertValid(); @@ -920,7 +920,7 @@ void CWorldBuilderDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWorldBuilderDoc commands diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp index 12fae2096a..214679d5f6 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/WorldBuilderView.cpp @@ -137,7 +137,7 @@ void CWorldBuilderView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) ///////////////////////////////////////////////////////////////////////////// // CWorldBuilderView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWorldBuilderView::AssertValid() const { WbView::AssertValid(); @@ -148,7 +148,7 @@ void CWorldBuilderView::Dump(CDumpContext& dc) const WbView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG /** Set the cell size, and invalidate. */ void CWorldBuilderView::setCellSize(Int cellSize) diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp index 2024bcba23..028dc1171d 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/mapobjectprops.cpp @@ -39,7 +39,7 @@ const char* NEUTRAL_TEAM_UI_STR = "(neutral)"; const char* NEUTRAL_TEAM_INTERNAL_STR = "team"; -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/wbview.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/wbview.cpp index ccd272a2de..3366701712 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/wbview.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/wbview.cpp @@ -36,7 +36,7 @@ #include "teamsdialog.h" #include "LayersList.h" -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -159,7 +159,7 @@ void WbView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // WbView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void WbView::AssertValid() const { CView::AssertValid(); @@ -169,7 +169,7 @@ void WbView::Dump(CDumpContext& dc) const { CView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // WbView message handlers diff --git a/GeneralsMD/Code/Tools/WorldBuilder/src/wbview3d.cpp b/GeneralsMD/Code/Tools/WorldBuilder/src/wbview3d.cpp index 6ae830f5ec..94e9c6f51e 100644 --- a/GeneralsMD/Code/Tools/WorldBuilder/src/wbview3d.cpp +++ b/GeneralsMD/Code/Tools/WorldBuilder/src/wbview3d.cpp @@ -95,7 +95,7 @@ #include -#ifdef _INTERNAL +#ifdef RTS_INTERNAL // for occasional debugging... //#pragma optimize("", off) //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes") @@ -138,7 +138,7 @@ static void Debug_Refs(void); // ---------------------------------------------------------------------------- static void WWDebug_Message_Callback(DebugType type, const char * message) { -#ifdef _DEBUG +#ifdef RTS_DEBUG ::OutputDebugString(message); #endif } @@ -146,7 +146,7 @@ static void WWDebug_Message_Callback(DebugType type, const char * message) // ---------------------------------------------------------------------------- static void WWAssert_Callback(const char * message) { -#ifdef _DEBUG +#ifdef RTS_DEBUG ::OutputDebugString(message); ::DebugBreak(); #endif @@ -2210,7 +2210,7 @@ void WbView3d::OnDraw(CDC* pDC) // ---------------------------------------------------------------------------- // WbView3d diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG // ---------------------------------------------------------------------------- void WbView3d::AssertValid() const { @@ -2222,7 +2222,7 @@ void WbView3d::Dump(CDumpContext& dc) const { WbView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG // ---------------------------------------------------------------------------- void WbView3d::initWW3D() diff --git a/GeneralsMD/Code/Tools/assetcull/CMakeLists.txt b/GeneralsMD/Code/Tools/assetcull/CMakeLists.txt deleted file mode 100644 index 3ee3a49fe9..0000000000 --- a/GeneralsMD/Code/Tools/assetcull/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -set(ASSETCULL_SRC - "assetcull.cpp" -) - -add_executable(z_assetcull WIN32) -set_target_properties(z_assetcull PROPERTIES OUTPUT_NAME assetcull) - -target_sources(z_assetcull PRIVATE ${ASSETCULL_SRC}) - -target_link_libraries(z_assetcull PRIVATE - core_config -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(z_assetcull PRIVATE /subsystem:console) -endif() diff --git a/GeneralsMD/Code/Tools/buildVersionUpdate/CMakeLists.txt b/GeneralsMD/Code/Tools/buildVersionUpdate/CMakeLists.txt deleted file mode 100644 index 687861c9d7..0000000000 --- a/GeneralsMD/Code/Tools/buildVersionUpdate/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -set(BUILDVERSIONUPDATE_SRC - "buildVersionUpdate.cpp" -) - -add_executable(z_buildversionupdate WIN32) -set_target_properties(z_buildversionupdate PROPERTIES OUTPUT_NAME buildversionupdate) - -target_sources(z_buildversionupdate PRIVATE ${BUILDVERSIONUPDATE_SRC}) - -target_link_libraries(z_buildversionupdate PRIVATE - core_config - core_wwlib -) diff --git a/GeneralsMD/Code/Tools/mangler/Makefile b/GeneralsMD/Code/Tools/mangler/Makefile deleted file mode 100644 index d1176c2b04..0000000000 --- a/GeneralsMD/Code/Tools/mangler/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -all = mangler - -TARGET=mangler -TESTTARGET=manglertest - -OBJECTS=mangler.o crc.o -TESTOBJECTS=manglertest.o crc.o - - -LINKFLAGS= -LINKDIRS=-L. -Lwlib -Lwnet -############################################################################ -### -lpthread ### MUST MUST MUST be the last library! -############################################################################ -LINKLIBS = -lwnet -lwlib -lsocket -lnsl -lposix4 -lpthread - -INCDIR=-I. -Iwlib -Iwnet - -CPPFLAGS=$(INCDIR) -c -gstabs+ -DDEBUG -D_UNIX -#CPPFLAGS=$(INCDIR) -c -gstabs+ -D_UNIX - -CPPFILES=${OBJECTS:.o=.cpp} -CFILES=${OBJECTS:.o=.c} -.SUFFIXES : .c .cpp - - -$(TARGET) : $(OBJECTS) - g++ $(LINKFLAGS) $(OBJECTS) $(LINKDIRS) $(LINKLIBS) -o $(TARGET) - -$(TESTTARGET) : $(TESTOBJECTS) $(TARGET) - g++ $(LINKFLAGS) $(TESTOBJECTS) $(LINKDIRS) $(LINKLIBS) -o $(TESTTARGET) - -.cpp.o: - g++ $(CPPFLAGS) $< - -.c.o: - g++ $(CPPFLAGS) $< - - -depend: - g++ -M $(INCDIR) ${CFILES} $(CPPFILES) > dependencies - - -clean: - -rm *.o $(TARGET) $(TESTTARGET) core *.dat - -rebuild: - make clean; make - -run: - make; $(TARGET) - -debug: - gdb -s noxc noxc - -dist: - make clean; make; cp wdtd gavin; cp START gavin; cp STOP gavin; cp world.wdt gavin; - -#include dependencies diff --git a/GeneralsMD/Code/Tools/mangler/wlib/Makefile b/GeneralsMD/Code/Tools/mangler/wlib/Makefile deleted file mode 100644 index 1163a2ba61..0000000000 --- a/GeneralsMD/Code/Tools/mangler/wlib/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -########################################################################### -# WLIB library makefile -########################################################################## - -#Define cc to be your C compiler -CC = g++ - -#This tells make how to go from a .cpp to a .o -.SUFFIXES: .cpp -.cpp.o: - ${CC} ${CFLAGS} -c $< - -INCLUDE = -I. -I.. - -CFLAGS = ${INCLUDE} -D_REENTRANT -DDEBUG -D_UNIX - -AR = ar -r -#CC is dumb and won't include templates in a library uness you define -#CC -xar as your replacement for 'ar' -#AR = CC -xar - -RM = rm -f -RANLIB = ranlib - -############################################################################ -#Dont mess with any of this stuff -OBJECTS = wtime.o monod.o wdebug.o sem4.o streamer.o syslogd.o wstring.o \ - configfile.o threadfac.o critsec.o xtime.o timezone.o - -LIBRARY = libwlib.a - -all: $(LIBRARY) - -$(LIBRARY): $(OBJECTS) - ${RM} libwlib.a - ${AR} libwlib.a $(OBJECTS) - #${AR} $(OBJECTS) -o libwlib.a - $(RANLIB) libwlib.a - -clean: - - rm -f $(LIBRARY) *.o core diff --git a/GeneralsMD/Code/Tools/mangler/wnet/Makefile b/GeneralsMD/Code/Tools/mangler/wnet/Makefile deleted file mode 100644 index e5321ff0a3..0000000000 --- a/GeneralsMD/Code/Tools/mangler/wnet/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -########################################################################### -# TCP library makefile -########################################################################## - -#Define cc to be your C compiler -CC = g++ -CFLAGS = -gstabs ${INCLUDE} -D_REENTRANT #-DDEBUG - -#This tells make how to go from a .cpp to a .o -.SUFFIXES: .cpp -.cpp.o: - ${CC} ${CFLAGS} -c $< - -INCLUDE = -I.. -I. - -AR = ar -r -RM = rm -f -RANLIB = ranlib - -############################################################################ -#Dont mess with any of this stuff -OBJECTS = tcp.o udp.o packet.o field.o -LIBRARY = libwnet.a - -all: $(LIBRARY) - -$(LIBRARY): $(OBJECTS) - $(RM) $(LIBRARY) - $(AR) $(LIBRARY) $(OBJECTS) - $(RANLIB) $(LIBRARY) - -clean: - - rm -f $(LIBRARY) $(OBJECTS) core diff --git a/GeneralsMD/Code/Tools/matchbot/CMakeLists.txt b/GeneralsMD/Code/Tools/matchbot/CMakeLists.txt deleted file mode 100644 index d5d4183f70..0000000000 --- a/GeneralsMD/Code/Tools/matchbot/CMakeLists.txt +++ /dev/null @@ -1,78 +0,0 @@ -set(MATCHBOT_SRC - "debug.cpp" - "debug.h" - "encrypt.cpp" - "encrypt.h" - "generals.cpp" - "generals.h" - "global.cpp" - "global.h" - "main.cpp" - "matcher.cpp" - "matcher.h" - "mydebug.cpp" - "mydebug.h" - "rand.cpp" - "rand.h" - "wlib/arraylist.h" - "wlib/configfile.cpp" - "wlib/configfile.h" - "wlib/critsec.cpp" - "wlib/critsec.h" - "wlib/dictionary.h" - "wlib/filed.h" - "wlib/linkedlist.h" - "wlib/mboxd.h" - "wlib/monod.cpp" - "wlib/monod.h" - "wlib/odevice.h" - "wlib/sem4.cpp" - "wlib/sem4.h" - "wlib/stderrd.h" - "wlib/stdoutd.h" - "wlib/streamer.cpp" - "wlib/streamer.h" - "wlib/syslogd.cpp" - "wlib/syslogd.h" - "wlib/threadfac.cpp" - "wlib/threadfac.h" - "wlib/threadsafe.h" - "wlib/timezone.cpp" - "wlib/timezone.h" - "wlib/ustring.h" - "wlib/wdebug.cpp" - "wlib/wdebug.h" - "wlib/wstring.cpp" - "wlib/wstring.h" - "wlib/wstypes.h" - "wlib/wtime.cpp" - "wlib/wtime.h" - "wlib/xtime.cpp" - "wlib/xtime.h" - "wnet/field.cpp" - "wnet/field.h" - "wnet/packet.cpp" - "wnet/packet.h" - "wnet/tcp.cpp" - "wnet/tcp.h" - "wnet/udp.cpp" - "wnet/udp.h" -) - -add_executable(z_matchbot WIN32) -set_target_properties(z_matchbot PROPERTIES OUTPUT_NAME matchbot) - -target_sources(z_matchbot PRIVATE ${MATCHBOT_SRC}) - -target_include_directories(z_matchbot PRIVATE . wlib wnet) - -target_link_libraries(z_matchbot PRIVATE - gamespy::gamespy - core_config - core_utility - stlport -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(z_matchbot PRIVATE /subsystem:console) -endif() diff --git a/GeneralsMD/Code/Tools/textureCompress/CMakeLists.txt b/GeneralsMD/Code/Tools/textureCompress/CMakeLists.txt deleted file mode 100644 index 809053918c..0000000000 --- a/GeneralsMD/Code/Tools/textureCompress/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -set(TEXTURECOMPRESS_SRC - "resource.h" - "textureCompress.cpp" -) - -add_executable(z_texturecompress WIN32) -set_target_properties(z_texturecompress PROPERTIES OUTPUT_NAME texturecompress) - -target_sources(z_texturecompress PRIVATE ${TEXTURECOMPRESS_SRC}) - -target_link_libraries(z_texturecompress PRIVATE - core_config - core_wwlib -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(z_texturecompress PRIVATE textureCompress.rc) -endif() diff --git a/GeneralsMD/Code/Tools/textureCompress/textureCompress.rc b/GeneralsMD/Code/Tools/textureCompress/textureCompress.rc deleted file mode 100644 index 1279ff6bfe..0000000000 --- a/GeneralsMD/Code/Tools/textureCompress/textureCompress.rc +++ /dev/null @@ -1,96 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_LOADING DIALOG DISCARDABLE 0, 0, 186, 59 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Scanning..." -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "",IDC_FILENAME,7,20,172,16 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_LOADING, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 179 - TOPMARGIN, 7 - BOTTOMMARGIN, 52 - END -END -#endif // APSTUDIO_INVOKED - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/GeneralsMD/Code/Tools/timingTest/CMakeLists.txt b/GeneralsMD/Code/Tools/timingTest/CMakeLists.txt deleted file mode 100644 index 88377d5e6e..0000000000 --- a/GeneralsMD/Code/Tools/timingTest/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -set(TIMINGTEST_SRC - "StdAfx.cpp" - "StdAfx.h" - "timingTest.cpp" -) - -add_executable(z_timingtest WIN32) -set_target_properties(z_timingtest PROPERTIES OUTPUT_NAME timingtest) - -target_sources(z_timingtest PRIVATE ${TIMINGTEST_SRC}) - -target_link_libraries(z_timingtest PRIVATE - core_config - core_utility - winmm -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_link_options(z_timingtest PRIVATE /subsystem:console) -endif() diff --git a/GeneralsMD/Code/Tools/versionUpdate/CMakeLists.txt b/GeneralsMD/Code/Tools/versionUpdate/CMakeLists.txt deleted file mode 100644 index 5443295614..0000000000 --- a/GeneralsMD/Code/Tools/versionUpdate/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -set(VERSIONUPDATE_SRC - "versionUpdate.cpp" -) - -add_executable(z_versionupdate WIN32) -set_target_properties(z_versionupdate PROPERTIES OUTPUT_NAME versionupdate) - -target_sources(z_versionupdate PRIVATE ${VERSIONUPDATE_SRC}) - -target_link_libraries(z_versionupdate PRIVATE - core_config - core_wwlib -) diff --git a/GeneralsMD/Code/Tools/wdump/CMakeLists.txt b/GeneralsMD/Code/Tools/wdump/CMakeLists.txt index b7d437121c..a363e40260 100644 --- a/GeneralsMD/Code/Tools/wdump/CMakeLists.txt +++ b/GeneralsMD/Code/Tools/wdump/CMakeLists.txt @@ -18,13 +18,14 @@ set_target_properties(z_wdump PROPERTIES OUTPUT_NAME wdump) target_sources(z_wdump PRIVATE ${WDUMP_SRC}) target_link_libraries(z_wdump PRIVATE + core_config + core_utility + core_wwstub # avoid linking GameEngine dbghelplib imm32 vfw32 winmm - z_debug - z_gameengine - z_gameenginedevice + z_wwvegas ) if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") diff --git a/GeneralsMD/Code/Tools/wdump/FindDialog.cpp b/GeneralsMD/Code/Tools/wdump/FindDialog.cpp index 293286af37..6c92491bb2 100644 --- a/GeneralsMD/Code/Tools/wdump/FindDialog.cpp +++ b/GeneralsMD/Code/Tools/wdump/FindDialog.cpp @@ -23,7 +23,7 @@ #include "wdump.h" #include "FindDialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/wdump/chunk_d.cpp b/GeneralsMD/Code/Tools/wdump/chunk_d.cpp index a1f15ec9ab..732b9ffb8c 100644 --- a/GeneralsMD/Code/Tools/wdump/chunk_d.cpp +++ b/GeneralsMD/Code/Tools/wdump/chunk_d.cpp @@ -41,7 +41,7 @@ #include "rawfilem.h" #include "finddialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW @@ -315,8 +315,7 @@ void ChunkTableClass::List_W3D_CHUNK_MESH(ChunkItem *Item, CListCtrl *List) { } void ChunkTableClass::List_W3D_CHUNK_MESH_HEADER(ChunkItem *Item, CListCtrl *List) { - struct W3dMeshHeaderStruct *data; - data = (W3dMeshHeaderStruct *) Item->Data; + W3dMeshHeaderStruct *data = (W3dMeshHeaderStruct *) Item->Data; int Counter = 0; char buf[64]; @@ -359,54 +358,50 @@ void ChunkTableClass::List_W3D_CHUNK_MESH_HEADER(ChunkItem *Item, CListCtrl *Lis AddItem(List, Counter,"FutureUse", data->FutureUse, 24); } void ChunkTableClass::List_W3D_CHUNK_VERTICES(ChunkItem *Item, CListCtrl *List) { - W3dVectorStruct *data; - data = (W3dVectorStruct *) Item->Data; + W3dVectorStruct *data = (W3dVectorStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVectorStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Vertex[%d]", counter++); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); data++; } } void ChunkTableClass::List_W3D_CHUNK_VERTEX_NORMALS(ChunkItem *Item, CListCtrl *List) { - W3dVectorStruct *data; - data = (W3dVectorStruct *) Item->Data; + W3dVectorStruct *data = (W3dVectorStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVectorStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Normal[%d]", counter++); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); data++; } } void ChunkTableClass::List_W3D_CHUNK_SURRENDER_NORMALS(ChunkItem *Item, CListCtrl *List) { - W3dVectorStruct *data; - data = (W3dVectorStruct *) Item->Data; + W3dVectorStruct *data = (W3dVectorStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVectorStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "SRNormal[%d]", counter++); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); data++; } } void ChunkTableClass::List_W3D_CHUNK_TEXCOORDS(ChunkItem *Item, CListCtrl *List) { - W3dTexCoordStruct *data; - data = (W3dTexCoordStruct *) Item->Data; + W3dTexCoordStruct *data = (W3dTexCoordStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dTexCoordStruct) == 0); int counter = 0; char buf[256]; while(data < max) { @@ -417,35 +412,34 @@ void ChunkTableClass::List_W3D_CHUNK_TEXCOORDS(ChunkItem *Item, CListCtrl *List) } void ChunkTableClass::List_O_W3D_CHUNK_MATERIALS(ChunkItem *Item, CListCtrl *List) { - struct W3dMaterialStruct *data; - data = (W3dMaterialStruct *) Item->Data; + W3dMaterialStruct *data = (W3dMaterialStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dMaterialStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Material[%d].MaterialName", counter); - AddItem(List, Counter,buf, data->MaterialName); + AddItem(List, Counter, buf, data->MaterialName); sprintf(buf, "Material[%d].PrimaryName", counter); - AddItem(List, Counter,buf, data->PrimaryName); + AddItem(List, Counter, buf, data->PrimaryName); sprintf(buf, "Material[%d].SecondaryName", counter); - AddItem(List, Counter,buf, data->SecondaryName); + AddItem(List, Counter, buf, data->SecondaryName); sprintf(buf, "Material[%d].RenderFlags", counter); - AddItem(List, Counter,buf, data->RenderFlags); + AddItem(List, Counter, buf, data->RenderFlags); sprintf(buf, "Material[%d].Red", counter); - AddItem(List, Counter,buf, data->Red); + AddItem(List, Counter, buf, data->Red); sprintf(buf, "Material[%d].Green", counter); - AddItem(List, Counter,buf, data->Green); + AddItem(List, Counter, buf, data->Green); sprintf(buf, "Material[%d].Blue", counter); - AddItem(List, Counter,buf, data->Blue); + AddItem(List, Counter, buf, data->Blue); counter++; data++; @@ -464,32 +458,31 @@ void ChunkTableClass::List_O_W3D_CHUNK_QUADRANGLES(ChunkItem *Item, CListCtrl *L AddItem(List, Counter, "Outdated structure", ""); } void ChunkTableClass::List_O_W3D_CHUNK_SURRENDER_TRIANGLES(ChunkItem *Item, CListCtrl *List) { - struct W3dSurrenderTriStruct *data; - data = (W3dSurrenderTriStruct *) Item->Data; + W3dSurrenderTriStruct *data = (W3dSurrenderTriStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dSurrenderTriStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Triangle[%d].Attributes", counter); - AddItem(List, Counter,buf, data->Attributes); + AddItem(List, Counter, buf, data->Attributes); sprintf(buf, "Triangle[%d].Gouraud", counter); - AddItem(List, Counter,buf, data->Gouraud, 3); + AddItem(List, Counter, buf, data->Gouraud, 3); sprintf(buf, "Triangle[%d].VertexIndices", counter); - AddItem(List, Counter,buf, data->Vindex, 3); + AddItem(List, Counter, buf, data->Vindex, 3); sprintf(buf, "Triangle[%d].MaterialIdx", counter); - AddItem(List, Counter,buf, data->MaterialIdx); + AddItem(List, Counter, buf, data->MaterialIdx); sprintf(buf, "Triangle[%d].Normal", counter); - AddItem(List, Counter,buf, &data->Normal); + AddItem(List, Counter, buf, &data->Normal); sprintf(buf, "Triangle[%d].TexCoord", counter); - AddItem(List, Counter,buf, data->TexCoord, 3); + AddItem(List, Counter, buf, data->TexCoord, 3); counter++; data++; @@ -510,11 +503,10 @@ void ChunkTableClass::List_W3D_CHUNK_MESH_USER_TEXT(ChunkItem *Item, CListCtrl * } void ChunkTableClass::List_W3D_CHUNK_VERTEX_COLORS(ChunkItem *Item, CListCtrl *List) { - struct W3dRGBStruct *data; - data = (W3dRGBStruct *) Item->Data; + W3dRGBStruct *data = (W3dRGBStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dRGBStruct) == 0); int counter = 0; char buf[256]; @@ -523,7 +515,7 @@ void ChunkTableClass::List_W3D_CHUNK_VERTEX_COLORS(ChunkItem *Item, CListCtrl *L while(data < max) { sprintf(buf, "Vertex[%d].RGB", counter); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); counter++; data++; @@ -532,19 +524,18 @@ void ChunkTableClass::List_W3D_CHUNK_VERTEX_COLORS(ChunkItem *Item, CListCtrl *L void ChunkTableClass::List_W3D_CHUNK_VERTEX_INFLUENCES(ChunkItem *Item, CListCtrl *List) { - struct W3dVertInfStruct *data; - data = (W3dVertInfStruct *) Item->Data; + W3dVertInfStruct *data = (W3dVertInfStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVertInfStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "VertexInfluence[%d].BoneIdx", counter); - AddItem(List, Counter,buf, data->BoneIdx); + AddItem(List, Counter, buf, data->BoneIdx); sprintf(buf, "VertexInfluence[%d].Pad", counter); - AddItem(List, Counter,buf, data->Pad, 6); + AddItem(List, Counter, buf, data->Pad, 6); counter++; data++; @@ -556,23 +547,22 @@ void ChunkTableClass::List_W3D_CHUNK_DAMAGE(ChunkItem *Item, CListCtrl *List) { } void ChunkTableClass::List_W3D_CHUNK_DAMAGE_HEADER(ChunkItem *Item, CListCtrl *List) { - struct W3dMeshDamageStruct *data; - data = (W3dMeshDamageStruct *) Item->Data; + W3dMeshDamageStruct *data = (W3dMeshDamageStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dMeshDamageStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "DamageStruct[%d].NumDamageMaterials", counter); - AddItem(List, Counter,buf, data->NumDamageMaterials); + AddItem(List, Counter, buf, data->NumDamageMaterials); sprintf(buf, "DamageStruct[%d].NumDamageVerts", counter); - AddItem(List, Counter,buf, data->NumDamageVerts); + AddItem(List, Counter, buf, data->NumDamageVerts); sprintf(buf, "DamageStruct[%d].NumDamageColors", counter); - AddItem(List, Counter,buf, data->NumDamageColors); + AddItem(List, Counter, buf, data->NumDamageColors); sprintf(buf, "DamageStruct[%d].DamageIndex", counter); - AddItem(List, Counter,buf, data->DamageIndex); + AddItem(List, Counter, buf, data->DamageIndex); counter++; data++; @@ -581,20 +571,19 @@ void ChunkTableClass::List_W3D_CHUNK_DAMAGE_HEADER(ChunkItem *Item, CListCtrl *L void ChunkTableClass::List_W3D_CHUNK_DAMAGE_VERTICES(ChunkItem *Item, CListCtrl *List) { - struct W3dMeshDamageVertexStruct *data; - data = (W3dMeshDamageVertexStruct *) Item->Data; + W3dMeshDamageVertexStruct *data = (W3dMeshDamageVertexStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dMeshDamageVertexStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "DamageVertexStruct[%d].VertexIndex", counter); - AddItem(List, Counter,buf, data->VertexIndex); + AddItem(List, Counter, buf, data->VertexIndex); sprintf(buf, "DamageVertexStruct[%d].NewVertex", counter); - AddItem(List, Counter,buf, data->VertexIndex); + AddItem(List, Counter, buf, data->VertexIndex); counter++; data++; @@ -603,20 +592,19 @@ void ChunkTableClass::List_W3D_CHUNK_DAMAGE_VERTICES(ChunkItem *Item, CListCtrl void ChunkTableClass::List_W3D_CHUNK_DAMAGE_COLORS(ChunkItem *Item, CListCtrl *List) { - struct W3dMeshDamageColorStruct *data; - data = (W3dMeshDamageColorStruct *) Item->Data; + W3dMeshDamageColorStruct *data = (W3dMeshDamageColorStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dMeshDamageColorStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "DamageColorStruct[%d].VertexIndex", counter); - AddItem(List, Counter,buf, data->VertexIndex); + AddItem(List, Counter, buf, data->VertexIndex); sprintf(buf, "DamageColorStruct[%d].NewColor", counter); - AddItem(List, Counter,buf, &data->NewColor); + AddItem(List, Counter, buf, &data->NewColor); counter++; data++; @@ -624,44 +612,43 @@ void ChunkTableClass::List_W3D_CHUNK_DAMAGE_COLORS(ChunkItem *Item, CListCtrl *L } void ChunkTableClass::List_O_W3D_CHUNK_MATERIALS2(ChunkItem *Item, CListCtrl *List) { - struct W3dMaterial2Struct *data; - data = (W3dMaterial2Struct *) Item->Data; + W3dMaterial2Struct *data = (W3dMaterial2Struct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dMaterial2Struct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Material[%d].MaterialName", counter); - AddItem(List, Counter,buf, data->MaterialName); + AddItem(List, Counter, buf, data->MaterialName); sprintf(buf, "Material[%d].PrimaryName", counter); - AddItem(List, Counter,buf, data->PrimaryName); + AddItem(List, Counter, buf, data->PrimaryName); sprintf(buf, "Material[%d].SecondaryName", counter); - AddItem(List, Counter,buf, data->SecondaryName); + AddItem(List, Counter, buf, data->SecondaryName); sprintf(buf, "Material[%d].RenderFlags", counter); - AddItem(List, Counter,buf, data->RenderFlags); + AddItem(List, Counter, buf, data->RenderFlags); sprintf(buf, "Material[%d].Red", counter); - AddItem(List, Counter,buf, data->Red); + AddItem(List, Counter, buf, data->Red); sprintf(buf, "Material[%d].Green", counter); - AddItem(List, Counter,buf, data->Green); + AddItem(List, Counter, buf, data->Green); sprintf(buf, "Material[%d].Blue", counter); - AddItem(List, Counter,buf, data->Blue); + AddItem(List, Counter, buf, data->Blue); sprintf(buf, "Material[%d].Alpha", counter); - AddItem(List, Counter,buf, data->Alpha); + AddItem(List, Counter, buf, data->Alpha); sprintf(buf, "Material[%d].PrimaryNumFrames", counter); - AddItem(List, Counter,buf, data->PrimaryNumFrames); + AddItem(List, Counter, buf, data->PrimaryNumFrames); sprintf(buf, "Material[%d].SecondaryNumFrames", counter); - AddItem(List, Counter,buf, data->SecondaryNumFrames); + AddItem(List, Counter, buf, data->SecondaryNumFrames); counter++; data++; @@ -689,8 +676,7 @@ void ChunkTableClass::List_W3D_CHUNK_MATERIAL3_NAME(ChunkItem *Item, CListCtrl * void ChunkTableClass::List_W3D_CHUNK_MATERIAL3_INFO(ChunkItem *Item, CListCtrl *List) { int Counter = 0; - struct W3dMaterial3Struct *data; - data = (W3dMaterial3Struct *) Item->Data; + W3dMaterial3Struct *data = (W3dMaterial3Struct *) Item->Data; AddItem(List,Counter,"Attributes",data->Attributes); if (data->Attributes & W3DMATERIAL_USE_ALPHA) AddItem(List,Counter,"Attributes","W3DMATERIAL_USE_ALPHA"); if (data->Attributes & W3DMATERIAL_USE_SORTING) AddItem(List,Counter,"Attributes","W3DMATERIAL_USE_SORTING"); @@ -726,8 +712,7 @@ void ChunkTableClass::List_W3D_CHUNK_MAP3_FILENAME(ChunkItem * Item,CListCtrl * void ChunkTableClass::List_W3D_CHUNK_MAP3_INFO(ChunkItem * Item,CListCtrl * List) { int Counter = 0; - struct W3dMap3Struct * data; - data = (W3dMap3Struct *)Item->Data; + W3dMap3Struct * data = (W3dMap3Struct *)Item->Data; AddItem(List, Counter, "Mapping Type",data->MappingType); AddItem(List, Counter, "Frame Count",data->FrameCount); @@ -756,8 +741,7 @@ void ChunkTableClass::List_W3D_CHUNK_MATERIAL3_SI_MAP(ChunkItem *Item, CListCtrl void ChunkTableClass::List_W3D_CHUNK_MESH_HEADER3(ChunkItem *Item, CListCtrl *List) { - struct W3dMeshHeader3Struct *data; - data = (W3dMeshHeader3Struct *) Item->Data; + W3dMeshHeader3Struct *data = (W3dMeshHeader3Struct *) Item->Data; int Counter = 0; char buf[64]; @@ -840,26 +824,26 @@ void ChunkTableClass::List_W3D_CHUNK_MESH_HEADER3(ChunkItem *Item, CListCtrl *Li } void ChunkTableClass::List_W3D_CHUNK_TRIANGLES(ChunkItem *Item, CListCtrl *List) { - struct W3dTriStruct *data; - data = (W3dTriStruct *) Item->Data; + W3dTriStruct *data = (W3dTriStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dTriStruct) == 0); + int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Triangle[%d].VertexIndices", counter); - AddItem(List, Counter,buf, data->Vindex, 3); + AddItem(List, Counter, buf, data->Vindex, 3); sprintf(buf, "Triangle[%d].Attributes", counter); - AddItem(List, Counter,buf, data->Attributes); + AddItem(List, Counter, buf, data->Attributes); sprintf(buf, "Triangle[%d].Normal", counter); - AddItem(List, Counter,buf, &data->Normal); + AddItem(List, Counter, buf, &data->Normal); sprintf(buf, "Triangle[%d].Dist", counter); - AddItem(List, Counter,buf, data->Dist); + AddItem(List, Counter, buf, data->Dist); counter++; data++; @@ -869,29 +853,28 @@ void ChunkTableClass::List_W3D_CHUNK_TRIANGLES(ChunkItem *Item, CListCtrl *List) void ChunkTableClass::List_W3D_CHUNK_PER_TRI_MATERIALS(ChunkItem * Item,CListCtrl *List) { - unsigned short *data; - data = (unsigned short *) Item->Data; + unsigned short *data = (unsigned short *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(unsigned short) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Triangle[%d].MaterialIdx", counter); - AddItem(List, Counter,buf, *data); + AddItem(List, Counter, buf, *data); counter++; data++; } } -void ChunkTableClass::List_W3D_CHUNK_VERTEX_SHADE_INDICES(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_VERTEX_SHADE_INDICES(ChunkItem * Item,CListCtrl *List) { uint32 * data = (uint32 *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(uint32) == 0); int counter = 0; char buf[256]; @@ -931,9 +914,9 @@ void ChunkTableClass::List_W3D_CHUNK_VERTEX_MATERIAL_NAME(ChunkItem * Item,CList AddItem(List, Counter,"Material Name:", data); } -void ChunkTableClass::List_W3D_CHUNK_VERTEX_MATERIAL_INFO(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_VERTEX_MATERIAL_INFO(ChunkItem * Item,CListCtrl *List) { - struct W3dVertexMaterialStruct *data = (W3dVertexMaterialStruct *)Item->Data; + W3dVertexMaterialStruct *data = (W3dVertexMaterialStruct *)Item->Data; int Counter = 0; if (data->Attributes & W3DVERTMAT_USE_DEPTH_CUE) AddItem (List, Counter, "Material.Attributes", "W3DVERTMAT_USE_DEPTH_CUE", "flag"); @@ -1018,11 +1001,12 @@ void ChunkTableClass::List_W3D_CHUNK_VERTEX_MAPPER_ARGS1(ChunkItem *Item, CListC AddItem(List, Counter, "Stage1 Mapper Args:", data); } -void ChunkTableClass::List_W3D_CHUNK_SHADERS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_SHADERS(ChunkItem * Item,CListCtrl *List) { - struct W3dShaderStruct *shader = (W3dShaderStruct *)Item->Data; + W3dShaderStruct *shader = (W3dShaderStruct *)Item->Data; void *max = (char *)Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dShaderStruct) == 0); int counter = 0; char label[256]; @@ -1035,11 +1019,40 @@ void ChunkTableClass::List_W3D_CHUNK_SHADERS(ChunkItem * Item,CListCtrl *List) } } -void ChunkTableClass::List_W3D_CHUNK_PS2_SHADERS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_VERTEX_TANGENTS(ChunkItem *Item, CListCtrl *List) { + W3dVectorStruct *data = (W3dVectorStruct *) Item->Data; + int Counter = 0; + void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVectorStruct) == 0); + int counter = 0; + char buf[256]; + while(data < max) { + sprintf(buf, "Tangent[%d]", counter++); + AddItem(List, Counter, buf, data); + data++; + } +} + +void ChunkTableClass::List_W3D_CHUNK_VERTEX_BINORMALS(ChunkItem *Item, CListCtrl *List) { + W3dVectorStruct *data = (W3dVectorStruct *) Item->Data; + int Counter = 0; + void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVectorStruct) == 0); + int counter = 0; + char buf[256]; + while(data < max) { + sprintf(buf, "Binormal[%d]", counter++); + AddItem(List, Counter, buf, data); + data++; + } +} + +void ChunkTableClass::List_W3D_CHUNK_PS2_SHADERS(ChunkItem * Item,CListCtrl *List) { - struct W3dPS2ShaderStruct *shader = (W3dPS2ShaderStruct *)Item->Data; + W3dPS2ShaderStruct *shader = (W3dPS2ShaderStruct *)Item->Data; void *max = (char *)Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dPS2ShaderStruct) == 0); int counter = 0; char label[256]; @@ -1052,17 +1065,17 @@ void ChunkTableClass::List_W3D_CHUNK_PS2_SHADERS(ChunkItem * Item,CListCtrl *Lis } } -void ChunkTableClass::List_W3D_CHUNK_FX_SHADERS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_FX_SHADERS(ChunkItem * Item,CListCtrl *List) { List_Subitems(Item,List); } -void ChunkTableClass::List_W3D_CHUNK_FX_SHADER(ChunkItem* Item, CListCtrl* List) +void ChunkTableClass::List_W3D_CHUNK_FX_SHADER(ChunkItem* Item, CListCtrl* List) { List_Subitems(Item, List); } -void ChunkTableClass::List_W3D_CHUNK_FX_SHADER_INFO(ChunkItem* Item, CListCtrl* List) +void ChunkTableClass::List_W3D_CHUNK_FX_SHADER_INFO(ChunkItem* Item, CListCtrl* List) { uint8 version = *(uint8*)Item->Data; W3dFXShaderInfoStruct* shaderinfo = (W3dFXShaderInfoStruct*)((uint8*)Item->Data + 1); @@ -1073,7 +1086,7 @@ void ChunkTableClass::List_W3D_CHUNK_FX_SHADER_INFO(ChunkItem* Item, CListCtrl* AddItem(List, counter, "Technique", shaderinfo->Technique); } -void ChunkTableClass::List_W3D_CHUNK_FX_SHADER_CONSTANT(ChunkItem* Item, CListCtrl* List) +void ChunkTableClass::List_W3D_CHUNK_FX_SHADER_CONSTANT(ChunkItem* Item, CListCtrl* List) { int counter = 0; uint8 *chunkdata = (uint8 *)Item->Data; @@ -1116,26 +1129,26 @@ void ChunkTableClass::List_W3D_CHUNK_FX_SHADER_CONSTANT(ChunkItem* Item, CListCt } } -void ChunkTableClass::List_W3D_CHUNK_TEXTURES(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_TEXTURES(ChunkItem * Item,CListCtrl *List) { List_Subitems(Item,List); } -void ChunkTableClass::List_W3D_CHUNK_TEXTURE(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_TEXTURE(ChunkItem * Item,CListCtrl *List) { List_Subitems(Item,List); } -void ChunkTableClass::List_W3D_CHUNK_TEXTURE_NAME(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_TEXTURE_NAME(ChunkItem * Item,CListCtrl *List) { int Counter = 0; char * data = (char *)Item->Data; AddItem(List, Counter,"Texture Name:", data); } -void ChunkTableClass::List_W3D_CHUNK_TEXTURE_INFO(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_TEXTURE_INFO(ChunkItem * Item,CListCtrl *List) { - struct W3dTextureInfoStruct *data = (W3dTextureInfoStruct *)Item->Data; + W3dTextureInfoStruct *data = (W3dTextureInfoStruct *)Item->Data; int Counter = 0; AddItem(List, Counter, "Texture.Attributes", data->Attributes); @@ -1150,35 +1163,37 @@ void ChunkTableClass::List_W3D_CHUNK_TEXTURE_INFO(ChunkItem * Item,CListCtrl *Li AddItem(List, Counter, "Texture.FrameRate", data->FrameRate); } -void ChunkTableClass::List_W3D_CHUNK_MATERIAL_PASS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_MATERIAL_PASS(ChunkItem * Item,CListCtrl *List) { List_Subitems(Item,List); } -void ChunkTableClass::List_W3D_CHUNK_VERTEX_MATERIAL_IDS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_VERTEX_MATERIAL_IDS(ChunkItem * Item,CListCtrl *List) { int Counter = 0; int counter = 0; uint32 *data = (uint32 *)Item->Data; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(uint32) == 0); char buf[256]; while(data < max) { sprintf(buf, "Vertex[%d] Vertex Material Index", counter); - AddItem(List, Counter,buf, *data); + AddItem(List, Counter, buf, *data); counter++; data++; } } -void ChunkTableClass::List_W3D_CHUNK_SHADER_IDS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_SHADER_IDS(ChunkItem * Item,CListCtrl *List) { int Counter = 0; int counter = 0; uint32 *data = (uint32 *)Item->Data; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(uint32) == 0); char buf[256]; while(data < max) { @@ -1191,69 +1206,70 @@ void ChunkTableClass::List_W3D_CHUNK_SHADER_IDS(ChunkItem * Item,CListCtrl *List } } -void ChunkTableClass::List_W3D_CHUNK_DCG(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_DCG(ChunkItem * Item,CListCtrl *List) { W3dRGBAStruct *data = (W3dRGBAStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dRGBAStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Vertex[%d].DCG", counter); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); counter++; data++; } } -void ChunkTableClass::List_W3D_CHUNK_DIG(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_DIG(ChunkItem * Item,CListCtrl *List) { W3dRGBStruct *data = (W3dRGBStruct *)Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dRGBStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Vertex[%d].DIG", counter); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); counter++; data++; } } -void ChunkTableClass::List_W3D_CHUNK_SCG(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_SCG(ChunkItem * Item,CListCtrl *List) { W3dRGBStruct *data = (W3dRGBStruct *)Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dRGBStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Vertex[%d].SCG", counter); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); counter++; data++; } } -void ChunkTableClass::List_W3D_CHUNK_FXSHADER_IDS(ChunkItem* Item, CListCtrl* List) +void ChunkTableClass::List_W3D_CHUNK_FXSHADER_IDS(ChunkItem* Item, CListCtrl* List) { int Counter = 0; int counter = 0; uint32* data = (uint32*)Item->Data; void* max = (char*)Item->Data + Item->Length; + assert(Item->Length % sizeof(uint32) == 0); char buf[256]; while (data < max) { @@ -1266,17 +1282,18 @@ void ChunkTableClass::List_W3D_CHUNK_FXSHADER_IDS(ChunkItem* Item, CListCtrl* Li } } -void ChunkTableClass::List_W3D_CHUNK_TEXTURE_STAGE(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_TEXTURE_STAGE(ChunkItem * Item,CListCtrl *List) { List_Subitems(Item,List); } -void ChunkTableClass::List_W3D_CHUNK_TEXTURE_IDS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_TEXTURE_IDS(ChunkItem * Item,CListCtrl *List) { int Counter = 0; int counter = 0; uint32 *data = (uint32 *)Item->Data; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(uint32) == 0); char buf[256]; while(data < max) { @@ -1289,12 +1306,12 @@ void ChunkTableClass::List_W3D_CHUNK_TEXTURE_IDS(ChunkItem * Item,CListCtrl *Lis } } -void ChunkTableClass::List_W3D_CHUNK_STAGE_TEXCOORDS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_STAGE_TEXCOORDS(ChunkItem * Item,CListCtrl *List) { W3dTexCoordStruct *data = (W3dTexCoordStruct *)Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dTexCoordStruct) == 0); int counter = 0; char buf[256]; @@ -1308,12 +1325,13 @@ void ChunkTableClass::List_W3D_CHUNK_STAGE_TEXCOORDS(ChunkItem * Item,CListCtrl } } -void ChunkTableClass::List_W3D_CHUNK_PER_FACE_TEXCOORD_IDS(ChunkItem * Item,CListCtrl *List) +void ChunkTableClass::List_W3D_CHUNK_PER_FACE_TEXCOORD_IDS(ChunkItem * Item,CListCtrl *List) { int Counter = 0; int counter = 0; Vector3i *data = (Vector3i *)Item->Data; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(Vector3i) == 0); char buf[256]; while(data < max) { @@ -1345,6 +1363,7 @@ void ChunkTableClass::List_W3D_CHUNK_AABTREE_POLYINDICES(ChunkItem * Item,CListC int counter = 0; uint32 *data = (uint32 *)Item->Data; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(uint32) == 0); char buf[256]; while(data < max) { @@ -1362,18 +1381,18 @@ void ChunkTableClass::List_W3D_CHUNK_AABTREE_NODES(ChunkItem * Item,CListCtrl *L W3dMeshAABTreeNode * data = (W3dMeshAABTreeNode *)Item->Data; int Counter = 0; - int index = 0; void *max = (char *)Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dMeshAABTreeNode) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Node[%d].Min", counter); - AddItem(List, Counter,buf, &data->Min); + AddItem(List, Counter, buf, &data->Min); sprintf(buf, "Node[%d].Max", counter); - AddItem(List, Counter,buf, &data->Max); + AddItem(List, Counter, buf, &data->Max); if (data->FrontOrPoly0 & 0x80000000) { sprintf(buf, "Node[%d].Poly0",counter); @@ -1397,8 +1416,7 @@ void ChunkTableClass::List_W3D_CHUNK_HIERARCHY(ChunkItem *Item, CListCtrl *List) } void ChunkTableClass::List_W3D_CHUNK_HIERARCHY_HEADER(ChunkItem *Item, CListCtrl *List) { - struct W3dHierarchyStruct *data; - data = (W3dHierarchyStruct *) Item->Data; + W3dHierarchyStruct *data = (W3dHierarchyStruct *) Item->Data; int Counter = 0; char buf[64]; @@ -1409,29 +1427,28 @@ void ChunkTableClass::List_W3D_CHUNK_HIERARCHY_HEADER(ChunkItem *Item, CListCtrl AddItem(List, Counter, "Center", &data->Center); } void ChunkTableClass::List_W3D_CHUNK_PIVOTS(ChunkItem *Item, CListCtrl *List) { - struct W3dPivotStruct *data; - data = (W3dPivotStruct *) Item->Data; + W3dPivotStruct *data = (W3dPivotStruct *) Item->Data; int Counter = 0; - int index = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dPivotStruct) == 0); int counter = 0; char buf[256]; while(data < max) { sprintf(buf, "Pivot[%d].Name", counter); - AddItem(List, Counter,buf, data->Name); + AddItem(List, Counter, buf, data->Name); sprintf(buf, "Pivot[%d].ParentIdx", counter); - AddItem(List, Counter,buf, data->ParentIdx); + AddItem(List, Counter, buf, data->ParentIdx); sprintf(buf, "Pivot[%d].Translation", counter); - AddItem(List, Counter,buf, &data->Translation); + AddItem(List, Counter, buf, &data->Translation); sprintf(buf, "Pivot[%d].EulerAngles", counter); - AddItem(List, Counter,buf, &data->EulerAngles); + AddItem(List, Counter, buf, &data->EulerAngles); sprintf(buf, "Pivot[%d].Rotation", counter); - AddItem(List, Counter,buf, &data->Rotation); + AddItem(List, Counter, buf, &data->Rotation); counter++; data++; @@ -1679,17 +1696,17 @@ void ChunkTableClass::List_W3D_CHUNK_TRANSFORM_NODE(ChunkItem * Item,CListCtrl * void ChunkTableClass::List_W3D_CHUNK_POINTS(ChunkItem * Item,CListCtrl * List) { - W3dVectorStruct *data; - data = (W3dVectorStruct *) Item->Data; + W3dVectorStruct *data = (W3dVectorStruct *) Item->Data; int Counter = 0; void *max = (char *) Item->Data + Item->Length; + assert(Item->Length % sizeof(W3dVectorStruct) == 0); int counter = 0; char buf[256]; while (data < max) { sprintf(buf, "Point[%d]", counter++); - AddItem(List, Counter,buf, data); + AddItem(List, Counter, buf, data); data++; } } @@ -2143,6 +2160,8 @@ ChunkTableClass::ChunkTableClass() { NewType( W3D_CHUNK_FX_SHADER,"W3D_CHUNK_FX_SHADER",List_W3D_CHUNK_FX_SHADER, true); NewType( W3D_CHUNK_FX_SHADER_INFO, "W3D_CHUNK_FX_SHADER_INFO", List_W3D_CHUNK_FX_SHADER_INFO); NewType( W3D_CHUNK_FX_SHADER_CONSTANT, "W3D_CHUNK_FX_SHADER_CONSTANT", List_W3D_CHUNK_FX_SHADER_CONSTANT); + NewType( W3D_CHUNK_VERTEX_TANGENTS, "W3D_CHUNK_VERTEX_TANGENTS", List_W3D_CHUNK_VERTEX_TANGENTS); + NewType( W3D_CHUNK_VERTEX_BINORMALS, "W3D_CHUNK_VERTEX_BINORMALS", List_W3D_CHUNK_VERTEX_BINORMALS); NewType( W3D_CHUNK_PS2_SHADERS,"W3D_CHUNK_PS2_SHADERS",List_W3D_CHUNK_PS2_SHADERS); NewType( W3D_CHUNK_VERTEX_MATERIALS, "W3D_CHUNK_VERTEX_MATERIALS",List_W3D_CHUNK_VERTEX_MATERIALS,true); @@ -2377,7 +2396,7 @@ void ChunkData::Add_Chunk(ChunkLoadClass & cload, ChunkItem *Parent) existing.SetAt(data, data); if(theApp.TextureDumpFile != 0) - fprintf(theApp.TextureDumpFile, "%s,%s\n", theApp.Filename, data); + fprintf(theApp.TextureDumpFile, "%s,%s\n", (LPCTSTR)theApp.Filename, data); TRACE("%s,%s\n", theApp.Filename, data); } } diff --git a/GeneralsMD/Code/Tools/wdump/chunk_d.h b/GeneralsMD/Code/Tools/wdump/chunk_d.h index 5bc6842bc4..8efb942622 100644 --- a/GeneralsMD/Code/Tools/wdump/chunk_d.h +++ b/GeneralsMD/Code/Tools/wdump/chunk_d.h @@ -111,6 +111,9 @@ class ChunkTableClass { static void List_W3D_CHUNK_VERTEX_SHADE_INDICES(ChunkItem * Item,CListCtrl *List); static void List_W3D_CHUNK_MATERIAL_INFO(ChunkItem * Item,CListCtrl *List); + static void List_W3D_CHUNK_VERTEX_TANGENTS(ChunkItem *Item, CListCtrl *List); + static void List_W3D_CHUNK_VERTEX_BINORMALS(ChunkItem *Item, CListCtrl *List); + static void List_W3D_CHUNK_SHADERS(ChunkItem * Item,CListCtrl *List); static void List_W3D_CHUNK_PS2_SHADERS(ChunkItem * Item,CListCtrl *List); static void List_W3D_CHUNK_FX_SHADERS(ChunkItem * Item,CListCtrl *List); diff --git a/GeneralsMD/Code/Tools/wdump/mainfrm.cpp b/GeneralsMD/Code/Tools/wdump/mainfrm.cpp index 1efc2acf8f..756c533d85 100644 --- a/GeneralsMD/Code/Tools/wdump/mainfrm.cpp +++ b/GeneralsMD/Code/Tools/wdump/mainfrm.cpp @@ -26,7 +26,7 @@ #include "MainFrm.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -132,7 +132,7 @@ BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) ///////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); @@ -143,7 +143,7 @@ void CMainFrame::Dump(CDumpContext& dc) const CFrameWnd::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CMainFrame message handlers diff --git a/GeneralsMD/Code/Tools/wdump/mainfrm.h b/GeneralsMD/Code/Tools/wdump/mainfrm.h index 8c975ea402..6286bcb544 100644 --- a/GeneralsMD/Code/Tools/wdump/mainfrm.h +++ b/GeneralsMD/Code/Tools/wdump/mainfrm.h @@ -52,7 +52,7 @@ class CMainFrame : public CFrameWnd // Implementation public: virtual ~CMainFrame(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/wdump/wdeview.cpp b/GeneralsMD/Code/Tools/wdump/wdeview.cpp index 7eececc4e0..43af26d910 100644 --- a/GeneralsMD/Code/Tools/wdump/wdeview.cpp +++ b/GeneralsMD/Code/Tools/wdump/wdeview.cpp @@ -25,7 +25,7 @@ #include "wdumpdoc.h" #include "chunk_d.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -63,7 +63,7 @@ void CWDumpEditView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // CWDumpEditView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWDumpEditView::AssertValid() const { CEditView::AssertValid(); @@ -73,7 +73,7 @@ void CWDumpEditView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWDumpEditView message handlers diff --git a/GeneralsMD/Code/Tools/wdump/wdeview.h b/GeneralsMD/Code/Tools/wdump/wdeview.h index 9e1dab7c1b..e6d80fd97f 100644 --- a/GeneralsMD/Code/Tools/wdump/wdeview.h +++ b/GeneralsMD/Code/Tools/wdump/wdeview.h @@ -51,7 +51,7 @@ class CWDumpEditView : public CEditView // Implementation protected: virtual ~CWDumpEditView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/wdump/wdlview.cpp b/GeneralsMD/Code/Tools/wdump/wdlview.cpp index 0627d35e24..020ce22fe6 100644 --- a/GeneralsMD/Code/Tools/wdump/wdlview.cpp +++ b/GeneralsMD/Code/Tools/wdump/wdlview.cpp @@ -23,7 +23,7 @@ #include "wdump.h" #include "WDLView.h" #include "WDumpDoc.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -61,7 +61,7 @@ void CWDumpListView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // CWDumpListView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWDumpListView::AssertValid() const { CListView::AssertValid(); @@ -71,7 +71,7 @@ void CWDumpListView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWDumpListView message handlers diff --git a/GeneralsMD/Code/Tools/wdump/wdlview.h b/GeneralsMD/Code/Tools/wdump/wdlview.h index 32994aa6f3..2407c3c2d6 100644 --- a/GeneralsMD/Code/Tools/wdump/wdlview.h +++ b/GeneralsMD/Code/Tools/wdump/wdlview.h @@ -53,7 +53,7 @@ class CWDumpListView : public CListView // Implementation protected: virtual ~CWDumpListView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/wdump/wdtview.cpp b/GeneralsMD/Code/Tools/wdump/wdtview.cpp index 73415807f7..6c5e3d0d1e 100644 --- a/GeneralsMD/Code/Tools/wdump/wdtview.cpp +++ b/GeneralsMD/Code/Tools/wdump/wdtview.cpp @@ -26,7 +26,7 @@ #include "chunk_d.h" #include "finddialog.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -67,7 +67,7 @@ void CWDumpTreeView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // CWDumpTreeView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWDumpTreeView::AssertValid() const { CTreeView::AssertValid(); @@ -77,7 +77,7 @@ void CWDumpTreeView::Dump(CDumpContext& dc) const { CTreeView::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWDumpTreeView message handlers diff --git a/GeneralsMD/Code/Tools/wdump/wdtview.h b/GeneralsMD/Code/Tools/wdump/wdtview.h index 80239f337d..b03cfa9339 100644 --- a/GeneralsMD/Code/Tools/wdump/wdtview.h +++ b/GeneralsMD/Code/Tools/wdump/wdtview.h @@ -51,7 +51,7 @@ class CWDumpTreeView : public CTreeView // Implementation protected: virtual ~CWDumpTreeView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/wdump/wdump.cpp b/GeneralsMD/Code/Tools/wdump/wdump.cpp index d458d89204..ae54ba86b8 100644 --- a/GeneralsMD/Code/Tools/wdump/wdump.cpp +++ b/GeneralsMD/Code/Tools/wdump/wdump.cpp @@ -28,7 +28,7 @@ #include "FCNTL.H" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; diff --git a/GeneralsMD/Code/Tools/wdump/wdump.rc b/GeneralsMD/Code/Tools/wdump/wdump.rc index d8356f71ac..355094fd92 100644 --- a/GeneralsMD/Code/Tools/wdump/wdump.rc +++ b/GeneralsMD/Code/Tools/wdump/wdump.rc @@ -186,7 +186,7 @@ VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL -#ifdef _DEBUG +#ifdef RTS_DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L diff --git a/GeneralsMD/Code/Tools/wdump/wdumpdoc.cpp b/GeneralsMD/Code/Tools/wdump/wdumpdoc.cpp index bdf7e70e6a..5976c4ed24 100644 --- a/GeneralsMD/Code/Tools/wdump/wdumpdoc.cpp +++ b/GeneralsMD/Code/Tools/wdump/wdumpdoc.cpp @@ -24,7 +24,7 @@ #include "wdumpDoc.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -87,7 +87,7 @@ void CWdumpDoc::Serialize(CArchive& ar) ///////////////////////////////////////////////////////////////////////////// // CWdumpDoc diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWdumpDoc::AssertValid() const { CDocument::AssertValid(); @@ -97,7 +97,7 @@ void CWdumpDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWdumpDoc commands diff --git a/GeneralsMD/Code/Tools/wdump/wdumpdoc.h b/GeneralsMD/Code/Tools/wdump/wdumpdoc.h index 97654b4175..720885626e 100644 --- a/GeneralsMD/Code/Tools/wdump/wdumpdoc.h +++ b/GeneralsMD/Code/Tools/wdump/wdumpdoc.h @@ -60,7 +60,7 @@ class CWdumpDoc : public CDocument // Implementation public: virtual ~CWdumpDoc(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif diff --git a/GeneralsMD/Code/Tools/wdump/wdview.cpp b/GeneralsMD/Code/Tools/wdump/wdview.cpp index 67ff08d926..b4dfb2bdd5 100644 --- a/GeneralsMD/Code/Tools/wdump/wdview.cpp +++ b/GeneralsMD/Code/Tools/wdump/wdview.cpp @@ -25,7 +25,7 @@ #include "wdumpDoc.h" #include "wdView.h" -#ifdef _DEBUG +#ifdef RTS_DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; @@ -78,7 +78,7 @@ void CWdumpView::OnDraw(CDC* pDC) ///////////////////////////////////////////////////////////////////////////// // CWdumpView diagnostics -#ifdef _DEBUG +#ifdef RTS_DEBUG void CWdumpView::AssertValid() const { CView::AssertValid(); @@ -94,7 +94,7 @@ CWdumpDoc* CWdumpView::GetDocument() // non-debug version is inline ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CWdumpDoc))); return (CWdumpDoc*)m_pDocument; } -#endif //_DEBUG +#endif //RTS_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWdumpView message handlers diff --git a/GeneralsMD/Code/Tools/wdump/wdview.h b/GeneralsMD/Code/Tools/wdump/wdview.h index 9f1b5529a7..c65b8fb2d3 100644 --- a/GeneralsMD/Code/Tools/wdump/wdview.h +++ b/GeneralsMD/Code/Tools/wdump/wdview.h @@ -52,7 +52,7 @@ class CWdumpView : public CView // Implementation public: virtual ~CWdumpView(); -#ifdef _DEBUG +#ifdef RTS_DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif @@ -68,7 +68,7 @@ class CWdumpView : public CView DECLARE_MESSAGE_MAP() }; -#ifndef _DEBUG // debug version in wdumpView.cpp +#ifndef RTS_DEBUG // debug version in wdumpView.cpp inline CWdumpDoc* CWdumpView::GetDocument() { return (CWdumpDoc*)m_pDocument; } #endif diff --git a/GeneralsMD/Code/Tools/wolSetup/CMakeLists.txt b/GeneralsMD/Code/Tools/wolSetup/CMakeLists.txt deleted file mode 100644 index 3ba070248c..0000000000 --- a/GeneralsMD/Code/Tools/wolSetup/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -set(WOLSETUP_SRC - "resource.h" - "StdAfx.cpp" - "StdAfx.h" - "verchk.cpp" - "verchk.h" - "wolInit.cpp" - "wolSetup.cpp" - "wolSetup.h" - "WOLAPI/chatdefs.h" - "WOLAPI/downloaddefs.h" - "WOLAPI/ftpdefs.h" - "WOLAPI/netutildefs.h" - "WOLAPI/wolapi_i.c" - "WOLAPI/wolapi.h" -) - -add_executable(z_wolsetup WIN32) -set_target_properties(z_wolsetup PROPERTIES OUTPUT_NAME wolsetup) - -target_sources(z_wolsetup PRIVATE ${WOLSETUP_SRC}) - -target_link_libraries(z_wolsetup PRIVATE - core_config - Version -) - -if(WIN32 OR "${CMAKE_SYSTEM}" MATCHES "Windows") - target_sources(z_wolsetup PRIVATE wolSetup.rc) -endif() - -# TODO: Copy the dll's that reside in the WOLAPI folder. diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi.dll b/GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi.dll deleted file mode 100644 index 026a11bf08..0000000000 Binary files a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/wolapi.dll and /dev/null differ diff --git a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/woldbg.dll b/GeneralsMD/Code/Tools/wolSetup/WOLAPI/woldbg.dll deleted file mode 100644 index 334558d78e..0000000000 Binary files a/GeneralsMD/Code/Tools/wolSetup/WOLAPI/woldbg.dll and /dev/null differ diff --git a/GeneralsMD/Code/Tools/wolSetup/makedist.bat b/GeneralsMD/Code/Tools/wolSetup/makedist.bat deleted file mode 100644 index f0958000d1..0000000000 --- a/GeneralsMD/Code/Tools/wolSetup/makedist.bat +++ /dev/null @@ -1,5 +0,0 @@ -copy debug\wolsetup.exe dist\wolsetupD.exe -copy release\wolsetup.exe dist\wolsetup.exe -copy ..\..\libraries\source\wwvegas\wolapi\redist\woldbg.dll dist\woldbg.dll -copy ..\..\libraries\source\wwvegas\wolapi\redist\wolapi.dll dist\wolapi.dll - diff --git a/GeneralsMD/Code/Tools/wolSetup/small.ico b/GeneralsMD/Code/Tools/wolSetup/small.ico deleted file mode 100644 index 8f94d9aa82..0000000000 Binary files a/GeneralsMD/Code/Tools/wolSetup/small.ico and /dev/null differ diff --git a/GeneralsMD/Code/Tools/wolSetup/wolSetup.ico b/GeneralsMD/Code/Tools/wolSetup/wolSetup.ico deleted file mode 100644 index 386883523b..0000000000 Binary files a/GeneralsMD/Code/Tools/wolSetup/wolSetup.ico and /dev/null differ diff --git a/GeneralsMD/Code/Tools/wolSetup/wolSetup.rc b/GeneralsMD/Code/Tools/wolSetup/wolSetup.rc deleted file mode 100644 index 557d25a9ed..0000000000 --- a/GeneralsMD/Code/Tools/wolSetup/wolSetup.rc +++ /dev/null @@ -1,158 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ICON1 ICON DISCARDABLE "wolSetup.ico" -IDI_ICON2 ICON DISCARDABLE "small.ico" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_MAINBOX DIALOG DISCARDABLE 22, 17, 234, 115 -STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU -CAPTION "Generals WOLSetup" -FONT 8, "System" -BEGIN - ICON IDI_ICON1,IDC_MYICON,14,9,20,20 - LTEXT "WOLSetup Version 1.0",IDC_STATIC,49,10,119,8, - SS_NOPREFIX - LTEXT "Copyright (C) 2001 EA Pacific",IDC_STATIC,45,20,119,8 - DEFPUSHBUTTON "Done",IDOK,200,40,30,35,WS_GROUP - PUSHBUTTON "Debug",IDC_DEBUG_WOLAPI,50,90,35,15 - PUSHBUTTON "Release",IDC_RELEASE_WOLAPI,10,90,35,15 - PUSHBUTTON "Uninstall",IDC_UNINSTALL_WOLAPI,90,90,35,15 - GROUPBOX "WOLAPI",IDC_STATIC,5,80,125,30 - GROUPBOX "Generals Registry",IDC_STATIC,135,80,95,30 - PUSHBUTTON "Setup",IDC_SETUP_GENERALS,140,90,40,15 - PUSHBUTTON "Remove",IDC_UNINSTALL_GENERALS,185,90,40,15 - GROUPBOX "Current Setup",IDC_STATIC,5,35,190,40 - GROUPBOX "",IDC_STATIC,5,0,225,35 - LTEXT "WOLAPI dir:",IDC_STATIC,10,45,60,8,SS_NOPREFIX - LTEXT "Generals dir:",IDC_STATIC,10,55,60,8,SS_NOPREFIX - LTEXT "WOLAPI version:",IDC_STATIC,10,65,60,8,SS_NOPREFIX - LTEXT "No registry entry",IDC_TEXT_WOLDIR,70,45,120,8, - SS_NOPREFIX - LTEXT "No registry entry",IDC_TEXT_GENERALSDIR,70,55,120,8, - SS_NOPREFIX - CONTROL "(Uninstalled)",IDC_TEXT_WOLVER,"Static", - SS_LEFTNOWORDWRAP | SS_NOPREFIX | WS_GROUP,70,65,120,8 -END - -IDD_GENERALSSETUPBOX DIALOG DISCARDABLE 22, 17, 194, 70 -STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU -CAPTION "Setup Generals Registry" -FONT 8, "System" -BEGIN - DEFPUSHBUTTON "OK",IDOK,155,40,30,20,WS_GROUP - DEFPUSHBUTTON "Cancel",IDCANCEL,5,40,35,20,WS_GROUP - EDITTEXT IDC_EDIT_PATH,50,10,135,10,ES_AUTOHSCROLL - EDITTEXT IDC_EDIT_SERIAL,50,25,135,10,ES_AUTOHSCROLL - LTEXT "Install path:",IDC_STATIC,10,10,40,8 - LTEXT "Serial:",IDC_STATIC,10,25,25,8 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_MAINBOX, DIALOG - BEGIN - RIGHTMARGIN, 230 - BOTTOMMARGIN, 75 - END - - IDD_GENERALSSETUPBOX, DIALOG - BEGIN - RIGHTMARGIN, 190 - BOTTOMMARGIN, 30 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE DISCARDABLE -BEGIN - IDS_APP_TITLE "wolSetup" - IDS_HELLO "Hello World!" - IDC_WOLSETUP "WOLSETUP" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/cmake/config-build.cmake b/cmake/config-build.cmake index 4fa2973928..a001e42c59 100644 --- a/cmake/config-build.cmake +++ b/cmake/config-build.cmake @@ -1,23 +1,48 @@ # Do we want to build extra SDK stuff or just the game binary? +option(RTS_BUILD_CORE_TOOLS "Build core tools" ON) +option(RTS_BUILD_CORE_EXTRAS "Build core extra tools/tests" OFF) option(RTS_BUILD_ZEROHOUR "Build Zero Hour code." ON) option(RTS_BUILD_GENERALS "Build Generals code." ON) option(RTS_BUILD_OPTION_INTERNAL "Build code with the \"Internal\" configuration." OFF) option(RTS_BUILD_OPTION_PROFILE "Build code with the \"Profile\" configuration." OFF) option(RTS_BUILD_OPTION_DEBUG "Build code with the \"Debug\" configuration." OFF) option(RTS_BUILD_OPTION_ASAN "Build code with Address Sanitizer." OFF) +option(RTS_BUILD_OPTION_FFMPEG "Enable FFmpeg support" OFF) if(NOT RTS_BUILD_ZEROHOUR AND NOT RTS_BUILD_GENERALS) set(RTS_BUILD_ZEROHOUR TRUE) message("You must select one project to build, building Zero Hour by default.") endif() +add_feature_info(CoreTools RTS_BUILD_CORE_TOOLS "Build Core Mod Tools") +add_feature_info(CoreExtras RTS_BUILD_CORE_EXTRAS "Build Core Extra Tools/Tests") add_feature_info(ZeroHourStuff RTS_BUILD_ZEROHOUR "Build Zero Hour code") add_feature_info(GeneralsStuff RTS_BUILD_GENERALS "Build Generals code") add_feature_info(InternalBuild RTS_BUILD_OPTION_INTERNAL "Building as an \"Internal\" build") add_feature_info(ProfileBuild RTS_BUILD_OPTION_PROFILE "Building as a \"Profile\" build") add_feature_info(DebugBuild RTS_BUILD_OPTION_DEBUG "Building as a \"Debug\" build") add_feature_info(AddressSanitizer RTS_BUILD_OPTION_ASAN "Building with address sanitizer") +add_feature_info(FFmpegSupport RTS_BUILD_OPTION_FFMPEG "Building with FFmpeg support") +if(RTS_BUILD_ZEROHOUR) + option(RTS_BUILD_ZEROHOUR_TOOLS "Build tools for Zero Hour" ON) + option(RTS_BUILD_ZEROHOUR_EXTRAS "Build extra tools/tests for Zero Hour" OFF) + option(RTS_BUILD_ZEROHOUR_DOCS "Build documentation for Zero Hour" OFF) + + add_feature_info(ZeroHourTools RTS_BUILD_ZEROHOUR_TOOLS "Build Zero Hour Mod Tools") + add_feature_info(ZeroHourExtras RTS_BUILD_ZEROHOUR_EXTRAS "Build Zero Hour Extra Tools/Tests") + add_feature_info(ZeroHourDocs RTS_BUILD_ZEROHOUR_DOCS "Build Zero Hour Documentation") +endif() + +if(RTS_BUILD_GENERALS) + option(RTS_BUILD_GENERALS_TOOLS "Build tools for Generals" ON) + option(RTS_BUILD_GENERALS_EXTRAS "Build extra tools/tests for Generals" OFF) + option(RTS_BUILD_GENERALS_DOCS "Build documentation for Generals" OFF) + + add_feature_info(GeneralsTools RTS_BUILD_GENERALS_TOOLS "Build Generals Mod Tools") + add_feature_info(GeneralsExtras RTS_BUILD_GENERALS_EXTRAS "Build Generals Extra Tools/Tests") + add_feature_info(GeneralsDocs RTS_BUILD_GENERALS_DOCS "Build Generals Documentation") +endif() if(NOT IS_VS6_BUILD) # Because we set CMAKE_CXX_STANDARD_REQUIRED and CMAKE_CXX_EXTENSIONS in the compilers.cmake this should be enforced. @@ -31,15 +56,19 @@ if(MSVC) target_compile_definitions(core_config INTERFACE _CRT_NONSTDC_NO_WARNINGS _CRT_SECURE_NO_WARNINGS $<$:_DEBUG_CRT>) endif() +if(UNIX) + target_compile_definitions(core_config INTERFACE _UNIX) +endif() + if(RTS_BUILD_OPTION_DEBUG) - target_compile_definitions(core_config INTERFACE _DEBUG WWDEBUG DEBUG) + target_compile_definitions(core_config INTERFACE RTS_DEBUG WWDEBUG DEBUG) else() - target_compile_definitions(core_config INTERFACE _RELEASE) + target_compile_definitions(core_config INTERFACE RTS_RELEASE) if(RTS_BUILD_OPTION_INTERNAL) - target_compile_definitions(core_config INTERFACE _INTERNAL) + target_compile_definitions(core_config INTERFACE RTS_INTERNAL) endif() if(RTS_BUILD_OPTION_PROFILE) - target_compile_definitions(core_config INTERFACE _PROFILE) + target_compile_definitions(core_config INTERFACE RTS_PROFILE) endif() endif() diff --git a/cmake/config-debug.cmake b/cmake/config-debug.cmake index 1d52400bab..e9bb8f3ece 100644 --- a/cmake/config-debug.cmake +++ b/cmake/config-debug.cmake @@ -10,27 +10,39 @@ set_property(CACHE RTS_DEBUG_STACKTRACE PROPERTY STRINGS DEFAULT ON OFF) set(RTS_DEBUG_PROFILE "DEFAULT" CACHE STRING "Enables debug profiling. When DEFAULT, this option is enabled with DEBUG or INTERNAL") set_property(CACHE RTS_DEBUG_PROFILE PROPERTY STRINGS DEFAULT ON OFF) +option(RTS_DEBUG_INCLUDE_DEBUG_LOG_IN_CRC_LOG "Includes normal debug log in crc log" OFF) +option(RTS_DEBUG_MULTI_INSTANCE "Enables multi client instance support" OFF) -add_feature_info(DebugLogging RTS_DEBUG_LOGGING "Build with Debug Logging") -add_feature_info(DebugLogging RTS_DEBUG_CRASHING "Build with Debug Crashing") -add_feature_info(DebugLogging RTS_DEBUG_STACKTRACE "Build with Debug Stacktracing") -add_feature_info(DebugLogging RTS_DEBUG_PROFILE "Build with Debug Profiling") - -macro(define_debug_option OptionName OptionEnabledCompileDef OptionDisabledCompileDef) +# Helper macro that handles DEFAULT ON OFF options +macro(define_debug_option OptionName OptionEnabledCompileDef OptionDisabledCompileDef FeatureInfoName FeatureInfoDescription) if(${OptionName} STREQUAL "DEFAULT") # Does nothing elseif(${OptionName} STREQUAL "ON") target_compile_definitions(core_config INTERFACE ${OptionEnabledCompileDef}=1) + add_feature_info(${FeatureInfoName} TRUE ${FeatureInfoDescription}) elseif(${OptionName} STREQUAL "OFF") target_compile_definitions(core_config INTERFACE ${OptionDisabledCompileDef}=1) + add_feature_info(${FeatureInfoName} FALSE ${FeatureInfoDescription}) else() message(FATAL_ERROR "Unhandled option") endif() endmacro() -define_debug_option(RTS_DEBUG_LOGGING DEBUG_LOGGING DISABLE_DEBUG_LOGGING ) -define_debug_option(RTS_DEBUG_CRASHING DEBUG_CRASHING DISABLE_DEBUG_CRASHING ) -define_debug_option(RTS_DEBUG_STACKTRACE DEBUG_STACKTRACE DISABLE_DEBUG_STACKTRACE) -define_debug_option(RTS_DEBUG_PROFILE DEBUG_PROFILE DISABLE_DEBUG_PROFILE ) +define_debug_option(RTS_DEBUG_LOGGING DEBUG_LOGGING DISABLE_DEBUG_LOGGING DebugLogging "Build with Debug Logging") +define_debug_option(RTS_DEBUG_CRASHING DEBUG_CRASHING DISABLE_DEBUG_CRASHING DebugCrashing "Build with Debug Crashing") +define_debug_option(RTS_DEBUG_STACKTRACE DEBUG_STACKTRACE DISABLE_DEBUG_STACKTRACE DebugStacktrace "Build with Debug Stacktracing") +define_debug_option(RTS_DEBUG_PROFILE DEBUG_PROFILE DISABLE_DEBUG_PROFILE DebugProfile "Build with Debug Profiling") + +add_feature_info(DebugIncludeDebugLogInCrcLog RTS_DEBUG_INCLUDE_DEBUG_LOG_IN_CRC_LOG "Build with Debug Logging in CRC log") +add_feature_info(DebugMultiInstance RTS_DEBUG_MULTI_INSTANCE "Build with Multi Client Instance support") + + +if(RTS_DEBUG_INCLUDE_DEBUG_LOG_IN_CRC_LOG) + target_compile_definitions(core_config INTERFACE INCLUDE_DEBUG_LOG_IN_CRC_LOG) +endif() + +if(RTS_DEBUG_MULTI_INSTANCE) + target_compile_definitions(core_config INTERFACE RTS_MULTI_INSTANCE) +endif() diff --git a/cmake/config-memory.cmake b/cmake/config-memory.cmake index 1365d67eb9..72a28d1c94 100644 --- a/cmake/config-memory.cmake +++ b/cmake/config-memory.cmake @@ -1,6 +1,11 @@ # Game Memory features option(RTS_GAMEMEMORY_ENABLE "Enables the memory pool and dynamic memory allocator." ON) +# Disable Game Memory if ASAN is enabled - Game Memory overrides new/delete and interferes with ASAN +if(RTS_BUILD_OPTION_ASAN) + set(RTS_GAMEMEMORY_ENABLE OFF) +endif() + # Memory pool features option(RTS_MEMORYPOOL_OVERRIDE_MALLOC "Enables the Dynamic Memory Allocator for malloc calls." OFF) option(RTS_MEMORYPOOL_MPSB_DLINK "Adds a backlink to MemoryPoolSingleBlock. Makes it faster to free raw DMA blocks, but increases memory consumption." ON) diff --git a/cmake/zlib.cmake b/cmake/zlib.cmake index 3dbd7254ab..f202f3f6d8 100644 --- a/cmake/zlib.cmake +++ b/cmake/zlib.cmake @@ -1,5 +1,4 @@ -set(ZLIB_PARENT_DIR ${CMAKE_CURRENT_BINARY_DIR}/_deps/zlib-1.1.4-src) -set(ZLIB_DIR ${ZLIB_PARENT_DIR}/ZLib) +set(ZLIB_DIR ${CMAKE_CURRENT_BINARY_DIR}/_deps/zlib-1.1.4-src/ZLib) FetchContent_Populate(zlib DOWNLOAD_EXTRACT_TIMESTAMP GIT_REPOSITORY https://github.com/TheSuperHackers/zlib-1.1.4 @@ -26,6 +25,6 @@ target_sources(libzlib PRIVATE "${ZLIB_DIR}/inffast.c" ) -target_include_directories(libzlib PUBLIC ${ZLIB_PARENT_DIR}) +target_include_directories(libzlib PUBLIC ${ZLIB_DIR}) target_compile_definitions(libzlib PUBLIC Z_PREFIX) diff --git a/vcpkg.json b/vcpkg.json new file mode 100644 index 0000000000..011b913c8a --- /dev/null +++ b/vcpkg.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", + "builtin-baseline": "b02e341c927f16d991edbd915d8ea43eac52096c", + "dependencies": [ + "zlib", + "ffmpeg" + ] + } \ No newline at end of file